text:
package com.google.common.math;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNoOverflow;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.UnsignedLongs;

import java.math.BigInteger;
import java.math.RoundingMode;

/**
 * A class for arithmetic on values of type {@code long}. Where possible, methods are defined and
 * named analogously to their {@code BigInteger} counterparts.
 *
 *
The implementations of many methods in this class are based on material from Henry S. Warren,
 * Jr.'s Hacker's Delight, (Addison Wesley, 2002).
 *
 *
Similar functionality for {@code int} and for {@link BigInteger} can be found in
 * {@link IntMath} and {@link BigIntegerMath} respectively.  For other common operations on
 * {@code long} values, see {@link com.google.common.primitives.Longs}.
 *
 * @author Louis Wasserman
 * @since 11.0
 */
@GwtCompatible(emulated = true)
public final class LongMath {
  // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||

  /**
   * Returns {@code true} if {@code x} represents a power of two.
   *
   *
This differs from {@code Long.bitCount(x) == 1}, because
   * {@code Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two.
   */
  public static boolean isPowerOfTwo(long x) {
    return x > 0 & (x & (x - 1)) == 0;
  }

  /**
   * Returns 1 if {@code x < y} as unsigned longs, and 0 otherwise.  Assumes that x - y fits into a
   * signed long.  The implementation is branch-free, and benchmarks suggest it is measurably
   * faster than the straightforward ternary expression.
   */
  @VisibleForTesting
  static int lessThanBranchFree(long x, long y) {
    // Returns the sign bit of x - y.
    return (int) (~~(x - y) >>> (Long.SIZE - 1));
  }

  /**
   * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
   *
   * @throws IllegalArgumentException if {@code x <= 0}
   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
   *         is not a power of two
   */
  @SuppressWarnings("fallthrough")
  // TODO(kevinb): remove after this warning is disabled globally
  public static int log2(long x, RoundingMode mode) {
    checkPositive("x", x);
    switch (mode) {
      case UNNECESSARY:
        checkRoundingUnnecessary(isPowerOfTwo(x));
        // fall through
      case DOWN:
      case FLOOR:
        return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x);

      case UP:
      case CEILING:
        return Long.SIZE - Long.numberOfLeadingZeros(x - 1);

      case HALF_DOWN:
      case HALF_UP:
      case HALF_EVEN:
        // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
        int leadingZeros = Long.numberOfLeadingZeros(x);
        long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
        // floor(2^(logFloor + 0.5))
        int logFloor = (Long.SIZE - 1) - leadingZeros;
        return logFloor + lessThanBranchFree(cmp, x);

      default:
        throw new AssertionError("impossible");
    }
  }

  /** The biggest half power of two that fits into an unsigned long */
  @VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L;

  /**
   * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
   *
   * @throws IllegalArgumentException if {@code x <= 0}
   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
   *         is not a power of ten
   */
  @GwtIncompatible("TODO")
  @SuppressWarnings("fallthrough")
  // TODO(kevinb): remove after this warning is disabled globally
  public static int log10(long x, RoundingMode mode) {
    checkPositive("x", x);
    int logFloor = log10Floor(x);
    long floorPow = powersOf10[logFloor];
    switch (mode) {
      case UNNECESSARY:
        checkRoundingUnnecessary(x == floorPow);
        // fall through
      case FLOOR:
      case DOWN:
        return logFloor;
      case CEILING:
      case UP:
        return logFloor + lessThanBranchFree(floorPow, x);
      case HALF_DOWN:
      case HALF_UP:
      case HALF_EVEN:
        // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5
        return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x);
      default:
        throw new AssertionError();
    }
  }

  @GwtIncompatible("TODO")
  static int log10Floor(long x) {
    /*
     * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
     *
     * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
     * we can narrow the possible floor(log10(x)) values to two.  For example, if floor(log2(x))
     * is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
     */
    int y = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(x)];
    /*
     * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the
     * lower of the two possible values, or y - 1, otherwise, we want y.
     */
    return y - lessThanBranchFree(x, powersOf10[y]);
  }

  // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i)))
  @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = {
      19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12,
      12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4,
      3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 };

  @GwtIncompatible("TODO")
  @VisibleForTesting
  static final long[] powersOf10 = {
    1L,
    10L,
    100L,
    1000L,
    10000L,
    100000L,
    1000000L,
    10000000L,
    100000000L,
    1000000000L,
    10000000000L,
    100000000000L,
    1000000000000L,
    10000000000000L,
    100000000000000L,
    1000000000000000L,
    10000000000000000L,
    100000000000000000L,
    1000000000000000000L
  };

  // halfPowersOf10[i] = largest long less than 10^(i + 0.5)
  @GwtIncompatible("TODO")
  @VisibleForTesting
  static final long[] halfPowersOf10 = {
    3L,
    31L,
    316L,
    3162L,
    31622L,
    316227L,
    3162277L,
    31622776L,
    316227766L,
    3162277660L,
    31622776601L,
    316227766016L,
    3162277660168L,
    31622776601683L,
    316227766016837L,
    3162277660168379L,
    31622776601683793L,
    316227766016837933L,
    3162277660168379331L
  };

  /**
   * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
   * {@code BigInteger.valueOf(b).pow(k).longValue()}. This implementation runs in {@code O(log k)}
   * time.
   *
   * @throws IllegalArgumentException if {@code k < 0}
   */
  @GwtIncompatible("TODO")
  public static long pow(long b, int k) {
    checkNonNegative("exponent", k);
    if (-2 <= b && b <= 2) {
      switch ((int) b) {
        case 0:
          return (k == 0) ? 1 : 0;
        case 1:
          return 1;
        case (-1):
          return ((k & 1) == 0) ? 1 : -1;
        case 2:
          return (k < Long.SIZE) ? 1L << k : 0;
        case (-2):
          if (k < Long.SIZE) {
            return ((k & 1) == 0) ? 1L << k : -(1L << k);
          } else {
            return 0;
          }
        default:
          throw new AssertionError();
      }
    }
    for (long accum = 1;; k >>= 1) {
      switch (k) {
        case 0:
          return accum;
        case 1:
          return accum * b;
        default:
          accum *= ((k & 1) == 0) ? 1 : b;
          b *= b;
      }
    }
  }

  /**
   * Returns the square root of {@code x}, rounded with the specified rounding mode.
   *
   * @throws IllegalArgumentException if {@code x < 0}
   * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
   *         {@code sqrt(x)} is not an integer
   */
  @GwtIncompatible("TODO")
  @SuppressWarnings("fallthrough")
  public static long sqrt(long x, RoundingMode mode) {
    checkNonNegative("x", x);
    if (fitsInInt(x)) {
      return IntMath.sqrt((int) x, mode);
    }
    /*
     * Let k be the true value of floor(sqrt(x)), so that
     *
     *            k * k <= x          <  (k + 1) * (k + 1)
     * (double) (k * k) <= (double) x <= (double) ((k + 1) * (k + 1))
     *          since casting to double is nondecreasing.
     *          Note that the right-hand inequality is no longer strict.
     * Math.sqrt(k * k) <= Math.sqrt(x) <= Math.sqrt((k + 1) * (k + 1))
     *          since Math.sqrt is monotonic.
     * (long) Math.sqrt(k * k) <= (long) Math.sqrt(x) <= (long) Math.sqrt((k + 1) * (k + 1))
     *          since casting to long is monotonic
     * k <= (long) Math.sqrt(x) <= k + 1
     *          since (long) Math.sqrt(k * k) == k, as checked exhaustively in
     *          {@link LongMathTest#testSqrtOfPerfectSquareAsDoubleIsPerfect}
     */
    long guess = (long) Math.sqrt(x);
    // Note: guess is always <= FLOOR_SQRT_MAX_LONG.
    long guessSquared = guess * guess;
    // Note (2013-2-26): benchmarks indicate that, inscrutably enough, using if statements is
    // faster here than using lessThanBranchFree.
    switch (mode) {
      case UNNECESSARY:
        checkRoundingUnnecessary(guessSquared == x);
        return guess;
      case FLOOR:
      case DOWN:
        if (x < guessSquared) {
          return guess - 1;
        }
        return guess;
      case CEILING:
      case UP:
        if (x > guessSquared) {
          return guess + 1;
        }
        return guess;
      case HALF_DOWN:
      case HALF_UP:
      case HALF_EVEN:
        long sqrtFloor = guess - ((x < guessSquared) ? 1 : 0);
        long halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
        /*
         * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both
         * x and halfSquare are integers, this is equivalent to testing whether or not x <=
         * halfSquare. (We have to deal with overflow, though.)
         *
         * If we treat halfSquare as an unsigned long, we know that
         *            sqrtFloor^2 <= x < (sqrtFloor + 1)^2
         * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1
         * so |x - halfSquare| <= sqrtFloor.  Therefore, it's safe to treat x - halfSquare as a
         * signed long, so lessThanBranchFree is safe for use.
         */
        return sqrtFloor + lessThanBranchFree(halfSquare, x);
      default:
        throw new AssertionError();
    }
  }

  /**
   * Returns the result of dividing {@code p} by {@code q}, rounding using the specified
   * {@code RoundingMode}.
   *
   * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
   *         is not an integer multiple of {@code b}
   */
  @GwtIncompatible("TODO")
  @SuppressWarnings("fallthrough")
  public static long divide(long p, long q, RoundingMode mode) {
    checkNotNull(mode);
    long div = p / q; // throws if q == 0
    long rem = p - q * div; // equals p % q

    if (rem == 0) {
      return div;
    }

    /*
     * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
     * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
     * p / q.
     *
     * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
     */
    int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1));
    boolean increment;
    switch (mode) {
      case UNNECESSARY:
        checkRoundingUnnecessary(rem == 0);
        // fall through
      case DOWN:
        increment = false;
        break;
      case UP:
        increment = true;
        break;
      case CEILING:
        increment = signum > 0;
        break;
      case FLOOR:
        increment = signum < 0;
        break;
      case HALF_EVEN:
      case HALF_DOWN:
      case HALF_UP:
        long absRem = abs(rem);
        long cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
        // subtracting two nonnegative longs can't overflow
        // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
        if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
          increment = (mode == HALF_UP | (mode == HALF_EVEN & (div & 1) != 0));
        } else {
          increment = cmpRemToHalfDivisor > 0; // closer to the UP value
        }
        break;
      default:
        throw new AssertionError();
    }
    return increment ? div + signum : div;
  }

  /**
   * Returns {@code x mod m}, a non-negative value less than {@code m}.
   * This differs from {@code x % m}, which might be negative.
   *
   *
For example:
   *
   *
 {@code
   *
   * mod(7, 4) == 3
   * mod(-7, 4) == 1
   * mod(-1, 4) == 3
   * mod(-8, 4) == 0
   * mod(8, 4) == 0}

   *
   * @throws ArithmeticException if {@code m <= 0}
   * @see
   *      Remainder Operator
   */
  @GwtIncompatible("TODO")
  public static int mod(long x, int m) {
    // Cast is safe because the result is guaranteed in the range [0, m)
    return (int) mod(x, (long) m);
  }

  /**
   * Returns {@code x mod m}, a non-negative value less than {@code m}.
   * This differs from {@code x % m}, which might be negative.
   *
   *
For example:
   *
   *
 {@code
   *
   * mod(7, 4) == 3
   * mod(-7, 4) == 1
   * mod(-1, 4) == 3
   * mod(-8, 4) == 0
   * mod(8, 4) == 0}

   *
   * @throws ArithmeticException if {@code m <= 0}
   * @see
   *      Remainder Operator
   */
  @GwtIncompatible("TODO")
  public static long mod(long x, long m) {
    if (m <= 0) {
      throw new ArithmeticException("Modulus must be positive");
    }
    long result = x % m;
    return (result >= 0) ? result : result + m;
  }

  /**
   * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
   * {@code a == 0 && b == 0}.
   *
   * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
   */
  public static long gcd(long a, long b) {
    /*
     * The reason we require both arguments to be >= 0 is because otherwise, what do you return on
     * gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't
     * an int.
     */
    checkNonNegative("a", a);
    checkNonNegative("b", b);
    if (a == 0) {
      // 0 % b == 0, so b divides a, but the converse doesn't hold.
      // BigInteger.gcd is consistent with this decision.
      return b;
    } else if (b == 0) {
      return a; // similar logic
    }
    /*
     * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
     * This is >60% faster than the Euclidean algorithm in benchmarks.
     */
    int aTwos = Long.numberOfTrailingZeros(a);
    a >>= aTwos; // divide out all 2s
    int bTwos = Long.numberOfTrailingZeros(b);
    b >>= bTwos; // divide out all 2s
    while (a != b) { // both a, b are odd
      // The key to the binary GCD algorithm is as follows:
      // Both a and b are odd.  Assume a > b; then gcd(a - b, b) = gcd(a, b).
      // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.

      // We bend over backwards to avoid branching, adapting a technique from
      // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax

      long delta = a - b; // can't overflow, since a and b are nonnegative

      long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1));
      // equivalent to Math.min(delta, 0)

      a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
      // a is now nonnegative and even

      b += minDeltaOrZero; // sets b to min(old a, b)
      a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
    }
    return a << min(aTwos, bTwos);
  }

  /**
   * Returns the sum of {@code a} and {@code b}, provided it does not overflow.
   *
   * @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic
   */
  @GwtIncompatible("TODO")
  public static long checkedAdd(long a, long b) {
    long result = a + b;
    checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0);
    return result;
  }

  /**
   * Returns the difference of {@code a} and {@code b}, provided it does not overflow.
   *
   * @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic
   */
  @GwtIncompatible("TODO")
  public static long checkedSubtract(long a, long b) {
    long result = a - b;
    checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0);
    return result;
  }

  /**
   * Returns the product of {@code a} and {@code b}, provided it does not overflow.
   *
   * @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic
   */
  @GwtIncompatible("TODO")
  public static long checkedMultiply(long a, long b) {
    // Hacker's Delight, Section 2-12
    int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a)
        + Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b);
    /*
     * If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE it's definitely
     * bad. We do the leadingZeros check to avoid the division below if at all possible.
     *
     * Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 and 1. We take
     * care of all a < 0 with their own check, because in particular, the case a == -1 will
     * incorrectly pass the division check below.
     *
     * In all other cases, we check that either a is 0 or the result is consistent with division.
     */
    if (leadingZeros > Long.SIZE + 1) {
      return a * b;
    }
    checkNoOverflow(leadingZeros >= Long.SIZE);
    checkNoOverflow(a >= 0 | b != Long.MIN_VALUE);
    long result = a * b;
    checkNoOverflow(a == 0 || result / a == b);
    return result;
  }

  /**
   * Returns the {@code b} to the {@code k}th power, provided it does not overflow.
   *
   * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
   *         {@code long} arithmetic
   */
  @GwtIncompatible("TODO")
  public static long checkedPow(long b, int k) {
    checkNonNegative("exponent", k);
    if (b >= -2 & b <= 2) {
      switch ((int) b) {
        case 0:
          return (k == 0) ? 1 : 0;
        case 1:
          return 1;
        case (-1):
          return ((k & 1) == 0) ? 1 : -1;
        case 2:
          checkNoOverflow(k < Long.SIZE - 1);
          return 1L << k;
        case (-2):
          checkNoOverflow(k < Long.SIZE);
          return ((k & 1) == 0) ? (1L << k) : (-1L << k);
        default:
          throw new AssertionError();
      }
    }
    long accum = 1;
    while (true) {
      switch (k) {
        case 0:
          return accum;
        case 1:
          return checkedMultiply(accum, b);
        default:
          if ((k & 1) != 0) {
            accum = checkedMultiply(accum, b);
          }
          k >>= 1;
          if (k > 0) {
            checkNoOverflow(b <= FLOOR_SQRT_MAX_LONG);
            b *= b;
          }
      }
    }
  }

  @VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L;

  /**
   * Returns {@code n!}, that is, the product of the first {@code n} positive
   * integers, {@code 1} if {@code n == 0}, or {@link Long#MAX_VALUE} if the
   * result does not fit in a {@code long}.
   *
   * @throws IllegalArgumentException if {@code n < 0}
   */
  @GwtIncompatible("TODO")
  public static long factorial(int n) {
    checkNonNegative("n", n);
    return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE;
  }

  static final long[] factorials = {
      1L,
      1L,
      1L * 2,
      1L * 2 * 3,
      1L * 2 * 3 * 4,
      1L * 2 * 3 * 4 * 5,
      1L * 2 * 3 * 4 * 5 * 6,
      1L * 2 * 3 * 4 * 5 * 6 * 7,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19,
      1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20
  };

  /**
   * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
   * {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}.
   *
   * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
   */
  public static long binomial(int n, int k) {
    checkNonNegative("n", n);
    checkNonNegative("k", k);
    checkArgument(k <= n, "k (%s) > n (%s)", k, n);
    if (k > (n >> 1)) {
      k = n - k;
    }
    switch (k) {
      case 0:
        return 1;
      case 1:
        return n;
      default:
        if (n < factorials.length) {
          return factorials[n] / (factorials[k] * factorials[n - k]);
        } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) {
          return Long.MAX_VALUE;
        } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) {
          // guaranteed not to overflow
          long result = n--;
          for (int i = 2; i <= k; n--, i++) {
            result *= n;
            result /= i;
          }
          return result;
        } else {
          int nBits = LongMath.log2(n, RoundingMode.CEILING);

          long result = 1;
          long numerator = n--;
          long denominator = 1;

          int numeratorBits = nBits;
          // This is an upper bound on log2(numerator, ceiling).

          /*
           * We want to do this in long math for speed, but want to avoid overflow. We adapt the
           * technique previously used by BigIntegerMath: maintain separate numerator and
           * denominator accumulators, multiplying the fraction into result when near overflow.
           */
          for (int i = 2; i <= k; i++, n--) {
            if (numeratorBits + nBits < Long.SIZE - 1) {
              // It's definitely safe to multiply into numerator and denominator.
              numerator *= n;
              denominator *= i;
              numeratorBits += nBits;
            } else {
              // It might not be safe to multiply into numerator and denominator,
              // so multiply (numerator / denominator) into result.
              result = multiplyFraction(result, numerator, denominator);
              numerator = n;
              denominator = i;
              numeratorBits = nBits;
            }
          }
          return multiplyFraction(result, numerator, denominator);
        }
    }
  }

  /**
   * Returns (x * numerator / denominator), which is assumed to come out to an integral value.
   */
  static long multiplyFraction(long x, long numerator, long denominator) {
    if (x == 1) {
      return numerator / denominator;
    }
    long commonDivisor = gcd(x, denominator);
    x /= commonDivisor;
    denominator /= commonDivisor;
    // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact,
    // so denominator must be a divisor of numerator.
    return x * (numerator / denominator);
  }

  /*
   * binomial(biggestBinomials[k], k) fits in a long, but not
   * binomial(biggestBinomials[k] + 1, k).
   */
  static final int[] biggestBinomials =
      {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733,
          887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68,
          67, 67, 66, 66, 66, 66};

  /*
   * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl,
   * but binomial(biggestSimpleBinomials[k] + 1, k) does.
   */
  @VisibleForTesting static final int[] biggestSimpleBinomials =
      {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313,
          684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62,
          61, 61, 61};
  // These values were generated by using checkedMultiply to see when the simple multiply/divide
  // algorithm would lead to an overflow.

  static boolean fitsInInt(long x) {
    return (int) x == x;
  }

  /**
   * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward
   * negative infinity. This method is resilient to overflow.
   *
   * @since 14.0
   */
  public static long mean(long x, long y) {
    // Efficient method for computing the arithmetic mean.
    // The alternative (x + y) / 2 fails for large values.
    // The alternative (x + y) >>> 1 fails for negative values.
    return (x & y) + ((x ^ y) >> 1);
  }

  /*
   * If n <= millerRabinBases[i][0], then testing n against bases millerRabinBases[i][1..]
   * suffices to prove its primality.  Values from miller-rabin.appspot.com.
   *
   * NOTE: We could get slightly better bases that would be treated as unsigned, but benchmarks
   * showed negligible performance improvements.
   */
  private static final long[][] millerRabinBaseSets = {
    {291830, 126401071349994536L},
    {885594168, 725270293939359937L, 3569819667048198375L},
    {273919523040L, 15, 7363882082L, 992620450144556L},
    {47636622961200L, 2, 2570940, 211991001, 3749873356L},
    {7999252175582850L,
      2, 4130806001517L, 149795463772692060L, 186635894390467037L, 3967304179347715805L},
    {585226005592931976L,
      2, 123635709730000L, 9233062284813009L, 43835965440333360L, 761179012939631437L,
      1263739024124850375L},
    {Long.MAX_VALUE,
        2, 325, 9375, 28178, 450775, 9780504, 1795265022}
  };

  private enum MillerRabinTester {
    /**
     * Works for inputs <= FLOOR_SQRT_MAX_LONG.
     */
    SMALL {
      @Override
      long mulMod(long a, long b, long m) {
        /*
         * NOTE(user, 2015-Feb-12): Benchmarks suggest that changing this to
         * UnsignedLongs.remainder and increasing the threshold to 2^32 doesn't pay for itself,
         * and adding another enum constant hurts performance further -- I suspect because
         * bimorphic implementation is a sweet spot for the JVM.
         */
        return (a * b) % m;
      }

      @Override
      long squareMod(long a, long m) {
        return (a * a) % m;
      }
    },
    /**
     * Works for all nonnegative signed longs.
     */
    LARGE {
      /**
       * Returns (a + b) mod m.  Precondition: 0 <= a, b < m < 2^63.
       */
      private long plusMod(long a, long b, long m) {
        return (a >= m - b) ? (a + b - m) : (a + b);
      }

      /**
       * Returns (a * 2^32) mod m.  a may be any unsigned long.
       */
      private long times2ToThe32Mod(long a, long m) {
        int remainingPowersOf2 = 32;
        do {
          int shift = Math.min(remainingPowersOf2, Long.numberOfLeadingZeros(a));
          // shift is either the number of powers of 2 left to multiply a by, or the biggest shift
          // possible while keeping a in an unsigned long.
          a = UnsignedLongs.remainder(a << shift, m);
          remainingPowersOf2 -= shift;
        } while (remainingPowersOf2 > 0);
        return a;
      }

      @Override
      long mulMod(long a, long b, long m) {
        long aHi = a >>> 32; // < 2^31
        long bHi = b >>> 32; // < 2^31
        long aLo = a & 0xFFFFFFFFL; // < 2^32
        long bLo = b & 0xFFFFFFFFL; // < 2^32

        /*
         * a * b == aHi * bHi * 2^64 + (aHi * bLo + aLo * bHi) * 2^63 + aLo * bLo.
         *       == (aHi * bHi * 2^32 + aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo
         *
         * We carry out this computation in modular arithmetic.  Since times2ToThe32Mod accepts
         * any unsigned long, we don't have to do a mod on every operation, only when intermediate
         * results can exceed 2^63.
         */
        long result = times2ToThe32Mod(aHi * bHi /* < 2^62 */, m); // < m < 2^63
        result += aHi * bLo; // aHi * bLo < 2^63, result < 2^64
        if (result < 0) {
          result = UnsignedLongs.remainder(result, m);
        }
        // result < 2^63 again
        result += aLo * bHi; // aLo * bHi < 2^63, result < 2^64
        result = times2ToThe32Mod(result, m); // result < m < 2^63
        return plusMod(
            result,
            UnsignedLongs.remainder(aLo * bLo /* < 2^64 */, m),
            m);
      }

      @Override
      long squareMod(long a, long m) {
        long aHi = a >>> 32; // < 2^31
        long aLo = a & 0xFFFFFFFFL; // < 2^32

        /*
         * a^2 == aHi^2 * 2^64 + aHi * aLo * 2^33 + aLo^2
         *     == (aHi^2 * 2^32 + aHi * aLo * 2) * 2^32 + aLo^2
         * We carry out this computation in modular arithmetic.  Since times2ToThe32Mod accepts
         * any unsigned long, we don't have to do a mod on every operation, only when intermediate
         * results can exceed 2^63.
         */
        long result = times2ToThe32Mod(aHi * aHi /* < 2^62 */, m); // < m < 2^63
        long hiLo = aHi * aLo * 2;
        if (hiLo < 0) {
          hiLo = UnsignedLongs.remainder(hiLo, m);
        }
        // hiLo < 2^63
        result += hiLo; // result < 2^64
        result = times2ToThe32Mod(result, m); // result < m < 2^63
        return plusMod(
            result,
            UnsignedLongs.remainder(aLo * aLo /* < 2^64 */, m),
            m);
      }
    };

    static boolean test(long base, long n) {
      // Since base will be considered % n, it's okay if base > FLOOR_SQRT_MAX_LONG,
      // so long as n <= FLOOR_SQRT_MAX_LONG.
      return ((n <= FLOOR_SQRT_MAX_LONG) ? SMALL : LARGE).testWitness(base, n);
    }

    /**
     * Returns a * b mod m.
     */
    abstract long mulMod(long a, long b, long m);

    /**
     * Returns a^2 mod m.
     */
    abstract long squareMod(long a, long m);

    /**
     * Returns a^p mod m.
     */
    private long powMod(long a, long p, long m) {
      long res = 1;
      for (; p != 0; p >>= 1) {
        if ((p & 1) != 0) {
          res = mulMod(res, a, m);
        }
        a = squareMod(a, m);
      }
      return res;
    }

    /**
     * Returns true if n is a strong probable prime relative to the specified base.
     */
    private boolean testWitness(long base, long n) {
      int r = Long.numberOfTrailingZeros(n - 1);
      long d = (n - 1) >> r;
      base %= n;
      if (base == 0) {
        return true;
      }
      // Calculate a := base^d mod n.
      long a = powMod(base, d, n);
      // n passes this test if
      //    base^d = 1 (mod n)
      // or base^(2^j * d) = -1 (mod n) for some 0 <= j < r.
      if (a == 1) {
        return true;
      }
      int j = 0;
      while (a != n - 1) {
        if (++j == r) {
          return false;
        }
        a = squareMod(a, n);
      }
      return true;
    }
  }

  private LongMath() {}
}


text:
layout: post
title: Disable Nouveau on CentOS 7
tags: [centos, nvidia]
author: Spencer Riner
comment: false
---

# Prerequisites

Install latest kernel and download Nvidia driver. Nvidia drivers can be downloaded in `elinks` if graphics aren't available:

```bash
elinks http://download.nvidia.com/XFree86/Linux-x86_64
```

or using `wget` if the desired version is known:

```bash
wget http://download.nvidia.com/XFree86/Linux-x86_64/390.87/NVIDIA-Linux-x86_64-390.87.run
```

# Steps

Edit `/etc/default/grub` and add the following line to `GRUB_CMDLINE_LINUX`:

```bash
rdblacklist=nouveau nouveau.modeset=0
```

Generate new grub config:

```bash
grub2-mkconfig –o /boot/grub2/grub.cfg
```

Add the following line to `/etc/modprobe.d/blacklist.conf`. Create that file if it doesn't exist.

```bash
blacklist nouveau
```

Back up old initramfs and generate a new one:

```bash
mv /boot/initramfs-$(uname -r).img /boot/initramfs-$(uname -r)-nouveau.img
dracut /boot/initramfs-$(uname -r).img $(uname -r)
```

Reboot the computer and install the Nvidia driver.

```bash
init 3
chmod u+x NVIDIA-Linux-x86_64-390.87.run
./NVIDIA-Linux-x86_64-390.87.run
init 5
```

redpajama_set_name: RedPajamaGithub


text:
# gulp-changed

> Only pass through changed files

No more wasting precious time on processing unchanged files.

By default it's only able to detect whether files in the stream changed. If you require something more advanced like knowing if imports/dependencies changed, create a custom comparator, or use [another plugin](https://github.com/gulpjs/gulp#incremental-builds).

## Install

```
$ npm install --save-dev gulp-changed
```

## Usage

```js
const gulp = require('gulp');
const changed = require('gulp-changed');
const ngAnnotate = require('gulp-ng-annotate'); // Just as an example

const SOURCE = 'src/*.js';
const DESTINATION = 'dist';

exports.default = () => (
	gulp.src(SOURCE)
		.pipe(changed(DESTINATION))
		// `ngAnnotate` will only get the files that
		// changed since the last time it was run
		.pipe(ngAnnotate())
		.pipe(gulp.dest(DESTINATION))
);
```

## API

### changed(destination, options?)

#### destination

Type: `string | Function`

Destination directory. Same as you put into `gulp.dest()`.

This is needed to be able to compare the current files with the destination files.

Can also be a function returning a destination directory path.

#### options

Type: `object`

##### cwd

Type: `string`

Default: `process.cwd()`

Working directory the folder is relative to.

##### extension

Type: `string`

Extension of the destination files.

Useful if it differs from the original, like in the example below:

```js
exports.jade = () => (
	gulp.src('src/**/*.jade')
		.pipe(changed('app', {extension: '.html'}))
		.pipe(jade())
		.pipe(gulp.dest('app'))
);
```

##### hasChanged

Type: `Function`

Default: `changed.compareLastModifiedTime`

Function that determines whether the source file is different from the destination file.

###### Built-in comparators

- `changed.compareLastModifiedTime`
- `changed.compareContents`

###### Example

```js
exports.jade = () => (
	gulp.src('src/**/*.jade')
		.pipe(changed('app', {hasChanged: changed.compareContents}))
		.pipe(jade())
		.pipe(gulp.dest('app'))
);
```

You can also supply a custom comparator function which will receive the following arguments and should return `Promise`.

- `stream` *([transform object stream](https://github.com/rvagg/through2#transformfunction))* - Should be used to queue `sourceFile` if it passes some comparison
- `sourceFile` *([Vinyl file object](https://github.com/wearefractal/vinyl#file))*
- `destPath` *(string)* - Destination for `sourceFile` as an absolute path

##### transformPath

Type: `Function`

Function to transform the path to the destination file. Should return the absolute path to the (renamed) destination file.

Useful if you rename your file later on, like in the below example:

```js
exports.marked = () => (
	gulp.src('src/content/about.md')
		.pipe(changed('dist', {transformPath: newPath => path.join(path.dirname(newPath), path.basename(newPath, '.md'), 'index.html')}))
		.pipe(marked())
		.pipe(rename(newPath => path.join(path.dirname(newPath), path.basename(newPath, '.md'), 'index.html'))))
		.pipe(gulp.dest('dist'))
);
```

## In-place change monitoring

If you're looking to process source files in-place without any build output (formatting, linting, etc), have a look at [gulp-changed-in-place](https://github.com/alexgorbatchev/gulp-changed-in-place).


text:
namespace blink {
namespace user_level_memory_pressure_signal_generator_test {

using testing::_;

// Mock that allows setting mock memory usage.
class MockMemoryUsageMonitor : public MemoryUsageMonitor {
 public:
  MockMemoryUsageMonitor() = default;
  ~MockMemoryUsageMonitor() override = default;

  MemoryUsage GetCurrentMemoryUsage() override { return mock_memory_usage_; }

  // MemoryUsageMonitor will report the current memory usage as this value.
  void SetMockMemoryUsage(MemoryUsage usage) { mock_memory_usage_ = usage; }

 private:
  MemoryUsage mock_memory_usage_;
};

class MockUserLevelMemoryPressureSignalGenerator
    : public UserLevelMemoryPressureSignalGenerator {
 public:
  explicit MockUserLevelMemoryPressureSignalGenerator(
      scoped_refptr<base::TestMockTimeTaskRunner> mock_time_task_runner)
      : UserLevelMemoryPressureSignalGenerator(
            mock_time_task_runner,
            mock_time_task_runner->GetMockTickClock()) {
    ON_CALL(*this, Generate(_))
        .WillByDefault(testing::Invoke(
            this, &MockUserLevelMemoryPressureSignalGenerator::RealGenerate));
  }
  ~MockUserLevelMemoryPressureSignalGenerator() override = default;

  MOCK_METHOD1(Generate, void(MemoryUsage));

  void RealGenerate(MemoryUsage usage) {
    UserLevelMemoryPressureSignalGenerator::Generate(usage);
  }

  using UserLevelMemoryPressureSignalGenerator::OnRAILModeChanged;
};

class ScopedMockMemoryUsageMonitor {
 public:
  ScopedMockMemoryUsageMonitor(MemoryUsageMonitor* monitor) {
    MemoryUsageMonitor::SetInstanceForTesting(monitor);
  }
  ~ScopedMockMemoryUsageMonitor() {
    MemoryUsageMonitor::SetInstanceForTesting(nullptr);
  }
};

class UserLevelMemoryPressureSignalGeneratorTest : public testing::Test {
 public:
  UserLevelMemoryPressureSignalGeneratorTest() = default;

  void SetUp() override {
    std::map<std::string, std::string> feature_parameters;
    feature_parameters["param_512mb_device_memory_threshold_mb"] = "1024.0";
    feature_parameters["param_1gb_device_memory_threshold_mb"] = "1024.0";
    feature_parameters["param_2gb_device_memory_threshold_mb"] = "1024.0";
    feature_parameters["param_3gb_device_memory_threshold_mb"] = "1024.0";
    feature_parameters["param_4gb_device_memory_threshold_mb"] = "1024.0";
    feature_parameters["minimum_interval_s"] = "600.0";

    scoped_feature_list_.InitAndEnableFeatureWithParameters(
        blink::features::kUserLevelMemoryPressureSignal, feature_parameters);

    test_task_runner_ = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  }

  void AdvanceClock(base::TimeDelta delta) {
    test_task_runner_->FastForwardBy(delta);
  }

 protected:
  base::test::ScopedFeatureList scoped_feature_list_;
  scoped_refptr<base::TestMockTimeTaskRunner> test_task_runner_;
};

constexpr double kMemoryThresholdBytes = 1024 * 1024 * 1024;

// Flaky on Android, see crbug/1054788.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_GeneratesWhenOverThreshold DISABLED_GeneratesWhenOverThreshold
#else
#define MAYBE_GeneratesWhenOverThreshold GeneratesWhenOverThreshold
#endif
TEST_F(UserLevelMemoryPressureSignalGeneratorTest,
       MAYBE_GeneratesWhenOverThreshold) {
  {
    std::unique_ptr<MockMemoryUsageMonitor> mock_memory_usage_monitor =
        std::make_unique<MockMemoryUsageMonitor>();
    ScopedMockMemoryUsageMonitor mock_memory_usage_scope(
        mock_memory_usage_monitor.get());
    MockUserLevelMemoryPressureSignalGenerator generator(test_task_runner_);
    // Ensure we are not loading as no signals are sent during a loading phase.
    generator.OnRAILModeChanged(RAILMode::kAnimation);
    {
      EXPECT_CALL(generator, Generate(_)).Times(0);
      MemoryUsage usage;
      usage.v8_bytes = 0;
      usage.blink_gc_bytes = 0;
      usage.partition_alloc_bytes = 0;
      usage.private_footprint_bytes = kMemoryThresholdBytes - 1024 * 1024;
      usage.swap_bytes = 0;
      usage.vm_size_bytes = 0;
      mock_memory_usage_monitor->SetMockMemoryUsage(usage);
      AdvanceClock(base::Seconds(1));
      test::RunDelayedTasks(base::Seconds(1));
    }
    {
      EXPECT_CALL(generator, Generate(_)).Times(1);
      MemoryUsage usage;
      usage.v8_bytes = 0;
      usage.blink_gc_bytes = 0;
      usage.partition_alloc_bytes = 0;
      usage.private_footprint_bytes = kMemoryThresholdBytes + 1024 * 1024;
      usage.swap_bytes = 0;
      usage.vm_size_bytes = 0;
      mock_memory_usage_monitor->SetMockMemoryUsage(usage);
      AdvanceClock(base::Minutes(10));
      test::RunDelayedTasks(base::Seconds(1));
    }
  }
}

// Flaky on Android, see crbug/1058178.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_GenerationPauses DISABLED_GenerationPauses
#else
#define MAYBE_GenerationPauses GenerationPauses
#endif
TEST_F(UserLevelMemoryPressureSignalGeneratorTest, MAYBE_GenerationPauses) {
  {
    std::unique_ptr<MockMemoryUsageMonitor> mock_memory_usage_monitor =
        std::make_unique<MockMemoryUsageMonitor>();
    ScopedMockMemoryUsageMonitor mock_memory_usage_scope(
        mock_memory_usage_monitor.get());
    MockUserLevelMemoryPressureSignalGenerator generator(test_task_runner_);
    // Ensure we are not loading as no signals are sent during a loading phase.
    generator.OnRAILModeChanged(RAILMode::kAnimation);
    {
      MemoryUsage usage;
      usage.v8_bytes = 0;
      usage.blink_gc_bytes = 0;
      usage.partition_alloc_bytes = 0;
      usage.private_footprint_bytes = kMemoryThresholdBytes + 1024 * 1024;
      usage.swap_bytes = 0;
      usage.vm_size_bytes = 0;
      mock_memory_usage_monitor->SetMockMemoryUsage(usage);
      AdvanceClock(base::Minutes(10));
      // Generated
      {
        EXPECT_CALL(generator, Generate(_)).Times(1);
        test::RunDelayedTasks(base::Seconds(1));
      }

      AdvanceClock(base::Minutes(1));
      // Not generated because too soon
      {
        EXPECT_CALL(generator, Generate(_)).Times(0);
        test::RunDelayedTasks(base::Seconds(1));
      }

      AdvanceClock(base::Minutes(10));
      generator.OnRAILModeChanged(RAILMode::kLoad);
      // Not generated because loading
      {
        EXPECT_CALL(generator, Generate(_)).Times(0);
        test::RunDelayedTasks(base::Seconds(1));
      }

      generator.OnRAILModeChanged(RAILMode::kAnimation);
      // Generated
      {
        EXPECT_CALL(generator, Generate(_)).Times(1);
        test::RunDelayedTasks(base::Seconds(1));
      }
    }
  }
}

}  // namespace user_level_memory_pressure_signal_generator_test
}  // namespace blink


text:
if (Drupal.jsEnabled) {
  $(document).ready(function() {
    // I am assuming that all of the links are refering to an internal node

    // add the attribute rel=facebox to all of the links I want to have a popup
    $('div.view-field > a').attr('class', 'popup');

    // on click of a link
    $('a.popup').click(function(a) {

      // Make sure that other stuff is closed. This seems to cause a problem in Fx2 and IE7.
      $('div#calpopup').fadeOut();
      $('div#calpopup').remove();

      // create div to hold data and add it to the end of the body
      var div = $('

').attr('style','display: none');
      div.appendTo(document.body);

      // Locate Popup
      var offset = $(this).offset();
      // Check position with window width.
      var offset_left = offset.left + 5;
      if ($(window).width() < $('#calpopup').width() + offset.left) {
        offset_left -= $('#calpopup').width() + 5;
        if (offset_left < 0) {
          offset_left = 0;
        }
      }
      var offset_top = offset.top + 25;
      if ($(window).height() < $('#calpopup').height() + offset_top) {
        offset_top -= $('#calpopup').height() + 25;
	      if (offset_top < 0) {
          offset_top = 0;
        }
      }
      $('#calpopup').css('left', offset_left);
      $('#calpopup').css('top', offset_top);

      // Show Popup
      $('#calpopup').fadeIn('slow');

      // If sucessful call this
      function domCallback(msg) {
        $('#calpopup-body').html(msg);
      }

      // Get NodeID and ItemID
      var ids = $(this).parent().parent().attr('id');
      var arr = ids.split(":");
      var nid = arr[1];
      var id = arr[4];

      // fill the div with data
      $.ajax({
        type: "GET",
        url: var_base_path + "?q=jcalendar/getnode/"+nid+"/"+ids,
        success: function(msg){
          domCallback(msg);
        }
      });

      // On click of the close image
      $('img#popup-close-img').click(function(x) {
        $('div#calpopup').fadeOut();
        $('div#calpopup').remove();
      });

      $(document).click(function(y) {
        var $tgt = $(y.target);
        if (!$tgt.parents().is('div#calpopup')) {
          $('div#calpopup').fadeOut();
          $('div#calpopup').remove();
          $(document).unbind("click");
        }
      });

      // Don't Follow the real link
      return false;
    });
  });
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.faustool.iib.resteasy</groupId>
	<artifactId>iib-resteasy</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<resteasy.version>3.0.13.Final</resteasy.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.faustool.iib.junit4</groupId>
			<artifactId>iib-junit4</artifactId>
			<version>1.0.0-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>tjws</artifactId>
			<version>${resteasy.version}</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>${resteasy.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.4.0</version>
				<executions>
					<execution>
						<goals>
							<goal>java</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<mainClass>com.faustool.iib.resteasy.RestService</mainClass>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text: My solutions for the problems on CodeEval


text:
package com.thoughtworks.go.server.service;

import com.thoughtworks.go.domain.GoVersion;
import com.thoughtworks.go.domain.VersionInfo;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.dao.VersionInfoDao;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.SystemTimeClock;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class ServerVersionInfoManagerTest {

    VersionInfoDao versionInfoDao;
    ServerVersionInfoBuilder builder;
    ServerVersionInfoManager manager;
    GoCache goCache;
    SystemEnvironment systemEnvironment;

    @Before
    public void setUp() {
        builder = mock(ServerVersionInfoBuilder.class);
        versionInfoDao = mock(VersionInfoDao.class);
        goCache = mock(GoCache.class);
        systemEnvironment = mock(SystemEnvironment.class);
        manager = new ServerVersionInfoManager(builder, versionInfoDao, new SystemTimeClock(), goCache, systemEnvironment);

        stub(systemEnvironment.isProductionMode()).toReturn(true);
        when(systemEnvironment.isGOUpdateCheckEnabled()).thenReturn(true);
    }

    @Test
    public void shouldUseServerVersionInfoBuilderToGetServerVersionInfo(){
        when(builder.getServerVersionInfo()).thenReturn(new VersionInfo());

        manager.initialize();

        verify(builder).getServerVersionInfo();
    }

    @Test
    public void shouldAddNewVersionInfoToCacheIfLatestVersionIsGreaterThanInstalledVersion(){
        GoVersion currentVersion = new GoVersion("1.2.3-1");
        GoVersion latestVersion = new GoVersion("2.3.4-2");
        VersionInfo versionInfo = new VersionInfo("go_server", currentVersion, latestVersion, null);

        when(builder.getServerVersionInfo()).thenReturn(versionInfo);

        manager.initialize();

        verify(builder).getServerVersionInfo();
        verify(goCache).put("GOUpdate", latestVersion.toString());
    }

    @Test
    public void shouldNotUpdateCacheIfLatestVersionIsLesserThanInstalledVersion(){
        GoVersion currentVersion = new GoVersion("4.7.3-1");
        GoVersion latestVersion = new GoVersion("2.3.4-2");
        VersionInfo versionInfo = new VersionInfo("go_server", currentVersion, latestVersion, null);

        when(builder.getServerVersionInfo()).thenReturn(versionInfo);

        manager.initialize();

        verify(builder).getServerVersionInfo();
        verify(goCache, never()).put(anyString(), anyString());
    }

    @Test
    public void shouldNotUpdateCacheIfServerVersionInfoIsUnAvailable(){
        when(builder.getServerVersionInfo()).thenReturn(null);

        manager.initialize();

        verify(builder).getServerVersionInfo();
        verify(goCache, never()).put(anyString(), anyString());
    }
    @Test
    public void shouldReturnVersionInfoIfServerLatestVersionNotUpdated(){
        Date yesterday = new Date(System.currentTimeMillis() - 24*60*60*1000);
        VersionInfo versionInfo = new VersionInfo("go_server", new GoVersion("1.2.3-1"), new GoVersion("2.3.4-2"), yesterday);

        when(builder.getServerVersionInfo()).thenReturn(versionInfo);

        manager.initialize();
        VersionInfo goVersionInfo = manager.versionInfoForUpdate();

        assertThat(goVersionInfo, is(versionInfo));
    }

    @Test
    public void shouldNotReturnVersionInfoIfLatestVersionUpdatedToday(){
        Date today = new Date();
        VersionInfo versionInfo = new VersionInfo("go_server", new GoVersion("1.2.3-1"), new GoVersion("2.3.4-2"), today);

        when(builder.getServerVersionInfo()).thenReturn(versionInfo);

        manager.initialize();
        VersionInfo serverVersionInfo = manager.versionInfoForUpdate();

        assertNull(serverVersionInfo);
    }

    @Test
    public void shouldNotReturnVersionInfoForDevelopementServer(){
        when(builder.getServerVersionInfo()).thenReturn(null);
        when(systemEnvironment.isProductionMode()).thenReturn(false);

        manager.initialize();

        assertNull(manager.versionInfoForUpdate());
    }

    @Test
    public void shouldNotGetVersionInfoIfLatestVersionIsBeingUpdated(){
        Date yesterday = new Date(System.currentTimeMillis() - 24*60*60*1000);
        VersionInfo versionInfo = new VersionInfo("go_server", new GoVersion("1.2.3-1"), new GoVersion("2.3.4-2"), yesterday);

        when(builder.getServerVersionInfo()).thenReturn(versionInfo);

        manager.initialize();
        VersionInfo serverVersionInfo1 = manager.versionInfoForUpdate();
        VersionInfo serverVersionInfo2 = manager.versionInfoForUpdate();

        assertNotNull(serverVersionInfo1);
        assertNull(serverVersionInfo2);
    }

    @Test
    public void shouldGetVersionInfoIflatestVersionIsBeingUpdatedForMoreThanHalfAnHour(){
        SystemTimeClock systemTimeClock = mock(SystemTimeClock.class);
        Date yesterday = new Date(System.currentTimeMillis() - 24*60*60*1000);
        DateTime halfAnHourFromNow = new DateTime(System.currentTimeMillis() - 35 * 60 * 1000);
        VersionInfo versionInfo = new VersionInfo("go_server", new GoVersion("1.2.3-1"), new GoVersion("2.3.4-2"), yesterday);

        when(builder.getServerVersionInfo()).thenReturn(versionInfo);
        when(systemTimeClock.currentDateTime()).thenReturn(halfAnHourFromNow);

        manager = new ServerVersionInfoManager(builder, versionInfoDao, systemTimeClock, goCache, systemEnvironment);
        manager.initialize();

        VersionInfo serverVersionInfo1 = manager.versionInfoForUpdate();
        VersionInfo serverVersionInfo2 = manager.versionInfoForUpdate();

        assertNotNull(serverVersionInfo1);
        assertNotNull(serverVersionInfo2);
    }

    @Test
    public void shouldBeAbleToUpdateTheLatestGOVersion(){
        SystemTimeClock systemTimeClock = mock(SystemTimeClock.class);
        VersionInfo versionInfo = new VersionInfo("go_server", new GoVersion("1.2.3-1"), new GoVersion("2.3.4-1"), null);
        Date now = new Date();

        when(builder.getServerVersionInfo()).thenReturn(versionInfo);
        when(systemTimeClock.currentTime()).thenReturn(now);

        manager = new ServerVersionInfoManager(builder, versionInfoDao, systemTimeClock, goCache, systemEnvironment);

        manager.initialize();
        VersionInfo info = manager.updateLatestVersion("15.0.1-123");

        assertThat(info.getLatestVersion().toString(), is("15.0.1-123"));
        assertThat(info.getLatestVersionUpdatedAt(), is(now));
        verify(versionInfoDao).saveOrUpdate(versionInfo);
    }

    @Test
    public void shouldUpdateCacheWithNewVersionIfLatestVersionIsGreaterThanInstalledVersion(){
        SystemTimeClock systemTimeClock = mock(SystemTimeClock.class);
        VersionInfo versionInfo = new VersionInfo("go_server", new GoVersion("1.2.3-1"), new GoVersion("1.2.3-1"), null);
        Date now = new Date();

        when(builder.getServerVersionInfo()).thenReturn(versionInfo);
        when(systemTimeClock.currentTime()).thenReturn(now);

        manager = new ServerVersionInfoManager(builder, versionInfoDao, systemTimeClock, goCache, systemEnvironment);
        manager.initialize();
        manager.updateLatestVersion("15.0.1-123");

        verify(goCache).put("GOUpdate", "15.0.1-123");
    }

    @Test
    public void shouldGetGoUpdateFromCache(){
        String newRelease = "15.0.1-123";
        GoCache goCache = mock(GoCache.class);

        when(goCache.get("GOUpdate")).thenReturn(newRelease);

        manager = new ServerVersionInfoManager(builder, versionInfoDao, new SystemTimeClock(), goCache, null);

        assertThat(manager.getGoUpdate(), is(newRelease));
    }

    @Test
    public void shouldBeTrueIfVersionCheckEnabledOnProductionServer(){
        SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);

        when(builder.getServerVersionInfo()).thenReturn(new VersionInfo());
        when(systemEnvironment.isGOUpdateCheckEnabled()).thenReturn(true);
        when(systemEnvironment.isProductionMode()).thenReturn(true);

        manager = new ServerVersionInfoManager(builder, versionInfoDao, new SystemTimeClock(), goCache, systemEnvironment);
        manager.initialize();

        assertTrue(manager.isUpdateCheckEnabled());
    }

    @Test
    public void updateCheckShouldBeDisabledForADevelopmentServer(){
        SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);

        when(builder.getServerVersionInfo()).thenReturn(new VersionInfo());
        when(systemEnvironment.isProductionMode()).thenReturn(false);
        when(systemEnvironment.isGOUpdateCheckEnabled()).thenReturn(true);

        manager = new ServerVersionInfoManager(builder, versionInfoDao, new SystemTimeClock(), goCache, systemEnvironment);
        manager.initialize();

        assertFalse(manager.isUpdateCheckEnabled());
    }

    @Test
    public void shouldBeFalseIfVersionCheckIsDisabled(){
        SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);

        when(builder.getServerVersionInfo()).thenReturn(new VersionInfo());
        when(systemEnvironment.isProductionMode()).thenReturn(true);
        when(systemEnvironment.isGOUpdateCheckEnabled()).thenReturn(false);

        manager = new ServerVersionInfoManager(builder, versionInfoDao, new SystemTimeClock(), goCache, systemEnvironment);
        manager.initialize();

        assertFalse(manager.isUpdateCheckEnabled());
    }
}


text:
<refentry id="shade.verbatim">
<refmeta>
<refentrytitle>shade.verbatim</refentrytitle>
<refmiscinfo role="type">boolean</refmiscinfo>
</refmeta>
<refnamediv>
<refname>shade.verbatim</refname>
<refpurpose>Should verbatim environments be shaded?</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment id='shade.verbatim.frag'><xsl:param name="shade.verbatim" select="0"/></src:fragment>
</refsynopsisdiv>

<refsect1><title>Description</title>

<para>In the FO stylesheet, if this parameter is non-zero then the
<property>shade.verbatim.style</property> properties will be applied
to verbatim environments.</para>

<para>In the HTML stylesheet, this parameter is now deprecated. Use
CSS instead.</para>

</refsect1>
</refentry>


text:
The Rust compiler supports building with some dependencies from `crates.io`.
Examples are `log` and `env_logger`.

In general,
you should avoid adding dependencies to the compiler for several reasons:

- The dependency may not be of high quality or well-maintained.
- The dependency may not be using a compatible license.
- The dependency may have transitive dependencies that have one of the above
  problems.

As of <!-- date-check --> Aug 2022,
there is no official policy for vetting new dependencies to the compiler.
Decisions are made on a case-by-case basis,
during code review.

## Permitted dependencies

The `tidy` tool has [a list of crates that are allowed]. To add a
dependency that is not already in the compiler, you will need to add it to the list.

[a list of crates that are allowed]: https://github.com/rust-lang/rust/blob/9d1b2106e23b1abd32fce1f17267604a5102f57a/src/tools/tidy/src/deps.rs#L73


text:
/**
 * Squirrel-3
 * @version 1.0.1
 * @anthor: iinterest.bell@gmail.com
 */
/* jshint strict: false, quotmark: false */

/**
 * change log
 * 1.0.1    * autoprefixer 设置为 'android 4', 'ios 7'
 *          - 删除 gulp-minify-css
 */

// Load plugins
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var del = require('del');
var footer = require('gulp-footer');
var gulpif = require('gulp-if');
var jshint = require('gulp-jshint');
var less = require('gulp-less');
var livereload = require('gulp-livereload');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var replace = require('gulp-replace');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');

var pkg = require('./package.json');
var date = new Date();
pkg.date = date.getFullYear() + '-' + ('00' + (date.getMonth() + 1)).slice(-2) + '-' +
('00' + date.getDate()).slice(-2) + ' ' + ('00' + date.getHours()).slice(-2) + ':' +
('00' + date.getMinutes()).slice(-2) + ':' + ('00' + date.getSeconds()).slice(-2);
var timestamp = ['\n/*',
    ' <%= pkg.name %>',
    ' @version v<%= pkg.version %>',
    ' @date <%= pkg.date %>',
    ' */'].join('');

// Config
var toggle = {
    autoprefix: true,
    imagemin: false,
    jshint: true,
    sourcemaps: true
};
var paths = {
    scripts: [
        'src/scripts/core/*.js',
        'src/scripts/global.js',
        'src/scripts/*.js',
        'src/scripts/plugins/*.js',
        'src/scripts/**/*.js'
    ],
    styles: 'src/styles/' + pkg.name + '.less',
    images: [
        'src/images/**/*.jpg',
        'src/images/**/*.gif',
        'src/images/**/*.png'
    ],
    fonts: [
        /*'bower_components/fontawesome/fonts/fontawesome.otf',
        'bower_components/fontawesome/fonts/fontawesome-webfont.eot',
        'bower_components/fontawesome/fonts/fontawesome-webfont.svg',*/
        'bower_components/fontawesome/fonts/fontawesome-webfont.ttf',
        'bower_components/fontawesome/fonts/fontawesome-webfont.woff'
    ],
    lib: [
        'bower_components/jquery/dist/jquery.min.js',
        'bower_components/jquery/dist/jquery.min.map'
    ],
    watchs: {
        scripts: 'src/scripts/**/*.js',
        styles: 'src/styles/**/*.less',
        templates: 'example/**/*.html',
        dist: 'dist/**/*'
    }
};
var dests = {
    styles: './dist/css',
    scripts: './dist/js',
    images: './dist/images',
    fonts: './dist/fonts',
    maps: '../maps'
};
var options = {
    autoprefix: {
        browsers: ['android 4', 'ios 7']
    },
    fileName: pkg.name,
    less: {compress: true},
    imagemin: {progressive: true},
    jshint: '.jshintrc',
    jshintReporter: 'default',
    rename: {suffix: '.min'}
};

// Tasks
// 通常情况,以下任务是不能修改的,如果遇到特殊情况需要修改,请注明!

// Styles
gulp.task('styles', function () {
    gulp.src(paths.styles)
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
        .pipe(gulpif(toggle.sourcemaps, sourcemaps.init()))
        .pipe(less(options.less))
        .pipe(gulpif(toggle.autoprefix, autoprefixer(options.autoprefix)))
        .pipe(rename(options.rename))
        .pipe(footer(timestamp, {pkg: pkg}))
        .pipe(gulpif(toggle.sourcemaps, sourcemaps.write(dests.maps)))
        .pipe(gulp.dest(dests.styles));
});

// Scripts
gulp.task('scripts', function () {
    gulp.src(paths.scripts)
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
        .pipe(gulpif(toggle.sourcemaps, sourcemaps.init()))
        .pipe(gulpif(toggle.jshint, jshint(options.jshint)))
        .pipe(gulpif(toggle.jshint, jshint.reporter(options.jshintReporter)))
        .pipe(concat(options.fileName + '.js'))
        .pipe(rename(options.rename))
        .pipe(uglify())
        .pipe(footer(timestamp, {pkg: pkg}))
        .pipe(gulpif(toggle.sourcemaps, sourcemaps.write(dests.maps)))
        .pipe(gulp.dest(dests.scripts));
});

// Images
gulp.task('images', function () {
    gulp.src(paths.images)
        .pipe(gulp.dest(dests.images));
});

// Fonts
gulp.task('coypFonts', function () {
    gulp.src(paths.fonts)
        .pipe(gulp.dest(dests.fonts));
});

// Lib
gulp.task('copyLib', function () {
    gulp.src(paths.lib)
        .pipe(gulp.dest(dests.scripts));
});

// Clean
gulp.task('clean', function (cb) {
    del(['dist', 'build'], cb);
});

// Build
gulp.task('build', ['clean'], function () {
    gulp.start('styles', 'scripts', 'images', 'coypFonts', 'copyLib');
});

// Default
gulp.task('default', ['build']);

// Release 发布
gulp.task('release', function (cb) {
    // 因为 UAE 不支持 .map 文件类型,所以暂时在发布时去除 sourcemaps
    toggle.sourcemaps = false;
    gulp.start('build');
});

// Watch
gulp.task('watch', function () {
    // .js files
    gulp.watch(paths.watchs.scripts, ['scripts']);
    // .less files
    gulp.watch(paths.watchs.styles, ['styles']);
    // images files
    gulp.watch(paths.images, ['images']);
    // LiveReload server
    livereload.listen();
    // Watch any files in dist/, pages/, reload on change
    gulp.watch([paths.watchs.dist, paths.watchs.templates]).on('change', livereload.changed);
});


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<!--
Copyright © 1991-2014 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<ldml>
	<identity>
		<version number="$Revision: 11914 $" />
		<language type="ca" />
	</identity>
	<collations>
		<collation type="search">
			<cr><![CDATA[
				[import und-u-co-search]
				# Below are the rules specific to ca.
				# Per Apple language group, these are modified from standard rules below
				# to make L primary-different from L-dot for search.
				&L<ŀ=l·<<<Ŀ=L·
			]]></cr>
		</collation>
		<!-- standard collation &L<<ŀ=l·<<<Ŀ=L· is equivalent to root collation order
			(except root uses prefix rules for the middle dot, rather than contractions)
			references="Enciclopèdia Catalana: Diccionari de la llengua catalana ISBN 84-85194-46-2" -->
		<collation draft="unconfirmed" alt="proposed" type="standard">
			<cr><![CDATA[
				&C<ch<<<cH<<<Ch<<<CH
				&L<ll<<<l·l<<<lL<<<l·L<<<Ll<<<L·l<<<LL<<<L·L
			]]></cr>
		</collation>
	</collations>
</ldml>


text:
/*
 * USED ONLY TO STYLE THE DEMO PAGES
 * THIS CSS HAS NOTHING TO DO WITH HOW FORESIGHT.JS WORKS
 *
 */
body { margin:0; padding:0; font:12px/16px "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif }

body.index { padding:2px 15px; }

h1, h2 { margin: 10px 0; }
h3 { margin:25px 0 0; }

li { margin-bottom: 10px;}

.index p { margin-top:2px; }

section { margin:0 10px; }

article p { padding-right:15px; }

article p:first-child { margin-top:0; }

pre { font-size: 0.9em; text-align:left; }

.fs-standard-resolution { border-top:5px solid red; border-bottom:5px solid red; }

.fs-high-resolution { border-top:5px solid green; border-bottom:5px solid green; }

#qr { margin-top:90px; width:200px; font-size:10px; text-align:center; }


text:
declare const paper: any;

const PI = Math.PI;

/**
 * Return a paper.js rectangle with two points.
 * Ratio should be height divided by width. (Ex. ratio = 1 means square)
 * If ratio is false, then rectangle will not be snapped to ratio
 */

export function getRect(fromPoint, toPoint, ratio: number | false = false) {

	const rect = new paper.Rectangle(fromPoint, toPoint);

	if (ratio) {
		const squarePoint = roundLinePoint(fromPoint, toPoint, true, ratio);
		return new paper.Rectangle(fromPoint, squarePoint);
	}

	return rect;
}

/**
 * Returns a paper.js point which rounds the currentPoint either horizontal, vertical, or diagonal to the startPoint.
 * Ratio should be height divided by width. (Ex. ratio = 1 means square)
 */

export function roundLinePoint(startPoint, currentPoint, diagonalOnly = false, ratio = 1) {
	// When holding shift, lines may also be rounded to straightly vertical or horizontal
	const vector = new paper.Point(currentPoint.x - startPoint.x, currentPoint.y - startPoint.y);
	const unroundedAngle = vector.getAngle();

	const ratioAngle = slopeToAngle(ratio);

	// Round angle
	let roundAngles = [
		ratioAngle,
		-ratioAngle,
		180 - ratioAngle,
		-180 + ratioAngle
	];

	if (!diagonalOnly) {
		roundAngles = roundAngles.concat([0, 90, 180, -90]);
	}

	const roundedAngle = roundClosest(roundAngles, unroundedAngle);

	// Now find what point is along a squared rectangle with the rounded angle
	const square = getExpandedRect(startPoint, currentPoint, ratio);

	// Find the farthest point
	const farthest = getFarthestPoint(square, startPoint);
	// Mirror farthest point across startPoint, to get bigger rect surrounding whole startPoint
	const oppositeX = -(farthest.x - startPoint.x) + startPoint.x;
	const oppositeY = -(farthest.y - startPoint.y) + startPoint.y;
	const opposite = new paper.Point(oppositeX, oppositeY);
	// Create big rectangle that surrounds whole center
	const bigSquare = new paper.Rectangle(farthest, opposite);

	return edgeOfRect(bigSquare, -roundedAngle);
}

/**
 * Return a paper.js rectangle with two points. Will expand rectangle to be a square, so toPoint will not necessarily be a corner.
 */

export function getExpandedRect(fromPoint, toPoint, ratio = 1) {

	const currentRect = new paper.Rectangle(fromPoint, toPoint);
	const currentRatio = currentRect.height / currentRect.width;

	// Remember which corner fromPoint is. This is the anchor and this point should not move.
	const corners = [
		'topLeft',
		'topRight',
		'bottomLeft',
		'bottomRight'
	];

	let anchorCorner = null;

	for (let i = 0; i < corners.length; i++) {
		const corner = corners[i];
		if (currentRect[corner].equals(fromPoint)) {
			anchorCorner = corner;
			break;
		}
	}

	// Check if current ratio is greater than target ratio
	if (currentRatio > ratio) {
		// Current ratio is greater than target
		// Width needs to change to fit ratio
		currentRect.width = currentRect.height / ratio;
	} else if (currentRatio < ratio) {
		// Current ratio is less than target
		// Height need to change to fit ratio
		currentRect.height = currentRect.width * ratio;
	}

	// Find how much anchor moved
	const changePos = currentRect[anchorCorner].subtract(fromPoint);
	// Move whole rectangle however much anchor moved
	currentRect.point = currentRect.point.subtract(changePos);

	return currentRect;
}

/**
 * Find the farthest corner on a rectangle from a specific point
 */

export function getFarthestPoint(rect, point) {
	const sides = [
		'topLeft',
		'topRight',
		'bottomLeft',
		'bottomRight'
	];

	let lengths = [];
	let farthest = null;

	sides.forEach(corner => {
		const distance = point.getDistance(rect[corner]);

		// Check if distance is farthest distance so far
		let isFarthest = true;
		lengths.forEach(length => {
			if (distance < length) {
				isFarthest = false;
			}
		});
		if (isFarthest) {
			farthest = corner;
		}

		lengths.push(distance);
	});

	return rect[farthest];
}

/**
 * Gets the intersection of perimeter of rectangle, given angle from center
 * http://stackoverflow.com/a/4062485/4594858
 */

export function edgeOfRect(rect, deg) {

	const twoPI = PI * 2;
	let theta = (deg * PI) / 180;

	while (theta < -PI) {
		theta += twoPI;
	}

	while (theta > PI) {
		theta -= twoPI;
	}

	const rectAtan = Math.atan2(rect.height, rect.width);
	const tanTheta = Math.tan(theta);
	let region;

	if ((theta > -rectAtan) && (theta <= rectAtan)) {
		region = 1;
	} else if ((theta > rectAtan) && (theta <= (PI - rectAtan))) {
		region = 2;
	} else if ((theta > (PI - rectAtan)) || (theta <= -(PI - rectAtan))) {
		region = 3;
	} else {
		region = 4;
	}

	const edgePoint = rect.center.clone();
	let xFactor = 1;
	let yFactor = 1;

	switch (region) {
		case 1: yFactor = -1; break;
		case 2: yFactor = -1; break;
		case 3: xFactor = -1; break;
		case 4: xFactor = -1; break;
	}

	if ((region === 1) || (region === 3)) {
		edgePoint.x += xFactor * (rect.width / 2);
		edgePoint.y += yFactor * (rect.width / 2) * tanTheta;
	} else {
		edgePoint.x += xFactor * (rect.height / (2 * tanTheta));
		edgePoint.y += yFactor * (rect.height /  2);
	}

	return edgePoint;
}

/**
 * Rounds a value to closest set of numbers in a predetermined array
 */

function roundClosest(roundNumbers: number[], value: number) {
	return roundNumbers.reduce((prev, curr) => {
		return (Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev);
	});
}

/**
 * Converts slope (height divided by width) to angle (degrees)
 */

function slopeToAngle(slope: number) {
	return radiansToDegrees(Math.atan(slope));
}

/**
 * Converts radians to degrees
 */

function radiansToDegrees(radians: number) {
	return radians * (180 / PI);
}


text:
package org.jboss.hal.testsuite.fragment.finder;

import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.findby.ByJQuery;
import org.jboss.arquillian.graphene.fragment.Root;
import org.jboss.hal.resources.CSS;
import org.jboss.hal.testsuite.Console;
import org.jboss.hal.testsuite.page.runtime.TopologyPage;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import static org.jboss.arquillian.graphene.Graphene.waitGui;

/** Fragment for domain topology preview. Use {@link TopologyPage#navigateToTopologyFragment()} to get an instance.*/
public class TopologyPreviewFragment {

    @Drone private WebDriver browser;
    @Root private WebElement root;
    @Inject private Console console;

    public boolean containsConnectedHostNamed(String hostName) {
        By selector = ByJQuery.selector("[data-host='" + hostName + "'] a:contains('" + hostName + "')");
        return isPresent(selector);
    }

    public boolean containsDisconnectedHostNamed(String hostName) {
        By selector = ByJQuery.selector("[data-host='" + hostName + "'] span." + CSS.disconnected + ":contains('" + hostName + "')");
        return isPresent(selector);
    }

    private boolean isPresent(By selector) {
        try {
            waitGui().until().element(root, selector).is().present();
        } catch (TimeoutException e) {
            return false;
        }
        return true;
    }

}


text:
@interface EaseStartView ()
@property (strong, nonatomic) UIImageView *bgImageView, *logoIconView;
@property (strong, nonatomic) UILabel *descriptionStrLabel;
@end

@implementation EaseStartView

+ (instancetype)startView{
    UIImage *logoIcon = [UIImage imageNamed:@"logo_coding_top"];
    StartImage *st = [[StartImagesManager shareManager] randomImage];
    return [[self alloc] initWithBgImage:st.image logoIcon:logoIcon descriptionStr:st.descriptionStr];
}

- (instancetype)initWithBgImage:(UIImage *)bgImage logoIcon:(UIImage *)logoIcon descriptionStr:(NSString *)descriptionStr{
    self = [super initWithFrame:kScreen_Bounds];
    if (self) {
        //add custom code
        UIColor *blackColor = [UIColor blackColor];
        self.backgroundColor = blackColor;

        _bgImageView = [[UIImageView alloc] initWithFrame:kScreen_Bounds];
        _bgImageView.contentMode = UIViewContentModeScaleAspectFill;
        _bgImageView.alpha = 0.0;
        [self addSubview:_bgImageView];
        if (![NSDate isDuringMidAutumn]) {
            [self addGradientLayerWithColors:@[(id)[blackColor colorWithAlphaComponent:0.4].CGColor, (id)[blackColor colorWithAlphaComponent:0.0].CGColor] locations:nil startPoint:CGPointMake(0.5, 0.0) endPoint:CGPointMake(0.5, 0.4)];
        }

        _logoIconView = [[UIImageView alloc] init];
        _logoIconView.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:_logoIconView];
        _descriptionStrLabel = [[UILabel alloc] init];
        _descriptionStrLabel.font = [UIFont systemFontOfSize:10];
        _descriptionStrLabel.textColor = [UIColor colorWithWhite:1.0 alpha:0.5];
        _descriptionStrLabel.textAlignment = NSTextAlignmentCenter;
        _descriptionStrLabel.alpha = 0.0;
        [self addSubview:_descriptionStrLabel];

        [_descriptionStrLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(@[self, _logoIconView]);
            make.height.mas_equalTo(10);
            make.bottom.equalTo(self.mas_bottom).offset(-15);
            make.left.equalTo(self.mas_left).offset(20);
            make.right.equalTo(self.mas_right).offset(-20);
        }];

        [_logoIconView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.top.mas_equalTo(kScreen_Height/7);
            make.width.mas_equalTo(kScreen_Width *2/3);
            make.height.mas_equalTo(kScreen_Width/4 *2/3);
        }];

        [self configWithBgImage:bgImage logoIcon:logoIcon descriptionStr:descriptionStr];
    }
    return self;
}

- (void)configWithBgImage:(UIImage *)bgImage logoIcon:(UIImage *)logoIcon descriptionStr:(NSString *)descriptionStr{
    bgImage = [bgImage scaleToSize:[_bgImageView doubleSizeOfFrame] usingMode:NYXResizeModeAspectFill];
    self.bgImageView.image = bgImage;
    self.logoIconView.image = logoIcon;
    self.descriptionStrLabel.text = descriptionStr;
    [self updateConstraintsIfNeeded];
}

- (void)startAnimationWithCompletionBlock:(void(^)(EaseStartView *easeStartView))completionHandler{
    [kKeyWindow addSubview:self];
    [kKeyWindow bringSubviewToFront:self];
    _bgImageView.alpha = 0.0;
    _descriptionStrLabel.alpha = 0.0;

    @weakify(self);
    [UIView animateWithDuration:2.0 animations:^{
        @strongify(self);
        self.bgImageView.alpha = 1.0;
        self.descriptionStrLabel.alpha = 1.0;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.6 delay:0.3 options:UIViewAnimationOptionCurveEaseIn animations:^{
            @strongify(self);
            [self setX:-kScreen_Width];
        } completion:^(BOOL finished) {
            @strongify(self);
            [self removeFromSuperview];
            if (completionHandler) {
                completionHandler(self);
            }
        }];
    }];
}

@end


text:
package net.coderbee.rpc.core.registry.support;

import io.netty.util.internal.ConcurrentSet;
import net.coderbee.rpc.core.URL;
import net.coderbee.rpc.core.registry.NotifyListener;
import net.coderbee.rpc.core.registry.Registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Set;

/**
 * 抽象的注册中心,主要用于记录日志。具体实现由子类提供。
 *
 * @author coderbee on 2017/6/24.
 */
public abstract class AbstractRegistry implements Registry {
	protected static Logger logger = LoggerFactory.getLogger(AbstractRegistry.class);

	protected URL registryUrl;

	protected Set<URL> registedUrls = new ConcurrentSet<>();

	public AbstractRegistry(URL registryUrl) {
		this.registryUrl = registryUrl;
	}

	@Override
	public void register(URL url) {
		if (url == null) {
			logger.warn("url is null");
			return;
		}
		logger.info("register url({}) in register({})", url, registryUrl);

		doRegister(url);
		registedUrls.add(url);
	}

	@Override
	public void unregister(URL url) {
		if (url == null) {
			logger.warn("url is null");
			return;
		}
		logger.info("unregister url({}) in register({})", url, registryUrl);

		doUnregister(url);
		registedUrls.remove(url);
	}

	@Override
	public void subscribe(URL url, NotifyListener listener) {
		if (url == null || listener == null) {
			logger.warn("url or listener is null");
			return;
		}
		logger.info("listener({}) subscribe url({}) in register({})", listener, url, registryUrl);

		doSubscribe(url, listener);
	}

	@Override
	public void unsubscribe(URL url, NotifyListener listener) {
		if (url == null || listener == null) {
			logger.warn("url or listener is null");
			return;
		}
		logger.info("[{}] listener will unsubscribe url({}) in register({})", listener, url, registryUrl);

		doUnsubscribe(url, listener);
	}

	@Override
	public URL getUrl() {
		return registryUrl;
	}

	@Override
	public List<URL> availableServiceUrls() {
		return null;
	}

	@Override
	public List<URL> discover(URL url) {
		return null;
	}

	protected abstract void doRegister(URL url);

	protected abstract void doUnregister(URL url);

	protected abstract void doSubscribe(URL url, NotifyListener listener);

	protected abstract void doUnsubscribe(URL url, NotifyListener listener);

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 资源数据访问映射 -->
<mapper namespace="com.saituo.order.dao.account.MenuDao" >

    <select id="getChildren" resultType="hashmap">
        SELECT
          id AS "id",
          icon AS "icon",
          name AS "name",
          permission AS "permission",
          remark AS "remark",
          sort AS "sort",
          type AS "type",
          value AS "value",
          parent_id AS "parent_id"
        FROM
          sys_menu
        WHERE
          parent_id = #{id}
    </select>

    <select id="getAll" resultType="hashmap">
        SELECT
          id AS "id",
          parent_id AS "parent_id",
          icon AS "icon",
          name AS "name",
          permission AS "permission",
          sort AS "sort",
          remarks AS "remark",
          is_show AS "isShow",
          href AS "value",
          type AS "type"
        FROM
          sys_menu
        WHERE module = 2
        AND del_flag = 0
        <if test="ignore != null and ignore.length > 0">
            AND id NOT IN
            <foreach collection="ignore" item="id" index="index" open="(" separator="," close=")" >
                #{id}
            </foreach>
        </if>
    </select>

    <select id="count" resultType="long">
        SELECT
          COUNT(id)
        FROM
          sys_menu
    </select>

    <select id="getUserMenus" resultType="hashmap">
      SELECT
	    r.id AS "id",
	    r.icon AS "icon",
	    r.name AS "name",
	    r.permission AS "permission",
	    r.sort AS "sort",
	    r.is_show AS "isShow",
	    r.href AS "value",
	    r.type AS "type",
	    r.parent_id AS "parent_id"
      FROM
	    sys_menu r
      LEFT JOIN
	    sys_role_menu gr ON gr.menu_id = r.id
      LEFT JOIN
	    sys_role g ON gr.role_id = g.id
      LEFT JOIN
	    sys_user_role gu ON gu.role_id = g.id
      LEFT JOIN
	    sys_user u ON gu.user_id = u.id
      WHERE
	    u.id = #{userId}
	  AND
	  	r.module = 2
	  AND
	  	r.is_show = 1
	  AND
	  	r.del_flag = 0
	  GROUP BY
	  	r.id
      ORDER BY
        r.sort
    </select>

</mapper>


text:
void* qtc_QTreeView();
void* qtc_QTreeView1(void*);
int qtc_QTreeView_allColumnsShowFocus(void*);
int qtc_QTreeView_autoExpandDelay(void*);
void qtc_QTreeView_collapse(void*,void*);
void qtc_QTreeView_collapseAll(void*);
int qtc_QTreeView_columnAt(void*,int);
void qtc_QTreeView_columnCountChanged(void*,int,int);
void qtc_QTreeView_columnMoved(void*);
void qtc_QTreeView_columnResized(void*,int,int,int);
int qtc_QTreeView_columnViewportPosition(void*,int);
int qtc_QTreeView_columnWidth(void*,int);
void qtc_QTreeView_currentChanged(void*,void*,void*);
void qtc_QTreeView_dataChanged(void*,void*,void*);
void qtc_QTreeView_doItemsLayout(void*);
void qtc_QTreeView_dragMoveEvent(void*,void*);
void qtc_QTreeView_drawBranches(void*,void*,void*,void*);
void qtc_QTreeView_drawBranches_qth(void*,void*, int, int, int, int,void*);
void qtc_QTreeView_drawRow(void*,void*,void*,void*);
void qtc_QTreeView_drawTree(void*,void*,void*);
void qtc_QTreeView_expand(void*,void*);
void qtc_QTreeView_expandAll(void*);
void qtc_QTreeView_expandToDepth(void*,int);
void* qtc_QTreeView_header(void*);
void qtc_QTreeView_hideColumn(void*,int);
int qtc_QTreeView_horizontalOffset(void*);
void qtc_QTreeView_horizontalScrollbarAction(void*,int);
int qtc_QTreeView_indentation(void*);
void* qtc_QTreeView_indexAbove(void*,void*);
void* qtc_QTreeView_indexAt(void*,void*);
void* qtc_QTreeView_indexAt_qth(void*, int,int);
void* qtc_QTreeView_indexBelow(void*,void*);
int qtc_QTreeView_indexRowSizeHint(void*,void*);
int qtc_QTreeView_isAnimated(void*);
int qtc_QTreeView_isColumnHidden(void*,int);
int qtc_QTreeView_isExpanded(void*,void*);
int qtc_QTreeView_isFirstColumnSpanned(void*,int,void*);
int qtc_QTreeView_isIndexHidden(void*,void*);
int qtc_QTreeView_isRowHidden(void*,int,void*);
int qtc_QTreeView_isSortingEnabled(void*);
int qtc_QTreeView_itemsExpandable(void*);
void qtc_QTreeView_keyPressEvent(void*,void*);
void qtc_QTreeView_keyboardSearch(void*,void*);
void qtc_QTreeView_mouseDoubleClickEvent(void*,void*);
void qtc_QTreeView_mouseMoveEvent(void*,void*);
void qtc_QTreeView_mousePressEvent(void*,void*);
void qtc_QTreeView_mouseReleaseEvent(void*,void*);
void* qtc_QTreeView_moveCursor(void*,long,long);
void qtc_QTreeView_paintEvent(void*,void*);
void qtc_QTreeView_reexpand(void*);
void qtc_QTreeView_reset(void*);
void qtc_QTreeView_resizeColumnToContents(void*,int);
int qtc_QTreeView_rootIsDecorated(void*);
int qtc_QTreeView_rowHeight(void*,void*);
void qtc_QTreeView_rowsAboutToBeRemoved(void*,void*,int,int);
void qtc_QTreeView_rowsInserted(void*,void*,int,int);
void qtc_QTreeView_rowsRemoved(void*,void*,int,int);
void qtc_QTreeView_scrollContentsBy(void*,int,int);
void qtc_QTreeView_scrollTo(void*,void*);
void qtc_QTreeView_scrollTo1(void*,void*,long);
void qtc_QTreeView_selectAll(void*);
void qtc_QTreeView_selectionChanged(void*,void*,void*);
void qtc_QTreeView_setAllColumnsShowFocus(void*,int);
void qtc_QTreeView_setAnimated(void*,int);
void qtc_QTreeView_setAutoExpandDelay(void*,int);
void qtc_QTreeView_setColumnHidden(void*,int,int);
void qtc_QTreeView_setColumnWidth(void*,int,int);
void qtc_QTreeView_setExpanded(void*,void*,int);
void qtc_QTreeView_setFirstColumnSpanned(void*,int,void*,int);
void qtc_QTreeView_setHeader(void*,void*);
void qtc_QTreeView_setIndentation(void*,int);
void qtc_QTreeView_setItemsExpandable(void*,int);
void qtc_QTreeView_setModel(void*,void*);
void qtc_QTreeView_setRootIndex(void*,void*);
void qtc_QTreeView_setRootIsDecorated(void*,int);
void qtc_QTreeView_setRowHidden(void*,int,void*,int);
void qtc_QTreeView_setSelection(void*,void*,long);
void qtc_QTreeView_setSelection_qth(void*, int, int, int, int,long);
void qtc_QTreeView_setSelectionModel(void*,void*);
void qtc_QTreeView_setSortingEnabled(void*,int);
void qtc_QTreeView_setUniformRowHeights(void*,int);
void qtc_QTreeView_setWordWrap(void*,int);
void qtc_QTreeView_showColumn(void*,int);
int qtc_QTreeView_sizeHintForColumn(void*,int);
void qtc_QTreeView_sortByColumn(void*,int);
void qtc_QTreeView_sortByColumn1(void*,int,long);
void qtc_QTreeView_timerEvent(void*,void*);
int qtc_QTreeView_uniformRowHeights(void*);
void qtc_QTreeView_updateGeometries(void*);
int qtc_QTreeView_verticalOffset(void*);
int qtc_QTreeView_viewportEvent(void*,void*);
void* qtc_QTreeView_visualRect(void*,void*);
void* qtc_QTreeView_visualRect_qth(void*,void*,int*,int*,int*,int*);
void* qtc_QTreeView_visualRegionForSelection(void*,void*);
int qtc_QTreeView_wordWrap(void*);
void qtc_QTreeView_finalizer(void*);
void* qtc_QTreeView_getFinalizer();
void qtc_QTreeView_delete(void*);
void qtc_QTreeView_deleteLater(void*);
void qtc_QTreeView_closeEditor(void*,void*,long);
void qtc_QTreeView_commitData(void*,void*);
void* qtc_QTreeView_dirtyRegionOffset(void*);
void* qtc_QTreeView_dirtyRegionOffset_qth(void*,int*,int*);
void qtc_QTreeView_doAutoScroll(void*);
void qtc_QTreeView_dragEnterEvent(void*,void*);
void qtc_QTreeView_dragLeaveEvent(void*,void*);
void qtc_QTreeView_dropEvent(void*,void*);
long qtc_QTreeView_dropIndicatorPosition(void*);
int qtc_QTreeView_edit(void*,void*,long,void*);
void qtc_QTreeView_editorDestroyed(void*,void*);
int qtc_QTreeView_event(void*,void*);
void qtc_QTreeView_executeDelayedItemsLayout(void*);
void qtc_QTreeView_focusInEvent(void*,void*);
int qtc_QTreeView_focusNextPrevChild(void*,int);
void qtc_QTreeView_focusOutEvent(void*,void*);
void qtc_QTreeView_horizontalScrollbarValueChanged(void*,int);
int qtc_QTreeView_horizontalStepsPerItem(void*);
void qtc_QTreeView_inputMethodEvent(void*,void*);
void* qtc_QTreeView_inputMethodQuery(void*,long);
void qtc_QTreeView_resizeEvent(void*,void*);
void qtc_QTreeView_scheduleDelayedItemsLayout(void*);
void qtc_QTreeView_scrollDirtyRegion(void*,int,int);
long qtc_QTreeView_selectionCommand(void*,void*);
long qtc_QTreeView_selectionCommand1(void*,void*,void*);
void qtc_QTreeView_setDirtyRegion(void*,void*);
void qtc_QTreeView_setHorizontalStepsPerItem(void*,int);
void qtc_QTreeView_setState(void*,long);
void qtc_QTreeView_setVerticalStepsPerItem(void*,int);
int qtc_QTreeView_sizeHintForRow(void*,int);
void qtc_QTreeView_startAutoScroll(void*);
void qtc_QTreeView_startDrag(void*,long);
long qtc_QTreeView_state(void*);
void qtc_QTreeView_stopAutoScroll(void*);
void qtc_QTreeView_updateEditorData(void*);
void qtc_QTreeView_updateEditorGeometries(void*);
void qtc_QTreeView_verticalScrollbarAction(void*,int);
void qtc_QTreeView_verticalScrollbarValueChanged(void*,int);
int qtc_QTreeView_verticalStepsPerItem(void*);
void* qtc_QTreeView_viewOptions(void*);
void qtc_QTreeView_contextMenuEvent(void*,void*);
void* qtc_QTreeView_minimumSizeHint(void*);
void* qtc_QTreeView_minimumSizeHint_qth(void*,int*,int*);
void qtc_QTreeView_setViewportMargins(void*,int,int,int,int);
void qtc_QTreeView_setupViewport(void*,void*);
void* qtc_QTreeView_sizeHint(void*);
void* qtc_QTreeView_sizeHint_qth(void*,int*,int*);
void qtc_QTreeView_wheelEvent(void*,void*);
void qtc_QTreeView_changeEvent(void*,void*);
void qtc_QTreeView_drawFrame(void*,void*);
void qtc_QTreeView_actionEvent(void*,void*);
void qtc_QTreeView_addAction(void*,void*);
void qtc_QTreeView_closeEvent(void*,void*);
void qtc_QTreeView_create(void*);
void qtc_QTreeView_create1(void*,void*);
void qtc_QTreeView_create2(void*,void*,int);
void qtc_QTreeView_create3(void*,void*,int,int);
void qtc_QTreeView_destroy(void*);
void qtc_QTreeView_destroy1(void*,int);
void qtc_QTreeView_destroy2(void*,int,int);
int qtc_QTreeView_devType(void*);
void qtc_QTreeView_enabledChange(void*,int);
void qtc_QTreeView_enterEvent(void*,void*);
int qtc_QTreeView_focusNextChild(void*);
int qtc_QTreeView_focusPreviousChild(void*);
void qtc_QTreeView_fontChange(void*,void*);
int qtc_QTreeView_heightForWidth(void*,int);
void qtc_QTreeView_hideEvent(void*,void*);
void qtc_QTreeView_keyReleaseEvent(void*,void*);
void qtc_QTreeView_languageChange(void*);
void qtc_QTreeView_leaveEvent(void*,void*);
int qtc_QTreeView_metric(void*,long);
void qtc_QTreeView_move(void*,void*);
void qtc_QTreeView_move_qth(void*);
void qtc_QTreeView_move1(void*,int,int);
void qtc_QTreeView_moveEvent(void*,void*);
void* qtc_QTreeView_paintEngine(void*);
void qtc_QTreeView_paletteChange(void*,void*);
void qtc_QTreeView_repaint(void*);
void qtc_QTreeView_repaint1(void*,void*);
void qtc_QTreeView_repaint2(void*,int,int,int,int);
void qtc_QTreeView_resetInputContext(void*);
void qtc_QTreeView_resize(void*,void*);
void qtc_QTreeView_resize_qth(void*);
void qtc_QTreeView_resize1(void*,int,int);
void qtc_QTreeView_setGeometry(void*,void*);
void qtc_QTreeView_setGeometry_qth(void*);
void qtc_QTreeView_setGeometry1(void*,int,int,int,int);
void qtc_QTreeView_setMouseTracking(void*,int);
void qtc_QTreeView_setVisible(void*,int);
void qtc_QTreeView_showEvent(void*,void*);
void qtc_QTreeView_tabletEvent(void*,void*);
void qtc_QTreeView_updateMicroFocus(void*);
void qtc_QTreeView_windowActivationChange(void*,int);
void qtc_QTreeView_childEvent(void*,void*);
void qtc_QTreeView_connectNotify(void*,void*);
void qtc_QTreeView_customEvent(void*,void*);
void qtc_QTreeView_disconnectNotify(void*,void*);
int qtc_QTreeView_eventFilter(void*,void*,void*);
int qtc_QTreeView_receivers(void*,void*);
void* qtc_QTreeView_sender(void*);


text:
/**
 * Base control component.
 * Similar to goog.ui.Control. Foundation for buttons, checkboxes, etc.
 * @project UI controls.
 * @author Anna Agte
 * @version 1.0
 */

goog.provide('DD.ui.controls.Control');

goog.require('DD.ui.controls');
goog.require('DD.ui.Item');
goog.require('DD.ui.controls.renderer.Control');
goog.require('DD.ui.Component');
goog.require('goog.ui.registry');

// ------------------------------
// Constructor
// ------------------------------

/**
 * @param {Object=} options Component's properties and event handlers.
 *    See other possible options in {@link DD.ui.Component}.
 * @param {string=} options.caption Component's caption.
 * @param {string=} options.icon Image url refering to an image or cssClass.
 *    Ignored if imageIndex is set.
 * @param {number=} options.imageIndex "Index of an image in a sprite sheet".
 *    Css class suffix. Creates class like "DD-sprite-index-<imageIndex>".
 * @param {string=} options.hint Element's popup hint.
 * @param {boolean=} options.wrap If TRUE, component will break the row
 *    in a parent toolbar. Useless if component is used without a toolbar.
 * @param {number=} options.priority Component's priority in a toolbar.
 *    If priority>=0 component's element will be collapsed by toolbar.
 * @param {string=} options.name Component's name. Used mostly by radiobuttons.
 * @param {*=} options.value Component's value.
 *    Used mostly by TextEdit and Spinner/Slider.
 * @param {eventCallback=} options.click Triggers when user clicks
 *    on the component's element.
 *    Handles event DD.ui.EventType.ACTION.
 * @param {eventCallback=} options.change Triggers when
 *    the component's value is changed.
 *    Handles event DD.ui.EventType.VALUE_CHANGED.
 * @constructor
 * @extends DD.ui.Item
 */
DD.ui.controls.Control = function(options) {
  DD.ui.Item.call(this, options);
};
goog.inherits(DD.ui.controls.Control, DD.ui.Item);
goog.ui.registry.setDefaultRenderer(DD.ui.controls.Control, DD.ui.controls.renderer.Control);

// ------------------------------
// Prototype
// ------------------------------

goog.scope(function() {

/** @alias DD.ui.controls.Control.prototype */
var prototype = DD.ui.controls.Control.prototype;
var superClass_ = DD.ui.controls.Control.superClass_;
var ACTION = DD.ui.EventType.ACTION;
var VALUE_CHANGED = DD.ui.EventType.VALUE_CHANGED;

// ------------------------------
// Properties
// ------------------------------

/**
 * Reference to an action. Action implements pattern COMMAND (ACTION).
 * @type {?DD.Action}
 * @private
 */
prototype.action_ = null;

/**
 * Native control name.
 * @type {string}
 * @private
 */
prototype.name_ = '';

/**
 * Hidden only if no empty space left. Visible if there is enough space.
 * @type {boolean}
 * @private
 */
prototype.hidden_ = false;

/**
 * The hint like an HTML title.
 * @type {string}
 * @private
 */
prototype.hint_ = '';

/**
 * Image sprite index.
 * @type {number}
 * @private
 */
prototype.imageIndex_ = -1;

/**
 * Priority to resize.
 * @type {number}
 * @private
 */
prototype.priority_ = 0;

/**
 * If TRUE the control interrupts the current row of controls.
 * @type {boolean}
 * @private
 */
prototype.wrap_ = false;

// ------------------------------
// Methods
// ------------------------------

/**
 * @inheritdoc
 */
prototype.assign = function(options) {

  if (!goog.isObject(options))
    return;

  superClass_.assign.call(this, options);

  if (goog.isNumber(options.imageIndex))
    this.setImageIndex(options.imageIndex);

  if (goog.isString(options.hint))
    this.setHint(options.hint);

  if (goog.isBoolean(options.wrap))
    this.setWrap(options.wrap);

  if (goog.isNumber(options.priority))
    this.setPriority(options.priority);

  if (goog.isString(options.name))
    this.setName(options.name);

  if (goog.isDefAndNotNull(options.value))
    this.setValue(options.value);

  if (goog.isFunction(options.click))
    this.listen(ACTION, options.click);

  if (goog.isFunction(options.change))
    this.listen(VALUE_CHANGED, options.change);
};

/**
 * @inheritdoc
 */
prototype.resize = function() {

  if (!this.isInDocument())
    return;

  var renderer = this.getRenderer();
  if (renderer.resize)
    renderer.resize(this);
};

/**
 * @param {?DD.Action} action
 * @public
 */
prototype.setAction = function(action) {
  this.action_ = action;
};

/**
 * @param {?DD.Action} action
 * @public
 */
prototype.getAction = function() {
  return this.action_;
};

/**
 * Sets the name.
 * @param {string} name
 * @public
 */
prototype.setName = function(name) {

  if (name === this.name_)
    return;

  this.name_ = name;

  var renderer = this.getRenderer();
  if (renderer.setName)
    renderer.setName(this, this.name_);
  this.changed();
};

/**
 * Gets the name.
 * @return {string}
 * @public
 */
prototype.getName = function() {
  return this.name_;
};

/**
 * Sets the "canFocus".
 * @param {boolean} canFocus
 * @public
 */
prototype.setCanFocus = function(canFocus) {
  this.setSupportedState(DD.ui.Component.State.FOCUSED, canFocus);
};

/**
 * Checks if the component can be focused.
 * @return {boolean}
 * @public
 */
prototype.canFocus = function() {
  return this.isSupportedState(DD.ui.Component.State.FOCUSED);
};

/**
 * Makes the component hidden.
 * No CHANGE event! setHidden is used during resize by renderers only.
 * @param {boolean} hidden
 * @public
 */
prototype.setHidden = function(hidden) {

  hidden = !!hidden;
  if (hidden === this.hidden_)
    return;

  this.hidden_ = hidden;

  var renderer = this.getRenderer();
  if (renderer.setHidden)
    renderer.setHidden(this, hidden);
};

/**
 * Checks if the component is hidden.
 * @return {boolean}
 * @public
 */
prototype.isHidden = function() {
  return this.hidden_;
};

/**
 * Sets the hint.
 * @param {string} hint
 * @public
 */
prototype.setHint = function(hint) {

  if (hint === this.hint_)
    return;

  this.hint_ = hint;

  var renderer = this.getRenderer();
  if (renderer.setHint)
    renderer.setHint(this, this.hint_);
  this.changed();
}

/**
 * Gets the hint.
 * @return {string}
 * @public
 */
prototype.getHint = function() {
  return this.hint_;
};

/**
 * @param {number} index
 * @public
 * @see {DD.ui.Item.prototype.setIcon}
 */
prototype.setImageIndex = function (index) {

  index = +index;
  if (index === this.imageIndex_)
    return;

  index === -1
    ? this.setIcon('')
    : this.setIcon('DD-sprite-index-' + index);

  this.imageIndex_ = index;
  this.changed();
};

/**
 * @return {number}
 * @public
 */
prototype.getImageIndex = function() {
  return this.imageIndex_;
};

/**
 * Sets the priority.
 * @param {number} priority
 * @public
 */
prototype.setPriority = function(priority) {

  priority = +priority;
  if (priority === this.priority_)
    return;

  this.priority_ = priority;
  this.changed();
};

/**
 * Gets the priority.
 * @return {number}
 * @public
 */
prototype.getPriority = function() {
    return this.priority_;
};

/**
 * Makes the control last in the row if wrap = TRUE.
 * @param {boolean} wrap
 * @public
 */
prototype.setWrap = function(wrap) {

  wrap = !!wrap;
  if (wrap === this.wrap_)
    return;

  this.wrap_ = !!wrap;
  this.changed();
};

/**
 * Checks if the control is breaking row.
 * @return {boolean}
 * @public
 */
prototype.isWrap = function() {
  return this.wrap_;
};

/**
 * Click, keydown and touch emulation.
 * Facade for method "activate".
 * Айрат просил метод именно с таким названием.
 * Так что просто сделаем фасад для уже существующего метода.
 * @return {boolean} FALSE if the click was stopped.
 * @public
 */
prototype.click = function() {
  return this.activate();
};

}); // goog.scope


text:
using System;
using Foundation;
using UIKit;

namespace BeerDrinkin.iOS
{
    partial class MyBeersTableViewCell : SWTableViewCell.SWTableViewCell
    {
        public MyBeersTableViewCell(IntPtr handle)
            : base(handle)
        {
        }

        public MyBeersTableViewCell(NSString cellId)
            : base(UITableViewCellStyle.Default, cellId)
        {
        }

        public string Name
        {
            get { return lblName.Text; }
            set { lblName.Text = value; }
        }

        public string Brewery
        {
            get { return lblBrewery.Text; }
            set { lblBrewery.Text = value; }
        }

        public string NumberOfServings
        {
            get { return lblNumberOfServings.Text; }
            set { lblNumberOfServings.Text = value; }
        }

        public UIImageView Image
        {
            get { return imgLabel; }
            set { imgLabel = value; }
        }

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

            imgLabel.Layer.CornerRadius = imgLabel.Frame.Width / 2;
            imgLabel.Layer.MasksToBounds = true;

            sideColor.Alpha = 0f;
        }
    }
}