package com.gu.scanamo.request

import com.amazonaws.services.dynamodbv2.model.AttributeValue
import com.gu.scanamo.EvaluationKey
import com.gu.scanamo.query.{Condition, Query}

case class ScanamoPutRequest(
    tableName: String,
    item: AttributeValue,
    condition: Option[RequestCondition]
)

case class ScanamoDeleteRequest(
    tableName: String,
    key: Map[String, AttributeValue],
    condition: Option[RequestCondition]
)

case class ScanamoUpdateRequest(
    tableName: String,
    key: Map[String, AttributeValue],
    updateExpression: String,
    attributeNames: Map[String, String],
    attributeValues: Map[String, AttributeValue],
    condition: Option[RequestCondition]
)

case class ScanamoScanRequest(
    tableName: String,
    index: Option[String],
    options: ScanamoQueryOptions
)

case class ScanamoQueryRequest(
    tableName: String,
    index: Option[String],
    query: Query[_],
    options: ScanamoQueryOptions
)

case class ScanamoQueryOptions(
    consistent: Boolean,
    scanIndexForward: Boolean,
    limit: Option[Int],
    exclusiveStartKey: Option[EvaluationKey],
    filter: Option[Condition[_]]
)
object ScanamoQueryOptions {
  val default = ScanamoQueryOptions(false, true, None, None, None)
}

case class RequestCondition(
    expression: String,
    attributeNames: Map[String, String],
    attributeValues: Option[Map[String, AttributeValue]]
)

package com.gu.scanamo.request

import com.amazonaws.services.dynamodbv2.model.AttributeValue
import com.gu.scanamo.EvaluationKey
import com.gu.scanamo.query.{Condition, Query}

case class ScanamoPutRequest(
    tableName: String,
    item: AttributeValue,
    condition: Option[RequestCondition]
)

case class ScanamoDeleteRequest(
    tableName: String,
    key: Map[String, AttributeValue],
    condition: Option[RequestCondition]
)

case class ScanamoUpdateRequest(
    tableName: String,
    key: Map[String, AttributeValue],
    updateExpression: String,
    attributeNames: Map[String, String],
    attributeValues: Map[String, AttributeValue],
    condition: Option[RequestCondition]
)

case class ScanamoScanRequest(
    tableName: String,
    index: Option[String],
    options: ScanamoQueryOptions
)

case class ScanamoQueryRequest(
    tableName: String,
    index: Option[String],
    query: Query[_],
    options: ScanamoQueryOptions
)

case class ScanamoQueryOptions(
    consistent: Boolean,
    limit: Option[Int],
    exclusiveStartKey: Option[EvaluationKey],
    filter: Option[Condition[_]]
)
object ScanamoQueryOptions {
  val default = ScanamoQueryOptions(false, None, None, None)
}

case class RequestCondition(
    expression: String,
    attributeNames: Map[String, String],
    attributeValues: Option[Map[String, AttributeValue]]
)

Revert "Add ScanIndexForward property to query options"

This reverts commit 0296997de5d0d30d10b66ae54e7857a01860970f.


package org.ergoplatform.settings

import org.ergoplatform.mining.emission.EmissionRules

/**
  * Configuration file for monetary settings of Ergo chain
  *
  * @see src/main/resources/application.conf for parameters description
  */
case class MonetarySettings(fixedRatePeriod: Int = 30 * 2 * 24 * 365,
                            epochLength: Int = 90 * 24 * 30,
                            fixedRate: Long = 75L * EmissionRules.CoinsInOneErgo,
                            oneEpochReduction: Long = 3L * EmissionRules.CoinsInOneErgo,
                            minerRewardDelay: Int = 720,
                            foundersInitialReward: Long = 75L * EmissionRules.CoinsInOneErgo / 10)

package org.ergoplatform.settings

import org.ergoplatform.ErgoScriptPredef
import org.ergoplatform.mining.emission.EmissionRules
import sigmastate.{SBoolean, Values}

/**
  * Configuration file for monetary settings of Ergo chain
  *
  * @see src/main/resources/application.conf for parameters description
  */
case class MonetarySettings(fixedRatePeriod: Int = 30 * 2 * 24 * 365,
                            epochLength: Int = 90 * 24 * 30,
                            fixedRate: Long = 75L * EmissionRules.CoinsInOneErgo,
                            oneEpochReduction: Long = 3L * EmissionRules.CoinsInOneErgo,
                            minerRewardDelay: Int = 720,
                            foundersInitialReward: Long = 75L * EmissionRules.CoinsInOneErgo / 10) {

  val feeProposition: Values.Value[SBoolean.type] = ErgoScriptPredef.feeProposition(minerRewardDelay)
  val feePropositionBytes: Array[Byte] = feeProposition.bytes

}

Add fee proposition to monetary settings


package com.softwaremill.codebrag.service.config

import com.softwaremill.codebrag.common.config.ConfigWithDefault

trait LicenceConfig extends ConfigWithDefault {

  lazy val expiresInDays = getInt("codebrag.licence-expiration-days", 30)

}

package com.softwaremill.codebrag.service.config

import com.softwaremill.codebrag.common.config.ConfigWithDefault

trait LicenceConfig extends ConfigWithDefault {

  lazy val expiresInDays = getInt("codebrag.licence-expiration-days", 45)

}

Extend licence to 45 days (for EA)

Extend licence to 45 days (for EA)


package core

import lib.{Datatype, PrimitiveMetadata, Primitives, Type, TypeKind}

case class TypeResolver(
  enumNames: Iterable[String] = Seq.empty,
  modelNames: Iterable[String] = Seq.empty
) {

  /**
    * Takes the name of a simple type - a primitive, model or enum. If
    * valid - returns a Type/
    */
  def toType(name: String): Option[Type] = {
    Primitives(name) match {
      case Some(pt) => Some(Type(TypeKind.Primitive, name))
      case None => {
        enumNames.find(_ == name) match {
          case Some(et) => Some(Type(TypeKind.Enum, name))
          case None => {
            modelNames.find(_ == name) match {
              case Some(mt) => Some(Type(TypeKind.Model, name))
              case None => None
            }
          }
        }
      }
    }
  }

  def parseWithError(internal: InternalDatatype): Datatype = {
    parse(internal).getOrElse {
      sys.error(s"Unrecognized datatype[${internal.label}]")
    }
  }

  /**
    * Resolves the type name into instances of a first class Type.
    */
  def parse(internal: InternalDatatype): Option[Datatype] = {
    internal match {
      case InternalDatatype.List(names) => {
        toTypesIfAllFound(names).map { Datatype.List(_) }
      }

      case InternalDatatype.Map(names) => {
        toTypesIfAllFound(names).map { Datatype.Map(_) }
      }

      case InternalDatatype.Option(names) => {
        toTypesIfAllFound(names).map { Datatype.Option(_) }
      }

      case InternalDatatype.Singleton(names) => {
        toTypesIfAllFound(names).map { Datatype.Singleton(_) }
      }
    }
  }

  private def toTypesIfAllFound(names: Seq[String]): Option[Seq[Type]] = {
    val types = names.map { n => toType(n) }
    types.filter(!_.isDefined) match {
      case Nil => Some(types.flatten)
      case unknowns => None
    }
  }

}

package core

import lib.{Datatype, DatatypeResolver, Type}

case class TypeResolver(
  enumNames: Iterable[String] = Seq.empty,
  modelNames: Iterable[String] = Seq.empty
) {

  private val resolver = DatatypeResolver(enumNames = enumNames, modelNames = modelNames)

  def toType(name: String): Option[Type] = {
    resolver.toType(name)
  }

  def parseWithError(internal: InternalDatatype): Datatype = {
    parse(internal).getOrElse {
      sys.error(s"Unrecognized datatype[${internal.label}]")
    }
  }

  /**
    * Resolves the type name into instances of a first class Type.
    */
  def parse(internal: InternalDatatype): Option[Datatype] = {
    resolver.parse(internal.label)
  }

}

Use datatype resolver from lib

Use datatype resolver from lib


package com.signalcollect.psl

import java.io.File
import com.signalcollect.psl.model.GroundedPredicate

object CommandLinePslInferencer extends App {

  val usage = """
    Usage: fox filename [--abseps num] [--releps num]
  """

  if (args.length == 0) {
    println(usage)
    System.exit(-1)
  }
  val arglist = args.toList
  val it = arglist.iterator
  val tupleOfArgs = it.zip(it).toList
  val mapOfArgs = tupleOfArgs.toMap

  val pslFile = new File(mapOfArgs.get("--filename").get)
  val config = InferencerConfig(
    absoluteEpsilon = mapOfArgs.get("--abseps").getOrElse("1e-8").toDouble,
    relativeEpsilon = mapOfArgs.get("--releps").getOrElse("1e-3").toDouble)
  val inferenceResults = Inferencer.runInferenceFromFile(
    pslFile = pslFile,
    config = config)
  val inferences = inferenceResults.solution.results
  val gps = inferenceResults.idToGpMap
  def reportInference(gpId: Int, truthValue: Double) {
    if (truthValue > 0) {
      val gp = gps(gpId)
      if (!gp.truthValue.isDefined) {
        println(s"$gp has truth value $truthValue")
      }
    }
  }
  inferences.foreach(reportInference)

  System.exit(0)

}

package com.signalcollect.psl

import java.io.File
import com.signalcollect.psl.model.GroundedPredicate

object CommandLinePslInferencer extends App {

  val usage = """
    Usage: fox filename [--absEps num] [--relEps num] [--queryList "pred1, pred2"]
  """

  if (args.length <= 1) {
    println(usage)
    System.exit(-1)
  }
  val arglist = args.toList
  val it = arglist.iterator
  val tupleOfArgs = it.zip(it).toList
  val mapOfArgs = tupleOfArgs.toMap

  val pslFile = new File(mapOfArgs.get("--filename").get)
  val queryList = if (mapOfArgs.get("--queryList").isDefined) {
    val argument = mapOfArgs.get("--queryList").get
    argument.split(",").toList
  } else {
    List.empty
  }

  val config = InferencerConfig(
    absoluteEpsilon = mapOfArgs.get("--absEps").getOrElse("1e-8").toDouble,
    relativeEpsilon = mapOfArgs.get("--relEps").getOrElse("1e-3").toDouble)
  val inferenceResults = Inferencer.runInferenceFromFile(
    pslFile = pslFile,
    config = config)

  println(inferenceResults.printSelected(queryList))
  System.exit(0)

}

Add more options to the command line.

Add more options to the command line.


package com.typesafe.sbt
package packager
package linux

import Keys._
import sbt._

/**
 * Plugin trait containing all the generic values used for
 * packaging linux software.
 */
trait LinuxPlugin extends Plugin {
  // TODO - is this needed
  val Linux = config("linux")

  def linuxSettings: Seq[Setting[_]] = Seq(
    linuxPackageMappings := Seq.empty,
    linuxPackageSymlinks := Seq.empty,
    sourceDirectory in Linux <<= sourceDirectory apply (_ / "linux"),
    generateManPages <<= (sourceDirectory in Linux, sbt.Keys.streams) map { (dir, s) =>
      for (file <- (dir / "usr/share/man/man1" ** "*.1").get) {
        val man = makeMan(file)
        s.log.info("Generated man page for[" + file + "] =")
        s.log.info(man)
      }
    },
    packageSummary in Linux <<= packageSummary,
    packageDescription in Linux <<= packageDescription)

  /** DSL for packaging files into .deb */
  def packageMapping(files: (File, String)*) = LinuxPackageMapping(files)

  /**
   * @param dir - use some directory, e.g. target.value
   * @param files
   */
  def packageTemplateMapping(dir: File, files: String*) = LinuxPackageMapping(files map ((dir, _)))

  // TODO - we'd like a set of conventions to take universal mappings and create linux package mappings.

  /** Create a ascii friendly string for a man page. */
  final def makeMan(file: File): String =
    Process("groff -man -Tascii " + file.getAbsolutePath).!!
}

package com.typesafe.sbt
package packager
package linux

import Keys._
import sbt._

/**
 * Plugin trait containing all the generic values used for
 * packaging linux software.
 */
trait LinuxPlugin extends Plugin {
  // TODO - is this needed
  val Linux = config("linux")

  def linuxSettings: Seq[Setting[_]] = Seq(
    linuxPackageMappings := Seq.empty,
    linuxPackageSymlinks := Seq.empty,
    sourceDirectory in Linux <<= sourceDirectory apply (_ / "linux"),
    generateManPages <<= (sourceDirectory in Linux, sbt.Keys.streams) map { (dir, s) =>
      for (file <- (dir / "usr/share/man/man1" ** "*.1").get) {
        val man = makeMan(file)
        s.log.info("Generated man page for[" + file + "] =")
        s.log.info(man)
      }
    },
    packageSummary in Linux <<= packageSummary,
    packageDescription in Linux <<= packageDescription)

  /** DSL for packaging files into .deb */
  def packageMapping(files: (File, String)*) = LinuxPackageMapping(files)

  /**
   * @param dir - use some directory, e.g. target.value
   * @param files
   */
  def packageTemplateMapping(files: String*)(dir: File = new File(sys.props("java.io.tmpdir"))) = LinuxPackageMapping(files map ((dir, _)))

  // TODO - we'd like a set of conventions to take universal mappings and create linux package mappings.

  /** Create a ascii friendly string for a man page. */
  final def makeMan(file: File): String =
    Process("groff -man -Tascii " + file.getAbsolutePath).!!
}

Add default to the temp directory we want for the linux packaging.


import javax.swing._

package display {
	object Display {
		def main(args : Array[String]) {
			val button = new Button("Click Me!")
			button.press.each(press => println("OH YEAH YOU CLICKED!"))

			val panel = new JPanel()
			val frame = new JFrame()
			panel.add(button)
			frame.add(panel, 0)

			frame.setSize(100, 70)
			frame.setLocationRelativeTo(null);
			frame.setVisible(true)
		}
	}
}

import javax.swing._

package display {
	object Display {
		def main(args : Array[String]) {
			val button = new Button("Click Me!")
			button.press.each(press => println("OH YEAH YOU CLICKED!"))

			addButtonToFrame(button)
		}

		def addButtonToFrame(button : Button) {
			val panel = new JPanel()
			val frame = new JFrame()
			panel.add(button)
			frame.add(panel, 0)

			frame.setSize(100, 70)
			frame.setLocationRelativeTo(null);
			frame.setVisible(true)
		}
	}
}

Make the display code easier to read

Make the display code easier to read


import sbt._, Keys._

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

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

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

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

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

import sbt._, Keys._

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

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

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

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

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

Update netty-codec-http, netty-handler, ... to 4.1.76.Final


import sbt._
import Keys._

import java.io.File

/** A helper object for running Jar Jar Links.
  *
  * @author robertf
  */
class JarJarRunner(java: File, jarjar: File) {
	def repackage(rulesFile: File, in: File, out: File) {
		val cmd =
			java.getCanonicalPath ::
			"-jar" :: jarjar.getCanonicalPath ::
			"process" :: rulesFile.getCanonicalPath :: in.getCanonicalPath :: out.getCanonicalPath ::
			Nil

		val ret = Process(cmd).!

		if (ret != 0) sys error s"Non-zero exit code from Jar Jar ($ret)"
	}

	override def toString() = s"JarJarRunner [java: $java, jarjar: $jarjar]"
}

object JarJarRunner {
	val jarjar = settingKey[File]("The location of jarjar.jar")

	def globalSettings = Seq(
		jarjar in Global := file("./project/utils/jarjar.jar")
	)

	def asTask(javaHome: SettingKey[Option[File]]): Def.Initialize[Task[JarJarRunner]] = Def.task {
		new JarJarRunner((javaHome.value getOrElse file(System getProperty "java.home")) / "bin" / "java", jarjar.value)
	}

	def asTask(): Def.Initialize[Task[JarJarRunner]] = asTask(Keys.javaHome)
}

import sbt._
import Keys._

import java.io.File

/** A helper object for running Jar Jar Links.
  *
  * @author robertf
  */
class JarJarRunner(java: File, jarjar: File) {
	def repackage(rulesFile: File, in: File, out: File) {
		val cmd =
			java.getCanonicalPath ::
			"-jar" :: jarjar.getCanonicalPath ::
			"process" :: rulesFile.getCanonicalPath :: in.getCanonicalPath :: out.getCanonicalPath ::
			Nil

		val ret = Process(cmd).!

		if (ret != 0) sys error s"Non-zero exit code from Jar Jar ($ret)"
	}

	override def toString() = s"JarJarRunner [java: $java, jarjar: $jarjar]"
}

object JarJarRunner {
	val jarjar = settingKey[File]("The location of jarjar.jar")

	def globalSettings = Seq(
		jarjar in Global := baseDirectory.value / "project" / "utils" / "jarjar.jar"
	)

	def asTask(javaHome: SettingKey[Option[File]]): Def.Initialize[Task[JarJarRunner]] = Def.task {
		new JarJarRunner((javaHome.value getOrElse file(System getProperty "java.home")) / "bin" / "java", jarjar.value)
	}

	def asTask(): Def.Initialize[Task[JarJarRunner]] = asTask(Keys.javaHome)
}

Fix jarjar path when referencing project


/*
 * Copyright (c) 2012 Crown Copyright
 *                    Animal Health and Veterinary Laboratories Agency
 *
 * 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 sampler.math

class Random extends scala.util.Random{
	def nextIndex(size: Int) = throw new UnsupportedOperationException("TODO")
}

/*
 * Copyright (c) 2012 Crown Copyright
 *                    Animal Health and Veterinary Laboratories Agency
 *
 * 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 sampler.math

class Random extends scala.util.Random{
	def nextDouble(min: Double, max: Double): Double =
		(max - min) * nextDouble() + min
}

Remove nextIndex since in super, add nextDouble


object Version {

  val logback    = "1.2.1"
  val scalaTest  = "3.0.1"
  val scalaCheck = "1.13.4"
  val scalaz     = "7.2.12"
  val akka       = "2.5.8"
  val akkaClusterManagement = "0.3"
  val akkaHttp   = "10.0.10"
  val leveldb    = "0.7"
  val leveldbjni = "1.8"
  val cassandra  = "0.54"
  val config     = "1.3.1"
  val enumeratum = "1.5.12"
  val inMemoryPersistence = "2.5.1.1"
  val slick      = "3.2.0"
  val h2         = "1.4.193"
  val postgresql = "42.0.0.jre7"
  val scalaCsv = "1.3.4"
  val constructrVersion = "0.17.0"
  val constructrZookeeperVersion = "0.3.3"
  val cassandraUnit = "3.1.3.2"
  val alpakka = "0.14"
  val cassandraDriver = "3.2.0"
  val javaMail = "1.4.7"
  val gatling = "2.3.0"
  val akkaQuartzScheduler = "1.6.1-akka-2.5.x"
}

object Version {

  val logback    = "1.2.1"
  val scalaTest  = "3.0.1"
  val scalaCheck = "1.13.4"
  val scalaz     = "7.2.12"
  val akka       = "2.5.8"
  val akkaClusterManagement = "0.3"
  val akkaHttp   = "10.0.11"
  val leveldb    = "0.7"
  val leveldbjni = "1.8"
  val cassandra  = "0.54"
  val config     = "1.3.1"
  val enumeratum = "1.5.12"
  val inMemoryPersistence = "2.5.1.1"
  val slick      = "3.2.0"
  val h2         = "1.4.193"
  val postgresql = "42.0.0.jre7"
  val scalaCsv = "1.3.4"
  val constructrVersion = "0.17.0"
  val constructrZookeeperVersion = "0.3.3"
  val cassandraUnit = "3.1.3.2"
  val alpakka = "0.14"
  val cassandraDriver = "3.2.0"
  val javaMail = "1.4.7"
  val gatling = "2.3.0"
  val akkaQuartzScheduler = "1.6.1-akka-2.5.x"
}

Upgrade Akka HTTP to version 10.0.11

Upgrade Akka HTTP to version 10.0.11


package lila.chess
package format

object PgnDump {

  def move(situation: Situation, data: Move, next: Situation): String = {
    import data._
    ((promotion, piece.role) match {
      case _ if castles         ⇒ if (orig ?> dest) "O-O-O" else "O-O"
      case _ if enpassant       ⇒ orig.file + 'x' + dest.rank
      case (Some(promotion), _) ⇒ dest.key + promotion.pgn
      case (_, Pawn)            ⇒ (if (captures) orig.file + "x" else "") + dest.key
      case (_, role) ⇒ role.pgn + {
        val candidates = situation.actors filter { a ⇒
          a.piece.role == piece.role && a.pos != orig && (a.destinations contains dest)
        }
        if (candidates.isEmpty) ""
        else if (candidates exists (_.pos ?| orig)) orig.file + orig.rank else orig.file
      } + (if (captures) "x" else "") + dest.key
      case _ ⇒ "?"
    }) + (if (next.check) if (next.checkMate) "#" else "+" else "")
  }
}

package lila.chess
package format

object PgnDump {

  def move(situation: Situation, data: Move, next: Situation): String = {
    import data._
    ((promotion, piece.role) match {
      case _ if castles         ⇒ if (orig ?> dest) "O-O-O" else "O-O"
      case _ if enpassant       ⇒ orig.file + 'x' + dest.key
      case (Some(promotion), _) ⇒ dest.key + promotion.pgn
      case (_, Pawn)            ⇒ (if (captures) orig.file + "x" else "") + dest.key
      case (_, role) ⇒ role.pgn + {
        val candidates = situation.actors filter { a ⇒
          a.piece.role == piece.role && a.pos != orig && (a.destinations contains dest)
        }
        if (candidates.isEmpty) ""
        else if (candidates exists (_.pos ?| orig)) orig.file + orig.rank else orig.file
      } + (if (captures) "x" else "") + dest.key
      case _ ⇒ "?"
    }) + (if (next.check) if (next.checkMate) "#" else "+" else "")
  }
}

Fix pgn notation of enpassant

Fix pgn notation of enpassant


package hmda.validation.rules.lar.quality

import hmda.model.fi.lar.LoanApplicationRegister
import hmda.validation.dsl.Result
import hmda.validation.dsl.PredicateCommon._
import hmda.validation.dsl.PredicateSyntax._

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try

object Q022 {

  def apply(lar: LoanApplicationRegister, year: Int): Result = {
    // This edit should not fail if applicationDate is equal to "NA" or is otherwise non-convertible
    val applicationYear = parseYear(lar).getOrElse(year)

    // The two year time frame is to allow for construction loans, where properties are typically built within two years.
    // SEE: https://github.com/cfpb/hmda-platform/issues/469
    (year - applicationYear) is between(0, 2)
  }

  def apply(lar: LoanApplicationRegister, fYear: Future[Int])(implicit ec: ExecutionContext): Future[Result] = {
    val applicationYear = parseYear(lar)

    fYear.map { year =>
      (year - applicationYear.getOrElse(year)) is between(0, 2)
    }
  }

  private def parseYear(lar: LoanApplicationRegister): Try[Int] = {
    Try(lar.loan.applicationDate.substring(0, 4).toInt)
  }

  def name = "Q022"
}

package hmda.validation.rules.lar.quality

import hmda.model.fi.lar.LoanApplicationRegister
import hmda.validation.EC
import hmda.validation.dsl.Result
import hmda.validation.dsl.PredicateCommon._
import hmda.validation.dsl.PredicateSyntax._

import scala.concurrent.Future
import scala.util.Try

object Q022 {

  def apply(lar: LoanApplicationRegister, year: Int): Result = {
    // This edit should not fail if applicationDate is equal to "NA" or is otherwise non-convertible
    val applicationYear = parseYear(lar).getOrElse(year)

    // The two year time frame is to allow for construction loans, where properties are typically built within two years.
    // SEE: https://github.com/cfpb/hmda-platform/issues/469
    (year - applicationYear) is between(0, 2)
  }

  def apply[_: EC](lar: LoanApplicationRegister, fYear: Future[Int]): Future[Result] = {
    val applicationYear = parseYear(lar)

    fYear.map { year =>
      (year - applicationYear.getOrElse(year)) is between(0, 2)
    }
  }

  private def parseYear(lar: LoanApplicationRegister): Try[Int] = {
    Try(lar.loan.applicationDate.substring(0, 4).toInt)
  }

  def name = "Q022"
}

Use context bound for implicit

Use context bound for implicit


package com.twitter.finagle

import java.util.concurrent.Executors
import com.twitter.concurrent.NamedPoolThreadFactory

/**
 * Package netty3 implements the bottom finagle primitives:
 * {{com.twitter.finagle.Server}} and a client transport in terms of
 * the netty3 event loop.
 *
 * Note: when {{com.twitter.finagle.builder.ClientBuilder}} and
 * {{com.twitter.finagle.builder.ServerBuilder}} are deprecated,
 * package netty3 can move into its own package, so that only the
 * (new-style) clients and servers that depend on netty3 bring it in.
 */
package object netty3 {
  val Executor = Executors.newCachedThreadPool(
    new NamedPoolThreadFactory("finagle/netty3", true/*daemon*/))

  object param {
    /**
     * A class eligible for configuring a netty3 timer.
     */
    case class Netty3Timer(timer: org.jboss.netty.util.Timer)
    implicit object Netty3Timer extends Stack.Param[Netty3Timer] {
      val default = Netty3Timer(util.DefaultTimer)
    }
  }
}

package com.twitter.finagle

import com.twitter.concurrent.NamedPoolThreadFactory
import java.util.concurrent.Executors
import org.jboss.netty.util.{ThreadNameDeterminer, ThreadRenamingRunnable}

/**
 * Package netty3 implements the bottom finagle primitives:
 * {{com.twitter.finagle.Server}} and a client transport in terms of
 * the netty3 event loop.
 *
 * Note: when {{com.twitter.finagle.builder.ClientBuilder}} and
 * {{com.twitter.finagle.builder.ServerBuilder}} are deprecated,
 * package netty3 can move into its own package, so that only the
 * (new-style) clients and servers that depend on netty3 bring it in.
 */
package object netty3 {
  // Disable Netty's thread name rewriting, to preserve the "finagle/netty3"
  // suffix specified below.
  ThreadRenamingRunnable.setThreadNameDeterminer(ThreadNameDeterminer.CURRENT);

  val Executor = Executors.newCachedThreadPool(
    new NamedPoolThreadFactory("finagle/netty3", true/*daemon*/))

  object param {
    /**
     * A class eligible for configuring a netty3 timer.
     */
    case class Netty3Timer(timer: org.jboss.netty.util.Timer)
    implicit object Netty3Timer extends Stack.Param[Netty3Timer] {
      val default = Netty3Timer(util.DefaultTimer)
    }
  }
}

Disable Netty's thread name renaming

[split] finagle: Disable Netty's thread name renaming

Problem

Netty is rewriting the name of the threads in the thread-pool with "New I/O worker #*".
This makes things difficult for new Finagle users to identify those threads as Finagle ones.

Solution

Disable Netty's thread renaming.

RB_ID=412147


package com.github.tminglei.slickpg
package trgm

import slick.jdbc.PostgresProfile

/**
  * Created by minglei on 6/21/17.
  */
trait PgTrgmSupport extends PgTrgmExtensions { driver: PostgresProfile =>
  import driver.api._

  trait PgTrgmImplicits {
    implicit def pgStringColumnExtensionMethods(c: Rep[String]) = new PgTrgmColumnExtensionMethods[String](c)
    implicit def pgStringOptionColumnExtensionMethods(c: Rep[Option[String]]) = new PgTrgmColumnExtensionMethods[Option[String]](c)
  }
}

package com.github.tminglei.slickpg
package trgm

import slick.jdbc.PostgresProfile

/**
  * Created by minglei on 6/21/17.
  */
trait PgTrgmSupport extends PgTrgmExtensions { driver: PostgresProfile =>
  import driver.api._

  trait PgTrgmImplicits {
    implicit def pgTrgmColumnExtensionMethods(c: Rep[String]) = new PgTrgmColumnExtensionMethods[String](c)
    implicit def pgTrgmOptionColumnExtensionMethods(c: Rep[Option[String]]) = new PgTrgmColumnExtensionMethods[Option[String]](c)
  }
}

Rename implicit defs in PgTrmImplicits to avoid collision with PgStringImplicits


package lila.round

import lila.hub.actorApi.timeline.{ Propagate, GameEnd => TLGameEnd }
import lila.notify.{ GameEnd, Notification, NotifyApi }

import lila.game.Game
import lila.user.User

final private class RoundNotifier(
    timeline: lila.hub.actors.Timeline,
    isUserPresent: (Game, User.ID) => Fu[Boolean],
    notifyApi: NotifyApi
)(implicit ec: scala.concurrent.ExecutionContext) {

  def gameEnd(game: Game)(color: chess.Color) =
    if (!game.aborted) game.player(color).userId foreach { userId =>
      game.perfType foreach { perfType =>
        timeline ! (Propagate(
          TLGameEnd(
            playerId = game fullIdOf color,
            opponent = game.player(!color).userId,
            win = game.winnerColor map (color ==),
            perf = perfType.key
          )
        ) toUser userId)
      }
      isUserPresent(game, userId) foreach {
        case false =>
          notifyApi.addNotification(
            Notification.make(
              Notification.Notifies(userId),
              GameEnd(
                GameEnd.GameId(game.id),
                game.opponent(color).userId map GameEnd.OpponentId.apply,
                game.wonBy(color) map GameEnd.Win.apply
              )
            )
          )
        case _ =>
      }
    }
}

package lila.round

import lila.hub.actorApi.timeline.{ Propagate, GameEnd => TLGameEnd }
import lila.notify.{ GameEnd, Notification, NotifyApi }

import lila.game.Game
import lila.user.User

final private class RoundNotifier(
    timeline: lila.hub.actors.Timeline,
    isUserPresent: (Game, User.ID) => Fu[Boolean],
    notifyApi: NotifyApi
)(implicit ec: scala.concurrent.ExecutionContext) {

  def gameEnd(game: Game)(color: chess.Color) =
    if (!game.aborted) game.player(color).userId foreach { userId =>
      game.perfType foreach { perfType =>
        timeline ! (Propagate(
          TLGameEnd(
            playerId = game fullIdOf color,
            opponent = game.player(!color).userId,
            win = game.winnerColor map (color ==),
            perf = perfType.key
          )
        ) toUser userId)
      }
      isUserPresent(game, userId) foreach {
        case false =>
          notifyApi.addNotification(
            Notification.make(
              Notification.Notifies(userId),
              GameEnd(
                GameEnd.GameId(game fullIdOf color),
                game.opponent(color).userId map GameEnd.OpponentId.apply,
                game.wonBy(color) map GameEnd.Win.apply
              )
            )
          )
        case _ =>
      }
    }
}

Include full game id in notification

Include full game id in notification


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

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

// web plugins

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

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

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

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

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

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

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

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

// web plugins

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

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

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

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

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

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

Update Play version to 2.3.4

Update Play version to 2.3.4


package com.trueaccord.scalapb.grpc

import com.google.common.util.concurrent.{FutureCallback, Futures, ListenableFuture}
import io.grpc.stub.StreamObserver

import scala.concurrent.{Promise, Future}
import scala.util.Try

object Grpc {
  def guavaFuture2ScalaFuture[A](guavaFuture: ListenableFuture[A]): Future[A] = {
    val p = Promise[A]()
    Futures.addCallback(guavaFuture, new FutureCallback[A] {
      override def onFailure(t: Throwable) = p.failure(t)
      override def onSuccess(a: A) = p.success(a)
    })
    p.future
  }

  def completeObserver[T](observer: StreamObserver[T])(t: Try[T]): Unit = t match {
    case scala.util.Success(value) =>
      observer.onNext(value)
      observer.onCompleted()
    case scala.util.Failure(error) =>
      observer.onError(error)
      observer.onCompleted()
  }
}

package com.trueaccord.scalapb.grpc

import com.google.common.util.concurrent.{FutureCallback, Futures, ListenableFuture}
import io.grpc.stub.StreamObserver

import scala.concurrent.{Promise, Future}
import scala.util.Try

object Grpc {
  def guavaFuture2ScalaFuture[A](guavaFuture: ListenableFuture[A]): Future[A] = {
    val p = Promise[A]()
    Futures.addCallback(guavaFuture, new FutureCallback[A] {
      override def onFailure(t: Throwable) = p.failure(t)
      override def onSuccess(a: A) = p.success(a)
    })
    p.future
  }

  def completeObserver[T](observer: StreamObserver[T])(t: Try[T]): Unit = t match {
    case scala.util.Success(value) =>
      observer.onNext(value)
      observer.onCompleted()
    case scala.util.Failure(error) =>
      observer.onError(error)
  }
}

Fix double stream close, don't call onComplete after onError

Fixes #71


// Global build settings

// Imports

import scalariform.formatter.preferences._

// Scalariform - source code formatter

// disable automatic reformat on compile
// instead use 'scalariform-format' command in sbt
defaultScalariformSettings // instead of scalariformSettings

// list of preferences available at http://mdr.github.io/scalariform/
ScalariformKeys.preferences := FormattingPreferences()
  .setPreference(AlignSingleLineCaseStatements, true)
  .setPreference(DoubleIndentClassDeclaration, true)
  .setPreference(PreserveDanglingCloseParenthesis, true)

// Imports

import scalariform.formatter.preferences._

// Global build settings

fork := true

// Scalariform - source code formatter

// disable automatic reformat on compile
// instead use 'scalariform-format' command in sbt
defaultScalariformSettings // instead of scalariformSettings

// list of preferences available at http://mdr.github.io/scalariform/
ScalariformKeys.preferences := FormattingPreferences()
  .setPreference(AlignSingleLineCaseStatements, true)
  .setPreference(DoubleIndentClassDeclaration, true)
  .setPreference(PreserveDanglingCloseParenthesis, true)

Update SBT config to always fork

Update SBT config to always fork


/*
* 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 py_sparkling.ml.algos

import org.apache.spark.ml.util.DefaultParamsReadable

/**
  * H2O AutoML Wrapper for PySparkling
  */
class H2OAutoML(override val uid: String) extends org.apache.spark.ml.h2o.algos.H2OAutoML(uid)

private[algos] object H2OAutoML extends DefaultParamsReadable[H2OXGBoost]

/*
* 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 py_sparkling.ml.algos

import org.apache.spark.ml.util.DefaultParamsReadable

/**
  * H2O AutoML Wrapper for PySparkling
  */
class H2OAutoML(override val uid: String) extends org.apache.spark.ml.h2o.algos.H2OAutoML(uid)

private[algos] object H2OAutoML extends DefaultParamsReadable[H2OAutoML]

Use default params reader in pipelines

[SW-1264][Followup] Use default params reader in pipelines


package core.interceptor

import javax.inject.Inject
import org.aopalliance.intercept.{MethodInterceptor, MethodInvocation}

import scala.concurrent.ExecutionContext

class InterceptorService @Inject()(implicit executionContext: ExecutionContext) extends MethodInterceptor {
  override def invoke(invocation: MethodInvocation): AnyRef = {
    invocation.proceed()
  }
}

package core.interceptor

import common.Logger
import core.guice.injection.Injecting.injector
import javax.inject.Inject
import org.aopalliance.intercept.{MethodInterceptor, MethodInvocation}

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

class InterceptorService @Inject() extends MethodInterceptor with Logger {
  override def invoke(invocation: MethodInvocation): AnyRef = {
    val classesAndArgs = invocation.getMethod.getParameterAnnotations.flatMap(_.zipWithIndex.flatMap {
      case (annotation, index) =>
        annotation.asInstanceOf[InterceptorArg].classes.flatMap {
          clazz =>
            List[(Class[_], Int)]((clazz, index))
        }
    }).toList
    val args = invocation.getArguments
    for (classAndArg <- classesAndArgs) {
      val clazz = classAndArg._1
      val argIndex = classAndArg._2
      log.debug(s"Handle $clazz with argument index $argIndex")
      Await.ready(
        injector.getInstance(clazz).asInstanceOf[Interceptor[AnyRef, AnyRef]].handle(args(argIndex)),
        Inf
      ).value.get.get match {
        case Left(error) =>
          log.debug(s"Handled with error: $error")
          return error
        case Right(value) =>
          log.debug(s"Handled with value: $value")
          value.foreach(args(argIndex) = _)
      }
    }
    log.debug(s"Proceed to the next interceptor in the chain")
    invocation.proceed()
  }
}

Add an implementation of interceptor service


package com.programmaticallyspeaking.ncd.e2e.java9

import com.programmaticallyspeaking.ncd.chrome.domains.{Runtime => RuntimeD}
import com.programmaticallyspeaking.ncd.e2e.RealRuntimeTestFixture
import com.programmaticallyspeaking.ncd.nashorn.java9.RunningJava9
import org.scalatest.prop.TableDrivenPropertyChecks

class RealRuntimeTest extends RealRuntimeTestFixture with TableDrivenPropertyChecks with RunningJava9 {

  private def waitForDebugger(testers: Tester*) = {
    runScript("debugger;")(testers: _*)
  }

  private def compileWithError(code: String)(f: RuntimeD.CompileScriptResult => Unit) = {
    waitForDebugger(_ => {
      val result = sendRequest(RuntimeD.compileScript(code, "", false, None))
      result match {
        case r: RuntimeD.CompileScriptResult =>
          f(r)
        case other => fail("unexpected: " + other)
      }
    })
  }

  "Runtime (Java 9)" - {
    "compileScript" - {

      "reports a _translated_ error if the script is an incomplete template literal (with persist=false)" in {
        compileWithError("`foo") { r =>
          val Some(desc) = r.exceptionDetails.flatMap(_.exception).flatMap(_.description)
          desc should startWith ("SyntaxError: Unterminated template literal")
        }
      }

      "doesn't translate a non-template literal related quite error" in {
        compileWithError("'foo") { r =>
          val desc = r.exceptionDetails.flatMap(_.exception).flatMap(_.description)
          desc should be (None)
        }
      }
    }
  }
}

package com.programmaticallyspeaking.ncd.e2e.java9

import com.programmaticallyspeaking.ncd.chrome.domains.{Runtime => RuntimeD}
import com.programmaticallyspeaking.ncd.e2e.RealRuntimeTestFixture
import com.programmaticallyspeaking.ncd.nashorn.java9.RunningJava9
import org.scalatest.prop.TableDrivenPropertyChecks

class RealRuntimeTest extends RealRuntimeTestFixture with TableDrivenPropertyChecks with RunningJava9 {

  private def waitForDebugger(testers: Tester*) = {
    runScript("debugger;")(testers: _*)
  }

  private def compileWithError(code: String)(f: RuntimeD.CompileScriptResult => Unit) = {
    waitForDebugger(_ => {
      val result = sendRequest(RuntimeD.compileScript(code, "", false, None))
      result match {
        case r: RuntimeD.CompileScriptResult =>
          f(r)
        case other => fail("unexpected: " + other)
      }
    })
  }

  "Runtime (Java 9)" - {
    "compileScript" - {

      "reports a _translated_ error if the script is an incomplete template literal (with persist=false)" in {
        compileWithError("`foo") { r =>
          val Some(desc) = r.exceptionDetails.flatMap(_.exception).flatMap(_.description)
          desc should startWith ("SyntaxError: Unterminated template literal")
        }
      }

      "doesn't translate a non-template literal related quote error" in {
        compileWithError("'foo") { r =>
          val desc = r.exceptionDetails.flatMap(_.exception).flatMap(_.description).getOrElse("")
          desc should not include ("Unterminated template literal")
        }
      }
    }
  }
}

Fix a failing compileScript test after refactoring


package io.udash.rpc

import com.avsystem.commons.rpc.rpcName

import scala.annotation.StaticAnnotation

@deprecated("RPC annotation is no longer needed", "0.7.0")
class RPC extends StaticAnnotation

object `package` {
  @deprecated("Use rpcName from com.avsystem.commons.rpc", "0.7.0")
  type RPCName = rpcName
}

package io.udash.rpc

import com.avsystem.commons.rpc.rpcName

import scala.annotation.StaticAnnotation

@deprecated("RPC annotation is no longer needed", "0.7.0")
class RPC extends StaticAnnotation

@deprecated("Use rpcName from com.avsystem.commons.rpc", "0.7.0")
class RPCName(override val name: String) extends rpcName(name)

Remove `rpc` package object from shared module


package ch.usi.inf.l3.sana.arrooj.symbols

import ch.usi.inf.l3.sana
import sana.tiny.symbols.Symbol
import sana.tiny.types.Type
import sana.tiny.names.Name
import sana.calcj.types.IntType
import sana.primj.symbols.VariableSymbol
import sana.ooj.modifiers._
import sana.primj.modifiers._

trait SymbolUtils extends sana.ooj.symbols.SymbolUtils {
  lazy val arrayLengthSymbol: Symbol = {
    val mods   = PUBLIC_ACC | FINAL
    val name   = Name("length")
    val tpt    = getSymbol(IntType)
    VariableSymbol(mods, name, tpt, None)
  }

  def mkArraySymbol(componentSymbol: Symbol): ArraySymbol =
    new ArraySymbolImpl(componentSymbol,
      objectClassSymbol, List(arrayLengthSymbol))
}

object SymbolUtils extends SymbolUtils

package ch.usi.inf.l3.sana.arrooj.symbols

import ch.usi.inf.l3.sana
import sana.tiny.symbols.Symbol
import sana.tiny.types.Type
import sana.tiny.names.Name
import sana.calcj.types.IntType
import sana.primj.symbols.VariableSymbol
import sana.ooj.modifiers._
import sana.primj.modifiers._

trait SymbolUtils extends sana.ooj.symbols.SymbolUtils {
  lazy val arrayLengthSymbol: Symbol = {
    val mods   = PUBLIC_ACC | FINAL | FIELD
    val name   = Name("length")
    val tpt    = getSymbol(IntType)
    VariableSymbol(mods, name, tpt, None)
  }

  def mkArraySymbol(componentSymbol: Symbol): ArraySymbol =
    new ArraySymbolImpl(componentSymbol,
      objectClassSymbol, List(arrayLengthSymbol))
}

object SymbolUtils extends SymbolUtils

Add the FIELD flag for array's length field


/*!md
---
layout: tutorial
title: Reactors
topic: reactors
logoname: reactress-mini-logo-flat.png
projectname: Reactors.IO
homepage: http://reactors.io
permalink: /reactors/index.html
---

To get started with Reactors.IO, you should grab the latest snapshot version distributed
on Maven. If you are using SBT, add the following to your project definition:

    resolvers ++= Seq(
      "Sonatype OSS Snapshots" at
        "https://oss.sonatype.org/content/repositories/snapshots",
      "Sonatype OSS Releases" at
        "https://oss.sonatype.org/content/repositories/releases"
    )

    libraryDependencies ++= Seq(
      "com.storm-enroute" %% "reactors" % "0.6-SNAPSHOT")

The getting started guide has the following parts:

{% for pg in site.pages %}
  {% if pg.topic == "reactors" and pg.section == "guide" and pg.pagetot %}
    {% assign totalPages = pg.pagetot %}
  {% endif %}
{% endfor %}

{% for i in (1..totalPages) %}
  {% for pg in site.pages %}
    {% if pg.topic == "reactors" and pg.section == "guide" %}
      {% if pg.pagenum and pg.pagenum == i %}

{{ pg.title }}

      {% endif %}
    {% endif %}
  {% endfor %}
{% endfor %}

!*/
package tutorial

/*!md
---
layout: tutorial
title: Reactors
topic: reactors
logoname: reactress-mini-logo-flat.png
projectname: Reactors.IO
homepage: http://reactors.io
permalink: /reactors/index.html
---

To get started with Reactors.IO, you should grab the latest snapshot version distributed
on Maven. If you are using SBT, add the following to your project definition:

    resolvers ++= Seq(
      "Sonatype OSS Snapshots" at
        "https://oss.sonatype.org/content/repositories/snapshots",
      "Sonatype OSS Releases" at
        "https://oss.sonatype.org/content/repositories/releases"
    )

    libraryDependencies ++= Seq(
      "com.storm-enroute" %% "reactors" % "0.7-SNAPSHOT")

The getting started guide has the following parts:

{% for pg in site.pages %}
  {% if pg.topic == "reactors" and pg.section == "guide" and pg.pagetot %}
    {% assign totalPages = pg.pagetot %}
  {% endif %}
{% endfor %}

{% for i in (1..totalPages) %}
  {% for pg in site.pages %}
    {% if pg.topic == "reactors" and pg.section == "guide" %}
      {% if pg.pagenum and pg.pagenum == i %}

{{ pg.title }}

      {% endif %}
    {% endif %}
  {% endfor %}
{% endfor %}

!*/
package tutorial

Use 0.7 snapshot in the instructions.

Use 0.7 snapshot in the instructions.


package org.talkingpuffin.ui

import org.talkingpuffin.util.Loggable
import twitter4j.User

/**
 * Helps with creating HTML for display in the UI
 */
object HtmlFormatter extends Loggable {

  def createTweetHtml(text: String, replyTo: Option[Long], source: String,
                      retweetingUser: Option[User]): String = {
    val arrowLinkToParent = LinkExtractor.getReplyToInfo(replyTo, text) match {
      case Some((user, id)) => "↑ "
      case None => ""
    }

    val r = LinkExtractor.createLinks(text).replaceAll("\n", "
")

    htmlAround(arrowLinkToParent + fontAround(r, "190%") +
        fontAround(" from " + source +
        (if (retweetingUser.isDefined) ", RT by " + retweetingUser.get.getScreenName else ""), "80%"))
  }

  def fontAround(s: String, size: String) =
    "" + s + ""

  def htmlAround(s: String) = "" + s + ""

}

package org.talkingpuffin.ui

import org.talkingpuffin.util.Loggable
import org.talkingpuffin.Constants.RetweetSymbol
import twitter4j.User

/**
 * Helps with creating HTML for display in the UI
 */
object HtmlFormatter extends Loggable {

  def createTweetHtml(text: String, replyTo: Option[Long], source: String, retweetingUser: Option[User]): String = {
    val arrowLinkToParent = LinkExtractor.getReplyToInfo(replyTo, text) match {
      case Some((user, id)) => "↑ "
      case None => ""
    }

    val r = LinkExtractor.createLinks(text).replaceAll("\n", "
")

    htmlAround(arrowLinkToParent + fontAround(r, "190%") + fontAround(
        (if (retweetingUser.isDefined) " " + RetweetSymbol + " " + retweetingUser.get.getScreenName else "") +
          " " + source, "80%"))
  }

  def fontAround(s: String, size: String) =
    "" + s + ""

  def htmlAround(s: String) = "" + s + ""

}

Use a symbol to mark retweets. Shorten display of source application (remove “from”).


package io.eels.component.parquet

import com.typesafe.scalalogging.slf4j.StrictLogging
import io.eels.{Column, Field, FilePattern, Reader, Row, Source}
import org.apache.avro.generic.GenericRecord
import org.apache.parquet.avro.AvroParquetReader

import scala.collection.JavaConverters._

case class ParquetSource(pattern: FilePattern) extends Source with StrictLogging {

  def reader: Reader = new Reader {

    private val paths = pattern.toPaths
    logger.debug(s"Parquet source will read from $paths")
    private val readers = paths.map(AvroParquetReader.builder[GenericRecord](_).build().asInstanceOf[AvroParquetReader[GenericRecord]])

    private val iterators = readers.map(reader => Iterator.continually(reader.read).takeWhile(_ != null).map { record =>
      val columns = record.getSchema.getFields.asScala.map(_.name).map(Column.apply)
      val fields = columns.map(col => record.get(col.name).toString).map(Field.apply)
      Row(columns, fields)
    })
    private val mergedIterator = iterators.reduce((a, b) => a ++ b)

    override val iterator: Iterator[Row] = new Iterator[Row] {
      override def hasNext: Boolean = {
        val hasNext = mergedIterator.hasNext
        if (!hasNext)
          close()
        hasNext
      }
      override def next(): Row = mergedIterator.next()
    }

    override def close(): Unit = readers.foreach(_.close)
  }
}

package io.eels.component.parquet

import com.typesafe.scalalogging.slf4j.StrictLogging
import io.eels.{Column, Field, FilePattern, Reader, Row, Source}
import org.apache.avro.generic.GenericRecord
import org.apache.parquet.avro.AvroParquetReader
import org.apache.parquet.hadoop.ParquetReader

import scala.collection.JavaConverters._

case class ParquetSource(pattern: FilePattern) extends Source with StrictLogging {

  def reader: Reader = new Reader {

    private val paths = pattern.toPaths
    logger.debug(s"Parquet source will read from $paths")
    private val readers = paths.map(AvroParquetReader.builder[GenericRecord](_).build().asInstanceOf[ParquetReader[GenericRecord]])

    private val iterators = readers.map(reader => Iterator.continually(reader.read).takeWhile(_ != null).map { record =>
      val columns = record.getSchema.getFields.asScala.map(_.name).map(Column.apply)
      val fields = columns.map(col => record.get(col.name).toString).map(Field.apply)
      Row(columns, fields)
    })
    private val mergedIterator = iterators.reduce((a, b) => a ++ b)

    override val iterator: Iterator[Row] = new Iterator[Row] {
      override def hasNext: Boolean = {
        val hasNext = mergedIterator.hasNext
        if (!hasNext)
          close()
        hasNext
      }
      override def next(): Row = mergedIterator.next()
    }

    override def close(): Unit = readers.foreach(_.close)
  }
}

Fix for parquet source fixes

Fix for parquet source fixes


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

addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.4.11")

addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.1")

addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.5.3")

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

addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.4.11")

addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.1")

//addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.5.3")

Disable scalafix to fix travis

Disable scalafix to fix travis


name := "pureconfig-cats"

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

libraryDependencies ++= Seq(
  "org.typelevel" %% "cats-core" % "1.6.1",
  "org.typelevel" %% "cats-laws" % "1.6.1" % "test")

developers := List(
  Developer("derekmorr", "Derek Morr", "morr.derek@gmail.com", url("https://github.com/derekmorr")),
  Developer("ruippeixotog", "Rui Gonçalves", "ruippeixotog@gmail.com", url("https://github.com/ruippeixotog")))

osgiSettings

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

name := "pureconfig-cats"

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

libraryDependencies ++= Seq(
  "org.typelevel" %% "cats-core" % "2.0.0",
  "org.typelevel" %% "cats-laws" % "2.0.0" % "test")

developers := List(
  Developer("derekmorr", "Derek Morr", "morr.derek@gmail.com", url("https://github.com/derekmorr")),
  Developer("ruippeixotog", "Rui Gonçalves", "ruippeixotog@gmail.com", url("https://github.com/ruippeixotog")))

osgiSettings

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

Update cats-core, cats-laws to 2.0.0

Update cats-core, cats-laws to 2.0.0


package dotty.tools.dotc
package transform

import core._
import Contexts.*
import DenotTransformers.IdentityDenotTransformer
import Decorators.*
import ast.tpd.*

/** A phase that adds mirror support for anonymous mirrors created at inlining. */
class PostInlining extends MacroTransform, IdentityDenotTransformer:
  thisPhase =>

  override def phaseName: String = PostInlining.name
  override def changesMembers = true

  override def run(using Context): Unit =
    if ctx.compilationUnit.needsMirrorSupport then super.run

  lazy val synthMbr: SyntheticMembers = new SyntheticMembers(thisPhase)

  def newTransformer(using Context): Transformer = new Transformer:
    override def transform(tree: Tree)(using Context): Tree =
      super.transform(tree) match
        case tree1: Template => synthMbr.addMirrorSupport(tree1)
        case tree1 => tree1

object PostInlining:
  val name: String = "postInlining"

package dotty.tools.dotc
package transform

import core._
import Contexts.*
import DenotTransformers.IdentityDenotTransformer
import Decorators.*
import SyntheticMembers.*
import ast.tpd.*

/** A phase that adds mirror support for anonymous mirrors created at inlining. */
class PostInlining extends MacroTransform, IdentityDenotTransformer:
  thisPhase =>

  override def phaseName: String = PostInlining.name
  override def changesMembers = true

  override def run(using Context): Unit =
    if ctx.compilationUnit.needsMirrorSupport then super.run

  lazy val synthMbr: SyntheticMembers = new SyntheticMembers(thisPhase)

  def newTransformer(using Context): Transformer = new Transformer:
    override def transform(tree: Tree)(using Context): Tree =
      super.transform(tree) match
        case tree1: Template
        if tree1.hasAttachment(ExtendsSingletonMirror)
          || tree1.hasAttachment(ExtendsProductMirror)
          || tree1.hasAttachment(ExtendsSumMirror) =>
          synthMbr.addMirrorSupport(tree1)
        case tree1 => tree1

object PostInlining:
  val name: String = "postInlining"

Fix double generation for mirror support


package uk.ac.wellcome.platform.common

import org.scalatest.{FunSpec, Matchers}

import uk.ac.wellcome.models.Work
import uk.ac.wellcome.utils.JsonUtil

class WorkTest extends FunSpec with Matchers {
  it("should have an LD type 'Work' when serialised to JSON") {
    val work = Work(
      identifiers=List(),
      label="A book about a blue whale"
    )
    val jsonString = JsonUtil.toJson(work).get

    jsonString.contains("""type":"Work"""") should be (true)
  }

  it("should not include fields where the value is empty or None") {
    val work = Work(
      identifiers=List(),
      label="A haiku about a heron",
      accessStatus=None
    )
    val jsonString = JsonUtil.toJson(work).get

    jsonString.contains(""""accessStatus":null""") should be (false)
    jsonString.contains(""""identifiers":[]""") should be (false)
  }
}

package uk.ac.wellcome.platform.common

import org.scalatest.{FunSpec, Matchers}

import uk.ac.wellcome.models.Work
import uk.ac.wellcome.utils.JsonUtil

class WorkTest extends FunSpec with Matchers {
  it("should have an LD type 'Work' when serialised to JSON") {
    val work = Work(
      identifiers=List(),
      label="A book about a blue whale"
    )
    val jsonString = JsonUtil.toJson(work).get

    jsonString.contains("""type":"Work"""") should be (true)
  }
}

class JsonUtilTest extends FunSpec with Matchers {
  it("should not include fields where the value is empty or None") {
    val work = Work(
      identifiers=List(),
      label="A haiku about a heron",
      accessStatus=None
    )
    val jsonString = JsonUtil.toJson(work).get

    jsonString.contains(""""accessStatus":null""") should be (false)
    jsonString.contains(""""identifiers":[]""") should be (false)
  }
}

Break tests into distinct classes

Break tests into distinct classes


package spmd

object NetAdm extends scala.actors.Actor {
  import scala.collection.mutable.{LinkedHashSet, SynchronizedSet}
  import scala.actors.Actor._
  import scala.actors.TIMEOUT
  import spmd.RemoteActor._

  val knownNodes = new LinkedHashSet[Node] with SynchronizedSet[Node]

  def act = {
    register('net_adm, this)
    loop { receive {
      case Ping(other) =>
        newKnownNode(other)
        reply(Pong)
      case NewNode(node) => newKnownNode(node)
      case GetNodes => knownNodes
    }}
  }

  def ping(nodeName: String): PingResponse = {
    Console.findNode(nodeName) match {
      case Some(node) =>
        val targetNetAdm = select('net_adm, node)
        targetNetAdm ! Ping(Console.node)
        self.receiveWithin(1000) {
          case pong @ Pong =>
            knownNodes.foreach { n =>
              select('net_adm, n) ! NewNode(node)
              targetNetAdm ! NewNode(n)
            }
            newKnownNode(node)
            pong
          case TIMEOUT => Pang("timout")
        }
      case None => Pang("no such node")
    }
  }

  def nodes: List[Node] = knownNodes.toList

  private def newKnownNode(other: Node) =
    if (other != Console.node) knownNodes += other

  case class Ping(other: Node)
  case class NewNode(node: Node)
  case object GetNodes

  sealed abstract class PingResponse
  case object Pong extends PingResponse
  case class Pang(cause: String) extends PingResponse
}

package spmd

object NetAdm extends scala.actors.Actor {
  import scala.collection.mutable.LinkedHashSet
  import scala.actors.Actor._
  import scala.actors.TIMEOUT
  import spmd.RemoteActor._

  private val knownNodes = new LinkedHashSet[Node]

  def act = {
    register('net_adm, this)
    loop { receive {
      case Ping(other) =>
        newKnownNode(other)
        reply(Pong)
      case NewNode(node) => newKnownNode(node)
    }}
  }

  def ping(nodeName: String): PingResponse = {
    Console.findNode(nodeName) match {
      case Some(node) =>
        val targetNetAdm = select('net_adm, node)
        targetNetAdm ! Ping(Console.node)
        self.receiveWithin(1000) {
          case pong @ Pong =>
            knownNodes.foreach { n =>
              select('net_adm, n) ! NewNode(node)
              targetNetAdm ! NewNode(n)
            }
            NetAdm ! NewNode(node)
            pong
          case TIMEOUT => Pang("timout")
        }
      case None => Pang("no such node")
    }
  }

  def nodes: List[Node] = knownNodes.toList

  private def newKnownNode(other: Node) =
    if (other != Console.node) knownNodes += other

  case class Ping(other: Node)
  case class NewNode(node: Node)

  sealed abstract class PingResponse
  case object Pong extends PingResponse
  case class Pang(cause: String) extends PingResponse
}

Update knownNodes only from receive loop


name := "Thunder"

version := "0.2.0"

scalaVersion := "2.10.3"

ivyXML := <dependency org="org.eclipse.jetty.orbit" name="javax.servlet" rev="3.0.0.v201112011016">
<artifact name="javax.servlet" type="orbit" ext="jar"/>
</dependency>

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.0.1"

libraryDependencies += "org.apache.spark" %% "spark-streaming" % "1.0.1"

libraryDependencies += "org.apache.spark" % "spark-mllib_2.10" % "1.0.1"

libraryDependencies += "org.scalatest" % "scalatest_2.10" % "2.0" % "test"

libraryDependencies += "io.spray" %% "spray-json" % "1.2.5"

libraryDependencies += "org.jblas" % "jblas" % "1.2.3"

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

resolvers ++= Seq(
  "Akka Repository" at "http://repo.akka.io/releases/",
  "Spray Repository" at "http://repo.spray.cc/")

name := "Thunder"

version := "0.2.0"

scalaVersion := "2.10.3"

ivyXML := <dependency org="org.eclipse.jetty.orbit" name="javax.servlet" rev="3.0.0.v201112011016">
<artifact name="javax.servlet" type="orbit" ext="jar"/>
</dependency>

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.0.2"

libraryDependencies += "org.apache.spark" %% "spark-streaming" % "1.0.2"

libraryDependencies += "org.apache.spark" % "spark-mllib_2.10" % "1.0.2"

libraryDependencies += "org.scalatest" % "scalatest_2.10" % "2.0" % "test"

libraryDependencies += "io.spray" %% "spray-json" % "1.2.5"

libraryDependencies += "org.jblas" % "jblas" % "1.2.3"

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

resolvers ++= Seq(
  "Akka Repository" at "http://repo.akka.io/releases/",
  "Spray Repository" at "http://repo.spray.cc/")

Update scala to use Spark 1.0.2

Update scala to use Spark 1.0.2


package controllers

import client.{ Apidoc, ApidocClient }
import play.api.mvc._
import play.api.mvc.Results.Redirect
import scala.concurrent.{ Await, Future }
import scala.concurrent.duration._

class AuthenticatedRequest[A](val user: Apidoc.User, request: Request[A]) extends WrappedRequest[A](request) {

  lazy val client = ApidocClient.instance(user.guid)

}

object Authenticated extends ActionBuilder[AuthenticatedRequest] {

  private lazy val masterClient = ApidocClient.instance("f3973f60-be9f-11e3-b1b6-0800200c9a66")

  def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A]) => Future[SimpleResult]) = {

    request.session.get("user_guid").map { userGuid =>
      val user = Await.result(masterClient.users.findByGuid(userGuid), 1500 millis)
      user match {

        case None => {
          // have a user guid, but user does not exist
          Future.successful(Redirect("/login").withNewSession)
        }

        case Some(u: Apidoc.User) => {
          block(new AuthenticatedRequest(u, request))
        }

      }

    } getOrElse {
      Future.successful(Redirect("/login"))

    }

  }
}

package controllers

import client.{ Apidoc, ApidocClient }
import play.api.mvc._
import play.api.mvc.Results.Redirect
import scala.concurrent.{ Await, Future }
import scala.concurrent.duration._

class AuthenticatedRequest[A](val user: Apidoc.User, request: Request[A]) extends WrappedRequest[A](request) {

  lazy val client = ApidocClient.instance(user.guid)

}

object Authenticated extends ActionBuilder[AuthenticatedRequest] {

  private lazy val masterClient = ApidocClient.instance("f3973f60-be9f-11e3-b1b6-0800200c9a66")

  def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A]) => Future[SimpleResult]) = {

    request.session.get("user_guid").map { userGuid =>
      val user = Await.result(masterClient.users.findByGuid(userGuid), 5000 millis)
      user match {

        case None => {
          // have a user guid, but user does not exist
          Future.successful(Redirect("/login").withNewSession)
        }

        case Some(u: Apidoc.User) => {
          block(new AuthenticatedRequest(u, request))
        }

      }

    } getOrElse {
      Future.successful(Redirect("/login"))

    }

  }
}

Increase timeout to 5 seconds - useful for startup


name := "play2-graylog2"

organization := "org.graylog2"

version := "1.2"

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

libraryDependencies ++= Seq(
)

// Settings for publishing to Maven Central, see http://www.scala-sbt.org/0.13/docs/Using-Sonatype.html
publishMavenStyle := true

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

licenses := Seq("Apache 2.0" -> url("https://www.apache.org/licenses/LICENSE-2.0"))

homepage := Some(url("https://github.com/Graylog2/play2-graylog2"))

pomExtra := (
  <scm>
    <url>https://github.com/Graylog2/play2-graylog2</url>
    <connection>scm:git:https://github.com/Graylog2/play2-graylog2.git</connection>
    <developerConnection>scm:git:git@github.com:Graylog2/play2-graylog2.git</developerConnection>
  </scm>)

name := "play2-graylog2"

organization := "org.graylog2"

version := "1.2"

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

libraryDependencies ++= Seq(
)

// Settings for publishing to Maven Central, see http://www.scala-sbt.org/0.13/docs/Using-Sonatype.html
publishMavenStyle := true

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

licenses := Seq("Apache 2.0" -> url("https://www.apache.org/licenses/LICENSE-2.0"))

homepage := Some(url("https://github.com/Graylog2/play2-graylog2"))

pomExtra := (
  <scm>
    <url>https://github.com/Graylog2/play2-graylog2</url>
    <connection>scm:git:https://github.com/Graylog2/play2-graylog2.git</connection>
    <developerConnection>scm:git:git@github.com:Graylog2/play2-graylog2.git</developerConnection>
  </scm>
    <developers>
      <developer>
        <id>kroepke</id>
        <name>Kay Roepke</name>
      </developer>
    </developers>)

Add missing developer information to POM


package quasar.project

object Versions {
  val algebraVersion      = "1.0.1"
  val argonautVersion     = "6.2.3"
  val catsVersion         = "1.6.0"
  val catsEffectVersion   = "1.3.0"
  val disciplineVersion   = "0.11.1"
  val jawnVersion         = "0.14.2"
  val jawnfs2Version      = "0.14.2"
  val matryoshkaVersion   = "0.18.3"
  val monocleVersion      = "1.5.0"
  val pathyVersion        = "0.2.13"
  val refinedVersion      = "0.9.5"
  val scodecBitsVersion   = "1.1.2"
  val scalacheckVersion   = "1.14.0"
  val scalazVersion       = "7.2.27"
  val scoptVersion        = "3.7.1"
  val shapelessVersion    = "2.3.3"
  val simulacrumVersion   = "0.16.0"
  val specsVersion        = "4.3.6"
  val spireVersion        = "0.16.1"
  val akkaVersion         = "2.5.1"
  val fs2Version          = "1.0.4"
  val slf4sVersion        = "1.7.25"
  val atomixVersion       = "3.0.6"
}

package quasar.project

object Versions {
  val algebraVersion      = "1.0.1"
  val argonautVersion     = "6.2.3"
  val catsVersion         = "1.6.0"
  val catsEffectVersion   = "1.3.0"
  val disciplineVersion   = "0.11.1"
  val jawnVersion         = "0.14.2"
  val jawnfs2Version      = "0.14.2"
  val matryoshkaVersion   = "0.18.3"
  val monocleVersion      = "1.5.0"
  val pathyVersion        = "0.2.13"
  val refinedVersion      = "0.9.5"
  val scodecBitsVersion   = "1.1.2"
  val scalacheckVersion   = "1.14.0"
  val scalazVersion       = "7.2.27"
  val scoptVersion        = "3.7.1"
  val shapelessVersion    = "2.3.3"
  val simulacrumVersion   = "0.16.0"
  val specsVersion        = "4.5.1"
  val spireVersion        = "0.16.1"
  val akkaVersion         = "2.5.1"
  val fs2Version          = "1.0.4"
  val slf4sVersion        = "1.7.25"
  val atomixVersion       = "3.0.6"
}

Update specs2-core, specs2-scalacheck, ... to 4.5.1


package app.ser.vice.cache

import java.util.UUID
import javax.inject.{ Inject, Singleton }
import scala.concurrent.duration.{ Duration, _ }
import scala.concurrent.{ Await, Future }
import scala.concurrent.ExecutionContext.Implicits.global
import scala.reflect.ClassTag
import play.api.cache.ehcache.EhCacheApi
import net.sf.ehcache.config.CacheConfiguration
import net.sf.ehcache.{ Cache, CacheManager }

class EhCacheProvider(cacheName: String) {

  private val name = cacheName
  private val cacheManager = CacheManager.create
  cacheManager.addCache(name)

  private val cache = new EhCacheApi(cacheManager.getEhcache(name))

  def get[T](key: String, dur: Duration = Duration.Inf)(implicit cTag: ClassTag[T]): Option[T] = {
    Await.result(cache.get[T](key), dur)
  }

  def set(key: String, value: Any, dur: Duration = Duration.Inf): Unit = {
    cache.set(key, value)
  }

  def remove(key: String): Unit = {
    cache.remove(key)
  }
}

package app.services.cache

import scala.concurrent.duration.{ Duration, _ }
import scala.concurrent.{ Await, Future }
import scala.concurrent.ExecutionContext.Implicits.global
import scala.reflect.ClassTag
import play.api.cache.ehcache.EhCacheApi
import net.sf.ehcache.config.CacheConfiguration
import net.sf.ehcache.{ Cache, CacheManager }

class EhCacheProvider(cacheName: String) {

  private val name = cacheName
  private val cacheManager = CacheManager.create
  cacheManager.addCache(name)

  private val cache = new EhCacheApi(cacheManager.getEhcache(name))

  def get[T](key: String, dur: Duration = Duration.Inf)(implicit cTag: ClassTag[T]): Option[T] = {
    Await.result(cache.get[T](key), dur)
  }

  def set(key: String, value: Any, dur: Duration = Duration.Inf): Unit = {
    cache.set(key, value)
  }

  def remove(key: String): Unit = {
    cache.remove(key)
  }
}

Fix namespace and delete unused imports

Fix namespace and delete unused imports


import AssemblyKeys._

assemblySettings

name := "example-scala-local-regression"

organization := "io.prediction"

libraryDependencies ++= Seq(
  "io.prediction"    %% "core"          % "0.8.0-SNAPSHOT" % "provided",
  "org.apache.spark" %% "spark-core"    % "1.1.0" % "provided",
  "org.json4s"       %% "json4s-native" % "3.2.10",
  "org.scalanlp"      % "nak"           % "1.2.1")

import AssemblyKeys._

assemblySettings

name := "example-scala-local-regression"

organization := "io.prediction"

libraryDependencies ++= Seq(
  "io.prediction"    %% "core"          % "0.8.0-SNAPSHOT" % "provided",
  "org.apache.spark" %% "spark-core"    % "1.1.0" % "provided",
  "org.json4s"       %% "json4s-native" % "3.2.10",
  "org.scalanlp"     %% "nak"           % "1.3")

Fix compatibility with Spark 1.1.0

Fix compatibility with Spark 1.1.0


package sbtdynver

import sbt._, Keys._

object DynverPlugin extends AutoPlugin {
  // TODO: Test if this requirement can be lowered
  override def requires = plugins.JvmPlugin
  override def trigger  = allRequirements

  override def buildSettings = Seq(
    version := {
      def overrideVersion = Option(sys props "project.version")
      def   dynverVersion = Some(makeDynVer())
      def    datedVersion = s"HEAD+$currentYearMonthDay"

      Seq(overrideVersion, dynverVersion) reduce (_ orElse _) getOrElse datedVersion
    },
    isSnapshot := isDirty() || hasNoTags()
  )

  def currentYearMonthDay() = "%1$tY%1$tm%1$td" format new java.util.Date

  def makeDynVer() = {
    s"""git describe --abbrev=8 --match v[0-9].* --always --dirty=+$currentYearMonthDay""".!!.init
      .replaceAll("^v", "")
      .replaceAll("-([0-9]+)-g([0-9a-f]{8})", "+$1-$2")
  }

  def isDirty() = "git status --untracked-files=no --porcelain".!!.nonEmpty

  def hasNoTags() = "git for-each-ref --format %(objecttype) refs/tags/".!!
    .linesIterator.forall(_ startsWith "commit")
}

package sbtdynver

import sbt._, Keys._

object DynverPlugin extends AutoPlugin {
  override def requires = plugins.JvmPlugin
  override def trigger  = allRequirements

  private val dynver = DynVer(None)

  override def buildSettings = Seq(
       version := dynver.version(),
    isSnapshot := dynver.isSnapshot()
  )
}

final case class DynVer(wd: Option[File]) {
  def version() = {
    def overrideVersion = Option(sys props "project.version")
    def   dynverVersion = Some(makeDynVer())
    def    datedVersion = s"HEAD+$currentYearMonthDay"

    Seq(overrideVersion, dynverVersion) reduce (_ orElse _) getOrElse datedVersion
  }

  def isSnapshot() = isDirty() || hasNoTags()

  def currentYearMonthDay() = "%1$tY%1$tm%1$td" format new java.util.Date

  def makeDynVer() = {
    Process(s"""git describe --abbrev=8 --match v[0-9].* --always --dirty=+$currentYearMonthDay""", wd).!!.init
      .replaceAll("^v", "")
      .replaceAll("-([0-9]+)-g([0-9a-f]{8})", "+$1-$2")
  }

  def isDirty() = Process("git status --untracked-files=no --porcelain", wd).!!.nonEmpty

  def hasNoTags() = Process("git for-each-ref --format %(objecttype) refs/tags/", wd).!!
    .linesIterator.forall(_ startsWith "commit")
}

Create DynVer, so the working dir can be set


import sbt._
import Keys._
import bintray._

lazy val roboVMVersion = settingKey[String]("RoboVM Version against which this plugin is built")

lazy val sbtRoboVM = (project in file(".")).
  enablePlugins(BuildInfoPlugin).
  settings(
    name := "sbt-robovm",
    roboVMVersion := "1.6.1-SNAPSHOT",
    licenses += ("BSD 3-Clause", url("http://opensource.org/licenses/BSD-3-Clause")),
    organization := "org.roboscala",
    version := roboVMVersion.value,
    sbtPlugin := true,
    publishMavenStyle := false,
    bintrayOrganization := None,
    bintrayRepository := "sbt-plugins",
    scalacOptions ++= Seq("-unchecked", "-deprecation", "-Xcheckinit", "-Xfatal-warnings"),
    javacOptions ++= Seq("-source","6","-target","6"),
    resolvers ++= {if (roboVMVersion.value.contains("-SNAPSHOT")) Seq(Resolver.sonatypeRepo("snapshots")) else Seq()},
    libraryDependencies += "org.robovm" % "robovm-dist-compiler" % roboVMVersion.value,
    libraryDependencies += "org.robovm" % "robovm-maven-resolver" % roboVMVersion.value,
    buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion, roboVMVersion),
    buildInfoPackage := "sbtrobovm"
  )

import sbt.Keys._
import sbt._

lazy val roboVMVersion = settingKey[String]("RoboVM Version against which this plugin is built")

lazy val sbtRoboVM = (project in file(".")).
  enablePlugins(BuildInfoPlugin).
  settings(
    name := "sbt-robovm",
    roboVMVersion := "1.6.1-SNAPSHOT",
    licenses += ("BSD 3-Clause", url("http://opensource.org/licenses/BSD-3-Clause")),
    organization := "org.roboscala",
    version := roboVMVersion.value,
    sbtPlugin := true,
    publishMavenStyle := false,
    bintrayOrganization := None,
    bintrayRepository := "sbt-plugins",
    scalacOptions ++= Seq("-unchecked", "-deprecation", "-Xcheckinit", "-Xfatal-warnings"),
    javacOptions ++= Seq("-source", "6", "-target", "6"),
    resolvers ++= {if (roboVMVersion.value.contains("-SNAPSHOT")) Seq(Resolver.sonatypeRepo("snapshots")) else Seq()},
    libraryDependencies += "org.robovm" % "robovm-dist-compiler" % roboVMVersion.value,
    libraryDependencies += "org.robovm" % "robovm-maven-resolver" % roboVMVersion.value,
    buildInfoKeys := Seq[BuildInfoKey](name, version, scalaVersion, sbtVersion, roboVMVersion),
    buildInfoPackage := "sbtrobovm"
  )

Remove unused import and format code

Remove unused import and format code


name := "gu-who"

version := "1.0-SNAPSHOT"

libraryDependencies ++= Seq(
  jdbc,
  anorm,
  cache,
  "org.kohsuke" % "github-api" % "1.50-SNAPSHOT",
  "com.github.scala-incubator.io" %% "scala-io-file" % "0.4.2",
  "org.eclipse.jgit" % "org.eclipse.jgit" % "3.2.0.201312181205-r",
  "com.madgag" %% "scala-git" % "1.11.1",
  "com.madgag" %% "scala-git-test" % "1.11.1" % "test"
)

resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository"

play.Project.playScalaSettings

name := "gu-who"

version := "1.0-SNAPSHOT"

libraryDependencies ++= Seq(
  jdbc,
  anorm,
  cache,
  "com.madgag" % "github-api" % "1.49.99.0.1",
  "com.github.scala-incubator.io" %% "scala-io-file" % "0.4.2",
  "org.eclipse.jgit" % "org.eclipse.jgit" % "3.2.0.201312181205-r",
  "com.madgag" %% "scala-git" % "1.11.1",
  "com.madgag" %% "scala-git-test" % "1.11.1" % "test"
)

resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository"

play.Project.playScalaSettings

Use released fork of github-api

Use released fork of github-api

I've published a small fork of the github-api, which includes these
pull-requests we need:

https://github.com/kohsuke/github-api/pull/66 - org member paging
https://github.com/kohsuke/github-api/pull/68 - org-member filtering


name := "Barrio"
organization := "com.codiply"
version := "0.0.1"

scalaVersion := "2.11.11"

libraryDependencies ++= {
  val akkaVersion = "2.4.19"
  val akkaHttpVersion = "10.0.9"

  Seq(
    "com.github.scopt" %% "scopt" % "3.6.0",
    "org.scalactic" %% "scalactic" % "3.0.1",
    "org.scalamock" %% "scalamock-scalatest-support" % "3.6.0" % Test,
    "org.scalatest" %% "scalatest" % "3.0.1" % Test,
    "com.typesafe.akka" %% "akka-actor" % akkaVersion,
    "com.typesafe.akka" %% "akka-cluster" % akkaVersion,
    "com.typesafe.akka" %% "akka-http" % akkaHttpVersion,
    "com.typesafe.akka" %% "akka-http-spray-json" % akkaHttpVersion,
    "com.typesafe.akka" %% "akka-testkit" % akkaVersion % Test
  )
}

// Do not run tests as part of assembly
test in assembly := {}
assemblyOutputPath in assembly := file("target/barrio/barrio.jar")
mainClass in assembly := Some("com.codiply.barrio.Main")

addCommandAlias("ss", ";scalastyle;test:scalastyle")

// A stage step is needed when deploying to demo app in Heroku
addCommandAlias("stage", "assembly")

Add stage step expected by Heroku

Add stage step expected by Heroku


import com.typesafe.sbt.SbtGit._
import sbt._

object Versioning {

  val snapshotSuffix = "-SNAPSHOT"
  val releasedVersion = """^r?([0-9\.]+)$""".r
  val releasedCandidateVersion = """^r?([0-9\.]+-rc\d+)$""".r
  val snapshotVersion = """^r?[0-9\.]+(.*)$""".r

  def settings(baseVersion: String): Seq[Def.Setting[_]] = Seq(
    git.baseVersion := baseVersion,
    git.uncommittedSignifier := None,
    git.useGitDescribe := true,
    git.gitTagToVersionNumber := {
      case releasedVersion(v) => Some(v)
      case releasedCandidateVersion(rc) => Some(rc)
      case snapshotVersion(v) => Some(s"$baseVersion$v$snapshotSuffix")
      case _ => None
    }
  )

}

import com.typesafe.sbt.SbtGit._
import sbt._

object Versioning {

  val snapshotSuffix = "-SNAPSHOT"
  val releasedVersion = """^r?([0-9\.]+)$""".r
  val releasedCandidateVersion = """^r?([0-9\.]+-rc\d+)$""".r
  val betaVersion = """^r?([0-9\.]+-beta\d+)$""".r
  val snapshotVersion = """^r?[0-9\.]+(.*)$""".r

  def settings(baseVersion: String): Seq[Def.Setting[_]] = Seq(
    git.baseVersion := baseVersion,
    git.uncommittedSignifier := None,
    git.useGitDescribe := true,
    git.gitTagToVersionNumber := {
      case releasedVersion(v) => Some(v)
      case releasedCandidateVersion(rc) => Some(rc)
      case betaVersion(beta) => Some(beta)
      case snapshotVersion(v) => Some(s"$baseVersion$v$snapshotSuffix")
      case _ => None
    }
  )

}

Build: Allow beta releases as well as release candidates.


package views.html
package account

import lila.api.Context
import lila.app.templating.Environment._
import lila.app.ui.ScalatagsTemplate._
import lila.pref.PrefCateg
import lila.user.User
import controllers.routes

object bits {

  def data(u: User)(implicit ctx: Context) =
    account.layout(title = s"${u.username} - personal data", active = "security") {
      div(cls := "account security personal-data box box-pad")(
        h1("My personal data"),
        div(cls := "personal-data__header")(
          p("Here is all personal information Lichess has about ", userLink(u)),
          a(cls := "button", href := s"${routes.Account.data}?user=${u.id}&text=1", downloadAttr)(
            trans.downloadRaw()
          )
        )
      )
    }

  def categName(categ: lila.pref.PrefCateg)(implicit ctx: Context): String =
    categ match {
      case PrefCateg.GameDisplay  => trans.preferences.gameDisplay.txt()
      case PrefCateg.ChessClock   => trans.preferences.chessClock.txt()
      case PrefCateg.GameBehavior => trans.preferences.gameBehavior.txt()
      case PrefCateg.Site         => "Site settings"
    }
}

package views.html
package account

import lila.api.Context
import lila.app.templating.Environment._
import lila.app.ui.ScalatagsTemplate._
import lila.pref.PrefCateg
import lila.user.User
import controllers.routes

object bits {

  def data(u: User)(implicit ctx: Context) =
    account.layout(title = s"${u.username} - personal data", active = "security") {
      div(cls := "account security personal-data box box-pad")(
        h1("My personal data"),
        div(cls := "personal-data__header")(
          p("Here is all personal information Lichess has about ", userLink(u)),
          a(cls := "button", href := s"${routes.Account.data}?user=${u.id}&text=1", downloadAttr)(
            trans.download()
          )
        )
      )
    }

  def categName(categ: lila.pref.PrefCateg)(implicit ctx: Context): String =
    categ match {
      case PrefCateg.GameDisplay  => trans.preferences.gameDisplay.txt()
      case PrefCateg.ChessClock   => trans.preferences.chessClock.txt()
      case PrefCateg.GameBehavior => trans.preferences.gameBehavior.txt()
      case PrefCateg.Site         => "Site settings"
    }
}

i18n: Fix /account/personal-data download button translation


package sigmastate.crypto

import java.math.BigInteger

import sigmastate.helpers.SigmaTestingCommons
import sigmastate.interpreter.CryptoConstants

class GroupLawsSpec extends SigmaTestingCommons {
  private val group = CryptoConstants.dlogGroup

  property("multiplication law is complete") {
    val identity = group.identity
    val ge = group.createRandomGenerator()

    group.multiplyGroupElements(ge, ge) shouldBe group.exponentiate(ge, new BigInteger("2"))
    group.multiplyGroupElements(ge, identity) shouldBe group.exponentiate(ge, BigInteger.ONE)
    group.multiplyGroupElements(ge, identity) shouldBe ge
    group.multiplyGroupElements(identity, identity) shouldBe identity

    val inverse = group.getInverse(ge)
    group.multiplyGroupElements(ge, inverse) shouldBe identity
  }

  property("exponentiation") {
    val identity = group.identity
    val ge = group.createRandomGenerator()

    group.exponentiate(ge, BigInteger.ZERO) shouldBe identity
    group.exponentiate(ge, BigInteger.ONE) shouldBe ge
    group.exponentiate(ge, group.order) shouldBe identity
    group.exponentiate(ge, group.order.add(BigInteger.ONE)) shouldBe ge
  }

}

package sigmastate.crypto

import java.math.BigInteger

import sigmastate.helpers.SigmaTestingCommons
import sigmastate.interpreter.CryptoConstants

class GroupLawsSpecification extends SigmaTestingCommons {
  private val group = CryptoConstants.dlogGroup

  property("multiplication law is complete") {
    val identity = group.identity
    val ge = group.createRandomGenerator()

    group.multiplyGroupElements(ge, ge) shouldBe group.exponentiate(ge, new BigInteger("2"))
    group.multiplyGroupElements(ge, identity) shouldBe group.exponentiate(ge, BigInteger.ONE)
    group.multiplyGroupElements(ge, identity) shouldBe ge
    group.multiplyGroupElements(identity, identity) shouldBe identity

    val inverse = group.getInverse(ge)
    group.multiplyGroupElements(ge, inverse) shouldBe identity
  }

  property("exponentiation") {
    val identity = group.identity
    val ge = group.createRandomGenerator()

    group.exponentiate(ge, BigInteger.ZERO) shouldBe identity
    group.exponentiate(ge, BigInteger.ONE) shouldBe ge
    group.exponentiate(ge, group.order) shouldBe identity
    group.exponentiate(ge, group.order.add(BigInteger.ONE)) shouldBe ge
  }

}

Rename GroupLawsSpec to correspond file name


package ml.combust.mleap

import com.typesafe.sbt.packager.docker.DockerPlugin.autoImport
import sbt.Keys._
import sbtrelease.ReleasePlugin.autoImport.{ReleaseStep, _}
import sbtrelease.ReleaseStateTransformations._
import xerial.sbt.Sonatype.SonatypeCommand

object Release {
  lazy val settings = Seq(releaseVersionBump := sbtrelease.Version.Bump.Minor,
    releaseCrossBuild := true,

    releaseProcess := Seq[ReleaseStep](
      checkSnapshotDependencies,
      inquireVersions,
      setReleaseVersion,
      runClean,
      runTest,
      tagRelease,
      publishArtifacts,
      commitReleaseVersion,
      releaseStepCommand(SonatypeCommand.sonatypeRelease),
      releaseStepTask(publish in autoImport.Docker in MleapProject.serving),
      setNextVersion,
      commitNextVersion,
      pushChanges
    ))
}

package ml.combust.mleap

import com.typesafe.sbt.packager.docker.DockerPlugin.autoImport
import sbt.Keys._
import sbtrelease.ReleasePlugin.autoImport.{ReleaseStep, _}
import sbtrelease.ReleaseStateTransformations._
import xerial.sbt.Sonatype.SonatypeCommand

object Release {
  lazy val settings = Seq(releaseVersionBump := sbtrelease.Version.Bump.Minor,
    releaseCrossBuild := true,

    releaseProcess := Seq[ReleaseStep](
      checkSnapshotDependencies,
      inquireVersions,
      setReleaseVersion,
      runClean,
      runTest,
      tagRelease,
      commitReleaseVersion,
      publishArtifacts,
      releaseStepCommand(SonatypeCommand.sonatypeRelease),
      releaseStepTask(publish in autoImport.Docker in MleapProject.serving),
      setNextVersion,
      commitNextVersion,
      pushChanges
    ))
}

Update release process once more.

Update release process once more.


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

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

// Use the Play sbt plugin for Play projects
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.3.0")

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

addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.5.2")

Remove sbt-idea plugin (should be global, not in the project)


// logLevel := Level.Warn

resolvers ++= Seq("typesafe" at "http://repo.typesafe.com/typesafe/releases/",
  Resolver.file("file", new File(Path.userHome.absolutePath + "/.ivy2/local/")),
  "Scalaz Bintray Repo" at "http://dl.bintray.com/scalaz/releases"
)
resolvers += "Sonatype snapshots" at "https://oss.sonatype.org/content/repositories/snapshots/"
resolvers += "Sonatype OSS Release Repository" at "https://oss.sonatype.org/content/repositories/releases/"
resolvers += Resolver.url(
  "bintray-sbt-plugin-releases",
  url("http://dl.bintray.com/content/sbt/sbt-plugin-releases"))(
  Resolver.ivyStylePatterns)
resolvers += Classpaths.sbtPluginReleases

// Use the Play sbt plugin for Play projects
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.16")

addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.6")

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

addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.2.2")

// logLevel := Level.Warn

resolvers ++= Seq("typesafe" at "http://repo.typesafe.com/typesafe/releases/",
  Resolver.file("file", new File(Path.userHome.absolutePath + "/.ivy2/local/")),
  "Scalaz Bintray Repo" at "http://dl.bintray.com/scalaz/releases"
)
resolvers += "Sonatype snapshots" at "https://oss.sonatype.org/content/repositories/snapshots/"
resolvers += "Sonatype OSS Release Repository" at "https://oss.sonatype.org/content/repositories/releases/"
resolvers += Resolver.url(
  "bintray-sbt-plugin-releases",
  url("http://dl.bintray.com/content/sbt/sbt-plugin-releases"))(
  Resolver.ivyStylePatterns)
resolvers += Classpaths.sbtPluginReleases

// Use the Play sbt plugin for Play projects
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.15")

addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.6")

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

addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.2.2")

Revert "update to play 2.6.16"

Revert "update to play 2.6.16"

This reverts commit 7180504


addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "0.6.0")

resolvers += "sonatype-releases" at "https://oss.sonatype.org/content/repositories/releases/"

resolvers += "Spark Package Main Repo" at "https://dl.bintray.com/spark-packages/maven"

addSbtPlugin("org.spark-packages" % "sbt-spark-package" % "0.2.2")

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

addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.0")

Add sbt-coverage and sbt-pgp, some progress towards coverage but some weird macro issues (so for now just clean/test)


addSbtPlugin("org.scala-lang.modules" % "sbt-scala-module" % "1.0.12")

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

addSbtPlugin("org.scala-lang.modules" % "sbt-scala-module" % "1.0.12")

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

Update scala-js plugin to 0.6.20

Update scala-js plugin to 0.6.20


addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.5.0")
addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.1.0")
addSbtPlugin("com.codacy" % "sbt-codacy-coverage" % "1.3.8")
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "1.2.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.0")
addSbtPlugin("com.orrsella" % "sbt-stats" % "1.0.5")

Add plugin for source code stats

Add plugin for source code stats


package com.ponkotuy.run

import java.io.{BufferedReader, InputStreamReader}

import pl.project13.scala.rainbow._
import skinny.http.HTTP

import scala.util.{Failure, Success, Try}

/**
 *
 * @author ponkotuy
 * Date: 15/03/03.
 */
object Tester extends App {
  val Host = args.headOption.getOrElse("http://localhost:9000")
  val urlFile = getClass.getResource("/urls")
  val br = new BufferedReader(new InputStreamReader(urlFile.openStream()))
  Iterator.continually(br.readLine()).takeWhile(_ != null).foreach { line =>
    val url = Host + line
    Try {
      HTTP.get(url).status
    } match {
      case Success(200) => println(s"Success: $url".green)
      case Success(302) => println(s"Redirect: $url".green)
      case Success(status) => println(s"Bad status $status: $url".red)
      case Failure(e) => println(s"Error ${e.getMessage}: $url".red)
    }
  }
}

package com.ponkotuy.run

import java.io.{BufferedReader, InputStreamReader}

import pl.project13.scala.rainbow._
import skinny.http.HTTP

import scala.util.{Failure, Success, Try}

/**
 *
 * @author ponkotuy
 * Date: 15/03/03.
 */
object Tester extends App {
  val Host = args.headOption.getOrElse("http://localhost:9000")
  val urlFile = getClass.getResource("/urls")
  val br = new BufferedReader(new InputStreamReader(urlFile.openStream()))
  Iterator.continually(br.readLine()).takeWhile(_ != null).foreach { line =>
    val url = Host + line
    Try {
      HTTP.get(url).status
    } match {
      case Success(200) => println(s"Success: $url".green)
      case Success(status) if 300 <= status && status < 400 => println(s"Redirect ${status}: $url".green)
      case Success(status) => println(s"Bad status $status: $url".red)
      case Failure(e) => println(s"Error ${e.getMessage}: $url".red)
    }
  }
}

Fix redirect status to tester

Fix redirect status to tester


package org.hashids

import org.hashids.syntax._
import org.scalacheck._
import org.specs2._

case class ZeroOrPosLong(value: Long)

class CheckHashids extends org.specs2.Specification with org.specs2.ScalaCheck {
  import CheckHashids.arbitraryZeroOrPosLong

  def is = {
    "List of random zero or positive longs should encode then decode" ! {
      check { (a: List[ZeroOrPosLong], salt: String) =>
        implicit val hashid = Hashids(salt)

        a.raw.toHashid.fromHashid must_== a.raw
      }
    } ^ {
      end
    }
  }

  implicit class RichListZeroOrPosLong(self: List[ZeroOrPosLong]) {
    def raw = self.map(_.value)
  }
}

object CheckHashids {
  implicit val arbitraryZeroOrPosLong: Arbitrary[ZeroOrPosLong] = Arbitrary {
    Gen.chooseNum(0L, Long.MaxValue, 2L, 75527867232L).map(ZeroOrPosLong(_))
  }
}

package org.hashids

import org.hashids.syntax._
import org.scalacheck._
import org.specs2._

case class ZeroOrPosLong(value: Long)

class CheckHashids extends org.specs2.Specification with org.specs2.ScalaCheck {
  import CheckHashids._

  def is = {
    "List of random zero or positive longs should encode then decode" ! {
      check { (a: List[ZeroOrPosLong], salt: String) =>
        implicit val hashid = Hashids(salt)

        a.raw.toHashid.fromHashid must_== a.raw
      }
    } ^ {
      end
    }
  }
}

object CheckHashids {
  implicit val arbitraryZeroOrPosLong: Arbitrary[ZeroOrPosLong] = Arbitrary {
    Gen.chooseNum(0L, Long.MaxValue, 2L, 75527867232L).map(ZeroOrPosLong(_))
  }

  implicit class RichListZeroOrPosLong(self: List[ZeroOrPosLong]) {
    def raw = self.map(_.value)
  }
}

Move non-specification code into companion object.


package com.github.sstone.amqp.proxy

import serializers._
import akka.serialization.Serializer

object Serializers {

  private val map = Map(
    "json" -> JsonSerializer,
    "protobuf" -> ProtobufSerializer,
    "thrift" -> ThriftSerializer,
    "snappy-json" -> SnappyJsonSerializer,
    "snappy-protobuf" -> SnappyProtobufSerializer,
    "snappy-thrift" -> SnappyThriftSerializer)

  def nameToSerializer(name: String) = map.get(name).get

  def serializerToName(serializer: Serializer) = map.map(_.swap).get(serializer).get
}

package com.github.sstone.amqp.proxy

import serializers._
import akka.serialization.Serializer

object Serializers {

  private val map = Map(
    "json" -> JsonSerializer,
    "protobuf" -> ProtobufSerializer,
    "thrift" -> ThriftSerializer,
    "snappy-json" -> SnappyJsonSerializer,
    "snappy-protobuf" -> SnappyProtobufSerializer,
    "snappy-thrift" -> SnappyThriftSerializer)

  def nameToSerializer(name: String) = map.getOrElse(name, JsonSerializer).get

  def serializerToName(serializer: Serializer) = map.map(_.swap).get(serializer).get
}

Enforce default when improper serializer is given


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
}

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|update)(?:\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
}

Add 'update' as a prefix for mutator like method names


package kantan.csv

import kantan.codecs.Codec

/** Combines [[CellDecoder]] and [[CellEncoder]].
  *
  * Instance for types that already have a [[CellDecoder]] and [[CellEncoder]] are derived automatically.
  */
trait CellCodec[A] extends Codec[String, A, CsvError, CellDecoder, CellEncoder] with CellDecoder[A] with CellEncoder[A]

/** Declares helpful methods for [[CellCodec]] creation. */
@export.exports(Subclass)
object CellCodec {
  def combine[A](decoder: CellDecoder[A], encoder: CellEncoder[A]): CellCodec[A] = CellCodec(decoder.decode _, encoder.encode _)

  /** Creates a new [[CellCodec]] from the specified decoding and encoding functions. */
  def apply[A](decoder: String ⇒ CsvResult[A], encoder: A ⇒ String): CellCodec[A] = new CellCodec[A] {
    override def decode(a: String) = decoder(a)
    override def encode(a: A) = encoder(a)
  }
}

package kantan.csv

import kantan.codecs.Codec

/** Combines [[CellDecoder]] and [[CellEncoder]].
  *
  * Instance for types that already have a [[CellDecoder]] and [[CellEncoder]] are derived automatically.
  */
trait CellCodec[A] extends Codec[String, A, CsvError, CellDecoder, CellEncoder] with CellDecoder[A] with CellEncoder[A]

/** Declares helpful methods for [[CellCodec]] creation. */
@export.exports(Subclass)
object CellCodec {
  /** Creates a new [[CellCodec]] from the specified decoding and encoding functions. */
  def apply[A](decoder: String ⇒ CsvResult[A], encoder: A ⇒ String): CellCodec[A] = new CellCodec[A] {
    override def decode(a: String) = decoder(a)
    override def encode(a: A) = encoder(a)
  }
}

Remove combine, which serves no practical purpose and can be confusing.