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

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

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

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

Set project version to 0.0.15-BETA

Set project version to 0.0.15-BETA


addSbtPlugin("com.typesafe.play" % "sbt-plugin"   % "2.8.5")
addSbtPlugin("org.scalameta"     % "sbt-scalafmt" % "2.4.2")

addSbtPlugin("com.typesafe.play" % "sbt-plugin"   % "2.8.6")
addSbtPlugin("org.scalameta"     % "sbt-scalafmt" % "2.4.2")

Update play-akka-http-server, play-docs, ... to 2.8.6


resolvers ++= Seq(
  Classpaths.typesafeReleases,
  Classpaths.sbtPluginReleases,
  "jgit-repo" at "http://download.eclipse.org/jgit/maven",
  Resolver.url("scoverage-bintray", url("https://dl.bintray.com/sksamuel/sbt-plugins/"))(Resolver.ivyStylePatterns),
  Resolver.sonatypeRepo("snapshots")
)

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.2.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-pgp" % "0.8.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.2")
addSbtPlugin("com.eed3si9n" % "sbt-unidoc" % "0.3.3")
addSbtPlugin("org.scalastyle" % "scalastyle-sbt-plugin" % "0.8.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.2.6")

resolvers ++= Seq(
  Classpaths.typesafeReleases,
  Classpaths.sbtPluginReleases,
  "jgit-repo" at "http://download.eclipse.org/jgit/maven",
  Resolver.url("scoverage-bintray", url("https://dl.bintray.com/sksamuel/sbt-plugins/"))(Resolver.ivyStylePatterns),
  Resolver.sonatypeRepo("snapshots")
)

// sbt-scoverage 1.3.5 has a bug that results in 2.10 tests not being run.
// See https://github.com/scoverage/sbt-scoverage/issues/146
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.2.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-pgp" % "0.8.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.2")
addSbtPlugin("com.eed3si9n" % "sbt-unidoc" % "0.3.3")
addSbtPlugin("org.scalastyle" % "scalastyle-sbt-plugin" % "0.8.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.2.6")

Add note about sbt-scoverage version

Add note about sbt-scoverage version


addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject"      % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.1.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"                   % "1.7.0")
addSbtPlugin("org.scala-native"   % "sbt-scala-native"              % "0.4.0")

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.10")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.8.2")

addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "1.0.1")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject"      % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.1.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"                   % "1.7.1")
addSbtPlugin("org.scala-native"   % "sbt-scala-native"              % "0.4.0")

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.10")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.8.2")

addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "1.0.1")

Update sbt-scalajs, scalajs-compiler, ... to 1.7.1


// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.8.13")

// For removing warts, maintain code quality
addSbtPlugin("org.wartremover" %% "sbt-wartremover" % "2.4.19")

// The sbt native packager - needed for docker builds
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.9")

// For code coverage test
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.3")

// For checkstyle
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")

// For formatting Scala source code
addSbtPlugin("com.lucidchart" % "sbt-scalafmt" % "1.16")

// Build fat JAR file
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "1.2.0")

// Check vulnerabilities in JAR's
addSbtPlugin("net.vonbuchholtz" % "sbt-dependency-check" % "4.0.0")

// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.8.14")

// For removing warts, maintain code quality
addSbtPlugin("org.wartremover" %% "sbt-wartremover" % "2.4.19")

// The sbt native packager - needed for docker builds
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.9")

// For code coverage test
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.9.3")

// For checkstyle
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")

// For formatting Scala source code
addSbtPlugin("com.lucidchart" % "sbt-scalafmt" % "1.16")

// Build fat JAR file
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "1.2.0")

// Check vulnerabilities in JAR's
addSbtPlugin("net.vonbuchholtz" % "sbt-dependency-check" % "4.0.0")

Update filters-helpers, play-ahc-ws, ... to 2.8.14


latestVersion in ThisBuild := "0.9.3"

bincompatVersions in ThisBuild := Set(
  "0.9.0",
  "0.9.1",
  "0.9.2",
  "0.9.3"
)

unreleasedModules in ThisBuild := Set(
  // Example:
  // "refined-eval"
)

latestVersion in ThisBuild := "0.9.3"

bincompatVersions in ThisBuild := Set(
  "0.9.3"
)

unreleasedModules in ThisBuild := Set(
  // Example:
  // "refined-eval"
)

Use 0.9.3 as new baseline for bincompat

Use 0.9.3 as new baseline for bincompat

This is required because 0.9.3 introduced a new module:

sbt.librarymanagement.ResolveException: unresolved dependency:
eu.timepit#refined-scalacheck_1.13_2.12;0.9.0: not found


package db

import org.scalatest.FlatSpec
import org.junit.Assert._
import java.util.UUID

class OrganizationDaoSpec extends FlatSpec {

  it should "create" in {
    assertEquals(Util.gilt.name, "Gilt")
    assertEquals(Util.gilt.key, "gilt")
  }

  it should "find by guid" in {
    assertEquals(OrganizationDao.findByGuid(Util.gilt.guid).get.guid, Util.gilt.guid)
  }

  it should "findAll by key" in {
    assertEquals(OrganizationDao.findAll(key = Some(Util.gilt.key)).head.key, Util.gilt.key)
  }

}

package db

import org.scalatest.{ FunSpec, Matchers }
import org.junit.Assert._
import java.util.UUID

class OrganizationDaoSpec extends FunSpec with Matchers {

  it("create") {
    assertEquals(Util.gilt.name, "Gilt")
    assertEquals(Util.gilt.key, "gilt")
  }

  it("user that creates org should be an admin") {
    val user = Util.upsertUser(UUID.randomUUID.toString + "@gilttest.com")
    val name = UUID.randomUUID.toString
    val org = OrganizationDao.createWithAdministrator(user, name)
    org.name should be(name)

    Membership.isUserAdmin(user, org) should be(true)
  }

  it("find by guid") {
    assertEquals(OrganizationDao.findByGuid(Util.gilt.guid).get.guid, Util.gilt.guid)
  }

  it("findAll by key") {
    assertEquals(OrganizationDao.findAll(key = Some(Util.gilt.key)).head.key, Util.gilt.key)
  }

}

Add test to ensure that user is admin of an org created


package io.mediachain.util

import cats.data.Xor
import gremlin.scala._
import io.mediachain.GraphError
import io.mediachain.GraphError.TransactionFailed

object GremlinUtils {

  def withTransaction[T](graph: Graph)(f: => T): Xor[GraphError, T] = {
    if (!graph.tx.isOpen) {
      graph.tx.open()
    }
    Xor.catchNonFatal {
      f
    }.leftMap(ex => {
      graph.tx.rollback()
      TransactionFailed(ex)
    })
      .map(result => {
        graph.tx.commit()
        result
      })
  }

}

package io.mediachain.util

import cats.data.Xor
import gremlin.scala._
import io.mediachain.GraphError
import io.mediachain.GraphError.TransactionFailed

object GremlinUtils {

  def withTransaction[T](graph: Graph)(f: => T): Xor[GraphError, T] = {
    if (!graph.tx.isOpen) graph.tx.open()

    val result: Xor[GraphError, T] =
      Xor.catchNonFatal(f).leftMap(TransactionFailed)

    result match {
      case Xor.Left(_) => graph.tx.rollback()
      case _ => graph.tx.commit()
    }

    result
  }

  def withTransactionXor[T](graph: Graph)(f: => Xor[GraphError, T])
  : Xor[GraphError, T] = {
    if (!graph.tx.isOpen) graph.tx.open()

    val result: Xor[GraphError, T] =
      Xor.catchNonFatal(f)
        .leftMap(TransactionFailed)
        .flatMap(res => res)

    result match {
      case Xor.Left(er) => graph.tx.rollback()
      case _ => graph.tx.commit()
    }

    result
  }
}

Add withTransactionXor helper to rollback on GraphError


package lib

case class ExampleService(
  organizationKey: String,
  applicationKey: String,
  version: String = "latest"
) {

  val label = s"$organizationKey/$applicationKey"

  val docsUrl = if (version == "latest") {
    s"/$organizationKey/$applicationKey"
  } else {
    s"/$organizationKey/$applicationKey/$version"
  }

  val originalJsonUrl = s"/$organizationKey/$applicationKey/$version/original.json"
  val serviceJsonUrl = s"/$organizationKey/$applicationKey/$version/service.json"

}

object Util {

  val Host = Config.requiredString("apidoc.www.host")

  val AddApplicationText = "Add Application"
  val OrgDetailsText = "Org Details"
  val ServiceJsonText = "service.json"

  val ApidocExample = ExampleService("gilt", "apidoc-api")
  val ApidocExampleWithVersionNumber = ExampleService("gilt", "apidoc-api", Config.requiredString("git.version"))
  val ApidocGeneratorExample = ExampleService("gilt", "apidoc-generator")
  val ApidocSpecExample = ExampleService("gilt", "apidoc-spec")
  val Examples = Seq(ApidocExample, ApidocGeneratorExample, ApidocSpecExample)

  val ApidocCliGitHubUrl = "https://github.com/gilt/apidoc-cli"
  val GitHubUrl = "https://github.com/gilt/apidoc"
  val GeneratorGitHubUrl = "https://github.com/gilt/apidoc-generator"

  def fullUrl(stub: String): String = s"$Host$stub"

}

package lib

case class ExampleService(
  organizationKey: String,
  applicationKey: String,
  version: String = "latest"
) {

  val label = s"$organizationKey/$applicationKey"

  val docsUrl = if (version == "latest") {
    s"/$organizationKey/$applicationKey"
  } else {
    s"/$organizationKey/$applicationKey/$version"
  }

  val originalJsonUrl = s"/$organizationKey/$applicationKey/$version/original"
  val serviceJsonUrl = s"/$organizationKey/$applicationKey/$version/service.json"

}

object Util {

  val Host = Config.requiredString("apidoc.www.host")

  val AddApplicationText = "Add Application"
  val OrgDetailsText = "Org Details"
  val ServiceJsonText = "service.json"

  val ApidocExample = ExampleService("gilt", "apidoc-api")
  val ApidocExampleWithVersionNumber = ExampleService("gilt", "apidoc-api", Config.requiredString("git.version"))
  val ApidocGeneratorExample = ExampleService("gilt", "apidoc-generator")
  val ApidocSpecExample = ExampleService("gilt", "apidoc-spec")
  val Examples = Seq(ApidocExample, ApidocGeneratorExample, ApidocSpecExample)

  val ApidocCliGitHubUrl = "https://github.com/gilt/apidoc-cli"
  val GitHubUrl = "https://github.com/gilt/apidoc"
  val GeneratorGitHubUrl = "https://github.com/gilt/apidoc-generator"

  def fullUrl(stub: String): String = s"$Host$stub"

}

Fix download link for api.json examples

Fix download link for api.json examples


/*
 * Copyright 2017 Daniel Urban
 *
 * 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 io.sigs.seals

package object refined
  extends Refinements
  with ReifiedInstances

/*
 * Copyright 2017 Daniel Urban
 *
 * 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 io.sigs.seals

package object refined extends AllInstances

trait AllInstances
  extends refined.Refinements
  with refined.ReifiedInstances

Add AllInstances trait in the refined module


lazy val root = (project in file(".")).enablePlugins(UniversalPlugin)

net.virtualvoid.sbt.graph.Plugin.graphSettings

name := "oxyjen"

version := "0.1"

scalaVersion := "2.11.4"

libraryDependencies ++= Seq(
  "ch.qos.logback" % "logback-classic" % "1.0.13",
  "commons-io" % "commons-io" % "2.4",
  "org.apache.ivy" % "ivy" % "2.3.0",
  "net.lingala.zip4j" % "zip4j" % "1.3.2",
  "net.databinder.dispatch" %% "dispatch-core" % "0.11.2",
  "org.json4s" %% "json4s-native" % "3.2.11" exclude("org.scala-lang", "scala-compiler"),
  "org.scalatest" %% "scalatest" % "2.2.1" % "test")

mappings in Universal <+= (packageBin in Compile) map { jar =>
  jar -> "oxyjen.jar"
}

mappings in Universal <++= (fullClasspath in Compile) map { jars =>
  for (jar <- jars) yield
    jar.data -> ("lib/" + jar.data.getName)
}

lazy val `oxyjen-cli` = (project in file(".")).enablePlugins(UniversalPlugin)

net.virtualvoid.sbt.graph.Plugin.graphSettings

name := "oxyjen"

version := "0.1"

scalaVersion := "2.11.4"

libraryDependencies ++= Seq(
  "ch.qos.logback" % "logback-classic" % "1.0.13",
  "commons-io" % "commons-io" % "2.4",
  "org.apache.ivy" % "ivy" % "2.3.0",
  "net.lingala.zip4j" % "zip4j" % "1.3.2",
  "net.databinder.dispatch" %% "dispatch-core" % "0.11.2",
  "org.json4s" %% "json4s-native" % "3.2.11" exclude("org.scala-lang", "scala-compiler"),
  "org.scalatest" %% "scalatest" % "2.2.1" % "test")

mappings in Universal <+= (packageBin in Compile) map { jar =>
  jar -> "oxyjen.jar"
}

mappings in Universal <++= (fullClasspath in Compile) map { jars =>
  for (jar <- jars) yield
    jar.data -> ("lib/" + jar.data.getName)
}

Change project name variable in sbt script to `oxyjen-cli` to prevent creation of weird modules by Intellij.


import sbt._
import com.twitter.sbt._

class KilldeerProject(info: ProjectInfo) extends StandardProject(info) {
  val codehaus = "codehaus" at "http://repository.codehaus.org/"

  val specs = "org.scala-tools.testing" % "specs_2.8.0" % "1.6.5"
  val jetty = "org.eclipse.jetty" % "jetty-http" % "7.1.5.v20100705"
  val jettyServer = "org.eclipse.jetty" % "jetty-server" % "7.1.5.v20100705"
  val jettyServlet = "org.eclipse.jetty" % "jetty-servlet" % "7.1.5.v20100705"
  val jettyCont = "org.eclipse.jetty" % "jetty-continuation" % "7.1.5.v20100705"

  // Renaming it to 1.2.0a so it doesn't read the broken POM file from the internet.
  val colt = "colt" % "colt" % "1.2.0a"

  override def mainClass = Some("com.twitter.killdeer.Killdeer")
}

import sbt._
import com.twitter.sbt._

class KilldeerProject(info: ProjectInfo) extends StandardProject(info) {
  val codehaus = "codehaus" at "http://repository.codehaus.org/"

  val specs = "org.scala-tools.testing" % "specs_2.8.0" % "1.6.5"
  val jetty = "org.eclipse.jetty" % "jetty-http" % "7.1.5.v20100705"
  val jettyServer = "org.eclipse.jetty" % "jetty-server" % "7.1.5.v20100705"
  val jettyServlet = "org.eclipse.jetty" % "jetty-servlet" % "7.1.5.v20100705"
  val jettyCont = "org.eclipse.jetty" % "jetty-continuation" % "7.1.5.v20100705"

  val apacheCommonsMath = "org.apache.commons" % "commons-math" % "2.1"

  override def mainClass = Some("com.twitter.killdeer.Killdeer")
}

Swap out colt library for the apache commons math package.


// The Play plugin
addSbtPlugin("com.typesafe.play" %% "sbt-plugin" % "2.8.0")

// play swagger plugin
addSbtPlugin("com.iheart" % "sbt-play-swagger" % "0.10.1-SNAPSHOT")

// The Play plugin
addSbtPlugin("com.typesafe.play" %% "sbt-plugin" % "2.8.0")

// play swagger plugin
addSbtPlugin("com.iheart" % "sbt-play-swagger" % "0.10.3-SNAPSHOT")

Update example project plugin version to 0.10.3-SNAPSHOT


package hyperion.ws

import akka.actor.{Actor, ActorLogging, ActorRef}

import hyperion.MessageDistributor.RegisterReceiver
import hyperion.p1.TelegramReceived

/**
  * Actor that forwards telegrams to a WebSocket connection
  *
  * @param source Ref to an Actor that publishes the telegrams to a [[Stream]].
  * @param messageDistributor Ref to the Actor that distributes messages.
  */
class ActualValuesHandlerActor(val source: ActorRef, val messageDistributor: ActorRef) extends Actor with ActorLogging {
  override def preStart(): Unit = {
    log.info("Registering for live updates")
    messageDistributor ! RegisterReceiver
  }

  override def receive: Receive = {
    case tr: TelegramReceived =>
      source ! tr
    case a: Any =>
      log.debug(s"Ignoring $a")
  }
}

package hyperion.ws

import akka.actor.{Actor, ActorLogging, ActorRef}

import hyperion.MessageDistributor.RegisterReceiver
import hyperion.p1.TelegramReceived

/**
  * Actor that forwards telegrams to a WebSocket connection
  *
  * @param source Ref to an Actor that publishes the telegrams to a [[Stream]].
  * @param messageDistributor Ref to the Actor that distributes messages.
  */
class ActualValuesHandlerActor(val source: ActorRef, val messageDistributor: ActorRef) extends Actor with ActorLogging {
  override def preStart(): Unit = {
    log.debug("Registering for live updates")
    messageDistributor ! RegisterReceiver
  }

  override def receive: Receive = {
    case tr: TelegramReceived =>
      source ! tr
    case a: Any =>
      log.debug(s"Ignoring $a")
  }
}

Reduce log level to debug, as this is expected behaviour


import org.scalatest.{Matchers, FlatSpec}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

import me.hawkweisman.util.collection.RepeatableSeq

/**
 * Created by hawk on 5/20/15.
 */
class CollectionSpec extends FlatSpec with GeneratorDrivenPropertyChecks with Matchers {

  "A RepeatableSeq" should "repeat an arbitrary sequence of integers to an arbitrary length" in {
    forAll { (s: Seq[Int], length: Int) =>
      val expected = for {
        i <- 0 to length
        e <- s (i % s.length)
      } yield e

      s take length shouldEqual expected
    }
  }

}

import org.scalatest.{Matchers, FlatSpec}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

import me.hawkweisman.util.collection.RepeatableSeq

/**
 * Created by hawk on 5/20/15.
 */
class CollectionSpec extends FlatSpec with GeneratorDrivenPropertyChecks with Matchers {

  "A RepeatableSeq" should "repeat an arbitrary sequence of integers to an arbitrary length" in {
    forAll { (s: Seq[Int]) =>
      whenever (s.nonEmpty && s.length <= 50) {  // 50 seems reasonable?
        val expected = for {
          i <- 0 to 49
        } yield s (i % s.length)

        s.repeat.take(50) shouldEqual expected.toStream
      }
    }
  }

}

Add a spec for Collection

Add a spec for Collection


package a
package b

object Givens

  given extension [A](any: A)
    def sayHello = s"Hello, I am $any"

  given extension [B](any: B)
    def sayGoodbye = s"Goodbye, from $any"
    def saySoLong = s"So Long, from $any"

  val hello1 = 1.sayHello
  val goodbye1 = 1.sayGoodbye
  val soLong1 = 1.saySoLong

  trait Monoid[A]
    def empty: A
    def (x: A).combine(y: A): A

  given Monoid[String]
    def empty = ""
    def (x: String).combine(y: String) = x + y

  inline given int2String: Conversion[Int, String] = _.toString

  def foo[A](using A: Monoid[A]): A = A.combine(A.empty)(A.empty)

package a
package b

object Givens:

  extension on [A](any: A):
    def sayHello = s"Hello, I am $any"

  extension on [B](any: B):
    def sayGoodbye = s"Goodbye, from $any"
    def saySoLong = s"So Long, from $any"

  val hello1 = 1.sayHello
  val goodbye1 = 1.sayGoodbye
  val soLong1 = 1.saySoLong

  trait Monoid[A]:
    def empty: A
    def (x: A).combine(y: A): A

  given Monoid[String]:
    def empty = ""
    def (x: String).combine(y: String) = x + y

  inline given int2String: Conversion[Int, String] = _.toString

  def foo[A](using A: Monoid[A]): A = A.combine(A.empty)(A.empty)

Fix more files to use new indent syntax

Fix more files to use new indent syntax


object Solution {

  def maxProduct(s: String): Int = {

    val n = s.size
    (0 to n / 2).map(x => largestPalSeq(0, x) * largestPalSeq(x + 1, n - 1)).max
  }

  def main(args: Array[String]) {

    val s = readLine
    println(maxProduct(s))
  }
}

object Solution {

  def maxProduct(s: String): Int = {
    val n = s.size
    // longest palindromic subsequences count.
    val lpc = (0 until n).map(x => Array.fill(n)(0)).toArray

    for (i <- 0 until n) lpc(i)(i) = 1 // 'x' is 1 size palindromic

    for {
      cl <- 2 to n
      i <- 0 until n -cl + 1
    } {
      val j = i + cl - 1
      if (s(i) == s(j)) lpc(i)(j) = lpc(i + 1)(j - 1) + 2
      else lpc(i)(j) = lpc(i)(j - 1) max lpc(i + 1)(j)
    }

    //println(lpc.map(_.mkString(" ")).mkString("\n"))
    // we can get the lpc now
    (0 until n - 1).map(x => lpc(0)(x) * lpc(x + 1)(n - 1)).max
  }

  def main(args: Array[String]) {

    val s = readLine
    println(maxProduct(s))
  }
}

Add solution to problem Play with words. The main idea of this algorithms is to get any longest palindromic subsequences count between string[i : j + 1]


package ingraph.ire

import hu.bme.mit.ire.datatypes.Tuple
import hu.bme.mit.ire.{PullTupleCreator, TransactionFactory, TupleCreator}
import ingraph.compiler.FPlanParser

class IngraphOneTimeAdapter(
    val querySpecification: String,
    val queryName: String,
    val indexer: Indexer = new Indexer()
  ) {

  val plan = FPlanParser.parse(querySpecification)
  val engine = EngineFactory.createQueryEngine(plan, indexer)

  val transactionFactory = new TransactionFactory(16)
  transactionFactory.subscribe(engine.inputLookup)
  val transaction = transactionFactory.newBatchTransaction()
  new PullTupleCreator(
    engine.vertexConverters.values.flatten.toVector.distinct,
    engine.edgeConverters.values.flatten.toVector.distinct,
    indexer, transaction, LongIdParser)

  def terminate(): Iterable[Tuple] = {
    transaction.close()
    engine.getResults()
  }
}

package ingraph.ire

import hu.bme.mit.ire.datatypes.Tuple
import hu.bme.mit.ire.{PullTupleCreator, TransactionFactory, TupleCreator}
import ingraph.compiler.FPlanParser

class IngraphOneTimeAdapter(
    val querySpecification: String,
    val queryName: String,
    val indexer: Indexer = new Indexer()
  ) {

  val plan = FPlanParser.parse(querySpecification)
  val engine = EngineFactory.createQueryEngine(plan, indexer)

  val transactionFactory = new TransactionFactory(16)
  transactionFactory.subscribe(engine.inputLookup)
  val transaction = transactionFactory.newBatchTransaction()
  new PullTupleCreator(
    engine.vertexConverters.values.flatten.toVector.distinct,
    engine.edgeConverters.values.flatten.toVector.distinct,
    indexer, transaction, LongIdParser)

  /**
    * Terminate execution and return results
    */
  def terminate(): Iterable[Tuple] = {
    transaction.close()
    engine.getResults()
  }
}

Add comment for terminate method

Add comment for terminate method


/*
 * Copyright 2017 Nicolas Rinaudo
 *
 * 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 kantan.csv.engine

import java.io.{Reader, Writer}
import kantan.codecs.resource.ResourceIterator
import kantan.csv._
import org.apache.commons.csv.{CSVFormat, CSVPrinter, QuoteMode}
import scala.collection.JavaConverters._

package object commons {
  def format(sep: Char): CSVFormat = CSVFormat.RFC4180.withDelimiter(sep)

  implicit val reader = ReaderEngine { (reader: Reader, sep: Char) ⇒
    ResourceIterator.fromIterator(format(sep).parse(reader).iterator.asScala.map(CsvSeq.apply))
  }

  implicit val writer = WriterEngine { (writer: Writer, sep: Char) ⇒
    CsvWriter(new CSVPrinter(writer, format(sep).withQuoteMode(QuoteMode.MINIMAL))) { (csv, ss) ⇒
      csv.printRecord(ss.asJava)
    }(_.close())
  }
}

/*
 * Copyright 2017 Nicolas Rinaudo
 *
 * 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 kantan.csv.engine

import kantan.codecs.resource.ResourceIterator
import kantan.csv._
import org.apache.commons.csv.{CSVFormat, CSVPrinter, QuoteMode}
import scala.collection.JavaConverters._

package object commons {
  def defaultFormat(sep: Char): CSVFormat = CSVFormat.RFC4180.withDelimiter(sep)

  def readerFrom(f: Char ⇒ CSVFormat): ReaderEngine = ReaderEngine { (r, s) ⇒
    ResourceIterator.fromIterator(f(s).parse(r).iterator.asScala.map(CsvSeq.apply))
  }

  implicit val reader: ReaderEngine = readerFrom(defaultFormat)

  def writerFrom(f: Char ⇒ CSVFormat): WriterEngine = WriterEngine { (w, s) ⇒
    CsvWriter(new CSVPrinter(w, f(s).withQuoteMode(QuoteMode.MINIMAL))) { (csv, ss) ⇒
      csv.printRecord(ss.asJava)
    }(_.close())
  }

  implicit val writer: WriterEngine = writerFrom(defaultFormat)
}

Make commons-csv much more configurable by exposing CSVFormat.


import sbt._
import Keys._
import org.scalajs.sbtplugin.ScalaJSPlugin.autoImport._

object ScalaJSHelper {
  def packageScalaJS(client: Project): Seq[Setting[_]] = Seq(
    watchSources ++= (client / watchSources).value,
    // Pick fastOpt when developing and fullOpt when publishing
    Compile / resourceGenerators += Def.task {
      val (js, map) = andSourceMap((client / Compile / fastOptJS).value.data)
      IO.copy(
        Seq(
          js -> (Compile / resourceManaged).value / js.getName,
          map -> (Compile / resourceManaged).value / map.getName
        )
      ).toSeq
    }.taskValue,
    Compile / packageBin / mappings := {
      val mappingExcludingNonOptimized =
        (Compile / packageBin / mappings).value.filterNot {
          case (f, r) =>
            f.getName.endsWith("-fastopt.js") ||
              f.getName.endsWith("js.map")
        }

      val optimized = {
        val (js, map) =
          andSourceMap((client / Compile / fullOptJS).value.data)
        Seq(
          js -> js.getName,
          map -> map.getName
        )
      }

      mappingExcludingNonOptimized ++ optimized
    }
  )

  private def andSourceMap(aFile: java.io.File) =
    aFile -> file(aFile.getAbsolutePath + ".map")
}

import sbt._
import Keys._
import org.scalajs.sbtplugin.ScalaJSPlugin.autoImport._

object ScalaJSHelper {
  def packageScalaJS(client: Project): Seq[Setting[_]] = Seq(
    watchSources ++= (client / watchSources).value,
    // Pick fastOpt when developing and fullOpt when publishing
    Compile / resourceGenerators += Def.task {
      val js = (client / Compile / fastOptJS).value.data
      val sourceMap = getSourceMap(js)
      IO.copy(
        Seq(
          js -> (Compile / resourceManaged).value / js.getName,
          sourceMap -> (Compile / resourceManaged).value / sourceMap.getName
        )
      ).toSeq
    }.taskValue,
    Compile / packageBin / mappings ++= {
      val optJs = (client / Compile / fullOptJS).value.data
      val sourceMap = getSourceMap(optJs)
      Seq(
        optJs -> optJs.getName,
        sourceMap -> sourceMap.getName
      )
    }
  )

  private def getSourceMap(jsFile: java.io.File): File =
    file(jsFile.getAbsolutePath + ".map")
}

Fix local packaging of webclient-fastopt.js


package sms

trait Handler {
  def keyword: String
  def process(message: SmsMessage): SmsMessage
}

object ErrorHandler extends Handler {
  def keyword = "ERROR"
  def process(message: SmsMessage) = message.reply("error")
}

object Handler {
  private var mapping = Map.empty[String, Handler]

  def register(handler: Handler) = {
    mapping += (handler.keyword -> handler)
  }

  def process(message: SmsMessage): SmsMessage = {
    val keyword = message.body.takeWhile(_ != ' ').toUpperCase
    mapping.get(keyword).getOrElse(ErrorHandler).process(message)
  }

  register(RouteHandler)
  register(NearHandler)
  register(AboutHandler)
  register(HelpHandler)
}

package sms

trait Handler {
  def keyword: String
  def process(message: SmsMessage): SmsMessage
}

object Handler {
  private var mapping = Map.empty[String, Handler]

  def register(handler: Handler) = {
    mapping += (handler.keyword -> handler)
  }

  def process(message: SmsMessage): SmsMessage = {
    val keyword = message.body.takeWhile(_ != ' ').toUpperCase
    mapping.get(keyword).getOrElse(HelpHandler).process(message)
  }

  register(RouteHandler)
  register(NearHandler)
  register(AboutHandler)
  register(HelpHandler)
}

Replace error handler with help

Replace error handler with help


import sbt._, Keys._

object Dependencies {
  val servletApiDep = "jakarta.servlet" % "jakarta.servlet-api" % "5.0.0"

  val specs2Dep = Def.setting {
    "org.specs2" %% "specs2-core" % "4.15.0"
  }

  def okHttp = "com.squareup.okhttp3" % "okhttp" % "4.9.3" :: Nil

  def integrationTestDeps = Def.setting((specs2Dep.value :: okHttp) map { _ % "test" })

  val commonsCodecVersion = "1.15"
  val scalaXmlVersion = "2.1.0"
  val commonsIoVersion = "2.11.0"
  val commonsFileUploadVersion = "1.4"
  val jettyVersion = "11.0.9"
  val nettyVersion = "4.1.77.Final"
  val scalatestVersion = "3.2.12"
  val scalatestScalacheckVersion = s"${scalatestVersion}.0"
  val json4sVersion = "4.0.5"
  val asyncHttpClientVersion = "1.8.17"
  val javaxActivationVersion = "1.1.1"
}

import sbt._, Keys._

object Dependencies {
  val servletApiDep = "jakarta.servlet" % "jakarta.servlet-api" % "5.0.0"

  val specs2Dep = Def.setting {
    "org.specs2" %% "specs2-core" % "4.16.0"
  }

  def okHttp = "com.squareup.okhttp3" % "okhttp" % "4.9.3" :: Nil

  def integrationTestDeps = Def.setting((specs2Dep.value :: okHttp) map { _ % "test" })

  val commonsCodecVersion = "1.15"
  val scalaXmlVersion = "2.1.0"
  val commonsIoVersion = "2.11.0"
  val commonsFileUploadVersion = "1.4"
  val jettyVersion = "11.0.9"
  val nettyVersion = "4.1.77.Final"
  val scalatestVersion = "3.2.12"
  val scalatestScalacheckVersion = s"${scalatestVersion}.0"
  val json4sVersion = "4.0.5"
  val asyncHttpClientVersion = "1.8.17"
  val javaxActivationVersion = "1.1.1"
}

Update specs2-core to 4.16.0 in main

Update specs2-core to 4.16.0 in main


import sbt._
import Keys._
import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._

object Dependencies {
  lazy val jaxbApi = "javax.xml.bind" % "jaxb-api" % "2.3.1" % "test"

  lazy val jodaTime = Seq(
    "joda-time" % "joda-time" % "2.12.1",
    "org.joda" % "joda-convert" % "2.2.2"
  )
  lazy val jackson = Seq(
    "com.fasterxml.jackson.core" % "jackson-databind" % "2.14.0"
  )
  lazy val scalaz_core = Def.setting(
    "org.scalaz" %%% "scalaz-core" % "7.3.6"
  )
  lazy val paranamer = "com.thoughtworks.paranamer" % "paranamer" % "2.8"
  lazy val scalatest = Def.setting(
    Seq("org.scalatest" %%% "scalatest-wordspec" % "3.2.14" % "test")
  )
  lazy val scalatestScalacheck = Def.setting(
    Seq("org.scalatestplus" %%% "scalacheck-1-17" % "3.2.14.0" % "test")
  )

  lazy val scalaXml = Def.setting {
    "org.scala-lang.modules" %%% "scala-xml" % "2.1.0"
  }
}

import sbt._
import Keys._
import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._

object Dependencies {
  lazy val jaxbApi = "javax.xml.bind" % "jaxb-api" % "2.3.1" % "test"

  lazy val jodaTime = Seq(
    "joda-time" % "joda-time" % "2.12.1",
    "org.joda" % "joda-convert" % "2.2.2"
  )
  lazy val jackson = Seq(
    "com.fasterxml.jackson.core" % "jackson-databind" % "2.14.1"
  )
  lazy val scalaz_core = Def.setting(
    "org.scalaz" %%% "scalaz-core" % "7.3.6"
  )
  lazy val paranamer = "com.thoughtworks.paranamer" % "paranamer" % "2.8"
  lazy val scalatest = Def.setting(
    Seq("org.scalatest" %%% "scalatest-wordspec" % "3.2.14" % "test")
  )
  lazy val scalatestScalacheck = Def.setting(
    Seq("org.scalatestplus" %%% "scalacheck-1-17" % "3.2.14.0" % "test")
  )

  lazy val scalaXml = Def.setting {
    "org.scala-lang.modules" %%% "scala-xml" % "2.1.0"
  }
}

Update jackson-databind to 2.14.1 in master


addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.1")

addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.0")

Revert "Update to tut 0.4.1"

Revert "Update to tut 0.4.1"


package metadoc.tests

import caseapp.RemainingArgs
import java.nio.file.Files
import metadoc.cli.MetadocCli
import metadoc.cli.MetadocOptions
import org.scalatest.BeforeAndAfterAll
import org.scalatest.FunSuite
import scala.meta.io.AbsolutePath
import scala.meta.testkit.DiffAssertions
import metadoc.{schema => d}
import metadoc.MetadocEnrichments._
import GeneratedSiteEnrichments._

class BaseMetadocCliSuite
    extends FunSuite
    with BeforeAndAfterAll
    with DiffAssertions {
  var out: AbsolutePath = _
  def options = MetadocOptions(
    Some(out.toString()),
    cleanTargetFirst = true,
    nonInteractive = true
  )
  def files: Seq[String] =
    BuildInfo.exampleClassDirectory.map(_.getAbsolutePath)

  def runCli(): Unit = MetadocCli.run(options, RemainingArgs(files, Nil))

  override def beforeAll(): Unit = {
    out = AbsolutePath(Files.createTempDirectory("metadoc"))
    out.toFile.deleteOnExit()
    runCli()
  }

  def checkSymbolIndex(id: String, expected: String) = {
    test(id) {
      val indexes = d.SymbolIndexes.parseFromCompressedPath(
        out.resolve("symbol").resolve(id.symbolIndexPath)
      )
      val index = indexes.indexes.find(_.symbol == id).get
      val obtained = index.toProtoString
      assertNoDiffOrPrintExpected(obtained, expected)
    }
  }

}

package metadoc.tests

import caseapp.RemainingArgs
import java.nio.file.Files
import metadoc.cli.MetadocCli
import metadoc.cli.MetadocOptions
import org.scalatest.BeforeAndAfterAll
import org.scalatest.FunSuite
import scala.meta.io.AbsolutePath
import scala.meta.testkit.DiffAssertions
import metadoc.{schema => d}
import metadoc.MetadocEnrichments._
import GeneratedSiteEnrichments._

class BaseMetadocCliSuite
    extends FunSuite
    with BeforeAndAfterAll
    with DiffAssertions {
  var out: AbsolutePath = _
  def options = MetadocOptions(
    Some(out.toString()),
    cleanTargetFirst = true,
    nonInteractive = true
  )
  def files: Seq[String] =
    BuildInfo.exampleClassDirectory.map(_.getAbsolutePath)

  def runCli(): Unit = MetadocCli.run(options, RemainingArgs(files, Nil))

  override def beforeAll(): Unit = {
    out = AbsolutePath(Files.createTempDirectory("metadoc"))
    out.toFile.deleteOnExit()
    runCli()
  }

  def checkSymbolIndex(id: String, expected: String) = {
    test(id) {
      val indexes = d.SymbolIndexes.parseFromCompressedPath(
        out.resolve("symbol").resolve(id.symbolIndexPath)
      )
      val index = indexes.indexes.find(_.symbol == id).get
      // Sort ranges to ensure we assert against deterministic input.
      val indexNormalized = index.copy(
        references = index.references.mapValues { ranges =>
          ranges.copy(ranges = ranges.ranges.sortBy(_.startLine))
        }
      )
      val obtained = indexNormalized.toProtoString
      assertNoDiffOrPrintExpected(obtained, expected)
    }
  }

}

Fix checkSymbolIndex to be independent of the order files are listed


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

import scala.io.Source
import java.io.File

object SMTI {

  def main(args: Array[String]) {

    if (args.length != 1) {
      println("Usage: /path/to/spark/bin/spark-submit " + "--class SMTI "
        + "target/scala-*/smti-assembly-*.jar " + "prefListDir")
      sys.exit(1)
    }

    // Set up Spark environment

    val conf = new SparkConf().setAppName("SMTI")
    val sc = new SparkContext(conf)

    // Load data

    val prefListDir = args(0)

    val config = loadConfig(prefListDir)

    println(config(0))

    // Clean up
    sc.stop()
  }

  def loadConfig(dir: String): Array[Int] = {
    val lines = Source.fromFile(new File(dir, "config.txt")).getLines().toArray
    assert(lines.length == 1)
    lines(0).split(" ").map( x => x.toInt )
  }

  /* Raw preference list for one person.
   * From the most preferred to the least.
   * Ties are represented using negative indices, i.e., negative index has the
   * same preference as the one before it.
   */
  type RawPrefList = List[Int]
}

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

import scala.io.Source
import java.io.File

object SMTI {

  def main(args: Array[String]) {

    if (args.length != 1) {
      println("Usage: /path/to/spark/bin/spark-submit " + "--class SMTI "
        + "target/scala-*/smti-assembly-*.jar " + "prefListDir")
      sys.exit(1)
    }

    // Set up Spark environment

    val conf = new SparkConf().setAppName("SMTI")
    val sc = new SparkContext(conf)

    // Load data

    val prefListDir = args(0)

    val config = loadConfig(prefListDir)

    println(config(0))

    // Clean up
    sc.stop()
  }

  def loadConfig(dir: String): Array[Long] = {
    val lines = Source.fromFile(new File(dir, "config.txt")).getLines().toArray
    assert(lines.length == 1)
    lines(0).split(" ").map( x => x.toLong )
  }

  /* Raw preference list for one person.
   * From the most preferred to the least.
   * Ties are represented using negative indices, i.e., negative index has the
   * same preference as the one before it.
   */
  type RawPrefList = Array[Long]
}

Use Long instead of Int as the index type.


package org.jetbrains.plugins.scala.debugger.ui

import com.intellij.debugger.ui.tree.render.{ChildrenRenderer, CompoundRendererProvider, ValueLabelRenderer}
import com.sun.jdi.Type

import java.util.concurrent.CompletableFuture

abstract class ScalaRendererProvider(private val renderer: ScalaClassRenderer) extends CompoundRendererProvider {

  override def getName: String = renderer.getName

  override def getValueLabelRenderer: ValueLabelRenderer = renderer

  override def getChildrenRenderer: ChildrenRenderer = renderer

  override def isEnabled: Boolean = true

  override def getIsApplicableChecker: java.util.function.Function[Type, CompletableFuture[java.lang.Boolean]] =
    tpe => CompletableFuture.completedFuture(renderer.isApplicableFor(tpe))
}

class ScalaClassRendererProvider extends ScalaRendererProvider(new ScalaClassRenderer())

class ScalaCollectionRendererProvider extends ScalaRendererProvider(new ScalaCollectionRenderer())

package org.jetbrains.plugins.scala.debugger.ui

import com.intellij.debugger.ui.tree.render.{ChildrenRenderer, CompoundRendererProvider, ValueLabelRenderer}
import com.sun.jdi.Type
import org.jetbrains.plugins.scala.debugger.filters.ScalaDebuggerSettings

import java.util.concurrent.CompletableFuture

abstract class ScalaRendererProvider(private val renderer: ScalaClassRenderer) extends CompoundRendererProvider {

  override def getName: String = renderer.getName

  override def getValueLabelRenderer: ValueLabelRenderer = renderer

  override def getChildrenRenderer: ChildrenRenderer = renderer

  override def isEnabled: Boolean = true

  override def getIsApplicableChecker: java.util.function.Function[Type, CompletableFuture[java.lang.Boolean]] =
    tpe => CompletableFuture.completedFuture(renderer.isApplicableFor(tpe))
}

class ScalaClassRendererProvider extends ScalaRendererProvider(new ScalaClassRenderer())

class ScalaCollectionRendererProvider extends ScalaRendererProvider(new ScalaCollectionRenderer()) {
  override def isEnabled: Boolean = ScalaDebuggerSettings.getInstance().FRIENDLY_COLLECTION_DISPLAY_ENABLED
}

Use the user setting for the Scala collection renderer


package com.davebsoft.sctw.ui
import com.davebsoft.sctw.twitter.Utils

/**
 * Helps with creating HTML for display in the UI
 * @author Dave Briccetti
 */

object HtmlFormatter {

  def createTweetHtml(text: String, replyTo: String): String = {
    val replyToUser = Utils.getReplyToUser(text)
    val parent = if (replyTo.length > 0 && replyToUser.length > 0)
      "↑ " else ""
    var r = text.replaceAll("""(https?://[^'"\s]+)""", "$1")
    r = r.replaceAll("""@([^\s:]+)""", "@$1")
    "" + parent + "" + r + ""
  }

}

package com.davebsoft.sctw.ui
import com.davebsoft.sctw.twitter.Utils

/**
 * Helps with creating HTML for display in the UI
 * @author Dave Briccetti
 */

object HtmlFormatter {

  def createTweetHtml(text: String, replyTo: String): String = {
    val replyToUser = Utils.getReplyToUser(text)

    val arrowLinkToParent = if (replyTo.length > 0 && replyToUser.length > 0)
      "↑ " else ""

    var r = text.replaceAll("""(https?://[^'"\s]+)""", "$1")

    r = r.replaceAll("""@([^\s:.,]+)""", "@$1")

    "" + arrowLinkToParent + "" + r + ""
  }

}

Add comma and period to the class of characters not in a @user name


package com.twitter.finagle.mysql

import com.twitter.util.{Future, Throw, Try}

/**
 * A [[LostSyncException]] indicates that this finagle-mysql client and the MySQL server are
 * no longer able to properly communicate, as there has been a failure to decode a message
 * from the server or data has become corrupted in transmission. It is a fatal error and the
 * communication with the server must be closed, then reopened, and renogotiated.
 */
final case class LostSyncException(underlying: Throwable) extends RuntimeException(underlying) {
  override def getMessage: String = underlying.toString
  override def getStackTrace: Array[StackTraceElement] = underlying.getStackTrace
}

// The companion object needs to be public for folks to be able to match on the
// `LostSyncException`.
object LostSyncException {

  private[mysql] val AsException: LostSyncException = LostSyncException(new Throwable)
  private[mysql] val AsFuture: Future[Nothing] = Future.exception(AsException)

  /**
   * Wrap a Try[T] into a Future[T]. This is useful for
   * transforming decoded results into futures. Any Throw
   * is assumed to be a failure to decode and thus a synchronization
   * error (or corrupt data) between the client and server.
   */
  private[mysql] def const[T](result: Try[T]): Future[T] =
    Future.const(result.rescue { case exc => Throw(LostSyncException(exc)) })

}

package com.twitter.finagle.mysql

import com.twitter.util.{Future, Throw, Try}

/**
 * A [[LostSyncException]] indicates that this finagle-mysql client and the MySQL server are
 * no longer able to properly communicate, as there has been a failure to decode a message
 * from the server or data has become corrupted in transmission. It is a fatal error and the
 * communication with the server must be closed, then reopened, and renegotiated.
 */
final case class LostSyncException(underlying: Throwable) extends RuntimeException(underlying) {
  override def getMessage: String = underlying.toString
  override def getStackTrace: Array[StackTraceElement] = underlying.getStackTrace
}

// The companion object needs to be public for folks to be able to match on the
// `LostSyncException`.
object LostSyncException {

  private[mysql] val AsException: LostSyncException = LostSyncException(new Throwable)
  private[mysql] val AsFuture: Future[Nothing] = Future.exception(AsException)

  /**
   * Wrap a Try[T] into a Future[T]. This is useful for
   * transforming decoded results into futures. Any Throw
   * is assumed to be a failure to decode and thus a synchronization
   * error (or corrupt data) between the client and server.
   */
  private[mysql] def const[T](result: Try[T]): Future[T] =
    Future.const(result.rescue { case exc => Throw(LostSyncException(exc)) })

}

finagle-mysql: Fix a typo in scaladoc: renogotiated -> renegotiated

Problem:
Typo in the scala doc

Solution / Result:
Fix the typo.

PR: https://github.com/twitter/finagle/pull/859

Signed-off-by: Hamdi Allam <hallam@twitter.com>

JIRA Issues: CSL-9904

Differential Revision: https://phabricator.twitter.biz/D506475


package centaur

import java.nio.file.Path

import scala.language.postfixOps
import org.scalatest._

/**
  * Tests with this tag expect their initial submission to Cromwell to fail
  */
object SubmissionFailureTest extends Tag("SubmissionFailureTest")
/**
  * Tests with this tag expect to fail
  */
object FailureTest extends Tag("FailureTest")
/**
  * Tests with this tag expect to succeed
  */
object SuccessTest extends Tag("SuccessTest")

class CentaurSpec extends FlatSpec with Matchers {

  def testCases(basePath: Path): List[WorkflowRequest] = {
    basePath.toFile.listFiles.toList collect { case x if x.isDirectory => x.toPath } map WorkflowRequest.apply
  }

  testCases(CentaurConfig.successfulTestCasePath) foreach { case w =>
    it should s"successfully run ${w.name}" taggedAs SuccessTest in {
      TestFormulas.runSuccessfulWorkflow(w).run.get
    }
  }

    testCases(CentaurConfig.failingTestCasePath) foreach { case w =>
      it should s"fail ${w.name}" taggedAs FailureTest in {
        TestFormulas.runFailingWorkflow(w).run.get
      }
    }

  testCases(CentaurConfig.submissionFailureTestCasePath) foreach { case w =>
    it should s"fail ${w.name}" taggedAs SubmissionFailureTest in {
      // TODO: This returns a string error message. With extra test metadata, we can verify that the error message is correct!
      TestFormulas.runSubmissionFailureWorkflow(w).run.get
    }
  }
}

package centaur

import java.nio.file.Path

import scala.language.postfixOps
import org.scalatest._

/**
  * Tests with this tag expect their initial submission to Cromwell to fail
  */
object SubmissionFailureTest extends Tag("SubmissionFailureTest")
/**
  * Tests with this tag expect to fail
  */
object FailureTest extends Tag("FailureTest")
/**
  * Tests with this tag expect to succeed
  */
object SuccessTest extends Tag("SuccessTest")

class CentaurSpec extends FlatSpec with Matchers with ParallelTestExecution{
  def testCases(basePath: Path): List[WorkflowRequest] = {
    basePath.toFile.listFiles.toList collect { case x if x.isDirectory => x.toPath } map WorkflowRequest.apply
  }

  testCases(CentaurConfig.successfulTestCasePath) foreach { case w =>
    it should s"successfully run ${w.name}" taggedAs SuccessTest in {
      TestFormulas.runSuccessfulWorkflow(w).run.get
    }
  }

    testCases(CentaurConfig.failingTestCasePath) foreach { case w =>
      it should s"fail ${w.name}" taggedAs FailureTest in {
        TestFormulas.runFailingWorkflow(w).run.get
      }
    }

  testCases(CentaurConfig.submissionFailureTestCasePath) foreach { case w =>
    it should s"fail ${w.name}" taggedAs SubmissionFailureTest in {
      // TODO: This returns a string error message. With extra test metadata, we can verify that the error message is correct!
      TestFormulas.runSubmissionFailureWorkflow(w).run.get
    }
  }
}

Add the parallel testing back in

Add the parallel testing back in


package cook.config

import java.net.URLClassLoader

object ConfigLoader {

  def load(configRef: ConfigRef, depConfigRefMap: Map[String, ConfigRef]): Config = {
    val cl = getClassLoader(configRef, depConfigRefMap)
    val clazz = cl.loadClass(configRef.configClassFullName)
    clazz.asInstanceOf[Class[Config]].newInstance
  }

  private def getClassLoader(configRef: ConfigRef, depConfigRefMap: Map[String, ConfigRef]) = {
    val depConfigRefs = depConfigRefMap.values.toList
    val cp = (configRef :: depConfigRefs).map(_.configByteCodeDir.toURI.toURL).toArray
    new URLClassLoader(cp, this.getClass.getClassLoader)
  }
}

package cook.config

import java.lang.ClassLoader
import java.net.URLClassLoader

object ConfigLoader {

  def load(configRef: ConfigRef, depConfigRefMap: Map[String, ConfigRef]): Config = synchronized {
    val cl = getClassLoader(configRef, depConfigRefMap)
    val clazz = cl.loadClass(configRef.configClassFullName)
    clazz.asInstanceOf[Class[Config]].newInstance
  }

  private var cl: ClassLoader = this.getClass.getClassLoader
  private def getClassLoader(configRef: ConfigRef, depConfigRefMap: Map[String, ConfigRef]) = {
    val depConfigRefs = depConfigRefMap.values.toList
    val cp = (configRef :: depConfigRefs).map(_.configByteCodeDir.toURI.toURL).toArray
    cl = new URLClassLoader(cp, cl)
    cl
  }
}

Use same class loader contexts for all config.


package scala.generator.anorm

import com.bryzek.apidoc.spec.v0.models.Service
import com.bryzek.apidoc.generator.v0.models.{File, InvocationForm}
import lib.generator.CodeGenerator
// import lib.Text._

object ParserGenerator extends CodeGenerator {

  override def invoke(form: InvocationForm): Either[Seq[String], Seq[File]] = {
    generateCode(form.service) match {
      case None => {
        Left(Seq("No models were found and thus no parsers were generated"))
      }
      case Some(code) => {
        Right(
          Seq(
            File(
              name = "Parsers.scala",
              contents = code
            )
          )
        )
      }
    }
  }

  private[this] def generateCode(service: Service): Option[String] = {
    None
  }

}

package scala.generator.anorm

import com.bryzek.apidoc.spec.v0.models.{Model, Service}
import com.bryzek.apidoc.generator.v0.models.{File, InvocationForm}
import lib.generator.CodeGenerator
// import lib.Text._

object ParserGenerator extends CodeGenerator {

  override def invoke(form: InvocationForm): Either[Seq[String], Seq[File]] = {
    generateCode(form.service) match {
      case None => {
        Left(Seq("No models were found and thus no parsers were generated"))
      }
      case Some(code) => {
        Right(
          Seq(
            File(
              name = "Parsers.scala",
              contents = code
            )
          )
        )
      }
    }
  }

  private[this] def generateCode(service: Service): Option[String] = {
    service.models.map(generateModelParser(_)) match {
      case Nil => {
        None
      }
      case models => {
        Some(
          Seq(
            "package TODO {",
            models.mkString("\n"),
            "}"
          ).mkString("\n")
        )
      }
    }
  }

  private[this] def generateModelParser(model: Model): String = {
    "TODO"
  }

}

Check for services with no models

Check for services with no models


package controllers.util

import play.api.mvc.{Action, Controller}
import models.WorkbenchConfig
import java.io.{BufferedInputStream, FileInputStream}
import play.api.templates.Html
import scala.io.Source

object Branding extends Controller {

  def logo = Action {
    val imgStream = WorkbenchConfig.get.logo.load
    val bytes = scala.Stream.continually(imgStream.read).takeWhile(_ != -1).map(_.toByte).toArray
    Ok(bytes).as("image/png")
  }

  def aboutDialog = Action {
    val aboutHtml = Html(Source.fromInputStream(WorkbenchConfig.get.about.load).getLines.mkString("\n"))

    Ok(views.html.aboutDialog(aboutHtml))
  }

}

package controllers.util

import play.api.mvc.{Action, Controller}
import models.WorkbenchConfig
import play.api.templates.Html
import scala.io.{Codec, Source}

object Branding extends Controller {

  def logo = Action {
    val imgStream = WorkbenchConfig.get.logo.load
    val bytes = scala.Stream.continually(imgStream.read).takeWhile(_ != -1).map(_.toByte).toArray
    Ok(bytes).as("image/png")
  }

  def aboutDialog = Action {
    val aboutHtml = Html(Source.fromInputStream(WorkbenchConfig.get.about.load)(Codec.UTF8).getLines.mkString("\n"))

    Ok(views.html.aboutDialog(aboutHtml))
  }

}

Load about message with UTF8 encoding

Load about message with UTF8 encoding


name := "lib-apidoc-json-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.30"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.12",
      "org.scalatest" %% "scalatest" % "3.0.1" % 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 := "lib-apidoc-json-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.31"

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


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.3.9"

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

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

import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.3.10"

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

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

autocommit: Update configuration to record version 0.3.10


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.1.2"

exportJars := true

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

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

import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.1.3"

exportJars := true

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

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

autocommit: Update configuration to record version 0.1.3


import sbt.Keys._

lazy val gallery = project.in( file( "." ) )
    .settings( androidBuildAar ++ Settings.common )
    .settings(
        libraryDependencies ++=
            "com.android.support" % "appcompat-v7" % "24.2.1" ::
            "com.github.chrisbanes" % "PhotoView" % "1.3.0" ::
            "com.github.google" % "flexbox-layout" % "0.2.3" ::
            "com.github.jkwiecien" % "EasyImage" % "1.3.1" ::
            "com.github.square.picasso" % "picasso" % "eac9b2b330" ::
            Nil,
        name := "gallery"
    )

lazy val sample = project
    .androidBuildWith( gallery )
    .settings( Settings.common )
    .settings(
        organization := organization.value + ".sample",
        run <<= run in Android
    )

import sbt.Keys._

lazy val gallery = project.in( file( "." ) )
    .settings( androidBuildAar ++ Settings.common )
    .settings(
        libraryDependencies ++=
            "com.android.support" % "appcompat-v7" % "24.2.1" ::
            "com.github.chrisbanes" % "PhotoView" % "1.3.0" ::
            "com.github.google" % "flexbox-layout" % "0.2.3" ::
            "com.github.jkwiecien" % "EasyImage" % "1.3.1" ::
            "com.github.square.picasso" % "picasso" % "eac9b2b330" ::
            Nil,
        name := "gallery",
        publishArtifact in ( Compile, packageDoc ) := false
    )

lazy val sample = project
    .androidBuildWith( gallery )
    .settings( Settings.common )
    .settings(
        organization := organization.value + ".sample",
        run <<= run in Android
    )

Disable doc generation for JitPack

Disable doc generation for JitPack


organization := "com.lightbend.studentify"

name := "studentify"

version := "1.0.0"

scalaVersion := Version.scalaVer

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

libraryDependencies ++= Dependencies.studentify

scalacOptions ++= List(
  "-unchecked",
  "-deprecation",
  "-language:_",
  "-target:jvm-1.6",
  "-encoding", "UTF-8"
)

addCommandAlias("studentify", "runMain com.lightbend.coursegentools.Studentify")

Add sbt command alias for 'studentify' application


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

version := "0.0.14"

exportJars := true

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

version := "0.0.15"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.4.6",
      "com.ning" % "async-http-client" % "1.9.32",
      "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")
  }
}

Increment version from 0.0.14 => 0.0.15

Increment version from 0.0.14 => 0.0.15


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

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

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

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

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

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

autocommit: Update configuration to record version 0.1.22


import AssemblyKeys._

Nice.javaProject

Nice.fatArtifactSettings

organization := "bio4j"

name := "neo4jdb"

description := "neo4jdb implementation of the Bio4j model"

bucketSuffix := "era7.com"

libraryDependencies ++= Seq(
  "bio4j" % "model" % "0.3.3",
  "ohnosequences" % "bioinfo-util" % "1.4.0-SNAPSHOT"
)

dependencyOverrides ++= Set(
  "com.fasterxml.jackson.core" % "jackson-core" % "2.1.2",
  "com.fasterxml.jackson.core" % "jackson-databind" % "2.1.2",
  "commons-beanutils" % "commons-beanutils" % "1.8.3",
  "commons-beanutils" % "commons-beanutils-core" % "1.8.3"
)

// fat jar assembly settings
mainClass in assembly := Some("com.ohnosequences.bio4j.neo4j.programs.ImportNeo4jDB")

assemblyOption in assembly ~= { _.copy(includeScala = false) }

mergeStrategy in assembly ~= { old => {
    case PathList("META-INF", "CHANGES.txt")                     => MergeStrategy.rename
    case PathList("META-INF", "LICENSES.txt")                    => MergeStrategy.rename
    case PathList("org", "apache", "commons", "collections", _*) => MergeStrategy.first
    case x                                                       => old(x)
  }
}

import AssemblyKeys._

Nice.javaProject

Nice.fatArtifactSettings

organization := "bio4j"

name := "neo4jdb"

description := "neo4jdb implementation of the Bio4j model"

bucketSuffix := "era7.com"

libraryDependencies ++= Seq(
  "bio4j" % "model" % "0.3.3",
  "ohnosequences" % "bioinfo-util" % "1.3.0"
)

dependencyOverrides ++= Set(
  "com.fasterxml.jackson.core" % "jackson-core" % "2.1.2",
  "com.fasterxml.jackson.core" % "jackson-databind" % "2.1.2",
  "commons-beanutils" % "commons-beanutils" % "1.8.3",
  "commons-beanutils" % "commons-beanutils-core" % "1.8.3"
)

// fat jar assembly settings
mainClass in assembly := Some("com.ohnosequences.bio4j.neo4j.programs.ImportNeo4jDB")

assemblyOption in assembly ~= { _.copy(includeScala = false) }

mergeStrategy in assembly ~= { old => {
    case PathList("META-INF", "CHANGES.txt")                     => MergeStrategy.rename
    case PathList("META-INF", "LICENSES.txt")                    => MergeStrategy.rename
    case PathList("org", "apache", "commons", "collections", _*) => MergeStrategy.first
    case x                                                       => old(x)
  }
}

Set dependency on the bioinfo-utils 1.3.0


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.12"

version := "0.1.62"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.6.8",
      "com.ning" % "async-http-client" % "1.9.40",
      "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")
  }
}

import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.12"

version := "0.1.63"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.6.8",
      "com.ning" % "async-http-client" % "1.9.40",
      "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.63


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.39"

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

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


import sbt._, Keys._

/** This local plugin provides ways of publishing just the binary jar. */
object PublishBinPlugin extends AutoPlugin {
  override def requires = plugins.JvmPlugin
  override def trigger  = allRequirements

  object autoImport {
    val publishLocalBin       = taskKey[Unit]("")
    val publishLocalBinConfig = taskKey[PublishConfiguration]("")
  }

  import autoImport._

  override def projectSettings = Def settings (
    publishLocalBin       := Classpaths.publishTask(publishLocalBinConfig, deliverLocal).value,
    publishLocalBinConfig := Classpaths.publishConfig(
      (packagedArtifacts in publishLocalBin).value, Some(deliverLocal.value),
      (checksums in publishLocalBin).value, logging = ivyLoggingLevel.value, overwrite = isSnapshot.value),
    packagedArtifacts in publishLocalBin := Classpaths.packaged(Seq(packageBin in Compile)).value
  )
}

import sbt._, Keys._

/** This local plugin provides ways of publishing just the binary jar. */
object PublishBinPlugin extends AutoPlugin {
  override def requires = plugins.JvmPlugin
  override def trigger  = allRequirements

  object autoImport {
    val publishLocalBin       = taskKey[Unit]("")
    val publishLocalBinConfig = taskKey[PublishConfiguration]("")
  }

  import autoImport._

  override def globalSettings = Seq(publishLocalBin := (()))

  override def projectSettings = Def settings (
    publishLocalBin       := Classpaths.publishTask(publishLocalBinConfig, deliverLocal).value,
    publishLocalBinConfig := Classpaths.publishConfig(
      (packagedArtifacts in publishLocalBin).value, Some(deliverLocal.value),
      (checksums in publishLocalBin).value, logging = ivyLoggingLevel.value, overwrite = isSnapshot.value),
    packagedArtifacts in publishLocalBin := Classpaths.packaged(Seq(packageBin in Compile)).value
  )
}

Make sure publishLocalBin has a default implementation


package io.vamp.workflow_driver

import akka.actor.{ ActorRef, ActorSystem }
import akka.util.Timeout
import io.vamp.common.{ ClassProvider, Config, Namespace }
import io.vamp.common.akka.{ ActorBootstrap, IoC }
import io.vamp.workflow_driver.notification.{ UnsupportedWorkflowDriverError, WorkflowDriverNotificationProvider }

import scala.concurrent.{ ExecutionContext, Future }

class WorkflowDriverBootstrap extends ActorBootstrap with WorkflowDriverNotificationProvider {

  def createActors(implicit actorSystem: ActorSystem, namespace: Namespace, timeout: Timeout) = {
    implicit val ec: ExecutionContext = actorSystem.dispatcher
    val types = Config.string("vamp.workflow-driver.type")().toLowerCase.split(',').map(_.trim).toList

    val drivers: Future[List[ActorRef]] = Future.sequence(types.map { name ⇒
      ClassProvider.find[WorkflowDriver](name) match {
        case Some(clazz) ⇒ IoC.createActor(clazz)
        case None        ⇒ throwException(UnsupportedWorkflowDriverError(name))
      }
    })

    types.foreach { t ⇒ info(s"Workflow driver: $t") }
    drivers.flatMap(IoC.createActor[WorkflowDriverActor](_)).map(_ :: Nil)
  }
}

package io.vamp.workflow_driver

import akka.actor.{ActorRef, ActorSystem}
import akka.util.Timeout
import com.typesafe.scalalogging.LazyLogging
import io.vamp.common.{ClassProvider, Config, Namespace}
import io.vamp.common.akka.{ActorBootstrap, IoC}
import io.vamp.workflow_driver.notification.{UnsupportedWorkflowDriverError, WorkflowDriverNotificationProvider}

import scala.concurrent.{ExecutionContext, Future}

class WorkflowDriverBootstrap extends ActorBootstrap with WorkflowDriverNotificationProvider with LazyLogging {

  def createActors(implicit actorSystem: ActorSystem, namespace: Namespace, timeout: Timeout) = {
    implicit val ec: ExecutionContext = actorSystem.dispatcher
    val types = Config.string("vamp.workflow-driver.type")().toLowerCase.split(',').map(_.trim).toList

    val drivers: Future[List[ActorRef]] = Future.sequence(types.map { name ⇒
      ClassProvider.find[WorkflowDriver](name) match {
        case Some(clazz) ⇒ IoC.createActor(clazz)
        case None        ⇒ {
          logger.info(s"UnsupportedWorkflowDriverError : ${name}")
          throwException(UnsupportedWorkflowDriverError(name))
        }
      }
    })

    types.foreach { t ⇒ info(s"Workflow driver: $t") }
    drivers.flatMap(IoC.createActor[WorkflowDriverActor](_)).map(_ :: Nil)
  }
}

Add log to Worfflow Driver Bootstrap

Add log to Worfflow Driver Bootstrap


class C(val a: Any) {
  /*resolved: false*/a = 0
  /*resolved: true*/a
}

class C(val a: Any) {
  /*resolved: true*/a = 0
  /*resolved: true*/a
}

Fix reference resolve in assignment statements, fixing reassignment to val highlighting.


package processing

import akka.actor.{ Actor, ActorLogging, ActorRef, ActorSystem, Props }
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.{ Publish, Put }
import common.CommonMessages._

object WordCounter {
  def props(): Props = Props(new WordCounter)
  def createWordCounter(system: ActorSystem): ActorRef = {
    system.actorOf(WordCounter.props())
  }
}

class WordCounter extends Actor with ActorLogging {

  val mediator = DistributedPubSub(context.system).mediator

  mediator ! Put(self)

  override def receive: Receive = {
    case msg: ProcessLine =>
      val words = msg.line.split(" ").length
      log.debug(s"Counting words: $words")
      sender() ! words
  }
}

package processing

import akka.actor.{ Actor, ActorLogging, ActorRef, ActorSystem, Props }
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.{ Publish, Put }
import common.CommonMessages._

object WordCounter {
  def props(): Props = Props(new WordCounter)
  def createWordCounter(system: ActorSystem): ActorRef = {
    system.actorOf(WordCounter.props())
  }
}

class WordCounter extends Actor with ActorLogging {

  val mediator = DistributedPubSub(context.system).mediator

  mediator ! Put(self)

  override def receive: Receive = {
    case msg: ProcessLine =>
      val words = msg.line.split(" ").length
      log.info(s"Counting words: $words")
      sender() ! words
  }
}

Print out words per line

Print out words per line


BuildSettings.baseSettings

name := "testkit"

version := "0.0.1-SNAPSHOT"

libraryDependencies ++= Seq(
  "org.scalatest" % "scalatest_2.10" % "2.1.0",
  "org.scalacheck" %% "scalacheck" % "1.10.1",
  "com.typesafe.akka" %% "akka-actor" % "2.2.3" % "provided",
  "com.typesafe.akka" %% "akka-testkit" % "2.2.3",
  "com.typesafe.akka" %% "akka-actor" % "2.2.3" % "test"
)

BuildSettings.baseSettings

name := "testkit"

version := "0.0.1-SNAPSHOT"

libraryDependencies ++= Seq(
  "org.scalatest" % "scalatest_2.10" % "2.1.0",
  "org.scalacheck" %% "scalacheck" % "1.11.3",
  "com.typesafe.akka" %% "akka-actor" % "2.2.3" % "provided",
  "com.typesafe.akka" %% "akka-testkit" % "2.2.3",
  "com.typesafe.akka" %% "akka-actor" % "2.2.3" % "test"
)

Upgrade scalacheck to version compatible with scalatest 2.1.0


package omnibus.api

import akka.io.IO
import spray.can.Http

import omnibus.configuration._
import omnibus.api.endpoint.HttpEndpointActor
import omnibus.core.{CoreActors, Core}

trait Rest {
  this: CoreActors with Core =>

  val rootService = system.actorOf(HttpEndpointActor.props(this), "omnibus-http")
}

trait Web {
  this: Rest with CoreActors with Core =>

  val httpPort = Settings(system).Http.Port

  IO(Http)(system) ! Http.Bind(rootService, "localhost", port = 8080)
}

package omnibus.api

import akka.io.IO
import spray.can.Http

import omnibus.configuration._
import omnibus.api.endpoint.HttpEndpointActor
import omnibus.core.{CoreActors, Core}

trait Rest {
  this: CoreActors with Core =>

  val rootService = system.actorOf(HttpEndpointActor.props(this), "omnibus-http")
}

trait Web {
  this: Rest with CoreActors with Core =>

  val httpPort = Settings(system).Http.Port

  IO(Http)(system) ! Http.Bind(rootService, "localhost", port = httpPort)
}

Use configured http port instead of hard-coded value


package varys.util

import org.apache.commons.io.FileUtils

import java.io._

import varys.Logging

/**
 * Various utility classes for working with HFT.
 */
private[varys] object HFTUtils extends Logging {
  val GetReadToken  = 0
  val GetWriteToken = 1
  val ReadToken     = 2
  val WriteToken    = 3

  val HFT_WORKDIR_PATH = "/tmp/HFT"
  val HFT_LOCAL_SLAVE_PATH = HFT_WORKDIR_PATH + "/SLAVE"

  def createWorkDirPath(id: String): String = {
    HFT_WORKDIR_PATH + "/" + id
  }

  def cleanWorkDir() {
    FileUtils.deleteDirectory(new File(HFT_WORKDIR_PATH))
  }
}

package varys.util

import org.apache.commons.io.FileUtils

import java.io._

import varys.Logging

/**
 * Various utility classes for working with HFT.
 */
private[varys] object HFTUtils extends Logging {
  val GetReadToken  = 0
  val GetWriteToken = 1
  val ReadToken     = 2
  val WriteToken    = 3

  val HFT_WORKDIR_PATH = System.getProperty("varys.framework.hftWorkDir", "/tmp/HFT")
  val HFT_LOCAL_SLAVE_PATH = HFT_WORKDIR_PATH + "/SLAVE"

  def createWorkDirPath(id: String): String = {
    HFT_WORKDIR_PATH + "/" + id
  }

  def cleanWorkDir() {
    FileUtils.deleteDirectory(new File(HFT_WORKDIR_PATH))
  }
}

Make OFT work directory configurable

Make OFT work directory configurable


object Example extends App {
  final case class Foo[A](run: A ?=> Int) {
    // def copy[A]: this.A ?=> Int = (using a) => run
  }
}

object Example extends App {
  final case class Foo[A](run: A ?=> Int)
}

object Example2 extends App {
  final case class Foo[A, B](run: (A, B) ?=> Int)
}

object Example3 extends App {
  final case class Foo[A, B](run: () ?=> Int)
}

Add test for different arities

Add test for different arities


// code-examples/ObjectSystem/typehierarchy/either-script.scala

def exceptionToLeft[T](f: => T): Either[java.lang.Throwable, T] = try {
  Right(f)
} catch {
  case ex => Left(ex)
}

def throwsOnOddInt(i: Int) = i % 2 match {
  case 0 => i
  case 1 => throw new RuntimeException(i + " is odd!")
}

for(i <- 0 to 3)
  exceptionToLeft(throwsOnOddInt(i)) match {
    case Left(ex) => println("Oops, got exception " + ex.toString)
    case Right(x) => println(x)
  }

// code-examples/ObjectSystem/typehierarchy/either-script.scala

def exceptionToLeft[T](f: => T): Either[java.lang.Throwable, T] = try {
  Right(f)
} catch {
  case ex:Throwable => Left(ex)
}

def throwsOnOddInt(i: Int) = i % 2 match {
  case 0 => i
  case 1 => throw new RuntimeException(i + " is odd!")
}

for(i <- 0 to 3)
  exceptionToLeft(throwsOnOddInt(i)) match {
    case Left(ex) => println("Oops, got exception " + ex.toString)
    case Right(x) => println(x)
  }

Fix a `case ex : Throwable` warning

Fix a `case ex : Throwable` warning


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

package net.liftweb
package proto

import net.liftweb.common._
import net.liftweb.util._
import net.liftweb.http._
import scala.reflect.Manifest

import java.util.regex.Pattern

/**
 * This singleton contains the rules for persistence
 */
object ProtoRules extends Factory with LazyLoggable {
  /**
   * The regular expression pattern for matching email addresses.
   */
  val emailRegexPattern = new FactoryMaker(Pattern.compile("(?i)^[a-z0-9._%\\-+]+@(?:[a-z0-9\\-]+\\.)+[a-z]{2,}$")) {}

}

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

package net.liftweb
package proto

import net.liftweb.common._
import net.liftweb.util._
import net.liftweb.http._
import scala.reflect.Manifest

import java.util.regex.Pattern

/**
 * This singleton contains the rules for persistence
 */
object ProtoRules extends Factory with LazyLoggable {
  /**
   * The regular expression pattern for matching email addresses.
   */
  val emailRegexPattern = new FactoryMaker(Pattern.compile("^[a-z0-9._%\\-+]+@(?:[a-z0-9\\-]+\\.)+[a-z]{2,}$", Pattern.CASE_INSENSITIVE)) {}

}

Change the using the CASE_INSENSITIVE flag in compile.

This should make the case insensitivity of the pattern more visible to
someone else who is looking at the code.


package scalaguide.advanced.filters.essential

// #essential-filter-example
import play.api.Logger
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits.defaultContext

object LoggingFilter extends EssentialFilter {
  def apply(nextFilter: EssentialAction) = new EssentialAction {
    def apply(requestHeader: RequestHeader) = {

      val startTime = System.currentTimeMillis

      nextFilter(requestHeader).map { result =>

        val endTime = System.currentTimeMillis
        val requestTime = endTime - startTime

        Logger.info(s"${requestHeader.method} ${requestHeader.uri}" +
          s" took ${requestTime}ms and returned ${result.header.status}")
        result.withHeaders("Request-Time" -> requestTime.toString)

      }
    }
  }
}
// #essential-filter-example

package scalaguide.advanced.filters.essential

// #essential-filter-example
import play.api.Logger
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class LoggingFilter extends EssentialFilter {
  def apply(nextFilter: EssentialAction) = new EssentialAction {
    def apply(requestHeader: RequestHeader) = {

      val startTime = System.currentTimeMillis

      nextFilter(requestHeader).map { result =>

        val endTime = System.currentTimeMillis
        val requestTime = endTime - startTime

        Logger.info(s"${requestHeader.method} ${requestHeader.uri}" +
          s" took ${requestTime}ms and returned ${result.header.status}")
        result.withHeaders("Request-Time" -> requestTime.toString)

      }
    }
  }
}
// #essential-filter-example

Change LoggingFilter to be a class

[doc] Change LoggingFilter to be a class


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

package com.powertuple.intellij.haskell.navigate

import com.intellij.navigation.{ChooseByNameContributor, NavigationItem}
import com.intellij.openapi.project.Project
import com.powertuple.intellij.haskell.util.HaskellFindUtil

class HaskellDeclarationContributor extends ChooseByNameContributor {

  def getNames(project: Project, includeNonProjectItems: Boolean): Array[String] = {
    HaskellFindUtil.findDeclarationElements(project, includeNonProjectItems).flatMap(_.getIdentifierElements.map(_.getName)).toArray
  }

  def getItemsByName(name: String, pattern: String, project: Project, includeNonProjectItems: Boolean): Array[NavigationItem] = {
    HaskellFindUtil.findDeclarationElements(project, pattern, includeNonProjectItems).toSeq.toArray
  }
}

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

package com.powertuple.intellij.haskell.navigate

import com.intellij.navigation.{ChooseByNameContributor, NavigationItem}
import com.intellij.openapi.project.Project
import com.powertuple.intellij.haskell.util.HaskellFindUtil

class HaskellDeclarationContributor extends ChooseByNameContributor {

  def getNames(project: Project, includeNonProjectItems: Boolean): Array[String] = {
    HaskellFindUtil.findDeclarationElements(project, includeNonProjectItems).flatMap(_.getIdentifierElements.map(_.getName)).toArray
  }

  def getItemsByName(name: String, pattern: String, project: Project, includeNonProjectItems: Boolean): Array[NavigationItem] = {
    HaskellFindUtil.findDeclarationElements(project, pattern, includeNonProjectItems).toArray
  }
}

Revert because does not improve search results.


object Solution {
  val moduloP = 1e9.toInt + 7
  val upperBound = 1e5.toInt
  val ways = Array.fill(upperBound + 1)(0)
  ways(0) = 1
  val coinSizes = Array(1, 2, 5, 10, 20, 50, 100, 200)
  for {i <- 0 until coinSizes.length
       j <- coinSizes(i) to upperBound} {
     ways(j) = (ways(j) + ways(j - coinsSize(i))) % moduloP
  }

  def main(args: Array[String]) {
    val t = readLine.toInt
    for (i <- 1 to t) {
      val n = readLine.toInt
      println(ways(n))
    }
  }
}

object Solution {
  val moduloP = 1e9.toInt + 7
  val coinSizes = Array(1, 2, 5, 10, 20, 50, 100, 200)

  def countTable(coinSizes: Array[Int], n: Int): Array[Int] = {
    val ways = Array.fill(n + 1)(0)
    ways(0) = 1
    for {i <- 0 until coinSizes.length
         j <- coinSizes(i) to n} {
      ways(j) = (ways(j) + ways(j - coinSizes(i))) % moduloP
    }
    ways
  }

  def main(args: Array[String]) {
    val t = readLine.toInt
    val testCases = (1 to t).map(x => readLine.toInt)
    val n = testCases.max
    val table = countTable(coinSizes, n)
    testCases foreach { x =>
      println(table(x))
    }
  }
}

Update the solution for problem 31.

Update the solution for problem 31.


package gloving

import scala.collection.mutable.SortedSet

object Top {
	implicit class ToppableTraversable[T](val self: TraversableOnce[T]) extends AnyVal {
		def top(n: Int)(implicit ord: Ordering[T]): Seq[T] = {
			var topValues = SortedSet[T]()

	    var min: Option[T] = None

	    self.foreach { e =>
	    	if (topValues.size < n) {

	    		topValues += e

	    		min = Some(topValues.head)

	    	} else if (ord.gt(e, min.get)) {
	    		//If e is greater than the lowest value we've seen  yet, bump the lowest value and replace it with e

	      	topValues -= min.get
	      	topValues += e

	      	min = Some(topValues.head)
	      }
	    }

	    topValues.toSeq.reverse //The SortedSet stores values from lowest to highest, but this is top n so we want highest to lowest
		}
	}
}

package gloving

import scala.collection._
import scala.collection.generic._
import scala.collection.mutable.SortedSet
import scala.collection.mutable.ArrayOps

object Top {
	implicit class ToppableTraversable[A](val self: GenTraversableOnce[A]) extends AnyVal {
		def top(n: Int)(implicit ord: Ordering[A]): Seq[A] = {
			var topValues = SortedSet[A]()

	    var min: Option[A] = None

	    self.foreach { e =>
	    	if (topValues.size < n) {

	    		topValues += e

	    		min = Some(topValues.head)

	    	} else if (ord.gt(e, min.get)) {
	    		//If e is greater than the lowest value we've seen  yet, bump the lowest value and replace it with e

	      	topValues -= min.get
	      	topValues += e

	      	min = Some(topValues.head)
	      }
	    }

	    topValues.toSeq.reverse //The SortedSet stores values from lowest to highest, but this is top n so we want highest to lowest
		}
	}

	implicit class ToppableArray[A](val self: Array[A]) extends AnyVal {
		def top(n: Int)(implicit ord: Ordering[A]): Seq[A] = {
			//TODO: Get a PhD so I can understand Scala's collection library and implement a generic method that works
			//on Array as well as Iterator types without resorting to this hack
			val ops: ArrayOps[A] = self

			ops.top(n)
		}
	}
}

Extend my top() implementation to work with arrays as well as iterators


import sbt._
class Plugins(info: ProjectInfo) extends PluginDefinition(info) {

  // Add ScalaToolsSnapshots
  lazy val snapshots = ScalaToolsSnapshots

  // Add plugin
  lazy val liftsbt = "net.liftweb" % "lift-sbt" % "2.4-SNAPSHOT"
  lazy val bnd4sbt = "com.weiglewilczek.bnd4sbt" % "bnd4sbt" % "1.0.2"
}

import sbt._
class Plugins(info: ProjectInfo) extends PluginDefinition(info) {

  // Add ScalaToolsSnapshots
  lazy val snapshots = ScalaToolsSnapshots

  // Add plugin
  lazy val liftsbt = "net.liftweb" % "lift-sbt" % "2.5-SNAPSHOT"
  lazy val bnd4sbt = "com.weiglewilczek.bnd4sbt" % "bnd4sbt" % "1.0.2"
}

Update to use 2.5-SNAPSHOT of lift-sbt plugin


package com.roundeights.shnappy.admin

import scala.concurrent.ExecutionContext.Implicits.global
import com.roundeights.skene._
import com.roundeights.shnappy._

/**
 * Page HTML handler
 */
class HtmlHandler (
    val template: Templater, val req: Registry
) extends Skene {

    get("/admin")(
        req.use[Auth, AdminTemplate].in((prereqs, resp, recover) => {
            if ( prereqs.user.sites.size > 1 || prereqs.user.isAdmin ) {
                resp.html( prereqs.template("admin/pages/sites") ).done
            }
            else {
                resp.moved("/admin/site/%s".format(
                    prereqs.user.sites.head.toString
                )).done
            }
        })
    )

    get("/admin/users")(
        req.use[Admin, AdminTemplate].in((prereqs, resp, recover) => {
            resp.html( prereqs.template("admin/pages/users") ).done
        })
    )

    get("/admin/sites/:siteID")(
        req.use[SiteEditor, AdminTemplate].in((prereqs, resp, recover) => {
            resp.html( prereqs.template("admin/pages/edit") ).done
        })
    )
}

package com.roundeights.shnappy.admin

import scala.concurrent.ExecutionContext.Implicits.global
import com.roundeights.skene._
import com.roundeights.shnappy._

/**
 * Page HTML handler
 */
class HtmlHandler (
    val template: Templater, val req: Registry
) extends Skene {

    get("/admin")(
        req.use[Auth, AdminTemplate].in((prereqs, resp, recover) => {
            if ( prereqs.user.sites.size > 1 || prereqs.user.isAdmin ) {
                resp.html( prereqs.template("admin/pages/sites") ).done
            }
            else if ( prereqs.user.sites.size == 0 ) {
                throw new Unauthorized("User can not edit any sites")
            }
            else {
                resp.moved("/admin/site/%s".format(
                    prereqs.user.sites.head.toString
                )).done
            }
        })
    )

    get("/admin/users")(
        req.use[Admin, AdminTemplate].in((prereqs, resp, recover) => {
            resp.html( prereqs.template("admin/pages/users") ).done
        })
    )

    get("/admin/sites/:siteID")(
        req.use[SiteEditor, AdminTemplate].in((prereqs, resp, recover) => {
            resp.html( prereqs.template("admin/pages/edit") ).done
        })
    )
}

Handle non-admin users without permissions


/*
 * Copyright 2016 Krzysztof Pado
 *
 * 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 io.rdbc.sapi

import scala.concurrent.Future

/** Provides access to a database [[Connection]].
  *
  * Implementors are encouraged to make the implementation of this trait thread-safe.
  */
trait ConnectionFactory {

  /** Returns a future of a [[Connection]].
    *
    * Future can fail with subclasses of [[io.rdbc.api.exceptions.ConnectException]]. //TODO describe subclasses
    */
  def connection(): Future[Connection]

  /** Shuts down this connection factory.
    *
    * Returned future never fails - it completes on finished shutdown attempt.
    * After the factory is shut down it is illegal to request new connections from it.
    */
  def shutdown(): Future[Unit]
}

/*
 * Copyright 2016 Krzysztof Pado
 *
 * 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 io.rdbc.sapi

import scala.concurrent.{ExecutionContext, Future}

/** Provides access to a database [[Connection]].
  *
  * Implementors are encouraged to make the implementation of this trait thread-safe.
  */
trait ConnectionFactory {

  /** Execution context used to execute code asynchronously. */
  implicit protected def ec: ExecutionContext

  /** Returns a future of a [[Connection]].
    *
    * Future can fail with subclasses of [[io.rdbc.api.exceptions.ConnectException]]. //TODO describe subclasses
    */
  def connection(): Future[Connection]

  /** Executes a function (which can be passed as a code block) in a context of a connection
    * obtained via [[connection()]], and releases the connection afterwards.
    */
  def withConnection[A](body: Connection => Future[A]): Future[A] = {
    connection().flatMap { conn =>
      body(conn).andThen { case _ =>
        conn.release()
      }
    }
  }

  /** Shuts down this connection factory.
    *
    * Returned future never fails - it completes on finished shutdown attempt.
    * After the factory is shut down it is illegal to request new connections from it.
    */
  def shutdown(): Future[Unit]
}

Use borrow-pattern for obtaining a connection


name := "test"

version := "0.1.0-SNAPSHOT"

libraryDependencies += "javax.servlet" % "javax.servlet-api" % "3.0.1" % "provided"

lazy val root = (project in file("."))
  .enablePlugins(WarPlugin, ContainerPlugin)
  .settings(
    containerLibs in Container := Seq(
      "org.eclipse.jetty" %  "jetty-webapp" % "9.1.0.v20131115"
    , "org.eclipse.jetty" %  "jetty-plus"   % "9.1.0.v20131115"
    , "test"              %% "runner"       % "0.1.0-SNAPSHOT"
    )
  , containerLaunchCmd in Container := Seq("runner.Run", "8080")
  )

lazy val runner = project

name := "test"

version := "0.1.0-SNAPSHOT"

libraryDependencies += "javax.servlet" % "javax.servlet-api" % "3.0.1" % "provided"

lazy val root = (project in file("."))
  .enablePlugins(ContainerPlugin)
  .settings(
    containerLibs in Container := Seq(
      "org.eclipse.jetty" %  "jetty-webapp" % "9.1.0.v20131115"
    , "org.eclipse.jetty" %  "jetty-plus"   % "9.1.0.v20131115"
    , "test"              %% "runner"       % "0.1.0-SNAPSHOT"
    )
  , containerLaunchCmd in Container := Seq("runner.Run", "8080")
  )

lazy val runner = project

Remove unnecessary plugin usage in test

Remove unnecessary plugin usage in test


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

class Plugins(info: ProjectInfo) extends PluginDefinition(info) {

  lazy val fusesource_snapshot_repo = "FuseSource Snapshots" at
           "http://repo.fusesource.com/nexus/content/repositories/snapshots"

  lazy val scalate_plugin = "org.fusesource.scalate" % "sbt-scalate-plugin" % "1.6.1"

}

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

class Plugins(info: ProjectInfo) extends PluginDefinition(info) {

}

Remove unused scalatest plugin references