text:
package breeze.linalg

import breeze.generic._
import breeze.linalg.Axis.{_0, _1}
import breeze.linalg.operators._
import breeze.linalg.support.CanTraverseValues.ValuesVisitor
import breeze.linalg.support._
import breeze.math._
import breeze.storage.Zero
import breeze.storage.Zero._
import breeze.util.{ArrayUtil, ReflectionUtil}
import breeze.macros._

import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag
import scala.{specialized => spec}
import breeze.macros._

/**
 * A DenseMatrix is a matrix with all elements found in an array. It is column major unless isTranspose is true,
 * It is designed to be fast: Double- (and potentially Float-)valued DenseMatrices
 * can be used with blas, and support operations to that effect.
 *
 * @author dlwh
 * @param rows number of rows
 * @param cols number of cols
 * @param data The underlying data.
 *             Column-major unless isTranpose is true.
 *             Mutate at your own risk.
 *             Note that this matrix may be a view of the data.
 *             Use linearIndex(r,c) to calculate indices.
 * @param offset starting point into array
 * @param majorStride distance separating columns (or rows, for isTranspose). should have absolute value >= rows (or cols, for isTranspose)
 * @param isTranspose if true, then the matrix is considered to be "transposed" (that is, row major)
 */
@SerialVersionUID(1L)
final class DenseMatrix[@spec(Double, Int, Float, Long) V](
    val rows: Int,
    val cols: Int,
    val data: Array[V],
    val offset: Int,
    val majorStride: Int,
    val isTranspose: Boolean = false)
    extends Matrix[V]
    with MatrixLike[V, DenseMatrix[V]]
    with Serializable {

  /** Creates a matrix with the specified data array, rows, and columns. */
  def this(rows: Int, cols: Int)(implicit man: ClassTag[V]) = this(rows, cols, new Array[V](rows * cols), 0, rows)

  /** Creates a matrix with the specified data array, rows, and columns. Data must be column major */
  def this(rows: Int, cols: Int, data: Array[V], offset: Int) = this(rows, cols, data, offset, rows)

  /** Creates a matrix with the specified data array, rows, and columns. Data must be column major */
  def this(rows: Int, cols: Int, data: Array[V]) = this(rows, cols, data, 0, rows)

  /** Creates a matrix with the specified data array and rows. columns inferred automatically */
  def this(rows: Int, data: Array[V], offset: Int) =
    this(rows, { assert(data.length % rows == 0); data.length / rows }, data, offset)

  if (isTranspose && (math.abs(majorStride) < cols) && majorStride != 0) {
    throw new IndexOutOfBoundsException(
      "MajorStride == " + majorStride + " is smaller than cols == " + cols + ", which is impossible")
  }
  if (!isTranspose && (math.abs(majorStride) < rows) && majorStride != 0) {
    throw new IndexOutOfBoundsException(
      "MajorStride == " + majorStride + " is smaller than rows == " + rows + ", which is impossible")
  }
  if (rows < 0) { throw new IndexOutOfBoundsException("Rows must be larger than zero. It was " + rows) }
  if (cols < 0) { throw new IndexOutOfBoundsException("Cols must be larger than zero. It was " + cols) }
  if (offset < 0) { throw new IndexOutOfBoundsException("Offset must be larger than zero. It was " + offset) }
  if (majorStride > 0) {
    if (data.length < linearIndex(rows - 1, cols - 1)) {
      throw new IndexOutOfBoundsException(
        "Storage array has size " + data.size + " but indices can grow as large as " + linearIndex(rows - 1, cols - 1))
    }
  } else if (majorStride < 0) {
    if (data.length < linearIndex(rows - 1, 0)) {
      throw new IndexOutOfBoundsException(
        "Storage array has size " + data.size + " but indices can grow as large as " + linearIndex(rows - 1, cols - 1))
    }
    if (linearIndex(0, cols - 1) < 0) {
      throw new IndexOutOfBoundsException(
        "Storage array has negative stride " + majorStride + " and offset " + offset + " which can result in negative indices.")
    }
  }

  def apply(row: Int, col: Int) = {
    if (row < -rows || row >= rows)
      throw new IndexOutOfBoundsException(
        s"${(row, col)} not in [-$rows,$rows) x [-$cols,$cols)")
    if (col < -cols || col >= cols)
      throw new IndexOutOfBoundsException(
        s"${(row, col)} not in [-$rows,$rows) x [-$cols,$cols)")
    val trueRow = if (row < 0) row + rows else row
    val trueCol = if (col < 0) col + cols else col
    data(linearIndex(trueRow, trueCol))
  }

  // don't delete
  DenseMatrix.init()

  /** Calculates the index into the data array for row and column */
  def linearIndex(row: Int, col: Int): Int = {
    if (isTranspose)
      offset + col + row * majorStride
    else
      offset + row + col * majorStride
  }

  def rowColumnFromLinearIndex(index: Int): (Int, Int) = {
    val r = (index - offset) % majorStride
    val c = (index - offset) / majorStride
    if (isTranspose) {
      (c, r)
    } else {
      (r, c)
    }
  }

  def update(row: Int, col: Int, v: V): Unit = {
    if (row < -rows || row >= rows)
      throw new IndexOutOfBoundsException(
        s"${(row, col)} not in [-$rows,$rows) x [-$cols,$cols)")
    if (col < -cols || col >= cols)
      throw new IndexOutOfBoundsException(
        s"${(row, col)} not in [-$rows,$rows) x [-$cols,$cols)")
    val trueRow = if (row < 0) row + rows else row
    val trueCol = if (col < 0) col + cols else col
    data(linearIndex(trueRow, trueCol)) = v
  }

  // <editor-fold defaultstate="collapsed" desc=" conversions (toArray, toDenseVector) ">

  /** Converts this matrix to a flat Array (column-major) */
  def toArray: Array[V] = {
    implicit val man: ClassTag[V] = ReflectionUtil.elemClassTagFromArray(data)
    if (isContiguous && !isTranspose) {
      ArrayUtil.copyOfRange(data, offset, offset + size)
    } else {
      // TODO: consider using cache oblivious transpose here?
      val ret = new Array[V](rows * cols)
      cforRange2(0 until cols, 0 until rows) { (i,j) =>
        ret(i * rows + j) = data(linearIndex(j, i))
      }
      ret
    }
  }

  /** Converts this matrix to a DenseVector (column-major) */
  def toDenseVector: DenseVector[V] = DenseVector(toArray)

  // </editor-fold>

  /** Converts this matrix to a DenseVector (column-major)
   * If view = true (or View.Require), throws an exception if we cannot return a view. otherwise returns a view.
   * If view == false (or View.Copy) returns a copy
   * If view == View.Prefer (the default), returns a view if possible, otherwise returns a copy.
   *
   * Views are only possible (if(isTranspose) majorStride == cols else majorStride == rows) == true
   */
  def flatten(view: View = View.Prefer): DenseVector[V] = view match {
    case View.Require =>
      if (!canFlattenView)
        throw new UnsupportedOperationException("Cannot make a view of this matrix.")
      else
        DenseVector.create(data, offset, 1, rows * cols)
    case View.Copy =>
      toDenseVector
    case View.Prefer =>
      flatten(canFlattenView)
  }

  private def canFlattenView = !isTranspose && majorStride == rows
  private def canReshapeView = canFlattenView

  /** Reshapes this matrix to have the given number of rows and columns
   * If view = true (or View.Require), throws an exception if we cannot return a view. otherwise returns a view.
   * If view == false (or View.Copy) returns a copy
   * If view == View.Prefer (the default), returns a view if possible, otherwise returns a copy.
   *
   * Views are only possible if (!isTranspose && majorStride == rows)
   *
   * rows * cols must equal size, or cols < 0 && (size / rows * rows == size)
   * @param rows the number of rows
   * @param cols the number of columns, or -1 to auto determine based on size and rows
   */
  def reshape(rows: Int, cols: Int, view: View = View.Prefer): DenseMatrix[V] = {
    val _cols = cols //if(cols < 0) size / rows else cols
    require(
      rows * _cols == size,
      "Cannot reshape a (%d,%d) matrix to a (%d,%d) matrix!".format(this.rows, this.cols, rows, _cols))

    view match {
      case View.Require =>
        if (!canReshapeView)
          throw new UnsupportedOperationException("Cannot make a view of this matrix.")
        else
          new DenseMatrix(rows, _cols, data, offset, if (isTranspose) cols else rows, isTranspose)
      case View.Copy =>
        // calling copy directly gives a verify error. TODO: submit bug
        val result = new DenseMatrix(this.rows, this.cols, ArrayUtil.newArrayLike(data, size))
        result := this
        result.reshape(rows, _cols, View.Require)
      case View.Prefer =>
        reshape(rows, cols, canReshapeView)
    }
  }

  def repr: DenseMatrix[V] = this

  def activeIterator: Iterator[((Int, Int), V)] = iterator

  def activeValuesIterator: Iterator[V] = valuesIterator

  def activeKeysIterator: Iterator[(Int, Int)] = keysIterator

  def activeSize = data.length

  def valueAt(i: Int): V = data(i)
  def valueAt(row: Int, col: Int): V = apply(row, col)

  def indexAt(i: Int) = i

  def isActive(i: Int) = true
  def allVisitableIndicesActive = true

  override def toDenseMatrix(implicit cm: ClassTag[V], zero: Zero[V]): DenseMatrix[V] = {
    val result = DenseMatrix.create[V](rows, cols, new Array[V](size))
    result := this
    result
  }

  def copy: DenseMatrix[V] = {
    implicit val man: ClassTag[V] = ReflectionUtil.elemClassTagFromArray(data)
    val result = DenseMatrix.create[V](rows, cols, new Array[V](size))
    result := this
    result
  }

  private implicit def dontNeedZero[V]: Zero[V] = null.asInstanceOf[Zero[V]]

  def delete(row: Int, axis: Axis._0.type): DenseMatrix[V] = {
    implicit val man: ClassTag[V] = ReflectionUtil.elemClassTagFromArray(data)
    require(row >= 0 && row < rows, s"row $row is not in bounds: [0, $rows)")
    if (row == 0) this(1 until rows, ::).copy
    else if (row == rows - 1) this(0 until rows - 1, ::).copy
    else DenseMatrix.vertcat(this(0 until row, ::), this((row + 1) until rows, ::))
  }

  def delete(col: Int, axis: Axis._1.type): DenseMatrix[V] = {
    implicit val man: ClassTag[V] = ReflectionUtil.elemClassTagFromArray(data)
    require(col >= 0 && col < cols, s"col $col is not in bounds: [0, $cols)")
    if (col == 0) this(::, 1 until cols).copy
    else if (col == cols - 1) this(::, 0 until cols - 1).copy
    else DenseMatrix.horzcat(this(::, 0 until col), this(::, (col + 1) until cols))
  }

  def delete(rows: Seq[Int], axis: Axis._0.type): DenseMatrix[V] = {
    implicit val man: ClassTag[V] = ReflectionUtil.elemClassTagFromArray(data)
    if (rows.isEmpty) copy
    else if (rows.size == 1) delete(rows(0), axis)
    else {
      val sorted = rows.sorted
      require(sorted.head >= 0 && sorted.last < this.rows, s"row $rows are not in bounds: [0, ${this.rows})")
      var last = 0
      val matrices = breeze.collection.compat.arraySeqBuilder[DenseMatrix[V]]
      for (index <- sorted) {
        assert(index >= last)
        if (index != last) {
          matrices += this(last until index, ::)
        }
        last = index + 1
      }
      if (last != this.rows) {
        matrices += this(last until this.rows, ::)
      }
      DenseMatrix.vertcat(matrices.result(): _*)
    }
  }

  def delete(cols: Seq[Int], axis: Axis._1.type): DenseMatrix[V] = {
    implicit val man: ClassTag[V] = ReflectionUtil.elemClassTagFromArray(data)
    if (cols.isEmpty) this.copy
    else if (cols.size == 1) delete(cols(0), axis)
    else {
      val sorted = cols.sorted
      require(sorted.head >= 0 && sorted.last < this.cols, s"col $cols are not in bounds: [0, ${this.cols})")
      var last = 0
      val matrices = breeze.collection.compat.arraySeqBuilder[DenseMatrix[V]]
      for (index <- sorted) {
        assert(index >= last)
        if (index != last) {
          matrices += this(::, last until index)
        }
        last = index + 1
      }
      if (last != this.cols) {
        matrices += this(::, last until this.cols)
      }
      DenseMatrix.horzcat(matrices.result(): _*)
    }
  }

  private[linalg] def majorSize = if (isTranspose) rows else cols
  private[linalg] def minorSize = if (isTranspose) cols else rows
  private def footprint = majorSize * majorStride

  /** Returns true if this dense matrix takes up a contiguous segment of the array */
  def isContiguous: Boolean = majorSize == majorStride

  /** Returns true if this dense matrix overlaps any content with the other matrix */
  private[linalg] def overlaps(other: DenseMatrix[V]): Boolean = (this.data eq other.data) && {
    val astart = offset
    val aend = offset + footprint
    val bstart = other.offset
    val bend = other.offset + other.footprint
    Range(astart, aend).contains(bstart) ||
    Range(astart, aend).contains(bend) ||
    Range(bstart, bend).contains(astart) ||
    Range(bstart, bend).contains(aend)
  }

  private def checkIsSpecialized(): Unit = {
    if (data.isInstanceOf[Array[Double]] && getClass.getName() == "breeze.linalg.DenseMatrix")
      throw new Exception("...")
  }
  // uncomment to debug places where specialization fails
//  checkIsSpecialized()

}

object DenseMatrix extends MatrixConstructors[DenseMatrix] {

  /**
   * The standard way to create an empty matrix, size is rows * cols
   */
  def zeros[@spec(Double, Int, Float, Long) V: ClassTag: Zero](rows: Int, cols: Int): DenseMatrix[V] = {
    val data = new Array[V](rows * cols)
    if (implicitly[Zero[V]] != null && rows * cols != 0 && data(0) != implicitly[Zero[V]].zero)
      ArrayUtil.fill(data, 0, data.length, implicitly[Zero[V]].zero)
    DenseMatrix.create(rows, cols, data)
  }

  /**
   *
   * Creates a new DenseMatrix using the provided array (not making a copy!). In generic contexts, prefer to
   * use this (or the other create methd) instead of `new DenseMatrix[V](rows, cols, data)`, which in general
   * won't give specialized implementations.
   * @param rows
   * @param cols
   * @param data
   * @tparam V
   * @return
   */
  def create[@spec(Double, Int, Float, Long) V: Zero](rows: Int, cols: Int, data: Array[V]): DenseMatrix[V] = {
    create(rows, cols, data, 0, rows, isTranspose = false)
  }

  /**
   *
   * Creates a new DenseMatrix using the provided array (not making a copy!). In generic contexts, prefer to
   * use this (or the other create methd) instead of `new DenseMatrix[V](rows, cols, data)`, which in general
   * won't give specialized implementations.
   * @param rows
   * @param cols
   * @param data
   * @tparam V
   * @return
   */
  def create[@spec(Double, Int, Float, Long) V](
      rows: Int,
      cols: Int,
      data: Array[V],
      offset: Int,
      majorStride: Int,
      isTranspose: Boolean = false): DenseMatrix[V] = {
    (data: Any) match {
      case d: Array[Double] =>
        new DenseMatrix(rows, cols, d, offset, majorStride, isTranspose).asInstanceOf[DenseMatrix[V]]
      case d: Array[Float] =>
        new DenseMatrix(rows, cols, d, offset, majorStride, isTranspose).asInstanceOf[DenseMatrix[V]]
      case d: Array[Long] =>
        new DenseMatrix(rows, cols, d, offset, majorStride, isTranspose).asInstanceOf[DenseMatrix[V]]
      case d: Array[Int] =>
        new DenseMatrix(rows, cols, d, offset, majorStride, isTranspose).asInstanceOf[DenseMatrix[V]]
      case _ => new DenseMatrix(rows, cols, data, offset, majorStride, isTranspose)
    }
  }

  /**
   * Creates a matrix of all ones.
   * @param rows
   * @param cols
   * @tparam V
   * @return
   */
  override def ones[@specialized(Int, Float, Double, Long) V: ClassTag: Zero: Semiring](
      rows: Int,
      cols: Int): DenseMatrix[V] = {
    val data = new Array[V](rows * cols)
    if (rows * cols != 0 && data(0) != implicitly[Semiring[V]].one)
      ArrayUtil.fill(data, 0, data.length, implicitly[Semiring[V]].one)
    DenseMatrix.create(rows, cols, data)
  }

  /**
   * Creates a square diagonal array of size dim x dim, with 1's along the diagonal.
   */
  def eye[@spec(Double, Int, Float, Long) V: ClassTag: Zero: Semiring](dim: Int): DenseMatrix[V] = {
    val r = zeros[V](dim, dim)
    breeze.linalg.diag.diagDMDVImpl.apply(r) := implicitly[Semiring[V]].one
    r
  }

  /** Horizontally tiles some matrices. They must have the same number of rows */
  def horzcat[M, V](matrices: M*)(
      implicit ev: M <:< Matrix[V],
      opset: OpSet.InPlaceImpl2[DenseMatrix[V], M],
      vman: ClassTag[V],
      zero: Zero[V]) = {
    if (matrices.isEmpty) zeros[V](0, 0)
    else {
      require(matrices.forall(m => m.rows == matrices(0).rows), "Not all matrices have the same number of rows")
      val numCols = matrices.foldLeft(0)(_ + _.cols)
      val numRows = matrices(0).rows
      val res = DenseMatrix.zeros[V](numRows, numCols)
      var offset = 0
      for (m <- matrices) {
        res(0 until numRows, (offset) until (offset + m.cols)) := m
        offset += m.cols
      }
      res
    }
  }

  /** Vertically tiles some matrices. They must have the same number of columns */
  def vertcat[V](matrices: DenseMatrix[V]*)(
      implicit opset: OpSet.InPlaceImpl2[DenseMatrix[V], DenseMatrix[V]],
      vman: ClassTag[V],
      zero: Zero[V]) = {
    if (matrices.isEmpty) zeros[V](0, 0)
    else {
      require(matrices.forall(m => m.cols == matrices(0).cols), "Not all matrices have the same number of columns")
      val numRows = matrices.foldLeft(0)(_ + _.rows)
      val numCols = matrices(0).cols
      val res = DenseMatrix.zeros[V](numRows, numCols)
      var offset = 0
      for (m <- matrices) {
        res((offset) until (offset + m.rows), 0 until numCols) := m
        offset += m.rows
      }
      res
    }
  }

  implicit def scalarOf[T]: ScalarOf[DenseMatrix[T], T] = ScalarOf.dummy

  // zerosLike
  implicit def canCreateZerosLike[V: ClassTag: Zero]: CanCreateZerosLike[DenseMatrix[V], DenseMatrix[V]] =
    new CanCreateZerosLike[DenseMatrix[V], DenseMatrix[V]] {
      def apply(v1: DenseMatrix[V]): DenseMatrix[V] = {
        zeros[V](v1.rows, v1.cols)
      }
    }

  object FrobeniusInnerProductDenseMatrixSpace {
    implicit def space[S: Field: Zero: ClassTag]: MutableFiniteCoordinateField[DenseMatrix[S], (Int, Int), S] = {
      val norms = EntrywiseMatrixNorms.make[DenseMatrix[S], S]
      import norms._
      MutableFiniteCoordinateField.make[DenseMatrix[S], (Int, Int), S]
    }
  }

  @noinline
  private def init() = {}
}


text:
@implementation NSObject (YSKit)

+ (BOOL)ys_addInstanceMethodWithSelectorName:(NSString *)selectorName block:(void (^)(id))block {
	// don't accept nil name
	NSParameterAssert(selectorName);

	// don't accept NULL block
	NSParameterAssert(block);

	// See http://stackoverflow.com/questions/6357663/casting-a-block-to-a-void-for-dynamic-class-method-resolution

#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_7
    void *impBlockForIMP = (void *)objc_unretainedPointer(block);
#else
    id impBlockForIMP = (__bridge id)(__bridge void *)(block);
#endif

    IMP myIMP = imp_implementationWithBlock(impBlockForIMP);

    SEL selector = NSSelectorFromString(selectorName);
    return class_addMethod(self, selector, myIMP, "v@:");
}

#pragma mark - Method Swizzling

+ (void)ys_swizzleMethod:(SEL)selector withMethod:(SEL)otherSelector {
	// my own class is being targetted
	Class c = [self class];

	// get the methods from the selectors
	Method originalMethod = class_getInstanceMethod(c, selector);
	Method otherMethod = class_getInstanceMethod(c, otherSelector);

	if (class_addMethod(c, selector, method_getImplementation(otherMethod), method_getTypeEncoding(otherMethod))) {
		class_replaceMethod(c, otherSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
	}
	else {
		method_exchangeImplementations(originalMethod, otherMethod);
	}
}

+ (void)ys_swizzleClassMethod:(SEL)selector withMethod:(SEL)otherSelector {
	// my own class is being targetted
	Class c = [self class];

	// get the methods from the selectors
	Method originalMethod = class_getClassMethod(c, selector);
	Method otherMethod = class_getClassMethod(c, otherSelector);

	//    if (class_addMethod(c, selector, method_getImplementation(otherMethod), method_getTypeEncoding(otherMethod)))
	//	{
	//		class_replaceMethod(c, otherSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
	//	}
	//	else
	//	{
	method_exchangeImplementations(originalMethod, otherMethod);
	//	}
}

- (NSArray *)ys_getPropertyKeys{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:outCount];
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        [keys addObject:propertyName];
    }
    free(properties);
    return keys;
}

- (NSMutableDictionary *)ys_getProperties{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    NSMutableDictionary* propertiesDictionary = [NSMutableDictionary dictionaryWithCapacity:outCount];
    for (i = 0; i < outCount; i++) {
        NSString *propertyName = [NSString  stringWithUTF8String:property_getName(properties[i])];
        id propertyValue = [self valueForKey:propertyName];
        if (propertyValue) {
            [propertiesDictionary setObject:propertyValue forKey:propertyName];
        }
    }
    free(properties);
    return propertiesDictionary;
}

- (void)ys_reflectDataFromObject:(id)dataSource{
    BOOL ret = NO;
    for (NSString *key in [self ys_getPropertyKeys]) {
        if ([dataSource isKindOfClass:[NSDictionary class]]) {
            ret = [dataSource valueForKey:key]? YES : NO;
        }
        else {
            ret = [dataSource respondsToSelector:NSSelectorFromString(key)];
        }
        if (ret) {
            id propertyValue = [dataSource valueForKey:key];
            if (![propertyValue isKindOfClass:[NSNull class]] && propertyValue != nil) {
                [self setValue:propertyValue forKey:key];
            }
        }
    }
}

#pragma mark - DynamicProperties

+ (void)ys_implementDynamicPropertyAccessors {
	[self ys_implementDynamicPropertyAccessorsForPropertyMatching:nil];
}

+ (void)ys_implementDynamicPropertyAccessorsForPropertyName:(NSString *)propertyName {
	[self ys_implementDynamicPropertyAccessorsForPropertyMatching:[NSString stringWithFormat:@"^%@$", propertyName]];
}

+ (void)ys_implementDynamicPropertyAccessorsForPropertyMatching:(NSString *)regexString {
	[self enumeratePropertiesMatching:regexString withBlock: ^(objc_property_t property) {
	    [self implementAccessorsIfNecessaryForProperty:property];
	}];
}

+ (void)enumeratePropertiesMatching:(NSString *)regexString withBlock:(void (^)(objc_property_t property))block {
	NSParameterAssert(block);
	uint count = 0;
	objc_property_t *properties = class_copyPropertyList(self, &count);
	for (uint i = 0; i < count; i++) {
		objc_property_t property = properties[i];
		BOOL isMatch = !regexString || ({
		                                    NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
		                                    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:NULL];
		                                    [regex numberOfMatchesInString:propertyName options:0 range:NSMakeRange(0, propertyName.length)];
										});
		if (isMatch) {
			block(property);
		}
	}
	free(properties);
}

+ (void)implementAccessorsIfNecessaryForProperty:(objc_property_t)property {
	NSArray *attributes = [self attributesOfProperty:property];
	BOOL isDynamic = [attributes containsObject:@"D"];
	if (!isDynamic) {
		return;
	}

	BOOL isObjectType = YES;
	NSString *customGetterName;
	NSString *customSetterName;

	for (NSString *attribute in attributes) {
		unichar firstChar = [attribute characterAtIndex:0];
		switch (firstChar) {
			case 'T': isObjectType = [attribute characterAtIndex:1] == '@'; break;

			case 'G': customGetterName = [attribute substringFromIndex:1]; break;

			case 'S': customSetterName = [attribute substringFromIndex:1]; break;

			default: break;
		}
	}
	if (!isObjectType) {
		return;
	}

	const void *key = &key;
	key++;

	const char *name = property_getName(property);
	[self implementGetterIfNecessaryForPropertyName:name customGetterName:customGetterName key:key];

	BOOL isReadonly = [attributes containsObject:@"R"];
	if (!isReadonly) {
		[self implementSetterIfNecessaryForPropertyName:name customSetterName:customSetterName key:key attributes:attributes];
	}
}

+ (NSArray *)attributesOfProperty:(objc_property_t)property {
	return [[NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding] componentsSeparatedByString:@","];
}

+ (void)implementGetterIfNecessaryForPropertyName:(char const *)propertyName customGetterName:(NSString *)customGetterName key:(const void *)key {
	SEL getter = NSSelectorFromString(customGetterName ? : [NSString stringWithFormat:@"%s", propertyName]);
	[self implementMethodIfNecessaryForSelector:getter parameterTypes:NULL block: ^id (id _self) {
	    return objc_getAssociatedObject(self, key);
	}];
}

+ (void)implementSetterIfNecessaryForPropertyName:(char const *)propertyName customSetterName:(NSString *)customSetterName key:(const void *)key attributes:(NSArray *)attributes {
	BOOL isCopy = [attributes containsObject:@"C"];
	BOOL isRetain = [attributes containsObject:@"&"];
	objc_AssociationPolicy associationPolicy = isCopy ? OBJC_ASSOCIATION_COPY : isRetain ? OBJC_ASSOCIATION_RETAIN : OBJC_ASSOCIATION_ASSIGN;
	BOOL isNonatomic = [attributes containsObject:@"N"];
	if (isNonatomic) {
		objc_AssociationPolicy nonatomic = OBJC_ASSOCIATION_COPY_NONATOMIC - OBJC_ASSOCIATION_COPY;
		associationPolicy += nonatomic;
	}

	SEL setter = NSSelectorFromString(customSetterName ? : [NSString stringWithFormat:@"set%c%s:", toupper(*propertyName), propertyName + 1]);
	[self implementMethodIfNecessaryForSelector:setter parameterTypes:"@" block: ^(id _self, id var) {
	    objc_setAssociatedObject(self, key, var, associationPolicy);
	}];
}

+ (void)implementMethodIfNecessaryForSelector:(SEL)selector parameterTypes:(const char *)types block:(id)block {
	BOOL instancesRespondToSelector = [self instancesRespondToSelector:selector];
	if (!instancesRespondToSelector) {
		IMP implementation = imp_implementationWithBlock(block);
		class_addMethod(self, selector, implementation, types);
	}
}

@end

redpajama_set_name: RedPajamaGithub


text:
namespace rx
{
class RendererVk;
class RenderTargetVk;
class WindowSurfaceVk;

class FramebufferVk : public FramebufferImpl
{
  public:
    // Factory methods so we don't have to use constructors with overloads.
    static FramebufferVk *CreateUserFBO(RendererVk *renderer, const gl::FramebufferState &state);

    // The passed-in SurfaceVK must be destroyed after this FBO is destroyed. Our Surface code is
    // ref-counted on the number of 'current' contexts, so we shouldn't get any dangling surface
    // references. See Surface::setIsCurrent(bool).
    static FramebufferVk *CreateDefaultFBO(RendererVk *renderer,
                                           const gl::FramebufferState &state,
                                           WindowSurfaceVk *backbuffer);

    ~FramebufferVk() override;
    void destroy(const gl::Context *context) override;

    angle::Result discard(const gl::Context *context,
                          size_t count,
                          const GLenum *attachments) override;
    angle::Result invalidate(const gl::Context *context,
                             size_t count,
                             const GLenum *attachments) override;
    angle::Result invalidateSub(const gl::Context *context,
                                size_t count,
                                const GLenum *attachments,
                                const gl::Rectangle &area) override;

    angle::Result clear(const gl::Context *context, GLbitfield mask) override;
    angle::Result clearBufferfv(const gl::Context *context,
                                GLenum buffer,
                                GLint drawbuffer,
                                const GLfloat *values) override;
    angle::Result clearBufferuiv(const gl::Context *context,
                                 GLenum buffer,
                                 GLint drawbuffer,
                                 const GLuint *values) override;
    angle::Result clearBufferiv(const gl::Context *context,
                                GLenum buffer,
                                GLint drawbuffer,
                                const GLint *values) override;
    angle::Result clearBufferfi(const gl::Context *context,
                                GLenum buffer,
                                GLint drawbuffer,
                                GLfloat depth,
                                GLint stencil) override;

    GLenum getImplementationColorReadFormat(const gl::Context *context) const override;
    GLenum getImplementationColorReadType(const gl::Context *context) const override;
    angle::Result readPixels(const gl::Context *context,
                             const gl::Rectangle &area,
                             GLenum format,
                             GLenum type,
                             void *pixels) override;

    angle::Result blit(const gl::Context *context,
                       const gl::Rectangle &sourceArea,
                       const gl::Rectangle &destArea,
                       GLbitfield mask,
                       GLenum filter) override;

    bool checkStatus(const gl::Context *context) const override;

    angle::Result syncState(const gl::Context *context,
                            const gl::Framebuffer::DirtyBits &dirtyBits) override;

    angle::Result getSamplePosition(const gl::Context *context,
                                    size_t index,
                                    GLfloat *xy) const override;
    RenderTargetVk *getDepthStencilRenderTarget() const;

    // Internal helper function for readPixels operations.
    angle::Result readPixelsImpl(ContextVk *contextVk,
                                 const gl::Rectangle &area,
                                 const PackPixelsParams &packPixelsParams,
                                 VkImageAspectFlagBits copyAspectFlags,
                                 RenderTargetVk *renderTarget,
                                 void *pixels);

    gl::Extents getReadImageExtents() const;
    gl::Rectangle getCompleteRenderArea() const;
    gl::Rectangle getScissoredRenderArea(ContextVk *contextVk) const;

    void onScissorChange(ContextVk *contextVk);

    const gl::DrawBufferMask &getEmulatedAlphaAttachmentMask() const;
    RenderTargetVk *getColorDrawRenderTarget(size_t colorIndex) const;
    RenderTargetVk *getColorReadRenderTarget() const;

    // This will clear the current write operation if it is complete.
    bool appendToStartedRenderPass(vk::CommandGraph *graph,
                                   const gl::Rectangle &renderArea,
                                   vk::CommandBuffer **commandBufferOut)
    {
        return mFramebuffer.appendToStartedRenderPass(graph, renderArea, commandBufferOut);
    }

    vk::FramebufferHelper *getFramebuffer() { return &mFramebuffer; }

    angle::Result startNewRenderPass(ContextVk *context,
                                     const gl::Rectangle &renderArea,
                                     vk::CommandBuffer **commandBufferOut);

    RenderTargetVk *getFirstRenderTarget() const;
    GLint getSamples() const;

    const vk::RenderPassDesc &getRenderPassDesc() const { return mRenderPassDesc; }

  private:
    FramebufferVk(RendererVk *renderer,
                  const gl::FramebufferState &state,
                  WindowSurfaceVk *backbuffer);

    // The 'in' rectangles must be clipped to the scissor and FBO. The clipping is done in 'blit'.
    angle::Result blitWithCommand(ContextVk *contextVk,
                                  const gl::Rectangle &sourceArea,
                                  const gl::Rectangle &destArea,
                                  RenderTargetVk *readRenderTarget,
                                  RenderTargetVk *drawRenderTarget,
                                  GLenum filter,
                                  bool colorBlit,
                                  bool depthBlit,
                                  bool stencilBlit,
                                  bool flipX,
                                  bool flipY);

    // Resolve color with vkCmdResolveImage
    angle::Result resolveColorWithCommand(ContextVk *contextVk,
                                          const UtilsVk::BlitResolveParameters &params,
                                          vk::ImageHelper *srcImage);

    angle::Result getFramebuffer(ContextVk *contextVk, vk::Framebuffer **framebufferOut);

    angle::Result clearImpl(const gl::Context *context,
                            gl::DrawBufferMask clearColorBuffers,
                            bool clearDepth,
                            bool clearStencil,
                            const VkClearColorValue &clearColorValue,
                            const VkClearDepthStencilValue &clearDepthStencilValue);
    angle::Result clearWithRenderPassOp(ContextVk *contextVk,
                                        const gl::Rectangle &clearArea,
                                        gl::DrawBufferMask clearColorBuffers,
                                        bool clearDepth,
                                        bool clearStencil,
                                        const VkClearColorValue &clearColorValue,
                                        const VkClearDepthStencilValue &clearDepthStencilValue);
    angle::Result clearWithDraw(ContextVk *contextVk,
                                const gl::Rectangle &clearArea,
                                gl::DrawBufferMask clearColorBuffers,
                                bool clearStencil,
                                VkColorComponentFlags colorMaskFlags,
                                uint8_t stencilMask,
                                const VkClearColorValue &clearColorValue,
                                uint8_t clearStencilValue);
    void updateActiveColorMasks(size_t colorIndex, bool r, bool g, bool b, bool a);
    void updateRenderPassDesc();
    angle::Result updateColorAttachment(const gl::Context *context, size_t colorIndex);
    void invalidateImpl(ContextVk *contextVk, size_t count, const GLenum *attachments);

    WindowSurfaceVk *mBackbuffer;

    vk::RenderPassDesc mRenderPassDesc;
    vk::FramebufferHelper mFramebuffer;
    RenderTargetCache<RenderTargetVk> mRenderTargetCache;

    // These two variables are used to quickly compute if we need to do a masked clear. If a color
    // channel is masked out, we check against the Framebuffer Attachments (RenderTargets) to see
    // if the masked out channel is present in any of the attachments.
    VkColorComponentFlags mActiveColorComponents;
    gl::DrawBufferMask mActiveColorComponentMasksForClear[4];
    vk::DynamicBuffer mReadPixelBuffer;

    // When we draw to the framebuffer, and the real format has an alpha channel but the format of
    // the framebuffer does not, we need to mask out the alpha channel. This DrawBufferMask will
    // contain the mask to apply to the alpha channel when drawing.
    gl::DrawBufferMask mEmulatedAlphaAttachmentMask;
};
}  // namespace rx

#endif  // LIBANGLE_RENDERER_VULKAN_FRAMEBUFFERVK_H_


text:
package xacml

import (
	"log"
)

const (
	ResultPermit        = "Permit"
	ResultDeny          = "Deny"
	ResultNotApplicable = "NotApplicable"
	ResultIndeterminate = "Indeterminate"
)

type Policy struct {
	policy map[string]interface{}
}

func evaluatePolicy(policy map[string]interface{}, request map[string]interface{}) Response {
	p := Policy{policy}
	r := Request{request}
	response := p.Evaluate(r)
	return response
}

func (policy Policy) Evaluate(request Request) Response {
	policyBody, _ := policy.policy["Policy"].(map[string]interface{})
	response := Response{make(map[string]interface{})}

	//Evaluate Target
	targetResponse := evaluateTargetBody(policyBody["Target"], request)
	//log.Println(targetResponse)
	if targetResponse != targetMatch {
		if targetResponse == targetNoMatch {
			response.AddResult(ResponseNotApplicable, "Policy Target returned No Match")
			return response
		}
		if targetResponse == targetIndeterminate {
			response.AddResult(ResponseIndeterminate, "Policy Target returned Indeterminate")
			return response
		}
	}

	rules := make([]evaluatable, 0)
	switch policyBody["Rule"].(type) {
	case map[string]interface{}:
		rules = append(rules, Rule{policyBody["Rule"].(map[string]interface{})})
	case []interface{}:
		for _, ruleInterface := range policyBody["Rule"].([]interface{}) {
			ruleMap, _ := ruleInterface.(map[string]interface{})
			rule := Rule{ruleMap}
			rules = append(rules, rule)
		}
	default:
		log.Println("Invalid Rule, was neither a tag or array")
		response.AddResult(ResponseIndeterminate, "Invalid Rule, was neither a tag or array")
		return response
	}

	ruleCombiningAlgorithm, _ := policyBody["-RuleCombiningAlgId"].(string)
	//Evaluate Rules
	response = combineAlgorithm(ruleCombiningAlgorithm, rules, request)
	//log.Println(response)
	return response
}


text:
<?php

/*
User item:
email,
password,
createdAt,
userRole: admin, user, guest,
lastLogin
 */

function loginFunction()
{
    try {
        $data = json_decode(file_get_contents("php://input"), true);
        if (empty($data)) {
            return array('result' => 'Empty data for update');
        }
        $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
        if (isset($data['username']) && !empty($data['username'])) {
            $filters = [
                'email' => $data['username']
            ];
        } else {
            return [
                'result' => false,
                'message' => "Email field can't be empty."
            ];
        }
        if (!isset($data['password']) || empty($data['password'])) {
            return [
                'result' => false,
                'message' => "Password field can't be empty."
            ];
        }
        $query = new MongoDB\Driver\Query($filters);
        $res = $manager->executeQuery('todos.users', $query);
        $users = array();
        $item = new stdClass();
        foreach ($res as $row) {
            $item = new stdClass();
            foreach ($row as $key => $value) {
                if ($key == '_id') {
                    $value = (string)$value;
                }
                $item->$key = $value;
            }
            $users[] = $item;
        }
        if (empty($users)) {
            return [
                'result' => false,
                'message' => 'Account not exist.'
            ];
        } else if (count($users) > 1) {
            return [
                'result' => false,
                'message' => 'There are too much accounts with same email.'
            ];
        } else if (count($users) == 1 && $item->password == $data['password']) {
            $filter = ['_id' => new MongoDB\BSON\ObjectID($item->_id)];
            $update = [
                'email' => $item->email,
                'password' => $item->password,
                'userRole' => $item->userRole,
                'createAt' => $item->createAt,
                'lastLogin' => date('Y-m-d H:i:s'),
            ];
            $bulk = new MongoDB\Driver\BulkWrite;
            $bulk->update($filter, $update);
            $manager->executeBulkWrite('todos.users', $bulk);
            return [
                'result' => true,
                'role' => $item->userRole,
                'id' => $item->_id
            ];
        } else {
            return [
                'result' => false,
                'message' => 'Password is not correct.'
            ];
        }
    } catch (Throwable $e) {
        print_r("Throwable\n");
        print_r($e->getMessage() . "\n");
    } catch (Exception $e) {
        print_r("Exception\n");
        print_r($e->getMessage() . "\n");
    }
    die;
}

$result = loginFunction();

header('HTTP/1.1 200 OK', true, 200);
header('Content-Type: application/json');
echo json_encode($result);
exit(0);


text:
package st.gravel.support.compiler.jvm;

/*
	This file is automatically generated from typed smalltalk source. Do not edit by hand.
	(C) AG5.com
*/

import java.math.BigInteger;
import st.gravel.support.jvm.NonLocalReturn;
import st.gravel.support.compiler.jvm.JVMPrimitiveType;
import st.gravel.support.compiler.jvm.JVMPrimitiveType.JVMPrimitiveType_Factory;
import st.gravel.support.compiler.jvm.JVMNodeVisitor;
import st.gravel.support.compiler.jvm.JVMType;
import st.gravel.support.compiler.jvm.CastObjectToShort;
import st.gravel.support.compiler.jvm.CastTo;

public class JVMShortType extends JVMPrimitiveType implements Cloneable {

	public static JVMShortType_Factory factory = new JVMShortType_Factory();

	public static class JVMShortType_Factory extends JVMPrimitiveType_Factory {

		public JVMShortType basicNew() {
			JVMShortType newInstance = new JVMShortType();
			newInstance.initialize();
			return newInstance;
		}
	}

	@Override
	public <X> X accept_(final JVMNodeVisitor<X> _visitor) {
		return _visitor.visitJVMShortType_(this);
	}

	@Override
	public JVMType commonSuperTypeWith_(final JVMType _aJVMType) {
		return _aJVMType.commonSuperTypeWithShort_(this);
	}

	public JVMShortType copy() {
		try {
			JVMShortType _temp1 = (JVMShortType) this.clone();
			_temp1.postCopy();
			return _temp1;
		} catch (CloneNotSupportedException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public JVMShortType descriptorOn_(final StringBuilder _aStream) {
		this.sourceOn_(_aStream);
		return this;
	}

	public JVMShortType_Factory factory() {
		return factory;
	}

	@Override
	public CastObjectToShort newCastInstructionFromDynamicObject() {
		return CastObjectToShort.factory.basicNew();
	}

	@Override
	public CastTo newCastInstructionTo_(final JVMType _aJVMType) {
		return _aJVMType.newCastInstructionFromShort();
	}

	@Override
	public JVMShortType printOn_(final StringBuilder _aStream) {
		this.sourceOn_(_aStream);
		return this;
	}

	@Override
	public JVMShortType sourceOn_(final StringBuilder _aStream) {
		_aStream.append('S');
		return this;
	}
}


text:
package org.apache.hadoop.hbase.chaos.actions;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.CompactType;

/**
 * Action that queues a table compaction.
 */
public class CompactMobAction extends Action {
  private final TableName tableName;
  private final int majorRatio;
  private final long sleepTime;

  public CompactMobAction(TableName tableName, float majorRatio) {
    this(-1, tableName, majorRatio);
  }

  public CompactMobAction(
          int sleepTime, TableName tableName, float majorRatio) {
    this.tableName = tableName;
    this.majorRatio = (int) (100 * majorRatio);
    this.sleepTime = sleepTime;
  }

  @Override
  public void perform() throws Exception {
    HBaseTestingUtility util = context.getHBaseIntegrationTestingUtility();
    Admin admin = util.getAdmin();
    boolean major = RandomUtils.nextInt(100) < majorRatio;

    // Don't try the modify if we're stopping
    if (context.isStopping()) {
      return;
    }

    LOG.info("Performing action: Compact mob of table " + tableName + ", major=" + major);
    try {
      if (major) {
        admin.majorCompact(tableName, CompactType.MOB);
      } else {
        admin.compact(tableName, CompactType.MOB);
      }
    } catch (Exception ex) {
      LOG.warn("Mob Compaction failed, might be caused by other chaos: " + ex.getMessage());
    }
    if (sleepTime > 0) {
      Thread.sleep(sleepTime);
    }
  }
}


text:
import logging
import traceback
import importlib

logger = logging.getLogger('qtile')

def safe_import(module_name, class_name):
    """
    try to import a module, and if it fails because an ImporError
    it logs on WARNING, and logs the traceback on DEBUG level
    """
    if type(class_name) is list:
        for name in class_name:
            safe_import(module_name, name)
        return
    package = __package__
    # python 3.2 don't set __package__
    if not package:
        package = __name__
    try:
        module = importlib.import_module(module_name, package)
        globals()[class_name] = getattr(module, class_name)
    except ImportError as error:
        msg = "Can't Import Widget: '%s.%s', %s"
        logger.warning(msg % (module_name, class_name, error))
        logger.debug(traceback.format_exc())

safe_import(".backlight", "Backlight")
safe_import(".battery", ["Battery", "BatteryIcon"])
safe_import(".clock", "Clock")
safe_import(".currentlayout", "CurrentLayout")
safe_import(".debuginfo", "DebugInfo")
safe_import(".graph", ["CPUGraph", "MemoryGraph", "SwapGraph", "NetGraph",
                       "HDDGraph", "HDDBusyGraph"])
safe_import(".groupbox", ["AGroupBox", "GroupBox"])
safe_import(".maildir", "Maildir")
safe_import(".notify", "Notify")
safe_import(".prompt", "Prompt")
safe_import(".sensors", "ThermalSensor")
safe_import(".sep", "Sep")
safe_import(".she", "She")
safe_import(".spacer", "Spacer")
safe_import(".systray", "Systray")
safe_import(".textbox", "TextBox")
safe_import(".generic_poll_text", ["GenPollText", "GenPollUrl"])
safe_import(".volume", "Volume")
safe_import(".windowname", "WindowName")
safe_import(".windowtabs", "WindowTabs")
safe_import(".keyboardlayout", "KeyboardLayout")
safe_import(".df", "DF")
safe_import(".image", "Image")
safe_import(".gmail_checker", "GmailChecker")
safe_import(".clipboard", "Clipboard")
safe_import(".countdown", "Countdown")
safe_import(".tasklist", "TaskList")
safe_import(".pacman", "Pacman")
safe_import(".launchbar", "LaunchBar")
safe_import(".canto", "Canto")
safe_import(".mpriswidget", "Mpris")
safe_import(".mpris2widget", "Mpris2")
safe_import(".mpdwidget", "Mpd")
safe_import(".yahoo_weather", "YahooWeather")
safe_import(".bitcoin_ticker", "BitcoinTicker")
safe_import(".wlan", "Wlan")
safe_import(".google_calendar", "GoogleCalendar")
safe_import(".imapwidget", "ImapWidget")
safe_import(".net", "Net")
safe_import(".keyboardkbdd", "KeyboardKbdd")
safe_import(".cmus", "Cmus")
safe_import(".wallpaper", "Wallpaper")
safe_import(".check_updates", "CheckUpdates")


text:
<?php

namespace Foo;

class Foo
{
    public function __construct(
        public string $property = 'value',
    ) {}
}


text:
GameBaseObject::GameBaseObject()
{
	m_id = -1;
	m_idInRegistr = -1;
}

GameBaseObject::GameBaseObject(GameBaseObject &other)
{
	m_id = -1;
	m_idInRegistr = -1;
	m_resources = other.m_resources;
}

void GameBaseObject::PreInit(DX::DeviceResources *resources)
{
	m_id = -1;
	m_idInRegistr = -1;
	m_resources = resources;
}

void GameBaseObject::PerformancePersistence(bool onlyGetSize, bool isSaveMod)
{
	m_persistenceIsOnlyGetSizeMod = onlyGetSize;

	//save object data to buffer mod == true or load object data from buffer == false
	m_persistenceIsSaveMod = isSaveMod;
	m_persistenceIndex = 0;
	m_persistenceSize = 0;
}

int GameBaseObject::SaveOrLoadValue(void * ptr, int size)
{
	if (m_persistenceIsOnlyGetSizeMod == false)
	{

		if (m_persistenceIsSaveMod == true)
		{
			memcpy(&m_persistenceBuffer[m_persistenceIndex], ptr, size);
			m_persistenceIndex += size;
		}
		else
		{
			memcpy(ptr, &m_persistenceBuffer[m_persistenceIndex], size);
			m_persistenceIndex += size;
		}
	}

	return size;
}

int GameBaseObject::SaveOrLoadString(std::string *S)
{
	int size = 0;
	if (m_persistenceIsOnlyGetSizeMod == false)
	{
		if (m_persistenceIsSaveMod == true)
		{
			size = S->size();
			memcpy(&m_persistenceBuffer[m_persistenceIndex], &size, sizeof(size));
			m_persistenceIndex += sizeof(size);
			memcpy(&m_persistenceBuffer[m_persistenceIndex], &S->at(0), size);
			m_persistenceIndex += size;
		}
		else
		{
			memcpy(&size, &m_persistenceBuffer[m_persistenceIndex], sizeof(size));
			m_persistenceIndex += sizeof(size);
			S->resize(size);
			memcpy(&S->at(0), &m_persistenceBuffer[m_persistenceIndex], size);
			m_persistenceIndex += size;
		}
	}

	return (sizeof(int) + S->size());
}

void GameBaseObject::SetSizeOfPersistenceBuffer(int size)
{
	m_persistenceBuffer.resize(size);
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Peach.Log
{
    public class Configurator
    {
        public static void Configurate(string logConfig)
        {
           log4net.Config.XmlConfigurator.Configure(new FileInfo(logConfig));
        }
        public static void Configurate(Stream logConfigStream)
        {
            log4net.Config.XmlConfigurator.Configure(logConfigStream);
        }
    }
}


text:
package edu.uci.ics.asterix.runtime.external;

import edu.uci.ics.hyracks.api.context.IHyracksTaskContext;
import edu.uci.ics.hyracks.api.dataflow.IOperatorNodePushable;
import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import edu.uci.ics.hyracks.api.dataflow.value.INullWriterFactory;
import edu.uci.ics.hyracks.api.dataflow.value.IRecordDescriptorProvider;
import edu.uci.ics.hyracks.api.dataflow.value.ITypeTraits;
import edu.uci.ics.hyracks.api.dataflow.value.RecordDescriptor;
import edu.uci.ics.hyracks.api.job.IOperatorDescriptorRegistry;
import edu.uci.ics.hyracks.dataflow.std.file.IFileSplitProvider;
import edu.uci.ics.hyracks.storage.am.common.api.IIndexLifecycleManagerProvider;
import edu.uci.ics.hyracks.storage.am.common.api.ISearchOperationCallbackFactory;
import edu.uci.ics.hyracks.storage.am.lsm.rtree.dataflow.ExternalRTreeDataflowHelperFactory;
import edu.uci.ics.hyracks.storage.am.rtree.dataflow.RTreeSearchOperatorDescriptor;
import edu.uci.ics.hyracks.storage.common.IStorageManagerInterface;

public class ExternalRTreeSearchOperatorDescriptor extends RTreeSearchOperatorDescriptor {

    private static final long serialVersionUID = 1L;

    public ExternalRTreeSearchOperatorDescriptor(IOperatorDescriptorRegistry spec, RecordDescriptor recDesc,
            IStorageManagerInterface storageManager, IIndexLifecycleManagerProvider lifecycleManagerProvider,
            IFileSplitProvider fileSplitProvider, ITypeTraits[] typeTraits,
            IBinaryComparatorFactory[] comparatorFactories, int[] keyFields,
            ExternalRTreeDataflowHelperFactory dataflowHelperFactory, boolean retainInput, boolean retainNull,
            INullWriterFactory iNullWriterFactory, ISearchOperationCallbackFactory searchOpCallbackFactory) {
        super(spec, recDesc, storageManager, lifecycleManagerProvider, fileSplitProvider, typeTraits,
                comparatorFactories, keyFields, dataflowHelperFactory, retainInput, retainNull, iNullWriterFactory,
                searchOpCallbackFactory, null, null);
    }

    @Override
    public IOperatorNodePushable createPushRuntime(final IHyracksTaskContext ctx,
            IRecordDescriptorProvider recordDescProvider, int partition, int nPartitions) {
        return new ExternalRTreeSearchOperatorNodePushable(this, ctx, partition, recordDescProvider, keyFields);
    }

}


text:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace _2.Cards
{
    class Program
    {
        static void Main(string[] args)
        {
            string pattern = @"([1]?[0-9JQKA])([SHDC])";
            Regex needed = new Regex(pattern);

            string inputLine = Console.ReadLine();

            var cards = needed.Matches(inputLine);

            List<string> validCards = new List<string>();

            foreach (Match card in cards)
            {
                int cardPower;
                if (int.TryParse(card.Groups[1].Value, out cardPower))
                {
                    if (cardPower < 2 || cardPower > 10)
                    {
                        continue;
                    }
                }
                validCards.Add(card.Value);
            }

            Console.WriteLine(string.Join(", ", validCards));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright (c) 2015 The Chromium Authors. All rights reserved.  Use of this
  source code is governed by a BSD-style license that can be found in the
  LICENSE file.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.chromium.tools.spnegoauthenticator" >

    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" >
        <service
            android:name=".SpnegoAuthenticatorService"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.accounts.AccountAuthenticator" />
            </intent-filter>

            <meta-data
                android:name="android.accounts.AccountAuthenticator"
                android:resource="@xml/spnego_authenticator" />
        </service>
    </application>

</manifest>


text:
package com.github.codechapin.postcss.internal;

import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 *
 */
public class Utils {
    public static final String EMPTY = "";

    private Utils() {
    }

    public static boolean isNullOrEmpty(final String string) {
        return string == null || string.isEmpty();
    }

    public static Reader newBufferedReader(final Path path) {
        try {
            return Files.newBufferedReader(path, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}


text:
#include "Rendering/Volume.h"

#include "GLBlaat/GL.h"
#include "GLBlaat/GLProgram.h"
#include "GLBlaat/GLTexture3D.h"
#include "GLBlaat/GLTextureManager.h"
#include "GLBlaat/GLFramebuffer.h"
#include "GLBlaat/GLRenderTexture3DLayer.h"
#include "GLBlaat/GLUtility.h"

#include <cassert>
#include <iostream>

namespace NQVTK
{
	namespace GPGPU
	{
		// --------------------------------------------------------------------
		VolumeToVolumeFilter::VolumeToVolumeFilter()
			: tm(0), program(0), input(0)
		{
		}

		// --------------------------------------------------------------------
		VolumeToVolumeFilter::~VolumeToVolumeFilter()
		{
			delete tm;
			delete program;
		}

		// --------------------------------------------------------------------
		bool VolumeToVolumeFilter::Setup(Volume *input)
		{
            tm = GLTextureManager::New();

			assert(input);
			this->input = input;

			std::cout << "Creating filter..." << std::endl;
			program = CreateProgram();
			if (!program)
			{
				std::cerr << "Could not create filter program!" << std::endl;
				return false;
			}

			return true;
		}

		// --------------------------------------------------------------------------
		void VolumeToVolumeFilter::ExecutePass(Volume *input, Volume *output)
		{
			// Make sure the input uses nearest neighbor filtering
			input->BindToCurrent();
			glTexParameterf(input->GetTextureTarget(),
				GL_TEXTURE_MAG_FILTER, GL_NEAREST);
			glTexParameterf(input->GetTextureTarget(),
				GL_TEXTURE_MIN_FILTER, GL_NEAREST);
			input->UnbindCurrent();

			// Set the input
			tm->AddTexture("volume", input, false);

			// Prepare an FBO for the output
			GLFramebuffer *fbo = GLFramebuffer::New(
				output->GetWidth(), output->GetHeight());

			// Run over the slices of the output
			// We render 4 slices simultaneously
			int numSlices = output->GetDepth();
			GLenum bufs[] = {
				GL_COLOR_ATTACHMENT0_EXT,
				GL_COLOR_ATTACHMENT1_EXT,
				GL_COLOR_ATTACHMENT2_EXT,
				GL_COLOR_ATTACHMENT3_EXT
			};
			for (int slice = 0; slice < numSlices; slice += 4)
			{
				// Attach the slices
				int i;
				for (i = 0; i < 4 && slice + i < numSlices; ++i)
				{
					GLRenderTexture3DLayer *rt =
						GLRenderTexture3DLayer::New(output, slice + i);
					GLRendertarget *rtOld = fbo->AttachRendertarget(
						bufs[i], rt);
					delete rtOld;
				}
				glDrawBuffers(i, bufs);
				// Check the FBO
				if (!fbo->IsOk())
				{
					std::cerr << "FBO for output volume not ok!" << std::endl;
					delete fbo;
					return;
				}

				// FBO should still be bound after this

				// Start the program
				program->Start();
				// TODO: pass volume metadata for spacing etc.
				Vector3 dims(
					static_cast<float>(input->GetWidth()),
					static_cast<float>(input->GetHeight()),
					static_cast<float>(input->GetDepth()));
				program->SetUniform3f("volumeDims",
					static_cast<float>(dims.x),
					static_cast<float>(dims.y),
					static_cast<float>(dims.z));
				Vector3 size = input->GetOriginalSize();
				program->SetUniform3f("volumeSpacing",
					static_cast<float>(size.x / dims.x),
					static_cast<float>(size.y / dims.y),
					static_cast<float>(size.z / dims.z));
				program->SetUniform1f("volumeDataShift",
					static_cast<float>(input->GetDataShift()));
				program->SetUniform1f("volumeDataScale",
					static_cast<float>(input->GetDataScale()));
				program->SetUniform1i("slice", slice);

				SetupProgramParameters(program);

				tm->SetupProgram(program);
				tm->Bind();

				// Render a full screen quad to process the slices
				glColor3d(1.0, 1.0, 1.0);
				glBegin(GL_QUADS);
				glVertex3d(-1.0, -1.0, 0.0);
				glVertex3d(1.0, -1.0, 0.0);
				glVertex3d(1.0, 1.0, 0.0);
				glVertex3d(-1.0, 1.0, 0.0);
				glEnd();

				program->Stop();
				tm->Unbind();
			}

			// Deleting the fbo will unbind it
			delete fbo;

			// Restore linear interpolation for the input volume
			input->BindToCurrent();
			glTexParameterf(input->GetTextureTarget(),
				GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameterf(input->GetTextureTarget(),
				GL_TEXTURE_MIN_FILTER, GL_LINEAR);
			input->UnbindCurrent();
		}
	}
}


text:
'''Support module for translating strings.

This module provides several functions
for definitions, keys, and transforms.'''

__version__ = 1.3

################################################################################

import random

def definition(name=None):
    'Returns a valid definition.'
    random.seed(name)
    definition, list_one, list_two = str(), range(256), range(256)
    for index in range(256):
        index_one, index_two = random.randrange(256 - index), random.randrange(256 - index)
        definition += chr(list_one[index_one]) + chr(list_two[index_two])
        del list_one[index_one], list_two[index_two]
    return definition

def key(definition, select):
    'Returns a valid key.'
    key = range(256)
    for index in range(256):
        key[ord(definition[index * 2 + int(bool(select))])] = definition[index * 2 + int(not bool(select))]
    return ''.join(key)

def transform(key, string):
    'Returns a valid transformation.'
    return string.translate(key)

################################################################################

if __name__ == '__main__':
    import sys
    print 'Content-Type: text/plain'
    print
    print file(sys.argv[0]).read()


text:
Doctor Andy's Simulation Language (DASL)
===

Darl can be used to simulate knowledge in the form of a transform between a set of inputs and a set of outputs.
These inputs and outputs represent some moment in time, some state pertaining in a real or imagined world within prescribed time limits.
Clearly Darl could be much more useful if time could be added to this processing, where a sequence of such states could be presented to Darl, and where Darl could be driven by time series and create simulated time series in turn.

Adding the dimension of time can complicate a system enormously.
Happily, Darl can be extended to become a time based simulation engine very easily. These extensions constitute DASL.

We need only one addition to the Darl language to handle the dimension of time: a delay element.

The Delay element exists at the top level of a Darl program, defined along with the Wire elements that connect rule sets together and to the connectors of the code block.

```darl
delay map1 logisticMap.in1 {1};
```

The above defines a delay element taking it's input from a program level output(the first parameter), and passing it's delayed value to a ruleset input (the second parameter). The delay characteristics can be determined by the third parameter.
This third parameter is a fuzzy number, so can consist of 1,4 ascending values. Its units are those of the clock used to time the simulation, so only integer values make sense here.

The concept of a fuzzy delay is quite esoteric, but matches real world situations very well.

Suppose you wished to simulate the opening of a new company. The process of registering a company with the national registration body might take 1-2 days. Opening a bank account might take 2-3 weeks.
If we choose the simulation clock to be one day, then the first is
```darl
delay namechosen company.registered {1,2};
```

and the second might be

```darl
delay bankapplication company.bankaccount {7,14};
```

In other circumstances triangular or trapezoidal fuzzy numbers may be useful.

As well as the extensions to the Darl language we need to extend the functionality of the Darl interpreter to handle an extra dimension of data.

The following is a complete Darl program simulating the [Logistic Map](https://en.wikipedia.org/wiki/Logistic_map) equation, that creates a chaotic sequence of numbers.

```darl
ruleset logisticMap
{
	input numeric in1 ;
	output numeric out1;
	if anything then out1 will be 4 * in1 * ( 1 - in1);
}
mapoutput map1;
mapinput in1;
wire logisticMap.out1 map1;
wire in1 logisticMap.in1;
delay map1 logisticMap.in1 {0};
```

The form of the logistic map equation is simply X(n+1) = rX(n)(1-X(n))
Selecting r as 4 guarantees chaos.

The following diagram shows how the delay is wired:
![logistic map diagram](Images/Logisticmap_diagram.jpg)

## Handling temporal data
Temporal data comes in two forms, events associated with one or more data values, and regularly sampled time series.
Of the two, an event representation is the most general, since a sampled time series can be represented as a sequence of events.

We are interested here in multivariate data. In the real world data that might be used is sampled at a range of frequencies, or occurs as spontaneous events.
We would like, however, our simulation to have a regular sample period so that calculations using delays can be generated cleanly and graphed easily.

The solution is a data structure, [DaslState](../DarlCommon/DaslState), and the addition of a Temporal database to Dasl.

DaslState is a data structure that contains a time stamp and a list of [DarlVar](../DarlCommon/DarlVar) data structures, each of which contains a single named value.

A DaslState data structure represents an event, holding a time tag and containing the named data values that changed at the moment represented.

The temporal database is a way of collecting a set of such events, ordering them in time, and then constructing a regularly sampled series representing the state of each required value at the sample time.

## Initialising a simulation

The logistic map equation above defines how to create the next value from the previous one, but does not define the initial conditions.
I.e. what is the first value of X?

In the case above we need only a single value to start the sequence, but in the general case, where long delays may be present it may take many sample steps to initialize a model.

Furthermore a typical use case of a Dasl rule set  would be to fine tune it against existing data before using it to create predictive simulations.

For instance, given a model of factory processes and the progress of products through manufacturing, the user would be interested in first discovering whether the simulated model matched the real flow using real data, before using the simulation to work out what would happen if, say, a particular machine failed.

This leads us to define the following conventions that you should adhere to in creating data as a list of DaslState objects.

+ You should supply an array of DaslState objects for input to the simulation
+ You should also supply a sample time interval for the simulation
+ The array of DaslState objects can be in any order.
+ There should be at least two DaslState objects in the array.
+ DaslState objects may have an empty list of DarlVar data values.
+ DaslState objects need only contain DarlVar data values that have changed at the given time stamp point in time.
+ The earliest of the DaslState objects in the array, as defined by their time stamp, will be used as the start of the simulation.
+ The simulation proceeds at sample time intervals from this earliest time until simulation time is equal to or greater than the latest DaslState value as defined by its time stamp.
+ At each sample created by the temporal database the value of an input is set by the last event occurring at or before that time, but not occurring in the previous sample.
+ if an input is served by a delay, but there is no value in the DaslState array supplying that input value the delay value is used. If there is a value the delay is ignored.

The last feature is the most powerful. It means you can supply a sequence of data values for the simulation, and when they stop, and they don't all need to stop at the same time, then the simulation takes over.
You could thus use real time data with a simulation where the latest DaslState (with an empty DarlVar array) is set to some time in the future, thus forcing the simulation to generate true predictions.

The only drawback to using events rather than simple arrays of data is that you need to create dummy time tags for any series, like the Logistic map example above, where no real world time is required. This is a small price to pay for the power of this representation form.

As a note, it would be quite possible to arrange Dasl so that it was event driven - i.e. the simulation could be run for every event in the DaslState array, rather than at clocked intervals. This and other additions like trading times are in the pipeline.


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_PAL_H_INCLUDED
#define CONF_PAL_H_INCLUDED

/** Enable Debug to see PRIME messages */
//#define PAL_DBG_PRIME_MESSAGES

/** Enable Swith Off LED 0 each Transmission */
//#define PAL_TX_LED0_SWITCH_OFF

/** Enable Swith Off LED 1 each Transmission */
//#define PAL_TX_LED1_SWITCH_OFF

/** Enable Swith Off LED 0 each Reception */
//#define PAL_RX_LED0_SWITCH_OFF

/** Enable Swith Off LED 1 each Reception */
//#define PAL_RX_LED1_SWITCH_OFF

#endif  /* CONF_PAL_H_INCLUDED */


text:
using namespace std;

// ---------------------------------------------------------------------------|
// Anonymous namespace
// ---------------------------------------------------------------------------|
namespace
{
    /// The maximum time to wait for blocking IO
    const uint16_t MaxReadWaitSeconds = 20;
}

// ---------------------------------------------------------------------------|
namespace YumaTest
{

// ---------------------------------------------------------------------------!
SysTestNCSessionBase::SysTestNCSessionBase(
        const string& user,
        shared_ptr< AbstractYumaOpLogPolicy > policy,
        uint16_t sessionId )
   : AbstractNCSession( policy, sessionId )
   , ncxsock_( -1 )
   , connected_( false )
   , user_( user )
{
}

// ---------------------------------------------------------------------------!
SysTestNCSessionBase::~SysTestNCSessionBase()
{
   if ( connected_ )
   {
       close( ncxsock_ );
   }
}

// ---------------------------------------------------------------------------!
uint16_t SysTestNCSessionBase::injectMessage( const string& queryStr )
{
    // open an output log file
    shared_ptr<ofstream> out = openLogFileForQuery( queryStr );

    // write out the initial query to the logfile
    *out<< queryStr << "\n";

    sendMessage( queryStr );

    // read the reply and log it
    const string replyStr = receiveMessage();
    *out << replyStr << "\n";

    return extractMessageId( queryStr );
}

// ---------------------------------------------------------------------------!
void SysTestNCSessionBase::sendMessage( const string& queryStr )
{
    // TODO: Commonalise with receive ...
    const string fullQuery = queryStr + NC_SSH_END;
    BOOST_REQUIRE_MESSAGE( connected_, "ERROR Not connected to server!" );

    ssize_t remainingLength = fullQuery.length();
    const char* currentPosition = fullQuery.c_str();
    ssize_t sentLength;
    uint16_t numRemainingRetries = MaxReadWaitSeconds * 1000;

    while( remainingLength && numRemainingRetries )
    {
        sentLength = send(currentPosition, remainingLength);

        if ( sentLength ==0 || sentLength == LIBSSH2_ERROR_EAGAIN )
        {
            --numRemainingRetries;
            usleep( 1000 );
        }
        else if ( sentLength < 0 )
        {
                BOOST_FAIL( "Yuma IO Opeartion Failed!" );
        }
        else if ( sentLength > 0 )
        {
            currentPosition += sentLength;
            remainingLength -= sentLength;
        }
    }

    if ( remainingLength )
    {
        BOOST_FAIL( "Failed to send the full message, sent( "
                    << fullQuery.length() - remainingLength
                    << " ) bytes, attempted( " << fullQuery.length() << " )" );
    }
}

// ---------------------------------------------------------------------------!
void SysTestNCSessionBase::sendHelloResponse()
{
    using namespace boost::xpressive;

    // write out the initial query to the logfile
    const string capabilities = receiveMessage();

    // extract the session id as assigned by the remote agent
    sregex sesIdRegex_( sregex::compile( "<session-id>(\\d+)<" ) );
    smatch what;
    BOOST_REQUIRE_MESSAGE( regex_search( capabilities, what, sesIdRegex_ ),
                           "Session ID not found in capabilities message!" );
    sessionId_ = boost::lexical_cast<uint16_t>( what[1] );

    // open an output log file
    const string helloLogFile(
            opLogFilenamePolicy_->generateHelloLog( sessionId_ ) );
    shared_ptr<ofstream> out = openLogFile( helloLogFile );

    // the hello message is a special case and is always added as id 0.
    messageIdToLogMap_[ 0 ] = helloLogFile;

    *out<< capabilities << "\n";

    // verify that the agent is running in the same mode as the test
    string dbName( TestContext::getTestContext()->writeableDbName_ );
    if  ( string::npos == capabilities.find( dbName ) )
    {
        BOOST_FAIL( "Agent is not in '" << dbName << "' mode!" );
    }

    // verify that the agent has the startup capability enabled if required
    bool usingStartup =  TestContext::getTestContext()->usingStartup_;
    if  ( usingStartup && (string::npos == capabilities.find( "startup" )) )
    {
        BOOST_FAIL( "Agent has not enabled the startup capability!" );
    }

    const string helloMsg = NCMessageBuilder().buildHelloMessage();
    sendMessage( helloMsg );
    *out<< helloMsg << "\n";
}

// ---------------------------------------------------------------------------!
string SysTestNCSessionBase::receiveMessage()
{
    BOOST_REQUIRE_MESSAGE( connected_, "ERROR Not connected to server!" );

    const ssize_t maxBufLen = 16*1024;
    shared_ptr<char> buffer( new char[maxBufLen], ArrayDeleter<char>() );
    ssize_t remainingLength = maxBufLen;
    char* currentPosition = buffer.get();
    ssize_t receivedLength;
    uint16_t numRemainingRetries = MaxReadWaitSeconds * 1000;

    // Note: the use case is send a message to the netconf server
    //       then wait for a reply, ergo we will never received more
    //       than one full message at a time.
    while( remainingLength && numRemainingRetries )
    {
        receivedLength = receive(currentPosition, remainingLength);

        if ( receivedLength == 0  || receivedLength == LIBSSH2_ERROR_EAGAIN )
        {
            --numRemainingRetries;
            usleep( 1000 );
        }
        else if ( receivedLength < 0 )
        {
            BOOST_FAIL( "Yuma IO Opeartion Failed!" );
        }
        else if ( receivedLength > 0 )
        {
            *(currentPosition+receivedLength)='\0';
            if ( strstr( currentPosition, NC_SSH_END ) )
            {
                string message( buffer.get() );
                return message;
            }
            currentPosition += receivedLength;
            remainingLength -= receivedLength;
        }
    }

    return string();
}

// ---------------------------------------------------------------------------!
shared_ptr<ofstream> SysTestNCSessionBase::openLogFileForQuery( const string& queryStr )
{
    const string logFilename = newQueryLogFilename( queryStr );

    return openLogFile( logFilename );
}

// ---------------------------------------------------------------------------!
shared_ptr<ofstream> SysTestNCSessionBase::openLogFile( const string& logFilename )
{
    shared_ptr<ofstream> outFile( new ofstream( logFilename.c_str() ) );
    BOOST_REQUIRE_MESSAGE( *outFile, "Failed to open file " << logFilename.c_str() );

    return outFile;
}

} // namespace YumaTest


text:
<!DOCTYPE html>

  <title>Cereal Club</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>
      <a

Home

Cocoa Puffs

Reese's Puffs

Captain Crunch

 Login

Meetings when we feel like it

STREAM upper commons

Different cereals every week

Captain Crunch usually

      Previous

      Next

What We Do

Cereal 1

Cereal 2

       ""

ce·re·al
   /ˈsirēəl/
    noun, a breakfast food made from roasted grain, typically eaten with milk.


text:
using storage::FileSystemURL;

namespace sync_file_system {
namespace drive_backend {

namespace {

class SyncTaskAdapter : public ExclusiveTask {
 public:
  explicit SyncTaskAdapter(const SyncTaskManager::Task& task) : task_(task) {}
  ~SyncTaskAdapter() override {}

  void RunExclusive(const SyncStatusCallback& callback) override {
    task_.Run(callback);
  }

 private:
  SyncTaskManager::Task task_;

  DISALLOW_COPY_AND_ASSIGN(SyncTaskAdapter);
};

}  // namespace

SyncTaskManager::PendingTask::PendingTask() {}

SyncTaskManager::PendingTask::PendingTask(
    const base::Closure& task, Priority pri, int seq)
    : task(task), priority(pri), seq(seq) {}

SyncTaskManager::PendingTask::PendingTask(const PendingTask& other) = default;

SyncTaskManager::PendingTask::~PendingTask() {}

bool SyncTaskManager::PendingTaskComparator::operator()(
    const PendingTask& left,
    const PendingTask& right) const {
  if (left.priority != right.priority)
    return left.priority < right.priority;
  return left.seq > right.seq;
}

SyncTaskManager::SyncTaskManager(
    base::WeakPtr<Client> client,
    size_t maximum_background_task,
    const scoped_refptr<base::SequencedTaskRunner>& task_runner,
    const scoped_refptr<base::SequencedWorkerPool>& worker_pool)
    : client_(client),
      maximum_background_task_(maximum_background_task),
      pending_task_seq_(0),
      task_token_seq_(SyncTaskToken::kMinimumBackgroundTaskTokenID),
      task_runner_(task_runner),
      worker_pool_(worker_pool),
      weak_ptr_factory_(this) {
}

SyncTaskManager::~SyncTaskManager() {
  weak_ptr_factory_.InvalidateWeakPtrs();

  client_.reset();
  token_.reset();
}

void SyncTaskManager::Initialize(SyncStatusCode status) {
  DCHECK(sequence_checker_.CalledOnValidSequence());
  DCHECK(!token_);
  NotifyTaskDone(
      SyncTaskToken::CreateForForegroundTask(
          weak_ptr_factory_.GetWeakPtr(), task_runner_.get()),
      status);
}

void SyncTaskManager::ScheduleTask(
    const tracked_objects::Location& from_here,
    const Task& task,
    Priority priority,
    const SyncStatusCallback& callback) {
  DCHECK(sequence_checker_.CalledOnValidSequence());

  ScheduleSyncTask(from_here,
                   std::unique_ptr<SyncTask>(new SyncTaskAdapter(task)),
                   priority, callback);
}

void SyncTaskManager::ScheduleSyncTask(
    const tracked_objects::Location& from_here,
    std::unique_ptr<SyncTask> task,
    Priority priority,
    const SyncStatusCallback& callback) {
  DCHECK(sequence_checker_.CalledOnValidSequence());

  std::unique_ptr<SyncTaskToken> token(GetToken(from_here, callback));
  if (!token) {
    PushPendingTask(
        base::Bind(&SyncTaskManager::ScheduleSyncTask,
                   weak_ptr_factory_.GetWeakPtr(), from_here,
                   base::Passed(&task), priority, callback),
        priority);
    return;
  }
  RunTask(std::move(token), std::move(task));
}

bool SyncTaskManager::ScheduleTaskIfIdle(
        const tracked_objects::Location& from_here,
        const Task& task,
        const SyncStatusCallback& callback) {
  DCHECK(sequence_checker_.CalledOnValidSequence());

  return ScheduleSyncTaskIfIdle(
      from_here, std::unique_ptr<SyncTask>(new SyncTaskAdapter(task)),
      callback);
}

bool SyncTaskManager::ScheduleSyncTaskIfIdle(
    const tracked_objects::Location& from_here,
    std::unique_ptr<SyncTask> task,
    const SyncStatusCallback& callback) {
  DCHECK(sequence_checker_.CalledOnValidSequence());

  std::unique_ptr<SyncTaskToken> token(GetToken(from_here, callback));
  if (!token)
    return false;
  RunTask(std::move(token), std::move(task));
  return true;
}

// static
void SyncTaskManager::NotifyTaskDone(std::unique_ptr<SyncTaskToken> token,
                                     SyncStatusCode status) {
  DCHECK(token);

  SyncTaskManager* manager = token->manager();
  if (token->token_id() == SyncTaskToken::kTestingTaskTokenID) {
    DCHECK(!manager);
    SyncStatusCallback callback = token->callback();
    token->clear_callback();
    callback.Run(status);
    return;
  }

  if (manager)
    manager->NotifyTaskDoneBody(std::move(token), status);
}

// static
void SyncTaskManager::UpdateTaskBlocker(
    std::unique_ptr<SyncTaskToken> current_task_token,
    std::unique_ptr<TaskBlocker> task_blocker,
    const Continuation& continuation) {
  DCHECK(current_task_token);

  SyncTaskManager* manager = current_task_token->manager();
  if (current_task_token->token_id() == SyncTaskToken::kTestingTaskTokenID) {
    DCHECK(!manager);
    continuation.Run(std::move(current_task_token));
    return;
  }

  if (!manager)
    return;

  std::unique_ptr<SyncTaskToken> foreground_task_token;
  std::unique_ptr<SyncTaskToken> background_task_token;
  std::unique_ptr<TaskLogger::TaskLog> task_log =
      current_task_token->PassTaskLog();
  if (current_task_token->token_id() == SyncTaskToken::kForegroundTaskTokenID)
    foreground_task_token = std::move(current_task_token);
  else
    background_task_token = std::move(current_task_token);

  manager->UpdateTaskBlockerBody(
      std::move(foreground_task_token), std::move(background_task_token),
      std::move(task_log), std::move(task_blocker), continuation);
}

bool SyncTaskManager::IsRunningTask(int64_t token_id) const {
  DCHECK(sequence_checker_.CalledOnValidSequence());

  // If the client is gone, all task should be aborted.
  if (!client_)
    return false;

  if (token_id == SyncTaskToken::kForegroundTaskTokenID)
    return true;

  return running_background_tasks_.find(token_id) !=
         running_background_tasks_.end();
}

void SyncTaskManager::DetachFromSequence() {
  sequence_checker_.DetachFromSequence();
}

bool SyncTaskManager::ShouldTrackTaskToken() const {
  return !worker_pool_ || !worker_pool_->IsShutdownInProgress();
}

void SyncTaskManager::NotifyTaskDoneBody(std::unique_ptr<SyncTaskToken> token,
                                         SyncStatusCode status) {
  DCHECK(sequence_checker_.CalledOnValidSequence());
  DCHECK(token);

  DVLOG(3) << "NotifyTaskDone: " << "finished with status=" << status
           << " (" << SyncStatusCodeToString(status) << ")"
           << " " << token->location().ToString();

  if (token->task_blocker()) {
    dependency_manager_.Erase(token->task_blocker());
    token->clear_task_blocker();
  }

  if (client_) {
    if (token->has_task_log()) {
      token->FinalizeTaskLog(SyncStatusCodeToString(status));
      client_->RecordTaskLog(token->PassTaskLog());
    }
  }

  std::unique_ptr<SyncTask> task;
  SyncStatusCallback callback = token->callback();
  token->clear_callback();
  if (token->token_id() == SyncTaskToken::kForegroundTaskTokenID) {
    token_ = std::move(token);
    task = std::move(running_foreground_task_);
  } else {
    task = std::move(running_background_tasks_[token->token_id()]);
    running_background_tasks_.erase(token->token_id());
  }

  // Acquire the token to prevent a new task to jump into the queue.
  token = std::move(token_);

  bool task_used_network = false;
  if (task)
    task_used_network = task->used_network();

  if (client_)
    client_->NotifyLastOperationStatus(status, task_used_network);

  if (!callback.is_null())
    callback.Run(status);

  // Post MaybeStartNextForegroundTask rather than calling it directly to avoid
  // making the call-chaing longer.
  task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&SyncTaskManager::MaybeStartNextForegroundTask,
                 weak_ptr_factory_.GetWeakPtr(), base::Passed(&token)));
}

void SyncTaskManager::UpdateTaskBlockerBody(
    std::unique_ptr<SyncTaskToken> foreground_task_token,
    std::unique_ptr<SyncTaskToken> background_task_token,
    std::unique_ptr<TaskLogger::TaskLog> task_log,
    std::unique_ptr<TaskBlocker> task_blocker,
    const Continuation& continuation) {
  DCHECK(sequence_checker_.CalledOnValidSequence());

  // Run the task directly if the parallelization is disabled.
  if (!maximum_background_task_) {
    DCHECK(foreground_task_token);
    DCHECK(!background_task_token);
    foreground_task_token->SetTaskLog(std::move(task_log));
    continuation.Run(std::move(foreground_task_token));
    return;
  }

  // Clear existing |task_blocker| from |dependency_manager_| before
  // getting |foreground_task_token|, so that we can avoid dead lock.
  if (background_task_token && background_task_token->task_blocker()) {
    dependency_manager_.Erase(background_task_token->task_blocker());
    background_task_token->clear_task_blocker();
  }

  // Try to get |foreground_task_token|.  If it's not available, wait for
  // current foreground task to finish.
  if (!foreground_task_token) {
    DCHECK(background_task_token);
    foreground_task_token = GetToken(background_task_token->location(),
                                     SyncStatusCallback());
    if (!foreground_task_token) {
      PushPendingTask(
          base::Bind(&SyncTaskManager::UpdateTaskBlockerBody,
                     weak_ptr_factory_.GetWeakPtr(),
                     base::Passed(&foreground_task_token),
                     base::Passed(&background_task_token),
                     base::Passed(&task_log),
                     base::Passed(&task_blocker),
                     continuation),
          PRIORITY_HIGH);
      MaybeStartNextForegroundTask(nullptr);
      return;
    }
  }

  // Check if the task can run as a background task now.
  // If there are too many task running or any other task blocks current
  // task, wait for any other task to finish.
  bool task_number_limit_exceeded =
      !background_task_token &&
      running_background_tasks_.size() >= maximum_background_task_;
  if (task_number_limit_exceeded ||
      !dependency_manager_.Insert(task_blocker.get())) {
    DCHECK(!running_background_tasks_.empty());
    DCHECK(pending_backgrounding_task_.is_null());

    // Wait for NotifyTaskDone to release a |task_blocker|.
    pending_backgrounding_task_ =
        base::Bind(&SyncTaskManager::UpdateTaskBlockerBody,
                   weak_ptr_factory_.GetWeakPtr(),
                   base::Passed(&foreground_task_token),
                   base::Passed(&background_task_token),
                   base::Passed(&task_log),
                   base::Passed(&task_blocker),
                   continuation);
    return;
  }

  if (background_task_token) {
    background_task_token->set_task_blocker(std::move(task_blocker));
  } else {
    tracked_objects::Location from_here = foreground_task_token->location();
    SyncStatusCallback callback = foreground_task_token->callback();
    foreground_task_token->clear_callback();

    background_task_token = SyncTaskToken::CreateForBackgroundTask(
        weak_ptr_factory_.GetWeakPtr(), task_runner_.get(), task_token_seq_++,
        std::move(task_blocker));
    background_task_token->UpdateTask(from_here, callback);
    running_background_tasks_[background_task_token->token_id()] =
        std::move(running_foreground_task_);
  }

  token_ = std::move(foreground_task_token);
  MaybeStartNextForegroundTask(nullptr);
  background_task_token->SetTaskLog(std::move(task_log));
  continuation.Run(std::move(background_task_token));
}

std::unique_ptr<SyncTaskToken> SyncTaskManager::GetToken(
    const tracked_objects::Location& from_here,
    const SyncStatusCallback& callback) {
  DCHECK(sequence_checker_.CalledOnValidSequence());

  if (!token_)
    return nullptr;
  token_->UpdateTask(from_here, callback);
  return std::move(token_);
}

void SyncTaskManager::PushPendingTask(
    const base::Closure& closure, Priority priority) {
  DCHECK(sequence_checker_.CalledOnValidSequence());

  pending_tasks_.push(PendingTask(closure, priority, pending_task_seq_++));
}

void SyncTaskManager::RunTask(std::unique_ptr<SyncTaskToken> token,
                              std::unique_ptr<SyncTask> task) {
  DCHECK(sequence_checker_.CalledOnValidSequence());
  DCHECK(!running_foreground_task_);

  running_foreground_task_ = std::move(task);
  running_foreground_task_->RunPreflight(std::move(token));
}

void SyncTaskManager::MaybeStartNextForegroundTask(
    std::unique_ptr<SyncTaskToken> token) {
  DCHECK(sequence_checker_.CalledOnValidSequence());

  if (token) {
    DCHECK(!token_);
    token_ = std::move(token);
  }

  if (!pending_backgrounding_task_.is_null()) {
    base::Closure closure = pending_backgrounding_task_;
    pending_backgrounding_task_.Reset();
    closure.Run();
    return;
  }

  if (!token_)
    return;

  if (!pending_tasks_.empty()) {
    base::Closure closure = pending_tasks_.top().task;
    pending_tasks_.pop();
    closure.Run();
    return;
  }

  if (client_)
    client_->MaybeScheduleNextTask();
}

}  // namespace drive_backend
}  // namespace sync_file_system


text:
var Controller = require('./Controller'),
    Device = require('../../core/Device'),
    tempArray = [];

function Gamepad(game){
    this._init(game);
}

Gamepad.prototype.constructor = Gamepad;

Gamepad.prototype._init = function(game){
    this.game = game;
    this.isEnabled = false;

    this.axeDeadZone = 0.2;

    this.controllers = [
        new Controller(0, this),
        new Controller(1, this),
        new Controller(2, this),
        new Controller(3, this)
    ];

    this._connectedGamepads = [false, false, false, false];

    this._onGamepadConnectedCallback = function(){};
    this._onGamepadDisconnectedCallback = function(){};
};

Gamepad.prototype.enable = function(value){
    if(!Device.hasGamepad)return this;

    value = (value !== false);

    if(value&&!this.isEnabled) {
        this.isEnabled = true;
    }else if(!value&&this.isEnabled){
        this.isEnabled = false;
    }

    return this;
};

Gamepad.prototype.disable = function(){
    return this.enable(false);
};

Gamepad.prototype._onGamepadConnected = function(e){
    this._onGamepadConnectedCallback(e);
};

Gamepad.prototype._onGamepadDisconnected = function(e){
    this._onGamepadDisconnectedCallback(e);
};

Gamepad.prototype.update = function(gameTime){
    if(!this.isEnabled)return;

    var i, gamepads = this._getGamepads();

    for(i = 0; i < gamepads.length; i++){
        if(gamepads[i]){
            this._connectedGamepads[gamepads[i].index] = true;

            if(!this.getController(gamepads[i].index).isConnected){
                this._connect(gamepads[i]);
            }

            this.getController(gamepads[i].index).updateData(gamepads[i]);

        }
    }

    for(i = 0; i < this._connectedGamepads.length; i++){
        if(!this._connectedGamepads[i] && this.controllers[i].isConnected){
            this._disconnect(i);
        }

        this._connectedGamepads[i] = false;
    }

};

Gamepad.prototype._connect = function(gamepad){
    this.getController(gamepad.index).connect(gamepad);
    this._onGamepadConnected(this.getController(gamepad.index));
};

Gamepad.prototype._disconnect = function(index){
    this._onGamepadDisconnected(this.getController(index));
    this.getController(index).disconnect();
};

Gamepad.prototype._getGamepads = function(){
    var gamepads;
    if(navigator.getGamepads){
        gamepads = navigator.getGamepads();
    }else if(navigator.webkitGetGamepads){
        gamepads = navigator.webkitGetGamepads();
    }

    return gamepads || tempArray;
};

Gamepad.prototype.onConnect = function(callback){
    this._onGamepadConnectedCallback = callback;
    return this;
};

Gamepad.prototype.onDisconnect = function(callback){
    this._onGamepadDisconnectedCallback = callback;
    return this;
};

Gamepad.prototype.getController = function(index){
    return this.controllers[index];
};

module.exports = Gamepad;


text:
package org.hibernate.validator.method;

import java.lang.reflect.Method;
import java.util.Set;

import org.hibernate.validator.method.metadata.TypeDescriptor;

/**
 *

 * Provides an API for method-level constraint validation, based on JSR 303: Bean Validation,
 * Appendix C ("Proposal for method-level validation").
 *

 *

 * The purpose of this API is to provide a facility for the Programming by
 * Contract approach to program design based on the concepts defined by the
 * Bean Validation API. More specifically this means that any Bean Validation
 * constraints (built-in as well as custom constraints) can be used to describe
 *

 *

 *

 * any preconditions that must be met before a method may legally be invoked (by annotating
 * method parameters with constraints) and

 *

 * any postconditions that are guaranteed after a method invocation returns (by
 * annotating methods).

 *

 *

 * These constraints may be declared directly on a method's parameters and/or return values.
 * Alternatively, by annotating method parameters/return values with the special {@link javax.validation.Valid}
 * annotation a recursive validation of those parameters/return
 * values against the constraints defined on their types can be triggered.
 * Consider for instance the method declaration
 *

 *

 *
 *

 * @NotNull
 * @Valid
 * Customer findCustomerByName(@NotNull @Size(min = 5) String name) {
 * 	// ...
 * }
 *

 *

 * Here, the validation engine will check for the following pre- and postconditions (provided
 * the method validation is triggered automatically by some integration layer, see below):
 *

 *

 *
The name parameter is guaranteed to be not null and at least 5 characters
 * long. In particular it is not necessary for the implementor of this method to
 * perform these checks manually.

 *
It is guaranteed that the call yields a non-null object, which itself is
 * valid according to all the bean validation constraints declared on its type.
 * In particular it is not necessary for the caller to perform these
 * checks manually.

 *

 *

 * This service only deals with the actual validation of method
 * parameters/return values itself, but not with the invocation of such
 * a validation. It is expected that this invocation is triggered by an
 * integration layer using AOP or similar method interception facilities such as
 * the JDK's {@link java.lang.reflect.Proxy} API or CDI (
 * "JSR 299: Contexts and Dependency Injection for the JavaTM EE platform"
 * ).
 *

 *

 * Such an integration layer would typically intercept each method call to be
 * validated, validate the call's parameters, proceed with the method invocation
 * and finally validate the invocation's return value. If any of the validation
 * steps yields a non-empty set of constraint violations the integration layer
 * would typically throw a {@link MethodConstraintViolationException} wrapping
 * these violations which in turn guarantees that the call flow only arrives at
 * the method's implementation respectively call site if all pre- respectively
 * postconditions are fulfilled.
 *

 *

 * MethodValidator instances are obtained by
 * {@link javax.validation.Validator#unwrap(Class) unwrapping} a {@link javax.validation.Validator} object:
 *

 *
 *

 * Validator validator = ...;
 * MethodValidator methodValidator = validator.unwrap(MethodValidator.class);
 *

 *

 * Method level validation is (currently) a proprietary feature of Hibernate
 * Validator (HV), so the unwrapped Validator instance
 * must be HV's implementation. In case there are multiple Bean
 * Validation implementations on the classpath, this can be done be explicitly
 * choosing HV as validation provider:
 *

 *
 *

 * MethodValidator methodValidator = Validation.byProvider(HibernateValidator.class)
 * 	.configure()
 * 	.buildValidatorFactory()
 * 	.getValidator()
 * 	.unwrap(MethodValidator.class);
 *

 *

 *

 * If not stated otherwise, none of this interface's methods allow
 * null as parameter value.
 *

 *
 * @author Gunnar Morling
 */
public interface MethodValidator {

	/**
	 * Validates a given parameter of a given method.
	 *
	 * @param <T> The type hosting the invoked method.
	 * @param object The object on which the given method was invoked.
	 * @param method The invoked method for which the given parameter shall be
	 * validated.
	 * @param parameterValue The value provided by the caller for the given method.
	 * @param parameterIndex The index of the parameter to be validated within the given
	 * method's parameter array.
	 * @param groups A - potentially empty - number of validation groups for which
	 * the validation shall be performed. The @link {@link javax.validation.groups.Default}
	 * group will be validated if no group is given.
	 *
	 * @return A set with the constraint violations caused by this validation.
	 *         Will be empty, of no error occurs, but never null.
	 */
	<T> Set<MethodConstraintViolation<T>> validateParameter(T object,
															Method method,
															Object parameterValue,
															int parameterIndex,
															Class<?>... groups);

	/**
	 * Validates all parameters of a given method.
	 *
	 * @param <T> The type hosting the invoked method.
	 * @param object The object on which the given method was invoked.
	 * @param method The invoked method for which the given parameter shall be
	 * validated.
	 * @param parameterValues The values provided by the caller for the given method's
	 * parameters.
	 * @param groups A - potentially empty - number of validation groups for which
	 * the validation shall be performed. The @link {@link javax.validation.groups.Default}
	 * group will be validated if no group is given.
	 *
	 * @return A set with the constraint violations caused by this validation.
	 *         Will be empty, of no error occurs, but never null.
	 */
	<T> Set<MethodConstraintViolation<T>> validateAllParameters(T object, Method method, Object[] parameterValues, Class<?>... groups);

	/**
	 * Validates the return value of a given method.
	 *
	 * @param <T> The type hosting the invoked method.
	 * @param object The object on which the given method was invoked.
	 * @param method The invoked method for which the given return value shall be
	 * validated.
	 * @param returnValue The value returned by the invoked method.
	 * @param groups A - potentially empty - number of validation groups for which
	 * the validation shall be performed. The @link {@link javax.validation.groups.Default}
	 * group will be validated if no group is given.
	 *
	 * @return A set with the constraint violations caused by this validation.
	 *         Will be empty, of no error occurs, but never null.
	 */
	<T> Set<MethodConstraintViolation<T>> validateReturnValue(T object,
															  Method method, Object returnValue, Class<?>... groups);

	/**
	 * Returns a descriptor providing access to constraint-related meta data for
	 * the given type.
	 *
	 * @param clazz The type of interest.
	 *
	 * @return A descriptor for the given type, will never be null.
	 */
	TypeDescriptor getConstraintsForType(Class<?> clazz);
}


text:
namespace YAF.Controls
{

    public partial class ForumWelcome
    {

        /// <summary>
        /// TimeNow-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label TimeNow;

        /// <summary>
        /// LastVisitHolder-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.PlaceHolder LastVisitHolder;

        /// <summary>
        /// TimeLastVisit-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label TimeLastVisit;
    }
}


text:
package net.boreeas.riotapi.rest;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import net.boreeas.riotapi.constants.PlayerSide;
import net.boreeas.riotapi.com.riotgames.platform.game.QueueType;
import net.boreeas.riotapi.com.riotgames.platform.game.GameMode;
import net.boreeas.riotapi.com.riotgames.platform.game.GameType;

import java.util.ArrayList;
import java.util.List;

/**
 * Created on 4/14/2014.
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Game {
    private int championId;
    private long createDate;
    private List<Player> fellowPlayers = new ArrayList<>();
    private long gameId;
    private String gameMode;
    private String gameType;
    private boolean invalid;
    private int ipEarned;
    private int level;
    private int mapId;
    private int spell1;
    private int spell2;
    private Stats stats;
    private String subType;
    private int teamId;

    public GameMode getGameMode() {
        return GameMode.getByName(gameMode);
    }

    public GameType getGameType() {
        return GameType.getByName(gameType);
    }

    public QueueType getSubType() {
        return QueueType.getByName(subType);
    }

    public PlayerSide getTeam() {
        return PlayerSide.getById(teamId);
    }
}