name := "sphere-sunrise"

organization := "io.sphere"

version := "1.0-SNAPSHOT"

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

scalaVersion := "2.11.6"

javacOptions ++= Seq("-source", "1.8", "-target", "1.8")

resolvers += Resolver.sonatypeRepo("snapshots")

resolvers += Resolver.sonatypeRepo("releases")

val jvmSdkVersion = "1.0.0-M13"

libraryDependencies ++=
  ("io.sphere.sdk.jvm" % "sphere-models" % jvmSdkVersion withSources()) ::
  "io.sphere.sdk.jvm" %% "sphere-play-2_4-java-client" % jvmSdkVersion ::
  "com.google.inject" % "guice" % "3.0" ::
  "org.easytesting" % "fest-assert" % "1.4" % "test" ::
  Nil

dependencyOverrides += ("com.typesafe.play" %% "play-omnidoc" % "2.4.0-M3")

javaUnidocSettings

name := "sphere-sunrise"

organization := "io.sphere"

version := "1.0-SNAPSHOT"

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

scalaVersion := "2.11.6"

javacOptions ++= Seq("-source", "1.8", "-target", "1.8")

resolvers += Resolver.sonatypeRepo("snapshots")

resolvers += Resolver.sonatypeRepo("releases")

val jvmSdkVersion = "1.0.0-M13"

libraryDependencies ++=
  ("io.sphere.sdk.jvm" % "sphere-models" % jvmSdkVersion withSources()) ::
  "io.sphere.sdk.jvm" %% "sphere-play-2_4-java-client" % jvmSdkVersion ::
  "com.google.inject" % "guice" % "3.0" ::
  "org.easytesting" % "fest-assert" % "1.4" % "test" ::
  "com.typesafe.netty" % "netty-http-pipelining" % "1.1.4" ::
  Nil

dependencyOverrides += ("com.typesafe.play" %% "play-omnidoc" % "2.4.0-M3")

javaUnidocSettings

Add explicit dependency for "com.typesafe.netty" % "netty-http-pipelining" % "1.1.4" since travis cannot found version 1.1.2.


class I {
  object A1
  object A2
  object A3
  object A4
  object A5
  object A6
  object A7
  object A8
  object A9
  object A10
  object A11
  object A12
  object A13
  object A14
  object A15
  object A16
  object A17
  object A18
}

object Test {
  def main(args: Array[String]): Unit = {
    val c = new I
    import c._
    val l1 = List(A1,
		  A2,
		  A3,
                  A4,
                  A5,
                  A6,
                  A7,
                  A8,
                  A9,
                  A10,
                  A11,
                  A12,
                  A13,
                  A14,
                  A15,
                  A16,
                  A17,
                  A18)
    val l2 = List(A1,
		  A2,
		  A3,
                  A4,
                  A5,
                  A6,
                  A7,
                  A8,
                  A9,
                  A10,
                  A11,
                  A12,
                  A13,
                  A14,
                  A15,
                  A16,
                  A17,
                  A18)
    assert(l1.mkString == l2.mkString)
    assert(!l1.contains(null))
  }
}

Test that more than 16 lazy vals can be safely used in one object.


package spire.math.interval

import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{Matchers, PropSpec}
import spire.laws.arb._
import spire.syntax.eq._
import spire.math.Rational

class BoundTest extends PropSpec with Matchers with GeneratorDrivenPropertyChecks {

  property("Bound equality") {
    forAll { (x: Rational, y: Rational) =>
      whenever(x =!= y) {
        import spire.algebra.Eq

        val eq = Eq[Bound[Rational]]

        eq.eqv(EmptyBound(), EmptyBound()) shouldBe true
        eq.eqv(Unbound(), Unbound()) shouldBe true

        eq.eqv(Open(x), Open(x)) shouldBe true
        eq.eqv(Open(x), Open(y)) shouldBe false

        eq.eqv(Closed(x), Closed(x)) shouldBe true
        eq.eqv(Closed(x), Closed(y)) shouldBe false
      }
    }
  }
}

Add test for Bound Eq instance

Add test for Bound Eq instance


/**
 *
 * ByteReader
 * Ledger wallet
 *
 * Created by Pierre Pollastri on 19/10/15.
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Ledger
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */
package co.ledger.wallet.utils

import java.math.BigInteger
import java.nio.charset.Charset

class ByteReader(val bytes: Array[Byte]) {

  private[this] var _offset = 0

  def read(length: Int): Array[Byte]  = {
    if (length > available) {
      throw new IndexOutOfBoundsException(s"Invalid length ($length) is greater than available byte to read ($available)")
    }
    val offset = _offset
    _offset = offset + (if (length >= 0) length else available)
    bytes.slice(offset, _offset)
  }

  def readString(length: Int, charset: Charset = Charset.defaultCharset()): String = {
    new String(read(length), charset)
  }

  def readBigInteger(length: Int, signum: Int = 1): BigInteger = {
    new BigInteger(1, read(length))
  }
  def readNextInt(): Int = readBigInteger(4).intValue()
  def readNextLong(): Long = readBigInteger(8).longValue()

  def readLeBigInteger(length: Int, signum: Int = 1): BigInteger = {
    new BigInteger(1, read(length).reverse)
  }
  def readNextLeInt(): Int = readLeBigInteger(4).intValue()
  def readNextLeLong(): Long = readLeBigInteger(8).longValue()

  def available: Int = bytes.length - _offset
  def length: Int = bytes.length
}

Add byte reader for easy bytes array parsing


package lore.types

abstract class BasicType(name: String) extends Type {
  override def isAbstract: Boolean = false
  override def toString: String = name
}

object BasicType {
  case object Real extends BasicType("Real")
  case object Int extends BasicType("Int")
  case object Boolean extends BasicType("Boolean")
  case object String extends BasicType("String")
}

Add basic types: Real, Int, Boolean, String.


package com.ataraxer.zooowner

import akka.actor.ActorSystem
import akka.testkit.{TestKit, TestActorRef, TestProbe, ImplicitSender}

import com.ataraxer.test.UnitSpec
import com.ataraxer.zooowner.message._

import org.apache.curator.test.TestingServer

import org.scalatest.concurrent.Eventually

import scala.concurrent.duration._

object ZooownerActorSpec {
  val port = 9181
  val zkAddress = "localhost:%d".format(port)
}

class ZooownerActorSpec(_system: ActorSystem)
    extends TestKit(_system)
    with ImplicitSender
    with Eventually
    with UnitSpec
{
  import ZooownerSpec._

  def this() = this { ActorSystem("zooowner-actor-spec") }

  var zkServer: TestingServer = null
  var zk: TestActorRef[ZooownerActor] = null

  before {
    zkServer = new TestingServer(port)
    zk = TestActorRef {
      new ZooownerActor(zkAddress, 15.seconds, "prefix")
    }
    eventually { zk.underlyingActor.zk.isConnected should be (true) }
  }

  after {
    val probe = TestProbe()
    probe watch zk
    system stop zk
    probe expectTerminated zk
  }

  "ZooownerActor" should "create nodes with paths asynchronously" in {
    zk ! Create("foo", Some("value"))
    expectMsg { NodeCreated("/prefix/foo", None) }
  }
}

// vim: set ts=2 sw=2 et:

Add test for actor-based API's Create message


import sbt._
object Dependencies {

  object Versions {
    val akka = "2.4.1"
    val akkaStream = "2.0.2"
    val scalatest = "3.0.0-M10"
    val upickle = "0.3.6"
  }

  val upickle = "com.lihaoyi" %% "upickle" % Versions.upickle
  val akkaActor = "com.typesafe.akka" %% "akka-actor" % Versions.akka
  val akkaStream = "com.typesafe.akka" %% "akka-stream-experimental" % Versions.akkaStream
  val akkaHttpCore = "com.typesafe.akka" %% "akka-http-core-experimental" % Versions.akkaStream
  val akkaHttp = "com.typesafe.akka" %% "akka-http-experimental" % Versions.akkaStream
  val akkaHttpTestkit = "com.typesafe.akka" %% "akka-http-testkit-experimental" % Versions.akkaStream
  val scalatest = "org.scalatest" %% "scalatest" % Versions.scalatest % "test"

  val backend = Seq(upickle, akkaActor, akkaStream, akkaHttp, scalatest)

}

Move backend dependencies to object

Move backend dependencies to object


package edu.nus.systemtesting.hg

import scala.sys.process.Process
import java.io.File
import edu.nus.systemtesting.Runnable

/**
 * For modelling non-destructive mercurial commands on a repository.
 * @author richardg
 */
class Repository(dir : String) {
  val repoDir = new File(dir)

  /**
   * Creates a copy of some revision of the repo at some `dest`.
   * (Latest revision if `rev` is `None`).
   */
  def archive(dest : String, rev : Option[String]) : Boolean = {
    val cmd = "hg archive" + s"${rev.map(r => s" -r $r").getOrElse("")} $dest"
    val proc = Process(cmd, repoDir)

    println(s"Exporting archive of $dir to $dest " +
            s"(${rev.map(r => "Revision " + r).getOrElse("Current revision")})")
    val execOutp = Runnable.executeProc(proc)

    // for now, let's not deal with errors
    execOutp.exitValue != 0
  }

  def identify(rev : Option[String] = None) : String = {
    val cmd = "hg identify -i" + rev.map(r => s" -r $r").getOrElse("")
    val proc = Process(cmd, repoDir)

    val execOutp = Runnable.executeProc(proc)

    execOutp.output.trim()
  }

  def isDirty() : Boolean = {
    val hash = identify()
    hash.endsWith("+")
  }

  def status() : Iterable[(String, String)] = {
    /* Recall, from `hg help status`
     M = modified
     A = added
     R = removed
     C = clean
     ! = missing (deleted by non-hg command, but still tracked)
     ? = not tracked
     I = ignored
       = origin of the previous file listed as A (added)
     */

    val cmd = s"hg status"
    val proc = Process(cmd, repoDir)

    val execOutp = Runnable.executeProc(proc)

    // for now, let's not deal with errors
    execOutp.stdoutLines.map(line => {
      // line is like
      //   "? file.txt"
      val parts = line.split(" ", 2)
      (parts(0), parts(1))
    })
  }
}

Add representation of Hg repo

Add representation of Hg repo


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

package com.johnsnowlabs.ml.tensorflow.io

import java.io.{BufferedOutputStream, FileInputStream, FileOutputStream, IOException}
import java.nio.file.Path
import scala.collection.mutable.ArrayBuffer

object ChunkBytes {

  /**
   * readFileInByteChunks will read a file by chuning the size of BufferSize and return array of arrays of Byte
   *
   * @param inputPath the path to an input file
   * @param BuferSize the size of bytes in each chunk
   * @return Array of Arrays of Byte
   */
  def readFileInByteChunks(inputPath: Path, BufferSize: Int = 1024 * 1024): Array[Array[Byte]] = {

    val varBytes = ArrayBuffer.empty[Array[Byte]]
    val fis = new FileInputStream(inputPath.toString)
    var buffer = new Array[Byte](BufferSize)

    var read = fis.read(buffer)

    while (read > -1) {
      varBytes.append(buffer)
      buffer = new Array[Byte](BufferSize)
      read = fis.read(buffer)
    }
    fis.close()
    varBytes.toArray
  }

  /**
   * writeByteChunksInFile will write chunks of bytes into a file
   *
   * @param outputPath the path to an output file
   * @param chunkBytes the array containing chunks of bytes
   */
  def writeByteChunksInFile(outputPath: Path, chunkBytes: Array[Array[Byte]]): Unit = {

    try {
      val out = new BufferedOutputStream(new FileOutputStream(outputPath.toString))
      var count = 0

      while (count < chunkBytes.length) {
        val bytes = chunkBytes(count)
        out.write(bytes, 0, bytes.length)
        count += 1
      }
      out.close()
    }
    catch {
      case e: IOException =>
        e.printStackTrace()
    }
  }

}

Implement chunking in read and write [skip test]


object Solution {
  import scala.annotation.tailrec

  @tailrec
  def gcd(m: Int, n: Int): Int = if (n == 0) m else gcd(n, m % n)

  def generateNumbers(x: Int): IndexedSeq[Int] = {
    val triangles = Array.fill(x + 1)(0)
    val mLimit = math.sqrt(x / 2).toInt
    for {
      m <- 2 to mLimit
      n <- (m & 1) + 1 until m by 2
      if gcd(m, n) == 1
    } {
      val a = m * m + n * n
      val b = m * m - n * n
      val c = 2 * m * n
      println(m, n)
      println(a, b, c)
      val p = a + b + c
      for (j <- p to x by p) triangles(j) += 1
    }

    var count = 0
    for (i <- 0 to x) yield {
      if (triangles(i) == 1) count += 1
      count
    }
  }

  def main(args: Array[String]) {
    val t = readInt
    val tcs = (1 to t).map(x => readInt)
    val result = generateNumbers(tcs.max)
    for (t <- tcs) {
      println(result(t))
    }
  }
}

Add solution to problem 75

Add solution to problem 75


package ingraph.sandbox

import java.net.URI
import java.util.concurrent.atomic.AtomicLong

import org.apache.spark.sql.catalyst.{InternalRow, SQLBuilder}
import org.apache.spark.sql.catalyst.analysis.{Analyzer, FunctionRegistry}
import org.apache.spark.sql.catalyst.catalog.{CatalogDatabase, InMemoryCatalog, SessionCatalog}
import org.apache.spark.sql.catalyst.expressions.AttributeReference
import org.apache.spark.sql.catalyst.plans.logical.LocalRelation
import org.apache.spark.sql.execution.SparkSqlParser
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{IntegerType, StringType}
import org.scalatest.FunSuite

import scala.collection.mutable

class ResolutionTest extends FunSuite {

  test("Observe what happens during query resolution") {
    val originalSql = "SELECT y AS z FROM (SELECT x AS y FROM t)"

    val conf = new SQLConf
    val parser = new SparkSqlParser(conf)
    val plan = parser.parsePlan(originalSql)

    println(plan)
//    'Project ['y AS z#1]
//    +- 'Project ['x AS y#0]
//        +- 'UnresolvedRelation `t`

    val catalog = new SessionCatalog(new InMemoryCatalog, FunctionRegistry.builtin, conf)
    catalog.createDatabase(CatalogDatabase("default", "", new URI("loc"), Map.empty), ignoreIfExists = false)
    val attributes: Seq[AttributeReference] = Seq(AttributeReference("x", IntegerType)())
    catalog.createTempView("t", LocalRelation(attributes), overrideIfExists = true)

    val analyzer = new Analyzer(catalog, conf)
    val resolvedPlan = analyzer.execute(plan)

    println(resolvedPlan)
//    Project [y#0 AS z#1]
//    +- Project [x#2 AS y#0]
//       +- SubqueryAlias t
//          +- LocalRelation <empty>, [x#2]
   }

}

Add test to see how Catalyst's resolution works


object Solution {

  def maxXor(l: Int, r: Int): Int = {
    var result = 0
    for {
      i <- l to r
      j <- i + 1 to r
    } {
      val m = i ^ j
      if (m > result) result = m
    }

    result
  }

  def main(args: Array[String]) {
    var _l:Int = Console.readInt
    var _r:Int = Console.readInt

    val res = maxXor(_l, _r)
    println(res)
  }
}

Add a brute force solution to problem Maximizing XOR.


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

import ch.usi.inf.l3.sana
import sana.tiny.symbols.Symbol
import sana.tiny.modifiers.Ops.noflags
import sana.tiny.types.Type
import sana.tiny.names.Name
import sana.calcj.symbols._
import sana.ooj.names.StdNames
import sana.ooj.modifiers.Ops._
import sana.ooj.types.TypeUtils
import sana.tiny.symbols.{TypeSymbol, TermSymbol}
import sana.primj.symbols.{ProgramSymbol, MethodSymbol,
                           VariableSymbol, ScopeSymbol}

trait SymbolUtils extends sana.arrooj.symbols.SymbolUtils {

  def enclosingModule(symbol: Option[Symbol]): Option[Symbol] =
    symbol.flatMap {
      case sym: ModuleSymbol  => Some(sym)
      case sym                => enclosingModule(sym.owner)
    }
}

object SymbolUtils extends SymbolUtils

Add symbol utils for oberon0

Add symbol utils for oberon0


package scala.in.programming.functional_object

/**
  * @author loustler
  * @since 01/20/2017 21:17
  */
class Rational(n: Int, d: Int) {
  //
  /**
    * constructor의 제한조건
    *
    * 제약조건에 불일치 하면 throw new IllegalArgumentException
    * [[scala.Predef.require()]]
    */
  require(d != 0)

  val numer: Int = n
  val denom: Int = d

  def this(n: Int) = this(n, 1) // Auxiliary Constructor for this class.

  /**
    * Like below
    * {{{ 1/2 + 1/3 }}} =>
    * {{{ 1 * 3 + 1 * 2 / 2 * 3 }}} =
    * {{{ 5 / 6 }}}
    *
    * @param that Another Rational to add
    * @return Add reuslt
    */
  def add(that: Rational): Rational =
    new Rational(
      numer * that.denom + that.numer * denom,
      denom * that.denom
    )

  /**
    * Like below
    * {{{ 1/2 lessThen 2/3 }}} =>
    * {{{ 1 * 3 < 1 * 2 }}} ==
    * {{{ false }}} ==>
    * {{{ 0.5 lessThen 0.6666666..... }}}
    *
    * @param that
    * @return
    */
  def lessThen(that: Rational) =
    this.numer * that.denom < that.numer * this.denom

  override def toString: String = n + "/" + d
}

Add example for functional object

Add example for functional object

- primary constructor
- auxiliary constructor
- side-effect function
- field
- Reference self


package sjsonnet

import java.io.{OutputStream, PrintStream}
import java.util.concurrent.TimeUnit

import org.openjdk.jmh.annotations._
import org.openjdk.jmh.infra._

import scala.collection.mutable.ArrayBuffer

@BenchmarkMode(Array(Mode.AverageTime))
@Fork(2)
@Threads(1)
@Warmup(iterations = 10)
@Measurement(iterations = 10)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
class MainBenchmark {

  val mainArgs = Array[String](
    "../../universe2/rulemanager/deploy/rulemanager.jsonnet",
    "-J", "../../universe2",
    "-J", "../../universe2/mt-shards/dev/az-westus-c2",
  )

  val dummyOut = new PrintStream(new OutputStream {
    def write(b: Int): Unit = ()
    override def write(b: Array[Byte]): Unit = ()
    override def write(b: Array[Byte], off: Int, len: Int): Unit = ()
  })

  @Benchmark
  def main(bh: Blackhole): Unit = {
    bh.consume(SjsonnetMain.main0(
      mainArgs,
      collection.mutable.Map.empty,
      System.in,
      dummyOut,
      System.err,
      os.pwd,
      None
    ))
  }
}

Add simple benchmark using JMH

Add simple benchmark using JMH


import stainless.annotation._

object GoodInitialization {
  case class A(x: BigInt) {
    val y = x
    val z = y + y
  }
  def f(z: BigInt) = {
    assert(A(21).z == 42)
  }
}

Add example of valid val initialization

Add example of valid val initialization


package org.apache.spark.streaming.event

import org.apache.spark.internal.Logging
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.util.Clock

case class TimerEvent(source: EventSource, override val time: Long, index: Long)
  extends Event(source)

class TimerEventSource(
    ssc: StreamingContext,
    clock: Clock,
    startTime: Long,
    endTime: Long,
    period: Long,
    name: String
  ) extends EventSource(ssc) with Logging {

  require(startTime < endTime,
    s"End time ($endTime ms) should be greater than start time ($startTime ms).")

  require(period > 0, s"Period ($period ms) should be greater than 0.")

  private var stopped = false
  private var nextTime: Long = -1

  private val thread = new Thread(s"TimerEventSource $name") {
    setDaemon(true)
    override def run() { loop() }
  }

  private def loop(): Unit = {
    var index = 0
    while (!stopped && nextTime <= endTime) {
      clock.waitTillTime(nextTime)
      post(TimerEvent(this, nextTime, index))
      logDebug(s"Timer ($name) event with time $nextTime ms and period index $index")
      index += 1
      nextTime += period
    }
    stop()
  }

  override def start(): Unit = synchronized {
    val currTime = System.currentTimeMillis
    if (startTime < currTime) {
      // if start time already elapsed, start from the next possible
      // period after current time
      nextTime = startTime + period * (1 + (currTime - startTime) / period)
    } else {
      nextTime = startTime
    }
    thread.start()
    logDebug(s"Timer ($name) started, next time $nextTime ms")
  }

  override def stop(): Unit = synchronized {
    if (!stopped) {
      stopped = true
      logDebug(s"Timer ($name) stopped")
    }
  }
}

Implement a timer event source

Implement a timer event source


object Test {

  def main(args: Array[String]) {
    val regex = """\$\{(.+?)\}""".r
    val replaced = regex.replaceAllMatchDataIn("Replacing: ${main}. And another method: ${foo}.",
        (m: util.matching.Regex.Match) => {
      val identifier = m.group(1)
      identifier
    })
    assert(replaced == "Replacing: main. And another method: foo.")

    val regex2 = """\$\{(.+?)\}""".r
    val replaced2 = regex2.replaceAllIn("Replacing: ${main}. And then one more: ${bar}.", (s: String) => {
      "$1"
    })
    assert(replaced2 == "Replacing: main. And then one more: bar.")
  }

}

Test file for matching with replace.

Test file for matching with replace.


import TestUtil._
import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import hu.bme.mit.ire._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class TransitiveClosureNodeTestextends(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "A TransitiveClosureNode" must {
    "calculate transitive closure" in {
      val prim = ChangeSet(
        positive = Vector(tuple(15, 16, 17, 18), tuple(4, 5, 6, 7))
      )
      val sec = ChangeSet(
        positive = Vector(Map(1 -> 15, 2 -> 16, 4 -> 13))
      )
      val primarySel = Vector(0, 1)
      val secondarySel = Vector(1, 2)
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val joiner = system.actorOf(Props(new JoinNode(echoActor ! _, primarySel, secondarySel)), name = "testSelector")

      joiner ! Primary(prim)
      joiner ! Secondary(sec)
      expectMsg(ChangeSet(
        positive = Vector(tuple(15, 16, 17, 18, 13))
      ))
    }
  }

}

Add class for testing transitive closures


object Solution {

  def doQuery(A: Array[Int], B: Array[Int], C: Array[Int]): Array[Long] = {
    val moduloP = 1e9.toInt + 7
    val n = A.size
    val m = B.size
    val result = A.map(_.toLong)
    val bWithIndex = B.zipWithIndex
    val bWithMuls = bWithIndex.groupBy(_._1)
      .mapValues(x => x.map(y => C(y._2)).foldLeft(1L) { (m, n) => m * n % moduloP } )

    for ((b, cm) <- bWithMuls if cm != 1) {
      var mul = b
      while (mul <= n) {
        result(mul - 1) = result(mul - 1) * cm % moduloP
        mul += b
      }
    }
    result
  }

  def main(args: Array[String]) {
    val _ = readLine
    val lines = (0 until 3).map(x => readLine)
    val Seq(as, bs, cs) = lines.map(l => l.split(" ").map(_.toInt))
    val result = doQuery(as, bs, cs)
    println(result.mkString(" "))
  }
}

Add solution to problem Sherlock and Queries. My first attempt didn't try to eliminate the duplicates, so the worst case time complexity is O(m * n). After elimination, the worst case time complexity is n + n / 2 + n / 3 + ... + n /n = ~ nln(n). So, the worst case is nln(n). The scala version of groupBy operation may have time issues when n and m get really big. But for n <= 1e5, this just works fine.


object Solution {

  def fullCountingSort(lines: Seq[(Int, String)]): Array[String] = {
    val size = lines.size
    val result = Array.fill(size)("")
    val nums = lines.map(_._1)
    val occCount = Array.fill(100)(0)
    for (num <- nums) occCount(num) += 1
    var sum = 0
    val countSum = for (c <- occCount) yield {
      sum += c
      sum
    }
    var i = 0
    for ((n, string) <- lines) {
      val index = countSum(n) - occCount(n)
      occCount(n) -= 1
      i += 1
      if (i <= size / 2) result(index) = "-"
      else result(index) = string
    }
    result
  }

  def main(args: Array[String]) {
    val n = readLine.toInt
    val lines = (1 to n).map { x =>
      val Array(num, s) = readLine.split(" ")
      (num.toInt, s)
    }
    println(fullCountingSort(lines).mkString(" "))
  }
}

Add solution to problem The Full Counting Sort. The worst case takes 3.62s on hackerrank, which is not that good.


package jigg.pipeline

/*
 Copyright 2013-2016 Hiroshi Noji

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

import java.util.Properties

import scala.xml.{Node, Elem, Text, Atom}
import jigg.util.XMLUtil

/** This simple annotator just segments a sentence by spaces, i.e.,
  * assuming the input sentence is already correctly tokenized.
  */
class SpaceTokenizerAnnotator(override val name: String, override val props: Properties)
    extends SentencesAnnotator {

  override def newSentenceAnnotation(sentence: Node): Node = {

    val sindex = sentence \@ "id"
    val text = sentence.text
    val range = (0 until text.size)

    def isSpace(c: Char) = c == ' ' || c == '\t'

    val begins = 0 +: (1 until text.size).filter { i => isSpace(text(i-1)) && !isSpace(text(i)) }

    val ends = begins map {
      range indexWhere (i=>isSpace(text(i)), _) match {
        case -1 => text.size
        case e => e
      }
    }

    val tokenSeq = begins.zip(ends).zipWithIndex map { case ((b, e), i) =>
      <token
        id={ sindex + "_tok" + i }
        form={ text.substring(b, e) }
        characterOffsetBegin={ b+"" }
        characterOffsetEnd={ e+"" }/>
    }
    val tokens = <tokens annotators={ name }>{ tokenSeq }</tokens>
    XMLUtil.addChild(sentence, tokens)
  }

  override def requires = Set(Requirement.Ssplit)
  override def requirementsSatisfied = Set(Requirement.Tokenize)
}

Add simple tokenizer by space

Add simple tokenizer by space


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

addSbtPlugin("com.github.gseitz" % "sbt-release" % "0.8")

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

resolvers += "allenai nexus repository" at "http://utility.allenai.org:8081/nexus/content/repositories/releases"

credentials += Credentials("Sonatype Nexus Repository Manager", "utility.allenai.org", "deployment", "answermyquery")

addSbtPlugin("org.allenai.plugins" % "sbt-travis-publisher" % "0.2.0")

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

addSbtPlugin("com.github.gseitz" % "sbt-release" % "0.8")

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

resolvers += "allenai nexus repository" at "http://utility.allenai.org:8081/nexus/content/repositories/releases"

credentials += Credentials("Sonatype Nexus Repository Manager", "utility.allenai.org", "deployment", "answermyquery")

addSbtPlugin("org.allenai.plugins" % "sbt-travis-publisher" % "2014.2.24-1-SNAPSHOT")

Change travis publisher plugin version so we don't publish pull requests


/*
 * Copyright (C) 2012 mathieu
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 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.ide.core.implementation.data

import org.openmole.core.implementation.validation.DataflowProblem
import org.openmole.core.implementation.validation.Validation
import org.openmole.core.model.data.IPrototype
import org.openmole.core.model.mole.ICapsule
import org.openmole.ide.core.implementation.serializer.MoleMaker
import org.openmole.ide.core.model.dataproxy.IPrototypeDataProxyUI
import org.openmole.ide.core.model.workflow.ICapsuleUI
import org.openmole.ide.core.model.workflow.IMoleSceneManager
import scala.collection.JavaConversions._

object CheckData {
  def checkMole(manager : IMoleSceneManager) = {
    manager.startingCapsule match {
      case Some(x:ICapsuleUI) =>
        val (mole,cMap,pMap) = MoleMaker.buildMole(manager)
        val capsuleMap : Map[ICapsule,ICapsuleUI] = cMap.map{case (k,v) => v -> k}
        val prototypeMap : Map[IPrototype[_],IPrototypeDataProxyUI] = pMap.map{case (k,v) => v -> k}.toMap
        val errors = Validation.typeErrors(mole) ++ Validation.duplicatedTransitions(mole)
        errors.isEmpty match {
          case false =>
            errors.map{
              _ match {
                case x : DataflowProblem =>
                  capsuleMap(x.capsule)-> (prototypeMap(x.data.prototype),x)
              }
            }.groupBy(_._1).map{ case (k,v) => (k,v.map(_._2))}.foreach{
              case(capsuleUI,e)=>
                capsuleUI.updateErrors(e.toList)
            }
          case true => manager.capsules.values.foreach{_.updateErrors(List.empty)}
        }
      case _ =>
    }
  }
}
//   case x : WrongType => println("wrong type on capsule " + capsuleMap(x.capsule))
//   case x : MissingInput => println("missing input "+x.data.prototype.name +" on capsule " + capsuleMap(x.capsule).)

Check dataflow problems in the workflow

Check dataflow problems in the workflow


// Copyright (c) 2013-2018 Rob Norris and Contributors
// This software is licensed under the MIT License (MIT).
// For more information see LICENSE or https://opensource.org/licenses/MIT

package doobie.util.arbitraries

import java.time._

import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.{Arbitrary, Gen}

import scala.jdk.CollectionConverters._

object TimeArbitraries {

  implicit val arbitraryLocalDate: Arbitrary[LocalDate] = Arbitrary {
    for {
      d <- Gen.chooseNum(
        LocalDate.of(-500, 1, 1).toEpochDay,
        LocalDate.of(294276, 1, 1).toEpochDay
      )
    } yield LocalDate.ofEpochDay(d)
  }

  implicit val arbitraryInstant: Arbitrary[Instant] = Arbitrary {
    for {
      l <- arbitrary[LocalDateTime]
      z <- arbitrary[ZoneOffset]
    } yield l.toInstant(z)
  }

  implicit val arbitraryLocalTime: Arbitrary[LocalTime] = Arbitrary {
    for {
      n <- Gen.chooseNum(LocalTime.MIN.toNanoOfDay, LocalTime.MAX.toNanoOfDay)
    } yield LocalTime.ofNanoOfDay(n)
  }

  implicit val arbitraryZoneOffset: Arbitrary[ZoneOffset] = Arbitrary {
    for {
      s <- Gen.chooseNum(ZoneOffset.MIN.getTotalSeconds, ZoneOffset.MAX.getTotalSeconds)
    } yield ZoneOffset.ofTotalSeconds(s)
  }

  implicit val arbitraryLocalDateTime: Arbitrary[LocalDateTime] = Arbitrary {
    for {
      o <- arbitrary[ZoneOffset]
      e <- Gen.chooseNum(
        LocalDateTime.of(-500, 1, 1, 1, 1, 1).toEpochSecond(o),
        LocalDateTime.of(294276, 1, 1, 1, 1).toEpochSecond(o)
      )
      n <- Gen.chooseNum(0, 999999999)
    } yield LocalDateTime.ofEpochSecond(e, n, o)
  }

  implicit val arbitraryZoneId: Arbitrary[ZoneId] = Arbitrary {
    for {
      k <- Gen.oneOf(ZoneId.SHORT_IDS.asScala.values)
    } yield ZoneId.of(k)
  }

  implicit val arbitraryOffsetTime: Arbitrary[OffsetTime] = Arbitrary {
    for {
      i <- arbitrary[Instant]
      z <- arbitrary[ZoneId]
    } yield OffsetTime.ofInstant(i, z)
  }

  implicit val arbitraryOffsetDateTime: Arbitrary[OffsetDateTime] = Arbitrary {
    for {
      i <- arbitrary[Instant]
      z <- arbitrary[ZoneId]
    } yield OffsetDateTime.ofInstant(i, z)
  }

  implicit val arbitraryZonedDateTime: Arbitrary[ZonedDateTime] = Arbitrary {
    for {
      l <- arbitrary[LocalDateTime]
      z <- arbitrary[ZoneId]
    } yield ZonedDateTime.of(l, z)

  }

}

Create Arbitraries for java.time.* classes.


package edu.nus.systemtesting

import scala.io.Source

/**
 * @author richardg
 */
object OutputDumps {
  def loadResource(url : String) : String = {
    val resourceIS = OutputDumps.getClass().getClassLoader().getResourceAsStream(url)

    val source = Source.fromInputStream(resourceIS)
    val contentStr = source.mkString

    source.close()

    contentStr
  }

  lazy val SleekExResource = loadResource("outputdump/sleek.sleek.slk.soccf-plser2-05.7ac44bdb0dfd.txt")
}

Add way for ScalaTests to make use of resource


package org.jetbrains.plugins.scala.performance.typing

import java.io.File

import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.util.ThrowableRunnable
import org.jetbrains.plugins.scala.base.ScalaFixtureTestCase
import org.jetbrains.plugins.scala.util.TestUtils

/**
  * Author: Svyatoslav Ilinskiy
  * Date: 10/29/15.
  */
abstract class TypingPerformanceTestBase extends ScalaFixtureTestCase {
  def doTest(stringsToType: List[String], timeoutInMillis: Int) {
    val fileName = getTestName(false) + ".scala"
    val filePath = folderPath + fileName
    val ioFile = new File(filePath)
    var fileText: String = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8)
    fileText = StringUtil.convertLineSeparators(fileText)
    myFixture.configureByText(fileName, fileText)
    PlatformTestUtil.startPerformanceTest("TypingTest" + getTestName(false), timeoutInMillis, new ThrowableRunnable[Nothing] {
      override def run(): Unit = {
        stringsToType.foreach(myFixture.`type`)
      }
    }).ioBound().assertTiming()
  }

  protected def folderPath: String = TestUtils.getTestDataPath + "/typingPerformance/"
}

Add test base for measuring typing performance


package collins.controllers

import org.specs2._
import specification._

import collins.controllers.forms._

class FormsSpec extends mutable.Specification {

  "Solr expression format should correctly bind a valid query" in {
    val result = SolrExpressionFormat.bind("query", Map("query" -> "tag=TRQ* AND name=SomeThing"))
    result must beRight
  }

  "Solr expression format should return errors on invalid query" in {
    val result = SolrExpressionFormat.bind("query", Map("query" -> "!A#!!"))
    result must beLeft
  }

  "Solr expression format must return valid query by interpreting as a tag" in {
    val result = SolrExpressionFormat.bind("query", Map("query" -> "TRQ12"))
    result must beRight
  }
}

Add a specification for solr expression format


package scala.in.programming.packazee

/**
  * Use Companion Object.
  *
  * Companion object have permission to access private members.
  *
  * Caution : Object must have not protected member, cause object is single object.
  *
  * Therefore that cannot extension.
  *
  * @author loustler
  * @since 04/14/2017 19:56
  */
class Rocket {
  import Rocket.fuel
  private def canGoHomeAgain = fuel > 20
}

object Rocket {
  private def fuel = 10

  def chooseStrategy(rocket: Rocket): Unit = {
    if (rocket.canGoHomeAgain)
      goHome()
    else
      pickAStar()
  }

  def goHome(): Unit = {
    println("go Home!")
  }

  def pickAStar(): Unit = {
    println("pick a star")
  }
}

Add exmaple for companion object in scala.


addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "3.0.0")
addSbtPlugin("de.johoop" % "jacoco4sbt" % "2.1.6")

Add jacoco for code coverage metrics

Add jacoco for code coverage metrics


package modules.upload.graphql.schema

import javax.inject.Inject
import akka.stream.ActorMaterializer
import common.{InputUnmarshallerGenerator, Logger}
import core.graphql.{GraphQLSchema, UserContext}
import modules.upload.graphql.resovlers.FileUploadResolver
import sangria.schema.{Argument, Field, _}
import spray.json.DefaultJsonProtocol

class FileSchema @Inject()(fileUploadResolver: FileUploadResolver)
                          (implicit val materializer: ActorMaterializer) extends GraphQLSchema
  with InputUnmarshallerGenerator
  with Logger
  with DefaultJsonProtocol {

  val fileUploadType: ScalarType[OptionType[Nothing]] = new ScalarType[OptionType[Nothing]](
    name = "FileUpload",
    coerceOutput = (_, _) => null,
    coerceUserInput = _ => Right(null),
    coerceInput = _ => Right(null)
  )

  override def mutations: List[Field[UserContext, Unit]] = List(
    Field(
      name = "uploadFiles",
      fieldType = sangria.schema.BooleanType,
      arguments = Argument(name = "files", argumentType = ListInputType(fileUploadType)) :: Nil,
      resolve = sc => {
        fileUploadResolver.upload(sc.ctx.filesData)
      }
    )
  )
}

Implement GraphQL schema for the 'uploadFiles' mutation


package com.softwaremill.codebrag.service.github

import org.scalatest.{GivenWhenThen, FlatSpec}
import org.scalatest.mock.MockitoSugar
import org.eclipse.egit.github.core.User
import org.mockito.Mockito._
import org.eclipse.egit.github.core.service.UserService
import org.mockito.Mockito

class GitHubAuthServiceSpec extends FlatSpec with MockitoSugar with GivenWhenThen {
  behavior of ("GitHub Auth Service")

  it should "read email of user" in {
    Given("auth service")
    val service = new GitHubAuthService
    And("loaded user data")
    val user = mock[User]
    Mockito.when(user.getEmail).thenReturn("some@email.com")

    When("Extracting user email")
    service.readEmail(user, null)

    Then("user's public email is read")
    verify(user, times(2)).getEmail
  }

  it should "fetch list of emails if user doesn't have public email" in {
    import scala.collection.JavaConversions._

    Given("auth service")
    val service = new GitHubAuthService
    And("user service")
    val userService = mock[UserService]
    val user = mock[User]
    Mockito.when(userService.getEmails).thenReturn(List("email@email.com"))

    When("extracting user data")
    service.readEmail(user, userService)

    Then("service is used to look up users private emails")
  }
}

Read email from user or from list of user emails


object Main {
    def main(args: Array[String]) {
        val _ = io.StdIn.readLine()
        val b = io.StdIn.readLine().toDouble
        val c = io.StdIn.readLine().toDouble

        println("TOTAL = R$ %.2f".format(b + (c * 0.15)))
    }
}

Solve Salary with Bonus in scala

Solve Salary with Bonus in scala


package com.gu.scanamo.time

import java.time.Instant

object InstantAsLongs {
  sealed abstract class InstantAsLongImpl {
    type T
    def apply(x: Instant): T
    def unwrap(x: T): Instant
  }

  val InstantAsLong: InstantAsLongImpl = new InstantAsLongImpl {
    type T = Instant
    def apply(x: Instant) = x
    def unwrap(x: T) = x
  }

  type InstantAsLong = InstantAsLong.T
}

Add opaque type for the subset of Instants isomorphic to Longs


package com.gu.management

import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import javax.servlet.FilterChain
import org.slf4j.MDC

class UniqueIdFilter extends AbstractHttpFilter {

  lazy val uniqueIdHeaderName = "X-GU-UniqueId"
  lazy val uniqueIdKey = "GUUID"
  lazy val defaultId = "None"

  def doHttpFilter(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain){
    val headerValue = request.getHeader(uniqueIdHeaderName)
    val value = if (headerValue != null) headerValue else defaultId
    MDC.put(uniqueIdKey, value)
    chain.doFilter(request, response)
  }

}

Add a unique id filter that puts the unique id into MDC from a request header


// Copyright (c) 2013-2018 Rob Norris and Contributors
// This software is licensed under the MIT License (MIT).
// For more information see LICENSE or https://opensource.org/licenses/MIT

package doobie.util.arbitraries

import java.sql.{Date, Time, Timestamp}

import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Arbitrary.arbitrary
import com.github.ghik.silencer.silent
object SQLArbitraries {

  implicit val arbitraryTime: Arbitrary[Time] = Arbitrary {
    for {
      h <- Gen.chooseNum(0, 23)
      m <- Gen.chooseNum(0, 59)
      s <- Gen.chooseNum(0, 59)
    } yield new Time(h, m, s): @silent
  }

  implicit val arbitraryDate: Arbitrary[Date] = Arbitrary {
    for {
      y <- Gen.chooseNum(0,8099)
      m <- Gen.chooseNum(0, 11)
      d <- Gen.chooseNum(1, 31)
    } yield new Date(y,m,d): @silent
  }

  implicit val arbitraryTimestamp: Arbitrary[Timestamp] = Arbitrary {
    for {
      d <- arbitrary[Date]
      t <- arbitrary[Time]
      n <- Gen.chooseNum(0,999999999)
    } yield new Timestamp(d.getYear, d.getMonth, d.getDate, t.getHours, t.getMinutes, t.getSeconds, n): @silent
  }

}

Create arbitraries for java.sql.* classes.


package beyond.engine.javascript

import com.typesafe.scalalogging.slf4j.StrictLogging
import java.io.StringReader
import java.net.URI
import org.mozilla.javascript.Scriptable
import org.mozilla.javascript.commonjs.module.provider.ModuleSource
import org.mozilla.javascript.commonjs.module.provider.ModuleSourceProvider
import play.api.Play
import scala.io.Source

class AssetsModuleSourceProvider extends ModuleSourceProvider with StrictLogging {
  override def loadSource(moduleId: String, paths: Scriptable, validator: AnyRef): ModuleSource = {
    import Play.current
    Play.resource(s"public/js_lib/$moduleId.js").map {
      resource =>
        val stream = resource.openStream()
        val source = Source.fromInputStream(stream).getLines().mkString("\n")
        new ModuleSource(new StringReader(source), null, resource.toURI, resource.toURI, validator)
    }.orNull
  }

  // FIXME: I didn't implement it because there is no use case that this method
  //       is used.
  //       Implement it when it's used.
  override def loadSource(uri: URI, baseUri: URI, validator: AnyRef): ModuleSource =
    ???
}

Implement rhino source provider for assets.


package com.bryanjswift.web.resources

import org.scalatest.WordSpec
import org.scalatest.matchers.ShouldMatchers
import scala.collection.mutable.Stack

class IndexSpec extends WordSpec with ShouldMatchers {
  "Index" should {
    val index = new IndexResource
    "render Hello from Jersey" in {
      assert(index.message === "
Hello Bryan, From Jersey
")
    }
    "render Hello from Velocity" in {
      assert(index.velocity.indexOf("
Hello Bryan, from Velocity
") != 1)
    }
  }
}

Add some specs for the basic Index behavior


package tutorial

import io.reactors._
import org.scalatest._
import scala.concurrent.Promise
import scala.concurrent.ExecutionContext

class GuideJvmHelloWorld extends AsyncFunSuite {
  val system = new ReactorSystem("test-system")

  implicit override def executionContext = ExecutionContext.Implicits.global

  test("start on a dedicated thread") {
    val done = Promise[String]()
    def println(s: String) = done.success(s)

    import io.reactors._

    object HelloWorld {
      def main(args: Array[String]) {
        val welcomeReactor = Reactor[String] {
          self =>
            self.main.events onEvent { name =>
              println(s"Welcome, $name!")
              self.main.seal()
            }
        }
        val system = ReactorSystem.default("test-system")
        /*!begin-include!*/
        /*!begin-code!*/
        val ch = system.spawn(
          welcomeReactor.withScheduler(JvmScheduler.Key.newThread))
        /*!end-code!*/
        /*!end-include(reactors-scala-jvm-spawn-thread.html)!*/
        ch ! "Alan"
      }
    }

    HelloWorld.main(Array())

    done.future.map(s => assert(s == "Welcome, Alan!"))
  }
}

Make the JVM hello world example an async suite.


package com.anchortab.migrate

import com.anchortab.model._

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

import org.joda.time._

import org.bson.types.ObjectId

import com.stripe

object GrantBetaUsersTrialSubscription {
  implicit val formats = User.formats

  def run(planId: ObjectId) = {
    for {
      plan <- Plan.find(planId)
      stripePlanId <- plan.stripeId
    } {
      println ("Granting beta users a 30-day trial of " + plan.name)

      val thirtyDaysFromNow = (new DateTime()).plusDays(30).getMillis() / 1000
      println("Thirty days from now is timecode " + thirtyDaysFromNow)

      println("Starting trial grant.")

      for {
        user <- User.findAll
        stripeCustomerId <- user.stripeCustomerId
        customer <- tryo(stripe.Customer.retrieve(stripeCustomerId))
        updatedSubscription <- tryo(customer.updateSubscription(Map(
          "plan" -> stripePlanId,
          "trial_end" -> thirtyDaysFromNow
        )))
      } {
        println("Associating subscription for " + user.email)

        val subscription = UserSubscription(planId, plan.price, plan.term, status = "active")
        User.update("_id" -> user._id, "$addToSet" -> ("subscriptions" -> decompose(subscription)))

      }

      println("Migration complete.")
    }
  }
}

Add migration to port all existing users to a plan.


package edu.berkeley.cs.amplab.adam.projection

import org.apache.avro.Schema
import scala.collection.JavaConversions._
import edu.berkeley.cs.amplab.adam.avro.ADAMRecord

/**
 * Avro utility object to create a projection of a Schema, e.g.
 *
 * val schema = Projection(ADAMRecord.SCHEMA$, Set("referenceName", "readName"))
 */
object Projection {

  def apply(fullSchema: Schema, includedFields: Set[String]): Schema = {
    val projectedSchema = Schema.createRecord(fullSchema.getName, fullSchema.getDoc, fullSchema.getNamespace, fullSchema.isError)
    projectedSchema.setFields(fullSchema.getFields.filter(includedFields.contains(_)))
    projectedSchema
  }

}

Add a simple utility class for creation schema projections


package com.nekopiano.scala.processing.sandbox

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

/**
  * Created on 07/08/2016.
  */
class LineFieldApp extends ThreeDimensionalPApp {

  override def settings: Unit = {
    size(1024, 768, P3D)
    pixelDensity(displayDensity())
    //smooth(8)
  }

  var pCam:PeasyCam = null

  override def setup(): Unit = {
    surface.setResizable(true)

    colorMode(HSB, 360, 100, 100, 100)

    val cam = new PeasyCam(this, 100)
    cam.setMinimumDistance(55)
    cam.setMaximumDistance(5000)
    //cam.setPitchRotationMode()

    cam.lookAt(width/2, height/2, 0)

    pCam = cam
  }

  val interval = 10f

  override def draw(): Unit = {
    background(0,0,0)

    // create a matrix
    stroke(100, 200, 200, 200)
    // x
    val xSlices = (0 to (width / interval).toInt) map(_ * interval)
    xSlices foreach (x => {
      line(x, 0, 0, x, height, 0)
    })
    val ySlices = (0 to (height / interval).toInt) map(_ * interval)
    ySlices foreach (y => {
      line(0, y, 0, width, y, 0)
    })

  }

}
object LineFieldApp extends ScalaPAppCompanion {}

class LuminousLine {

}

Add an app to create a matrix in 3D.

Add an app to create a matrix in 3D.


/**
 * What sort of big data book would this be if we didn't mention wordcount?
 */
import org.apache.spark.rdd._

object WordCount {
  // bad idea: uses group by key
  def badIdea(rdd: RDD[String]): RDD[(String, Int)] = {
    val words = rdd.flatMap(_.split(" "))
    val wordPairs = words.map((_, 1))
    val grouped = wordPairs.groupByKey()
    val wordCounts = grouped.mapValues(_.sum)
    wordCounts
  }

  // good idea: doesn't use group by key
  def goodIdea(rdd: RDD[String]): RDD[(String, Int)] = {
    val words = rdd.flatMap(_.split(" "))
    val wordPairs = words.map((_, 1))
    val wordCounts = wordPairs.reduceByKey(_ + _)
    wordCounts
  }
}

Add a simple wordcount example

Add a simple wordcount example


object Solution {

  def getNumOfCholocates(n: Int, c: Int, m: Int): Int = {
    var result = n / c
    var wrapers = result
    while (wrapers >= m) {
      val newCandys = wrapers / m
      result += newCandys
      wrapers = newCandys + wrapers % m
    }
    result
  }

  def main(args: Array[String]) {
    val t = readLine.toInt
    for (_ <- 1 to t) {
      val Array(n, c, m) = readLine.split(" ").map(_.toInt)
      println(getNumOfCholocates(n, c, m))
    }
  }
}

Add solution to problem Chocolate Feast.


package no.nrk.samnorsk.synonymmapper

import java.io.File

import no.nrk.samnorsk.synonymmapper.SynonymMapper.{Mapping, SynonymLine}
import org.scalatest.FlatSpec

import scala.io.Source

class SynonymMapperTest extends FlatSpec {

  testSynonymWriter
  testSynonymCreation

  def testSynonymWriter = {

    val testFile = File.createTempFile("synfile", "test")
    testFile.deleteOnExit()

    val inputSynonyms = Seq(SynonymLine(Seq("anledning", "mulighet"), "høve"), SynonymLine(Seq("kanskje", "muligens"), "truleg"))
    SynonymMapper.writeSynonyms(inputSynonyms, testFile, false)

    val reductionLines = Source.fromFile(testFile).getLines().toSeq
    assert(reductionLines.head === "anledning,mulighet => høve")
    assert(reductionLines.last === "kanskje,muligens => truleg")

    SynonymMapper.writeSynonyms(inputSynonyms, testFile, true)
    val expansionLines = Source.fromFile(testFile).getLines().toSeq
    assert(expansionLines.head === "anledning,mulighet,høve")
    assert(expansionLines.last === "kanskje,muligens,truleg")
  }

  def testSynonymCreation = {
    val frequencyMap = Map(Mapping("høve", "mulighet") -> 20,
      Mapping("høve", "anledning") -> 16,
      Mapping("høve", "min") -> 2,
      Mapping("snakke", "preike") -> 100,
      Mapping("snakke", "preke") -> 105)

    val synonyms = SynonymMapper.createSynonymsFromFrequencies(frequencyMap)
    assert(synonyms.head.canonicalForm == "høve")
    assert(synonyms.head.synonyms.toSet === Set("mulighet", "anledning"))

    assert(synonyms.last.canonicalForm == "snakke")
    assert(synonyms.last.synonyms.toSet === Set("preike", "preke"))
  }
}

Add simple unit tests for SynonymMapper

Add simple unit tests for SynonymMapper


/*
 Copyright 2013 Jason Baldridge

 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 nak.cluster

object ClusterReport {

  import nak.util.CollectionUtil._

  /**
   * Given the ids (descriptors) for each point, their true label and the id
   * for the cluster they have been assigned, print all the ids for each
   * label-cluster_id.
   *
   * @param ids the sequence of descriptors for each point
   * @param labels the sequence of true cluster labels for each point
   * @param predictedClusterIds the ids of the clusters predicted by k-means
   */
  def apply(ids: Seq[String], labels: Seq[String], predictedClusterIds: Seq[Int]) {
    labels.zip(predictedClusterIds).zip(ids).groupByKey.foreach {
      case ((label, cluster), idsInCluster) =>
        println("[Label: " + label + "] <=> [Cluster: " + cluster + "]")
        println("Ids: " + idsInCluster.mkString("\t"))
        println
    }
  }
}

Add ClusterReport object for simple error analysis.


package quasar.project

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

package quasar.project

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

Update spire, spire-laws to 0.16.2

Update spire, spire-laws to 0.16.2


package io.reactors
package protocol

import scala.collection._
import scala.concurrent._
import scala.concurrent.duration._

class StreamingLibraryTest extends AsyncFunSuite with AsyncTimeLimitedTests {
  val system = ReactorSystem.default("streaming-lib")

  def timeLimit = 10.seconds

  implicit override def executionContext = ExecutionContext.Implicits.global

  test("streaming map") {
    // TODO: Implement test.
  }
}

Add streaming library test stub.

Add streaming library test stub.


package net.sansa_stack.rdf.spark.model.tensor

import com.holdenkarau.spark.testing.DataFrameSuiteBase
import net.sansa_stack.rdf.spark.io._
import org.apache.jena.graph.{ Node, Triple }
import org.apache.jena.riot.Lang
import org.scalatest.FunSuite

class TensorTripleOpsTests extends FunSuite with DataFrameSuiteBase {

  import net.sansa_stack.rdf.spark.model._

  test("converting RDD of triples into Tensor should match") {
    val path = getClass.getResource("/rdf.nt").getPath
    val lang: Lang = Lang.NTRIPLES

    val triples = spark.rdf(lang)(path)

    val tensor = triples.asTensor()
    val size = tensor.count()

    assert(size == 450)
  }

  test("getting number of entities from RDD of triples should match") {
    val path = getClass.getResource("/rdf.nt").getPath
    val lang: Lang = Lang.NTRIPLES

    val triples = spark.rdf(lang)(path)

    val num = triples.getNumEntities()

    assert(num == 30)
  }

  test("getting number of relations from RDD of triples should match") {
    val path = getClass.getResource("/rdf.nt").getPath
    val lang: Lang = Lang.NTRIPLES

    val triples = spark.rdf(lang)(path)

    val num = triples.getNumRelations()

    assert(num == 26)
  }

}

Add basic unit test for the Tensor TripleOps


package org.phenoscape.kb

object MatrixRendererTest extends App {

  val innerMap: Map[Any, Boolean] = Map("y1" -> true, "y2" -> false, "y3" -> true)

  val outerMap: Map[Any, Map[Any, Boolean]] = Map("y1" -> innerMap, "y2" -> innerMap, "y3" -> innerMap)

  val outputString = Similarity.matrixRendererFromMapOfMaps(outerMap)

  println(outputString)

}

Add test for matrix renderer

Add test for matrix renderer


package codesample.scala.coursera.course1.week4

object ObjectOrientedNaturalNumber {

  abstract class Nat {
    def isZero: Boolean
    def predecessor: Nat
    def successor: Nat = new Succ(this)
    def +(that: Nat): Nat
    def -(that: Nat): Nat
  }

  object Zero extends Nat {

    override def isZero: Boolean = true
    override def predecessor: Nat = throw new IllegalArgumentException("Zero.predecessor called")
    override def +(that: Nat): Nat = that
    override def -(that: Nat): Nat = if (that.isZero) Zero else throw new IllegalArgumentException("Zero.- negative number")

    override def toString: String = "0"
  }

  class Succ(n: Nat) extends Nat {
    override def isZero: Boolean = false
    override def predecessor: Nat = n
    override def +(that: Nat): Nat = new Succ(n+that)
    override def -(that: Nat): Nat = if (that.isZero) this else n - that.predecessor

    override def toString: String = "not 0"
  }

  def main(args: Array[String]): Unit = {
    val number = new Succ(Zero)
    println(number)
    val inceremementedTwice = number.successor.successor
    var anotherOne = number.successor.successor.successor
    val yetAnother = inceremementedTwice + anotherOne
    println(yetAnother)

    // wtf is going on...
  }

}

Add natural numbers example... wtf is going on?


package ccf

import ccf.operation.Operation

class JupiterOperationSynchronizerFactory[T <: Operation](isPrimary: Boolean, transformer: JupiterTransformer[T]) extends OperationSynchronizerFactory[T] {
  def createSynchronizer = new JupiterOperationSynchronizer(isPrimary, transformer)
}

Introduce a synchronizer factory for jupiter synchronizers

Signed-off-by: Aki Saarinen <2c8035bb80cf98a391872dcbe797b269d759f6d9@reaktor.fi>


package uk.ac.wellcome.platform.sierra_item_merger.fixtures

import uk.ac.wellcome.messaging.sns.NotificationMessage
import uk.ac.wellcome.messaging.test.fixtures.SQS
import uk.ac.wellcome.models.transformable.sierra.SierraItemRecord
import uk.ac.wellcome.models.work.test.util.IdentifiersUtil
import uk.ac.wellcome.storage.fixtures.S3
import uk.ac.wellcome.storage.fixtures.S3.Bucket
import uk.ac.wellcome.storage.vhs.HybridRecord
import uk.ac.wellcome.utils.JsonUtil._

trait ItemMergerFixtures extends IdentifiersUtil with S3 with SQS {
  def createItemNotification(bucket: Bucket, itemRecord: SierraItemRecord): NotificationMessage = {
    val key = s"messaging/${randomAlphanumeric(10)}.json"
    s3Client.putObject(bucket.name, key, toJson(itemRecord).get)

    val hybridRecord = HybridRecord(
      id = itemRecord.id.withoutCheckDigit,
      s3key = key,
      version = 1
    )

    createNotificationMessageWith(hybridRecord)
  }
}

Add an item merger fixture for ItemRecord notifications


package hmda.publication.reports.disclosure

import akka.NotUsed
import akka.stream.scaladsl.Source
import hmda.model.fi.lar.LoanApplicationRegister
import hmda.publication.reports._
import hmda.util.SourceUtils

import scala.concurrent.Future

object DisclosureReportGenerator extends SourceUtils {

  def generateReports[as: AS, mat: MAT, ec: EC](larSource: Source[LoanApplicationRegister, NotUsed]): Future[Unit] = {
    genD51Report(larSource)
  }

  // Table filters:
  // Loan Type 2,3,4
  // Property Type 1,2
  // Purpose of Loan 1
  private def genD51Report(larSource: Source[LoanApplicationRegister, NotUsed]): Future[Unit] = {

    val filtered = larSource.filter { lar =>
      (lar.loan.loanType == 2 || lar.loan.loanType == 3 || lar.loan.loanType == 4) &&
        (lar.loan.propertyType == 1 || lar.loan.propertyType == 2) &&
        (lar.loan.purpose == 1)
    }

    //Income statistics

    Future {
      ()
    }
  }

}

Add disclosure report generator stub

Add disclosure report generator stub


import stainless.lang._

object Inconsistency {
  sealed abstract class Code
  case class Fold(f: Code => Boolean) extends Code

  def looping(c: Code): Boolean = c match {
    case Fold(f) => !f(c)
  }
}

Add benchmark for negative datatypes

Add benchmark for negative datatypes


package cc.factorie.optimize

import cc.factorie.la.Tensor
import cc.factorie.model.{WeightsMap, WeightsSet}

// NOTE: these won't work with optimizers that replace the Tensor in the weights, since it needs to be able to mutate things

object ConstraintHelpers {
  def projectl2(t: Tensor, lambda: Double): Unit = {
    val twonorm = t.twoNorm
    if (twonorm > lambda)
      t *= lambda / twonorm
  }
  def projectHypercube(t: Tensor, min: Double, max: Double): Unit = {
    val arr = t.asArray
    val len = arr.length
    var i = 0
    while (i < len) {
      arr(i) = math.min(max, math.max(min, arr(i)))
      i += 1
    }
  }
}

trait L2ConstraintStep extends GradientStep {
  def lambda: Double
  abstract override def doGradStep(weights: WeightsSet, gradient: WeightsMap, value: Double): Unit = {
    super.doGradStep(weights, gradient, value)
    for (k <- gradient.keys) ConstraintHelpers.projectl2(weights(k), lambda)
  }
}
trait L2Constraint extends GradientOptimizer {
  def lambda: Double
  abstract override def step(weights: WeightsSet, gradient: WeightsMap, value: Double): Unit = {
    super.step(weights, gradient, value)
    for (k <- gradient.keys) ConstraintHelpers.projectl2(weights(k), lambda)
  }
}

trait HypercubeConstraintStep extends GradientStep {
  def min: Double
  def max: Double
  abstract override def doGradStep(weights: WeightsSet, gradient: WeightsMap, value: Double): Unit = {
    super.doGradStep(weights, gradient, value)
    for (k <- gradient.keys) ConstraintHelpers.projectHypercube(weights(k), min, max)
  }
}
trait HypercubeConstraint extends GradientOptimizer {
  def min: Double
  def max: Double
  abstract override def step(weights: WeightsSet, gradient: WeightsMap, value: Double): Unit = {
    super.step(weights, gradient, value)
    for (k <- gradient.keys) ConstraintHelpers.projectHypercube(weights(k), min, max)
  }
}

Add l2 and hypercube constraint mixins for GradientOptimizer


package info.mukel.telegrambot4s

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

package object api {
  implicit class FutureTransformWith[T](future: Future[T]) {
    def transformWith[S](f: (Try[T]) ⇒ Future[S])(implicit executor: ExecutionContext): Future[S] = {
      future
        .flatMap(t => f(Success(t)))
        .recoverWith { case e => f(Failure(e)) }
    }
  }
}

Add missing tranformWith implementation for Scala 2.11


package com.redislabs.provider.redis

import java.io.{File, FileWriter, PrintWriter}
import java.time.{Duration => JDuration}

import com.redislabs.provider.redis.util.Logging

/**
  * @author The Viet Nguyen
  */
trait RedisBenchmarks extends Logging {

  val benchmarkReportDir = new File("target/reports/benchmarks/")
  benchmarkReportDir.mkdirs()

  def time[R](tag: String)(block: => R): R = {
    val t0 = System.nanoTime()
    val result = block // call-by-name
    val t1 = System.nanoTime()
    new PrintWriter(new FileWriter(s"$benchmarkReportDir/results.txt", true)) {
      println(s"$tag, ${JDuration.ofNanos(t1 - t0)}")
      close()
    }
    result
  }
}

Create base Redis benchmark suite

Create base Redis benchmark suite


// Copyright (c) 2011 Thomas Suckow
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html

package net.codingwell.weave

import com.google.inject._
import akka.actor._

class ActorProvider[T <: Actor] @Inject() ( val m:TypeLiteral[T], val injector:Injector ) extends Provider[ActorRef] {
  def get = {
    Actor.actorOf( injector.getInstance( Key.get( m ) ) ).start
  }
}

Add missing file from last commit

Add missing file from last commit


import leon.Annotations._
import leon.Utils._

object Nat {
  sealed abstract class Nat
  case class Zero() extends Nat
  case class Succ(num: Nat) extends Nat

  def plus(a: Nat, b: Nat): Nat = a match {
    case Zero()   => b
    case Succ(a1) => Succ(plus(a1, b))
  }

  def nat2Int(n: Nat): Int = n match {
    case Zero() => 0
    case Succ(n1) => 1 + nat2Int(n1)
  }

  def int2Nat(n: Int): Nat = if (n == 0) Zero() else Succ(int2Nat(n-1))

  def sum_lemma(): Boolean = {
    3 == nat2Int(plus(int2Nat(1), int2Nat(2)))
  }.holds
}

Fix potential infinite loop with unlocking of reused blockers

Unlocking reused, already-unlocked blockers would result in a no-op
while still keeping this blocker into the list of blockers to address.
This patch makes sure that reused, unlocked blockers are excluded from
the worklist.


package ignition.core.utils

object ExceptionUtils {

  implicit class ExceptionImprovements(e: Throwable) {
    def getFullStacktraceString(): String = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e)
  }

}

Make it partially compatible with scala 2.11 and Xlint free and minor cleanups


// generic immutable binary tree
sealed trait BinaryTree[T] {
  def add(value: T)(implicit ordering: Ordering[T]): BinaryTree[T]
  def walk(f: T => Unit) {}
}

case class Empty[T]() extends BinaryTree[T] {
  override def add(value: T)(implicit ordering: Ordering[T]) =
    Node[T](value, this, this)
}

case class Node[T](value: T, left: BinaryTree[T], right: BinaryTree[T])
  extends BinaryTree[T] {
  override def add(newValue: T)(implicit ordering: Ordering[T]) =
    if (ordering.gt(newValue, value)) copy(right = right.add(newValue))
    else copy(left = left.add(newValue))

  override def walk(f: T => Unit) {
    left.walk(f)
    f(value)
    right.walk(f)
  }
}

object BinaryTree {
  def create[T]: BinaryTree[T] = Empty[T]
}

var tree = BinaryTree.create[Int]

for (i <- 1 to 1000000) {
  val value = scala.util.Random.nextInt(i)
  tree = tree.add(value)
}

tree.walk(println)

Add binary tree in Scala

Add binary tree in Scala


package test

import org.specs2.mutable._

import play.api.test._
import play.api.test.Helpers._

class IntegrationTest extends Specification {
  "Frontend" should {
    "work from within a browser" in {
      running(TestServer(3333), HTMLUNIT) { browser =>
        browser.goTo("http://localhost:3333/")

        // Able to load the front page
        browser.$("h1.name a").first.getText must equalTo("Breakpoint.")
      }
    }
  }
}

Write a stupidly simple test just to have it.

This is more meant to add a "Put tests here" file handy.


object Solution {
  case class Cantor(size: Int) {
    if (size > 20) {
      throw new Exception("size too big for permutations, should less than 21")
    }

    private var factor = 1l
    private val factors = 1l +: (for (i <- 1 to size) yield {
      factor = i * factor
      factor
    })

    def revert(index: Long): Seq[Int] = {
      var i = index - 1
      val used = Array.fill(size)(false)

      for (j <- 1 to size) yield {
        val a = i / factors(size - j)
        i = i % factors(size - j)
        val selected = (0 until size).filter(!used(_))(a.toInt)
        used(selected) = true
        selected
      }
    }

    def order(arr: Seq[Int]): Long = {
      assert(arr.toSet.size == size)
      assert(arr.forall(_ < size))
      val used = Array.fill(size)(false)
      val coefficient = arr.map { x =>
        used(x) = true
        (0 until x).filter(!used(_)).size
      }
      1 + coefficient.zipWithIndex.foldLeft(0l) { (x, y) =>
        x + y._1 * factors(size - 1 - y._2)
      }
    }
  }

  def main(args: Array[String]) {
    val word = "abcdefghijklm"
    val cantor = Cantor(word.size)
    val t = readLine.toInt
    for (i <- 1 to t) {
      val order = readLine.toLong
      val indexes = cantor.revert(order)
      println(indexes.map(word(_)).mkString(""))
    }
  }
}

Add solution to problem 24. This solution used cantor sequences to decided the corresponding sequences for index. Should write a blog about this method.


object Solution {

  def insertionSort(nums: Array[Int]) {
    val n = nums.size
    var numOfShifts = 0
    for (i <- 1 until n) {
      var j = i
      while (j >= 1 && nums(j) < nums(j - 1)) {
        numOfShifts += 1
        val temp = nums(j)
        nums(j) = nums(j - 1)
        nums(j - 1) = temp
        j -= 1
      }
    }
    println(numOfShifts)
  }

  def main(args: Array[String]) {
    val _ = readLine
    val nums = readLine.split(" ").map(_.toInt)
    insertionSort(nums)
  }
}

Add solution to problem Running Time of Algorithms. It's just the Insertion Sort time.


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 SingleValueBenchmarkSuite extends DataframeBenchmarkSuite with RedisClusterEnv {

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

  override def rdd(): RDD[Person] = {
    spark.sparkContext.parallelize(Seq(Person(s"John", 30, "60 Wall Street", 150.5)))
  }
}

Create base dataframe benchmark suite for a single element


import TestUtil._
import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestActors, TestKit}
import hu.bme.mit.ire._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class TransitiveClosureNodeTestextends(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem("MySpec"))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }

  "A TransitiveClosureNode" must {
    "calculate transitive closure" in {
      val prim = ChangeSet(
        positive = Vector(tuple(15, 16, 17, 18), tuple(4, 5, 6, 7))
      )
      val sec = ChangeSet(
        positive = Vector(Map(1 -> 15, 2 -> 16, 4 -> 13))
      )
      val primarySel = Vector(0, 1)
      val secondarySel = Vector(1, 2)
      val echoActor = system.actorOf(TestActors.echoActorProps)
      val joiner = system.actorOf(Props(new JoinNode(echoActor ! _, primarySel, secondarySel)), name = "testSelector")

      joiner ! Primary(prim)
      joiner ! Secondary(sec)
      expectMsg(ChangeSet(
        positive = Vector(tuple(15, 16, 17, 18, 13))
      ))
    }
  }

}

Add class for testing transitive closures


object Test {
  class C[T]
  implicit def fGen[T](implicit ev: T): C[T] = ???
  implicit def fString(implicit ev: C[Int]): C[String] = ???
  implicit def fInt: C[Int] = ???

  implicitly[C[String]]
  implicitly[C[C[String]]]
  implicitly[C[C[C[String]]]]
  implicitly[C[C[C[C[String]]]]]
  implicitly[C[C[C[C[C[String]]]]]]
  implicitly[C[C[C[C[C[C[String]]]]]]] // error: no implicit argument found (because of divergence)
}

Add test for implicit divergence

Add test for implicit divergence

Error message could be improved


package com.yammer.dropwizard.cli

import com.yammer.metrics.HealthChecks
import com.codahale.fig.Configuration
import com.yammer.dropwizard.config.ServerFactory
import com.sun.jersey.spi.container.servlet.ServletContainer
import com.yammer.metrics.core.DeadlockHealthCheck
import com.yammer.dropwizard.jetty.JettyManaged
import com.yammer.dropwizard.{JerseyConfig, Environment, Service}

class ServerCommand(service: Service) extends ConfiguredCommand {
  def name = "server"

  override protected def commandSyntax(jarSyntax: String) =
    "%s %s <config file>".format(jarSyntax, name)

  override def description = Some("Starts an HTTP server running the service")

  final def run(service: Service, config: Configuration, opts: Map[String, List[String]], args: List[String]) = {
    val env = new Environment
    service.configure(config, env)
    env.healthChecks.foreach(HealthChecks.register)
    HealthChecks.register(new DeadlockHealthCheck)
    env.addServlet(new ServletContainer(new JerseyConfig(env)), "/*")

    val server = ServerFactory.provideServer(config, env.servlets, env.filters)
    env.jettyObjects.foreach(server.addBean)
    env.managedObjects.map { new JettyManaged(_) }.foreach(server.addBean)

    log.info("Starting %s", service.name)
    service.banner.foreach {s => log.info("\n%s\n", s)}

    server.start()
    server.join()

    None
  }
}

package com.yammer.dropwizard.cli

import com.yammer.metrics.HealthChecks
import com.codahale.fig.Configuration
import com.yammer.dropwizard.config.ServerFactory
import com.sun.jersey.spi.container.servlet.ServletContainer
import com.yammer.metrics.core.DeadlockHealthCheck
import com.yammer.dropwizard.jetty.JettyManaged
import com.yammer.dropwizard.{JerseyConfig, Environment, Service}

class ServerCommand(service: Service) extends ConfiguredCommand {
  def name = "server"

  override protected def commandSyntax(jarSyntax: String) =
    "%s %s <config file>".format(jarSyntax, name)

  override def description = Some("Starts an HTTP server running the service")

  final def run(service: Service, config: Configuration, opts: Map[String, List[String]], args: List[String]) = {
    val env = new Environment
    service.configure(config, env)
    env.healthChecks.foreach(HealthChecks.register)
    HealthChecks.register(new DeadlockHealthCheck)

    env.addServlet(new ServletContainer(new JerseyConfig(env)), "/*", initOrder = Int.MaxValue)

    val server = ServerFactory.provideServer(config, env.servlets, env.filters)
    env.jettyObjects.foreach(server.addBean)
    env.managedObjects.map { new JettyManaged(_) }.foreach(server.addBean)

    log.info("Starting %s", service.name)
    service.banner.foreach {s => log.info("\n%s\n", s)}

    server.start()
    server.join()

    None
  }
}

Allow all other servlets and filters to take precedence over Jersey.


package scala.in.programming.tests

import scala.in.programming.inheritance_composition.Element._

/**
  * @author loustler
  * @since 04/21/2017 22:06
  */
class ElementSuite extends org.scalatest.Suite{
  def testUniformElement(): Unit = {
    val ele = elem('x', 2, 3)
    assert(ele.width == 2)
  }
}

Add test example using scalatest.

Add test example using scalatest.


package com.codiply.barrio.neighbors.aggregators

import scala.concurrent.duration._

import akka.actor.ActorRef
import akka.actor.Props

import com.codiply.barrio.generic.AggregatorActor
import com.codiply.barrio.geometry.Point.Coordinates
import com.codiply.barrio.neighbors.LocationIndexActorProtocol.GetLocationResponse

object LocationIndexAggregatorActor {
  def props(
      responseRecipient: ActorRef,
      expectedNumberOfResponses: Int,
      timeout: FiniteDuration): Props = {
        val initialValue = None
        val folder = (aggregate: Option[Coordinates], newResponse: GetLocationResponse) =>
          if (aggregate.isDefined) {
            aggregate
          } else {
            newResponse.location
          }
        val mapper = (aggregate: Option[Coordinates]) => GetLocationResponse(aggregate)
        val earlyTerminationCondition = Some((aggregate: Option[Coordinates]) => aggregate.isDefined)
        AggregatorActor.props(
            responseRecipient, initialValue, folder, mapper, earlyTerminationCondition, expectedNumberOfResponses, timeout)
      }
}

Add aggregator for getting location by id


package com.anchortab.snippet

import org.scalatest._

class AffiliateCalculationSpec extends FunSpec with ShouldMatchers {
  describe("Total as of Target Month Calculator") {
    it("+1 for each paid sub w/ code; start before target month; no end date") (pending)

    it("+1 for each paid sub w/ code; start before target month; end date after target mo") (pending)

    it("+1 for each paid sub w/ code; start in target mo; without end date") (pending)

    it("+1 for each paid sub w/ code; start in target mo; end date 20 days after start") (pending)
  }

  describe("New Users for Target Month Calculator") {
    it("+1 for first sub by new user w/ code; start in target mo; no end date") (pending)

    it("+1 for first sub by new user w/ code; start in target mo; end date > 1 mo after start") (pending)
  }
}

Add the affiliate calculation spec.

Add the affiliate calculation spec.


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

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class WebSocketCompileTest extends Simulation {

  val httpConf = http
    .baseURL("http://localhost:9000")
    .acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    .doNotTrackHeader("1")
    .acceptLanguageHeader("en-US,en;q=0.5")
    .acceptEncodingHeader("gzip, deflate")
    .userAgentHeader("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20100101 Firefox/16.0")
    .wsBaseURL("ws://localhost:9000")
    .wsReconnect
    .wsMaxReconnects(3)

  val scn = scenario("WebSocket")
    .exec(http("Home").get("/"))
    .pause(1)
    .exec(session => session.set("id", "Steph" + session.userId))
    .exec(http("Login").get("/room?username=${id}"))
    .pause(1)
    .exec(websocket("Connect WS").open("/room/chat?username=${id}"))
    .pause(1)
    .repeat(1, "i") {
      exec(websocket("Say Hello WS").sendTextMessage( """{"text": "Hello, I'm ${id} and this is message ${i}!"}"""))
        .pause(1)
    }.exec(websocket("Close WS").close())

  setUp(scn.inject(rampUsers(100) over 10)).protocols(httpConf)
}

Add compile test for WebSockets

Add compile test for WebSockets


package com.johnsnowlabs.nlp.annotators.ner

import com.johnsnowlabs.nlp.annotator._
import com.johnsnowlabs.nlp.base._
import com.johnsnowlabs.nlp.embeddings.WordEmbeddingsModel
import com.johnsnowlabs.nlp.training.CoNLL
import com.johnsnowlabs.nlp.util.io.ResourceHelper
import org.scalatest._

class NerConverterTest extends FlatSpec {

  "NeConverter" should "correctly use any TOKEN type input" in {

    val conll = CoNLL()
    val training_data = conll.readDataset(ResourceHelper.spark, "src/test/resources/ner-corpus/test_ner_dataset.txt")

    val documentAssembler = new DocumentAssembler().
      setInputCol("text").
      setOutputCol("document")

    val sentenceDetector = new SentenceDetector()
      .setInputCols("document")
      .setOutputCol("sentence")
      .setUseAbbreviations(false)

    val tokenizer = new Tokenizer()
      .setInputCols(Array("sentence"))
      .setOutputCol("token")

    val normalize = new Normalizer()
      .setInputCols("token")
      .setOutputCol("cleaned")
      .setLowercase(true)

    val embeddings = WordEmbeddingsModel.pretrained()
      .setInputCols("document", "cleaned")
      .setOutputCol("embeddings")
      .setCaseSensitive(false)

    val ner = NerDLModel.pretrained()
      .setInputCols("sentence", "cleaned", "embeddings")
      .setOutputCol("ner")

    val converter = new NerConverter()
      .setInputCols("sentence", "cleaned", "ner")
      .setOutputCol("entities")
      .setPreservePosition(false)

    val recursivePipeline = new RecursivePipeline()
      .setStages(Array(
        documentAssembler,
        sentenceDetector,
        tokenizer,
        normalize,
        embeddings,
        ner,
        converter
      ))

    val nermodel = recursivePipeline.fit(training_data).transform(training_data)

    nermodel.select("token.result").show(1, false)
    nermodel.select("cleaned.result").show(1, false)
    nermodel.select("embeddings.result").show(1, false)
    nermodel.select("entities.result").show(1, false)
    nermodel.select("entities").show(1, false)

  }

}

Add a simple unit test for NerConverter

Add a simple unit test for NerConverter


package uk.ac.wellcome.transformer.transformers.sierra

import org.scalatest.{FunSpec, Matchers}
import uk.ac.wellcome.models.Language
import uk.ac.wellcome.transformer.source.SierraBibData
import uk.ac.wellcome.transformer.source.sierra.{Language => SierraLanguage}
import uk.ac.wellcome.test.utils.SierraData

class SierraLanguageTest extends FunSpec with Matchers with SierraData {

  val transformer = new SierraLanguage {}

  it("ignores records which don't have a lang field") {
    val bibData = SierraBibData(
      id = "1000001",
      lang = None
    )

    transformer.getLanguage(bibData = bibData) shouldBe None
  }

  it("picks up the language from the lang field") {
    val bibData = SierraBibData(
      id = "2000002",
      lang = Some(SierraLanguage(
        code = "eng",
        name = "English"
      ))
    )

    transformer.getLanguage(bibData = bibData) shouldBe Some(Language(
      id = "eng",
      label = "English"
    ))
  }
}

Add tests for the SierraLanguage trait

Add tests for the SierraLanguage trait


package controllers

import org.specs2.mutable.Specification
import play.api.http.HeaderNames
import play.api.libs.json._
import play.api.test._
import play.api.test.Helpers._
import test.WithTestApplication
import utils.JsonFormats._

/**
 * This test performs a simple happy-path end-to-end through the entire workflow.
 */
class EndToEndIntegrationTest extends Specification with HeaderNames {

  "The application" should {

    "work end-to-end" in new WithTestApplication(useMongo = true) {
      // Shorten a URL
      val shortenResult = route(FakeRequest(POST, "/v1/urls").withBody(Json.obj(
        "long_url" -> "http://www.google.com"
      ))).get
      status(shortenResult) must equalTo(OK)
      val shortenedUrl = contentAsJson(shortenResult).as[ShortUrlView]

      // "Visit" it a few times
      val visit1 = route(FakeRequest(GET, s"/${shortenedUrl.hash}")).get
      status(visit1) must equalTo(TEMPORARY_REDIRECT)
      header(LOCATION, visit1) must beSome.which(_ == "http://www.google.com")
      val visit2 = route(FakeRequest(GET, s"/${shortenedUrl.hash}")).get
      status(visit2) must equalTo(TEMPORARY_REDIRECT)
      header(LOCATION, visit2) must beSome.which(_ == "http://www.google.com")

      // Retrieve the click stats
      val statsResult = route(FakeRequest(GET, s"/v1/urls/${shortenedUrl.hash}/stats")).get
      status(statsResult) must equalTo(OK)
      contentAsJson(statsResult).as[StatsView] must equalTo(StatsView(clicks = 2))
    }

  }

}

Add a simple end-to-end functional integration test


object Solution {

  def main(args: Array[String]) {
    val _ = readInt
    val nums = readLine.split(" ").map(_.toInt)
    var zeros = 0
    val postZeros = (for (n <- nums.reverse) yield {
      val c = zeros
      if (n == 0) zeros += 1
      else zeros = 0
      c
    }).reverse
    for (_ <- 1 to readInt) {
      val Array(a, b) = readLine.split(" ").map(_.toInt)
      val zs = (b - a) min postZeros(a - 1)
      if (zs % 2 != 0 || nums(a - 1) % 2 != 0) println("Odd")
      else println("Even")
    }
  }
}

Add solution to problem Even Odd Query.

Add solution to problem Even Odd Query.


object Solution {
  import scala.collection.mutable.{HashSet, HashMap, PriorityQueue}

  // Dijkstra's Algorithm
  def minPathSum4(matrix: Array[Array[Int]]): Long = {
    val n = matrix.size
    val target = (n - 1, n - 1)
    val nodes = for {
                   i <- 0 until n
                   j <- 0 until n
                 } yield (i, j)
    // val reverseOrdering = Ordering[(Long, (Int, Int))]
    val nodesMap = Array.fill(n * n)(Long.MaxValue)
    val nodesSet = HashSet(nodes: _*)
    val nodePQueue = PriorityQueue(nodes.map(x => (-Long.MaxValue, x)): _*)
    // (Long.MaxValue, (0, 0)) happens to be the first element in the queue
    val minPath = 0L + matrix(0)(0)
    nodesMap(0) = minPath
    nodePQueue.enqueue((-minPath, (0, 0)))

    def extractMin(): (Long, (Int, Int)) = {
      var a = nodePQueue.dequeue
      while (! nodesSet(a._2)) {
        a = nodePQueue.dequeue
      }
      (-a._1, a._2)
    }

    while (nodesSet.size > 0) {
      val (length, (x, y)) = extractMin()
      // get the neighbors
      for {
        (i, j) <- List((-1, 0), (1, 0), (0, -1), (0, 1))
        if x + i >= 0 && x + i < n &&
        y + j >= 0 && y + j < n && nodesSet((x + i, y + j))
        dis = length + matrix(x + i)(y + j)
        if dis < nodesMap((x + i) * n + y + j)
      } {
        nodesMap((x + i) * n + y + j) = dis
        nodePQueue.enqueue((-dis, (x + i, y + j)))
      }
      nodesSet.remove((x, y))
      nodesMap(x * n + y) = length
      if (x == n - 1 && y == n - 1)
        return length
    }

    nodesMap(n * n - 1)
  }

  def main(args: Array[String]) {
    val n = readInt
    val matrix = (1 to n).map(x => readLine.split(" ").map(_.toInt)).toArray
    println(minPathSum4(matrix))
  }
}

Add solution to problem 83. Tuple2 will take too much space, using raw variable whenever possible.


package com.sageserpent.plutonium
import java.time.Instant

import com.sageserpent.americium.Unbounded
import com.sageserpent.plutonium.World.Revision

/**
  * Created by Gerard on 27/05/2016.
  */
class WorldRedisBasedImplementation[EventId] extends WorldImplementationCodeFactoring[EventId] {
  override def nextRevision: Revision = ???

  // NOTE: this increments 'nextRevision' if it succeeds, associating the new revision with 'revisionTime'.
  override def revise(events: Map[EventId, Option[Event]], asOf: Instant): Revision = ???

  // This produces a 'read-only' scope - raw objects that it renders from bitemporals will fail at runtime if an attempt is made to mutate them, subject to what the proxies can enforce.
  override def scopeFor(when: Unbounded[Instant], nextRevision: Revision): Scope = ???

  // This produces a 'read-only' scope - raw objects that it renders from bitemporals will fail at runtime if an attempt is made to mutate them, subject to what the proxies can enforce.
  override def scopeFor(when: Unbounded[Instant], asOf: Instant): Scope = ???

  // This creates a fresh world instance anew whose revision history is the same as the receiver world, with the important
  override def forkExperimentalWorld(scope: javaApi.Scope): World[EventId] = ???

  override def revisionAsOfs: Seq[Instant] = ???
}

Add skeleton of Redis-based world implementation.


package latis.ops

import org.junit.Assert.assertEquals
import org.junit.Test
import latis.dm.Dataset
import latis.dm.Function
import latis.dm.Real
import latis.dm.Sample
import latis.dm.Text
import latis.ops.filter.DailyNearestToNoon
import latis.reader.DatasetAccessor

class TestDailyNearestToNoon {

  @Test
  def test_utc_noon: Unit = {
    val ops = List(
      TimeFormatter("yyyy-MM-dd'T'HH:mm:ss"),
      DailyNearestToNoon()
    )
    val ds = DatasetAccessor.fromName("tsi_with_time_of_day").getDataset(ops)
    //latis.writer.AsciiWriter.write(ds)
    ds match {
      case Dataset(Function(it)) => it.next match {
        case Sample(Text(time), Real(tsi)) =>
          assertEquals("2000-03-08T11:30:00", time)
          assertEquals(1360.4933, tsi, 0)
      }
    }
  }

  @Test
  def test_offset_noon: Unit = {
    val ops = List(
      TimeFormatter("yyyy-MM-dd'T'HH:mm:ss"),
      DailyNearestToNoon(-8.0)
    )
    val ds = DatasetAccessor.fromName("tsi_with_time_of_day").getDataset(ops)
    //latis.writer.AsciiWriter.write(ds)
    ds match {
      case Dataset(Function(it)) => it.next match {
        case Sample(Text(time), Real(tsi)) =>
          assertEquals("2000-03-08T19:30:00", time)
          assertEquals(1360.4667, tsi, 0)
      }
    }
  }

}

Add unit tests for the DailyNearestToNoon operation


// Draft of higher order expressions
// ---------------------------------
// A higher order expression is a an expression that may contain unbound variables.
// Unbound variables are listed as arguments of the type lambda of the expression.
// Splicing can only be done on Expr[_ <: Any].
// `apply methods on higher order expression provide a way to replace the unbound variables.

// This can be used for HOAS quoted patterns to not return a lambda.
// The use would be the same as each higher order expression would have an apply method.
// But as it would be an expression, the expression would showable.
// The expression could also be directly transformed into a Term of the reflection API.

// Question: How to extend this to allow unbound type (Type) in the expression?

class Expr[+T <: AnyKind]
object Expr:
  extension [T, R](hoe: Expr[[_ >: T <: T] =>> R]) def apply(x1: Expr[T]): Expr[R] = ???
  extension [T1, T2, R](hoe: Expr[[_ >: T1 <: T1, _ >: T2 <: T2] =>> R]) def apply(x1: Expr[T1], x2: Expr[T2]): Expr[R] = ???
  // Are lower bounds in lambda parameters necessary?
  // How could this be generalized to n arguments?

def `'`[T](e: T): Expr[T] = ???
def `$`[T](e: Expr[T]): T = ???

def f(): Unit =
  val e: Expr[Int] = ???
  val hoe1: Expr[[T >: Int <: Int] =>> Int] = ??? // assumed to come from HOAS pattern with one unbound variable of type Int
  val hoe2: Expr[[T1 >: Int <: Int, T2 >: Int <: Int] =>> Int] = ??? // assumed to come from HOAS pattern with 2 unbound variables of type Int
  val e2: Expr[Int] = hoe1(e)
  val e3: Expr[Int] = hoe2(e, e)

  {
    `$`{e}
    `$`{e2}
    `$`{e3}
    `$`{hoe1(e)}
    `$`{hoe2(e, e)}
    `$`{hoe1} // error: Found: Expr[[T >: Int <: Int] =>> Int]), Required: Expr[Any] // may contain references to 1 unbound variable
    `$`{hoe2} // error // may contain references to 2 unbound variables
  }
  `'`{1}
  `'`{`$`{e}}
  `'`{??? : ([T >: Int <: Int] =>> Int)} // error: Missing type parameter for [T >: Int <: Int] =>> Int // not a valid quote literal expression

Add draft as regression tests

Add draft as regression tests

Draft higher order quoted expressions.


import stainless.lang._

object Copy2 {

  case class A[T](x: BigInt, b: B[T])
  case class B[T](y: BigInt, c: C[T])
  case class C[T](z: T)

  def double[T](a: A[T]): A[T] = {
    a.copy(
      x = a.x * 2,
      b = a.b.copy(
        y = a.b.y * 2,
        c = a.b.c.copy(z = a.b.c.z)
      )
    )
  }

  def sum[T](a: A[T]): BigInt = {
    a.x + a.b.y
  }

  def prop[T](a: A[T]) = (sum(a) * 2 == sum(double(a))).holds

}

Add synthetic copy method test with parametric class


package info.mukel.telegrambot4s.examples

import akka.actor.{Actor, ActorRef, Props, Terminated}
import info.mukel.telegrambot4s.actors.ActorBroker
import info.mukel.telegrambot4s.api.{AkkaDefaults, Commands, Polling}
import info.mukel.telegrambot4s.models.{Message, Update}

class PerChatRequestsBot(token: String) extends TestBot(token) with Polling with Commands with PerChatRequests {

  // Commands work as usual.
  on("/hello") { implicit msg => _ =>
    reply("Hello World!")
  }
}

trait PerChatRequests extends ActorBroker with Commands with AkkaDefaults {

  class Broker extends Actor {
    val chatActors = collection.mutable.Map[Long, ActorRef]()

    def receive = {
      case u : Update =>
        u.message.foreach { m =>
          val id = m.chat.id
          val handler = chatActors.getOrElseUpdate(m.chat.id, {
            val worker = system.actorOf(Props(new Worker), s"worker_$id")
            context.watch(worker)
            worker
          })
          handler ! m
        }

      case Terminated(worker) =>
        // This should be faster
        chatActors.find(_._2 == worker).foreach {
          case (k, _) => chatActors.remove(k)
        }

      case _ =>
    }
  }

  // Fo every chat a new worker actor will be spawned.
  // All requests will be routed through this worker actor; allowing to maintain a per-chat state.
  class Worker extends Actor {
    def receive = {
      case m : Message =>
        reply(self.toString)(m)

      case _ =>
    }
  }

  override val broker = Some(system.actorOf(Props(new Broker), "broker"))
}

Add per-chat request actor handler example


package lila.openingexplorer

import org.specs2.mutable._

import chess.Color

class LichessDatabasePackerTest extends Specification with LichessDatabasePacker {

  "lichess database packer" should {

    "pack a single game" in {
      val ref = GameRef("ref00000", Some(Color.White), SpeedGroup.Bullet, 1999)
      val entry = Entry.fromGameRef(ref)

      unpack(pack(entry)).select(RatingGroup.all, SpeedGroup.all).topGames mustEqual List(ref)
    }

    "pack two games" in {
      val g1 = GameRef("g0000001", Some(Color.Black), SpeedGroup.Classical, 2300)
      val g2 = GameRef("g0000002", None, SpeedGroup.Classical, 2455)
      val entry = Entry.fromGameRef(g1).withGameRef(g2)

      unpack(pack(entry)).select(RatingGroup.all, SpeedGroup.all).topGames.toSet mustEqual Set(g1, g2)
    }

  }

}

Add failing tests for entry packing

Add failing tests for entry packing


package uk.ac.wellcome.platform.recorder

import org.scalatest.{FunSpec, Matchers}
import uk.ac.wellcome.messaging.test.fixtures.{Messaging, SQS}
import uk.ac.wellcome.models.work.internal.{IdentifierSchemes, SourceIdentifier, UnidentifiedWork}
import uk.ac.wellcome.s3.S3ObjectLocation
import uk.ac.wellcome.test.fixtures.LocalVersionedHybridStore

class RecorderFeatureTest
    extends FunSpec
      with Matchers
      with fixtures.Server
      with LocalVersionedHybridStore
      with Messaging
      with SQS {

  it("receives a transformed Work, and saves it to the VHS") {
    val title = "Not from Guildford after all"

    val work = UnidentifiedWork(
      title = Some(title),
      sourceIdentifier = SourceIdentifier(
        identifierScheme = IdentifierSchemes.miroImageNumber,
        value = "V0237865",
        ontologyType = "Work"
      ),
      version = 1
    )

    withLocalSqsQueue { queue =>
      withLocalS3Bucket { bucket =>
        withLocalDynamoDbTable { table =>
          withVersionedHybridStore(bucket = bucket, table = table) { _ =>

            val flags = sqsLocalFlags(queue) ++ s3LocalFlags(bucket) ++ dynamoDbLocalEndpointFlags(table)
            withServer(flags) { _ =>

              val messageBody = put[UnidentifiedWork](
                obj = work,
                location = S3ObjectLocation(
                  bucket = bucket.name, key = "work_message.json"
                )
              )

              sqsClient.sendMessage(queue.url, messageBody)

              eventually {
                assertStored[UnidentifiedWork](bucket, table, work)
              }
            }
          }
        }
      }
    }
  }

}

Implement the first pass of a feature test for the recorder


/*
 * Copyright (c) 2011 Miles Sabin
 *
 * 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 shapeless

import TypeOperators._

class TypeOperatorTests {
  import org.junit.Test
  import org.junit.Assert._

  @Test
  def testImplicitScopeForTaggedType {
    val x = tag[ATag](1)
    val s: String = x
    assertEquals(ATag.message, s)
  }
}

trait ATag
object ATag {

  val message = "This object has ATag tag type"

  implicit def taggedToString[T](value: T with Tagged[ATag]): String = message
}

Add test that tagged-types search the tag's implicit scope


package pureconfig

import pureconfig.DerivationChecks._

class DerivationSuite extends BaseSuite {

  class Custom(x: Int, s: String)
  class Custom2(x: Int, s: String)

  sealed trait Conf
  case class ConfA(a: Boolean, b: Option[Boolean]) extends Conf
  sealed trait ConfB extends Conf
  case class ConfB1(a: Int) extends ConfB
  case class ConfB2(a: String) extends ConfB
  case class ConfC(a: Option[Custom], b: Custom2) extends Conf

  case class RecConf1(a: RecConf2)
  case class RecConf2(a: RecConf1)

  case class RecFailConf1(a: RecFailConf2)
  case class RecFailConf2(a: RecFailConf1, b: Custom)

  val customReader: ConfigReader[Custom] = ConfigReader.fromFunction(_ => Right(new Custom(0, "")))
  val customReader2: ConfigReader[Custom2] = ConfigReader.fromFunction(_ => Right(new Custom2(0, "")))

  behavior of "Derivation"

  it should "always materialize an implicit when it can be found" in {
    implicitly[Derivation[ConfigReader[Int]]]
    implicitly[Derivation[ConfigReader[List[Int]]]]
    implicitly[Derivation[ConfigReader[ConfA]]]
    implicitly[Derivation[ConfigReader[ConfB]]]
    implicitly[Derivation[ConfigReader[RecConf1]]]
    implicitly[Derivation[ConfigReader[RecConf2]]]

    {
      implicit val cr = customReader
      implicit val cr2 = customReader2
      implicitly[Derivation[ConfigReader[Custom]]]
      implicitly[Derivation[ConfigReader[ConfC]]]
      implicitly[Derivation[ConfigReader[Conf]]]
    }
  }

  it should "fail with a message indicating the root reason when an implicit cannot be found" in {
    illTyped(
      "implicitly[Derivation[ConfigReader[Custom]]]",
      "Could not find a ConfigReader instance for type Custom")

    illTyped(
      "implicitly[Derivation[ConfigReader[ConfC]]]",
      "Could not derive a ConfigReader instance for type ConfC, because:",
      "  - missing a ConfigReader instance for type Option\\[Custom\\], because:",
      "    - missing a ConfigReader instance for type Custom",
      "  - missing a ConfigReader instance for type Custom2")

    illTyped(
      "implicitly[Derivation[ConfigReader[Conf]]]",
      "Could not derive a ConfigReader instance for type Conf, because:",
      "  - missing a ConfigReader instance for type ConfC, because:",
      "    - missing a ConfigReader instance for type Option\\[Custom\\], because:",
      "      - missing a ConfigReader instance for type Custom",
      "    - missing a ConfigReader instance for type Custom2")

    illTyped(
      "implicitly[Derivation[ConfigReader[RecFailConf1]]]",
      "Could not derive a ConfigReader instance for type RecFailConf1, because:",
      "  - missing a ConfigReader instance for type RecFailConf2, because:",
      "    - missing a ConfigReader instance for type Custom")

    illTyped(
      "implicitly[Derivation[ConfigReader[RecFailConf2]]]",
      "Could not derive a ConfigReader instance for type RecFailConf2, because:",
      "  - missing a ConfigReader instance for type Custom")
  }
}

Add a test suite for Derivation in ConfigReaders