package scala.in.programming.abstract_internal_control

/**
  * @author loustler
  * @since 02/26/2017 17:27
  */
object Currying {
  /**
    * Currying the function that given parameter.
    *
    * @param x To currying function 1.
    * @param y like x. To currying function 2.
    * @return returns curreid function you wanted.
    */
  def curriedSum(x: Int)(y: Int) = x + y

  /**
    * Curry to function what i know.<br>
    *
    * It is example to use this function.
    * {{{
    *   val number: Int = 5
    *   val sumFunc = (x: Int, y: Int) => x + y
    *
    *   currying(number, sumFunc) // It returns like (5, Int) => 5 + Int
    *   currying(number, sumFunc)(5) // It returns 10
    * }}}
    *
    * @param x A types variable.
    * @param f To currying function.
    * @tparam A Generics type you wanted.
    * @tparam B Generics type you wanted.
    * @return Returns curried function you want.
    */
  def currying[A, B](x: A, f: (A, A) => B): A => B =
    a => f(x, a)

  def first(x: Int) = (y: Int) => x + y // It work same curriedSum function.
}

Add example for currying in scala.

Add example for currying in scala.


object Solution {

  def main(args: Array[String]) {
    for (_ <- 1 to readInt) {
      val Array(x, y) = readLine.split(" ").map(_.toInt)
      val Array(w, b, z) = readLine.split(" ").map(_.toInt)
      val cost1 = 1L * x * w + 1L * y * b
      val cost2 =
        if (w > b) 1L * x * (b + z) + 1L * y * b
        else 1L * x * w + 1L * y * (w + z)
      println(cost1 min cost2)
    }
  }
}

Add solution to problem Taum and B'day.

Add solution to problem Taum and B'day.


package com.nthportal.shell

import org.scalatest.{FlatSpec, Matchers}

class DefaultCommandTest extends FlatSpec with Matchers {
  behavior of "Default Command"

  it should "return `None` for `description` and `help` methods" in {
    val c = new Command {
      override val name: String = "something"

      override def execute(args: ImmutableSeq[String])(implicit sink: OutputSink): Unit = {}
    }

    c.description should be(None)
    c.help(Nil) should be(None)
    c.help(List(c.name)) should be(None)
    c.help(List("a", "list", "of", "sorts")) should be(None)
  }
}

Add test for default Command impl

Add test for default Command impl


/**
 * Illustrates writing data over JDBC
 */
package com.oreilly.learningsparkexamples.scala

import org.apache.spark._
import org.apache.spark.SparkContext._
import org.apache.spark.rdd.JdbcRDD
import java.sql.{PreparedStatement, DriverManager, ResultSet}
import org.apache.hadoop.mapred.lib.db._
import org.apache.hadoop.mapred.JobConf

object WriteSimpleDB {
  def main(args: Array[String]) {
    if (args.length < 1) {
      println("Usage: [sparkmaster]")
      exit(1)
    }
    val master = args(0)
    val sc = new SparkContext(master, "WriteSimpleJdbc", System.getenv("SPARK_HOME"))
    val data = sc.parallelize(List(("cat1", 1)))
    // foreach partition method
    data.foreachPartition{records =>
      records.foreach(record => println("fake db write"))
    }
    // DBOutputFormat approach
    val records = data.map(e => (catRecord(e._1, e._2), null))
    val tableName = "table"
    val fields = Array("name", "age")
    val jobConf = new JobConf()
    DBConfiguration.configureDB(jobConf, "com.mysql.jdbc.Driver", "jdbc:mysql://localhost/test?user=holden")
    DBOutputFormat.setOutput(jobConf, tableName, fields:_*)
    records.saveAsHadoopDataset(jobConf)
  }
  case class catRecord(name: String, age: Int) extends DBWritable {
    override def write(s: PreparedStatement) {
      s.setString(1, name)
      s.setInt(2, age)
    }
    override def readFields(r: ResultSet) = {
      // blank since only used for writing
    }
  }

  def createConnection() = {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    DriverManager.getConnection("jdbc:mysql://localhost/test?user=holden");
  }

  def extractValues(r: ResultSet) = {
    (r.getInt(1), r.getString(2))
  }
}

Add a simple write example

Add a simple write example


package hmda.publication.reports.protocol

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

class MinorityStatusEnumProtocolSpec extends PropSpec with PropertyChecks with MustMatchers with MinorityStatusEnumProtocol {

  forAll(minorityStatusEnumGen) { m =>
    m.toJson.convertTo[MinorityStatusEnum] mustBe m
  }
}

Add minority status enum protocol test

Add minority status enum protocol test


package scala.actors.controlflow

import org.testng.annotations.{Test, BeforeMethod}

import org.scalatest.testng.TestNGSuite
import org.scalatest.prop.Checkers
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary._
import org.scalacheck.Gen
import org.scalacheck.Prop._
import org.scalatest._

import scala.actors.controlflow.ControlFlow._

/**
 * Tests for control flow.
 *
 * @author Rich Dougherty
 */
class AsyncFunctionSuite extends TestNGSuite with Checkers {

  // XXX: Make shared function.
  private[this] def asyncTest(msec: Long)(body: => Unit) =
    callWithCCWithin(msec) (asAsync(() => body))

  val addOne = asAsync { x: Int => x + 1 }
  val double = asAsync { x: Int => x * 2 }
  val two = asAsync { () => 2 }

  @Test
  def testAsyncFunction = {
    assert(callWithCC(addOne(2) _) == 3)
    assert(callWithCC(double(2) _) == 4)
    assert(callWithCC((addOne andThen double)(2) _) == 6)
    assert(callWithCC((addOne andThen double)(2) _) == 6)
    assert(callWithCC((double andThen addOne)(2) _) == 5)
    assert(callWithCC((addOne compose double)(2) _) == 5)
    assert(callWithCC((double compose addOne)(2) _) == 6)

    assert(callWithCC(two) == 2)
    assert(callWithCC((two andThen addOne)) == 3)
    assert(callWithCC((two andThen double)) == 4)
    assert(callWithCC((two andThen addOne andThen double)) == 6)
    assert(callWithCC((two andThen addOne andThen double)) == 6)
    assert(callWithCC((two andThen double andThen addOne)) == 5)
    assert(callWithCC((two andThen (addOne compose double))) == 5)
    assert(callWithCC((two andThen (double compose addOne))) == 6)
  }

}

Restructure test files (missed this file).


package jp.sf.amateras.solr.scala.sample

import jp.sf.amateras.solr.scala.async._
import jp.sf.amateras.solr.scala.Order

object AsyncSolrClientSample extends App {

  val client = new AsyncSolrClient("http://localhost:8983/solr")

  client.query("name:%name%")
        .fields("id", "manu", "name")
        .facetFields("manu")
        .sortBy("id", Order.asc)
        .getResultAsMap(Map("name" -> "ThinkPad -X201s")){ result =>
    result.documents.foreach { doc =>
      println("id: " + doc("id"))
      println("  manu: " + doc.get("manu").getOrElse("<NULL>"))
      println("  name: " + doc("name"))
    }
  }

}

Add an example of async API.

Add an example of async API.


package modules.user.repositories

import core.slick.{SchemaInitializer, SchemaUtil}
import javax.inject.Inject
import modules.user.model.User
import slick.jdbc.SQLiteProfile.api._
import slick.lifted.TableQuery

import scala.concurrent.{ExecutionContext, Future}

class UserSchemaInitializer @Inject()(database: Database)
                                     (implicit executionContext: ExecutionContext) extends SchemaInitializer
  with SchemaUtil {

  val users: TableQuery[User.Table] = TableQuery[User.Table]

  override def create(): Future[Unit] = {
    withTable(database, users, User.name, _.isEmpty) {
      DBIO.seq(users.schema.create)
    }
  }

  override def drop(): Future[Unit] = {
    withTable(database, users, User.name, _.nonEmpty) {
      DBIO.seq(users.schema.drop)
    }
  }
}

Add schema initializer for 'User' table

Add schema initializer for 'User' table


/*
 * Copyright 2015 – 2016 Martin Seeler
 *
 * 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.martinseeler.rxoanda.accounts

import cats.data.Xor
import io.circe
import io.circe.DecodingFailure
import org.scalatest._

import circe.parse._

class BaseAccountDecoderSpec extends FlatSpec with Matchers {

  behavior of "The BaseAccount Decoder"

  it must "parse a short account info from valid json" in {
    val json =
      """
        |{
        | "accountId" : 8954947,
        | "accountName" : "Primary",
        | "accountCurrency" : "USD",
        | "marginRate" : 0.05
        |}
      """.stripMargin
    decode[BaseAccount](json) should matchPattern {
      case Xor.Right(BaseAccount(8954947L, "Primary", "USD", 0.05)) ⇒
    }
  }

  it must "fail on missing property" in {
    val json =
      """
        |{
        | "accountId" : 8954947,
        | "accountCurrency" : "USD",
        | "marginRate" : 0.05
        |}
      """.stripMargin
    decode[BaseAccount](json) should matchPattern {
      case Xor.Left(e: DecodingFailure) ⇒ //...
    }
  }

  it must "parse the account list from valid json" in {
    val json =
      """
        |{
        | "accounts": [
        |   {
        |    "accountId" : 8954947,
        |    "accountName" : "Primary",
        |    "accountCurrency" : "USD",
        |    "marginRate" : 0.05
        |   },
        |   {
        |    "accountId" : 8954950,
        |    "accountName" : "SweetHome",
        |    "accountCurrency" : "CAD",
        |    "marginRate" : 0.02
        |   }
        | ]
        |}
      """.stripMargin
    decode[Vector[BaseAccount]](json) should matchPattern {
      case Xor.Right(Vector(BaseAccount(8954947L, "Primary", "USD", 0.05), BaseAccount(8954950L, "SweetHome", "CAD", 0.02))) ⇒ //...
    }
  }

}

Add test for base account decoder

Add test for base account decoder


object Solution {

  def testSorted(nums: Array[Int]): String = {
    def isSorted(nums: Array[Int], lo: Int, hi: Int): Boolean =
      (lo + 1 to hi).forall(x => nums(x) >= nums(x - 1))

    def exch(i: Int, j: Int) {
      val temp = nums(i)
      nums(i) = nums(j)
      nums(j) = temp
    }

    if (isSorted(nums, 0, nums.size - 1)) "yes"
    else {
      val sortedNums = nums.sorted
      val leftIndex = (0 until nums.size).find(x => nums(x) != sortedNums(x)).get
      val rightIndex =
        (nums.size - 1 to 0 by -1).find(x => nums(x) != sortedNums(x)).get
      exch(leftIndex, rightIndex)
      if (isSorted(nums, leftIndex, rightIndex))
        s"yes\nswap ${leftIndex+1} ${rightIndex+1}"
      else {
        exch(leftIndex, rightIndex)
        val seg = nums.slice(leftIndex, rightIndex + 1).reverse
        if (isSorted(seg, 0, seg.size - 1))
          s"yes\nreverse ${leftIndex+1} ${rightIndex+1}"
        else "no"
      }
    }
  }

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

Add solution to problem Almost Sorted.

Add solution to problem Almost Sorted.


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

package com.sparklingpandas.sparklingml.param

import sys.process._

import org.scalatest.FunSuite

class SharedParamsCodeGenTest extends FunSuite {
  test("verify the generated code is up to date") {
    SharedParamsCodeGen.main(Array[String]())
    val basePath = "scala/com/sparklingpandas/sparklingml/param/"
    val result = s"git diff -q ./src/main/${basePath}/sharedParams.scala".!
    assert(result === 0)
  }
}

Test the params codegen too

Test the params codegen too


package com.example

object Decoration extends App {
  trait Logger {
    def debug(msg: String)
    def error(msg: String)
  }

  def log[A, B](logger: Logger)(fn: A => B): A => B = {
    input =>
      try {
        logger.debug(s"Start. <= $input")
        val start = System.nanoTime
        val output = fn(input)
        val time = (System.nanoTime - start) / 1000000
        logger.debug(s"End $time ms. => $output")
        output
      } catch {
        case e: Exception =>
          logger.error(e.toString)
          throw e
      }
  }

  trait DB {
    def begin
    def commit
    def rollback
    def select(sql: String)
  }

  class TestDB extends DB {
    def begin = println("[begin]")
    def commit = println("[commit]")
    def rollback = println("[rollback]")
    def select(sql: String) = println(s"[select] $sql")
  }

  def transaction[T](fn: DB => T): DB => T = {
    db =>
      try {
        db.begin
        val result = fn(db)
        db.commit
        result
      } catch {
        case e: Exception =>
          db.rollback
          throw e
      }
  }

  class TestLogger extends Logger {
    def debug(msg: String) = println(s"[Debug] $msg")
    def error(msg: String) = println(s"[Error] $msg")
  }

  def testLogger = new TestLogger
  def testDB = new TestDB

  val selectPerson = log(testLogger) {
    transaction {
      db =>
        db.select("select * from person")
        Thread.sleep(103)
        //throw new RuntimeException("Error")
        "Alex Smith"
    }
  }

  selectPerson(testDB)
}

Add FP decoration pattern sample

Add FP decoration pattern sample


import org.apache.spark._
import org.apache.spark.rdd.RDD
import org.apache.spark.mllib.random.RandomRDDs

object GenerateScalingData {
  /**
   * Generate a Goldilocks data set. We expect the key to follow an exponential
   * distribution and the data its self to be normal.
   */
  def generateGoldilocks(sc: SparkContext, size: Long): RDD[List[String]] = {
    val keyRDD = RandomRDDs.exponentialRDD(sc, mean = 1000,  size = size).map(_.toInt)
    val valuesRDD = RandomRDDs.normalVectorRDD(sc, numRows = 1, numCols = 500)
    keyRDD.zip(valuesRDD).map{case (k, v) => List(k.toString) ++ v.toArray.map(_.toString)}
  }
}

Add a quick function for generating some test like data


import scala.annotation.static

class Foo{
  class Bar {
    def qwa =
     Bar.field
         // 0: invokestatic  #31                 // Method Foo$Bar$.field:()I
         // 3: ireturn
  }
  object Bar {
     @static
     val field = 1
   }
}

object Foo{
 @static
 def method = 1

 @static
 val field = 2

 @static
 var mutable = 3

 @static
 def accessor = field
}

object Test {
 import Foo._
 def main(args: Array[String]): Unit = {
   method + field + mutable + accessor
 }
}

class WithLazies{
  @volatile lazy val s = 1
  //         98: getstatic     #30                 // Field WithLazies$.OFFSET$0:J
}

Add test that was used to see if @static works.


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

package com.comcast.money.akka.stream.acceptance

import akka.actor.ActorSystem
import akka.testkit.TestKit
import com.comcast.money.akka.MoneyExtension
import com.typesafe.config.ConfigFactory
import org.scalatest.{Matchers, WordSpecLike}

class MoneyExtensionSpec(_system: ActorSystem) extends TestKit(_system) with WordSpecLike with Matchers {

  def this() = this{
    val configString: String =
      """
        | money {
        |  enabled = false
        | }""".stripMargin

    ActorSystem("MoneyExtensionSpec", ConfigFactory.parseString(configString))
  }

  "A MoneyExtension" should {
    "construct a new MoneyExtension from an ActorSystem without Money config" in {
      MoneyExtension(system) shouldBe a[MoneyExtension]
    }
  }

}

Add test for disabled Money config MoneyExtension creation


import scala.io.Source

val words = Source.fromFile(args(0))
  .getLines()
  .flatMap(_.split(" "))
  .toSeq

words
  .groupBy(w => ((w.length - 1) / 5.0).toInt)
  .mapValues(_.size)
  .toSeq
  .sortBy(_._1)
  .foreach { case (l, n) =>
    val i = l * 5 + 1
    println(s"$i-${i + 4} : $n")
  }

Add script for word histogram data extraction


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

package net.liftweb
package actor

import org.specs2.mutable.Specification

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

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

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

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2

      mockActor.hasReceivedMessage_?(MockSpecActorMessage1) must beTrue
    }

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

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2

      mockActor.hasReceivedMessage_?(MockSpecActorMessage3) must beFalse
    }

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

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2
      mockActor ! MockSpecActorMessage3

      mockActor.messageCount must_== 3
    }
  }

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

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2

      mockActor.hasReceivedMessage_?(MockSpecActorMessage1) must beTrue
    }

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

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2

      mockActor.hasReceivedMessage_?(MockSpecActorMessage3) must beFalse
    }

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

      mockActor ! MockSpecActorMessage1
      mockActor ! MockSpecActorMessage2
      mockActor ! MockSpecActorMessage3

      mockActor.messageCount must_== 3
    }
  }
}

Add specs for mock actors.

Add specs for mock actors.


package com.sksamuel.elastic4s.search.aggs

import com.sksamuel.elastic4s.RefreshPolicy
import com.sksamuel.elastic4s.http.ElasticDsl
import com.sksamuel.elastic4s.testkit.DiscoveryLocalNodeProvider
import org.scalatest.{FreeSpec, Matchers}

import scala.util.Try

class AvgAggregationHttpTest extends FreeSpec with DiscoveryLocalNodeProvider with Matchers with ElasticDsl {

  Try {
    http.execute {
      deleteIndex("avgagg")
    }.await
  }

  http.execute {
    createIndex("avgagg") mappings {
      mapping("buildings") fields(
        textField("name").fielddata(true),
        intField("height").stored(true)
      )
    }
  }.await

  http.execute(
    bulk(
      indexInto("avgagg/buildings") fields("name" -> "Willis Tower", "height" -> 1244),
      indexInto("avgagg/buildings") fields("name" -> "Burj Kalifa", "height" -> 2456),
      indexInto("avgagg/buildings") fields("name" -> "Tower of London", "height" -> 169)
    ).refresh(RefreshPolicy.Immediate)
  ).await

  "avg agg" - {
    "should return the avg for the context" in {

      val resp = http.execute {
        search("avgagg").matchAllQuery().aggs {
          avgAgg("agg1", "height")
        }
      }.await.right.get.result
      resp.totalHits shouldBe 3
      val agg = resp.aggs.avg("agg1")
      agg.value > 1289 shouldBe true
      agg.value > 1290 shouldBe false
    }
  }
}

Fix Extended Stats Aggregation in http client (test included)


package view

import org.parboiled.common.StringUtils
import org.pegdown._
import org.pegdown.LinkRenderer.Rendering
import org.pegdown.ast.{WikiLinkNode, VerbatimNode}
import scala.collection.JavaConverters._

object Markdown {

//  /**
//   * Converts the issue number and the commit id to the link.
//   */
//  private def markdownFilter(value: String, repository: service.RepositoryService.RepositoryInfo)(implicit context: app.Context): String = {
//    value
//      .replaceAll("#([0-9]+)", "[$0](%s/%s/%s/issue/$1)".format(context.path, repository.owner, repository.name))
//      .replaceAll("[0-9a-f]{40}", "[$0](%s/%s/%s/commit/$0)".format(context.path, repository.owner, repository.name))
//  }

  /**
   * Converts Markdown of Wiki pages to HTML.
   */
  def toHtml(value: String, repository: service.RepositoryService.RepositoryInfo,
             wikiLink: Boolean)(implicit context: app.Context): String = {
    new PegDownProcessor(Extensions.AUTOLINKS | Extensions.WIKILINKS | Extensions.FENCED_CODE_BLOCKS | Extensions.TABLES)
      .markdownToHtml(value,
        new GitBucketLinkRender(wikiLink, context, repository),
        Map[String, VerbatimSerializer](VerbatimSerializer.DEFAULT -> new GitBucketVerbatimSerializer).asJava)
  }
}

class GitBucketLinkRender(wikiLink: Boolean, context: app.Context,
                          repository: service.RepositoryService.RepositoryInfo) extends LinkRenderer {

  override def render(node: WikiLinkNode): Rendering = {
    if(wikiLink){
      super.render(node)
    } else {
      try {
        val text = node.getText
        val (label, page) = if(text.contains('|')){
          val i = text.indexOf('|')
          (text.substring(0, i), text.substring(i + 1))
        } else {
          (text, text)
        }
        val url = "%s/%s/%s/wiki/%s".format(context.path, repository.owner, repository.name,
          java.net.URLEncoder.encode(page.replace(' ', '-'), "UTF-8"))
        new Rendering(url, label)
      } catch {
        case e: java.io.UnsupportedEncodingException => throw new IllegalStateException();
      }
    }
  }

}

class GitBucketVerbatimSerializer extends VerbatimSerializer {

  def serialize(node: VerbatimNode, printer: Printer) {
    printer.println.print("
")
    var text: String = node.getText
    while (text.charAt(0) == '\n') {
      printer.print("
")
      text = text.substring(1)
    }
    printer.printEncoded(text)
    printer.print("
")
  }

}

Add syntax highlighting in Wiki.

Add syntax highlighting in Wiki.


class MultiApply extends (Int => Int) with ((Int, Int) => Int) {
  def apply(x: Int): Int = x + x
  def apply(x: Int, y: Int): Int = x * y
}

@main
def Test = {
  val fun = new MultiApply
  assert(fun(2) == 4)
  assert(fun(2, 3) == 6)
}

Add forgotten test for function specialization


package org.precompiler.scala101.ch06

/**
  * Created by RL on 8/27/17.
  */
object HigherOrderFunctions {
  def calc(n: Int, fn: Int => Int): Int = {
    var result = 0
    for (i <- 1 to n) {
      result += fn(i)
    }
    result
  }
  def main(args: Array[String]): Unit = {
    println(calc(10, i => i))
    println(calc(10, i => i * 10))
    println(calc(10, i => if (i % 2 == 0) i else 0))
  }
}

Add higher order function demo

Add higher order function demo


package codesample.scala.coursera.course1.week4

object ScalaListsPartOne {

  def insSort(xs: List[Int]): List[Int] = xs match {
    case Nil => List()
    case y :: ys => insert(y, insSort(ys))
  }
  def insert(x: Int, xs: List[Int]): List[Int] = xs match {
    case Nil => List(x)
    case y :: ys => if (x <= y) x :: xs else y :: insert(x, ys)
  }

  def main(args: Array[String]): Unit = {
    val list = "Keks" :: "Magic" :: "And shit" :: Nil // You can not omit :: Nil
    val otherList = "abc" :: "def" :: Nil
    val mergedList: List[String] = list ::: otherList

    println("list: " + list)
    println("merged list: " + mergedList)

    println("Head of first: " + list.head)
    println("Tail of first: " + list.tail)

    // Isertion sort!
    val someList = List(9,5,3,2,1,6,3,2)
    println("Insertion sorted list: " + someList + " => " + insSort(someList))
  }

}

Add insertion sort example in scala

Add insertion sort example in scala


class Foo[A]
class Bar[B]
class Baz[C] extends Bar[C]

object Test1 {
  type Alias[F[X] <: Foo[X]] = F[Int]

  val x: Alias[Bar] = new Bar[Int] // error: Type argument [X0] -> Bar[X0] does not conform to upper bound [X0] -> Foo[X0]

  def foo[F[X] <: Foo[X]] = ()
  foo[Bar] // error: Type argument [X0] -> Bar[X0] does not conform to upper bound [X0] -> Foo[X0]

  def bar[B[X] >: Bar[X]] = ()
  bar[Bar] // ok
  bar[Baz] // // error: Type argument [X0] -> Baz[X0] does not conform to lower bound [X0] -> Bar[X0]
  bar[Foo] // error: Type argument [X0] -> Foo[X0] does not conform to lower bound [X0] -> Bar[X0]

  def baz[B[X] >: Baz[X]] = ()
  baz[Bar] //ok
  baz[Baz] //ok
  baz[Foo] // error: Type argument [X0] -> Foo[X0] does not conform to lower bound [X0] -> Baz[X0]

}

Add test case for hk bounds checking

Add test case for hk bounds checking


package com.github.log0ymxm.mapper.clustering

import org.scalatest._

class CutoffSpec extends FunSuite {
  val diameter = 1.00
  val linkage = Seq(
    (0, 7, 0.16, 2),
    (2, 3, 0.17, 2),
    (1, 7, 0.19, 3),
    (0, 2, 0.26, 5),
    (5, 7, 0.28, 6),
    (4, 5, 0.35, 7),
    (2, 6, 0.4, 8)
  )

  test("first gap chooses the right number of clusters") {
    assert(6 == Cutoff.firstGap(linkage, diameter, 0.05))
    assert(2 == Cutoff.firstGap(linkage, diameter, 0.1))
    assert(1 == Cutoff.firstGap(linkage, diameter, 0.6))
  }
}

Add test case for the first gap cutoff heuristic


package TurboRav

import Constants._
import Common._
import Chisel._

// Purely combinatorial Hazard Detection Unit
class HazardDetectionUnit() extends Module {

  val io = new HazardDetectionUnitIO()

  val load_use_rs1 = (
            ( io.hdu_mem.mem_read           &&
              io.hdu_mem.rd_addr != UInt(0) &&
              io.hdu_mem.rd_addr === io.hdu_exe.rs1_addr))

  val load_use_rs2 = (
            ( io.hdu_mem.mem_read           &&
              io.hdu_mem.rd_addr != UInt(0) &&
              io.hdu_mem.rd_addr === io.hdu_exe.rs2_addr))

  val load_use = load_use_rs1 || load_use_rs2

  val mult_busy = io.hdu_exe.mult_busy

  val fetchValidInstruction = io.hdu_fch.instructionValid

  // It is the responsebility of the pipeline stage
  // to insert bubbles when it is stalling.
  io.hdu_fch.stall := load_use || mult_busy || !fetchValidInstruction
  io.hdu_dec.stall := load_use || mult_busy
  io.hdu_exe.stall := load_use || mult_busy
  io.hdu_mem.stall := Bool(false)
  io.hdu_wrb.stall := Bool(false)

}

Add hazard detection unit for real this time


sonatypeProfileName := "co.theasi"

// For Maven Central
pomExtra in Global := {
  <url>https://github.com/the-asi/plotly-client</url>
  <licenses>
    <license>
      <name>MIT</name>
      <url>https://opensource.org/licenses/MIT</url>
    </license>
  </licenses>
  <scm>
    <connection>scm:git:github.com/the-asi/plotly-client</connection>
    <developerConnection>scm:git:git@github.com:the-asi/plotly-client</developerConnection>
    <url>github.com/the-asi/plotly-client</url>
  </scm>
  <developers>
    <developer>
      <id>pbugnion</id>
      <name>Pascal Bugnion</name>
      <url>pascalbugnion.net</url>
    </developer>
  </developers>
}

Add POM coordinates for Maven central.

Add POM coordinates for Maven central.


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

object AddMailchimpServiceCredentials {
  implicit val formats = DefaultFormats

  def run = {
    println("Adding Mailchimp Service credentials for users...")

    for {
      user <- User.findAll
      tab <- Tab.findAll("userId" -> user._id)
      service <- tab.service
    } {
      service match {
        case MailChimpServiceWrapper(apiKey, _) =>
          println("Found API key " + apiKey + " for user " +  user.email)

          for {
            latestUser <- User.find(user._id)
              if ! latestUser.credentialsFor("Mailchimp").isDefined
          } {
            println("Adding API key to user service credentials.")
            val serviceCredential = UserServiceCredentials("Mailchimp", apiKey, Map("token" -> apiKey))
            User.update("_id" -> user._id, "$addToSet" ->(
              ("serviceCredentials" -> decompose(serviceCredential))
            ))
          }

        case _ =>
      }
    }
  }
}

Add a migration for Mailchimp credentials.


package test

import org.scalatest.FunSuite
import scala.offheap.malloc

class MallocSuite extends FunSuite {
  test("out of memory") {
    intercept[OutOfMemoryError] {
      // request 1PB of memory
      malloc.allocate(1024L * 1024L * 1024L * 1024L * 1024L)
    }
  }
}

Test that malloc.allocate throws OutOfMemoryError


package com.beyondframework.rhino

import org.mozilla.javascript.Context
import org.mozilla.javascript.Scriptable

object ContextOps {
  implicit def from(cx: Context): ContextOps = new ContextOps(cx)
}

class ContextOps(context: Context) {
  def newObject(scope: Scriptable, constructorName: String, args: AnyRef*): Scriptable =
    context.newObject(scope, constructorName, args.toArray)

  def newArray(scope: Scriptable, elements: AnyRef*): Scriptable =
    context.newArray(scope, elements.toArray)
}

Extend newObject and newArray methods of Rhino Context.

Currently, arguments must be wrapped in an array when using newObject
and newArray method. It makes code verbose.


package com.trueaccord.scalapb

package object compiler {
  @deprecated("Please use scalapb.compiler.Version", "0.7.0")
  val Version = _root_.scalapb.compiler.Version
}

Add deprecation alias for com.trueaccord.scalapb.compiler.Version


package ch.usi.inf.l3.sana.guod.modifiers

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

import tiny.modifiers.{Flags, Flag}
import primj.modifiers._
import ooj.modifiers._
import robustj.modifiers._
import modulej.modifiers._
import ppj.modifiers._

import org.objectweb.asm.Opcodes

trait ModifiersUtils {
  def modifiersToBytecode(flags: Flags): Int = {
    modifiersToBytecodeAux(flags.flagsAsSet.toList)
  }
  protected def modifiersToBytecodeAux(flags: List[Flag]): Int = flags match {
    case (f::fs)                  =>
      f match {
        case INTERFACE            =>
          Opcodes.ACC_INTERFACE + modifiersToBytecodeAux(fs)
        case ABSTRACT             =>
          Opcodes.ACC_ABSTRACT + modifiersToBytecodeAux(fs)
        case PUBLIC_ACC           =>
          Opcodes.ACC_PUBLIC + modifiersToBytecodeAux(fs)
        case PRIVATE_ACC          =>
          Opcodes.ACC_PRIVATE + modifiersToBytecodeAux(fs)
        case PROTECTED_ACC        =>
          Opcodes.ACC_PROTECTED + modifiersToBytecodeAux(fs)
        case FINAL                =>
          Opcodes.ACC_FINAL + modifiersToBytecodeAux(fs)
        case NATIVE               =>
          Opcodes.ACC_NATIVE + modifiersToBytecodeAux(fs)
        case STATIC               =>
          Opcodes.ACC_STATIC + modifiersToBytecodeAux(fs)
        case SYNCHRONIZED         =>
          Opcodes.ACC_SYNCHRONIZED + modifiersToBytecodeAux(fs)
        case VOLATILE             =>
          Opcodes.ACC_VOLATILE + modifiersToBytecodeAux(fs)
        case TRANSIENT            =>
          Opcodes.ACC_TRANSIENT + modifiersToBytecodeAux(fs)
        case _                    =>
          modifiersToBytecodeAux(fs)
      }
    case _                        => Opcodes.NOP
  }
}

object ModifiersUtils extends ModifiersUtils

Add modifiers utility to translate guod modifiers to JVMs


object Solution {
  import scala.collection.mutable.HashMap

  // see
  // http://stackoverflow.com/questions/11161465/existence-of-a-permutation-under-constraints-interview-street-manipulative-nu
  // the second answer(Tuxdude's)
  def manipulativeK(nums: Array[Int]): Int = {
    val n = nums.size
    val maxBits = nums.max.toBinaryString.length - 1
    for (ki <- maxBits to 0 by -1) {
      val bitCounts = new HashMap[Int, Int]() {
        override def default(x: Int) = 0
      }
      for (num <- nums) bitCounts(num >> ki) += 1
      if (bitCounts.forall(x => x._2 <= n / 2)) return ki
    }
    -1
  }

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

Add solution to problem Manipulative Numbers


/*
 * Copyright 2017 Spotify AB.
 *
 * 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.spotify.scio.coders

import java.nio.ByteBuffer

import com.esotericsoftware.kryo.io.{Input, Output}
import com.spotify.scio.util.ScioUtil
import com.twitter.chill.{Kryo, KryoSerializer}
import org.scalatest.{FlatSpec, Matchers}

import scala.reflect.ClassTag

class JIterableWrapperSerializerTest extends FlatSpec with Matchers {

  private def testRoundTrip[T : ClassTag](ser: JIterableWrapperSerializer[T],
                                  elems: Iterable[T],
                                  k: Kryo = KryoSerializer.registered.newKryo(),
                                  bufferSize: Int = 1024): Unit = {
    val o = ByteBuffer.allocate(bufferSize).array()
    ser.write(k, new Output(o), elems)
    elems should contain theSameElementsAs ser.read(k, new Input(o), ScioUtil.classOf[Iterable[T]])
  }

  "JIterableWrapperSerializer" should "cope with the internal buffer overflow" in {
    val ser = new JIterableWrapperSerializer[String](128, 128)
    val input = List.fill(100)("foo")
    testRoundTrip(ser, input)
  }

  it should "be able to serialize a object larger than initial capacity of the internal buffer" in {
    val ser = new JIterableWrapperSerializer[String](1)
    val input = Seq("o" * 3)
    testRoundTrip(ser, input)
  }

  it should "be able to serialize a object larger than max capacity of the internal buffer" in {
    val ser = new JIterableWrapperSerializer[String](5, 10)
    val input = Seq("o" * 10)
    testRoundTrip(ser, input)
  }

}

Add tests for JIterableWrapperSerializer internal buffer


object Solution {
  def isDivisible(digits: IndexedSeq[Int], idx: Int) = idx match {
    case 1 => digits(3) % 2 == 0
    case 2 => digits.slice(2, 5).sum % 3 == 0
    case 3 => digits(5) % 5 == 0
    case 4 => digits.slice(4, 7).reduceLeft({ _ * 10 + _ }) % 7 == 0
    case 5 => digits.slice(5, 8).reduceLeft({ _ * 10 + _ }) % 11 == 0
    case 6 => digits.slice(6, 9).reduceLeft({ _ * 10 + _ }) % 13 == 0
    case 7 => digits.slice(7, 10).reduceLeft({ _ * 10 + _ }) % 17 == 0
  }
  def main(args: Array[String]) {
    val n = readLine.toInt
    val nums = (0 to n).permutations
      .filter { x => (0 to n - 3).forall(y => isDivisible(x, y + 1)) }
      .map { x => x.foldLeft(0l) { _ * 10 + _ } }
    println(nums.foldLeft(0l) { _ + _ })
  }
}

Add solution to problem 43. This code may not be very efficient as the 0-9 pandigital number takes 3.48s in the hackerrank env. But it works and there is no need to do more optimizations for now.


package ohnosequences.ivy

import org.scalatest._

/**
 * @author Michael Ahlers
 */
class S3UtilsSpec extends WordSpec with Matchers {

  "Getting buckets and keys" when {

    val scenarios =
      ("s3://bucket/p0/p1", ("bucket", "p0/p1")) ::
        ("s3://bucket/p0//p1", ("bucket", "p0/p1")) ::
        Nil

    scenarios foreach { case (given, (bucketName, objectKey)) =>
      s"""given "$given"""" must {
        s"""return bucket name "$bucketName"""" in {
          S3Utils.getBucket(given) should equal(bucketName)
        }
        s"""return object key "$objectKey"""" in {
          S3Utils.getKey(given) should equal(objectKey)
        }
      }
    }

  }

}

Verify bucket name and object key extraction (breaking change; TDD)


name := "sphere-sunrise"

organization := "io.sphere"

version := "1.0-SNAPSHOT"

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

scalaVersion := "2.10.4"

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

resolvers += Resolver.sonatypeRepo("snapshots")

resolvers += Resolver.sonatypeRepo("releases")

libraryDependencies ++=
  ("io.sphere.sdk.jvm" % "models" % "1.0.0-M11" withSources()) ::
  "io.sphere.sdk.jvm" %% "play-2_3-java-client" % "1.0.0-M11" ::
  "com.google.inject" % "guice" % "3.0" ::
  Nil

initialCommands in console := "import tutorial.ClientFactory.createClient;" +
  "import io.sphere.sdk.categories._;" +
  """println("Use 'val client = createClient()' to create a client instance.")"""

javaUnidocSettings

name := "sphere-sunrise"

organization := "io.sphere"

version := "1.0-SNAPSHOT"

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

scalaVersion := "2.10.4"

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

resolvers += Resolver.sonatypeRepo("snapshots")

resolvers += Resolver.sonatypeRepo("releases")

libraryDependencies ++=
  ("io.sphere.sdk.jvm" % "models" % "1.0.0-M12" withSources()) ::
  "io.sphere.sdk.jvm" %% "play-2_3-java-client" % "1.0.0-M12" ::
  "com.google.inject" % "guice" % "3.0" ::
  Nil

initialCommands in console := "import tutorial.ClientFactory.createClient;" +
  "import io.sphere.sdk.categories._;" +
  """println("Use 'val client = createClient()' to create a client instance.")"""

javaUnidocSettings

Update SPHERE.IO client to 1.0.0-M12.

Update SPHERE.IO client to 1.0.0-M12.


object Solution {

  def main(args: Array[String]) {
    val t = readLine.toInt
    for (_ <- 1 to t) {
      val n = readLine.toInt
      val (power, sub) = if ((n & 1) != 0) ((n + 3) / 2, 2) else (n / 2 + 1, 1)
      println(math.pow(2, power).toInt - sub)
    }
  }
}

Add solution to problem Utopian Tree.

Add solution to problem Utopian Tree.


object Solution {

  def minUnFairness(nums: IndexedSeq[Int], k: Int): Int = {
    val numsSorted = nums.sorted
    (0 to nums.size - k).map(i => numsSorted(i + k - 1) - numsSorted(i)).min
  }

  def main(args: Array[String]) {
    val (t, k) = (readLine.toInt, readLine.toInt)
    val nums = (1 to t).map(x => readLine.toInt)
    println(minUnFairness(nums, k))
  }
}

Add solution to problem Angry Children. The time complexity is O(nlog(n)).


package test

import org.specs2.mutable._

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

object FormSpec extends Specification {

  import controllers.Application.helloForm

  "HelloWorld form" should {

    "require all fields" in {
      val form = helloForm.bind(Map.empty)

      form.hasErrors must beTrue
      form.errors.size must equalTo(2)

      form("name").hasErrors must beTrue
      form("repeat").hasErrors must beTrue
      form("color").hasErrors must beFalse

      form.value must beNone
    }

    "require name" in {
      val form = helloForm.bind(Map("repeat" -> "10", "color" -> "red"))

      form.hasErrors must beTrue
      form.errors.size must equalTo(1)

      form("name").hasErrors must beTrue
      form("repeat").hasErrors must beFalse
      form("color").hasErrors must beFalse

      form.data must havePair("color" -> "red")
      form.data must havePair("repeat" -> "10")

      form("repeat").value must beSome.which(_ == "10")
      form("color").value must beSome.which(_ == "red")
      form("name").value must beNone

      form.value must beNone
    }

    "validate repeat as numeric" in {
      val form = helloForm.bind(Map("name" -> "Bob", "repeat" -> "xx", "color" -> "red"))

      form.hasErrors must beTrue
      form.errors.size must equalTo(1)

      form("name").hasErrors must beFalse
      form("repeat").hasErrors must beTrue
      form("color").hasErrors must beFalse

      form.data must havePair("color" -> "red")
      form.data must havePair("repeat" -> "xx")
      form.data must havePair("name" -> "Bob")

      form("repeat").value must beSome.which(_ == "xx")
      form("color").value must beSome.which(_ == "red")
      form("name").value must beSome.which(_ == "Bob")

      form.value must beNone
    }

    "be filled" in {
      val form = helloForm.bind(Map("name" -> "Bob", "repeat" -> "10", "color" -> "red"))

      form.hasErrors must beFalse

      form.data must havePair("color" -> "red")
      form.data must havePair("repeat" -> "10")
      form.data must havePair("name" -> "Bob")

      form("repeat").value must beSome.which(_ == "10")
      form("color").value must beSome.which(_ == "red")
      form("name").value must beSome.which(_ == "Bob")

      form.value must beSome.which { _ match {
        case ("Bob", 10, Some("red")) => true
        case _ => false
      }}
    }

  }

}

Add form specs to Scala helloworld

Add form specs to Scala helloworld


import stainless.lang._
import stainless.annotation._

object CastCorrectness {

  sealed abstract class List[@mutable T]
  case class Nil[@mutable T]() extends List[T]
  case class Cons[@mutable T](var head: T, var tail: List[T]) extends List[T]

  @pure
  def contains(self: List[Int], t: Int): Boolean =
    contents(freshCopy(self)).contains(t)

  @pure
  def contents(self: List[Int]): Set[Int] = {
    decreases(self)
    self match {
      case Nil() => Set.empty
      case Cons(head, tail) => contents(freshCopy(tail)) + head
    }
  }

  @pure
  def remove(self: List[Int], t: Int): List[Int] = {
    self match {
      case Nil() => freshCopy(Nil[Int]())
      case Cons(head, tail) if head == t => freshCopy(remove(tail, t))
      case Cons(head, tail) => freshCopy(Cons[Int](head, remove(tail, t)))
    }
  } ensuring {
    (ret: List[Int]) =>
      !contains(freshCopy(ret), t) &&
        contents(freshCopy(ret)).subsetOf(contents(freshCopy(self)))
  }

  @pure
  def remove_from_list(var0: List[Int]): Unit = {
    var list: List[Int] = freshCopy(var0)
    list match {
      case Cons(first_elem, _) =>
        list = remove(list, first_elem)
        if (contains(list, first_elem)) {
          error[Nothing]("still contained")
        }
      case _ => ()
    }
  }
}

Add test case for rewritings bug.

Add test case for rewritings bug.


/* Tests implicit parameters in the presence of context bounds.
 * See Section 7.4 of the Scala Language Specification.
 */
class C {

  def f[T: Manifest, S: Manifest](x: T, y: S)(implicit p: C) { }

}

Add test for SI-4839. No review.

Add test for SI-4839. No review.


package org.continuumio

package object bokeh {
    case class Percent(value: Double) {
        require(0.0 <= value && value <= 1.0)
    }

    implicit class IntPercent(value: Int) {
        def %% : Percent = Percent(value.toDouble/100)
    }
}

Add Percent and 100%% syntax

Add Percent and 100%% syntax


/*
 * sbt
 * Copyright 2011 - 2017, Lightbend, Inc.
 * Copyright 2008 - 2010, Mark Harrah
 * Licensed under BSD-3-Clause license (see LICENSE)
 */

package sbt.internal.util
package complete

import org.scalacheck._, Prop._

object DefaultParsersSpec extends Properties("DefaultParsers") {
  import DefaultParsers._

  property("validID == matches(ID, s)") = forAll((s: String) => validID(s) == matches(ID, s))
}

Add prop-based test for the validID re-impl


import stainless.lang._

object LifeAfterWhile {
  def f(N: BigInt): BigInt = {
    require(0 <= N)
    var i: BigInt = 0
    (while (i < N) {
      decreases(N - i)
      if (i == 42)
        return N - 200
      else
        i = i + 1
    }).invariant(0 <= i && i <= N)
    i = i - 100
    i
  } ensuring (res => res <= N - 100)
}

Add another @vkuncak example for return

Add another @vkuncak example for return


import shapeless._
import shapeless.labelled._
import org.scalacheck._
import hmrc.smartstub._

object AutoGen {

  def apply[A](implicit e: Gen[A]): Gen[A] = e

  trait GenProvider[A] { def gen(str: String): Gen[A] }

  implicit def strProvider: GenProvider[String] = new GenProvider[String] {
    override def gen(name: String): Gen[String] = name match {
      case "forename" => Gen.forename
      case "surname" => Gen.surname
      case _ => Gen.alphaStr
    }
  }

  // // Don't think I need this
  // implicit def hnilProvider: GenProvider[HNil] = new GenProvider[HNil] {
  //   override def gen(name: String): Gen[HNil] = Gen.const(HNil)
  // }

  implicit def hnilGen: Gen[HNil] = Gen.const(HNil)

  implicit def hconsGen[S <: Symbol, H, T <: HList]( implicit
    witness: Witness.Aux[S],
    headProvider: GenProvider[H],
    tailGen: Gen[T]
  ): Gen[FieldType[S,H] :: T] = for {
    head <- headProvider.gen(witness.value.name)
    tail <- tailGen
  } yield { field[S](head) :: tail }

  implicit def genGeneric[A, R <: HList](
    implicit gen: LabelledGeneric.Aux[A, R],
    enc: Gen[R]
  ): Gen[A] = enc.map{gen.from}

}

Add autogen. Currently not working correctly.


name := "shapeless"

organization := "com.chuusai"

version := "1.2.0-SNAPSHOT"

scalaVersion := "2.10.0-SNAPSHOT"

crossScalaVersions  := Seq("2.9.1", "2.9.1-1", "2.9.2", "2.10.0-SNAPSHOT")

scalacOptions ++= Seq("-unchecked", "-deprecation")

scalacOptions <++= scalaVersion map { version =>
  val Version = """(\d+)\.(\d+)\..*"""r
  val Version(major0, minor0) = version map identity
  val (major, minor) = (major0.toInt, minor0.toInt)
  if (major < 2 || (major == 2 && minor < 10))
  	Seq("-Ydependent-method-types")
 	else Nil
}

resolvers += ScalaToolsSnapshots

libraryDependencies ++= Seq(
  "com.novocode" % "junit-interface" % "0.7" % "test"
)

name := "shapeless"

organization := "com.chuusai"

version := "1.2.0-SNAPSHOT"

scalaVersion := "2.10.0-SNAPSHOT"

crossScalaVersions <<= (version) {
  v => Seq("2.9.1", "2.9.1-1", "2.9.2") ++ (if (v.endsWith("-SNAPSHOT")) Seq("2.10.0-SNAPSHOT") else Seq())
}

scalacOptions ++= Seq("-unchecked", "-deprecation")

scalacOptions <++= scalaVersion map { version =>
  val Version = """(\d+)\.(\d+)\..*"""r
  val Version(major0, minor0) = version map identity
  val (major, minor) = (major0.toInt, minor0.toInt)
  if (major < 2 || (major == 2 && minor < 10))
    Seq("-Ydependent-method-types")
 	else Nil
}

resolvers += ScalaToolsSnapshots

libraryDependencies ++= Seq(
  "com.novocode" % "junit-interface" % "0.7" % "test"
)

Make inclusion of 2.10.0-SNAPSHOT in crossScalaVersions conditional on the project version being a snapshot.


package se.gigurra.serviceutils.twitter.logging

import java.io._

/**
  * Created by kjolh on 3/15/2016.
  */
object Capture {

  case class Forwarded(oldStream: OutputStream, newStream: OutputStream) extends OutputStream {

    private val streams = Seq(oldStream, newStream)

    private def forward(f: OutputStream => Unit): Unit = streams.foreach(f)

    @throws[IOException]
    override def write(b: Int): Unit = forward(_.write(b))

    @throws[IOException]
    override def flush(): Unit = forward(_.flush())

    @throws[IOException]
    override def write(b: Array[Byte]): Unit = forward(_.write(b))

    @throws[IOException]
    override def write(b: Array[Byte], off: Int, len: Int): Unit = forward(_.write(b, off, len))

    @throws[IOException]
    override def close(): Unit = forward(_.close())
  }

  def stdOut(newStream: OutputStream): Unit = {
    System.setOut(new PrintStream(Forwarded(System.out, newStream), true, "UTF-8"))
  }

  def stdErr(newStream: OutputStream): Unit = {
    System.setErr(new PrintStream(Forwarded(System.err, newStream), true, "UTF-8"))
  }

  def stdOutToFile(path: String, append: Boolean = true): Unit = {
    stdOut(new FileOutputStream(prepareFile(path, append), append))
  }

  def stdErrToFile(path: String, append: Boolean = true): Unit = {
    stdErr(new FileOutputStream(prepareFile(path, append), append))
  }

  def prepareFile(path: String, append: Boolean): File = {

    val file = new File(path)

    if (append) {
      if (!file.exists && !file.createNewFile())
        throw new RuntimeException(s"Cannot create file: $path")
    } else {
      if (file.exists && !file.delete)
        throw new RuntimeException(s"Cannot delete old file: $path")
      if (!file.createNewFile)
        throw new RuntimeException(s"Cannot create file: $path")
    }

    if (!file.canWrite)
      throw new RuntimeException(s"Cannot write to file: $path")

    file
  }

}

Add utility for capturing stdout/err

Add utility for capturing stdout/err


package me.hawkweisman.util.tests

import me.hawkweisman.math.{ SequentialAlgebra, ParallelAlgebra, Linear}
import org.scalameter.api._

import scala.util.Random

/**
 * Performance tests comparing the parallel and sequential linear algebra
 * implementations.
 *
 * Created by hawk on 9/14/15.
 */
abstract class LinearBenchmark(val name: String)
extends PerformanceTest.OfflineRegressionReport
  with Linear {

  val sizes = Gen.range("size")(10,100,10)

  def intMatrix(n: Int): Matrix[Int]
    = Array.ofDim[Int](n * n)
           .map(_ ⇒ Random.nextInt())
           .grouped(n)
           .toArray

  def intVector(n: Int): Vector[Int]
    = Array.ofDim[Int](n)
           .map(_ ⇒ Random.nextInt())

  val intMatrices: Gen[(Matrix[Int], Matrix[Int])]
    = for { n ← sizes }
      yield (intMatrix(n), intMatrix(n))

  val intVectors: Gen[(Vector[Int], Vector[Int])]
    = for { n ← sizes }
      yield (intVector(n), intVector(n))

  performance of s"$name vector algebra" in {
    measure method "vector-vector addition" in {
      using(intVectors) in { case ((u, v)) ⇒ u + v }
    }

    measure method "vector-vector subtraction" in {
      using(intVectors) in { case ((u, v)) ⇒ u - v }
    }

    measure method "vector-vector multiplication" in {
      using(intVectors) in { case ((u, v)) ⇒ u * v }
    }

  }

  performance of s"$name matrix algebra" in {
    measure method "matrix-matrix addition" in {
      using(intMatrices) in { case ((m, n)) ⇒ m + n }
    }

    measure method "matrix-matrix subtraction" in {
      using(intMatrices) in { case ((m, n)) ⇒ m - n }
    }

    measure method "matrix-matrix multiplication" in {
      using(intMatrices) in { case ((m, n)) ⇒ m * n }
    }
  }
}

object SeqLinearBench
  extends LinearBenchmark("sequential")
  with SequentialAlgebra

object ParLinearBench
extends LinearBenchmark("parallel")
  with ParallelAlgebra

Add quick Scalameter benchmarks for Linear


package controllers

import beyond.UserAction
import play.api.data.Form
import play.api.data.Forms.text
import play.api.data.Forms.tuple
import play.api.mvc._

object Session extends Controller {
  private val loginForm = Form(
    tuple(
      "username" -> text,
      "password" -> text
    )
  )

  def login : Action[AnyContent] = Action { implicit request =>
    val data = loginForm.bindFromRequest.data
    // FIXME: Check password

    val username = data("username")
    val session = ("username", username)
    Ok("Hello " + username).withSession(session)
  }

  def logout : Action[AnyContent] = UserAction { request =>
    Ok("Goodbye " + request.username).withNewSession
  }
}

package controllers

import beyond.UserAction
import play.api.data.Form
import play.api.data.Forms.text
import play.api.data.Forms.tuple
import play.api.mvc._

object Session extends Controller {
  private val loginForm = Form(
    tuple(
      "username" -> text,
      "password" -> text
    )
  )

  def login : Action[AnyContent] = Action { implicit request =>
    val data = loginForm.bindFromRequest.data
    // FIXME: Check password

    val username = data("username")
    Ok("Hello " + username).withSession("username" -> username)
  }

  def logout : Action[AnyContent] = UserAction { request =>
    Ok("Goodbye " + request.username).withNewSession
  }
}

Use -> when creating a tuple.

Use -> when creating a tuple.


package models

import lib.Datatype

sealed trait Container {
    def multiple: Boolean
}

object Container {

  case object Singleton extends Container {
    override def multiple = false
  }

  case object Option extends Container {
    override def multiple = false
  }

  case object List extends Container {
    override def multiple = false
  }

  case object Map extends Container {
    override def multiple = false
  }

  def apply(dt: Datatype): Container = {
    dt match {
      case Datatype.Singleton(_) => Singleton
      case Datatype.Option(_) => Option
      case Datatype.List(_) => List
      case Datatype.Map(_) => Map
    }
  }

}

package models

import lib.Datatype

sealed trait Container {
    def multiple: Boolean
}

object Container {

  case object Singleton extends Container {
    override def multiple = false
  }

  case object Option extends Container {
    override def multiple = false
  }

  case object List extends Container {
    override def multiple = true
  }

  case object Map extends Container {
    override def multiple = true
  }

  def apply(dt: Datatype): Container = {
    dt match {
      case Datatype.Singleton(_) => Singleton
      case Datatype.Option(_) => Option
      case Datatype.List(_) => List
      case Datatype.Map(_) => Map
    }
  }

}

Fix bug w/ multiple - lists and maps are multi-valued


package compiler

import datamodel._
import dto.UnitSpec

class MessageDefinitionAnalyzerSpec extends UnitSpec{

  val validMessageDef = MessageDefinition("issue", List(
    FieldDefinition("number", NumberTypeDefinition(), List(JSONKeyAttribute("issueNumber"), CTypeAttribute("uint32_t"))),
    FieldDefinition("url", DynamicStringTypeDefinition(), List()),
    FieldDefinition("creator", ObjectTypeDefinition("user"), List(JSONKeyAttribute("user")))
  ))
  val validMessage = Message("issue", List(
    Field("number", AliasedType("uint32_t", NumberType), "issueNumber"),
    Field("url", DynamicStringType, "url"),
    Field("creator", ObjectType("user"), "user")
  ))

  val duplicateFieldsDef = MessageDefinition("issue", List(
    FieldDefinition("number", NumberTypeDefinition(), List(JSONKeyAttribute("issueNumber"), CTypeAttribute("uint32_t"))),
    FieldDefinition("number", DynamicStringTypeDefinition(), List()),
    FieldDefinition("creator", ObjectTypeDefinition("user"), List(JSONKeyAttribute("user")))
  ))
  val duplicateFieldsError = DuplicateFieldError(List("number"), "issue")

  val multipleDuplicateFieldsDef = MessageDefinition("issue", List(
    FieldDefinition("number", NumberTypeDefinition(), List(JSONKeyAttribute("issueNumber"), CTypeAttribute("uint32_t"))),
    FieldDefinition("creator", NumberTypeDefinition(), List(JSONKeyAttribute("creatorId"), CTypeAttribute("uint32-t"))),
    FieldDefinition("number", DynamicStringTypeDefinition(), List()),
    FieldDefinition("creator", ObjectTypeDefinition("user"), List(JSONKeyAttribute("user")))
  ))
  val multipleDuplicateFieldsError = DuplicateFieldError(List("number", "creator"), "issue")

  val fieldErrorsDef = MessageDefinition("issue", List(
    FieldDefinition("number", NumberTypeDefinition(), List(JSONKeyAttribute("issueNumber"), CTypeAttribute("uint32_t"), JSONKeyAttribute("issueId"))),
    FieldDefinition("url", DynamicStringTypeDefinition(), List()),
    FieldDefinition("creator", ObjectTypeDefinition("user"), List(JSONKeyAttribute("user"), CTypeAttribute("user_type")))
  ))
  val fieldErrorsError = FieldErrors(List(
    DuplicateAttributeError(Constants.JSON_KEY_ATTRIBUTE, "number"),
    TypeAliasNotAllowedError(ObjectType("user").toString, "creator")
  ), "issue")

  "Message definition analyzer" should "accept a valid message definition" in {
    MessageDefinitionAnalyzer(validMessageDef) shouldBe Right(validMessage)
  }

  it should "not accept a definition with duplicate fields" in {
    MessageDefinitionAnalyzer(duplicateFieldsDef) shouldBe Left(duplicateFieldsError)
  }

  it should "not accept a definition with multiple duplicate fields" in {
    MessageDefinitionAnalyzer(multipleDuplicateFieldsDef) shouldBe Left(multipleDuplicateFieldsError)
  }

  it should "not accept a definition with invalid fields" in {
    MessageDefinitionAnalyzer(fieldErrorsDef) shouldBe Left(fieldErrorsError)
  }
}

Add tests for message definition semantic analyzer


package enju.ccg

import java.io.FileWriter
import scala.collection.mutable.ArrayBuffer
import scala.sys.process.Process
import fig.exec.Execution
import lexicon._

object CCGBank2EnjuXML {

  object Opt extends Options {
    @Option(gloss="Path to CCGBank file", required=true) var ccgBankPath = ""
    @Option(gloss="Path to output (pdf)") var outputPath = ""
    @Option(gloss="Number of sentences") var numSentences = 50
  }

  def main(args:Array[String]) = {
    val runner = new Runner
    Execution.run(args, runner, Opt)
  }

  type Tree = ParseTree[NodeLabel]

  class Runner extends Runnable {

    def run = {
      val dict = new JapaneseDictionary(new Word2CategoryDictionary)

      val conv = new JapaneseParseTreeConverter(dict)

      val reader = new CCGBankReader(dict)
      val parseFragments: Seq[Seq[Tree]] =
        reader.takeLines(Opt.ccgBankPath, Opt.numSentences).toSeq.map { line =>
          reader.readParseFragments(line).map { conv.toLabelTree(_) }
        }

      val fw = new FileWriter(Opt.outputPath)

      parseFragments.zipWithIndex foreach { case (t, i) => fw.write(xmlFormat(t, i) + "\n") }

      fw.flush
      fw.close
    }

    def xmlFormat(trees: Seq[Tree], i: Int): String =
      s"""<sentence id="s$i" parse_status="success">""" + trees.map { xmlFormat(_) }.mkString + "</sentence>"

    def xmlFormat(tree: Tree): String = tree match {
      case UnaryTree(child, label) =>
        cons(label) + xmlFormat(child) + "</cons>"
      case BinaryTree(left, right, label) =>
        cons(label) + xmlFormat(left) + xmlFormat(right) + "</cons>"
      case LeafTree(label: TerminalLabel) => cons(label) + tok(label) + "</cons>"
      case _ => sys.error("A leaf node with a non-terminal label found.")
    }
    def cons(label: NodeLabel) = s"""<cons id="c${label.category.id}" cat="${label.category}">"""
    def tok(label: TerminalLabel) = s"""<tok id="t${label.category.id}" surface="${label.word}" pos="${label.pos.second}">${label.word}</tok>"""
  }
}

Support converting derivation to enju xml format


package quasar.project

object Versions {
  val algebraVersion      = "1.0.1"
  val argonautVersion     = "6.2.3"
  val catsVersion         = "1.6.1"
  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.19.0"
  val specsVersion        = "4.5.1"
  val spireVersion        = "0.16.2"
  val akkaVersion         = "2.5.1"
  val fs2Version          = "1.0.5"
  val slf4sVersion        = "1.7.25"
  val atomixVersion       = "3.1.5"
  val mapdbVersion        = "3.0.7"
}

package quasar.project

object Versions {
  val algebraVersion      = "1.0.1"
  val argonautVersion     = "6.2.3"
  val catsVersion         = "1.6.1"
  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.8"
  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.19.0"
  val specsVersion        = "4.5.1"
  val spireVersion        = "0.16.2"
  val akkaVersion         = "2.5.1"
  val fs2Version          = "1.0.5"
  val slf4sVersion        = "1.7.25"
  val atomixVersion       = "3.1.5"
  val mapdbVersion        = "3.0.7"
}

Update refined, refined-scalacheck, ... to 0.9.8


trait A {
  def foo(a: Int): Int = a
  def bar(a: Int): Int
}

trait B {
  def bar(a: Int): Int = a
}

object Test extends A with B{
  def main(args: Array[String]) = {
    assert(!this.getClass.getDeclaredMethods.exists{x: java.lang.reflect.Method => x.getName == "foo"},
      "no forwarder is needed here")
    assert(!this.getClass.getDeclaredMethods.exists{x: java.lang.reflect.Method => x.getName == "bar"},
      "no forwarder is needed here")
  }
}

Add a test that checks that no useless forwarders are being created.


package model.parser

import play.api.libs.json.Reads._
import model.Skimbo
import play.api.libs.json._

trait GenericParser[T] {
  def from(json: JsValue)(implicit fjs: Reads[T]): List[T] = json.as[List[T]]
  def from(json: String)(implicit fjs: Reads[T]): List[T] = from(Json.parse(json))
  def asSkimbos(elements: List[T]): List[Skimbo]
}

Add Generic Parser to Skimbo format

Add Generic Parser to Skimbo format


package org.precompiler.scala101.ch08

/**
  *
  * @author Richard Li
  */
object SetDemo extends App{
  val colors = Set("Red", "Green", "Blue")
  println(s"Colors: ${colors}")

  val colors2 = colors + "Yellow"
  val intersectColor = colors & colors2

  println(s"Colors: ${colors}")
  println(s"Colors2: ${colors2}")
  println(s"Colors + Colors2: ${colors ++ colors2}")
  println(s"Union colors: ${intersectColor}")

  val numbers = Set(1, 2, 3, 4, 5, 6)
  val sum = (0 /: numbers) {_ + _}
  val sum2 = (numbers :\ 0) {_ + _}
  println(sum)
  println(sum2)

}

Add collection - set demo.

Add collection - set demo.


/*
Copyright 2012 Twitter, Inc.

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

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

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

package com.twitter.chill

import org.specs._

import com.twitter.bijection.Bijection

/*
* This is just a test case for Kryo to deal with. It should
* be outside KryoSpec, otherwise the enclosing class, KryoSpec
* will also need to be serialized
*/
case class Point(x: Int, y: Int)
case class Color(name: String)
case class ColoredPoint(color: Color, point: Point)

class CustomSerializationSpec extends Specification with BaseProperties {
  "Custom KryoSerializers and KryoDeserializers" should {
    "serialize objects that have registered serialization" in {
      import KryoImplicits.toRich

      // write bijections
      implicit val pointBijection = Bijection.build[Point, (Int,Int)](
        Point.unapply(_).get)(
        (Point.apply _).tupled)
      implicit val colorBijection = Bijection.build[Color, String](
        Color.unapply(_).get)(
        Color.apply)
      implicit val coloredPointBijection = Bijection.build[ColoredPoint, (Color, Point)](
        ColoredPoint.unapply(_).get)(
        (ColoredPoint.apply _).tupled)

      val MyKryoInjection = new KryoBijection {
        override def getKryo = super.getKryo
          .forClassViaBijection[Point, (Int,Int)]
          .forClassViaBijection[Color, (String)]
          .forClassViaBijection[ColoredPoint, (Color, Point)]
      }

      val color = Color("blue")
      val point = Point(5, 6)
      val coloredPoint = ColoredPoint(color, point)

      rt(coloredPoint) must_== coloredPoint
    }
  }
}

Add test case for serialization of custom objects.

This doubles as example code for creating customized KryoBijection
subclasses that serialize custom classes that have a bijection to a
primitive type.


package scala.in.programming.abstract_internal_control

/**
  * Call by name paraemter.
  * Not ambiguous with named parameter.
  *
  * @author loustler
  * @since 02/26/2017 18:14
  */
object ByNameParameter {
  val assertionEnabled: Boolean = true

  /**
    * This function use closure from field in this object.
    *
    * @param predicate
    * @return
    */
  def myAssert(predicate: () => Boolean) =
    if ( assertionEnabled && !predicate() )
      throw new AssertionError

  def myAssert2(predicate: => Boolean) =
    if (assertionEnabled && !predicate)
      throw new AssertionError

  /**
    * What's difference between [[ByNameParameter.myAssert2()]] and this?
    *
    * If [[ByNameParameter.assertionEnabled]] is false,
    * [[ByNameParameter.myAssert2()]]'s predicate not work.
    * But this function must to work.
    * Cause this function's arguments have side-effects,
    * but [[ByNameParameter.myAssert2()]] haven't.
    *
    * Maybe like this
    * {{{
    *   val x = 10
    *
    *   myAssert2( x / 0 == 0 ) // Its happen nothing.
    *
    *   myAssert3( x / 0 == 0 ) // It is throw ArithmeticException.
    * }}}
    *
    * Therefore [[ByNameParameter.myAssert2()]] is lazy,
    * this function strict.
    *
    * @param predicate
    */
  def myAssert3(predicate: Boolean) =
    if (assertionEnabled && !predicate)
      throw new AssertionError

  def main(args: Array[String]): Unit = {
    myAssert(() => 5 >3) // It so strange. It is not good.

    myAssert2(5 > 3) // It is nice.
  }
}

Add example for by name parameter(maybe call by name parameter).


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.1"
  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"
}

Update cats-kernel-laws, cats-laws to 1.6.1


object Test {
  abstract class A1
  case class C1(x: Int) extends A1
  class C2(x: Int) extends C1(x) {
    override def productPrefix = "Shazbot!"
  }
  class C3(x: Int) extends C1(x) {
    override def canEqual(other: Any) = other.isInstanceOf[C3]
    override def equals(other: Any) = other match {
      case ob: C3 => x == ob.x
      case _      => false
    }
  }

  case class CS1(xs: Any*)
  class CS2(xs: Seq[_]*) extends CS1(xs: _*)
  class CS3(xs: IndexedSeq[Int]*) extends CS2(xs: _*)

  case class H1(x: Int, y: Double)
  class H2(x: Double, y: Int) extends H1(y, x)

  def main(args: Array[String]): Unit = {
    assert(C1(5) == new C2(5))
    assert(new C2(5) == C1(5))
    assert(C1(5).hashCode == new C2(5).hashCode)
    assert(new C2(5).hashCode == C1(5).hashCode)

    assert(C1(5) != new C3(5))
    assert(new C3(5) != C1(5))

    assert(CS1(List(1d,2d), Seq[Float](3f, 4f)) == new CS3(IndexedSeq(1,2), IndexedSeq(3, 4)))

    assert(H1(5, 10d) == new H2(10d, 5))
    assert(H1(5, 10d).hashCode == new H2(10d, 5).hashCode)
  }
}

Test case for case class equality.

Test case for case class equality.


package cloud4things.cli.fosstrak.client

/*
 * ALELRClient : A ALELR client implementation that
 * contains the methods stub's for the ALELR service
 * of the Fosstrak Filtering & Collecting Server.
 */
class ALELRClient {

}

Add the skeleton of the ALELR client.

Add the skeleton of the ALELR client.


package scala.tools.nsc.tasty
import scala.annotation.tailrec

object Names {

  object TastyName {
    final case class SimpleName(raw: String)                                                extends TastyName
    final case class ModuleName(base: TastyName)                                            extends TastyName
    final case class QualifiedName(qual: TastyName, name: SimpleName)                       extends TastyName
    final case class SignedName(qual: TastyName, sig: Signature.MethodSignature[TastyName]) extends TastyName
  }

  /** class to represent Names as defined in TASTy, with methods to extract scala identifiers
   */
  sealed trait TastyName extends Product with Serializable { self =>
    import TastyName._

    /** Standard representation of this as a [[scala.Product]].
     */
    final def show: String = runtime.ScalaRunTime._toString(self)

    final override def toString: String = debugTasty

    final def isModuleName: Boolean = self.isInstanceOf[ModuleName]

    /** Get the part of this name that represents a Scala identifier
     */
    @tailrec
    final def identifierPart: SimpleName = self match {
      case name: SimpleName       => name
      case QualifiedName(_, name) => name
      case ModuleName(name)       => name.identifierPart
      case SignedName(name,_)     => name.identifierPart
    }

    /** Get the optional qualifier if this name forms a path
     */
    @tailrec
    final def qualifierPart: Option[TastyName] = self match {
      case name: SimpleName       => None
      case QualifiedName(qual, _) => Some(qual)
      case ModuleName(name)       => name.qualifierPart
      case SignedName(name,_)     => name.qualifierPart
    }

    /** How to display the name in a TASTy file.
     */
    final def debugTasty: String = {
      self match {
        case name: SimpleName => name.raw
        case _ =>
          val sb = new StringBuilder(10)
          def inner(name: TastyName): Unit = name match {
            case name: SimpleName          => sb.append(name.raw)
            case QualifiedName(qual, name) => inner(qual); sb.append("[Qualified . "); inner(name); sb.append(']')
            case ModuleName(name)          => inner(name); sb.append("[ModuleClass]")
            case SignedName(name,sig)      => inner(name); sb.append("[Signed "); sb.append(sig.show); sb.append(']')
          }
          inner(self)
          sb.toString
      }
    }

    final def stripModulePart: TastyName = self match {
      case ModuleName(name)                                       => name
      case name @ (_:SimpleName | _:QualifiedName | _:SignedName) => name
    }

    final def signature: Signature[TastyName] = self match {
      case SignedName(_, signature)                       => signature
      case _:SimpleName | _:QualifiedName |  _:ModuleName => Signature.NotAMethod
    }
  }
}

Add Name ADT to scala.tools.nsc.tasty

Add Name ADT to scala.tools.nsc.tasty


/**
 * Example UDFs
 */

import org.apache.spark._
import org.apache.spark.sql._
import org.apache.spark.sql.catalyst.expressions.aggregate._
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.expressions._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.hive._
import org.apache.spark.sql.hive.thriftserver._
import org.apache.spark.sql.types._

object UDFs {
  //tag::setupUDFs[]
  def setupUDFs(sqlCtx: SQLContext) = {
    sqlCtx.udf.register("strLen", (s: String) => s.length())
  }
  //end::setupUDFs[]

  //tag::setupUDAFs[]
  def setupUDAFs(sqlCtx: SQLContext) = {
    class Avg extends UserDefinedAggregateFunction {
      // Input type
      def inputSchema: org.apache.spark.sql.types.StructType =
        StructType(StructField("value", DoubleType) :: Nil)

      def bufferSchema: StructType = StructType(
        StructField("count", LongType) ::
        StructField("sum", DoubleType) :: Nil
      )

      // Return type
      def dataType: DataType = DoubleType

      def deterministic: Boolean = true

      def initialize(buffer: MutableAggregationBuffer): Unit = {
        buffer(0) = 0L
        buffer(1) = 0.0
      }

      def update(buffer: MutableAggregationBuffer,input: Row): Unit = {
        buffer(0) = buffer.getAs[Long](0) + 1
        buffer(1) = buffer.getAs[Double](1) + input.getAs[Double](0)
      }

      def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = {
        buffer1(0) = buffer1.getAs[Long](0) + buffer2.getAs[Long](0)
        buffer1(1) = buffer1.getAs[Double](1) + buffer2.getAs[Double](1)
      }

      def evaluate(buffer: Row): Any = {
        math.pow(buffer.getDouble(1), 1.toDouble / buffer.getLong(0))
      }
    }
    // Optionally register
    val avg = new Avg
    sqlCtx.udf.register("ourAvg", avg)
  }
  //end::setupUDAFs[]
}

Add UDF & UDAF example

Add UDF & UDAF example


package lasp.latis.reader.tsml

import latis.reader.tsml.JdbcAdapter
import latis.reader.tsml.ml.Tsml

/**
 * Extend JdbcAdapter to change how row limits are applied for
 * Postgresql database queries.
 */
class PostgresqlAdapter(tsml: Tsml) extends JdbcAdapter(tsml) {

  /**
   * Override to apply the 'limit' property if it is set.
   * Limit, First, and Last Filters use this property.
   */
  override def makeQuery = {
    val sql = super.makeQuery

    getProperty("limit") match {
      case Some(limit) => sql + " limit " + limit.toInt
      case None => sql
    }
  }

}

Add adapter for postgresql databases that handles row limits differently

Former-commit-id: 8f7a71b94349282d7fb8bdcdfe5aa0351f4fa567


package kantan.xpath

import java.text.SimpleDateFormat
import java.util.{Date, Locale}
import kantan.xpath.laws.discipline.NodeDecoderTests
import kantan.xpath.laws.discipline.arbitrary._
import org.scalatest.FunSuite
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.typelevel.discipline.scalatest.Discipline

class DateDecoderTests extends FunSuite with GeneratorDrivenPropertyChecks with Discipline {
  implicit val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH)

  checkAll("NodeDecoder[Date]", NodeDecoderTests[Date].decoder[Int, Int])
}

Add tests for date decoders.

Add tests for date decoders.


import scala.quoted._

trait App[F[_],CT]:
  this: Base[F,CT] =>

  import qctx.tasty._

  trait AA

  def f(cpsCtx: FC[F]): AA =
    g(cpsCtx)

  def g(cpsCtx: FC[F]): AA =
    val paramSym: Symbol = ???
    println(paramSym.tree)   // println necessary for failure
    val t: Term = ???
    t match {                // match necessary for failure
      case Typed(_, _) => ???  // both cases necessary for failure
      case Lambda(_, _) => ???
    }
    f(cpsCtx)                 // necessary for failure
    val cpsBody = runRoot()   // necessary for failure
    g(cpsCtx)                 // failure
      // 26 |    g(cpsCtx)
      //    |    ^
      //    |Ambiguous overload. The overloaded alternatives of method g in trait App with types
      //    | (cpsCtx: FC[F]): Base.this.AA
      //    | (cpsCtx: FC[F]): App.this.AA
      //    |both match arguments ((cpsCtx : FC[F]))
      //    |
      //    |Note: this happens because two or more alternatives have the same erasure,
      //    |      so they cannot be distinguished by overloading resolution

class FC[F[_]]()

trait Base[F[_]:Type,CT:Type]  // Both :Type context bounds are necessary for failure
extends Cps with Root[F, CT] with App[F, CT]:
  implicit val qctx: QuoteContext

trait Root[F[_], CT]:
  this: Base[F, CT] =>
  def runRoot(): CpsTree = ???

trait Cps:
  sealed abstract class CpsTree

Add minimized test that demonstrates the failure to tests/pending


package nimrod.util

import org.mapdb.DB
import scala.collection.JavaConversions._
import java.lang.Integer

/**
 * An implementation of a counter that is disk-based and increments (and is thread-safe)
 */
class DiskCounter[A](sorted : Boolean = false, db : DB = DiskCounter.createDB()) {
  private val theMap = if(sorted) {
    db.getTreeMap[A,Integer]("map")
  } else {
    db.getHashMap[A,Integer]("map")
  }

  def inc(key : A) = {
    // First check if there is a value by trying to put 1
    var v = theMap.putIfAbsent(key,1)
    if(v != null) {
      // Guess there was, let's try to increment this value
      while(!theMap.replace(key,v,v+1)) {
        // Nope, changed again, reread the map
        v = theMap.get(key)
      }
    }
  }
  def get(key : A) : Int = theMap.get(key).intValue
  def values : Iterator[(A,Int)] = theMap.iterator.map {
    case (x,y) => (x,y.intValue)
  }
}

object DiskCounter {
  def createDB(cacheSize : Int = 65536) = org.mapdb.DBMaker.newTempFileDB().cacheSize(cacheSize).make()
  def closeDB(db : DB) = db.close
}

Add disk based counter util

Add disk based counter util


package scala.pickling.forwardedpickler

import org.scalatest.FunSuite
import scala.pickling._
import json._
import static.StaticOnly

sealed trait F { val fld: Int }

final case class G(fld: Int) extends F
final case class H(fld: Int) extends F

class PicklerCanBeForwarded extends FunSuite {

  // we should be able to use a passed-in implicit pickler
  // rather than trying to generate one, this allows people
  // to call pickle/unpickle in a different place from the
  // spot where they generate the pickler.

  // TODO remove the FastTypeTag implicit parameters when possible

  private def doPickle[T](t: T)(implicit pickler1: SPickler[T], tag1: FastTypeTag[T]): JSONPickle =
    t.pickle

  private def doUnpickle[T](p: JSONPickle)(implicit unpickler1: Unpickler[T], tag1: FastTypeTag[T]): T =
    p.unpickle[T]

  test("main") {
    val x: F = G(42)
    val pickle: JSONPickle = doPickle(x)
    assert(doUnpickle[F](pickle).fld == 1)
  }
}

Add test that pickle/unpickle can get the pickler from a parameter


object Solution {

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

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

Add solution to problem Insertion Sort Part 2.


class Arr {
  val s = new Array[Int](1)
  val s2 = new Array[Array[Int]](2)
  val s3: Array[Array[Int]] = Array.ofDim(2,3)
  /*
public Arr();
    Code:
       0: aload_0
       1: invokespecial #14                 // Method java/lang/Object."<init>":()V
       4: aload_0
       5: iconst_1
       6: newarray       int
       8: checkcast     #15                 // class "[I"
      11: putfield      #17                 // Field s$$local:[I
      14: aload_0
      15: iconst_2
      16: anewarray     #15                 // class "[I"
      19: checkcast     #18                 // class "[[I"
      22: putfield      #20                 // Field s2$$local:[[I
      25: aload_0
      26: getstatic     #26                 // Field scala/Array$.MODULE$:Lscala/Array$;
      29: pop
      30: iconst_2
      31: iconst_3
      32: multianewarray #18,  2            // class "[[I"
      36: checkcast     #18                 // class "[[I"
      39: putfield      #28                 // Field s3$$local:[[I
      42: return
*/
}

object Test{
  def main(args: Array[String]): Unit = {
    new Arr
  }
}

Add a test to check multidimenstionall arrays.


import java.time.{Duration, Instant}

import akka.actor.{Actor, ActorLogging, ActorSystem, Props}
import akka.io.IO
import akka.serial.{AccessDeniedException, Parity, Serial, SerialSettings}

object Messaging {
  private implicit val system: ActorSystem = ActorSystem("terminal-stream")
  def run(): Unit = system.actorOf(Props(new Messaging()), "messaging")
}

class Messaging extends Actor with ActorLogging {
  import Messaging._
  private val endTime = Instant.now().plus(Duration.ofSeconds(15))
  private val port = Main.defaultPort
  private val settings = SerialSettings(
    baud = 115200,
    characterSize = 8,
    twoStopBits = false,
    parity = Parity.None
  )
  IO(Serial) ! Serial.Open(port, settings)

  override def receive: Receive = opening

  def onError: Receive = {
    case Serial.CommandFailed(_: Serial.Open, _: AccessDeniedException) =>
      println("You're not allowed to open that port - now terminating")
      system.terminate()
    case Serial.CommandFailed(_: Serial.Open, reason) =>
      println(s"Could not open port for some other reason: ${reason.getMessage} - now terminating")
      system.terminate()
  }

  def opening: Receive = onError orElse  {
    case Serial.Opened(_) =>
      println("Opened port - now communicating")
      context.become(communicating)
  }

  def communicating: Receive = onError orElse {
    case Serial.Received(data) =>
      print(s"\rReceived $data")
      if (Instant.now().isAfter(endTime)) {
        println()
        println(s"Limit reached - now closing")
        val operator = sender
        context.become(closing)
        operator ! Serial.Close
      }
  }

  def closing: Receive = onError orElse  {
    case Serial.Closed =>
      println("Port closed - now terminating")
      system.terminate()
  }
}

Introduce messaging based serial communication


object Solution {

  def minPathSum3(matrix: Array[Array[Int]]): Long = {
    val n = matrix.size
    val minSumMatrix = Array.fill(n)(Array.fill(n)(0L))
    // set the first column.
    for (i <- 0 until n) {
      minSumMatrix(i)(0) = matrix(i)(0)
    }

    // calculate all the other columns
    for (i <- 1 until n) {
      // traverse down
      minSumMatrix(0)(i) = matrix(0)(i) + minSumMatrix(0)(i - 1)
      for (j <- 1 until n) {
        minSumMatrix(j)(i) =
          (minSumMatrix(j)(i - 1) min minSumMatrix(j - 1)(i)) + matrix(j)(i)
      }

      // traverse up
      for (j <- n - 2 to 0 by -1) {
        minSumMatrix(j)(i) =
          minSumMatrix(j)(i) min (minSumMatrix(j + 1)(i) + matrix(j)(i))
      }
    }

    (0 until n).map(minSumMatrix(_)(n-1)).min
  }

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

Add solution to problem 82. For every column other than the first column, we need two swaps. One swap for comparing going right or going down. The other swap for comparing go up or the previous result. We should notice all the element in the matrix is positive, if One can element can going down, it won't be going up.


package com.johnsnowlabs.nlp.annotators.classifier.dl

import com.johnsnowlabs.nlp.annotator._
import com.johnsnowlabs.nlp.base._
import com.johnsnowlabs.nlp.util.io.ResourceHelper
import org.apache.spark.ml.Pipeline
import org.scalatest._
import org.apache.spark.sql.functions.{col, udf}

class MultiClassifierDLTestSpec extends FlatSpec {

  val spark = ResourceHelper.getActiveSparkSession

  "MultiClassifierDL" should "correctly train E2E Challenge" ignore   {
    def splitAndTrim = udf { labels: String =>
      labels.split(", ").map(x=>x.trim)
    }

    val smallCorpus = spark.read
      .option("header", true)
      .option("inferSchema", true)
      .option("mode", "DROPMALFORMED")
      .csv("src/test/resources/classifier/e2e.csv")
      .withColumn("labels", splitAndTrim(col("mr")))
      .drop("mr")

    println("count of training dataset: ", smallCorpus.count)
    smallCorpus.select("labels").show()
    smallCorpus.printSchema()

    val documentAssembler = new DocumentAssembler()
      .setInputCol("ref")
      .setOutputCol("document")
      .setCleanupMode("shrink")

    val embeddings = UniversalSentenceEncoder.pretrained()
      .setInputCols("document")
      .setOutputCol("embeddings")

    val docClassifier = new MultiClassifierDLApproach()
      .setInputCols("embeddings")
      .setOutputCol("category")
      .setLabelColumn("labels")
      .setBatchSize(128)
      .setMaxEpochs(10)
      .setLr(1e-3f)
      .setThreshold(0.5f)
      .setValidationSplit(0.1f)

    val pipeline = new Pipeline()
      .setStages(
        Array(
          documentAssembler,
          embeddings,
          docClassifier
        )
      )

    val pipelineModel = pipeline.fit(smallCorpus)

  }

}

Add MultiClassifierDL unit test in Scala


package com.microsoft.partnercatalyst.fortis.spark.sinks.cassandra

import java.time.Instant

import com.microsoft.partnercatalyst.fortis.spark.SparkTestSpec
import com.microsoft.partnercatalyst.fortis.spark.dto.{Analysis, AnalyzedItem}
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD
import org.apache.spark.streaming.Seconds
import com.datastax.spark.connector._

import scala.collection.mutable

class CassandraSinkSpec extends SparkTestSpec {
  protected val appName = "test-cassandra"

  "The cassandra sink" should "connect to cassandra without exception" in {
    checkIfShouldRun()

    val rdds = mutable.Queue[RDD[AnalyzedItem]]()
    rdds += sc.makeRDD(Seq(
      AnalyzedItem(
        createdAtEpoch = Instant.now.getEpochSecond,
        body = "body-1",
        title = "title-1",
        publisher = "publisher-1",
        sourceUrl = "sourceUrl-1",
        analysis = Analysis())))
    rdds += sc.makeRDD(Seq(
      AnalyzedItem(
        createdAtEpoch = Instant.now.getEpochSecond,
        body = "body-2",
        title = "title-2",
        publisher = "publisher-2",
        sourceUrl = "sourceUrl-2",
        analysis = Analysis()),
      AnalyzedItem(
        createdAtEpoch = Instant.now.getEpochSecond,
        body = "body-3",
        title = "title-3",
        publisher = "publisher-3",
        sourceUrl = "sourceUrl-3",
        analysis = Analysis())))
    val stream = Some(ssc.queueStream(rdds))

    val keyspaceName = "fortistest"
    val tableName = "events"
    sc.cassandraTable(keyspaceName, tableName).deleteFromCassandra(keyspaceName, tableName)

    CassandraSink(stream, keyspaceName, tableName)
    ssc.start()
    ssc.awaitTerminationOrTimeout(Seconds(5).milliseconds)

    val numRows = sc.cassandraTable(keyspaceName, tableName).count()
    assert(numRows == 3)
  }

  private def checkIfShouldRun(): Unit = {
    if (conf.get("spark.cassandra.connection.host").isEmpty) {
      cancel("No cassandra connection defined, skipping test")
    }
  }

  protected override def setupSparkConf(conf: SparkConf): SparkConf = {
    CassandraConfig.init(conf, batchDuration)
  }
}

Add test to verify cassandra connection

Add test to verify cassandra connection


class A(a: Int) {
  trait X {
    def f: Int
    val x = a + f      // NPE: the outer for `Y` is not yet set
  }

  trait Y {
    val y = a
    def f: Int = A.this.a      // NPE: the outer for `Y` is not yet set
  }

  class Z(o: A) extends m.Y {  // error
    val m = o
  }

  class B extends Z(new A(4))
}

object Test {
  def main(args: Array[String]): Unit = {
    val a = new A(3)
    new a.B
  }
}

Add test: class fields cannot be used as parent prefix


package ch.usi.inf.l3.sana.guod.names

import ch.usi.inf.l3.sana
import sana.robustj
import sana.tiny
import tiny.names.Name

trait StdNames extends robustj.names.StdNames {
  val CLINIT_NAME              = Name("<clinit>")
}

object StdNames extends StdNames

Add the standard name for static init methods (clinit)


package com.robbyp.scab

import org.scalatra.test.scalatest.ScalatraFlatSpec

class MyScalatraServletSpec extends ScalatraFlatSpec {

  addServlet(classOf[MyScalatraServlet], "/*")

  "MyScalatraServlet" should "return status 200 with GET /" in {
    get("/") {
      status should be(200)
    }
  }

}

Add initial Scalatest to prove the framework.


package uk.ac.wellcome.utils

import akka.actor.ActorSystem
import org.scalatest.concurrent.{Eventually, IntegrationPatience}
import org.scalatest.{BeforeAndAfterEach, FunSpec, Matchers}
import scala.concurrent.duration._
import uk.ac.wellcome.utils.TryBackoff

class TryBackoffTest
    extends FunSpec
    with BeforeAndAfterEach
    with Eventually
    with IntegrationPatience
    with Matchers {
  val system = ActorSystem.create("TestActorSystem")

  var calls = List[Int]()

  val tryBackoff = new TryBackoff {
    override lazy val totalWait = 6 seconds
  }

  override def afterEach(): Unit = {
    calls = List()
    tryBackoff.cancelRun()
  }

  it("should always call a function that succeeds") {
    def alwaysSucceeds(): Unit = {
      calls = 0 :: calls
    }

    tryBackoff.run(alwaysSucceeds, system)
    eventually {
      calls shouldBe List(0)
    }
  }

  it("should recall a function after it fails on the first attempt") {
    def succeedsOnThirdAttempt(): Unit = {
      if (calls.length < 2) {
        calls = 0 :: calls
        throw new Exception("Not ready yet")
      } else {
        calls = 1 :: calls
      }
    }

    tryBackoff.run(succeedsOnThirdAttempt, system)
    eventually {
      calls.length should be > 1
    }
  }

  it("should eventually give up on a function that always fails") {
    def alwaysFails(): Unit = {
      calls = 0 :: calls
      throw new Exception("I will always fail")
    }

    tryBackoff.run(alwaysFails, system)

    Thread.sleep(10000)
    val finalLength = calls.length
    Thread.sleep(5000)
    calls.length shouldBe finalLength
  }
}

Check in initial test suite for TryBackoff


package geotrellis.osme.ingest

import org.scalatest._

import geotrellis.raster._
import geotrellis.raster.histogram._
import geotrellis.spark._
import geotrellis.spark.io._
import geotrellis.spark.io.s3._
import geotrellis.vector._
import geotrellis.spark.util.SparkUtils
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD

class RasterReaderTest extends FunSuite {
	test("Zoom 2 Tile(0,2) is all NoData") {
        val reader = S3ValueReader("osm-elevation", "catalog").reader[SpatialKey, Tile](LayerId("ned", 2))
        val tile: Tile = reader.read(SpatialKey(0,2))
        assert(!tile.isNoDataTile)
    }

    test("Zoom 2 Tile(1,2) is all NoData") {
        val reader = S3ValueReader("osm-elevation", "catalog").reader[SpatialKey, Tile](LayerId("ned", 2))
        val tile: Tile = reader.read(SpatialKey(1,2))
        assert(!tile.isNoDataTile)
    }
}

Create a test that instantiates value reader and reads a tile for zoom 2


package ccf.session

import ccf.transport.TransportResponse

sealed abstract class SessionResponse {
  val transportResponse: TransportResponse
  val result: Either[Success, Failure]
}

case class JoinResponse(transportResponse: TransportResponse, result: Either[Success, Failure]) extends SessionResponse

case class PartResponse(transportResponse: TransportResponse, result: Either[Success, Failure]) extends SessionResponse

case class InChannelResponse(transportResponse: TransportResponse, result: Either[Success, Failure]) extends SessionResponse

case class OperationContextResponse(transportResponse: TransportResponse, result: Either[Success, Failure]) extends SessionResponse

session: Add session response case class hierarchy

Reuses Result.scala generalized in previous commit.

Signed-off-by: Sami Rosendahl <b33c757bb777642ab0d59c699f8d5782929a814f@reaktor.fi>
Signed-off-by: Timo Mali <93a63fc11b7fc4c8615b3718bbdb07aef12d7334@reaktor.fi>


object Solution {

  def main(args: Array[String]) {
    val n = readLine.toInt
    val biggest = (0 until n).flatMap(x =>
                  (0 until n).map(BigInt(x).pow(_).toString.map(_.asDigit).sum))
                  .max
    println(biggest)
  }
}

Add solution to problem 56. BigInt rules the world.


// Scala Puzzler 54
object Test {
  case class Card(number: Int, suit: String = "clubs") {
    val value = (number % 13) + 1 // ace = 1, king = 13
    def isInDeck(implicit deck: List[Card]) = deck contains this
  }

  def main(args: Array[String]) = {
    implicit val deck = List(Card(1, "clubs"))
    implicit def intToCard(n: Int): Card = Card(n)
    assert(1.isInDeck)
  }
}

Add puzzler 54 as a test

Add puzzler 54 as a test


package com.tristanpenman.chordial.demo

import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{ImplicitSender, TestKit}
import com.tristanpenman.chordial.demo.Governor._
import org.scalatest._

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

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

  // Time to wait before concluding that a node creation confirmation will not be received
  private val creationDuration = 1000.milliseconds

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

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

  // Function to return the ID of an arbitrarily chosen Node owned by a given Governor actor
  private def getFirstNodeId(governor: ActorRef): Long = {
    governor ! GetNodeIdSet()
    expectMsgPF() {
      case GetNodeIdSetOk(nodeIds) =>
        if (nodeIds.isEmpty) {
          fail("Governor returned an empty set of Node IDs")
        } else {
          nodeIds.head
        }
    }
  }

  "A Governor actor" when {
    "initially constructed" should {
      def newGovernor: ActorRef = system.actorOf(Governor.props(keyspaceBits))

      "respond to a CreateNode message with a CreateNodeOk message, and then no further messages" in {
        newGovernor ! CreateNode()
        expectMsgType[CreateNodeOk]
        expectNoMsg(spuriousMessageDuration)
      }

      "respond to two CreateNode messages with two unique CreateNodeOk messages, and then no further messages" in {
        val governor = newGovernor
        governor ! CreateNode()
        expectMsgPF() {
          case CreateNodeOk(firstNodeId, _) =>
            governor ! CreateNode()
            expectMsgPF() {
              case CreateNodeOk(secondNodeId, _) =>
                assert(firstNodeId != secondNodeId)
            }
        }
      }
    }

    "already at its Node capacity" should {
      def newGovernor: ActorRef = {
        val governor = system.actorOf(Governor.props(keyspaceBits))
        1 to (1 << keyspaceBits) foreach {
          case _ =>
            governor ! CreateNode()
            expectMsgType[CreateNodeOk]
        }
        governor
      }

      "respond to a CreateNode message with a CreateNodeInvalidRequest message" in {
        newGovernor ! CreateNode()
        expectMsgType[CreateNodeInvalidRequest]
      }

      "respond to a CreateNodeWithSeed message with a CreateNodeWithSeedInvalidRequest message" in {
        val governor = newGovernor
        val seedId = getFirstNodeId(governor)
        governor ! CreateNodeWithSeed(seedId)
        expectMsgType[CreateNodeWithSeedInvalidRequest]
      }
    }
  }
}

Add some initial test cases for the Governor class


trait Matcher[AA]
case object MatchOne extends Matcher[Int]

object CollectIssue {
  def apply[A](m: Matcher[A]): A = m match {
    case MatchOne =>
      // This seems to break GADT refinement of A to Int.
      // Comment it out and the program typechecks.
      // Expanding the pattern matching anon partial function manually
      // also allows compilation.
      { case _ => 0 }: PartialFunction[Any, Int]

      // should conform to A, but doesn't.

      1
  }
}

Add regression test for GADT partial function issue

Closes scala/bug#9345


object Test extends App {
  import reflect.mirror._

  val s = "hello world"
  val sc = symbolOfInstance(s)
  val st = sc.asType
  val m = st member newTermName("indexOf")
  val IntType = definitions.IntClass.asType
  val indexOf = m resolveOverloaded(actuals = List(IntType))
  assert(invoke(s, indexOf)('w') == 6)
  assert((invoke(s, indexOf)('w') match { case x: Int => x }) == 6)

  val m2 = st member newTermName("substring")
  val substring = m2 resolveOverloaded(actuals = List(IntType, IntType))
  assert(invoke(s, substring)(2, 6) == "llo ")
}

Test case for overloading resolution during reflection.


package scala.pickling.generation.pickler

import org.scalatest.FunSuite

import scala.pickling._
import Defaults._
import json._
import scala.pickling.util.ClassMapper
import static._

class Tuple2Pickler extends FunSuite {

  test("pickle/unpickle (Int, String)") {
    val t = (1, "")
    val t2 = t.pickle.unpickle[(Int, String)]
    assert(t === t2)
  }

  test("pickle/unpickle any specialized tuple like (Int, Int)") {
    val t = (1, 2)
    val clz = classOf[(Int, Int)]
    val clzT = t.getClass
    println(ClassMapper.areSameClasses(clzT, clz))
    val t2 = t.pickle.unpickle[(Int, Int)]
    assert(t === t2)
  }

}

Add tests for Tuple2 (normal and specialized)

Now, we support pickling and unpickling specialized tuples. It's
necessary to add a special method to check class equality since the
specialized classes are implemented as subclasses and therefore have its
own class name, failing a simple class equality.