text:
package org.elasticsearch.index.similarity;

import com.google.common.collect.Maps;
import org.elasticsearch.ElasticSearchIllegalArgumentException;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.Scopes;
import org.elasticsearch.common.inject.assistedinject.FactoryProvider;
import org.elasticsearch.common.inject.multibindings.MapBinder;
import org.elasticsearch.common.settings.Settings;

import java.util.Map;

/**
 * {@link SimilarityModule} is responsible gathering registered and configured {@link SimilarityProvider}
 * implementations and making them available through the {@link SimilarityLookupService} and {@link SimilarityService}.
 *
 * New {@link SimilarityProvider} implementations can be registered through {@link #addSimilarity(String, Class)}
 * while existing Providers can be referenced through Settings under the {@link #SIMILARITY_SETTINGS_PREFIX} prefix
 * along with the "type" value.  For example, to reference the {@link BM25SimilarityProvider}, the configuration
 * <tt>"index.similarity.my_similarity.type : "BM25"</tt> can be used.
 */
public class SimilarityModule extends AbstractModule {

    public static final String SIMILARITY_SETTINGS_PREFIX = "index.similarity";

    private final Settings settings;
    private final Map<String, Class<? extends SimilarityProvider>> similarities = Maps.newHashMap();

    public SimilarityModule(Settings settings) {
        this.settings = settings;
    }

    /**
     * Registers the given {@link SimilarityProvider} with the given name
     *
     * @param name Name of the SimilarityProvider
     * @param similarity SimilarityProvider to register
     */
    public void addSimilarity(String name, Class<? extends SimilarityProvider> similarity) {
        similarities.put(name, similarity);
    }

    @Override
    protected void configure() {
        Map<String, Class<? extends SimilarityProvider>> providers = Maps.newHashMap(similarities);

        Map<String, Settings> similaritySettings = settings.getGroups(SIMILARITY_SETTINGS_PREFIX);
        for (Map.Entry<String, Settings> entry : similaritySettings.entrySet()) {
            String name = entry.getKey();
            Settings settings = entry.getValue();

            Class<? extends SimilarityProvider> type =
                    settings.getAsClass("type", null, "org.elasticsearch.index.similarity.", "SimilarityProvider");
            if (type == null) {
                throw new ElasticSearchIllegalArgumentException("SimilarityProvider [" + name + "] must have an associated type");
            }
            providers.put(name, type);
        }

        MapBinder<String, SimilarityProvider.Factory> similarityBinder =
                MapBinder.newMapBinder(binder(), String.class, SimilarityProvider.Factory.class);

        for (Map.Entry<String, Class<? extends SimilarityProvider>> entry : providers.entrySet()) {
            similarityBinder.addBinding(entry.getKey()).toProvider(FactoryProvider.newFactory(SimilarityProvider.Factory.class, entry.getValue())).in(Scopes.SINGLETON);
        }

        for (PreBuiltSimilarityProvider.Factory factory : Similarities.listFactories()) {
            if (!providers.containsKey(factory.name())) {
                similarityBinder.addBinding(factory.name()).toInstance(factory);
            }
        }

        bind(SimilarityLookupService.class).asEagerSingleton();
        bind(SimilarityService.class).asEagerSingleton();
    }
}


text:
using AzureFromTheTrenches.Commanding.Abstractions;

namespace AzureFromTheTrenches.Commanding.Implementation
{
    class OptionsProvider : IOptionsProvider
    {
        public OptionsProvider(IOptions options)
        {
            Options = options;
        }

        public IOptions Options { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.spark.sql.catalyst.expressions

import java.sql.{Date, Timestamp}

import scala.collection.immutable.HashSet

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.RandomDataGenerator
import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow}
import org.apache.spark.sql.catalyst.analysis.TypeCheckResult
import org.apache.spark.sql.catalyst.encoders.ExamplePointUDT
import org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext
import org.apache.spark.sql.catalyst.parser.CatalystSqlParser
import org.apache.spark.sql.catalyst.util.{ArrayData, GenericArrayData}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._

class PredicateSuite extends SparkFunSuite with ExpressionEvalHelper {

  private def booleanLogicTest(
    name: String,
    op: (Expression, Expression) => Expression,
    truthTable: Seq[(Any, Any, Any)]): Unit = {
    test(s"3VL $name") {
      truthTable.foreach {
        case (l, r, answer) =>
          val expr = op(NonFoldableLiteral.create(l, BooleanType),
            NonFoldableLiteral.create(r, BooleanType))
          checkEvaluation(expr, answer)
      }
    }
  }

  // scalastyle:off
  /**
   * Checks for three-valued-logic.  Based on:
   * http://en.wikipedia.org/wiki/Null_(SQL)#Comparisons_with_NULL_and_the_three-valued_logic_.283VL.29
   * I.e. in flat cpo "False -> Unknown -> True",
   *   OR is lowest upper bound,
   *   AND is greatest lower bound.
   * p       q       p OR q  p AND q  p = q
   * True    True    True    True     True
   * True    False   True    False    False
   * True    Unknown True    Unknown  Unknown
   * False   True    True    False    False
   * False   False   False   False    True
   * False   Unknown Unknown False    Unknown
   * Unknown True    True    Unknown  Unknown
   * Unknown False   Unknown False    Unknown
   * Unknown Unknown Unknown Unknown  Unknown
   *
   * p       NOT p
   * True    False
   * False   True
   * Unknown Unknown
   */
  // scalastyle:on

  test("3VL Not") {
    val notTrueTable =
      (true, false) ::
        (false, true) ::
        (null, null) :: Nil
    notTrueTable.foreach { case (v, answer) =>
      checkEvaluation(Not(NonFoldableLiteral.create(v, BooleanType)), answer)
    }
    checkConsistencyBetweenInterpretedAndCodegen(Not, BooleanType)
  }

  test("AND, OR, EqualTo, EqualNullSafe consistency check") {
    checkConsistencyBetweenInterpretedAndCodegen(And, BooleanType, BooleanType)
    checkConsistencyBetweenInterpretedAndCodegen(Or, BooleanType, BooleanType)
    DataTypeTestUtils.propertyCheckSupported.foreach { dt =>
      checkConsistencyBetweenInterpretedAndCodegen(EqualTo, dt, dt)
      checkConsistencyBetweenInterpretedAndCodegen(EqualNullSafe, dt, dt)
    }
  }

  booleanLogicTest("AND", And,
    (true, true, true) ::
      (true, false, false) ::
      (true, null, null) ::
      (false, true, false) ::
      (false, false, false) ::
      (false, null, false) ::
      (null, true, null) ::
      (null, false, false) ::
      (null, null, null) :: Nil)

  booleanLogicTest("OR", Or,
    (true, true, true) ::
      (true, false, true) ::
      (true, null, true) ::
      (false, true, true) ::
      (false, false, false) ::
      (false, null, null) ::
      (null, true, true) ::
      (null, false, null) ::
      (null, null, null) :: Nil)

  booleanLogicTest("=", EqualTo,
    (true, true, true) ::
      (true, false, false) ::
      (true, null, null) ::
      (false, true, false) ::
      (false, false, true) ::
      (false, null, null) ::
      (null, true, null) ::
      (null, false, null) ::
      (null, null, null) :: Nil)

  private def checkInAndInSet(in: In, expected: Any): Unit = {
    // expecting all in.list are Literal or NonFoldableLiteral.
    checkEvaluation(in, expected)
    checkEvaluation(InSet(in.value, HashSet() ++ in.list.map(_.eval())), expected)
  }

  test("basic IN/INSET predicate test") {
    checkInAndInSet(In(NonFoldableLiteral.create(null, IntegerType), Seq(Literal(1),
      Literal(2))), null)
    checkInAndInSet(In(NonFoldableLiteral.create(null, IntegerType),
      Seq(NonFoldableLiteral.create(null, IntegerType))), null)
    checkInAndInSet(In(NonFoldableLiteral.create(null, IntegerType), Seq.empty), null)
    checkInAndInSet(In(Literal(1), Seq.empty), false)
    checkInAndInSet(In(Literal(1), Seq(NonFoldableLiteral.create(null, IntegerType))), null)
    checkInAndInSet(In(Literal(1), Seq(Literal(1), NonFoldableLiteral.create(null, IntegerType))),
      true)
    checkInAndInSet(In(Literal(2), Seq(Literal(1), NonFoldableLiteral.create(null, IntegerType))),
      null)
    checkInAndInSet(In(Literal(1), Seq(Literal(1), Literal(2))), true)
    checkInAndInSet(In(Literal(2), Seq(Literal(1), Literal(2))), true)
    checkInAndInSet(In(Literal(3), Seq(Literal(1), Literal(2))), false)

    checkEvaluation(
      And(In(Literal(1), Seq(Literal(1), Literal(2))), In(Literal(2), Seq(Literal(1),
        Literal(2)))),
      true)
    checkEvaluation(
      And(InSet(Literal(1), HashSet(1, 2)), InSet(Literal(2), Set(1, 2))),
      true)

    val ns = NonFoldableLiteral.create(null, StringType)
    checkInAndInSet(In(ns, Seq(Literal("1"), Literal("2"))), null)
    checkInAndInSet(In(ns, Seq(ns)), null)
    checkInAndInSet(In(Literal("a"), Seq(ns)), null)
    checkInAndInSet(In(Literal("^Ba*n"), Seq(Literal("^Ba*n"), ns)), true)
    checkInAndInSet(In(Literal("^Ba*n"), Seq(Literal("aa"), Literal("^Ba*n"))), true)
    checkInAndInSet(In(Literal("^Ba*n"), Seq(Literal("aa"), Literal("^n"))), false)
  }

  test("IN with different types") {
    def testWithRandomDataGeneration(dataType: DataType, nullable: Boolean): Unit = {
      val maybeDataGen = RandomDataGenerator.forType(dataType, nullable = nullable)
      // Actually we won't pass in unsupported data types, this is a safety check.
      val dataGen = maybeDataGen.getOrElse(
        fail(s"Failed to create data generator for type $dataType"))
      val inputData = Seq.fill(10) {
        val value = dataGen.apply()
        def cleanData(value: Any) = value match {
          case d: Double if d.isNaN => 0.0d
          case f: Float if f.isNaN => 0.0f
          case _ => value
        }
        value match {
          case s: Seq[_] => s.map(cleanData(_))
          case m: Map[_, _] =>
            val pair = m.unzip
            val newKeys = pair._1.map(cleanData(_))
            val newValues = pair._2.map(cleanData(_))
            newKeys.zip(newValues).toMap
          case _ => cleanData(value)
        }
      }
      val input = inputData.map(NonFoldableLiteral.create(_, dataType))
      val expected = if (inputData(0) == null) {
        null
      } else if (inputData.slice(1, 10).contains(inputData(0))) {
        true
      } else if (inputData.slice(1, 10).contains(null)) {
        null
      } else {
        false
      }
      checkInAndInSet(In(input(0), input.slice(1, 10)), expected)
    }

    val atomicTypes = DataTypeTestUtils.atomicTypes.filter { t =>
      RandomDataGenerator.forType(t).isDefined &&
        !t.isInstanceOf[DecimalType] && !t.isInstanceOf[BinaryType]
    } ++ Seq(DecimalType.USER_DEFAULT)

    val atomicArrayTypes = atomicTypes.map(ArrayType(_, containsNull = true))

    // Basic types:
    for (
        dataType <- atomicTypes;
        nullable <- Seq(true, false)) {
      testWithRandomDataGeneration(dataType, nullable)
    }

    // Array types:
    for (
        arrayType <- atomicArrayTypes;
        nullable <- Seq(true, false)
        if RandomDataGenerator.forType(arrayType.elementType, arrayType.containsNull).isDefined) {
      testWithRandomDataGeneration(arrayType, nullable)
    }

    // Struct types:
    for (
        colOneType <- atomicTypes;
        colTwoType <- atomicTypes;
        nullable <- Seq(true, false)) {
      val structType = StructType(
        StructField("a", colOneType) :: StructField("b", colTwoType) :: Nil)
      testWithRandomDataGeneration(structType, nullable)
    }

    // In doesn't support map type and will fail the analyzer.
    val map = Literal.create(create_map(1 -> 1), MapType(IntegerType, IntegerType))
    In(map, Seq(map)).checkInputDataTypes() match {
      case TypeCheckResult.TypeCheckFailure(msg) =>
        assert(msg.contains("function in does not support ordering on type map"))
      case _ => fail("In should not work on map type")
    }
  }

  test("switch statements in InSet for bytes, shorts, ints, dates") {
    val byteValues = Set[Any](1.toByte, 2.toByte, Byte.MinValue, Byte.MaxValue)
    val shortValues = Set[Any](-10.toShort, 20.toShort, Short.MinValue, Short.MaxValue)
    val intValues = Set[Any](20, -100, 30, Int.MinValue, Int.MaxValue)
    val dateValues = Set[Any](
      CatalystTypeConverters.convertToCatalyst(Date.valueOf("2017-01-01")),
      CatalystTypeConverters.convertToCatalyst(Date.valueOf("1950-01-02")))

    def check(presentValue: Expression, absentValue: Expression, values: Set[Any]): Unit = {
      require(presentValue.dataType == absentValue.dataType)

      val nullLiteral = Literal(null, presentValue.dataType)

      checkEvaluation(InSet(nullLiteral, values), expected = null)
      checkEvaluation(InSet(nullLiteral, values + null), expected = null)
      checkEvaluation(InSet(presentValue, values), expected = true)
      checkEvaluation(InSet(presentValue, values + null), expected = true)
      checkEvaluation(InSet(absentValue, values), expected = false)
      checkEvaluation(InSet(absentValue, values + null), expected = null)
    }

    def checkAllTypes(): Unit = {
      check(presentValue = Literal(2.toByte), absentValue = Literal(3.toByte), byteValues)
      check(presentValue = Literal(Byte.MinValue), absentValue = Literal(5.toByte), byteValues)
      check(presentValue = Literal(20.toShort), absentValue = Literal(-14.toShort), shortValues)
      check(presentValue = Literal(Short.MaxValue), absentValue = Literal(30.toShort), shortValues)
      check(presentValue = Literal(20), absentValue = Literal(-14), intValues)
      check(presentValue = Literal(Int.MinValue), absentValue = Literal(2), intValues)
      check(
        presentValue = Literal(Date.valueOf("2017-01-01")),
        absentValue = Literal(Date.valueOf("2017-01-02")),
        dateValues)
      check(
        presentValue = Literal(Date.valueOf("1950-01-02")),
        absentValue = Literal(Date.valueOf("2017-10-02")),
        dateValues)
    }

    withSQLConf(SQLConf.OPTIMIZER_INSET_SWITCH_THRESHOLD.key -> "0") {
      checkAllTypes()
    }
    withSQLConf(SQLConf.OPTIMIZER_INSET_SWITCH_THRESHOLD.key -> "20") {
      checkAllTypes()
    }
  }

  test("SPARK-22501: In should not generate codes beyond 64KB") {
    val N = 3000
    val sets = (1 to N).map(i => Literal(i.toDouble))
    checkEvaluation(In(Literal(1.0D), sets), true)
  }

  test("SPARK-22705: In should use less global variables") {
    val ctx = new CodegenContext()
    In(Literal(1.0D), Seq(Literal(1.0D), Literal(2.0D))).genCode(ctx)
    assert(ctx.inlinedMutableStates.isEmpty)
  }

  test("IN/INSET: binary") {
    val onetwo = Literal(Array(1.toByte, 2.toByte))
    val three = Literal(Array(3.toByte))
    val threefour = Literal(Array(3.toByte, 4.toByte))
    val nl = NonFoldableLiteral.create(null, onetwo.dataType)
    val hS = Seq(Literal(Array(1.toByte, 2.toByte)), Literal(Array(3.toByte)))
    val nS = Seq(Literal(Array(1.toByte, 2.toByte)), Literal(Array(3.toByte)),
      NonFoldableLiteral.create(null, onetwo.dataType))
    checkInAndInSet(In(onetwo, hS), true)
    checkInAndInSet(In(three, hS), true)
    checkInAndInSet(In(three, nS), true)
    checkInAndInSet(In(threefour, hS), false)
    checkInAndInSet(In(threefour, nS), null)
    checkInAndInSet(In(nl, hS), null)
    checkInAndInSet(In(nl, nS), null)
  }

  test("IN/INSET: struct") {
    val oneA = Literal.create((1, "a"))
    val twoB = Literal.create((2, "b"))
    val twoC = Literal.create((2, "c"))
    val nl = NonFoldableLiteral.create(null, oneA.dataType)
    val hS = Seq(Literal.create((1, "a")), Literal.create((2, "b")))
    val nS = Seq(Literal.create((1, "a")), Literal.create((2, "b")),
      NonFoldableLiteral.create(null, oneA.dataType))
    checkInAndInSet(In(oneA, hS), true)
    checkInAndInSet(In(twoB, hS), true)
    checkInAndInSet(In(twoB, nS), true)
    checkInAndInSet(In(twoC, hS), false)
    checkInAndInSet(In(twoC, nS), null)
    checkInAndInSet(In(nl, hS), null)
    checkInAndInSet(In(nl, nS), null)
  }

  test("IN/INSET: array") {
    val onetwo = Literal.create(Seq(1, 2))
    val three = Literal.create(Seq(3))
    val threefour = Literal.create(Seq(3, 4))
    val nl = NonFoldableLiteral.create(null, onetwo.dataType)
    val hS = Seq(Literal.create(Seq(1, 2)), Literal.create(Seq(3)))
    val nS = Seq(Literal.create(Seq(1, 2)), Literal.create(Seq(3)),
      NonFoldableLiteral.create(null, onetwo.dataType))
    checkInAndInSet(In(onetwo, hS), true)
    checkInAndInSet(In(three, hS), true)
    checkInAndInSet(In(three, nS), true)
    checkInAndInSet(In(threefour, hS), false)
    checkInAndInSet(In(threefour, nS), null)
    checkInAndInSet(In(nl, hS), null)
    checkInAndInSet(In(nl, nS), null)
  }

  private case class MyStruct(a: Long, b: String)
  private case class MyStruct2(a: MyStruct, b: Array[Int])
  private val udt = new ExamplePointUDT

  private val smallValues =
    Seq(1.toByte, 1.toShort, 1, 1L, Decimal(1), Array(1.toByte), Date.valueOf("2000-01-01"),
      new Timestamp(1), "a", 1f, 1d, 0f, 0d, false, Array(1L, 2L))
      .map(Literal(_)) ++ Seq(Literal.create(MyStruct(1L, "b")),
      Literal.create(MyStruct2(MyStruct(1L, "a"), Array(1, 1))),
      Literal.create(ArrayData.toArrayData(Array(1.0, 2.0)), udt))
  private val largeValues =
    Seq(2.toByte, 2.toShort, 2, 2L, Decimal(2), Array(2.toByte), Date.valueOf("2000-01-02"),
      new Timestamp(2), "b", 2f, 2d, Float.NaN, Double.NaN, true, Array(2L, 1L))
      .map(Literal(_)) ++ Seq(Literal.create(MyStruct(2L, "b")),
      Literal.create(MyStruct2(MyStruct(1L, "a"), Array(1, 2))),
      Literal.create(ArrayData.toArrayData(Array(1.0, 3.0)), udt))

  private val equalValues1 =
    Seq(1.toByte, 1.toShort, 1, 1L, Decimal(1), Array(1.toByte), Date.valueOf("2000-01-01"),
      new Timestamp(1), "a", 1f, 1d, Float.NaN, Double.NaN, true, Array(1L, 2L))
      .map(Literal(_)) ++ Seq(Literal.create(MyStruct(1L, "b")),
      Literal.create(MyStruct2(MyStruct(1L, "a"), Array(1, 1))),
      Literal.create(ArrayData.toArrayData(Array(1.0, 2.0)), udt))
  private val equalValues2 =
    Seq(1.toByte, 1.toShort, 1, 1L, Decimal(1), Array(1.toByte), Date.valueOf("2000-01-01"),
      new Timestamp(1), "a", 1f, 1d, Float.NaN, Double.NaN, true, Array(1L, 2L))
      .map(Literal(_)) ++ Seq(Literal.create(MyStruct(1L, "b")),
      Literal.create(MyStruct2(MyStruct(1L, "a"), Array(1, 1))),
      Literal.create(ArrayData.toArrayData(Array(1.0, 2.0)), udt))

  test("BinaryComparison consistency check") {
    DataTypeTestUtils.ordered.foreach { dt =>
      checkConsistencyBetweenInterpretedAndCodegen(LessThan, dt, dt)
      checkConsistencyBetweenInterpretedAndCodegen(LessThanOrEqual, dt, dt)
      checkConsistencyBetweenInterpretedAndCodegen(GreaterThan, dt, dt)
      checkConsistencyBetweenInterpretedAndCodegen(GreaterThanOrEqual, dt, dt)
    }
  }

  test("BinaryComparison: lessThan") {
    for (i <- 0 until smallValues.length) {
      checkEvaluation(LessThan(smallValues(i), largeValues(i)), true)
      checkEvaluation(LessThan(equalValues1(i), equalValues2(i)), false)
      checkEvaluation(LessThan(largeValues(i), smallValues(i)), false)
    }
  }

  test("BinaryComparison: LessThanOrEqual") {
    for (i <- 0 until smallValues.length) {
      checkEvaluation(LessThanOrEqual(smallValues(i), largeValues(i)), true)
      checkEvaluation(LessThanOrEqual(equalValues1(i), equalValues2(i)), true)
      checkEvaluation(LessThanOrEqual(largeValues(i), smallValues(i)), false)
    }
  }

  test("BinaryComparison: GreaterThan") {
    for (i <- 0 until smallValues.length) {
      checkEvaluation(GreaterThan(smallValues(i), largeValues(i)), false)
      checkEvaluation(GreaterThan(equalValues1(i), equalValues2(i)), false)
      checkEvaluation(GreaterThan(largeValues(i), smallValues(i)), true)
    }
  }

  test("BinaryComparison: GreaterThanOrEqual") {
    for (i <- 0 until smallValues.length) {
      checkEvaluation(GreaterThanOrEqual(smallValues(i), largeValues(i)), false)
      checkEvaluation(GreaterThanOrEqual(equalValues1(i), equalValues2(i)), true)
      checkEvaluation(GreaterThanOrEqual(largeValues(i), smallValues(i)), true)
    }
  }

  test("BinaryComparison: EqualTo") {
    for (i <- 0 until smallValues.length) {
      checkEvaluation(EqualTo(smallValues(i), largeValues(i)), false)
      checkEvaluation(EqualTo(equalValues1(i), equalValues2(i)), true)
      checkEvaluation(EqualTo(largeValues(i), smallValues(i)), false)
    }
  }

  test("BinaryComparison: EqualNullSafe") {
    for (i <- 0 until smallValues.length) {
      checkEvaluation(EqualNullSafe(smallValues(i), largeValues(i)), false)
      checkEvaluation(EqualNullSafe(equalValues1(i), equalValues2(i)), true)
      checkEvaluation(EqualNullSafe(largeValues(i), smallValues(i)), false)
    }
  }

  test("BinaryComparison: null test") {
    // Use -1 (default value for codegen) which can trigger some weird bugs, e.g. SPARK-14757
    val normalInt = Literal(-1)
    val nullInt = NonFoldableLiteral.create(null, IntegerType)
    val nullNullType = Literal.create(null, NullType)

    def nullTest(op: (Expression, Expression) => Expression): Unit = {
      checkEvaluation(op(normalInt, nullInt), null)
      checkEvaluation(op(nullInt, normalInt), null)
      checkEvaluation(op(nullInt, nullInt), null)
      checkEvaluation(op(nullNullType, nullNullType), null)
    }

    nullTest(LessThan)
    nullTest(LessThanOrEqual)
    nullTest(GreaterThan)
    nullTest(GreaterThanOrEqual)
    nullTest(EqualTo)

    checkEvaluation(EqualNullSafe(normalInt, nullInt), false)
    checkEvaluation(EqualNullSafe(nullInt, normalInt), false)
    checkEvaluation(EqualNullSafe(nullInt, nullInt), true)
    checkEvaluation(EqualNullSafe(nullNullType, nullNullType), true)
  }

  test("EqualTo on complex type") {
    val array = new GenericArrayData(Array(1, 2, 3))
    val struct = create_row("a", 1L, array)

    val arrayType = ArrayType(IntegerType)
    val structType = new StructType()
      .add("1", StringType)
      .add("2", LongType)
      .add("3", ArrayType(IntegerType))

    val projection = UnsafeProjection.create(
      new StructType().add("array", arrayType).add("struct", structType))

    val unsafeRow = projection(InternalRow(array, struct))

    val unsafeArray = unsafeRow.getArray(0)
    val unsafeStruct = unsafeRow.getStruct(1, 3)

    checkEvaluation(EqualTo(
      Literal.create(array, arrayType),
      Literal.create(unsafeArray, arrayType)), true)

    checkEvaluation(EqualTo(
      Literal.create(struct, structType),
      Literal.create(unsafeStruct, structType)), true)
  }

  test("EqualTo double/float infinity") {
    val infinity = Literal(Double.PositiveInfinity)
    checkEvaluation(EqualTo(infinity, infinity), true)
  }

  test("SPARK-22693: InSet should not use global variables") {
    val ctx = new CodegenContext
    InSet(Literal(1), Set(1, 2, 3, 4)).genCode(ctx)
    assert(ctx.inlinedMutableStates.isEmpty)
  }

  test("SPARK-24007: EqualNullSafe for FloatType and DoubleType might generate a wrong result") {
    checkEvaluation(EqualNullSafe(Literal(null, FloatType), Literal(-1.0f)), false)
    checkEvaluation(EqualNullSafe(Literal(-1.0f), Literal(null, FloatType)), false)
    checkEvaluation(EqualNullSafe(Literal(null, DoubleType), Literal(-1.0d)), false)
    checkEvaluation(EqualNullSafe(Literal(-1.0d), Literal(null, DoubleType)), false)
  }

  test("Interpreted Predicate should initialize nondeterministic expressions") {
    val interpreted = Predicate.create(LessThan(Rand(7), Literal(1.0)))
    interpreted.initialize(0)
    assert(interpreted.eval(new UnsafeRow()))
  }

  test("SPARK-24872: Replace taking the $symbol with $sqlOperator in BinaryOperator's" +
    " toString method") {
    val expression = CatalystSqlParser.parseExpression("id=1 or id=2").toString()
    val expected = "(('id = 1) OR ('id = 2))"
    assert(expression == expected)
  }

  val row0 = create_row(null)
  val row1 = create_row(false)
  val row2 = create_row(true)

  test("istrue and isnottrue") {
    checkEvaluation(IsTrue(Literal.create(null, BooleanType)), false, row0)
    checkEvaluation(IsNotTrue(Literal.create(null, BooleanType)), true, row0)
    checkEvaluation(IsTrue(Literal.create(false, BooleanType)), false, row1)
    checkEvaluation(IsNotTrue(Literal.create(false, BooleanType)), true, row1)
    checkEvaluation(IsTrue(Literal.create(true, BooleanType)), true, row2)
    checkEvaluation(IsNotTrue(Literal.create(true, BooleanType)), false, row2)
    IsTrue(Literal.create(null, IntegerType)).checkInputDataTypes() match {
      case TypeCheckResult.TypeCheckFailure(msg) =>
        assert(msg.contains("argument 1 requires boolean type"))
    }
  }

  test("isfalse and isnotfalse") {
    checkEvaluation(IsFalse(Literal.create(null, BooleanType)), false, row0)
    checkEvaluation(IsNotFalse(Literal.create(null, BooleanType)), true, row0)
    checkEvaluation(IsFalse(Literal.create(false, BooleanType)), true, row1)
    checkEvaluation(IsNotFalse(Literal.create(false, BooleanType)), false, row1)
    checkEvaluation(IsFalse(Literal.create(true, BooleanType)), false, row2)
    checkEvaluation(IsNotFalse(Literal.create(true, BooleanType)), true, row2)
    IsFalse(Literal.create(null, IntegerType)).checkInputDataTypes() match {
      case TypeCheckResult.TypeCheckFailure(msg) =>
        assert(msg.contains("argument 1 requires boolean type"))
    }
  }

  test("isunknown and isnotunknown") {
    checkEvaluation(IsUnknown(Literal.create(null, BooleanType)), true, row0)
    checkEvaluation(IsNotUnknown(Literal.create(null, BooleanType)), false, row0)
    IsUnknown(Literal.create(null, IntegerType)).checkInputDataTypes() match {
      case TypeCheckResult.TypeCheckFailure(msg) =>
        assert(msg.contains("argument 1 requires boolean type"))
    }
  }

  test("SPARK-29100: InSet with empty input set") {
    val row = create_row(1)
    val inSet = InSet(BoundReference(0, IntegerType, true), Set.empty)
    checkEvaluation(inSet, false, row)
  }
}


text:
using System;
using System.Runtime.InteropServices;

namespace Vestris.VMWareComLib
{
    /// <summary>
    /// A COM interface to <see cref="Vestris.VMWareLib.VMWareSnapshot" />.
    /// </summary>
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    [Guid("BBE59046-66AF-458c-AD14-3F25546193E9")]
    public interface IVMWareSnapshot
    {
        void BeginReplay();
        void BeginReplay2(int powerOnOptions, int timeoutInSeconds);
        string Description { get; }
        string DisplayName { get; }
        void EndReplay();
        void EndReplay2(int timeoutInSeconds);
        bool IsReplayable { get; }
        IVMWareSnapshot Parent { get; }
        string Path { get; }
        int PowerState { get; }
        void RemoveSnapshot();
        void RemoveSnapshot2(int timeoutInSeconds);
        void RevertToSnapshot();
        void RevertToSnapshot2(int powerOnOptions, int timeoutInSeconds);
        IVMWareSnapshotCollection ChildSnapshots { get; }
        object ChildSnapshotsList { get; }
    }
}


text:
// cocos2d imports
#import "Scheduler.h"
#import "ccMacros.h"

//
// Timer
//
@implementation Timer

@synthesize interval;

-(id) init
{
	NSException* myException = [NSException
								exceptionWithName:@"TimerInvalid"
								reason:@"Invalid init for Timer. Use initWithTarget:sel:"
								userInfo:nil];
	@throw myException;
}

+(id) timerWithTarget:(id) t selector:(SEL)s
{
	return [[[self alloc] initWithTarget:t selector:s] autorelease];
}

+(id) timerWithTarget:(id) t selector:(SEL)s interval:(ccTime) i
{
	return [[[self alloc] initWithTarget:t selector:s interval:i] autorelease];
}

-(id) initWithTarget:(id) t selector:(SEL)s
{
	return [self initWithTarget:t selector:s interval:0];
}

-(id) initWithTarget:(id) t selector:(SEL)s interval:(ccTime) seconds
{
	if( (self=[super init]) ) {
#ifdef DEBUG
		NSMethodSignature *sig = [t methodSignatureForSelector:s];
		NSAssert(sig !=0 , @"Signature not found for selector - does it have the following form? -(void) name: (ccTime) dt");
#endif

		target = [t retain];
		selector = s;
		impMethod = (TICK_IMP) [t methodForSelector:s];

		interval = seconds;
	}
	return self;
}

-(void) dealloc
{
	CCLOG( @"deallocing %@", self);

	[target release];
	[super dealloc];
}

-(void) fire: (ccTime) dt
{
	elapsed += dt;
	if( elapsed >= interval ) {
		impMethod(target, selector, elapsed);
		elapsed = 0;
	}
}
@end

//
// Scheduler
//
@implementation Scheduler

static Scheduler *sharedScheduler;

+ (Scheduler *)sharedScheduler
{
	@synchronized([Scheduler class])
	{
		if (!sharedScheduler)
			[[Scheduler alloc] init];

		return sharedScheduler;
	}
	// to avoid compiler warning
	return nil;
}

+(id)alloc
{
	@synchronized([Scheduler class])
	{
		NSAssert(sharedScheduler == nil, @"Attempted to allocate a second instance of a singleton.");
		sharedScheduler = [super alloc];
		return sharedScheduler;
	}
	// to avoid compiler warning
	return nil;
}

- (id) init
{
	if( ! (self=[super init]) )
		return nil;

	scheduledMethods = [[NSMutableArray arrayWithCapacity:50] retain];
	methodsToRemove = [[NSMutableArray arrayWithCapacity:20] retain];
	methodsToAdd = [[NSMutableArray arrayWithCapacity:20] retain];

	return self;
}

- (void) dealloc
{
	CCLOG( @"deallocing %@", self);
	[scheduledMethods release];
	[methodsToRemove release];
	[methodsToAdd release];

	[super dealloc];
}

-(Timer*) scheduleTarget: (id) target selector:(SEL)sel
{
	Timer *t = [Timer timerWithTarget:target selector:sel];

	[methodsToAdd addObject: t];

	return t;
}

-(Timer*) scheduleTarget: (id) target selector:(SEL)sel interval:(ccTime) i
{
	Timer *t = [Timer timerWithTarget:target selector:sel];

	[t setInterval:i];

	[methodsToAdd addObject: t];

	return t;
}

-(void) scheduleTimer: (Timer*) t
{
	// it is possible that sometimes (in transitions in particular) an scene unschedule a timer
	// and before the timer is deleted, it is re-scheduled
	if( [methodsToRemove containsObject:t] )
	{
		[methodsToRemove removeObject:t];
		return;
	}

	if( [scheduledMethods containsObject:t] || [methodsToAdd containsObject:t]) {
		NSLog(@"Scheduler.schedulerTimer: timer %@ already scheduled", t);
		NSException* myException = [NSException
									exceptionWithName:@"SchedulerTimerAlreadyScheduled"
									reason:@"Scheduler.scheduleTimer already scheduled"
									userInfo:nil];
		@throw myException;
	}

	[methodsToAdd addObject: t];
}

-(void) unscheduleTimer: (Timer*) t;
{
	// someone wants to remove it before it was added
	if( [methodsToAdd containsObject:t] ) {
		[methodsToAdd removeObject:t];
		return;
	}

	if( ![scheduledMethods containsObject:t] ) {
		NSLog(@"Scheduler.unscheduleTimer: timer not scheduled");
		NSException* myException = [NSException
									exceptionWithName:@"SchedulerTimerNotFound"
									reason:@"Scheduler.unscheduleTimer not found"
									userInfo:nil];
		@throw myException;
	}

	[methodsToRemove addObject:t];
}

-(void) tick: (ccTime) dt
{
	for( id k in methodsToRemove )
		[scheduledMethods removeObject:k];

	[methodsToRemove removeAllObjects];

	for( id k in methodsToAdd )
		[scheduledMethods addObject:k];
	[methodsToAdd removeAllObjects];

	for( Timer *t in scheduledMethods )
		[t fire: dt];
}
@end


text:
title: Cumpleaños de la biblio 🎂
layout: post-novedad
categoria: noticia
featured: false
image_url: /img/cumple-biblio.png
meta: Hoy hace 3 años se creo el espacio de la Biblioteca Paraje Entre Ríos que funciona gracias al trabajo y el aporte de las y los vecinos del paraje
---

Hoy hace 3 años se creo el espacio de la Biblioteca Paraje Entre Ríos que funciona gracias al trabajo y el aporte de las y los vecinos del paraje.

Los invitamos a que se acerquen, a que busquen y encuentren un libro y si quieren, hasta pueden regalarle uno para que sea compartido con todos!

Les deseamos un feliz cumpleaños a quienes le dedican su tiempo y amor a un espacio tan importante como es la biblio.


text:
package org.darcstarsolutions.twitter.test.configurations;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Created by mharris on 6/7/15.
 */

@ConfigurationProperties(prefix = "twitter")
public class TwitterConfiguration {
    private String consumerKey;
    private String consumerSecret;
    private String accessToken;
    private String accessTokenSecret;

    public String getConsumerKey() {
        return consumerKey;
    }

    public void setConsumerKey(String consumerKey) {
        this.consumerKey = consumerKey;
    }

    public String getConsumerSecret() {
        return consumerSecret;
    }

    public void setConsumerSecret(String consumerSecret) {
        this.consumerSecret = consumerSecret;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public String getAccessTokenSecret() {
        return accessTokenSecret;
    }

    public void setAccessTokenSecret(String accessTokenSecret) {
        this.accessTokenSecret = accessTokenSecret;
    }
}


text:
layout: post
title: "VSCode and Markdown Monster with Powershell"
tags:
  - PowerShell
  - Blogging
date: "2017-05-06 13:00"
published: true
---
A few years back, i created a post showing you how to add an Alias to PowerShell [to easily start Sublime Text from a PowerShell command line][1] . This worked well, but this is 2017 (that post is from 2012!) and my daily text editor has changed. I have moved to [Visual Studio Code][2] for most of my daily work. It works well 95% of the time. I still use [Visual Studio Pro][5] for C# Development, but for quick fixes and work on, say [Go][6] or smaller edits, Code is great. For blogging, on the other hand, I am trying out [MarkDown Monster][3] but code still has some nice features. We will see how tests go.

Anyway, to upgrade the post, and to be able to use VS Code and MarkDown Monster from your PowerShell command line, I added the following:

    Set-Alias code "C:\Program Files (x86)\Microsoft VS Code\Code.exe"
    Set-Alias mm "C:\Program Files (x86)\Markdown Monster\MarkdownMonster.exe"

You can either run this each time you open PowerShell (a bit of pain) or you can add it to your `Microsoft.PowerShell_profile.ps1` which lives in your `Document\WindowsPowerShell` folder. If you dont have one, just create the file, add that piece of text, and next time you open PowerShell, you are good to go.

In my case, i am actually in the [Visual Studio Code Insiders][4] group, so my alias is:

    Set-Alias code "C:\Program Files (x86)\Microsoft VS Code Insiders\Code - Insiders.exe"

When these are set (and you have restarted your PowerShell windows), you can now run the following commands:

    code filename.txt
    code folder
    mm filename.txt

VSCode will open either files or folders, but it seems Markdown Monster only opens files.

[1]:https://www.tiernanotoole.ie/2012/08/30/SublimeText-With-Powershell.html
[2]:https://code.visualstudio.com/
[3]:https://markdownmonster.west-wind.com/
[4]:https://code.visualstudio.com/insiders
[5]:https://www.visualstudio.com/vs/
[6]:https://golang.org/


text:
			Site de Pronostics
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
				Menu
			</button>

					Accueil

					Inscription

					Connexion


text:
package com.google.common.escape;
public class ArrayBasedCharEscaperTest_gwt extends com.google.gwt.junit.client.GWTTestCase {
@Override public String getModuleName() {
  return "com.google.common.escape.testModule";
}
public void testDeleteUnsafeChars() throws Exception {
  com.google.common.escape.ArrayBasedCharEscaperTest testCase = new com.google.common.escape.ArrayBasedCharEscaperTest();
  testCase.testDeleteUnsafeChars();
}

public void testReplacementPriority() throws Exception {
  com.google.common.escape.ArrayBasedCharEscaperTest testCase = new com.google.common.escape.ArrayBasedCharEscaperTest();
  testCase.testReplacementPriority();
}

public void testSafeRange() throws Exception {
  com.google.common.escape.ArrayBasedCharEscaperTest testCase = new com.google.common.escape.ArrayBasedCharEscaperTest();
  testCase.testSafeRange();
}

public void testSafeRange_maxLessThanMin() throws Exception {
  com.google.common.escape.ArrayBasedCharEscaperTest testCase = new com.google.common.escape.ArrayBasedCharEscaperTest();
  testCase.testSafeRange_maxLessThanMin();
}
}


text: package java.com.siegerstein.wfw.framework;


text:
body {
  border: 1px solid red;
}

input {
    -moz-appearance: none !important;
    background-color: white;
    color: #222222;
}

textarea {
    -moz-appearance: none !important;
    background-color: white;
    color: #222222;
}

select {
    -moz-appearance: none !important;
    background-color: white;
    color: #222222;
}


text:
require 'spec_helper'

RSpec.describe Metrics::Dashboard::Annotations::DeleteService do
  let(:user) { create(:user) }
  let(:service_instance) { described_class.new(user, annotation) }

  shared_examples 'executed annotation deletion' do
    it 'returns success response', :aggregate_failures do
      expect(annotation).to receive(:destroy).and_return(true)

      response = service_instance.execute

      expect(response[:status]).to be :success
    end
  end

  shared_examples 'prevented annotation deletion' do |message|
    it 'returns error response', :aggregate_failures do
      response = service_instance.execute

      expect(response[:status]).to be :error
      expect(response[:message]).to eql message
    end

    it 'does not change db state' do
      expect(annotation).not_to receive(:destroy)

      service_instance.execute
    end
  end

  describe '.execute' do
    context 'with specific environment' do
      let(:annotation) { create(:metrics_dashboard_annotation, environment: environment) }
      let(:environment) { create(:environment) }

      context 'with anonymous user' do
        it_behaves_like 'prevented annotation deletion', 'You are not authorized to delete this annotation'
      end

      context 'with maintainer user' do
        before do
          environment.project.add_maintainer(user)
        end

        it_behaves_like 'executed annotation deletion'

        context 'annotation failed to delete' do
          it 'returns error response', :aggregate_failures do
            allow(annotation).to receive(:destroy).and_return(false)

            response = service_instance.execute

            expect(response[:status]).to be :error
            expect(response[:message]).to eql 'Annotation has not been deleted'
          end
        end
      end
    end

    context 'with specific cluster' do
      let(:annotation) { create(:metrics_dashboard_annotation, cluster: cluster, environment: nil) }

      context 'with anonymous user' do
        let(:cluster) { create(:cluster, :project) }

        it_behaves_like 'prevented annotation deletion', 'You are not authorized to delete this annotation'
      end

      context 'with maintainer user' do
        let(:cluster) { create(:cluster, :project) }

        before do
          cluster.project.add_maintainer(user)
        end

        it_behaves_like 'executed annotation deletion'
      end

      context 'with owner user' do
        let(:cluster) { create(:cluster, :group) }

        before do
          cluster.group.add_owner(user)
        end

        it_behaves_like 'executed annotation deletion'
      end
    end
  end
end


text:
<?php

use app\widgets\main\TeamMemberWidget;
use app\widgets\main\SpecialProject;
use app\assets\MainAsset;
use yii\helpers\Url;

//
// TODO: update localization algorythm
// NOTE! See https://github.com/samdark/yii2-cookbook/blob/master/book/i18n-selecting-application-language.md
//
$pageName = 'Main';
if (Yii::$app->language == 'ru-RU') {
    $pageName = 'Главная';
}

$this->title = 'Health & Help - ' . $pageName;

MainAsset::register($this);

?>

Благотворительный проект

            В проекте Health&Help почти сотня людей объединилась для того, чтобы дать гватемальским индейцам
            Майя доступ к базовой медицинской помощи. Работаем, чтобы помогать людям, а для покупки
            лекарств, расходных материалов и оборудования нам нужна ваша помощь. Даже сто рублей могут
            помочь вылечить человека

                <form class="common-donation_form" action="https://money.yandex.ru/quickpay/confirm.xml">
                     <input type="hidden" name="receiver" value="410012180500847" />
                     <input type="hidden" name="formcomment" value="Проект «Health & Help»" />
                     <input type="hidden" name="short-dest" value="Проект «Health & Help»" />
                     <input type="hidden" name="quickpay-form" value="donate" />
                     <input type="hidden" name="targets" value="Пожертвование на уставные цели" />
                     <input type="hidden" readonly="readonly" name="paymentType" value="PC" data-type="string" />

                     <input type="hidden" readonly="readonly" name="sum" value="" data-type="number" />

                    <input value="1000 ₽" class="common-donation_amount" size="1"/>

                    <button type="submit" class="common-donation_donate-button">Пожертвовать</button>
                </form>

Уже собрано

1 888 676 ₽

Проект на Generosity

                    Платеж через систему

                    Яндекс-деньги

    <a href="<?= Url::toRoute(['team']) ?>">Вся команда

    <?php foreach ($members as $member ) {?>
        <?= TeamMemberWidget::widget($member) ?>
    <?php } ?>

Наши спецпроекты

<?php foreach ($specialProjects as $specialProject) { ?>

        <?= SpecialProject::widget($specialProject) ?>

<?php } ?>


text:
// This file is automatically generated.

package adila.db;

/*
 * LG Optimus PAD LTE
 *
 * DEVICE: express
 * MODEL: LG-LU8300
 */
final class express_lg2dlu8300 {
    public static final String DATA = "LG|Optimus PAD LTE|";
}


text:
<?php

namespace PommProject\Foundation\Converter;

use PommProject\Foundation\Session\Session;

/**
 * PgString
 *
 * Converter for strings types.
 *
 * @package     Foundation
 * @copyright   2014 - 2015 Grégoire HUBERT
 * @author      Grégoire HUBERT
 * @license     X11 {@link http://opensource.org/licenses/mit-license.php}
 * @see         ConverterInterface
 */
class PgString implements ConverterInterface
{
    /**
     * toPg
     *
     * @see ConverterInterface
     */
    public function toPg($data, $type, Session $session)
    {
        return $data !== null
            ? sprintf("%s %s",  $type, $session->getConnection()->escapeLiteral($data))
            : sprintf("NULL::%s", $type)
            ;
    }

    /**
     * toPgStandardFormat
     *
     * @see ConverterInterface
     */
    public function toPgStandardFormat($data, $type, Session $session)
    {
        return $data;
    }

    /**
     * @see ConverterInterface
     */
    public function fromPg($data, $type, Session $session)
    {
        return $data !== null ? (string) $data : null;
    }
}


text:
package ru.job4j.tree;

import org.junit.Test;

import java.util.List;

import static org.junit.Assert.*;

/**
 * Test class Node.
 *
 * @author Ekaterina Turka (ekaterina2rka@gmail.com)
 * @since 07.02.2018
 */
public class NodeTest {
    @Test
    public void whenNodeWithoutChildThenLeavesEmpty() {
        Node<Integer> node = new Node<>(1);
        List<Node<Integer>> leaves = node.leaves();
        assertTrue(leaves.isEmpty());
    }

    @Test
    public void whenAddChildTwoThenLeavesContainsTwo() {
        Node<Integer> node = new Node<>(1), leaf = new Node<>(2);
        node.add(leaf);
        List<Node<Integer>> leaves = node.leaves();
        assertTrue(leaves.contains(leaf));
    }

    @Test
    public void whenCompareNodeWithSameValueThenEqValueTrue() {
        Node<Integer> node = new Node<>(1);
        assertTrue(node.eqValue(1));
    }

    @Test
    public void whenCompareNodeWithDifferentValueThenEqValueFalse() {
        Node<Integer> node = new Node<>(1);
        assertFalse(node.eqValue(2));
    }
}


text:
package com.hellhounds.battlefree.game.effects;

import com.hellhounds.battlefree.game.units.Unit;

public class CrushEffect extends Effect {

    public CrushEffect(int value, boolean friendly, boolean multiple)
    {
        super(EffectType.CRUSH, value, friendly, multiple);
    }

    @Override
    public void applyEffect(Unit source)
    {
        Unit[] targets = getTargets();

        for(Unit target : targets)
        {
            int rawDamage = getNumericalValue();
            int armor = target.getArmor();
            int health = target.getCurrentHealth();

            int calcDamage = rawDamage - armor;
            health  = health - calcDamage;

            if(calcDamage >= 0)
            {
                target.setArmor(0);
                target.setCurrentHealth(health - calcDamage);
            }
            else
            {
                target.setArmor(-rawDamage);
            }

            target.setCurrentHealth(health);

            System.out.format("%s's %s crushed %s's %s for %d%s\n",
                    source.getOwner().getUsername(),
                    source.getName(),
                    target.getOwner().getUsername(),
                    target.getName(),
                    calcDamage,
                    (armor > 0) ? " (" + armor + " blocked by armor)" :  "");
        }
    }
}


text:
using System;
using SuccincT.Unions;

namespace SuccincT.PatternMatchers
{
    public interface IActionMatcher<T1, T2>
    {
        IActionWithHandler<IActionMatcher<T1, T2>, T1, T2> With(Either<T1, Any> value1, Either<T2, Any> value2);
        IActionWhereHandler<IActionMatcher<T1, T2>, T1, T2> Where(Func<T1, T2, bool> expression);
        IActionMatcherAfterElse Else(Action<T1, T2> action);
        IActionMatcherAfterElse IgnoreElse();
        void Exec();
    }
}


text:
<?php

require_once (dirname(__FILE__).'/../../../GameUserManager.php');

class UserController extends AbstractController {

    private $gameUserManager;

    function __construct(){
        $this->gameUserManager = new GameUserManager();
    }

    public function get($request)
    {
        if(count($request->url_elements) == 2)
        {
            $methodName = $request->url_elements[1];

            switch ($methodName) {
                    case 'balance':
                        return $this->GetBalance();
                        break;
                    case 'reset-balance':
                        return $this->resetBalance();
                        break;
                    case 'buy-kg-coffe':
                        return $this->buyKgCoffee();
                        break;
                    case 'get-details':
                        return $this->getDetails();
                        break;
                    case 'get-top-stats':
                        return $this->getTopStats();
                        break;

                    default:
                        return;
                        break;
                }
        } else {
            return;
        }
    }

    public function post($request)
    {
        if(count($request->url_elements) == 2)
        {
            $settingName = $request->url_elements[1];

            switch ($settingName) {
                    case 'update-data':
                        return $this->updateData($request->parameters['opened_months'], $request->parameters['customers_in_queue'],$request->parameters['total_coffe_kg'],$request->parameters['total_drink'],$request->parameters['balance'],$request->parameters['buy_total_coffe_kg']);
                        break;

                    default:
                        return;
                        break;
            }

        } else {
            return;
        }
    }

    public function GetBalance (){
        return $this->gameUserManager->GetUserBalance();
    }

    /**
    * Reset all game information
    * @return {string}
    */
    public function resetBalance(){
        return $this->gameUserManager->globalReset();
    }

    public function buyKgCoffee(){
        return $this->gameUserManager->buyKgCoffee();
    }

    public function updateData($opened_months, $customers_in_queue,$total_coffe_kg,$total_drink,$balance,$buy_total_coffe_kg){
            return $this->gameUserManager->updateData($opened_months, $customers_in_queue,$total_coffe_kg,$total_drink,$balance,$buy_total_coffe_kg);

    }

    public function getDetails(){
           return $this->gameUserManager->getDetails();
    }

    public function getTopStats(){
        return $this->gameUserManager->getTopStats();
    }
}


text:
package ol.layer;

import jsinterop.annotations.JsType;

import ol.Map;
import ol.source.Source;

/**
 * Abstract base class; normally only used for creating subclasses and not
 * instantiated in apps. A visual representation of raster or vector map data.
 * Layers group together those properties that pertain to how the data is to be
 * displayed, irrespective of the source of that data.
 *
 * Layers are usually added to a map with {@link ol.Map#addLayer}. Components
 * like {@link ol.interaction.Select} use unmanaged layers internally. These
 * unmanaged layers are associated with the map using
 * {@link ol.layer.Layer#setMap} instead.
 *
 * A generic `change` event is fired when the state of the source changes.
 *
 * @author Tino Desjardins
 *
 */
@JsType(isNative = true)
public abstract class Layer extends Base {

    /**
     * Gets the source for this layer.
     *
     * @return {@link Source}
     */
    public native <T extends Source> T getSource();

    /**
     * Sets the layer to be rendered on top of other layers on a map. The map
     * will not manage this layer in its layers collection, and the callback in
     * {@link ol.Map#forEachLayerAtPixel} will receive `null` as layer. This is
     * useful for temporary layers. To remove an unmanaged layer from the map,
     * use `#setMap(null)`.
     *
     * To add the layer to a map and have it managed by the map, use
     * {@link ol.Map#addLayer} instead.
     *
     * @param map
     *            Map.
     */
    public native void setMap(Map map);

    /**
     * Sets the source for this layer. If not provided to the constructor, the
     * source can be set by calling layer.setSource(source) after construction.
     *
     * @param source
     *            {@link Source}
     */
    public native void setSource(Source source);

}


text:
package cmm

import (
	"fmt"
	"os"
	"reflect"
	"testing"
	"unsafe"
)

func TestUnZipTar(t *testing.T) {
	os.RemoveAll("./test")
	fmt.Println(UnZipTar("./testdata/test.tar.gz", "./"))
}

func CArrayToGoSlice(begin uintptr, size int) []byte {
	var theGoSlice []byte
	sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&theGoSlice)))
	sliceHeader.Cap = size
	sliceHeader.Len = size
	sliceHeader.Data = begin
	return theGoSlice
}

func TestGetPhysicsInterfaces(t *testing.T) {
	fmt.Println(GetPhysicsInterfaces(true))
}


text:
package cz.zcu.kiv.mobile.logger.devices.fora.glucose;

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

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.LimitLine.LimitLabelPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import cz.zcu.kiv.mobile.logger.Application;
import cz.zcu.kiv.mobile.logger.R;
import cz.zcu.kiv.mobile.logger.data.database.GlucoseMeasurementTable;
import cz.zcu.kiv.mobile.logger.data.database.loaders.AAnalysisLoader;
import cz.zcu.kiv.mobile.logger.devices.AAnalysisFragment;

public class GlucoseMeterAnalysisFragment extends AAnalysisFragment {
  private static final int LOADER_ID = 72;

  private static final int COLOR_LIMIT_HIGH = Color.RED;
  private static final int COLOR_LIMIT_OPTIMAL = Color.GREEN;
  private static final int COLOR_GM = Color.CYAN;

  private LineChart chart;

  private TextView tvTrend;
  private TextView tvAverage;
  private TextView tvCount;
  private TextView tvMax;
  private TextView tvMaxTime;
  private TextView tvMin;
  private TextView tvMinTime;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = super.onCreateView(inflater, container, savedInstanceState);
    chart = (LineChart) rootView.findViewById(R.id.chart);
    tvTrend = (TextView) rootView.findViewById(R.id.tv_stats_trend);
    tvAverage = (TextView) rootView.findViewById(R.id.tv_stats_average);
    tvCount = (TextView) rootView.findViewById(R.id.tv_stats_count);
    tvMax = (TextView) rootView.findViewById(R.id.tv_stats_max);
    tvMaxTime = (TextView) rootView.findViewById(R.id.tv_stats_max_time);
    tvMin = (TextView) rootView.findViewById(R.id.tv_stats_min);
    tvMinTime = (TextView) rootView.findViewById(R.id.tv_stats_min_time);
    initChart();
    return rootView;
  }

  private void initChart() {
    chart.setNoDataText(Application.getStringResource(R.string.no_data));
    chart.setDragEnabled(true);
    chart.setDrawGridBackground(true);

    YAxis leftAxis = chart.getAxisLeft();
    leftAxis.setDrawLimitLinesBehindData(true);
    LimitLine ll = new LimitLine(110f, Application.getStringResource(R.string.gm_level_high));
    ll.setLineColor(COLOR_LIMIT_HIGH);
    ll.setLineWidth(4f);
    ll.setTextColor(COLOR_LIMIT_HIGH);
    ll.setTextSize(10f);
    ll.setLabelPosition(LimitLabelPosition.POS_RIGHT);
    leftAxis.addLimitLine(ll);
    ll = new LimitLine(72f, Application.getStringResource(R.string.gm_level_optimal));
    ll.setLineColor(COLOR_LIMIT_OPTIMAL);
    ll.setLineWidth(4f);
    ll.setTextColor(COLOR_LIMIT_OPTIMAL);
    ll.setTextSize(10f);
    ll.setLabelPosition(LimitLabelPosition.POS_RIGHT);
    leftAxis.addLimitLine(ll);
  }

  @Override
  protected int getLoaderID() {
    return LOADER_ID;
  }

  @Override
  protected int getLayoutResourceID() {
    return R.layout.fragment_analysis_gm;
  }

  @Override
  protected AAnalysisLoader getAnalysisLoader(Context context, long userID) {
    return new GMeasurementAnalysisLoader(context, userID);
  }

  @Override
  protected void analyze(Cursor cursor) throws Exception {
    List<Entry> valGl = new ArrayList<Entry>();
    List<String> labels = new ArrayList<String>();

    int iGl = cursor.getColumnIndex(GlucoseMeasurementTable.COLUMN_GLUCOSE);
    int iTime = cursor.getColumnIndex(GlucoseMeasurementTable.COLUMN_TIME);

    int count = 0;
    int prev = 0;
    int trend = 0;
    int sum = 0;
    int max = Integer.MIN_VALUE;
    long maxTime = 0L;
    int min = Integer.MAX_VALUE;
    long minTime = 0L;

    while(cursor.moveToNext()) {
      int gl = cursor.getInt(iGl);
      long time = cursor.getLong(iTime);

      if(gl > max) {
        max = gl;
        maxTime = time;
      }
      if(gl < min) {
        min = gl;
        minTime = time;
      }
      sum += gl;
      trend = gl - prev;
      prev = gl;

      valGl.add(new Entry(gl, count));
      labels.add(timeFormat.format(new Date(time)));
      count++;
    }

    if(count > 1) {
      tvTrend.setText(trend > 0 ? "▲" : trend < 0 ? "▼" : "-");
    }
    if(count > 0) {
      tvAverage.setText(String.valueOf(sum / count));
      tvCount.setText(String.valueOf(count));
      tvMax.setText(String.valueOf(max));
      tvMaxTime.setText(timeFormat.format(new Date(maxTime)));
      tvMin.setText(String.valueOf(min));
      tvMinTime.setText(timeFormat.format(new Date(minTime)));
    }

    LineDataSet setGl = new LineDataSet(valGl, Application.getStringResource(R.string.gm_legend_glucose));
      setGl.setColor(COLOR_GM);
      setGl.setCircleColor(COLOR_GM);

    List<LineDataSet> dataSets = new ArrayList<LineDataSet>();
      dataSets.add(setGl);

    LineData values = new LineData(labels, dataSets);
    chart.setData(values);
    chart.invalidate();
  }

  public static Fragment newInstance(long userID) {
    Fragment instance = new GlucoseMeterAnalysisFragment();
      Bundle arguments = new Bundle(1);
        arguments.putLong(ARG_USER_ID, userID);
      instance.setArguments(arguments);
    return instance;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AutoSniper.ClientWPF.WPFModules.Views
{
    /// <summary>
    /// ActiveTradeControl.xaml 的交互逻辑
    /// </summary>
    public partial class ActiveTradeControl : UserControl
    {
        public ActiveTradeControl()
        {
            InitializeComponent();
        }
    }
}


text:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Delicious Recipes</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>


text:
<?php

namespace dkuzmenchuk\Rethinkdb;

use dkuzmenchuk\Rethinkdb\Console\Migrations\MigrateMakeCommand;
use dkuzmenchuk\Rethinkdb\Console\Model\ModelMakeCommand;
use dkuzmenchuk\Rethinkdb\Eloquent\Model;
use dkuzmenchuk\Rethinkdb\Migrations\MigrationCreator;
use Illuminate\Support\ServiceProvider;

class RethinkdbServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        Model::setConnectionResolver($this->app['db']);
        Model::setEventDispatcher($this->app['events']);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->resolving('db', function ($db) {
            $db->extend('rethinkdb', function ($config) {
                return new Connection($config);
            });
        });

        $this->app->singleton('command.rethink-migrate.make', function ($app) {

            $creator = new MigrationCreator($app['files']);
            $composer = $app['composer'];

            return new MigrateMakeCommand($creator, $composer);
        });

        $this->commands('command.rethink-migrate.make');

        $this->app->singleton('command.rethink-model.make', function ($app) {
            return new ModelMakeCommand($app['files']);
        });

        $this->commands('command.rethink-model.make');
    }

    public function provides()
    {
        return ['command.rethink-migrate.make', 'command.rethink-model.make'];
    }
}


text:
require_relative "test_helper"

class TestController < Webrb::Controller
  def index
    "Hello!"
  end
end
class TestApp < Webrb::Application
  def get_controller_and_action env
    [TestController, "index"]
  end
end

class WebrbAppTest < Test::Unit::TestCase
  include Rack::Test::Methods

  def app
    TestApp.new
  end

  def test_request
    get "/"

    assert last_response.ok?
    assert last_response.body['Hello']
  end
end


text:
import Logger from "../";

describe("Logger", function() {
  const l = new Logger(true, false);

  it("dbug", function() {
    l.dbug("testing dbug");
  });

  it("should handle JSON type object", function() {
    l.dbug({ testing: { object: ["dbug", 3] } });
  });
});


text:
package org.apache.struts.action;

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

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

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import model.Contact;
import service.IContactService;

public class ActionSearchContact extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		SearchContactForm sf = (SearchContactForm) form;
		@SuppressWarnings("resource")
		ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
		IContactService service = (service.IContactService) context.getBean("service");
		List<Contact> listResults = new ArrayList<Contact>(service.searchContacts(sf.getNom()));
//		sf.setListResults(listResults);
		request.setAttribute("listResults", listResults);

		return mapping.findForward("viewSearch");
	}

}


text:
template <class> class RefPtr;
class b;
class A {
  typedef b a;
};
template <class c> class e { RefPtr<c> d; };
template <class> class f {};
class g {
  f<e<int>> h;
};
class b : g {};
A Servo_Element_GetSnapshot();


text:
package com.leo.util;

import android.os.Build;

/**
 * Class containing some static utility methods.
 */
public class Utils {

    public static boolean hasFroyo() {
        // Can use static final constants like FROYO, declared in later versions
        // of the OS since they are inlined at compile time. This is guaranteed
        // behavior.
        return Build.VERSION.SDK_INT >= 8;// Build.VERSION_CODES.FROYO;
    }

    public static boolean hasGingerbread() {
        return Build.VERSION.SDK_INT >= 9;// Build.VERSION_CODES.GINGERBREAD;
    }

    public static boolean hasHoneycomb() {
        return Build.VERSION.SDK_INT >= 11;// Build.VERSION_CODES.HONEYCOMB;
    }

    public static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= 12;// Build.VERSION_CODES.HONEYCOMB_MR1;
    }

    public static boolean hasJellyBean() {
        return Build.VERSION.SDK_INT >= 16;// Build.VERSION_CODES.JELLY_BEAN;
    }

    public static boolean hasJellyBeamMR1() {
        return Build.VERSION.SDK_INT >= 17;// android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
    }

    public static boolean hasJellyBeamMR2() {
        return false;
        // return Build.VERSION.SDK_INT >=
        // android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
    }

    public static boolean hasKITKAT() {
        return false;
        // return Build.VERSION.SDK_INT >=
        // android.os.Build.VERSION_CODES.KITKAT;
    }
}


text:
// <memory> Forward declarations -*- C++ -*-

// Copyright (C) 2001-2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

/** @file bits/memoryfwd.h
 *  This is an internal header file, included by other library headers.
 *  Do not attempt to use it directly. @headername{memory}
 */

#ifndef _MEMORYFWD_H
#define _MEMORYFWD_H 1

#pragma GCC system_header

#include <bits/c++config.h>

namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION

  /**
   * @defgroup allocators Allocators
   * @ingroup memory
   *
   * Classes encapsulating memory operations.
   *
   * @{
   */

  template<typename>
    class allocator;

  template<>
    class allocator<void>;

  /// Declare uses_allocator so it can be specialized in \<queue\> etc.
  template<typename, typename>
    struct uses_allocator;

  /// @} group memory

_GLIBCXX_END_NAMESPACE_VERSION
} // namespace std

#endif


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BsDropdownModule } from "ngx-bootstrap/dropdown";
import { TabsModule } from 'ngx-bootstrap/tabs';

/* common */
import { AppFooterComponent } from './common/app-footer/app-footer.component';
import { AddNavComponent } from './common/add-nav/add-nav.component';
import { SidebarComponent } from './common/sidebar/sidebar.component';
import { SearchFilterPipe } from './common/search-input/search-filter.pipe';
import { SearchInputComponent } from './common/search-input/search-input.component';
import { BreadCrumbsComponent } from './common/breadCrumbs/breadCrumbs.component';
import { ComponentsPageComponent } from './common/components-page/components-page.component';
import { ConstructionPageComponent } from './common/construction-page/construction-page.component';
import { ThemesComponent } from './common/themes/themes.component';
/* docs */
import { DemoSectionComponent } from './demo-section/demo-section.component';
import { ContentSection } from './models/content-section.model';
import { ExamplesComponent, ExamplesComponentModule } from './demo-section-components/demo-examples-section/index';
import { ApiSectionsComponent, ApiSectionsComponentModule } from './demo-section-components/demo-api-section/index';
import { DocsSectionComponent } from './docs-section/docs-section.component';
import { NgApiDocClassComponent, NgApiDocComponent, NgApiDocConfigComponent, NgApiDocModule } from './api-docs/index';
import { LandingComponent } from './common/landing/landing.component';
import { DocumentationComponent } from './common/documentation/documentation.component';
import { DiscoverComponent } from './common/discover/discover.component';
import { SchematicsComponent } from './common/schematics/schematics.component';
import { TopMenuComponent } from './common/top-menu/top-menu.component';

/* export */
export {
  NgApiDocModule,
  NgApiDocComponent,
  NgApiDocClassComponent,
  NgApiDocConfigComponent
} from './api-docs/index';
export {
  ExamplesComponent,
  ExamplesComponentModule
} from './demo-section-components/demo-examples-section/index';
export {
  ApiSectionsComponent,
  ApiSectionsComponentModule
} from './demo-section-components/demo-api-section/index';
export { DemoSectionComponent } from './demo-section/demo-section.component';
export { DocsSectionComponent } from './docs-section/docs-section.component';
export { SampleBoxComponent } from './api-docs/sample-box/sample-box.component';
export { ContentSection } from './models/content-section.model';
export { AppFooterComponent } from './common/app-footer/app-footer.component';
export { AddNavComponent } from './common/add-nav/add-nav.component';
export { SidebarComponent } from './common/sidebar/sidebar.component';
export { SearchFilterPipe } from './common/search-input/search-filter.pipe';
export { SearchInputComponent } from './common/search-input/search-input.component';
export { LandingComponent } from './common/landing/landing.component';
export { DocumentationComponent } from './common/documentation/documentation.component';
export { DiscoverComponent } from './common/discover/discover.component';
export { SchematicsComponent } from './common/schematics/schematics.component';
export { StyleManager } from './theme/style-manager';
export { ThemeStorage } from './theme/theme-storage';
export { NgApiDoc } from './api-docs/api-docs.model';
export { TopMenuComponent } from './common/top-menu/top-menu.component';
export { Analytics } from './api-docs/analytics/analytics';
export { DOCS_TOKENS } from './tokens/docs-routes-token';
export { SIDEBAR_ROUTES } from './tokens/docs-sidebar-routes-token';
export { SidebarRoutesStructure } from './models/sidebar-routes.model';
export { ComponentsPageComponent } from './common/components-page/components-page.component';
export { ConstructionPageComponent } from './common/construction-page/construction-page.component';
export { ThemesComponent } from './common/themes/themes.component';
import { RouterModule } from '@angular/router';

@NgModule({
  declarations: [
    DemoSectionComponent,
    SidebarComponent,
    AppFooterComponent,
    SearchFilterPipe,
    AddNavComponent,
    DocsSectionComponent,
    LandingComponent,
    DocumentationComponent,
    DiscoverComponent,
    SchematicsComponent,
    SearchInputComponent,
    TopMenuComponent,
    BreadCrumbsComponent,
    ComponentsPageComponent,
    ConstructionPageComponent,
    ThemesComponent
  ],
  imports: [
    CommonModule,
    NgApiDocModule,
    ExamplesComponentModule,
    ApiSectionsComponentModule,
    TabsModule.forRoot(),
    BsDropdownModule.forRoot(),
    RouterModule
  ],
  exports: [
    SearchFilterPipe,
    SidebarComponent,
    AppFooterComponent,
    AddNavComponent,
    DemoSectionComponent,
    ExamplesComponentModule,
    ApiSectionsComponentModule,
    DocsSectionComponent,
    SearchInputComponent,
    TopMenuComponent
  ]
})
export class DocsModule {}


text:
http://www.beecrowd.com.br/judge/en/problems/view/1234

# Dancing Sentence

A sentence is called dancing if its first letter is uppercase and the case of
each subsequent letter is the opposite of the previous letter. Spaces should
be ignored when determining the case of a letter. For example, "A b Cd" is a
dancing sentence because the first letter ('A') is uppercase, the next letter
('b') is lowercase, the next letter ('C') is uppercase, and the next letter
('d') is lowercase.

## Input

The input contains several test cases. Each test case is composed by one line
that contais a string sentence. This string will contain between 1 and 50
characters ('A'-'Z','a'-'z' or space ' '), inclusive, or at least, one letter
('A'-'Z','a'-'z').

## Output

Turn the sentence into a dancing sentence (like following examples) by
changing the cases of the letters where necessary. All spaces in the original
sentence must be preserved, ie, "sentence" must be converted in "SeNtEnCe".


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

<TITLE>
Overview List (XMLBeans 2.6.0 Documentation)
</TITLE>

<META NAME="date" CONTENT="2012-07-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

Packages

javax.xml.namespace

org.apache.xmlbeans


text:
#include <aws/compute-optimizer/model/GetEnrollmentStatusesForOrganizationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::ComputeOptimizer::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetEnrollmentStatusesForOrganizationRequest::GetEnrollmentStatusesForOrganizationRequest() :
    m_filtersHasBeenSet(false),
    m_nextTokenHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false)
{
}

Aws::String GetEnrollmentStatusesForOrganizationRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_filtersHasBeenSet)
  {
   Array<JsonValue> filtersJsonList(m_filters.size());
   for(unsigned filtersIndex = 0; filtersIndex < filtersJsonList.GetLength(); ++filtersIndex)
   {
     filtersJsonList[filtersIndex].AsObject(m_filters[filtersIndex].Jsonize());
   }
   payload.WithArray("filters", std::move(filtersJsonList));

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("nextToken", m_nextToken);

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("maxResults", m_maxResults);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection GetEnrollmentStatusesForOrganizationRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "ComputeOptimizerService.GetEnrollmentStatusesForOrganization"));
  return headers;

}


text:
Syntax Options
==============

.. note::

   This content is currently in progress, and will appear soon!


text:
What is it?
===========

LFS is an online shop based on Python, Django and jQuery.

Information
===========

For more information please visit:

* http://www.getlfs.com

Documentation
=============

For the latest documentation please visit:

* http://docs.getlfs.com

Demo shop
=========

A demo shop can be tried here:

* http://demo.getlfs.com

Development
===========

For development environment please visit:

* https://github.com/diefenbach/lfs-buildout-development

Changes
=======

0.10.2 (2015-04-25)
===================

* Updates lfs-paypal to 1.3
* Fixes all tests

0.10.1 (2015-04-23)
===================

* Fixes MANIFEST.in
* Fixes adding and display of reviews when L10N is turned on

0.10.0 (2015-04-22)
===================

* Adds Django 1.8 support
* Moves static files to lfs.manage
* Moves manage templates to lfs.manage

HISTORY
=======

For the complete history please look into HISTORY.txt


text: touch usr/lib/X11/config/host.def


text:
<?php
namespace Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass;

class PeerAssessmentScore extends \Chamilo\Core\Tracking\Storage\DataClass\SimpleTracker
{
    const PROPERTY_ATTEMPT_STATUS_ID = 'attempt_status_id';
    const PROPERTY_USER_ID = 'user_id';
    const PROPERTY_INDICATOR_ID = 'indicator_id';
    const PROPERTY_SCORE = 'score';

    public function validate_parameters(array $parameters = array())
    {
        $this->set_attempt_status_id($parameters[self::PROPERTY_ATTEMPT_STATUS_ID]);
        $this->set_user_id($parameters[self::PROPERTY_USER_ID]);
        $this->set_indicator_id($parameters[self::PROPERTY_INDICATOR_ID]);
        $this->set_score($parameters[self::PROPERTY_SCORE]);
    }

    public static function get_default_property_names($extended_property_names = array())
    {
        return parent::get_default_property_names(
            array(
                self::PROPERTY_ATTEMPT_STATUS_ID,
                self::PROPERTY_USER_ID,
                self::PROPERTY_INDICATOR_ID,
                self::PROPERTY_SCORE));
    }

    public function set_score($score)
    {
        // ensure that invalid values are stored as null
        if (! is_numeric($score))
        {
            $score = null;
        }
        $this->set_default_property(self::PROPERTY_SCORE, $score);
    }

    public function __call($name, array $arguments)
    {
        // generate error if no getter or setter is called and return
        if (! preg_match('/^(get|set)_(.+)$/', $name, $matches))
        {
            trigger_error('method not found', E_USER_ERROR);
            return;
        }
        // determine the method and property to be called
        $method = $matches[1] . '_default_property';
        $prop = constant($this::class_name() . '::PROPERTY_' . strtoupper($matches[2]));
        // prepend the property to the argument list
        array_unshift($arguments, $prop);
        // call get_default_property or set_default_property with the arguments
        return call_user_func_array(array($this, $method), $arguments);
    }
}


text:
<?php

require 'Base/src/base.php';
function __autoload( $className )
{
        ezcBase::autoload( $className );
}

// Require custom palette
require dirname( __FILE__ ) . '/ez_green.php';

// Create the graph
$graph = new ezcGraphPieChart();
$graph->palette = new ezcGraphPaletteEzGreen();
$graph->legend = false;

// Add the data and hilight norwegian data set
$graph->data['week'] = new ezcGraphArrayDataSet( array(
    'Lukasz Serwatka' => 1805,
    'Paul Forsyth' => 1491,
    'Paul Borgermans' => 1316,
    'Kristof Coomans' => 956,
    'Alex Jones' => 942 ,
    'Bard Farstad' => 941,
    'Tony Wood' => 900,
) );

// Set graph title
$graph->title = 'Alltime 10 most active users on forum';

// Use 3d renderer, and beautify it
$graph->renderer = new ezcGraphRenderer3d();
$graph->renderer->options->pieChartShadowSize = 12;
$graph->renderer->options->pieChartGleam = .5;
$graph->renderer->options->dataBorder = false;
$graph->renderer->options->pieChartHeight = 16;
$graph->renderer->options->legendSymbolGleam = .5;
$graph->renderer->options->pieChartOffset = 100;

$graph->driver = new ezcGraphSvgDriver();

// Output the graph with std SVG driver
$graph->render( 500, 200, 'forum_year.svg' );

?>


text:
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

WebInspector.DashboardContainerView = (function (_WebInspector$Object) {
    _inherits(DashboardContainerView, _WebInspector$Object);

    function DashboardContainerView() {
        _classCallCheck(this, DashboardContainerView);

        _get(Object.getPrototypeOf(DashboardContainerView.prototype), "constructor", this).call(this);

        this._toolbarItem = new WebInspector.NavigationItem("dashboard-container", "group", WebInspector.UIString("Activity Viewer"));

        this._advanceForwardArrowElement = this._toolbarItem.element.appendChild(document.createElement("div"));
        this._advanceForwardArrowElement.className = "advance-arrow advance-forward";
        this._advanceBackwardArrowElement = this._toolbarItem.element.appendChild(document.createElement("div"));
        this._advanceBackwardArrowElement.className = "advance-arrow advance-backward";

        this._advanceForwardArrowElement.addEventListener("click", this._advanceForwardArrowClicked.bind(this));
        this._advanceBackwardArrowElement.addEventListener("click", this._advanceBackwardArrowClicked.bind(this));

        // Represents currently open dashboards, with the most recent entries appended to the end.
        this._dashboardStack = [];
        this._currentIndex = -1;

        this._updateAdvanceArrowVisibility();
    }

    // Public

    _createClass(DashboardContainerView, [{
        key: "showDashboardViewForRepresentedObject",
        value: function showDashboardViewForRepresentedObject(representedObject) {
            var dashboardView = this._dashboardViewForRepresentedObject(representedObject);
            if (!dashboardView) return null;

            if (this.currentDashboardView === dashboardView) return;

            var index = this._dashboardStack.indexOf(dashboardView);
            this._showDashboardAtIndex(index);
            return dashboardView;
        }
    }, {
        key: "hideDashboardViewForRepresentedObject",
        value: function hideDashboardViewForRepresentedObject(representedObject) {
            var onlyReturnExistingViews = true;
            var dashboardView = this._dashboardViewForRepresentedObject(representedObject, onlyReturnExistingViews);

            if (this.currentDashboardView !== dashboardView) return;

            console.assert(this._currentIndex > 0);
            this._showDashboardAtIndex(this._currentIndex - 1);
        }
    }, {
        key: "closeDashboardViewForRepresentedObject",
        value: function closeDashboardViewForRepresentedObject(representedObject) {
            var onlyReturnExistingViews = true;
            var dashboardView = this._dashboardViewForRepresentedObject(representedObject, onlyReturnExistingViews);
            if (!dashboardView) return null;

            this._closeDashboardView(dashboardView);
        }

        // Private

    }, {
        key: "_advanceForwardArrowClicked",
        value: function _advanceForwardArrowClicked() {
            this._showDashboardAtIndex(this._currentIndex + 1);
        }
    }, {
        key: "_advanceBackwardArrowClicked",
        value: function _advanceBackwardArrowClicked() {
            this._showDashboardAtIndex(this._currentIndex - 1);
        }
    }, {
        key: "_dismissAdvanceArrows",
        value: function _dismissAdvanceArrows() {
            this._advanceForwardArrowElement.classList.add(WebInspector.DashboardContainerView.InactiveStyleClassName);
            this._advanceBackwardArrowElement.classList.add(WebInspector.DashboardContainerView.InactiveStyleClassName);
        }
    }, {
        key: "_updateAdvanceArrowVisibility",
        value: function _updateAdvanceArrowVisibility() {
            var canAdvanceForward = this._currentIndex < this._dashboardStack.length - 1;
            var canAdvanceBackward = this._currentIndex > 0;
            this._advanceForwardArrowElement.classList.toggle(WebInspector.DashboardContainerView.InactiveStyleClassName, !canAdvanceForward);
            this._advanceBackwardArrowElement.classList.toggle(WebInspector.DashboardContainerView.InactiveStyleClassName, !canAdvanceBackward);
        }
    }, {
        key: "_dashboardViewForRepresentedObject",
        value: function _dashboardViewForRepresentedObject(representedObject, onlyReturnExistingViews) {
            console.assert(representedObject);

            // Iterate over all known dashboard views and see if any are for this object.
            var _iteratorNormalCompletion = true;
            var _didIteratorError = false;
            var _iteratorError = undefined;

            try {
                for (var _iterator = this._dashboardStack[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                    var dashboardView = _step.value;

                    if (dashboardView.representedObject === representedObject) return dashboardView;
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion && _iterator["return"]) {
                        _iterator["return"]();
                    }
                } finally {
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }

            if (onlyReturnExistingViews) return null;

            // No existing content view found, make a new one.
            dashboardView = WebInspector.DashboardView.create(representedObject);

            console.assert(dashboardView, "Unknown representedObject", representedObject);
            if (!dashboardView) return null;

            this._dashboardStack.push(dashboardView);
            this._toolbarItem.element.appendChild(dashboardView.element);

            return dashboardView;
        }
    }, {
        key: "_showDashboardAtIndex",
        value: function _showDashboardAtIndex(index) {
            console.assert(index >= 0 && index <= this._dashboardStack.length - 1);

            if (this._currentIndex === index) return;

            var advanceDirection = null;
            if (this._currentIndex < index) advanceDirection = WebInspector.DashboardContainerView.AdvanceDirection.Forward;else advanceDirection = WebInspector.DashboardContainerView.AdvanceDirection.Backward;
            var initialDirection = WebInspector.DashboardContainerView.AdvanceDirection.None;
            var isInitialDashboard = this._currentIndex === -1;
            if (!isInitialDashboard) this._hideDashboardView(this.currentDashboardView, advanceDirection);

            this._currentIndex = index;
            this._showDashboardView(this.currentDashboardView, isInitialDashboard ? initialDirection : advanceDirection);
        }
    }, {
        key: "_showDashboardView",
        value: function _showDashboardView(dashboardView, advanceDirection) {
            console.assert(dashboardView instanceof WebInspector.DashboardView);

            dashboardView.shown();
            this._dismissAdvanceArrows();

            var animationClass = null;
            if (advanceDirection === WebInspector.DashboardContainerView.AdvanceDirection.Forward) animationClass = WebInspector.DashboardContainerView.ForwardIncomingDashboardStyleClassName;
            if (advanceDirection === WebInspector.DashboardContainerView.AdvanceDirection.Backward) animationClass = WebInspector.DashboardContainerView.BackwardIncomingDashboardStyleClassName;

            var container = this;
            dashboardView.element.classList.add(WebInspector.DashboardContainerView.VisibleDashboardStyleClassName);

            function animationEnded(event) {
                if (event.target !== dashboardView.element) return;

                dashboardView.element.removeEventListener("animationend", animationEnded);
                dashboardView.element.classList.remove(animationClass);
                container._updateAdvanceArrowVisibility();
            }

            if (animationClass) {
                dashboardView.element.classList.add(animationClass);
                dashboardView.element.addEventListener("animationend", animationEnded);
            }

            return dashboardView;
        }
    }, {
        key: "_hideDashboardView",
        value: function _hideDashboardView(dashboardView, advanceDirection, callback) {
            console.assert(dashboardView instanceof WebInspector.DashboardView);
            console.assert(this.currentDashboardView === dashboardView);

            dashboardView.hidden();
            this._dismissAdvanceArrows();

            var animationClass = null;
            if (advanceDirection === WebInspector.DashboardContainerView.AdvanceDirection.Forward) animationClass = WebInspector.DashboardContainerView.ForwardOutgoingDashboardStyleClassName;
            if (advanceDirection === WebInspector.DashboardContainerView.AdvanceDirection.Backward) animationClass = WebInspector.DashboardContainerView.BackwardOutgoingDashboardStyleClassName;

            var container = this;

            function animationEnded(event) {
                if (event.target !== dashboardView.element) return;

                dashboardView.element.removeEventListener("animationend", animationEnded);
                dashboardView.element.classList.remove(animationClass);
                dashboardView.element.classList.remove(WebInspector.DashboardContainerView.VisibleDashboardStyleClassName);
                container._updateAdvanceArrowVisibility();

                if (typeof callback === "function") callback();
            }

            if (animationClass) {
                dashboardView.element.classList.add(animationClass);
                dashboardView.element.addEventListener("animationend", animationEnded);
            } else dashboardView.element.classList.remove(WebInspector.DashboardContainerView.VisibleDashboardStyleClassName);
        }
    }, {
        key: "_closeDashboardView",
        value: function _closeDashboardView(dashboardView) {
            console.assert(dashboardView instanceof WebInspector.DashboardView);

            function dissociateDashboardView() {
                dashboardView.closed();
                dashboardView.element.parentNode.removeChild(dashboardView.element);
            }

            var index = this._dashboardStack.indexOf(dashboardView);

            if (this.currentDashboardView === dashboardView) {
                var direction = WebInspector.DashboardContainerView.AdvanceDirection.Backward;
                this._hideDashboardView(this.currentDashboardView, direction, dissociateDashboardView);
                this._dashboardStack.splice(index, 1);
                --this._currentIndex;
                this._showDashboardView(this.currentDashboardView, direction);
                return;
            }

            this._dashboardStack.splice(index, 1);
            if (this._currentIndex > index) --this._currentIndex;
            dissociateDashboardView.call(this);

            this._updateAdvanceArrowVisibility();
        }
    }, {
        key: "toolbarItem",
        get: function get() {
            return this._toolbarItem;
        }
    }, {
        key: "currentDashboardView",
        get: function get() {
            if (this._currentIndex === -1) return null;

            return this._dashboardStack[this._currentIndex];
        }
    }]);

    return DashboardContainerView;
})(WebInspector.Object);

WebInspector.DashboardContainerView.VisibleDashboardStyleClassName = "visible";
WebInspector.DashboardContainerView.InactiveStyleClassName = "inactive";

WebInspector.DashboardContainerView.AdvanceDirection = {
    Forward: Symbol("dashboard-container-view-advance-direction-forward"),
    Backward: Symbol("dashboard-container-view-advance-direction-backward"),
    None: Symbol("dashboard-container-view-advance-direction-none")
};

WebInspector.DashboardContainerView.ForwardIncomingDashboardStyleClassName = "slide-in-down";
WebInspector.DashboardContainerView.BackwardIncomingDashboardStyleClassName = "slide-in-up";
WebInspector.DashboardContainerView.ForwardOutgoingDashboardStyleClassName = "slide-out-down";
WebInspector.DashboardContainerView.BackwardOutgoingDashboardStyleClassName = "slide-out-up";