import java.time.Clock

import com.google.inject.AbstractModule
import services._

class Module extends AbstractModule {

  override def configure() = {
//    bind(classOf[Queue]).to(classOf[DBQueue])
//    bind(classOf[Dispatcher]).to(classOf[DBQueue])
    bind(classOf[Queue]).to(classOf[SimpleQueue]).asEagerSingleton()
    bind(classOf[Dispatcher]).to(classOf[SimpleQueue])
    bind(classOf[LogStore]).to(classOf[SimpleLogStore])
    bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
  }

}

import java.time.Clock

import com.google.inject.AbstractModule
import services._

class Module extends AbstractModule {

  override def configure() = {
//    bind(classOf[Queue]).to(classOf[DBQueue]).asEagerSingleton()
//    bind(classOf[Dispatcher]).to(classOf[DBQueue])
    bind(classOf[Queue]).to(classOf[SimpleQueue]).asEagerSingleton()
    bind(classOf[Dispatcher]).to(classOf[SimpleQueue])
    bind(classOf[LogStore]).to(classOf[SimpleLogStore])
    bind(classOf[Clock]).toInstance(Clock.systemDefaultZone)
  }

}

Make DB queue eager singleton

Make DB queue eager singleton


package net.liftweb.json

/*
 * Copyright 2009 WorldWide Conferencing, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 */

import java.util.Date

trait Formats {
  val dateFormat: DateFormat
}

trait DateFormat {
  def parse(s: String): Option[Date]
}

object DefaultFormats extends DefaultFormats
trait DefaultFormats extends Formats {
  import java.text.{ParseException, SimpleDateFormat}

  val dateFormat = new DateFormat {
    def parse(s: String) = try {
      Some(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(s))
    } catch {
      case e: ParseException => None
    }
  }
}

package net.liftweb.json

/*
 * Copyright 2009 WorldWide Conferencing, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 */

import java.util.{Date, TimeZone}

trait Formats {
  val dateFormat: DateFormat
}

trait DateFormat {
  def parse(s: String): Option[Date]
}

/** Default date format is UTC time.
 */
object DefaultFormats extends DefaultFormats
trait DefaultFormats extends Formats {
  import java.text.{ParseException, SimpleDateFormat}

  val dateFormat = new DateFormat {
    def parse(s: String) = try {
      val format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
      format.setTimeZone(TimeZone.getTimeZone("UTC"))
      Some(format.parse(s))
    } catch {
      case e: ParseException => None
    }
  }
}

Fix timezone of default date format.

Fix timezone of default date format.


package dotty

import scala.reflect.runtime.universe.TypeTag
import scala.Predef.???

/** unimplemented implicit for TypeTag */
object DottyPredef {
  implicit def typeTag[T]: TypeTag[T] = ???

// not yet:
// def classOf[T](implicit ctag: ClassTag[T]): Class[T] =
//    ctag.runtimeClass
}

package dotty

import scala.reflect.runtime.universe.TypeTag
import scala.reflect.ClassTag
import scala.Predef.???

/** unimplemented implicit for TypeTag */
object DottyPredef {
  implicit def typeTag[T]: TypeTag[T] = ???

  implicit def arrayTag[T](implicit ctag: ClassTag[T]): ClassTag[Array[T]] =
    ctag.wrap
}

Fix search of Array classTags.

Fix search of Array classTags.

If a classtag for `T` is available, a classtag
for `Array[T]` can also be generated.


/**
 * Licensed to Big Data Genomics (BDG) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The BDG licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.fnothaft.ananas

import org.bdgenomics.utils.misc.SparkFunSuite

trait AnanasFunSuite extends SparkFunSuite {

  override val appName: String = "ananas"
  override val properties: Map[String, String] = Map(("spark.serializer", "org.apache.spark.serializer.KryoSerializer"),
    ("spark.kryo.registrator", "org.bdgenomics.adam.serialization.ADAMKryoRegistrator"),
    ("spark.kryoserializer.buffer.mb", "4"),
    ("spark.kryo.referenceTracking", "true"))
  override val master: String = "local[1]"
}

/**
 * Licensed to Big Data Genomics (BDG) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The BDG licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.fnothaft.ananas

import org.bdgenomics.utils.misc.SparkFunSuite

trait AnanasFunSuite extends SparkFunSuite {

  override val appName: String = "ananas"
  override val properties: Map[String, String] = Map(("spark.serializer", "org.apache.spark.serializer.KryoSerializer"),
    ("spark.kryo.registrator", "org.bdgenomics.adam.serialization.ADAMKryoRegistrator"))
  override val master: String = "local[1]"
}

[ananas-15] Remove deprecated kryo serializer buffer size.


package eu.timepit.refined.pureconfig

import com.typesafe.config.ConfigFactory
import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric.Positive
import org.scalacheck.Prop._
import org.scalacheck.Properties
import pureconfig._
import pureconfig.error.{CannotConvert, ConfigReaderFailures}

class RefTypeConfigConvertSpec extends Properties("RefTypeConfigConvert") {

  type PosInt = Int Refined Positive
  case class Config(value: PosInt)

  property("load success") = secure {
    loadConfigWithValue("1") ?=
      Right(Config(1))
  }

  property("load failure") = secure {
    loadConfigWithValue("0") =?
      Left(
        ConfigReaderFailures(
          CannotConvert(
            value = "0",
            toTyp = "",
            because = "Predicate failed: (0 > 0).",
            location = None
          )))
  }

  property("roundtrip success") = secure {
    val config = Config(1)
    val configValue = ConfigConvert[Config].to(config)
    ConfigConvert[Config].from(configValue) ?=
      Right(config)
  }

  def loadConfigWithValue(value: String): Either[ConfigReaderFailures, Config] =
    loadConfig[Config](ConfigFactory.parseString(s"value = $value"))
}

package eu.timepit.refined.pureconfig

import com.typesafe.config.ConfigFactory
import eu.timepit.refined.api.Refined
import eu.timepit.refined.auto._
import eu.timepit.refined.numeric.Positive
import org.scalacheck.Prop._
import org.scalacheck.Properties
import pureconfig._
import pureconfig.error.{CannotConvert, ConfigReaderFailures}

class RefTypeConfigConvertSpec extends Properties("RefTypeConfigConvert") {

  type PosInt = Int Refined Positive
  case class Config(value: PosInt)

  property("load success") = secure {
    loadConfigWithValue("1") ?=
      Right(Config(1))
  }

  property("load failure (predicate)") = secure {
    loadConfigWithValue("0") =?
      Left(
        ConfigReaderFailures(
          CannotConvert(
            value = "0",
            toTyp = "",
            because = "Predicate failed: (0 > 0).",
            location = None
          )))
  }

  property("load failure (wrong type)") = secure {
    loadConfigWithValue("abc") =?
      Left(
        ConfigReaderFailures(
          CannotConvert(
            value = "abc",
            toTyp = "Int",
            because = "java.lang.NumberFormatException: For input string: \"abc\"",
            location = None
          )))
  }

  property("roundtrip success") = secure {
    val config = Config(1)
    val configValue = ConfigConvert[Config].to(config)
    ConfigConvert[Config].from(configValue) ?=
      Right(config)
  }

  def loadConfigWithValue(value: String): Either[ConfigReaderFailures, Config] =
    loadConfig[Config](ConfigFactory.parseString(s"value = $value"))
}

Add pureconfig test for wrong config value type


/*
 * Copyright 2016 Codnos Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.codnos.dbgp

import java.util.concurrent.Callable

trait AwaitilitySupport {
  implicit def byNameFunctionToCallableOfType[T](function: () => T): Callable[T] = {
    new Callable[T] {
      def call(): T = function()
    }
  }
  implicit def byNameFunctionToRunnable[T](function: () => T): Runnable = {
    new Runnable {
      def run() = function()
    }
  }
}

/*
 * Copyright 2016 Codnos Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.codnos.dbgp

import java.util.concurrent.Callable

trait AwaitilitySupport {
  implicit def byNameFunctionToCallableOfType[T](function: () => T): Callable[T] = {
    new Callable[T] {
      def call(): T = function()
    }
  }
  implicit def byNameFunctionToRunnable[T](function: => T): Runnable = {
    new Runnable {
      def run() = function
    }
  }
}

Use nullified function to be able to pass in code blocks.


package susuru.twitter

import org.specs2._
import org.specs2.mock.Mockito
import twitter4j._

class TwitterSusuruTest extends Specification with Mockito {
  def is = s2"""
  Specification: ${this.getClass.getName}
    contain 11 characters                             $e1
  """

  def e1 = {
    val twitter = mock[Twitter]
    val pool = new TwitterSusuru(() => Map(1L -> twitter))
    true
  }
}

package susuru.twitter

import scala.collection.JavaConverters._

import org.specs2._
import org.specs2.mock.Mockito
import twitter4j._

import scala.concurrent.Await
import scala.concurrent.duration.Duration

class TwitterSusuruTest extends Specification with Mockito {
  def is = s2"""
  Specification: ${this.getClass.getName}
    contain 11 characters                             $e1
  """

  def e1 = {
    val twitter = mock[Twitter]
    val responce = mock[ResponseList[User]]
    responce.getRateLimitStatus returns new RateLimitStatus {
      override val getResetTimeInSeconds: Int = Int.MaxValue
      override val getLimit: Int = Int.MaxValue
      override val getRemaining: Int = Int.MaxValue
      override val getSecondsUntilReset: Int = Int.MaxValue
    }
    responce.iterator() returns List().iterator.asJava
    twitter.lookupUsers(1L, 2L, 3L) returns responce
    val susuru = new TwitterSusuru(() => Map(1L -> twitter))
    var a: List[Long] = Nil
    try {
      susuru.start()
      Await.result(susuru.loanDo(Some(1L)) { twitter =>
        val res: ResponseList[User] = twitter.lookupUsers(1L, 2L, 3L)
        a = res.asScala.map(_.getId).toList
        res
      }, Duration("10.0s"))
      a mustEqual List()
    } finally {
      susuru.kill()
    }
  }
}

Implement complete (with many issues)

Implement complete (with many issues)


package com.sumologic.sumobot.util

/**
 * This attempts to be a trivial replacement to Scala 2.13 moving .par to a new package, which ends up being hard to
 * import correctly with Gradle.  (It should be relatively easy with SBT, but alas.)
 *
 * See https://github.com/scala/scala-parallel-collections and
 * https://github.com/scala/scala-parallel-collections/issues/22
 */
object ParExecutor {

  def runInParallel[T](items: Seq[T])(f: T => Unit): Unit = {
    items.par.foreach {
      item => f(item)
    }
  }

  def runInParallelAndGetResults[T, U](items: Seq[T])(f: T => U): Seq[U] = {
    items.par.map {
      item => f(item)
    }.seq
  }

  def runInParallelAndGetFlattenedResults[T, U](items: Seq[T])(f: T => Seq[U]): Seq[U] = {
    items.par.flatMap {
      item => f(item)
    }.seq
  }

}

package com.sumologic.sumobot.util

import java.util.concurrent.{SynchronousQueue, ThreadPoolExecutor, TimeUnit}

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext, Future}

/**
 * This attempts to be a trivial replacement to Scala 2.13 moving .par to a new package, which ends up being hard to
 * import correctly with Gradle.  (It should be relatively easy with SBT, but alas.)
 *
 * See https://github.com/scala/scala-parallel-collections and
 * https://github.com/scala/scala-parallel-collections/issues/22
 */
object ParExecutor {
  implicit private[this] val executor = ExecutionContext.fromExecutor(
    new ThreadPoolExecutor(16, 32, 1000L, TimeUnit.MILLISECONDS, new SynchronousQueue[Runnable]())
  )

  def runInParallel[T](items: Seq[T])(f: T => Unit): Unit = {
    executeInThreadPool(items)(f)
  }

  def runInParallelAndGetResults[T, U](items: Seq[T])(f: T => U): Seq[U] = {
    executeInThreadPool(items)(f)
  }

  def runInParallelAndGetFlattenedResults[T, U](items: Seq[T])(f: T => Seq[U]): Seq[U] = {
    executeInThreadPool(items)(f).flatten
  }

  private[this] def executeInThreadPool[T, U, V](items: Seq[T])(f: T => U): Seq[U] = {
    val futures = items.map {
      item =>
        Future[U] {
          f(item)
        }
    }

    val seqFuture = Future.sequence(futures)
    Await.result(seqFuture, Duration.Inf)
  }

}

Replace .par with threadpool so it can work in 2.13


package cromwell.logging

import java.util.UUID

import cromwell.CromwellTestkitSpec
import cromwell.binding.values.WdlValue
import cromwell.engine.backend.local.{LocalBackend, LocalBackendCall}
import cromwell.engine.workflow.CallKey
import cromwell.engine.{AbortRegistrationFunction, WorkflowDescriptor, WorkflowId, WorkflowSourceFiles}
import org.scalatest.{FlatSpec, Matchers}

class WorkflowLoggerSpec extends FlatSpec with Matchers {
  val descriptor = WorkflowDescriptor(
    WorkflowId(UUID.fromString("fc6cfad9-65e9-4eb7-853f-7e08c1c8cf8e")),
    WorkflowSourceFiles(
      "task x {command {ps}} workflow w {call x}",
      "{}",
      "{}"
    )
  )
  val backend = LocalBackend(new CromwellTestkitSpec.TestWorkflowManagerSystem().actorSystem)
  val backendCall = LocalBackendCall(
    backend,
    descriptor,
    CallKey(descriptor.namespace.workflow.calls.find(_.unqualifiedName == "x").head, None),
    Map.empty[String, WdlValue],
    AbortRegistrationFunction(_ => ())
  )

  "WorkflowLogger" should "create a valid tag" in {
    backend.workflowLogger(descriptor).tag shouldBe "LocalBackend [UUID(fc6cfad9)]"
  }

  it should "create a valid tag for backend call" in {
    backend.workflowLoggerWithCall(backendCall).tag shouldBe "LocalBackend [UUID(fc6cfad9):x]"
  }
}

package cromwell.logging

import java.util.UUID

import cromwell.CromwellTestkitSpec
import cromwell.binding.values.WdlValue
import cromwell.engine.backend.local.{LocalBackend, LocalBackendCall}
import cromwell.engine.workflow.CallKey
import cromwell.engine.{AbortRegistrationFunction, WorkflowDescriptor, WorkflowId, WorkflowSourceFiles}
import org.scalatest.{FlatSpec, Matchers}

class WorkflowLoggerSpec extends FlatSpec with Matchers {
  val testWorkflowManagerSystem = new CromwellTestkitSpec.TestWorkflowManagerSystem()

  val descriptor = WorkflowDescriptor(
    WorkflowId(UUID.fromString("fc6cfad9-65e9-4eb7-853f-7e08c1c8cf8e")),
    WorkflowSourceFiles(
      "task x {command {ps}} workflow w {call x}",
      "{}",
      "{}"
    )
  )
  val backend = LocalBackend(testWorkflowManagerSystem.actorSystem)
  val backendCall = LocalBackendCall(
    backend,
    descriptor,
    CallKey(descriptor.namespace.workflow.calls.find(_.unqualifiedName == "x").head, None),
    Map.empty[String, WdlValue],
    AbortRegistrationFunction(_ => ())
  )

  "WorkflowLogger" should "create a valid tag" in {
    backend.workflowLogger(descriptor).tag shouldBe "LocalBackend [UUID(fc6cfad9)]"
  }

  it should "create a valid tag for backend call" in {
    backend.workflowLoggerWithCall(backendCall).tag shouldBe "LocalBackend [UUID(fc6cfad9):x]"
  }
}

Fix error that Travis seemed not to notice


package com.ruimo.scoins

import java.nio.charset.Charset

class ImmutableByteArray(private val table: Array[Byte]) {
  def apply(idx: Int): Byte = table(idx)
  def length: Int = table.length
  def asString(encoding: Charset): String = new String(table, encoding)
}

object ImmutableByteArray {
  def wrap(a: Array[Byte]) = new ImmutableByteArray(a)
  def apply(a: Array[Byte]) = new ImmutableByteArray(a.clone)
}

package com.ruimo.scoins

import java.nio.charset.Charset
import java.io.{InputStream, ByteArrayInputStream}

class ImmutableByteArray(private val table: Array[Byte]) {
  def apply(idx: Int): Byte = table(idx)
  def length: Int = table.length
  def asString(encoding: Charset): String = new String(table, encoding)
  def inputStream: InputStream = new ByteArrayInputStream(table)
}

object ImmutableByteArray {
  def wrap(a: Array[Byte]) = new ImmutableByteArray(a)
  def apply(a: Array[Byte]) = new ImmutableByteArray(a.clone)
}

Add method to serve InputStream.

Add method to serve InputStream.


package spark.examples

import spark._
import spark.rdd.NewHadoopRDD
import org.apache.hadoop.hbase.{HBaseConfiguration, HTableDescriptor}
import org.apache.hadoop.hbase.client.HBaseAdmin
import org.apache.hadoop.hbase.mapreduce.TableInputFormat

object HBaseTest {
  def main(args: Array[String]) {
    val sc = new SparkContext(args(0), "HBaseTest",
      System.getenv("SPARK_HOME"), Seq(System.getenv("SPARK_EXAMPLES_JAR")))

    val conf = HBaseConfiguration.create()

    // Other options for configuring scan behavior are available. More information available at
    // http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/mapreduce/TableInputFormat.html
    conf.set(TableInputFormat.INPUT_TABLE, args(1))

    // Initialize hBase table if necessary
    val admin = new HBaseAdmin(conf)
    if(!admin.isTableAvailable(args(1))) {
      val tableDesc = new HTableDescriptor(args(1))
      admin.createTable(tableDesc)
    }

    val hBaseRDD = new NewHadoopRDD(sc, classOf[TableInputFormat],
      classOf[org.apache.hadoop.hbase.io.ImmutableBytesWritable],
      classOf[org.apache.hadoop.hbase.client.Result], conf)

    hBaseRDD.count()

    System.exit(0)
  }
}

package spark.examples

import spark._
import spark.rdd.NewHadoopRDD
import org.apache.hadoop.hbase.{HBaseConfiguration, HTableDescriptor}
import org.apache.hadoop.hbase.client.HBaseAdmin
import org.apache.hadoop.hbase.mapreduce.TableInputFormat

object HBaseTest {
  def main(args: Array[String]) {
    val sc = new SparkContext(args(0), "HBaseTest",
      System.getenv("SPARK_HOME"), Seq(System.getenv("SPARK_EXAMPLES_JAR")))

    val conf = HBaseConfiguration.create()

    // Other options for configuring scan behavior are available. More information available at
    // http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/mapreduce/TableInputFormat.html
    conf.set(TableInputFormat.INPUT_TABLE, args(1))

    // Initialize hBase table if necessary
    val admin = new HBaseAdmin(conf)
    if(!admin.isTableAvailable(args(1))) {
      val tableDesc = new HTableDescriptor(args(1))
      admin.createTable(tableDesc)
    }

    val hBaseRDD = sc.newAPIHadoopRDD(conf, classOf[TableInputFormat],
      classOf[org.apache.hadoop.hbase.io.ImmutableBytesWritable],
      classOf[org.apache.hadoop.hbase.client.Result])

    hBaseRDD.count()

    System.exit(0)
  }
}

Switch to using SparkContext method to create RDD


//--------------------------------------
//
// MemoryAllocatorTest.scala
// Since: 2013/03/22 12:02
//
//--------------------------------------

package xerial.larray

/**
 * @author Taro L. Saito
 */
class MemoryAllocatorTest extends LArraySpec {
  "ConcurrentMemoryAllocator" should {
    "perform better than the default one in multi-threaded code" in {

      val N = 1000
      val B = 64 * 1024
      val m1 = new DefaultAllocator
      val m2 = new ConcurrentMemoryAllocator

      try {
        val t = time("alloc", repeat = 5) {
          block("default") {
            val l = for (i <- (0 until N).par) yield {
              new LIntArray(B)(m1)
            }
            l.foreach(_.free)
          }

          block("concurrent") {
            val l = for (i <- (0 until N).par) yield {
              new LIntArray(B)(m2)
            }
            l.foreach(_.free)
          }

          block("Array") {
            val l = for (i <- (0 until N).par) yield {
              new Array[Int](B)
            }
          }
        }
        t("concurrent") should be <= (t("default"))

      }
      finally {
        m1.releaseAll
        m2.releaseAll
      }
    }
  }
}

//--------------------------------------
//
// MemoryAllocatorTest.scala
// Since: 2013/03/22 12:02
//
//--------------------------------------

package xerial.larray

/**
 * @author Taro L. Saito
 */
class MemoryAllocatorTest extends LArraySpec {
  "ConcurrentMemoryAllocator" should {
    "perform better than the default one in multi-threaded code" in {

      val N = 1000
      val B = 64 * 1024
      val m1 = new DefaultAllocator
      val m2 = new ConcurrentMemoryAllocator

      try {
        val t = time("alloc", repeat = 5) {
          block("default") {
            val l = for (i <- (0 until N).par) yield {
              val a = new LIntArray(B)(m1)
              a(B-1) = 1
              a
            }
            l.foreach(_.free)
          }

          block("concurrent") {
            val l = for (i <- (0 until N).par) yield {
              val a = new LIntArray(B)(m2)
              a(B-1) = 1
              a
            }
            l.foreach(_.free)
          }

          block("Array") {
            val l = for (i <- (0 until N).par) yield {
              val a = new Array[Int](B)
              a(B-1) = 1
              a
            }
          }
        }
        t("concurrent") should be <= (t("default"))

      }
      finally {
        m1.releaseAll
        m2.releaseAll
      }
    }
  }
}

Add memory access in benchmark

Add memory access in benchmark


// Comment to get more information during initialization
logLevel := Level.Warn

// Resolvers
resolvers += "Typesafe repository" at "https://repo.typesafe.com/typesafe/releases/"

// Sbt plugins

// Use Scala.js 0.6.x
addSbtPlugin("com.vmunier"                  % "sbt-web-scalajs"           % "1.0.11-0.6")
addSbtPlugin("org.scala-js"                 % "sbt-scalajs"               % "0.6.32")
// If you prefer using Scala.js 1.x, uncomment the following plugins instead:
// addSbtPlugin("com.vmunier"               % "sbt-web-scalajs"           % "1.0.8")
// addSbtPlugin("org.scala-js"              % "sbt-scalajs"               % "1.0.0-M3")

addSbtPlugin("com.typesafe.play"         % "sbt-plugin"                % "2.8.1")
addSbtPlugin("org.portable-scala"        % "sbt-scalajs-crossproject"  % "1.0.0")
addSbtPlugin("com.typesafe.sbt"          % "sbt-gzip"                  % "1.0.2")
addSbtPlugin("com.typesafe.sbt"          % "sbt-digest"                % "1.1.4")
addSbtPlugin("com.typesafe.sbteclipse"   % "sbteclipse-plugin"         % "5.2.4")

// Comment to get more information during initialization
logLevel := Level.Warn

// Resolvers
resolvers += "Typesafe repository" at "https://repo.typesafe.com/typesafe/releases/"

// Sbt plugins

// Use Scala.js v1.x
addSbtPlugin("com.vmunier"               % "sbt-web-scalajs"           % "1.0.11")
addSbtPlugin("org.scala-js"              % "sbt-scalajs"               % "1.0.0")
// If you prefer using Scala.js v0.6.x, uncomment the following plugins instead:
// addSbtPlugin("com.vmunier"                  % "sbt-web-scalajs"           % "1.0.11-0.6")
// addSbtPlugin("org.scala-js"                 % "sbt-scalajs"               % "0.6.32")

addSbtPlugin("com.typesafe.play"         % "sbt-plugin"                % "2.8.1")
addSbtPlugin("org.portable-scala"        % "sbt-scalajs-crossproject"  % "1.0.0")
addSbtPlugin("com.typesafe.sbt"          % "sbt-gzip"                  % "1.0.2")
addSbtPlugin("com.typesafe.sbt"          % "sbt-digest"                % "1.1.4")
addSbtPlugin("com.typesafe.sbteclipse"   % "sbteclipse-plugin"         % "5.2.4")

Make Scala.js v1.0.0 the default.

Make Scala.js v1.0.0 the default.


package io.scalac.amqp.impl

import scala.concurrent.stm.Ref

import com.rabbitmq.client.{ShutdownSignalException, ShutdownListener, Connection}

import io.scalac.amqp.Delivery

import org.reactivestreams.{Subscriber, Publisher}

private[amqp] class QueuePublisher(connection: Connection, queue: String, prefetch: Int = 20)
  extends Publisher[Delivery] {
  val subscribers = Ref(Set[Subscriber[_ >: Delivery]]())

  override def subscribe(subscriber: Subscriber[_ >: Delivery]) =
    subscribers.single.getAndTransform(_ + subscriber) match {
      case ss if ss.contains(subscriber) ⇒
        throw new IllegalStateException(s"1.10: Subscriber=$subscriber is already subscribed to this publisher.")
      case _                             ⇒ try {
        val channel = connection.createChannel()
        channel.addShutdownListener(newShutdownListener(subscriber))

        val subscription = new QueueSubscription(channel, subscriber)
        subscriber.onSubscribe(subscription)

        channel.basicQos(prefetch)
        channel.basicConsume(queue, false, subscription)
      } catch {
        case exception: Exception ⇒ subscriber.onError(exception)
      }
    }

  def newShutdownListener(subscriber: Subscriber[_ >: Delivery]) = new ShutdownListener {
    override def shutdownCompleted(cause: ShutdownSignalException) =
      subscribers.single.transform(_ - subscriber)
  }
}

package io.scalac.amqp.impl

import scala.concurrent.stm.Ref

import com.rabbitmq.client.{ShutdownSignalException, ShutdownListener, Connection}

import io.scalac.amqp.Delivery

import org.reactivestreams.{Subscriber, Publisher}

private[amqp] class QueuePublisher(connection: Connection, queue: String, prefetch: Int = 20)
  extends Publisher[Delivery] {
  require(prefetch > 0, "prefetch <= 0")

  val subscribers = Ref(Set[Subscriber[_ >: Delivery]]())

  override def subscribe(subscriber: Subscriber[_ >: Delivery]) =
    subscribers.single.getAndTransform(_ + subscriber) match {
      case ss if ss.contains(subscriber) ⇒
        throw new IllegalStateException(s"1.10: Subscriber=$subscriber is already subscribed to this publisher.")
      case _                             ⇒ try {
        val channel = connection.createChannel()
        channel.addShutdownListener(newShutdownListener(subscriber))

        val subscription = new QueueSubscription(channel, subscriber)
        subscriber.onSubscribe(subscription)

        channel.basicQos(prefetch)
        channel.basicConsume(queue, false, subscription)
      } catch {
        case exception: Exception ⇒ subscriber.onError(exception)
      }
    }

  def newShutdownListener(subscriber: Subscriber[_ >: Delivery]) = new ShutdownListener {
    override def shutdownCompleted(cause: ShutdownSignalException) =
      subscribers.single.transform(_ - subscriber)
  }
}

Check if prefetch > 0

Check if prefetch > 0


/*
 * Copyright 2017 HM Revenue & Customs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package models.deregister

import org.joda.time.LocalDate
import play.api.libs.json.Json

case class DeRegisterSubscriptionRequest(acknowledgementReference: String,
                                         deregistrationDate: LocalDate,
                                         deregistrationReason: DeregistrationReason,
                                         deregistrationReasonOther: Option[String] = None)

object DeRegisterSubscriptionRequest {
  val DefaultAckReference = "A" * 32

  implicit val formats = Json.format[DeRegisterSubscriptionRequest]
}

/*
 * Copyright 2017 HM Revenue & Customs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package models.deregister

import org.joda.time.LocalDate
import play.api.libs.json.{Json, Writes}

case class DeRegisterSubscriptionRequest(acknowledgementReference: String,
                                         deregistrationDate: LocalDate,
                                         deregistrationReason: DeregistrationReason,
                                         deregistrationReasonOther: Option[String] = None)

object DeRegisterSubscriptionRequest {
  val DefaultAckReference = "A" * 32

  implicit val reads = Json.reads[DeRegisterSubscriptionRequest]

  implicit val writes: Writes[DeRegisterSubscriptionRequest] = {
    import play.api.libs.functional.syntax._
    import play.api.libs.json.Writes._
    import play.api.libs.json._
    Writes[DeRegisterSubscriptionRequest] { ep =>
      (
        (__ \ "acknowledgementReference").write[String] and
          (__ \ "deregistrationDate").write[LocalDate] and
          __.write[DeregistrationReason] and
          (__ \ "deregistrationReasonOther").writeNullable[String]
        ) (unlift(DeRegisterSubscriptionRequest.unapply)).writes(ep)
    }
  }
}

Remove duplicate path in json writes of deRegSub model


package net.ceedubs.ficus

import com.typesafe.config.ConfigFactory
import FicusConfig.{ booleanValueReader, optionValueReader, toFicusConfig }

class FicusConfigSpec extends Spec { def is =
  "A Ficus config should" ^
    "be implicitly converted from a Typesafe config" ! implicitlyConverted ^
    "read a value with a value reader" ! readAValue ^
    "get a value as an option"
    "accept a CongigKey and return the appropriate type" ! acceptAConfigKey

  def implicitlyConverted = {
    val cfg = ConfigFactory.parseString("myValue = true")
    cfg.as[Boolean]("myValue") must beTrue
  }

  def readAValue = {
    val cfg = ConfigFactory.parseString("myValue = true")
    cfg.as[Boolean]("myValue") must beTrue
  }

  def getAsOption = {
    val cfg = ConfigFactory.parseString("myValue = true")
    (cfg.getAs[Boolean]("myValue") must beSome(true)) and (cfg.getAs[Boolean]("nonValue") must beNone)
  }

  def acceptAConfigKey = {
    val cfg = ConfigFactory.parseString("myValue = true")
    val key: ConfigKey[Boolean] = SimpleConfigKey("myValue")
    cfg(key) must beTrue
  }
}

package net.ceedubs.ficus

import com.typesafe.config.ConfigFactory
import FicusConfig.{ booleanValueReader, optionValueReader, toFicusConfig }

class FicusConfigSpec extends Spec { def is =
  "A Ficus config should" ^
    "be implicitly converted from a Typesafe config" ! implicitlyConverted ^
    "read a value with a value reader" ! readAValue ^
    "get an existing value as a Some" + getAsSome ^
    "get a missing value as a None" + getAsNone ^
    "accept a CongigKey and return the appropriate type" ! acceptAConfigKey

  def implicitlyConverted = {
    val cfg = ConfigFactory.parseString("myValue = true")
    cfg.as[Boolean]("myValue") must beTrue
  }

  def readAValue = prop { b: Boolean =>
    val cfg = ConfigFactory.parseString(s"myValue = $b")
    cfg.as[Boolean]("myValue") must beEqualTo(b)
  }

  def getAsSome = prop { b: Boolean =>
    val cfg = ConfigFactory.parseString(s"myValue = $b")
    cfg.getAs[Boolean]("myValue") must beSome(b)
  }

  def getAsNone = {
    val cfg = ConfigFactory.parseString("myValue = true")
    cfg.getAs[Boolean]("nonValue") must beNone
  }

  def acceptAConfigKey = prop { b: Boolean =>
    val cfg = ConfigFactory.parseString(s"myValue = $b")
    val key: ConfigKey[Boolean] = SimpleConfigKey("myValue")
    cfg(key) must beEqualTo(b)
  }
}

Use ScalaCheck in FicusConfig spec

Use ScalaCheck in FicusConfig spec


package streamsend.pillar

import com.datastax.driver.core.Session
import com.datastax.driver.core.querybuilder.QueryBuilder
import scala.collection.JavaConversions
import java.util.Date

object AppliedMigrations {
  def apply(session: Session, registry: MigrationRegistry): AppliedMigrations = {
    val results = session.execute(QueryBuilder.select("authored_at", "description").from("applied_migrations"))
    new AppliedMigrations(JavaConversions.asScalaBuffer(results.all()).map {
      row => registry(MigrationKey(row.getDate("authored_at"), row.getString("description")))
    })
  }
}

class AppliedMigrations(applied: Seq[Migration]) extends Seq[Migration] {
  def length: Int = applied.length

  def apply(index: Int): Migration = applied.apply(index)

  def iterator: Iterator[Migration] = applied.iterator

  def authoredAfter(date: Date): Seq[Migration] = applied.filter(migration => migration.authoredAfter(date))
}

package streamsend.pillar

import com.datastax.driver.core.Session
import com.datastax.driver.core.querybuilder.QueryBuilder
import scala.collection.JavaConversions
import java.util.Date

object AppliedMigrations {
  def apply(session: Session, registry: MigrationRegistry): AppliedMigrations = {
    val results = session.execute(QueryBuilder.select("authored_at", "description").from("applied_migrations"))
    new AppliedMigrations(JavaConversions.asScalaBuffer(results.all()).map {
      row => registry(MigrationKey(row.getDate("authored_at"), row.getString("description")))
    })
  }
}

class AppliedMigrations(applied: Seq[Migration]) {
  def length: Int = applied.length

  def apply(index: Int): Migration = applied.apply(index)

  def iterator: Iterator[Migration] = applied.iterator

  def authoredAfter(date: Date): Seq[Migration] = applied.filter(migration => migration.authoredAfter(date))

  def contains(other: Migration): Boolean = applied.contains(other)
}

Change applied migrations collection so that it no longer behaves like a Seq


package com.michalrus.helper

import android.app.Activity

trait ScalaActivity extends Activity with ViewHelper {

  def find[T](id: Int) = findViewById(id).asInstanceOf[T]

}

package com.michalrus.helper

import android.app.Activity
import scala.concurrent.{ExecutionContext, future}
import ExecutionContext.Implicits.global

trait ScalaActivity extends Activity with ViewHelper {

  def find[T](id: Int) = findViewById(id).asInstanceOf[T]

  def laterOnUiThread(r: Runnable) {
    future {
      runOnUiThread(r)
    }
  }

}

Create a method to run something later on UI thread


package lila.pref

import play.api.mvc.RequestHeader

object RequestPref {

  import Pref.default

  def queryParamOverride(req: RequestHeader)(pref: Pref): Pref =
    queryParam(req, "bg").flatMap(Pref.Bg.fromString.get).fold(pref) { bg =>
      pref.copy(bg = bg)
    }

  def fromRequest(req: RequestHeader): Pref = {

    def paramOrSession(name: String): Option[String] =
      queryParam(req, name) orElse req.session.get(name)

    default.copy(
      bg = paramOrSession("bg").flatMap(Pref.Bg.fromString.get) | default.bg,
      theme = paramOrSession("theme") | default.theme,
      theme3d = req.session.data.getOrElse("theme3d", default.theme3d),
      pieceSet = req.session.data.getOrElse("pieceSet", default.pieceSet),
      pieceSet3d = req.session.data.getOrElse("pieceSet3d", default.pieceSet3d),
      soundSet = req.session.data.getOrElse("soundSet", default.soundSet),
      bgImg = req.session.data.get("bgImg"),
      is3d = req.session.data.get("is3d") has "true"
    )
  }

  private def queryParam(req: RequestHeader, name: String): Option[String] =
    req.queryString.get(name).flatMap(_.headOption).filter { v =>
      v.nonEmpty && v != "auto"
    }
}

package lila.pref

import play.api.mvc.RequestHeader

object RequestPref {

  import Pref.default

  def queryParamOverride(req: RequestHeader)(pref: Pref): Pref =
    queryParam(req, "bg").flatMap(Pref.Bg.fromString.get).fold(pref) { bg =>
      pref.copy(bg = bg)
    }

  def fromRequest(req: RequestHeader): Pref = {

    def paramOrSession(name: String): Option[String] =
      queryParam(req, name) orElse req.session.get(name)

    default.copy(
      bg = paramOrSession("bg").flatMap(Pref.Bg.fromString.get) | default.bg,
      theme = paramOrSession("theme") | default.theme,
      theme3d = paramOrSession("theme3d") | default.theme3d,
      pieceSet = paramOrSession("pieceSet") | default.pieceSet,
      pieceSet3d = paramOrSession("pieceSet3d") | default.pieceSet3d,
      soundSet = paramOrSession("soundSet") | default.soundSet,
      bgImg = paramOrSession("bgImg"),
      is3d = paramOrSession("is3d") has "true"
    )
  }

  private def queryParam(req: RequestHeader, name: String): Option[String] =
    req.queryString.get(name).flatMap(_.headOption).filter { v =>
      v.nonEmpty && v != "auto"
    }
}

Add query param overrides for all UI preferences


import bio._

import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers

package bio.test {

  class FastaReaderSpec extends FlatSpec with ShouldMatchers {
    "FastaReader" should "read from file" in {
      val f = new FastaReader("./test/data/fasta/nt.fa")
      val ids = f.map { res =>
        val (id,tag,dna) = res
        id
        }.toList
      ids.head should equal ("PUT-157a-Arabidopsis_thaliana-1")
    }
    "FastaReader" should "balk on nucleotide N with standard Sequence" in {
      val f = new FastaReader("./test/data/fasta/nt.fa")
      evaluating {
        val ids = f.map { res =>
          val (id,tag,dna) = res
          new DNA.Sequence(id,tag,dna)
          }.toList
        true
      } should produce [IllegalArgumentException]
      true
    }
  }
}

import bio._

import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers

package bio.test {

  class FastaReaderSpec extends FlatSpec with ShouldMatchers {
    "FastaReader" should "read from file" in {
      val f = new FastaReader("./test/data/fasta/nt.fa")
      val ids = f.map { res =>
        val (id,tag,dna) = res
        id
        }.toList
      ids.head should equal ("PUT-157a-Arabidopsis_thaliana-1")
    }
    "FastaReader" should "balk on nucleotide N with standard Sequence" in {
      val f = new FastaReader("./test/data/fasta/nt.fa")
      evaluating {
        val seqs = f.map { res =>
          val (id,tag,dna) = res
          new DNA.Sequence(id,tag,dna)
          }.toList
        true
      } should produce [IllegalArgumentException]
      true
    }
    "FastaReader" should "convert to IUPACSequence" in {
      val f = new FastaReader("./test/data/fasta/nt.fa")
      val seqs = f.map { res =>
        val (id,tag,dna) = res
        new DNA.IUPACSequence(id,tag,dna)
        }.toList
      seqs.head.id.toString should equal ("PUT-157a-Arabidopsis_thaliana-1")
    }
  }
}

Read FASTA into IUPACSequence works fine


package net.matthaynes.ner.controller

import net.matthaynes.ner.service._
import org.scalatra._
import net.liftweb.json._
import net.liftweb.json.Serialization.{write}

class ApiServlet extends ScalatraServlet {

  implicit val formats = new Formats {
    val dateFormat = DefaultFormats.lossless.dateFormat
    override val typeHints = ShortTypeHints(List(classOf[NamedEntity]))
    override val typeHintFieldName = "type"
  }

  def respond(responseBody : Map[String, Any], responseStatus : Int = 200) : String = {
    status(responseStatus)
    contentType = "application/json"
    write(responseBody)
  }

  def respondWithError(message : String, responseStatus : Int = 500) = {
    val responseBody = Map[String, Map[String, Any]]("error" -> Map[String, Any]("status" -> responseStatus, "message" -> message))
    respond(responseBody, responseStatus)
  }

  notFound {
    respondWithError("Not Found", 404)
  }

  methodNotAllowed { allow =>
    response.setHeader("Allow", allow.mkString(", "))
    respondWithError("Method Not Allowed", 405)
  }

  error {
    case e : java.util.NoSuchElementException => respondWithError("Bad Request " + e.getMessage, 400)
  }

}

package net.matthaynes.ner.controller

import net.matthaynes.ner.service._
import org.scalatra._
import net.liftweb.json._
import net.liftweb.json.Serialization.{write}

class ApiServlet extends ScalatraServlet {

  implicit val formats = new Formats {
    val dateFormat = DefaultFormats.lossless.dateFormat
    override val typeHints = ShortTypeHints(List(classOf[NamedEntity]))
    override val typeHintFieldName = "type"
  }

  def respond(responseBody : Map[String, Any], responseStatus : Int = 200) : String = {
    status(responseStatus)
    contentType = "application/json"
    write(responseBody)
  }

  def respondWithError(message : String, responseStatus : Int = 500) = {
    val responseBody = Map[String, Map[String, Any]]("error" -> Map[String, Any]("status" -> responseStatus, "message" -> message))
    respond(responseBody, responseStatus)
  }

  notFound {
    respondWithError("Not Found", 404)
  }

  methodNotAllowed { allow =>
    response.setHeader("Allow", allow.mkString(", "))
    respondWithError("Method Not Allowed", 405)
  }

  error {
    case e : java.util.NoSuchElementException => respondWithError("Bad Request " + e.getMessage, 400)
    case e : _  => respondWithError("Internal Server Error " + e.getMessage, 500)
  }

}

Add some error handling to the API

Add some error handling to the API


import Dependencies._

name := "scaffeine"

organization := "com.github.blemale"

licenses += "Apache 2" -> url("http://www.apache.org/licenses/LICENSE-2.0.txt")

description := "Thin Scala wrapper for Caffeine."

startYear := Some(2016)

homepage := Some(url("https://github.com/blemale/scaffeine"))

scalaVersion := "2.11.8"

libraryDependencies ++=
  Seq(
    Caffeine,
    Java8Compat,
    Jsr305 % "provided",
    Scalactic % "test",
    Scalatest % "test"
  )

scalacOptions ++= Seq("-target:jvm-1.8")

import Dependencies._

name := "scaffeine"

organization := "com.github.blemale"

licenses += "Apache 2" -> url("http://www.apache.org/licenses/LICENSE-2.0.txt")

description := "Thin Scala wrapper for Caffeine."

startYear := Some(2016)

homepage := Some(url("https://github.com/blemale/scaffeine"))

scalaVersion := "2.11.12"

libraryDependencies ++=
  Seq(
    Caffeine,
    Java8Compat,
    Jsr305 % "provided",
    Scalactic % "test",
    Scalatest % "test"
  )

scalacOptions ++= Seq("-target:jvm-1.8")

Upgrade scala to version 2.11.12 in dev

Upgrade scala to version 2.11.12 in dev


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.1.5"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.1",
      "org.scalatest" %% "scalatest" % "2.2.6" % "test",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.1.6"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.1",
      "org.scalatest" %% "scalatest" % "2.2.6" % "test",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

autocommit: Update configuration to record version 0.1.6


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.4"

crossScalaVersions := Seq("2.12.4", "2.11.12", "2.10.6")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

version := "0.1.54"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.4"

crossScalaVersions := Seq("2.12.4", "2.11.12", "2.10.6")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

version := "0.1.55"

autocommit: Update configuration to record version 0.1.55


name := "proxy"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(commonSettings: _*)
  .settings(
    libraryDependencies ++= Seq(
      filters,
      ws,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.1",
      "org.yaml" % "snakeyaml" % "1.17",
      "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.0" % "test"
    )
  )

val credsToUse = Option(System.getenv("ARTIFACTORY_USERNAME")) match {
  case None => Credentials(Path.userHome / ".ivy2" / ".artifactory")
  case _ => Credentials("Artifactory Realm","flow.artifactoryonline.com",System.getenv("ARTIFACTORY_USERNAME"),System.getenv("ARTIFACTORY_PASSWORD"))
}

lazy val commonSettings: Seq[Setting[_]] = Seq(
  name <<= name("proxy-" + _),
  scalacOptions += "-feature",
  sources in (Compile,doc) := Seq.empty,
  publishArtifact in (Compile, packageDoc) := false,
  credentials += credsToUse,
  resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
  resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/"
)
version := "0.0.10"

name := "proxy"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(commonSettings: _*)
  .settings(
    libraryDependencies ++= Seq(
      filters,
      ws,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.1",
      "org.yaml" % "snakeyaml" % "1.17",
      "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.0" % "test"
    )
  )

val credsToUse = Option(System.getenv("ARTIFACTORY_USERNAME")) match {
  case None => Credentials(Path.userHome / ".ivy2" / ".artifactory")
  case _ => Credentials("Artifactory Realm","flow.artifactoryonline.com",System.getenv("ARTIFACTORY_USERNAME"),System.getenv("ARTIFACTORY_PASSWORD"))
}

lazy val commonSettings: Seq[Setting[_]] = Seq(
  name <<= name("proxy-" + _),
  scalacOptions += "-feature",
  sources in (Compile,doc) := Seq.empty,
  publishArtifact in (Compile, packageDoc) := false,
  credentials += credsToUse,
  resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
  resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/"
)
version := "0.0.11"

autocommit: Update configuration to record version 0.0.11


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.6"

version := "0.1.80"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.6.9",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    )
  )

publishTo := {
  val host = "https://flow.jfrog.io/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.6"

version := "0.1.81"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.6.9",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    )
  )

publishTo := {
  val host = "https://flow.jfrog.io/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

autocommit: Update configuration to record version 0.1.81


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.3.18"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.3.19"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

autocommit: Update configuration to record version 0.3.19


addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.0")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.2.0")
addSbtPlugin("com.github.sbt" % "sbt-git" % "2.0.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.12.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.2.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.15")
addSbtPlugin("ohnosequences" % "sbt-github-release" % "0.7.0")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.7")

// https://github.com/ohnosequences/sbt-github-release/issues/28#issuecomment-426086656
libraryDependencies += "com.sun.activation" % "javax.activation" % "1.2.0"

addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.0")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.2.0")
addSbtPlugin("com.github.sbt" % "sbt-git" % "2.0.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.12.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.2.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.15")
addSbtPlugin("ohnosequences" % "sbt-github-release" % "0.7.0")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.9")

// https://github.com/ohnosequences/sbt-github-release/issues/28#issuecomment-426086656
libraryDependencies += "com.sun.activation" % "javax.activation" % "1.2.0"

Update nscplugin, sbt-scala-native, ... to 0.4.9


addSbtPlugin("com.eed3si9n"       % "sbt-unidoc"                    % "0.4.3")
addSbtPlugin("com.geirsson"       % "sbt-ci-release"                % "1.5.3")
addSbtPlugin("com.typesafe"       % "sbt-mima-plugin"               % "0.7.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh"                       % "0.3.7")

val scalaJSVersion =
  Option(System.getenv("SCALAJS_VERSION")).getOrElse("1.0.1")

addSbtPlugin("org.scala-js"       % "sbt-scalajs"                   % scalaJSVersion)
addSbtPlugin("org.portable-scala" % "sbt-crossproject"              % "1.0.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject"      % "1.0.0")
addSbtPlugin("com.47deg"          % "sbt-microsites"                % "0.9.4")
addSbtPlugin("org.scalameta"      % "sbt-scalafmt"                  % "2.3.4")
addSbtPlugin("org.scalameta"      % "sbt-mdoc"                      % "2.2.0")

scalacOptions += "-deprecation"

addSbtPlugin("com.eed3si9n"       % "sbt-unidoc"                    % "0.4.3")
addSbtPlugin("com.geirsson"       % "sbt-ci-release"                % "1.5.3")
addSbtPlugin("com.typesafe"       % "sbt-mima-plugin"               % "0.7.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh"                       % "0.3.7")

val scalaJSVersion =
  Option(System.getenv("SCALAJS_VERSION")).getOrElse("1.1.0")

addSbtPlugin("org.scala-js"       % "sbt-scalajs"                   % scalaJSVersion)
addSbtPlugin("org.portable-scala" % "sbt-crossproject"              % "1.0.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject"      % "1.0.0")
addSbtPlugin("com.47deg"          % "sbt-microsites"                % "0.9.4")
addSbtPlugin("org.scalameta"      % "sbt-scalafmt"                  % "2.3.4")
addSbtPlugin("org.scalameta"      % "sbt-mdoc"                      % "2.2.0")

scalacOptions += "-deprecation"

Update sbt-scalajs, scalajs-compiler to 1.1.0


addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.5.0")
addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.0-RC4")

Add coursier as dependency resolver

Add coursier as dependency resolver

This _should_ speed up the dependency resolution.


libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.10"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.9.34")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.10.0")
addSbtPlugin("com.github.sbt" % "sbt-unidoc" % "0.5.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.9")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.12.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.8")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.10"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.9.34")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.10.0")
addSbtPlugin("com.github.sbt" % "sbt-unidoc" % "0.5.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.9")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.12.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.8")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")

Update sbt-http4s-org to 0.12.1 in series/0.22


// Comment to get more information during initialization
logLevel := Level.Warn

// The Typesafe repository
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

// Use the Play sbt plugin for Play projects
addSbtPlugin("play" % "sbt-plugin" % "2.0-SNAPSHOT")

// The SBT-Idea plugin, https://github.com/mpeltonen/sbt-idea
// ---------------------------------------------------------------
resolvers += "sbt-idea-repo" at "http://mpeltonen.github.com/maven/"

// libraryDependencies += "com.github.mpeltonen" %% "sbt-idea" % "0.10.0"
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.0.0")

// Comment to get more information during initialization
logLevel := Level.Warn

// The Typesafe repository
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

// Use the Play sbt plugin for Play projects
addSbtPlugin("play" % "sbt-plugin" % "2.1-SNAPSHOT")

// The SBT-Idea plugin, https://github.com/mpeltonen/sbt-idea
// ---------------------------------------------------------------
resolvers += "sbt-idea-repo" at "http://mpeltonen.github.com/maven/"

// libraryDependencies += "com.github.mpeltonen" %% "sbt-idea" % "0.10.0"
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.0.0")

Use Play 2.1 unstable (?) branch again

Use Play 2.1 unstable (?) branch again

My OpenID fix isn't included in 2.0.x and 2.0.x doesn't generate source
code JARs.

Use this commit: f9dc390802960045bf6b0b1f249e42f863ad03fd
Committed on: 2012-04-27 03:02:23


import de.flapdoodle.embedmongo.config.MongodConfig
import de.flapdoodle.embedmongo.distribution.Version
import de.flapdoodle.embedmongo.{MongodProcess, MongodExecutable, MongoDBRuntime}
import play.api.{Application, GlobalSettings}

import play.api.Mode
/**
 * @author David Galichet.
 */

object Global extends GlobalSettings {

  override def beforeStart(app: Application) {
    app.mode match {
      case Mode.Dev => startMongo(app)
      case _ => Unit
    }

    super.beforeStart(app)
  }

  lazy val _mongodExe:MongodExecutable ={
    val runtime:MongoDBRuntime = MongoDBRuntime.getDefaultInstance();
    runtime.prepare(new MongodConfig(Version.V2_0, 27017,false));
  }
  lazy val _mongod:MongodProcess={_mongodExe.start()}

  def startMongo(app:Application) {
    _mongod
  }
  override def onStop(app: Application) {
    _mongod.stop()
    _mongodExe.cleanup()
  }
}

import de.flapdoodle.embedmongo.config.MongodConfig
import de.flapdoodle.embedmongo.distribution.Version
import de.flapdoodle.embedmongo.{MongodProcess, MongodExecutable, MongoDBRuntime}
import play.api.{Application, GlobalSettings}

import play.api.Mode
/**
 * @author David Galichet.
 */

object Global extends GlobalSettings {
}

Remove starting embedded mongo from global, the app needs an externally started mongodb


package org.jetbrains.plugins.scala.extensions

import com.intellij.psi.{PsiType, PsiMethod}

/**
 * Pavel Fatin
 */

class PsiMethodExt(repr: PsiMethod) {
  private val AccessorNamePattern =
    """(?-i)(?:get|is|can|could|has|have|to)\p{Lu}.*""".r

  private val MutatorNamePattern =
    """(?-i)(?:do|set|add|remove|insert|delete|aquire|release)(?:\p{Lu}.*)""".r

  def isAccessor: Boolean = {
    hasQueryLikeName && !hasVoidReturnType
  }

  def isMutator: Boolean = {
    hasVoidReturnType || hasMutatorLikeName
  }

  def hasQueryLikeName = repr.getNameIdentifier.getText match {
    case AccessorNamePattern() => true
    case _ => false
  }

  def hasMutatorLikeName = repr.getNameIdentifier.getText match {
    case MutatorNamePattern() => true
    case _ => false
  }

  def hasVoidReturnType = repr.getReturnType() == PsiType.VOID
}

package org.jetbrains.plugins.scala.extensions

import com.intellij.psi.{PsiType, PsiMethod}

/**
 * Pavel Fatin
 */

class PsiMethodExt(repr: PsiMethod) {
  private val AccessorNamePattern =
    """(?-i)(?:get|is|can|could|has|have|to)\p{Lu}.*""".r

  private val MutatorNamePattern =
    """(?-i)(?:do|set|add|remove|insert|delete|aquire|release)(?:\p{Lu}.*)""".r

  def isAccessor: Boolean = {
    hasQueryLikeName && !hasVoidReturnType
  }

  def isMutator: Boolean = {
    hasVoidReturnType || hasMutatorLikeName
  }

  def hasQueryLikeName = repr.getNameIdentifier.getText match {
    case "getInstance" => false // TODO others?
    case AccessorNamePattern() => true
    case _ => false
  }

  def hasMutatorLikeName = repr.getNameIdentifier.getText match {
    case MutatorNamePattern() => true
    case _ => false
  }

  def hasVoidReturnType = repr.getReturnType() == PsiType.VOID
}

Exclude getInstance() from "queryLike" names for Java methods.


package com.github.eerohele.expek

import java.io.{File, StringReader}
import javax.xml.transform.Source
import javax.xml.transform.stream.StreamSource

import net.sf.saxon.s9api._

import scala.xml.Elem

/** A trait that lets you run XSLT transformations. */
trait XsltSupport {
    import utils.NodeConversions._

    val xsltCompiler: XsltCompiler

    /** Functions for converting an XSLT stylesheet into a [[Source]]. */
    object XSLT {
        /** Read a stylesheet from a file. */
        def file(xslt: String): Source = file(new File(xslt))

        /** Read a stylesheet from a file. */
        def file(xslt: File): Source = new StreamSource(xslt)

        /** Read a stylesheet from an [[Elem]]. */
        def elem(elem: Elem): Source = new StreamSource(new StringReader(elem))

        /** Transform an [[Elem]] with the given stylesheet. */
        def transform[T <: XdmValue](stylesheet: Source, elem: Elem): T = {
            val t: Xslt30Transformer = xsltCompiler.compile(stylesheet).load30
            t.applyTemplates(elem).asInstanceOf[T]
        }
    }
}

package com.github.eerohele.expek

import java.io.{File, StringReader}
import javax.xml.transform.Source
import javax.xml.transform.stream.StreamSource

import net.sf.saxon.s9api._

import scala.xml.Elem

/** A trait that lets you run XSLT transformations. */
trait XsltSupport {
    import utils.NodeConversions._

    val xsltCompiler: XsltCompiler

    /** Functions for converting an XSLT stylesheet into a [[Source]]. */
    object XSLT {
        /** Read a stylesheet from a file. */
        def file(xslt: String): Source = file(new File(xslt))

        /** Read a stylesheet from a file. */
        def file(xslt: File): Source = new StreamSource(xslt)

        /** Read a stylesheet from an [[Elem]]. */
        def elem(elem: Elem): Source = new StreamSource(new StringReader(elem))

        /** Transform a [[Source]] with the given stylesheet. */
        def transform[T <: XdmValue](stylesheet: Source, input: Source): T = {
            val t: Xslt30Transformer = xsltCompiler.compile(stylesheet).load30
            t.applyTemplates(input).asInstanceOf[T]
        }

        /** Transform an [[Elem]] with the given stylesheet. */
        def transform[T <: XdmValue](stylesheet: Source, elem: Elem): T = transform(stylesheet, elem)
    }
}

Allow passing a Source to XSLT.transform


package hmda.model.validation

sealed trait ValidationErrorType
case object Syntactical extends ValidationErrorType
case object Validity extends ValidationErrorType
case object Quality extends ValidationErrorType
case object Macro extends ValidationErrorType

// errorID = Loan ID (LAR) or Agency Code + Respondent ID (TS)
trait ValidationError {
  def errorId: String
  def ruleName: String
  def errorType: ValidationErrorType
  def ts: Boolean
  def toCsv: String = s"$errorType, $ruleName, $publicErrorId"
  def publicErrorId = if (ts) "Transmittal Sheet" else errorId
}

case class SyntacticalValidationError(errorId: String, ruleName: String, ts: Boolean) extends ValidationError {
  override def errorType: ValidationErrorType = Syntactical
}
case class ValidityValidationError(errorId: String, ruleName: String, ts: Boolean) extends ValidationError {
  override def errorType: ValidationErrorType = Validity
}
case class QualityValidationError(errorId: String, ruleName: String, ts: Boolean) extends ValidationError {
  override def errorType: ValidationErrorType = Quality
}
case class MacroValidationError(ruleName: String) extends ValidationError {
  override def ts: Boolean = false
  override def errorId: String = ""
  override def errorType: ValidationErrorType = Macro
}
case object EmptyValidationError extends ValidationError {
  override def errorId: String = "empty"
  override def ruleName: String = "empty"
  override def errorType: ValidationErrorType = Macro
  override def ts: Boolean = false
}

package hmda.model.validation

sealed trait ValidationErrorType
case object Syntactical extends ValidationErrorType
case object Validity extends ValidationErrorType
case object Quality extends ValidationErrorType
case object Macro extends ValidationErrorType

// errorID = Loan ID (LAR) or Agency Code + Respondent ID (TS)
trait ValidationError {
  def errorId: String
  def ruleName: String
  def errorType: ValidationErrorType
  def ts: Boolean
  def toCsv: String = s"$errorType, $ruleName, $publicErrorId\n"
  def publicErrorId = if (ts) "Transmittal Sheet" else errorId
}

case class SyntacticalValidationError(errorId: String, ruleName: String, ts: Boolean) extends ValidationError {
  override def errorType: ValidationErrorType = Syntactical
}
case class ValidityValidationError(errorId: String, ruleName: String, ts: Boolean) extends ValidationError {
  override def errorType: ValidationErrorType = Validity
}
case class QualityValidationError(errorId: String, ruleName: String, ts: Boolean) extends ValidationError {
  override def errorType: ValidationErrorType = Quality
}
case class MacroValidationError(ruleName: String) extends ValidationError {
  override def ts: Boolean = false
  override def errorId: String = ""
  override def errorType: ValidationErrorType = Macro
}
case object EmptyValidationError extends ValidationError {
  override def errorId: String = "empty"
  override def ruleName: String = "empty"
  override def errorType: ValidationErrorType = Macro
  override def ts: Boolean = false
}

Fix bug where csv didn't have newlines

Fix bug where csv didn't have newlines


/*
 * Copyright 2015 Sanford Ryza, Uri Laserson, Sean Owen and Joshua Wills
 *
 * See LICENSE file for further information.
 */

package com.cloudera.datascience

object MyApp {
  def main(args: Array[String]) {
    val sc = new SparkContext(new SparkConf().setAppName("My App"))
    println("num lines: " + sc.countLines(args(0)))
  }

  def countLines(sc: SparkContext, path: String): Long = {
    sc.textFile(path).count()
  }
}

/*
 * Copyright 2015 Sanford Ryza, Uri Laserson, Sean Owen and Joshua Wills
 *
 * See LICENSE file for further information.
 */

package com.cloudera.datascience

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext

object MyApp {
  def main(args: Array[String]) {
    val sc = new SparkContext(new SparkConf().setAppName("My App"))
    println("num lines: " + countLines(sc, args(0)))
  }

  def countLines(sc: SparkContext, path: String): Long = {
    sc.textFile(path).count()
  }
}

Make simple spark project code compile

Make simple spark project code compile


package hyperion

import akka.testkit.TestProbe

class MeterAgentAppSpec extends BaseAkkaSpec {
  "Creating the MeterAgentApp" should {
    "result in creating the necessary top-level actors" in {
      new MeterAgentApp(system)
      TestProbe().expectActor("/user/meter-agent")
      TestProbe().expectActor("/user/meter-agent")
    }
  }
}

package hyperion

import akka.testkit.TestProbe

class MeterAgentAppSpec extends BaseAkkaSpec {
  "Creating the MeterAgentApp" should {
    "result in creating the necessary top-level actors" in {
      new MeterAgentApp(system)
      TestProbe().expectActor("/user/meter-agent")
      TestProbe().expectActor("/user/collecting-actor")
    }
  }
}

Test for precense of the right actors

Test for precense of the right actors


import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( buildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"com.android.support" % "appcompat-v7" % "21.0.0",
				"com.android.support" % "cardview-v7" % "21.0.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6",
				"org.scala-lang" % "scala-reflect" % scalaVersion.value
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			scalaVersion := "2.11.4",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			version := "0.2.1-BETA",
			libraryProject in Android := true,
			minSdkVersion in Android := "10",
			targetSdkVersion in Android := "21"
		)
}

import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( buildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"com.android.support" % "appcompat-v7" % "21.0.0",
				"com.android.support" % "cardview-v7" % "21.0.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6",
				"org.scala-lang" % "scala-reflect" % scalaVersion.value
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			scalaVersion := "2.11.4",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			version := "0.2.2-BETA",
			libraryProject in Android := true,
			minSdkVersion in Android := "10",
			targetSdkVersion in Android := "21"
		)
}

Set project version to 0.2.2-BETA

Set project version to 0.2.2-BETA


import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( androidBuildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"com.android.support" % "appcompat-v7" % "21.0.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6",
				"com.jpardogo.materialtabstrip" % "library" % "1.0.5",
				"org.scala-lang" % "scala-reflect" % scalaVersion.value
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			publishArtifact in ( Compile, packageDoc ) := false,
			scalaVersion := "2.11.4",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:existentials",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			// @see https://github.com/pfn/android-sdk-plugin/issues/88
			sourceGenerators in Compile <<= ( sourceGenerators in Compile ) ( generators => Seq( generators.last ) ),
			version := "0.3.2-BETA",
			minSdkVersion in Android := "10",
			platformTarget in Android := "android-21",
			targetSdkVersion in Android := "21"
		)
}

import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( androidBuildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"com.android.support" % "appcompat-v7" % "21.0.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6",
				"com.jpardogo.materialtabstrip" % "library" % "1.0.5",
				"org.scala-lang" % "scala-reflect" % scalaVersion.value
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			publishArtifact in ( Compile, packageDoc ) := false,
			scalaVersion := "2.11.4",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:existentials",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			// @see https://github.com/pfn/android-sdk-plugin/issues/88
			sourceGenerators in Compile <<= ( sourceGenerators in Compile ) ( generators => Seq( generators.last ) ),
			version := "0.3.3-BETA",
			minSdkVersion in Android := "10",
			platformTarget in Android := "android-21",
			targetSdkVersion in Android := "21"
		)
}

Set project version to 0.3.3-BETA

Set project version to 0.3.3-BETA


/*
 * Main plugins
 */

// Build, package and load native libraries
addSbtPlugin("ch.jodersky" % "sbt-jni" % "0.4.2")

/*
 * Utility plugins, can be disabled during plain build
 */

// Generate documentation for all sources
addSbtPlugin("com.eed3si9n" % "sbt-unidoc" % "0.3.3")

// Build website
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.2")

// Integrate website with GitHub pages
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")

// Automate release process
addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.0")

// Usually a global plugin, made explicit to work with release automation
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.0")

// Usually a global plugin, made explicit to work with release automation
addSbtPlugin("me.lessis" % "bintray-sbt" % "0.3.0")

/*
 * Main plugins
 */

resolvers += "jodersky-maven" at "http://dl.bintray.com/jodersky/maven/"

// Build, package and load native libraries
addSbtPlugin("ch.jodersky" % "sbt-jni" % "0.4.3")

/*
 * Utility plugins, can be disabled during plain build
 */

// Generate documentation for all sources
addSbtPlugin("com.eed3si9n" % "sbt-unidoc" % "0.3.3")

// Build website
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.2")

// Integrate website with GitHub pages
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")

// Automate release process
addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.0")

// Usually a global plugin, made explicit to work with release automation
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.0")

// Usually a global plugin, made explicit to work with release automation
addSbtPlugin("me.lessis" % "bintray-sbt" % "0.3.0")

Add bintray resolver and upgrade sbt-jni


// Comment to get more information during initialization
logLevel := Level.Warn

// The Typesafe repository
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

// Use Play's SBT plugin version.
addSbtPlugin("play" % "sbt-plugin" % "2.1-SNAPSHOT")

// The SBT-Idea plugin, https://github.com/mpeltonen/sbt-idea
// ---------------------------------------------------------------
resolvers += "sbt-idea-repo" at "http://mpeltonen.github.com/maven/"

// libraryDependencies += "com.github.mpeltonen" %% "sbt-idea" % "0.10.0"
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.0.0")

// Comment to get more information during initialization
logLevel := Level.Warn

// The Typesafe repository
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

// Use the Play sbt plugin for Play projects
addSbtPlugin("play" % "sbt-plugin" % "2.0-SNAPSHOT")

// The SBT-Idea plugin, https://github.com/mpeltonen/sbt-idea
// ---------------------------------------------------------------
resolvers += "sbt-idea-repo" at "http://mpeltonen.github.com/maven/"

// libraryDependencies += "com.github.mpeltonen" %% "sbt-idea" % "0.10.0"
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.0.0")

Use to Play v. 2.0.1; change to compatible SBT plugin version

Don't use the perhaps unstable Play 2.1 wip branch.


package ch.megard.akka.http.cors.javadsl

import java.util.function.Supplier

import akka.http.javadsl.server.Route
import akka.http.javadsl.server.directives.RouteAdapter
import ch.megard.akka.http.cors.javadsl.settings.CorsSettings
import ch.megard.akka.http.cors.scaladsl

object CorsDirectives {

  def cors(settings: CorsSettings, inner: Supplier[Route]): Route = RouteAdapter {
    // Currently the easiest way to go from Java models to their Scala equivalent is to cast.
    // See https://github.com/akka/akka-http/issues/661 for a potential opening of the JavaMapping API.
    val scalaSettings = settings.asInstanceOf[scaladsl.settings.CorsSettings]
    scaladsl.CorsDirectives.cors(scalaSettings) {
      inner.get() match {
        case ra: RouteAdapter => ra.delegate
      }
    }
  }

}

package ch.megard.akka.http.cors.javadsl

import java.util.function.Supplier

import akka.http.javadsl.server.{RejectionHandler, Route}
import akka.http.javadsl.server.directives.RouteAdapter
import ch.megard.akka.http.cors.javadsl.settings.CorsSettings
import ch.megard.akka.http.cors.scaladsl

object CorsDirectives {

  def cors(settings: CorsSettings, inner: Supplier[Route]): Route = RouteAdapter {
    // Currently the easiest way to go from Java models to their Scala equivalent is to cast.
    // See https://github.com/akka/akka-http/issues/661 for a potential opening of the JavaMapping API.
    val scalaSettings = settings.asInstanceOf[scaladsl.settings.CorsSettings]
    scaladsl.CorsDirectives.cors(scalaSettings) {
      inner.get() match {
        case ra: RouteAdapter => ra.delegate
      }
    }
  }

  def corsRejectionHandler: RejectionHandler =
    new RejectionHandler(scaladsl.CorsDirectives.corsRejectionHandler)
}

Add the corsRejectionHandler to the Java API.


package coursier.cli.install

import caseapp.core.app.CaseApp
import caseapp.core.RemainingArgs
import coursier.install.InstallDir

object List extends CaseApp[ListOptions] {
  def run(options: ListOptions, args: RemainingArgs): Unit = {
    val params = ListParams(options)
    val installDir = InstallDir(params.installPath, new NoopCache)
    val names = installDir.list()
    System.err.print(names.map(_ + System.lineSeparator).mkString)
  }
}

package coursier.cli.install

import caseapp.core.app.CaseApp
import caseapp.core.RemainingArgs
import coursier.install.InstallDir

object List extends CaseApp[ListOptions] {
  def run(options: ListOptions, args: RemainingArgs): Unit = {
    val params = ListParams(options)
    val installDir = InstallDir(params.installPath, new NoopCache)
    val names = installDir.list()
    print(names.map(_ + System.lineSeparator).mkString)
  }
}

Print app list on stdout rather than stderr in list command


package com.signalcollect.triplerush

import com.signalcollect._
import scala.concurrent.Promise

class QueryVertex(id: Int, promise: Promise[List[PatternQuery]], val expectedTickets: Long, initialState: List[PatternQuery] = List()) extends DataFlowVertex(id, initialState) {
  type Signal = PatternQuery
  var receivedTickets: Long = 0
  var complete = true

  def collect(query: PatternQuery) = {
    receivedTickets += query.tickets
    complete &&= query.isComplete
    //println(s"$id tickets: $receivedTickets/$expectedTickets. Total bindings so far: ${state.filter(!_.isFailed).length}.")
    if (!query.isFailed) {
      query :: state
    } else {
      state
    }
  }
  override def scoreSignal = if (expectedTickets == receivedTickets) 1 else 0

  override def afterInitialization(graphEditor: GraphEditor[Any, Any]) {
    //println("Query added: " + id)
  }

  override def doSignal(graphEditor: GraphEditor[Any, Any]) {
    //println(s"$id Result will be submitted. This query is going to do its laundry. Tickets: $receivedTickets/$expectedTickets. Total bindings so far: ${state.filter(!_.isFailed).length}.")
    promise success state
    graphEditor.removeVertex(id)
    //println(s"Query $id returns result: is complete = $complete" )
  }
}

package com.signalcollect.triplerush

import com.signalcollect._
import scala.concurrent.Promise

class QueryVertex(id: Int, promise: Promise[List[PatternQuery]], val expectedTickets: Long, initialState: List[PatternQuery] = List()) extends DataFlowVertex(id, initialState) {
  type Signal = PatternQuery
  var receivedTickets: Long = 0
  var complete = true

  def collect(query: PatternQuery) = {
    receivedTickets += query.tickets
    if (complete && !query.isComplete) {
      println("Query is n")
    }
    complete &&= query.isComplete
    //println(s"$id tickets: $receivedTickets/$expectedTickets. Total bindings so far: ${state.filter(!_.isFailed).length}.")
    if (!query.isFailed) {
      query :: state
    } else {
      state
    }
  }
  override def scoreSignal = if (expectedTickets == receivedTickets) 1 else 0

  override def afterInitialization(graphEditor: GraphEditor[Any, Any]) {
    //println("Query added: " + id)
  }

  override def doSignal(graphEditor: GraphEditor[Any, Any]) {
    //println(s"$id Result will be submitted. This query is going to do its laundry. Tickets: $receivedTickets/$expectedTickets. Total bindings so far: ${state.filter(!_.isFailed).length}.")
    promise success state
    graphEditor.removeVertex(id)
    //println(s"Query $id returns result: is complete = $complete" )
  }
}

Print if query is not complete.

Print if query is not complete.


/*
 * Copyright 2014-2020 http4s.org
 *
 * SPDX-License-Identifier: Apache-2.0
 */

package org.http4s.blaze

import java.nio.ByteBuffer

import org.http4s.blaze.pipeline.LeafBuilder

import scala.concurrent.Future

package object channel {
  type SocketPipelineBuilder = SocketConnection => Future[LeafBuilder[ByteBuffer]]

  /** Default number of threads used to make a new
    * [[org.http4s.blaze.channel.nio1.SelectorLoopPool]] if not specified
    */
  val DefaultPoolSize: Int =
    math.max(4, Runtime.getRuntime.availableProcessors() + 1)

  /** Default max number of connections that can be active at any time.
    * A negative number means that there is no max.
    */
  val DefaultMaxConnections: Int = -1
}

/*
 * Copyright 2014-2020 http4s.org
 *
 * SPDX-License-Identifier: Apache-2.0
 */

package org.http4s.blaze

import java.nio.ByteBuffer

import org.http4s.blaze.pipeline.LeafBuilder

import scala.concurrent.Future

package object channel {
  type SocketPipelineBuilder = SocketConnection => Future[LeafBuilder[ByteBuffer]]

  /** Default number of threads used to make a new
    * [[org.http4s.blaze.channel.nio1.SelectorLoopPool]] if not specified
    */
  val DefaultPoolSize: Int =
    math.max(4, Runtime.getRuntime.availableProcessors() + 1)

  /** Default max number of connections that can be active at any time.
    * A negative number means that there is no max.
    */
  val DefaultMaxConnections: Int = 512
}

Set default max connections to 512

Set default max connections to 512


package beyond.engine.javascript.lib

import org.mozilla.javascript.ScriptableObject
import org.mozilla.javascript.annotations.{JSConstructor, JSGetter}
import play.api.mvc.Request

// FIXME: Add more members.
// The type of param must be AnyRef.
// Otherwise, Rhino throws an exception when checking parameter types.
@JSConstructor
class ScriptableRequest[A](param: AnyRef) extends ScriptableObject {
  def this() = this(null)

  private val request: Request[A] = param.asInstanceOf[Request[A]]

  override def getClassName: String = "Request"

  @JSGetter
  def getMethod: String = request.method

  @JSGetter
  def getUri: String = request.uri

  // FIXME: Wrap maps as scriptables.
  // FIXME: toSimpleMap ignores multiple values.
  @JSGetter
  def getHeaders: Map[String, String] = request.headers.toSimpleMap
}

package beyond.engine.javascript.lib

import org.mozilla.javascript.ScriptableObject
import org.mozilla.javascript.annotations.JSConstructor
import org.mozilla.javascript.annotations.JSGetter
import play.api.mvc.Request

// FIXME: Add more members.
// The type of param must be AnyRef.
// Otherwise, Rhino throws an exception when checking parameter types.
class ScriptableRequest[A] @JSConstructor()(param: AnyRef) extends ScriptableObject {
  def this() = this(null)

  private val request: Request[A] = param.asInstanceOf[Request[A]]

  override def getClassName: String = "Request"

  @JSGetter
  def getMethod: String = request.method

  @JSGetter
  def getUri: String = request.uri

  // FIXME: Wrap maps as scriptables.
  // FIXME: toSimpleMap ignores multiple values.
  @JSGetter
  def getHeaders: Map[String, String] = request.headers.toSimpleMap
}

Use the Scala constructor annotation syntax.


package scala.tools.partest

import java.io.File

trait StubErrorMessageTest extends StoreReporterDirectTest {
  // Stub to feed to partest, unused
  def code = throw new Error("Use `userCode` instead of `code`.")

  def compileCode(code: String) = {
    val classpath = List(sys.props("partest.lib"), testOutput.path)
      .mkString(sys.props("path.separator"))
    compileString(newCompiler("-cp", classpath, "-d", testOutput.path))(code)
  }

  def removeClasses(inPackage: String, classNames: Seq[String]): Unit = {
    val pkg = new File(testOutput.path, inPackage)
    classNames.foreach { className =>
      val classFile = new File(pkg, s"$className.class")
      assert(classFile.exists)
      assert(classFile.delete())
    }
  }

  def removeFromClasspath(): Unit
  def codeA: String
  def codeB: String
  def userCode: String

  def show(): Unit = {
    compileCode(codeA)
    assert(filteredInfos.isEmpty, filteredInfos)

    compileCode(codeB)
    assert(filteredInfos.isEmpty, filteredInfos)
    removeFromClasspath()

    compileCode(userCode)
    import scala.reflect.internal.util.Position
    filteredInfos.map { report =>
      print(if (report.severity == storeReporter.ERROR) "error: " else "")
      println(Position.formatMessage(report.pos, report.msg, true))
    }
  }
}

package scala.tools.partest

trait StubErrorMessageTest extends StoreReporterDirectTest {
  // Stub to feed to partest, unused
  def code = throw new Error("Use `userCode` instead of `code`.")

  val classpath = List(sys.props("partest.lib"), testOutput.path)
    .mkString(sys.props("path.separator"))

  def compileCode(codes: String*) = {
    val global = newCompiler("-cp", classpath, "-d", testOutput.path)
    val sourceFiles = newSources(codes: _*)
    withRun(global)(_ compileSources sourceFiles)
  }

  def removeClasses(inPackage: String, classNames: Seq[String]): Unit = {
    val pkg = new File(testOutput.path, inPackage)
    classNames.foreach { className =>
      val classFile = new File(pkg, s"$className.class")
      assert(classFile.exists)
      assert(classFile.delete())
    }
  }

  def removeFromClasspath(): Unit
  def codeA: String
  def codeB: String
  def userCode: String
  def extraUserCode: String = ""

  def show(): Unit = {
    compileCode(codeA)
    assert(filteredInfos.isEmpty, filteredInfos)

    compileCode(codeB)
    assert(filteredInfos.isEmpty, filteredInfos)
    removeFromClasspath()

    if (extraUserCode == "") compileCode(userCode)
    else compileCode(userCode, extraUserCode)
    import scala.reflect.internal.util.Position
    filteredInfos.map { report =>
      print(if (report.severity == storeReporter.ERROR) "error: " else "")
      println(Position.formatMessage(report.pos, report.msg, true))
    }
  }
}

Allow several user codes in stub error test suite


package controllers.disposal_of_vehicle

import helpers.webbrowser.TestGlobal
import helpers.{UnitSpec, WithApplication}
import pages.disposal_of_vehicle._
import play.api.test.{FakeApplication, FakeRequest}
import play.api.test.Helpers._

final class BeforeYouStartUnitSpec extends UnitSpec {
  "present" should {
    "display the page" in new WithApplication {
      val result = beforeYouStart.present(FakeRequest())
      status(result) should equal(OK)
    }

    "display expected progress bar" in new WithApplication {
      val result = beforeYouStart.present(FakeRequest())
      contentAsString(result) should include("Step 1 of 6")
    }

    "display prototype message when config set to true" in new WithApplication {
      val result = beforeYouStart.present(FakeRequest())
      contentAsString(result) should include("""<div class="prototype">""")
    }
  }

  "submit" should {
    "redirect to next page after the button is clicked" in new WithApplication {
      val result = beforeYouStart.submit(FakeRequest())
      whenReady(result) {
        r => r.header.headers.get(LOCATION) should equal(Some(SetupTradeDetailsPage.address))
      }
    }
  }

  private val beforeYouStart = injector.getInstance(classOf[BeforeYouStart])
}

package controllers.disposal_of_vehicle

import common.ClientSideSessionFactory
import helpers.webbrowser.TestGlobal
import helpers.{UnitSpec, WithApplication}
import pages.disposal_of_vehicle._
import play.api.test.{FakeApplication, FakeRequest}
import play.api.test.Helpers._
import utils.helpers.Config
import org.mockito.Mockito._

final class BeforeYouStartUnitSpec extends UnitSpec {
  "present" should {
    "display the page" in new WithApplication {
      val result = beforeYouStart.present(FakeRequest())
      status(result) should equal(OK)
    }

    "display expected progress bar" in new WithApplication {
      val result = beforeYouStart.present(FakeRequest())
      contentAsString(result) should include("Step 1 of 6")
    }

    "display prototype message when config set to true" in new WithApplication {
      val result = beforeYouStart.present(FakeRequest())
      contentAsString(result) should include("""
""")
    }

    "not display prototype message when config set to false" in new WithApplication {
      val request = FakeRequest()
      implicit val clientSideSessionFactory = injector.getInstance(classOf[ClientSideSessionFactory])
      implicit val config: Config = mock[Config]
      when(config.isPrototypeBannerVisible).thenReturn(false)
      val beforeYouStartPrototypeNotVisible = new BeforeYouStart()

      val result = beforeYouStartPrototypeNotVisible.present(request)
      contentAsString(result) should not include """
"""
    }
  }

  "submit" should {
    "redirect to next page after the button is clicked" in new WithApplication {
      val result = beforeYouStart.submit(FakeRequest())
      whenReady(result) {
        r => r.header.headers.get(LOCATION) should equal(Some(SetupTradeDetailsPage.address))
      }
    }
  }

  private val beforeYouStart = injector.getInstance(classOf[BeforeYouStart])
}

Test for display prototype and progress bar

Former-commit-id: 4311a9d97a744ca6ea7e40238f7cd1c9e81d0a63


package controllers.disposal_of_vehicle

import helpers.common.CookieHelper
import play.api.test.FakeRequest
import play.api.test.Helpers._
import helpers.disposal_of_vehicle.CookieFactoryForUnitSpecs
import helpers.UnitSpec
import helpers.WithApplication
import pages.disposal_of_vehicle.DisposeFailurePage
import CookieHelper._
import scala.Some
import play.api.Play

final class DisposeFailureUnitSpec extends UnitSpec {
  "present" should {
    "display the page" in new WithApplication {
      val request = FakeRequest().
        withCookies(CookieFactoryForUnitSpecs.traderDetailsModel()).
        withCookies(CookieFactoryForUnitSpecs.vehicleDetailsModel()).
        withCookies(CookieFactoryForUnitSpecs.disposeFormModel()).
        withCookies(CookieFactoryForUnitSpecs.disposeTransactionId())
      val result = disposeFailure.present(request)
      whenReady(result) {
        r => r.header.status should equal(OK)
      }
    }
  }

  private val disposeFailure = injector.getInstance(classOf[DisposeFailure])
}

package controllers.disposal_of_vehicle

import helpers.common.CookieHelper
import play.api.test.FakeRequest
import play.api.test.Helpers._
import helpers.disposal_of_vehicle.CookieFactoryForUnitSpecs
import helpers.UnitSpec
import helpers.WithApplication
import pages.disposal_of_vehicle.DisposeFailurePage
import CookieHelper._
import scala.Some
import play.api.Play

final class DisposeFailureUnitSpec extends UnitSpec {
  "present" should {
    "display the page" in new WithApplication {
      whenReady(present) {
        r => r.header.status should equal(OK)
      }
    }

    "not display progress bar" in new WithApplication {
      contentAsString(present) should not include "Step "
    }

    "display prototype message when config set to true" in new WithApplication {
      contentAsString(present) should include("""<div class="prototype">""")
    }
  }

  private lazy val present = {
    val disposeFailure = injector.getInstance(classOf[DisposeFailure])
    val request = FakeRequest().
      withCookies(CookieFactoryForUnitSpecs.traderDetailsModel()).
      withCookies(CookieFactoryForUnitSpecs.vehicleDetailsModel()).
      withCookies(CookieFactoryForUnitSpecs.disposeFormModel()).
      withCookies(CookieFactoryForUnitSpecs.disposeTransactionId())
    disposeFailure.present(request)
  }
}

Test for display prototype but not progress bar

Former-commit-id: d3940f0e6b294ab0340ac9f0f59a7504dc2c9479


package quotidian.web.controller

import com.google.appengine.api.datastore.{Key,KeyFactory}
import com.google.appengine.api.labs.taskqueue.{Queue,QueueFactory,TaskOptions}
import java.io.Serializable
import quotidian.Config
import quotidian.model.Quote
import quotidian.persistence.datastore.DatastorePersister
import quotidian.search.DatastoreDirectory

trait DatastoreController {
	protected val persister = DatastoreController.persister
	protected val directory = DatastoreController.directory
	protected val MaxPerPage = 10
}

private object DatastoreController {
	private val persister = DatastorePersister
	private val directory = new DatastoreDirectory
}

class DatastoreQuoteController extends QuoteController with DatastoreController {
	def enqueue(id:Serializable):Unit = {
		val handle = QueueFactory.getQueue(Config.IndexQuoteQueue).add(TaskOptions.Builder.url("/task/index-quote")
			.method(TaskOptions.Method.POST).param(Quote.Id,KeyFactory.keyToString(id.asInstanceOf[Key])))
		info(String.format("Indexing job queued in %s with id %s",handle.getQueueName,handle.getName))
	}
}
class DatastoreSearchController extends SearchController with DatastoreController

package quotidian.web.controller

import com.google.appengine.api.datastore.{Key,KeyFactory}
import com.google.appengine.api.labs.taskqueue.{Queue,QueueFactory,TaskOptions}
import java.io.Serializable
import quotidian.Config
import quotidian.model.Quote
import quotidian.persistence.datastore.DatastorePersister
import quotidian.search.DatastoreDirectory

trait DatastoreController {
	protected val persister = DatastoreController.persister
	protected val directory = DatastoreController.directory
	protected lazy val MaxPerPage = Config.MaxPerPage
}

private object DatastoreController {
	private val persister = DatastorePersister
	private val directory = new DatastoreDirectory
}

class DatastoreQuoteController extends QuoteController with DatastoreController {
	def enqueue(id:Serializable):Unit = {
		val handle = QueueFactory.getQueue(Config.IndexQuoteQueue).add(TaskOptions.Builder.url("/task/index-quote")
			.method(TaskOptions.Method.POST).param(Quote.Id,KeyFactory.keyToString(id.asInstanceOf[Key])))
		info(String.format("Indexing job queued in %s with id %s",handle.getQueueName,handle.getName))
	}
}
class DatastoreSearchController extends SearchController with DatastoreController

Make MaxPerPage lazy so it doesn't evaluate to 0


name := "debiki-tck-dao"

organization := "com.debiki"

version := "0.0.2-SNAPSHOT"

scalaVersion := "2.8.1"

libraryDependencies ++= Seq(
  "net.liftweb" %% "lift-common" % "2.2",
  "net.liftweb" %% "lift-util" % "2.2",
  "junit" % "junit" % "4.7",
  "org.scala-tools.testing" %% "specs" % "1.6.6"
)

// vim: fdm=marker et ts=2 sw=2 tw=80 fo=tcqwn list

name := "debiki-tck-dao"

organization := "com.debiki"

version := "0.0.2-SNAPSHOT"

scalaVersion := "2.9.1"

libraryDependencies ++= Seq(
  "net.liftweb" %% "lift-common" % "2.4-M5",
  "net.liftweb" %% "lift-util" % "2.4-M5",
  "junit" % "junit" % "4.7",
  "org.scala-tools.testing" %% "specs" % "1.6.9"
)

// vim: fdm=marker et ts=2 sw=2 tw=80 fo=tcqwn list

Upgrade to Scala 2.9.1 and Lift-Web 2.4-M5

From Scala 2.8.1 and Lift-Web 2.2.