text:
package org.arakhne.afc.math.geometry.d3.continuous;

import java.io.Serializable;

import org.arakhne.afc.math.MathConstants;
import org.arakhne.afc.math.MathUtil;
import org.arakhne.afc.math.geometry.coordinatesystem.CoordinateSystem3D;
import org.arakhne.afc.math.geometry.d3.Vector3D;
import org.arakhne.afc.math.matrix.Matrix3f;
import org.arakhne.afc.math.matrix.Matrix4f;
import org.eclipse.xtext.xbase.lib.Pure;

/** A 4 element unit quaternion represented by single precision floating
 * point x,y,z,w coordinates.  The quaternion is always normalized.
 *
 *
Other Rotation Representations

 *
 * Other representations of an rotation are available from this class:
 * axis-angle, and Euler angles.
 *
 *
Axis Angles

 * The axis–angle representation of a rotation parameterizes a rotation in a three-dimensional
 * Euclidean space by two values: a unit vector, indicating the direction of an axis of rotation, and
 * an angle describing the magnitude of the rotation about the axis.
 * The rotation occurs in the sense prescribed by the (left/right)-hand rule.
 *
 *
 *
Euler Angles

 * The term "Euler Angle" is used for any representation of 3 dimensional
 * rotations where the rotation is decomposed into 3 separate angles.
 *

 * There is no single set of conventions and standards in this area,
 * therefore the following conventions was choosen:

 *
angle applied first:	heading;

 *
angle applied second: attitude;

 *
angle applied last: bank

 *

 *

 * Examples: NASA aircraft standard and telescope standard
 *
 *
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 */
public class Quaternion implements Cloneable, Serializable {

	private static final long serialVersionUID = 4494919776986180960L;

	private final static double EPS = 0.000001;
	private final static double EPS2 = 1.0e-30;

	/** x coordinate.
	 */
	protected double x;

	/** y coordinate.
	 */
	protected double y;

	/** z coordinate.
	 */
	protected double z;

	/** w coordinate.
	 */
	protected double w;

	/** Construct a zero quaternion.
	 */
	public Quaternion() {
		this.x = this.y = this.z = this.w = 0;
	}

	/** Construct a quaternion with the given components.
	 *
	 * @param x1
	 * @param y1
	 * @param z1
	 * @param w1
	 */
	public Quaternion(double x1, double y1, double z1, double w1) {
		double mag = (1.0/Math.sqrt( x1*x1 + y1*y1 + z1*z1 + w1*w1 ));
		this.x = x1*mag;
		this.y = y1*mag;
		this.z = z1*mag;
		this.w = w1*mag;
	}

	/** Construct a quaternion with the components of the given quaternion.
	 *
	 * @param q
	 */
	public Quaternion(Quaternion q) {
		this.x = q.x;
		this.y = q.y;
		this.z = q.z;
		this.w = q.w;
	}

	/** Construct a quaternion from an axis-angle representation.
	 *
	 * @param axis is the axis of the rotation.
	 * @param angle is the rotation angle around the axis.
	 */
	public Quaternion(Vector3D axis, double angle) {
		setAxisAngle(axis, angle);
	}

	/** Construct a quaternion from Euler angles.
	 * The {@link CoordinateSystem3D#getDefaultCoordinateSystem() default coordinate system}
	 * is used from applying the Euler angles.
	 *
	 * @param attitude is the rotation around left vector.
	 * @param bank is the rotation around front vector.
	 * @param heading is the rotation around top vector.
	 * @see Euler Angles
	 * @see Euler to Quaternion
	 * @see CoordinateSystem3D#getDefaultCoordinateSystem()
	 */
	public Quaternion(double attitude, double bank, double heading) {
		this(attitude, bank, heading, null);
	}

	/** Construct a quaternion from Euler angles.
	 *
	 * @param attitude is the rotation around left vector.
	 * @param bank is the rotation around front vector.
	 * @param heading is the rotation around top vector.
	 * @param system the coordinate system to use for applying the Euler angles.
	 * @see Euler Angles
	 * @see Euler to Quaternion
	 */
	public Quaternion(double attitude, double bank, double heading, CoordinateSystem3D system) {
		setEulerAngles(attitude, bank, heading, system);
	}

	/** {@inheritDoc}
	 */
	@Pure
	@Override
	public Quaternion clone() {
		try {
			return (Quaternion)super.clone();
		}
		catch(CloneNotSupportedException e) {
			throw new Error(e);
		}
	}

	/** Replies the X coordinate.
	 *
	 * @return x
	 */
	@Pure
	public double getX() {
		return this.x;
	}

	/** Set the X coordinate.
	 *
	 * @param x1
	 */
	public void setX(double x1) {
		this.x = x1;
	}

	/** Replies the Y coordinate.
	 *
	 * @return y
	 */
	@Pure
	public double getY() {
		return this.y;
	}

	/** Set the Y coordinate.
	 *
	 * @param y1
	 */
	public void setY(double y1) {
		this.y = y1;
	}

	/** Replies the Z coordinate.
	 *
	 * @return z
	 */
	@Pure
	public double getZ() {
		return this.z;
	}

	/** Set the Z coordinate.
	 *
	 * @param z1
	 */
	public void setZ(double z1) {
		this.z = z1;
	}

	/** Replies the W coordinate.
	 *
	 * @return w
	 */
	@Pure
	public double getW() {
		return this.w;
	}

	/** Set the W coordinate.
	 *
	 * @param w1
	 */
	public void setW(double w1) {
		this.w = w1;
	}

	/**
	 * {@inheritDoc}
	 */
	@Pure
	@Override
	public boolean equals(Object t1) {
		try {
			Quaternion t2 = (Quaternion) t1;
			return(this.x == t2.getX() && this.y == t2.getY() && this.z == t2.getZ() && this.w == t2.getW());
		}
		catch(AssertionError e) {
			throw e;
		}
		catch (Throwable e2) {
			return false;
		}
	}

	/**
	 * Returns true if the L-infinite distance between this tuple
	 * and tuple t1 is less than or equal to the epsilon parameter,
	 * otherwise returns false.  The L-infinite
	 * distance is equal to MAX[abs(x1-x2), abs(y1-y2)].
	 * @param t1  the tuple to be compared to this tuple
	 * @param epsilon  the threshold value
	 * @return  true or false
	 */
	@Pure
	public boolean epsilonEquals(Quaternion t1, double epsilon) {
		double diff;

		diff = this.x - t1.getX();
		if(Double.isNaN(diff)) return false;
		if((diff<0?-diff:diff) > epsilon) return false;

		diff = this.y - t1.getY();
		if(Double.isNaN(diff)) return false;
		if((diff<0?-diff:diff) > epsilon) return false;

		diff = this.z - t1.getZ();
		if(Double.isNaN(diff)) return false;
		if((diff<0?-diff:diff) > epsilon) return false;

		diff = this.w - t1.getW();
		if(Double.isNaN(diff)) return false;
		if((diff<0?-diff:diff) > epsilon) return false;

		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Pure
	@Override
	public int hashCode() {
		long bits = 1;
		bits = 31 * bits + Double.doubleToLongBits(this.x);
		bits = 31 * bits + Double.doubleToLongBits(this.y);
		bits = 31 * bits + Double.doubleToLongBits(this.z);
		bits = 31 * bits + Double.doubleToLongBits(this.w);
		int b = (int) bits;
		return b ^ (b >> 32);
	}

	/**
	 * {@inheritDoc}
	 */
	@Pure
	@Override
	public String toString() {
		return "("
				+this.x
				+";"
				+this.y
				+";"
				+this.z
				+";"
				+this.w
				+")";
	}

	/**
	 * Sets the value of this quaternion to the conjugate of quaternion q1.
	 * @param q1 the source vector
	 */
	public final void conjugate(Quaternion q1) {
		this.x = -q1.x;
		this.y = -q1.y;
		this.z = -q1.z;
		this.w = q1.w;
	}

	/**
	 * Sets the value of this quaternion to the conjugate of itself.
	 */
	public final void conjugate() {
		this.x = -this.x;
		this.y = -this.y;
		this.z = -this.z;
	}

	/**
	 * Sets the value of this quaternion to the quaternion product of
	 * quaternions q1 and q2 (this = q1 * q2).
	 * Note that this is safe for aliasing (e.g. this can be q1 or q2).
	 * @param q1 the first quaternion
	 * @param q2 the second quaternion
	 */
	public final void mul(Quaternion q1, Quaternion q2) {
		if (this != q1 && this != q2) {
			this.w = q1.w*q2.w - q1.x*q2.x - q1.y*q2.y - q1.z*q2.z;
			this.x = q1.w*q2.x + q2.w*q1.x + q1.y*q2.z - q1.z*q2.y;
			this.y = q1.w*q2.y + q2.w*q1.y - q1.x*q2.z + q1.z*q2.x;
			this.z = q1.w*q2.z + q2.w*q1.z + q1.x*q2.y - q1.y*q2.x;
		}
		else {
			double	x1, y1, w1;

			w1 = q1.w*q2.w - q1.x*q2.x - q1.y*q2.y - q1.z*q2.z;
			x1 = q1.w*q2.x + q2.w*q1.x + q1.y*q2.z - q1.z*q2.y;
			y1 = q1.w*q2.y + q2.w*q1.y - q1.x*q2.z + q1.z*q2.x;
			this.z = q1.w*q2.z + q2.w*q1.z + q1.x*q2.y - q1.y*q2.x;
			this.w = w1;
			this.x = x1;
			this.y = y1;
		}
	}

	/**
	 * Sets the value of this quaternion to the quaternion product of
	 * itself and q1 (this = this * q1).
	 * @param q1 the other quaternion
	 */
	public final void mul(Quaternion q1) {
		double x1, y1, w1;

		w1 = this.w*q1.w - this.x*q1.x - this.y*q1.y - this.z*q1.z;
		x1 = this.w*q1.x + q1.w*this.x + this.y*q1.z - this.z*q1.y;
		y1 = this.w*q1.y + q1.w*this.y - this.x*q1.z + this.z*q1.x;
		this.z = this.w*q1.z + q1.w*this.z + this.x*q1.y - this.y*q1.x;
		this.w = w1;
		this.x = x1;
		this.y = y1;
	}

	/**
	 * Multiplies quaternion q1 by the inverse of quaternion q2 and places
	 * the value into this quaternion.  The value of both argument quaternions
	 * is preservered (this = q1 * q2^-1).
	 * @param q1 the first quaternion
	 * @param q2 the second quaternion
	 */
	public final void mulInverse(Quaternion q1, Quaternion q2)
	{
		Quaternion  tempQuat = q2.clone();

		tempQuat.inverse();
		this.mul(q1, tempQuat);
	}

	/**
	 * Multiplies this quaternion by the inverse of quaternion q1 and places
	 * the value into this quaternion.  The value of the argument quaternion
	 * is preserved (this = this * q^-1).
	 * @param q1 the other quaternion
	 */
	public final void mulInverse(Quaternion q1) {
		Quaternion  tempQuat = q1.clone();

		tempQuat.inverse();
		this.mul(tempQuat);
	}

	/**
	 * Sets the value of this quaternion to quaternion inverse of quaternion q1.
	 * @param q1 the quaternion to be inverted
	 */
	public final void inverse(Quaternion q1) {
		double norm;

		norm = 1f/(q1.w*q1.w + q1.x*q1.x + q1.y*q1.y + q1.z*q1.z);
		this.w =  norm*q1.w;
		this.x = -norm*q1.x;
		this.y = -norm*q1.y;
		this.z = -norm*q1.z;
	}

	/**
	 * Sets the value of this quaternion to the quaternion inverse of itself.
	 */
	public final void inverse() {
		double norm;

		norm = 1f/(this.w*this.w + this.x*this.x + this.y*this.y + this.z*this.z);
		this.w *=  norm;
		this.x *= -norm;
		this.y *= -norm;
		this.z *= -norm;
	}

	/**
	 * Sets the value of this quaternion to the normalized value
	 * of quaternion q1.
	 * @param q1 the quaternion to be normalized.
	 */
	public final void normalize(Quaternion q1) {
		double norm;

		norm = (q1.x*q1.x + q1.y*q1.y + q1.z*q1.z + q1.w*q1.w);

		if (norm > 0f) {
			norm = 1f/Math.sqrt(norm);
			this.x = norm*q1.x;
			this.y = norm*q1.y;
			this.z = norm*q1.z;
			this.w = norm*q1.w;
		} else {
			this.x = 0f;
			this.y = 0f;
			this.z = 0f;
			this.w = 0f;
		}
	}

	/**
	 * Normalizes the value of this quaternion in place.
	 */
	public final void normalize() {
		double norm;

		norm = (this.x*this.x + this.y*this.y + this.z*this.z + this.w*this.w);

		if (norm > 0f) {
			norm = 1f / Math.sqrt(norm);
			this.x *= norm;
			this.y *= norm;
			this.z *= norm;
			this.w *= norm;
		} else {
			this.x = 0f;
			this.y = 0f;
			this.z = 0f;
			this.w = 0f;
		}
	}

	/**
	 * Sets the value of this quaternion to the rotational component of
	 * the passed matrix.
	 * @param m1 the Matrix4f
	 */
	public final void setFromMatrix(Matrix4f m1) {
		double ww = 0.25f*(m1.m00 + m1.m11 + m1.m22 + m1.m33);

		if (ww >= 0) {
			if (ww >= EPS2) {
				this.w =  Math.sqrt(ww);
				ww =  0.25f/this.w;
				this.x = (m1.m21 - m1.m12)*ww;
				this.y = (m1.m02 - m1.m20)*ww;
				this.z = (m1.m10 - m1.m01)*ww;
				return;
			}
		}
		else {
			this.w = 0;
			this.x = 0;
			this.y = 0;
			this.z = 1;
			return;
		}

		this.w = 0;
		ww = -0.5f*(m1.m11 + m1.m22);

		if (ww >= 0) {
			if (ww >= EPS2) {
				this.x =  Math.sqrt(ww);
				ww = 1.0f/(2.0f*this.x);
				this.y = m1.m10*ww;
				this.z = m1.m20*ww;
				return;
			}
		} else {
			this.x = 0;
			this.y = 0;
			this.z = 1;
			return;
		}

		this.x = 0;
		ww = 0.5f*(1.0f - m1.m22);

		if (ww >= EPS2) {
			this.y =  Math.sqrt(ww);
			this.z = m1.m21/(2.0f*this.y);
			return;
		}

		this.y = 0;
		this.z = 1;
	}

	/**
	 * Sets the value of this quaternion to the rotational component of
	 * the passed matrix.
	 * @param m1 the Matrix3f
	 */
	public final void setFromMatrix(Matrix3f m1) {
		double ww = 0.25f*(m1.m00 + m1.m11 + m1.m22 + 1.0f);

		if (ww >= 0) {
			if (ww >= EPS2) {
				this.w =  Math.sqrt(ww);
				ww = 0.25f/this.w;
				this.x = (m1.m21 - m1.m12)*ww;
				this.y = (m1.m02 - m1.m20)*ww;
				this.z = (m1.m10 - m1.m01)*ww;
				return;
			}
		} else {
			this.w = 0;
			this.x = 0;
			this.y = 0;
			this.z = 1;
			return;
		}

		this.w = 0;
		ww = -0.5f*(m1.m11 + m1.m22);
		if (ww >= 0) {
			if (ww >= EPS2) {
				this.x =  Math.sqrt(ww);
				ww = 0.5f/this.x;
				this.y = m1.m10*ww;
				this.z = m1.m20*ww;
				return;
			}
		} else {
			this.x = 0;
			this.y = 0;
			this.z = 1;
			return;
		}

		this.x = 0;
		ww =  0.5f*(1.0f - m1.m22);
		if (ww >= EPS2) {
			this.y =  Math.sqrt(ww);
			this.z = m1.m21/(2.0f*this.y);
			return;
		}

		this.y = 0;
		this.z = 1;
	}

	/** Set the quaternion coordinates.
	 *
	 * @param x1
	 * @param y1
	 * @param z1
	 * @param w1
	 */
	public void set(double x1, double y1, double z1, double w1) {
		double mag = (1.0/Math.sqrt( x1*x1 + y1*y1 + z1*z1 + w1*w1 ));
		this.x = x1*mag;
		this.y = y1*mag;
		this.z = z1*mag;
		this.w = w1*mag;
	}

	/** Set the quaternion coordinates.
	 *
	 * @param q
	 */
	public void set(Quaternion q) {
		this.x = q.x;
		this.y = q.y;
		this.z = q.z;
		this.w = q.w;
	}

	/**
	 * Sets the value of this quaternion to the equivalent rotation
	 * of the Axis-Angle arguments.
	 * @param axis is the axis of rotation.
	 * @param angle is the rotation around the axis.
	 */
	public final void setAxisAngle(Vector3D axis, double angle) {
		setAxisAngle(axis.getX(),  axis.getY(), axis.getZ(), angle);
	}

	/**
	 * Sets the value of this quaternion to the equivalent rotation
	 * of the Axis-Angle arguments.
	 * @param x1 is the x coordinate of the rotation axis
	 * @param y1 is the y coordinate of the rotation axis
	 * @param z1 is the z coordinate of the rotation axis
	 * @param angle is the rotation around the axis.
	 */
	public final void setAxisAngle(double x1, double y1, double z1, double angle) {
		double mag,amag;
		// Quat = cos(theta/2) + sin(theta/2)(roation_axis)
		amag = Math.sqrt(x1*x1 + y1*y1 + z1*z1);
		if (amag < EPS ) {
			this.w = 0.0f;
			this.x = 0.0f;
			this.y = 0.0f;
			this.z = 0.0f;
		}
		else {
			amag = 1.0f/amag;
			mag = Math.sin(angle/2.0);
			this.w = Math.cos(angle/2.0);
			this.x = x1*amag*mag;
			this.y = y1*amag*mag;
			this.z = z1*amag*mag;
		}
	}

	/** Replies the rotation axis-angle represented by this quaternion.
	 *
	 * @return the rotation axis-angle.
	 */
	@Pure
	public final Vector3f getAxis() {
		double mag = this.x*this.x + this.y*this.y + this.z*this.z;

		if ( mag > EPS ) {
			mag = Math.sqrt(mag);
			double invMag = 1f/mag;

			return new Vector3f(
					this.x*invMag,
					this.y*invMag,
					this.z*invMag);
		}
		return new Vector3f(0f, 0f, 1f);
	}

	/** Replies the rotation angle represented by this quaternion.
	 *
	 * @return the rotation axis
	 * @see #setAxisAngle(Vector3D, double)
	 * @see #setAxisAngle(double, double, double, double)
	 * @see #getAxis()
	 */
	@Pure
	public final double getAngle() {
		double mag = this.x*this.x + this.y*this.y + this.z*this.z;

		if ( mag > EPS ) {
			mag = Math.sqrt(mag);
			return (2.f*Math.atan2(mag, this.w));
		}
		return 0f;
	}

	/** Replies the rotation axis represented by this quaternion.
	 *
	 * @return the rotation axis
	 * @see #setAxisAngle(Vector3D, double)
	 * @see #setAxisAngle(double, double, double, double)
	 * @see #getAngle()
	 */
	@SuppressWarnings("synthetic-access")
	@Pure
	public final AxisAngle getAxisAngle() {
		double mag = this.x*this.x + this.y*this.y + this.z*this.z;

		if ( mag > EPS ) {
			mag = Math.sqrt(mag);
			double invMag = 1f/mag;

			return new AxisAngle(
					this.x*invMag,
					this.y*invMag,
					this.z*invMag,
					(2.*Math.atan2(mag, this.w)));
		}
		return new AxisAngle(0, 0, 1, 0);
	}

	/**
	 *  Performs a great circle interpolation between this quaternion
	 *  and the quaternion parameter and places the result into this
	 *  quaternion.
	 *  @param q1  the other quaternion
	 *  @param alpha  the alpha interpolation parameter
	 */
	public final void interpolate(Quaternion q1, double alpha) {
		// From "Advanced Animation and Rendering Techniques"
		// by Watt and Watt pg. 364, function as implemented appeared to be
		// incorrect.  Fails to choose the same quaternion for the double
		// covering. Resulting in change of direction for rotations.
		// Fixed function to negate the first quaternion in the case that the
		// dot product of q1 and this is negative. Second case was not needed.

		double dot,s1,s2,om,sinom;

		dot = this.x*q1.x + this.y*q1.y + this.z*q1.z + this.w*q1.w;

		if ( dot < 0 ) {
			// negate quaternion
			q1.x = -q1.x;  q1.y = -q1.y;  q1.z = -q1.z;  q1.w = -q1.w;
			dot = -dot;
		}

		if ( (1.0 - dot) > EPS ) {
			om = Math.acos(dot);
			sinom = Math.sin(om);
			s1 = Math.sin((1.0-alpha)*om)/sinom;
			s2 = Math.sin( alpha*om)/sinom;
		} else{
			s1 = 1.0 - alpha;
			s2 = alpha;
		}

		this.w = (s1*this.w + s2*q1.w);
		this.x = (s1*this.x + s2*q1.x);
		this.y = (s1*this.y + s2*q1.y);
		this.z = (s1*this.z + s2*q1.z);
	}

	/**
	 *  Performs a great circle interpolation between quaternion q1
	 *  and quaternion q2 and places the result into this quaternion.
	 *  @param q1  the first quaternion
	 *  @param q2  the second quaternion
	 *  @param alpha  the alpha interpolation parameter
	 */
	public final void interpolate(Quaternion q1, Quaternion q2, double alpha) {
		// From "Advanced Animation and Rendering Techniques"
		// by Watt and Watt pg. 364, function as implemented appeared to be
		// incorrect.  Fails to choose the same quaternion for the double
		// covering. Resulting in change of direction for rotations.
		// Fixed function to negate the first quaternion in the case that the
		// dot product of q1 and this is negative. Second case was not needed.

		double dot,s1,s2,om,sinom;

		dot = q2.x*q1.x + q2.y*q1.y + q2.z*q1.z + q2.w*q1.w;

		if ( dot < 0 ) {
			// negate quaternion
			q1.x = -q1.x;  q1.y = -q1.y;  q1.z = -q1.z;  q1.w = -q1.w;
			dot = -dot;
		}

		if ( (1.0 - dot) > EPS ) {
			om = Math.acos(dot);
			sinom = Math.sin(om);
			s1 = Math.sin((1.0-alpha)*om)/sinom;
			s2 = Math.sin( alpha*om)/sinom;
		} else{
			s1 = 1.0 - alpha;
			s2 = alpha;
		}
		this.w = s1*q1.w + s2*q2.w;
		this.x = s1*q1.x + s2*q2.x;
		this.y = s1*q1.y + s2*q2.y;
		this.z = s1*q1.z + s2*q2.z;
	}

	/** Set the quaternion with the Euler angles.
	 *
	 * @param angles the Euler angles.
	 * @see Euler Angles
	 * @see Euler to Quaternion
	 */
	@SuppressWarnings("synthetic-access")
	public void setEulerAngles(EulerAngles angles) {
		setEulerAngles(
				angles.getAttitude(),
				angles.getBank(),
				angles.getHeading(),
				angles.getSystem());
	}

	/** Set the quaternion with the Euler angles.
	 * The {@link CoordinateSystem3D#getDefaultCoordinateSystem() default coordinate system}
	 * is used from applying the Euler angles.
	 *
	 * @param attitude is the rotation around left vector.
	 * @param bank is the rotation around front vector.
	 * @param heading is the rotation around top vector.
	 * @see CoordinateSystem3D#getDefaultCoordinateSystem()
	 * @see Euler Angles
	 * @see Euler to Quaternion
	 */
	public void setEulerAngles(double attitude, double bank, double heading) {
		setEulerAngles(attitude, bank, heading, null);
	}

	/** Set the quaternion with the Euler angles.
	 *
	 * @param attitude is the rotation around left vector.
	 * @param bank is the rotation around front vector.
	 * @param heading is the rotation around top vector.
	 * @param system the coordinate system to use for applying the Euler angles.
	 * @see Euler Angles
	 * @see Euler to Quaternion
	 */
	public void setEulerAngles(double attitude, double bank, double heading, CoordinateSystem3D system) {
		CoordinateSystem3D cs = (system == null) ? CoordinateSystem3D.getDefaultCoordinateSystem() : system;

		double c1 = Math.cos(heading / 2.);
		double s1 = Math.sin(heading / 2.);
		double c2 = Math.cos(attitude / 2.);
		double s2 = Math.sin(attitude / 2.);
		double c3 = Math.cos(bank / 2.);
		double s3 = Math.sin(bank / 2.);

		double x1, y1, z1, w1;

		// Source: http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm
		// Standard used: XZY_RIGHT_HAND
		double c1c2 = c1 * c2;
		double s1s2 = s1 * s2;
		w1 = c1c2 * c3 - s1s2 * s3;
		x1 = c1c2 * s3 + s1s2 * c3;
		y1 = s1 * c2 * c3 + c1 * s2 * s3;
		z1 = c1 * s2 * c3 - s1 * c2 * s3;

		set(x1, y1, z1, w1);
		CoordinateSystem3D.XZY_RIGHT_HAND.toSystem(this, cs);
	}

	/**
	 * Replies the Euler's angles that corresponds to the quaternion.
	 * The {@link CoordinateSystem3D#getDefaultCoordinateSystem() default coordinate system}
	 * is used from applying the Euler angles.
	 *
	 * @return the heading, attitude and bank angles.
	 * @see CoordinateSystem3D#getDefaultCoordinateSystem()
	 * @see Euler Angles
	 * @see Quaternion to Euler
	 */
	@Pure
	public EulerAngles getEulerAngles() {
		return getEulerAngles(CoordinateSystem3D.getDefaultCoordinateSystem());
	}

	/**
	 * Replies the Euler's angles that corresponds to the quaternion.
	 *
	 * @param system is the coordinate system used to define the up,left and front vectors.
	 * @return the heading, attitude and bank angles.
	 * @see Euler Angles
	 * @see Quaternion to Euler
	 */
	@SuppressWarnings("synthetic-access")
	@Pure
	public EulerAngles getEulerAngles(CoordinateSystem3D system) {
		// See http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm
		// Standard used: XZY_RIGHT_HAND
		Quaternion q = new Quaternion(this);
		system.toSystem(q, CoordinateSystem3D.XZY_RIGHT_HAND);

		double sqw = q.w * q.w;
		double sqx = q.x * q.x;
		double sqy = q.y * q.y;
		double sqz = q.z * q.z;
		double unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor
		double test = q.x * q.y + q.z * q.w;

		if (MathUtil.compareEpsilon(test, .5 * unit) >= 0) { // singularity at north pole
			return new EulerAngles(
					2. * Math.atan2(q.x, q.w), // heading
					MathConstants.DEMI_PI, // attitude
					0.,
					system);
		}
		if (MathUtil.compareEpsilon(test, -.5 * unit) <= 0) { // singularity at south pole
			return new EulerAngles(
					-2. * Math.atan2(q.x, q.w), // heading
					-MathConstants.DEMI_PI, // attitude
					0.,
					system);
		}
		return new EulerAngles(
				Math.atan2(2. * q.y * q.w - 2. * q.x * q.z, sqx - sqy - sqz + sqw),
				Math.asin(2. * test / unit),
				Math.atan2(2. * q.x * q.w - 2. * q.y * q.z, -sqx + sqy - sqz + sqw),
				system);
	}

	/** A representation of Euler Angles.
	 * The term "Euler Angle" is used for any representation of 3 dimensional
	 * rotations where the rotation is decomposed into 3 separate angles.
	 *

	 * There is no single set of conventions and standards in this area,
	 * therefore the following conventions was choosen:

	 *
angle applied first:	heading;

	 *
angle applied second: attitude;

	 *
angle applied last: bank

	 *

	 *

	 * Examples: NASA aircraft standard and telescope standard
	 *
	 *
	 *
	 * For creating an instance of this class, you must invoke
	 * {@link Quaternion#getEulerAngles(CoordinateSystem3D)}.
	 *
	 * @author $Author: sgalland$
	 * @version $Name$ $Revision$ $Date$
	 * @mavengroupid $GroupId$
	 * @mavenartifactid $ArtifactId$
	 */
	public static final class EulerAngles implements Cloneable, Serializable {

		private static final long serialVersionUID = -1532832128836084395L;

		private final double attitude;
		private final double bank;
		private final double heading;
		private final CoordinateSystem3D system;

		private EulerAngles(double attitude1, double bank1, double heading1, CoordinateSystem3D system1) {
			this.attitude = attitude1;
			this.bank = bank1;
			this.heading = heading1;
			this.system = system1;
		}

		/** Replies the attitude, the rotation around left vector.
		 *
		 * @return the attitude angle.
		 */
		@Pure
		public double getAttitude() {
			return this.attitude;
		}

		/** Replies the bank, the rotation around front vector.
		 *
		 * @return the bank angle.
		 */
		@Pure
		public double getBank() {
			return this.bank;
		}

		/** Replies the heading, the rotation around top vector.
		 *
		 * @return the heading angle.
		 */
		@Pure
		public double getHeading() {
			return this.heading;
		}

		/** Replies coordinate system used for obtaining the euler angles.
		 *
		 * @return the coordinate system.
		 */
		@Pure
		private CoordinateSystem3D getSystem() {
			return this.system;
		}

	}

	/** A representation of axis-angle.
	 * The axis–angle representation of a rotation parameterizes a rotation in a three-dimensional
	 * Euclidean space by two values: a unit vector, indicating the direction of an axis of rotation, and
	 * an angle describing the magnitude of the rotation about the axis.
	 * The rotation occurs in the sense prescribed by the (left/right)-hand rule.
	 *
	 *
	 * For creating an instance of this class, you must invoke
	 * {@link Quaternion#getAxisAngle()}.
	 *
	 * @author $Author: sgalland$
	 * @version $Name$ $Revision$ $Date$
	 * @mavengroupid $GroupId$
	 * @mavenartifactid $ArtifactId$
	 */
	public static final class AxisAngle implements Cloneable, Serializable {

		private static final long serialVersionUID = -7228694369177792159L;

		private final double x;
		private final double y;
		private final double z;
		private final double angle;

		private AxisAngle(double x1, double y1, double z1, double angle1) {
			this.x = x1;
			this.y = y1;
			this.z = z1;
			this.angle = angle1;
		}

		/** Replies the rotation axis.
		 *
		 * @return the rotation axis.
		 */
		@Pure
		public Vector3f getAxis() {
			return new Vector3f(this.x, this.y, this.z);
		}

		/** Replies the rotation angle.
		 *
		 * @return the rotation angle.
		 */
		@Pure
		public double getAngle() {
			return this.angle;
		}

	}

}


text:
import { Component, OnInit, Renderer2, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, HostBinding } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { select } from '@angular-redux/store';
import { Observable } from 'rxjs/Observable';

import { routerAnimation } from '../shared/router.animations';
import { ResizeWindow } from '../shared/resize.service';
import { PrepareObj } from '../shared/prepareObjects.service';
import { TopService } from '../shared/top.service';
import { CommonCalls } from '../shared/commonCalls.service';

    @Component({
        selector: 'press', // tslint:disable-line
        templateUrl: './press.template.html',
        styleUrls: ['../exhibitions/exhi-press.component.scss'],
        animations: [routerAnimation()],
        changeDetection: ChangeDetectionStrategy.OnPush
        })

export class PressComponent implements OnInit, AfterViewInit {

  @select(['applicationData', 'routeData', 'press']) pressData$: Observable<any>;
  @HostBinding('@routeAnimation')

public data: Object;
private wholeContent: Object;
public htmlObject: any;
private subscriptionRoute: any;
private _routeSegment: string;
private _response: Array<Object>;
private _url = 'press';

constructor (
    private route: ActivatedRoute,
    private _resizeWindow: ResizeWindow,
    private _prepObj: PrepareObj,
    private _topService: TopService,
    private _renderer: Renderer2,
    private _common: CommonCalls,
    private _changeDetectorRef: ChangeDetectorRef) {}

    ngOnInit() {

        this.subscriptionRoute = this.route.params.subscribe(params => {
            this._routeSegment = params['article'];
        });

        this._common.calls(this._url, this.pressData$,
            response => this.populateResponse(response)
        );
    }

    populateResponse(response) {
        this._changeDetectorRef.markForCheck();

        const lookForResize = (() => {
            this.data = this._resizeWindow.dataTrimmed(response)
        });
        lookForResize();
        this._resizeWindow.winResize(lookForResize);
        this.wholeContent = this._prepObj.prepObj(response, 'press');
        if (this._routeSegment !== undefined) {
            this.popUpActivateByRoute(response, this._routeSegment);
        }
    }

    ngAfterViewInit() {
        this._topService.setTop(this._renderer);
    }

    popUpActivate(index: number) {
        this.htmlObjMethod(index);
    }

    popUpActivateByRoute(res, routeSegment) {
        const current =  this._prepObj.getClicked(res, routeSegment);
            this.htmlObjMethod(current);
    }

    htmlObjMethod(clickedCurrent) {
        this.htmlObject = this._prepObj.htmlObj(clickedCurrent, 'press', this.wholeContent);
    }

    onPopOff(off: boolean) {
        this.htmlObject = off;
    }

}

redpajama_set_name: RedPajamaGithub


text:
/* SPDX-License-Identifier: BSD-2-Clause */

#include <tilck/common/basic_defs.h>
#include <tilck/common/printk.h>

#include <tilck/kernel/sched.h>
#include <tilck/kernel/timer.h>
#include <tilck/kernel/datetime.h>

#include "osl.h"
#include <3rd_party/acpi/acpi.h>
#include <3rd_party/acpi/accommon.h>

ACPI_MODULE_NAME("osl_misc")
static ulong boot_acpi_root_ptr;

void acpi_set_root_pointer(ulong ptr)
{
   boot_acpi_root_ptr = ptr;
}

ACPI_STATUS
AcpiOsInitialize(void)
{
   ACPI_STATUS rc;
   ACPI_FUNCTION_TRACE(__FUNC__);

   if ((rc = osl_init_malloc()) != AE_OK)
      return_ACPI_STATUS(rc);

   if ((rc = osl_init_tasks()) != AE_OK)
      return_ACPI_STATUS(rc);

   if ((rc = osl_init_irqs()) != AE_OK)
      return_ACPI_STATUS(rc);

   return_ACPI_STATUS(AE_OK);
}

ACPI_STATUS
AcpiOsTerminate(void)
{
   ACPI_FUNCTION_TRACE(__FUNC__);
   return_ACPI_STATUS(AE_OK);
}

ACPI_PHYSICAL_ADDRESS
AcpiOsGetRootPointer(void)
{
   if (boot_acpi_root_ptr)
      return boot_acpi_root_ptr;

   ACPI_PHYSICAL_ADDRESS ptr = 0;
   AcpiFindRootPointer(&ptr);
   return ptr;
}

ACPI_STATUS
AcpiOsPredefinedOverride(
    const ACPI_PREDEFINED_NAMES *InitVal,
    ACPI_STRING                 *NewVal)
{
   *NewVal = NULL;
   return AE_OK;
}

ACPI_STATUS
AcpiOsTableOverride(
    ACPI_TABLE_HEADER       *ExistingTable,
    ACPI_TABLE_HEADER       **NewTable)
{
   *NewTable = NULL;
   return AE_OK;
}

ACPI_STATUS
AcpiOsPhysicalTableOverride(
    ACPI_TABLE_HEADER       *ExistingTable,
    ACPI_PHYSICAL_ADDRESS   *NewAddress,
    UINT32                  *NewTableLength)
{
   *NewAddress = 0;
   return AE_OK;
}

void
AcpiOsSleep(UINT64 Milliseconds)
{
   kernel_sleep_ms(Milliseconds);
}

void
AcpiOsStall(UINT32 Microseconds)
{
   disable_preemption();
   {
      delay_us(Microseconds);
   }
   enable_preemption_nosched();
}

UINT64
AcpiOsGetTimer(void)
{
   /* system time in 100-ns units */
   return get_sys_time() / 100;
}

ACPI_THREAD_ID
AcpiOsGetThreadId(void)
{
   return get_curr_tid();
}

ACPI_STATUS
AcpiOsSignal (
    UINT32                  Function,
    void                    *Info)
{
   if (Function == ACPI_SIGNAL_FATAL) {

      ACPI_SIGNAL_FATAL_INFO *i = Info;

      panic("ACPI: fatal signal. Type: 0x%x, Code: 0x%x, Arg: 0x%x\n",
            i->Type, i->Code, i->Argument);

   } else if (Function == ACPI_SIGNAL_BREAKPOINT) {

      printk("ACPI: breakpoint: %s\n", (char *)Info);
      printk("ACPI: ignoring the breakpoint\n");
      return AE_OK;

   } else {

      panic("ACPI: unknown signal: %u\n", Function);
   }
}

ACPI_STATUS
AcpiOsEnterSleep(
    UINT8                   SleepState,
    UINT32                  RegaValue,
    UINT32                  RegbValue)
{
   ACPI_FUNCTION_TRACE(__FUNC__);
   printk("ACPI sleep: %u, 0x%x, 0x%x\n", SleepState, RegaValue, RegaValue);
   return_ACPI_STATUS(AE_OK);
}

ACPI_PRINTF_LIKE (1)
void ACPI_INTERNAL_VAR_XFACE
AcpiOsPrintf(const char *Format, ...)
{
   va_list args;
   va_start(args, Format);
   vprintk(Format, args);
   va_end(args);
}

void
AcpiOsVprintf(
    const char              *Format,
    va_list                 Args)
{
   vprintk(Format, Args);
}

/* ACPI DEBUGGER funcs: keep not implemented for the moment */

void
AcpiOsRedirectOutput(void *Destination)
{
   printk("AcpiOsRedirectOutput ignored\n");
}

ACPI_STATUS
AcpiOsGetLine (
    char                    *Buffer,
    UINT32                  BufferLength,
    UINT32                  *BytesRead)
{
   NOT_IMPLEMENTED();
}

ACPI_STATUS
AcpiOsInitializeDebugger(void)
{
   /* do nothing */
   return AE_OK;
}

void
AcpiOsTerminateDebugger(void)
{
   /* do nothing */
}

ACPI_STATUS
AcpiOsWaitCommandReady(void)
{
   NOT_IMPLEMENTED();
}

ACPI_STATUS
AcpiOsNotifyCommandComplete(void)
{
   NOT_IMPLEMENTED();
}

void
AcpiOsTracePoint(
    ACPI_TRACE_EVENT_TYPE   Type,
    BOOLEAN                 Begin,
    UINT8                   *Aml,
    char                    *Pathname)
{
   /* do nothing */
}


text:
package dev.satyrn.wolfarmor.common.network;

import dev.satyrn.wolfarmor.api.util.Resources;
import dev.satyrn.wolfarmor.common.network.packets.WolfDropChestMessage;
import dev.satyrn.wolfarmor.common.network.packets.WolfEatMessage;
import dev.satyrn.wolfarmor.common.network.packets.WolfHealMessage;
import dev.satyrn.wolfarmor.common.network.MessageBase.ClientMessageBase;
import dev.satyrn.wolfarmor.common.network.MessageBase.ServerMessageBase;

import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;

public abstract class PacketHandler {
    private static final SimpleNetworkWrapper CHANNEL = NetworkRegistry.INSTANCE.newSimpleChannel(Resources.MOD_ID);
    private static byte ID = 0;
    public static void initialize() {
        registerMessage(WolfEatMessage.class);
        registerMessage(WolfHealMessage.class);
        registerMessage(WolfDropChestMessage.class);
    }

    private static <T extends MessageBase<T> & IMessageHandler<T, IMessage>>void registerMessage(Class<T> clazz) {
        if(ClientMessageBase.class.isAssignableFrom(clazz)) {
            CHANNEL.registerMessage(clazz, clazz, ID++, Side.CLIENT);
            return;
        }
        if(ServerMessageBase.class.isAssignableFrom(clazz)) {
            CHANNEL.registerMessage(clazz, clazz, ID++, Side.SERVER);
            return;
        }
        CHANNEL.registerMessage(clazz, clazz, ID, Side.CLIENT);
        CHANNEL.registerMessage(clazz, clazz, ID++, Side.SERVER);
    }

    public static SimpleNetworkWrapper getChannel() {
        return CHANNEL;
    }
}


text:
  #include <GL/glew.h>
#endif

#include "GLEWManager.hpp"

#include "Logger.hpp"

namespace mobagen {
  GLEWManager::GLEWManager(void) {
#ifndef ANDROID
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();

    if (GLEW_OK != err) {
      log_err("GLEW failed to initalize: %s", glewGetErrorString(err));
    }

    log_info("Status: Using GLEW %s", glewGetString(GLEW_VERSION));
#endif
  }

  GLEWManager::~GLEWManager(void) {}
}


text:
- I fuck you
- Baby
- God's in his heaven
- all right with the world


text:
file(REMOVE_RECURSE
  "CMakeFiles/test_pair.dir/pair.cpp.o"
  "test_pair.pdb"
  "test_pair"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/test_pair.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
package gumble

import (
	"github.com/golang/protobuf/proto"
	"github.com/layeh/gumble/gumble/MumbleProto"
)

// Channel represents a channel in the server's channel tree.
type Channel struct {
	// The channel's unique ID.
	ID uint32
	// The channel's name.
	Name string
	// The channel's parent. nil if the channel is the root channel.
	Parent *Channel
	// The channels directly underneath the channel.
	Children Channels
	// The channels that are linked to the channel.
	Links Channels
	// The users currently in the channel.
	Users Users
	// The channel's description. Contains the empty string if the channel does
	// not have a description, or if it needs to be requested.
	Description string
	// The channel's description hash. nil if Channel.Description has
	// been populated.
	DescriptionHash []byte
	// The maximum number of users allowed in the channel. If the value is zero,
	// the maximum number of users per-channel is dictated by the server's
	// "usersperchannel" setting.
	MaxUsers uint32
	// The position at which the channel should be displayed in an ordered list.
	Position int32
	// Is the channel temporary?
	Temporary bool

	client *Client
}

// IsRoot returns true if the channel is the server's root channel.
func (c *Channel) IsRoot() bool {
	return c.ID == 0
}

// Add will add a sub-channel to the given channel.
func (c *Channel) Add(name string, temporary bool) {
	packet := MumbleProto.ChannelState{
		Parent:    &c.ID,
		Name:      &name,
		Temporary: &temporary,
	}
	c.client.Conn.WriteProto(&packet)
}

// Remove will remove the given channel and all sub-channels from the server's
// channel tree.
func (c *Channel) Remove() {
	packet := MumbleProto.ChannelRemove{
		ChannelId: &c.ID,
	}
	c.client.Conn.WriteProto(&packet)
}

// SetName will set the name of the channel. This will have no effect if the
// channel is the server's root channel.
func (c *Channel) SetName(name string) {
	packet := MumbleProto.ChannelState{
		ChannelId: &c.ID,
		Name:      &name,
	}
	c.client.Conn.WriteProto(&packet)
}

// SetDescription will set the description of the channel.
func (c *Channel) SetDescription(description string) {
	packet := MumbleProto.ChannelState{
		ChannelId:   &c.ID,
		Description: &description,
	}
	c.client.Conn.WriteProto(&packet)
}

// SetPosition will set the position of the channel.
func (c *Channel) SetPosition(position int32) {
	packet := MumbleProto.ChannelState{
		ChannelId: &c.ID,
		Position:  &position,
	}
	c.client.Conn.WriteProto(&packet)
}

// SetMaxUsers will set the maximum number of users allowed in the channel.
func (c *Channel) SetMaxUsers(maxUsers uint32) {
	packet := MumbleProto.ChannelState{
		ChannelId: &c.ID,
		MaxUsers:  &maxUsers,
	}
	c.client.Conn.WriteProto(&packet)
}

// Find returns a channel whose path (by channel name) from the current channel
// is equal to the arguments passed.
//
// For example, given the following server channel tree:
//         Root
//           Child 1
//           Child 2
//             Child 2.1
//             Child 2.2
//               Child 2.2.1
//           Child 3
// To get the "Child 2.2.1" channel:
//         root.Find("Child 2", "Child 2.2", "Child 2.2.1")
func (c *Channel) Find(names ...string) *Channel {
	if len(names) == 0 {
		return c
	}
	for _, child := range c.Children {
		if child.Name == names[0] {
			return child.Find(names[1:]...)
		}
	}
	return nil
}

// RequestDescription requests that the actual channel description
// (i.e. non-hashed) be sent to the client.
func (c *Channel) RequestDescription() {
	packet := MumbleProto.RequestBlob{
		ChannelDescription: []uint32{c.ID},
	}
	c.client.Conn.WriteProto(&packet)
}

// RequestACL requests that the channel's ACL to be sent to the client.
func (c *Channel) RequestACL() {
	packet := MumbleProto.ACL{
		ChannelId: &c.ID,
		Query:     proto.Bool(true),
	}
	c.client.Conn.WriteProto(&packet)
}

// RequestPermission requests that the channel's permission information to be
// sent to the client.
//
// Note: the server will not reply to the request if the client has up-to-date
// permission information.
func (c *Channel) RequestPermission() {
	packet := MumbleProto.PermissionQuery{
		ChannelId: &c.ID,
	}
	c.client.Conn.WriteProto(&packet)
}

// Send will send a text message to the channel.
func (c *Channel) Send(message string, recursive bool) {
	textMessage := TextMessage{
		Message: message,
	}
	if recursive {
		textMessage.Trees = []*Channel{c}
	} else {
		textMessage.Channels = []*Channel{c}
	}
	c.client.Send(&textMessage)
}

// Permission returns the permissions the user has in the channel, or nil if
// the permissions are unknown.
func (c *Channel) Permission() *Permission {
	return c.client.permissions[c.ID]
}

// Link links the given channels to the channel.
func (c *Channel) Link(channel ...*Channel) {
	packet := MumbleProto.ChannelState{
		ChannelId: &c.ID,
		LinksAdd:  make([]uint32, len(channel)),
	}
	for i, ch := range channel {
		packet.LinksAdd[i] = ch.ID
	}
	c.client.Conn.WriteProto(&packet)
}

// Unlink unlinks the given channels from the channel. If no arguments are
// passed, all linked channels are unlinked.
func (c *Channel) Unlink(channel ...*Channel) {
	packet := MumbleProto.ChannelState{
		ChannelId: &c.ID,
	}
	if len(channel) == 0 {
		packet.LinksRemove = make([]uint32, len(c.Links))
		i := 0
		for channelID := range c.Links {
			packet.LinksRemove[i] = channelID
			i++
		}
	} else {
		packet.LinksRemove = make([]uint32, len(channel))
		for i, ch := range channel {
			packet.LinksRemove[i] = ch.ID
		}
	}
	c.client.Conn.WriteProto(&packet)
}


text:
<?php

class Profile extends User {
	public $follow_status;
	public $outfit_count;
	public $following_count;
	public $followers_count;
	public $photo_array;

	function __construct($user_id) {
	  $this->set_user_data($user_id);
	  $this->set_follow_status();
	  $this->set_outfit_count();
	  $this->set_following_count();
	  $this->set_followers_count();
	}

	// Move follower functions into its own class.
	public function set_follow_status () {
		if (isset($_SESSION['user_id'])) {
			$sql = "
				SELECT COUNT(1) AS rows
				FROM follower_directory
				WHERE followee_id = {$this->user_id}
				AND follower_id = {$_SESSION['user_id']};
			";
			$sql_dbo = mysql_query($sql);
			$sql_row = mysql_fetch_assoc($sql_dbo);
			$this->follow_status = $sql_row['rows'] > 0 ? 1 : 0;
		} else {
			$this->follow_status = 0;
		}
	}

	public function set_outfit_count () {
		$sql = "
			SELECT COUNT(1) AS rows
			FROM photo_directory
			WHERE user_id = {$this->user_id};
		";
		$sql_dbo = mysql_query($sql);
		$sql_row = mysql_fetch_assoc($sql_dbo);
		$count = $sql_row['rows'] > 0 ? $sql_row['rows'] : 0;
		$this->outfit_count = $count;
	}

	public function set_following_count () {
		$sql = "
			SELECT COUNT(1) AS rows
			FROM follower_directory
			WHERE follower_id = {$this->user_id};
		";
		$sql_dbo = mysql_query($sql);
		$sql_row = mysql_fetch_assoc($sql_dbo);
		$count = $sql_row['rows'] > 0 ? $sql_row['rows'] : 0;
		$this->following_count = $count;
	}

	public function set_followers_count () {
		$sql = "
			SELECT COUNT(1) AS rows
			FROM follower_directory
			WHERE followee_id = {$this->user_id};
		";
		$sql_dbo = mysql_query($sql);
		$sql_row = mysql_fetch_assoc($sql_dbo);
		$count = $sql_row['rows'] > 0 ? $sql_row['rows'] : 0;
		$this->followers_count = $count;
	}

	public static function follow ($followee_id) {
		if (isset($_SESSION['user_id'])) {
			$sql = "
				INSERT INTO follower_directory
				(follower_id, followee_id, timestamp)
				VALUES ({$_SESSION['user_id']}, {$followee_id}, NOW());
			";
			$do_it_bitch = mysql_query($sql);
		}
	}

	public static function unfollow ($followee_id) {
		if (isset($_SESSION['user_id'])) {
			$sql = "
				DELETE FROM follower_directory
				WHERE
				  follower_id = {$_SESSION['user_id']}
				AND
				  followee_id = {$followee_id};
			";
			$do_it_bitch = mysql_query($sql);
		}
	}

	public function print_profile () {
		echo '

								' . $this->user_handle . '

								follow_status == true ? 'following-true' : 'following-false') . '">
									' . ($this->follow_status == true ? 'Following' : 'Follow') . '

								Rinchen Olthang

								Rome based. Well-loved bicycles, worn-in Chuck Taylors and descriptive hand gestures. @rinchenDe

								http://rinchen.tumblr.com

								' . $this->outfit_count . '
								outfits

								' . $this->following_count . '
								following

								' . $this->followers_count . '
								followers

';
								Photo::print_photos_by_user($this->user_id);
		echo '

';
	}
}


text:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Haberdasher.Support.ExpressionBuilders
{
	public class GetterBuilder
	{
		public static Func<object, object> Build(PropertyInfo property) {
			var classType = property.DeclaringType;

			if (classType == null)
				return null;

			var model = Expression.Parameter(typeof(object), "model");

			var body = Expression.Property(Expression.Convert(model, classType), property.Name);

			var convertedBody = Expression.Convert(body, typeof (object));

			return Expression.Lambda<Func<object, object>>(convertedBody, model).Compile();
		}
	}
}


text:
Originally published: 2014-04-17 22:33:38
Last updated: 2014-04-17 22:33:39
Author: Keisuke URAGO

This code is find and print file extensions from directory.


text:
import os
import json
import logging
import numpy as np
from datetime import datetime

import tensorflow as tf
import tensorflow.contrib.slim as slim

def prepare_dirs_and_logger(config):
  formatter = logging.Formatter(
      "%(asctime)s:%(levelname)s::%(message)s")
  logger = logging.getLogger('tensorflow')

  for hdlr in logger.handlers:
    logger.removeHandler(hdlr)

  handler = logging.StreamHandler()
  handler.setFormatter(formatter)

  logger.addHandler(handler)
  logger.setLevel(tf.logging.INFO)

  if config.load_path:
    if config.load_path.startswith(config.task):
      config.model_name = config.load_path
    else:
      config.model_name = "{}_{}".format(config.task, config.load_path)
  else:
    config.model_name = "{}_{}".format(config.task, get_time())

  config.model_dir = os.path.join(config.log_dir, config.model_name)

  for path in [config.log_dir, config.data_dir, config.model_dir]:
    if not os.path.exists(path):
      os.makedirs(path)

def get_time():
  return datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

def show_all_variables():
  model_vars = tf.trainable_variables()
  slim.model_analyzer.analyze_vars(model_vars, print_info=True)

def save_config(model_dir, config):
  param_path = os.path.join(model_dir, "params.json")

  tf.logging.info("MODEL dir: %s" % model_dir)
  tf.logging.info("PARAM path: %s" % param_path)

  with open(param_path, 'w') as fp:
    json.dump(config.__dict__, fp,  indent=4, sort_keys=True)


text:
"""
# Excel to NGDS Service ArcGIS Tool
# Written by Jessica Good Alisdairi at the Arizona Geological Survey, May-Aug 2013
# This tool validates and converts a spreadsheet in an Excel file to a feature class
# ready to be deployed as an NDGS service.
"""

# import required modules
import csv
import arcpy
from arcpy import env
import os
import datetime
import dateutil.parser
try:
    import usginmodels
except:
    arcpy.AddError("There was a problem with the usginmodels. Check that http://schemas.usgin.org/contentmodels.json is up and running.")
    raise Exception
try:
    import xlrd
except:
    arcpy.AddError("Import of XLRD module failed.\nThe XLRD module can be downloaded from: http://pypi.python.org/pypi/xlrd")
    raise Exception

# Main function for the Excel to NGDS Feature ArcGIS Tool
def main(argv=None):
    # Don't allow overwriting
    arcpy.env.overwriteOutput = False

    # Get the parameters of the tool
    in_file = arcpy.GetParameterAsText(0)
    sheet_name = arcpy.GetParameterAsText(1)
    schema_name = arcpy.GetParameterAsText(2)
    service_name = arcpy.GetParameterAsText(3)
    layer_name = arcpy.GetParameterAsText(4)
    validate_only = arcpy.GetParameterAsText(5)

	# Get the path for the folder of the Excel file (used for output of GeoDB)
    path = os.path.dirname(in_file) + "\\"

    # Paste from development environment below here

    schema_uri = get_schema_uri(schema_name)
    layer_info = usginmodels.get_layer(schema_uri, layer_name)

    # If data is in a sheet in an Excel file convert to CSV, otherwise just read
    if sheet_name != "N/A":
        csv_file = excel_to_csv(in_file, sheet_name)
    else:
        csv_file = open(in_file)

    if csv_file:
        # Pass in the the CSV as a dictionary, the schema to validate against and the layer name
        valid, messages, dataCorrected, long_fields, srs = usginmodels.validate_file(csv_file, schema_uri, layer_name)
        print_errors(valid, messages, dataCorrected)

        try:
            if (validate_only == "false" and valid == True):
                CreateGeodatabase(path, service_name)

                arcpy.env.workspace = path + service_name + ".mdb"
                table = layer_name + "Table"

                MakeTable(table, layer_info.fields[1:][:-1], long_fields)
                InsertData(table, dataCorrected[1:], layer_info.fields[1:][:-1])
                CreateXYEventLayer(table, layer_name + "Layer", srs)
                CreateFeatureClass(layer_name + "Layer", layer_name, srs)

                # Make sure the final feature class has the same number of rows as the original table
                rowsTemp = int(arcpy.GetCount_management(table).getOutput(0))
                rowsFinal = int(arcpy.GetCount_management(layer_name).getOutput(0))
                if rowsTemp != rowsFinal:
                    rowsDeleted = rowsTemp - rowsFinal
                    if rowsDeleted == 1:
                        arcpy.AddError(str(rowsDeleted) + " row was deleted when converting the table to the feature class.")
                    else:
                        arcpy.AddError(str(rowsDeleted) + " rows were deleted when converting the table to the feature class.")
                    arcpy.AddError("Check the Lat & Long values for errors.")
                    raise Exception ("Conversion Failed.")
                else:
                    arcpy.Delete_management(table)

                arcpy.AddMessage("Conversion Successful!")

        except Exception as err:
            arcpy.AddError("Error: {0}".format(err))

    return

# Get a list of sheet names for the selected Excel file
def sheet_names(inExcel):
    wb = xlrd.open_workbook(inExcel)
    potential_sheets = [sht.name for sht in wb.sheets()]
    return potential_sheets

# Get the uri for the schema
def get_schema_uri(schema_name):
    versions_dict = {}
    models = usginmodels.get_models()
    for m in models:
      for v in m.versions:
        versions_dict[m.title + " " + v.version] = v.uri
    return versions_dict[schema_name]

# Convert the Excel sheet to CSV
def excel_to_csv(in_file, sheet_name):

    # Get the path for the folder of the Excel file (used for output of GeoDB)
    path = os.path.dirname(in_file) + "/"
    wb = xlrd.open_workbook(in_file)
    try:
        sht = wb.sheet_by_name(sheet_name)
    except:
        arcpy.AddError("Invalid Sheet Name")
        return None

    csv_rows = []
    for rownum in xrange(sht.nrows):
        row = sht.row_values(rownum)
        for colnum, col in enumerate(xrange(sht.ncols)):
            cell = sht.cell(rownum, colnum)

            # Check that conversion from unicode to utf-8 and Win-1252 encoding (used by the server) is possible
            if isinstance(cell.value, unicode):
                try:
                    cell.value = cell.value.encode("utf-8")
                    cell.value = cell.value.encode("windows-1252")
                except:
                    arcpy.AddError("Encoding Error! Found an unrecognized character in row " + str(rownum+1) + ", column " + str(colnum+1) + ": " + str(cell.value))
                    arcpy.AddError("CSV conversion failed")
                    return None

            # Excel stores #N/A with the internal code 42, change it back to #N/A
            if isinstance(cell.value, int):
                if cell.value == 42:
                    cell.value = "#N/A"

            # If the cell contains a date timestamp convert it to an iso date
            if cell.ctype == 3:
                if cell.value >= 61:
                    year, month, day, hour, minute, second = xlrd.xldate_as_tuple(cell.value, wb.datemode)
                    cell.value = datetime.datetime(year, month, day, hour, minute, second).isoformat()
                # Excel treats the first 60 days of 1900 as ambiguous (see Microsoft documentation)
                # Assume the dates are what is indicated in the cell
                else:
                    cell.value = datetime.datetime(1900, 1, 1, 0, 0, 0) + datetime.timedelta(days = cell.value - 1)
                    cell.value = cell.value.isoformat()

            # Remove decimal and trailing zeros that were added on Excel import
            if isinstance(cell.value, float):
                if cell.value == int(cell.value):
                    cell.value = '%d'%cell.value

            # Change any single quotes already in the data to double quotes since
            # entire data values in the csv are enclosed with single quotes
            if isinstance(cell.value, str):
                cell.value = str(cell.value).replace("\"","\"\"")

            row[colnum] = "\""+ str(cell.value) + "\""
        csv_rows.append(','.join(row))

    return csv_rows

# Print the error messages
def print_errors(valid, messages, dataCorrected):
    # Message counts
    msgs = {'warnCount': 0, 'warnMax': 25, 'errCount': 0, 'errMax': 25, 'noteCount': 0, 'noteMax': 5}

    if valid and messages:
        arcpy.AddMessage("The document is valid if the changes below are acceptable.")
    elif valid and not messages:
        arcpy.AddMessage("The document is valid.")
    else:
        arcpy.AddMessage("Not Valid! Error messages:")

    # Only print notices, warnings and error messages
    for m in messages:
        if "Warning!" in m:
            if msgs['warnCount'] < msgs['warnMax']:
                arcpy.AddWarning(m)
                msgs['warnCount'] += 1
            elif msgs['warnCount'] == msgs['warnMax']:
                arcpy.AddWarning("Max number of warning messages reached (" + str(msgs['warnMax']) + "). Not showing anymore warnings that are not errors.")
                msgs['warnCount'] += 1
        elif "Error!" in m:
            if msgs['errCount'] < msgs['errMax']:
                arcpy.AddError(m)
                msgs['errCount'] += 1
            elif msgs['errCount'] == msgs['errMax']:
                arcpy.AddError("Max number of error messages reached (" + str(msgs['errMax']) + "). Fix indicated errors and import again.")
                msgs['errCount'] += 1
        elif "Notice!" in m:
            if msgs['noteCount'] < msgs['noteMax']:
                arcpy.AddMessage(m)
                msgs['noteCount'] += 1
            elif msgs['noteCount'] == msgs['noteMax']:
                arcpy.AddMessage("Max number of notices reached (" + str(msgs['noteMax']) + "). Not showing anymore messages that are not warnings or errors.")
                msgs['noteCount'] += 1
        else:
            arcpy.AddMessage(m)
    return

# Create the personal Geodatabase (Microsoft Access DB)
def CreateGeodatabase(path, name):
    arcpy.AddMessage("Creating Geodatabase ...")
    arcpy.CreatePersonalGDB_management(path, name)
    arcpy.AddMessage("Finished Creating Geodatabase.")
    return

# Create the output table, add all required fields for that table
def MakeTable(table, fields_info, long_fields):
    arcpy.AddMessage("Creating Table in ArcGIS ...")
    arcpy.CreateTable_management(env.workspace, table)

    # Add the fields to the table
    for i in range(0, len(fields_info)):
        if (long_fields[fields_info[i].field_name] == True):
           arcpy.AddField_management(table, fields_info[i].field_name, "TEXT", "", "", 2147483647)
        else:
            if fields_info[i].field_type == "string":
                arcpy.AddField_management(table, fields_info[i].field_name, "TEXT")
                arcpy.AddMessage("  " + fields_info[i].field_name + " added with type TEXT")
            elif fields_info[i].field_type == "double":
                arcpy.AddField_management(table, fields_info[i].field_name, "DOUBLE")
                arcpy.AddMessage("  " + fields_info[i].field_name + " added with type DOUBLE")
            elif fields_info[i].field_type == "dateTime":
                arcpy.AddField_management(table, fields_info[i].field_name, "DATE")
                arcpy.AddMessage("  " + fields_info[i].field_name + " added with type DATE")
            else:
                arcpy.Error(fields_info[i].field_type + " is not a valid field type for " + fields_info[i].field_name)
                return

    arcpy.AddMessage("Finished Creating Table.")
    return

# Insert the data rows in the the table
def InsertData(table, data, fields_info):
    arcpy.AddMessage("Inserting Rows ...")

    field_names = []
    field_types = []
    for field in fields_info:
        field_names.append(field.field_name)
        field_types.append(field.field_type)

    # If running on 10.1, use da insert cursor
    if arcpy.GetInstallInfo()['Version'] == '10.1':
        insertCur = arcpy.da.InsertCursor(table, field_names)
        for row in data:
            insertCur.insertRow(row)

    # Otherwise use original insert cursor
    else:
        insertCur = arcpy.InsertCursor(table)
        for d in data:
            row = insertCur.newRow()
            for x in range(len(d)):
                if d[x] == "":
                    row.setValue(field_names[x], None)
                else:
                    if field_types[x] == "dateTime":
                        row.setValue(field_names[x], dateutil.parser.parse(d[x]))
                    else:
                        row.setValue(field_names[x], d[x])
            insertCur.insertRow(row)
    del row, insertCur

    arcpy.AddMessage("Finished Inserting Rows")
    return

# Convert the Table to an XY Event Layer in ArcGIS, using EPSG:4326 (WGS84) as the projection
def CreateXYEventLayer(table, layer, srs):
    arcpy.AddMessage("Converting Table to XY Event Layer ...")

    # Set the spatial reference
    if srs == "EPSG:4326":
        spRef = os.path.dirname(__file__) + "\\WGS 1984.prj"
    elif srs == "EPSG:4269":
        spRef = os.path.dirname(__file__) + "\\NAD 1983.prj"
    elif srs == "EPSG:4267":
        spRef = os.path.dirname(__file__) + "\\NAD 1927.prj"
    else:
        arcpy.AddWarning("Unable to determine spatial reference system. The reference system for the data will need to be defined and then reprojected to EPSG:4326 (WGS84).")
        spRef = os.path.dirname(__file__) + "\\WGS 1984.prj"
    arcpy.AddMessage("Spatial Reference System of data is " + srs)

    try:
        testOpen = open(spRef)
    except:
        arcpy.AddError("Unable to find the .prj files that should be located in the same folder as the script. Download the tool again.")
        raise Exception ("Missing Needed File.")

    # Create the XY Event Layer
    try:
        arcpy.MakeXYEventLayer_management(table, "LongDegreeWGS84", "LatDegreeWGS84", layer, spRef)
    except:
        try:
            arcpy.MakeXYEventLayer_management(table, "LongDegree", "LatDegree", layer, spRef)
        except:
            arcpy.AddError("Unable to determine Lat and Long fields.")
            raise Exception ("Conversion Failed.")

    arcpy.AddMessage("Finished Converting Table.")
    return

# Create the Feature Class in ArcGIS & reproject if SRS doesn't indicate EPSG:4326 (WGS84)
def CreateFeatureClass(layer, featureClass, srs):
    arcpy.AddMessage("Creating Feature Class ....")

    arcpy.CopyFeatures_management(layer, featureClass)

    if srs == "EPSG:4267" or srs == "EPSG:4269":
        if srs == "EPSG:4267":
            spRef = os.path.dirname(__file__) + "\\NAD 1927.prj"
            trans = "NAD_1927_To_WGS_1984_4"
        if srs == "EPSG:4269":
            spRef = os.path.dirname(__file__) + "\\NAD 1983.prj"
            trans = "NAD_1983_To_WGS_1984_1"

        inCS = spRef
        outCS = os.path.dirname(__file__) + "\\WGS 1984.prj"

        arcpy.AddMessage("Reprojecting from " + srs + " to EPSG:4326 (WGS84) using the transformation " + trans + "....")
        arcpy.AddWarning("If the data indicates a region other than the continental US you may need to use a different transformation.")

        # Reproject the feature class to WGS 84 and save in a temporary feature class
        featureClassTemp = featureClass + "Temp"
        arcpy.Project_management(featureClass, featureClassTemp, outCS, trans, inCS)

        try:
            # Calculate XY coordinates for the points in the feature class
            arcpy.AddXY_management(featureClassTemp)

        except:
            # Delete the temporary feature class since the calculation of the new X & Y values failed
            arcpy.Delete_management(featureClassTemp)

            # The default maximum number of records on which calculations can be performed is 9500.
            # Upon failure ouptut a message telling the user how to increase this number.
            installDir = arcpy.GetInstallInfo()['InstallDir']
            arcpy.AddError("The MaxLocksPerFile value needs to be increased before reprojection.")
            arcpy.AddError("Open the ArcMap Advanced Settings utility in " + installDir + "Utilities\\AdvancedArcMapSettings.exe.")
            arcpy.AddError("Click the Editor tab and update the 'Jet Engine max # of records to calculate' value to any number larger than the number of records in the current dataset.")
            arcpy.AddError("Run the tool again.")
            raise Exception ("Reprojection Failed.")

        # Replace the value in the Lat & Long fields with the calculated XY coordinates
        # Update the SRS column to WGS 84
        rows = arcpy.UpdateCursor(featureClassTemp)
        for row in rows:
            try:
                row.LatDegree = row.POINT_Y
                row.LongDegree = row.POINT_X
            except:
                try:
                    row.LatDegreeWGS84 = row.POINT_Y
                    row.LongDegreeWGS84 = row.POINT_X
                except:
                    raise Exception ("Unable to determine Lat & Long columns. Conversion Failed.")
            row.SRS = "EPSG:4326"
            rows.updateRow(row)

        # Delete cursor and row objects to remove locks on the data
        del row, rows

        arcpy.DeleteField_management(featureClassTemp, ["POINT_Y", "POINT_X"])
        arcpy.AddMessage("Finished Reprojecting.")

        # Delete the original feature class and rename the temporary feature class the same as the original
        arcpy.Delete_management(featureClass)
        arcpy.Rename_management(featureClassTemp, featureClass)

    arcpy.AddMessage("Finished Creating Feature Class.")
    return

if __name__ == "__main__":
    main()


text:
import Ember from 'ember';
import startApp from '../helpers/start-app';

var App;

module('Integration: Load Thanks Page', {
  setup: function() {
    App = startApp();
  },
  teardown: function() {
    Ember.run(App, 'destroy');
  }
});

test('visiting /thanks', function() {
  visit('/thanks');

  andThen(function() {
    equal(currentPath(), 'thanks');
  });
});

test('loads thanks element', function() {
  visit('/thanks');

  andThen(function() {
    equal(find('.thank-you-img-container').length, 1);
  });
});


text:
layout: blog_feed
tag: details
---


text:
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// 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

package com.google.devtools.build.lib.rules.config;

import static com.google.devtools.build.lib.analysis.starlark.FunctionTransitionUtil.COMMAND_LINE_OPTION_PREFIX;

import com.google.common.collect.Sets;
import com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition;
import com.google.devtools.build.lib.analysis.starlark.StarlarkTransition.Settings;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.skylarkbuildapi.config.ConfigGlobalLibraryApi;
import com.google.devtools.build.lib.skylarkbuildapi.config.ConfigurationTransitionApi;
import com.google.devtools.build.lib.syntax.Dict;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.Sequence;
import com.google.devtools.build.lib.syntax.Starlark;
import com.google.devtools.build.lib.syntax.StarlarkCallable;
import com.google.devtools.build.lib.syntax.StarlarkSemantics;
import com.google.devtools.build.lib.syntax.StarlarkThread;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * Implementation of {@link ConfigGlobalLibraryApi}.
 *
 * <p>A collection of top-level Starlark functions pertaining to configuration.
 */
public class ConfigGlobalLibrary implements ConfigGlobalLibraryApi {

  @Override
  public ConfigurationTransitionApi transition(
      StarlarkCallable implementation,
      Sequence<?> inputs, // <String> expected
      Sequence<?> outputs, // <String> expected
      StarlarkThread thread)
      throws EvalException {
    StarlarkSemantics semantics = thread.getSemantics();
    List<String> inputsList = Sequence.cast(inputs, String.class, "inputs");
    List<String> outputsList = Sequence.cast(outputs, String.class, "outputs");
    validateBuildSettingKeys(
        inputsList, Settings.INPUTS, semantics.experimentalStarlarkConfigTransitions());
    validateBuildSettingKeys(
        outputsList, Settings.OUTPUTS, semantics.experimentalStarlarkConfigTransitions());
    return StarlarkDefinedConfigTransition.newRegularTransition(
        implementation, inputsList, outputsList, semantics, thread);
  }

  @Override
  public ConfigurationTransitionApi analysisTestTransition(
      Dict<?, ?> changedSettings, // <String, String> expected
      StarlarkThread thread)
      throws EvalException {
    Map<String, Object> changedSettingsMap =
        Dict.cast(changedSettings, String.class, Object.class, "changed_settings dict");
    validateBuildSettingKeys(changedSettingsMap.keySet(), Settings.OUTPUTS, true);
    return StarlarkDefinedConfigTransition.newAnalysisTestTransition(
        changedSettingsMap, thread.getCallerLocation());
  }

  private void validateBuildSettingKeys(
      Iterable<String> optionKeys,
      Settings keyErrorDescriptor,
      boolean starlarkTransitionsEnabled)
      throws EvalException {

    HashSet<String> processedOptions = Sets.newHashSet();
    String singularErrorDescriptor = keyErrorDescriptor == Settings.INPUTS ? "input" : "output";

    for (String optionKey : optionKeys) {
      if (!optionKey.startsWith(COMMAND_LINE_OPTION_PREFIX)) {
        if (!starlarkTransitionsEnabled) {
          throw Starlark.errorf(
              "transitions on Starlark-defined build settings is experimental and "
                  + "disabled by default. This API is in development and subject to change at any"
                  + "time. Use --experimental_starlark_config_transitions to use this experimental "
                  + "API.");
        }
        try {
          Label.parseAbsoluteUnchecked(optionKey);
        } catch (IllegalArgumentException e) {
          throw Starlark.errorf(
              "invalid transition %s '%s'. If this is intended as a native option, "
                  + "it must begin with //command_line_option: %s",
              singularErrorDescriptor, optionKey, e.getMessage());
        }
      } else {
        String optionName = optionKey.substring(COMMAND_LINE_OPTION_PREFIX.length());
        if (optionName.startsWith("experimental_") || optionName.startsWith("incompatible_")) {
          throw Starlark.errorf(
              "Invalid transition %s '%s'. Cannot transition on --experimental_* or "
                  + "--incompatible_* options",
              singularErrorDescriptor, optionKey);
        }
      }
      if (!processedOptions.add(optionKey)) {
        throw Starlark.errorf("duplicate transition %s '%s'", singularErrorDescriptor, optionKey);
      }
    }
  }
}


text:
class CreatePayloadLogEntriesIndex < ActiveRecord::Migration
  def up
    add_index :payload_log_entries, [:project_id, :created_at]
  end

  def down
    remove_index :payload_log_entries, :column => [:project_id, :created_at]
  end
end


text:
import React from 'react';
// const ErrorPageContainer = require('../containers/ErrorPageContainer');

class DataWrapper extends React.Component {

  getChildContext() {
    return {
      data: this.props.data
    };
  }

  render() {
    if (typeof (this.props.data.data) != 'undefined') {
      if (typeof (this.props.data.data.error) == 'undefined') {
        return this.props.children;
      } else {
        return <div> Error</div>
      }
    } else {
      return this.props.children;
    }
  }

}

DataWrapper.childContextTypes = {
  data: React.PropTypes.oneOfType([
    React.PropTypes.object,
    React.PropTypes.string,
    React.PropTypes.array
  ]).isRequired
};

export default DataWrapper;


text:
package org.bitcoinj.governance;

/**
 * Created by Hash Engineering on 6/5/2018.
 */
public class SuperblockException extends Exception {
    public SuperblockException(String message) {
        super(message);
    }
}


text:
$(function(){ $(document).foundation(); });

// Sticky footer js
// Thanks to Charles Smith for this -- http://foundation.zurb.com/forum/posts/629-sticky-footer
$(window).bind("load", function () {
  var footer = $("#footer");
  var pos = footer.position();
  var height = $(window).height();
  height = height - pos.top;
  height = height - footer.height();
  if (height > 0) {
      footer.css({
          'margin-top': height + 'px'
      });
  }
});

// Flash fade
$(function() {
   $('.alert-box').fadeIn('normal', function() {
      $(this).delay(3700).fadeOut();
   });
});

// Datepicker code
$(function() {
  $(".datepicker").datepicker({
    format: 'mm/dd/YYYY'
  });
});


text:
from __future__ import print_function, unicode_literals

import json

from gratipay.testing import Harness, P

class Tests(Harness):

    def make_participant(self, *a, **kw):
        kw['claimed_time'] = 'now'
        return Harness.make_participant(self, *a, **kw)

    def test_on_key_gives_gratipay(self):
        self.make_participant('alice', last_bill_result='')
        data = json.loads(self.client.GET('/~alice/public.json').body)
        assert data['on'] == 'gratipay'

    def test_anonymous_gets_taking(self):
        alice = self.make_participant('alice', last_bill_result='')
        Enterprise = self.make_team(is_approved=True)
        alice.set_payment_instruction(Enterprise, '1.00')
        data = json.loads(self.client.GET('/~picard/public.json').body)
        assert data['taking'] == '1.00'

    def test_anonymous_gets_giving(self):
        alice = self.make_participant('alice', last_bill_result='')
        Enterprise = self.make_team(is_approved=True)
        alice.set_payment_instruction(Enterprise, '1.00')
        data = json.loads(self.client.GET('/~alice/public.json').body)
        assert data['giving'] == '1.00'

    def test_anonymous_gets_null_giving_if_user_anonymous(self):
        alice = self.make_participant('alice', last_bill_result='', anonymous_giving=True)
        Enterprise = self.make_team(is_approved=True)
        alice.set_payment_instruction(Enterprise, '1.00')
        data = json.loads(self.client.GET('/~alice/public.json').body)
        assert data['giving'] == None

    def test_access_control_allow_origin_header_is_asterisk(self):
        self.make_participant('alice', last_bill_result='')
        response = self.client.GET('/~alice/public.json')
        assert response.headers['Access-Control-Allow-Origin'] == '*'

    def test_jsonp_works(self):
        alice = self.make_participant('alice', last_bill_result='')
        Enterprise = self.make_team(is_approved=True)
        alice.set_payment_instruction(Enterprise, '3.00')
        picard = P('picard')
        raw = self.client.GxT('/~picard/public.json?callback=foo', auth_as='picard').body
        assert raw == '''\
foo({
    "avatar": null,
    "elsewhere": {
        "github": {
            "id": %(elsewhere_id)s,
            "user_id": "%(user_id)s",
            "user_name": "picard"
        }
    },
    "giving": "0.00",
    "id": %(user_id)s,
    "ngiving_to": 0,
    "ntaking_from": 1,
    "on": "gratipay",
    "taking": "3.00",
    "username": "picard"
})''' % dict(user_id=picard.id, elsewhere_id=picard.get_accounts_elsewhere()['github'].id)


text:
One or more of the batch jobs have not indicated a successful run in awhile.
You are expected to debug why the job is not working and try to repair.

* [prometheus console](http://prod.example.org:9093/status)
* [alertmanger console](http://prod.example.org:9093/status)
* [man periodic](https://www.freebsd.org/cgi/man.cgi?query=periodic&format=html)


text:
<?php
namespace ZBateson\MailMimeParser\Message\Part;

use LegacyPHPUnit\TestCase;
use GuzzleHttp\Psr7;

/**
 * PartBuilderTest
 *
 * @group PartBuilder
 * @group MessagePart
 * @covers ZBateson\MailMimeParser\Message\Part\PartBuilder
 * @author Zaahid Bateson
 */
class PartBuilderTest extends TestCase
{
    private $mockMessagePartFactory;

    protected function legacySetUp()
    {
        $this->mockMessagePartFactory = $this->getMockBuilder('ZBateson\MailMimeParser\Message\Part\Factory\MessagePartFactory')
            ->disableOriginalConstructor()
            ->setMethods(['newInstance'])
            ->getMock();
    }

    private function newMockHeaderContainer()
    {
        return $this->getMockBuilder('ZBateson\MailMimeParser\Header\HeaderContainer')
            ->disableOriginalConstructor()
            ->getMock();
    }

    public function testCanHaveHeaders()
    {
        $mockHeader = $this->getMockBuilder('ZBateson\MailMimeParser\Header\ParameterHeader')
            ->disableOriginalConstructor()
            ->setMethods(['getValueFor'])
            ->getMock();
        $mockHeader->expects($this->any())
            ->method('getValueFor')
            ->with('boundary')
            ->willReturn('Castle Black');

        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );

        $this->assertTrue($instance->canHaveHeaders());

        $hc = $this->newMockHeaderContainer();
        $parent = new PartBuilder(
            $this->mockMessagePartFactory,
            $hc
        );
        $hc->expects($this->once())
            ->method('add')
            ->with('CONTENT-TYPE', 'kookoo-keekee');
        $hc->expects($this->once())
            ->method('get')
            ->with('Content-Type')
            ->willReturn($mockHeader);
        $parent->addHeader('CONTENT-TYPE', 'kookoo-keekee');
        $parent->addChild($instance);

        $parent->setEndBoundaryFound('--Castle Black--');
        $this->assertFalse($instance->canHaveHeaders());
    }

    public function testAddChildren()
    {
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );
        $children = [
            new PartBuilder(
                $this->mockMessagePartFactory,
                $this->newMockHeaderContainer()
            ),
            new PartBuilder(
                $this->mockMessagePartFactory,
                $this->newMockHeaderContainer()
            )
        ];
        foreach ($children as $child) {
            $instance->addChild($child);
        }
        $this->assertEquals($children, $instance->getChildren());
        $this->assertSame($instance, $children[0]->getParent());
        $this->assertSame($instance, $children[1]->getParent());
    }

    public function testAddAndGetRawHeaders()
    {
        $hc = $this->newMockHeaderContainer();
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $hc
        );
        $hc->expects($this->exactly(3))
            ->method('add')
            ->withConsecutive(
                [ 'Mime-VERSION', '42' ],
                [ 'Content-TYPE', 'text/blah; blooh' ],
                [ 'X-Northernmost-Castle', 'Castle black' ]
            );
        $instance->addHeader('Mime-VERSION', '42');
        $instance->addHeader('Content-TYPE', 'text/blah; blooh');
        $instance->addHeader('X-Northernmost-Castle', 'Castle black');

        $this->assertSame($hc, $instance->getHeaderContainer());
    }

    public function testIsMime()
    {
        $hc = $this->newMockHeaderContainer();
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $hc
        );
        $hc->expects($this->exactly(5))
            ->method('exists')
            ->withConsecutive(
                [ 'Content-Type', 0 ],
                [ 'Content-Type', 0 ],
                [ 'Mime-Version', 0 ],
                [ 'Content-Type', 0 ],
                [ 'Mime-Version', 0 ]
            )
            ->willReturnOnConsecutiveCalls(true, false, true, false, false);

        $this->assertTrue($instance->isMime());
        $this->assertTrue($instance->isMime());
        $this->assertFalse($instance->isMime());
    }

    public function testGetContentType()
    {
        $hc = $this->newMockHeaderContainer();
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $hc
        );
        $hc->expects($this->once())
            ->method('get')
            ->with('Content-Type', 0)
            ->willReturn(true);
        $this->assertTrue($instance->getContentType());
    }

    public function testGetMimeBoundary()
    {
        $mockHeader = $this->getMockBuilder('ZBateson\MailMimeParser\Header\ParameterHeader')
            ->disableOriginalConstructor()
            ->setMethods(['getValueFor'])
            ->getMock();
        $mockHeader->expects($this->any())
            ->method('getValueFor')
            ->with('boundary')
            ->willReturn('Castle Black');

        $hc = $this->newMockHeaderContainer();
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $hc
        );
        $hc->expects($this->once())
            ->method('get')
            ->with('Content-Type', 0)
            ->willReturn($mockHeader);
        $this->assertEquals('Castle Black', $instance->getMimeBoundary());
    }

    public function testIsMultiPart()
    {
        $mockHeader = $this->getMockBuilder('ZBateson\MailMimeParser\Header\ParameterHeader')
            ->disableOriginalConstructor()
            ->setMethods(['getValue'])
            ->getMock();
        $mockHeader->expects($this->any())
            ->method('getValue')
            ->willReturnOnConsecutiveCalls('multipart/kookoo', 'text/plain');

        $hc = $this->newMockHeaderContainer();
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $hc
        );
        $hc->expects($this->atLeastOnce())
            ->method('get')
            ->with('Content-Type', 0)
            ->willReturn($mockHeader);

        $this->assertTrue($instance->isMultiPart());
        $this->assertFalse($instance->isMultiPart());
    }

    public function testSetEndBoundaryFound()
    {
        $mockHeader = $this->getMockBuilder('ZBateson\MailMimeParser\Header\ParameterHeader')
            ->disableOriginalConstructor()
            ->setMethods(['getValueFor'])
            ->getMock();
        $mockHeader->expects($this->any())
            ->method('getValueFor')
            ->with('boundary')
            ->willReturn('Castle Black');

        $hc = $this->newMockHeaderContainer();
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $hc
        );
        $hc->expects($this->atLeastOnce())
            ->method('get')
            ->with('Content-Type', 0)
            ->willReturn($mockHeader);

        $this->assertFalse($instance->isParentBoundaryFound());
        $this->assertFalse($instance->setEndBoundaryFound('Somewhere... obvs not Castle Black'));
        $this->assertFalse($instance->setEndBoundaryFound('Castle Black'));
        $this->assertTrue($instance->setEndBoundaryFound('--Castle Black'));
        $this->assertFalse($instance->isParentBoundaryFound());
        $this->assertTrue($instance->setEndBoundaryFound('--Castle Black--'));

        $child = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );
        $instance->addChild($child);
        $this->assertEquals($instance, $child->getParent());
        $this->assertCount(0, $instance->getChildren());
        $this->assertFalse($child->canHaveHeaders());
    }

    public function testSetEndBoundaryFoundWithParent()
    {
        $mockParentHeader = $this->getMockBuilder('ZBateson\MailMimeParser\Header\ParameterHeader')
            ->disableOriginalConstructor()
            ->setMethods(['getValueFor'])
            ->getMock();
        $mockParentHeader->expects($this->any())
            ->method('getValueFor')
            ->with('boundary')
            ->willReturn('King\'s Landing');

        $mockHeader = $this->getMockBuilder('ZBateson\MailMimeParser\Header\ParameterHeader')
            ->disableOriginalConstructor()
            ->setMethods(['getValueFor'])
            ->getMock();
        $mockHeader->expects($this->any())
            ->method('getValueFor')
            ->with('boundary')
            ->willReturn(null);

        $hc = $this->newMockHeaderContainer();
        $hc->expects($this->atLeastOnce())
            ->method('get')
            ->with('Content-Type', 0)
            ->willReturn($mockHeader);
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $hc
        );

        $hcp = $this->newMockHeaderContainer();
        $hcp->expects($this->atLeastOnce())
            ->method('get')
            ->with('Content-Type', 0)
            ->willReturn($mockParentHeader);
        $parent = new PartBuilder(
            $this->mockMessagePartFactory,
            $hcp
        );
        $parent->addChild($instance);

        $this->assertSame($parent, $instance->getParent());
        $this->assertFalse($instance->isParentBoundaryFound());
        $this->assertFalse($instance->setEndBoundaryFound('Somewhere... obvs not Castle Black'));
        $this->assertFalse($instance->setEndBoundaryFound('King\'s Landing'));
        $this->assertTrue($instance->setEndBoundaryFound('--King\'s Landing'));
        $this->assertTrue($instance->isParentBoundaryFound());
    }

    public function testSetEof()
    {
        $mockParentHeader = $this->getMockBuilder('ZBateson\MailMimeParser\Header\ParameterHeader')
            ->disableOriginalConstructor()
            ->setMethods(['getValueFor'])
            ->getMock();
        $mockParentHeader->expects($this->any())
            ->method('getValueFor')
            ->with('boundary')
            ->willReturn('King\'s Landing');

        $mockHeader = $this->getMockBuilder('ZBateson\MailMimeParser\Header\ParameterHeader')
            ->disableOriginalConstructor()
            ->setMethods(['getValueFor'])
            ->getMock();
        $mockHeader->expects($this->any())
            ->method('getValueFor')
            ->with('boundary')
            ->willReturn(null);

        $hc = $this->newMockHeaderContainer();
        $hc->expects($this->atLeastOnce())
            ->method('get')
            ->with('Content-Type', 0)
            ->willReturn($mockHeader);
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $hc
        );

        $hcp = $this->newMockHeaderContainer();
        $hcp->expects($this->atLeastOnce())
            ->method('get')
            ->with('Content-Type', 0)
            ->willReturn($mockParentHeader);
        $parent = new PartBuilder(
            $this->mockMessagePartFactory,
            $hcp
        );
        $parent->addChild($instance);

        $this->assertSame($parent, $instance->getParent());
        $this->assertFalse($instance->isParentBoundaryFound());
        $this->assertFalse($instance->setEndBoundaryFound('Somewhere... obvs not Castle Black'));
        $this->assertFalse($instance->setEndBoundaryFound('Szprotka'));
        $this->assertFalse($instance->setEndBoundaryFound('--szprotka'));
        $this->assertFalse($instance->isParentBoundaryFound());
        $instance->setEof();
        $this->assertTrue($instance->isParentBoundaryFound());
        $this->assertTrue($parent->isParentBoundaryFound());
    }

    public function testSetStreamPartPosAndGetFilename()
    {
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );
        $instance->setStreamPartStartPos(42);
        $instance->setStreamPartEndPos(84);
        $this->assertEquals(42, $instance->getStreamPartStartOffset());
        $this->assertEquals(42, $instance->getStreamPartLength());
    }

    public function testSetStreamContentPosAndGetFilename()
    {
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );
        $instance->setStreamPartStartPos(11);
        $instance->setStreamContentStartPos(42);
        $instance->setStreamPartAndContentEndPos(84);
        $this->assertEquals(11, $instance->getStreamPartStartOffset());
        $this->assertEquals(84 - 11, $instance->getStreamPartLength());
        $this->assertEquals(42, $instance->getStreamContentStartOffset());
        $this->assertEquals(84 - 42, $instance->getStreamContentLength());
    }

    public function testSetStreamContentPosAndGetFilenameWithParent()
    {
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );
        $parent = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );
        $super = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );
        $parent->addChild($instance);
        $super->addChild($parent);

        $super->setStreamPartStartPos(0);
        $super->setStreamContentStartPos(3);
        $super->setStreamPartAndContentEndPos(3);

        $parent->setStreamPartStartPos(11);
        $parent->setStreamContentStartPos(13);
        $parent->setStreamPartAndContentEndPos(20);

        $instance->setStreamPartStartPos(22);
        $instance->setStreamContentStartPos(42);
        $instance->setStreamPartAndContentEndPos(84);

        $this->assertEquals(42 - $parent->getStreamPartStartOffset(), $instance->getStreamContentStartOffset());
        $this->assertEquals(84 - 42, $instance->getStreamContentLength());
        $this->assertEquals(22 - $parent->getStreamPartStartOffset(), $instance->getStreamPartStartOffset());
        $this->assertEquals(84 - 22, $instance->getStreamPartLength());

        $this->assertEquals(13, $parent->getStreamContentStartOffset());
        $this->assertEquals(20 - 13, $parent->getStreamContentLength());
        $this->assertEquals(11, $parent->getStreamPartStartOffset());
        $this->assertEquals(84 - 11, $parent->getStreamPartLength());

        $this->assertEquals(3, $super->getStreamContentStartOffset());
        $this->assertEquals(0, $super->getStreamContentLength());
        $this->assertEquals(0, $super->getStreamPartStartOffset());
        $this->assertEquals(84, $super->getStreamPartLength());
    }

    public function testSetAndGetProperties()
    {
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );
        $instance->setProperty('island', 'Westeros');
        $instance->setProperty('capital', 'King\'s Landing');
        $this->assertSame('Westeros', $instance->getProperty('island'));
        $this->assertSame('King\'s Landing', $instance->getProperty('capital'));
        $this->assertNull($instance->getProperty('Joffrey\'s kindness'));
    }

    public function testCreateMessagePart()
    {
        $stream = Psr7\stream_for('thingsnstuff');
        $instance = new PartBuilder(
            $this->mockMessagePartFactory,
            $this->newMockHeaderContainer()
        );

        $this->mockMessagePartFactory->expects($this->once())
            ->method('newInstance')
            ->with($instance, $stream)
            ->willReturn(true);
        $this->assertTrue($instance->createMessagePart($stream));
    }
}


text:
#
#
# /* See http://www.lslboost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_ENUM_SHIFTED_PARAMS_HPP
# define BOOST_PREPROCESSOR_ENUM_SHIFTED_PARAMS_HPP
#
# include <lslboost/preprocessor/repetition/enum_shifted_params.hpp>
#
# endif


text:
<?php
header('Content-type: application/json');
echo CJSON::encode($return);
Yii::app()->end();
?>


text:
namespace Network {
namespace Unix {

class LinuxNetwork : public ANetwork
{
private:
  static std::atomic<bool>   _init;

public:
  LinuxNetwork(size_t maxEvents = 200);
  virtual ~LinuxNetwork();

  void registerClient(const std::weak_ptr<Network::ABasicSocket>& cli) override;
  void registerListener(const std::weak_ptr<Network::AListenSocket>& listener) override;

  void poll(bool block) override;

protected:
  void updateRequest();
  void dispatchEvent(struct epoll_event* ev);

protected:
  int _pollFd;
  size_t _maxEvents;
  struct epoll_event* _events;
};
};
};

#endif // UNIXNETWORK_H


text:
module Hashtags
  class ResourcesController < ApplicationController
    def index
      respond_to do |format|
        format.json { render json: resources_as_json, root: false }
      end
    end

    private

    def resources_as_json
      return unless hashtag_class.present?
      @resources_as_json ||= hashtag_class.resources_for_query(query)
    end

    def query
      URI.decode(params.fetch(:q, nil).to_s)
    end

    def hashtag_class
      class_name.safe_constantize
    end

    def class_name
      params[:class_name]
    end
  end
end


text:
<project name="Expr" default="help">

	<property file="../../../build.properties"/>

	<target name="jflextask" unless="jflex.available" description="creates JFlex Ant task">
		<taskdef name="jflex" classname="JFlex.anttask.JFlexTask" classpath="${jflex_jar}"/>
		<property name="jflex.available" value="yes"/>
	</target>

	<target name="beavertask" unless="beaver.available" description="creates Beaver Ant task">
		<taskdef name="beaver" classname="beaver.comp.run.AntTask" classpath="../../../lib/beaver.jar"/>
		<property name="beaver.available" value="yes"/>
	</target>

	<target name="help" description="show help message">
		<echo message="Ant build file for Calculator example. Useful targets:"/>
		<echo message=""/>
		<echo message="clean:  remove compiled files"/>
		<echo message="make:   compiles the example"/>
	</target>

	<target name="scanner" depends="jflextask" description="generate scanner">
		<jflex file="expr.flex" nobak="yes"/>
	</target>

	<target name="parser" depends="beavertask" description="generate parser">
		<beaver file="expr.grammar" terminalNames="no"/>
	</target>

	<target name="compile" description="compile all classes">
		<javac srcdir="." destdir="../.." includes="*.java" source="1.3" debug="${debug.info}">
			<classpath>
				<pathelement location="../.."/>
				<pathelement location="../../../lib/beaver-rt.jar"/>
			</classpath>
        </javac>
	</target>

	<target name="make" depends="scanner,parser,compile" description="makes the example"/>

	<target name="clean" description="remove compiled files">
		<delete>
			<fileset dir="." includes="*.class,*.java,*.spec,*.*~" excludes="Calculator.java,Expr.java"/>
		</delete>
	</target>

</project>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>O-Index (JavaFX 3D Model Importers)</title>
<meta name="date" content="2014-02-09">
<link rel="stylesheet" type="text/css" href="../stylesheet-im.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

JavaFX 3D Model Importers

Prev Letter

Next Letter

Frames

No Frames

All Classes

C F G I M O R S T V X

O

ObjImportOption - Enum in com.interactivemesh.jfx.importer.obj

Import options for the JavaFX OBJ model importer.

ObjModelImporter - Class in com.interactivemesh.jfx.importer.obj

A JavaFX importer for OBJ files.

ObjModelImporter() - Constructor for class com.interactivemesh.jfx.importer.obj.ObjModelImporter

Creates an OBJ model importer.

onFileImported() - Method in class com.interactivemesh.jfx.importer.col.ColModelImporter

Method is invoked upon completion of import.

onFileImported() - Method in class com.interactivemesh.jfx.importer.fxml.FxmlModelImporter

Method is invoked upon completion of import.

onFileImported() - Method in interface com.interactivemesh.jfx.importer.Importer

Method is invoked upon completion of import.

onFileImported() - Method in class com.interactivemesh.jfx.importer.obj.ObjModelImporter

Method is invoked upon completion of import.

onFileImported() - Method in class com.interactivemesh.jfx.importer.stl.StlMeshImporter

Method is invoked upon completion of import.

onFileImported() - Method in class com.interactivemesh.jfx.importer.tds.TdsModelImporter

Method is invoked upon completion of import.

onFileImported() - Method in class com.interactivemesh.jfx.importer.x3d.X3dModelImporter

Method is invoked upon completion of import.

C F G I M O R S T V X

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

JavaFX 3D Model Importers

Prev Letter

Next Letter

Frames

No Frames

All Classes

Copyright (C) 2013-2014 InteractiveMesh e.K.


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Library_IndexedSearch {

	public $searchBatchSize = PAGE_SEARCH_INDEX_BATCH_SIZE;
	public $searchReindexTimeout = PAGE_SEARCH_INDEX_LIFETIME;

	private $cPathSections = array();
	private $searchableAreaNamesManual = array();

	public function addSearchableArea($arr) {
		$this->searchableAreaNamesManual[] = $arr;
	}

	public function getSearchableAreaAction() {
		$action = Config::get('SEARCH_INDEX_AREA_METHOD');
		if (!strlen($action)) {
			$action = 'blacklist';
		}
		return $action;
	}

	public function getSavedSearchableAreas() {
		$areas = Config::get('SEARCH_INDEX_AREA_LIST');
		$areas = unserialize($areas);
		if (!is_array($areas)) {
			$areas = array();
		}
		return $areas;
	}

	public function clearSearchIndex() {
		$db = Loader::db();
		$db->Execute('truncate table PageSearchIndex');
	}

	public function reindexPage($page) {
		$db = Loader::db();
		if (is_object($page) && ($page instanceof Collection) && ($page->getAttribute('exclude_search_index') != 1)) {
			$datetime = Loader::helper('date')->getSystemDateTime();
			$db->Replace('PageSearchIndex', array(
				'cID' => $page->getCollectionID(),
				'cName' => $page->getCollectionName(),
				'cDescription' => $page->getCollectionDescription(),
				'cPath' => $page->getCollectionPath(),
				'cDatePublic' => $page->getCollectionDatePublic(),
				'content' => $this->getBodyContentFromPage($page),
				'cDateLastIndexed' => $datetime
			), array('cID'), true);
		} else {
			$db->Execute('delete from PageSearchIndex where cID = ?', array($page->getCollectionID()));
		}
	}

	public function getBodyContentFromPage($c) {
		$searchableAreaNamesInitial=$this->getSavedSearchableAreas();
		foreach($this->searchableAreaNamesManual as $sm) {
			$searchableAreaNamesInitial[] = $sm;
		}

		$searchableAreaNames = array();
		if ($this->getSearchableAreaAction() == 'blacklist') {
			$areas = Area::getHandleList();
			foreach($areas as $arHandle) {
				if (!in_array($arHandle, $searchableAreaNamesInitial)) {
					$searchableAreaNames[] = $arHandle;
				}
			}
		} else {
			$searchableAreaNames = $searchableAreaNamesInitial;
		}

		if (count($searchableAreaNames) == 0) {
			return false;
		}

		$text = '';

		$tagsToSpaces=array('
','
','
','
','
','
','
','
','
',' ');
		$blarray=array();
		$db = Loader::db();
		$r = $db->Execute('select bID, arHandle from CollectionVersionBlocks where cID = ? and cvID = ?', array($c->getCollectionID(), $c->getVersionID()));
		$th = Loader::helper('text');
		while ($row = $r->FetchRow()) {
			if (in_array($row['arHandle'], $searchableAreaNames)) {
				$b = Block::getByID($row['bID'], $c, $row['arHandle']);
				if (!is_object($b)) {
					continue;
				}
				$bi = $b->getInstance();
				$bi->bActionCID = $c->getCollectionID();
				if(method_exists($bi,'getSearchableContent')){
					$searchableContent = $bi->getSearchableContent();
					if(strlen(trim($searchableContent)))
						$text .= $th->decodeEntities(strip_tags(str_ireplace($tagsToSpaces,' ',$searchableContent)), ENT_QUOTES, APP_CHARSET).' ';
				}
				unset($b);
				unset($bi);
			}
		}

		$returned_text = Events::fire('on_page_body_index', $c, $text);

		if ( $returned_text !== null && $returned_text !== false){
			$text = $returned_text;
		}

		return $text;
	}

	/**
	 * Reindexes the search engine.
	 */
	public function reindexAll($fullReindex = false) {
		Cache::disableLocalCache();

		$db = Loader::db();
		Loader::model('collection_attributes');

		if ($fullReindex) {
			$db->Execute("truncate table PageSearchIndex");
		}

		$pl = new PageList();
		$pl->ignoreAliases();
		$pl->ignorePermissions();
		$pl->sortByCollectionIDAscending();
		$pl->filter(false, '(c.cDateModified > psi.cDateLastIndexed or UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(psi.cDateLastIndexed) > ' . $this->searchReindexTimeout . ' or psi.cID is null or psi.cDateLastIndexed is null)');
		$pl->filter(false, '(ak_exclude_search_index is null or ak_exclude_search_index = 0)');
		$pages = $pl->get($this->searchBatchSize);

		$num = 0;
		foreach($pages as $c) {

			// make sure something is approved
			$cv = $c->getVersionObject();
			if(!$cv->cvIsApproved) {
				continue;
			}

			$c->reindex($this, true);
			$num++;
			unset($c);
		}

		$pnum = Collection::reindexPendingPages();
		$num = $num + $pnum;

		Cache::enableLocalCache();
		$result = new stdClass;
		$result->count = $num;
		return $result;
	}

}


text:
package org.slc.sli.sandbox.idp.controller;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

/**
 * Injects instructions to not cache pages
 *
 * @author dkornishev
 *
 */
@Component
public class NoCacheHeadersInjector implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // nothing to do.
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // HTTP 1.1
        resp.setHeader("Pragma", "no-cache"); // HTTP 1.0
        resp.setDateHeader("Expires", -1); // prevents caching at the proxy server

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // nothing to do
    }
}