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

import java.util.{ArrayList, List => JList}

import test.org.apache.spark.sql.sources.v2._

import org.apache.spark.SparkException
import org.apache.spark.sql.{AnalysisException, DataFrame, QueryTest, Row}
import org.apache.spark.sql.catalyst.expressions.UnsafeRow
import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, DataSourceV2ScanExec}
import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
import org.apache.spark.sql.functions._
import org.apache.spark.sql.sources.{Filter, GreaterThan}
import org.apache.spark.sql.sources.v2.reader._
import org.apache.spark.sql.sources.v2.reader.partitioning.{ClusteredDistribution, Distribution, Partitioning}
import org.apache.spark.sql.test.SharedSQLContext
import org.apache.spark.sql.types.{IntegerType, StructType}
import org.apache.spark.sql.vectorized.ColumnarBatch

class DataSourceV2Suite extends QueryTest with SharedSQLContext {
  import testImplicits._

  test("simplest implementation") {
    Seq(classOf[SimpleDataSourceV2], classOf[JavaSimpleDataSourceV2]).foreach { cls =>
      withClue(cls.getName) {
        val df = spark.read.format(cls.getName).load()
        checkAnswer(df, (0 until 10).map(i => Row(i, -i)))
        checkAnswer(df.select('j), (0 until 10).map(i => Row(-i)))
        checkAnswer(df.filter('i > 5), (6 until 10).map(i => Row(i, -i)))
      }
    }
  }

  test("advanced implementation") {
    def getReader(query: DataFrame): AdvancedDataSourceV2#Reader = {
      query.queryExecution.executedPlan.collect {
        case d: DataSourceV2ScanExec => d.reader.asInstanceOf[AdvancedDataSourceV2#Reader]
      }.head
    }

    def getJavaReader(query: DataFrame): JavaAdvancedDataSourceV2#Reader = {
      query.queryExecution.executedPlan.collect {
        case d: DataSourceV2ScanExec => d.reader.asInstanceOf[JavaAdvancedDataSourceV2#Reader]
      }.head
    }

    Seq(classOf[AdvancedDataSourceV2], classOf[JavaAdvancedDataSourceV2]).foreach { cls =>
      withClue(cls.getName) {
        val df = spark.read.format(cls.getName).load()
        checkAnswer(df, (0 until 10).map(i => Row(i, -i)))

        val q1 = df.select('j)
        checkAnswer(q1, (0 until 10).map(i => Row(-i)))
        if (cls == classOf[AdvancedDataSourceV2]) {
          val reader = getReader(q1)
          assert(reader.filters.isEmpty)
          assert(reader.requiredSchema.fieldNames === Seq("j"))
        } else {
          val reader = getJavaReader(q1)
          assert(reader.filters.isEmpty)
          assert(reader.requiredSchema.fieldNames === Seq("j"))
        }

        val q2 = df.filter('i > 3)
        checkAnswer(q2, (4 until 10).map(i => Row(i, -i)))
        if (cls == classOf[AdvancedDataSourceV2]) {
          val reader = getReader(q2)
          assert(reader.filters.flatMap(_.references).toSet == Set("i"))
          assert(reader.requiredSchema.fieldNames === Seq("i", "j"))
        } else {
          val reader = getJavaReader(q2)
          assert(reader.filters.flatMap(_.references).toSet == Set("i"))
          assert(reader.requiredSchema.fieldNames === Seq("i", "j"))
        }

        val q3 = df.select('i).filter('i > 6)
        checkAnswer(q3, (7 until 10).map(i => Row(i)))
        if (cls == classOf[AdvancedDataSourceV2]) {
          val reader = getReader(q3)
          assert(reader.filters.flatMap(_.references).toSet == Set("i"))
          assert(reader.requiredSchema.fieldNames === Seq("i"))
        } else {
          val reader = getJavaReader(q3)
          assert(reader.filters.flatMap(_.references).toSet == Set("i"))
          assert(reader.requiredSchema.fieldNames === Seq("i"))
        }

        val q4 = df.select('j).filter('j < -10)
        checkAnswer(q4, Nil)
        if (cls == classOf[AdvancedDataSourceV2]) {
          val reader = getReader(q4)
          // 'j < 10 is not supported by the testing data source.
          assert(reader.filters.isEmpty)
          assert(reader.requiredSchema.fieldNames === Seq("j"))
        } else {
          val reader = getJavaReader(q4)
          // 'j < 10 is not supported by the testing data source.
          assert(reader.filters.isEmpty)
          assert(reader.requiredSchema.fieldNames === Seq("j"))
        }
      }
    }
  }

  test("unsafe row scan implementation") {
    Seq(classOf[UnsafeRowDataSourceV2], classOf[JavaUnsafeRowDataSourceV2]).foreach { cls =>
      withClue(cls.getName) {
        val df = spark.read.format(cls.getName).load()
        checkAnswer(df, (0 until 10).map(i => Row(i, -i)))
        checkAnswer(df.select('j), (0 until 10).map(i => Row(-i)))
        checkAnswer(df.filter('i > 5), (6 until 10).map(i => Row(i, -i)))
      }
    }
  }

  test("columnar batch scan implementation") {
    Seq(classOf[BatchDataSourceV2], classOf[JavaBatchDataSourceV2]).foreach { cls =>
      withClue(cls.getName) {
        val df = spark.read.format(cls.getName).load()
        checkAnswer(df, (0 until 90).map(i => Row(i, -i)))
        checkAnswer(df.select('j), (0 until 90).map(i => Row(-i)))
        checkAnswer(df.filter('i > 50), (51 until 90).map(i => Row(i, -i)))
      }
    }
  }

  test("schema required data source") {
    Seq(classOf[SchemaRequiredDataSource], classOf[JavaSchemaRequiredDataSource]).foreach { cls =>
      withClue(cls.getName) {
        val e = intercept[AnalysisException](spark.read.format(cls.getName).load())
        assert(e.message.contains("requires a user-supplied schema"))

        val schema = new StructType().add("i", "int").add("s", "string")
        val df = spark.read.format(cls.getName).schema(schema).load()

        assert(df.schema == schema)
        assert(df.collect().isEmpty)
      }
    }
  }

  test("partitioning reporting") {
    import org.apache.spark.sql.functions.{count, sum}
    Seq(classOf[PartitionAwareDataSource], classOf[JavaPartitionAwareDataSource]).foreach { cls =>
      withClue(cls.getName) {
        val df = spark.read.format(cls.getName).load()
        checkAnswer(df, Seq(Row(1, 4), Row(1, 4), Row(3, 6), Row(2, 6), Row(4, 2), Row(4, 2)))

        val groupByColA = df.groupBy('a).agg(sum('b))
        checkAnswer(groupByColA, Seq(Row(1, 8), Row(2, 6), Row(3, 6), Row(4, 4)))
        assert(groupByColA.queryExecution.executedPlan.collectFirst {
          case e: ShuffleExchangeExec => e
        }.isEmpty)

        val groupByColAB = df.groupBy('a, 'b).agg(count("*"))
        checkAnswer(groupByColAB, Seq(Row(1, 4, 2), Row(2, 6, 1), Row(3, 6, 1), Row(4, 2, 2)))
        assert(groupByColAB.queryExecution.executedPlan.collectFirst {
          case e: ShuffleExchangeExec => e
        }.isEmpty)

        val groupByColB = df.groupBy('b).agg(sum('a))
        checkAnswer(groupByColB, Seq(Row(2, 8), Row(4, 2), Row(6, 5)))
        assert(groupByColB.queryExecution.executedPlan.collectFirst {
          case e: ShuffleExchangeExec => e
        }.isDefined)

        val groupByAPlusB = df.groupBy('a + 'b).agg(count("*"))
        checkAnswer(groupByAPlusB, Seq(Row(5, 2), Row(6, 2), Row(8, 1), Row(9, 1)))
        assert(groupByAPlusB.queryExecution.executedPlan.collectFirst {
          case e: ShuffleExchangeExec => e
        }.isDefined)
      }
    }
  }

  test("simple writable data source") {
    // TODO: java implementation.
    Seq(classOf[SimpleWritableDataSource]).foreach { cls =>
      withTempPath { file =>
        val path = file.getCanonicalPath
        assert(spark.read.format(cls.getName).option("path", path).load().collect().isEmpty)

        spark.range(10).select('id, -'id).write.format(cls.getName)
          .option("path", path).save()
        checkAnswer(
          spark.read.format(cls.getName).option("path", path).load(),
          spark.range(10).select('id, -'id))

        // test with different save modes
        spark.range(10).select('id, -'id).write.format(cls.getName)
          .option("path", path).mode("append").save()
        checkAnswer(
          spark.read.format(cls.getName).option("path", path).load(),
          spark.range(10).union(spark.range(10)).select('id, -'id))

        spark.range(5).select('id, -'id).write.format(cls.getName)
          .option("path", path).mode("overwrite").save()
        checkAnswer(
          spark.read.format(cls.getName).option("path", path).load(),
          spark.range(5).select('id, -'id))

        spark.range(5).select('id, -'id).write.format(cls.getName)
          .option("path", path).mode("ignore").save()
        checkAnswer(
          spark.read.format(cls.getName).option("path", path).load(),
          spark.range(5).select('id, -'id))

        val e = intercept[Exception] {
          spark.range(5).select('id, -'id).write.format(cls.getName)
            .option("path", path).mode("error").save()
        }
        assert(e.getMessage.contains("data already exists"))

        // test transaction
        val failingUdf = org.apache.spark.sql.functions.udf {
          var count = 0
          (id: Long) => {
            if (count > 5) {
              throw new RuntimeException("testing error")
            }
            count += 1
            id
          }
        }
        // this input data will fail to read middle way.
        val input = spark.range(10).select(failingUdf('id).as('i)).select('i, -'i)
        val e2 = intercept[SparkException] {
          input.write.format(cls.getName).option("path", path).mode("overwrite").save()
        }
        assert(e2.getMessage.contains("Writing job aborted"))
        // make sure we don't have partial data.
        assert(spark.read.format(cls.getName).option("path", path).load().collect().isEmpty)

        // test internal row writer
        spark.range(5).select('id, -'id).write.format(cls.getName)
          .option("path", path).option("internal", "true").mode("overwrite").save()
        checkAnswer(
          spark.read.format(cls.getName).option("path", path).load(),
          spark.range(5).select('id, -'id))
      }
    }
  }

  test("simple counter in writer with onDataWriterCommit") {
    Seq(classOf[SimpleWritableDataSource]).foreach { cls =>
      withTempPath { file =>
        val path = file.getCanonicalPath
        assert(spark.read.format(cls.getName).option("path", path).load().collect().isEmpty)

        val numPartition = 6
        spark.range(0, 10, 1, numPartition).select('id, -'id).write.format(cls.getName)
          .option("path", path).save()
        checkAnswer(
          spark.read.format(cls.getName).option("path", path).load(),
          spark.range(10).select('id, -'id))

        assert(SimpleCounter.getCounter == numPartition,
          "method onDataWriterCommit should be called as many as the number of partitions")
      }
    }
  }

  test("SPARK-23293: data source v2 self join") {
    val df = spark.read.format(classOf[SimpleDataSourceV2].getName).load()
    val df2 = df.select(($"i" + 1).as("k"), $"j")
    checkAnswer(df.join(df2, "j"), (0 until 10).map(i => Row(-i, i, i + 1)))
  }

  test("SPARK-23301: column pruning with arbitrary expressions") {
    def getReader(query: DataFrame): AdvancedDataSourceV2#Reader = {
      query.queryExecution.executedPlan.collect {
        case d: DataSourceV2ScanExec => d.reader.asInstanceOf[AdvancedDataSourceV2#Reader]
      }.head
    }

    val df = spark.read.format(classOf[AdvancedDataSourceV2].getName).load()

    val q1 = df.select('i + 1)
    checkAnswer(q1, (1 until 11).map(i => Row(i)))
    val reader1 = getReader(q1)
    assert(reader1.requiredSchema.fieldNames === Seq("i"))

    val q2 = df.select(lit(1))
    checkAnswer(q2, (0 until 10).map(i => Row(1)))
    val reader2 = getReader(q2)
    assert(reader2.requiredSchema.isEmpty)

    // 'j === 1 can't be pushed down, but we should still be able do column pruning
    val q3 = df.filter('j === -1).select('j * 2)
    checkAnswer(q3, Row(-2))
    val reader3 = getReader(q3)
    assert(reader3.filters.isEmpty)
    assert(reader3.requiredSchema.fieldNames === Seq("j"))

    // column pruning should work with other operators.
    val q4 = df.sort('i).limit(1).select('i + 1)
    checkAnswer(q4, Row(1))
    val reader4 = getReader(q4)
    assert(reader4.requiredSchema.fieldNames === Seq("i"))
  }

  test("SPARK-23315: get output from canonicalized data source v2 related plans") {
    def checkCanonicalizedOutput(df: DataFrame, numOutput: Int): Unit = {
      val logical = df.queryExecution.optimizedPlan.collect {
        case d: DataSourceV2Relation => d
      }.head
      assert(logical.canonicalized.output.length == numOutput)

      val physical = df.queryExecution.executedPlan.collect {
        case d: DataSourceV2ScanExec => d
      }.head
      assert(physical.canonicalized.output.length == numOutput)
    }

    val df = spark.read.format(classOf[AdvancedDataSourceV2].getName).load()
    checkCanonicalizedOutput(df, 2)
    checkCanonicalizedOutput(df.select('i), 1)
  }
}

class SimpleDataSourceV2 extends DataSourceV2 with ReadSupport {

  class Reader extends DataSourceReader {
    override def readSchema(): StructType = new StructType().add("i", "int").add("j", "int")

    override def createDataReaderFactories(): JList[DataReaderFactory[Row]] = {
      java.util.Arrays.asList(new SimpleDataReaderFactory(0, 5), new SimpleDataReaderFactory(5, 10))
    }
  }

  override def createReader(options: DataSourceOptions): DataSourceReader = new Reader
}

class SimpleDataReaderFactory(start: Int, end: Int)
  extends DataReaderFactory[Row]
  with DataReader[Row] {
  private var current = start - 1

  override def createDataReader(): DataReader[Row] = new SimpleDataReaderFactory(start, end)

  override def next(): Boolean = {
    current += 1
    current < end
  }

  override def get(): Row = Row(current, -current)

  override def close(): Unit = {}
}

class AdvancedDataSourceV2 extends DataSourceV2 with ReadSupport {

  class Reader extends DataSourceReader
    with SupportsPushDownRequiredColumns with SupportsPushDownFilters {

    var requiredSchema = new StructType().add("i", "int").add("j", "int")
    var filters = Array.empty[Filter]

    override def pruneColumns(requiredSchema: StructType): Unit = {
      this.requiredSchema = requiredSchema
    }

    override def pushFilters(filters: Array[Filter]): Array[Filter] = {
      val (supported, unsupported) = filters.partition {
        case GreaterThan("i", _: Int) => true
        case _ => false
      }
      this.filters = supported
      unsupported
    }

    override def pushedFilters(): Array[Filter] = filters

    override def readSchema(): StructType = {
      requiredSchema
    }

    override def createDataReaderFactories(): JList[DataReaderFactory[Row]] = {
      val lowerBound = filters.collect {
        case GreaterThan("i", v: Int) => v
      }.headOption

      val res = new ArrayList[DataReaderFactory[Row]]

      if (lowerBound.isEmpty) {
        res.add(new AdvancedDataReaderFactory(0, 5, requiredSchema))
        res.add(new AdvancedDataReaderFactory(5, 10, requiredSchema))
      } else if (lowerBound.get < 4) {
        res.add(new AdvancedDataReaderFactory(lowerBound.get + 1, 5, requiredSchema))
        res.add(new AdvancedDataReaderFactory(5, 10, requiredSchema))
      } else if (lowerBound.get < 9) {
        res.add(new AdvancedDataReaderFactory(lowerBound.get + 1, 10, requiredSchema))
      }

      res
    }
  }

  override def createReader(options: DataSourceOptions): DataSourceReader = new Reader
}

class AdvancedDataReaderFactory(start: Int, end: Int, requiredSchema: StructType)
  extends DataReaderFactory[Row] with DataReader[Row] {

  private var current = start - 1

  override def createDataReader(): DataReader[Row] = {
    new AdvancedDataReaderFactory(start, end, requiredSchema)
  }

  override def close(): Unit = {}

  override def next(): Boolean = {
    current += 1
    current < end
  }

  override def get(): Row = {
    val values = requiredSchema.map(_.name).map {
      case "i" => current
      case "j" => -current
    }
    Row.fromSeq(values)
  }
}

class UnsafeRowDataSourceV2 extends DataSourceV2 with ReadSupport {

  class Reader extends DataSourceReader with SupportsScanUnsafeRow {
    override def readSchema(): StructType = new StructType().add("i", "int").add("j", "int")

    override def createUnsafeRowReaderFactories(): JList[DataReaderFactory[UnsafeRow]] = {
      java.util.Arrays.asList(new UnsafeRowDataReaderFactory(0, 5),
        new UnsafeRowDataReaderFactory(5, 10))
    }
  }

  override def createReader(options: DataSourceOptions): DataSourceReader = new Reader
}

class UnsafeRowDataReaderFactory(start: Int, end: Int)
  extends DataReaderFactory[UnsafeRow] with DataReader[UnsafeRow] {

  private val row = new UnsafeRow(2)
  row.pointTo(new Array[Byte](8 * 3), 8 * 3)

  private var current = start - 1

  override def createDataReader(): DataReader[UnsafeRow] = this

  override def next(): Boolean = {
    current += 1
    current < end
  }
  override def get(): UnsafeRow = {
    row.setInt(0, current)
    row.setInt(1, -current)
    row
  }

  override def close(): Unit = {}
}

class SchemaRequiredDataSource extends DataSourceV2 with ReadSupportWithSchema {

  class Reader(val readSchema: StructType) extends DataSourceReader {
    override def createDataReaderFactories(): JList[DataReaderFactory[Row]] =
      java.util.Collections.emptyList()
  }

  override def createReader(schema: StructType, options: DataSourceOptions): DataSourceReader =
    new Reader(schema)
}

class BatchDataSourceV2 extends DataSourceV2 with ReadSupport {

  class Reader extends DataSourceReader with SupportsScanColumnarBatch {
    override def readSchema(): StructType = new StructType().add("i", "int").add("j", "int")

    override def createBatchDataReaderFactories(): JList[DataReaderFactory[ColumnarBatch]] = {
      java.util.Arrays.asList(new BatchDataReaderFactory(0, 50), new BatchDataReaderFactory(50, 90))
    }
  }

  override def createReader(options: DataSourceOptions): DataSourceReader = new Reader
}

class BatchDataReaderFactory(start: Int, end: Int)
  extends DataReaderFactory[ColumnarBatch] with DataReader[ColumnarBatch] {

  private final val BATCH_SIZE = 20
  private lazy val i = new OnHeapColumnVector(BATCH_SIZE, IntegerType)
  private lazy val j = new OnHeapColumnVector(BATCH_SIZE, IntegerType)
  private lazy val batch = new ColumnarBatch(Array(i, j))

  private var current = start

  override def createDataReader(): DataReader[ColumnarBatch] = this

  override def next(): Boolean = {
    i.reset()
    j.reset()

    var count = 0
    while (current < end && count < BATCH_SIZE) {
      i.putInt(count, current)
      j.putInt(count, -current)
      current += 1
      count += 1
    }

    if (count == 0) {
      false
    } else {
      batch.setNumRows(count)
      true
    }
  }

  override def get(): ColumnarBatch = {
    batch
  }

  override def close(): Unit = batch.close()
}

class PartitionAwareDataSource extends DataSourceV2 with ReadSupport {

  class Reader extends DataSourceReader with SupportsReportPartitioning {
    override def readSchema(): StructType = new StructType().add("a", "int").add("b", "int")

    override def createDataReaderFactories(): JList[DataReaderFactory[Row]] = {
      // Note that we don't have same value of column `a` across partitions.
      java.util.Arrays.asList(
        new SpecificDataReaderFactory(Array(1, 1, 3), Array(4, 4, 6)),
        new SpecificDataReaderFactory(Array(2, 4, 4), Array(6, 2, 2)))
    }

    override def outputPartitioning(): Partitioning = new MyPartitioning
  }

  class MyPartitioning extends Partitioning {
    override def numPartitions(): Int = 2

    override def satisfy(distribution: Distribution): Boolean = distribution match {
      case c: ClusteredDistribution => c.clusteredColumns.contains("a")
      case _ => false
    }
  }

  override def createReader(options: DataSourceOptions): DataSourceReader = new Reader
}

class SpecificDataReaderFactory(i: Array[Int], j: Array[Int])
  extends DataReaderFactory[Row]
  with DataReader[Row] {
  assert(i.length == j.length)

  private var current = -1

  override def createDataReader(): DataReader[Row] = this

  override def next(): Boolean = {
    current += 1
    current < i.length
  }

  override def get(): Row = Row(i(current), j(current))

  override def close(): Unit = {}
}


text:
module Zafu
  module Process
    module Forms
      def self.included(base)
        base.expander :make_form
      end

      def r_form
        if node.dom_prefix
          fnode = node
        else
          fnode = node.dup
          fnode.dom_prefix = dom_name
        end
        with_context(:node => fnode) do

          unless @params[:on].nil? || @params[:on].split(',').include?(@context[:ajax_action])
            return ''
          end

          return parser_error('Cannot render update form in list context.') if node.list_context?

          options = form_options

          @markup.set_id(options[:id]) if options[:id]
          @markup.set_param(:style, options[:style]) if options[:style]

          if descendant('form_tag')
            # We have a specific place to insert our form
            out expand_with(:form_options => options, :form => self)
          else
            r_form_tag(options)
          end
        end
      end

      def r_form_tag(options = @context[:form_options])
        form_tag(options) do |opts|
          # Render error messages tag
          form_error_messages(opts[:form_helper])

          # Render form elements
          out expand_with(opts)

          # Render hidden fields (these must go after normal elements so that focusFirstElement works)
          hidden_fields = form_hidden_fields(options)

          out "
"
          hidden_fields.each do |k,v|
            if v.kind_of?(String)
              v = "'#{v}'" unless v.kind_of?(String) && ['"', "'"].include?(v[0..0])
              out "<input type='hidden' name='#{k}' value=#{v}/>"
            elsif v.kind_of?(Array)
              # We use ['ffff'] to indicate that the content is already escaped and ready for ERB.
              out v.first
            end
          end
          out '
'
        end
      end

      private
        def make_form
          return nil unless @context[:make_form]

          if method == 'each' || method == 'block'
            r_form
          else
            nil
          end
        end

        # Return id, style, form and cancel parts of the form.
        def form_options
          opts = {}

          # Do we need this ?
          # opts[:klass] = node.master_class(ActiveRecord::Base).to_s

          if @context[:in_add]
            opts[:id]    = "#{node.dom_prefix}_add"
            opts[:style] = 'display:none;'
          elsif @markup.tag == 'table'
            # the normal id goes to the form wrapping the table
            opts[:id]    = "#{node.dom_prefix}_tbl"
            form_id      = node.dom_prefix
          end

          form_id ||= "#{node.dom_prefix}_form_t"
          if @context[:template_url]
            opts[:form_tag]    = "<% remote_form_for(:#{node.form_name}, #{node}, :html => {:id => #{form_id.inspect}}) do |f| %>"
            opts[:form_helper] = 'f'
          else
            opts[:form_tag]    = "<% form_for(:#{node.form_name}, #{node}, :html => {:id => #{form_id.inspect}}) do |f| %>"
            opts[:form_helper] = 'f'
          end
          opts[:form_prefix] = node.dom_prefix || dom_name
          opts
        end

        # Return hidden fields that need to be inserted in the form.
        def form_hidden_fields(opts)
          if t_url = @context[:template_url]
            {'t_url' => t_url}
          else
            {}
          end
        end

        # Render the 'form' tag and set expansion context.
        def form_tag(options)
          opts = options.dup

          if descendant('cancel') || descendant('edit')
            # Pass 'form_cancel' content to expand_with (already in options).
          else
            # Insert cancel before form
            out opts.delete(:form_cancel).to_s
          end

          # form_for ... do |f|
          out opts.delete(:form_tag)
            # f.xxx
            if markup.tag == 'table'
              # Avoid
<form> (invalid HTML)
              bak = @result
              @result = ''
              yield(opts.merge(:in_form => true))
              @result = bak + markup.wrap(@result)
            else
              yield(opts.merge(:in_form => true))
            end
          # close form
          out opts[:form_helper] ? "<% end %>" : '</form>'
        end

        def form_error_messages(f)
          out "<%= #{f}.error_messages %>"
        end

    end # Forms
  end # Process
end # Zafu

redpajama_set_name: RedPajamaGithub


text:
@class IOSByteArray;
@class IOSLongArray;

@interface BSDataOutput : NSObject

#pragma mark Public

- (instancetype)init;

+ (jint)growSizeWithInt:(jint)currentSize;

- (IOSByteArray *)toByteArray;

- (void)writeASN1LengthWithInt:(jint)length;

- (void)writeByteWithByte:(jbyte)v;

- (void)writeByteWithInt:(jint)v;

- (void)writeBytesWithByteArray:(IOSByteArray *)v;

- (void)writeBytesWithByteArray:(IOSByteArray *)v
                        withInt:(jint)ofs
                        withInt:(jint)len;

- (void)writeIntWithInt:(jint)v;

- (void)writeLongWithLong:(jlong)v;

- (void)writeProtoBoolWithBoolean:(jboolean)v;

- (void)writeProtoBytesWithByteArray:(IOSByteArray *)v
                             withInt:(jint)ofs
                             withInt:(jint)len;

- (void)writeProtoLongsWithLongArray:(IOSLongArray *)values;

- (void)writeProtoStringWithNSString:(NSString *)value;

- (void)writeVarIntWithLong:(jlong)v;

@end

J2OBJC_EMPTY_STATIC_INIT(BSDataOutput)

FOUNDATION_EXPORT void BSDataOutput_init(BSDataOutput *self);

FOUNDATION_EXPORT BSDataOutput *new_BSDataOutput_init() NS_RETURNS_RETAINED;

FOUNDATION_EXPORT jint BSDataOutput_growSizeWithInt_(jint currentSize);

J2OBJC_TYPE_LITERAL_HEADER(BSDataOutput)

typedef BSDataOutput ImActorModelDroidkitBserDataOutput;

#endif // _BSDataOutput_H_


text:
package postgresweb.models

/**
  * Created by andreaminetti on 23/02/16.
  */
case class JSONCount(count:Int)


text:
require_relative './parameter_type'

# Refinements
# =======================================================================

require 'nrser/refinements/regexps'
using NRSER::Regexps

# Namespace
# =======================================================================

module  NRSER
module  Described
module  Cucumber
module  ParameterTypes

# Definitions
# =======================================================================

# Mixin extended in to modules that declare parameter types, providing the
# necessary methods.
#
module Declare

  def parameter_types
    @parameter_types ||= {}
  end

  def [] name
    parameter_types.fetch name.to_sym
  end

  def def_parameter_type name:, **kwds
    name = name.to_sym unless name.is_a?( ::Symbol )

    if parameter_types.key? name
      raise NRSER::ConflictError.new \
        "Already defined parameter type with name", name,
        existing_parameter_type: parameter_types[ name ],
        attempted_definition: { name: name, **kwds }
    end

    ParameterType.new( name: name, **kwds ).tap { |parameter_type|
      parameter_types[ name ] = parameter_type
    }
  end

end # module Declare

# /Namespace
# =======================================================================

end # module ParameterTypes
end # module Cucumber
end # module Described
end # module NRSER


text:
<?php
/**
 * Error Content Template
 *
 * This template is the content template for error screens. It is used to display a message
 * to the viewer when no appropriate page can be found by WordPress.
 *
 * @package WooFramework
 * @subpackage Template
 */

/**
 * Settings for this template file.
 *
 * This is where the specify the HTML tags for the title.
 * These options can be filtered via a child theme.
 *
 * @link http://codex.wordpress.org/Plugin_API#Filters
 */

 $title_before = '
';
 $title_after = '
';

 $page_link_args = apply_filters( 'woothemes_pagelinks_args', array( 'before' => '
' . __( 'Pages:', 'woothemes' ), 'after' => '
' ) );

 woo_post_before();
?>
<article <?php post_class(); ?>>
<?php woo_post_inside_before();	?>

		<?php echo $title_before . apply_filters( 'woo_404_title', __( 'Error 404 - Page not found!', 'woothemes' ) ) . $title_after; ?>

	    <?php
	    	echo apply_filters( 'woo_404_content', __( 'The page you are trying to reach does not exist, or has been moved. Please use the menus or the search box to find what you are looking for.', 'woothemes' ) );
	    	if ( $woo_options['woo_post_content'] == 'content' || is_singular() ) wp_link_pages( $page_link_args );
	    ?>

<?php
	woo_post_inside_after();
?>

<?php
	woo_post_after();
?>


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>

#include "trousers/tss.h"
#include "trousers/trousers.h"
#include "trousers_types.h"
#include "tsplog.h"
#include "hosttable.h"
#include "tcsd_wrap.h"
#include "rpc_tcstp_tsp.h"

TSS_RESULT
RPC_SetOperatorAuth_TP(struct host_table_entry *hte,
			TCPA_SECRET *operatorAuth)	/* in */
{
	TSS_RESULT result;

	initData(&hte->comm, 2);
	hte->comm.hdr.u.ordinal = TCSD_ORD_SETOPERATORAUTH;
	LogDebugFn("TCS Context: 0x%x", hte->tcsContext);

	if (setData(TCSD_PACKET_TYPE_UINT32, 0, &hte->tcsContext, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_SECRET, 1, operatorAuth, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);

	result = sendTCSDPacket(hte);

	if (result == TSS_SUCCESS)
		result = hte->comm.hdr.u.result;

	return result;
}


text:
package io.sweers.barber;

import android.util.AttributeSet;
import android.util.Log;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Entry point for applications.
 * <p>
 * Use one of the {@link #style(java.lang.Object, android.util.AttributeSet, int[])} variants to
 * style your custom views.
 */
public class Barber {

    public static final String SUFFIX = "$$Barbershop";
    public static final String ANDROID_PREFIX = "android.";
    public static final String JAVA_PREFIX = "java.";
    private static final String TAG = "Barber";
    private static final IBarbershop<Object> NO_OP = null;
    private static boolean debug = false;
    private static final Map<Class<?>, IBarbershop<Object>> BARBERSHOPS = new LinkedHashMap<>();

    public static void style(Object target, AttributeSet set, int[] attrs) {
        style(target, set, attrs, 0);
    }

    public static void style(Object target, AttributeSet set, int[] attrs, int defStyleAttr) {
        style(target, set, attrs, defStyleAttr, 0);
    }

    public static void style(Object target, AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes) {
        Class<?> targetClass = target.getClass();
        if (debug) {
            Log.d(TAG, "Looking up barbershop for " + targetClass.getName());
        }
        IBarbershop<Object> barbershop = findBarbershopForClass(targetClass);
        if (barbershop != NO_OP) {
            barbershop.style(target, set, attrs, defStyleAttr, defStyleRes);
        }
    }

    /**
     * Searches for $$Barbershop class for the given instance, cached for efficiency.
     *
     * @param cls Source class to find a matching $$Barbershop class for
     * @return $$Barbershop class instance
     */
    private static IBarbershop<Object> findBarbershopForClass(Class<?> cls) {
        IBarbershop<Object> barbershop = BARBERSHOPS.get(cls);
        if (barbershop != null) {
            if (debug) Log.d(TAG, "HIT: Cached in barbershop map.");
            return barbershop;
        }
        String clsName = cls.getName();
        if (clsName.startsWith(ANDROID_PREFIX) || clsName.startsWith(JAVA_PREFIX)) {
            if (debug) {
                Log.d(TAG, "MISS: Reached framework class. Abandoning search.");
            }
            return NO_OP;
        }
        //noinspection TryWithIdenticalCatches
        try {
            Class<?> barbershopClass = Class.forName(clsName + SUFFIX);
            //noinspection unchecked
            barbershop = (IBarbershop<Object>) barbershopClass.newInstance();
            if (debug) {
                Log.d(TAG, "HIT: Class loaded barbershop class.");
            }
        } catch (ClassNotFoundException e) {
            if (debug) {
                Log.d(TAG, "Not found. Trying superclass " + cls.getSuperclass().getName());
            }
            barbershop = findBarbershopForClass(cls.getSuperclass());
        } catch (InstantiationException e) {
            Log.e(TAG, e.getMessage());
        } catch (IllegalAccessException e) {
            Log.e(TAG, e.getMessage());
        }
        BARBERSHOPS.put(cls, barbershop);
        return barbershop;
    }

    /** DO NOT USE. Exposed for generated classes' use. */
    public interface IBarbershop<T> {
        public void style(final T target, final AttributeSet set, final int[] attrs, final int defStyleAttr, final int defStyleRes);
    }
}


text:
namespace lldb_private {

//-------------------------------------------------------------------------
// CommandObjectMultiwordWatchpoint
//-------------------------------------------------------------------------

class CommandObjectWatchpointCommand : public CommandObjectMultiword {
public:
  CommandObjectWatchpointCommand(CommandInterpreter &interpreter);

  ~CommandObjectWatchpointCommand() override;
};

} // namespace lldb_private

#endif // liblldb_CommandObjectWatchpointCommand_h_


text:
<template name="tpioComments">

        {{#each commentData}}
            {{> comment}}
        {{/each}}

</template>

<template name="comment">

{{message}}

</template>


text:
from __future__ import division, absolute_import, print_function, unicode_literals
import unittest, os, random
# misc
from kasaya.conf import set_value, settings

from kasaya.workers.kasayad.db.netstatedb import NetworkStateDB
from kasaya.core.lib import make_kasaya_id

class NetstateDBTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        set_value("KASAYAD_DB_BACKEND", "memory")

    def test_host_up_and_down(self):
        DB = NetworkStateDB()
        ID, addr = make_kasaya_id(True), "tcp://192.168.1.2:4000"

        # adding host
        res = DB.host_register(ID, addr)
        self.assertEqual(res, True)
        res = DB.host_register(ID, addr)
        self.assertEqual(res, False)

        # listing hosts
        lst = list( DB.host_list() )
        self.assertEqual( len(lst), 1 )
        self.assertEqual( lst[0]['id'], ID )
        self.assertEqual( lst[0]['hostname'], None )
        self.assertEqual( lst[0]['addr'], addr )

        # get host by ID
        h = DB.host_addr_by_id(ID)
        self.assertEqual( h, addr )

        # unregister
        DB.host_unregister(ID)

        # check unregistering result
        lst = list( DB.host_list() )
        self.assertEqual( len(lst), 0 )
        h = DB.host_addr_by_id(ID)
        self.assertEqual( h, None )

        # register 10 hosts
        for n in range(10,20):
            ID, hn, addr = make_kasaya_id(True), "host_%i" % n, "tcp://192.168.1.%i:4000" % n
            res = DB.host_register(ID, addr)
            self.assertEqual(res, True)
            res = DB.host_register(ID, addr)
            self.assertEqual(res, False)

        # is there 10 hosts on list?
        lst = list( DB.host_list() )
        self.assertEqual( len(lst), 10 )

        # check host query
        for n in range(10,20):
            DB.host_addr_by_id(ID)
        DB.close()

    def assertDictEequal(self, d1, d2):
        self.assertItemsEqual( d1.keys(), d2.keys(), "Keys for dicts not equal. %r != %r" % (d1.keys(), d2.keys()) )
        for k,v in d1.items():
            self.assertEqual( type(v), type(d2[k]), "Types [%r] not equal: %s != %s" % (k, type(v), type(d2[k])) )
            self.assertEqual( v, d2[k], "Value [%r] not equal: %r != %r" % (k, v, d2[k]) )

    def test_worker_registers(self):
        DB = NetworkStateDB()
        host_id, addr = make_kasaya_id(True), "tcp://127.0.0.1:4000"
        DB.host_register(host_id, addr)

        wid1, svc1, addr1 = make_kasaya_id(), "srvc1", "tcp://127.0.0.1:5000"
        wid2, svc2, addr2 = make_kasaya_id(), "srvc2", "tcp://127.0.0.1:5001"
        wid3, svc3, addr3 = make_kasaya_id(), "srvc3", "tcp://127.0.0.1:5002"

        DB.worker_register( host_id, wid1, svc1, addr1, 100, online=True )
        DB.worker_register( host_id, wid2, svc2, addr2, 101, online=False )
        DB.worker_register( host_id, wid3, svc3, addr3 )

        self.assertDictEequal(
            DB.worker_get( wid1 ),
            { 'id'      : wid1,
              'host_id' : host_id,
              'service' : svc1,
              'addr'    : addr1,
              'pid'     : 100,
              'online'  : True })

        self.assertDictEequal(
            DB.worker_get( wid2 ),
            { 'id'      : wid2,
              'host_id' : host_id,
              'service' : svc2,
              'addr'    : addr2,
              'pid'     : 101,
              'online'  : False })

        self.assertDictEequal(
            DB.worker_get( wid3 ),
            { 'id'      : wid3,
              'host_id' : host_id,
              'service' : svc3,
              'addr'    : addr3,
              'pid'     : -1,
              'online'  : True })

        # selecting only online workers for service
        self.assertEqual( DB.choose_worker_for_service(svc1)['id'], wid1 )
        self.assertEqual( DB.choose_worker_for_service(svc2), None )
        self.assertEqual( DB.choose_worker_for_service(svc3)['id'], wid3 )

        # change worker state
        DB.worker_set_state( wid2, True )
        self.assertEqual( DB.choose_worker_for_service(svc2)['id'], wid2 )
        DB.worker_set_state( wid1, False )
        self.assertEqual( DB.choose_worker_for_service(svc1), None )

    def test_host_with_workers(self):
        _hosts = []

        DB = NetworkStateDB()
        svce = ("mail","sms","bubbles","spam")
        # create hosts
        for n in range(6):
            ip = '192.168.1.%i' % n
            HID, hn, addr = make_kasaya_id(True), "host_%i" % n, "tcp://%s:4000" % ip
            _hosts.append(HID)
            DB.host_register(HID, addr)

            # make workers
            for w in range(10):
                WID = make_kasaya_id(False) # worker id
                addr="tcp://%s:%i" % (ip, 5000+w)
                DB.worker_register(HID, WID, random.choice(svce), addr, n+((w+1)*100) )

        # check hosts
        hlst = list( DB.host_list() )
        self.assertItemsEqual(  [ x['id'] for x in hlst ] , _hosts )

        # check existance of workers in hosts
        for h in hlst:
            itms=0
            wids = []
            haddr = h['addr'].rsplit(":",1)[0]

            for w in DB.worker_list(h['id']):
                itms+=1
                waddr = w['addr'].rsplit(":",1)[0]
                self.assertEqual( waddr, haddr )
                # is this worker listed only one
                assert w['id'] not in wids, "Worker has been listed before!"
                wids.append(w['id'])

            # how many workers was on the list
            self.assertEqual(itms, 10)

        removed = []
        # check unregistering workers
        for h in DB.host_list():
            remove = False
            by_id = False
            for w in DB.worker_list(h['id']):
                # remove this worker
                if remove:
                    w['hid'] = h['id']
                    removed.append(w)
                    if by_id:
                        DB.worker_unregister(ID=w['id'])
                    else:
                        DB.worker_unregister(address=w['addr'])
                    by_id = not by_id
                remove = not remove

        # check removef workers
        for i in removed:
            w = DB.worker_get(i['id'])
            self.assertEqual(w,None, "Worker should be removed but still exists in database")

        # random worker choice
        for s in svce:
            for n in range(10):
                w = DB.choose_worker_for_service(s)
                wrkr = DB.worker_get(w['id'])
                self.assertEqual( wrkr['service'], s )

        # unknown service
        w = DB.choose_worker_for_service("foobar")
        self.assertEqual(w, None)

if __name__ == '__main__':
    unittest.main()


text:
@implementation BLMainScrollView

- (void)awakeFromNib
{
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    self.backgroundColor = [UIColor clearColor];
    self.bounces = NO;

    CGFloat screenWidth = mainScreen.bounds.size.width;

    for (int i = 0; i <= 5; i++) {
        if (i == 1) {
            BLCommendViewController *view = [[BLCommendViewController alloc] initWithFrame:CGRectMake(i * screenWidth, 0, screenWidth, mainScreen.bounds.size.height)];
            [self addSubview:view];
        }

        if (i != 1) {
            BLBaseViewController *view =  [[BLBaseViewController alloc] initWithFrame:CGRectMake(i * screenWidth, 0, screenWidth, mainScreen.bounds.size.height)];
                [self addSubview:view];

        }

    }

    self.contentSize = CGSizeMake(6 * screenWidth, 0);
    // 一开始就显示第二页
    [self setContentOffset:CGPointMake(mainScreen.bounds.size.width, 0)];
    self.pagingEnabled = YES;
}

@end


text:
package com.jme3.bullet.debug;

import com.jme3.bullet.objects.PhysicsVehicle;
import com.jme3.bullet.objects.VehicleWheel;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.debug.Arrow;

/**
 *
 * @author normenhansen
 */
public class BulletVehicleDebugControl extends AbstractPhysicsDebugControl {

    protected final PhysicsVehicle body;
    protected final Node suspensionNode;
    protected final Vector3f location = new Vector3f();
    protected final Quaternion rotation = new Quaternion();

    public BulletVehicleDebugControl(BulletDebugAppState debugAppState, PhysicsVehicle body) {
        super(debugAppState);
        this.body = body;
        suspensionNode = new Node("Suspension");
        createVehicle();
    }

    @Override
    public void setSpatial(Spatial spatial) {
        if (spatial != null && spatial instanceof Node) {
            Node node = (Node) spatial;
            node.attachChild(suspensionNode);
        } else if (spatial == null && this.spatial != null) {
            Node node = (Node) this.spatial;
            node.detachChild(suspensionNode);
        }
        super.setSpatial(spatial);
    }

    private void createVehicle() {
        suspensionNode.detachAllChildren();
        for (int i = 0; i < body.getNumWheels(); i++) {
            VehicleWheel physicsVehicleWheel = body.getWheel(i);
            Vector3f location = physicsVehicleWheel.getLocation().clone();
            Vector3f direction = physicsVehicleWheel.getDirection().clone();
            Vector3f axle = physicsVehicleWheel.getAxle().clone();
            float restLength = physicsVehicleWheel.getRestLength();
            float radius = physicsVehicleWheel.getRadius();

            Arrow locArrow = new Arrow(location);
            Arrow axleArrow = new Arrow(axle.normalizeLocal().multLocal(0.3f));
            Arrow wheelArrow = new Arrow(direction.normalizeLocal().multLocal(radius));
            Arrow dirArrow = new Arrow(direction.normalizeLocal().multLocal(restLength));
            Geometry locGeom = new Geometry("WheelLocationDebugShape" + i, locArrow);
            Geometry dirGeom = new Geometry("WheelDirectionDebugShape" + i, dirArrow);
            Geometry axleGeom = new Geometry("WheelAxleDebugShape" + i, axleArrow);
            Geometry wheelGeom = new Geometry("WheelRadiusDebugShape" + i, wheelArrow);
            dirGeom.setLocalTranslation(location);
            axleGeom.setLocalTranslation(location.add(direction));
            wheelGeom.setLocalTranslation(location.add(direction));
            locGeom.setMaterial(debugAppState.DEBUG_MAGENTA);
            dirGeom.setMaterial(debugAppState.DEBUG_MAGENTA);
            axleGeom.setMaterial(debugAppState.DEBUG_MAGENTA);
            wheelGeom.setMaterial(debugAppState.DEBUG_MAGENTA);
            suspensionNode.attachChild(locGeom);
            suspensionNode.attachChild(dirGeom);
            suspensionNode.attachChild(axleGeom);
            suspensionNode.attachChild(wheelGeom);
        }
    }

    @Override
    protected void controlUpdate(float tpf) {
        for (int i = 0; i < body.getNumWheels(); i++) {
            VehicleWheel physicsVehicleWheel = body.getWheel(i);
            Vector3f location = physicsVehicleWheel.getLocation().clone();
            Vector3f direction = physicsVehicleWheel.getDirection().clone();
            Vector3f axle = physicsVehicleWheel.getAxle().clone();
            float restLength = physicsVehicleWheel.getRestLength();
            float radius = physicsVehicleWheel.getRadius();

            Geometry locGeom = (Geometry) suspensionNode.getChild("WheelLocationDebugShape" + i);
            Geometry dirGeom = (Geometry) suspensionNode.getChild("WheelDirectionDebugShape" + i);
            Geometry axleGeom = (Geometry) suspensionNode.getChild("WheelAxleDebugShape" + i);
            Geometry wheelGeom = (Geometry) suspensionNode.getChild("WheelRadiusDebugShape" + i);

            Arrow locArrow = (Arrow) locGeom.getMesh();
            locArrow.setArrowExtent(location);
            Arrow axleArrow = (Arrow) axleGeom.getMesh();
            axleArrow.setArrowExtent(axle.normalizeLocal().multLocal(0.3f));
            Arrow wheelArrow = (Arrow) wheelGeom.getMesh();
            wheelArrow.setArrowExtent(direction.normalizeLocal().multLocal(radius));
            Arrow dirArrow = (Arrow) dirGeom.getMesh();
            dirArrow.setArrowExtent(direction.normalizeLocal().multLocal(restLength));

            dirGeom.setLocalTranslation(location);
            axleGeom.setLocalTranslation(location.addLocal(direction));
            wheelGeom.setLocalTranslation(location);
            i++;
        }
        applyPhysicsTransform(body.getPhysicsLocation(location), body.getPhysicsRotation(rotation));
    }

}


text:
@interface SysMessage : BmobObject

@property (strong, nonatomic) BmobUser *fromUser;

@property (strong, nonatomic) BmobUser *toUser;

@property (strong, nonatomic) NSNumber *type;

@end


text:
title: Rocket Height
view: page_curriculum
theme: none
---

<%
lesson_id = 'alg10'
lesson = DB[:cdo_lessons].where(id_s:lesson_id).first
%>

<%= partial('../docs/_header', :lesson => lesson) %>

[summary]

## Teaching Summary
### **Getting Started**

1) [Introduction](#GetStarted)

### **Activity: Rocket Height**

2) [Online Puzzles](#Activity1)

### **Extension Activities**

3) [Non-linear Animation](#Extension)

[/summary]

[together]

# Teaching Guide

## Materials, Resources, and Prep
### For the Student
- [Rocket-Height Design Recipe](../docs/worksheets/rocket_height.pdf) (in the student workbook)

## Getting Started

###  1) Introduction

Functions are a key part of animation in computer programs. A function that draws a static picture of a bat, for example, can place the bat at a different location based on the input. When that input changes slightly based on time or user-interaction, the bat will appear to move. This is similar to the way that flip-book animations work, in which each page draws a static image that has changed by a small amount. When the pages are displayed quickly, the images appear to change smoothly.

Putting these images together, we arrive at an animation of the bat turning around.

In the online puzzles, students will find a black block for each function they create, in addition to the colored blocks they are used to. The black function box, which has no parameter inputs, represents the function as a Type of data. This allows you to pass your function into the 'start' function, where it can be used to control the rocket animation.

Another curiosity with this program is that the rocket-height function will be executed multiple times.  The periodic execution creates the flip-book effect.  As each second passes, the rocket-height function is executed again, the new location is calculated, and the rocket is re-drawn in its new location.  This drawing and re-drawing in different locations gives the appearance of motion.

[tip]

# Lesson Tip

After creating simple linear movement, students will be asked to write functions to animate simple acceleration. Students will be given an input/output table from which to write their new function. You may want to work through these problems as a whole class, so that students can see how you might analyze an input/output table in order understand the relationship between input and output values.

[/tip]

[/together]

[together]

## Activity: Rocket Height
###  2) Online Puzzles

In this stage you'll write functions that manipulate images to create animations. Head to [CS in Algebra stage 10](http://studio.code.org/s/algebra/stage/10/puzzle/1) in Code Studio to get started programming.

[/together]

[together]

## Extension Activities
###  3) Non-linear Animation

The final puzzle of this stage is a Free Play puzzle that will allow you amd your students to experiment with other variations on the rocket-height formula. One activity that students find particularly interesting (and often challenging) is to write functions that produce non-linear acceleration. If your students are familiar with quadratics then you can call this out as such, but even younger students who haven't yet seen quadratics can enjoy this extension challenge.

Place the following input/output tables on the board and see if students can come up with functions that will produce the appropriate animation.

Challenge 1

      Input
      Output

      1
      10

      2
      40

      3
      90

      4
      160

Challenge 2

      Input
      Output

      1
      15

      2
      45

      3
      95

      4
      165

Once students have figured out the provided Input Output tables, encourage them to come up with non-linear animation functions of their own.

[together]

<%= partial('../docs/_footer', :lesson => lesson) %>


text:
Load images as blob and store them in buffer of the bowser

### Installation
```bash
$ npm install blobimage
$ bower install blobimage
```

### Example
```html
<script type="type/javascript" src="/path/to/script/blobimage.js"></script>
```

### API

#### new BlobImage(url)
```js
var blobImage = new BlobImage('http://iwillwen.u.qiniudn.com/mindb.png');
// Or
var blobImage = BlobImage('http://iwillwen.u.qiniudn.com/mindb.png');
```

#### BlobImage.element
The `Image` element of the BlobImage.

```js
document.body.appendChild(blobImage.element);
```

#### BlobImage.toDataURL(callback)
Generate the data url(base64) of the BlobImage.

```js
blobImage.toDataURL(function(err, dataURL) {
  if (err) {
    return console.error(err);
  }

  console.log(dataURL);
});
```

#### BlobImage.release()
Release the BlobImage from the buffer.

```js
blobImage.release();
```

### Contributing
- Fork this repo
- Clone your repo
- Install dependencies
- Checkout a feature branch
- Feel free to add your features
- Make sure your features are fully tested
- Open a pull request, and enjoy <3

### MIT license
Copyright (c) 2015 iwillwen(willwengunn@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
package com.netflix.prana.http.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelOption;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.pipeline.PipelineConfigurators;
import io.reactivex.netty.protocol.http.client.HttpClient;
import io.reactivex.netty.protocol.http.server.HttpServer;
import io.reactivex.netty.protocol.http.server.RequestHandler;
import org.junit.After;
import org.junit.Before;

public abstract class AbstractIntegrationTest {
    protected ObjectMapper objectMapper = new ObjectMapper();
    protected HttpServer<ByteBuf, ByteBuf> server;
    protected HttpClient<ByteBuf, ByteBuf> client;

    protected abstract RequestHandler<ByteBuf, ByteBuf> getHandler();

    @Before
    public void setUp() {
        server = RxNetty.newHttpServerBuilder(0, getHandler())
                .pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpServerConfigurator()).build();
        server.start();
        client = RxNetty.<ByteBuf, ByteBuf>newHttpClientBuilder("localhost", server.getServerPort())
                .pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpClientConfigurator())
                .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000)
                .build();

    }

    @After
    public void tearDown() throws InterruptedException {
        server.shutdown();
    }
}


text:
require 'serf/command'

require 'moogle/error'
require 'moogle/events/target_destroyed'
require 'moogle/requests/destroy_target'
require 'moogle/models'

module Moogle
module Commands

  class DestroyTarget
    include Serf::Command

    self.request_factory = Moogle::Requests::DestroyTarget

    def call
      target_model = opts :target_model, Moogle::Target
      event_class = opts :event_class, Moogle::Events::TargetDestroyed

      target_id = request.target_id
      target = target_model.get target_id

      # We only attempt to destroy the link if it exists.
      # We raise an error if we are unable to destroy an existing link.
      raise 'Unable to destroy target' unless target.destroy if target

      return event_class.new(
        request.create_child_uuids.merge(target_id: target_id))
    rescue => e
      e.extend Moogle::Error
      raise e
    end

  end

end
end


text:
package ch.heigvd.amt.amt_project.models;

import java.io.UnsupportedEncodingException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

/**
 *
 * @author YounTheory, mberthouzoz
 */
@Entity
@NamedQueries({
    @NamedQuery(name = "Account.login", query = "SELECT a FROM Account a WHERE a.email = :email AND a.password = :password")
})
public class Account extends AbstractDomainModel<Long> {
    /* Attributs */

    @Column(unique = true)
    private String email;

    private String firstName;

    private String lastName;

    private String password;

    @ManyToMany(mappedBy = "accounts")
    private List<Role> roles;

    public Account() {

    }

    public Account(String email, String firstName, String lastName, String password) {
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
        try {
            this.password = doHash(password, email);
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
            Logger.getLogger(Account.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param password the string password not hashed
     * @param salt the salt of the pwd
     * @return the password hashed
     * @throws java.io.UnsupportedEncodingException
     * @throws java.security.NoSuchAlgorithmException
     */
    public static String doHash(String password, String salt) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.reset();
        digest.update(salt.getBytes());

        byte[] byteData = digest.digest(password.getBytes("UTF-8"));

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }

        return sb.toString();
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        try {
            this.password = doHash(password, getEmail());
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
            Logger.getLogger(Account.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @return the roles
     */
    public List<Role> getRoles() {
        return roles;
    }

    /**
     * @param roles the Role to set
     */
    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    /**
     * Add a role to Account
     *
     * @param role
     */
    public void addRole(Role role) {
        this.roles.add(role);
    }

    /**
     * Remove a role to Account
     *
     * @param role
     */
    public void removeRole(Role role) {
        if (roles.contains(role)) {
            this.roles.remove(role);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<section xmlns="http://docbook.org/ns/docbook"
  xmlns:xi="http://www.w3.org/2001/XInclude"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  version="5.0"
  xml:id="swift-verify">
  <title>验证</title>
  <para>本章节讲述了如何使用OpenStack中的对象存储服务。</para>
  <procedure>
    <note>
      <para><literal>swift</literal> client 需要加
        <literal>-V 3</literal> 参数去访问Identity Service V3 API。</para>
    </note>
    <note>
      <para>下列操作需要在控制节点上进行。</para>
    </note>
    <step>
      <para>切换到demo账号:</para>
      <screen><prompt>$</prompt> <userinput>source demo-openrc.sh</userinput></screen>
    </step>
    <step>
      <para>查看服务状态:</para>
      <screen><prompt>$</prompt> <userinput>swift -V 3 stat</userinput>
<computeroutput>Account: AUTH_c75cafb58f5049b8a976506737210756
     Containers: 0
        Objects: 0
          Bytes: 0
X-Put-Timestamp: 1429736713.92936
    X-Timestamp: 1429736713.92936
     X-Trans-Id: txdea07add01ca4dbdb49a2-0055380d09
   Content-Type: text/plain; charset=utf-8</computeroutput></screen>
    </step>
    <step>
      <para>上传测试文件:</para>
      <screen><prompt>$</prompt> <userinput>swift -V 3 upload demo-container1 <replaceable>FILE</replaceable></userinput>
<computeroutput><replaceable>FILE</replaceable></computeroutput></screen>
      <para>将 <replaceable>FILE</replaceable> 替换成本地的文件上传到 <literal>demo-container1</literal>
        容器.</para>
    </step>
    <step>
      <para>列出容器:</para>
      <screen><prompt>$</prompt> <userinput>swift -V 3 list</userinput>
<computeroutput>demo-container1</computeroutput></screen>
    </step>
    <step>
      <para>下载测试文件:</para>
      <screen><prompt>$</prompt> <userinput>swift -V 3 download demo-container1 <replaceable>FILE</replaceable></userinput>
<computeroutput><replaceable>FILE</replaceable> [auth 0.295s, headers 0.339s, total 0.339s, 0.005 MB/s]</computeroutput></screen>
      <para>将 <replaceable>FILE</replaceable> 替换成刚刚上传到容器 <literal>demo-container1</literal>
        中的文件.</para>
    </step>
  </procedure>
</section>


text:
package org.ec.jap.dao.sistema;

import org.ec.jap.entiti.sistema.RolAccionNegocio;

/**
 * Interfaz de Acceso a Datos de {@link RolAccionNegocio}
 *
 * @author Freddy
 * @version {@code 1.0}
 */
public interface RolAccionNegocioDAO extends Sistema<RolAccionNegocio, Integer> {

}


text:
title: Before You Head Out
published: true
featured: false
date: 2016-05-17T10:00:00.000Z
description: Let the Booksmith inspire your next big adventure
featured_image_path: /uploads/mg_0924-compressor.jpg
featured_image_position: 50
show_featured_image_in_post: false
cover_image_path:
fancy_font:
category:
staff:
  - gwen
books:
---

![](/uploads/versions/mg_1024-compressor---x----500-500x---.jpg)

Here at Brookline Booksmith we have everything you need to inspire you this summer.  Before your vacation (or staycation) cycle through our great titles, helpful travel guides and nifty magazines like [Far Ride](https://farridemag.com/main).

*Far Ride* is a periodical dedicated to documenting cycling journeys around the world. The beautiful photos and detailed articles illuminate the world of adventure cycling – a challenging but rewarding way to travel.

---

![](/uploads/versions/mg_0950-compressor---x----750-500x---.jpg)

If you're spending time indoors grab a copy of [The Bicycling Coloring Book – Journey to the Edge of the World by Shan Jiang ](https://www.brooklinebooksmith-shop.com/book/9781780677491)

This detailed coloring book will certainly take you places. While most coloring books are geared toward calming meditation, this book asks its audience to journey into a wild, psychedelic new reality.

---

![](/uploads/versions/mg_0929-compressor---x----500-500x---.jpg)

Whether you're riding your bike this Summer or admiring the composition of spokes and wheels on your tea towel we have everything you'll need for your journey.  As the weather warms up get outside, ride a bike (or wear a bike) and come visit your favorite local bookstore.

---

*Photos by Gwendolyn Corkill 2016*


text:
<?php
namespace Skrz\Bundle\BunnyBundle\Tests\Command;

use Bunny\Client;
use Bunny\Message as BunnyMessage;
use Skrz\Bundle\BunnyBundle\ContentTypes;
use Skrz\Bundle\BunnyBundle\SkrzBunnyBundle;
use Skrz\Bundle\BunnyBundle\Tests\Fixtures\Message;
use Skrz\Bundle\BunnyBundle\Tests\Fixtures\Meta\MessageMeta;
use Skrz\Bundle\BunnyBundle\Tests\Fixtures\TestKernel;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

class ProducerCommandTest extends \PHPUnit_Framework_TestCase
{

	private function runWithConfig($config, $input)
	{
		$kernel = new TestKernel($config);
		$kernel->boot();
		/** @var SkrzBunnyBundle $bundle */
		$bundle = $kernel->getBundle("SkrzBunnyBundle");
		$application = new Application($kernel);
		$bundle->registerCommands($application);
		$tester = new CommandTester($application->find("bunny:producer"));
		$tester->execute($input);

		return $kernel->getContainer();
	}

	protected function setUp()
	{
		$client = new Client();
		$client->connect();

		$channel = $client->channel();

		$channel->queueDelete("producer_test_queue");
		$channel->exchangeDelete("producer_test_exchange");

		$client->disconnect();
	}

	protected function tearDown()
	{
		$this->setUp();
	}

	public function testProducerWithJson()
	{
		$this->runWithConfig(__DIR__ . "/../Fixtures/producer.yml", [
			"producer-name" => "JsonMessage",
			"message" => MessageMeta::toJson(
				(new Message())
					->setIntValue(234)
					->setFloatValue(2.41)
					->setStringValue("test")
			)
		]);

		$client = new Client();
		$client->connect();
		$channel = $client->channel();

		/** @var BunnyMessage $msg */
		$msg = $channel->get("producer_test_queue", true);
		$this->assertNotNull($msg);

		$this->assertEquals(ContentTypes::APPLICATION_JSON, $msg->getHeader("content-type"));
		$object = MessageMeta::fromJson($msg->content);
		$this->assertNotNull($object);
		$this->assertEquals(234, $object->getIntValue());
		$this->assertEquals(2.41, $object->getFloatValue());
		$this->assertEquals("test", $object->getStringValue());
	}

	public function testProducerWithProtobuf()
	{
		$this->runWithConfig(__DIR__ . "/../Fixtures/producer.yml", [
			"producer-name" => "ProtobufMessage",
			"message" => MessageMeta::toJson(
				(new Message())
					->setIntValue(234)
					->setFloatValue(2.41)
					->setStringValue("test")
			)
		]);

		$client = new Client();
		$client->connect();
		$channel = $client->channel();

		/** @var BunnyMessage $msg */
		$msg = $channel->get("producer_test_queue", true);
		$this->assertNotNull($msg);

		$this->assertEquals(ContentTypes::APPLICATION_PROTOBUF, $msg->getHeader("content-type"));
		$object = MessageMeta::fromProtobuf($msg->content);
		$this->assertNotNull($object);
		$this->assertEquals(234, $object->getIntValue());
		$this->assertEquals(2.41, $object->getFloatValue());
		$this->assertEquals("test", $object->getStringValue());
	}

	public function testEmptyExchangeProducer()
	{
		$this->runWithConfig(__DIR__ . "/../Fixtures/producer.yml", [
			"producer-name" => "EmptyExchange",
			"message" => MessageMeta::toJson(
				(new Message())
					->setIntValue(234)
					->setFloatValue(2.41)
					->setStringValue("test")
			)
		]);

		$client = new Client();
		$client->connect();
		$channel = $client->channel();

		/** @var BunnyMessage $msg */
		$msg = $channel->get("producer_test_queue", true);
		$this->assertNotNull($msg);

		$this->assertEquals(ContentTypes::APPLICATION_JSON, $msg->getHeader("content-type"));
		$object = MessageMeta::fromJson($msg->content);
		$this->assertNotNull($object);
		$this->assertEquals(234, $object->getIntValue());
		$this->assertEquals(2.41, $object->getFloatValue());
		$this->assertEquals("test", $object->getStringValue());
	}

}


text:
package com.github.aureliano.edocs.annotation.validation.apply;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import com.github.aureliano.edocs.annotation.validation.Decimal;
import com.github.aureliano.edocs.common.exception.EDocsException;
import com.github.aureliano.edocs.common.helper.ReflectionHelper;

public class DecimalValidator implements IValidator {

	public DecimalValidator() {
		super();
	}

	@Override
	public Set<ConstraintViolation> validate(Object object, Method method, Annotation annotation) {
		String property = ReflectionHelper.getSimpleAccessMethodName(method);
		Object returnedValue = ReflectionHelper.callMethod(object, method.getName(), null, null);

		if (returnedValue == null) {
			return null;
		}

		Set<ConstraintViolation> violations = new HashSet<ConstraintViolation>();
		Decimal decimalAnnotation = (Decimal) annotation;
		String message = decimalAnnotation.message();
		double minSize = decimalAnnotation.min();
		double maxSize = decimalAnnotation.max();

		if (!((returnedValue instanceof Double) || (returnedValue instanceof Float))) {
			throw new EDocsException("Decimal validator supports only Double and Float values but got " +
					returnedValue.getClass().getName());
		}

		Double objectSize = Double.parseDouble(returnedValue.toString());

		if ((minSize > objectSize) || (maxSize < objectSize)) {
			violations.add(new ConstraintViolation()
				.withValidator(Decimal.class)
				.withMessage(message
					.replaceFirst("#\\{0\\}", property)
					.replaceFirst("#\\{1\\}", String.valueOf(minSize))
					.replaceFirst("#\\{2\\}", String.valueOf(maxSize))
					.replaceFirst("#\\{3\\}", String.valueOf(objectSize))));
		}

		return violations;
	}
}


text:
using bpulse_sdk_csharp.pulseRepository;
using log4net;
using me.bpulse.domain.proto.collector;
using System;
using System.Collections.Generic;
using bpulse_sdk_csharp.rest;
using System.Configuration;
using bpulse_sdk_csharp.bpulsesConstants;
using System.Runtime.CompilerServices;

namespace bpulse_sdk_csharp.thread
{
    /// <summary>
    /// clase que maneja el envio
    /// </summary>
    public class PulsesRestSenderThread : ISyncService
    {
        private PulsesRQ _pulseToSendByRest;
        private IRepository _PulsesRepository;
        private List<string> _keysToDelete;
        private int _tableIndex;
        private string _dbMode;
        private string _username = ConfigurationManager.AppSettings[BPulsesConstants.BPULSE_PROPERTY_USER_CREDENTIALS_USERNAME];
        private string _pass = ConfigurationManager.AppSettings[BPulsesConstants.BPULSE_PROPERTY_USER_CREDENTIALS_PASSWORD];

        private static readonly ILog logger = LogManager.GetLogger("bpulseLogger");

        /// <summary>
        /// Constructor de la clase para iniciar el proceso de envio
        /// </summary>
        /// <param name="pulseToSendByRest">Pulso a enviar</param>
        /// <param name="pulseRepository">repositorio de pulsos</param>
        /// <param name="pKeysToDelete">lista de guid de los pulsos a eliminar</param>
        /// <param name="tabindex"></param>
        /// <param name="dbMode">modo de bd por defecto MEMoria</param>
        public PulsesRestSenderThread(PulsesRQ pulseToSendByRest, IRepository pulseRepository, List<string> pKeysToDelete, int tabindex, string dbMode)
        {
            _pulseToSendByRest = pulseToSendByRest;
            _PulsesRepository = pulseRepository;
            _keysToDelete = pKeysToDelete;
            _tableIndex = tabindex;
            _dbMode = dbMode;
            Run();
        }

        /// <summary>
        /// Metodo que inicializa los procesos
        /// </summary>
        public void Run()
        {
            RestInvoker sendByRestServices = new RestInvoker();

            bool sended = sendByRestServices.SendByRestService(_username, _pass, _pulseToSendByRest);
            if (sended)
            {
                logger.Info("Enviado Exitosamente " + _PulsesRepository.getDBSize());
                deletePulseKeysProcessedByRest();
            }
            else
            {
                logger.Error("Falla al Enviar " + _PulsesRepository.getDBSize() + "los siguientes pulsos ");
            }

        }

        /// <summary>
        ///  Metodo para eliminar los pulsos que ya han sido procesados del repositorio de pulsos en memoria.
        /// </summary>
        [MethodImpl(MethodImplOptions.Synchronized)]
        private void deletePulseKeysProcessedByRest()
        {
            if (_dbMode.Equals(BPulsesConstants.BPULSE_MEM_PULSES_REPOSITORY))
            {
                foreach (string keyToDelete in _keysToDelete)
                {
                    _PulsesRepository.deleteBpulseRQByKey(keyToDelete);
                }
            }
        }
    }
}


text:
<?php

namespace Drupal\Tests\node\FunctionalJavascript;

use Drupal\FunctionalJavascriptTests\WebDriverTestBase;

/**
 * Tests that outlines of node meta values are displayed in summaries and tabs.
 *
 * @group node
 */
class CollapsedSummariesTest extends WebDriverTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['node'];

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    $this->drupalCreateContentType([
      'type' => 'page',
      'name' => 'Basic page',
    ]);

    $this->drupalCreateNode([
      'title' => $this->randomMachineName(),
      'type' => 'page',
    ]);

    $this->drupalLogin($this->createUser(['edit any page content']));
  }

  /**
   * Confirm that summaries are provided for node meta at all widths.
   */
  public function testSummaries() {
    $page = $this->getSession()->getPage();
    $assert_session = $this->assertSession();

    // At a wider width, vertical tabs are used for the meta section of the node
    // form.
    $this->getSession()->resizeWindow(1200, 1200);
    $this->drupalGet('node/1/edit');

    $assert_session->waitForText("New revision");
    $summary = $assert_session->waitForElement('css', '.vertical-tabs__menu-item-summary');
    $this->assertNotNull($summary);
    $this->assertTrue($summary->isVisible());
    $this->assertEquals('New revision', $summary->getText());
    $page->uncheckField('revision');
    $assert_session->waitForText('No revision');
    $this->assertEquals('No revision', $summary->getText());

    // At a narrower width, details are used for the meta section of the node
    // form.
    $this->getSession()->resizeWindow(600, 1200);
    $this->drupalGet('node/1/edit');

    $summary = $assert_session->waitForElement('css', 'span.summary');
    $this->assertNotNull($summary);
    $this->assertTrue($summary->isVisible());
    $page->uncheckField('revision');
    $assert_session->waitForText('No revision');
    $this->assertEquals('(No revision)', $summary->getText());
  }

}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-head',
  templateUrl: './head.component.html',
  styleUrls: ['./head.component.scss']
})
export class HeadComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
package com.facebook.buck.util.versioncontrol;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import com.facebook.buck.cli.BuckConfig;
import com.facebook.buck.cli.FakeBuckConfig;
import com.google.common.collect.ImmutableMap;

import org.junit.Test;

public class VersionControlBuckConfigTest {
  private static final String HG_CMD = "myhg";
  private static final String GENERATE_STATISTICS = "true";
  private static final boolean GENERATE_STATISTICS_RESULT = true;

  @Test
  public void givenHgCmdInConfigThenReturnHgCmdFromConfig() {
    BuckConfig buckConfig = FakeBuckConfig.builder().setSections(
        ImmutableMap.of(
            VersionControlBuckConfig.VC_SECTION_KEY,
            ImmutableMap.of(VersionControlBuckConfig.HG_CMD_SETTING_KEY, HG_CMD))).build();
    VersionControlBuckConfig config = new VersionControlBuckConfig(buckConfig);
    assertThat(HG_CMD, is(equalTo(config.getHgCmd())));
  }

  @Test
  public void givenHgCmdNotInConfigThenReturnDefault() {
    BuckConfig buckConfig = FakeBuckConfig.builder().setSections(
        ImmutableMap.of(
            VersionControlBuckConfig.VC_SECTION_KEY,
            ImmutableMap.of())).build();
    VersionControlBuckConfig config = new VersionControlBuckConfig(buckConfig);
    assertThat(VersionControlBuckConfig.HG_CMD_DEFAULT, is(equalTo(config.getHgCmd())));
  }

  @Test
  public void givenGenerateStatisticsInConfigThenReturnGenerateStatisticsFromConfig() {
    BuckConfig buckConfig = FakeBuckConfig.builder().setSections(
        ImmutableMap.of(
            VersionControlBuckConfig.VC_SECTION_KEY,
            ImmutableMap.of(
                VersionControlBuckConfig.GENERATE_STATISTICS_KEY, GENERATE_STATISTICS))).build();
    VersionControlBuckConfig config = new VersionControlBuckConfig(buckConfig);
    assertThat(GENERATE_STATISTICS_RESULT, is(equalTo(config.shouldGenerateStatistics())));
  }

  @Test
  public void givenGenerateStatisticsNotInConfigThenReturnDefault() {
    BuckConfig buckConfig = FakeBuckConfig.builder().setSections(
        ImmutableMap.of(
            VersionControlBuckConfig.VC_SECTION_KEY,
            ImmutableMap.of())).build();
    VersionControlBuckConfig config = new VersionControlBuckConfig(buckConfig);
    assertThat(
        VersionControlBuckConfig.GENERATE_STATISTICS_DEFAULT,
        is(equalTo(config.shouldGenerateStatistics())));
  }
}


text:
<meta_metadata_repository name="springer_editor"
  package="ecologylab.bigsemantics.generated.library.person.author">

  <meta_metadata name="springer_editor" extends="author" schema_org_itemtype="http://schema.org/Person"
    comment="An editor of a book or article on Springer Link.">
    <collection name="creative_works">
      <xpath></xpath>
      <scalar name="title">
        <xpath></xpath>
      </scalar>
      <scalar name="location">
        <xpath></xpath>
      </scalar>
    </collection>
  </meta_metadata>

</meta_metadata_repository>


text:
/**
 * \file opt_conditional_discard.cpp
 *
 * Replace
 *
 *    if (cond) discard;
 *
 * with
 *
 *    (discard <condition>)
 */

#include "compiler/glsl_types.h"
#include "ir.h"

namespace {

class opt_conditional_discard_visitor : public ir_hierarchical_visitor {
public:
   opt_conditional_discard_visitor()
   {
      progress = false;
   }

   ir_visitor_status visit_leave(ir_if *);

   bool progress;
};

} /* anonymous namespace */

bool
opt_conditional_discard(exec_list *instructions)
{
   opt_conditional_discard_visitor v;
   v.run(instructions);
   return v.progress;
}

ir_visitor_status
opt_conditional_discard_visitor::visit_leave(ir_if *ir)
{
   /* Look for "if (...) discard" with no else clause or extra statements. */
   if (ir->then_instructions.is_empty() ||
       !ir->then_instructions.get_head_raw()->next->is_tail_sentinel() ||
       !((ir_instruction *) ir->then_instructions.get_head_raw())->as_discard() ||
       !ir->else_instructions.is_empty())
      return visit_continue;

   /* Move the condition and replace the ir_if with the ir_discard. */
   ir_discard *discard = (ir_discard *) ir->then_instructions.get_head_raw();
   if (!discard->condition)
      discard->condition = ir->condition;
   else {
      void *ctx = ralloc_parent(ir);
      discard->condition = new(ctx) ir_expression(ir_binop_logic_and,
                                                  ir->condition,
                                                  discard->condition);
   }
   ir->replace_with(discard);

   progress = true;

   return visit_continue;
}