text:
package spire.math

import scala.annotation.tailrec
import scala.math.{ScalaNumber, ScalaNumericConversions}

import java.lang.Math

import spire.algebra.{Field, IsReal, NRoot, Sign}
import spire.algebra.Sign.{ Positive, Zero, Negative }

sealed abstract class Rational extends ScalaNumber with ScalaNumericConversions with Ordered[Rational] { lhs =>
  import LongRationals.LongRational
  import BigRationals.BigRational

  def numerator: BigInt
  def denominator: BigInt

  def numeratorAsLong: Long
  def denominatorAsLong: Long

  def isWhole: Boolean

  // ugh, ScalaNumber and ScalaNumericConversions in 2.10 require this hack
  override def underlying: Object = this

  def abs: Rational = if (this < Rational.zero) -this else this
  def inverse: Rational = Rational.one / this
  def reciprocal: Rational
  def signum: Int = numerator.signum

  def unary_-(): Rational = Rational.zero - this

  def +(rhs: Rational): Rational
  def -(rhs: Rational): Rational
  def *(rhs: Rational): Rational
  def /(rhs: Rational): Rational

  def /~(rhs: Rational): Rational = Rational(SafeLong((this / rhs).toBigInt), SafeLong.one)
  def %(rhs: Rational): Rational = this - (this /~ rhs) * rhs
  def /%(rhs: Rational): (Rational, Rational) = {
    val q = this /~ rhs
    (q, this - q * rhs)
  }

  def gcd(rhs: Rational): Rational

  def toBigInt: BigInt
  def toBigDecimal: BigDecimal
  override def shortValue = longValue.toShort
  override def byteValue = longValue.toByte

  def floor: Rational
  def ceil: Rational
  def round: Rational

  def roundTo(denom: SafeLong): Rational = (this * denom).round / denom

  def pow(exp: Int): Rational

  /**
   * Returns this `Rational` to the exponent `exp`. Both the numerator and
   * denominator of `exp` must be valid integers. Anything larger will cause
   * `pow` to throw an `ArithmeticException`.
   */
  def pow(exp: Rational)(implicit ctxt: ApproximationContext[Rational]): Rational = {
    if (exp < 0) {
      this.inverse.pow(-exp)(ctxt)
    } else if (!(exp.numerator.isValidInt) || !(exp.denominator.isValidInt)) {
      throw new ArithmeticException("Exponent is too large!")
    } else {

      // nroot must be done last so the context is still valid, otherwise, we'd
      // need to adjust the error, as the absolute error would increase,
      // relatively, by (1 + e)^exp.numerator if nroot was done before the pow.

      (this pow exp.numerator.toInt).nroot(exp.denominator.toInt)(ctxt)
    }
  }

  /**
   * Find the n-th root of this `Rational`. This requires an (implicit)
   * `ApproximationContext` to bound the allowable absolute error of the answer.
   */
  def nroot(k: Int)(implicit ctxt: ApproximationContext[Rational]): Rational = if (k == 0) {
    Rational.one
  } else if (k < 0) {
    this.inverse.nroot(-k)(ctxt)
  } else if (numerator == 0) {
    Rational.zero
  } else {

    // TODO: Is this necessary with the better init. approx in the else?

    val (low, high) = this match {
      case LongRational(n, d) => {
        val n_ = Rational.nroot(n, k)
        val d_ = Rational.nroot(d, k)
        (Rational(n_._1, d_._2), Rational(n_._2, d_._1))
      }
      case BigRational(n, d) => {
        val n_ = Rational.nroot(n, k)
        val d_ = Rational.nroot(d, k)
        (Rational(n_._1, d_._2), Rational(n_._2, d_._1))
      }
    }

    if (low == high) {
      low
    } else {

      import Rational.{ nroot => intNroot }

      // To ensure the initial approximation is within (relatively) 1/n of the
      // actual root, we need to ensure the num. and den. are both >= min.
      // Otherwise, we need to find a single multiplier for them that can
      // guarantee this. From there, we can simply use the integer version of
      // nroot to get a good approximation.

      val min = (BigInt(k) * 2 + 1) pow k
      val mul = min / (this.numerator min this.denominator) + 1
      val numIntRt = intNroot(numerator * mul, k)
      val denIntRt = intNroot(denominator * mul, k)
      val low = Rational(numIntRt._1, denIntRt._2)
      val high = Rational(numIntRt._2, denIntRt._1)

      // Reduction in absolute error from n-th root algorithm:
      // Let x(k) be the approximation at step k, x(oo) be the n-th root. Let
      // e(k) be the relative error at step k, thus x(k) = x(oo)(1 + e(k)). If
      // x(0) > x(oo), then x(k) > x(oo) (this can be seen during the
      // derivation).
      //
      // x(k+1) = 1/n [(n-1) * x(k) + x(oo)^n / x(k)^(n-1)]
      //          1/n [(n-1) * x(oo) * (1 + e(k)) + x(oo)^n / (x(oo) * (1 + e(k)))^(n-1)]
      //          x(oo)[(n-1)*(1+e(k)) / n + 1 / (n * (1 + e(k))^(n-1))]
      //          x(oo)[1 + e(k) + (1 + e(k))/n + 1 / (n * (1 + e(k))^(n-1))]
      //          x(oo)[1 + e(k) * (1 - ((1 + e(k))^n - 1) / (e(k) * n * (1 + e(k))^(n-1))]
      //          x(oo)[1 + e(k) * (1 - ((1 + n*e(k) + nC2*e(k)^2 + ... + e(k)^n) - 1) / (.. as above ..))]
      //          x(oo)[1 + e(k) * (1 - (1 + nC2*e^2/n + ... + e^(n-1)/n) / (1 + e(k))^(n-1))]
      //        < x(oo)[1 + e(k) * (1 - 1 / (1 + e(k))^(n-1))]
      //        < x(oo)[1 + e(k) * (1 - 1 / (1 + 1/n)^(n-1))]
      // Let e = (1 + 1/n)^(n-1).
      //        < x(oo)[1 + e(k) * (e - 1 / e)]
      //
      // So, we use a = (e - 1) / e as the relative error multiplier.

      val e = Rational(k + 1, k) pow (k - 1)
      val a = (e - 1) / e   // The relative error is multiplied by this each iter.
      val error = ctxt.error
      val absErr = high - low // I have no idea why I had this: high / k

      // absErr * a^k < error => a^k = error / absErr => k = log(error / absErr) / log(a)
      val maxiters = math.ceil(math.log((error / absErr).toDouble) / math.log(a.toDouble)).toInt

      // A single step of the nth-root algorithm.
      @inline def refine(x: Rational) = (x * (k - 1) + this / (x pow (k - 1))) / k

      def findNthRoot(prev: Rational, i: Int): Rational = if (i == maxiters) {
        prev
      } else {
        val next = refine(prev)

        // We know x(e0 - e1) > (1 - a)xe0, so xe0 < x(e0 - e1) / (1 - a).
        // Thus, if we have the difference, we can recalculate our guess of the
        // absolute error more "accurately" by dividing the difference of the
        // previous 2 guesses by (1 - a).
        //
        // This recalculation helps a lot. The numbers are a lot saner.

        // TODO: If we remove the iters constraint and just use this, will we
        //       ever perform worse than iters + 1 iterations? Need proof.

        if (prev == next || ((prev - next) / (Rational(1) - a)) < error) {
          prev
        } else {
          findNthRoot(next, i + 1)
        }
      }

      findNthRoot(high, 0)
    }
  }

  def sign: Sign = Sign(signum)

  def compareToOne: Int

  def min(rhs: Rational): Rational =
    if ((lhs compare rhs) < 0) lhs else rhs

  def max(rhs: Rational): Rational =
    if ((lhs compare rhs) > 0) lhs else rhs

  /**
   * Returns a `Rational` whose numerator and denominator both fit in an `Int`.
   */
  def limitToInt: Rational = limitTo(BigInt(Int.MaxValue))

  /**
   * Returns a `Rational` whose numerator and denominator both fit in a `Long`.
   */
  def limitToLong: Rational = limitTo(BigInt(Long.MaxValue))

  /**
   * Returns a `Rational` whose denominator and numerator are no larger than
   * `max` and whose value is close to the original. This applies, even if, for
   * example, this `Rational` is greater than `max`. In that case,
   * `Rational(max, 1)` is returned.
   *
   * @param max A positive integer.
   */
  def limitTo(max: BigInt): Rational = if (this.signum < 0) {
    -((-this).limitTo(max))
  } else {
    require(max > 0, "Limit must be a positive integer.")

    val half = max >> 1
    val floor = this.toBigInt
    if (floor >= max) {
      Rational(max)
    } else if (floor >= (max >> 1)) {
      Rational(floor.toLong)
    } else if (this < Rational(1)) {
      limitDenominatorTo(max)
    } else {
      limitDenominatorTo(max * denominator / numerator)
    }
  }

  /**
   * Finds the closest `Rational` to this `Rational` whose denominator is no
   * larger than `limit`.
   *
   * See [[http://en.wikipedia.org/wiki/Stern%E2%80%93Brocot_tree#Mediants_and_binary_search]]
   */
  def limitDenominatorTo(limit: BigInt): Rational = {
    require(limit > 0, "Cannot limit denominator to non-positive number.")

    // TODO: We should always perform a binary search from the left or right to
    //       speed up computation. For example, if in a search, we have a lower
    //       bound of 1/2 for many steps, then each step will only add 1/2 to
    //       the upper-bound, and so we'd converge on the number quite slowly.
    //       However, we can speed this up by tentatively checking if we could
    //       skip some intermediate values, by performing an adaptive search.
    //       We'd simply keep doubling the number of steps we're skipping until
    //       the upper-bound (eg) is now the lower bound, then go back to find
    //       the greatest lower bound in the steps we missed by binary search.
    //       Instead of adding 1/2 n times, we would try to add 1/2, 2/4, 4/8,
    //       8/16, etc., until the upper-bound swiches to a lower bound. Say
    //       this happens a (1/2)*2^k, then we simply perform a binary search in
    //       between (1/2)*2^(k-1) and (1/2)*2^k to find the new lower bound.
    //       This would reduce the number of steps to O(log n).

    @tailrec
    def closest(l: Rational, u: Rational): Rational = {
      val mediant = Rational(l.numerator + u.numerator, l.denominator + u.denominator)

      if (mediant.denominator > limit) {
        if ((this - l).abs > (u - this).abs) u else l
      } else if (mediant == this) {
        mediant
      } else if (mediant < this) {
        closest(mediant, u)
      } else {
        closest(l, mediant)
      }
    }

    this.sign match {
      case Zero => this
      case Positive => closest(Rational(this.toBigInt), LongRationals.LongRational(1, 0))
      case Negative => closest(LongRationals.LongRational(-1, 0), Rational(this.toBigInt))
    }
  }
}

object Rational extends RationalInstances {
  private val RationalString = """^(-?\d+)/(-?\d+)$""".r
  private val IntegerString = """^(-?\d+)$""".r

  import LongRationals.LongRational
  import BigRationals.BigRational

  val zero: Rational = LongRational(0L, 1L)
  val one: Rational = LongRational(1L, 1L)

  def apply(n: SafeLong, d: SafeLong): Rational = {
    if (d < 0) return apply(-n, -d)
    val g = n gcd d
    (n / g).foldWith[Rational,LongRational,BigRational](d / g)(LongRational(_, _), BigRational(_, _))
  }

  def apply(n: Long, d: Long): Rational = LongRationals.build(n, d)
  def apply(n: BigInt, d: BigInt): Rational = BigRationals.build(n, d)

  protected[math] def unsafeBuild(n: Long, d: Long) = LongRationals.unsafeBuild(n, d)
  protected[math] def unsafeBuild(n: BigInt, d: BigInt) = BigRationals.unsafeBuild(n, d)

  implicit def apply(x: Int): Rational = LongRationals.build(x, 1L)
  implicit def apply(x: Long): Rational = LongRationals.build(x, 1L)
  implicit def apply(x: BigInt): Rational = BigRationals.build(x, BigInt(1))

  implicit def apply(x: Float): Rational = apply(x.toDouble)

  implicit def apply(x: Double): Rational = {
    val bits = java.lang.Double.doubleToLongBits(x)
    val value = if ((bits >> 63) < 0) -(bits & 0x000FFFFFFFFFFFFFL | 0x0010000000000000L)
                else (bits & 0x000FFFFFFFFFFFFFL | 0x0010000000000000L)
    val exp = ((bits >> 52) & 0x7FF).toInt - 1075 // 1023 + 52
    if (exp > 10) {
        apply(BigInt(value) << exp, BigInt(1))
    } else if (exp >= 0) {
      apply(value << exp, 1L)
    } else if (exp >= -52 && (~((-1L) << (-exp)) & value) == 0L) {
      apply(value >> (-exp), 1L)
    } else {
      apply(BigInt(value), BigInt(1) << (-exp))
    }
  }

  implicit def apply(x:BigDecimal): Rational = {
    if (x.ulp >= 1) {
      BigRationals.build(x.toBigInt, 1)
    } else {
      val n = (x / x.ulp).toBigInt
      val d = (BigDecimal(1.0) / x.ulp).toBigInt
      BigRationals.build(n, d)
    }
  }

  def apply(r: String): Rational = r match {
    case RationalString(n, d) => Rational(BigInt(n), BigInt(d))
    case IntegerString(n) => Rational(BigInt(n))
    case s => try {
      Rational(BigDecimal(s))
    } catch {
      case nfe: NumberFormatException => throw new NumberFormatException("For input string: " + s)
    }
  }

  implicit def apply(x: SafeLong): Rational =
    x.fold(LongRationals.unsafeBuild(_, 1L), BigRationals.unsafeBuild(_, BigInt(1)))

  implicit def apply(x: Number): Rational = x match {
    case RationalNumber(n) => apply(n)
    case IntNumber(n) => apply(n)
    case FloatNumber(n) => apply(n)
    case DecimalNumber(n) => apply(n)
  }

  /**
   * Returns an interval that bounds the nth-root of the integer x.
   *
   * TODO: This is really out-of-place too.
   */
  def nroot(x: BigInt, n: Int): (BigInt, BigInt) = {
    def findnroot(prev: BigInt, add: Int): (BigInt, BigInt) = {
      val min = prev setBit add
      val max = min + 1

      val fl = min pow n
      val cl = max pow n

      if (fl > x) {
        findnroot(prev, add - 1)
      } else if (cl < x) {
        findnroot(min, add - 1)
      } else if (cl == x) {
        (max, max)
      } else if (fl == x) {
        (min, min)
      } else {
        (min, max)
      }
    }

    findnroot(BigInt(0), (x.bitLength + n - 1) / n) // ceil(x.bitLength / n)
  }

  /**
   * Returns an interval that bounds the nth-root of the integer x.
   */
  def nroot(x: Long, n: Int): (Long, Long) = {
    def findnroot(prev: Long, add: Long): (Long, Long) = {
      val min = prev | add
      val max = min + 1
      val fl = pow(min, n)
      val cl = pow(max, n)

      if (fl <= 0 || fl > x) {
        findnroot(prev, add >> 1)
      } else if (cl < x) {
        findnroot(min, add >> 1)
      } else if (cl == x) {
        (max, max)
      } else if (fl == x) {
        (min, min)
      } else {
        (min, max)
      }
    }

    // TODO: Could probably get a better initial add then this.
    findnroot(0, 1L << ((65 - n) / n))
  }
}

private[math] abstract class Rationals[@specialized(Long) A](implicit integral: Integral[A]) {
  import integral._

  def build(n: A, d: A): Rational

  //sealed trait RationalLike extends Rational with Fraction[A] {
  sealed trait RationalLike extends Rational {
    def num: A
    def den: A

    override def signum: Int = scala.math.signum(integral.compare(num, zero))

    def isWhole: Boolean = den == one

    def toBigInt: BigInt = (integral.toBigInt(num) / integral.toBigInt(den))
    def toBigDecimal: BigDecimal = integral.toBigDecimal(num) / integral.toBigDecimal(den)

    def longValue = toBigInt.longValue    // Override if possible.
    def intValue = longValue.intValue

    def floatValue = doubleValue.toFloat

    def doubleValue: Double = if (num == zero) {
      0.0
    } else if (integral.lt(num, zero)) {
      -((-this).toDouble)
    } else {

      // We basically just shift n so that integer division gives us 54 bits of
      // accuracy. We use the last bit for rounding, so end w/ 53 bits total.

      val n = integral.toBigInt(num)
      val d = integral.toBigInt(den)

      val sharedLength = Math.min(n.bitLength, d.bitLength)
      val dLowerLength = d.bitLength - sharedLength

      val nShared = n >> (n.bitLength - sharedLength)
      val dShared = d >> dLowerLength

      d.underlying.getLowestSetBit() < dLowerLength
      val addBit = if (nShared < dShared || (nShared == dShared && d.underlying.getLowestSetBit() < dLowerLength)) {
        1
      } else {
        0
      }

      val e = d.bitLength - n.bitLength + addBit
      val ln = n << (53 + e)    // We add 1 bit for rounding.
      val lm = (ln / d).toLong
      val m = ((lm >> 1) + (lm & 1)) & 0x000fffffffffffffL
      val bits = (m | ((1023L - e) << 52))
      java.lang.Double.longBitsToDouble(bits)
    }

    override def hashCode: Int =
      if (isWhole && toBigInt == toLong) unifiedPrimitiveHashcode
      else 29 * (37 * num.## + den.##)

    override def equals(that: Any): Boolean = that match {
      case that: Real => this == that.toRational
      case that: Algebraic => that == this
      case that: RationalLike => num == that.num && den == that.den
      case that: BigInt => isWhole && toBigInt == that
      case that: BigDecimal => try { toBigDecimal == that } catch { case ae: ArithmeticException => false }
      case that: SafeLong => SafeLong(toBigInt) == that
      case that: Number => Number(this) == that
      case that: Natural => isWhole && this == Rational(that.toBigInt)
      case that: Complex[_] => that == this
      case that: Quaternion[_] => that == this
      case that => unifiedPrimitiveEquals(that)
    }

    override def toString: String = if (den == 1L)
      num.toString
    else
      "%s/%s" format (num, den)
  }
}

private[math] object LongRationals extends Rationals[Long] {
  import BigRationals.BigRational

  def build(n: Long, d: Long): Rational = {
    if (d == 0) throw new IllegalArgumentException("0 denominator")
    else if (d > 0) unsafeBuild(n, d)
    else if (n == Long.MinValue || d == Long.MinValue) Rational(-BigInt(n), -BigInt(d))
    else unsafeBuild(-n, -d)
  }

  def unsafeBuild(n: Long, d: Long): Rational = {
    if (n == 0L) return Rational.zero

    val divisor = spire.math.gcd(n, d)
    if (divisor == 1L) {
      if (d < 0)
        Rational(SafeLong(-n), SafeLong(-d))
      else
        LongRational(n, d)
    } else {
      if (d < 0)
        LongRational(-n / divisor, -d / divisor)
      else
        LongRational(n / divisor, d / divisor)
    }
  }

  @SerialVersionUID(0L)
  case class LongRational private[math] (n: Long, d: Long) extends RationalLike with Serializable {
    def num: Long = n
    def den: Long = d

    def numerator = ConvertableFrom[Long].toBigInt(n)
    def denominator = ConvertableFrom[Long].toBigInt(d)

    def numeratorAsLong: Long = n
    def denominatorAsLong: Long = d

    def reciprocal =
      if (n == 0L) throw new ArithmeticException("reciprocal called on 0/1")
      else if (n > 0L) LongRational(d, n)
      else if (n == Long.MinValue || d == Long.MinValue) BigRational(-BigInt(d), -BigInt(n))
      else LongRational(-d, -n)

    override def signum: Int = java.lang.Long.signum(n)

    override def unary_-(): Rational =
      if (n == Long.MinValue) BigRational(-BigInt(Long.MinValue), BigInt(d))
      else LongRational(-n, d)

    def +(r: Rational): Rational = r match {
      case r: LongRationals.LongRational =>
        val dgcd: Long = spire.math.gcd(d, r.d)
        if (dgcd == 1L) {

          val num = SafeLong(n) * r.d + SafeLong(r.n) * d
          val den = SafeLong(d) * r.d
          Rational(num, den)

        } else {

          val lden: Long = d / dgcd
          val rden: Long = r.d / dgcd
          val num: SafeLong = SafeLong(n) * rden + SafeLong(r.n) * lden
          val ngcd: Long = num.fold(spire.math.gcd(_, dgcd), num => spire.math.gcd(dgcd, (num % dgcd).toLong))
          if (ngcd == 1L)
            Rational(num, SafeLong(lden) * r.d)
          else
            Rational(num / ngcd, SafeLong(lden) * (r.d / ngcd))
        }
      case r: BigRational =>
        val dgcd: Long = spire.math.gcd(d, (r.d % d).toLong)
        if (dgcd == 1L) {

          val num = SafeLong(r.d * n + r.n * d)
          val den = SafeLong(r.d * d)
          Rational(num, den)

        } else {

          val lden: Long = d / dgcd
          val rden: SafeLong = SafeLong(r.d) / dgcd
          val num: SafeLong = rden * n + SafeLong(r.n) * lden
          val ngcd: Long = num.fold(spire.math.gcd(_, dgcd), num => spire.math.gcd(dgcd, (num % dgcd).toLong))
          if (ngcd == 1L)
            Rational(num, SafeLong(lden) * r.d)
          else
            Rational(num / ngcd, SafeLong(r.d / ngcd) * lden)

        }
    }

    def -(r: Rational): Rational = r match {
      case r: LongRationals.LongRational =>
        val dgcd: Long = spire.math.gcd(d, r.d)
        if (dgcd == 1L) {

          val num = SafeLong(n) * r.d - SafeLong(r.n) * d
          val den = SafeLong(d) * r.d
          Rational(num, den)

        } else {

          val lden: Long = d / dgcd
          val rden: Long = r.d / dgcd
          val num: SafeLong = SafeLong(n) * rden - SafeLong(r.n) * lden
          val ngcd: Long = num.fold(spire.math.gcd(_, dgcd), num => spire.math.gcd(dgcd, (num % dgcd).toLong))
          if (ngcd == 1L)
            Rational(num, SafeLong(lden) * r.d)
          else
            Rational(num / ngcd, SafeLong(lden) * (r.d / ngcd))
        }
      case r: BigRational =>
        val dgcd: Long = spire.math.gcd(d, (r.d % d).toLong)
        if (dgcd == 1L) {

          val num = SafeLong(r.d * n - r.n * d)
          val den = SafeLong(r.d * d)
          Rational(num, den)

        } else {

          val lden: Long = d / dgcd
          val rden: SafeLong = SafeLong(r.d) / dgcd
          val num: SafeLong = rden * n - SafeLong(r.n) * lden
          val ngcd: Long = num.fold(spire.math.gcd(_, dgcd), num => spire.math.gcd(dgcd, (num % dgcd).toLong))
          if (ngcd == 1L)
            Rational(num, SafeLong(lden) * r.d)
          else
            Rational(num / ngcd, SafeLong(r.d / ngcd) * lden)

        }
    }

    def *(r: Rational): Rational = {
      if (n == 0L) Rational.zero else (r match {
        case r: LongRationals.LongRational =>
          val a = spire.math.gcd(n, r.d)
          val b = spire.math.gcd(d, r.n)
          Rational(SafeLong(n / a) * (r.n / b), SafeLong(d / b) * (r.d / a))
        case r: BigRational =>
          val a = spire.math.gcd(n, (r.d % n).toLong)
          val b = spire.math.gcd(d, (r.n % d).toLong)
          Rational(SafeLong(n / a) * (r.n / b), SafeLong(d / b) * (r.d / a))
      })
    }

    def /(r: Rational): Rational = {
      if (r == Rational.zero) throw new ArithmeticException("divide (/) by 0")
      if (this == Rational.zero) return this
      r match {
        case r: LongRationals.LongRational => {
          val a = spire.math.gcd(n, r.n)
          val b = spire.math.gcd(d, r.d)
          val num = SafeLong(n / a) * (r.d / b)
          val den = SafeLong(d / b) * (r.n / a)
          if (den < SafeLong.zero) Rational(-num, -den) else Rational(num, den)
        }
        case r: BigRational => {
          val a = spire.math.gcd(n, (r.n % n).toLong)
          val b = spire.math.gcd(d, (r.d % d).toLong)
          val num = SafeLong(n / a) * (r.d / b)
          val den = SafeLong(d / b) * (r.n / a)
          if (den < SafeLong.zero) Rational(-num, -den) else Rational(num, den)
        }
      }
    }

    def gcd(r: Rational): Rational = r match {
      case r: LongRationals.LongRational =>
        val dgcd: Long = spire.math.gcd(d, r.d)
        val n0 = spire.math.abs(n)
        val n1 = spire.math.abs(r.n)
        if (dgcd == 1L) {
          Rational(spire.math.gcd(n0, n1), SafeLong(d) * r.d)
        } else {
          val lm = d / dgcd
          val rm = r.d / dgcd
          Rational((SafeLong(n0) * rm) gcd (SafeLong(n1) * lm), SafeLong(dgcd) * lm * rm)
        }

      case r: BigRational =>
        val dgcd: Long = spire.math.gcd(d, (r.d % d).toLong)
        if (dgcd == 1L) {
          Rational(spire.math.gcd(spire.math.abs(n), spire.math.abs((r.n % n).toLong)),
            SafeLong(d) * r.d)
        } else {
          val lm = d / dgcd
          val rm = r.d / dgcd
          Rational((SafeLong(spire.math.abs(n)) * rm) gcd (SafeLong(r.n.abs) * lm),
            SafeLong(dgcd) * lm * rm)
        }
    }

    def floor: Rational =
      if (d == 1L) this
      else if (n >= 0) Rational(n / d, 1L)
      else Rational(n / d - 1L, 1L)

    def ceil: Rational =
      if (d == 1L) this
      else if (n >= 0) Rational(n / d + 1L, 1L)
      else Rational(n / d, 1L)

    def round: Rational =
      if (n >= 0) {
        val m = (n % d)
        if (m >= (d - m)) Rational(n / d + 1) else Rational(n / d)
      } else {
        val m = -(n % d)
        if (m >= (d - m)) Rational(n / d - 1) else Rational(n / d)
      }

    def pow(exp: Int): Rational = if (exp == 0)
      Rational.one
    else if (exp < 0)
      reciprocal.pow(-exp)
    else
      Rational(SafeLong(n).pow(exp), SafeLong(d).pow(exp))

    def compareToOne: Int = n compare d

    def compare(r: Rational): Int = r match {
      case r: LongRationals.LongRational =>
        val dgcd = spire.math.gcd(d, r.d)
        if (dgcd == 1L)
          (SafeLong(n) * r.d - SafeLong(r.n) * d).signum
        else
          (SafeLong(n) * (r.d / dgcd) - SafeLong(r.n) * (d / dgcd)).signum

      case r: BigRational =>
        val dgcd = spire.math.gcd(d, (r.d % d).toLong)
        if (dgcd == 1L)
          (SafeLong(n) * r.d - SafeLong(r.n) * d).signum
        else
          (SafeLong(n) * (r.d / dgcd) - SafeLong(r.n) * (d / dgcd)).signum
    }
  }
}

private[math] object BigRationals extends Rationals[BigInt] {
  import LongRationals.LongRational

  def build(n: BigInt, d: BigInt): Rational = {
    if (d == 0) throw new IllegalArgumentException("0 denominator")
    else if (d > 0) unsafeBuild(n, d)
    else unsafeBuild(-n, -d)
  }

  def unsafeBuild(n: BigInt, d:BigInt): Rational = {
    if (n == 0) return Rational.zero

    val gcd = n.gcd(d)
    if (gcd == 1) {
      if (d < 0)
        Rational(SafeLong(-n), SafeLong(-d))
      else
        Rational(SafeLong(n), SafeLong(d))
    } else {
      if (d < 0)
        Rational(-SafeLong(n / gcd), -SafeLong(d / gcd))
      else
        Rational(SafeLong(n / gcd), SafeLong(d / gcd))
    }
  }

  @SerialVersionUID(0L)
  case class BigRational private[math] (n: BigInt, d: BigInt) extends RationalLike with Serializable {
    def num: BigInt = n
    def den: BigInt = d

    def numerator = n
    def denominator = d

    def numeratorAsLong: Long = n.toLong
    def denominatorAsLong: Long = d.toLong

    def reciprocal = if (n == 0)
      throw new ArithmeticException("reciprocal called on 0/1")
    else if (n < 0)
      BigRational(-d, -n)
    else
      BigRational(d, n)

    override def signum: Int = n.signum

    override def unary_-(): Rational = Rational(-SafeLong(n), SafeLong(d))

    def +(r: Rational): Rational = r match {
      case r: LongRational => r + this
      case r: BigRationals.BigRational =>
        val dgcd: BigInt = d.gcd(r.d)
        if (dgcd == 1) {
          Rational(SafeLong(r.d * n + r.n * d), SafeLong(r.d * d))
        } else {
          val lden: BigInt = d / dgcd
          val rden: BigInt = r.d / dgcd
          val num: BigInt = rden * n + r.n * lden
          val ngcd: BigInt = num.gcd(dgcd)
          if (ngcd == 1)
            Rational(SafeLong(num), SafeLong(lden * r.d))
          else
            Rational(SafeLong(num / ngcd), SafeLong(r.d / ngcd) * lden)
        }
    }

    def -(r: Rational): Rational = r match {
      case r: LongRational => (-r) + this
      case r: BigRationals.BigRational =>
        val dgcd: BigInt = d.gcd(r.d)
        if (dgcd == 1) {
          Rational(SafeLong(r.d * n - r.n * d), SafeLong(r.d * d))
        } else {
          val lden: BigInt = d / dgcd
          val rden: BigInt = r.d / dgcd
          val num: BigInt = rden * n - r.n * lden
          val ngcd: BigInt = num.gcd(dgcd)
          if (ngcd == 1)
            Rational(SafeLong(num), SafeLong(lden * r.d))
          else
            Rational(SafeLong(num / ngcd), SafeLong(r.d / ngcd) * lden)
        }
    }

    def *(r: Rational): Rational = r match {
      case r: LongRational => r * this
      case r: BigRationals.BigRational =>
        val a = n.gcd(r.d)
        val b = d.gcd(r.n)
        Rational(SafeLong((n / a) * (r.n / b)), SafeLong((d / b) * (r.d / a)))
    }

    def /(r: Rational): Rational = r match {
      case r: LongRational => r.inverse * this
      case r: BigRationals.BigRational =>
        val a = n.gcd(r.n)
        val b = d.gcd(r.d)
        val num = SafeLong(n / a) * (r.d / b)
        val den = SafeLong(d / b) * (r.n / a)
        if (den < SafeLong.zero) Rational(-num, -den) else Rational(num, den)
    }

    def gcd(r: Rational): Rational = r match {
      case r: LongRational => r gcd this
      case r: BigRationals.BigRational =>
        val dgcd: BigInt = d.gcd(r.d)
        if (dgcd == 1) {
          Rational(n.abs gcd r.n.abs, d * r.d)
        } else {
          val lm = d / dgcd
          val rm = r.d / dgcd
          Rational((n * rm).abs gcd (r.n * lm).abs, dgcd * lm * rm)
        }
    }

    def floor: Rational =
      if (d == 1) this
      else if (n >= 0) Rational(n / d, BigInt(1))
      else Rational(n / d - 1, BigInt(1))

    def ceil: Rational =
      if (d == 1) this
      else if (n >= 0) Rational(n / d + 1, BigInt(1))
      else Rational(n / d, BigInt(1))

    def round: Rational =
      if (n >= 0) {
        val m = (n % d)
        if (m >= (d - m)) Rational(n / d + 1) else Rational(n / d)
      } else {
        val m = -(n % d)
        if (m >= (d - m)) Rational(n / d - 1) else Rational(n / d)
      }

    def pow(exp: Int): Rational = if (exp == 0)
      Rational.one
    else if (exp < 0)
      BigRationals.build(d pow -exp, n pow -exp)
    else
      BigRationals.build(n pow exp, d pow exp)

    def compareToOne: Int = n compare d

    def compare(r: Rational): Int = r match {
      case r: LongRational => {
        val dgcd = spire.math.gcd(r.d, (d % r.d).toLong)
        if (dgcd == 1L)
          (SafeLong(n) * r.d - SafeLong(r.n) * d).signum
        else
          (SafeLong(n) * (r.d / dgcd) - SafeLong(r.n) * (d / dgcd)).signum
      }
      case r: BigRationals.BigRational => {
        val dgcd = d.gcd(r.d)
        if (dgcd == 1)
          (SafeLong(n * r.d) - r.n * d).signum
        else
          (SafeLong(r.d / dgcd) * n - SafeLong(d / dgcd) * r.n).signum
      }
    }
  }
}

trait RationalInstances {
  implicit final val RationalAlgebra = new RationalAlgebra
  implicit def RationalIsNRoot(implicit c:ApproximationContext[Rational]) = new RationalIsNRoot0
}

private[math] trait RationalIsField extends Field[Rational] {
  override def minus(a:Rational, b:Rational): Rational = a - b
  def negate(a:Rational): Rational = -a
  def one: Rational = Rational.one
  def plus(a:Rational, b:Rational): Rational = a + b
  override def pow(a:Rational, b:Int): Rational = a.pow(b)
  override def times(a:Rational, b:Rational): Rational = a * b
  def zero: Rational = Rational.zero
  def quot(a:Rational, b:Rational) = a /~ b
  def mod(a:Rational, b:Rational) = a % b
  override def quotmod(a:Rational, b:Rational) = a /% b
  def gcd(a:Rational, b:Rational):Rational = a gcd b
  override def fromInt(n: Int): Rational = Rational(n)
  override def fromDouble(n: Double): Rational = Rational(n)
  def div(a:Rational, b:Rational) = a / b
}

private[math] trait RationalIsNRoot extends NRoot[Rational] with Serializable {
  implicit def context:ApproximationContext[Rational]
  def nroot(a: Rational, k: Int): Rational = a.nroot(k)
  def fpow(a: Rational, b: Rational): Rational = a.pow(b)
}

private[math] trait RationalIsReal extends IsReal[Rational] {
  override def eqv(x:Rational, y:Rational) = x == y
  override def neqv(x:Rational, y:Rational) = x != y
  override def gt(x: Rational, y: Rational) = x > y
  override def gteqv(x: Rational, y: Rational) = x >= y
  override def lt(x: Rational, y: Rational) = x < y
  override def lteqv(x: Rational, y: Rational) = x <= y
  def compare(x: Rational, y: Rational) = if (x < y) -1 else if (x > y) 1 else 0

  override def sign(a: Rational): Sign = a.sign
  def signum(a: Rational): Int = a.signum
  def abs(a: Rational): Rational = a.abs

  def toDouble(r: Rational): Double = r.toDouble
  def ceil(a:Rational): Rational = a.ceil
  def floor(a:Rational): Rational = a.floor
  def round(a:Rational): Rational = a.round
  def isWhole(a:Rational) = a.denominator == 1
}

@SerialVersionUID(0L)
class RationalAlgebra extends RationalIsField with RationalIsReal with Serializable

@SerialVersionUID(0L)
class RationalIsNRoot0(implicit val context: ApproximationContext[Rational])
extends RationalIsNRoot with Serializable


text:
package apolo.api.controller.advice;

import apolo.business.service.TenantService;
import apolo.business.service.UserService;
import apolo.common.config.model.ApplicationProperties;
import apolo.data.model.Tenant;
import apolo.data.model.User;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class GlobalControllerAdvice {

    @Inject
    private UserService userService;

    @Inject
    private TenantService tenantService;

    @Inject
    private ApplicationProperties applicationProperties;

    @ModelAttribute
    public void validateTenant(HttpServletRequest request, HttpServletResponse response) {
        String[] pathArray = request.getServletPath().split("/");

        if (pathArray != null
                && pathArray.length > 1
                && ("web".equals(pathArray[1]) || "api".equals(pathArray[1]))
                ) {
            User user = userService.getAuthenticatedUser();

            if (user != null) {
                request.getSession().setAttribute("tenant", user.getTenant());
            } else {
                String tenantUrl = null;

                if (pathArray.length >= 3
                        && ("web".equals(pathArray[1]) || "api".equals(pathArray[1]))
                        ) {
                    tenantUrl = pathArray[2];

                    if ("login".equals(tenantUrl)
                            || "error".equals(tenantUrl)) {
                        tenantUrl = null;
                    }
                }

                Tenant sessionTenant = (Tenant) request.getSession().getAttribute("tenant");

                if (sessionTenant == null || !sessionTenant.getUrl().equals(tenantUrl)) {
                    if (tenantUrl == null) {
                        tenantUrl = applicationProperties.getDefaultTenant();
                    }

                    sessionTenant = tenantService.getValidatedTenant(tenantUrl);

                    request.getSession().setAttribute("tenant", sessionTenant);
                }
            }
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.geode.redis.internal.executor;

import org.apache.geode.redis.internal.netty.Command;
import org.apache.geode.redis.internal.netty.ExecutionHandlerContext;

/**
 * Interface for executors of a {@link Command}.
 */
public interface Executor {

  /**
   * This method executes the command and sets the response. Any runtime errors from this execution
   * should be handled by caller to ensure the client gets a response
   *
   * @param command The command to be executed
   * @param context The execution context by which this command is to be executed
   */
  RedisResponse executeCommand(Command command, ExecutionHandlerContext context);
}


text:
require 'test_helper'

class Spud::Admin::PrintersControllerTest < ActionController::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
import { IEntity, IQEntity, QEntity, QDateField, QStringField } from 'querydsl-typescript';
export interface IDeltaRecord extends IEntity {
    id?: string;
    createDeviceId?: string;
    createDateTime?: Date;
    createUserId?: string;
}
export declare class QDeltaRecord<IQ extends IQEntity> extends QEntity<QDeltaRecord<IQ>> {
    id: QStringField<QDeltaRecord<IQ>>;
    createDeviceId: QStringField<QDeltaRecord<IQ>>;
    createDateTime: QDateField<QDeltaRecord<IQ>>;
    createUserId: QStringField<QDeltaRecord<IQ>>;
    constructor(entityConstructor: {
        new (): any;
    }, entityName: string, alias: string);
    toJSON(): any;
}


text:
/**
 * User: https://github.com/korve/
 * Date: 12.08.13
 * Time: 21:55
 */

var i18n = require('i18n'),
	util = require('../util.js');

module.exports = (function(){

	var defaults = {
		min: 0,
		max: undefined
	};

	/**
	 * Validates Numbers and checks if they are between a certain range
	 */
	return function(field, fieldName, value, options){

		if( ! options || typeof value === 'undefined' || value === '')
			return true;

		options = util.extend(options || {}, defaults);

		value = parseFloat(value);

		if(isNaN(value))
		{
			return i18n.__('between.isNotNumeric', fieldName);
		}

		if(value < options.min || (typeof options.max !== 'undefined' && value > options.max))
		{
			return i18n.__('between.notInRange', fieldName, options.min, options.max);
		}

		return true;
	}
})();


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.co.samholder.genetiq.selection;

import java.util.List;
import java.util.Random;
import uk.co.samholder.genetiq.population.IndividualFitness;

/**
 * An abstract base class for selectors to extend that require common selection
 * logic.
 *
 * @author sam
 */
public abstract class ScaledSelectorBase<I> {

    protected final Random random;

    public ScaledSelectorBase(Random random) {
        this.random = random;
    }

    /**
     * Selects a single individual from the population at a given position in
     * the cumulative fitness space.
     *
     * @param selectPosition the position to select for in cumulative fitness
     * space
     * @param individualFitnesses list of individual fitness values
     * @return selected individual
     */
    protected I selectOneAtPos(double selectPosition, List<IndividualFitness<I>> individualFitnesses) {
        // Select the individual when the cumulative fitness >= the random value.
        double count = 0;
        for (IndividualFitness<I> individualFitness : individualFitnesses) {
            count += individualFitness.getFitness();
            if (count >= selectPosition) {
                return individualFitness.getIndividual();
            }
        }
        // Should never get to here.
        throw new IllegalStateException("Error occured while performing fitness proportionate selection!");
    }

    /**
     * Selects a single individual from the population.
     *
     * @param total The fitness sum of the population.
     * @param individualFitnesses list of individual fitness values.
     * @return selected individual.
     */
    protected I selectOne(double total, List<IndividualFitness<I>> individualFitnesses) {
        // Get a random number within the total.
        double randomNum = random.nextDouble() * total;
        return selectOneAtPos(randomNum, individualFitnesses);
    }
}


text:
BEGIN;

-- Plan the tests
SELECT plan( 5 );

SELECT is(node::VARCHAR, 'job_test', 'Job result node is incorrect')
  FROM job_result where job_id = '1';

SELECT is(function::VARCHAR, 'java-weka-simplelr', 'Job result function is incorrect')
  FROM job_result where job_id = '1';

SELECT is(shape::VARCHAR, 'pfa_json', 'Job result shape is incorrect')
  FROM job_result where job_id = '1';

SELECT isnt(data::TEXT, NULL, 'Job result should contain data')
  FROM job_result where job_id = '1';

SELECT is(error::VARCHAR, NULL, 'Job result should not have error')
  FROM job_result where job_id = '1';

-- Clean up
SELECT * FROM finish();
ROLLBACK;


text:
package org.assertj.core.api;

import static org.assertj.core.test.ErrorMessages.descriptionIsNull;
import static org.assertj.core.test.ExpectedException.none;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

import org.assertj.core.description.Description;
import org.assertj.core.description.TextDescription;
import org.assertj.core.test.ExpectedException;
import org.junit.Rule;
import org.junit.Test;

/**
 * Tests for {@link DescriptionValidations#checkIsNotNull(org.assertj.core.description.Description)} and
 * {@link DescriptionValidations#checkIsNotNull(String)}.
 *
 * @author Yvonne Wang
 * @author Alex Ruiz
 */
public class DescriptionValidator_notNull_Test {

  @Rule
  public ExpectedException thrown = none();

  @Test
  public void should_throw_error_if_description_is_null() {
    thrown.expectNullPointerException(descriptionIsNull());
    Description d = null;
    DescriptionValidations.checkIsNotNull(d);
  }

  @Test
  public void should_throw_error_if_text_description_is_null() {
    thrown.expectNullPointerException(descriptionIsNull());
    String d = null;
    DescriptionValidations.checkIsNotNull(d);
  }

  @Test
  public void should_return_description_with_given_text() {
    Description d = DescriptionValidations.checkIsNotNull("Yoda");
    assertEquals("Yoda", d.value());
  }

  @Test
  public void should_return_same_description() {
    Description e = new TextDescription("Yoda");
    Description d = DescriptionValidations.checkIsNotNull(e);
    assertSame(e, d);
  }
}


text:
App.ResponsesRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('response');
  },
  renderTemplate: function() {
    this.render({
      outlet: 'responses'
    });
  }
})


text:
package org.apache.click.control;

import org.apache.click.util.HtmlStringBuffer;

/**
 * Provides a Label display control. The Label control performs no server side
 * processing, and is used primarily to add descriptive labels or horizontal
 * rules to auto rendered forms.
 *
 *
Label Example

 *
 * A Label example:
 *
 *

 * Form form = new Form("form");
 * ..
 *
 * form.add(new Label("hr", "<hr/>"));

 *
 * HTML output:
 *

 * <tr><td colspan='2' align='left'><hr/></td></tr>

 */
public class Label extends Field {

    private static final long serialVersionUID = 1L;

    // ----------------------------------------------------------- Constructors

    /**
     * Create a Label display control.
     *

     * Note the Label control will attempt to find a localized label message
     * in the parent messages, and if not found then in the field messages
     * using the key name of <tt>getName() + ".label"</tt>.
     *

     * If a value cannot be found in the parent or control messages then the
     * Field name will be converted into a label using the
     * {@link org.apache.click.util.ClickUtils#toLabel(String)} method.
     *
     * @param name the name of the Field
     */
    public Label(String name) {
        super(name);
    }

    /**
     * Create a Label display control with the given name and label.
     *
     * @param name the name of the Field
     * @param label the display label caption
     */
    public Label(String name, String label) {
        super(name, label);
    }

    /**
     * Create a Label with no label/name defined.
     *

     * Please note the control's name must be defined before it is valid.
     */
    public Label() {
        super();
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Returns true.
     *
     * @see Field#onProcess()
     *
     * @return true to continue Page event processing or false otherwise
     */
    @Override
    public boolean onProcess() {
        return true;
    }

    /**
     * Render a label.
     *
     * @see #toString()
     *
     * @param buffer the specified buffer to render the control's output to
     */
    @Override
    public void render(HtmlStringBuffer buffer) {
        buffer.append(getLabel());
    }

    /**
     * Returns the label.
     *
     * @see Object#toString()
     *
     * @return the label string value
     */
    @Override
    public String toString() {
        return getLabel();
    }
}


text:
export interface Balance {
  month_to_date_balance: string;
  account_balance: string;
  month_to_date_usage: string;
  generated_at: string;
}


text:
extern crate curl;
use std::sync::Arc;
use mio::*;
use mio::tcp::{TcpStream, TcpSocket};
use mio::buf::ByteBuf;
use std::net::SocketAddr;
use std::net::lookup_host;
use std::collections::VecMap;
use url::Url;
use curl::http;
use eventual;

#[derive(Debug, Clone)]
pub enum HttpAction {
    Get(Arc<Url>),
}

pub struct ClientInfo {
    tcp_stream: TcpStream,
    action: HttpAction,
    complete: eventual::Complete<Box<Vec<u8>>, &'static str>,
    mut_buf: Vec<u8>
}

impl ClientInfo {

    pub fn complete(self) {
        self.complete.complete(Box::new(self.mut_buf));
    }
}

pub struct Echo {
    client_info: VecMap<ClientInfo>,
}

impl Echo {
    pub fn new() -> Echo {
        Echo {
            client_info: VecMap::new(),
        }
    }
}

impl Handler for Echo {
    type Timeout = usize;
    type Message = (String, eventual::Complete<Box<Vec<u8>>, &'static str>);

    fn readable(&mut self, event_loop: &mut EventLoop<Echo>, token: Token, hint: ReadHint) {
        let mut closed = false;

        if !hint.is_hup() {
            let mut buf = ByteBuf::mut_with_capacity(4096 * 16);
            let mut client_info = self.client_info.get_mut(&token.as_usize()).unwrap();
            match client_info.tcp_stream.try_read_buf(&mut buf).unwrap() {
                Some(r) => {
                    if r > 0 {
                        client_info.mut_buf.push_all(buf.flip().bytes());

                        event_loop.reregister(&client_info.tcp_stream, token, Interest::readable(),
                                              PollOpt::edge() | PollOpt::oneshot()).unwrap();
                    } else {
                        event_loop.deregister(&client_info.tcp_stream).unwrap();
                        closed = true;
                    }
                }
                _ => {
                    panic!("err!");
                }
            }

        } else {
            let client_info = self.client_info.remove(&token.as_usize()).unwrap();

            event_loop.deregister(&client_info.tcp_stream).unwrap();
            closed = true;
        }
        if closed {
            self.client_info.remove(&token.as_usize()).unwrap().complete();
        }
    }

    fn writable(&mut self, event_loop: &mut EventLoop<Echo>, token: Token) {
        let client_info = self.client_info.get_mut(&token.as_usize()).unwrap();
        let get_command: String = body(client_info.action.clone());
        match client_info.action {
            HttpAction::Get(_) => {
                let mut buf = ByteBuf::from_slice(get_command.as_bytes());
                match client_info.tcp_stream.try_write_buf(&mut buf) {
                    Ok(None) => {
                        panic!("client flushing buf; WOULDBLOCK");
                        //   self.buf = Some(buf);
                    }
                    Ok(Some(_)) => {}
                    Err(e) => panic!("not implemented; client err={:?}", e),
                }

                event_loop.reregister(&client_info.tcp_stream, token, Interest::readable(),
                                      PollOpt::edge() | PollOpt::oneshot()).unwrap();
            }
        }
    }
    fn notify(&mut self,
              event_loop: &mut EventLoop<Echo>,
              tuple: (String, eventual::Complete<Box<Vec<u8>>, &'static str>)) {
        let token = Token(self.client_info.len() + 1);

        let action = get_action(tuple.0);
        match action.clone() {
            HttpAction::Get(url_p) => {
                let url: Url = (*url_p).clone();
                let ip = lookup_host(url.domain().unwrap()).unwrap().next().unwrap().unwrap();
                let port = url.port_or_default().unwrap();
                let address = SocketAddr::new(ip.ip(), port);
                let (sock, _) = TcpSocket::v4().unwrap().connect(&address).unwrap();
                let client_info = ClientInfo {
                    tcp_stream: sock,
                    action: action,
                    complete: tuple.1,
                    mut_buf: Vec::new()
                };

                event_loop.register_opt(&client_info.tcp_stream, token, Interest::writable(),
                                        PollOpt::edge() | PollOpt::oneshot()).unwrap();
                self.client_info.insert(token.as_usize(), client_info);
            }
        }
    }
}

fn body(action: HttpAction) -> String {
    match action {
        HttpAction::Get(ref resource) => {
            format!(
                "GET {}  HTTP/1.1\r\nHost: {}\r\nUser-Agent: curl/7.37.1\r\nAccept */*\r\nConnection: close \r\n\r\n",
                resource.serialize_path().unwrap(), resource.domain().unwrap())
        }
    }
}
fn get_action(url_s: String) -> HttpAction {
    let htt = http::multi_handle();

    let handle = http::handle();
    htt.add_connection(handle);
    let url = Url::parse(url_s.as_str()).unwrap();
    HttpAction::Get(Arc::new(url))
}


text:
#region license
// Sqloogle
// Copyright 2013-2017 Dale Newman
//
// 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.
#endregion
namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Options
{
    public class SqlOptionFilterItem
    {
        private Enums.ObjectType type;
        private string filter;

        public SqlOptionFilterItem(Enums.ObjectType type, string value)
        {
            this.filter = value;
            this.type = type;
        }

        public Enums.ObjectType Type
        {
            get { return type; }
            set { type = value; }
        }
        public string Filter
        {
            get { return filter; }
            set { this.filter = value; }
        }

    }
}


text:
$(document).ready( function() {

    //This code will run after your page loads
    console.log('hello Jan');
var gpio = require('rpi-gpio');
var async = require('async');

gpio.on('change', function(channel, value) {
    console.log('Channel ' + channel + ' value is now ' + value);
});

async.parallel([
    function(callback) {
        gpio.setup(7, gpio.DIR_OUT, callback)
    },
    function(callback) {
        gpio.setup(15, gpio.DIR_OUT, callback)
    },
    function(callback) {
        gpio.setup(16, gpio.DIR_OUT, callback)
    },
], function(err, results) {
    console.log('Pins set up');
    write();
});

function write() {
    async.series([
        function(callback) {
            delayedWrite(7, true, callback);
        },
        function(callback) {
            delayedWrite(15, true, callback);
        },
        function(callback) {
            delayedWrite(16, true, callback);
        },
        function(callback) {
            delayedWrite(7, false, callback);
        },
        function(callback) {
            delayedWrite(15, false, callback);
        },
        function(callback) {
            delayedWrite(16, false, callback);
        },
    ], function(err, results) {
        console.log('Writes complete, pause then unexport pins');
        setTimeout(function() {
            gpio.destroy(function() {
                console.log('Closed pins, now exit');
                return process.exit(0);
            });
        }, 500);
    });
};

function delayedWrite(pin, value, callback) {
    setTimeout(function() {
        gpio.write(pin, value, callback);
    }, 500);
}
//document.write(console.log);
});


text:
ZendService\ReCaptcha component

You can install using:

```
curl -s https://getcomposer.org/installer | php
php composer.phar install
```

At that point, follow the instructions in the documentation folder for actual
usage of the component. (Documentation is forthcoming.)


text:
var Aria = require("../../Aria");
var ariaUtilsIdManager = require("../../utils/IdMgr");
var ariaUtilsArray = require("../../utils/Array");
var ariaWidgetsFormRadioButtonStyle = require("./RadioButtonStyle.tpl.css");
var ariaWidgetsFormCheckBox = require("./CheckBox");

(function () {

    var idManager = null;

    /**
     * Radio Button widget
     * @class aria.widgets.form.RadioButton
     */
    module.exports = Aria.classDefinition({
        $classpath : 'aria.widgets.form.RadioButton',
        $extends : ariaWidgetsFormCheckBox,
        $css : [ariaWidgetsFormRadioButtonStyle],
        /**
         * RadioButton constructor
         * @param {aria.widgets.CfgBeans:RadioButtonCfg} cfg the widget configuration
         * @param {aria.templates.TemplateCtxt} ctxt template context
         * @param {Number} lineNumber Line number corresponding in the .tpl file where the widget is created
         */
        $constructor : function (cfg, ctxt) {
            this.$CheckBox.constructor.apply(this, arguments);
            if (this._skinObj.simpleHTML) {
                if (!idManager) {
                    idManager = new ariaUtilsIdManager("radio");
                }
                this._inputName = idManager.getId();
            }

            // use array and not store as index is important
            if (!this._cfg.disabled) {
                this._instances.push(this);
            }
        },

        $destructor : function () {
            ariaUtilsArray.remove(this._instances, this);

            if (this._inputName) {
                idManager.releaseId(this._inputName);
                this._inputName = null;
            }
            this.$CheckBox.$destructor.call(this);
        },

        $onunload : function () {
            if (idManager) {
                idManager.$dispose();
                idManager = null;
            }
            this._instances = null;
        },

        $prototype : {
            /**
             * Skinnable class to use for this widget.
             * @protected
             * @type String
             */
            _skinnableClass : "RadioButton",

            /**
             * List of radio button instances for keyboard nav
             * @protected
             * @type Array
             */
            _instances : [],

            /**
             * Internal method to set the _inputType property from the _cfg description
             */
            _setInputType : function () {
                this._cfg._inputType = "radio";
            },

            /**
             * Return whether the radio button is currently checked.
             * @return {Boolean}
             * @protected
             */
            _isChecked : function () {
                return (this.getProperty("value") === this._cfg.keyValue);
            },

            /**
             * Internal method called when one of the model property that the widget is bound to has changed Must be
             * overridden by sub-classes defining bindable properties
             * @param {String} propertyName the property name
             * @param {Object} newValue the new value
             * @param {Object} oldValue the old property value
             */
            _onBoundPropertyChange : function (propertyName, newValue, oldValue) {
                this.$CheckBox._onBoundPropertyChange.apply(this, arguments);
            },

            /**
             * Internal method to hande the mousedown event
             * @param {aria.DomEvent} event
             */
            _dom_onmousedown : function (event) {
                this._focus();
            },

            /**
             * Internal method to hande the mouseup event
             * @param {aria.DomEvent} event
             */
            _dom_onmouseup : function (event) {
                this._setRadioValue();
                this._focus();
            },

            /**
             * Toggle value on SPACE key down
             * @param {aria.DomEvent} event
             */
            _dom_onkeydown : function (event) {
                if (event.keyCode == aria.DomEvent.KC_SPACE) {
                    this._setRadioValue();
                    event.preventDefault(true);
                } else if (event.keyCode == aria.DomEvent.KC_LEFT) {
                    this._navigate(-1);
                    event.preventDefault(true);
                } else if (event.keyCode == aria.DomEvent.KC_RIGHT) {
                    this._navigate(+1);
                    event.preventDefault(true);
                } else if (event.keyCode == aria.DomEvent.KC_DOWN) {
                    this._navigate(+1);
                    event.preventDefault(true);
                } else if (event.keyCode == aria.DomEvent.KC_UP) {
                    this._navigate(-1);
                    event.preventDefault(true);
                }
            },

            /**
             * Find next valid radio button to activate
             * @protected
             * @param {Number} direction, 1 or -1
             */
            _navigate : function (direction) {
                if (!this._cfg || !this._cfg.bind || !this._cfg.bind.value) {
                    // no binding for the value : return
                    return;
                }
                var currentBinding = this._cfg.bind.value;
                var index = ariaUtilsArray.indexOf(this._instances, this), radioButtonNb = this._instances.length;
                var bindings, next, nextBinding;
                while (index > 0 || index < radioButtonNb) {
                    index = index + direction;
                    if (index < 0 || index >= radioButtonNb) {
                        break;
                    }
                    next = this._instances[index];
                    bindings = next._cfg.bind;
                    if (bindings) {
                        nextBinding = bindings.value;
                        if (nextBinding) {
                            // next radio button needs to be bound to the same data. Otherwise, continue.
                            if (currentBinding.inside === nextBinding.inside && currentBinding.to === nextBinding.to) {
                                next._setRadioValue();
                                next._focus();
                                break;
                            }
                        }
                    }
                }
            },

            /**
             * Sets the value property to the key value of this radio button and updates state, dom etc. Typically
             * called when user "selects" the radio button
             */
            _setRadioValue : function () {
                var newValue = this._cfg.keyValue;
                this._cfg.value = newValue;
                this.setProperty("value", newValue);
                this._setState();
                this._updateDomForState();
                if (this._cfg.onchange) {
                    this.evalCallback(this._cfg.onchange);
                }
            }
        }
    });
})();


text:
#include "am_driver_legacy/automower_legacy.h"
#include "am_driver_legacy/amproto_legacy.h"
#include <tf/transform_datatypes.h>

#include <math.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>

#define DEG2RAD(DEG) ((DEG) * ((M_PI) / (180.0)))

#define AUTMOWER_WHEEL_BASE_WIDTH (0.4645)

#define MODE_MANUAL (0x0000)
#define MODE_RANDOM (0x0001)

// OPERATIONAL MODES (i.e. published in SensorStatus)
#define AM_OP_MODE_OFFLINE (0x0000)
#define AM_OP_MODE_CONNECTED_MANUAL (0x0001)
#define AM_OP_MODE_CONNECTED_RANDOM (0x0002)

#define AM_CTRL_THRESHOLD (0.05)
#define AM_CTRL_INCREASE (1.00)
#define AM_CTRL_DECREASE (1.00)
#define AM_CTRL_MAX_SPEED (0.50)
#define AM_CTRL_MIN_SPEED (-0.50)

#define AM_SP_STATE_OFFLINE (0)
#define AM_SP_STATE_ONLINE (1)
#define AM_SP_STATE_CONNECTED (2)

#define AM_MAINBOARD_NEEDS_CONFIG (0)
#define AM_MAINBOARD_ROS_IN_CONTROL (1)
#define AM_MAINBOARD_HMB_IN_CONTROL (2)

namespace Husqvarna
{

AutomowerLegacy::AutomowerLegacy(const ros::NodeHandle& nodeh)
{
    // Init attributes
    nh = nodeh;
    lin_vel = 0.0;
    ang_vel = 0.0;

    wanted_lv = 0.0;
    wanted_rv = 0.0;

    current_lv = 0.0;
    current_rv = 0.0;

    // Parameters
    ros::NodeHandle n_private("~");
    std::string defPort = "/dev/ttyACM0";
    n_private.param("serialPort", pSerialPort, defPort);
    ROS_INFO("Param: serialPort: [%s]", pSerialPort.c_str());

    // Check if we shall publish the TF's?
    // It could be our "position" node that should do this...
    n_private.param("publishTf", publishTf, 1);
    ROS_INFO("Param: publishTf: [%d]", publishTf);

    n_private.param("velocityRegulator", velocityRegulator, 1);
    ROS_INFO("Param: velocityRegulator: [%d]", velocityRegulator);

    // Setup some ROS stuff
    cmd_sub = nh.subscribe("cmd_mode", 5, &AutomowerLegacy::modeCallback, this);

    odom_pub = nh.advertise<nav_msgs::Odometry>("odom", 1);
    pose_pub = nh.advertise<geometry_msgs::PoseStamped>("pose", 1);

    encoder_pub = nh.advertise<am_driver::WheelEncoder>("wheel_encoder", 1);
    current_pub = nh.advertise<am_driver::WheelCurrent>("wheel_current", 1);

    imuResetSub = nh.subscribe("imu_reset", 1, &AutomowerLegacy::imuResetCallback, this);

    velocity_sub = nh.subscribe("cmd_vel", 1, &AutomowerLegacy::velocityCallback, this);

    loop_pub = nh.advertise<am_driver::Loop>("loop", 1);
    sensorStatus_pub = nh.advertise<am_driver::SensorStatus>("sensor_status", 1);

    // Initialize the intial pose
    robot_pose.pose.position.x = 0.0;
    robot_pose.pose.position.y = 0.0;
    robot_pose.pose.position.z = 0.0;

    xpos = 0.0;
    ypos = 0.0;
    yaw = 0.0;
    lastLeftPulses = 0;
    lastRightPulses = 0;
    automowerInterfaceInited = false;
    mode = MODE_MANUAL;

    tf::Quaternion q = tf::createQuaternionFromYaw(yaw);
    robot_pose.pose.orientation.x = q.x();
    robot_pose.pose.orientation.y = q.y();
    robot_pose.pose.orientation.z = q.z();
    robot_pose.pose.orientation.w = q.w();

    robot_pose.header.frame_id = "base_link";
    robot_pose.header.stamp = ros::Time::now();

    imuOffset = 0.0;

    cuttingDiscOn = false;

    cuttingHeight = 20;
    lastCuttingHeight = 20;

    serialPortState = AM_SP_STATE_OFFLINE;

    reqFinished = false;

    actionResponse = 0;

    reqFrontOutside = false;
    reqRearOutside = false;

    invertedMotors = false;
}

AutomowerLegacy::~AutomowerLegacy()
{
    if (serialFd >= 0)
    {
        close(serialFd);
    }
}

bool AutomowerLegacy::setup()
{
    struct termios term;

    ROS_INFO("AutomowerLegacy::setup()");

    // Open serial port
    serialFd = open(pSerialPort.c_str(), O_RDWR /*| O_NONBLOCK */);
    if (serialFd < 0)
    {
        ROS_ERROR("AutomowerLegacy::Serial port open:");
        return false;
    }

    /*
            if (tcgetattr(serialFd, &term) < 0 )
            {
                    ROS_ERROR("AutomowerLegacy::setup():tcgetattr():");
                    close(serialFd);
                    serialFd = -1;
                    return false;
            }

            //cfmakeraw(&term);
            cfsetispeed(&term, B115200);
            cfsetospeed(&term, B115200);

            term.c_lflag &= ~ICANON;
            term.c_cc[VTIME] = 20;
            term.c_cc[VMIN] = 0;

            if (tcflush(serialFd, TCIOFLUSH ) < 0)
            {
                    ROS_ERROR("AutomowerLegacy::setup():tcflush():");
                    close(serialFd);
                    serialFd = -1;
                    return false;
            }

            if (tcsetattr(serialFd, TCSANOW, &term ) < 0)
            {
                    ROS_ERROR("AutomowerLegacy::setup():tcsetattr():");
                    close(serialFd);
                    serialFd = -1;
                    return false;
            }
    */

    memset(&term, 0, sizeof(term));

    /* man termios get more info on below settings */
    /* CS8 - character size mask
     * CLOCAL - ignore modem control lines
     * CREAD - enable receiver
     */
    term.c_cflag = B115200 | CS8 | CLOCAL | CREAD; /* control modes */
    term.c_iflag = 0;                              /* input mode */
    term.c_oflag = 0;                              /* output modes */
    term.c_lflag = 0;                              /* local modes */

    tcflush(serialFd, TCIFLUSH);

    /*
    VMIN specifies the minimum number of bytes to read before read() returns.
    VTIME is the time to wait (in tenths of a second) before returning from
    read (). VMIN and VTIME are used only when the ICANON flag is clear in
    the c_lflag parameter. In the previous example, you probably noticed
    that c_cc[VMIN] and c_cc[VTIME] were set to 1 to enable non-blocking
    reads. Many programmers are confused by VMIN and VTIME, but the rules are
    reasonably simple; four possible combinations of VMIN and VTIME are
    possible, as follows (from POSIX.1, 7.1.1.7):

    VMIN > 0 and VTIME > 0
            TIME is an interbyte timer that is activated after the first byte
            is received and is reset after each received byte. If the timer
            expires, at least one byte has been received because the timer
            is not activated until after a byte has been received.
    VMIN > 0 and VTIME = 0
            There is no timer, so read() returns when MIN bytes have been
            received or when a signal is received.
    VMIN = 0 and VTIME > 0
            Because MIN is 0, TIME is a read () operation timer that is
            activated as soon as read() is called. The read() operation
            returns as soon as a byte is received or when the timer expires.
    VMIN = 0 and VTIME = 0
            The read() operation returns immediately with the data that is
            in the input buffer. If the input buffer is empty, read()
            returns immediately with zero bytes of data.
    */
    term.c_cc[VMIN] = 0;
    term.c_cc[VTIME] = 20;
    tcsetattr(serialFd, TCSANOW, &term);

    return true;
}
void AutomowerLegacy::imuResetCallback(const geometry_msgs::Pose::ConstPtr& msg)
{

    ROS_INFO("AutomowerLegacy::imuResetCallback!");
    // Set heading from orientation
    tf::Quaternion q;
    double r, p, y;
    tf::quaternionMsgToTF(msg->orientation, q);
    tf::Matrix3x3(q).getRPY(r, p, y);
    yaw = y;

    // Set pose to the IMU Positions
    xpos = msg->position.x;
    ypos = msg->position.y;
    //~ zpos = msg->position.z;
}

void AutomowerLegacy::velocityCallback(const geometry_msgs::Twist::ConstPtr& vel)
{
    last_command_time = ros::WallTime::now();
    lin_vel = (double)vel->linear.x;
    ang_vel = (double)vel->angular.z;

    wanted_lv = lin_vel - ang_vel * AUTMOWER_WHEEL_BASE_WIDTH / 2;
    wanted_rv = lin_vel + ang_vel * AUTMOWER_WHEEL_BASE_WIDTH / 2;

    // ROS_INFO("AutomowerLegacy::cmd_vel: %f m/s  %f rad/s => wanted_lv=%f, wanted_rv=%f", (float)lin_vel, (float)ang_vel,
    // (float)wanted_lv, (float)wanted_rv);
}

void AutomowerLegacy::modeCallback(const std_msgs::UInt16::ConstPtr& msg)
{
    if (msg->data < 0x90)
    {
        // Not for us...
        return;
    }

    if (msg->data == 0x90)
    {
        mode = MODE_MANUAL;
    }
    else if (msg->data == 0x91)
    {
        mode = MODE_RANDOM;
    }
    else if (msg->data == 0x92)
    {
        cuttingDiscOn = false;
        ROS_INFO("Cutting Disc OFF");
    }
    else if (msg->data == 0x93)
    {
        cuttingDiscOn = true;
        ROS_INFO("Cutting Disc ON");
    }
    else if (msg->data == 0x94)
    {
        cuttingHeight = 60;
        ROS_INFO("Cutting Height = 60mm");
    }
    else if (msg->data == 0x95)
    {
        cuttingHeight = 40;
        ROS_INFO("Cutting Height = 40mm");
    }
    else if (msg->data == 0x100)
    {
        reqFinished = true;
        ROS_INFO("FINISHED requested");
    }
    else if (msg->data == 0x101)
    {
        reqFinished = false;
        ROS_INFO("FINISHED cleared");
    }
    else if (msg->data == 0x102)
    {
        reqFrontOutside = true;
        ROS_INFO("FRONT OUTSIDE geofence requested");
    }
    else if (msg->data == 0x103)
    {
        reqFrontOutside = false;
        ROS_INFO("FRONT OUTSIDE geofence cleared");
    }
    else if (msg->data == 0x104)
    {
        reqRearOutside = true;
        ROS_INFO("REAR OUTSIDE geofence requested");
    }
    else if (msg->data == 0x105)
    {
        reqRearOutside = false;
        ROS_INFO("REAR OUTSIDE geofence cleared");
    }
    else
    {
        // Do nothing...probably not for me...
        return;
    }

    // ROS_INFO("AutomowerLegacy::cmd_mode: %d", msg->data);
}

bool AutomowerLegacy::initAutomowerBoard()
{
    ROS_INFO("AutomowerLegacy::initAutomowerBoard");

    NavigationSetup navSetup;

    unsigned char msg[AM_PROTO_MAX_LENGTH];
    unsigned char resp[AM_PROTO_MAX_LENGTH];

    int messageLength = navSetup.getMessage((unsigned char*)&msg);

    int reclength = sendMessage(msg, messageLength, resp, AM_PROTO_MAX_LENGTH, true);

    if (reclength == 0)
    {
        ROS_ERROR("AutomowerLegacy::Failed to init mower!!!");
        return false;
    }

    // Get some stuff out from the mower...
    WHEEL_SPEED_TIMER_TICK = (resp[15] << 24) + (resp[14] << 16) + (resp[13] << 8) + (resp[12] << 0);
    int dia = (resp[7] << 8) + (resp[6] << 0);
    WHEEL_DIAMETER = (double)(dia) / 1000.0;

    WHEEL_PULSES_PER_TURN = (resp[5] << 8) + (resp[4] << 0);
    WHEEL_METER_PER_TICK = (2.0 * M_PI * WHEEL_DIAMETER / 2.0) / (double)WHEEL_PULSES_PER_TURN;

    ROS_INFO("AutomowerLegacy::WHEEL_SPEED_TIMER_TICK = %d", WHEEL_SPEED_TIMER_TICK);
    ROS_INFO("AutomowerLegacy::WHEEL_DIAMETER = %f", WHEEL_DIAMETER);
    ROS_INFO("AutomowerLegacy::WHEEL_PULSES_PER_TURN = %d", WHEEL_PULSES_PER_TURN);
    ROS_INFO("AutomowerLegacy::WHEEL_METER_PER_TICK = %f", WHEEL_METER_PER_TICK);

    // Motortypes:
    // - 1093 - A330 old motors
    // - 349  - A330/320 UltraSilent Motors
    // - 1192 - A320

    // UltraSilent motors are inverted...
    if ((WHEEL_PULSES_PER_TURN == 349) || (WHEEL_PULSES_PER_TURN == 1192))
    {
        invertedMotors = true;
    }

    return true;
}

int AutomowerLegacy::sendMessage(unsigned char* msg, int len, unsigned char* ansmsg, int maxAnsLength, bool retry)
{

    /*
            std::cout << "SEND: " << std::hex;
            for (int i=0; i<len; i++)
            {
                    std::cout << "0x" << (int)msg[i] << " ";
            }
            std::cout << std::dec << std::endl;
    */

    // Sending
    int cnt = 0;
    cnt = write(serialFd, msg, len);

    if (cnt != len)
    {
        ROS_ERROR("AutomowerLegacy::Could not send on serial port!");
        return -1;
    }

    cnt = 0;
    int res;
    int payloadLength = 0;

    // Clear answer buffer
    memset(ansmsg, 0, maxAnsLength);

    // Keep reading until we find an STX
    while (ansmsg[cnt] != 0x02)
    {
        res = read(serialFd, &ansmsg[cnt], 1);

        if (res <= 0)
        {
            // ROS_WARN("AutomowerLegacy::Failed to get STX...sleeping?");
            serialPortState = AM_SP_STATE_OFFLINE;
            return 0;
        }
    }

    cnt++;

    // Read MESSAGE TYPE
    res = read(serialFd, &ansmsg[cnt], 1);
    // std::cout << "MESSAGE TYPE: " << (int)ansmsg[cnt] << std::endl;
    cnt++;

    // Read LENGTH
    res = read(serialFd, &ansmsg[cnt], 1);
    payloadLength = ansmsg[cnt];
    // std::cout << "PAYLOAD LENGTH: " << (int)payloadLength << std::endl;
    cnt++;

    // Read PAYLOAD
    unsigned char readBytes = 0;
    unsigned max_retries = 100;
    while ((readBytes < payloadLength) && (max_retries > 0))
    {
        int bytes = read(serialFd, &ansmsg[cnt], payloadLength - readBytes);
        if (bytes > 0)
        {
            readBytes += bytes;
            cnt += bytes;
        }
        max_retries--;
    }

    // Read CRC
    // TODO: Use it!
    res = read(serialFd, &ansmsg[cnt], 1);
    cnt++;

    // Read ETX
    res = read(serialFd, &ansmsg[cnt], 1);
    cnt++;

    /*
            std::cout << "CNT: " << cnt << std::endl;
            std::cout << "RESPONSE: " << std::hex;
            for (int i=0; i<cnt; i++)
            {
                    std::cout << "0x" << (int)ansmsg[i] << " ";
            }
            std::cout << std::dec << std::endl;
    */

    // Check some stuff
    if (ansmsg[0] != 0x02)
    {
        // FAILED
        ROS_WARN("AutomowerLegacy::Failed STX");
        return 0;
    }
    if (ansmsg[cnt - 1] != 0x03)
    {
        // FAILED
        ROS_WARN("AutomowerLegacy::Failed ETX");
        return 0;
    }

    return cnt;
}

int AutomowerLegacy::twosComp(int val, int bits)
{
    // compute the 2's compliment of int value val
    if ((val & (1 << (bits - 1))) != 0)
    {
        val = val - (1 << bits);
    }
    return val;
}

double AutomowerLegacy::regulateVelocity(ros::Duration dt, double wanted_vel, double actual_vel)
{
    double res = actual_vel;

    if (fabs(wanted_vel - actual_vel) < AM_CTRL_THRESHOLD)
    {
        // We are ok...
        res = wanted_vel;
        // ROS_INFO("Within threshold...");
    }
    else if (wanted_vel > actual_vel)
    {
        // We are too slow...increase!
        res = actual_vel + AM_CTRL_INCREASE * dt.toSec();

        if (res > wanted_vel)
        {
            res = wanted_vel;
        }

        if (res > AM_CTRL_MAX_SPEED)
        {
            res = AM_CTRL_MAX_SPEED;
        }
        // ROS_INFO("Increase");
    }
    else
    {
        // We are too fast...decrease!
        res = actual_vel - AM_CTRL_DECREASE * dt.toSec();

        if (res < wanted_vel)
        {
            res = wanted_vel;
        }

        if (res < AM_CTRL_MIN_SPEED)
        {
            res = AM_CTRL_MIN_SPEED;
        }
        // ROS_INFO("Decrease");
    }

    return res;
}

void AutomowerLegacy::doAccelerationControl(ros::Duration dt)
{
    if (velocityRegulator == 1)
    {
        // Regulate the speed (left and right)
        current_lv = regulateVelocity(dt, wanted_lv, current_lv);
        current_rv = regulateVelocity(dt, wanted_rv, current_rv);
        // ROS_INFO("current_vel: %f, %f", current_lv, current_rv);

        // Make sure we send 0.0 m/s when close
        if (fabs(current_lv) < 0.01)
        {
            current_lv = 0.0;
        }
        if (fabs(current_rv) < 0.01)
        {
            current_rv = 0.0;
        }
    }
    else
    {
        // Just hit it...
        current_lv = wanted_lv;
        current_rv = wanted_rv;
    }
}

bool AutomowerLegacy::sendNavigation(signed short lv, signed short rv)
{
    // The same message for getting of odometry as setting new speed
    // hence the odo class here will have to also be responsible for
    // setting the speed (calculated by motor class).
    Navigation nav;

    if (mode == MODE_RANDOM)
    {
        nav.releaseControl();
    }
    else
    {
        nav.requestControl();
    }

    nav.setSpeed(lv, rv);

    unsigned short status = 0x00;

    if (cuttingDiscOn)
    {
        status |= 0x20;
    }

    if (reqFinished)
    {
        status |= 0x10;
    }

    if (reqFrontOutside)
    {
        status |= 1 << 14;
    }
    if (reqRearOutside)
    {
        status |= 1 << 13;
    }
    nav.setStatus(status);

    unsigned char msg[AM_PROTO_MAX_LENGTH];
    unsigned char resp[AM_PROTO_MAX_LENGTH];

    int messageLength = nav.getMessage((unsigned char*)&msg);
    int reclength = sendMessage(msg, messageLength, resp, AM_PROTO_MAX_LENGTH, true);
    if (reclength == 0)
    {
        return false;
    }

    // Get the status of the main board
    actionResponse = resp[4];

    // Pulses
    leftPulses = (resp[8] << 24) + (resp[7] << 16) + (resp[6] << 8) + (resp[5] << 0);
    rightPulses = (resp[12] << 24) + (resp[11] << 16) + (resp[10] << 8) + (resp[9] << 0);

    if (invertedMotors)
    {
        leftPulses = -leftPulses;
        rightPulses = -rightPulses;
    }

    // First time only...
    if (!automowerInterfaceInited)
    {
        automowerInterfaceInited = true;
        lastLeftPulses = leftPulses;
        lastRightPulses = rightPulses;
    }

    // Status for sensors, e.g. collision, lift, etc...
    sensorStatus.sensorStatus = (resp[14] << 8) + resp[13];

    // 15..16 (max wheel speed, suggested)
    int maxWheelSpeed = (resp[16] << 8) + resp[15];

    // 17..18 (error code) 0 = OK
    int errorCode = (resp[18] << 8) + resp[17];

    leftTicks = (resp[22] << 24) + (resp[21] << 16) + (resp[20] << 8) + (resp[19] << 0);
    rightTicks = (resp[26] << 24) + (resp[25] << 16) + (resp[24] << 8) + (resp[23] << 0);

    // Save the loop data for sending
    // loop.header.stamp = ros::Time::now();
    loop.header.frame_id = "loop_base";

    // 27..28 - Signed, A0 from FrontCenter
    loop.frontCenter = twosComp((resp[28] << 8) + resp[27], 16);
    // 29..30 - Signed, A0 from FrontRight
    loop.frontRight = twosComp((resp[30] << 8) + resp[29], 16);
    // 31..32 - Signed, A0 from RearLeft
    loop.rearLeft = twosComp((resp[32] << 8) + resp[31], 16);
    // 33..34 - Signed, A0 from RearRight
    loop.rearRight = twosComp((resp[34] << 8) + resp[33], 16);

    // Left/Right motor current
    // 35..36 Left
    wheelCurrent.left = twosComp((resp[36] << 8) + resp[35], 16);
    // 37..38 Right
    wheelCurrent.right = twosComp((resp[38] << 8) + resp[37], 16);

    // ROS_INFO("AutomowerLegacy::lv = %d, rv = %d", lv, rv);
    // ROS_INFO("AutomowerLegacy::leftPulses = %d, rightPulses = %d", leftPulses, rightPulses);

    return true;
}

bool AutomowerLegacy::update(ros::Duration dt)
{
    ros::Time current_time = ros::Time::now();

    if (serialPortState == AM_SP_STATE_OFFLINE)
    {
        if (initAutomowerBoard())
        {
            ROS_INFO("AutomowerLegacy::Serial port ONLINE!");
            serialPortState = AM_SP_STATE_ONLINE;
        }
        else
        {
            ROS_WARN("AutomowerLegacy::Failed to contact Mower board - SLEEPING?");
        }
    }

    if (serialPortState == AM_SP_STATE_ONLINE)
    {
        ROS_INFO("AutomowerLegacy::Serial port connected!");
        serialPortState = AM_SP_STATE_CONNECTED;
    }

    doAccelerationControl(dt);

    // Automower wants to have mm/s
    signed short lv_mm = current_lv * 1000;
    signed short rv_mm = current_rv * 1000;

    // Only send messages if we are connected...else we just publish data
    // but indicate in the sensorStatus that we are not online...
    if (serialPortState == AM_SP_STATE_CONNECTED)
    {
        bool res = sendNavigation((signed short)lv_mm, (signed short)rv_mm);
        if (!res)
        {
            ROS_ERROR("AutomowerLegacy::Failed Navigation message => OFFLINE!");
            serialPortState = AM_SP_STATE_OFFLINE;
            return false;
        }
    }

    // Get the odo data and convert to meters
    int deltaLeftPulses = leftPulses - lastLeftPulses;
    int deltaRightPulses = rightPulses - lastRightPulses;
    lastLeftPulses = leftPulses;
    lastRightPulses = rightPulses;

    double leftDist = -deltaLeftPulses * WHEEL_METER_PER_TICK;
    double rightDist = deltaRightPulses * WHEEL_METER_PER_TICK;

    // handle ZEROING of counters from mower?
    if ((fabs(leftDist) > 1.0) || (fabs(rightDist) > 1.0))
    {
        ROS_WARN("AutomowerLegacy::Strange distance? => ld = %f, rd = %f", leftDist, rightDist);
        leftDist = 0;
        rightDist = 0;
    }

    // ROS_INFO("AutomowerLegacy::ld = %f, rd = %f", leftDist, rightDist);

    double distance = (rightDist + leftDist) / 2.0;
    double delta_yaw = -(leftDist - rightDist) / AUTMOWER_WHEEL_BASE_WIDTH;

    yaw = yaw + delta_yaw;

    double vYaw = (yaw - last_yaw) / dt.toSec();
    last_yaw = yaw;

    double xdist = distance * cos(yaw);
    double ydist = distance * sin(yaw);

    double vx = distance / dt.toSec();
    double vy = 0.0;

    xpos = xpos + xdist;
    ypos = ypos + ydist;

    // ROS_INFO("AutomowerLegacy::pos: dt=%f xpos=%f, ypos=%f", (dt.toSec()), (float)xpos, (float)ypos);

    // Set this into the pose
    robot_pose.pose.position.x = xpos;
    robot_pose.pose.position.y = ypos;

    tf::Quaternion qyaw = tf::createQuaternionFromYaw(yaw);
    robot_pose.pose.orientation.x = qyaw.x();
    robot_pose.pose.orientation.y = qyaw.y();
    robot_pose.pose.orientation.z = qyaw.z();
    robot_pose.pose.orientation.w = qyaw.w();

    // Publish the pose
    pose_pub.publish(robot_pose);

    // Calculate the TF from the pose...
    tf::Transform transform;
    transform.setOrigin(
        tf::Vector3(robot_pose.pose.position.x, robot_pose.pose.position.y, robot_pose.pose.position.z));
    tf::Quaternion q;
    tf::quaternionMsgToTF(robot_pose.pose.orientation, q);
    transform.setRotation(q);

    // Send the TF
    if (publishTf)
    {
        br.sendTransform(tf::StampedTransform(transform, current_time, "odom", "base_link"));
    }

    // Odometry message over ROS
    nav_msgs::Odometry odom;
    odom.header.stamp = current_time;
    odom.header.frame_id = "odom";
    odom.child_frame_id = "base_link";

    // Set the position
    odom.pose.pose.position.x = robot_pose.pose.position.x;
    odom.pose.pose.position.y = robot_pose.pose.position.y;
    odom.pose.pose.position.z = robot_pose.pose.position.z;
    odom.pose.pose.orientation = robot_pose.pose.orientation;

    // Set the velocity
    odom.twist.twist.linear.x = vx;
    odom.twist.twist.linear.y = vy;
    odom.twist.twist.angular.z = vYaw;

    // Publish the message
    odom_pub.publish(odom);

    // Publish the loop
    loop.header.stamp = current_time;
    loop_pub.publish(loop);

    // Publish the sensorStatus
    sensorStatus.operationalMode = 0;
    if (serialPortState == AM_SP_STATE_CONNECTED)
    {
        // In which ONLINE mode?
        if (actionResponse == AM_MAINBOARD_ROS_IN_CONTROL)
        {
            sensorStatus.operationalMode = AM_OP_MODE_CONNECTED_MANUAL;
        }
        else
        {
            sensorStatus.operationalMode = AM_OP_MODE_CONNECTED_RANDOM;
        }
    }
    else
    {
        // We are offline (i.e. standby?)
        sensorStatus.operationalMode = AM_OP_MODE_OFFLINE;
    }

    sensorStatus.header.stamp = current_time;
    sensorStatus.header.frame_id = "odom";
    sensorStatus_pub.publish(sensorStatus);

    // Publish wheel encoders
    encoder.header.stamp = current_time;
    encoder.lwheel = leftDist;
    encoder.rwheel = rightDist;
    encoder.lwheelAccum = leftPulses;
    encoder.rwheelAccum = rightPulses;
    encoder.lticks = leftTicks;
    encoder.rticks = rightTicks;

    // std::cout << "LeftDist: " << leftDist << " RightDist: " << rightDist;
    // std::cout << " LeftAccum: " << (int)leftPulses << " RightAccum: " << (int)rightPulses << std::endl;

    encoder_pub.publish(encoder);

    // Publish wheel current (updated when read from mower)
    wheelCurrent.header.stamp = current_time;
    wheelCurrent.header.frame_id = "odom";
    current_pub.publish(wheelCurrent);

    // Cutting height
    if (cuttingHeight != lastCuttingHeight)
    {
        ROS_INFO("AutomowerLegacy::set new cutting height= %d mm", cuttingHeight);

        unsigned char msg[AM_PROTO_MAX_LENGTH];
        unsigned char resp[AM_PROTO_MAX_LENGTH];
        int messageLength;
        int reclength;

        CuttingHeight height;

        height.setCuttingHeight(cuttingHeight);
        messageLength = height.getMessage((unsigned char*)&msg);
        reclength = sendMessage(msg, messageLength, resp, AM_PROTO_MAX_LENGTH, true);
        if (reclength == 0)
        {
            ROS_ERROR("AutomowerLegacy::Failed setting cutting height.");
        }

        lastCuttingHeight = cuttingHeight;
    }

    return true;
}
}


text:
var assert = require('assert'),
    error = require('../../../lib/error/index'),
    math = require('../../../index'),
    approx = require('../../../tools/approx'),
    pi = math.pi,
    complex = math.complex,
    matrix = math.matrix,
    unit = math.unit,
    asin = math.asin,
    sin = math.sin;

describe('asin', function() {
  it('should return the arcsin of a boolean', function () {
    approx.equal(asin(true), 0.5 * pi);
    approx.equal(asin(false), 0);
  });

  it('should return the arcsin of null', function () {
    approx.equal(asin(null), 0);
  });

  it('should return the arcsin of a number', function() {
    approx.equal(asin(-1) / pi, -0.5);
    approx.equal(asin(-0.5) / pi, -1/6);
    approx.equal(asin(0) / pi, 0);
    approx.equal(asin(0.5) / pi, 1/6);
    approx.equal(asin(1) / pi, 0.5);
  });

  it('should return the arcsin of a bignumber (downgrades to number)', function() {
    approx.equal(asin(math.bignumber(-1)), -pi / 2);
  });

  it('should be the inverse function of sin', function() {
    approx.equal(asin(sin(-1)), -1);
    approx.equal(asin(sin(0)), 0);
    approx.equal(asin(sin(0.1)), 0.1);
    approx.equal(asin(sin(0.5)), 0.5);
    approx.equal(asin(sin(2)), 1.14159265358979);
  });

  it('should return the arcsin of a complex number', function() {
    var re = 0.570652784321099;
    var im = 1.983387029916536;
    approx.deepEqual(asin(complex('2+3i')), complex(re, im));
    approx.deepEqual(asin(complex('2-3i')), complex(re, -im));
    approx.deepEqual(asin(complex('-2+3i')), complex(-re, im));
    approx.deepEqual(asin(complex('-2-3i')), complex(-re, -im));
    approx.deepEqual(asin(complex('i')), complex(0, 0.881373587019543));
    approx.deepEqual(asin(complex('1')), complex(1.57079632679490, 0));
    approx.deepEqual(asin(complex('1+i')), complex(0.666239432492515, 1.061275061905036));
  });

  it('should throw an error if called with a unit', function() {
    assert.throws(function () {asin(unit('45deg'))});
    assert.throws(function () {asin(unit('5 celsius'))});
  });

  it('should throw an error if called with a string', function() {
    assert.throws(function () {asin('string')});
  });

  it('should calculate the arcsin element-wise for arrays and matrices', function() {
    // note: the results of asin(2) and asin(3) differs in octave
    // the next tests are verified with mathematica
    var asin123 = [
      1.57079632679490,
      complex(1.57079632679490, -1.31695789692482),
      complex(1.57079632679490, -1.76274717403909)];
    approx.deepEqual(asin([1,2,3]), asin123);
    approx.deepEqual(asin(matrix([1,2,3])), matrix(asin123));
  });

  it('should throw an error in case of invalid number of arguments', function() {
    assert.throws(function () {asin()}, error.ArgumentsError);
    assert.throws(function () {asin(1, 2)}, error.ArgumentsError);
  });

});


text:
[![npm version](https://badge.fury.io/js/timut.svg)](https://badge.fury.io/js/timut)

> Simple timing utils for the poor man's toolbox.

 ## Install

 ```bash
yarn add --dev timut@next # npm install --save-dev timut@next
```

 ## Example

 ```javascript
// in somefile.js
require('timut').push('just a message');

// in anotherfile.js
require('timut').push('another message');

// ...push as many messages as required

// wherever
require('timut').log();
```

`.log()` will output a table including time deltas to the console.

```
Time          |  Context     |  Message               |  Rel. Delta  |  Abs. Delta
----------------------------------------------------------------------------------
00:01:01:007  |  default...  |  just a message......  |         0ms  |         0ms
00:01:01:019  |  default...  |  another message.....  |       +12ms  |       +12ms
00:01:01:023  |  default...  |  yet another thing...  |        +4ms  |       +16ms
```

This is not fancy, but sometimes useful as a quicker and less complicated inspection tool than
full-blown profilers.

The `require('timut')` syntax is recommended, as it easily allows simple `sed` commands to remove
all occurrences in the complete codebase.

### Contexts

```javascript
// You can push messages to different contexts
require('timut').push('hello, message'); // pushes to context `default`
require('timut').push('another context', 'foo'); // pushes to context `foo`

// .log() takes an optional argument to log a context
require('timut').log('foo'); // logs all messages in context `foo`

// to remove all entries for a context
require('timut').resetContext('foo');

// or to reset all contexts
require('timut').reset();
```

## Library Targets

- browser (`dist/timut.min.js`)
- commonjs (`lib/index.js`)
- es2015 modules (`es/index.js`)

## API

See exports in [index.ts](https://github.com/sthzg/timut/blob/develop/src/index.ts).

## Use Case

The original use case behind the library was debugging asynchronous Karma tests running in
PhantomJS, transpiled by Babel and bundled by Webpack. The node debugger was not working reliably.
Inspecting by logging to console has been a pragmatic workaround.

To inspect the timing and application flow `timut` provides a 'trash-it-after-usage' approach and
simply a quick way to get an idea about where some code spends its time.


text:
QT_BEGIN_NAMESPACE
class QGraphicsPolygonItem;
class QGraphicsLineItem;
class QGraphicsScene;
class QRectF;
class QGraphicsSceneMouseEvent;
class QPainterPath;
QT_END_NAMESPACE

class LabelItem;

class EdgeItem : public QGraphicsLineItem {
  public:
    enum { Type = UserType + 4 };

    EdgeItem ( VertexItem* startItem, VertexItem* endItem,
               QGraphicsItem* parent = 0, QGraphicsScene* scene = 0 );

    int type() const {
      return Type;
    }
    QRectF boundingRect() const;
    QPainterPath shape() const;
    void setColor ( const QColor& color ) {
      myColor = color;
    }
    VertexItem* startItem() const {
      return myStartItem;
    }
    VertexItem* endItem() const {
      return myEndItem;
    }

    void updatePosition();

  protected:
    void paint ( QPainter* painter, const QStyleOptionGraphicsItem* option,
                 QWidget* widget = 0 );

  private:
    VertexItem* myStartItem;
    VertexItem* myEndItem;
    QColor myColor;
    QPolygonF arrowHead;
    LabelItem* label;
};

#endif


text:
package org.terasology.rendering.nui;

import org.terasology.math.Rect2i;

/**
 * @author Immortius
 */
public enum HorizontalAlign {
    /**
     * Starts on the left edge of the area
     */
    LEFT {
        @Override
        public int getOffset(int elementWidth, int availableWidth) {
            return 0;
        }
    },
    /**
     * Ends on the right edge of the area
     */
    RIGHT {
        @Override
        public int getOffset(int elementWidth, int availableWidth) {
            return availableWidth - elementWidth;
        }
    },
    /**
     * Centered in the middle of the area, with equal space on each side.
     */
    CENTER {
        @Override
        public int getOffset(int elementWidth, int availableWidth) {
            return (availableWidth - elementWidth) / 2;
        }
    };

    /**
     * Given the elementWidth and availableWidth, the offset of the element so that it will be correctly aligned
     *
     * @param elementWidth   The width of the element being drawn
     * @param availableWidth The width of the available space for the element
     * @return The horizontal offset that is needed to align the element
     */
    public abstract int getOffset(int elementWidth, int availableWidth);

    /**
     * Given a region, gets the start position for the alignment
     *
     * @param region
     * @return
     */
    public int getStart(Rect2i region) {
        return region.minX() + getOffset(0, region.width());
    }

}


text:
// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
//
// 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.

#ifndef _ESP_TRANSPORT_SSL_H_
#define _ESP_TRANSPORT_SSL_H_

#include "esp_transport.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief       Create new SSL transport, the transport handle must be release esp_transport_destroy callback
 *
 * @return      the allocated esp_transport_handle_t, or NULL if the handle can not be allocated
 */
esp_transport_handle_t esp_transport_ssl_init();

/**
 * @brief      Set SSL certificate data (as PEM format).
 *             Note that, this function stores the pointer to data, rather than making a copy.
 *             So this data must remain valid until after the connection is cleaned up
 *
 * @param      t     ssl transport
 * @param[in]  data  The pem data
 * @param[in]  len   The length
 */
void esp_transport_ssl_set_cert_data(esp_transport_handle_t t, const char *data, int len);

/**
 * @brief      Set SSL client certificate data for mutual authentication (as PEM format).
 *             Note that, this function stores the pointer to data, rather than making a copy.
 *             So this data must remain valid until after the connection is cleaned up
 *
 * @param      t     ssl transport
 * @param[in]  data  The pem data
 * @param[in]  len   The length
 */
void esp_transport_ssl_set_client_cert_data(esp_transport_handle_t t, const char *data, int len);

/**
 * @brief      Set SSL client key data for mutual authentication (as PEM format).
 *             Note that, this function stores the pointer to data, rather than making a copy.
 *             So this data must remain valid until after the connection is cleaned up
 *
 * @param      t     ssl transport
 * @param[in]  data  The pem data
 * @param[in]  len   The length
 */
void esp_transport_ssl_set_client_key_data(esp_transport_handle_t t, const char *data, int len);

#ifdef __cplusplus
}
#endif
#endif /* _ESP_TRANSPORT_SSL_H_ */


text:
package nl.hvanderheijden.prutscript.core.exceptions;

/**
 * When an instruction encountered something it doesn't know how to handle.
 * @author Heiko van der Heijden
 */
public class UndefinedBehaviourException extends PrutException{
    public UndefinedBehaviourException(final int lineNr, final String msg) {
        super(msg,lineNr);
    }
}


text:
/* Created by Casper S. Hornstrup <chorns@users.sourceforge.net> */
#ifndef __NTDDMOU_H
#define __NTDDMOU_H
#pragma GCC system_header
#include <_mingw.h>

/*
 * Mouse device IOCTL interface.
 */

#ifdef __cplusplus
extern "C" {
#endif

#include "ntddk.h"

#define DD_MOUSE_DEVICE_NAME              "\\Device\\PointerClass"
#define DD_MOUSE_DEVICE_NAME_U            L"\\Device\\PointerClass"

#define IOCTL_MOUSE_QUERY_ATTRIBUTES \
  CTL_CODE(FILE_DEVICE_MOUSE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS)

DEFINE_GUID(GUID_DEVINTERFACE_MOUSE, \
  0x378de44c, 0x56ef, 0x11d1, 0xbc, 0x8c, 0x00, 0xa0, 0xc9, 0x14, 0x05, 0xdd);

#define MOUSE_ERROR_VALUE_BASE            20000

/* MOUSE_INPUT_DATA.ButtonFlags constants */
#define MOUSE_LEFT_BUTTON_DOWN            0x0001
#define MOUSE_LEFT_BUTTON_UP              0x0002
#define MOUSE_RIGHT_BUTTON_DOWN           0x0004
#define MOUSE_RIGHT_BUTTON_UP             0x0008
#define MOUSE_MIDDLE_BUTTON_DOWN          0x0010
#define MOUSE_MIDDLE_BUTTON_UP            0x0020
#define MOUSE_BUTTON_4_DOWN               0x0040
#define MOUSE_BUTTON_4_UP                 0x0080
#define MOUSE_BUTTON_5_DOWN               0x0100
#define MOUSE_BUTTON_5_UP                 0x0200
#define MOUSE_WHEEL                       0x0400

#define MOUSE_BUTTON_1_DOWN               MOUSE_LEFT_BUTTON_DOWN
#define MOUSE_BUTTON_1_UP                 MOUSE_LEFT_BUTTON_UP
#define MOUSE_BUTTON_2_DOWN               MOUSE_RIGHT_BUTTON_DOWN
#define MOUSE_BUTTON_2_UP                 MOUSE_RIGHT_BUTTON_UP
#define MOUSE_BUTTON_3_DOWN               MOUSE_MIDDLE_BUTTON_DOWN
#define MOUSE_BUTTON_3_UP                 MOUSE_MIDDLE_BUTTON_UP

/* MOUSE_INPUT_DATA.Flags constants */
#define MOUSE_MOVE_RELATIVE               0
#define MOUSE_MOVE_ABSOLUTE               1
#define MOUSE_VIRTUAL_DESKTOP             0x02
#define MOUSE_ATTRIBUTES_CHANGED          0x04

typedef struct _MOUSE_INPUT_DATA {
	USHORT  UnitId;
	USHORT  Flags;
	_ANONYMOUS_UNION union {
		ULONG Buttons;
		_ANONYMOUS_STRUCT struct  {
			USHORT  ButtonFlags;
			USHORT  ButtonData;
		} DUMMYSTRUCTNAME;
	} DUMMYUNIONNAME;
	ULONG  RawButtons;
	LONG  LastX;
	LONG  LastY;
	ULONG  ExtraInformation;
} MOUSE_INPUT_DATA, *PMOUSE_INPUT_DATA;

typedef struct _MOUSE_UNIT_ID_PARAMETER {
  USHORT  UnitId;
} MOUSE_UNIT_ID_PARAMETER, *PMOUSE_UNIT_ID_PARAMETER;

/* MOUSE_ATTRIBUTES.MouseIdentifier constants */
#define MOUSE_INPORT_HARDWARE             0x0001
#define MOUSE_I8042_HARDWARE              0x0002
#define MOUSE_SERIAL_HARDWARE             0x0004
#define BALLPOINT_I8042_HARDWARE          0x0008
#define BALLPOINT_SERIAL_HARDWARE         0x0010
#define WHEELMOUSE_I8042_HARDWARE         0x0020
#define WHEELMOUSE_SERIAL_HARDWARE        0x0040
#define MOUSE_HID_HARDWARE                0x0080
#define WHEELMOUSE_HID_HARDWARE           0x0100

typedef struct _MOUSE_ATTRIBUTES {
  USHORT  MouseIdentifier;
  USHORT  NumberOfButtons;
  USHORT  SampleRate;
  ULONG  InputDataQueueLength;
} MOUSE_ATTRIBUTES, *PMOUSE_ATTRIBUTES;

#ifdef __cplusplus
}
#endif

#endif /* __NTDDMOU_H */


text:
package uk.gov.hmrc.ct.computations

import uk.gov.hmrc.ct.box._
import uk.gov.hmrc.ct.computations.retriever.ComputationsBoxRetriever

case class CP78(value: Option[Int]) extends CtBoxIdentifier(name = "Written down value brought forward") with CtOptionalInteger with Input with SelfValidatableBox[ComputationsBoxRetriever,  Option[Int]] {
  override def validate(boxRetriever: ComputationsBoxRetriever) = {
    collectErrors(
      validateZeroOrPositiveInteger()
    )
  }
}

object CP78 {

  def apply(value: Int): CP78 = CP78(Some(value))
}


text:
def extractSabishiidesuCom(item):
	'''
	Parser for 'sabishiidesu.com'
	'''

	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or "preview" in item['title'].lower():
		return None

	tagmap = [
		('Isekai Sagishi',                 'The Other World Con Artist's Management Techniques',                      'translated'),
		('Saikyou no Budouka',             'Saikyou no Budouka',                                                      'translated'),
		('Saikyou no Butouka',             'Saikyou no Budouka',                                                      'translated'),
		('maou-sama kansatsu nikki',       'maou-sama kansatsu nikki',                                                'translated'),
		('PRC',       'PRC',                      'translated'),
		('Loiterous', 'Loiterous',                'oel'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False