package com.github.mauricio.async.db.postgresql

import org.specs2.mutable.Specification

class NumericSpec extends Specification with DatabaseTestHelper {

  "when processing numeric columns" should {

    "support first update of num column with floating" in {

      withHandler {
        handler =>
          executeDdl(handler, "CREATE TEMP TABLE numeric_test (id BIGSERIAL, numcol NUMERIC)")

          val id = executePreparedStatement(handler, "INSERT INTO numeric_test DEFAULT VALUES RETURNING id").rows.get(0)("id")
          executePreparedStatement(handler, "UPDATE numeric_test SET numcol = ? WHERE id = ?", Array[Any](123.123, id))
          executePreparedStatement(handler, "UPDATE numeric_test SET numcol = ? WHERE id = ?", Array[Any](1234, id))
          executePreparedStatement(handler, "UPDATE numeric_test SET numcol = ? WHERE id = ?", Array[Any](123.123, id))

          id === 1
      }

    }

    "support first update of num column with integer (fails currently)" in {

      withHandler {
        handler =>
          executeDdl(handler, "CREATE TEMP TABLE numeric_test (id BIGSERIAL, numcol NUMERIC)")

          val id = executePreparedStatement(handler, "INSERT INTO numeric_test DEFAULT VALUES RETURNING id").rows.get(0)("id")
          executePreparedStatement(handler, "UPDATE numeric_test SET numcol = ? WHERE id = ?", Array[Any](1234, id))
          executePreparedStatement(handler, "UPDATE numeric_test SET numcol = ? WHERE id = ?", Array[Any](123.123, id))

          id === 1
      }

    }

    "support using first update with queries instead of prepared statements" in {

      withHandler {
        handler =>
          executeDdl(handler, "CREATE TEMP TABLE numeric_test (id BIGSERIAL, numcol NUMERIC)")

          val id = executeQuery(handler, "INSERT INTO numeric_test DEFAULT VALUES RETURNING id").rows.get(0)("id")
          executeQuery(handler, s"UPDATE numeric_test SET numcol = 1234 WHERE id = $id")
          executeQuery(handler, s"UPDATE numeric_test SET numcol = 123.123 WHERE id = $id")

          id === 1
      }

    }

  }

}

Add test to show issue with numeric columns

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


package com.twitter.scalding

object ArgOptions extends Enumeration {
  type ArgOptions = Value
  val RequiredArg, OptionalArg, ListArg, BooleanArg = Value
}

class DescriptionArgs(override val m: Map[String, List[String]]) extends Args(m){
  import ArgOptions._

  private val map = new scala.collection.mutable.HashMap[String, (String, ArgOptions)]()

  def isHelpState = boolean("help")

  def optionalDescription(key: String, description: String): Unit =
    map += key -> (description, OptionalArg)

  def requiredDescription(key: String, description: String): Unit =
    map += key -> (description, RequiredArg)

  def booleanDescription(key: String, description: String): Unit =
    map += key -> (description, BooleanArg)

  def listDescription(key: String, description: String): Unit =
    map += key -> (description, ListArg)

  def argString: String = {
    map.foldLeft("") { case (str, (key, (description, opt))) =>
      val msg = opt match {
        case RequiredArg => s"--$key VALUE "
        case OptionalArg => s"[--$key VALUE] "
        case ListArg => s"[--$key VALUE VALUE2] "
        case BooleanArg => s"[--$key] "
      }
      str + msg
    } + "[--help]"
  }

  def help: String = {
    map.foldLeft("") { case (str, (key, (description, opt))) =>
      str + s"--$key($opt) :: $description \n"
    } + "--help :: Show this help message."
  }
}

/**
  * Extending this Trait allows for descriptions to be added to Jobs
  * If you run a job with --help the descriptions are output
  */
trait DescribedExecutionApp { this: ExecutionApp =>

  def descriptions(args: DescriptionArgs): Unit

  def describedJob(args: Args): Execution[Unit]

  def job = {
    Execution.getArgs.flatMap{args =>
      val descriptionArgs = new DescriptionArgs(args.m)
      descriptions(descriptionArgs)
      if(descriptionArgs.isHelpState){
        val top = "\n###########################################################################\n\n"
        val usage = s"Command Line Args :: ${descriptionArgs.argString}\n\n\n"
        val help = descriptionArgs.help
        val bottom = "\n\n###########################################################################\n"
        println(top + usage + help + bottom)
        Execution.unit
      } else {
        describedJob(descriptionArgs)
      }
    }
  }
}

Add a ExecutionApp Trait that allows for an user to describe the Job args and output the args with a help command


package mesosphere.marathon.core.launchqueue.impl

import akka.Done
import akka.actor.{ Actor, Props }
import akka.pattern.ask
import akka.testkit.{ ImplicitSender, TestActorRef }
import akka.util.Timeout
import mesosphere.AkkaFunTest
import mesosphere.marathon.core.instance.TestInstanceBuilder
import mesosphere.marathon.core.instance.update.{ InstanceChange, InstanceUpdated }
import mesosphere.marathon.core.launchqueue.LaunchQueue.QueuedInstanceInfo
import mesosphere.marathon.core.launchqueue.LaunchQueueConfig
import mesosphere.marathon.state.{ AppDefinition, PathId, RunSpec, Timestamp }
import org.rogach.scallop.ScallopConf

import scala.concurrent.duration._

class LaunchQueueActorTest extends AkkaFunTest with ImplicitSender {

  implicit val timeout = Timeout(1.seconds)

  test("InstanceChange message is answered with Done, if there is no launcher actor") {
    Given("A LaunchQueueActor without any task launcher")
    val f = new Fixture
    import f._

    When("An InstanceChange is send to the task launcher actor")
    launchQueue ! instanceUpdate

    Then("A Done is send directly from the LaunchQueue")
    expectMsg(Done)
  }

  test("InstanceChange message is answered with Done, if there is a launcher actor") {
    Given("A LaunchQueueActor with a task launcher for app /foo")
    val f = new Fixture
    import f._
    launchQueue.ask(LaunchQueueDelegate.Add(app, 3)).futureValue
    launchQueue.underlyingActor.launchers should have size 1

    When("An InstanceChange is send to the task launcher actor")
    launchQueue ! instanceUpdate

    Then("A Done is send as well, but this time the answer comes from the LauncherActor")
    expectMsg(Done)
    val launcher = launchQueue.underlyingActor.launchers(app.id)
    launcher ! "GetChanges"
    expectMsg(List(instanceUpdate))
  }

  class Fixture {
    val config = new ScallopConf(Seq.empty) with LaunchQueueConfig {
      verify()
    }
    def runSpecActorProps(runSpec: RunSpec, count: Int) = Props(new TestLauncherActor)
    val app = AppDefinition(PathId("/foo"))
    val instance = TestInstanceBuilder.newBuilder(app.id).addTaskRunning().getInstance()
    val instanceUpdate = InstanceUpdated(instance, None, Seq.empty)
    val instanceInfo = QueuedInstanceInfo(app, true, 1, 1, Timestamp.now(), Timestamp.now())
    val launchQueue = TestActorRef[LaunchQueueActor](LaunchQueueActor.props(config, Actor.noSender, runSpecActorProps))

    // Mock the behaviour of the TaskLauncherActor
    class TestLauncherActor extends Actor {
      var changes = List.empty[InstanceChange]
      override def receive: Receive = {
        case TaskLauncherActor.GetCount => sender() ! instanceInfo
        case change: InstanceChange =>
          changes = change :: changes
          sender() ! Done
        case "GetChanges" => sender() ! changes // not part of the LauncherActor protocol. Only used to verify changes.
      }
    }
  }
}

Add TestCase for handling InstanceUpdate events in the LaunchQueue

Test Plan: sbt test

Reviewers: unterstein, meichstedt

Reviewed By: unterstein, meichstedt

Subscribers: jenkins, marathon-team

Differential Revision: https://phabricator.mesosphere.com/D332


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

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

Add solution to problem 31.

Add solution to problem 31.


package org.jetbrains.plugins.scala.lang.typeInference

class HKTypeParamLubTest extends TypeInferenceTestBase {
  def testSCL17527(): Unit = doTest(
    s"""
       |def foo[F[_]](): Int = {
       |  val fu: F[Unit] = ???
       |  val fs: F[String] = ???
       |  val res = ${START}if (true) fu else fs$END
       |  1
       |}
       |//F[_ >: Unit with String]
       |""".stripMargin
  )
}

Add test for ht-type param lub calculation

#SCL-17527 fixed


package io.github.interestinglab.waterdrop.apis

import org.apache.spark.api.java.JavaRDD
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{Dataset, Row, SparkSession}
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.streaming.api.java.{JavaDStream, JavaStreamingContext}
import org.apache.spark.streaming.dstream.DStream

/**
 * Superclass of all streaming input, extends this abstract class to implement a streaming input.
 * */
abstract class BaseJavaStreamingInput[T] extends BaseStreamingInput[T] {

  def rdd2dataset(spark: SparkSession, rdd: RDD[T]): Dataset[Row] = {
    javaRdd2dataset(spark, rdd.toJavaRDD())
  }

  def getDStream(ssc: StreamingContext): DStream[T] = {
    getJavaDstream(new JavaStreamingContext(ssc)).dstream
  }

  /**
   * Create spark javaDStream from data source, you can specify type parameter.
   * */
  def getJavaDstream(jssc: JavaStreamingContext): JavaDStream[T]

  /**
   * This must be implemented to convert JavaRDD[T] to Dataset[Row] for later processing
   * */
  def javaRdd2dataset(sparkSession: SparkSession, javaRDD: JavaRDD[T]): Dataset[Row]
}

Add java streaming input api

Add java streaming input api


trait Num[T] {
  def plus(x: T, y: T): T
}

object Num {
  class IntNum extends Num[Int] {
    inline def plus(inline x: Int, inline y: Int): Int = x + y
  }
  given IntNum

  extension Extension on [T](inline x: T)(using inline num: Num[T]) {
    inline def +(inline y: T): T = num.plus(x, y)
  }
}

import Num.Extension._

inline def twiceInlined[T: Num](x : T): T = x + x
def twice[T: Num](x : T): T = x + x

@main def Test =
  val x: Int = 3
  assert(6 == twiceInlined(x)) // code will be x + x using the primitive Int.+
  assert(6 == twice(x)) // will call IntNum.plus through virtual dispatch

Add inline override regression test

Add inline override regression test


package doodle
package image
package examples

// Example that demonstrates writing to a file
import doodle.core._
import doodle.syntax._
import doodle.image.syntax._
import doodle.effect.Writer._
import doodle.java2d._
import doodle.java2d.effect.Frame

object Write {
  val frame = Frame.fitToPicture().background(Color.black)

  def rainbowCircles(count: Int, color: Color): Image =
    count match {
      case 0 => Image.empty
      case n =>
        val here =
          Image
            .circle((n * 10).toDouble)
            .strokeWidth(3.0)
            .strokeColor(color)
        here.on(rainbowCircles(n - 1, color.spin(33.degrees)))
    }

  // Draw with `Background.image.draw(Background.frame)`
  val image = rainbowCircles(12, Color.red)
  image.write[Png]("rainbow-circles.png", frame)
}

Add example demonstrating how to write to a file


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

package net.liftweb
package actor

import org.specs2.mutable.Specification

class MockLiftActorSpec extends Specification {
  "Mock Actor Specification".title

  sealed trait MockSpecActorMessage
  case object MockSpecActorMessage1 extends MockSpecActorMessage
  case object MockSpecActorMessage2 extends MockSpecActorMessage
  case object MockSpecActorMessage3 extends MockSpecActorMessage

  "A MockSpecializedLiftActor" should {
    "correctly indicate when it has received a message" in {
      val mockActor = new MockSpecializedLiftActor[MockSpecActorMessage]

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2

      mockActor.hasReceivedMessage_?(MockSpecActorMessage1) must beTrue
    }

    "correctly indicate when it has not received a message" in {
      val mockActor = new MockSpecializedLiftActor[MockSpecActorMessage]

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2

      mockActor.hasReceivedMessage_?(MockSpecActorMessage3) must beFalse
    }

    "correctly indicate the number of messages it has received" in {
      val mockActor = new MockSpecializedLiftActor[MockSpecActorMessage]

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2
      mockActor ! MockSpecActorMessage3

      mockActor.messageCount must_== 3
    }
  }

  "A MockLiftActor" should {
    "correctly indicate when it has received a message" in {
      val mockActor = new MockLiftActor

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2

      mockActor.hasReceivedMessage_?(MockSpecActorMessage1) must beTrue
    }

    "correctly indicate when it has not received a message" in {
      val mockActor = new MockLiftActor

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2

      mockActor.hasReceivedMessage_?(MockSpecActorMessage3) must beFalse
    }

    "correctly indicate the number of messages it has received" in {
      val mockActor = new MockLiftActor

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2
      mockActor ! MockSpecActorMessage3

      mockActor.messageCount must_== 3
    }
  }
}

Add specs for mock actors.

Add specs for mock actors.


package opencl.generator

import ir.ArrayType
import ir.ast.{Get, Iterate, Join, Split, Zip, fun}
import opencl.executor.{Execute, TestWithExecutor, Utils}
import opencl.ir.pattern.{MapGlb, MapSeq}
import opencl.ir.{Int, IntToValue, add}
import org.junit.Assert.assertArrayEquals
import org.junit.{Assume, Test}

object TestIterate extends TestWithExecutor

class TestIterate {
  @Test
  def IterateAfterGet(): Unit = {
    Assume.assumeFalse("Disabled on AMD GPUs.", Utils.isAmdGpu)

    def increment = fun(Int, x => add(Int).apply(1, x))
    def f = fun(
      ArrayType(Int, 128),
      ArrayType(Int, 128),
      (v, w) =>
        Join() o MapGlb(
          Iterate(5)(MapSeq(increment)) o Get(0)
        ) $ Zip(Split(32) $ v, Split(32) $ w)
    )

    val V = Array.fill(128)(util.Random.nextInt(1024))
    val W = Array.fill(128)(util.Random.nextInt(1024))
    val (output, _) = Execute(4, 4)[Array[Int]](f, V, W)
    assertArrayEquals(V.map(_ + 5), output)
  }
}

Add failing test : Iterate after a Get(_)


package ch.usi.inf.l3.sana.oberon0.namers

import ch.usi.inf.l3.sana
import sana.tiny
import sana.calcj
import sana.primj
import sana.brokenj
import sana.ooj
import sana.oberon0

import tiny.dsl._
import oberon0.ast._
import tiny.ast.{DefTree, UseTree}
import tiny.names.Name
import tiny.source.Position
import tiny.symbols.{Symbol, TypeSymbol}
import ooj.symbols.ClassSymbol
import ooj.ast.{ClassDefApi, TemplateApi}
import tiny.errors.ErrorReporting.{error, warning}
import oberon0.errors.ErrorCodes._
import primj.ast.BlockApi
import oberon0.ast.Implicits._
import oberon0.symbols._
import primj.namers.NamerComponent
import oberon0.symbols.SymbolUtils

@component
trait ModuleDefNamerComponent extends NamerComponent {
  (module: ModuleDefApi) => {
    val declarations = module.declarations.map(name(_).asInstanceOf[DefTree])
    val block        = module.block.map(name(_).asInstanceOf[BlockApi])
    TreeCopiers.copyModuleDef(module)(declarations = declarations, block = block)
  }
}

@component
trait TypeDefNamerComponent extends NamerComponent {
  (tdef: TypeDefApi) => {
    val tpt = name(tdef.tpt).asInstanceOf[UseTree]
    tdef.symbol.foreach {
      case sym: TypeDefSymbol => sym.typeSymbol = tpt.symbol
      case _                  => ()
    }
    TreeCopiers.copyTypeDef(tdef)(tpt = tpt)
  }
}

@component
trait ClassDefNamerComponent extends ooj.namers.ClassDefNamerComponent {

  override protected def addObjectParentIfNeeded(
    clazz: ClassDefApi): List[UseTree] = Nil

  override protected def packageName(symbol: Option[Symbol]): String = {
    val mdl = SymbolUtils.enclosingModule(symbol)
    mdl.map(_.name.asString).getOrElse("")
  }
}

Add namer components for oberon0

Add namer components for oberon0


package ceedubs.config

import org.specs2.mutable.Specification
import com.typesafe.config.{Config, ConfigFactory}
import KindsafeConfig._
import ceedubs.config.readers.ValueReader

case class ServiceConfig(urls: Set[String], maxConnections: Int, httpsRequired: Boolean)

class Examples extends Specification {
  // an example config snippet for us to work with
  val config = ConfigFactory.parseString(
    """
      |services {
      |  users {
      |    urls = ["localhost:8001"]
      |    maxConnections = 100
      |    httpsRequired = true
      |  }
      |  analytics {
      |    urls = ["localhost:8002", "localhost:8003"]
      |    maxConnections = 25
      |  }
      |}
    """.stripMargin)

  "Kindsafe config" should {
    "make Typesafe config more Scala-friendly" in {
      val userServiceConfig = config.getAs[Config]("services.users")
      userServiceConfig.getAs[Set[String]]("urls") must beEqualTo(Set("localhost:8001"))
      userServiceConfig.getAs[Int]("maxConnections") must beEqualTo(100)
      userServiceConfig.getAs[Option[Boolean]]("httpsRequired") must beSome(true)

      val analyticsServiceConfig = config.getAs[Config]("services.analytics")
      analyticsServiceConfig.getAs[List[String]]("urls") must beEqualTo(List("localhost:8002", "localhost:8003"))
      val analyticsServiceRequiresHttps = analyticsServiceConfig.getAs[Option[Boolean]]("httpsRequired") getOrElse false
      analyticsServiceRequiresHttps must beFalse
    }

    "Be easily extensible" in {
      // need to define an implicit ValueReader[ServiceConfig] to be able to extract a ServiceConfig
      // if we try to call getAs[ServiceConfig] without one, the compiler will give you an error
      implicit val serviceConfigReader: ValueReader[ServiceConfig] = new ValueReader[ServiceConfig] {
        def get(config: Config, path: String): ServiceConfig = {
          val serviceConfig = config.getAs[Config](path)
          ServiceConfig(
            urls = serviceConfig.getAs[Set[String]]("urls"),
            maxConnections = serviceConfig.getInt("maxConnections"), // the old-fashioned way is fine too!
            httpsRequired = serviceConfig.getAs[Option[Boolean]]("httpsRequired") getOrElse false
          )
        }
      }

      // so we don't have to add a "services." prefix for each service
      val servicesConfig = config.getAs[Config]("services")

      val userServiceConfig: ServiceConfig = servicesConfig.getAs[ServiceConfig]("users")
      userServiceConfig.maxConnections must beEqualTo(100)

      val analyticsServiceConfig: ServiceConfig = servicesConfig.getAs[ServiceConfig]("analytics")
      // the analytics service config doesn't define an "httpsRequired" value, but the serviceConfigReader defaults
      // to false if it is empty with its 'getOrElse false' on the extracted Option
      analyticsServiceConfig.httpsRequired must beFalse

    }
  }
}

Add spec with example usage

Add spec with example usage


object LiteralMaps {
  def test(): Map[Int, Int] = {
    Map(1 -> 2, 3 -> 4, (5, 6))
  }

  def test2(): (Int, Int) = {
    1 -> 2
  }

  def test3(): Map[Int, Int] = {
    Map()
  }

  def test4(): Map[Int, Int] = {
    Map.empty[Int, Int]
  }

  def test5(): Map[Int, Int] = {
    Map.empty[Int, Int]
  }
}

Implement Literal Maps along with Tuple2 shorthands

This is now supported in Leon:

  Map(elem1, elem2, ...) where elem* are Tuple2 literals.

In particular we can have:

  Map(1 -> 2, 3 -> 4, (5, 6))


package hmda.publication.reports.protocol

import hmda.model.publication.reports.MSAReport
import org.scalatest.{ MustMatchers, PropSpec }
import org.scalatest.prop.PropertyChecks
import hmda.publication.reports.ReportGenerators._
import spray.json._

class MSAReportProtocolSpec extends PropSpec with PropertyChecks with MustMatchers with MSAReportProtocol {

  property("MSA Report must convert to and from JSON") {
    forAll(msaReportGen) { m =>
      m.toJson.convertTo[MSAReport] mustBe m
    }
  }
}

Add msa report protocol test

Add msa report protocol test


package com.nekopiano.scala.processing.sandbox.sample.peasycam

import com.nekopiano.scala.processing.{ScalaPAppCompanion, ThreeDimensionalPApp}
import peasy.PeasyCam

/**
  * Created by neko on 29/07/2016.
  */
class HelloPeasy extends ThreeDimensionalPApp {

  override def settings(): Unit = {
    size(200,200,P3D)

  }

  var cam:PeasyCam = null

  override def setup() {
    cam = new PeasyCam(this, 100);
    cam.setMinimumDistance(50);
    cam.setMaximumDistance(500);
  }

  override def draw() {
    rotateX(-.5f);
    rotateY(-.5f);
    background(0);
    fill(255,0,0);
    box(30);
    pushMatrix();
    translate(0,0,20);
    fill(0,0,255);
    box(5);
    popMatrix();

  }

}

object HelloPeasy extends ScalaPAppCompanion {}

Add an official example of PeasyCam.

Add an official example of PeasyCam.


object Solution {

  def deletionForAnagram(s: String, t: String): Int = {
    val sc,tc = Array.fill(256)(0)
    for (c <- s) sc(c) += 1
    for (c <- t) tc(c) += 1
    sc.zip(tc).map(x => math.abs(x._1 - x._2)).sum
  }

  def main(args: Array[String]) {
    val s = readLine
    val t = readLine
    println(deletionForAnagram(s, t))
  }
}

Add solution to problem Make it Anagram

Add solution to problem Make it Anagram


import sbt._

object Dependencies {
  val servletApiDep = "javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided"

  def specs2Dep(sv: String) =
    "org.specs2" %% "specs2-core" % "3.8.9"

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

  def integrationTestDeps(sv: String) = (specs2Dep(sv) :: okHttp) map { _ % "test" }

  val commonsCodecVersion = "1.10"
  val scalacheckVersion = "1.13.4"
  val jodaTimeVersion = "2.9.7"
  val jodaConvertVersion = "1.8.1"
  val scalaXmlVersion = "1.0.6"
  val commonsIoVersion = "2.5"
  val commonsFileUploadVersion = "1.3.2"
  val jettyVersion = "9.2.21.v20170120"
  val nettyVersion = "4.1.8.Final"
  val scalatestVersion = "3.0.1"
  val json4sVersion = "3.5.0"
  val asyncHttpClientVersion = "1.8.17"
  val scribeJavaVersion = "3.3.0"
}

import sbt._

object Dependencies {
  val servletApiDep = "javax.servlet" % "javax.servlet-api" % "3.1.0" % "provided"

  def specs2Dep(sv: String) =
    "org.specs2" %% "specs2-core" % "3.8.9"

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

  def integrationTestDeps(sv: String) = (specs2Dep(sv) :: okHttp) map { _ % "test" }

  val commonsCodecVersion = "1.10"
  val scalacheckVersion = "1.13.5"
  val jodaTimeVersion = "2.9.9"
  val jodaConvertVersion = "1.8.1"
  val scalaXmlVersion = "1.0.6"
  val commonsIoVersion = "2.5"
  val commonsFileUploadVersion = "1.3.2"
  val jettyVersion = "9.2.21.v20170120"
  val nettyVersion = "4.1.9.Final"
  val scalatestVersion = "3.0.1"
  val json4sVersion = "3.5.1"
  val asyncHttpClientVersion = "1.8.17"
  val scribeJavaVersion = "3.3.0"
}

Update netty, jodatime, json4s, and scalacheck.


package lila.openingexplorer

sealed abstract class SpeedGroup(
    val id: Int,
    val name: String,
    val range: Range) {
}

object SpeedGroup {

  case object Bullet extends Speed(1, "bullet", 0 to 179)
  case object Blitz extends Speed(2, "blitz", 180 to 479)
  case object Classical extends Speed(3, "classical", 480 to Int.MaxValue)

  val all = List(Bullet, Blitz, Classical)

  val byId = all map { v => (v.id, v) } toMap

  def apply(speed: chess.Speed) = speed match {
    case chess.Speed.Bullet                                 => Bullet
    case chess.Speed.Blitz                                  => Blitz
    case chess.Speed.Classical | chess.Speed.Correspondence => Classical
  }

}

Add the discussed speed groups

Add the discussed speed groups


package uk.ac.wellcome.platform.transformer.transformers.miro

import org.scalatest.{FunSpec, Matchers}
import uk.ac.wellcome.models.work.internal.License_CC0

class MiroLicensesTest extends FunSpec with Matchers {

  it("finds a recognised license") {
    transformer.chooseLicense(useRestrictions = "CC-0") shouldBe License_CC0
  }

  val transformer = new MiroLicenses {}
}

Implement some tests for MiroLicenses

Implement some tests for MiroLicenses


import stainless.lang._
import stainless.collection._

object BVMaxInterpret {

  case class Reg(n: BigInt)

  sealed abstract class Op {
    def out: Reg
  }
  case class BVSge(out: Reg, ra: Reg, rb: Reg) extends Op
  case class BVNeg(out: Reg, ra: Reg)          extends Op
  case class BVXor(out: Reg, ra: Reg, rb: Reg) extends Op
  case class BVAnd(out: Reg, ra: Reg, rb: Reg) extends Op

  case class State(
    registers: CMap[Reg, Int],
  ) {
    def load(reg: Reg): Int = registers(reg)
    def store(reg: Reg, v: Int): State = copy(registers = registers.updated(reg, v))
  }

  object State {
    def empty: State = State(CMap(_ => 0))
  }

  def eval1(op: Op, state: State): Int = op match {
    case BVSge(_, ra, rb) =>
      if (state.load(ra) >= state.load(rb)) 1 else 0

    case BVNeg(_, ra) =>
      -state.load(ra)

    case BVXor(_, ra, rb) =>
      state.load(ra) ^ state.load(rb)

    case BVAnd(_, ra, rb) =>
      state.load(ra) & state.load(rb)
  }

  def eval(op: Op, state: State): State = {
    val res = eval1(op, state)
    state.store(op.out, res)
  }

  case class Program(stmts: List[Op], ret: Reg)

  def interpret(prog: Program, init: State): Int = {
    def go(stmts: List[Op], state: State): State = {
      decreases(stmts)
      stmts match {
        case Nil() => state
        case Cons(op, rest) => go(rest, eval(op, state))
      }
    }

    val end = go(prog.stmts, init)
    end.load(prog.ret)
  }

  val r0 = Reg(0)
  val r1 = Reg(1)
  val r2 = Reg(2)
  val r3 = Reg(3)
  val r4 = Reg(4)
  val r5 = Reg(5)
  val r6 = Reg(6)

  def bvmax(r0v: Int, r1v: Int) = {
    val init = State.empty.store(r0, r0v).store(r1, r1v)

    val prog = Program(
      List(
        BVSge(r2, r0, r1),
        BVNeg(r3, r2),
        BVXor(r4, r0, r1),
        BVAnd(r5, r3, r4),
        BVXor(r6, r1, r5),
      ),
      r6
    )

    interpret(prog, init)
  }

  def thm(a: Int, b: Int) = {
    assert(bvmax(a, b) == stainless.math.max(a, b))
  }

}

Add new bvmax interpreter benchmark

Add new bvmax interpreter benchmark

Inspired from https://tube.switch.ch/videos/166c6218


package com.negrisoli.algorithms.implementation

import java.math.BigInteger

object AcmIcpcTeam {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt()
    val m = sc.nextInt()

    val topics = 1.to(n).map(x => sc.next() ).map( new BigInteger(_, 2)).toArray

    var max = 0
    var pairs = 0
    for (i <- 0 to topics.size - 1) {
      for (j <- i + 1 to topics.size - 1) {
        val c = count(topics(i), topics(j))
        if (c > max) {
          max = c
          pairs = 1
        } else if (c == max && pairs > 0) {
          pairs = pairs + 1
        }
      }
    }

    println(max)
    println(pairs)
  }

  def count(x: BigInteger, y:BigInteger): Int = x.or(y).bitCount()

}

Add ACM ICPC team solution.

Add ACM ICPC team solution.


trait HList
trait HNil extends HList

trait FromTraversable[Out <: HList]
object FromTraversable {
  implicit def hnilFromTraversable[T]: FromTraversable[HNil] =
    new FromTraversable[HNil]{}
}

object Filter {
  def apply[A <: HList, O <: HList]()(implicit ftA: FromTraversable[A],
                                      ftO: FromTraversable[O]): Unit = ()
}
object Main {
  def main = Filter[HNil, HNil]()
}

Add test case for issue fixed in previous commit

Fixes #2981 which was a duplicate of #3213


package berlin.jentsch.modelchecker.example
import berlin.jentsch.modelchecker.{EveryPathTraverser, Traverser}
import org.scalatest.FlatSpec

class FerrymanSpec extends FlatSpec {

  it should "be possible to carry over all parts" in {
    val traverser: Traverser = new EveryPathTraverser
    var pathsCount = 0
    var everDone = false
    var wolfBeforeCabbage = false
    var cabbageBeforeWolf = false
    do {
      var wolf, goat, cabbage, ferryman: Boolean = false
      /** Upper bound found by experimentation, actually 7 is enough */
      var steps = 8

      def done: Boolean = wolf && goat && cabbage && ferryman

      /** Either when one thing gets eaten or when no more steps available */
      def failed: Boolean =
        (wolf == goat && wolf != ferryman) ||
          (goat == cabbage && goat != ferryman) ||
          (steps <= 0)

      def allActions: List[(Boolean, () => Unit)] =
        (wolf == ferryman) -> (() => { wolf = !wolf; ferryman = !ferryman }) ::
          (goat == ferryman) -> (() => { goat = !goat; ferryman = !ferryman }) ::
          (cabbage == ferryman) -> (() => {
          cabbage = !cabbage; ferryman = !ferryman
        }) ::
          true -> (() => { ferryman = !ferryman }) ::
          Nil

      def possibleActions: List[() => Unit] = allActions.collect {
        case (true, action) => action
      }

      while (!done && !failed) {
        traverser.choose(possibleActions)()
        steps -= 1
      }

      wolfBeforeCabbage |= wolf && !goat & !cabbage
      cabbageBeforeWolf |= ! wolf && !goat & cabbage

      if (!everDone && done) {
        info("First found path: " ++ traverser.getCurrentPath.toString)
      }
      everDone |= done
      pathsCount += 1
    } while (traverser.hasMoreOptions())

    info("Paths: " ++ pathsCount.toString)
    assert(everDone)
    assert(wolfBeforeCabbage)
    assert(cabbageBeforeWolf)
  }
}

Add Ferryman example to core

Add Ferryman example to core


package uk.ac.ncl.openlab.intake24.sql.tools.food.localisation

import anorm.{BatchSql, NamedParameter}
import org.rogach.scallop.ScallopConf
import uk.ac.ncl.openlab.intake24.sql.tools.{DatabaseConfigurationOptions, DatabaseConnection, ErrorHandler, WarningMessage}

object FixPortugueseAssociatedFoodNames extends App with WarningMessage with DatabaseConnection with ErrorHandler {

  val translations = Seq(
    "mixer" -> "bebida",
    "milk" -> "leite",
    "sugar" -> "açúcar",
    "mayonnaise" -> "maionese",
    "sauce" -> "molho",
    "butter or margarine" -> "manteiga ou margarina",
    "jam/preserve" -> "compota",
    "other spreads" -> "creme de barrar",
    "ice cream" -> "gelado",
    "cream" -> "chantilly",
    "rice" -> "arroz",
    "fries" -> "batatas fritas",
    "drink" -> "bebida",
    "bread or toast" -> "pão ou torrada",
    "gravy" -> "molho",
    "jam/spread" -> "compota/creme de barrar",
    "bread or toast" -> "pão ou torrada",
    "bread" -> "pão",
    "toast" -> "torrada",
    "sugar/sauce" -> "açúcar/molho",
    "crackers or crispbreads" -> "biscoitos ou batatas fritas",
    "noodles or rice" -> "macarrão ou arroz",
    "salsa dip" -> "mergulho de salsa",
    "other dips" -> "outros mergulhos",
    "burger" -> "pão",
    "custard" -> "creme custard",
    "quindim" -> "creme custard",
    "pineapple" -> "ananás",
    "abacaxi" -> "ananás",
    "egg" -> "ovo",
    "butter/margarine" -> "manteiga ou margarina"

  )

  trait Options extends DatabaseConfigurationOptions {

  }

  val options = new ScallopConf(args) with Options

  options.verify()

  val dbConfig = chooseDatabaseConfiguration(options)

  displayWarningMessage(s"This will update Portuguese associated foods in ${dbConfig.host}/${dbConfig.database}. Are you sure?")

  val dataSource = getDataSource(dbConfig)

  val params = translations.map {
    case (en, pt) =>
      Seq[NamedParameter]('en_name -> en, 'pt_name -> pt, 'locale_id -> "pt_PT")
  }

  implicit val con = dataSource.getConnection()

  BatchSql("UPDATE associated_foods SET generic_name={pt_name} WHERE generic_name={en_name} AND locale_id={locale_id}", params.head, params.tail: _*).execute()

  con.close()
}

Fix Portuguese associated foods translations


package spa.client.modules

import japgolly.scalajs.react.vdom.prefix_<^._
import japgolly.scalajs.react.{ReactComponentB, Callback, BackendScope}
import japgolly.scalajs.react.extra.router.RouterCtl
import spa.client.SPAMain.Loc
import spa.client.components.Bootstrap.{Button, Panel}
import spa.client.components.GlobalStyles
import spa.client.logger._

/**
  * Created by skypage on 6/14/16.
  */
object Feedback {
  case class Props(router: RouterCtl[Loc])
  @inline private def bss = GlobalStyles.bootstrapStyles

  class Backend($: BackendScope[Props, Unit]) {

    def onSubmit= {
      Callback.log("Testing")
    }

    def render(p: Props) = {//}, s: State) = {
      <.div(^.className:="col-md-8 col-md-offset-2")(
        Panel(Panel.Props("Feedback"),
          <.form()(
            <.div(^.className:="form-group")(
              <.label(^.`for`:="subject")("Subject:"), <.br,
              <.input.text(^.id:="subject", ^.className:="form-control")(), <.br,
              <.label(^.`for`:="message")("Message:"), <.br,
              <.textarea(^.id:="message", ^.className:="form-control", ^.rows:="5")(), <.br, <.br,

              <.b("Optional information:"),
              <.p()(
                """You may leave everything below blank to send a completely anonymous note,
                   or you may provide what information you like. I can't reply to your message
                   without an email address, so keep that in mind.  Your email address will only
                   be used as a possible way for me to reply to you."""),
              <.label(^.`for`:="name")("Your name:"), <.br,
              <.input.text(^.id:="name", ^.className:="form-control"), <.br,
              <.label(^.`for`:="email")("Your email:"), <.br,
              <.input.email(^.id:="email", ^.className:="form-control"), <.br,

              Button(Button.Props(onSubmit, addStyles = Seq(bss.pullRight, bss.button)), "Submit")
            )
          ))
      )
    }

  }

  val component = ReactComponentB[Props]("Feedback")
    .initialState({
      log.debug("Feedback init")
    })
    .renderBackend[Backend]
    .build

  /** Returns a function compatible with router location system while using our own props */
  def apply(router: RouterCtl[Loc]) = component(Props(router))
}

Add UI for feedback form

Add UI for feedback form


object Solution {

  def main(args: Array[String]) {
    val p = 1e5.toInt
    for (_ <- 1 to readLine.toInt) {
      val n = readLine.toInt
      println(BigInt(2).modPow(n, p) - 1)
    }
  }
}

Add solution to Diwali Lights.

Add solution to Diwali Lights.


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

package org.openmole.misc.tools.collection

object ArrayUtils {

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

}

Implement unsecure concatenation for arrays.


package uk.ac.wellcome.platform.api.works

import com.twitter.finagle.http.Status
import uk.ac.wellcome.models.Work

class PublishersTest extends ApiWorksTestBase {

  it("includes an empty publishers field if the work has no publishers") { }

  it("includes the publishers field for agent publishers") { }

  it("includes the publishers field with a mixture of agents/organisations") { }
}

Define a test stub for publishers in the API


package scala.in.programming.build_in_control_structure

/**
  * These methods included this object refactor coding style of Imperative.
  *
  * If you want show source code not refactored coding style of Imperative,
  * find source in PIS p.180.
  *
  * @author loustler
  * @since 02/03/2017 21:12
  */
object RefactorImperativeStyle extends App {

  /**
    * This function convert single row to sequence.
    *
    * @param row To convert row to sequence.
    * @return Single row converted to sequence.
    */
  def makeRowSeq(row: Int) =
    for ( col <- 1 to 10 ) yield {
      val prod = (row * col).toString

      val padding = " " + (4 - prod.length)

      padding + prod
    }

  /**
    * This function convert single row to strings.
    *
    * @param row To convert row to strings
    * @return Single row converted to string.
    */
  def makeRow(row: Int) = makeRowSeq(row).mkString

  def multiTable() = {
    val tableSeq =
      for (row <- 1 to 10)
        yield makeRow(row)

    tableSeq.mkString("\n")
  }
}

Add example for refactor coding style of imperative


BuildSettings.baseSettings

name := "testkit"

version := "0.0.2-SNAPSHOT"

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

BuildSettings.baseSettings

name := "testkit"

version := "0.0.2-SNAPSHOT"

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

Bump testkit akka dependency to 2.3.2

Bump testkit akka dependency to 2.3.2


package scala.scalanative
package compiler
package analysis

import scala.collection.immutable
import scala.collection.mutable
import ControlFlow.Block

object DominatorTree {

  private def pred(block: Block) = block.pred.map(_.from)
  private def succ(block: Block) = block.succ.map(_.to)

  /** Fixpoint-based method to build the dominator tree
   *  from the CFG. The dominator tree is simply represented
   *  as a Map from a CFG block to the set of blocks dominating
   *  this block.
   */
  def build(cfg: ControlFlow.Graph): Map[Block, Set[Block]] = {
    val domination = mutable.HashMap.empty[Block, Set[Block]]
    var workList = immutable.Queue(cfg.entry)

    while (workList.nonEmpty) {
      val (block, dequeued) = workList.dequeue
      workList = dequeued.filterNot(_ == block) // remove duplicates

      val visitedPreds = pred(block).filter(domination.contains)
      val predDomination =
        visitedPreds.toList.map(pred => domination.getOrElse(pred, Set.empty))
      val correctPredDomination = predDomination.filterNot(
          predDominators =>
            predDominators
              .contains(block)) // removes the potential dominators that are dominated by this block (counters loop problems)

      val blockDomination =
        if (correctPredDomination.isEmpty)
          Set.empty[Block]
        else
          correctPredDomination.tail.foldLeft(correctPredDomination.head)(
              (a, b) => a.intersect(b))

      val oldDomination = domination.getOrElse(block, Set.empty)
      val newDomination = blockDomination + block // a block dominates itself

      if (oldDomination != newDomination) {
        domination += (block -> newDomination)
        workList ++= succ(block)
      }
    }

    domination.toMap
  }

}

Implement a fix-point based algorithm for constructing the dominator tree


package dotty.dokka.tasty.comments

import org.junit.{Test, Rule}
import org.junit.Assert.{assertSame, assertTrue, assertEquals}

class MarkdownConverterTests {
  @Test def test(): Unit = {
    assertEquals(("a", "b c d"), MarkdownConverter.splitWikiLink("a b c d"))
    assertEquals(("a", "b\\ c d"), MarkdownConverter.splitWikiLink("a b\\ c d"))
    assertEquals(("a\\ b", "c d"), MarkdownConverter.splitWikiLink("a\\ b c d"))
  }
}

Add tests for Wiki link splitting

Add tests for Wiki link splitting


package net.ruippeixotog.scalascraper.util

import java.net.{ ConnectException, Socket, SocketException }

import net.ruippeixotog.scalascraper.browser._
import org.specs2.matcher.ThrownMessages
import org.specs2.mutable.Specification

// This test works only if an external Tor client is running. It tries to connect to localhost:9050; if no service is
// listening in that endpoint, the test is skipped. The test makes a request to http://ipv4.icanhazip.com and the IPs
// returned with and without proxy are compared.
//
// The host and port of the Tor server can be changed by setting the TOR_CLIENT_HOST and TOR_CLIENT_PORT ports. Other
// SOCKS proxies may be used, as long as they execute the request from another external IP.
class ProxyUtilsSpec extends Specification with BrowserHelper with ThrownMessages {
  sequential

  val torClientHost = Option(System.getenv("TOR_CLIENT_HOST")).getOrElse("localhost")
  val torClientPort = Option(System.getenv("TOR_CLIENT_PORT")).fold(9050)(_.toInt)

  def withSocksProxy[T](host: String, port: Int)(block: => T): T = {
    ProxyUtils.setSocksProxy(host, port)
    val res = block
    ProxyUtils.removeSocksProxy()
    res
  }

  def withTorProxy[T](block: => T): T = {
    try {
      new Socket(torClientHost, torClientPort).close() // test if port is open
      withSocksProxy(torClientHost, torClientPort)(block)
    } catch {
      case _: ConnectException | _: SocketException => skip("A Tor proxy is not available")
    }
  }

  "A Browser" should {
    usingBrowsers(JsoupBrowser(), HtmlUnitBrowser()) { browser =>

      "make requests through a SOCKS server if configured" in {
        val proxyIP = withTorProxy { browser.get("http://ipv4.icanhazip.com").body.text }
        val myIP = browser.get("http://ipv4.icanhazip.com").body.text
        proxyIP !=== myIP
      }
    }
  }
}

Add test for checking if the support for SOCKS proxies is working


object Test extends App {

  class TC

  implied StringListOps given TC {
    type T = List[String]
    def (x: T) foo (y: T) = (x ++ y, the[TC])
    def (x: T) bar (y: Int) = (x(y), the[TC])
  }

  def test given TC = {
    assert(List("abc").foo(List("def"))._1 == List("abc", "def"))
    assert(List("abc").bar(2)._1 == "c")
  }

  test given TC()
}

Test demonstrating extension method shorthands

This test shows that the overhead of extension methods can be reduced
to be no more than 7 characters per method, using two tricks:

 - Any implicit parameters become parameters of the enclosing implied instance
 - A local type alias can be used to abbreviate the (repetitive) first parameter
   string.

This demonstration strengthens the case for the current syntax for extension methods.


object Solution {

  def main(args: Array[String]) {
    val n = readInt
    val matrix = (1 to n).map(x => readLine.split(" ").map(_.toInt))
    val pathSumMinimum = Array.fill(n)(Array.fill(n)(0L))
    var sum = 0L
    for (i <- 0 until n) {
      sum += matrix(0)(i)
      pathSumMinimum(0)(i) = sum
    }
    sum = matrix(0)(0)
    for (i <- 1 until n) {
      sum += matrix(i)(0)
      pathSumMinimum(i)(0) = sum
    }
    for { i <- 1 until n
          j <- 1 until n
    }
    pathSumMinimum(i)(j) = matrix(i)(j) +
      math.min(pathSumMinimum(i - 1)(j), pathSumMiminum(i)(j - 1))

    println(pathSumMinimum(n - 1)(n - 1))
  }
}

Add solution to problem path sum: two ways. It's quite a simple problem. Simple dp can nail it.


package dotty.collections
package immutable

import annotation.unchecked.uncheckedVariance

trait Collection[+CC[X] <: Collection[CC, X], T] {
  def companion: CollectionCompanion[CC]
}

trait Iterable[T] extends Collection[Iterable, T] {
  def iterator: Iterator[T]
  override def companion: IterableCompanion[Iterable] = Iterable
}

trait Seq[T] extends Iterable[T] with Collection[Seq, T] {
  def apply(x: Int): T
  override def companion: IterableCompanion[Seq] = Seq
}

abstract class CollectionCompanion[+CC[X] <: Collection[CC, X]]

trait IterableImpls[CC[X]] {
  def fromIterator[T](it: Iterator[T]): CC[T]
  def toIterator[T](xs: CC[T]): Iterator[T]
  def map[T, U](xs: CC[T], f: T => U): CC[U] =
    fromIterator(toIterator(xs).map(f))
  def filter[T](xs: CC[T], p: T => Boolean): CC[T] =
    fromIterator(toIterator(xs).filter(p))
  def flatMap[T, U](xs: CC[T], f: T => TraversableOnce[U]): CC[U] =
    fromIterator(toIterator(xs).flatMap(f))
}

abstract class IterableCompanion[+CC[X] <: Iterable[X] with Collection[CC, X]]
extends CollectionCompanion[CC] with IterableImpls[CC] @uncheckedVariance {
  def toIterator[T](xs: CC[T] @uncheckedVariance) = xs.iterator
  implicit def transformOps[T](xs: CC[T] @uncheckedVariance): TransformOps[CC, T] = new TransformOps[CC, T](xs)
}

class TransformOps[+CC[X] <: Iterable[X] with Collection[CC, X], T] (val xs: CC[T]) extends AnyVal {
  def companion[T](xs: CC[T] @uncheckedVariance): IterableCompanion[CC] = xs.companion.asInstanceOf
  def map[U](f: T => U): CC[U] = companion(xs).map(xs, f)
  def filter(p: T => Boolean): CC[T] = companion(xs).filter(xs, p)
  def flatMap[U](f: T => TraversableOnce[U]): CC[U] = companion(xs).flatMap(xs, f)
}

object Iterable extends IterableCompanion[Iterable] {
  def fromIterator[T](it: Iterator[T]): Iterable[T] = ???
}
object Seq extends IterableCompanion[Seq] {
  def fromIterator[T](it: Iterator[T]): Seq[T] = ???
}

Add test case for higher-kinded operations on collections The test case that caused all previous commits in this branch.


package kantan.xpath.cats

import cats.data.Xor
import kantan.xpath.NodeDecoder

object codecs {
  implicit def xor[A, B](implicit da: NodeDecoder[A], db: NodeDecoder[B]): NodeDecoder[Xor[A, B]] = NodeDecoder { node =>
    da.decode(node).map(a => Xor.left(a)).orElse(db.decode(node).map(b => Xor.right(b)))
  }
}

Add NodeDecoder instance for Xor.

Add NodeDecoder instance for Xor.


package org.precompiler.scala101.ch03

/**
  *
  * @author Richard Li
  */
object ImplicitParameters {
  // global scope implicit variable
  implicit val vodafone = new Wifi("Vodafone")

  class Wifi(name: String) {
    override def toString: String = name
  }

  def connectToNetwork(user: String)(implicit wifi: Wifi): Unit = {
    println(s"User ${user} connected to WIFI ${wifi}")
  }

  def atOffice(): Unit = {
    println("----office----")
    // method scope implicit variable
    // will get ambiguous implicit values runtime exception if
    // multiple implicit values of the same type found in scope
    // implicit val officeNetwork = new Wifi("Office")
    val cafeteriaNetwork = new Wifi("Cafe")
    connectToNetwork("guest")(cafeteriaNetwork)
    connectToNetwork("John Doe")
  }

  def atHome(): Unit = {
    println("----home----")
    // implicit val homeNetwork = new Wifi("Home")
    connectToNetwork("Scott Tiger")
  }

  def main(args: Array[String]): Unit = {
    atOffice()
    atHome()
  }
}

Add implicit parameters example code.

Add implicit parameters example code.


package hmda.publication.reports.protocol

import hmda.model.publication.reports.ReportTypeEnum
import hmda.publication.reports.ReportGenerators._
import org.scalatest.prop.PropertyChecks
import org.scalatest.{ MustMatchers, PropSpec }
import spray.json._

class ReportTypeEnumProtocolSpec extends PropSpec with PropertyChecks with MustMatchers with ReportTypeEnumProtocol {

  property("Report Type must convert to and from JSON") {
    forAll(reportTypeGen) { r =>
      r.toJson.convertTo[ReportTypeEnum] mustBe r
    }
  }
}

Add report type enum protocol test

Add report type enum protocol test


package eu.timepit.refined.scalacheck

import eu.timepit.refined.scalacheck.string._
import eu.timepit.refined.types.string.NonEmptyString
import org.scalacheck.Prop._
import org.scalacheck.{Properties, Test}

class ZeroDiscardRatioSpec extends Properties("ZeroDiscardRatioSpec") {
  override def overrideParameters(p: Test.Parameters): Test.Parameters =
    p.withMaxDiscardRatio(Float.MinPositiveValue)

  property("NonEmptyString") = forAll((_: NonEmptyString) => true)
}

Check that Arbitrary[NonEmptyString] does not discard values


package vtpassim

import org.apache.spark.sql.SparkSession

import scala.collection.mutable.StringBuilder
import scala.util.Try
import scala.xml.pull._

object TEIPages {
  def main(args: Array[String]) {
    val spark = SparkSession.builder().appName("TEIPages Import").getOrCreate()
    import spark.implicits._

    spark.sparkContext.hadoopConfiguration
      .set("mapreduce.input.fileinputformat.input.dir.recursive", "true")

    spark.sparkContext.binaryFiles(args(0), spark.sparkContext.defaultParallelism)
      .filter(_._1.endsWith(".xml"))
      .flatMap( in => {
        val fname = new java.io.File(new java.net.URL(in._1).toURI)
        val id = fname.getName.replaceAll(".xml$", "")
        val buf = new StringBuilder
        var buffering = false
        var seq = -1

        val pass = new XMLEventReader(scala.io.Source.fromURL(in._1))
        pass.flatMap { event =>
          event match {
            case EvElemStart(_, "pb", attr, _) => {
              val rec = if ( buffering ) {
                Some((f"$id%s_$seq%04d", id, seq, buf.toString.trim))
              } else {
                None
              }
              buffering = true
              seq += 1
              buf.clear
              rec
            }
            case EvElemEnd(_, "text") => {
              if ( buffering ) {
                seq += 1
                val text = buf.toString.trim
                buffering = false
                buf.clear
                Some((f"$id%s_$seq%04d", id, seq, text))
              } else {
                None
              }
            }
            case EvText(t) => {
              if ( buffering ) buf ++= t
              None
            }
            case EvEntityRef(n) => {
              if ( buffering ) buf ++= "&" + n + ";"
              None
            }
            case _ => None
          }
        }
      })
      .toDF("id", "book", "seq", "text")
      .write.save(args(1))
    spark.stop()
  }
}

Copy TEIPages for DTA texts.

Copy TEIPages for DTA texts.


object Test {
  def res(x: quoted.Expr[Int]) given tasty.Reflection: quoted.Expr[Int] = x match {
    case '{ val a: Int = ${ Foo('{ val b: Int = $y; b }) }; a } => y // owner of y is res
  }
  object Foo {
    def unapply(x: quoted.Expr[Int]): Option[quoted.Expr[Int]] = Some(x)
  }
}

Add a test on nested quoted patterns

Add a test on nested quoted patterns


/*
 * In the United Kingdom the currency is made up of pound (£) and pence (p).
 * There are eight coins in general circulation:
 *
 *   1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p).
 *
 * It is possible to make £2 in the following way:
 *
 *   1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
 *
 * How many different ways can £2 be made using any number of coins?
 */

// Look at this in terms of finding the number of nodes in the following tree:
//
//  * There is a root node with child nodes labelled for each of the coin
//    denominations, 200, 100, 50, 20, 10, 5, 2, 1.
//  * A node cannot have any descendent nodes labelled with a coin denomination
//    larger than its value.
//  * A node will have a child node of a given coin denomination if the sum of
//    that and all node coin denominations ancestors does not exceed 200.
//
// And depth-first search to count the tree elements.

def countCoinSums(target: Int, coins: List[Int]): Int = {
  val childNodeCoinSums = coins.map { coin =>
    if (coin > target) {
      // Base case: Can't make the target if this coin is included.
      0
    } else if (coin == target) {
      // Base case: Found a unique combination of coins.
      1
    } else {
      // Only include smaller or equal coins in descendants.
      countCoinSums(target - coin, coins.filter { _ <= coin })
    }
  }

  childNodeCoinSums.sum
}

val answer = countCoinSums(200, List(200, 100, 50, 20, 10, 5, 2, 1))
println(answer)

Add Scala implementation for problem 31.


package org.geoscript

import org.scalatest._
import org.scalatest.matchers.ShouldMatchers

import geometry.Implicits._

class UsageTests extends FlatSpec with ShouldMatchers {
  "geometries" should "support buffering" in {
    var p = geometry.Point(-111, 45.7)
    // var p2 = projection.transform(p, "epsg:4326", "epsg:26912")
    var poly = p.buffer(100)
    poly.area should be (31214.45 plusOrMinus 0.01)
  }
}

Add simple test case to get a suite started.


object Solution {

  def getCutsForSticks(sticks: Array[Int]): Seq[Int] = {
    val n = sticks.size
    val upperBound = 1000 // the upperBound for a_i in the sticks array.
    val counts = Array.fill(upperBound + 1)(0)
    for (s <- sticks) counts(s) += 1
    var result = n
    for (c <- counts if c > 0 && result > 0) yield {
      result = result - c
      result + c
    }
  }

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

Add solution to problem Cut the Sticks.

Add solution to problem Cut the Sticks.


class Box[V](val value: V)

class Test:
  def value: Box["text"] = Box("text")

  def test: String = value match
    case b: Box[_ <: String] => b.value

Add a test case there the pattern has a bound

Looking at the log of constr, gadts, and gadtsConstr there seems to be
no change in behaviour compared to before the implementation change in
PatternTypeConstrainer.


package com.mlh.spraysample

import org.scalatest.FreeSpecLike
import org.scalatest.Matchers
import org.scalatest.BeforeAndAfterAll

import akka.actor.ActorSystem
import akka.testkit.TestActorRef
import akka.testkit.TestKit
import akka.testkit.ImplicitSender

import scala.concurrent.duration._
import scala.concurrent.Await
import akka.pattern.ask

class WorkerSpec extends TestKit(ActorSystem("WorkerSpec"))
with ImplicitSender
with FreeSpecLike
with Matchers
with BeforeAndAfterAll {
  import WorkerActor._

  val actorRef = TestActorRef[WorkerActor]

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "Worker" - {
    "creates" - {
      "receive Ok" - {
        val future = actorRef ! Create(new Foo("bar"))
        expectMsgClass(classOf[Ok])
      }
    }
  }
}

Add simplest test of worker actor

Add simplest test of worker actor


package glint.models.cache

import glint.models.BigModel

import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future}
import spray.caching.{Cache, LruCache}

import scala.reflect.ClassTag

/**
  * A Cache trait for models
  */
class CacheModel[K: ClassTag, V: ClassTag](bigModel: BigModel[K, V],
                                           aggregate: (V, V) => V,
                                           val pushQueueSize: Int = 200) {

  val cache: Cache[V] = LruCache()
  val pushQueue = mutable.HashMap[K, V]()

  /**
    * Pushes a (key, value) pair asynchronously
    *
    * @param key The key
    * @param value The value
    */
  def push(key: K, value: V)(implicit ec: ExecutionContext): Unit = {
    pushQueue(key) = aggregate(pushQueue.getOrElse(key, bigModel.default), value)
    if (pushQueue.keySet.size > pushQueueSize) {
      flush()
    }
  }

  /**
    * Pulls a (key, value) pair asynchronously
    *
    * @param key The key
    * @return A future holding the value (could be returned from cache)
    */
  def pull(key: K)(implicit ec: ExecutionContext): Future[V] = cache(key) {
    bigModel.pullSingle(key)
  }

  /**
    * Runs all pending operations
    *
    * @return A future for the completion of the pending operations
    */
  def flush()(implicit ec: ExecutionContext): Future[Unit] = {
    val keys = pushQueue.keys.toArray
    val values = keys.map(k => pushQueue(k))
    pushQueue.clear()
    println(s"Flushing keys: [${keys.mkString(",")}]")
    bigModel.push(keys, values)
  }

}

Add basic cache model wrapper

Add basic cache model wrapper


package org.geoserver.community.css

import org.geotools.{ styling => gt }

object Benchmark {
  val template = """
[%1$s < 10] {
  stroke: black;
  label: "%1$s - 1";
}

[%1$s > 20] {
  stroke: red;
  label: "%1$s - 2";
}

[%1$s < 20] {
  stroke: blue;
  label: "%1$s - 3";
}

[%1$s = 15] {
  stroke: green;
  label: "%1$s - 4";
}
"""

  val tx = new org.geotools.styling.SLDTransformer()
  tx.setIndentation(4)

  def encodeSLD(sld: gt.Style): String = {
    val out = new java.io.StringWriter()
    tx.transform(sld, out)
    out.toString()
  }

  def time[A](op: => A): (A, Long) = {
    val startTime = System.currentTimeMillis()
    (op, System.currentTimeMillis() - startTime)
  }

  def main(args: Array[String]) {
    for (end <- 'A' to 'B') {
      // dry run; warm up the JIT statistics
      encodeSLD(
        Translator.css2sld(
          CssParser.parse(
            'A' to end map { template.format(_) } mkString
          ).get
        )
      )
    }

    println("properties, parse_time, transform_time, encode_time")

    for (end <- 'A' to 'D') {
      val range = 1 + (end - 'A')
      val css = 'A' to end map { template.format(_) } mkString
      val (cssRules, parseTime) = time { CssParser.parse(css).get }
      val (sldRules, transformTime) = time { Translator.css2sld(cssRules) }
      val (sld, encodeTime) = time { encodeSLD(sldRules) }
      println(Seq(range, parseTime, transformTime, encodeTime).mkString(", "))
    }
  }
}

Add a simple benchmark driver for speed testing

git-svn-id: 56982e1c1b6234e31d7615247a239def746bba9e@14568 ef1d6e69-97e5-0310-af46-8a06194da32a


package lore.compiler.types

import org.scalatest.Assertion

class DirectSubtypesSpec extends TypeSpec {

  import TypesExample._

  private def assertDirectSubtypes(dt: DeclaredType)(expected: DeclaredType*): Assertion = {
    registry.declaredTypeHierarchy.getDirectSubtypes(dt).toSet shouldEqual expected.toSet
  }

  private def assertConcreteSubtypes(dt: DeclaredType)(expected: DeclaredType*): Assertion = {
    registry.declaredTypeHierarchy.getConcreteSubtypes(dt).toSet shouldEqual expected.toSet
  }

  "DeclaredTypeHierarchy.getDirectSubtypes" should "compute the correct subtypes for parameterized traits" in {
    assertDirectSubtypes(Cage(Animal))(
      Aquarium(Fish), UnicornPen, ConfusedCage1, ConfusedCage2, ConfusedCage3, ConfusedCage4
    )
    assertDirectSubtypes(Cage(Fish))(
      Aquarium(Fish), ConfusedCage1, ConfusedCage4
    )
  }

  "DeclaredTypeHierarchy.getConcreteSubtypes" should "compute the correct concrete subtypes for parameterized traits" in {
    // TODO (schemas): Write some tests for DeclaredTypeHierarchy.getConcreteSubtypes.
  }

}

Add tests for direct subtypes and concrete subtypes.


package scalafortheimpatient.chapter2

/**
 * @author Wei Xing
 */

object Section01 {
  def main(args: Array[String]) {
    // Similar to "1 == 1 ? 1 : -1" in Java/C++.
    val v1 = if (1 == 1) 1 else -1

    // If the type after if and else are not same, use the common super type.
    // In this example, return Any.
    val v2 = if (1 == 1) 1 else "1"

    // If not exist else expr and if expr is not true, return Unit.
    val v3 = if (1 == 1) 1
    val v4 = if (1 == 1) 1 else () // () is Unit, like void.
  }
}

/**
 * Statement terminal.
 */
object Section02 {
  def main(args: Array[String]) {

  }
}

/**
 * Block Expression
 */
object Section03 {
  def main(args: Array[String]): Unit = {
    // {} is a set of expressions, which result is a expression, too.
    // The value of {} is the value of the last expression in it.
    // It is useful when a value's initial need two or more steps.
    val v1 = {
      val dx = 1 - 2
      val dy = 3 - 4
      Math.sqrt(dx * dx + dy * dy)
    }

    // Assign expression return Unit value.
    val v2 = { var i = 1; i += 1}
    // So, assign can not be go on
    var x = 1
    var y = x = 1 // y is Unit or ()
  }
}

/**
 * I/O
 */
object Section04 {
  def main(args: Array[String]) {
    // print println
    print(1)
    println(2)

    // Format print, C Style.
    printf("Hello, %s!\n", "World")

    // readLine readInt readDouble readByte readShort readLong readFloat readBoolean readChar
    // new method: scala.io.StdIn
    // val name = StdIn.readLine("Your name: ")
  }
}

/**
 * Loop Syntax
 */
object Section05 {
  def main(args: Array[String]) {
    // while and do like Java/C++
    var v1 = 1
    while (v1 > 0) {
      v1 -= 1
    }
    do {
      v1 += 1
    } while (v1 != 0)

    // for like Java's foreach
    for (i <- 1 to 10) {}

    // to, until
    (0 to 9)
    (0 until 10)

    // There is no break or continue statement in scala.
    // 1. Boolean value to control;
    // 2. Inner function, to return;
    // 3. Breaks
  }
}

Add Source of "Scala for the Impatient" Chapter2.


package beyond

import java.io.File
import java.net.URLClassLoader
import play.api.Mode

object BeyondRuntime {
  lazy val classPath: String = {
    import play.api.Play.current
    val currentClassLoaderURLs = current.classloader.asInstanceOf[URLClassLoader].getURLs
    val urls = current.mode match {
      case Mode.Dev =>
        val parentURLs = current.classloader.getParent.asInstanceOf[URLClassLoader].getURLs
        currentClassLoaderURLs ++ parentURLs
      case _ =>
        currentClassLoaderURLs
    }
    urls.mkString(File.pathSeparator)
  }
}

Add a method to get the current classpath.

Play framework uses a custom class loader for auto-reloading in development
mode. So in development mode, we must join the class loader with the parent
class loader to get the complete classpath.


object Solution {

  def main(args: Array[String]) {
    val Array(r, c) = readLine.split(" ").map(_.toInt)
    println(10L * ((r - 1) / 2) + ((r - 1) & 1) + 2 * (c - 1))
  }
}

Add solution to strange grid.

Add solution to strange grid.


/* https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited */
package com.negrisoli.algorithms.implementation

object JumpingInTheCloudsRevisited {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val List(n, k) = (0 to 1) map (i => sc.nextInt) toList
    val clouds = (0 to n-1) map (i => sc.nextInt) toList

    println(calcEnergy(k, clouds))
  }

  def calcEnergy(k: Int, clouds: List[Int]): Int = {
    100 - (((0 to clouds.size - 1 by k) count (i => clouds(i) == 1)) * 2 + clouds.size / k)
  }
}

Add jumping in the clouds revisited solution.


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

addSbtPlugin("org.xerial.sbt" % "sbt-pack" % "0.3.1")

addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.2.1")

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

addSbtPlugin("org.xerial.sbt" % "sbt-pack" % "0.3.1")

addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.2.1")

Upgrade to sbt assembly 0.10.1 for speed improvement


package fpinscala

import org.scalatest.FunSuite
import fpinscala.monoids.Monoid._
import fpinscala.testing._

class ch10_MonoidsTests extends FunSuite {

  test("ex 10.1") {
    assert(intAddition.op(1, 2) == 3)
  }

  test("test monoids using laws") {
    Prop.run(monoidLaws(intAddition, Gen.smallInt))
    Prop.run(monoidLaws(intMultiplication, Gen.smallInt))
    Prop.run(monoidLaws(booleanAnd, Gen.boolean))
    Prop.run(monoidLaws(booleanOr, Gen.boolean))
    def optionGen[A](g: Gen[A]): Gen[Option[A]] = g.flatMap(a => Gen.boolean.map(b => if (b) Some(a) else None))
    Prop.run(monoidLaws(optionMonoid[Int], optionGen(Gen.smallInt)))
    // TODO check below property: fails
        def endoGen(g: Gen[Int]): Gen[Int => Int] = g.flatMap { a: Int => Gen.boolean.map(b => if (b) { x: Int => a * x } else { x: Int => a + x }) }
        Prop.run(monoidLaws(endoMonoid[Int], endoGen(Gen.smallInt)))
  }
}

Add test: still one failing

Add test: still one failing


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

import ch.usi.inf.l3.sana
import sana.tiny
import sana.ooj

import tiny.names.Name
import tiny.modifiers.Flags
import tiny.modifiers.Ops.noflags
import tiny.types.Type
import tiny.symbols.{Symbol, TermSymbol, TypeSymbol}
import ooj.symbols.PackageSymbol

object ModuleSymbol {
  private class ModuleSymbolImpl(var name: Name,
    var owner: Option[Symbol]) extends ModuleSymbol

  def apply(name: Name, owner: Option[Symbol]): ModuleSymbol =
    new ModuleSymbolImpl(name, owner)

  def unapply(sym: ModuleSymbol): Option[(Name, Option[Symbol])] = sym match {
    case null              => None
    case _                 => Some((sym.name, sym.owner))
  }
}

trait ModuleSymbol extends PackageSymbol {
  override def qualifiedName: String = name.asString

  override def qualifiedNameAsList: List[Name] = List(name)

  override def equals(other: Any): Boolean = other match {
    case null                 => false
    case that: ModuleSymbol   =>
      this.name == that.name
    case _                    =>
      false
  }

  override def toString(): String = s"Module symbol: $name"
  override def hashCode(): Int = name.hashCode * 43
}

trait TypeDefSymbol extends TypeSymbol {
  def mods: Flags = noflags
  def mods_=(flags: Flags): Unit = ???

  var name: Name
  var typeSymbol: Option[Symbol]
  var owner: Option[Symbol]

  def tpe: Option[Type] = typeSymbol.flatMap(_.tpe)
  def tpe_=(tpe: Option[Type]): Unit = ???

  override def declare(symbol: Symbol): Unit = ???
  override def delete(symbol: Symbol): Unit = ???
  override def defines(symbol: Symbol,
    p: Symbol => Boolean): Boolean =
    typeSymbol.map(_.defines(symbol, p)).getOrElse(false)

  override def getSymbol(name: Name,
    p: Symbol => Boolean): Option[Symbol] = {
    typeSymbol.flatMap(_.getSymbol(name, p))
  }

  override def equals(other: Any): Boolean = other match {
    case null                    => false
    case that: TypeDefSymbol =>
        this.name == that.name &&
        this.owner == that.owner &&
        this.typeSymbol == that.typeSymbol
    case _                    =>
      false
  }
  override def toString(): String = s"TypeDef symbol $name"
  override def hashCode(): Int = name.hashCode * 43 +
    typeSymbol.hashCode * mods.hashCode + 47 * owner.hashCode
}

object TypeDefSymbol {
  private class TypeDefSymbolImpl(var name: Name,
    var typeSymbol: Option[Symbol], var owner: Option[Symbol])
    extends TypeDefSymbol

  def apply(name: Name, typeSymbol: Option[Symbol],
      owner: Option[Symbol]): TypeDefSymbol =
        new TypeDefSymbolImpl(name, typeSymbol, owner)

  def unapply(sym: TypeDefSymbol):
    Option[(Name, Option[Symbol], Option[Symbol])] = sym match {
      case null      => None
      case _         => Some((sym.name, sym.typeSymbol, sym.owner))
    }
}

Add symbol types for both TypeDef and ModuleDef


package com.github.log0ymxm.mapper

import org.scalatest._

class UnionFindSpec extends FunSuite {
  test("union find") {
    val uf = new UnionFind(10)
    assert(uf.nComponents == 10)
    uf.add(1, 2)
    uf.add(2, 3)
    assert(uf.nComponents == 8)
    uf.add(1, 2)
    assert(uf.nComponents == 8)

    assert(uf.connected(1, 3) == true)
    assert(uf.connected(1, 4) == false)
  }
}

Add a union find test

Add a union find test


package io.flow.play.util

import io.flow.common.v0.models.UserReference

object Constants {

  val SystemUser = UserReference("usr-20151006-1")
  val AnonymousUser = UserReference("usr-20151006-2")

}

Move system/anonymous user into a constants object


javacOptions in Compile ++=
  "-source" :: "1.7" ::
    "-target" :: "1.7" ::
    "-g:lines" ::
    Nil

crossPaths in Compile := false

autoScalaLibrary in Compile := false

scalaVersion in Test := "2.11.8"

/**
 * Strict settings to avoid common bugs. Class files are limited in length to support builds on Windows.
 */
scalacOptions in Test ++=
  "-feature" ::
    "-unchecked" ::
    "-deprecation" ::
    "-target:jvm-1.8" ::
    "-Xfatal-warnings" ::
    "-Xmax-classfile-name" :: "150" ::
    Nil

Allow Scala in tests, but exclude it from the main package


package skiis

import java.util.concurrent.Executors

import org.scalatest.WordSpec
import org.scalatest.matchers.ShouldMatchers

import scala.collection._

@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class MergeSuite extends WordSpec with ShouldMatchers {
  import Skiis._

  val r = new scala.util.Random

  def random(n: Int) = math.abs(r.nextInt) % n

  "Skiis" should {
    implicit val context = Skiis.DefaultContext

    val big = new Skiis.Context {
      override val parallelism = 10
      override val queue = 1
      override val batch = 1
      override val executor = Executors.newFixedThreadPool(parallelism)
    }

    // torture-test Skiis.merge()
    for (i <- 1 to 1000) {
      ("merge %d" format i) in {
        val ranges = for (r <- 1 to (random(100) + 10)) yield (1 to (r + random(10000)))
        val skiis = ranges map { r => Skiis.apply(r.iterator) }

        val expectedTotal = ranges map (_.sum) sum

        val merged = Skiis.merge(skiis: _*)

        val actualTotal = new java.util.concurrent.atomic.AtomicInteger()
        val n = new java.util.concurrent.atomic.AtomicInteger()
        merged parForeach { x =>
          if (random(1000) == 0) Thread.sleep(1)
          actualTotal.addAndGet(x)
          n.incrementAndGet()
        }

        actualTotal.get should be === expectedTotal
        println("total adds: " + n.get)
      }
    }
  }
}

Add concurrency torture test for Skiis.merge()


package com.twitter.finagle.stats

/**
 * A StatsReceiver proxy that configures all counters, stats, and gauges marked as KeyIndicators.
 * This is used with [[ReadableIndicator]].
 *
 * @param self The underlying StatsReceiver to which modified schemas are passed
 */
private[finagle] class KeyIndicatorMarkingStatsReceiver(protected val self: StatsReceiver)
    extends StatsReceiverProxy {

  override def counter(counterSchema: CounterSchema): Counter = {
    self.counter(CounterSchema(counterSchema.metricBuilder.withKeyIndicator()))
  }

  override def stat(histogramSchema: HistogramSchema): Stat = {
    self.stat(HistogramSchema(histogramSchema.metricBuilder.withKeyIndicator()))
  }

  override def addGauge(gaugeSchema: GaugeSchema)(f: => Float): Gauge = {
    self.addGauge(GaugeSchema(gaugeSchema.metricBuilder.withKeyIndicator()))(f)
  }
}

finagle-internal/slo: Mark SLIs as key indicators in Metrics Metadata

Problem

The user-defined SLIs in SLO can be seen as more important metrics. And we want
to mark these metrics in the metrics metadata for future usage.

Solution

The `keyIndicator` field is already defined in the MetricBuilder and by default
the value is false.  If a metric is instrumented through SLO indicators, the
`keyIndicator` should be filled as true.  Introduce the
KeyIndicatorMarkingStatsReceiverProxy for this purpose.

JIRA Issues: CSL-9961

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


object test {
  final class HKTVar[+T[_]]

  def foo[F[_], G[_], X](m : HKTVar[G]) = m match {
    case _ : HKTVar[F] =>
      val fx : F[X] = ???
      val gx : G[X] = fx
  }

}

Add pos testcase for HKT GADT orderings

Add pos testcase for HKT GADT orderings


/**
 * Copyright (C) 2012 Typesafe Inc. <http://www.typesafe.com>
 */

package scala.async
package run
package toughtype

import language.{reflectiveCalls, postfixOps}
import scala.concurrent._
import scala.concurrent.duration._
import scala.async.Async._
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

object ToughTypeObject {

  import ExecutionContext.Implicits.global

  class Inner

  def m2 = async[(List[_], ToughTypeObject.Inner)] {
    val y = await(future[List[_]](Nil))
    val z = await(future[Inner](new Inner))
    (y, z)
  }
}

@RunWith(classOf[JUnit4])
class ToughTypeSpec {

  @Test def `propogates tough types`() {
    val fut = ToughTypeObject.m2
    val res: (List[_], scala.async.run.toughtype.ToughTypeObject.Inner) = Await.result(fut, 2 seconds)
    res._1 mustBe (Nil)
  }
}

Test with less trivial types.

Test with less trivial types.

Works like it says on the box.


package org.allenai.common

import java.net.MalformedURLException
import java.net.URL
import scala.util.control.Exception._

/** Util methods for java.net.URL. */
object UrlUtil {
  def parse(url: String): Option[URL] =
    catching(classOf[MalformedURLException]) opt new URL(url)
}

Add a utility to parse String=>Option[URL].


package ch.usi.inf.l3.sana.ppj.ast

import ch.usi.inf.l3.sana
import sana.tiny
import sana.primj
import sana.ooj
import sana.ppj

import tiny.ast.{Tree, Expr}
import primj.ast.{BlockApi}

/********************* AST Nodes *********************************/

trait SynchronizedApi extends Expr {
  def expr:  Expr
  def block: BlockApi

  def bottomUp[R](z: R)(f: (R, Tree) => R): R = {
    val r1 = f(z, expr)
    val r2 = f(r1, block)
    f(r2, this)
  }
}

protected[ast] class Synchronized(val expr: Expr,
    val block: BlockApi) extends SynchronizedApi {
  override def toString: String = s"Synchronized($expr, $block)"
}

Add synchronized ast node for ppj

Add synchronized ast node for ppj


package ch.usi.inf.l3.sana.ppj.typechecker

import ch.usi.inf.l3.sana
import sana.primj
import sana.tiny
import sana.calcj
import sana.brokenj
import sana.arrayj
import sana.ppj
import sana.robustj

import sana.dsl._
import tiny.ast.{Tree, Expr}
import tiny.errors.ErrorReporting.{error,warning}
import tiny.errors.ErrorCodes._
import tiny.ast.Implicits._
import primj.ast.BlockApi
import brokenj.typechecker.LabelNameCheckerComponent
import ppj.ast.TreeUtils
import ppj.ast._

@component(tree, labelNames)
trait SynchronizedLabelNameCheckerComponent
  extends LabelNameCheckerComponent {
  (sync: SynchronizedApi)     => {
    check((sync.expr, labelNames))
    check((sync.block, labelNames))
  }
}

Add label checkers for synchronized blocks


package spire.random

import java.nio.ByteBuffer
import java.util.Arrays
import java.security.SecureRandom

class SecureJava(rand: SecureRandom) extends IntBasedGenerator {
  def copy: SecureJava = new SecureJava(rand)

  def getSeedBytes: Array[Byte] =
    throw new UnsupportedOperationException("getSeedBytes")

  def setSeedBytes(bytes: Array[Byte]): Unit =
    throw new UnsupportedOperationException("setSeedBytes")

  def nextInt(): Int = rand.nextInt()
}

object SecureJava {
  def fromBytes(bytes: Array[Byte]): SecureJava =
    new SecureJava(new SecureRandom(bytes))

  def apply(): SecureJava =
    new SecureJava(new SecureRandom())
}

Add Generator for Java's cryptographic RNG


/*
 * Telefónica Digital - Product Development and Innovation
 *
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
 * All rights reserved.
 */

package es.tid.cosmos.admin

import org.scalatest.FlatSpec
import org.scalatest.matchers.MustMatchers
import org.scalatest.mock.MockitoSugar
import scala.concurrent._
import ExecutionContext.Implicits.global

class UtilTest extends FlatSpec with MustMatchers with MockitoSugar {

  "The waitUntilReady method" must "wait for the future to finish successfully" in {
    Util.waitUntilReady(Future { Thread.sleep(2000) }) must be (true)
  }

  "it" must "wait for the future to finish with error" in {
    Util.waitUntilReady(Future { Thread.sleep(2000); throw new Exception("foo") }) must be (false)
  }
}

Add unit tests for Util.waitUntilReady

Add unit tests for Util.waitUntilReady


package scala.xml

import org.junit.Test

class BillionLaughsAttackTest {

  /**
   * org.xml.sax.SAXParseException: JAXP00010001: The parser has
   * encountered more than "64000" entity expansions in this document;
   * this is the limit imposed by the JDK.
   */
  @Test(expected=classOf[org.xml.sax.SAXParseException])
  def lolzTest: Unit = {
    XML.loadString(lolz)
  }

  // Copied from https://msdn.microsoft.com/en-us/magazine/ee335713.aspx
  val lolz =
    """<?xml version="1.0"?>
      |<!DOCTYPE lolz [
      | <!ENTITY lol "lol">
      | <!ELEMENT lolz (#PCDATA)>
      | <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
      | <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
      | <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
      | <!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;">
      | <!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;">
      | <!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;">
      | <!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;">
      | <!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;">
      | <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
      |]>
      |<lolz>&lol9;</lolz>
      |""".stripMargin

}

Add billion laughs attack to test suite

Add billion laughs attack to test suite


object Solution {

  def productSumNumber(n: Int): Long = {
    // For k size product sum, the minimal n will be greater than k as there are
    // k integers. The max will be less than 2 * k as we can {2, k} and k -2
    // ones to get 2 * k
    val kmax = n
    val result = Array.fill(kmax + 1)(2 * kmax)

    def prodSumHelper(prod: Int, sum: Int, c: Int, start: Int) {
      val k = prod - sum + c // product - sum + number of factors
      if (k <= kmax) {
        if (prod < result(k)) result(k) = prod
        for (i <- start to kmax/prod * 2)
          prodSumHelper(prod * i, sum + i, c + 1, i)
      }
    }

    prodSumHelper(1, 1, 1, 2)
    result.slice(2, n + 1).toSet.foldLeft(0L) { _ + _ }
  }

  def main(args: Array[String]) {
    val n = readInt
    print(productSumNumber(n))
  }
}

Add solution to problem 88

Add solution to problem 88


package coursier.test

import java.util.concurrent.ConcurrentHashMap

import coursier.{Fetch, Module}
import coursier.core.ResolutionProcess
import utest._

import scala.collection.JavaConverters._
import scala.concurrent.duration.DurationInt
import scalaz.{-\/, \/-}
import scalaz.concurrent.Task

object ResolutionProcessTests extends TestSuite {

  val tests = TestSuite {

    'fetchAll - {

      // check that tasks fetching different versions of the same module are spawned sequentially
      // rather than all at once
      def check(extra: Int): Unit = {

        val mod = Module("org", "name")
        val modVers = (1 to (9 + extra))
          .map(_.toString)
          .map((mod, _))

        val called = new ConcurrentHashMap[String, Unit]

        val fetch: Fetch.Metadata[Task] = {

          case Seq((`mod`, "9")) =>
            // never calls the callback
            Task.async { _ =>
              called.put("9", ())
              ()
            }

          case Seq(mv @ (`mod`, v)) =>
            Task.async { cb =>
              called.put(v, ())
              cb(\/-(Seq((mv, -\/(Seq("w/e"))))))
            }

          case _ => sys.error(s"Cannot happen ($modVers)")
        }

        val res = ResolutionProcess.fetchAll(modVers, fetch)
          .timed(1.second)
          .attempt
          .unsafePerformSync

        // must have timed out
        assert(res.swap.exists[Throwable] { case _: java.util.concurrent.TimeoutException => true; case _ => false })

        val called0 = called.asScala.iterator.map(_._1).toSet
        val expectedCalled = (0 to extra)
          .map(9 + _)
          .map(_.toString)
          .toSet
        assert(called0 == expectedCalled)
      }

      * - check(0)
      * - check(1)
      * - check(3)
    }

  }

}

Add small test of the code ensuring a module isn't fetched concurrently twice


package ch.usi.inf.l3.sana.dynj.ast

import ch.usi.inf.l3.sana.calcj
import calcj.ast.operators.BOp

trait operators extends calcj.ast.operators {
  object IsInstanceOf extends BOp {
    override def toString: String = "isinstanceof"
  }
}

object operators extends operators

Add isinstanceof operator to dynj

Add isinstanceof operator to dynj


package dataframe

import org.apache.spark.sql.{Column, SQLContext}
import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.sql.functions._

//
// Transform a single column of a DataFrame using a UDF
//
object Transform {

  private case class Cust(id: Integer, name: String, sales: Double, discounts: Double, state: String)

  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("DataFrame-Transform").setMaster("local[4]")
    val sc = new SparkContext(conf)
    val sqlContext = new SQLContext(sc)

    import sqlContext.implicits._

    // create an RDD with some data
    val custs = Seq(
      Cust(1, "Widget Co", 120000.00, 0.00, "AZ"),
      Cust(2, "Acme Widgets", 410500.00, 500.00, "CA"),
      Cust(3, "Widgetry", 410500.00, 200.00, "CA"),
      Cust(4, "Widgets R Us", 410500.00, 0.0, "CA"),
      Cust(5, "Ye Olde Widgete", 500.00, 0.0, "MA")
    )
    val customerDF = sc.parallelize(custs, 4).toDF()

    // the original UDF
    customerDF.show()

    // a trivial UDF
    val myFunc = udf {(x: Double) => x + 1}

    // get the columns, having applied the UDF to the "discount" column and leaving the others as they were
    val colNames = customerDF.columns
    val cols = colNames.map(cName => customerDF.col(cName))
    val mappedCols = cols.map(c => if (c.toString() == "discounts") myFunc(c) else c)

    // use select() to produce the new DataFrame
    val newDF = customerDF.select(mappedCols:_*)
    newDF.show()

  }

}

Add an example of transforming a DataFrame


package opencl.generator

import org.junit.{BeforeClass, AfterClass, Test}
import org.junit.Assert.assertArrayEquals

import benchmarks.DbSelect
import opencl.executor.{Executor, Execute}

object TestDbSelect {
  @BeforeClass def before(): Unit = {
    Executor.loadLibrary()
    println("Initialize the executor")
    Executor.init()
  }

  @AfterClass def after(): Unit = {
    println("Shutdown the executor")
    Executor.shutdown()
  }
}

class TestDbSelect {
  // As long as junit is not able to compare of objects of type
  // Array[(Int, Int, Int)], we flatten them.
  private def goldSelect(colA: Array[Int],
                         colB: Array[Int],
                         colC: Array[Int]): Array[Int] =
    Array(
      colC.map(n => if (n == 1) 1 else 0),
      colA,
      colB
    ).transpose.flatten

  @Test def testNaive(): Unit = {
    val inputSize = 1024
    val colA = Array.fill(inputSize)(util.Random.nextInt(5))
    val colB = Array.fill(inputSize)(util.Random.nextInt(5))
    val colC = Array.fill(inputSize)(util.Random.nextInt(5))

    val (output: Array[Int], runtime) = Execute(inputSize)(
      DbSelect.naive, colA, colB, colC
    )

    println(s"Runtime: $runtime")

    assertArrayEquals(goldSelect(colA, colB, colC), output)
  }

  @Test def testDivideNConquer(): Unit = {
    val inputSize = 1024
    val colA = Array.fill(inputSize)(util.Random.nextInt(5))
    val colB = Array.fill(inputSize)(util.Random.nextInt(5))
    val colC = Array.fill(inputSize)(util.Random.nextInt(5))

    val (output: Array[Int], runtime) = Execute(inputSize)(
      DbSelect.divideNConquer, colA, colB, colC
    )

    println(s"Runtime: $runtime")

    assertArrayEquals(goldSelect(colA, colB, colC), output)
  }
}

Add tests for the DbSelect benchmark

Add tests for the DbSelect benchmark


package com.redislabs.provider.redis.df

import com.redislabs.provider.redis.env.RedisClusterEnv
import com.redislabs.provider.redis.util.Person
import org.apache.spark.rdd.RDD

/**
  * @author The Viet Nguyen
  */
trait ManyValueBenchmarkSuite extends DataframeBenchmarkSuite with RedisClusterEnv {

  private def num = 800000

  override def suiteTags: String = s"${super.suiteTags}, Many:$num"

  override def rdd(): RDD[Person] = {
    val partitionsNum = 8
    val sectionLength = num / partitionsNum
    spark.sparkContext
      .parallelize(0 until partitionsNum, partitionsNum)
      .mapPartitions {
        _
          .flatMap { i =>
            val start = i * sectionLength
            val end = start + sectionLength + 1
            Stream.range(start, end)
          }
          .map { i =>
            Person(s"John-$i", 30, "60 Wall Street", 150.5)
          }
      }
  }
}

Create base dataframe benchmark suite for multiple elements


package org.jetbrains.bsp.protocol.session

import java.util.concurrent.CompletableFuture

/**
 * JDK's CompletableFuture does not handle cancellation well.
 * When a future overrides a `cancel` method, it is lost
 * when doing transformations like `thenApply` or `thenCompose`.
 *
 * In Java 9, the new CompletableFuture's method was introduced: `newIncompleteFuture`.
 * When using it, the cancel method of the original future will be called event when the
 * `cancel` is done on a transformed one.
 *
 * When we know about CompletableFutures that override `cancel` methods, we should convert them
 * to CancellableFuture before calling methods like `thenCompose`
 *
 * @param original
 */
class CancellableFuture[T](original: CompletableFuture[_]) extends CompletableFuture[T] {
  override def cancel(mayInterruptIfRunning: Boolean): Boolean = {
    original.cancel(mayInterruptIfRunning)
    super.cancel(mayInterruptIfRunning)
  }

  def newIncompleteFuture[U](): CompletableFuture[U] = {
    new CancellableFuture(original)
  }
}

object CancellableFuture {
  def from[T](original: CompletableFuture[T]): CancellableFuture[T] = {
    val result = new CancellableFuture[T](original)
    original.whenComplete{ (value, error) =>
      if (error != null) {
        result.completeExceptionally(error)
      }
      else {
        result.complete(value)
      }
      ()
    }
    result
  }
}

Revert "static factory method replaced with a plain constructor call, newIncompleteFuture commented out until Java 9"

This reverts commit e0c4e0ac5afd29756f5c81782b0d8d4b0e84fae8.

(cherry picked from commit b70fe2c5013bc86b5ca65515ce527335e004b096)


object Solution {
  import scala.annotation.tailrec

  @tailrec
  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  def generateList(nums: IndexedSeq[Int]): IndexedSeq[Int] = {
    val paddedList = 1 +: nums :+ 1
    for (i <- 1 until paddedList.size) yield {
      val (x, y) = (paddedList(i), paddedList(i - 1))
      x * y / gcd(x, y)
    }
  }

  def main(args: Array[String]) {
    for (_ <- 1 to readInt) {
      val n = readInt
      val nums = readLine.split(" ").map(_.toInt)
      println(generateList(nums).mkString(" "))
    }
  }
}

Add solution to problem John and GCD list


package uk.ac.wellcome.platform.archive.common.models
import org.scalatest.FunSpec
import uk.ac.wellcome.json.JsonUtil._
import uk.ac.wellcome.json.utils.JsonAssertions

class BagIdTest extends FunSpec with JsonAssertions {
  it("serialises with strings") {
    val bagId = BagId(StorageSpace("digitised"), ExternalIdentifier("b1234567x"))
    val expectedJson =
      s"""
         |{
         |  "space": "digitised",
         |  "externalIdentifier": "b1234567x"
         |}
       """.stripMargin
    assertJsonStringsAreEqual(toJson(bagId).get, expectedJson)
  }

}

Test that bagId gets serialised correctly


package ch.usi.inf.l3.sana.ppj.ast

import ch.usi.inf.l3.sana
import sana.tiny
import sana.calcj
import sana.primj
import sana.brokenj
import sana.ooj
import sana.arrayj
import sana.arrooj
import sana.robustj
import sana.dynj
import sana.ppj

import tiny.ast.Tree

trait TreeUtils extends robustj.ast.TreeUtils {
  override def isValidStatement(e: Tree): Boolean = e match {
    case _: SynchronizedApi => true
    case _                  => super.isValidStatement(e)
  }

  override def allPathsReturn(expr: Tree): Boolean = expr match {
    case s: SynchronizedApi => allPathsReturn(s.block)
    case _                  => super.allPathsReturn(expr)
  }

  override def isSimpleExpression(tree: Tree): Boolean = tree match {
    case _: SynchronizedApi => false
    case _                  => super.isSimpleExpression(tree)
  }

  override def canHaveLabel(tree: Tree): Boolean = tree match {
    case _: SynchronizedApi => true
    case _                  => super.isValidStatement(tree)
  }
}

object TreeUtils extends TreeUtils

Make synchronized block a statement

Make synchronized block a statement


package nl.tudelft.graphalytics.graphx.evo

import java.util
import java.lang.{Long => JLong}

import nl.tudelft.graphalytics.domain.GraphFormat
import nl.tudelft.graphalytics.domain.algorithms.ForestFireModelParameters
import nl.tudelft.graphalytics.graphx.{ValidationGraphUtils, GraphXJobTest}
import nl.tudelft.graphalytics.validation.GraphStructure
import nl.tudelft.graphalytics.validation.evo.ForestFireModelValidationTest

/**
 * Integration test for Forest Fire Model job on GraphX.
 *
 * @author Tim Hegeman
 */
class ForestFireModelJobTest extends ForestFireModelValidationTest with GraphXJobTest {

	override def executeDirectedForestFireModel(graph : GraphStructure, parameters : ForestFireModelParameters)
	: GraphStructure = {
		val (vertexData, edgeData) = ValidationGraphUtils.directedValidationGraphToEdgeList(graph)
		executeForestFireModel(vertexData, edgeData, true, parameters)
	}

	override def executeUndirectedForestFireModel(graph : GraphStructure, parameters : ForestFireModelParameters)
	: GraphStructure = {
		val (vertexData, edgeData) = ValidationGraphUtils.undirectedValidationGraphToEdgeList(graph)
		executeForestFireModel(vertexData, edgeData, false, parameters)
	}

	private def executeForestFireModel(vertexData : List[String], edgeData : List[String], directed : Boolean,
			parameters : ForestFireModelParameters) : GraphStructure = {
		val ffmJob = new ForestFireModelJob("", "", new GraphFormat(directed), "", parameters)
		val (vertexOutput, edgeOutput) = executeJob(ffmJob, vertexData, edgeData)
		val edgeLists = new util.HashMap[JLong, util.Set[JLong]]()
		vertexOutput.foreach { case (vid, _) => edgeLists.put(vid, new util.HashSet[JLong]())}
		edgeOutput.foreach { case (from, to) => edgeLists.get(from).add(to) }
		new GraphStructure(edgeLists)
	}

}

Add Forest Fire Model test

Add Forest Fire Model test


package com.tristanpenman.chordial.dht

import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestKit}
import org.scalatest._

import scala.concurrent.duration.DurationInt

final class CoordinatorSpec extends TestKit(ActorSystem("CoordinatorSpec")) with WordSpecLike with ImplicitSender {

  // Time to wait before concluding that no additional messages will be received
  private val spuriousMessageDuration = 150.milliseconds

  // Limit size of keyspace / number of nodes to 2^3 == 8
  private val keyspaceBits = 3

  "A Coordinator actor" when {
    "initially constructed" should {
      def coordinator = system.actorOf(Coordinator.props(keyspaceBits, "0.0.0.0", 0, None))

      "not crash when it receives messages" in {
        coordinator ! "Test"
        expectNoMessage(spuriousMessageDuration)
      }
    }
  }
}

Add placeholder test suite for Coordinator


object Solution {

  def theBeastOfN(n: Int): String = {
    var numOf3 = 0
    var numOf5 = n - numOf3
    while (numOf3 <= n) {
      numOf5 = n - numOf3
      if (numOf5 % 3 == 0) return "5" * numOf5 + "3" * numOf3
      numOf3 += 5
    }
    "-1"
  }

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

Add solution to problem Sherlock and The Beast.


package slick.osgi.test

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert._
import org.ops4j.pax.exam
import org.ops4j.pax.exam.junit.{Configuration, ExamReactorStrategy, JUnit4TestRunner}
import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory
import slick.SlickException
import slick.osgi.testutil._

@RunWith(classOf[JUnit4TestRunner])
@ExamReactorStrategy(Array(classOf[AllConfinedStagedReactorFactory]))
class BasicTest extends SlickOsgiHelper {

  @Configuration
  def config(): Array[exam.Option] = {
    standardOptions
  }

  @Test
  def testPlainSQL: Unit = {
    import slick.jdbc.JdbcBackend._
    import slick.jdbc.StaticQuery.interpolation
    Database.forURL("jdbc:h2:mem:test-osgi") withSession { implicit session =>
      assertEquals("TEST-OSGI", sql"select {fn database()}".as[String].first)
    }
  }
}

package slick.osgi.test

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert._
import org.ops4j.pax.exam
import org.ops4j.pax.exam.junit.{Configuration, ExamReactorStrategy, JUnit4TestRunner}
import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory
import slick.SlickException
import slick.osgi.testutil._
import slick.util.GlobalConfig

@RunWith(classOf[JUnit4TestRunner])
@ExamReactorStrategy(Array(classOf[AllConfinedStagedReactorFactory]))
class BasicTest extends SlickOsgiHelper {

  @Configuration
  def config(): Array[exam.Option] = {
    standardOptions
  }

  @Test
  def testPlainSQL: Unit = {
    import slick.jdbc.JdbcBackend._
    import slick.jdbc.StaticQuery.interpolation
    Database.forURL("jdbc:h2:mem:test-osgi") withSession { implicit session =>
      assertEquals("TEST-OSGI", sql"select {fn database()}".as[String].first)
    }
  }
  @Test
  def testConfig: Unit = {
    assertFalse(GlobalConfig.driverConfig("MySQL").isEmpty)
  }
}

Add test for resolving reference.conf in OSGi context


package com.negrisoli.algorithms.implementation

object SherlockAndSquares {

  def main(args:Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val nTests = sc.nextInt()
    for (i <- 0 to nTests-1) {
      val begin = sc.nextInt()
      val end = sc.nextInt()

      var i =  math.sqrt(begin).ceil.toInt
      var j =  math.sqrt(end).floor.toInt
      printf("%d\n", j - i + 1)
    }
  }

}

Add sherlock and squares solution.

Add sherlock and squares solution.


package com.tristanpenman.chordial.core.algorithms

import akka.actor.{Actor, ActorSystem}
import akka.testkit.{ImplicitSender, TestActorRef, TestKit}
import akka.util.Timeout
import com.tristanpenman.chordial.core.Node.{Notify, NotifyOk}
import com.tristanpenman.chordial.core.Pointers
import com.tristanpenman.chordial.core.Pointers.{GetPredecessor, GetPredecessorOk, GetSuccessorList, GetSuccessorListOk}
import com.tristanpenman.chordial.core.algorithms.StabilisationAlgorithm.{StabilisationAlgorithmFinished, StabilisationAlgorithmStart}
import com.tristanpenman.chordial.core.shared.NodeInfo
import org.scalatest.WordSpecLike

import scala.concurrent.duration._
import scala.language.postfixOps

class StabilisationAlgorithmSpec
  extends TestKit(ActorSystem("StabilisationAlgorithmSpec")) with WordSpecLike with ImplicitSender {

  private val keyspaceBits = 3

  // Timeout for requests performed within CheckPredecessorAlgorithm actor
  private val algorithmTimeout = Timeout(300.milliseconds)

  // Time to wait before concluding that no additional messages will be received
  private val spuriousMessageDuration = 150.milliseconds

  val nodeRef = TestActorRef(new Actor {
    override def receive: Receive = {
      case GetPredecessor() =>
        sender() ! GetPredecessorOk(NodeInfo(1L, self))
      case GetSuccessorList() =>
        sender() ! GetSuccessorListOk(NodeInfo(1L, self), List.empty)
      case Notify(_, _) =>
        sender() ! NotifyOk()
      case m =>
        fail(s"Stub Node actor received an unexpected message of type: ${m.getClass})")
    }
  })

  val pointersRef = system.actorOf(Pointers.props(1L, keyspaceBits, NodeInfo(1L, nodeRef), system.eventStream))

  val algorithm = system.actorOf(
    StabilisationAlgorithm.props(NodeInfo(1L, nodeRef), pointersRef, algorithmTimeout))

  "A StabilisationAlgorithm actor" when {
    "initialised with a Pointers actor for a node that is its own successor" should {
      "finish successfully without sending any further messages" in {
        algorithm ! StabilisationAlgorithmStart()
        expectMsg(StabilisationAlgorithmFinished())
        expectNoMsg(spuriousMessageDuration)
      }
    }
  }
}

Add a simple test case for the StablisationAlgorithm class


package quasar.project

object Versions {
  val algebraVersion      = "1.0.1"
  val argonautVersion     = "6.2.3"
  val catsEffectVersion   = "1.3.0"
  val disciplineVersion   = "0.7.2"
  val jawnVersion         = "0.14.1"
  val jawnfs2Version      = "0.14.2"
  val matryoshkaVersion   = "0.18.3"
  val monocleVersion      = "1.5.0"
  val pathyVersion        = "0.2.13"
  val refinedVersion      = "0.8.7"
  val scodecBitsVersion   = "1.1.2"
  val scalacheckVersion   = "1.14.0"
  val scalazVersion       = "7.2.27"
  val scalazStreamVersion = "0.8.6a"
  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.2"
  val slf4sVersion        = "1.7.25"
}

package quasar.project

object Versions {
  val algebraVersion      = "1.0.1"
  val argonautVersion     = "6.2.3"
  val catsEffectVersion   = "1.3.0"
  val disciplineVersion   = "0.7.2"
  val jawnVersion         = "0.14.1"
  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 scalazStreamVersion = "0.8.6a"
  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.2"
  val slf4sVersion        = "1.7.25"
}

Update refined, refined-scalacheck, ... to 0.9.5