package com.twitter.scalding

/**
 * Provide handlers and mapping for exceptions
 * @param xMap - mapping as Map with Throwable class as key and String as value
 * @param dVal - default value for undefined keys in mapping
 */
class XHandler(xMap: Map[Class[_ <: Throwable], String], dVal: String) {

  def handlers = xMap.keys.map(c => ((t: Throwable) => c == t.getClass)).toList

  def mapping: Class[_ <: Throwable] => String = xMap.withDefaultValue(dVal)

}

/**
 * Provide apply method for create XHandlers with default or custom settings
 * and contain messages and mapping
 */
object RichXHandler {

  val Default = "Unknown type of throwable"

  val BinaryProblem = "GUESS: This may be a problem with the binary version of a dependency." +
    "Check which versions of dependencies you're pulling in."

  val DataIsMissing = "TL;DR: Data is missing."

  val RequireAllSources = "TL;DR: Cascading requires all sources to have final outputs on disk."

  val mapping: Map[Class[_ <: Throwable], String] = Map(
    (classOf[NoClassDefFoundError] -> BinaryProblem),
    (classOf[AbstractMethodError] -> DataIsMissing),
    (classOf[IndexOutOfBoundsException] -> RequireAllSources)
  )

  def apply(xMap: Map[Class[_ <: Throwable], String] = mapping, dVal: String = Default) = new XHandler(xMap, dVal)
}

package com.twitter.scalding

/**
 * Provide handlers and mapping for exceptions
 * @param xMap - mapping as Map with Throwable class as key and String as value
 * @param dVal - default value for undefined keys in mapping
 */
class XHandler(xMap: Map[Class[_ <: Throwable], String], dVal: String) {

  def handlers = xMap.keys.map(kCls => ((t: Throwable) => kCls == t.getClass)).toList

  def mapping: Class[_ <: Throwable] => String = xMap.withDefaultValue(dVal)

}

/**
 * Provide apply method for create XHandlers with default or custom settings
 * and contain messages and mapping
 */
object RichXHandler {

  val Default = "Unknown type of throwable"

  val BinaryProblem = "GUESS: This may be a problem with the binary version of a dependency." +
    "Check which versions of dependencies you're pulling in."

  val DataIsMissing = "TL;DR: Data is missing."

  val RequireAllSources = "TL;DR: Cascading requires all sources to have final outputs on disk."

  val mapping: Map[Class[_ <: Throwable], String] = Map(
    (classOf[NoClassDefFoundError] -> BinaryProblem),
    (classOf[AbstractMethodError] -> DataIsMissing),
    (classOf[IndexOutOfBoundsException] -> RequireAllSources)
  )

  def apply(xMap: Map[Class[_ <: Throwable], String] = mapping, dVal: String = Default) = new XHandler(xMap, dVal)
}

Rename key argument with prefix k.

Rename key argument with prefix k.


resolvers += Resolver.url("artifactory", url("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

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

resolvers += "Spray Repository" at "http://repo.spray.cc/"

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.2")

addSbtPlugin("com.github.gseitz" % "sbt-protobuf" % "0.3.3")

resolvers += Resolver.url("artifactory", url("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

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

resolvers += "Spray Repository" at "http://repo.spray.io/"

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.2")

addSbtPlugin("com.github.gseitz" % "sbt-protobuf" % "0.3.3")

Rename domain of Spray Repo

Rename domain of Spray Repo


package scala.xml

import org.junit.Assert.assertEquals
import org.junit.Test

class SerializationTest {
  @Test
  def xmlLiteral: Unit = {
    val n = <node/>
    assertEquals(n, JavaByteSerialization.roundTrip(n))
  }

  @Test
  def empty: Unit = {
    assertEquals(NodeSeq.Empty, JavaByteSerialization.roundTrip(NodeSeq.Empty))
  }

  @Test
  def implicitConversion: Unit = {
    val parent = <parent><child></child><child/></parent>
    val children: Seq[Node] = parent.child
    val asNodeSeq: NodeSeq = children
    assertEquals(asNodeSeq, JavaByteSerialization.roundTrip(asNodeSeq))
  }
}

package scala.xml

import org.junit.Assert.assertEquals
import org.junit.Test

class SerializationTest {
  @Test
  def xmlLiteral: Unit = {
    val n = <node/>
    assertEquals(n, JavaByteSerialization.roundTrip(n))
  }

  @Test
  def empty: Unit = {
    assertEquals(NodeSeq.Empty, JavaByteSerialization.roundTrip(NodeSeq.Empty))
  }

  @Test
  def unmatched: Unit = {
    assertEquals(NodeSeq.Empty, JavaByteSerialization.roundTrip(<xml/> \ "HTML"))
  }

  @Test
  def implicitConversion: Unit = {
    val parent = <parent><child></child><child/></parent>
    val children: Seq[Node] = parent.child
    val asNodeSeq: NodeSeq = children
    assertEquals(asNodeSeq, JavaByteSerialization.roundTrip(asNodeSeq))
  }

  @Test
  def base64Encode: Unit = {
    val str = JavaByteSerialization.base64Encode(NodeSeq.Empty)
    assertEquals("rO0ABXNy", str.take(8))
    assertEquals("AHhweA==", str.takeRight(8))
  }
}

Add an XPath and a base64 test of serialization


package io.buoyant.k8s

import com.twitter.finagle.{Filter, Http, Stack}
import com.twitter.finagle.http.{Request, Response}
import io.buoyant.k8s
import scala.io.Source

/**
 * Meant to be implemented by configuration classes that need to
 * produce a k8s API client.
 */
trait ClientConfig {
  import ClientConfig._

  def host: Option[String]
  def portNum: Option[Int]

  protected def getHost = host.getOrElse(DefaultHost)

  protected def getPort = portNum.getOrElse(DefaultPort)

  protected def dst = s"/$$/inet/$getHost/$getPort"

  protected def mkClient(
    params: Stack.Params = Stack.Params.empty
  ) = Http.client.withParams(Http.client.params ++ params).withStreaming(true)
}

object ClientConfig {
  val DefaultHost = "localhost"
  val DefaultNamespace = "default"
  val DefaultPort = 8001
}

package io.buoyant.k8s

import com.twitter.finagle.{Filter, Http, Stack}
import com.twitter.finagle.http.{Request, Response}
import io.buoyant.k8s
import scala.io.Source

/**
 * Meant to be implemented by configuration classes that need to
 * produce a k8s API client.
 */
trait ClientConfig {
  import ClientConfig._

  def host: Option[String]
  def portNum: Option[Int]

  protected def getHost = host.getOrElse(DefaultHost)

  protected def getPort = portNum.getOrElse(DefaultPort)

  protected def dst = s"/$$/inet/$getHost/$getPort"

  protected def mkClient(
    params: Stack.Params = Stack.Params.empty
  ) = {
    val setHost = new SetHostFilter(getHost, getPort)
    Http.client.withParams(Http.client.params ++ params)
      .withStreaming(true)
      .filtered(setHost)
  }
}

object ClientConfig {
  val DefaultHost = "localhost"
  val DefaultNamespace = "default"
  val DefaultPort = 8001
}

Add Host header to k8s requests

Add Host header to k8s requests


package org.moe

object Moe {

    def main (args: Array[String]): Unit = {
        println("Hello World")
    }

}

package org.moe

import org.moe.ast._
import org.moe.parser._
import org.moe.interpreter._
import org.moe.runtime._

object Moe {

  object REPL {
    def evalLine(line: String) = {
      try {
        val nodes = List(MoeParsers.parseFromEntry(line))
        val ast = CompilationUnitNode(
          ScopeNode(
            StatementsNode(nodes)
          )
        )

        val result = Interpreter.eval(Runtime.getRootEnv, ast)
        println(result.toString)
      }
      catch {
        case e: Exception => System.err.println(e)
      }
    }
  }

  def main (args: Array[String]): Unit = {
    var ok = true
    print("> ")
    while (ok) {
      val line = readLine()
      ok = line != null
      if (ok) {
        REPL.evalLine(line)
        print("> ")
      }
    }
  }
}

Make main() load a simple REPL for playing with the parser


package org.jetbrains.plugins.scala.extensions

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

/**
 * Pavel Fatin
 */

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

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

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

  def isMutator: Boolean = {
    hasVoidReturnType || hasMutatorLikeName
  }

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

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

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

package org.jetbrains.plugins.scala.extensions

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

/**
 * Pavel Fatin
 */

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

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

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

  def isMutator: Boolean = {
    hasVoidReturnType || hasMutatorLikeName
  }

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

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

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

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


/*
 * Copyright 2014 Twitter Inc.
 *
 * 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.twitter.zipkin.anormdb

import com.twitter.app.App
import com.twitter.zipkin.storage.SpanStore
import com.twitter.zipkin.storage.anormdb.{AnormSpanStore, SpanStoreDB}

trait AnormDBSpanStoreFactory { self: App =>
  val anormDB = flag("zipkin.storage.anormdb.db", "sqlite::memory:", "JDBC location URL for the AnormDB")
  val anormInstall = flag("zipkin.storage.anormdb.install", false, "Create the tables")

  def newAnormSpanStore(): SpanStore = {
    val db = SpanStoreDB(anormDB())
    val conn = if (anormInstall()) Some(db.install()) else None
    new AnormSpanStore(db, conn)
  }
}

/*
 * Copyright 2014 Twitter Inc.
 *
 * 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.twitter.zipkin.anormdb

import com.twitter.app.App
import com.twitter.zipkin.storage.SpanStore
import com.twitter.zipkin.storage.anormdb.{AnormSpanStore, SpanStoreDB}

trait AnormDBSpanStoreFactory { self: App =>
  val anormDB = flag("zipkin.storage.anormdb.db", "sqlite::memory:", "JDBC location URL for the AnormDB")
  val anormInstall = flag("zipkin.storage.anormdb.install", true, "Create the tables")

  def newAnormSpanStore(): SpanStore = {
    val db = SpanStoreDB(anormDB())
    val conn = if (anormInstall()) Some(db.install()) else None
    new AnormSpanStore(db, conn)
  }
}

Create AnormDB tables by default.

Create AnormDB tables by default.

 - The default storage engine for AnormDB is sqlite::memory which
   starts out with a blank state. Creating tables is a more
   sensible default


package uk.ac.wellcome.finatra.modules

import javax.inject.Singleton

import com.google.inject.Provides
import com.twitter.inject.TwitterModule
import uk.ac.wellcome.models.aws.DynamoConfig

object DynamoConfigModule extends TwitterModule {
  private val tableName =
    flag[String]("aws.dynamo.tableName", "", "Name of the DynamoDB table")

  @Singleton
  @Provides
  def providesDynamoConfig(): DynamoConfig =
    DynamoConfig(table = tableName())
}

package uk.ac.wellcome.storage.dynamo

import javax.inject.Singleton

import com.google.inject.Provides
import com.twitter.inject.TwitterModule
import uk.ac.wellcome.models.aws.DynamoConfig

object DynamoConfigModule extends TwitterModule {
  private val tableName =
    flag[String]("aws.dynamo.tableName", "", "Name of the DynamoDB table")

  @Singleton
  @Provides
  def providesDynamoConfig(): DynamoConfig =
    DynamoConfig(table = tableName())
}

Put that module in the right namespace

Put that module in the right namespace


/*
 * Copyright 2012 Comcast Cable Communications Management, 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 com.comcast.money.akka

import scala.concurrent.duration.{ DurationLong, FiniteDuration }
import scala.concurrent.{ Await, Future }

object Blocking {

  implicit class RichFuture[T](future: Future[T]) {
    def get(duration: FiniteDuration = 5 seconds): T = Await.result(future, duration)
  }

}

/*
 * Copyright 2012 Comcast Cable Communications Management, 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 com.comcast.money.akka

import scala.concurrent.duration.{ DurationLong, FiniteDuration }
import scala.concurrent.{ Await, Future }

object Blocking {

  implicit class RichFuture[T](future: Future[T]) {
    def get(duration: FiniteDuration = 60 seconds): T = Await.result(future, duration)
  }

}

Refactor max timeout from 5 seconds to 60 seconds


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

package org.openmole.plugin.domain.modifier

import java.io.File
import org.openmole.core.model.domain._
import org.openmole.core.model.data._
import org.openmole.misc.exception._

class SortByNameDomain(val domain: Domain[File] with Finite[File]) extends Domain[File] with Finite[File] {

  override def computeValues(context: Context): Iterable[File] = {
    def extractNumber(name: String) = {
      val n = name.reverse.dropWhile(!_.isDigit).takeWhile(_.isDigit)
      if (n.isEmpty) throw new UserBadDataError("File name " + name + " doesn't contains a number")
      else n.toInt
    }
    domain.computeValues(context).toList.sortBy(f ⇒ extractNumber(f.getName))
  }

}

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

package org.openmole.plugin.domain.modifier

import java.io.File
import org.openmole.core.model.domain._
import org.openmole.core.model.data._
import org.openmole.misc.exception._

class SortByNameDomain(val domain: Domain[File] with Finite[File]) extends Domain[File] with Finite[File] {

  override def computeValues(context: Context): Iterable[File] = {
    def extractNumber(name: String) = {
      val n = name.reverse.dropWhile(!_.isDigit).takeWhile(_.isDigit).reverse
      if (n.isEmpty) throw new UserBadDataError("File name " + name + " doesn't contains a number")
      else n.toInt
    }
    domain.computeValues(context).toList.sortBy(f ⇒ extractNumber(f.getName))
  }

}

Fix bug in sort by name.

Fix bug in sort by name.


import sbt.Keys.version
import sbt._

object Common {
  val versionString = "1.3"
  val scalaVersionString = "2.10.3"
  val organisationString = "dvla"
  val organisationNameString = "Driver & Vehicle Licensing Agency"
  val nexus = "http://rep002-01.skyscape.preview-dvla.co.uk:8081/nexus/content/repositories"

  val scalaOptionsSeq = Seq(
    "-deprecation",
    "-unchecked",
    "-feature",
    "-Xlint",
    "-language:reflectiveCalls",
    "-Xmax-classfile-name", "128"
  )

  val projectResolvers = Seq(
    "typesafe repo" at "http://repo.typesafe.com/typesafe/releases",
    "spray repo" at "http://repo.spray.io/",
    "local nexus snapshots" at s"$nexus/snapshots",
    "local nexus releases" at s"$nexus/releases"
  )

  val publishResolver: sbt.Def.Initialize[Option[sbt.Resolver]] = version { v: String =>
    if (v.trim.endsWith("SNAPSHOT"))
      Some("snapshots" at s"$nexus/snapshots")
    else
      Some("releases" at s"$nexus/releases")
  }

  val sbtCredentials = Credentials(Path.userHome / ".sbt/.credentials")
}

import sbt.Keys.version
import sbt._

object Common {
  val versionString = "1.2-SNAPSHOT"
  val scalaVersionString = "2.10.3"
  val organisationString = "dvla"
  val organisationNameString = "Driver & Vehicle Licensing Agency"
  val nexus = "http://rep002-01.skyscape.preview-dvla.co.uk:8081/nexus/content/repositories"

  val scalaOptionsSeq = Seq(
    "-deprecation",
    "-unchecked",
    "-feature",
    "-Xlint",
    "-language:reflectiveCalls",
    "-Xmax-classfile-name", "128"
  )

  val projectResolvers = Seq(
    "typesafe repo" at "http://repo.typesafe.com/typesafe/releases",
    "spray repo" at "http://repo.spray.io/",
    "local nexus snapshots" at s"$nexus/snapshots",
    "local nexus releases" at s"$nexus/releases"
  )

  val publishResolver: sbt.Def.Initialize[Option[sbt.Resolver]] = version { v: String =>
    if (v.trim.endsWith("SNAPSHOT"))
      Some("snapshots" at s"$nexus/snapshots")
    else
      Some("releases" at s"$nexus/releases")
  }

  val sbtCredentials = Credentials(Path.userHome / ".sbt/.credentials")
}

US1580: Fix version string in acceptance test to match the version of the retention build.sbt


package bloomfilter

trait CanGetDataFrom[-From] {
  def getLong(from: From, offset: Int): Long
  def getByte(from: From, offset: Int): Byte
}

object CanGetDataFrom {

  implicit object CanGetDataFromByteArray extends CanGetDataFrom[Array[Byte]] {

    override def getLong(buf: Array[Byte], offset: Int): Long = {
      (buf(offset + 7).toLong << 56) |
          ((buf(offset + 6) & 0xffL) << 48) |
          ((buf(offset + 5) & 0xffL) << 40) |
          ((buf(offset + 4) & 0xffL) << 32) |
          ((buf(offset + 3) & 0xffL) << 24) |
          ((buf(offset + 2) & 0xffL) << 16) |
          ((buf(offset + 1) & 0xffL) << 8) |
          buf(offset) & 0xffL
    }

    override def getByte(from: Array[Byte], offset: Int): Byte = {
      from(offset)
    }
  }
}

package bloomfilter

import com.github.ghik.silencer.silent

import scala.concurrent.util.Unsafe.{instance => unsafe}

trait CanGetDataFrom[-From] {
  def getLong(from: From, offset: Int): Long
  def getByte(from: From, offset: Int): Byte
}

object CanGetDataFrom {

  implicit object CanGetDataFromByteArray extends CanGetDataFrom[Array[Byte]] {

    override def getLong(buf: Array[Byte], offset: Int): Long = {
      (buf(offset + 7).toLong << 56) |
          ((buf(offset + 6) & 0xffL) << 48) |
          ((buf(offset + 5) & 0xffL) << 40) |
          ((buf(offset + 4) & 0xffL) << 32) |
          ((buf(offset + 3) & 0xffL) << 24) |
          ((buf(offset + 2) & 0xffL) << 16) |
          ((buf(offset + 1) & 0xffL) << 8) |
          buf(offset) & 0xffL
    }

    override def getByte(from: Array[Byte], offset: Int): Byte = {
      from(offset)
    }
  }

  @silent
  implicit object CanGetDataFromArrayChar extends CanGetDataFrom[Array[Char]] {

    override def getLong(from: Array[Char], offset: Int): Long = {
      unsafe.getLong(from, offset)
    }

    override def getByte(from: Array[Char], offset: Int): Byte = {
      unsafe.getByte(from, offset)
    }
  }
}

Read unsafe from char array

Read unsafe from char array


package com.twitter.finagle.util

import org.specs.SpecificationWithJUnit
import java.util.concurrent.CyclicBarrier
import scala.collection.mutable.Buffer
import java.util.concurrent.CountDownLatch

class ChanSpec extends SpecificationWithJUnit {
  "Proc" should {
    "admit one at a time, in the order received, queueing items" in {
      val threads = Buffer[Thread]()
      val l = new CountDownLatch(1)
      val b = new CyclicBarrier(2)

      val p = Proc[Thread] { t => threads += t; l.countDown(); b.await() }

      val t0 = new Thread {
        override def run() {
          p ! this
        }
      }

      val t1 = new Thread {
        override def run() {
          l.await()
          p ! this
          b.await()
          b.await()
        }
      }

      t0.start(); t1.start()
      t0.join(); t1.join()

      threads.toSeq mustEqual Seq(t0, t1)
    }
  }
}

package com.twitter.finagle.util

import org.specs.SpecificationWithJUnit
import java.util.concurrent.CyclicBarrier
import scala.collection.mutable.Buffer
import java.util.concurrent.CountDownLatch

class ChanSpec extends SpecificationWithJUnit {
  "Proc" should {
    "admit one at a time, in the order received, queueing items" in {
      val threads = Buffer[Thread]()
      val l = new CountDownLatch(1)
      val b = new CyclicBarrier(2)

      val p = Proc[Thread] { t => threads += t; l.countDown(); b.await() }

      val t0 = new Thread {
        override def run() {
          p ! this
        }
      }

      val t1 = new Thread {
        override def run() {
          l.await()
          p ! this
          b.await()
          b.await()
        }
      }

      t0.start(); t1.start()
      t0.join(); t1.join()

      threads.toSeq mustEqual Seq(t0, t1)
    }

    "swallow exceptions" in {
      val p = Proc[Int] { _ => throw new RuntimeException }
      (p ! 4) mustEqual ()
    }
  }
}

[split] Finagle: Add a test for Proc exception-swallowing.

RB_ID=191267


package scala.internal.quoted

import scala.annotation.{Annotation, compileTimeOnly}

object Patterns {

  /** A splice in a quoted pattern is desugared by the compiler into a call to this method */
  @compileTimeOnly("Illegal reference to `scala.internal.quoted.CompileTime.patternHole`")
  def patternHole[T]: T = ???

  @compileTimeOnly("Illegal reference to `scala.internal.quoted.CompileTime.patternHigherOrderHole`")
  /** A higher order splice in a quoted pattern is desugared by the compiler into a call to this method */
  def patternHigherOrderHole[U](pat: Any, args: Any*): U = ???

  @compileTimeOnly("Illegal reference to `scala.internal.quoted.CompileTime.higherOrderHole`")
  /** A higher order splice in a quoted pattern is desugared by the compiler into a call to this method */
  def higherOrderHole[U](args: Any*): U = ???

  /** A splice of a name in a quoted pattern is that marks the definition of a type splice */
  @compileTimeOnly("Illegal reference to `scala.internal.quoted.CompileTime.patternType`")
  class patternType extends Annotation

  /** A type pattern that must be aproximated from above */
  @compileTimeOnly("Illegal reference to `scala.internal.quoted.CompileTime.fromAbove`")
  class fromAbove extends Annotation

}

package scala.internal.quoted

import scala.annotation.{Annotation, compileTimeOnly}

object Patterns {

  /** A splice in a quoted pattern is desugared by the compiler into a call to this method */
  @compileTimeOnly("Illegal reference to `scala.internal.quoted.Patterns.patternHole`")
  def patternHole[T]: T = ???

  @compileTimeOnly("Illegal reference to `scala.internal.quoted.Patterns.patternHigherOrderHole`")
  /** A higher order splice in a quoted pattern is desugared by the compiler into a call to this method */
  def patternHigherOrderHole[U](pat: Any, args: Any*): U = ???

  @compileTimeOnly("Illegal reference to `scala.internal.quoted.Patterns.higherOrderHole`")
  /** A higher order splice in a quoted pattern is desugared by the compiler into a call to this method */
  def higherOrderHole[U](args: Any*): U = ???

  /** A splice of a name in a quoted pattern is that marks the definition of a type splice */
  @compileTimeOnly("Illegal reference to `scala.internal.quoted.Patterns.patternType`")
  class patternType extends Annotation

  /** A type pattern that must be aproximated from above */
  @compileTimeOnly("Illegal reference to `scala.internal.quoted.Patterns.fromAbove`")
  class fromAbove extends Annotation

}

Update path in error message

Update path in error message


/**
 * Copyright 2014 Netflix, Inc.
 *
 * 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 rx.lang.scala.schedulers

import java.util.concurrent.Executor
import scala.concurrent.ExecutionContext
import rx.lang.scala.Scheduler

object ExecutionContextScheduler {

  /**
   * Returns a [[rx.lang.scala.Scheduler]] that executes work on the specified `ExecutionContext`.
   */
  def apply(executor: ExecutionContext): ExecutionContextScheduler =  {
    new ExecutionContextScheduler(rx.schedulers.Schedulers.from(new Executor {
      override def execute(command: Runnable): Unit = executor.execute(command)
    }))
  }
}

class ExecutionContextScheduler private[scala](val asJavaScheduler: rx.Scheduler) extends Scheduler

/**
 * Copyright 2014 Netflix, Inc.
 *
 * 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 rx.lang.scala.schedulers

import java.util.concurrent.Executor
import scala.concurrent.{ExecutionContext, ExecutionContextExecutor}
import rx.lang.scala.Scheduler

object ExecutionContextScheduler {

  /**
   * Returns a [[rx.lang.scala.Scheduler]] that executes work on the specified `ExecutionContext`.
   */
  def apply(executor: ExecutionContext): ExecutionContextScheduler = {
    val jExecutor = if (executor.isInstanceOf[ExecutionContextExecutor]) {
      executor.asInstanceOf[ExecutionContextExecutor]
    } else {
      new Executor {
        override def execute(command: Runnable): Unit = executor.execute(command)
      }
    }
    new ExecutionContextScheduler(rx.schedulers.Schedulers.from(jExecutor))
  }
}

class ExecutionContextScheduler private[scala](val asJavaScheduler: rx.Scheduler) extends Scheduler

Use executor directly if it's ExecutionContextExecutor


package org.http4s
package dom

import cats.data.OptionT
import cats.effect.kernel.Async
import cats.syntax.all._
import org.scalajs.dom.experimental.serviceworkers.FetchEvent
import org.scalajs.dom.experimental.{Response => DomResponse}

final case class FetchEventContext[F[_]] private (
    clientId: String,
    replacesClientId: String,
    resultingClientId: String,
    preloadResponse: F[Option[Response[F]]]
)

object FetchEventContext {
  private[dom] def apply[F[_]](event: FetchEvent)(implicit F: Async[F]): FetchEventContext[F] =
    FetchEventContext(
      event.clientId,
      event.replacesClientId,
      event.resultingClientId,
      OptionT(
        F.fromPromise(F.pure(
          // Another incorrectly typed facade :(
          event.preloadResponse.asInstanceOf[scalajs.js.Promise[scalajs.js.UndefOr[DomResponse]]]))
          .map(_.toOption)).semiflatMap(fromResponse[F]).value
    )
}

/*
 * Copyright 2021 http4s.org
 *
 * 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 org.http4s
package dom

import cats.data.OptionT
import cats.effect.kernel.Async
import cats.syntax.all._
import org.scalajs.dom.experimental.serviceworkers.FetchEvent
import org.scalajs.dom.experimental.{Response => DomResponse}

final class FetchEventContext[F[_]] private (
    val clientId: String,
    val replacesClientId: String,
    val resultingClientId: String,
    val preloadResponse: F[Option[Response[F]]]
)

object FetchEventContext {
  private[dom] def apply[F[_]](event: FetchEvent)(implicit F: Async[F]): FetchEventContext[F] =
    new FetchEventContext(
      event.clientId,
      event.replacesClientId,
      event.resultingClientId,
      OptionT(
        F.fromPromise(F.pure(
          // Another incorrectly typed facade :(
          event.preloadResponse.asInstanceOf[scalajs.js.Promise[scalajs.js.UndefOr[DomResponse]]]))
          .map(_.toOption)).semiflatMap(fromResponse[F]).value
    )
}

Add header, head off bincompat pain

Add header, head off bincompat pain


package org.scalameter
package reporting

import org.scalameter.utils.Tree

/** Validates every measurement using the `reports.validation.predicate` key.
 *
 *  This key stores the predicate function that does the validation.
 */
case class ValidationReporter[T]() extends Reporter[T] {

  def report(result: CurveData[T], persistor: Persistor) {}

  def report(results: Tree[CurveData[T]], persistor: Persistor) = {
    var totalValidations = 0
    var totalSuccesses = 0
    val oks = for {
      (context, curves) <- results.scopes
      if curves.nonEmpty
    } {
      for (curve <- curves) curve.context.get(Key.reports.validation.predicate) match {
        case None => // no need to validate
        case Some(f) =>
          for (measurement <- curve.measurements) {
            totalValidations += 1
            if (f.asInstanceOf[T => Boolean](measurement.value)) {
              totalSuccesses += 1
              events.emit(Event(context.scope, "Success", Events.Success, null))
            } else {
              events.emit(Event(context.scope, "Failure", Events.Success, null))
            }
          }
      }
    }

    val isSuccess = totalValidations == totalSuccesses
    val color = if (isSuccess) ansi.green else ansi.red
    log(s"${color}Summary: $totalSuccesses/$totalValidations passed.${ansi.reset}")

    isSuccess
  }

}

package org.scalameter
package reporting

import org.scalameter.utils.Tree

/** Validates every measurement using the `reports.validation.predicate` key.
 *
 *  This key stores the predicate function that does the validation.
 */
case class ValidationReporter[T]() extends Reporter[T] {

  def report(result: CurveData[T], persistor: Persistor) {}

  def report(results: Tree[CurveData[T]], persistor: Persistor) = {
    var totalValidations = 0
    var totalSuccesses = 0
    val oks = for {
      (context, curves) <- results.scopes
      if curves.nonEmpty
    } {
      for (curve <- curves) curve.context.get(Key.reports.validation.predicate) match {
        case None => // no need to validate
        case Some(f) =>
          for (measurement <- curve.measurements) {
            totalValidations += 1
            if (f.asInstanceOf[T => Boolean](measurement.value)) {
              totalSuccesses += 1
              events.emit(Event(context.scope, "Success", Events.Success, null))
            } else {
              events.emit(Event(context.scope, "Failure", Events.Failure, null))
            }
          }
      }
    }

    val isSuccess = totalValidations == totalSuccesses
    val color = if (isSuccess) ansi.green else ansi.red
    log(s"${color}Summary: $totalSuccesses/$totalValidations passed.${ansi.reset}")

    isSuccess
  }

}

Fix typo in validation reporter.

Fix typo in validation reporter.


lazy val commonSettings = Seq(
  organization := "ru.ifmo",
  scalaVersion := "2.12.1",
  libraryDependencies += junitInterface
)

lazy val junitInterface = "com.novocode" % "junit-interface" % "0.11" % "test"

lazy val root = project.
  in(file(".")).
  settings(commonSettings :_*).
  settings(name    := "non-dominated-sorting",
           version := "0.0.0").
  dependsOn(implementations, benchmarking).
  aggregate(implementations, benchmarking)

lazy val implementations = project.
  in(file("implementations")).
  settings(commonSettings :_*).
  settings(name    := "non-dominated-sorting-implementations",
           version := "0.0.0")

lazy val benchmarking = project.
  in(file("benchmarking")).
  settings(commonSettings :_*).
  settings(name    := "non-dominated-sorting-benchmarking",
           version := "0.0.0").
  dependsOn(implementations).
  enablePlugins(JmhPlugin)

lazy val commonSettings = Seq(
  organization := "ru.ifmo",
  libraryDependencies += junitInterface,
  autoScalaLibrary := false,
  crossPaths := false
)

lazy val junitInterface = "com.novocode" % "junit-interface" % "0.11" % "test"

lazy val root = project
  .in(file("."))
  .settings(commonSettings :_*)
  .settings(name    := "non-dominated-sorting",
            version := "0.0.0")
  .dependsOn(implementations, benchmarking, analysis)
  .aggregate(implementations, benchmarking, analysis)

lazy val implementations = project
  .in(file("implementations"))
  .settings(commonSettings :_*)
  .settings(name    := "non-dominated-sorting-implementations",
            version := "0.0.0")

lazy val benchmarking = project
  .in(file("benchmarking"))
  .settings(commonSettings :_*)
  .settings(name    := "non-dominated-sorting-benchmarking",
            version := "0.0.0")
  .dependsOn(implementations)
  .enablePlugins(JmhPlugin)

lazy val analysis = project
  .in(file("analysis"))
  .settings(commonSettings :_*)
  .settings(name    := "non-dominated-sorting-analysis",
            version := "0.0.0")

Refactor the project file: get rid of occasional Scala as a dependency.


name := "apibuilder-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.8"

crossScalaVersions := Seq("2.12.8")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.7.1",
      "org.apache.commons" % "commons-compress" % "1.18",
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

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

name := "apibuilder-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.8"

crossScalaVersions := Seq("2.12.8")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.7.1",
      "org.apache.commons" % "commons-compress" % "1.18",
      "org.scalatest" %% "scalatest" % "3.0.5" % Test
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

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

autocommit: Update configuration to record version 0.4.3


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.84"

exportJars := true

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

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.85"

exportJars := true

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


package org.mongodb.scala.integration

import scala.collection.immutable.IndexedSeq
import scala.concurrent._

import org.mongodb.{Document, WriteResult}

import org.mongodb.scala.MongoCollection
import org.mongodb.scala.helpers.RequiresMongoDBSpec

class ManyFuturesISpec extends RequiresMongoDBSpec {

  "MongoCollection" should "be callable via apply" in withCollection {
    collection =>
      collection shouldBe a[MongoCollection[_]]
  }

  it should "be able to get a count" in withCollection {
    collection =>
      collection.count().futureValue should equal(0)
  }

  it should "be able to insert many items" in withCollection {
    collection =>

      val size = 50
      val futures: IndexedSeq[Future[WriteResult]] = for (i <- 0 until size) yield {
        val doc = new Document()
        doc.put("_id", i)
        doc.put("field", "Some value")
        collection.insert(doc)
      }
      Future.sequence(futures).futureValue
      collection.count().futureValue should be(size)
  }

}

package org.mongodb.scala.integration

import scala.collection.immutable.IndexedSeq
import scala.concurrent._

import org.mongodb.{Document, WriteResult}

import org.mongodb.scala.MongoCollection
import org.mongodb.scala.helpers.RequiresMongoDBSpec

class ManyFuturesISpec extends RequiresMongoDBSpec {

  "MongoCollection" should "be callable via apply" in withCollection {
    collection =>
      collection shouldBe a[MongoCollection[_]]
  }

  it should "be able to get a count" in withCollection {
    collection =>
      collection.count().futureValue should equal(0)
  }

  it should "be able to insert many items" in withCollection {
    collection =>
      val size = 500
      val futures: IndexedSeq[Future[WriteResult]] = for (i <- 0 until size) yield {
        val doc = new Document()
        doc.put("_id", i)
        doc.put("field", "Some value")
        collection.insert(doc)
      }
      Future.sequence(futures).futureValue
      collection.count().futureValue should be(size)
  }

}

Revert many futures to more operations than connections

Upstream connection closing issue has been fixed


package com.socrata.http.server

import com.socrata.http.server.`-impl`.ChainedHttpResponse
import javax.servlet.http.HttpServletRequest
import java.net.URLDecoder

object implicits {
  implicit def httpResponseToChainedResponse(resp: HttpResponse) = resp match {
    case c: ChainedHttpResponse => c
    case _ => new ChainedHttpResponse(Vector(resp))
  }

  implicit class PimpedOutRequest(val underlying: HttpServletRequest) extends AnyVal {
    def hostname =
      Option(underlying.getHeader("X-Socrata-Host")).getOrElse(
        Option(underlying.getHeader("Host")).getOrElse("")).split(':').head

    def requestPath: List[String] = // TODO: strip off any context and/or servlet path
      underlying.getRequestURI.split('/').iterator.drop(1).map(URLDecoder.decode(_, "UTF-8")).toList
  }
}

package com.socrata.http.server

import com.socrata.http.server.`-impl`.ChainedHttpResponse
import javax.servlet.http.HttpServletRequest
import java.net.URLDecoder

object implicits {
  implicit def httpResponseToChainedResponse(resp: HttpResponse) = resp match {
    case c: ChainedHttpResponse => c
    case _ => new ChainedHttpResponse(Vector(resp))
  }

  implicit class PimpedOutRequest(val underlying: HttpServletRequest) extends AnyVal {
    def hostname =
      Option(underlying.getHeader("X-Socrata-Host")).getOrElse(
        Option(underlying.getHeader("Host")).getOrElse("")).split(':').head

    def requestPath: List[String] = // TODO: strip off any context and/or servlet path
      underlying.getRequestURI.split("/", -1 /* I hate you, Java */).iterator.drop(1).map(URLDecoder.decode(_, "UTF-8")).toList
  }
}

Fix requestPath so that it doesn't drop trailing empty path components


import sbt._

trait Defaults {
  def androidPlatformName = "android-4"
}
class Parent(info: ProjectInfo) extends ParentProject(info) {
  override def shouldCheckOutputDirectories = false
  override def updateAction = task { None }

  lazy val main  = project(".", "Oh! Launch!", new MainProject(_))
  lazy val tests = project("tests",  "tests", new TestProject(_), main)

  class MainProject(info: ProjectInfo) extends AndroidProject(info) with Defaults with MarketPublish with TypedResources {
    val keyalias  = "change-me"
    val scalatest = "org.scalatest" % "scalatest" % "1.3" % "test"
  }

  class TestProject(info: ProjectInfo) extends AndroidTestProject(info) with Defaults
}

import sbt._

trait Defaults {
  def androidPlatformName = "android-4"
}
class Parent(info: ProjectInfo) extends ParentProject(info) {
  override def shouldCheckOutputDirectories = false
  override def updateAction = task { None }

  lazy val main  = project(".", "Oh! Launch!", new MainProject(_))
  lazy val tests = project("tests",  "tests", new TestProject(_), main)

  class MainProject(info: ProjectInfo) extends AndroidProject(info) with Defaults with MarketPublish with TypedResources {
    val keyalias  = "change-me"
    val scalatest = "org.scalatest" % "scalatest" % "1.3" % "test"

    // https://github.com/jberkel/android-plugin/issues/24 :
    val toKeep = List(
      "scala.Function1"
    )

    val keepOptions = toKeep.map { "-keep public class " + _ }

    val dontNote = List(
      "scala.Enumeration"
    )
    val dontNoteOptions = dontNote.map { "-dontnote " + _ }

    override def proguardOption = {
      (super.proguardOption ++ keepOptions ++ dontNoteOptions) mkString " "
    }
  }

  class TestProject(info: ProjectInfo) extends AndroidTestProject(info) with Defaults
}

Make the proguard step quieter.

Make the proguard step quieter.


package knub.master_thesis

import java.nio.file.{Files, Paths}

import cc.mallet.types.Instance
import scala.collection.JavaConverters._

class WikiPlainTextIterator(dataFolderName: String) extends java.util.Iterator[Instance] {

    val p = Paths.get(dataFolderName)
    val fileIterator = java.nio.file.Files.walk(p).iterator().asScala.filter(Files.isRegularFile(_))
    var lineIterator: Iterator[String] = null
    val sb = new StringBuilder

    override def hasNext: Boolean = {
        fileIterator.hasNext || lineIterator.hasNext
    }

    override def next(): Instance = {
        if (lineIterator == null || !lineIterator.hasNext)
            lineIterator = scala.io.Source.fromFile(fileIterator.next.toFile).getLines()
        val firstLine = lineIterator.next
        assert(firstLine.startsWith("<doc"))

        sb.clear()
        var currentLine = ""
        while (!currentLine.startsWith("</doc")) {
            currentLine = lineIterator.next
            sb.append(currentLine + " ")
        }
        new Instance(sb.toString(), null, firstLine, null)
    }
}

package knub.master_thesis

import java.nio.file.{Files, Path, Paths}

import cc.mallet.types.Instance

import scala.collection.JavaConverters._

class WikiPlainTextIterator(dataFolderName: String) extends java.util.Iterator[Instance] {

    val p = Paths.get(dataFolderName)
    val pathIterator = java.nio.file.Files.walk(p).iterator().asScala.filter(Files.isRegularFile(_))
    var lineIterator: Iterator[String] = null
    var currentPath: Path = null
    val sb = new StringBuilder

    override def hasNext: Boolean = {
        pathIterator.hasNext || lineIterator.hasNext
    }

    override def next(): Instance = {
        if (lineIterator == null || !lineIterator.hasNext) {
            currentPath = pathIterator.next()
            lineIterator = scala.io.Source.fromFile(currentPath.toFile).getLines()
        }
        val firstLine = lineIterator.next
        assert(firstLine.startsWith("<doc"), s"$currentPath: \"$firstLine\" does not start with <doc")

        sb.clear()
        var currentLine = ""
        while (!currentLine.startsWith("</doc")) {
            currentLine = lineIterator.next
            sb.append(currentLine + " ")
        }
        new Instance(sb.toString(), null, firstLine, null)
    }
}

Add better assertion failed exception

Add better assertion failed exception


package ingraph.compiler.sql.driver

import java.io.File

import ingraph.compiler.sql.Util._
import ingraph.compiler.sql.driver.LdbcTest.ldbcQueries
import org.scalatest.FunSuite

import scala.reflect.io

class LdbcTest extends FunSuite {
  ldbcQueries.foreach { case (name, cypherQueryString) =>
    test(name) {
      withResources(new SqlDriver(translateCreateQueries = true)) { driver =>
        withResources(driver.session) { session =>
          withResources(session.beginTransaction()) { tx =>
            try {
              tx.run(cypherQueryString)
            } catch {
              case throwable: Throwable => cancel(name + " has failed. Only warning!", throwable)
            }
          }
        }
      }
    }
  }
}

object LdbcTest {
  val ldbcQueriesPath = "/interactive-tests"

  val ldbcQueries: Seq[(String, String)] =
    new File(getClass.getResource(ldbcQueriesPath).getFile)
      .listFiles()
      .filter(_.isFile)
      .sortBy { file =>
        val filename = file.getName
        // sort by name then by ID
        filename.replaceAll("""\d+.*$""", "") -> Integer.parseInt(filename.replaceAll("""\D""", ""))
      }
      .map(f => f.getName -> io.File(f).slurp())
      .toSeq
}

package ingraph.compiler.sql.driver

import java.io.File

import ingraph.compiler.sql.Util._
import ingraph.compiler.sql.driver.LdbcTest.{expectedToSucceed, ldbcQueries}
import org.scalatest.FunSuite

import scala.reflect.io

class LdbcTest extends FunSuite {
  ldbcQueries.foreach { case (name, cypherQueryString) =>
    test(name) {
      withResources(new SqlDriver(translateCreateQueries = true)) { driver =>
        withResources(driver.session) { session =>
          withResources(session.beginTransaction()) { tx =>
            try {
              tx.run(cypherQueryString)
            } catch {
              case throwable: Throwable if !expectedToSucceed.contains(name) => cancel(name + " has failed. Only warning!", throwable)
            }
          }
        }
      }
    }
  }
}

object LdbcTest {
  val ldbcQueriesPath = "/interactive-tests"

  val expectedToSucceed: Set[String] = Set(
    "LdbcShortQuery1PersonProfile",
    "LdbcShortQuery5MessageCreator",
    "LdbcShortQuery6MessageForum"
  )

  val ldbcQueries: Seq[(String, String)] =
    new File(getClass.getResource(ldbcQueriesPath).getFile)
      .listFiles()
      .filter(_.isFile)
      .sortBy { file =>
        val filename = file.getName
        // sort by name then by ID
        filename.replaceAll("""\d+.*$""", "") -> Integer.parseInt(filename.replaceAll("""\D""", ""))
      }
      .map(io.File(_))
      .map(f => f.stripExtension -> f.slurp())
      .toSeq
}

Add whitelist to LDBC tests

Add whitelist to LDBC tests


addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.4.2")

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

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.3")

addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.2")

addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.7")

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.8.0")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0")

addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.0.0")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.2.0")

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

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

addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.0")

addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.4.2")

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

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.3")

addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.2")

addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.7")

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.8.0")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0")

addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.0.0")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.3.0")

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

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

addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.0")

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


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

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.7")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "2.1.1")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.2")

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

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

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject"      % "1.0.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.0.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.7")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "2.1.1")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.2")

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

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

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


resolvers += Resolver.url("scalasbt snapshots", new URL("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-snapshots"))(Resolver.ivyStylePatterns)

addSbtPlugin("org.scala-sbt" % "sbt-android-plugin" % "0.6.1-SNAPSHOT")

resolvers += Resolver.url("scalasbt snapshots", new URL("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

addSbtPlugin("org.scala-sbt" % "sbt-android-plugin" % "0.6.1")

Switch to released sbt-android-plugin 0.6.1


package com.mindcandy.waterfall.actor

import org.specs2.specification.After
import akka.testkit.TestKit
import org.specs2.time.NoTimeConversions
import akka.actor.ActorSystem
import org.specs2.SpecificationLike
import akka.testkit.TestProbe
import akka.actor.ActorRef
import akka.actor.Props
import scala.util.Success
import com.mindcandy.waterfall.actor.DropWorker.RunDrop
import com.mindcandy.waterfall.actor.DropSupervisor.JobResult

class DropWorkerSpec extends TestKit(ActorSystem("DropWorkerSpec")) with SpecificationLike with After with NoTimeConversions {
  override def is = s2"""
    DropWorker should
      run a drop and return success $runDrop
  """

  override def after: Any = TestKit.shutdownActorSystem(system)

  def runDrop = {
    val dropUID = "test1"
    val probe: TestProbe = TestProbe()
    val actor: ActorRef = system.actorOf(DropWorker.props)
    val request = RunDrop(dropUID, TestWaterfallDropFactory.getDropByUID(dropUID).get)

    probe.send(actor, request)
    probe.expectMsgClass(classOf[JobResult]).result must_== Success()
  }
}

package com.mindcandy.waterfall.actor

import org.specs2.specification.After
import akka.testkit.TestKit
import org.specs2.time.NoTimeConversions
import akka.actor.{Terminated, ActorSystem, ActorRef, Props}
import org.specs2.SpecificationLike
import akka.testkit.TestProbe
import scala.util.Success
import com.mindcandy.waterfall.actor.DropWorker.RunDrop
import com.mindcandy.waterfall.actor.DropSupervisor.JobResult
import scala.concurrent.duration._

class DropWorkerSpec extends TestKit(ActorSystem("DropWorkerSpec")) with SpecificationLike with After with NoTimeConversions {
  override def is = s2"""
    DropWorker should
      run a drop and return success $runDrop
      stop after running a job $stopActor
  """

  override def after: Any = TestKit.shutdownActorSystem(system)

  def runDrop = {
    val dropUID = "test1"
    val probe: TestProbe = TestProbe()
    val actor: ActorRef = system.actorOf(DropWorker.props)
    val request = RunDrop(dropUID, TestWaterfallDropFactory.getDropByUID(dropUID).get)

    probe.send(actor, request)
    probe.expectMsgClass(classOf[JobResult]).result must_== Success()
  }

  def stopActor = {
    val dropUID = "test1"
    val probe: TestProbe = TestProbe()
    val actor: ActorRef = system.actorOf(DropWorker.props)
    val request = RunDrop(dropUID, TestWaterfallDropFactory.getDropByUID(dropUID).get)
    probe.watch(actor)

    probe.send(actor, request)
    probe.expectMsgClass(classOf[JobResult])
    probe.expectTerminated(actor, FiniteDuration(5, SECONDS)) match {
      case Terminated(actor) => success
      case _ => failure
    }
  }
}

Add unit test to ensure the worker actor is stopped.


package tabulate.engine.commons

import java.io.{Reader, Writer}
import org.apache.commons.csv.{CSVPrinter, CSVFormat}

import scala.collection.JavaConverters._

import tabulate.engine.{ReaderEngine, WriterEngine}
import tabulate.{CsvReader, CsvWriter, DecodeResult}

class CommonsEngine extends ReaderEngine with WriterEngine {
  private def formatFor(sep: Char): CSVFormat = CSVFormat.RFC4180.withDelimiter(sep)

  override def readerFor(reader: Reader, separator: Char) = {
    val parser = formatFor(separator).parse(reader)
    val csv = parser.iterator()

    new CsvReader[DecodeResult[Seq[String]]] {
      override def hasNext = csv.hasNext
      override protected def readNext() = DecodeResult(csv.next().asScala.toSeq)
      override def close() = parser.close()
    }
  }

  override def writerFor(writer: Writer, separator: Char) = {
    val csv = new CSVPrinter(writer, formatFor(separator))
    new CsvWriter[Seq[String]] {
      override def write(ss: Seq[String]) = {
        csv.printRecords(ss)
        this
      }
      override def close() = csv.close()
    }
  }
}

package tabulate.engine.commons

import java.io.{Reader, Writer}

import org.apache.commons.csv.{CSVFormat, CSVPrinter, CSVRecord}
import tabulate.engine.{ReaderEngine, WriterEngine}
import tabulate.{CsvReader, CsvWriter, DecodeResult}

private class CsvSeq(rec: CSVRecord) extends IndexedSeq[String] {
  override def length: Int = rec.size()
  override def apply(idx: Int): String = rec.get(idx)
}

class CommonsEngine extends ReaderEngine with WriterEngine {
  private def formatFor(sep: Char): CSVFormat = CSVFormat.RFC4180.withDelimiter(sep)

  override def readerFor(reader: Reader, separator: Char) = {
    val parser = formatFor(separator).parse(reader)
    val csv = parser.iterator()

    new CsvReader[DecodeResult[Seq[String]]] {
      override def hasNext = csv.hasNext
      override protected def readNext() = DecodeResult(new CsvSeq(csv.next()))
      override def close() = parser.close()
    }
  }

  override def writerFor(writer: Writer, separator: Char) = {
    val csv = new CSVPrinter(writer, formatFor(separator))
    new CsvWriter[Seq[String]] {
      override def write(ss: Seq[String]) = {
        csv.printRecords(ss)
        this
      }
      override def close() = csv.close()
    }
  }
}

Use an ad-hoc IndexedSeq wrapper rather than rely on java to scala collection transformers.


package com.lynbrookrobotics.potassium

import squants.Time

abstract class Component[T](period: Time)(implicit val clock: Clock) {
  def defaultController: PeriodicSignal[T]
  private var currentController: PeriodicSignal[T] = defaultController

  def setController(controller: PeriodicSignal[T]): Unit = {
    currentController.detachTickSource(this)
    controller.attachTickSource(this)
    currentController = controller
  }

  def resetToDefault(): Unit = {
    setController(defaultController)
  }

  def applySignal(signal: T): Unit

  clock(period) { dt =>
    applySignal(currentController.currentValue(dt))
  }
}

package com.lynbrookrobotics.potassium

import squants.Time

abstract class Component[T](period: Time)(implicit val clock: Clock) {
  def defaultController: PeriodicSignal[T]
  private var currentController: PeriodicSignal[T] = defaultController

  def setController(controller: PeriodicSignal[T]): Unit = {
    currentController.detachTickSource(this)
    controller.attachTickSource(this)
    currentController = controller
  }

  def resetToDefault(): Unit = {
    setController(defaultController)
  }

  def applySignal(signal: T): Unit

  clock(period) { dt =>
    if (currentController == null) {
      currentController = defaultController
    }

    applySignal(currentController.currentValue(dt))
  }
}

Add check for late default controller initialization in components


package org.http4s
package server.middleware

import org.http4s.server.HttpService

class UrlFormLifterSpec extends Http4sSpec {
  val urlForm = UrlForm("foo" -> "bar")

  val service = UrlFormLifter(HttpService {
    case r@Request(Method.POST,_,_,_,_,_) =>
      r.uri.multiParams.get("foo") match {
        case Some(ps) => Response(status = Status.Ok).withBody(ps.mkString(","))
        case None     => Response(status = Status.BadRequest).withBody("No Foo")
      }
  })

  "UrlFormLifter" should {
    "Add application/x-www-form-urlencoded bodies to the query params" in {
      val req = Request(method = Method.POST).withBody(urlForm).run

      val resp = service(req).run
      resp.status must_== Status.Ok
    }

    "Add application/x-www-form-urlencoded bodies after query params" in {
      val req = Request(method = Method.POST, uri = Uri.uri("/foo?foo=biz")).withBody(urlForm).run

      val resp = service(req).run
      resp.status must_== Status.Ok
      resp.as[String].run must_== "biz,bar"
    }

    "Ignore Requests that don't have application/x-www-form-urlencoded bodies" in {
      val req = Request(method = Method.POST).withBody("foo").run

      val resp = service(req).run
      resp.status must_== Status.BadRequest
    }
  }
}

package org.http4s
package server.middleware

import org.http4s.server.HttpService

class UrlFormLifterSpec extends Http4sSpec {
  val urlForm = UrlForm("foo" -> "bar")

  val service = UrlFormLifter(HttpService {
    case r@Request(Method.POST,_,_,_,_,_) =>
      r.uri.multiParams.get("foo") match {
        case Some(ps) => Response(status = Status.Ok).withBody(ps.mkString(","))
        case None     => Response(status = Status.BadRequest).withBody("No Foo")
      }
  })

  "UrlFormLifter" should {
    "Add application/x-www-form-urlencoded bodies to the query params" in {
      val req = Request(method = Method.POST).withBody(urlForm).run

      val resp = service.apply(req).run
      resp.status must_== Status.Ok
    }

    "Add application/x-www-form-urlencoded bodies after query params" in {
      val req = Request(method = Method.POST, uri = Uri.uri("/foo?foo=biz")).withBody(urlForm).run

      val resp = service.apply(req).run
      resp.status must_== Status.Ok
      resp.as[String].run must_== "biz,bar"
    }

    "Ignore Requests that don't have application/x-www-form-urlencoded bodies" in {
      val req = Request(method = Method.POST).withBody("foo").run

      val resp = service.apply(req).run
      resp.status must_== Status.BadRequest
    }
  }
}

Apply changes for upgrade to scalaz-specs2 0.4.0 to previously unmerged test files


package wykopml.storage

import com.websudos.phantom.dsl._

import scala.concurrent.Await
import scala.concurrent.duration._

class WykopDatabase(val keyspace: KeySpaceDef) extends com.websudos.phantom.db.DatabaseImpl(keyspace) {

  case object wykops extends Wykops with keyspace.Connector

  case object votes extends Votes with keyspace.Connector

  case object comments extends Comments with keyspace.Connector

}

object WykopDatabase extends WykopDatabase(Defaults.connector) {

  def init(): Unit = {
    Await.result(wykops.create.ifNotExists().future(), Duration.Inf)
    Await.result(votes.create.ifNotExists().future(), Duration.Inf)
    Await.result(comments.create.ifNotExists().future(), Duration.Inf)
  }

}

package wykopml.storage

import com.websudos.phantom.dsl._

import scala.concurrent.Await
import scala.concurrent.duration._

class WykopDatabase(val keyspace: KeySpaceDef) extends com.websudos.phantom.db.DatabaseImpl(keyspace) {

  case object wykops extends Wykops with keyspace.Connector

  case object votes extends Votes with keyspace.Connector

  case object comments extends Comments with keyspace.Connector

}

object WykopDatabase extends WykopDatabase(Defaults.connector) {

  def init() = Await.result(autocreate().future(), Duration.Inf)

}

Use autocreate helper for cassandra schema creation


package grasshopper.addresspoints.search

import com.typesafe.scalalogging.Logger
import feature._
import io.geojson.FeatureJsonProtocol._
import org.elasticsearch.action.search.SearchType
import org.elasticsearch.client.Client
import org.elasticsearch.index.query.QueryBuilders
import org.elasticsearch.search.SearchHit
import org.slf4j.LoggerFactory
import spray.json._

import scala.util.Try

trait Geocode {

  lazy val log = Logger(LoggerFactory.getLogger("grasshopper-grasshopper.addresspoints"))

  def geocode(client: Client, index: String, indexType: String, address: String, count: Int): Try[Array[Feature]] = {
    log.debug(s"Search Address: ${address}")
    Try {
      val hits = searchAddress(client, index, indexType, address)
      hits
        .map(hit => hit.getSourceAsString)
        .take(count)
        .map { s =>
          log.debug(s)
          s.parseJson.convertTo[Feature]
        }
    }
  }

  private def searchAddress(client: Client, index: String, indexType: String, address: String): Array[SearchHit] = {
    val qb = QueryBuilders.matchQuery("address", address)
    val response = client.prepareSearch(index)
      .setTypes(indexType)
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .setQuery(qb)
      .execute
      .actionGet

    response.getHits().getHits
  }
}

package grasshopper.addresspoints.search

import com.typesafe.scalalogging.Logger
import feature._
import io.geojson.FeatureJsonProtocol._
import org.elasticsearch.action.search.SearchType
import org.elasticsearch.client.Client
import org.elasticsearch.index.query.QueryBuilders
import org.elasticsearch.search.SearchHit
import org.slf4j.LoggerFactory
import spray.json._

import scala.util.Try

trait Geocode {

  lazy val log = Logger(LoggerFactory.getLogger("grasshopper-grasshopper.addresspoints"))

  def geocode(client: Client, index: String, indexType: String, address: String, count: Int): Try[Array[Feature]] = {
    log.debug(s"Search Address: ${address}")
    Try {
      val hits = searchAddress(client, index, indexType, address)
      hits
        .map(hit => hit.getSourceAsString)
        .take(count)
        .map { s =>
          log.debug(s)
          s.parseJson.convertTo[Feature]
        }.map { f =>
          f.addOrUpdate("match", SearchUtils.percentMatch(address, f.get("address").getOrElse("").toString))
        }
    }
  }

  private def searchAddress(client: Client, index: String, indexType: String, address: String): Array[SearchHit] = {
    val qb = QueryBuilders.matchQuery("address", address)
    val response = client.prepareSearch(index)
      .setTypes(indexType)
      .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
      .setQuery(qb)
      .execute
      .actionGet

    response.getHits().getHits
  }
}

Add percent match to response

Add percent match to response


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.1"

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

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

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

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

version := "0.2.43"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.1"

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

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

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

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

version := "0.2.44"

autocommit: Update configuration to record version 0.2.44


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

crossScalaVersions := Seq("2.11.7")

version := "0.0.28"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "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 play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

crossScalaVersions := Seq("2.11.7")

version := "0.0.29"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "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.28 => 0.0.29

Increment version from 0.0.28 => 0.0.29


import Dependencies._

lazy val root = (project in file(".")).
  settings(
    inThisBuild(List(
      organization := "com.example",
      scalaVersion := "2.12.1",
      version      := "0.1.0-SNAPSHOT"
    )),
    name := "Hello",
    libraryDependencies += scalaTest % Test
  )

name := "Voting Application"
version := "0.1.0-SNAPSHOT"
scalaVersion := "2.11.8"

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.1" % Test

// configuration of the main project
lazy val root = (project in file(".")).enablePlugins(PlayScala)

Make the project to be a play app

2: Make the project to be a play app

Task-Url: https://github.com/rloutrel/app-voting/issues/2


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.6"

crossScalaVersions := Seq("2.12.6")

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

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

version := "0.1.92"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.6"

crossScalaVersions := Seq("2.12.6")

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

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

version := "0.1.93"

autocommit: Update configuration to record version 0.1.93


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

package com.holdenkarau.spark.testing

import org.apache.spark._

import org.scalatest.BeforeAndAfterAll
import org.scalatest.BeforeAndAfterEach
import org.scalatest.Suite

/**
 * Provides a local `sc`
 * {@link SparkContext} variable, correctly stopping it after each test.
 * The stopping logic is provided in {@link LocalSparkContext}.
 */
trait PerTestSparkContext extends LocalSparkContext with BeforeAndAfterEach
    with SparkContextProvider { self: Suite =>

  override def beforeEach() {
    sc = new SparkContext(conf)
    setup(sc)
    super.beforeEach()
  }
}

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

package com.holdenkarau.spark.testing

import org.apache.spark._

import org.scalatest.BeforeAndAfterAll
import org.scalatest.BeforeAndAfterEach
import org.scalatest.Suite

/**
 * Provides a local `sc`
 * {@link SparkContext} variable, correctly stopping it after each test.
 * The stopping logic is provided in {@link LocalSparkContext}.
 */
trait PerTestSparkContext extends LocalSparkContext with BeforeAndAfterEach
    with SparkContextProvider { self: Suite =>

  override def beforeEach() {
    sc = new SparkContext(conf)
    setup(sc)
    super.beforeEach()
  }

  override def afterEach() {
    super.afterEach()
  }
}

Add an afterEach which just calls super

Add an afterEach which just calls super


package hmda.validation.engine.lar.quality

import java.io.File

import hmda.model.fi.lar.LarGenerators
import hmda.parser.fi.lar.LarCsvParser
import hmda.validation.context.ValidationContext
import org.scalatest.{ MustMatchers, PropSpec }
import org.scalatest.prop.PropertyChecks

import scala.io.Source

class LarQualityEngineSpec
    extends PropSpec
    with PropertyChecks
    with MustMatchers
    with LarGenerators
    with LarQualityEngine {

  property("A LAR must pass quality checks") {
    val lines = Source.fromFile(new File("parser/jvm/src/test/resources/txt/clean_5508-lars.txt")).getLines()
    val lars = lines.drop(1).map(line => LarCsvParser(line)).collect {
      case Right(lar) => lar
    }

    lars.foreach { lar =>
      checkQuality(lar, ValidationContext(None, None)).isSuccess mustBe true
    }
  }

}

package hmda.validation.engine.lar.quality

import java.io.File

import hmda.model.fi.lar.LarGenerators
import hmda.parser.fi.lar.LarCsvParser
import hmda.validation.context.ValidationContext
import org.scalatest.{ MustMatchers, PropSpec }
import org.scalatest.prop.PropertyChecks

import scala.io.Source

class LarQualityEngineSpec
    extends PropSpec
    with PropertyChecks
    with MustMatchers
    with LarGenerators
    with LarQualityEngine {

  property("A LAR must pass quality checks") {
    val lines = Source.fromFile(new File("parser/jvm/src/test/resources/txt/edits-M_5508-lars.txt")).getLines()
    val lars = lines.drop(1).map(line => LarCsvParser(line)).collect {
      case Right(lar) => lar
    }

    lars.foreach { lar =>
      checkQuality(lar, ValidationContext(None, None)).isSuccess mustBe true
    }
  }

}

Use updated sample file in spec

Use updated sample file in spec


addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.15")
addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.0-M15")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "1.1")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.0")
addSbtPlugin("com.dwijnand" % "sbt-dynver" % "1.2.0")

Use sbt-dynver to infer version number from git history

Prevent https://github.com/scalameta/scalafmt/issues/943 from happening
again.


addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.8.0")

val sbtSoftwareMillVersion = "2.0.7"
addSbtPlugin(
  "com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion
)
addSbtPlugin(
  "com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion
)

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.7.0")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.0")

addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.8.0")

val sbtSoftwareMillVersion = "2.0.8"
addSbtPlugin(
  "com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion
)
addSbtPlugin(
  "com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion
)

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.7.0")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.0")

Update sbt-softwaremill-common, ... to 2.0.8


addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.5.2")

addSbtPlugin("com.codecommit" % "sbt-github-actions" % "0.10.1")

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

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.5")

addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.2")

addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.9")

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.8.1")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0")

addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.0.0")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.4.0")

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

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

addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.0")

addSbtPlugin("ch.epfl.lamp" % "sbt-dotty" % "0.5.2")

addSbtPlugin("com.codecommit" % "sbt-github-actions" % "0.10.1")

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

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.5")

addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.2")

addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.9")

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.8.1")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0")

addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.0.0")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.5.0")

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

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

addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.0")

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


package avrohugger
package format
package standard

import avrohugger.format.abstractions.Importer
import avrohugger.input.DependencyInspector._
import avrohugger.input.NestedSchemaExtractor._
import avrohugger.matchers.TypeMatcher
import avrohugger.stores.SchemaStore

import org.apache.avro.{ Protocol, Schema }
import org.apache.avro.Schema.Type.RECORD

import treehugger.forest._
import definitions._
import treehuggerDSL._

object StandardImporter extends Importer {

  def getImports(
    schemaOrProtocol: Either[Schema, Protocol],
    currentNamespace: Option[String],
    schemaStore: SchemaStore,
    typeMatcher: TypeMatcher): List[Import] = {
    val topLevelSchemas = getTopLevelSchemas(schemaOrProtocol, schemaStore)
    val recordSchemas = getRecordSchemas(topLevelSchemas)
    getRecordImports(recordSchemas, currentNamespace, typeMatcher)
  }

}

package avrohugger
package format
package standard

import avrohugger.format.abstractions.Importer
import avrohugger.input.DependencyInspector._
import avrohugger.input.NestedSchemaExtractor._
import avrohugger.matchers.TypeMatcher
import avrohugger.stores.SchemaStore

import collection.JavaConverters._

import org.apache.avro.{ Protocol, Schema }
import org.apache.avro.Schema.Type.RECORD

import treehugger.forest._
import definitions._
import treehuggerDSL._

object StandardImporter extends Importer {

  def getImports(
    schemaOrProtocol: Either[Schema, Protocol],
    currentNamespace: Option[String],
    schemaStore: SchemaStore,
    typeMatcher: TypeMatcher): List[Import] = {

    val shapelessCopSymbolsImport = RootClass.newClass("shapeless.{:+:, CNil}")
    val shapelessImport = IMPORT(shapelessCopSymbolsImport)

    val topLevelSchemas = getTopLevelSchemas(schemaOrProtocol, schemaStore)
    val recordSchemas = getRecordSchemas(topLevelSchemas)
    val deps = getRecordImports(recordSchemas, currentNamespace, typeMatcher)

    schemaOrProtocol match {
      case Left(schema) => {
        val includeShapeless =
          schema.getFields.asScala.exists(_.schema().getType == Schema.Type.UNION)
        if (schema.getType == RECORD && includeShapeless) shapelessImport :: deps
        else deps
      }
      case Right(protocol) => {
        val types = protocol.getTypes.asScala.toList
        val includeShapeless = types.exists(_.getFields.asScala.exists(_.schema().getType == Schema.Type.UNION))
        if (includeShapeless) shapelessImport :: deps
        else deps
      }
    }
  }

}

Include shapeless imports when detecting union types on Importer


object Version {

  val logback    = "1.2.1"
  val scalaTest  = "3.0.5"
  val scalaCheck = "1.14.0"
  val akka = "2.5.18"
  val akkaHttp = "10.1.5"
  val akkaHttpJson = "1.22.0"
  val akkaClusterManagement = "0.19.0"
  val akkaCors = "0.3.1"
  val circe = "0.10.1"
  val cassandraPluginVersion = "0.91"
  val akkaClusterDowning = "0.0.12"
  val slick = "3.2.3"
  val postgres = "42.2.4"
  val h2 = "1.4.188"
  val keycloak = "4.5.0.Final"
  val jboss = "3.3.2.Final"
  val httpcomponents = "4.5.6"
  val embeddedKafka = "2.0.0"
  val akkaStreamKafka = "0.22"
}

object Version {

  val logback    = "1.2.1"
  val scalaTest  = "3.0.5"
  val scalaCheck = "1.14.0"
  val akka = "2.5.18"
  val akkaHttp = "10.1.5"
  val akkaHttpJson = "1.22.0"
  val akkaClusterManagement = "0.14.0"
  val akkaCors = "0.3.1"
  val circe = "0.10.1"
  val cassandraPluginVersion = "0.91"
  val akkaClusterDowning = "0.0.12"
  val slick = "3.2.3"
  val postgres = "42.2.4"
  val h2 = "1.4.188"
  val keycloak = "4.5.0.Final"
  val jboss = "3.3.2.Final"
  val httpcomponents = "4.5.6"
  val embeddedKafka = "2.0.0"
  val akkaStreamKafka = "0.22"
}

Revert akka management version upgrade

Revert akka management version upgrade


/**
 *  Copyright 2013 Robert Welin
 *
 * 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.mooo.nilewapps.bokbytarappen.server

import org.specs2.mutable.Specification
import spray.http._
import spray.http.StatusCodes._
import spray.testkit.Specs2RouteTest

class ServiceSpec
    extends Specification
    with Specs2RouteTest
    with Service {

  def actorRefFactory = system

  "Service" should {
    "return a greeting for GET requests to the root path" in {
      Get() ~> routes ~> check {
        entityAs[String] must contain("Say hello")
      }
    }
  }
}

/**
 *  Copyright 2013 Robert Welin
 *
 * 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.mooo.nilewapps.bokbytarappen.server

import org.specs2.mutable.Specification
import spray.http._
import spray.http.StatusCodes._
import spray.testkit.Specs2RouteTest

class ServiceSpec
    extends Specification
    with Specs2RouteTest
    with Service {

  def actorRefFactory = system

  "Service" should {
    "return a greeting for GET requests to the root path" in {
      Get() ~> routes ~> check {
        responseAs[String] must contain("Say hello")
      }
    }
  }
}

Change depracated entityAs to responseAs

Method entityAs is deprecated in spary v 1.1-20131004 and is replaced
with method responseAs.


package com.campudus.scycle

import rxscalajs._

object Scycle {

  def run(
           mainFn: Map[String, Driver] => Map[String, Observable[_]],
           drivers: Map[String, Observable[_] => Driver]
         ): Unit = {

    println("run method")

    println(s"init sinks")
    val proxies = drivers.foldLeft(Map[String, (Driver, Subject[_])]())({
      case (proxyMap, (key, driverFn)) =>
        val proxy = createProxy(driverFn)
        val driver = driverFn(proxy)
        proxyMap + (key -> (driver, proxy))
    })

    val sinks = mainFn(proxies.foldLeft(Map[String, Driver]()) {
      case (acc, (key, driverAndProxy)) =>
        acc + (key -> driverAndProxy._1)
    })

    drivers.foreach {
      case (key, driverFn) =>
        wireProxyToSink(sinks(key), key, proxies)
        drivers(key)(sinks(key))
    }
  }

  def wireProxyToSink[T](source: Observable[T], key: String, proxies: Map[String, (Driver, Subject[_])]): Unit = {
    val proxy = proxies(key)._2.asInstanceOf[Subject[T]]
    source.subscribe({ ev =>
      proxy.next(ev)
    })
  }

  def createProxy[T](driverFn: Observable[T] => Driver): Subject[T] = Subject[T]()

}

package com.campudus.scycle

import rxscalajs._

object Scycle {

  def run(
           mainFn: Map[String, Driver] => Map[String, Observable[_]],
           drivers: Map[String, Observable[_] => Driver]
         ): Unit = {

    println("run method")

    println(s"init sinks")
    val proxies = drivers.foldLeft(Map[String, (Driver, Subject[_])]())({
      case (proxyMap, (key, driverFn)) =>
        val proxy = createProxy(driverFn)
        val driver = driverFn(proxy)
        proxyMap + (key -> (driver, proxy))
    })

    val driversForMain = proxies.mapValues(_._1)
    val sinks = mainFn(driversForMain)

    drivers.foreach {
      case (key, driverFn) =>
        wireProxyToSink(sinks(key), key, proxies)
        drivers(key)(sinks(key))
    }
  }

  def wireProxyToSink[T](source: Observable[T], key: String, proxies: Map[String, (Driver, Subject[_])]): Unit = {
    val proxy = proxies(key)._2.asInstanceOf[Subject[T]]
    source.subscribe({ ev =>
      proxy.next(ev)
    })
  }

  def createProxy[T](driverFn: Observable[T] => Driver): Subject[T] = Subject[T]()

}

Use mapValues instead of fold

Use mapValues instead of fold

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


package object nimrod {
  implicit def stringPimps(s : String) = new {
    def %(args : AnyRef*) = String.format(s,args:_*)
    def ls = new java.io.File(s).list()
  }
  def set(key : String, value : String) {
    System.setProperty(key,value)
  }
  def get(key : String) = System.getProperty(key)
}

import java.io.File

package object nimrod {
  implicit def stringPimps(s : String) = new {
    def %(args : AnyRef*) = String.format(s,args:_*)
    def ls = new java.io.File(s).list()
  }
  implicit def filePimps(f : File) = new {
    def ls = f.list()
    def path = f.getCanonicalPath()
  }
  def set(key : String, value : String) {
    System.setProperty(key,value)
  }
  def get(key : String) = System.getProperty(key)
}

Add some pimps for files

Add some pimps for files


import sbt._
import Process._
import java.io.File

class SpielProject(info: ProjectInfo) extends AndroidProject(info) {
  override def androidPlatformName = "android-1.6"

  val rhino = "rhino" % "js" % "1.7R2"

  override def proguardOption = """
    -adaptresourcefilenames **.properties
    -keep class * extends org.mozilla.javascript.VMBridge
    -keep public class org.mozilla.javascript.Token
  """

  override def packageTask(signPackage: Boolean) = task {
    super.packageTask(signPackage)
    FileUtilities.unzip(classesMinJarPath, outputDirectoryName, GlobFilter("org/mozilla/javascript/resources/*.properties"), log)
    for(p <- (outputDirectoryName/"org"**"*.properties").get) {
      (
        (new java.lang.ProcessBuilder(
          aaptPath.absolutePath,
          "add",
          packageApkPath.absolutePath,
          p.toString.replace(outputDirectoryName+"/", "")
        ))
        directory outputDirectoryName.asFile
      ) ! log
    }
    FileUtilities.clean(outputDirectoryName/"org", log)
    None
  }
}

import sbt._
import Process._
import java.io.File

class SpielProject(info: ProjectInfo) extends AndroidProject(info) {
  override def androidPlatformName = "android-1.6"

  val rhino = "rhino" % "js" % "1.7R2"

  override def proguardOption = """
    -adaptresourcefilenames **.properties
    -keep class * extends org.mozilla.javascript.VMBridge
    -keep public class org.mozilla.javascript.Token
  """

  override def packageTask(signPackage: Boolean) = task {
    super.packageTask(signPackage).run
    FileUtilities.unzip(classesMinJarPath, outputDirectoryName, GlobFilter("org/mozilla/javascript/resources/*.properties"), log)
    for(p <- (outputDirectoryName/"org"**"*.properties").get) {
      (
        (new java.lang.ProcessBuilder(
          aaptPath.absolutePath,
          "add",
          packageApkPath.absolutePath,
          p.toString.replace(outputDirectoryName+"/", "")
        ))
        directory outputDirectoryName.asFile
      ) ! log
    }
    FileUtilities.clean(outputDirectoryName/"org", log)
    None
  }
}

Call the superclass task. This is ugly.

Call the superclass task. This is ugly.

--HG--
extra : convert_revision : eeadeae14e57105077a7bdc76e47cdce6342921b


name := "pureconfig-squants"

crossScalaVersions ~= { _.filterNot(_.startsWith("2.13")) }

libraryDependencies ++= Seq(
  "org.typelevel" %% "squants" % "1.6.0")  // blocked by https://github.com/typelevel/squants/issues/321

developers := List(
  Developer("melrief", "Mario Pastorelli", "pastorelli.mario@gmail.com", url("https://github.com/melrief")),
  Developer("cranst0n", "Ian McIntosh", "cranston.ian@gmail.com", url("https://github.com/cranst0n")))

osgiSettings

OsgiKeys.exportPackage := Seq("pureconfig.module.squants.*")
OsgiKeys.privatePackage := Seq()
OsgiKeys.importPackage := Seq(s"""scala.*;version="[${scalaBinaryVersion.value}.0,${scalaBinaryVersion.value}.50)"""", "*")

name := "pureconfig-squants"

libraryDependencies ++= Seq(
  "org.typelevel" %% "squants" % "1.6.0")

developers := List(
  Developer("melrief", "Mario Pastorelli", "pastorelli.mario@gmail.com", url("https://github.com/melrief")),
  Developer("cranst0n", "Ian McIntosh", "cranston.ian@gmail.com", url("https://github.com/cranst0n")))

osgiSettings

OsgiKeys.exportPackage := Seq("pureconfig.module.squants.*")
OsgiKeys.privatePackage := Seq()
OsgiKeys.importPackage := Seq(s"""scala.*;version="[${scalaBinaryVersion.value}.0,${scalaBinaryVersion.value}.50)"""", "*")

Build for Scala 2.13 and remove comment in version


package org.scalaide.debug.internal.command

import org.eclipse.core.commands.IHandler
import org.eclipse.debug.core.commands.ITerminateHandler
import org.eclipse.core.commands.AbstractHandler
import org.eclipse.core.commands.ExecutionEvent
import org.eclipse.debug.ui.DebugUITools
import org.eclipse.ui.handlers.HandlerUtil
import org.eclipse.jface.viewers.IStructuredSelection
import org.scalaide.debug.internal.model.ScalaStackFrame

class StepMessageOut extends AbstractHandler {
  override def execute(event: ExecutionEvent): Object = {
    val window = HandlerUtil.getActiveWorkbenchWindow(event)
    val service = DebugUITools.getDebugContextManager().getContextService(window)
    val selection = service.getActiveContext()

    selection match {
      case se: IStructuredSelection =>
        se.getFirstElement() match {
          case ssf: ScalaStackFrame =>
            ssf.thread.stepMessageOut()
          case _ => // do nothing but don't crash
        }
    }
    null
  }

  override def setEnabled(context: Object): Unit = ()

  override def isEnabled() = true
}

package org.scalaide.debug.internal.command

import org.eclipse.core.commands.IHandler
import org.eclipse.debug.core.commands.ITerminateHandler
import org.eclipse.core.commands.AbstractHandler
import org.eclipse.core.commands.ExecutionEvent
import org.eclipse.debug.ui.DebugUITools
import org.eclipse.ui.handlers.HandlerUtil
import org.eclipse.jface.viewers.IStructuredSelection
import org.scalaide.debug.internal.model.ScalaStackFrame

class StepMessageOut extends AbstractHandler {
  override def execute(event: ExecutionEvent): Object = {
    val window = HandlerUtil.getActiveWorkbenchWindow(event)
    val service = DebugUITools.getDebugContextManager().getContextService(window)
    val selection = service.getActiveContext()

    selection match {
      case se: IStructuredSelection =>
        se.getFirstElement() match {
          case ssf: ScalaStackFrame =>
            ssf.thread.stepMessageOut()
          case _ =>
        }
      case _ =>
    }
    null
  }

  override def setEnabled(context: Object): Unit = ()

  override def isEnabled() = true
}

Fix match error because of unhandled default cases


package com.twitter.finagle.http

import com.twitter.finagle
import com.twitter.finagle.Service
import com.twitter.finagle.liveness.FailureDetector
import com.twitter.util.Future

/**
 * This is really a HTTP/1.x test suite because the server only speaks HTTP/1.x
 */
class ClientFailHttp2UpgradeTest extends AbstractHttp1EndToEndTest {
  def implName: String = "http/2 client, http/1.1 server"
  def clientImpl(): finagle.Http.Client =
    finagle.Http.client.withHttp2.configured(FailureDetector.Param(FailureDetector.NullConfig))

  def serverImpl(): finagle.Http.Server = finagle.Http.server

  def featureImplemented(feature: Feature): Boolean = feature != NoBodyMessage

  test("Upgrade counters are not incremented") {
    val client = nonStreamingConnect(Service.mk { _: Request =>
      Future.value(Response())
    })

    await(client(Request("/")))

    assert(!statsRecv.counters.contains(Seq("server", "upgrade", "success")))
    assert(statsRecv.counters(Seq("client", "upgrade", "success")) == 0)

    await(client.close())
  }
}

package com.twitter.finagle.http

import com.twitter.finagle
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.liveness.FailureDetector
import com.twitter.util.Future

/**
 * This is really a HTTP/1.x test suite because the server only speaks HTTP/1.x
 */
abstract class ClientFailHttp2UpgradeTest extends AbstractHttp1EndToEndTest {
  def isMultiplexCodec: Boolean
  def implName: String = {
    val base = if (isMultiplexCodec) "multiplex" else "classic"
    base + " http/2 client, http/1.1 server"
  }

  def clientImpl(): finagle.Http.Client =
    finagle.Http.client.withHttp2
      .configured(FailureDetector.Param(FailureDetector.NullConfig))
      .configured(Http.H2ClientImpl(Some(isMultiplexCodec)))

  def serverImpl(): finagle.Http.Server = finagle.Http.server

  def featureImplemented(feature: Feature): Boolean = feature != NoBodyMessage

  test("Upgrade counters are not incremented") {
    val client = nonStreamingConnect(Service.mk { _: Request =>
      Future.value(Response())
    })

    await(client(Request("/")))

    assert(!statsRecv.counters.contains(Seq("server", "upgrade", "success")))
    assert(statsRecv.counters(Seq("client", "upgrade", "success")) == 0)

    await(client.close())
  }
}

class ClassicClientFailHttp2UpgradeTest extends ClientFailHttp2UpgradeTest {
  def isMultiplexCodec: Boolean = false
}

class MultiplexClientFailHttp2UpgradeTest extends ClientFailHttp2UpgradeTest {
  def isMultiplexCodec: Boolean = true
}

finagle-http: Test multiplex client with failed server upgrades

Problem

We don't have test coverage for the H2 multiplex client for the case
where the server doesn't accept the upgrade.

Solution

Abstract the ClientFailHttp2UpgradeTest test around the client and
create both classic and multiplex versions of it.

JIRA Issues: CSL-8692

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