package eu.timepit.refined

import _root_.cats.implicits._
import _root_.cats.Show
import _root_.cats.kernel.Eq
import eu.timepit.refined.api.RefType

package object cats {

  /**
   * `Eq` instance for refined types that delegates to the `Eq`
   * instance of the base type.
   */
  implicit def refTypeEq[F[_, _], T: Eq, P](implicit rt: RefType[F]): Eq[F[T, P]] =
    Eq[T].contramap(rt.unwrap)

  /**
   * `Show` instance for refined types that delegates to the `Show`
   * instance of the base type.
   */
  implicit def refTypeShow[F[_, _], T: Show, P](implicit rt: RefType[F]): Show[F[T, P]] =
    Show[T].contramap(rt.unwrap)
}

package eu.timepit.refined

import _root_.cats.Show
import _root_.cats.instances.eq._
import _root_.cats.kernel.Eq
import _root_.cats.syntax.contravariant._
import eu.timepit.refined.api.RefType

package object cats {

  /**
   * `Eq` instance for refined types that delegates to the `Eq`
   * instance of the base type.
   */
  implicit def refTypeEq[F[_, _], T: Eq, P](implicit rt: RefType[F]): Eq[F[T, P]] =
    Eq[T].contramap(rt.unwrap)

  /**
   * `Show` instance for refined types that delegates to the `Show`
   * instance of the base type.
   */
  implicit def refTypeShow[F[_, _], T: Show, P](implicit rt: RefType[F]): Show[F[T, P]] =
    Show[T].contramap(rt.unwrap)
}

Use fine grained imports and fix style error


object Solution {
  import java.math.BigInteger

  // This code came from
  // http://stackoverflow.com/questions/18828377/biginteger-count-the-number-of-decimal-digits-in-a-scalable-method
  def log10(bigNumber: BigInteger): Int = {
    var digits = 0
    var huge = bigNumber
    var bits = huge.bitLength()
    // Serious reductions.
    while (bits > 4) {
      // 4 > log[2](10) so we should not reduce it too far.
      val reduce = bits / 4;
      // Divide by 10^reduce
      huge = huge.divide(BigInteger.TEN.pow(reduce));
      // Removed that many decimal digits.
      digits += reduce;
      // Recalculate bitLength
      bits = huge.bitLength();
    }
    // Now 4 bits or less - add 1 if necessary.
    if ( huge.intValue() > 9 ) {
      digits += 1;
    }
    return digits;
  }

  def main(args: Array[String]) {
    val n = readLine.toInt
    var (num, den) = (BigInt(1393), BigInt(185))
    for (i <- 8 to n) {
      val nc = log10(num.bigInteger)
      val dc = log10(den.bigInteger)
      if (nc - dc > 0) println(i)
      num = num + 2 * den
      den = num - den
    }
  }
}

object Solution {
  import java.math.BigInteger

  // This code came from
  // http://stackoverflow.com/questions/18828377/biginteger-count-the-number-of-decimal-digits-in-a-scalable-method
  def log10(bigNumber: BigInteger): Int = {
    var digits = 0
    var huge = bigNumber
    var bits = huge.bitLength()
    // Serious reductions.
    while (bits > 4) {
      // 4 > log[2](10) so we should not reduce it too far.
      val reduce = bits / 4;
      // Divide by 10^reduce
      huge = huge.divide(BigInteger.TEN.pow(reduce));
      // Removed that many decimal digits.
      digits += reduce;
      // Recalculate bitLength
      bits = huge.bitLength();
    }
    // Now 4 bits or less - add 1 if necessary.
    if ( huge.intValue() > 9 ) {
      digits += 1;
    }
    return digits;
  }

  def main(args: Array[String]) {
    val n = readLine.toInt
    var (num, den) = (BigInt(1393), BigInt(985))
    for (i <- 8 to n) {
      val nc = log10(num.bigInteger)
      val dc = log10(den.bigInteger)
      if (nc - dc > 0) println(i)
      num = num + 2 * den
      den = num - den
    }
  }
}

Update solution to project euler 57. 185 -> 985. It's a typo.


name := "qdb-spark-connector"
version := "1.0.0-SNAPSHOT"

resolvers += "QuasarDB Maven Repository" at "https://maven.quasardb.net/"

spName := "quasardb/spark-connector"
scalaVersion := "2.11.7"
crossScalaVersions := Seq("2.10.5", "2.11.7")

sparkVersion := "1.5.2"
sparkComponents ++= Seq("streaming", "sql")

organization := "net.quasardb"
organizationName := "QuasarDB"
organizationHomepage := Some(url("https://www.quasardb.net"))

libraryDependencies ++= Seq(
  "org.scalatest" %% "scalatest" % "2.2.4" % "test",
  "com.novocode" % "junit-interface" % "0.9" % "test"
)

name := "qdb-spark-connector"
version := "1.0.0-SNAPSHOT"

resolvers += "QuasarDB Maven Repository" at "https://maven.quasardb.net/"

spName := "quasardb/spark-connector"
scalaVersion := "2.11.7"
crossScalaVersions := Seq("2.10.5", "2.11.7")

sparkVersion := "1.5.2"
sparkComponents ++= Seq("streaming", "sql")

organization := "net.quasardb"
organizationName := "QuasarDB"
organizationHomepage := Some(url("https://www.quasardb.net"))

libraryDependencies ++= Seq(
  "net.quasardb" % "qdb" % "2.0.0",
  "org.scalatest" %% "scalatest" % "3.0.4" % "test",
  "com.novocode" % "junit-interface" % "0.9" % "test"
)

Add qdb dependency from qdb private maven


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.2.3"

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.2.4"

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.2.4


name := "beyond"

version := "1.0-SNAPSHOT"

libraryDependencies ++= Seq(
  jdbc,
  anorm,
  cache,
  "com.typesafe.scala-logging" %% "scala-logging-slf4j" % "2.1.2",
  "org.apache.curator" % "curator-recipes" % "2.4.2",
  "org.apache.zookeeper" % "zookeeper" % "3.4.6",
  "org.mozilla" % "rhino" % "1.7R4",
  "org.reactivemongo" %% "play2-reactivemongo" % "0.10.2",
  "org.reactivemongo" %% "reactivemongo" % "0.10.0"
).map(_.exclude("org.slf4j", "slf4j-log4j12"))

play.Project.playScalaSettings

org.scalastyle.sbt.ScalastylePlugin.Settings

scalariformSettings

name := "beyond"

version := "1.0-SNAPSHOT"

libraryDependencies ++= Seq(
  jdbc,
  anorm,
  cache,
  "com.typesafe.scala-logging" %% "scala-logging-slf4j" % "2.1.2",
  "org.apache.curator" % "curator-recipes" % "2.4.2",
  "org.apache.zookeeper" % "zookeeper" % "3.4.6",
  "org.mozilla" % "rhino" % "1.7R4",
  "org.reactivemongo" %% "play2-reactivemongo" % "0.10.2",
  "org.reactivemongo" %% "reactivemongo" % "0.10.0"
).map(_.exclude("org.slf4j", "slf4j-log4j12"))

val toolsJar = if (System.getProperty("os.name") != "Mac OS X") {
  Seq(Attributed.blank(file(System.getProperty("java.home").dropRight(3) + "lib/tools.jar")))
} else {
  Nil
}

// adding the tools.jar to the unmanaged-jars seq
unmanagedJars in Compile ~= (toolsJar ++ _)

play.Project.playScalaSettings

org.scalastyle.sbt.ScalastylePlugin.Settings

scalariformSettings

Add tools.jar to classpath only on Windows and Linux.

Mac OS X bundles tools.jar with classes.jar so there is no need to add
tools.jar. But on Windows and Linux, tools.jar is not bundled in rt.jar, so
tools.jar must be added to classpath separately.

See http://stackoverflow.com/questions/12409847/how-to-add-tools-jar-as-a-dynamic-dependency-in-sbt-is-it-possible


name := "apibuilder-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.3"

crossScalaVersions := Seq("2.12.3", "2.11.11")

version := "0.1.7"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.6.6",
      "org.scalatest" %% "scalatest" % "3.0.4" % 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")
  }
}

name := "apibuilder-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.3"

crossScalaVersions := Seq("2.12.3", "2.11.11")

version := "0.1.8"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.6.6",
      "org.scalatest" %% "scalatest" % "3.0.4" % 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.8


//
// Project metadata
//

name := "tempgres-client"

organization := "dk.cwconsult"

version := "1.0"

//
// sbt-pgp settings
//

useGpg := true

//
// This is a Java-only project, so we don't need the scala
// library nor the artifact name mangling.
//

crossPaths := false

autoScalaLibrary := false

//
// Compiler settings
//

javacOptions ++= Seq("-source", "1.7")

//
// Project metadata
//

name := "tempgres-client"

organization := "dk.cwconsult"

version := "1.1-SNAPSHOT"

//
// sbt-pgp settings
//

useGpg := true

//
// This is a Java-only project, so we don't need the scala
// library nor the artifact name mangling.
//

crossPaths := false

autoScalaLibrary := false

//
// Compiler settings
//

javacOptions ++= Seq("-source", "1.7")

Bump version to 1.1-SNAPSHOT for next development cycle


// Copyright © 2013, Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package fi.jumi.sbt

import sbt._
import sbt.Keys._
import fi.jumi.launcher.JumiBootstrap

object SbtJumiPlugin extends Plugin {

  val jumiTest = TaskKey[Unit]("jumi-test", "Run tests using Jumi")

  override val settings = Seq(
    jumiTest <<= (fullClasspath in Test) map jumiTestTask dependsOn (compile in Test)
  )

  def jumiTestTask(testClasspath: Classpath) {
    val bootstrap = new JumiBootstrap()
    bootstrap.suite.
      setClassPath(testClasspath map (_.data.toPath): _*).
      addJvmOptions("-ea"). // TODO: parameterize
      setIncludedTestsPattern("glob:**Test.class") // TODO: parameterize
    bootstrap.
      //enableDebugMode().
      runSuite() // TODO: make fail without throwing the exception from here
  }
}

// Copyright © 2013, Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package fi.jumi.sbt

import sbt._
import sbt.Keys._
import fi.jumi.launcher.JumiBootstrap

object SbtJumiPlugin extends Plugin {

  val jumiTest = TaskKey[Unit]("jumi-test", "Run tests using Jumi")

  override val settings = Seq(
    jumiTest <<= (fullClasspath in Test) map jumiTestTask dependsOn (compile in Test)
  )

  def jumiTestTask(testClasspath: Classpath) {
    val bootstrap = new JumiBootstrap()
    bootstrap.suite.
      setClassPath(testClasspath map (_.data.toPath): _*).
      addJvmOptions("-ea"). // TODO: parameterize
      setIncludedTestsPattern("glob:**Test.class") // TODO: parameterize
    try {
      bootstrap.runSuite()
    } catch {
      case e: AssertionError => throw new TestsFailedException
    }
  }
}

Hide the failure message's stack trace using sbt.FeedbackProvidedException


package sbt

import scala.annotation.implicitNotFound

object Remove {
  @implicitNotFound(msg = "No implicit for Remove.Value[${A}, ${B}] found,\n  so ${B} cannot be removed from ${A}")
  trait Value[A, B] extends Any {
    def removeValue(a: A, b: B): A
  }
  @implicitNotFound(msg = "No implicit for Remove.Values[${A}, ${B}] found,\n  so ${B} cannot be removed from ${A}")
  trait Values[A, -B] extends Any {
    def removeValues(a: A, b: B): A
  }
  sealed trait Sequence[A, -B, T] extends Value[A, T] with Values[A, B]

  implicit def removeSeq[T, V <: T] = new Sequence[Seq[T], Seq[V], V] {
    def removeValue(a: Seq[T], b: V): Seq[T] = a filterNot b.==
    def removeValues(a: Seq[T], b: Seq[V]): Seq[T] = a diff b
  }
}

package sbt

import scala.annotation.implicitNotFound

object Remove {
  @implicitNotFound(msg = "No implicit for Remove.Value[${A}, ${B}] found,\n  so ${B} cannot be removed from ${A}")
  trait Value[A, B] extends Any {
    def removeValue(a: A, b: B): A
  }
  @implicitNotFound(msg = "No implicit for Remove.Values[${A}, ${B}] found,\n  so ${B} cannot be removed from ${A}")
  trait Values[A, -B] extends Any {
    def removeValues(a: A, b: B): A
  }
  sealed trait Sequence[A, -B, T] extends Value[A, T] with Values[A, B]

  implicit def removeSeq[T, V <: T]: Sequence[Seq[T], Seq[V], V] = new Sequence[Seq[T], Seq[V], V] {
    def removeValue(a: Seq[T], b: V): Seq[T] = a filterNot b.==
    def removeValues(a: Seq[T], b: Seq[V]): Seq[T] = a diff b
  }
}

Add explicit return type for implicit removeSeq.


package io.scalac.amqp

case class Delivery(/** Delivered message. */
                    message: Message,

                    /** Delivery tag. */
                    deliveryTag: String,

                    /** The exchange used for the current operation. */
                    exchange: String,

                    /** The associated routing key. */
                    routingKey: String,

                    /** This is a hint as to whether this message may have been delivered before
                      * (but not acknowledged). If the flag is not set, the message definitely has
                      * not been delivered before. If it is set, it may have been delivered before. */
                    redeliver: Boolean)

package io.scalac.amqp

case class Delivery(/** Delivered message. */
                    message: Message,

                    /** Delivery tag. */
                    deliveryTag: Long,

                    /** The exchange used for the current operation. */
                    exchange: String,

                    /** The associated routing key. */
                    routingKey: String,

                    /** This is a hint as to whether this message may have been delivered before
                      * (but not acknowledged). If the flag is not set, the message definitely has
                      * not been delivered before. If it is set, it may have been delivered before. */
                    redeliver: Boolean)

Change type of deliveryTag from String to Long


package org.orbeon.oxf.util

import java.{util => ju}

import org.orbeon.oxf.externalcontext.ExternalContext.Request

object URLRewriterUtils {
  // TODO: placeholder, does it matter for Scala.js?
  def isResourcesVersioned = false

  def rewriteResourceURL(
    request      : Request,
    urlString    : String,
    pathMatchers : ju.List[PathMatcher],
    rewriteMode  : Int
  ): String = {
    println(s"xxx URLRewriterUtils.rewriteResourceURL called for $urlString")
    ???
  }

  def rewriteServiceURL(
    request     : Request,
    urlString   : String,
    rewriteMode : Int
  ): String = {
    println(s"xxx URLRewriterUtils.rewriteServiceURL called for $urlString")
    if (PathUtils.urlHasProtocol(urlString))
      urlString
    else
      ???
  }

  def getPathMatchers: ju.List[PathMatcher] = {
    println(s"xxx URLRewriterUtils.getPathMatchers called")
    ???
  }
}

package org.orbeon.oxf.util

import java.{util => ju}

import org.orbeon.oxf.externalcontext.ExternalContext.Request

object URLRewriterUtils {

  // TODO: placeholder, does it matter for Scala.js?
  def isResourcesVersioned = false

  def rewriteResourceURL(
    request      : Request,
    urlString    : String,
    pathMatchers : ju.List[PathMatcher],
    rewriteMode  : Int
  ): String = {
    println(s"xxx URLRewriterUtils.rewriteResourceURL called for $urlString")
    ???
  }

  def rewriteServiceURL(
    request     : Request,
    urlString   : String,
    rewriteMode : Int
  ): String = {
    println(s"xxx URLRewriterUtils.rewriteServiceURL called for $urlString")
    if (PathUtils.urlHasProtocol(urlString))
      urlString
    else
      ???
  }

  // Used by `rewriteResourceURL` for `XFormsOutputControl`.
  // Q: Does anything make sense there?
  def getPathMatchers: ju.List[PathMatcher] =
    ju.Collections.emptyList[PathMatcher]
}

Add missing implementation and comment

Add missing implementation and comment


package monocle

import monocle.function.SafeCast._
import monocle.syntax.prism._
import org.specs2.scalaz.Spec

class SafeCastExample extends Spec {

  "safeCast creates a Prism from Int to Char" in {
    safeCast[Int, Char].getOption(65)   shouldEqual Some('A')
    safeCast[Int, Char].reverseGet('a') shouldEqual 97

    // with some syntax sugar
    (65 <-? safeCast[Int, Char] getOption) shouldEqual Some('A')
  }

  "safeCast creates a Prism from String to Int" in {
    safeCast[String, Int].getOption("352") shouldEqual Some(352)
    safeCast[String, Int].reverseGet(8921) shouldEqual "8921"
    safeCast[String, Int].getOption("")    shouldEqual None
  }

  "safeCast creates a Prism from String to Boolean" in {
    safeCast[String, Boolean].getOption("true") shouldEqual Some(true)
    safeCast[String, Boolean].reverseGet(false) shouldEqual "false"
  }

 // idem for all other instances of SafeCast

}

package monocle

import monocle.function.SafeCast._
import monocle.syntax.prism._
import org.specs2.scalaz.Spec

class SafeCastExample extends Spec {

  "safeCast creates a Prism from Int to Char" in {
    safeCast[Int, Char].getOption(65)   shouldEqual Some('A')
    safeCast[Int, Char].reverseGet('a') shouldEqual 97

    // with some syntax sugar
    (65 <-? safeCast[Int, Char] getOption) shouldEqual Some('A')
  }

  "safeCast creates a Prism from String to Int" in {
    safeCast[String, Int].getOption("352") shouldEqual Some(352)
    safeCast[String, Int].reverseGet(8921) shouldEqual "8921"
    safeCast[String, Int].getOption("")    shouldEqual None
  }

  "With safeCast[String,Int] one could map a String with an Int => Int function." in {
    safeCast[String, Int].modify("1024", _ * 2) shouldEqual "2048"
  }

  "safeCast creates a Prism from String to Boolean" in {
    safeCast[String, Boolean].getOption("true") shouldEqual Some(true)
    safeCast[String, Boolean].reverseGet(false) shouldEqual "false"
  }

 // idem for all other instances of SafeCast

}

Add an interesting String<->Int prism modify example.


package io.flow.oneapi

case class Module(name: String, serviceNames: Seq[String])

object Module {

  val General = Module("general", Seq("common", "healthcheck", "organization", "search", "session", "token", "user"))
  val Webhook = Module("webhook", Seq("webhook"))

  val All = Seq(
    Module("localization", Seq("catalog", "experience")),
    Module("pricing", Seq("currency")),
    Module("landed cost", Seq("harmonization")),
    Module("payment", Seq("payment")),
    Module("logistics", Seq("fulfillment", "inventory", "label", "ratecard", "return", "tracking")),
    Webhook,
    Module("customer service", Nil),
    Module("geolocation", Seq("location")),
    Module("reference", Seq("reference")),
    Module("partner", Seq("partner")),
    General
  )

  def findByServiceName(name: String): Option[Module] = {
    All.find(_.serviceNames.contains(name.toLowerCase))
  }

  def findByModuleName(name: String): Option[Module] = {
    All.find(_.name == name.toLowerCase)
  }

  def moduleSortIndex(name: String): Int = {
    val module = findByModuleName(name).getOrElse {
      sys.error(s"Invalid module[$name]")
    }

    val i = All.indexOf(module)
    assert(i >= 0, s"Could not find module: $module")
    i
  }
}

package io.flow.oneapi

case class Module(name: String, serviceNames: Seq[String])

object Module {

  val General = Module("general", Seq("common", "feed", "healthcheck", "link", "organization", "search", "session", "token", "user"))
  val Webhook = Module("webhook", Seq("webhook"))

  val All = Seq(
    Module("localization", Seq("catalog", "experience")),
    Module("pricing", Seq("currency")),
    Module("landed cost", Seq("harmonization")),
    Module("payment", Seq("payment")),
    Module("logistics", Seq("fulfillment", "inventory", "label", "ratecard", "return", "tracking")),
    Webhook,
    Module("customer service", Nil),
    Module("geolocation", Seq("location")),
    Module("reference", Seq("reference")),
    Module("partner", Seq("partner")),
    General
  )

  def findByServiceName(name: String): Option[Module] = {
    All.find(_.serviceNames.contains(name.toLowerCase))
  }

  def findByModuleName(name: String): Option[Module] = {
    All.find(_.name == name.toLowerCase)
  }

  def moduleSortIndex(name: String): Int = {
    val module = findByModuleName(name).getOrElse {
      sys.error(s"Invalid module[$name]")
    }

    val i = All.indexOf(module)
    assert(i >= 0, s"Could not find module: $module")
    i
  }
}

Add link, feed to general

Add link, feed to general


trait Demo {
  def main(args: Array[String]): Unit =
    ()
}

trait Demo {
  println("\n...\n")

  def main(args: Array[String]): Unit =
    println("\n...\n")
}

Print blank line before/after running a demo


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.iscpif.gridscale.jobservice

import java.util.UUID
import fr.iscpif.gridscale.tools._

trait PBSJobDescription extends JobDescription {
  val uniqId = UUID.randomUUID.toString
  def workDirectory: String
  def queue: Option[String] = None
  def cpuTime: Option[Int] = None
  def memory: Option[Int] = None
  def output: String = uniqId + ".out"
  def error: String = uniqId + ".err"

  def toPBS =  {
    val buffer = new ScriptBuffer
    buffer += "#!/bin/bash"

    buffer += "#PBS -o " + output
    buffer += "#PBS -e " + error

    queue match {
      case Some(q) => buffer += "#PBS -q " + q
      case None =>
    }

    memory match {
      case Some(m) => buffer += "#PBS -lmem=" + m + "mb"
      case None =>
    }

    cpuTime match {
      case Some(t) =>
        val df = new java.text.SimpleDateFormat("HH:mm:ss")
        df.setTimeZone(java.util.TimeZone.getTimeZone("GMT"))
        buffer += "#PBS -lwalltime=" + df.format(t * 1000)
      case None =>
    }

    buffer += "cd " + workDirectory

    buffer += executable +  " " + arguments
    buffer.toString
  }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.iscpif.gridscale.jobservice

import java.util.UUID
import fr.iscpif.gridscale.tools._

trait PBSJobDescription extends JobDescription {
  val uniqId = UUID.randomUUID.toString
  def workDirectory: String
  def queue: Option[String] = None
  def cpuTime: Option[Int] = None
  def memory: Option[Int] = None
  def output: String = uniqId + ".out"
  def error: String = uniqId + ".err"

  def toPBS =  {
    val buffer = new ScriptBuffer
    buffer += "#!/bin/bash"

    buffer += "#PBS -o " + output
    buffer += "#PBS -e " + error

    queue match {
      case Some(q) => buffer += "#PBS -q " + q
      case None =>
    }

    memory match {
      case Some(m) => buffer += "#PBS -lmem=" + m + "mb"
      case None =>
    }

    cpuTime match {
      case Some(t) =>
        val df = new java.text.SimpleDateFormat("HH:mm:ss")
        df.setTimeZone(java.util.TimeZone.getTimeZone("GMT"))
        buffer += "#PBS -lwalltime=" + df.format(t * 60 * 1000)
      case None =>
    }

    buffer += "cd " + workDirectory

    buffer += executable +  " " + arguments
    buffer.toString
  }
}

Use minutes for time requirements in pbs.


package de.frosner.broccoli.models

import de.frosner.broccoli.models.ParameterInfo.parameterInfoWrites
import org.apache.commons.codec.digest.DigestUtils
import play.api.libs.functional.syntax._
import play.api.libs.json._

import scala.collection.JavaConversions._
import scala.collection.immutable.TreeSet

case class Template(id: String, template: String, description: String, parameterInfos: Map[String, ParameterInfo])
    extends Serializable {

  @transient
  lazy val parameters: Set[String] = parameterInfos.keySet

  // We sort the parameterInfos by the key to make the String deterministic
  @transient
  lazy val version: String = DigestUtils.md5Hex(template.trim() + "_" + parameterInfos.toSeq.sortBy(_._1).toString)

}

object Template {

  implicit val templateApiWrites: Writes[Template] = (
    (JsPath \ "id").write[String] and
      (JsPath \ "description").write[String] and
      (JsPath \ "parameters").write[Set[String]] and
      (JsPath \ "parameterInfos").write[Map[String, ParameterInfo]] and
      (JsPath \ "version").write[String]
  )((template: Template) =>
    (template.id, template.description, template.parameters, template.parameterInfos, template.version))

  implicit val templatePersistenceReads: Reads[Template] = Json.reads[Template]

  implicit val templatePersistenceWrites: Writes[Template] = Json.writes[Template]

}

package de.frosner.broccoli.models

import de.frosner.broccoli.models.ParameterInfo.parameterInfoWrites
import org.apache.commons.codec.digest.DigestUtils
import play.api.libs.functional.syntax._
import play.api.libs.json._

import scala.collection.JavaConversions._

case class Template(id: String, template: String, description: String, parameterInfos: Map[String, ParameterInfo])
    extends Serializable {

  @transient
  lazy val parameters: Set[String] = parameterInfos.keySet

  // used for JSON serialization to have a deterministic order in the array representation of the set
  @transient
  lazy val sortedParameters: Seq[String] = parameters.toSeq.sorted

  // We sort the parameterInfos by the key to make the String deterministic
  @transient
  lazy val version: String = DigestUtils.md5Hex(template.trim() + "_" + parameterInfos.toSeq.sortBy(_._1).toString)

}

object Template {

  implicit val templateApiWrites: Writes[Template] = (
    (JsPath \ "id").write[String] and
      (JsPath \ "description").write[String] and
      (JsPath \ "parameters").write[Seq[String]] and
      (JsPath \ "parameterInfos").write[Map[String, ParameterInfo]] and
      (JsPath \ "version").write[String]
  )((template: Template) =>
    (template.id, template.description, template.sortedParameters, template.parameterInfos, template.version))

  implicit val templatePersistenceReads: Reads[Template] = Json.reads[Template]

  implicit val templatePersistenceWrites: Writes[Template] = Json.writes[Template]

}

Use sortedParameters for for JSON serialization


/*
 * Copyright 2016 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 controllers

import model.exchange.Phase1TestResultReady
import play.api.mvc.Action
import uk.gov.hmrc.play.microservice.controller.BaseController
import play.api.Logger
import scala.concurrent.Future

object Phase1TestGroupController extends Phase1TestGroupController {

}

trait Phase1TestGroupController extends BaseController {

  def getStatus(applicationId: String) = Action.async(parse.json) { implicit request =>

    Future.successful(Ok)
  }
}

/*
 * Copyright 2016 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 controllers

import play.api.libs.json.JsValue
import play.api.mvc.Action
import uk.gov.hmrc.play.microservice.controller.BaseController
import repositories._
import repositories.application.OnlineTestRepository

import scala.concurrent.Future

object Phase1TestGroupController extends Phase1TestGroupController {
  override val phase1TestRepository = onlineTestRepository
}

trait Phase1TestGroupController extends BaseController {

  val phase1TestRepository: OnlineTestRepository

  def getStatus(applicationId: String): Action[JsValue] = Action.async(parse.json) { implicit request =>
    for {
      phase1TestGroupOpt <- phase1TestRepository.getPhase1TestProfile(applicationId)
    } yield {
      phase1TestGroupOpt.map { Ok(_) }.getOrElse(NotFound)
    }
  }
}

Add placeholding controller method for getting test group status


package com.trueaccord.scalapb.compiler

import com.google.protobuf.Descriptors._
import scala.collection.JavaConverters._

class ProtoValidation(val params: GeneratorParams) extends DescriptorPimps {
  val ForbiddenFieldNames = Set(
    "hashCode", "equals", "clone", "finalize", "getClass", "notify", "notifyAll", "toString", "wait")

  def validateFile(fd: FileDescriptor): Unit = {
    fd.getEnumTypes.asScala.foreach(validateEnum)
    fd.getMessageTypes.asScala.foreach(validateMessage)
  }

  def validateEnum(e: EnumDescriptor): Unit = {
    if (e.getValues.asScala.exists(_.getName.toUpperCase == "UNRECOGNIZED")) {
      throw new GeneratorException(
        s"The enum value 'UNRECOGNIZED' in ${e.getName} is not allowed due to conflict with the catch-all " +
          "Unrecognized(v: Int) value.")
    }
  }

  def validateMessage(m: Descriptor): Unit = {
    m.getEnumTypes.asScala.foreach(validateEnum)
    m.getNestedTypes.asScala.foreach(validateMessage)
    m.getFields.asScala.foreach(validateField)
  }

  def validateField(fd: FieldDescriptor): Unit = {
    if (ForbiddenFieldNames.contains(fd.scalaName))
      throw new GeneratorException(
        s"Field named '${fd.getName}' in message '${fd.getFullName}' is not allowed.")
  }
}

package com.trueaccord.scalapb.compiler

import com.google.protobuf.Descriptors._
import scala.collection.JavaConverters._

class ProtoValidation(val params: GeneratorParams) extends DescriptorPimps {
  val ForbiddenFieldNames = Set(
    "hashCode", "equals", "clone", "finalize", "getClass", "notify", "notifyAll", "toString", "wait")

  def validateFile(fd: FileDescriptor): Unit = {
    fd.getEnumTypes.asScala.foreach(validateEnum)
    fd.getMessageTypes.asScala.foreach(validateMessage)
  }

  def validateEnum(e: EnumDescriptor): Unit = {
    if (e.getValues.asScala.exists(_.getName.toUpperCase == "UNRECOGNIZED")) {
      throw new GeneratorException(
        s"The enum value 'UNRECOGNIZED' in ${e.getName} is not allowed due to conflict with the catch-all " +
          "Unrecognized(v: Int) value.")
    }
  }

  def validateMessage(m: Descriptor): Unit = {
    m.getEnumTypes.asScala.foreach(validateEnum)
    m.getNestedTypes.asScala.foreach(validateMessage)
    m.getFields.asScala.foreach(validateField)
  }

  def validateField(fd: FieldDescriptor): Unit = {
    if (ForbiddenFieldNames.contains(fd.scalaName))
      throw new GeneratorException(
        s"Field named '${fd.getName}' in message '${fd.getFullName}' is not allowed. See https://scalapb.github.io/customizations.html#custom-names")
  }
}

Add reference to how to use custom names.


lazy val specs2Version = "4.8.0"
lazy val catsVersion   = "1.6.1"

libraryDependencies in Global ++=
  cats ++
  specs2

resolvers ++= Seq(
    Resolver.sonatypeRepo("releases")
  , Resolver.typesafeRepo("releases")
  , Resolver.url("ambiata-oss", new URL("https://ambiata-oss.s3.amazonaws.com"))(Resolver.ivyStylePatterns))

lazy val cats = Seq(
  "org.typelevel" %% "cats-core" % catsVersion)

lazy val specs2 = Seq(
    "org.specs2" %% "specs2-core"
  , "org.specs2" %% "specs2-matcher-extra"
  , "org.specs2" %% "specs2-scalacheck"
  , "org.specs2" %% "specs2-html"
  , "org.specs2" %% "specs2-junit").map(_ % specs2Version % "test")

lazy val specs2Version = "4.8.1"
lazy val catsVersion   = "1.6.1"

libraryDependencies in Global ++=
  cats ++
  specs2

resolvers ++= Seq(
    Resolver.sonatypeRepo("releases")
  , Resolver.typesafeRepo("releases")
  , Resolver.url("ambiata-oss", new URL("https://ambiata-oss.s3.amazonaws.com"))(Resolver.ivyStylePatterns))

lazy val cats = Seq(
  "org.typelevel" %% "cats-core" % catsVersion)

lazy val specs2 = Seq(
    "org.specs2" %% "specs2-core"
  , "org.specs2" %% "specs2-matcher-extra"
  , "org.specs2" %% "specs2-scalacheck"
  , "org.specs2" %% "specs2-html"
  , "org.specs2" %% "specs2-junit").map(_ % specs2Version % "test")

Update specs2-core, specs2-html, ... to 4.8.1


package uk.ac.wellcome.messaging.sqs

import javax.inject.Singleton

import com.google.inject.Provides
import com.twitter.inject.TwitterModule
import uk.ac.wellcome.messaging.sqs.SQSConfig

import scala.concurrent.duration._

object SQSConfigModule extends TwitterModule {
  private val queueUrl =
    flag[String]("aws.sqs.queue.url", "", "URL of the SQS Queue")
  val waitTime = flag(
    "aws.sqs.waitTime",
    20,
    "Time to wait (in seconds) for a message to arrive on the queue before returning")
  val maxMessages =
    flag("aws.sqs.maxMessages", 10, "Maximum number of SQS messages to return")

  @Singleton
  @Provides
  def providesSQSConfig(): SQSConfig =
    SQSConfig(queueUrl(), waitTime() seconds, maxMessages())
}

package uk.ac.wellcome.messaging.sqs

import javax.inject.Singleton

import com.google.inject.Provides
import com.twitter.inject.TwitterModule

import scala.concurrent.duration._

object SQSConfigModule extends TwitterModule {
  private val queueUrl =
    flag[String]("aws.sqs.queue.url", "", "URL of the SQS Queue")
  val waitTime = flag(
    "aws.sqs.waitTime",
    20,
    "Time to wait (in seconds) for a message to arrive on the queue before returning")
  val maxMessages =
    flag("aws.sqs.maxMessages", 10, "Maximum number of SQS messages to return")

  @Singleton
  @Provides
  def providesSQSConfig(): SQSConfig =
    SQSConfig(queueUrl(), waitTime() seconds, maxMessages())
}

Remove an import that isn't needed any more


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

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

addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.10.0")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.sbt" % "sbt-unidoc" % "0.5.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.13.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.9")
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.11"

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

addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.10.0")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.sbt" % "sbt-unidoc" % "0.5.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.13.2")
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.9")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")

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


package com.campudus.scycle

import org.scalajs.dom
import rx._

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport

@JSExport
object TutorialApp extends JSApp {

  @JSExport
  def main(): Unit = {
    val i = Var(0)
    val text = Rx {
      s"Seconds elapsed ${i()}"
    }

    dom.setInterval(() => {
      i() = i() + 1
      dom.console.log(text())
    }, 1000)

    dom.document.getElementById("app").textContent = text()
  }

}

package com.campudus.scycle

import org.scalajs.dom
import rx._

import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport

@JSExport
object TutorialApp extends JSApp {

  @JSExport
  def main(): Unit = {
    val container = dom.document.getElementById("app")
    val i = Var(0)
    val text = Rx {
      s"Seconds elapsed ${i()}"
    }

    val iObserver = Obs(text) {
      container.textContent = text()
    }

    dom.setInterval(() => {
      i() = i() + 1
    }, 1000)
  }

}

Use Obs to observe text changes and write them into the DOM

Signed-off-by: Joern Bernhardt <7b85a41a628204b76aba4326273a3ccc74bd009a@campudus.com>


package com.softwaremill.codebrag.dao

import com.softwaremill.codebrag.domain.CommitReviewTask
import net.liftweb.mongodb.record.{MongoMetaRecord, MongoRecord}
import net.liftweb.mongodb.record.field.{ObjectIdPk, ObjectIdField}
import com.foursquare.rogue.LiftRogue._

class MongoCommitReviewTaskDAO extends CommitReviewTaskDAO {

  def save(reviewTask: CommitReviewTask) {
    val ifExistsQuery = CommitReviewTaskRecord.where(_.userId eqs reviewTask.userId).and(_.commitId eqs reviewTask.commitId).asDBObject
    CommitReviewTaskRecord.upsert(ifExistsQuery, toRecord(reviewTask).asDBObject)
  }

  def delete(task: CommitReviewTask) {
    CommitReviewTaskRecord.where(_.commitId eqs task.commitId).and(_.userId eqs task.userId).findAndDeleteOne()
  }

  private def toRecord(commitToReview: CommitReviewTask) = {
    CommitReviewTaskRecord.createRecord
      .commitId(commitToReview.commitId)
      .userId(commitToReview.userId)
  }

}

class CommitReviewTaskRecord extends MongoRecord[CommitReviewTaskRecord] with ObjectIdPk[CommitReviewTaskRecord] {
  def meta = CommitReviewTaskRecord
  object commitId extends ObjectIdField(this)
  object userId extends ObjectIdField(this)
}

object CommitReviewTaskRecord extends CommitReviewTaskRecord with MongoMetaRecord[CommitReviewTaskRecord] {
  override def collectionName = "commit_review_tasks"
}

package com.softwaremill.codebrag.dao

import com.softwaremill.codebrag.domain.CommitReviewTask
import net.liftweb.mongodb.record.{MongoMetaRecord, MongoRecord}
import net.liftweb.mongodb.record.field.{ObjectIdPk, ObjectIdField}
import com.foursquare.rogue.LiftRogue._

class MongoCommitReviewTaskDAO extends CommitReviewTaskDAO {

  def save(reviewTask: CommitReviewTask) {
    val ifExistsQuery = CommitReviewTaskRecord.where(_.userId eqs reviewTask.userId).and(_.commitId eqs reviewTask.commitId).asDBObject
    CommitReviewTaskRecord.upsert(ifExistsQuery, toRecord(reviewTask))
  }

  def delete(task: CommitReviewTask) {
    CommitReviewTaskRecord.where(_.commitId eqs task.commitId).and(_.userId eqs task.userId).findAndDeleteOne()
  }

  private def toRecord(commitToReview: CommitReviewTask) = {
    val dbo = CommitReviewTaskRecord.createRecord
      .commitId(commitToReview.commitId)
      .userId(commitToReview.userId)
    .asDBObject
    dbo.removeField("_id")
    dbo
  }

}

class CommitReviewTaskRecord extends MongoRecord[CommitReviewTaskRecord] with ObjectIdPk[CommitReviewTaskRecord] {
  def meta = CommitReviewTaskRecord
  object commitId extends ObjectIdField(this)
  object userId extends ObjectIdField(this)
}

object CommitReviewTaskRecord extends CommitReviewTaskRecord with MongoMetaRecord[CommitReviewTaskRecord] {
  override def collectionName = "commit_review_tasks"
}

Fix ReviewTaskDao to remove _id field from upsert query.


addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.2.27")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.5")

addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.3.4")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.6")

Update the SBT plugin versions.

Update the SBT plugin versions.


package enju.ccg.ml

import scala.collection.mutable.HashMap

class FeatureIndexer[Feature] extends HashMap[Feature, Int] {
  def getIndex(key: Feature) = getOrElseUpdate(key, size)

  def removeIndexes(idxs: Seq[Int]): Unit = {
    val features = this.toSeq.sortWith(_._2 < _._2).map(_._1)
    for (i <- 0 until features.size) {
      assert(this(features(i)) == i)
    }
    (0 to idxs.size) foreach { i =>
      val idx = if (i == idxs.size) size else idxs(i)
      val lastIdx = if (i == 0) -1 else idxs(i - 1)
      (lastIdx + 1 until idx).foreach { f => this(features(f)) -= i }
      if (i != idxs.size) this -= features(idx)
    }
  }
  def removeElemsOver(lastIdx: Int): Unit = this.toSeq.foreach { case (feature, idx) =>
    if (idx >= lastIdx) this -= feature
  }
}

package enju.ccg.ml

import scala.collection.mutable.HashMap

class FeatureIndexer[Feature] extends HashMap[Feature, Int] {
  def getIndex(key: Feature) = getOrElseUpdate(key, size)

  def removeIndexes(idxs: Seq[Int]): Unit = {
    val features = this.toSeq.sortWith(_._2 < _._2).map(_._1)
    val originalSize = size
    (0 to idxs.size) foreach { i =>
      val idx = if (i == idxs.size) originalSize else idxs(i)
      val lastIdx = if (i == 0) -1 else idxs(i - 1)
      (lastIdx + 1 until idx).foreach { f => this(features(f)) -= i }
      if (i != idxs.size) this -= features(idx)
    }
  }
  def removeElemsOver(lastIdx: Int): Unit = this.toSeq.foreach { case (feature, idx) =>
    if (idx >= lastIdx) this -= feature
  }
}

Fix a bug in removing zero elements

Fix a bug in removing zero elements


package net.ceedubs.ficus

import org.specs2.specification.{FormattingFragments, FragmentsBuilder, BaseSpecification}
import org.specs2.matcher.MustMatchers
import org.specs2.ScalaCheck
import org.scalacheck.Gen

trait Spec extends BaseSpecification with MustMatchers with FragmentsBuilder with FormattingFragments with ScalaCheck {
  private[this] val SpecialJsonCharacters = Set('\\', '"')

  private[this] val JsonStringChars = ('\u0020' to '\u007E').filterNot(SpecialJsonCharacters.contains)

  val jsonStringValue = Gen.listOf(JsonStringChars).map(_.mkString)
}

package net.ceedubs.ficus

import org.specs2.specification.{FormattingFragments, FragmentsBuilder, BaseSpecification}
import org.specs2.matcher.MustMatchers
import org.specs2.ScalaCheck
import org.scalacheck.Gen

trait Spec extends BaseSpecification with MustMatchers with FragmentsBuilder with FormattingFragments with ScalaCheck {
  val jsonStringValue = Spec.jsonStringValue
}

object Spec {
  private[this] val SpecialJsonCharacters = Set('\\', '"')

  private[this] val JsonStringChars = ('\u0020' to '\u007E').filterNot(SpecialJsonCharacters.contains)

  val jsonStringValue = Gen.listOf(JsonStringChars).map(_.mkString)
}

Move jsonStringValue ScalaCheck generator to companion object


object Packaging {
  import com.typesafe.sbt.packager.archetypes.JavaAppPackaging
  import com.typesafe.sbt.packager.docker.DockerPlugin
  import com.typesafe.sbt.packager.Keys._
  import sbt.Keys._
  import DockerPlugin.autoImport.Docker
  import com.typesafe.sbt.SbtGit.git

  lazy val settings = Seq(
    packageName in Docker := "sota-" + packageName.value,
    version in Docker := git.gitDescribedVersion.value.get,
    dockerUpdateLatest in Docker := true
  )

  val plugins = Seq(DockerPlugin, JavaAppPackaging)
}

object Packaging {
  import com.typesafe.sbt.packager.archetypes.JavaAppPackaging
  import com.typesafe.sbt.packager.docker.DockerPlugin
  import com.typesafe.sbt.packager.Keys._
  import sbt.Keys._
  import DockerPlugin.autoImport.Docker
  import com.typesafe.sbt.SbtGit.git

  lazy val settings = Seq(
    packageName in Docker := "sota-" + packageName.value,
    dockerBaseImage := "advancedtelematic/java:openjdk-8-jre",
    version in Docker := git.gitDescribedVersion.value.get,
    dockerUpdateLatest in Docker := true
  )

  val plugins = Seq(DockerPlugin, JavaAppPackaging)
}

Use a Debian 8 baseimage

Use a Debian 8 baseimage


import play.Play.autoImport._
import sbt.Keys._
import sbt._
import sbt.plugins._

object ApplicationBuild extends Build {

  val appName         = "admin"
  val appVersion      = "1.1"

  val appDependencies = Seq(
    jdbc,
    anorm,
    "org.quartz-scheduler" % "quartz" % "2.1.7",
    "com.lucidchart" %% "piezo-worker" % "1.13-SNAPSHOT"
  )

  val main = Project(appName, file(".")).enablePlugins(play.PlayScala).settings(
    retrieveManaged := true,
    version := appVersion,
    libraryDependencies ++= appDependencies,
    scalaVersion := "2.11.7",
    resolvers ++= List(
      Resolver.file("local ivy repository", file(System.getenv("HOME") + "/.ivy2/local/"))(Resolver.ivyStylePatterns),
      "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots",
      "Staging Sonatype repository" at "https://oss.sonatype.org/content/groups/staging/"
    )
  )

}

import play.Play.autoImport._
import sbt.Keys._
import sbt._
import sbt.plugins._

object ApplicationBuild extends Build {

  val appName         = "admin"
  val appVersion      = "1.1"

  val appDependencies = Seq(
    jdbc,
    anorm,
    "org.quartz-scheduler" % "quartz" % "2.1.7",
    "com.lucidchart" %% "piezo-worker" % "1.14"
  )

  val main = Project(appName, file(".")).enablePlugins(play.PlayScala).settings(
    retrieveManaged := true,
    version := appVersion,
    libraryDependencies ++= appDependencies,
    scalaVersion := "2.11.7",
    resolvers ++= List(
      Resolver.file("local ivy repository", file(System.getenv("HOME") + "/.ivy2/local/"))(Resolver.ivyStylePatterns),
      "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots",
      "Staging Sonatype repository" at "https://oss.sonatype.org/content/groups/staging/"
    )
  )

}

Update admin to depend on worker 1.14

Update admin to depend on worker 1.14


package org.apache.spark.streaming

import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.streaming.event.Event

import scala.reflect.ClassTag

abstract class Dependency[T: ClassTag](val stream: DStream[T]) {
  def rdds(event: Event): Seq[RDD[T]]
}

class EventDependency[T: ClassTag](
    override val stream: DStream[T]
  ) extends Dependency[T](stream) {
  override def rdds(event: Event): Seq[RDD[T]] = {
    stream.getOrCompute(event).map(Seq[RDD[T]](_)).getOrElse(Seq[RDD[T]]())
  }
}

class TailDependency[T: ClassTag](
    override val stream: DStream[T],
    val skip: Int,
    val size: Int,
    val computeEvent: Boolean
  ) extends Dependency[T](stream) {
  override def rdds(event: Event): Seq[RDD[T]] = {
    if (computeEvent) {
      stream.getOrCompute(event)
    }
    stream.generatedRDDs.values.dropRight(skip).takeRight(size).toSeq
    //Some(stream.ssc.sc.union(tailRDDs.toSeq))
  }
}

package org.apache.spark.streaming

import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.streaming.event.Event

import scala.reflect.ClassTag

abstract class Dependency[T: ClassTag](val stream: DStream[T]) {
  def rdds(event: Event): Seq[RDD[T]]
}

class EventDependency[T: ClassTag](
    override val stream: DStream[T]
  ) extends Dependency[T](stream) {
  override def rdds(event: Event): Seq[RDD[T]] = {
    stream.getOrCompute(event).map(Seq[RDD[T]](_)).getOrElse(Seq[RDD[T]]())
  }
}

class TailDependency[T: ClassTag](
    override val stream: DStream[T],
    val skip: Int,
    val size: Int,
    val computeEvent: Boolean
  ) extends Dependency[T](stream) {
  override def rdds(event: Event): Seq[RDD[T]] = {
    val events = if (computeEvent) {
      stream.getOrCompute(event)
      stream.generatedEvents.to(event)
    } else {
      stream.generatedEvents.until(event)
    }

    events.dropRight(skip).takeRight(size)
      .map(e => stream.getOrCompute(e))
      .filter(_.nonEmpty).map(_.get).toSeq
    //Some(stream.ssc.sc.union(tailRDDs.toSeq))
  }
}

Use stream generated events for tail dependency resolution


addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % sys.props("plugin.version"))
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.1.1")

addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % sys.props("plugin.version"))
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.2.0")

Use sbt-scalajs 1.2.0 in the tests of sbt-dotty.

This was forgotten in 1ed50db745adbc15971444a413fb31150c98387c.


package scala.slick
package ql

/**
 * Aliases for QL features. This trait can be mixed into aliasing objects
 * which simplify the use of the Query Language.
 */
trait Aliases {
  type Query[+E, U] = ql.Query[E, U]
  val Query = ql.Query
  type Column[T] = ql.Column[T]
  type ConstColumn[T] = ql.ConstColumn[T]
  val ConstColumn = ql.ConstColumn
  val Case = ql.Case
  type Re[T] = ql.Rep[T]
  val Functions = ql.Functions
  type Parameters[PU, PP] = ql.Parameters[PU, PP]
  val Parameters = ql.Parameters
  type Sequence[T] = ql.Sequence[T]
  val Sequence = ql.Sequence
  type SimpleFunction = ql.SimpleFunction
  val SimpleFunction = ql.SimpleFunction
  type SimpleBinaryOperator = ql.SimpleBinaryOperator
  val SimpleBinaryOperator = ql.SimpleBinaryOperator
  type SimpleExpression = ql.SimpleExpression
  val SimpleExpression = ql.SimpleExpression
  type SimpleLiteral = ql.SimpleLiteral
  val SimpleLiteral = ql.SimpleLiteral
  type TypeMapper[T] = ql.TypeMapper[T]
  val TypeMapper = ql.TypeMapper
  type TypeMapperDelegate[T] = ql.TypeMapperDelegate[T]
  val TypeMapperDelegate = ql.TypeMapperDelegate
  type MappedTypeMapper[T, U] = ql.MappedTypeMapper[T, U]
  val MappedTypeMapper = ql.MappedTypeMapper
}

package scala.slick
package ql

/**
 * Aliases for QL features. This trait can be mixed into aliasing objects
 * which simplify the use of the Query Language.
 */
trait Aliases {
  type Query[+E, U] = ql.Query[E, U]
  val Query = ql.Query
  type Column[T] = ql.Column[T]
  type ConstColumn[T] = ql.ConstColumn[T]
  val ConstColumn = ql.ConstColumn
  val Case = ql.Case
  type Re[T] = ql.Rep[T]
  val Functions = ql.Functions
  type Parameters[PU, PP] = ql.Parameters[PU, PP]
  val Parameters = ql.Parameters
  type Sequence[T] = ql.Sequence[T]
  val Sequence = ql.Sequence
  type SimpleFunction = ql.SimpleFunction
  val SimpleFunction = ql.SimpleFunction
  type SimpleBinaryOperator = ql.SimpleBinaryOperator
  val SimpleBinaryOperator = ql.SimpleBinaryOperator
  type SimpleExpression = ql.SimpleExpression
  val SimpleExpression = ql.SimpleExpression
  type SimpleLiteral = ql.SimpleLiteral
  val SimpleLiteral = ql.SimpleLiteral
  type TypeMapper[T] = ql.TypeMapper[T]
  val TypeMapper = ql.TypeMapper
  type TypeMapperDelegate[T] = ql.TypeMapperDelegate[T]
  val TypeMapperDelegate = ql.TypeMapperDelegate
  type MappedTypeMapper[T, U] = ql.MappedTypeMapper[T, U]
  val MappedTypeMapper = ql.MappedTypeMapper
  val ~ = ql.~
}

Add ~ to simple imports

Add ~ to simple imports


package io.flow.oneapi

case class Module(name: String, serviceNames: Seq[String])

object Module {

  val General = Module("general", Seq("common", "organization", "search", "token", "user"))
  val Webhook = Module("webhook", Seq("webhook"))

  val All = Seq(
    Module("localization", Seq("catalog", "experience")),
    Module("pricing", Seq("currency")),
    Module("landed cost", Seq("harmonization")),
    Module("payment", Seq("payment")),
    Module("logistics", Seq("delivery_window", "fulfillment", "inventory", "label", "ratecard", "tracking")),
    Webhook,
    Module("customer service", Nil),
    Module("geolocation", Seq("location")),
    Module("reference", Seq("reference")),
    General
  )

  def findByServiceName(name: String): Option[Module] = {
    All.find(_.serviceNames.contains(name.toLowerCase))
  }

  def findByModuleName(name: String): Option[Module] = {
    All.find(_.name == name.toLowerCase)
  }

  def moduleSortIndex(name: String): Int = {
    val module = findByModuleName(name).getOrElse {
      sys.error(s"Invalid module[$name]")
    }

    val i = All.indexOf(module)
    assert(i >= 0, s"Could not find module: $module")
    i
  }
}

package io.flow.oneapi

case class Module(name: String, serviceNames: Seq[String])

object Module {

  val General = Module("general", Seq("common", "healthcheck", "organization", "search", "token", "user"))
  val Webhook = Module("webhook", Seq("webhook"))

  val All = Seq(
    Module("localization", Seq("catalog", "experience")),
    Module("pricing", Seq("currency")),
    Module("landed cost", Seq("harmonization")),
    Module("payment", Seq("payment")),
    Module("logistics", Seq("delivery_window", "fulfillment", "inventory", "label", "ratecard", "tracking")),
    Webhook,
    Module("customer service", Nil),
    Module("geolocation", Seq("location")),
    Module("reference", Seq("reference")),
    General
  )

  def findByServiceName(name: String): Option[Module] = {
    All.find(_.serviceNames.contains(name.toLowerCase))
  }

  def findByModuleName(name: String): Option[Module] = {
    All.find(_.name == name.toLowerCase)
  }

  def moduleSortIndex(name: String): Int = {
    val module = findByModuleName(name).getOrElse {
      sys.error(s"Invalid module[$name]")
    }

    val i = All.indexOf(module)
    assert(i >= 0, s"Could not find module: $module")
    i
  }
}

Add healthcheck to general module

Add healthcheck to general module


releasePublishArtifactsAction := PgpKeys.publishSigned.value

publishMavenStyle := true

pomIncludeRepository := { _ => false }

publishTo := {
  val nexus = "https://oss.sonatype.org/"
  if (isSnapshot.value)
    Some("snapshots" at nexus + "content/repositories/snapshots")
  else
    Some("releases"  at nexus + "service/local/staging/deploy/maven2")
}

pomExtra := (
  <url>https://github.com/waylayio/kairosdb-scala</url>
    <licenses>
      <license>
        <name>MIT License</name>
        <url>http://www.opensource.org/licenses/mit-license.php</url>
        <distribution>repo</distribution>
      </license>
    </licenses>
    <developers>
      <developer>
        <id>francisdb</id>
        <name>Francis De Brabandere</name>
        <url>https://github.com/francisdb</url>
      </developer>
      <developer>
        <id>thomastoye</id>
        <name>Thomas Toye</name>
        <url>https://github.com/thomastoye</url>
      </developer>
    </developers>)

releasePublishArtifactsAction := PgpKeys.publishSigned.value

publishMavenStyle := true

pomIncludeRepository := { _ => false }

publishTo := {
  val nexus = "https://oss.sonatype.org/"
  if (isSnapshot.value)
    Some("snapshots" at nexus + "content/repositories/snapshots")
  else
    Some("releases"  at nexus + "service/local/staging/deploy/maven2")
}

updateOptions := updateOptions.value.withGigahorse(false)

pomExtra := (
  <url>https://github.com/waylayio/kairosdb-scala</url>
    <licenses>
      <license>
        <name>MIT License</name>
        <url>http://www.opensource.org/licenses/mit-license.php</url>
        <distribution>repo</distribution>
      </license>
    </licenses>
    <developers>
      <developer>
        <id>francisdb</id>
        <name>Francis De Brabandere</name>
        <url>https://github.com/francisdb</url>
      </developer>
      <developer>
        <id>thomastoye</id>
        <name>Thomas Toye</name>
        <url>https://github.com/thomastoye</url>
      </developer>
      <developer>
        <id>brunoballekens</id>
        <name>Bruno Ballekens</name>
        <url>https://github.com/brunoballekens</url>
      </developer>
    </developers>)

Update for to prepare for release

Update for to prepare for release


/*
 * Copyright (C) 13/02/13 Romain Reuillon
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.openmole.misc.tools.collection

object ArrayUtils {

  def unsecureConcat(a1: Array[_], a2: Array[_], t: Manifest[_]): Array[_] = {
    val res = t.newArray(a1.size + a2.size)
    (a1 ++ a2).zipWithIndex.foreach {
      case (v, i) ⇒ java.lang.reflect.Array.set(res, i, v)
    }
    res
  }

}

/*
 * Copyright (C) 13/02/13 Romain Reuillon
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.openmole.misc.tools.collection

object ArrayUtils {

  def unsecureBuild(t: Manifest[_], values: Any*) = {
    val res = manifest.newArray(values.size)
    values.zipWithIndex.foreach {
      case(v, i) =>  java.lang.reflect.Array.set(res, i, v)
    }
    res
  }

  def unsecureConcat(t: Manifest[_], a1: Array[_], a2: Array[_]): Array[_] = {
    val res = t.newArray(a1.size + a2.size)
    (a1 ++ a2).zipWithIndex.foreach {
      case (v, i) ⇒ java.lang.reflect.Array.set(res, i, v)
    }
    res
  }

}

Implement unsecure build for arrays.

Implement unsecure build for arrays.


package com.codahale.jdub

import java.sql.ResultSet

trait Query[A] extends RawQuery[A] {
  def handle(rs: ResultSet) = {
    val width = rs.getMetaData.getColumnCount
    var results = Vector.empty[Vector[Any]]
    while (rs.next()) {
      var row = Vector.empty[Any]
      for (i <- 1 to width) {
        row = row :+ rs.getObject(i)
      }
      results = results :+ row
    }
    reduce(results)
  }

  def reduce(results: Vector[Vector[Any]]): A
}

package com.codahale.jdub

import scala.collection.JavaConversions._
import java.sql.ResultSet

trait Query[A] extends RawQuery[A] {
  def handle(rs: ResultSet) = {
    val width = rs.getMetaData.getColumnCount
    var results = Vector.empty[Vector[Any]]
    while (rs.next()) {
      var row = Vector.empty[Any]
      for (i <- 1 to width) {
        row = row :+ rs.getObject(i, typeMap)
      }
      results = results :+ row
    }
    reduce(results)
  }

  def reduce(results: Vector[Vector[Any]]): A

  protected def typeMap = Map.empty[String, Class[_]]
}

Allow for type map overrides.

Allow for type map overrides.


/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2011, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.util.control

/** A trait for exceptions which, for efficiency reasons, do not
 *  fill in the stack trace.  Stack trace suppression can be disabled
 *  on a global basis via a system property wrapper in
 *  [[scala.sys.SystemProperties]].
 *
 *  @author   Paul Phillips
 *  @since    2.8
 */
trait NoStackTrace extends Throwable {
  override def fillInStackTrace(): Throwable =
    if (noSuppression) super.fillInStackTrace()
    else this
}

object NoStackTrace {
  final val noSuppression = sys.SystemProperties.noTraceSupression.value
}

/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2011, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.util.control

/** A trait for exceptions which, for efficiency reasons, do not
 *  fill in the stack trace.  Stack trace suppression can be disabled
 *  on a global basis via a system property wrapper in
 *  [[scala.sys.SystemProperties]].
 *
 *  @author   Paul Phillips
 *  @since    2.8
 */
trait NoStackTrace extends Throwable {
  override def fillInStackTrace(): Throwable =
    if (NoStackTrace.noSuppression) super.fillInStackTrace()
    else this
}

object NoStackTrace {
  final val noSuppression = sys.SystemProperties.noTraceSupression.value
}

Fix for that slightly not compiling previous pa...

Fix for that slightly not compiling previous patch, no review.


object Solution {

  def genMultiples(n: Int, k: Int): Seq[Int] = {
    val upperBound = 1e5.toInt
    val limit = if (k == 8) upperBound / 2 else upperBound

    def canBePandigitalMultiples(m: Int): Boolean = {
      val digitAppeared = Array.fill(9 + 1)(false)
      // set 0 to has be appeared. If we see 0 again, we can just return false
      digitAppeared(0) = true
      if (k == 8) digitAppeared(9) = true
      var count = 0 // the number of digits has be appeared.
      var mb = 1
      while (count < k) {
        var mm = mb * m
        while (mm > 0) {
          val digit = mm % 10
          if (digitAppeared(digit)) return false
          else {
            digitAppeared(digit) = true
            count += 1
            mm /= 10
          }
        }
        mb += 1
      }
      true
    }

    for {
      m <- 2 to math.min(n, limit)
      if canBePandigitalMultiples(m)
    } yield m
  }

  def main(args: Array[String]) {
    val Array(n, k) = readLine.split(" ").map(_.toInt)
    println(genMultiples(n, k).mkString("\n"))
  }
}

object Solution {

  def genMultiples(n: Int, k: Int): Seq[Int] = {
    val upperBound = 1e5.toInt
    val limit = if (k == 8) upperBound / 2 else upperBound

    val digitAppeared = Array.fill(9 + 1)(false)
    // set 0 to has be appeared. If we see 0 again, we can just return false
    digitAppeared(0) = true
    if (k == 8) digitAppeared(9) = true

    def canBePandigitalMultiples(m: Int): Boolean = {
      for (i <- 1 to k) digitAppeared(i) = false
      var count = 0 // the number of digits has be appeared.
      var mb = 1
      while (count < k) {
        var mm = mb * m
        while (mm > 0) {
          val digit = mm % 10
          if (digitAppeared(digit)) return false
          else {
            digitAppeared(digit) = true
            count += 1
            mm /= 10
          }
        }
        mb += 1
      }
      true
    }

    for {
      m <- 2 to math.min(n, limit)
      if canBePandigitalMultiples(m)
    } yield m
  }

  def main(args: Array[String]) {
    val Array(n, k) = readLine.split(" ").map(_.toInt)
    println(genMultiples(n, k).mkString("\n"))
  }
}

Optimize for array usage. There's no obvious time gain for this change.


package ccf.transport.http

import java.io.IOException
import java.net.URL

import org.apache.http.params.HttpConnectionParams
import ccf.transport.json.{JsonFormatter, JsonParser}

import dispatch.{Request => HttpRequest, Http}
import dispatch.Http._

class HttpConnection(url: URL, timeoutMillis: Int, http: Http) extends Connection {
  private val formatter = JsonFormatter
  private val parser = JsonParser
  init
  def this(url: URL, timeoutMillis: Int) = this(url, timeoutMillis, new Http)
  def send(request: Request): Option[Response] = {
    val req = requestUrl(request).POST << formatter.format(request)
    http(req >- { parser.parse(_) })
  }
  private def requestUrl(request: Request) = url.toString / request.header("type").getOrElse(requestTypeMissing)
  private def requestTypeMissing = throw new InvalidRequestException("Request header \"type\" missing")
  private def init = {
    HttpConnectionParams.setConnectionTimeout(httpClientParams, timeoutMillis)
    HttpConnectionParams.setSoTimeout(httpClientParams, timeoutMillis)
  }
  private def httpClientParams = http.client.getParams
}

package ccf.transport.http

import java.io.IOException
import java.net.URL

import ccf.transport.json.{JsonFormatter, JsonParser}

class HttpConnection(url: URL, timeoutMillis: Int, http: Http) extends Connection {
  private val formatter = JsonFormatter
  private val parser = JsonParser
  def this(url: URL, timeoutMillis: Int) = this(url, timeoutMillis, new HttpImpl(timeoutMillis))
  def send(request: Request): Option[Response] = try {
    http.post(requestUrl(request), formatter.format(request)) { parser.parse }
  } catch {
    case e: IOException => throw new ConnectionException(e.toString)
  }
  private def requestUrl(request: Request) = new URL(url, request.header("type").getOrElse(requestTypeMissing))
  private def requestTypeMissing = throw new InvalidRequestException("Request header \"type\" missing")
}

transport: Drop direct dep. from HTTP connection to Databinder Dispatch

While at it, transform IO exceptions to ConnectionExceptions.

Signed-off-by: Karim Osman <94396faf6cc817be76165477038b3cfa832e89a4@reaktor.fi>
Acked-by: Harri Salokorpi <eefb23b8deb8c30dca252cd0ae751b67337dc69f@reaktor.fi>


package com.anchortab.snippet

import scala.xml.NodeSeq

import net.liftweb._
  import common._
  import http._
    import provider._
    import js._
      import JsCmds._
    import SHtml._
    import LiftRules._
  import util._
    import Helpers._
  import json._
    import JsonDSL._
  import mongodb.BsonDSL._

object inviteCode extends RequestVar[Box[String]](Empty)

object Invites extends Loggable {
  def statelessRewrite: RewritePF = {
    case RewriteRequest(ParsePath("accept-invite" :: userInviteCode :: Nil, _, _, _), _, _) =>
      inviteCode(Full(userInviteCode))
      RewriteResponse("register" :: Nil)
  }
}

package com.anchortab.snippet

import scala.xml.NodeSeq

import net.liftweb._
  import common._
  import http._
    import provider._
    import js._
      import JsCmds._
    import SHtml._
    import LiftRules._
  import util._
    import Helpers._
  import json._
    import JsonDSL._
  import mongodb.BsonDSL._

import com.anchortab.model.InviteCode

object inviteCode extends RequestVar[Box[InviteCode]](Empty)

object Invites extends Loggable {
  def statelessRewrite: RewritePF = {
    case RewriteRequest(ParsePath("accept-invite" :: userInviteCode :: Nil, _, _, _), _, _) =>
      for {
        invite <- InviteCode.findAll("code" -> userInviteCode)
          if invite.numberOfUsesAvailable.map(_ > invite.numberOfUses) getOrElse true
      } {
        inviteCode(Full(invite))
      }

      RewriteResponse("register" :: Nil)
  }
}

Set the entire InviteCode object iff it's valid.


package scala.reflect.macros
package contexts

import scala.tools.nsc.reporters.StoreReporter

trait Parsers {
  self: Context =>
  import global._

  def parse(code: String) = {
    val sreporter = new StoreReporter()
    val oldReporter = global.reporter
    try {
      global.reporter = sreporter
      val parser = newUnitParser(new CompilationUnit(newSourceFile(code, "<macro>")))
      val tree = gen.mkTreeOrBlock(parser.parseStatsOrPackages())
      sreporter.infos.foreach {
        case sreporter.Info(pos, msg, sreporter.ERROR) => throw ParseException(pos, msg)
      }
      tree
    } finally global.reporter = oldReporter
  }
}

package scala.reflect.macros
package contexts

import scala.tools.nsc.reporters.StoreReporter

trait Parsers {
  self: Context =>
  import global._

  def parse(code: String) = {
    val sreporter = new StoreReporter()
    val oldReporter = global.reporter
    try {
      global.reporter = sreporter
      val parser = newUnitParser(new CompilationUnit(newSourceFile(code, "<macro>")))
      val tree = gen.mkTreeOrBlock(parser.parseStatsOrPackages())
      sreporter.infos.foreach {
        case sreporter.Info(pos, msg, sreporter.ERROR) => throw ParseException(pos, msg)
        case _ =>
      }
      tree
    } finally global.reporter = oldReporter
  }
}

Fix non-exhaustive match in macro code parsing

Before:

```
⚡ qscala -deprecation
Welcome to Scala 2.12.0-20160126-000825-1e302b76aa (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_66).
Type in expressions for evaluation. Or try :help.

scala> import reflect.macros.blackbox.Context; import language.experimental.macros
import reflect.macros.blackbox.Context
import language.experimental.macros

scala> def impl(c: Context) = {println(c.universe.showRaw(c.parse("val then = 0"))); c.literalUnit}; def m: Unit = macro impl;
<console>:13: warning: method literalUnit in trait ExprUtils is deprecated: Use quasiquotes instead
       def impl(c: Context) = {println(c.universe.showRaw(c.parse("val then = 0"))); c.literalUnit}; def m: Unit = macro impl;
                                                                                ^
impl: (c: scala.reflect.macros.blackbox.Context)c.Expr[Unit]
defined term macro m: Unit

scala> m
<console>:16: error: exception during macro expansion:
scala.MatchError: pos: source-<macro>,line-1,offset=4 then is now a reserved word; usage as an identifier is deprecated WARNING (of class scala.tools.nsc.reporters.StoreReporter$Info)
	at scala.reflect.macros.contexts.Parsers$class.scala$reflect$macros$contexts$Parsers$class$$$anonfun$1(Parsers.scala:17)
```


/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 water

/**
  * Support classes used to help with various H2O and Spark operations such as
  *

  *
Creating H2O Frames

  *
Adding files to H2O and Spark clusters

  *
Model creation

  *
Model import and export

  *
  */
package object support {

}

[SW-989] Improve Scala Doc API of the support classes - Fix Scala style


package cook.config.dsl.buildin

import cook.config.dsl.ConfigContext
import cook.ref.{TargetRef, NativeTargetRef}
import cook.target.{Target, NativeTarget, TargetResult, TargetResultFn, TargetBuildCmd, TargetMetaFn, TargetRunCmd}

trait DefineTarget {

  def defineTarget[T <: TargetResult](
    name: String,
    resultFn: TargetResultFn[T],
    buildCmd: TargetBuildCmd[T],
    inputMetaFn: TargetMetaFn[T],
    runCmd: Option[TargetRunCmd[T]] = None,
    deps: Seq[TargetRef] = Nil
  )(implicit context: ConfigContext): NativeTarget[T] = {
    checkTargetName(name)

    val targetRef = new NativeTargetRef(context.dir, name)
    val t = new NativeTarget[T](
      ref = targetRef,
      buildCmd = buildCmd,
      resultFn = resultFn,
      inputMetaFn = inputMetaFn,
      runCmd = runCmd,
      deps = deps
    )

    context addTarget t

    t
  }

  private def checkTargetName(name: String) {
    // TODO(timgreen):
  }
}

package cook.config.dsl.buildin

import cook.config.dsl.ConfigContext
import cook.ref.{TargetRef, NativeTargetRef}
import cook.target.{Target, NativeTarget, TargetResult, TargetResultFn, TargetBuildCmd, TargetMetaFn, TargetRunCmd}

trait DefineTarget {

  def defineTarget[T <: TargetResult](
    name: String,
    resultFn: TargetResultFn[T],
    buildCmd: TargetBuildCmd[T],
    inputMetaFn: TargetMetaFn[T],
    runCmd: Option[TargetRunCmd[T]] = None,
    deps: Seq[TargetRef] = Nil
  )(implicit context: ConfigContext): NativeTarget[T] = {
    require(resultFn    != null, "resultFn can not be null")
    require(buildCmd    != null, "buildCmd can not be null")
    require(inputMetaFn != null, "inputMetaFn can not be null")
    require(runCmd      != null, "runCmd can not be null")
    require(deps        != null, "deps can not be null")
    require(passTargetNameCheck(name), "invalid target name: " + name)

    val targetRef = new NativeTargetRef(context.dir, name)
    val t = new NativeTarget[T](
      ref = targetRef,
      buildCmd = buildCmd,
      resultFn = resultFn,
      inputMetaFn = inputMetaFn,
      runCmd = runCmd,
      deps = deps
    )

    context addTarget t

    t
  }

  private def passTargetNameCheck(name: String): Boolean = {
    name.matches("^[a-zA-Z0-9_]+$")
  }
}

Add require for defineTarget cmd.

Add require for defineTarget cmd.


/* ************************************************************** *
 *                                                                *
 * Copyright (c) 2005-2012, Kota Mizushima, All rights reserved.  *
 *                                                                *
 *                                                                *
 * This software is distributed under the modified BSD License.   *
 * ************************************************************** */
package onion.compiler

import java.util.ArrayList
import java.util.Iterator
import java.lang.Iterable

/**
 * A type safe import list.
 * @author Kota Mizushima
 *
 */
class ImportList extends Iterable[ImportItem] {
  private var items = new ArrayList[ImportItem]

  def add(item: ImportItem): Unit =  items.add(item)
  def get(index: Int): ImportItem = items.get(index)
  def getItems: Array[ImportItem] = items.toArray(new Array[ImportItem](0)).asInstanceOf[Array[ImportItem]]
  def size: Int =  items.size
  def iterator: Iterator[ImportItem] = items.iterator
}

/* ************************************************************** *
 *                                                                *
 * Copyright (c) 2005-2012, Kota Mizushima, All rights reserved.  *
 *                                                                *
 *                                                                *
 * This software is distributed under the modified BSD License.   *
 * ************************************************************** */
package onion.compiler

import scala.collection.mutable

/**
 * A type safe import list.
 * @author Kota Mizushima
 *
 */
class ImportList extends Iterable[ImportItem] {
  private var items = mutable.Buffer[ImportItem]()

  def add(item: ImportItem): Unit =  items += item
  def get(index: Int): ImportItem = items(index)
  def getItems: Array[ImportItem] = items.toArray
  override def size: Int = items.size
  def iterator: Iterator[ImportItem] = items.iterator
}

Use Scala's collection libraries instead of Java's them


package scalan.util

import java.io.{InputStreamReader, BufferedReader, File}

object ProcessUtil {
  def launch(workingDir: File, command: String*) {
    val builder = new ProcessBuilder(command: _*)
    val absoluteWorkingDir = workingDir.getAbsoluteFile
    builder.directory(absoluteWorkingDir)
    builder.inheritIO()
    val proc = builder.start()
    val exitCode = proc.waitFor()
    if (exitCode != 0) {
      val stream = proc.getInputStream
      try {
        val sb = new StringBuilder()
        val reader = new BufferedReader(new InputStreamReader(stream))
        var line: String = reader.readLine()
        while (line != null) {
          sb.append(line).append("\n")
          line = reader.readLine()
        }
        throw new RuntimeException(s"Executing '${command.mkString(" ")}' in directory $absoluteWorkingDir returned exit code $exitCode with following output:\n$sb")
      } finally {
        stream.close()
      }
    } else {
      // program executed successfully
    }
  }

}

package scalan.util

import java.io.{InputStreamReader, BufferedReader, File}

object ProcessUtil {
  def launch(workingDir: File, command: String*) {
    val absoluteWorkingDir = workingDir.getAbsoluteFile
    val builder = new ProcessBuilder(command: _*).
      directory(absoluteWorkingDir).
      redirectErrorStream(true)
    val proc = builder.start()
    val exitCode = proc.waitFor()
    val output = readOutput(proc)
    if (exitCode != 0) {
      throw new RuntimeException(s"Executing '${command.mkString(" ")}' in directory $absoluteWorkingDir returned exit code $exitCode with following output:\n$output")
    } else {
      Console.print(output)
    }
  }

  def readOutput(process: Process) = {
    val stream = process.getInputStream
    try {
      val sb = new StringBuilder()
      val reader = new BufferedReader(new InputStreamReader(stream))
      var line: String = reader.readLine()
      while (line != null) {
        sb.append(line).append("\n")
        line = reader.readLine()
      }
      sb.result()
    } finally {
      stream.close()
    }
  }
}

Fix process output not showing up in the exception


package uk.gov.gds.common.calendar

object RealCalendarApiClient extends CalendarApiClient {
  def getBankHolidays = CalendarHttpClient.get("")
}

package uk.gov.gds.common.calendar

import com.google.common.cache.CacheBuilder
import java.util.concurrent.TimeUnit
import com.google.common.cache.CacheLoader

object RealCalendarApiClient extends CalendarApiClient {

  private val cache = CacheBuilder
    .newBuilder()
    .expireAfterWrite(1, TimeUnit.DAYS)
    .build(new CacheLoader[String, String] {
      def load(key: String) = CalendarHttpClient.get("")
    })

  def getBankHolidays = cache.get("")
}

Add a guava cache for bank holiday details


package com.twitter.inject.app.internal

import com.google.inject.Key
import com.twitter.finatra.annotations.FlagImpl
import com.twitter.inject.{TwitterModule, Logging}

object FlagsModule {
  def create(flags: Seq[com.twitter.app.Flag[_]]) = {
    val flagsMap = (for (flag <- flags) yield {
      flag.name -> flag()
    }).toMap

    new FlagsModule(flagsMap)
  }
}

//TODO: Use type information in Flag instead of hardcoding java.lang.String
class FlagsModule(
  flagsMap: Map[String, Any])
  extends TwitterModule
  with Logging {

  override def configure() {
    for ((flagName, value) <- flagsMap) {
      debug("Binding flag: " + flagName + " = " + value)
      val key = Key.get(classOf[java.lang.String], new FlagImpl(flagName))
      binder.bind(key).toInstance(value.toString)
    }
  }
}

package com.twitter.inject.app.internal

import com.google.inject.Key
import com.twitter.finatra.annotations.FlagImpl
import com.twitter.inject.{TwitterModule, Logging}

object FlagsModule {
  def create(flags: Seq[com.twitter.app.Flag[_]]) = {
    val flagsMap = (for (flag <- flags) yield {
      flag.name -> flag.getWithDefault
    }).toMap

    new FlagsModule(flagsMap)
  }
}

//TODO: Use type information in Flag instead of hardcoding java.lang.String
class FlagsModule(
  flagsMap: Map[String, Option[Any]])
  extends TwitterModule
  with Logging {

  override def configure() {
    for ((flagName, valueOpt) <- flagsMap) {
      valueOpt match {
        case Some(value) =>
          debug("Binding flag: " + flagName + " = " + value)
          val key = Key.get(classOf[java.lang.String], new FlagImpl(flagName))
          binder.bind(key).toInstance(value.toString)
        case None =>
          warn("flag without default: " + flagName + " has an unspecified value and is not eligible for @Flag injection")
      }
    }
  }
}

Fix flagNotFound exception if flag doesn't have default value

RB_ID=661070


package io.reactors
package protocol

trait LinkProtocols {
  case class Link[T](channel: Channel[T], available: Signal[Boolean])

  object Link {
  }
}

package io.reactors
package protocol

trait LinkProtocols {
  case class Link[T](
    channel: Channel[T],
    available: Signal[Boolean],
    subscription: Subscription
  )
}

Add subscription to link protocols.

Add subscription to link protocols.


package textapp.server

import scala.io.Source
import java.io.InputStream
import java.net.URLDecoder

class FormDecoder(inputStream: InputStream) {
  private val source = Source.fromInputStream(inputStream)
  private val sourceAsString = source.getLines.toList.foldLeft("")(_+_)
  private val paramArray = sourceAsString.split("&").filter(_ != "").map(_.split("=")).map { kvPair =>
    if (kvPair.size != 2) throw new RuntimeException("Invalid key-value pair in '%s'".format(kvPair.mkString("=")))
    val (encodedKey, encodedValue) = (kvPair(0), kvPair(1))
    val key = URLDecoder.decode(encodedKey)
    val value = URLDecoder.decode(encodedValue)
    (key, value)
  }
  val params = Map(paramArray: _*)
}

package textapp.server

import scala.io.Source
import java.io.InputStream
import java.net.URLDecoder

class FormDecoder(inputStream: InputStream) {
  private val source = Source.fromInputStream(inputStream)
  private val sourceAsString = source.getLines.toList.foldLeft("")(_+_)
  private val paramArray = sourceAsString.split("&").filter(_ != "").map(_.split("=")).map { kvPair =>
    if (kvPair.size != 2) throw new RuntimeException("Invalid key-value pair in '%s'".format(kvPair.mkString("=")))
    val (encodedKey, encodedValue) = (kvPair(0), kvPair(1))
    val key = URLDecoder.decode(encodedKey, "UTF-8")
    val value = URLDecoder.decode(encodedValue, "UTF-8")
    (key, value)
  }
  val params = Map(paramArray: _*)
}

Remove call to deprecated decode by giving explicit encoding

Signed-off-by: Sami Rosendahl <b33c757bb777642ab0d59c699f8d5782929a814f@reaktor.fi>
Signed-off-by: Antti Mattila <422fa99ecc9af171a83eb3d69d51885324be22a3@reaktor.fi>
Acked-by: Aki Saarinen <2c8035bb80cf98a391872dcbe797b269d759f6d9@reaktor.fi>


package org.mdoc.rendering.service

import org.http4s.{ Request, Uri }
import org.http4s.dsl._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object ServiceSpec extends Properties("Service") {

  property("showRequest") = forAll { (s: String) =>
    Service.showRequest(Request(uri = Uri(path = s))) ?= s"GET $s"
  }

  property("route: /") = secure {
    Service.route.run(Request()).run.status ?= NotFound
  }

  property("route: /version") = secure {
    Service.route.run(Request(uri = Uri(path = "/version"))).run.status ?= Ok
  }
}

package org.mdoc.rendering.service

import org.http4s.{ Request, Uri }
import org.http4s.dsl._
import org.scalacheck.Prop._
import org.scalacheck.Properties

object ServiceSpec extends Properties("Service") {

  property("showRequest") = forAll { (s: String) =>
    Service.showRequest(Request(uri = Uri(path = s))) ?= s"GET $s"
  }

  property("route: /") = secure {
    Service.route.run(Request()).run.status ?= NotFound
  }

  property("route: /render/pdf/test.pdf") = secure {
    val req = Request(uri = Uri(path = "/render/pdf/test.pdf"))
    Service.route.run(req).run.status ?= BadRequest
  }

  property("route: /version") = secure {
    Service.route.run(Request(uri = Uri(path = "/version"))).run.status ?= Ok
  }
}

Test /render without specifying an URL

Test /render without specifying an URL


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

package org.http4s

import cats._

final case class ContextResponse[F[_], A](context: A, response: Response[F]) {
  def mapContext[B](f: A => B): ContextResponse[F, B] =
    ContextResponse(f(context), response)

  def mapK[G[_]](fk: F ~> G): ContextResponse[G, A] =
    ContextResponse(context, response.mapK(fk))
}

object ContextResponse{}

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

package org.http4s

import cats._

final case class ContextResponse[F[_], A](context: A, response: Response[F]) {
  def mapContext[B](f: A => B): ContextResponse[F, B] =
    ContextResponse(f(context), response)

  def mapK[G[_]](fk: F ~> G): ContextResponse[G, A] =
    ContextResponse(context, response.mapK(fk))
}

// Include to avoid binary compatibility issues with the apply method if/when
// we ever need a companion object in the future.
object ContextResponse {}

Add Comment About Why Companion Object Is Empty


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.42"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.3",
      "com.ning" % "async-http-client" % "1.9.38",
      "org.scalatest" %% "scalatest" % "2.2.6" % 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 com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.43"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.3",
      "com.ning" % "async-http-client" % "1.9.38",
      "org.scalatest" %% "scalatest" % "2.2.6" % 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.0.43


addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject"      % "0.6.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "0.6.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"                   % "0.6.23")
addSbtPlugin("org.scala-native"   % "sbt-scala-native"              % "0.3.7")

addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.9.0")

addSbtPlugin("com.thesamet" % "sbt-protoc" % "0.99.25")

libraryDependencies += "com.thesamet.scalapb" %% "compilerplugin" % "0.9.0"

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject"      % "0.6.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "0.6.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"                   % "0.6.23")
addSbtPlugin("org.scala-native"   % "sbt-scala-native"              % "0.3.7")

addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.9.0")

addSbtPlugin("com.thesamet" % "sbt-protoc" % "0.99.25")

libraryDependencies += "com.thesamet.scalapb" %% "compilerplugin" % "0.8.4"

Revert example project to older scalapb version


package spire.macros

object compat {

  type Context = scala.reflect.macros.Context

  def freshTermName[C <: Context](c: C)(s: String) =
    c.universe.newTermName(c.fresh(s))

  def termName[C <: Context](c: C)(s: String) =
    c.universe.newTermName(s)

  def typeCheck[C <: Context](c: C)(t: c.Tree) =
    c.typeCheck(t)

  def resetLocalAttrs[C <: Context](c: C)(t: c.Tree) =
    c.resetLocalAttrs(t)

  def setOrig[C <: Context](c: C)(tt: c.TypeTree, t: c.Tree) =
    tt.setOriginal(t)
}

package spire.macros

object compat {

  type Context = scala.reflect.macros.Context

  def freshTermName[C <: Context](c: C)(s: String) =
    c.universe.newTermName(c.fresh(s))

  def termName[C <: Context](c: C)(s: String) =
    c.universe.newTermName(s)

  def typeCheck[C <: Context](c: C)(t: c.Tree) =
    c.typeCheck(t)

  def resetLocalAttrs[C <: Context](c: C)(t: c.Tree) =
    c.resetLocalAttrs(t)

  def setOrig[C <: Context](c: C)(tt: c.universe.TypeTree, t: c.Tree) =
    tt.setOriginal(t)
}

Fix issue with compiling under 2.10.

Fix issue with compiling under 2.10.


name := "skill"

version := "0.3"

scalaVersion := "2.11.8"

javacOptions ++= Seq("-encoding", "UTF-8")

compileOrder := CompileOrder.JavaThenScala

libraryDependencies ++= Seq(
	"junit" % "junit" % "4.12" % "test",
	"org.scalatest" % "scalatest_2.11" % "2.2.4" % "test"
)

exportJars := true

mainClass := Some("de.ust.skill.main.CommandLine")

(testOptions in Test) += Tests.Argument(TestFrameworks.ScalaTest, "-u", "target/tests")

libraryDependencies += "commons-lang" % "commons-lang" % "2.6"

libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.4"

libraryDependencies += "com.github.scopt" %% "scopt" % "3.5.0"

libraryDependencies += "org.json" %% "json" % "20160810"

buildInfoSettings

sourceGenerators in Compile <+= buildInfo

buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion)

buildInfoPackage := "de.ust.skill"

assemblyJarName in assembly := "skill.jar"
assemblyMergeStrategy in assembly := {
  case PathList("META-INF", "MANIFEST.MF") => MergeStrategy.discard
  case _ => MergeStrategy.first
}
test in assembly := {}

name := "skill"

version := "0.3"

scalaVersion := "2.11.8"

javacOptions ++= Seq("-encoding", "UTF-8")

compileOrder := CompileOrder.JavaThenScala

libraryDependencies ++= Seq(
	"junit" % "junit" % "4.12" % "test",
	"org.scalatest" % "scalatest_2.11" % "2.2.4" % "test"
)

exportJars := true

mainClass := Some("de.ust.skill.main.CommandLine")

(testOptions in Test) += Tests.Argument(TestFrameworks.ScalaTest, "-u", "target/tests")

libraryDependencies += "commons-lang" % "commons-lang" % "2.6"

libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.4"

libraryDependencies += "com.github.scopt" %% "scopt" % "3.5.0"

libraryDependencies += "org.json" % "json" % "20160810"

buildInfoSettings

sourceGenerators in Compile <+= buildInfo

buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion)

buildInfoPackage := "de.ust.skill"

assemblyJarName in assembly := "skill.jar"
assemblyMergeStrategy in assembly := {
  case PathList("META-INF", "MANIFEST.MF") => MergeStrategy.discard
  case _ => MergeStrategy.first
}
test in assembly := {}

Fix typo in declaration of org.json dependency


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.1"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.1.0" % Test,
      compilerPlugin("com.github.ghik" %% "silencer-plugin" % "1.4.4" cross CrossVersion.full),
      "com.github.ghik" %% "silencer-lib" % "1.4.4" % Provided cross CrossVersion.full,
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

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")
  }
}

// silence all warnings on autogenerated files
flowGeneratedFiles ++= Seq(
  "src/main/scala/io/flow/generated/.*".r,
)

// Make sure you only exclude warnings for the project directories, i.e. make builds reproducible
scalacOptions += s"-P:silencer:sourceRoots=${baseDirectory.value.getCanonicalPath}"

version := "0.2.37"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.1"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.1.0" % Test,
      compilerPlugin("com.github.ghik" %% "silencer-plugin" % "1.4.4" cross CrossVersion.full),
      "com.github.ghik" %% "silencer-lib" % "1.4.4" % Provided cross CrossVersion.full,
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

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")
  }
}

// silence all warnings on autogenerated files
flowGeneratedFiles ++= Seq(
  "src/main/scala/io/flow/generated/.*".r,
)

// Make sure you only exclude warnings for the project directories, i.e. make builds reproducible
scalacOptions += s"-P:silencer:sourceRoots=${baseDirectory.value.getCanonicalPath}"

version := "0.2.38"

autocommit: Update configuration to record version 0.2.38


import com.github.retronym.SbtOneJar._
import sbt.Credentials

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.6"

version := "0.1.90"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "io.flow" %% "lib-util" % "0.1.0",
      "io.flow" %% "apibuilder-validation" % "0.2.1",
      "com.typesafe.play" %% "play-json" % "2.6.10",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    )
  )

resolvers += "Artifactory" at "https://flow.jfrog.io/flow/libs-release/"

credentials += Credentials(
  "Artifactory Realm",
  "flow.jfrog.io",
  System.getenv("ARTIFACTORY_USERNAME"),
  System.getenv("ARTIFACTORY_PASSWORD")
)

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._
import sbt.Credentials

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.6"

version := "0.1.91"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "io.flow" %% "lib-util" % "0.1.0",
      "io.flow" %% "apibuilder-validation" % "0.2.1",
      "com.typesafe.play" %% "play-json" % "2.6.10",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    )
  )

resolvers += "Artifactory" at "https://flow.jfrog.io/flow/libs-release/"

credentials += Credentials(
  "Artifactory Realm",
  "flow.jfrog.io",
  System.getenv("ARTIFACTORY_USERNAME"),
  System.getenv("ARTIFACTORY_PASSWORD")
)

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.91


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.6"

lazy val allScalacOptions = Seq(
  "-feature",
  "-Xfatal-warnings",
  "-unchecked",
  "-Xcheckinit",
  "-Xlint:adapted-args",
  "-Ypatmat-exhaust-depth", "100", // Fixes: Exhaustivity analysis reached max recursion depth, not all missing cases are reported.
  "-Wconf:src=generated/.*:silent",
  "-Wconf:src=target/.*:silent", // silence the unused imports errors generated by the Play Routes
)

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.2.12" % Test,
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

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")
  }
}

scalacOptions ++= allScalacOptions

version := "0.3.4"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.6"

lazy val allScalacOptions = Seq(
  "-feature",
  "-Xfatal-warnings",
  "-unchecked",
  "-Xcheckinit",
  "-Xlint:adapted-args",
  "-Ypatmat-exhaust-depth", "100", // Fixes: Exhaustivity analysis reached max recursion depth, not all missing cases are reported.
  "-Wconf:src=generated/.*:silent",
  "-Wconf:src=target/.*:silent", // silence the unused imports errors generated by the Play Routes
)

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.2.12" % Test,
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

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")
  }
}

scalacOptions ++= allScalacOptions

version := "0.3.5"

autocommit: Update configuration to record version 0.3.5