text:
package org.scalatest.fixture

import org.scalatest._
import SharedHelpers.EventRecordingReporter
import scala.concurrent.Future

class AsyncFixturesSpec extends org.scalatest.FunSpec {

  describe("AsyncFixtures") {

    it("should fail tests with NotAllowedException when mixed in classic FunSpec") {
      val spec = new FunSpec with AsyncFixtures {

        type FixtureParam = String
        def withAsyncFixture(test: OneArgAsyncTest): Future[Outcome] =
          test("testing")

        it("a test") { fixture => }
      }
      val rep = new EventRecordingReporter
      spec.run(None, Args(reporter = rep))
      assert(rep.testFailedEventsReceived.size == 1)
      val tfe = rep.testFailedEventsReceived(0)
      assert(tfe.throwable.isDefined)
      assert(tfe.throwable.get.isInstanceOf[exceptions.NotAllowedException])
    }

    it("should fail tests with NotAllowedException when mixed in classic FunSpecLike") {
      val spec = new FunSpecLike with AsyncFixtures {

        type FixtureParam = String
        def withAsyncFixture(test: OneArgAsyncTest): Future[Outcome] =
          test("testing")

        it("a test") { fixture => }
      }
      val rep = new EventRecordingReporter
      spec.run(None, Args(reporter = rep))
      assert(rep.testFailedEventsReceived.size == 1)
      val tfe = rep.testFailedEventsReceived(0)
      assert(tfe.throwable.isDefined)
      assert(tfe.throwable.get.isInstanceOf[exceptions.NotAllowedException])
    }

    it("should fail tests with NotAllowedException when mixed in classic FunSuite") {
      val suite = new FunSuite with AsyncFixtures {

        type FixtureParam = String
        def withAsyncFixture(test: OneArgAsyncTest): Future[Outcome] =
          test("testing")

        test("a test") { fixture => }
      }
      val rep = new EventRecordingReporter
      suite.run(None, Args(reporter = rep))
      assert(rep.testFailedEventsReceived.size == 1)
      val tfe = rep.testFailedEventsReceived(0)
      assert(tfe.throwable.isDefined)
      assert(tfe.throwable.get.isInstanceOf[exceptions.NotAllowedException])
    }

    it("should fail tests with NotAllowedException when mixed in classic FunSuiteLike") {
      val suite = new FunSuiteLike with AsyncFixtures {

        type FixtureParam = String
        def withAsyncFixture(test: OneArgAsyncTest): Future[Outcome] =
          test("testing")

        test("a test") { fixture => }
      }
      val rep = new EventRecordingReporter
      suite.run(None, Args(reporter = rep))
      assert(rep.testFailedEventsReceived.size == 1)
      val tfe = rep.testFailedEventsReceived(0)
      assert(tfe.throwable.isDefined)
      assert(tfe.throwable.get.isInstanceOf[exceptions.NotAllowedException])
    }

  }

}


text:
package org.apache.spark.sql.sources

import java.io.File
import java.sql.Date

import org.apache.spark.SparkException
import org.apache.spark.sql._
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.catalog.{CatalogStorageFormat, CatalogTable, CatalogTableType}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.SQLConf.PartitionOverwriteMode
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types._
import org.apache.spark.util.Utils

class SimpleInsertSource extends SchemaRelationProvider {
  override def createRelation(
      sqlContext: SQLContext,
      parameters: Map[String, String],
      schema: StructType): BaseRelation = {
    SimpleInsert(schema)(sqlContext.sparkSession)
  }
}

case class SimpleInsert(userSpecifiedSchema: StructType)(@transient val sparkSession: SparkSession)
  extends BaseRelation with InsertableRelation {

  override def sqlContext: SQLContext = sparkSession.sqlContext

  override def schema: StructType = userSpecifiedSchema

  override def insert(input: DataFrame, overwrite: Boolean): Unit = {
    input.collect
  }
}

class InsertSuite extends DataSourceTest with SharedSparkSession {
  import testImplicits._

  protected override lazy val sql = spark.sql _
  private var path: File = null

  override def beforeAll(): Unit = {
    super.beforeAll()
    path = Utils.createTempDir()
    val ds = (1 to 10).map(i => s"""{"a":$i, "b":"str$i"}""").toDS()
    spark.read.json(ds).createOrReplaceTempView("jt")
    sql(
      s"""
        |CREATE TEMPORARY VIEW jsonTable (a int, b string)
        |USING org.apache.spark.sql.json.DefaultSource
        |OPTIONS (
        |  path '${path.toURI.toString}'
        |)
      """.stripMargin)
  }

  override def afterAll(): Unit = {
    try {
      spark.catalog.dropTempView("jsonTable")
      spark.catalog.dropTempView("jt")
      Utils.deleteRecursively(path)
    } finally {
      super.afterAll()
    }
  }

  test("Simple INSERT OVERWRITE a JSONRelation") {
    sql(
      s"""
        |INSERT OVERWRITE TABLE jsonTable SELECT a, b FROM jt
      """.stripMargin)

    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      (1 to 10).map(i => Row(i, s"str$i"))
    )
  }

  test("insert into a temp view that does not point to an insertable data source") {
    import testImplicits._
    withTempView("t1", "t2") {
      sql(
        """
          |CREATE TEMPORARY VIEW t1
          |USING org.apache.spark.sql.sources.SimpleScanSource
          |OPTIONS (
          |  From '1',
          |  To '10')
        """.stripMargin)
      sparkContext.parallelize(1 to 10).toDF("a").createOrReplaceTempView("t2")

      val message = intercept[AnalysisException] {
        sql("INSERT INTO TABLE t1 SELECT a FROM t2")
      }.getMessage
      assert(message.contains("does not allow insertion"))
    }
  }

  test("PreInsert casting and renaming") {
    sql(
      s"""
        |INSERT OVERWRITE TABLE jsonTable SELECT a * 2, a * 4 FROM jt
      """.stripMargin)

    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      (1 to 10).map(i => Row(i * 2, s"${i * 4}"))
    )

    sql(
      s"""
        |INSERT OVERWRITE TABLE jsonTable SELECT a * 4 AS A, a * 6 as c FROM jt
      """.stripMargin)

    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      (1 to 10).map(i => Row(i * 4, s"${i * 6}"))
    )
  }

  test("SELECT clause generating a different number of columns is not allowed.") {
    val message = intercept[AnalysisException] {
      sql(
        s"""
        |INSERT OVERWRITE TABLE jsonTable SELECT a FROM jt
      """.stripMargin)
    }.getMessage
    assert(message.contains("target table has 2 column(s) but the inserted data has 1 column(s)")
    )
  }

  test("INSERT OVERWRITE a JSONRelation multiple times") {
    sql(
      s"""
         |INSERT OVERWRITE TABLE jsonTable SELECT a, b FROM jt
    """.stripMargin)
    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      (1 to 10).map(i => Row(i, s"str$i"))
    )

    // Writing the table to less part files.
    val rdd1 = sparkContext.parallelize((1 to 10).map(i => s"""{"a":$i, "b":"str$i"}"""), 5)
    spark.read.json(rdd1.toDS()).createOrReplaceTempView("jt1")
    sql(
      s"""
         |INSERT OVERWRITE TABLE jsonTable SELECT a, b FROM jt1
    """.stripMargin)
    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      (1 to 10).map(i => Row(i, s"str$i"))
    )

    // Writing the table to more part files.
    val rdd2 = sparkContext.parallelize((1 to 10).map(i => s"""{"a":$i, "b":"str$i"}"""), 10)
    spark.read.json(rdd2.toDS()).createOrReplaceTempView("jt2")
    sql(
      s"""
         |INSERT OVERWRITE TABLE jsonTable SELECT a, b FROM jt2
    """.stripMargin)
    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      (1 to 10).map(i => Row(i, s"str$i"))
    )

    sql(
      s"""
         |INSERT OVERWRITE TABLE jsonTable SELECT a * 10, b FROM jt1
    """.stripMargin)
    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      (1 to 10).map(i => Row(i * 10, s"str$i"))
    )

    spark.catalog.dropTempView("jt1")
    spark.catalog.dropTempView("jt2")
  }

  test("INSERT INTO JSONRelation for now") {
    sql(
      s"""
      |INSERT OVERWRITE TABLE jsonTable SELECT a, b FROM jt
    """.stripMargin)
    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      sql("SELECT a, b FROM jt").collect()
    )

    sql(
      s"""
         |INSERT INTO TABLE jsonTable SELECT a, b FROM jt
    """.stripMargin)
    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      sql("SELECT a, b FROM jt UNION ALL SELECT a, b FROM jt").collect()
    )
  }

  test("INSERT INTO TABLE with Comment in columns") {
    val tabName = "tab1"
    withTable(tabName) {
      sql(
        s"""
           |CREATE TABLE $tabName(col1 int COMMENT 'a', col2 int)
           |USING parquet
         """.stripMargin)
      sql(s"INSERT INTO TABLE $tabName SELECT 1, 2")

      checkAnswer(
        sql(s"SELECT col1, col2 FROM $tabName"),
        Row(1, 2) :: Nil
      )
    }
  }

  test("INSERT INTO TABLE - complex type but different names") {
    val tab1 = "tab1"
    val tab2 = "tab2"
    withTable(tab1, tab2) {
      sql(
        s"""
           |CREATE TABLE $tab1 (s struct<a: string, b: string>)
           |USING parquet
         """.stripMargin)
      sql(s"INSERT INTO TABLE $tab1 SELECT named_struct('col1','1','col2','2')")

      sql(
        s"""
           |CREATE TABLE $tab2 (p struct<c: string, d: string>)
           |USING parquet
         """.stripMargin)
      sql(s"INSERT INTO TABLE $tab2 SELECT * FROM $tab1")

      checkAnswer(
        spark.table(tab1),
        spark.table(tab2)
      )
    }
  }

  test("it is not allowed to write to a table while querying it.") {
    val message = intercept[AnalysisException] {
      sql(
        s"""
        |INSERT OVERWRITE TABLE jsonTable SELECT a, b FROM jsonTable
      """.stripMargin)
    }.getMessage
    assert(
      message.contains("Cannot overwrite a path that is also being read from."),
      "INSERT OVERWRITE to a table while querying it should not be allowed.")
  }

  test("Caching")  {
    // write something to the jsonTable
    sql(
      s"""
         |INSERT OVERWRITE TABLE jsonTable SELECT a, b FROM jt
      """.stripMargin)
    // Cached Query Execution
    spark.catalog.cacheTable("jsonTable")
    assertCached(sql("SELECT * FROM jsonTable"))
    checkAnswer(
      sql("SELECT * FROM jsonTable"),
      (1 to 10).map(i => Row(i, s"str$i")))

    assertCached(sql("SELECT a FROM jsonTable"))
    checkAnswer(
      sql("SELECT a FROM jsonTable"),
      (1 to 10).map(Row(_)).toSeq)

    assertCached(sql("SELECT a FROM jsonTable WHERE a < 5"))
    checkAnswer(
      sql("SELECT a FROM jsonTable WHERE a < 5"),
      (1 to 4).map(Row(_)).toSeq)

    assertCached(sql("SELECT a * 2 FROM jsonTable"))
    checkAnswer(
      sql("SELECT a * 2 FROM jsonTable"),
      (1 to 10).map(i => Row(i * 2)).toSeq)

    assertCached(sql(
      "SELECT x.a, y.a FROM jsonTable x JOIN jsonTable y ON x.a = y.a + 1"), 2)
    checkAnswer(sql(
      "SELECT x.a, y.a FROM jsonTable x JOIN jsonTable y ON x.a = y.a + 1"),
      (2 to 10).map(i => Row(i, i - 1)).toSeq)

    // Insert overwrite and keep the same schema.
    sql(
      s"""
        |INSERT OVERWRITE TABLE jsonTable SELECT a * 2, b FROM jt
      """.stripMargin)
    // jsonTable should be recached.
    assertCached(sql("SELECT * FROM jsonTable"))

    // The cached data is the new data.
    checkAnswer(
      sql("SELECT a, b FROM jsonTable"),
      sql("SELECT a * 2, b FROM jt").collect())

    // Verify uncaching
    spark.catalog.uncacheTable("jsonTable")
    assertCached(sql("SELECT * FROM jsonTable"), 0)
  }

  test("it's not allowed to insert into a relation that is not an InsertableRelation") {
    sql(
      """
        |CREATE TEMPORARY VIEW oneToTen
        |USING org.apache.spark.sql.sources.SimpleScanSource
        |OPTIONS (
        |  From '1',
        |  To '10'
        |)
      """.stripMargin)

    checkAnswer(
      sql("SELECT * FROM oneToTen"),
      (1 to 10).map(Row(_)).toSeq
    )

    val message = intercept[AnalysisException] {
      sql(
        s"""
        |INSERT OVERWRITE TABLE oneToTen SELECT CAST(a AS INT) FROM jt
        """.stripMargin)
    }.getMessage
    assert(
      message.contains("does not allow insertion."),
      "It is not allowed to insert into a table that is not an InsertableRelation."
    )

    spark.catalog.dropTempView("oneToTen")
  }

  test("SPARK-15824 - Execute an INSERT wrapped in a WITH statement immediately") {
    withTable("target", "target2") {
      sql(s"CREATE TABLE target(a INT, b STRING) USING JSON")
      sql("WITH tbl AS (SELECT * FROM jt) INSERT OVERWRITE TABLE target SELECT a, b FROM tbl")
      checkAnswer(
        sql("SELECT a, b FROM target"),
        sql("SELECT a, b FROM jt")
      )

      sql(s"CREATE TABLE target2(a INT, b STRING) USING JSON")
      val e = sql(
        """
          |WITH tbl AS (SELECT * FROM jt)
          |FROM tbl
          |INSERT INTO target2 SELECT a, b WHERE a <= 5
          |INSERT INTO target2 SELECT a, b WHERE a > 5
        """.stripMargin)
      checkAnswer(
        sql("SELECT a, b FROM target2"),
        sql("SELECT a, b FROM jt")
      )
    }
  }

  test("SPARK-21203 wrong results of insertion of Array of Struct") {
    val tabName = "tab1"
    withTable(tabName) {
      spark.sql(
        """
          |CREATE TABLE `tab1`
          |(`custom_fields` ARRAY<STRUCT<`id`: BIGINT, `value`: STRING>>)
          |USING parquet
        """.stripMargin)
      spark.sql(
        """
          |INSERT INTO `tab1`
          |SELECT ARRAY(named_struct('id', 1, 'value', 'a'), named_struct('id', 2, 'value', 'b'))
        """.stripMargin)

      checkAnswer(
        spark.sql("SELECT custom_fields.id, custom_fields.value FROM tab1"),
        Row(Array(1, 2), Array("a", "b")))
    }
  }

  test("insert overwrite directory") {
    withTempDir { dir =>
      val path = dir.toURI.getPath

      val v1 =
        s"""
           | INSERT OVERWRITE DIRECTORY '${path}'
           | USING json
           | OPTIONS (a 1, b 0.1, c TRUE)
           | SELECT 1 as a, 'c' as b
         """.stripMargin

      spark.sql(v1)

      checkAnswer(
        spark.read.json(dir.getCanonicalPath),
        sql("SELECT 1 as a, 'c' as b"))
    }
  }

  test("insert overwrite directory with path in options") {
    withTempDir { dir =>
      val path = dir.toURI.getPath

      val v1 =
        s"""
           | INSERT OVERWRITE DIRECTORY
           | USING json
           | OPTIONS ('path' '${path}')
           | SELECT 1 as a, 'c' as b
         """.stripMargin

      spark.sql(v1)

      checkAnswer(
        spark.read.json(dir.getCanonicalPath),
        sql("SELECT 1 as a, 'c' as b"))
    }
  }

  test("Insert overwrite directory using Hive serde without turning on Hive support") {
    withTempDir { dir =>
      val path = dir.toURI.getPath
      val e = intercept[AnalysisException] {
        sql(
          s"""
             |INSERT OVERWRITE LOCAL DIRECTORY '$path'
             |STORED AS orc
             |SELECT 1, 2
           """.stripMargin)
      }.getMessage
      assert(e.contains(
        "Hive support is required to INSERT OVERWRITE DIRECTORY with the Hive format"))
    }
  }

  test("insert overwrite directory to data source not providing FileFormat") {
    withTempDir { dir =>
      val path = dir.toURI.getPath

      val v1 =
        s"""
           | INSERT OVERWRITE DIRECTORY '${path}'
           | USING JDBC
           | OPTIONS (a 1, b 0.1, c TRUE)
           | SELECT 1 as a, 'c' as b
         """.stripMargin
      val e = intercept[SparkException] {
        spark.sql(v1)
      }.getMessage

      assert(e.contains("Only Data Sources providing FileFormat are supported"))
    }
  }

  test("SPARK-20236: dynamic partition overwrite without catalog table") {
    withSQLConf(SQLConf.PARTITION_OVERWRITE_MODE.key -> PartitionOverwriteMode.DYNAMIC.toString) {
      withTempPath { path =>
        Seq((1, 1, 1)).toDF("i", "part1", "part2")
          .write.partitionBy("part1", "part2").parquet(path.getAbsolutePath)
        checkAnswer(spark.read.parquet(path.getAbsolutePath), Row(1, 1, 1))

        Seq((2, 1, 1)).toDF("i", "part1", "part2")
          .write.partitionBy("part1", "part2").mode("overwrite").parquet(path.getAbsolutePath)
        checkAnswer(spark.read.parquet(path.getAbsolutePath), Row(2, 1, 1))

        Seq((2, 2, 2)).toDF("i", "part1", "part2")
          .write.partitionBy("part1", "part2").mode("overwrite").parquet(path.getAbsolutePath)
        checkAnswer(spark.read.parquet(path.getAbsolutePath), Row(2, 1, 1) :: Row(2, 2, 2) :: Nil)
      }
    }
  }

  test("SPARK-20236: dynamic partition overwrite") {
    withSQLConf(SQLConf.PARTITION_OVERWRITE_MODE.key -> PartitionOverwriteMode.DYNAMIC.toString) {
      withTable("t") {
        sql(
          """
            |create table t(i int, part1 int, part2 int) using parquet
            |partitioned by (part1, part2)
          """.stripMargin)

        sql("insert into t partition(part1=1, part2=1) select 1")
        checkAnswer(spark.table("t"), Row(1, 1, 1))

        sql("insert overwrite table t partition(part1=1, part2=1) select 2")
        checkAnswer(spark.table("t"), Row(2, 1, 1))

        sql("insert overwrite table t partition(part1=2, part2) select 2, 2")
        checkAnswer(spark.table("t"), Row(2, 1, 1) :: Row(2, 2, 2) :: Nil)

        sql("insert overwrite table t partition(part1=1, part2=2) select 3")
        checkAnswer(spark.table("t"), Row(2, 1, 1) :: Row(2, 2, 2) :: Row(3, 1, 2) :: Nil)

        sql("insert overwrite table t partition(part1=1, part2) select 4, 1")
        checkAnswer(spark.table("t"), Row(4, 1, 1) :: Row(2, 2, 2) :: Row(3, 1, 2) :: Nil)
      }
    }
  }

  test("SPARK-20236: dynamic partition overwrite with customer partition path") {
    withSQLConf(SQLConf.PARTITION_OVERWRITE_MODE.key -> PartitionOverwriteMode.DYNAMIC.toString) {
      withTable("t") {
        sql(
          """
            |create table t(i int, part1 int, part2 int) using parquet
            |partitioned by (part1, part2)
          """.stripMargin)

        val path1 = Utils.createTempDir()
        sql(s"alter table t add partition(part1=1, part2=1) location '$path1'")
        sql(s"insert into t partition(part1=1, part2=1) select 1")
        checkAnswer(spark.table("t"), Row(1, 1, 1))

        sql("insert overwrite table t partition(part1=1, part2=1) select 2")
        checkAnswer(spark.table("t"), Row(2, 1, 1))

        sql("insert overwrite table t partition(part1=2, part2) select 2, 2")
        checkAnswer(spark.table("t"), Row(2, 1, 1) :: Row(2, 2, 2) :: Nil)

        val path2 = Utils.createTempDir()
        sql(s"alter table t add partition(part1=1, part2=2) location '$path2'")
        sql("insert overwrite table t partition(part1=1, part2=2) select 3")
        checkAnswer(spark.table("t"), Row(2, 1, 1) :: Row(2, 2, 2) :: Row(3, 1, 2) :: Nil)

        sql("insert overwrite table t partition(part1=1, part2) select 4, 1")
        checkAnswer(spark.table("t"), Row(4, 1, 1) :: Row(2, 2, 2) :: Row(3, 1, 2) :: Nil)
      }
    }
  }

  test("Throw exception on unsafe cast with strict casting policy") {
    withSQLConf(
      SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
      SQLConf.STORE_ASSIGNMENT_POLICY.key -> SQLConf.StoreAssignmentPolicy.STRICT.toString) {
      withTable("t") {
        sql("create table t(i int, d double) using parquet")
        var msg = intercept[AnalysisException] {
          sql("insert into t select 1L, 2")
        }.getMessage
        assert(msg.contains("Cannot safely cast 'i': LongType to IntegerType"))

        msg = intercept[AnalysisException] {
          sql("insert into t select 1, 2.0")
        }.getMessage
        assert(msg.contains("Cannot safely cast 'd': DecimalType(2,1) to DoubleType"))

        msg = intercept[AnalysisException] {
          sql("insert into t select 1, 2.0D, 3")
        }.getMessage
        assert(msg.contains("`t` requires that the data to be inserted have the same number of " +
          "columns as the target table: target table has 2 column(s)" +
          " but the inserted data has 3 column(s)"))

        msg = intercept[AnalysisException] {
          sql("insert into t select 1")
        }.getMessage
        assert(msg.contains("`t` requires that the data to be inserted have the same number of " +
          "columns as the target table: target table has 2 column(s)" +
          " but the inserted data has 1 column(s)"))

        // Insert into table successfully.
        sql("insert into t select 1, 2.0D")
        checkAnswer(sql("select * from t"), Row(1, 2.0D))
      }
    }
  }

  test("Throw exception on unsafe cast with ANSI casting policy") {
    withSQLConf(
      SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
      SQLConf.STORE_ASSIGNMENT_POLICY.key -> SQLConf.StoreAssignmentPolicy.ANSI.toString) {
      withTable("t") {
        sql("create table t(i int, d double) using parquet")
        var msg = intercept[AnalysisException] {
          sql("insert into t values('a', 'b')")
        }.getMessage
        assert(msg.contains("Cannot safely cast 'i': StringType to IntegerType") &&
          msg.contains("Cannot safely cast 'd': StringType to DoubleType"))
        msg = intercept[AnalysisException] {
          sql("insert into t values(now(), now())")
        }.getMessage
        assert(msg.contains("Cannot safely cast 'i': TimestampType to IntegerType") &&
          msg.contains("Cannot safely cast 'd': TimestampType to DoubleType"))
        msg = intercept[AnalysisException] {
          sql("insert into t values(true, false)")
        }.getMessage
        assert(msg.contains("Cannot safely cast 'i': BooleanType to IntegerType") &&
          msg.contains("Cannot safely cast 'd': BooleanType to DoubleType"))
      }
    }
  }

  test("Allow on writing any numeric value to numeric type with ANSI policy") {
    withSQLConf(
      SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
      SQLConf.STORE_ASSIGNMENT_POLICY.key -> SQLConf.StoreAssignmentPolicy.ANSI.toString) {
      withTable("t") {
        sql("create table t(i int, d float) using parquet")
        sql("insert into t values(1L, 2.0)")
        sql("insert into t values(3.0, 4)")
        sql("insert into t values(5.0, 6L)")
        checkAnswer(sql("select * from t"), Seq(Row(1, 2.0F), Row(3, 4.0F), Row(5, 6.0F)))
      }
    }
  }

  test("Allow on writing timestamp value to date type with ANSI policy") {
    withSQLConf(
      SQLConf.USE_V1_SOURCE_LIST.key -> "parquet",
      SQLConf.STORE_ASSIGNMENT_POLICY.key -> SQLConf.StoreAssignmentPolicy.ANSI.toString) {
      withTable("t") {
        sql("create table t(i date) using parquet")
        sql("insert into t values(TIMESTAMP('2010-09-02 14:10:10'))")
        checkAnswer(sql("select * from t"), Seq(Row(Date.valueOf("2010-09-02"))))
      }
    }
  }

  test("SPARK-24860: dynamic partition overwrite specified per source without catalog table") {
    withTempPath { path =>
      Seq((1, 1), (2, 2)).toDF("i", "part")
        .write.partitionBy("part")
        .parquet(path.getAbsolutePath)
      checkAnswer(spark.read.parquet(path.getAbsolutePath), Row(1, 1) :: Row(2, 2) :: Nil)

      Seq((1, 2), (1, 3)).toDF("i", "part")
        .write.partitionBy("part").mode("overwrite")
        .option("partitionOverwriteMode", "dynamic").parquet(path.getAbsolutePath)
      checkAnswer(spark.read.parquet(path.getAbsolutePath),
        Row(1, 1) :: Row(1, 2) :: Row(1, 3) :: Nil)

      Seq((1, 2), (1, 3)).toDF("i", "part")
        .write.partitionBy("part").mode("overwrite")
        .option("partitionOverwriteMode", "static").parquet(path.getAbsolutePath)
      checkAnswer(spark.read.parquet(path.getAbsolutePath), Row(1, 2) :: Row(1, 3) :: Nil)
    }
  }

  test("SPARK-24583 Wrong schema type in InsertIntoDataSourceCommand") {
    withTable("test_table") {
      val schema = new StructType()
        .add("i", LongType, false)
        .add("s", StringType, false)
      val newTable = CatalogTable(
        identifier = TableIdentifier("test_table", None),
        tableType = CatalogTableType.EXTERNAL,
        storage = CatalogStorageFormat(
          locationUri = None,
          inputFormat = None,
          outputFormat = None,
          serde = None,
          compressed = false,
          properties = Map.empty),
        schema = schema,
        provider = Some(classOf[SimpleInsertSource].getName))

      spark.sessionState.catalog.createTable(newTable, false)

      sql("INSERT INTO TABLE test_table SELECT 1, 'a'")
      sql("INSERT INTO TABLE test_table SELECT 2, null")
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using cartservice.interfaces;
using Grpc.Health.V1;
using StackExchange.Redis;
using static Grpc.Health.V1.Health;

namespace cartservice {
    internal class HealthImpl : HealthBase {
        private ICartStore dependency { get; }
        public HealthImpl (ICartStore dependency) {
            this.dependency = dependency;
        }

        public HealthCheckResponse Check (HealthCheckRequest request) {
            Console.WriteLine ("Checking CartService Health");

            return new HealthCheckResponse {
                Status = dependency.Ping() ? HealthCheckResponse.Types.ServingStatus.Serving : HealthCheckResponse.Types.ServingStatus.NotServing
            };
        }
    }
}


text:
<!DOCTYPE html>

		<title>three.js webgl - geometry - minecraft</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

Generating world...

three.js - minecraft demo. featuring painterly pack
(left click: forward, right click: backward)


text:
<?php

final class PholioMockEditor extends PhabricatorApplicationTransactionEditor {

  private $newImages = array();

  public function getEditorApplicationClass() {
    return 'PhabricatorPholioApplication';
  }

  public function getEditorObjectsDescription() {
    return pht('Pholio Mocks');
  }

  private function setNewImages(array $new_images) {
    assert_instances_of($new_images, 'PholioImage');
    $this->newImages = $new_images;
    return $this;
  }
  private function getNewImages() {
    return $this->newImages;
  }

  public function getTransactionTypes() {
    $types = parent::getTransactionTypes();

    $types[] = PhabricatorTransactions::TYPE_EDGE;
    $types[] = PhabricatorTransactions::TYPE_COMMENT;
    $types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
    $types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;

    $types[] = PholioTransaction::TYPE_NAME;
    $types[] = PholioTransaction::TYPE_DESCRIPTION;
    $types[] = PholioTransaction::TYPE_STATUS;
    $types[] = PholioTransaction::TYPE_INLINE;

    $types[] = PholioTransaction::TYPE_IMAGE_FILE;
    $types[] = PholioTransaction::TYPE_IMAGE_NAME;
    $types[] = PholioTransaction::TYPE_IMAGE_DESCRIPTION;
    $types[] = PholioTransaction::TYPE_IMAGE_REPLACE;
    $types[] = PholioTransaction::TYPE_IMAGE_SEQUENCE;

    return $types;
  }

  protected function getCustomTransactionOldValue(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PholioTransaction::TYPE_NAME:
        return $object->getName();
      case PholioTransaction::TYPE_DESCRIPTION:
        return $object->getDescription();
      case PholioTransaction::TYPE_STATUS:
        return $object->getStatus();
      case PholioTransaction::TYPE_IMAGE_FILE:
        $images = $object->getImages();
        return mpull($images, 'getPHID');
      case PholioTransaction::TYPE_IMAGE_NAME:
        $name = null;
        $phid = null;
        $image = $this->getImageForXaction($object, $xaction);
        if ($image) {
          $name = $image->getName();
          $phid = $image->getPHID();
        }
        return array($phid => $name);
      case PholioTransaction::TYPE_IMAGE_DESCRIPTION:
        $description = null;
        $phid = null;
        $image = $this->getImageForXaction($object, $xaction);
        if ($image) {
          $description = $image->getDescription();
          $phid = $image->getPHID();
        }
        return array($phid => $description);
      case PholioTransaction::TYPE_IMAGE_REPLACE:
        $raw = $xaction->getNewValue();
        return $raw->getReplacesImagePHID();
      case PholioTransaction::TYPE_IMAGE_SEQUENCE:
        $sequence = null;
        $phid = null;
        $image = $this->getImageForXaction($object, $xaction);
        if ($image) {
          $sequence = $image->getSequence();
          $phid = $image->getPHID();
        }
        return array($phid => $sequence);
    }
  }

  protected function getCustomTransactionNewValue(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PholioTransaction::TYPE_NAME:
      case PholioTransaction::TYPE_DESCRIPTION:
      case PholioTransaction::TYPE_STATUS:
      case PholioTransaction::TYPE_IMAGE_NAME:
      case PholioTransaction::TYPE_IMAGE_DESCRIPTION:
      case PholioTransaction::TYPE_IMAGE_SEQUENCE:
        return $xaction->getNewValue();
      case PholioTransaction::TYPE_IMAGE_REPLACE:
        $raw = $xaction->getNewValue();
        return $raw->getPHID();
      case PholioTransaction::TYPE_IMAGE_FILE:
        $raw_new_value = $xaction->getNewValue();
        $new_value = array();
        foreach ($raw_new_value as $key => $images) {
          $new_value[$key] = mpull($images, 'getPHID');
        }
        $xaction->setNewValue($new_value);
        return $this->getPHIDTransactionNewValue($xaction);
    }
  }

  protected function extractFilePHIDsFromCustomTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    $images = $this->getNewImages();
    $images = mpull($images, null, 'getPHID');

    switch ($xaction->getTransactionType()) {
      case PholioTransaction::TYPE_IMAGE_FILE:
        $file_phids = array();
        foreach ($xaction->getNewValue() as $image_phid) {
          $image = idx($images, $image_phid);
          if (!$image) {
            continue;
          }
          $file_phids[] = $image->getFilePHID();
        }
        return $file_phids;
      case PholioTransaction::TYPE_IMAGE_REPLACE:
        $image_phid = $xaction->getNewValue();
        $image = idx($images, $image_phid);

        if ($image) {
          return array($image->getFilePHID());
        }
        break;
    }

    return parent::extractFilePHIDsFromCustomTransaction($object, $xaction);
  }

  protected function transactionHasEffect(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PholioTransaction::TYPE_INLINE:
        return true;
    }

    return parent::transactionHasEffect($object, $xaction);
  }

  protected function shouldApplyInitialEffects(
    PhabricatorLiskDAO $object,
    array $xactions) {

    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
        case PholioTransaction::TYPE_IMAGE_FILE:
        case PholioTransaction::TYPE_IMAGE_REPLACE:
          return true;
          break;
      }
    }
    return false;
  }

  protected function applyInitialEffects(
    PhabricatorLiskDAO $object,
    array $xactions) {

    $new_images = array();
    foreach ($xactions as $xaction) {
      switch ($xaction->getTransactionType()) {
        case PholioTransaction::TYPE_IMAGE_FILE:
          $new_value = $xaction->getNewValue();
          foreach ($new_value as $key => $txn_images) {
            if ($key != '+') {
              continue;
            }
            foreach ($txn_images as $image) {
              $image->save();
              $new_images[] = $image;
            }
          }
          break;
        case PholioTransaction::TYPE_IMAGE_REPLACE:
          $image = $xaction->getNewValue();
          $image->save();
          $new_images[] = $image;
          break;
      }
    }
    $this->setNewImages($new_images);
  }

  protected function applyCustomInternalTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PholioTransaction::TYPE_NAME:
        $object->setName($xaction->getNewValue());
        if ($object->getOriginalName() === null) {
          $object->setOriginalName($xaction->getNewValue());
        }
        break;
      case PholioTransaction::TYPE_DESCRIPTION:
        $object->setDescription($xaction->getNewValue());
        break;
      case PholioTransaction::TYPE_STATUS:
        $object->setStatus($xaction->getNewValue());
        break;
    }
  }

  private function getImageForXaction(
    PholioMock $mock,
    PhabricatorApplicationTransaction $xaction) {
    $raw_new_value = $xaction->getNewValue();
    $image_phid = key($raw_new_value);
    $images = $mock->getImages();
    foreach ($images as $image) {
      if ($image->getPHID() == $image_phid) {
        return $image;
      }
    }
    return null;
  }

  protected function applyCustomExternalTransaction(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PholioTransaction::TYPE_IMAGE_FILE:
        $old_map = array_fuse($xaction->getOldValue());
        $new_map = array_fuse($xaction->getNewValue());

        $obsolete_map = array_diff_key($old_map, $new_map);
        $images = $object->getImages();
        foreach ($images as $seq => $image) {
          if (isset($obsolete_map[$image->getPHID()])) {
            $image->setIsObsolete(1);
            $image->save();
            unset($images[$seq]);
          }
        }
        $object->attachImages($images);
        break;
      case PholioTransaction::TYPE_IMAGE_REPLACE:
        $old = $xaction->getOldValue();
        $images = $object->getImages();
        foreach ($images as $seq => $image) {
          if ($image->getPHID() == $old) {
            $image->setIsObsolete(1);
            $image->save();
            unset($images[$seq]);
          }
        }
        $object->attachImages($images);
        break;
      case PholioTransaction::TYPE_IMAGE_NAME:
        $image = $this->getImageForXaction($object, $xaction);
        $value = (string)head($xaction->getNewValue());
        $image->setName($value);
        $image->save();
        break;
      case PholioTransaction::TYPE_IMAGE_DESCRIPTION:
        $image = $this->getImageForXaction($object, $xaction);
        $value = (string)head($xaction->getNewValue());
        $image->setDescription($value);
        $image->save();
        break;
      case PholioTransaction::TYPE_IMAGE_SEQUENCE:
        $image = $this->getImageForXaction($object, $xaction);
        $value = (int)head($xaction->getNewValue());
        $image->setSequence($value);
        $image->save();
        break;
    }
  }

  protected function applyFinalEffects(
    PhabricatorLiskDAO $object,
    array $xactions) {

    $images = $this->getNewImages();
    foreach ($images as $image) {
      $image->setMockID($object->getID());
      $image->save();
    }

    return $xactions;
  }

  protected function mergeTransactions(
    PhabricatorApplicationTransaction $u,
    PhabricatorApplicationTransaction $v) {

    $type = $u->getTransactionType();
    switch ($type) {
      case PholioTransaction::TYPE_NAME:
      case PholioTransaction::TYPE_DESCRIPTION:
      case PholioTransaction::TYPE_STATUS:
        return $v;
      case PholioTransaction::TYPE_IMAGE_REPLACE:
        $u_img = $u->getNewValue();
        $v_img = $v->getNewValue();
        if ($u_img->getReplacesImagePHID() == $v_img->getReplacesImagePHID()) {
          return $v;
        }
        break;
      case PholioTransaction::TYPE_IMAGE_FILE:
        return $this->mergePHIDOrEdgeTransactions($u, $v);
      case PholioTransaction::TYPE_IMAGE_NAME:
      case PholioTransaction::TYPE_IMAGE_DESCRIPTION:
      case PholioTransaction::TYPE_IMAGE_SEQUENCE:
        $raw_new_value_u = $u->getNewValue();
        $raw_new_value_v = $v->getNewValue();
        $phid_u = key($raw_new_value_u);
        $phid_v = key($raw_new_value_v);
        if ($phid_u == $phid_v) {
          return $v;
        }
        break;
    }

    return parent::mergeTransactions($u, $v);
  }

  protected function shouldSendMail(
    PhabricatorLiskDAO $object,
    array $xactions) {
    return true;
  }

  protected function buildReplyHandler(PhabricatorLiskDAO $object) {
    return id(new PholioReplyHandler())
      ->setMailReceiver($object);
  }

  protected function buildMailTemplate(PhabricatorLiskDAO $object) {
    $id = $object->getID();
    $name = $object->getName();
    $original_name = $object->getOriginalName();

    return id(new PhabricatorMetaMTAMail())
      ->setSubject("M{$id}: {$name}")
      ->addHeader('Thread-Topic', "M{$id}: {$original_name}");
  }

  protected function getMailTo(PhabricatorLiskDAO $object) {
    return array(
      $object->getAuthorPHID(),
      $this->requireActor()->getPHID(),
    );
  }

  protected function buildMailBody(
    PhabricatorLiskDAO $object,
    array $xactions) {

    $body = new PhabricatorMetaMTAMailBody();
    $headers = array();
    $comments = array();
    $inline_comments = array();

    foreach ($xactions as $xaction) {
      if ($xaction->shouldHide()) {
        continue;
      }
      $comment = $xaction->getComment();
      switch ($xaction->getTransactionType()) {
        case PholioTransaction::TYPE_INLINE:
          if ($comment && strlen($comment->getContent())) {
            $inline_comments[] = $comment;
          }
          break;
        case PhabricatorTransactions::TYPE_COMMENT:
          if ($comment && strlen($comment->getContent())) {
            $comments[] = $comment->getContent();
          }
        // fallthrough
        default:
          $headers[] = id(clone $xaction)
            ->setRenderingTarget('text')
            ->getTitle();
          break;
      }
    }

    $body->addRawSection(implode("\n", $headers));

    foreach ($comments as $comment) {
      $body->addRawSection($comment);
    }

    if ($inline_comments) {
      $body->addRawSection(pht('INLINE COMMENTS'));
      foreach ($inline_comments as $comment) {
        $text = pht(
          'Image %d: %s',
          $comment->getImageID(),
          $comment->getContent());
        $body->addRawSection($text);
      }
    }

    $body->addLinkSection(
      pht('MOCK DETAIL'),
      PhabricatorEnv::getProductionURI('/M'.$object->getID()));

    return $body;
  }

  protected function getMailSubjectPrefix() {
    return PhabricatorEnv::getEnvConfig('metamta.pholio.subject-prefix');
  }

  public function getMailTagsMap() {
    return array(
      PholioTransaction::MAILTAG_STATUS =>
        pht("A mock's status changes."),
      PholioTransaction::MAILTAG_COMMENT =>
        pht('Someone comments on a mock.'),
      PholioTransaction::MAILTAG_UPDATED =>
        pht('Mock images or descriptions change.'),
      PholioTransaction::MAILTAG_OTHER =>
        pht('Other mock activity not listed above occurs.'),
    );
  }

  protected function shouldPublishFeedStory(
    PhabricatorLiskDAO $object,
    array $xactions) {
    return true;
  }

  protected function supportsSearch() {
    return true;
  }

  protected function shouldApplyHeraldRules(
    PhabricatorLiskDAO $object,
    array $xactions) {
    return true;
  }

  protected function buildHeraldAdapter(
    PhabricatorLiskDAO $object,
    array $xactions) {

    return id(new HeraldPholioMockAdapter())
      ->setMock($object);
  }

  protected function sortTransactions(array $xactions) {
    $head = array();
    $tail = array();

    // Move inline comments to the end, so the comments precede them.
    foreach ($xactions as $xaction) {
      $type = $xaction->getTransactionType();
      if ($type == PholioTransaction::TYPE_INLINE) {
        $tail[] = $xaction;
      } else {
        $head[] = $xaction;
      }
    }

    return array_values(array_merge($head, $tail));
  }

  protected function shouldImplyCC(
    PhabricatorLiskDAO $object,
    PhabricatorApplicationTransaction $xaction) {

    switch ($xaction->getTransactionType()) {
      case PholioTransaction::TYPE_INLINE:
        return true;
    }

    return parent::shouldImplyCC($object, $xaction);
  }

}


text:
How to connect to Matrikon Test Server using utgard / openScada

The purpose of this project is to connect an OPC Server, particularly MatrikonOPC Server for
Simulation and Testing, to an OPC Client, implemented in Java. The study case shown here
takes as model that one described in the tutorial HowToStartWithUtgard.


text:
#import <Cocoa/Cocoa.h>

@interface PlayerWindowController : NSWindowController
{
@private
	void			*_player;				// An instance of AudioPlayer
	NSTimer			*_uiTimer;				// User interface update timer

	NSSlider		*_slider;				// UI elements
	NSTextField		*_elapsed;
	NSTextField		*_remaining;
	NSButton		*_playButton;
	NSButton		*_forwardButton;
	NSButton		*_backwardButton;
}

// IB properties
@property (assign) IBOutlet NSSlider *		slider;
@property (assign) IBOutlet NSTextField *	elapsed;
@property (assign) IBOutlet NSTextField *	remaining;
@property (assign) IBOutlet NSButton *		playButton;
@property (assign) IBOutlet NSButton *		forwardButton;
@property (assign) IBOutlet NSButton *		backwardButton;

// Action methods
- (IBAction) playPause:(id)sender;

- (IBAction) seekForward:(id)sender;
- (IBAction) seekBackward:(id)sender;

- (IBAction) seek:(id)sender;

// Attempt to play the specified file- returns YES if successful
- (BOOL) playURL:(NSURL *)url;

@end


text:
import React from 'react'
import { Advertisement } from 'semantic-ui-react'

const AdvertisementExampleBanner = () => (
  <Advertisement unit='banner' test='Banner' />
)

export default AdvertisementExampleBanner


text:
define(['module_base', 'twitter_fetcher'], function (mod_base, fetcher) {
    return mod_base.extend({
        api_root: "/api/mod/twitter-feed",
        template_root: "/modules/twitter-feed/",
        initialize: function (el, o, callback) {
            var self = this;
            self.base_initialize(el, o, function () {
                if (!self.manifest.options.layout) {
                    throw "Invalid layout specified.";
                }
                require(['text!' + self.template_root + self.manifest.options.layout + '.html'], function (layout) {
                    self.base_render(layout, window.culture, function () {
                        self.load_view_data();
                        if (callback) {
                            callback(self);
                        }
                    });
                });
            });
        },
        load_view_data: function () {
            twitterFetcher.fetch('377701061588316160', 'twitter-feed', 3, true, false, false, '', false, this.handleTweets, false);
        },
        handleTweets: function (tweets) {
            var x = tweets.length;
            var n = 0;
            var html = "";
            var element = document.getElementById('twitter-feed');
            while (n < x) {
                html += "
" + tweets[n] + "
";
                n++;
            }
            element.innerHTML = html;
        }
    });
});


text:
from __future__ import absolute_import
from __future__ import print_function

from typing import Any

from argparse import ArgumentParser
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
from django.db.utils import IntegrityError
from django.utils.translation import ugettext as _
from zerver.models import get_realm, can_add_alias, \
    Realm, RealmAlias
from zerver.lib.actions import get_realm_aliases
from zerver.lib.domains import validate_domain
import sys

class Command(BaseCommand):
    help = """Manage aliases for the specified realm"""

    def add_arguments(self, parser):
        # type: (ArgumentParser) -> None
        parser.add_argument('-r', '--realm',
                            dest='string_id',
                            type=str,
                            required=True,
                            help='The subdomain or string_id of the realm.')
        parser.add_argument('--op',
                            dest='op',
                            type=str,
                            default="show",
                            help='What operation to do (add, show, remove).')
        parser.add_argument('--allow-subdomains',
                            dest='allow_subdomains',
                            action="store_true",
                            default=False,
                            help='Whether subdomains are allowed or not.')
        parser.add_argument('alias', metavar='<alias>', type=str, nargs='?',
                            help="alias to add or remove")

    def handle(self, *args, **options):
        # type: (*Any, **str) -> None
        realm = get_realm(options["string_id"])
        if options["op"] == "show":
            print("Aliases for %s:" % (realm.domain,))
            for alias in get_realm_aliases(realm):
                if alias["allow_subdomains"]:
                    print(alias["domain"] + " (subdomains allowed)")
                else:
                    print(alias["domain"] + " (subdomains not allowed)")
            sys.exit(0)

        domain = options['alias'].strip().lower()
        try:
            validate_domain(domain)
        except ValidationError as e:
            print(e.messages[0])
            sys.exit(1)
        if options["op"] == "add":
            try:
                if not can_add_alias(domain):
                    print(_("The domain %(domain)s belongs to another organization.") % {'domain': domain})
                    sys.exit(1)
                RealmAlias.objects.create(realm=realm, domain=domain,
                                          allow_subdomains=options["allow_subdomains"])
                sys.exit(0)
            except IntegrityError:
                print(_("The domain %(domain)s is already a part of your organization.") % {'domain': domain})
                sys.exit(1)
        elif options["op"] == "remove":
            try:
                RealmAlias.objects.get(realm=realm, domain=domain).delete()
                sys.exit(0)
            except RealmAlias.DoesNotExist:
                print("No such entry found!")
                sys.exit(1)
        else:
            self.print_help("./manage.py", "realm_alias")
            sys.exit(1)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SGTF - Créer Tournoi</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

	<?php include ("connexion_bd.php");?>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Accueil

                        À propos

                        Modifier Tournoi

                        Supprimer Tournoi

                        Contact

				<form action="cible_orga.php" method="post">
					<fieldset>
						<legend> Tournoi </legend>

Nom <input type="text" name="nom_tournoi" autofocus required/>     Date <input type="datetime-local" name="date_tournoi" required/>

Adresse <input type="text" name="rue_tournoi" required/>   Code Postal <input type="text" name="cp_tournoi" required/>   Ville <input type="text" name="ville_tournoi" required/>

Console <select name="console_tournoi" required >
										<option value="Xbox 360">Xbox 360</option>
										<option value="PS3">PS3</option>
										<option value="Xbox One">Xbox One</option>
										<option value="PS4">PS4</option>
									</select>
						Nombre de joueurs maximum <input type="number" min=2 name="nb_joueurs_max" required/>

					</fieldset>

					<fieldset>
						<legend> Organisateur </legend>

 Nom <input type="text" name="nom_orga" required/>  Prénom <input type="text" name="prenom_orga" required/>

 E-mail <input type="email" name="mail_orga" required/> N°Téléphone <input type="tel" name="tel_orga" required/>

					</fieldset>

					<input type="submit" value="Valider" />
				</form>

Par Gabriel Artigues, IG3, 2015


text:
package de.fraunhofer.fokus.ants.jipfix.data;
import de.fraunhofer.fokus.ants.jipfix.jIPFIX;

public class IPFIXSNode {
  //public IPFIXSNode next; //may not always be set
  public long odid;
  public IPFIXInput input;
  public IPFIXTNode templates;
  public long last_seqno;

  public IPFIXSNode(IPFIXSNode n, long o, IPFIXInput i, IPFIXTNode t, String f, long l) {
    //next=n;
    odid=o;
    input=i;
    templates=t;
    last_seqno=l;
  }
}


text:
#include <aws/wisdom/model/KnowledgeBaseType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace ConnectWisdomService
  {
    namespace Model
    {
      namespace KnowledgeBaseTypeMapper
      {

        static const int EXTERNAL_HASH = HashingUtils::HashString("EXTERNAL");
        static const int CUSTOM_HASH = HashingUtils::HashString("CUSTOM");

        KnowledgeBaseType GetKnowledgeBaseTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == EXTERNAL_HASH)
          {
            return KnowledgeBaseType::EXTERNAL;
          }
          else if (hashCode == CUSTOM_HASH)
          {
            return KnowledgeBaseType::CUSTOM;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<KnowledgeBaseType>(hashCode);
          }

          return KnowledgeBaseType::NOT_SET;
        }

        Aws::String GetNameForKnowledgeBaseType(KnowledgeBaseType enumValue)
        {
          switch(enumValue)
          {
          case KnowledgeBaseType::EXTERNAL:
            return "EXTERNAL";
          case KnowledgeBaseType::CUSTOM:
            return "CUSTOM";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace KnowledgeBaseTypeMapper
    } // namespace Model
  } // namespace ConnectWisdomService
} // namespace Aws


text:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var User = require('./models/user-model.js');

/* ============= GOOGLE AUTHENTICATION & PASSPORT CONFIG ================= */
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

// GOOGLE CREDENTIALS
var GOOGLE_CLIENT_ID = "615669438819-m1ilq060a5u3grritkida3edigottqa0.apps.googleusercontent.com";
var GOOGLE_CLIENT_SECRET = "LHzp14JwYUpuKn50eAbr4Xn3";

passport.serializeUser(function (user, done) {
  done(null, user);
});
passport.deserializeUser(function (id, done) {
  console.log("DESERIALIZING!!!!! ", id);
  User.getOne(id, function (err, user) {
  	done(err, user);
  });
});

// WELCOME TO HELL
passport.use(new GoogleStrategy({
    clientID: GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "http://localhost:3000/login-verify"
  },
  function(accessToken, refreshToken, profile, done) {
  	User.getOne(profile.id, function (err, result) {
  		if (result.length === 0) {
  			User.addOne([profile.displayName ,profile.id], function (err, result) {
          if (err) {
            console.log("ERROR: ", err);
          } else {
            console.log("RESULTS: ", result);
          }
  				done(null, result);
  			});
  		} else {
  			done(null, result[0]);
  		};
  	});
  }
));

/* ==================== MIDDLEWARE ================== */
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());

// Allow cross origin requests
var allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8100');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
}
app.use(allowCrossDomain);

//Set up routes
require('./routes/index.js')(app, express, passport);

//Set up static files
app.use(express.static(path.join(__dirname ,'../client')));

// Set up ports
var port = process.env.PORT || 3000;
app.listen(port, function(){
  console.log('Server listening on port ' + port);
});

module.exports = app;


text:
import _ from 'lodash'

const headers = {}

export function setHeaders(_headers) {
  _.extend(headers, _headers)
}

export function beforeSend(xhr) {
  _.forEach(headers, (value, header) => {
    xhr.setRequestHeader(header, value)
  })
}


text:
<?php

namespace OAuth2;

use OAuth2\Request\TestRequest;
use OAuth2\ResponseType\AuthorizationCode;
use OAuth2\Storage\Bootstrap;
use PHPUnit\Framework\TestCase;

class ServerTest extends TestCase
{
    /**
     * @expectedException LogicException OAuth2\Storage\ClientInterface
     **/
    public function testGetAuthorizeControllerWithNoClientStorageThrowsException()
    {
        // must set Client Storage
        $server = new Server();
        $server->getAuthorizeController();
    }

    /**
     * @expectedException LogicException OAuth2\Storage\AccessTokenInterface
     **/
    public function testGetAuthorizeControllerWithNoAccessTokenStorageThrowsException()
    {
        // must set AccessToken or AuthorizationCode
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface'));
        $server->getAuthorizeController();
    }

    public function testGetAuthorizeControllerWithClientStorageAndAccessTokenResponseType()
    {
        // must set AccessToken or AuthorizationCode
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface'));
        $server->addResponseType($this->getMock('OAuth2\ResponseType\AccessTokenInterface'));

        $this->assertNotNull($server->getAuthorizeController());
    }

    public function testGetAuthorizeControllerWithClientStorageAndAuthorizationCodeResponseType()
    {
        // must set AccessToken or AuthorizationCode
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface'));
        $server->addResponseType($this->getMock('OAuth2\ResponseType\AuthorizationCodeInterface'));

        $this->assertNotNull($server->getAuthorizeController());
    }

    /**
     * @expectedException LogicException allow_implicit
     **/
    public function testGetAuthorizeControllerWithClientStorageAndAccessTokenStorageThrowsException()
    {
        // must set AuthorizationCode or AccessToken / implicit
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface'));
        $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface'));

        $this->assertNotNull($server->getAuthorizeController());
    }

    public function testGetAuthorizeControllerWithClientStorageAndAccessTokenStorage()
    {
        // must set AuthorizationCode or AccessToken / implicit
        $server = new Server(array(), array('allow_implicit' => true));
        $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface'));
        $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface'));

        $this->assertNotNull($server->getAuthorizeController());
    }

    public function testGetAuthorizeControllerWithClientStorageAndAuthorizationCodeStorage()
    {
        // must set AccessToken or AuthorizationCode
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface'));
        $server->addStorage($this->getMock('OAuth2\Storage\AuthorizationCodeInterface'));

        $this->assertNotNull($server->getAuthorizeController());
    }

    /**
     * @expectedException LogicException grant_types
     **/
    public function testGetTokenControllerWithGrantTypeStorageThrowsException()
    {
        $server = new Server();
        $server->getTokenController();
    }

    /**
     * @expectedException LogicException OAuth2\Storage\ClientCredentialsInterface
     **/
    public function testGetTokenControllerWithNoClientCredentialsStorageThrowsException()
    {
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\UserCredentialsInterface'));
        $server->getTokenController();
    }

    /**
     * @expectedException LogicException OAuth2\Storage\AccessTokenInterface
     **/
    public function testGetTokenControllerWithNoAccessTokenStorageThrowsException()
    {
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface'));
        $server->getTokenController();
    }

    public function testGetTokenControllerWithAccessTokenAndClientCredentialsStorage()
    {
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface'));
        $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface'));
        $server->getTokenController();
    }

    public function testGetTokenControllerAccessTokenStorageAndClientCredentialsStorageAndGrantTypes()
    {
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface'));
        $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface'));
        $server->addGrantType($this->getMockBuilder('OAuth2\GrantType\AuthorizationCode')->disableOriginalConstructor()->getMock());
        $server->getTokenController();
    }

    /**
     * @expectedException LogicException OAuth2\Storage\AccessTokenInterface
     **/
    public function testGetResourceControllerWithNoAccessTokenStorageThrowsException()
    {
        $server = new Server();
        $server->getResourceController();
    }

    public function testGetResourceControllerWithAccessTokenStorage()
    {
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface'));
        $server->getResourceController();
    }

    /**
     * @expectedException InvalidArgumentException OAuth2\Storage\AccessTokenInterface
     **/
    public function testAddingStorageWithInvalidClass()
    {
        $server = new Server();
        $server->addStorage(new \StdClass());
    }

    /**
     * @expectedException InvalidArgumentException access_token
     **/
    public function testAddingStorageWithInvalidKey()
    {
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface'), 'nonexistant_storage');
    }

    /**
     * @expectedException InvalidArgumentException OAuth2\Storage\AuthorizationCodeInterface
     **/
    public function testAddingStorageWithInvalidKeyStorageCombination()
    {
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface'), 'authorization_code');
    }

    public function testAddingStorageWithValidKeyOnlySetsThatKey()
    {
        $server = new Server();
        $server->addStorage($this->getMock('OAuth2\Storage\Memory'), 'access_token');

        $reflection = new \ReflectionClass($server);
        $prop = $reflection->getProperty('storages');
        $prop->setAccessible(true);

        $storages = $prop->getValue($server); // get the private "storages" property

        $this->assertEquals(1, count($storages));
        $this->assertTrue(isset($storages['access_token']));
        $this->assertFalse(isset($storages['authorization_code']));
    }

    public function testAddingClientStorageSetsClientCredentialsStorageByDefault()
    {
        $server = new Server();
        $memory = $this->getMock('OAuth2\Storage\Memory');
        $server->addStorage($memory, 'client');

        $client_credentials = $server->getStorage('client_credentials');

        $this->assertNotNull($client_credentials);
        $this->assertEquals($client_credentials, $memory);
    }

    public function testAddStorageWithNullValue()
    {
        $memory = $this->getMock('OAuth2\Storage\Memory');
        $server = new Server($memory);
        $server->addStorage(null, 'refresh_token');

        $client_credentials = $server->getStorage('client_credentials');

        $this->assertNotNull($client_credentials);
        $this->assertEquals($client_credentials, $memory);

        $refresh_token = $server->getStorage('refresh_token');

        $this->assertNull($refresh_token);
    }

    public function testNewServerWithNullStorageValue()
    {
        $memory = $this->getMock('OAuth2\Storage\Memory');
        $server = new Server(array(
            'client_credentials' => $memory,
            'refresh_token'      => null,
        ));

        $client_credentials = $server->getStorage('client_credentials');

        $this->assertNotNull($client_credentials);
        $this->assertEquals($client_credentials, $memory);

        $refresh_token = $server->getStorage('refresh_token');

        $this->assertNull($refresh_token);
    }

    public function testAddingClientCredentialsStorageSetsClientStorageByDefault()
    {
        $server = new Server();
        $memory = $this->getMock('OAuth2\Storage\Memory');
        $server->addStorage($memory, 'client_credentials');

        $client = $server->getStorage('client');

        $this->assertNotNull($client);
        $this->assertEquals($client, $memory);
    }

    public function testSettingClientStorageByDefaultDoesNotOverrideSetStorage()
    {
        $server = new Server();
        $pdo = $this->getMockBuilder('OAuth2\Storage\Pdo')
            ->disableOriginalConstructor()->getMock();

        $memory = $this->getMock('OAuth2\Storage\Memory');

        $server->addStorage($pdo, 'client');
        $server->addStorage($memory, 'client_credentials');

        $client = $server->getStorage('client');
        $client_credentials = $server->getStorage('client_credentials');

        $this->assertEquals($client, $pdo);
        $this->assertEquals($client_credentials, $memory);
    }

    public function testAddingResponseType()
    {
        $storage = $this->getMock('OAuth2\Storage\Memory');
        $storage
          ->expects($this->any())
          ->method('getClientDetails')
          ->will($this->returnValue(array('client_id' => 'some_client')));
        $storage
          ->expects($this->any())
          ->method('checkRestrictedGrantType')
          ->will($this->returnValue(true));

        // add with the "code" key explicitly set
        $codeType = new AuthorizationCode($storage);
        $server = new Server();
        $server->addStorage($storage);
        $server->addResponseType($codeType);
        $request = new Request(array(
            'response_type' => 'code',
            'client_id' => 'some_client',
            'redirect_uri' => 'http://example.com',
            'state' => 'xyx',
        ));
        $server->handleAuthorizeRequest($request, $response = new Response(), true);

        // the response is successful
        $this->assertEquals($response->getStatusCode(), 302);
        $parts = parse_url($response->getHttpHeader('Location'));
        parse_str($parts['query'], $query);
        $this->assertTrue(isset($query['code']));
        $this->assertFalse(isset($query['error']));

        // add with the "code" key not set
        $codeType = new AuthorizationCode($storage);
        $server = new Server(array($storage), array(), array(), array($codeType));
        $request = new Request(array(
            'response_type' => 'code',
            'client_id' => 'some_client',
            'redirect_uri' => 'http://example.com',
            'state' => 'xyx',
        ));
        $server->handleAuthorizeRequest($request, $response = new Response(), true);

        // the response is successful
        $this->assertEquals($response->getStatusCode(), 302);
        $parts = parse_url($response->getHttpHeader('Location'));
        parse_str($parts['query'], $query);
        $this->assertTrue(isset($query['code']));
        $this->assertFalse(isset($query['error']));
    }

    public function testCustomClientAssertionType()
    {
        $request = TestRequest::createPost(array(
            'grant_type' => 'authorization_code',
            'client_id' =>'Test Client ID',
            'code' => 'testcode',
        ));
        // verify the mock clientAssertionType was called as expected
        $clientAssertionType = $this->getMock('OAuth2\ClientAssertionType\ClientAssertionTypeInterface', array('validateRequest', 'getClientId'));
        $clientAssertionType
            ->expects($this->once())
            ->method('validateRequest')
            ->will($this->returnValue(true));
        $clientAssertionType
            ->expects($this->once())
            ->method('getClientId')
            ->will($this->returnValue('Test Client ID'));

        // create mock storage
        $storage = Bootstrap::getInstance()->getMemoryStorage();
        $server = new Server(array($storage), array(), array(), array(), null, null, $clientAssertionType);
        $server->handleTokenRequest($request, $response = new Response());
    }

    public function testHttpBasicConfig()
    {
        // create mock storage
        $storage = Bootstrap::getInstance()->getMemoryStorage();
        $server = new Server(array($storage), array(
            'allow_credentials_in_request_body' => false,
            'allow_public_clients' => false
        ));
        $server->getTokenController();
        $httpBasic = $server->getClientAssertionType();

        $reflection = new \ReflectionClass($httpBasic);
        $prop = $reflection->getProperty('config');
        $prop->setAccessible(true);

        $config = $prop->getValue($httpBasic); // get the private "config" property

        $this->assertEquals($config['allow_credentials_in_request_body'], false);
        $this->assertEquals($config['allow_public_clients'], false);
    }

    public function testRefreshTokenConfig()
    {
        // create mock storage
        $storage = Bootstrap::getInstance()->getMemoryStorage();
        $server1 = new Server(array($storage));
        $server2 = new Server(array($storage), array('always_issue_new_refresh_token' => true, 'unset_refresh_token_after_use' => false));

        $server1->getTokenController();
        $refreshToken1 = $server1->getGrantType('refresh_token');

        $server2->getTokenController();
        $refreshToken2 = $server2->getGrantType('refresh_token');

        $reflection1 = new \ReflectionClass($refreshToken1);
        $prop1 = $reflection1->getProperty('config');
        $prop1->setAccessible(true);

        $reflection2 = new \ReflectionClass($refreshToken2);
        $prop2 = $reflection2->getProperty('config');
        $prop2->setAccessible(true);

        // get the private "config" property
        $config1 = $prop1->getValue($refreshToken1);
        $config2 = $prop2->getValue($refreshToken2);

        $this->assertEquals($config1['always_issue_new_refresh_token'], false);
        $this->assertEquals($config2['always_issue_new_refresh_token'], true);

        $this->assertEquals($config1['unset_refresh_token_after_use'], true);
        $this->assertEquals($config2['unset_refresh_token_after_use'], false);
    }

    /**
     * Test setting "always_issue_new_refresh_token" on a server level
     *
     * @see test/OAuth2/GrantType/RefreshTokenTest::testValidRefreshTokenWithNewRefreshTokenInResponse
     **/
    public function testValidRefreshTokenWithNewRefreshTokenInResponse()
    {
        $storage = Bootstrap::getInstance()->getMemoryStorage();
        $server = new Server($storage, array('always_issue_new_refresh_token' => true));

        $request = TestRequest::createPost(array(
            'grant_type' => 'refresh_token', // valid grant type
            'client_id' => 'Test Client ID', // valid client id
            'client_secret' => 'TestSecret', // valid client secret
            'refresh_token' => 'test-refreshtoken', // valid refresh token
        ));
        $token = $server->grantAccessToken($request, new Response());
        $this->assertTrue(isset($token['refresh_token']), 'refresh token should always refresh');

        $refresh_token = $storage->getRefreshToken($token['refresh_token']);
        $this->assertNotNull($refresh_token);
        $this->assertEquals($refresh_token['refresh_token'], $token['refresh_token']);
        $this->assertEquals($refresh_token['client_id'], $request->request('client_id'));
        $this->assertTrue($token['refresh_token'] != 'test-refreshtoken', 'the refresh token returned is not the one used');
        $used_token = $storage->getRefreshToken('test-refreshtoken');
        $this->assertFalse($used_token, 'the refresh token used is no longer valid');
    }

    /**
     * @expectedException InvalidArgumentException OAuth2\ResponseType\AuthorizationCodeInterface
     **/
    public function testAddingUnknownResponseTypeThrowsException()
    {
        $server = new Server();
        $server->addResponseType($this->getMock('OAuth2\ResponseType\ResponseTypeInterface'));
    }

    /**
     * @expectedException LogicException OAuth2\Storage\PublicKeyInterface
     **/
    public function testUsingJwtAccessTokensWithoutPublicKeyStorageThrowsException()
    {
        $server = new Server(array(), array('use_jwt_access_tokens' => true));
        $server->addGrantType($this->getMock('OAuth2\GrantType\GrantTypeInterface'));
        $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface'));
        $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface'));

        $server->getTokenController();
    }

    public function testUsingJustJwtAccessTokenStorageWithResourceControllerIsOkay()
    {
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $server = new Server(array($pubkey), array('use_jwt_access_tokens' => true));

        $this->assertNotNull($server->getResourceController());
        $this->assertInstanceOf('OAuth2\Storage\PublicKeyInterface', $server->getStorage('public_key'));
    }

    /**
     * @expectedException LogicException OAuth2\Storage\ClientInterface
     **/
    public function testUsingJustJwtAccessTokenStorageWithAuthorizeControllerThrowsException()
    {
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $server = new Server(array($pubkey), array('use_jwt_access_tokens' => true));
        $this->assertNotNull($server->getAuthorizeController());
    }

    /**
     * @expectedException LogicException grant_types
     **/
    public function testUsingJustJwtAccessTokenStorageWithTokenControllerThrowsException()
    {
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $server = new Server(array($pubkey), array('use_jwt_access_tokens' => true));
        $server->getTokenController();
    }

    public function testUsingJwtAccessTokenAndClientStorageWithAuthorizeControllerIsOkay()
    {
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $client = $this->getMock('OAuth2\Storage\ClientInterface');
        $server = new Server(array($pubkey, $client), array('use_jwt_access_tokens' => true, 'allow_implicit' => true));
        $this->assertNotNull($server->getAuthorizeController());

        $this->assertInstanceOf('OAuth2\ResponseType\JwtAccessToken', $server->getResponseType('token'));
    }

    /**
     * @expectedException LogicException UserClaims
     **/
    public function testUsingOpenIDConnectWithoutUserClaimsThrowsException()
    {
        $client = $this->getMock('OAuth2\Storage\ClientInterface');
        $server = new Server($client, array('use_openid_connect' => true));

        $server->getAuthorizeController();
    }

    /**
     * @expectedException LogicException PublicKeyInterface
     **/
    public function testUsingOpenIDConnectWithoutPublicKeyThrowsException()
    {
        $client = $this->getMock('OAuth2\Storage\ClientInterface');
        $userclaims = $this->getMock('OAuth2\OPenID\Storage\UserClaimsInterface');
        $server = new Server(array($client, $userclaims), array('use_openid_connect' => true));

        $server->getAuthorizeController();
    }

    /**
     * @expectedException LogicException issuer
     **/
    public function testUsingOpenIDConnectWithoutIssuerThrowsException()
    {
        $client = $this->getMock('OAuth2\Storage\ClientInterface');
        $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface');
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $server = new Server(array($client, $userclaims, $pubkey), array('use_openid_connect' => true));

        $server->getAuthorizeController();
    }

    public function testUsingOpenIDConnectWithIssuerPublicKeyAndUserClaimsIsOkay()
    {
        $client = $this->getMock('OAuth2\Storage\ClientInterface');
        $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface');
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $server = new Server(array($client, $userclaims, $pubkey), array(
            'use_openid_connect' => true,
            'issuer' => 'someguy',
        ));

        $server->getAuthorizeController();

        $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenInterface', $server->getResponseType('id_token'));
        $this->assertNull($server->getResponseType('id_token token'));
    }

    /**
     * @expectedException LogicException OAuth2\ResponseType\AccessTokenInterface
     **/
    public function testUsingOpenIDConnectWithAllowImplicitWithoutTokenStorageThrowsException()
    {
        $client = $this->getMock('OAuth2\Storage\ClientInterface');
        $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface');
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $server = new Server(array($client, $userclaims, $pubkey), array(
            'use_openid_connect' => true,
            'issuer' => 'someguy',
            'allow_implicit' => true,
        ));

        $server->getAuthorizeController();
    }

    public function testUsingOpenIDConnectWithAllowImplicitAndUseJwtAccessTokensIsOkay()
    {
        $client = $this->getMock('OAuth2\Storage\ClientInterface');
        $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface');
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $server = new Server(array($client, $userclaims, $pubkey), array(
            'use_openid_connect' => true,
            'issuer' => 'someguy',
            'allow_implicit' => true,
            'use_jwt_access_tokens' => true,
        ));

        $server->getAuthorizeController();

        $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenInterface', $server->getResponseType('id_token'));
        $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenTokenInterface', $server->getResponseType('id_token token'));
    }

    public function testUsingOpenIDConnectWithAllowImplicitAndAccessTokenStorageIsOkay()
    {
        $client = $this->getMock('OAuth2\Storage\ClientInterface');
        $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface');
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $token = $this->getMock('OAuth2\Storage\AccessTokenInterface');
        $server = new Server(array($client, $userclaims, $pubkey, $token), array(
            'use_openid_connect' => true,
            'issuer' => 'someguy',
            'allow_implicit' => true,
        ));

        $server->getAuthorizeController();

        $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenInterface', $server->getResponseType('id_token'));
        $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenTokenInterface', $server->getResponseType('id_token token'));
    }

    public function testUsingOpenIDConnectWithAllowImplicitAndAccessTokenResponseTypeIsOkay()
    {
        $client = $this->getMock('OAuth2\Storage\ClientInterface');
        $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface');
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        // $token = $this->getMock('OAuth2\Storage\AccessTokenInterface');
        $server = new Server(array($client, $userclaims, $pubkey), array(
            'use_openid_connect' => true,
            'issuer' => 'someguy',
            'allow_implicit' => true,
        ));

        $token = $this->getMock('OAuth2\ResponseType\AccessTokenInterface');
        $server->addResponseType($token, 'token');

        $server->getAuthorizeController();

        $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenInterface', $server->getResponseType('id_token'));
        $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenTokenInterface', $server->getResponseType('id_token token'));
    }

    /**
     * @expectedException LogicException OAuth2\OpenID\Storage\AuthorizationCodeInterface
     **/
    public function testUsingOpenIDConnectWithAuthorizationCodeStorageThrowsException()
    {
        $client = $this->getMock('OAuth2\Storage\ClientCredentialsInterface');
        $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface');
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $token = $this->getMock('OAuth2\Storage\AccessTokenInterface');
        $authcode = $this->getMock('OAuth2\Storage\AuthorizationCodeInterface');

        $server = new Server(array($client, $userclaims, $pubkey, $token, $authcode), array(
            'use_openid_connect' => true,
            'issuer' => 'someguy'
        ));

        $server->getTokenController();

        $this->assertInstanceOf('OAuth2\OpenID\GrantType\AuthorizationCode', $server->getGrantType('authorization_code'));
    }

    public function testUsingOpenIDConnectWithOpenIDAuthorizationCodeStorageCreatesOpenIDAuthorizationCodeGrantType()
    {
        $client = $this->getMock('OAuth2\Storage\ClientCredentialsInterface');
        $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface');
        $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface');
        $token = $this->getMock('OAuth2\Storage\AccessTokenInterface');
        $authcode = $this->getMock('OAuth2\OpenID\Storage\AuthorizationCodeInterface');

        $server = new Server(array($client, $userclaims, $pubkey, $token, $authcode), array(
            'use_openid_connect' => true,
            'issuer' => 'someguy'
        ));

        $server->getTokenController();

        $this->assertInstanceOf('OAuth2\OpenID\GrantType\AuthorizationCode', $server->getGrantType('authorization_code'));
    }

    public function testMultipleValuedResponseTypeOrderDoesntMatter()
    {
        $responseType = $this->getMock('OAuth2\OpenID\ResponseType\IdTokenTokenInterface');
        $server = new Server(array(), array(), array(), array(
            'token id_token' => $responseType,
        ));

        $this->assertEquals($responseType, $server->getResponseType('id_token token'));
    }

    public function testAddGrantTypeWithoutKey()
    {
        $server = new Server();
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($this->getMock('OAuth2\Storage\AuthorizationCodeInterface')));

        $grantTypes = $server->getGrantTypes();
        $this->assertEquals('authorization_code', key($grantTypes));
    }

    public function testAddGrantTypeWithKey()
    {
        $server = new Server();
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($this->getMock('OAuth2\Storage\AuthorizationCodeInterface')), 'ac');

        $grantTypes = $server->getGrantTypes();
        $this->assertEquals('ac', key($grantTypes));
    }

    public function testAddGrantTypeWithKeyNotString()
    {
        $server = new Server();
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($this->getMock('OAuth2\Storage\AuthorizationCodeInterface')), 42);

        $grantTypes = $server->getGrantTypes();
        $this->assertEquals('authorization_code', key($grantTypes));
    }
}


text:
            <?php echo $title ?>
            Web Applications

                <?php echo $this->session->flashdata('notif') ?>

 Data Panitia

                        <form method="GET" action="<?php echo base_url('apps/panitia/search');?>" style="margin-top: 10px">

                              <a href="<?php echo base_url('apps/panitia/add?source=add&utf8=✓') ?>" class = "btn btn-default btn-md" type = "button">
                                 Tambah

                                <input type = "text" name = "q" class = "form-control input-md" placeholder="Masukkan kata kunci dan enter" autocomplete="off" id="articles">
                                <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">

                              <button class = "btn btn-default btn-md" type = "submit">
                                  Search
                              </button>

                        </form>

                                    No.
                                     NAMA PANITIA
                                     OPTIONS

                                <?php
                                if($panitia != NULL):
                                $no = $this->uri->segment(4) + 1;
                                foreach($panitia->result() as $hasil):
                                    ?>

                                        <?php echo $no++; ?>
                                         <?php echo $hasil->nama_panitia ?>

                                            <a class='badge badge-success' style="font-family: Roboto;font-weight: 400;background-color: #358420;" data-toggle="tooltip" data-placement="top" title="Edit" href='<?php echo base_url() ?>apps/panitia/edit/<?php echo $this->encryption->encode($hasil->id_panitia) ?>'> Edit

                                    <?php
                                endforeach;
                                ?>

                            <?php echo $paging ?>
                            <?php else : ?>

                                     Warning!  Data tidak ada didatabase

                                    <a  href="<?php echo base_url('apps/panitia?source=reload&utf8=✓') ?>" class="btn btn-danger btn-reset btn-fill" id="load" data-loading-text=" Reloading..."> Reload Page

                            <?php endif; ?>


text:
package storm.kafka.trident.functions;

import backtype.storm.tuple.Values;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;

public class WordSplit extends BaseFunction {
    public void execute(TridentTuple tuple, TridentCollector collector) {
        String sentence = (String) tuple.getValue(0);
        if (sentence != null) {
            sentence = sentence.replaceAll("\r", "");
            sentence = sentence.replaceAll("\n", "");
            for (String word : sentence.split(" ")) {
                collector.emit(new Values(word));
            }
        }
    }
}


text:
package org.apache.ignite.spi.loadbalancing.weightedrandom;

import org.apache.ignite.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.testframework.*;
import org.apache.ignite.testframework.junits.spi.*;

import java.util.*;

/**
 * Weighted random load balancing SPI.
 */
@GridSpiTest(spi = WeightedRandomLoadBalancingSpi.class, group = "Load Balancing SPI")
public class GridWeightedRandomLoadBalancingSpiSelfTest extends
    GridSpiAbstractTest<WeightedRandomLoadBalancingSpi> {
    /**
     * @throws Exception If failed.
     */
    @SuppressWarnings({"ObjectEquality"})
    public void testSingleNode() throws Exception {
        List<ClusterNode> nodes = Collections.singletonList((ClusterNode)new GridTestNode(UUID.randomUUID()));

        ClusterNode node = getSpi().getBalancedNode(new GridTestTaskSession(), nodes, new GridTestJob());

        assert nodes.contains(node);

        // Verify that same instance is returned every time.
        ClusterNode balancedNode = getSpi().getBalancedNode(new GridTestTaskSession(), nodes, new GridTestJob());

        assert node == balancedNode;
    }

    /**
     * @throws Exception If failed.
     */
    public void testMultipleNodes() throws Exception {
        List<ClusterNode> nodes = new ArrayList<>();

        for (int i = 0; i < 10; i++)
            nodes.add(new GridTestNode(UUID.randomUUID()));

        // Seal it.
        nodes = Collections.unmodifiableList(nodes);

        ClusterNode node = getSpi().getBalancedNode(new GridTestTaskSession(), nodes, new GridTestJob());

        assert node != null;
        assert nodes.contains(node);
    }
}


text:
package httpserverexample.stackoverflow.ase.com.httpserverexample;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * To work on unit tests, switch the Test Artifact in the Build Variants view.
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}


text:
use math::{Point2, Point3, Point4};
use rand::{Rand, Rng, SeedableRng, XorShiftRng};
use std::fmt;

const TABLE_SIZE: usize = 256;

/// A seed table, required by all noise functions.
///
/// Table creation is expensive, so in most circumstances you'll only want to
/// create one of these per generator.
#[derive(Copy)]
pub struct PermutationTable {
    values: [u8; TABLE_SIZE],
}

impl Rand for PermutationTable {
    /// Generates a PermutationTable using a random seed.
    fn rand<R: Rng>(rng: &mut R) -> PermutationTable {
        let mut seq: Vec<u8> = (0..TABLE_SIZE).map(|x| x as u8).collect();
        rng.shuffle(&mut *seq);

        // It's unfortunate that this double-initializes the array, but Rust
        // doesn't currently provide a clean way to do this in one pass. Hopefully
        // it won't matter, as Seed creation will usually be a one-time event.
        let mut perm_table = PermutationTable { values: [0; TABLE_SIZE] };
        let seq_it = seq.iter();
        for (x, y) in perm_table.values.iter_mut().zip(seq_it) {
            *x = *y
        }
        perm_table
    }
}

impl PermutationTable {
    /// Deterministically generates a new permutation table based on a `u32` seed value.
    ///
    /// Internally this uses a `XorShiftRng`, but we don't really need to worry
    /// about cryptographic security when working with procedural noise.
    pub fn new(seed: u32) -> PermutationTable {
        let mut rng: XorShiftRng = SeedableRng::from_seed([1, seed, seed, seed]);
        rng.gen()
    }

    #[inline(always)]
    pub fn get1(&self, x: isize) -> usize {
        let x = (x & 0xff) as usize;
        self.values[x] as usize
    }

    #[inline(always)]
    pub fn get2(&self, pos: Point2<isize>) -> usize {
        let y = (pos[1] & 0xff) as usize;
        self.values[self.get1(pos[0]) ^ y] as usize
    }

    #[inline(always)]
    pub fn get3(&self, pos: Point3<isize>) -> usize {
        let z = (pos[2] & 0xff) as usize;
        self.values[self.get2([pos[0], pos[1]]) ^ z] as usize
    }

    #[inline(always)]
    pub fn get4(&self, pos: Point4<isize>) -> usize {
        let w = (pos[3] & 0xff) as usize;
        self.values[self.get3([pos[0], pos[1], pos[2]]) ^ w] as usize
    }
}

impl Clone for PermutationTable {
    fn clone(&self) -> PermutationTable {
        PermutationTable { values: self.values }
    }
}

impl fmt::Debug for PermutationTable {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "PermutationTable {{ .. }}")
    }
}

#[cfg(test)]
mod tests {
    use {NoiseFn, Perlin, Seedable};
    use rand::random;

    #[test]
    fn test_random_seed() {
        let perlin = Perlin::new().set_seed(random());
        let _ = perlin.get([1.0, 2.0, 3.0]);
    }

    #[test]
    fn test_negative_params() {
        let perlin = Perlin::new();
        let _ = perlin.get([-1.0, 2.0, 3.0]);
    }
}


text:
<?php

class PluginLitwit_ActionLitwit extends ActionPlugin
{
    function Init()
    {
        $this->SetDefaultEvent('index');
    }

    protected function RegisterEvent()
    {
        $this->AddEvent('index', 'ShowPost');

    }

    public function ShowPost()
    {

    }
}


text:
"""
Management class for Storage-related functions (attach, detach, etc).
"""

from nova import exception
from nova.i18n import _
from nova.openstack.common import excutils
from nova.openstack.common import log as logging
from nova.virt.xenapi import vm_utils
from nova.virt.xenapi import volume_utils

LOG = logging.getLogger(__name__)

class VolumeOps(object):
    """Management class for Volume-related tasks."""

    def __init__(self, session):
        self._session = session

    def attach_volume(self, connection_info, instance_name, mountpoint,
                      hotplug=True):
        """Attach volume to VM instance."""
        # TODO(johngarbutt) move this into _attach_volume_to_vm
        dev_number = volume_utils.get_device_number(mountpoint)

        vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name)
        return self._attach_volume(connection_info, vm_ref,
                                   instance_name, dev_number, hotplug)

    def connect_volume(self, connection_info):
        """Attach volume to hypervisor, but not the VM."""
        return self._attach_volume(connection_info)

    def _attach_volume(self, connection_info, vm_ref=None, instance_name=None,
                       dev_number=None, hotplug=False):

        self._check_is_supported_driver_type(connection_info)

        connection_data = connection_info['data']
        sr_ref, sr_uuid = self._connect_to_volume_provider(connection_data,
                                                           instance_name)
        try:
            vdi_ref = self._connect_hypervisor_to_volume(sr_ref,
                                                         connection_data)
            vdi_uuid = self._session.VDI.get_uuid(vdi_ref)
            LOG.info(_('Connected volume (vdi_uuid): %s'), vdi_uuid)

            if vm_ref:
                self._attach_volume_to_vm(vdi_ref, vm_ref, instance_name,
                                          dev_number, hotplug)

            return (sr_uuid, vdi_uuid)
        except Exception:
            with excutils.save_and_reraise_exception():
                # NOTE(sirp): Forgetting the SR will have the effect of
                # cleaning up the VDI and VBD records, so no need to handle
                # that explicitly.
                volume_utils.forget_sr(self._session, sr_ref)

    def _check_is_supported_driver_type(self, connection_info):
        driver_type = connection_info['driver_volume_type']
        if driver_type not in ['iscsi', 'xensm']:
            raise exception.VolumeDriverNotFound(driver_type=driver_type)

    def _connect_to_volume_provider(self, connection_data, instance_name):
        sr_uuid, sr_label, sr_params = volume_utils.parse_sr_info(
                connection_data, 'Disk-for:%s' % instance_name)
        sr_ref = volume_utils.find_sr_by_uuid(self._session, sr_uuid)
        if not sr_ref:
            # introduce SR because not already present
            sr_ref = volume_utils.introduce_sr(
                    self._session, sr_uuid, sr_label, sr_params)
        return (sr_ref, sr_uuid)

    def _connect_hypervisor_to_volume(self, sr_ref, connection_data):
        LOG.debug("Connect volume to hypervisor: %s", connection_data)
        if 'vdi_uuid' in connection_data:
            vdi_ref = volume_utils.introduce_vdi(
                    self._session, sr_ref,
                    vdi_uuid=connection_data['vdi_uuid'])

        elif 'target_lun' in connection_data:
            vdi_ref = volume_utils.introduce_vdi(
                    self._session, sr_ref,
                    target_lun=connection_data['target_lun'])

        else:
            # NOTE(sirp): This will introduce the first VDI in the SR
            vdi_ref = volume_utils.introduce_vdi(self._session, sr_ref)

        return vdi_ref

    def _attach_volume_to_vm(self, vdi_ref, vm_ref, instance_name, dev_number,
                             hotplug):
        msg = _('Attach_volume vdi: %(vdi_ref)s vm: %(vm_ref)s')
        LOG.debug(msg, {'vdi_ref': vdi_ref, 'vm_ref': vm_ref})

        # osvol is added to the vbd so we can spot which vbds are volumes
        vbd_ref = vm_utils.create_vbd(self._session, vm_ref, vdi_ref,
                                      dev_number, bootable=False,
                                      osvol=True)
        if hotplug:
            # NOTE(johngarbutt) can only call VBD.plug on a running vm
            running = not vm_utils.is_vm_shutdown(self._session, vm_ref)
            if running:
                LOG.debug("Plugging VBD: %s", vbd_ref)
                self._session.VBD.plug(vbd_ref, vm_ref)

        LOG.info(_('Dev %(dev_number)s attached to'
                   ' instance %(instance_name)s'),
                 {'instance_name': instance_name, 'dev_number': dev_number})

    def detach_volume(self, connection_info, instance_name, mountpoint):
        """Detach volume storage to VM instance."""
        LOG.debug("Detach_volume: %(instance_name)s, %(mountpoint)s",
                  {'instance_name': instance_name, 'mountpoint': mountpoint})

        vm_ref = vm_utils.vm_ref_or_raise(self._session, instance_name)

        device_number = volume_utils.get_device_number(mountpoint)
        vbd_ref = volume_utils.find_vbd_by_number(self._session, vm_ref,
                                                  device_number)

        if vbd_ref is None:
            # NOTE(sirp): If we don't find the VBD then it must have been
            # detached previously.
            LOG.warn(_('Skipping detach because VBD for %s was not found'),
                     instance_name)
        else:
            self._detach_vbds_and_srs(vm_ref, [vbd_ref])
            LOG.info(_('Mountpoint %(mountpoint)s detached from instance'
                       ' %(instance_name)s'),
                     {'instance_name': instance_name,
                      'mountpoint': mountpoint})

    def _detach_vbds_and_srs(self, vm_ref, vbd_refs):
        is_vm_shutdown = vm_utils.is_vm_shutdown(self._session, vm_ref)

        for vbd_ref in vbd_refs:
            # find sr before we destroy the vbd
            sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref)

            if not is_vm_shutdown:
                vm_utils.unplug_vbd(self._session, vbd_ref, vm_ref)

            vm_utils.destroy_vbd(self._session, vbd_ref)
            # Forget (i.e. disconnect) SR only if not in use
            volume_utils.purge_sr(self._session, sr_ref)

    def detach_all(self, vm_ref):
        """Detach all cinder volumes."""
        vbd_refs = self._get_all_volume_vbd_refs(vm_ref)
        if vbd_refs:
            self._detach_vbds_and_srs(vm_ref, vbd_refs)

    def _get_all_volume_vbd_refs(self, vm_ref):
        """Return VBD refs for all Nova/Cinder volumes."""
        vbd_refs = self._session.VM.get_VBDs(vm_ref)
        for vbd_ref in vbd_refs:
            other_config = self._session.VBD.get_other_config(vbd_ref)
            if other_config.get('osvol'):
                yield vbd_ref

    def find_bad_volumes(self, vm_ref):
        """Find any volumes with their connection severed.

        Certain VM operations (e.g. `VM.start`, `VM.reboot`, etc.) will not
        work when a VBD is present that points to a non-working volume. To work
        around this, we scan for non-working volumes and detach them before
        retrying a failed operation.
        """
        bad_devices = []
        vbd_refs = self._get_all_volume_vbd_refs(vm_ref)
        for vbd_ref in vbd_refs:
            sr_ref = volume_utils.find_sr_from_vbd(self._session, vbd_ref)

            try:
                # TODO(sirp): bug1152401 This relies on a 120 sec timeout
                # within XenServer, update this to fail-fast when this is fixed
                # upstream
                self._session.SR.scan(sr_ref)
            except self._session.XenAPI.Failure as exc:
                if exc.details[0] == 'SR_BACKEND_FAILURE_40':
                    device = self._session.VBD.get_device(vbd_ref)
                    bad_devices.append('/dev/%s' % device)
                else:
                    raise

        return bad_devices

    def safe_cleanup_from_vdis(self, vdi_refs):
        # A helper method to detach volumes that are not associated with an
        # instance

        for vdi_ref in vdi_refs:
            try:
                sr_ref = volume_utils.find_sr_from_vdi(self._session, vdi_ref)
            except exception.StorageError as exc:
                LOG.debug(exc.format_message())
                continue
            try:
                # Forget (i.e. disconnect) SR only if not in use
                volume_utils.purge_sr(self._session, sr_ref)
            except Exception:
                LOG.debug('Ignoring error while purging sr: %s' % sr_ref,
                        exc_info=True)