import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.2.10"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.4",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

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

import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.2.11"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.4",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

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

autocommit: Update configuration to record version 0.2.11


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.3.2"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

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

import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.3.3"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      filters,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    ),
    resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
    resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
    resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/",
    credentials += Credentials(
      "Artifactory Realm",
      "flow.artifactoryonline.com",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
)

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

autocommit: Update configuration to record version 0.3.3


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.3"

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

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

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

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

version := "0.2.53"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.3"

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

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

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

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

version := "0.2.54"

autocommit: Update configuration to record version 0.2.54


lazy val root = (project in file(".")).
  settings(
    name := "units-of-information",
    version := "1.0",
    scalaVersion := "2.11.8",
    libraryDependencies ++= Seq(
      "junit" % "junit" % "4.11" % Test
    )
  )

lazy val root = (project in file(".")).
  settings(
    name := "units-of-information",
    version := "1.0",
    scalaVersion := "2.11.8",
    testOptions += Tests.Argument(TestFrameworks.JUnit, "-v", "-a"),
    libraryDependencies ++= Seq(
        "junit" % "junit" % "4.12" % Test,
        "com.novocode" % "junit-interface" % "0.11" % Test
          exclude("junit", "junit-dep")
    )
  )

Use correct dependencies for JUnit in SBT


package gov.wicourts.json

import argonaut.Cursor

import scalaz.Id.Id

import scala.language.higherKinds

import scalaz.NonEmptyList

package object formlet {
  type IdFieldFormlet[A] = Formlet[Id, Option[Cursor], NonEmptyList[String], A, FieldView]
  type IdObjectFormlet[A] = Formlet[Id, Option[Cursor], ValidationErrors, A, JsonObjectBuilder]

  type FieldFormlet[M[_], A] = Formlet[M, Option[Cursor], NonEmptyList[String], A, FieldView]
  type ObjectFormlet[M[_], A] = Formlet[M, Option[Cursor], ValidationErrors, A, JsonObjectBuilder]

  type JsonFormlet[M[_], E, A, V] = Formlet[M, Option[Cursor], E, A, V]

  object syntax extends ToFieldFormletOps with ToObjectFormletOps
}

package gov.wicourts.json

import argonaut.Cursor

import scalaz.Id.Id

import scala.language.higherKinds

import scalaz.NonEmptyList

package object formlet {

  type JsonFormlet[M[_], E, A, V] = Formlet[M, Option[Cursor], E, A, V]

  type FieldFormlet[M[_], A] = JsonFormlet[M, NonEmptyList[String], A, FieldView]
  type ObjectFormlet[M[_], A] = JsonFormlet[M, ValidationErrors, A, JsonObjectBuilder]

  type IdFieldFormlet[A] = FieldFormlet[Id, A]
  type IdObjectFormlet[A] = ObjectFormlet[Id, A]

  object syntax extends ToFieldFormletOps with ToObjectFormletOps
}

Redefine the Formlet type aliases to make the relation between them clearer


package com.gu.notifications.events.model

import play.api.libs.json.{Json, Writes}

case class EventAggregation(platformCounts: PlatformCount)

object EventAggregation {
  implicit val jreads = Json.reads[EventAggregation]
  implicit val jwrites: Writes[EventAggregation] = Json.writes[EventAggregation]
}

package com.gu.notifications.events.model

import play.api.libs.json._

case class EventAggregation(platformCounts: PlatformCount)

object EventAggregation {
  private val defaultJsonReads = Json.reads[EventAggregation]

  implicit val jreads = new Reads[EventAggregation] {
    override def reads(json: JsValue): JsResult[EventAggregation] = json match {
      case JsObject(fields) =>
        val platformCount = fields.get("platform").orElse(fields.get("platformCounts"))
        val newFields = platformCount.map(pc => Map("platformCounts" -> pc)).getOrElse(Map.empty)
        defaultJsonReads.reads(JsObject(newFields))
      case _ => JsError("Expected a JsObject to parse EventAggregation")
    }
  }
  implicit val jwrites: Writes[EventAggregation] = Json.writes[EventAggregation]
}

Fix the report service such that it can parse the event aggregation with both attribute names (platformCounts and platform)


//--------------------------------------
//
// TaskDispatcherComponent.scala
// Since: 2013/11/12 10:49
//
//--------------------------------------

package xerial.silk.framework.scheduler

import xerial.silk.Silk
import xerial.core.log.LoggerFactory
import akka.actor.Props
import xerial.silk.framework.LocalActorService

trait TaskDispatcherComponent {

  type TaskDispatcher <: TaskDispatcherAPI
  val taskDispatcher : TaskDispatcher

  val taskDispatcherTimeout = 60

  trait TaskDispatcherAPI {
    def dispatch[A](op:Silk[A])
  }
}

trait TaskDispatcherImpl extends TaskDispatcherComponent {

  type TaskDispatcher = DefaultTaskDispatcher
  val taskDispatcher = new DefaultTaskDispatcher

  class DefaultTaskDispatcher extends TaskDispatcherAPI {

    val logger = LoggerFactory(classOf[TaskDispatcher])

    def dispatch[A](op:Silk[A]) {

      // Create a schedule graph
      val sg = ScheduleGraph(op)
      logger.debug(s"Schedule graph:\n$sg")

      // Launch TaskScheduler and submitter
      for(as <- LocalActorService.local) {
        val taskQueue = as.actorOf(Props[TaskQueue], name="taskQueue")
        val schedulerRef = as.actorOf(Props(new TaskScheduler(sg)), name="scheduler")

        // Tick scheduler periodically
        import scala.concurrent.duration._
        import as.dispatcher
        as.scheduler.scheduleOnce(taskDispatcherTimeout.seconds){ schedulerRef ! TaskScheduler.Timeout }

        // Start evaluation
        schedulerRef ! TaskScheduler.Start

        // Await termination of the scheduler
        as.awaitTermination()
      }
    }
  }

}

//--------------------------------------
//
// TaskDispatcherComponent.scala
// Since: 2013/11/12 10:49
//
//--------------------------------------

package xerial.silk.framework.scheduler

import xerial.silk.Silk
import xerial.core.log.LoggerFactory
import akka.actor.Props
import xerial.silk.framework.LocalActorService

trait TaskDispatcherComponent {

  type TaskDispatcher <: TaskDispatcherAPI
  val taskDispatcher : TaskDispatcher

  val taskDispatcherTimeout = 60

  trait TaskDispatcherAPI {
    def dispatch[A](op:Silk[A])
  }
}

trait TaskDispatcherImpl extends TaskDispatcherComponent {

  type TaskDispatcher = DefaultTaskDispatcher
  val taskDispatcher = new DefaultTaskDispatcher

  class DefaultTaskDispatcher extends TaskDispatcherAPI {

    val logger = LoggerFactory(classOf[TaskDispatcher])

    def dispatch[A](op:Silk[A]) {

      // Create a schedule graph
      val sg = ScheduleGraph(op)
      logger.debug(s"Schedule graph:\n$sg")

      // Launch TaskScheduler and submitter
      for(as <- LocalActorService.local) {
        // FIXME assign node name to the task queue
        val taskQueue = as.actorOf(Props(new TaskQueue("localhost")), name="taskQueue")
        val schedulerRef = as.actorOf(Props(new TaskScheduler(sg)), name="scheduler")

        // Tick scheduler periodically
        import scala.concurrent.duration._
        import as.dispatcher
        as.scheduler.scheduleOnce(taskDispatcherTimeout.seconds){ schedulerRef ! TaskScheduler.Timeout }

        // Start evaluation
        schedulerRef ! TaskScheduler.Start

        // Await termination of the scheduler
        as.awaitTermination()
      }
    }
  }

}

Fix actor creation of TaskQueue

Fix actor creation of TaskQueue


package com.sksamuel.elastic4s.searches.aggs

trait AbstractAggregation {
  type T <: AbstractAggregation
  def name: String
  def metadata: Map[String, AnyRef]
  def metadata(map: Map[String, AnyRef]): T
}

trait AggregationDefinition extends AbstractAggregation {

  def subaggs: Seq[AbstractAggregation]

  def subagg(agg: AbstractAggregation): T = subaggs(agg)
  def subaggs(first: AbstractAggregation, rest: AbstractAggregation*): T = subaggs(first +: rest)
  def subaggs(aggs: Iterable[AbstractAggregation]): T = subAggregations(aggs)

  def subAggregation(agg: AbstractAggregation): T = subAggregations(agg)
  def subAggregations(first: AbstractAggregation, rest: AbstractAggregation*): T = subAggregations(first +: rest)
  def subAggregations(aggs: Iterable[AbstractAggregation]): T
}

package com.sksamuel.elastic4s.searches.aggs

trait AbstractAggregation {
  type T <: AbstractAggregation
  def name: String
  def metadata: Map[String, AnyRef]
  def metadata(map: Map[String, AnyRef]): T
}

trait AggregationDefinition extends AbstractAggregation {

  def subaggs: Seq[AbstractAggregation]

  def subagg(agg: AbstractAggregation): T = subaggs(agg, subaggs: _*)
  def subaggs(first: AbstractAggregation, rest: AbstractAggregation*): T = subaggs(first +: rest)
  def subaggs(aggs: Iterable[AbstractAggregation]): T = subAggregations(aggs)

  def subAggregation(agg: AbstractAggregation): T = subAggregations(agg, subaggs: _*)
  def subAggregations(first: AbstractAggregation, rest: AbstractAggregation*): T = subAggregations(first +: rest)
  def subAggregations(aggs: Iterable[AbstractAggregation]): T
}

Add sub aggregation rather than replacing all of the previously added ones


package scorex.consensus

import scorex.crypto.encode.Base58
import scorex.transaction.Transaction
import scorex.transaction.assets.exchange.ExchangeTransaction

object TransactionsOrdering extends Ordering[Transaction] {
  private def orderBy(t: Transaction): (Int, Long, Long, String) = {
    //TODO sort by real value of fee?
    val byFee = t.assetFee._1.foldLeft(-t.assetFee._2)((_, asset) => 0L)
    val byTimestamp = -t.timestamp
    val byAddress = Base58.encode(t.id)
    val typeOrdering = t match {
      case exchange: ExchangeTransaction => -1
      case _ => 0
    }

    (typeOrdering, byFee, byTimestamp, byAddress)
  }
  override def compare(first: Transaction, second: Transaction): Int = {
    implicitly[Ordering[(Int, Long, Long, String)]].compare(orderBy(first), orderBy(second))
  }
}

package scorex.consensus

import scorex.crypto.encode.Base58
import scorex.transaction.Transaction

object TransactionsOrdering extends Ordering[Transaction] {
  private def orderBy(t: Transaction): (Long, Long, String) = {
    //TODO sort by real value of fee?
    val byFee = t.assetFee._1.foldLeft(-t.assetFee._2)((_, asset) => 0L)
    val byTimestamp = -t.timestamp
    val byAddress = Base58.encode(t.id)

    (byFee, byTimestamp, byAddress)
  }
  override def compare(first: Transaction, second: Transaction): Int = {
    implicitly[Ordering[(Long, Long, String)]].compare(orderBy(first), orderBy(second))
  }
}

Remove special ordering for ExchangeTransaction


package dotty
package tools
package scripting

import java.io.File

import org.junit.Test

import vulpix.TestConfiguration

/** Runs all tests contained in `compiler/test-resources/repl/` */
class ScriptingTests:
  extension (str: String) def dropExtension =
    str.reverse.dropWhile(_ != '.').drop(1).reverse

  @Test def scriptingTests =
    val testFiles = scripts("/scripting")

    val argss: Map[String, Array[String]] = (
      for
        argFile <- testFiles
        if argFile.getName.endsWith(".args")
        name = argFile.getName.dropExtension
        scriptArgs = readLines(argFile).toArray
      yield name -> scriptArgs).toMap

    for
      scriptFile <- testFiles
      if scriptFile.getName.endsWith(".scala")
      name = scriptFile.getName.dropExtension
      scriptArgs = argss.getOrElse(name, Array.empty[String])
    do
      ScriptingDriver(
        compilerArgs = Array(
            "-classpath", TestConfiguration.basicClasspath,
            "-color:never",
            "-Yerased-terms",
          ),
        scriptFile = scriptFile,
        scriptArgs = scriptArgs
      ).compileAndRun()

package dotty
package tools
package scripting

import java.io.File

import org.junit.Test

import vulpix.TestConfiguration

/** Runs all tests contained in `compiler/test-resources/repl/` */
class ScriptingTests:
  extension (str: String) def dropExtension =
    str.reverse.dropWhile(_ != '.').drop(1).reverse

  @Test def scriptingTests =
    val testFiles = scripts("/scripting")

    val argss: Map[String, Array[String]] = (
      for
        argFile <- testFiles
        if argFile.getName.endsWith(".args")
        name = argFile.getName.dropExtension
        scriptArgs = readLines(argFile).toArray
      yield name -> scriptArgs).toMap

    for
      scriptFile <- testFiles
      if scriptFile.getName.endsWith(".scala")
      name = scriptFile.getName.dropExtension
      scriptArgs = argss.getOrElse(name, Array.empty[String])
    do
      ScriptingDriver(
        compilerArgs = Array(
          "-classpath", TestConfiguration.basicClasspath),
        scriptFile = scriptFile,
        scriptArgs = scriptArgs
      ).compileAndRun()

Remove redundant flags from scripting tests


import stainless.lang._
object Countable2 {
  // an instance of Countable[T] gives a bijection between T and BigInt
  abstract class Countable[T] {
    require(
      forall((t: T) => g(f(t)) == t) &&
      forall((h: BigInt) => f(g(h)) == h)
    )

    def f(x: T): BigInt
    def g(x: BigInt): T
  }

  type Empty = Countable[BigInt => BigInt]

  // there is no element of Countable[BigInt => BigInt]
  // (since there is no bijection between BigInt and BigInt => BigInt)
  def lemma(e: Empty) = {
    val f: (BigInt => BigInt) => BigInt = e.f _
    val g: BigInt => (BigInt => BigInt) = e.g _
    def d(x: BigInt): BigInt = g(x)(x) + 1
    assert(d(f(d)) == g(f(d))(f(d)) + 1)
    assert(d(f(d)) == d(f(d)) + 1)
    false
  } holds

  def theorem() = {
    assert(forall((e: Empty) => lemma(e)))
    forall((e: Empty) => false)
  }.holds
}

import stainless.lang._
object Countable2 {
  // an instance of Countable[T] gives a bijection between T and BigInt
  abstract class Countable[T] {
    require(
      forall((t: T) => g(f(t)) == t) &&
      forall((h: BigInt) => f(g(h)) == h)
    )

    def f(x: T): BigInt
    def g(x: BigInt): T
  }

  type Empty = Countable[BigInt => BigInt]

  // there is no element of Countable[BigInt => BigInt]
  // (since there is no bijection between BigInt and BigInt => BigInt)
  def lemma(e: Empty) = {
    val f: (BigInt => BigInt) => BigInt = e.f _
    val g: BigInt => (BigInt => BigInt) = e.g _
    def d(x: BigInt): BigInt = g(x)(x) + 1
    assert(d(f(d)) == g(f(d))(f(d)) + 1)
    assert(d(f(d)) == d(f(d)) + 1)
    false
  } holds

  /* true but unprovable with current quantifier module
  def theorem() = {
    assert(forall((e: Empty) => lemma(e)))
    forall((e: Empty) => false)
  }.holds
  */
}

Fix benchmark that shouldn't be passing

Fix benchmark that shouldn't be passing


package modules.jwt.decoder

import scala.util.Try

class JwtDecoderImpl extends JwtDecoder {
  override def decode(token: String): Try[String] = ???
}

package modules.jwt.decoder

import javax.inject.{Inject, Named}
import pdi.jwt.Jwt
import pdi.jwt.algorithms.JwtHmacAlgorithm

import scala.util.Try

class JwtDecoderImpl @Inject()(@Named("jwt.secretKey") secretKey: String,
                               algorithm: JwtHmacAlgorithm) extends JwtDecoder {
  override def decode(token: String): Try[String] = {
    Jwt.decodeRaw(token, secretKey, Seq(algorithm))
  }
}

Add an implementation to JwtDecoder

Add an implementation to JwtDecoder


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

package org.openmole.misc.tools.io

import java.io.OutputStream

class StringBuilderOutputStream(val builder: StringBuilder = new StringBuilder) extends OutputStream {
  override def write(b: Int) = builder.append(b)
}

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

package org.openmole.misc.tools.io

import java.io.OutputStream

class StringBuilderOutputStream(val builder: StringBuilder = new StringBuilder) extends OutputStream {
  override def write(b: Int) = builder.append(b.toChar)
}

Fix bug in string builder output stream.


package ingraph.ire

import hu.bme.mit.ire.TransactionFactory
import org.scalatest.FlatSpec

import scala.io.Source

class IntegrationTest extends FlatSpec {
  val modelPath = "../trainbenchmark/models/railway-repair-1-tinkerpop.graphml"
  def queryPath(query: String): String = s"queries/trainbenchmark/$query.cypher"
  case class TestCase(name: String, expectedResultSize: Int)

  Vector(
    TestCase("PosLength", 95),
    TestCase("RouteSensor", 18),
    TestCase("SemaphoreNeighbor", 3),
    TestCase("SwitchMonitored", 0),
    TestCase("SwitchSet", 5)
  ).foreach(
    t => t.name should "work" in {
      val query = Source.fromFile(queryPath(t.name)).getLines().mkString
      val adapter = new IngraphAdapter(query)
      val tf = new TransactionFactory(16)
      tf.subscribe(adapter.engine.inputLookup)
      val tran = tf.newBatchTransaction()

      adapter.readGraph(modelPath, tran)
      tran.close()
      val results = adapter.engine.getResults().size
      assert(results == t.expectedResultSize)
    }
  )
}

package ingraph.ire

import hu.bme.mit.ire.TransactionFactory
import org.scalatest.FlatSpec

import scala.io.Source

// in Eclipse / ScalaTest, open the run configuration, go to the Arguments tab and set the
// Working directory to Other: ${workspace_loc:ingraph}
class IntegrationTest extends FlatSpec {
  val modelPath = "../trainbenchmark/models/railway-repair-1-tinkerpop.graphml"
  def queryPath(query: String): String = s"queries/trainbenchmark/$query.cypher"
  case class TestCase(name: String, expectedResultSize: Int)

  Vector(
    TestCase("PosLength", 95),
    TestCase("RouteSensor", 18),
    TestCase("SemaphoreNeighbor", 3),
    TestCase("SwitchMonitored", 0),
    TestCase("SwitchSet", 5)
  ).foreach(
    t => t.name should "work" in {
      val query = Source.fromFile(queryPath(t.name)).getLines().mkString
      val adapter = new IngraphAdapter(query)
      val tf = new TransactionFactory(16)
      tf.subscribe(adapter.engine.inputLookup)
      val tran = tf.newBatchTransaction()

      adapter.readGraph(modelPath, tran)
      tran.close()
      val results = adapter.engine.getResults().size
      assert(results == t.expectedResultSize)
    }
  )
}

Add comment for Eclipse & ScalaTest

Add comment for Eclipse & ScalaTest


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

package org.openmole.plugin.domain

import org.openmole.core.model.data._
import org.openmole.core.model.sampling._
import org.openmole.core.implementation.data._

package object collection {
  implicit def scalaIterableDomainDecorator[T](iterable: Iterable[T]) = new {
    def toDomain = new IterableDomain[T](iterable)
  }

  implicit def prototypeDomainDecorator[T](variable: Prototype[Array[T]]) = new {
    def toDomain = new VariableDomain[T](variable)
    def toFactor = Factor(variable.fromArray, new VariableDomain[T](variable))
  }
}

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

package org.openmole.plugin.domain

import org.openmole.core.model.data._
import org.openmole.core.model.sampling._
import org.openmole.core.implementation.data._

package object collection {

  implicit def scalaIterableDomainDecorator[T](iterable: Iterable[T]) = new {
    def toDomain = new IterableDomain[T](iterable)
  }

  implicit def prototypeDomainDecorator[T](variable: Prototype[Array[T]]) = new {
    def toDomain = new VariableDomain[T](variable)
    def toFactor = Factor(variable.fromArray, new VariableDomain[T](variable))
  }

  implicit def booleanPrototypeDecorator(p: Prototype[Boolean]) = new {
    def toFactor = Factor(p, List(true, false) toDomain)
  }

}

Add to factor for booleans prototypes.

Add to factor for booleans prototypes.


/**
 * Definition for singly-linked list.
 * class ListNode(_x: Int = 0, _next: ListNode = null) {
 *   var next: ListNode = _next
 *   var x: Int = _x
 * }
 */
object Solution {
  def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
    var sum, c, l1_val, l2_val:Int = 0
    var dump = new ListNode
    var (p, pl1, pl2) = (dump, l1, l2)

    while(pl1 != null || pl2 != null) {
      if (pl1 != null) {
        l1_val = pl1.x
        pl1 = pl1.next
      }

      if (pl2 != null) {
        l2_val = pl2.x
        pl2 = pl2.next
      }

      sum = c + l1_val + l2_val
      p.next = new ListNode(sum % 10)
      p = p.next
      c = sum / 10

      l1_val = 0; l2_val = 0
    }

    if (c == 1) {
      p.next = new ListNode(1)
    }

    return dump.next
  }
}

/**
 * Definition for singly-linked list.
 * class ListNode(_x: Int = 0, _next: ListNode = null) {
 *   var next: ListNode = _next
 *   var x: Int = _x
 * }
 */
object Solution {
  def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
    val dump = new ListNode
    var sum, c, l1_val, l2_val:Int = 0
    var (p, pl1, pl2) = (dump, l1, l2)

    while(pl1 != null || pl2 != null) {
      if (pl1 != null) {
        l1_val = pl1.x
        pl1 = pl1.next
      }

      if (pl2 != null) {
        l2_val = pl2.x
        pl2 = pl2.next
      }

      sum = c + l1_val + l2_val
      p.next = new ListNode(sum % 10)
      p = p.next
      c = sum / 10

      l1_val = 0; l2_val = 0
    }

    if (c == 1) {
      p.next = new ListNode(1)
    }

    return dump.next
  }
}

[LEETCODE] Add Two Numbers - scala - update var to val for one constant


package org.scalatest.tools

import org.scalatest.Spec
import org.scalatest.matchers.ShouldMatchers

class SbtCommandParserSpec extends Spec with ShouldMatchers {

  describe("the cmd terminal?") {
    it("should parse 'st'") {

      val parser = new SbtCommandParser
      val result = parser.parseResult("""st""")
      result match {
        case parser.Success(result, _) => println("success: " + result)
        case ns: parser.NoSuccess => fail(ns.toString)
      }
    }
    it("should parse 'st --'") {

      val parser = new SbtCommandParser
      val result = parser.parseResult("""st --""")
      result match {
        case parser.Success(result, _) => println("success: " + result)
        case ns: parser.NoSuccess => fail(ns.toString)
      }
    }
  }
}

package org.scalatest.tools

import org.scalatest.Spec
import org.scalatest.matchers.ShouldMatchers

class SbtCommandParserSpec extends Spec with ShouldMatchers {

  val parser = new SbtCommandParser

  def canParsePhrase(s: String) {
      val result = parser.parseResult(s)
      result match {
        case ns: parser.NoSuccess => fail(ns.toString)
        case _ =>
      }
  }

  def cannotParsePhrase(s: String) {
      val result = parser.parseResult(s)
      result match {
        case parser.Success(result, _) => fail("wasn't supposed to, but parsed: " + result)
        case _ =>
      }
  }

  describe("the cmd terminal?") {
    it("should parse 'st'") {
      canParsePhrase("""st""")
      canParsePhrase("""st --""")
    }
  }
}

Reduce code dup in test.

Reduce code dup in test.


package info.spielproject.spiel
package utils

import android.util.Log

object HtmlParser {

  import xml.XML
  import java.io.{ByteArrayInputStream, ByteArrayOutputStream, OutputStreamWriter}
  import org.ccil.cowan.tagsoup._
  import org.xml.sax.InputSource

  def apply(html:String) = {
    val parser = new Parser()
    parser.setProperty(Parser.schemaProperty, new HTMLSchema())
    val input = new InputSource(new ByteArrayInputStream(html.getBytes))
    val output = new ByteArrayOutputStream()
    val writer = new OutputStreamWriter(output)
    val xmlWriter = new XMLWriter(writer)
    xmlWriter.setOutputProperty(XMLWriter.OMIT_XML_DECLARATION, "yes")
    parser.setContentHandler(xmlWriter)
    parser.parse(input)
    Log.d("spielcheck", "HTML: "+html)
    XML.loadString(new String(output.toByteArray))
  }

}

package info.spielproject.spiel
package utils

import android.util.Log

object HtmlParser {

  import xml.XML
  import java.io.{ByteArrayInputStream, ByteArrayOutputStream, OutputStreamWriter}
  import org.ccil.cowan.tagsoup._
  import org.xml.sax.InputSource

  def apply(html:String) = {
    val parser = new Parser()
    parser.setProperty(Parser.schemaProperty, new HTMLSchema())
    val input = new InputSource(new ByteArrayInputStream(html.getBytes))
    val output = new ByteArrayOutputStream()
    val writer = new OutputStreamWriter(output)
    val xmlWriter = new XMLWriter(writer)
    xmlWriter.setOutputProperty(XMLWriter.OMIT_XML_DECLARATION, "yes")
    parser.setContentHandler(xmlWriter)
    parser.parse(input)
    val x = XML.loadString(new String(output.toByteArray))
    x
  }

}

Remove debugging output from HTML parser.

--HG--
extra : convert_revision : 25c5c9b2d23090e7270daee1ab7ecb9cf34e2a2c


package hmda

import cats.data.ValidatedNel
import hmda.model.validation.ValidationError

package object validation {
  type Seq[+A] = collection.immutable.Seq[A]
  type HmdaValidation[+B] = ValidatedNel[ValidationError, B]
  type HmdaValidated[+B] = Either[List[ValidationError], B]
}

package hmda

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import cats.data.ValidatedNel
import hmda.model.validation.ValidationError

import scala.concurrent.ExecutionContext

package object validation {
  type Seq[+A] = collection.immutable.Seq[A]
  type HmdaValidation[+B] = ValidatedNel[ValidationError, B]
  type HmdaValidated[+B] = Either[List[ValidationError], B]

  type AS[_] = ActorSystem
  type MAT[_] = ActorMaterializer
  type EC[_] = ExecutionContext
}

Add implicit context bounds types

Add implicit context bounds types


package skinny.standalone

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.{ DefaultServlet, ServletContextHandler }
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener

/**
 * Jetty server launcher for standalone apps.
 *
 * see: http://scalatra.org/2.2/guides/deployment/standalone.html
 */
object JettyLauncher {

  def main(args: Array[String]) {
    val port = sys.env.get("SKINNY_PORT").orElse(getEnvVarOrSysProp("skinny.port")).map(_.toInt).getOrElse(8080)
    println(s"Starting Jetty on port ${port}")

    val server = new Server(port)
    val context = new WebAppContext()
    val contextPath = sys.env.get("SKINNY_PREFIX").orElse(getEnvVarOrSysProp("skinny.prefix")).getOrElse("/")
    context.setContextPath(contextPath)
    context.setResourceBase("src/main/webapp")
    context.addEventListener(new ScalatraListener)
    context.addServlet(classOf[DefaultServlet], "/")
    server.setHandler(context)
    server.start
    server.join
  }

  def getEnvVarOrSysProp(key: String): Option[String] = {
    sys.env.get(key) orElse sys.props.get(key)
  }

}

package skinny.standalone

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.{ DefaultServlet, ServletContextHandler }
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener

/**
 * Jetty server launcher for standalone apps.
 *
 * see: http://scalatra.org/2.2/guides/deployment/standalone.html
 */
object JettyLauncher {

  def main(args: Array[String]) {
    val port = sys.env.get("SKINNY_PORT").orElse(getEnvVarOrSysProp("skinny.port")).map(_.toInt).getOrElse(8080)
    println(s"Starting Jetty on port ${port}")

    val server = new Server(port)
    val context = new WebAppContext()
    val contextPath = sys.env.get("SKINNY_PREFIX").orElse(getEnvVarOrSysProp("skinny.prefix")).getOrElse("/")
    context.setContextPath(contextPath)
    context.setWar({
      val domain = this.getClass.getProtectionDomain
      val location = domain.getCodeSource.getLocation
      location.toExternalForm
    })
    context.addEventListener(new ScalatraListener)
    context.addServlet(classOf[DefaultServlet], "/")
    server.setHandler(context)
    server.start
    server.join
  }

  def getEnvVarOrSysProp(key: String): Option[String] = {
    sys.env.get(key) orElse sys.props.get(key)
  }

}

Fix resources in standalone jar are not available


package net.sansa_stack.rdf.spark.qualityassessment.metrics.performance

import org.apache.spark.rdd.RDD
import org.apache.jena.graph.{ Triple, Node }

import net.sansa_stack.rdf.spark.qualityassessment.utils.NodeUtils._

/**
 * @author Gezim Sejdiu
 */
object NoHashURIs {
  implicit class NoHashURIsFunctions(dataset: RDD[Triple]) extends Serializable {
    def assessNoHashUris() = {

      val triples = dataset.count().toDouble

      val subjects = dataset.filter(f => f.getSubject.isURI() && isHashUri(f.getSubject)).count().toDouble
      val predicate = dataset.filter(f => isHashUri(f.getPredicate)).count().toDouble
      val objects = dataset.filter(f => f.getObject.isURI() && isHashUri(f.getObject)).count().toDouble

      val NoHashURIs = subjects + predicate + objects

      val value = if (triples > 0.0)
        NoHashURIs / triples;
      else 0

      value
    }
  }
}

package net.sansa_stack.rdf.spark.qualityassessment.metrics.performance

import net.sansa_stack.rdf.spark.qualityassessment.utils.NodeUtils._
import org.apache.jena.graph.{ Node, Triple }
import org.apache.spark.rdd.RDD

/**
 * @author Gezim Sejdiu
 */
object NoHashURIs {

  def assessNoHashUris(dataset: RDD[Triple]): Double = {

    val triples = dataset.count().toDouble

    val subjects = dataset.filter(f => f.getSubject.isURI() && isHashUri(f.getSubject)).count().toDouble
    val predicate = dataset.filter(f => isHashUri(f.getPredicate)).count().toDouble
    val objects = dataset.filter(f => f.getObject.isURI() && isHashUri(f.getObject)).count().toDouble

    val NoHashURIs = subjects + predicate + objects

    val value = if (triples > 0.0) {
      NoHashURIs / triples
    } else 0

    value
  }
}

Refactor performance metrics and make Scala-style compliant


package modules.upload.graphql.schema

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

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

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

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

package modules.upload.graphql.schema

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

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

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

  implicit val fileMetadata: ObjectType[Unit, FileMetadata] = deriveObjectType(ObjectTypeName("File"))

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

  override def queries: List[Field[UserContext, Unit]] = List(
    Field(
      name = "files",
      fieldType = ListType(fileMetadata),
      resolve = _ => fileUploadResolver.files
    )
  )
}

Add GraphQL types for the 'files' query

Add GraphQL types for the 'files' query


import sbt.Keys._
import sbt._

object Common extends AutoPlugin {

  override def trigger: PluginTrigger = allRequirements

  override def requires: Plugins = plugins.JvmPlugin

  override lazy val projectSettings: Seq[Setting[_]] = Seq(
    scalaVersion := "2.12.0",
    crossScalaVersions := Seq("2.12.0", "2.11.8"),
    scalacOptions ++= Seq(
      "-deprecation",
      "-unchecked",
      "-feature",
      "-Xlint",
      "-Xexperimental",
      "-language:higherKinds",
      "-language:implicitConversions",
      "-language:experimental.macros"
    ),
    updateOptions := updateOptions.value.withCachedResolution(true),
    incOptions := incOptions.value.withLogRecompileOnMacro(false)
  )

}

import BuildUtil.scala211Only
import sbt.Keys._
import sbt._

object Common extends AutoPlugin {

  override def trigger: PluginTrigger = allRequirements

  override def requires: Plugins = plugins.JvmPlugin

  override lazy val projectSettings: Seq[Setting[_]] = Seq(
    scalaVersion := "2.12.0",
    crossScalaVersions := Seq("2.12.0", "2.11.8"),
    scalacOptions ++= Seq(
      "-deprecation",
      "-unchecked",
      "-feature",
      "-Xlint",
      "-language:higherKinds",
      "-language:implicitConversions",
      "-language:experimental.macros"
    ) ++ scala211Only(
      // lambda syntax for SAM types
      "-Xexperimental"
    ).value,
    updateOptions := updateOptions.value.withCachedResolution(true),
    incOptions := incOptions.value.withLogRecompileOnMacro(false)
  )

}

Enable -Xexperimental for Scala 2.11 only


package core

import component._

import akka.actor.{ Actor, ActorRef, ActorSystem, Props }

case class Config(host: String = "localhost", port: Int = 9000,
    router: Option[String] = None, mode: Option[String] = None)

object Main extends App {
  val parser = new scopt.OptionParser[Config]("jeeves") {
    head("jeeves", "1.0")
    opt[String]('h', "host") action { (x, c) =>
      c.copy(host = x) } text("host. Default: localhost")
    opt[Int]('p', "port") action { (x, c) =>
      c.copy(port = x) } text("port number. Default: 9000")
    opt[String]('r', "router") action { (x, c) =>
      c.copy(router = Some(x)) } text("router's host and port. e.g.: localhost:9101")
    opt[String]('m', "mode") action { (x, c) =>
      c.copy(mode = Some(x)) } text("running mode. e.g.: dev, test")
   }

  // parser.parse returns Option[C]
  parser.parse(args, Config()) match {
    case Some(config) =>
      val superVisor = Supervisor.actorSystem.actorOf(Supervisor.props(config), Supervisor.name)
    case None =>
  }
}

package core

import component._

import akka.actor.{ Actor, ActorRef, ActorSystem, Props }

case class Config(host: String = "0.0.0.0", port: Int = 9000,
    router: Option[String] = None, mode: Option[String] = None)

object Main extends App {
  val parser = new scopt.OptionParser[Config]("jeeves") {
    head("jeeves", "1.0")
    opt[String]('h', "host") action { (x, c) =>
      c.copy(host = x) } text("host. Default: 0.0.0.0")
    opt[Int]('p', "port") action { (x, c) =>
      c.copy(port = x) } text("port number. Default: 9000")
    opt[String]('r', "router") action { (x, c) =>
      c.copy(router = Some(x)) } text("router's host and port. e.g.: localhost:9101")
    opt[String]('m', "mode") action { (x, c) =>
      c.copy(mode = Some(x)) } text("running mode. e.g.: dev, test")
   }

  // parser.parse returns Option[C]
  parser.parse(args, Config()) match {
    case Some(config) =>
      val superVisor = Supervisor.actorSystem.actorOf(Supervisor.props(config), Supervisor.name)
    case None =>
  }
}

Set default host to 0.0.0.0

Set default host to 0.0.0.0


package com.kubukoz.scala99

import scala.annotation.tailrec

/**
  * P01 (*) Find the last element of a list.
  * Example:
  * scala> last(List(1, 1, 2, 3, 5, 8))
  * res0: Option[Int] = Some(8)
  **/
object P01 {

  @tailrec
  def last[T](list: List[T]): Option[T] = list match {
    case Nil => None
    case h :: Nil => Some(h)
    case _ :: rest => last(rest)
  }
}

package com.kubukoz.scala99

import scala.annotation.tailrec

/**
  * P01 (*) Find the last element of a list.
  * Example:
  * scala> last(List(1, 1, 2, 3, 5, 8))
  * res0: Option[Int] = Some(8)
  **/
object P01 {

  /**
    * Built-in, inherited from `TraversableLike`.
    *
    * As of Scala 2.11.8 internally implemented in terms of
    * `isEmpty` and `last`.
    **/
  def lastBuiltin[T](list: List[T]): Option[T] = list.lastOption

  /**
    * Probably the most idiomatic implementation,
    * if you don't have the built-in `.last` method on `List`.
    *
    * Implemented with pattern matching.
    **/
  @tailrec
  def last[T](list: List[T]): Option[T] = list match {
    case Nil => None
    case h :: Nil => Some(h)
    case _ :: rest => last(rest)
  }
}

Add more information and a second implementation for the task


// Recursive version:
def _replicateM[A](n: Int, ma: F[A]): F[List[A]] =
  if (n <= 0) unit(List[A]()) else map2(ma, replicateM(n - 1, ma))(_ :: _)

// Using `sequence` and the `List.fill` function of the standard library:
def replicateM[A](n: Int, ma: F[A]): F[List[A]] =
  sequence(List.fill(n)(ma))

// Recursive version:
def _replicateM[A](n: Int, ma: F[A]): F[List[A]] =
  if (n <= 0) unit(List[A]()) else map2(ma, _replicateM(n - 1, ma))(_ :: _)

// Using `sequence` and the `List.fill` function of the standard library:
def replicateM[A](n: Int, ma: F[A]): F[List[A]] =
  sequence(List.fill(n)(ma))

Fix 04Answer Monads - wrong function call


package lila.common

import ornicar.scalalib.Random
import play.api.mvc.{ Cookie, DiscardingCookie, Session, RequestHeader }

object LilaCookie {

  private val domainRegex = """\.[^.]++\.[^.]++$""".r

  private def domain(req: RequestHeader): String =
    domainRegex.findFirstIn(req.domain).getOrElse(req.domain)

  private lazy val defaultHttpOnly = false // Session.httpOnly

  val sessionId = "sid"

  def makeSessionId(implicit req: RequestHeader) = session(sessionId, Random secureString 10)

  def session(name: String, value: String)(implicit req: RequestHeader): Cookie = withSession { s =>
    s + (name -> value)
  }

  def newSession(implicit req: RequestHeader): Cookie = withSession(identity)

  def withSession(op: Session => Session)(implicit req: RequestHeader): Cookie = cookie(
    Session.COOKIE_NAME,
    Session.encode(Session.serialize(op(req.session)))
  )

  def cookie(name: String, value: String, maxAge: Option[Int] = None, httpOnly: Option[Boolean] = None)(implicit req: RequestHeader): Cookie = Cookie(
    name,
    value,
    maxAge orElse Session.maxAge orElse 86400.some,
    "/",
    domain(req).some,
    Session.secure || req.headers.get("X-Forwarded-Proto").contains("https"),
    httpOnly | defaultHttpOnly
  )

  def discard(name: String)(implicit req: RequestHeader) =
    DiscardingCookie(name, "/", domain(req).some, defaultHttpOnly)
}

package lila.common

import ornicar.scalalib.Random
import play.api.mvc.{ Cookie, DiscardingCookie, Session, RequestHeader }

object LilaCookie {

  private val domainRegex = """\.[^.]++\.[^.]++$""".r

  private def domain(req: RequestHeader): String =
    domainRegex.findFirstIn(req.domain).getOrElse(req.domain)

  val sessionId = "sid"

  def makeSessionId(implicit req: RequestHeader) = session(sessionId, Random secureString 10)

  def session(name: String, value: String)(implicit req: RequestHeader): Cookie = withSession { s =>
    s + (name -> value)
  }

  def newSession(implicit req: RequestHeader): Cookie = withSession(identity)

  def withSession(op: Session => Session)(implicit req: RequestHeader): Cookie = cookie(
    Session.COOKIE_NAME,
    Session.encode(Session.serialize(op(req.session)))
  )

  def cookie(name: String, value: String, maxAge: Option[Int] = None, httpOnly: Option[Boolean] = None)(implicit req: RequestHeader): Cookie = Cookie(
    name,
    value,
    maxAge orElse Session.maxAge orElse 86400.some,
    "/",
    domain(req).some,
    Session.secure || req.headers.get("X-Forwarded-Proto").contains("https"),
    httpOnly | Session.httpOnly
  )

  def discard(name: String)(implicit req: RequestHeader) =
    DiscardingCookie(name, "/", domain(req).some, Session.httpOnly)
}

Revert "default cookie httpOnly=false for stage"

This reverts commit 9197b25d5445664d03751a069677d46098f5b2ad.


package dotty.tools.dotc
package core

import Contexts._
import config.Printers.typr

trait ConstraintRunInfo { self: Run =>
  private[this] var maxSize = 0
  private[this] var maxConstraint: Constraint = _
  def recordConstraintSize(c: Constraint, size: Int) =
    if (size > maxSize) {
      maxSize = size
      maxConstraint = c
    }
  def printMaxConstraint()(implicit ctx: Context) =
    if (maxSize > 0) typr.println(s"max constraint = ${maxConstraint.show}")

  protected def reset() = maxConstraint = null
}

package dotty.tools.dotc
package core

import Contexts._
import config.Printers.{default, typr}

trait ConstraintRunInfo { self: Run =>
  private[this] var maxSize = 0
  private[this] var maxConstraint: Constraint = _
  def recordConstraintSize(c: Constraint, size: Int) =
    if (size > maxSize) {
      maxSize = size
      maxConstraint = c
    }
  def printMaxConstraint()(implicit ctx: Context) = {
    val printer = if (ctx.settings.YdetailedStats.value) default else typr
    if (maxSize > 0) printer.println(s"max constraint = ${maxConstraint.show}")
  }
  protected def reset() = maxConstraint = null
}

Print max constraint under -Ydetailed-stats


/**
 * Illustrates a simple fold in scala
 */
package com.oreilly.learningsparkexamples.scala

import org.apache.spark._

object BasicSum {
    def main(args: Array[String]) {
      val master = args.length match {
        case x: Int if x > 0 => args(0)
        case _ => "local"
      }
      val sc = new SparkContext(master, "BasicMap", System.getenv("SPARK_HOME"))
      val input = sc.parallelize(List(1,2,3,4))
      val squared = input.map(x => x*x)
      val result = squared.fold(0)((x, y) => (x + y))
      println(result)
    }
}

/**
 * Illustrates a simple fold in scala
 */
package com.oreilly.learningsparkexamples.scala

import org.apache.spark._

object BasicSum {
    def main(args: Array[String]) {
      val master = args.length match {
        case x: Int if x > 0 => args(0)
        case _ => "local"
      }
      val sc = new SparkContext(master, "BasicMap", System.getenv("SPARK_HOME"))
      val input = sc.parallelize(List(1,2,3,4))
      val result = input.fold(0)((x, y) => (x + y))
      println(result)
    }
}

Change basic sum scala example to match java one more closely


resolvers ++= Seq(
  Resolver.url("fix-sbt-plugin-releases", url("https://dl.bintray.com/sbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns),
  Resolver.bintrayRepo("scala-js", "scala-js-releases")
)

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

addSbtPlugin("com.lihaoyi" % "workbench" % "0.2.3")

addSbtPlugin("me.lessis" % "bintray-sbt" % "0.2.1")

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

resolvers ++= Seq(
  Resolver.bintrayRepo("scala-js", "scala-js-releases")
)

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

addSbtPlugin("com.lihaoyi" % "workbench" % "0.2.3")

addSbtPlugin("me.lessis" % "bintray-sbt" % "0.2.1")

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

Remove temporary SBT plugin repo

Remove temporary SBT plugin repo


addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.9.0")
addSbtPlugin("org.scala-js" % "sbt-jsdependencies" % "1.0.2")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.4")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.9.0")

val sbtSoftwareMillVersion = "2.0.9"
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-browser-test-js" % sbtSoftwareMillVersion)

addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.3.1")

addSbtPlugin("org.jetbrains.scala" % "sbt-ide-settings" % "1.1.1")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.1")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.9.0")
addSbtPlugin("org.scala-js" % "sbt-jsdependencies" % "1.0.2")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.4")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.9.0")

val sbtSoftwareMillVersion = "2.0.9"
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion)
addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-browser-test-js" % sbtSoftwareMillVersion)

addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.3.2")

addSbtPlugin("org.jetbrains.scala" % "sbt-ide-settings" % "1.1.1")
addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.1")

Update mdoc, sbt-mdoc to 2.3.2

Update mdoc, sbt-mdoc to 2.3.2


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

// The Typesafe repository
resolvers ++= Seq(
    "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"
//    "Play2war plugins release" at "http://repository-play-war.forge.cloudbees.com/release/"
)

// Use the Play sbt plugin for Play projects
addSbtPlugin("play" % "sbt-plugin" % "2.0.2")

// addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "0.6")

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

// The Typesafe repository
resolvers ++= Seq(
    "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"
//    "Play2war plugins release" at "http://repository-play-war.forge.cloudbees.com/release/"
)

// Use the Play sbt plugin for Play projects
addSbtPlugin("play" % "sbt-plugin" % "2.0.4")

// addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "0.6")

Update Play sbt-plugin to 2.0.4

Update Play sbt-plugin to 2.0.4


scalaVersion := "2.10.6"

addSbtPlugin("com.eed3si9n" % "sbt-doge" % "0.1.5")
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.8.5")
addSbtPlugin("com.typesafe.sbt" % "sbt-javaversioncheck" % "0.1.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0") // 1.6.0 is out but is a hard upgrade
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.2")
addSbtPlugin("me.lessis" % "bintray-sbt" % "0.3.0")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.2")

scalaVersion := "2.10.6"

addSbtPlugin("com.eed3si9n" % "sbt-doge" % "0.1.5")
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.4")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.8.5")
addSbtPlugin("com.typesafe.sbt" % "sbt-javaversioncheck" % "0.1.0")
addSbtPlugin("com.jsuereth"     % "sbt-pgp"              % "1.0.0")
addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0") // 1.6.0 is out but is a hard upgrade
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.2")
addSbtPlugin("me.lessis" % "bintray-sbt" % "0.3.0")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.2")

Add sbt-pgp, required by publishSigned in release-sbt


libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.10"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.9.34")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.10.0")
addSbtPlugin("com.github.sbt" % "sbt-unidoc" % "0.5.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.9")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.12.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.8")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.10"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.9.34")
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.sbt" % "sbt-unidoc" % "0.5.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.9.9")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.12.1")
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.8")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")

Update sbt-buildinfo to 0.11.0 in series/0.22


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

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.5")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "2.1.1")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1")

addSbtPlugin("io.youi" % "youi-plugin" % "1.2.0")

libraryDependencies += "org.scala-js" %% "scalajs-env-jsdom-nodejs" % "1.1.0"

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

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.5")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "2.1.1")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1")

addSbtPlugin("io.youi" % "youi-plugin" % "1.2.0")

libraryDependencies += "org.scala-js" %% "scalajs-env-jsdom-nodejs" % "1.1.0"

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


resolvers += "jgit-repo" at "http://download.eclipse.org/jgit/maven"

addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "1.4.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3")

addSbtPlugin("com.eed3si9n" % "sbt-unidoc" % "0.4.3")

resolvers += Classpaths.sbtPluginReleases

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

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

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.4")

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

// cross-compiling
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject"      % "1.0.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"                   % "1.1.1")

resolvers += "jgit-repo" at "http://download.eclipse.org/jgit/maven"

addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "1.4.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3")

addSbtPlugin("com.eed3si9n" % "sbt-unidoc" % "0.4.3")

resolvers += Classpaths.sbtPluginReleases

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

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

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.4")

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

// cross-compiling
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject"      % "1.0.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"                   % "0.6.33")

Revert "Update sbt-scalajs to 1.1.1"

Revert "Update sbt-scalajs to 1.1.1"


package skinny.controller.feature

import skinny.SkinnyEnv
import org.scalatra.ScalatraBase

/**
 * SkinnyEnv support.
 */
trait EnvFeature extends ScalatraBase {

  /**
   * Env string value from "skinny.env" or "org.scalatra.environment".
   *
   * @return env string such as "production"
   */
  def skinnyEnv: Option[String] = SkinnyEnv.get().orElse(Option(environment))

  /**
   * Predicates current env is "development" or "dev".
   *
   * @return true/false
   */
  def isDevelopment(): Boolean = SkinnyEnv.isDevelopment(skinnyEnv)

  /**
   * Predicates current env is "test".
   *
   * @return true/false
   */
  def isTest(): Boolean = SkinnyEnv.isTest(skinnyEnv)

  /**
   * Predicates current env is "staging" or "qa".
   *
   * @return true/false
   */
  def isStaging(): Boolean = SkinnyEnv.isStaging(skinnyEnv)

  /**
   * Predicates current env is "production" or "prod".
   *
   * @return true/false
   */
  def isProduction(): Boolean = SkinnyEnv.isProduction(skinnyEnv)

}

package skinny.controller.feature

import skinny.SkinnyEnv
import org.scalatra.ScalatraBase

/**
 * SkinnyEnv support.
 */
trait EnvFeature extends ScalatraBase {

  /**
   * Env string value from "skinny.env" or "org.scalatra.environment".
   *
   * @return env string such as "production"
   */
  def skinnyEnv: Option[String] = SkinnyEnv.get().orElse(Option(environment))

  /**
   * Predicates current env is "development" or "dev".
   *
   * @return true/false
   */
  def isDevelopment(): Boolean = SkinnyEnv.isDevelopment(skinnyEnv)

  /**
   * Predicates current env is "test".
   *
   * @return true/false
   */
  def isTest(): Boolean = SkinnyEnv.isTest(skinnyEnv)

  /**
   * Predicates current env is "staging" or "qa".
   *
   * @return true/false
   */
  def isStaging(): Boolean = SkinnyEnv.isStaging(skinnyEnv)

  /**
   * Predicates current env is "production" or "prod".
   *
   * @return true/false
   */
  def isProduction(): Boolean = SkinnyEnv.isProduction(skinnyEnv)

  /**
   * Replaces Scalatra's development mode with SkinnyEnv.
   */
  override protected def isDevelopmentMode = isDevelopment()

}

Replace Scalatra's isDevelopmentMode with SkinnyEnv


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

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

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

addSbtPlugin("org.databrary" % "sbt-angular-templates" % "0.1")

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

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

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

addSbtPlugin("com.typesafe.sbt" % "sbt-uglify" % "1.0.3")

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

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

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

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

addSbtPlugin("org.databrary" % "sbt-angular-templates" % "0.1")

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

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

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

addSbtPlugin("com.typesafe.sbt" % "sbt-uglify" % "1.0.3")

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

Upgrade sbt-jshint to 1.0.2 (jshint 2.4.3)


/*
This file is part of Intake24.

Copyright 2015, 2016 Newcastle University.

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.
*/

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

addSbtPlugin("com.lihaoyi" % "scalatex-sbt-plugin" % "0.3.7")

addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.8.2")

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

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

/*
This file is part of Intake24.

Copyright 2015, 2016 Newcastle University.

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.
*/

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

addSbtPlugin("com.lihaoyi" % "scalatex-sbt-plugin" % "0.3.7")

addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.8.2")

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

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

Update SBT native packages version

Update SBT native packages version


libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.11"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.14.8")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.11")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.11.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.7")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.6")

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.11"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.14.9")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.11")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.11.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.7")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.6")

Update sbt-http4s-org to 0.14.9 in series/0.23


package info.spielproject.spiel

import org.acra._
import annotation._

@ReportsCrashes(
  formKey = "",
  mailTo = "spiel@thewordnerd.info",
  customReportContent = Array(ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.CUSTOM_DATA, ReportField.STACK_TRACE, ReportField.LOGCAT)
)
class Application extends android.app.Application {
  override def onCreate() {
    ACRA.init(this)
    super.onCreate()
  }
}

package info.spielproject.spiel

import org.acra._
import annotation._

import events._

@ReportsCrashes(
  formKey = "",
  mailTo = "spiel@thewordnerd.info",
  customReportContent = Array(ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.CUSTOM_DATA, ReportField.STACK_TRACE, ReportField.LOGCAT)
)
class Application extends android.app.Application {
  override def onCreate() {
    ACRA.init(this)
    UnhandledException += { t:Throwable => ErrorReporter.getInstance.handleException(t, false) }
    super.onCreate()
  }
}

Send uncaught exceptions through ACRA without crashing Spiel.


libraryDependencies ++= Seq(
  component("play"),
  jdbc,
  "com.github.mauricio" %% "postgresql-async" % "0.2.14",
  "org.postgresql" % "postgresql" % "9.3-1101-jdbc41"
)

libraryDependencies ++= Seq(
  component("play"),
  jdbc,
  "com.github.mauricio" %% "postgresql-async" % "0.2.15",
  "org.postgresql" % "postgresql" % "9.3-1102-jdbc41"
)

Upgrade DBIs: postgresql-async 1.2.15, 9.3-1102


name := "example"

version := "1.0"

scalaVersion := "2.12.10"

libraryDependencies ++= Seq(
  "com.github.pureconfig" %% "pureconfig" % "0.12.1-SNAPSHOT")

crossScalaVersions := Seq("2.12.10", "2.11.12", "2.13.0")

scalacOptions ++= Seq(
  "-deprecation",
  "-encoding", "UTF-8",
  "-language:experimental.macros",
  "-feature",
  "-unchecked",
  "-Xfatal-warnings",
  "-Xlint",
  "-Ywarn-numeric-widen",
  "-Ywarn-value-discard")

name := "example"

version := "1.0"

scalaVersion := "2.12.10"

libraryDependencies ++= Seq(
  "com.github.pureconfig" %% "pureconfig" % "0.12.2-SNAPSHOT")

crossScalaVersions := Seq("2.12.10", "2.11.12", "2.13.0")

scalacOptions ++= Seq(
  "-deprecation",
  "-encoding", "UTF-8",
  "-language:experimental.macros",
  "-feature",
  "-unchecked",
  "-Xfatal-warnings",
  "-Xlint",
  "-Ywarn-numeric-widen",
  "-Ywarn-value-discard")

Update PureConfig version in example project


package io.flow.lint.linters

import io.flow.lint.Linter
import com.bryzek.apidoc.spec.v0.models.{Model, Service}

/**
  * For models w/ field named organization, ensure organization's position is:
  *   a. fourth (if first 3 fields are id, timestamp, type), to
  *      support journals
  *   b. second field (after id)
  *   c. first field (if no id)
  */
case object ModelsWithOrganizationField extends Linter with Helpers {

  override def validate(service: Service): Seq[String] = {
    service.models.flatMap(validateModel(_))
  }

  def validateModel(model: Model): Seq[String] = {
    val fieldNames = model.fields.map(_.name)
    val index = fieldNames.indexOf("organization")

    index < 0 match {
      case true => {
        Nil
      }
      case false => {
        val position = fieldNames.take(3) match {
          case "id" :: "timestamp" :: "type" :: Nil => 3
          case "id" :: rest => 1
          case _ => 0
        }

        position == index match {
          case true => Nil
          case false => {
            Seq(error(model, s"Field[organization] must be in position[$position] and not[$index]"))
          }
        }
      }
    }
  }

}

package io.flow.lint.linters

import io.flow.lint.Linter
import com.bryzek.apidoc.spec.v0.models.{Model, Service}

/**
  * For models w/ field named organization, ensure organization's position is:
  *   a. fourth (if first 3 fields are id, timestamp, type), to
  *      support journals
  *   b. second field (after id)
  *   c. first field (if no id)
  */
case object ModelsWithOrganizationField extends Linter with Helpers {

  override def validate(service: Service): Seq[String] = {
    service.models.flatMap(validateModel(_))
  }

  def validateModel(model: Model): Seq[String] = {
    val fieldNames = model.fields.map(_.name)
    val index = fieldNames.indexOf("organization")

    index < 0 match {
      case true => {
        Nil
      }
      case false => {
        val position = fieldNames.take(3) match {
          case "event_id" :: "organization" :: rest => 1
          case "id" :: "timestamp" :: "type" :: Nil => 3
          case "id" :: rest => 1
          case _ => 0
        }

        position == index match {
          case true => Nil
          case false => {
            Seq(error(model, s"Field[organization] must be in position[$position] and not[$index]"))
          }
        }
      }
    }
  }

}

Fix position of organization in event models


package doodle
package svg
package effect

import cats.effect.IO
import doodle.core.Transform
import doodle.effect._
import doodle.algebra.Picture
import java.io.File
import java.nio.file.Files
import scalatags.Text

object SvgWriter extends Writer[Algebra, Drawing, SvgFrame, Writer.Svg] {
  val algebra = doodle.svg.algebra.Algebra(Text)

  def write[A](file: File,
               description: SvgFrame,
               picture: Picture[Algebra,Drawing,A]): IO[A] = {
    // Frame is (currently) meaningless for writing
    val _ = description
    write(file, picture)
  }

  def write[A](file: File,
               picture: Picture[Algebra,Drawing,A]): IO[A] =
    for {
      drawing <- IO { picture(algebra) }
      (bb, rdr) = drawing.runA(List.empty).value
      (_, (txt, a)) = rdr.run(Transform.identity).value
      _ = Files.write(file.toPath, txt.render.getBytes())
    } yield a
}

package doodle
package svg
package effect

import cats.effect.IO
import doodle.core.Transform
import doodle.effect._
import doodle.algebra.Picture
import java.io.File
import java.nio.file.Files
import scalatags.Text

object SvgWriter extends Writer[Algebra, Drawing, SvgFrame, Writer.Svg] {
  import Text.implicits._
  import Text.{svgTags => svg}
  import Text.svgAttrs

  val algebra = doodle.svg.algebra.Algebra(Text)

  def write[A](file: File,
               description: SvgFrame,
               picture: Picture[Algebra,Drawing,A]): IO[A] = {
    // Frame is (currently) meaningless for writing
    val _ = description
    write(file, picture)
  }

  def write[A](file: File,
               picture: Picture[Algebra,Drawing,A]): IO[A] =
    for {
      drawing <- IO { picture(algebra) }
      (bb, rdr) = drawing.runA(List.empty).value
      (_, (tags, a)) = rdr.run(Transform.identity).value
      nodes = svg.svg(svgAttrs.width:=bb.width,
                      svgAttrs.height:=bb.height,
                      svgAttrs.viewBox:=s"${bb.left} ${bb.bottom} ${bb.width} ${bb.height}",
                      tags).render
      _ = Files.write(file.toPath, nodes.render.getBytes())
    } yield a
}

Fix SVG rendering on the JVM backend

Fix SVG rendering on the JVM backend

Corresponding fix for the JVM: gotta wrap a SVG tag around the whole thing.


package io.udash.testing

import io.udash._

class TestViewFactory[T <: TestState] extends ViewFactory[T] {
  val view = new TestView
  val presenter = new TestPresenter[T]
  var count = 0

  override def create(): (View, Presenter[T]) = {
    count += 1
    (view, presenter)
  }
}

class TestView extends ContainerView {
  import scalatags.JsDom.all._
  var lastChild: View = _
  var renderingCounter = 0
  var closed = false

  override def renderChild(view: Option[View]): Unit = {
    view.foreach(_.getTemplate)
    lastChild = view.orNull
  }

  override def getTemplate: Modifier = {
    renderingCounter += 1
    div().render
  }

  override def onClose(): Unit = {
    closed = true
  }
}

class TestFinalView extends View {
  import scalatags.JsDom.all._
  var renderingCounter = 0

  override def getTemplate: Modifier = {
    renderingCounter += 1
    div().render
  }
}

class TestPresenter[T <: TestState] extends Presenter[T] {
  var lastHandledState: T = _
  var closed = false

  override def handleState(state: T): Unit = lastHandledState = state
  override def onClose(): Unit = closed = true
}

package io.udash.testing

import io.udash._

class TestViewFactory[T <: TestState] extends ViewFactory[T] {
  val view = new TestView
  val presenter = new TestPresenter[T]
  var count = 0

  override def create(): (View, Presenter[T]) = {
    count += 1
    (view, presenter)
  }
}

class TestView extends ContainerView {
  import scalatags.JsDom.all._
  var lastChild: View = _
  var renderingCounter = 0
  var closed = false

  override def renderChild(view: Option[View]): Unit = {
    super.renderChild(view)
    lastChild = view.orNull
  }

  override def getTemplate: Modifier = {
    renderingCounter += 1
    div(
      toString,
      childViewContainer
    )
  }

  override def onClose(): Unit = {
    closed = true
  }
}

class TestFinalView extends View {
  import scalatags.JsDom.all._
  var renderingCounter = 0

  override def getTemplate: Modifier = {
    renderingCounter += 1
    span(toString)
  }
}

class TestPresenter[T <: TestState] extends Presenter[T] {
  var lastHandledState: T = _
  var closed = false

  override def handleState(state: T): Unit = lastHandledState = state
  override def onClose(): Unit = closed = true
}

Enable child rendering in tests

Enable child rendering in tests


package org.scalafmt.config.hocon

import scala.util.control.NonFatal

import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory

object Hocon2Class {
  private def config2map(config: Config): Map[String, Any] = {
    import scala.collection.JavaConverters._
    def loop(obj: Any): Any = obj match {
      case map: java.util.Map[_, _] =>
        map.asScala
          .map {
            case (key, value) => key -> loop(value)
          }
          .toMap
      case map: java.util.List[_] =>
        map.asScala.map(loop).toList
      case e => e
    }
    loop(config.root().unwrapped()).asInstanceOf[Map[String, Any]]
  }

  def gimmeConfig(
      str: String,
      path: Option[String]): metaconfig.Result[Map[String, Any]] = {
    try {
      val config = ConfigFactory.parseString(str)
      val extracted = path match {
        case Some(p) => config.getConfig(p)
        case _ => config
      }
      Right(config2map(extracted))
    } catch {
      case NonFatal(e) => Left(e)
    }
  }

  def gimmeClass[T](configStr: String,
                    reader: metaconfig.Reader[T],
                    path: Option[String]): metaconfig.Result[T] = {
    for {
      config <- gimmeConfig(configStr, path).right
      clz <- reader.read(config).right
    } yield clz
  }

}

package org.scalafmt.config.hocon

import scala.util.control.NonFatal

import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import com.typesafe.config.ConfigResolveOptions

object Hocon2Class {
  private def config2map(config: Config): Map[String, Any] = {
    import scala.collection.JavaConverters._
    def loop(obj: Any): Any = obj match {
      case map: java.util.Map[_, _] =>
        map.asScala
          .map {
            case (key, value) => key -> loop(value)
          }
          .toMap
      case map: java.util.List[_] =>
        map.asScala.map(loop).toList
      case e => e
    }
    loop(config.root().unwrapped()).asInstanceOf[Map[String, Any]]
  }

  def gimmeConfig(
      str: String,
      path: Option[String]): metaconfig.Result[Map[String, Any]] = {
    try {
      val config = ConfigFactory.parseString(str)
      val extracted = path match {
        case Some(p) => config.getConfig(p).resolve(ConfigResolveOptions.noSystem)
        case _ => config
      }
      Right(config2map(extracted))
    } catch {
      case NonFatal(e) => Left(e)
    }
  }

  def gimmeClass[T](configStr: String,
                    reader: metaconfig.Reader[T],
                    path: Option[String]): metaconfig.Result[T] = {
    for {
      config <- gimmeConfig(configStr, path).right
      clz <- reader.read(config).right
    } yield clz
  }

}

Resolve references in config file

Resolve references in config file

In HOCON one might define values using substitutions[1] which are references to
other parts of the configuration tree.

Those references need to be resolved before trying to query the configuration.

Usually substitutions could be resolved by looking at the system environment
variables, but that is explicitly disabled to begin with.

[1]: https://github.com/typesafehub/config/blob/master/HOCON.md#substitutions


import scala.collection.mutable

case class Foo[K, V]()(implicit conv: ImplicitConverter[V, Ordered[V]])
extends mutable.HashMap[K,V] {

  val a = this.toSeq.sortWith { case ((_, v1), (_, v2)) => v1 > v2 }

  val b = this.toSeq.sortWith(_._2 > _._2)
}

import scala.collection.mutable

case class Foo[K, V]()(implicit conv: Conversion[V, Ordered[V]])
extends mutable.HashMap[K,V] {

  val a = this.toSeq.sortWith { case ((_, v1), (_, v2)) => v1 > v2 }

  val b = this.toSeq.sortWith(_._2 > _._2)
}

Fix build: ImplicitConverter has been renamed Conversion


package controllers

import play.api.mvc._
import model.{Instance, Cluster}
import com.amazonaws.auth.BasicAWSCredentials
import lib.{AWSCost, AmazonConnection, Config}
import java.text.DecimalFormat
import java.io.File
import play.api.Configuration
import com.typesafe.config.ConfigFactory

object Application extends Controller {

  implicit lazy val amazonConnection = new AmazonConnection(Config.credentials)

  def index = Action {
    Ok(views.html.index(Cluster.findAll, AWSCost.totalSunkCost, new DecimalFormat("#,###.00")))
    //Ok(views.html.index(Cluster.findAll, 0, new DecimalFormat("#,###.00")))
  }

  def instance(id: String) = Action {
    Ok(views.html.instance(Instance.get(id)))
  }

  def es = Action {
    Ok(views.html.elasticsearch())
  }

  def fileConfig(filePath: String): Configuration = {
    val file = new File(filePath)
    if (!file.exists) throw new Error("Could not find %s" format (filePath))
    Configuration(ConfigFactory.parseFile(file))
  }

}

package controllers

import play.api.mvc._
import model.{Instance, Cluster}
import lib.{AWSCost, AmazonConnection, Config}
import java.text.DecimalFormat

object Application extends Controller {

  implicit lazy val amazonConnection = new AmazonConnection(Config.credentials)

  def index = Action {
    Ok(views.html.index(Cluster.findAll, AWSCost.totalSunkCost, new DecimalFormat("#,###.00")))
    //Ok(views.html.index(Cluster.findAll, 0, new DecimalFormat("#,###.00")))
  }

  def instance(id: String) = Action {
    Ok(views.html.instance(Instance.get(id)))
  }

  def es = Action {
    Ok(views.html.elasticsearch())
  }

}

Clean up application from config stuff

Clean up application from config stuff


resolvers += Resolver.sonatypeRepo("snapshots")

addSbtPlugin("com.github.gseitz"  % "sbt-release"              % "1.0.6")
addSbtPlugin("org.xerial.sbt"     % "sbt-sonatype"             % "2.0")
addSbtPlugin("com.jsuereth"       % "sbt-pgp"                  % "1.1.0")
addSbtPlugin("io.get-coursier"    % "sbt-coursier"             % "1.0.0")
addSbtPlugin("org.scoverage"      % "sbt-scoverage"            % "1.5.1")
addSbtPlugin("com.geirsson"       % "sbt-scalafmt"             % "1.4.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"              % "0.6.21")
addSbtPlugin("org.portable-scala" % "sbt-crossproject"         % "0.3.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.3.0")
addSbtPlugin("com.typesafe.sbt"   % "sbt-ghpages"              % "0.6.2")

addSbtPlugin("com.47deg" % "sbt-microsites" % "0.7.13")

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

resolvers += Resolver.sonatypeRepo("snapshots")

addSbtPlugin("com.github.gseitz"  % "sbt-release"              % "1.0.7")
addSbtPlugin("org.xerial.sbt"     % "sbt-sonatype"             % "2.0")
addSbtPlugin("com.jsuereth"       % "sbt-pgp"                  % "1.1.0")
addSbtPlugin("io.get-coursier"    % "sbt-coursier"             % "1.0.0")
addSbtPlugin("org.scoverage"      % "sbt-scoverage"            % "1.5.1")
addSbtPlugin("com.geirsson"       % "sbt-scalafmt"             % "1.4.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"              % "0.6.21")
addSbtPlugin("org.portable-scala" % "sbt-crossproject"         % "0.3.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.3.0")
addSbtPlugin("com.typesafe.sbt"   % "sbt-ghpages"              % "0.6.2")

addSbtPlugin("com.47deg" % "sbt-microsites" % "0.7.13")

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

Upgrade to sbt-release 1.0.7 for supporting sbt 1.1.x


latestVersion in ThisBuild := "0.6.2"
latestBinaryCompatibleVersion in ThisBuild := None
unreleasedModuleNames in ThisBuild := Set("ciris-cats")

latestVersion in ThisBuild := "0.7.0"
latestBinaryCompatibleVersion in ThisBuild := Some("0.7.0")
unreleasedModuleNames in ThisBuild := Set()

Set latest version to 0.7.0

Set latest version to 0.7.0


import scala.reflect.runtime.universe
import scala.reflect.runtime.universe._

class Test {

  def repo(): String = {
    val tag = implicitly[TypeTag[Array[Byte]]]
    val mirror = universe.runtimeMirror(Thread.currentThread().getContextClassLoader)
    tag.in(mirror).tpe.dealias.toString
  }
}

object Test extends Test {

  def main(args: Array[String]): Unit = {
    for (i <- 1 to 16) {
      val settings = new scala.tools.nsc.Settings
      settings.Xnojline.value = true
      settings.usejavacp.value = true
      val intp = new scala.tools.nsc.interpreter.IMain(settings)

      try {
        intp.quietRun("object C { val data = new Array[Byte](16 * 1024 * 1024) }")
        intp.quietRun("identity(C.data); Test.repo()")
      } finally {
        intp.close()
      }
    }
  }
}

import scala.reflect.runtime.universe
import scala.reflect.runtime.universe._
import scala.tools.nsc.interpreter._
import java.io._

class Test {

  def repo(): String = {
    val tag = implicitly[TypeTag[Array[Byte]]]
    val mirror = universe.runtimeMirror(Thread.currentThread().getContextClassLoader)
    tag.in(mirror).tpe.dealias.toString
  }
}

object Test extends Test {

  def main(args: Array[String]): Unit = {
    for (i <- 1 to 16) {
      val settings = new scala.tools.nsc.Settings
      settings.Xnojline.value = true
      settings.usejavacp.value = true

      val intp = new IMain(settings, new shell.ReplReporterImpl(settings, new PrintWriter(new StringWriter)))

      try {
        intp.quietRun("object C { val data = new Array[Byte](16 * 1024 * 1024) }")
        intp.quietRun("identity(C.data); Test.repo()")
      } finally {
        intp.close()
      }
    }
  }
}

Fix semantic merge error in type tag test


import sbt._

object Dependencies {
  val sparkVersion = "2.0.0"

  lazy val baseDependencies = Seq("org.scalatest" %% "scalatest" % "3.0.0" % "test")

  lazy val sparkDependencies = Seq("org.apache.spark" %% "spark-core" % sparkVersion,
    "org.apache.spark" %% "spark-sql" % sparkVersion,
    "org.apache.spark" %% "spark-mllib" % sparkVersion,
    "org.apache.spark" %% "spark-catalyst" % sparkVersion).map(_ % "provided")

  lazy val mleapCoreDependencies = baseDependencies.union(Seq("org.apache.spark" %% "spark-mllib-local" % sparkVersion))

  lazy val mleapRuntimeDependencies = baseDependencies

  lazy val mleapSerializationDependencies = baseDependencies

  lazy val mleapSparkDependencies = baseDependencies
    .union(sparkDependencies)

  lazy val bundleMlDependencies = baseDependencies.
    union(Seq("io.spray" %% "spray-json" % "1.3.2",
      "com.jsuereth" %% "scala-arm" % "1.4"))
}

import sbt._

object Dependencies {
  val sparkVersion = "2.0.0"

  lazy val baseDependencies = Seq("org.scalatest" %% "scalatest" % "3.0.0" % "test")

  lazy val sparkLocalDependencies = Seq("org.apache.spark" %% "spark-mllib-local" % sparkVersion % "optional")
  lazy val sparkDependencies = Seq("org.apache.spark" %% "spark-core" % sparkVersion,
    "org.apache.spark" %% "spark-sql" % sparkVersion,
    "org.apache.spark" %% "spark-mllib" % sparkVersion,
    "org.apache.spark" %% "spark-catalyst" % sparkVersion).map(_ % "provided").union(sparkLocalDependencies)

  lazy val mleapCoreDependencies = baseDependencies.union(sparkLocalDependencies)

  lazy val mleapRuntimeDependencies = baseDependencies.union(sparkLocalDependencies)

  lazy val mleapSparkDependencies = baseDependencies
    .union(sparkDependencies)

  lazy val bundleMlDependencies = baseDependencies.
    union(Seq("io.spray" %% "spray-json" % "1.3.2",
      "com.jsuereth" %% "scala-arm" % "1.4"))
}

Make MLlib-local optional dependency to not break fat jars.


import scala.io._
import scala.actors._
import Actor._

def pageSize(url: String) = Source.fromURL(url).mkString.length

def printPageSizes(urls: Iterable[String]) = {
    for(url <- urls) {
        println("Loading " + url + "...")
        val ps = pageSize(url)
        println(url + " -> " + ps)
    }
}

val urls = List("https://www.facebook.com", "https://www.twitter.com", "https://www.linkedin.com")

printPageSizes(urls)

import scala.io._
import scala.actors._
import Actor._

def pageSize(url: String) = Source.fromURL(url).mkString.length

def printPageSizes(urls: Iterable[String]) = {
    var caller = self

    for(url <- urls) {
        actor {
            println("Loading " + url + "...")
            caller ! (url,  pageSize(url))
        }
    }

    for(i <- 1 to urls.size) {
        receive {
            case (url, size) =>
                println(url + " -> " + size)
        }
    }
}

val urls = List("https://www.facebook.com", "https://www.twitter.com", "https://www.linkedin.com")

printPageSizes(urls)

Use actors in page sizer

Use actors in page sizer


package ccf.messaging

import ccf.operation.Operation

case class Message[T <: Operation]()
case class ConcurrentOperationMessage[T <: Operation](val op: T, val localMessage: Int, val expectedRemoteMessage: Int) extends Message[T]()
case class ChannelShutdown[T <: Operation](reason: String) extends Message[T]()

package ccf.messaging

import ccf.operation.Operation

case class Message[T <: Operation]()
case class ConcurrentOperationMessage[T <: Operation](val op: T, val localMessage: Int, val expectedRemoteMessage: Int) extends Message[T]()
case class ErrorMessage[T <: Operation](reason: String) extends Message[T]()
case class ChannelShutdown[T <: Operation](override val reason: String) extends ErrorMessage[T](reason)

Introduce a generic error message

Introduce a generic error message

In order to deliver custom error messages, we introduce a generic error
message which can be sent for various purposes. Also make the
ChannelShutdown extend from ErrorMessage.

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


package org.scalaide.ui.internal.preferences

import org.scalaide.ui.syntax.ScalaSyntaxClass.Category
import org.eclipse.jface.viewers._
import org.scalaide.ui.syntax.ScalaSyntaxClass

/** Content and label provider for the tree of syntax element in the syntax coloring
 *  preference pages.
 */
class SyntaxColoringTreeContentAndLabelProvider(categories: List[Category]) extends LabelProvider with ITreeContentProvider {

  def getElements(inputElement: AnyRef) = categories.toArray

  def getChildren(parentElement: AnyRef) = parentElement match {
    case Category(_, children) => children.toArray
    case _ => Array()
  }

  def getParent(element: AnyRef): Category = categories.find(_.children contains element).orNull

  def hasChildren(element: AnyRef) = getChildren(element).nonEmpty

  def inputChanged(viewer: Viewer, oldInput: AnyRef, newInput: AnyRef): Unit = {}

  override def getText(element: AnyRef) = element match {
    case Category(name, _) => name
    case ScalaSyntaxClass(displayName, _, _, _) => displayName
  }

  override def dispose() = ()
}

package org.scalaide.ui.internal.preferences

import org.scalaide.ui.syntax.ScalaSyntaxClass.Category
import org.eclipse.jface.viewers._
import org.scalaide.ui.syntax.ScalaSyntaxClass

/** Content and label provider for the tree of syntax element in the syntax coloring
 *  preference pages.
 */
class SyntaxColoringTreeContentAndLabelProvider(categories: List[Category]) extends LabelProvider with ITreeContentProvider {

  def getElements(inputElement: AnyRef) = categories.toArray

  def getChildren(parentElement: AnyRef) = parentElement match {
    case Category(_, children) => children.toArray
    case _ => Array()
  }

  def getParent(element: AnyRef): Category = categories.find(_.children contains element).orNull

  def hasChildren(element: AnyRef) = getChildren(element).nonEmpty

  override def inputChanged(viewer: Viewer, oldInput: AnyRef, newInput: AnyRef): Unit = {}

  override def getText(element: AnyRef) = element match {
    case Category(name, _) => name
    case ScalaSyntaxClass(displayName, _, _, _) => displayName
  }

  override def dispose() = ()
}

Fix compilation error because of missing override keyword


package com.socrata.http.client

import java.io.{InputStream, Closeable}
import java.nio.charset.StandardCharsets

import com.rojoma.simplearm.{SimpleArm, Managed}
import org.apache.http.entity.ContentType

trait HttpClient extends Closeable {
  type RawResponse = (ResponseInfo, InputStream)

  /**
   * Executes the request.
   *
   * @note Usually, you'll want to use `execute` instead.
   * @return an `InputStream` and the HTTP header info.
   */
  def executeRaw(req: SimpleHttpRequest): Managed[RawResponse]

  /**
   * Executes the request, returning an object which can be used to query the
   * response headers and decode the body.
   */
  def execute(req: SimpleHttpRequest): Managed[Response] =
    new SimpleArm[Response] {
      def flatMap[A](f: Response => A): A =
        for(rawResponse <- executeRaw(req)) yield {
          val cooked = new StandardResponse(rawResponse._1, rawResponse._2)
          f(cooked)
        }
    }
}

object HttpClient {
  val jsonContentTypeBase = "application/json"
  val jsonContentType = ContentType.create(jsonContentTypeBase, StandardCharsets.UTF_8)
  val formContentTypeBase = "application/x-www-form-urlencoded"
  val formContentType = ContentType.create(formContentTypeBase)
}

package com.socrata.http.client

import java.io.{InputStream, Closeable}
import java.nio.charset.StandardCharsets

import com.rojoma.simplearm.{SimpleArm, Managed}
import org.apache.http.entity.ContentType

trait HttpClient extends Closeable {
  type RawResponse = (ResponseInfo, InputStream)

  /**
   * Executes the request.
   *
   * @note Usually, you'll want to use `execute` instead.
   * @return an `InputStream` and the HTTP header info.
   */
  def executeRaw(req: SimpleHttpRequest): Managed[RawResponse]

  /**
   * Executes the request, returning an object which can be used to query the
   * response headers and decode the body.
   */
  def execute(req: SimpleHttpRequest): Managed[Response] =
    new SimpleArm[Response] {
      def flatMap[A](f: Response => A): A =
        for(rawResponse <- executeRaw(req)) yield {
          val cooked = new StandardResponse(rawResponse._1, rawResponse._2)
          f(cooked)
        }
    }
}

object HttpClient {
  val jsonContentTypeBase = "application/json"
  val jsonContentType = ContentType.create(jsonContentTypeBase, StandardCharsets.UTF_8)
  val formContentTypeBase = "application/x-www-form-urlencoded"
  val formContentType = ContentType.create(formContentTypeBase, StandardCharsets.UTF_8)
}

Set charset on form uploads to UTF-8

Set charset on form uploads to UTF-8


package org.ciroque.ccr.datastores

import com.mongodb.casbah.MongoClient
import org.scalatest.BeforeAndAfterAll

class MongoSettingsDataStoreTests
  extends SettingsDataStoreTests
  with BeforeAndAfterAll {

  val settings: DataStoreProperties = new DataStoreProperties("localhost", 27017, "test-ccr", "configurations", "", "")

  override implicit val settingsDataStore: SettingsDataStore = new MongoSettingsDataStore(settings)

  override def afterAll() = {
    MongoClient(settings.hostname, settings.port)(settings.databaseName)(settings.catalog).drop()
  }
}

package org.ciroque.ccr.datastores

import com.mongodb.casbah.MongoClient
import org.scalatest.BeforeAndAfterAll

class MongoSettingsDataStoreTests
  extends SettingsDataStoreTests
  with BeforeAndAfterAll {

  val settings: DataStoreProperties = new DataStoreProperties("localhost", 27017, "test-ccr", "configurations", "", "")

  override implicit val settingsDataStore: SettingsDataStore = new MongoSettingsDataStore(settings)

  override def beforeAll() = {
    MongoClient(settings.hostname, settings.port)(settings.databaseName)(settings.catalog).drop()
  }
}

Clean the collection BEFORE the tests. See if that fixes CI.


name := "24hCodeBot"

libraryDependencies += "org.specs2" %% "specs2" % "2.3.6" % "test"

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

Add deprecation check to sbt

Add deprecation check to sbt


name := """keepit"""

version := "0.1-SNAPSHOT"

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

scalaVersion := "2.11.1"

libraryDependencies ++= Seq(
//  javaJdbc,
//  javaEbean,
  cache,
  javaWs,
  "org.webjars" % "jquery" % "2.1.1",
  "org.webjars" % "bootstrap" % "3.2.0"
)

name := """keepit"""

version := "0.1-SNAPSHOT"

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

scalaVersion := "2.11.1"

libraryDependencies ++= Seq(
//  javaJdbc,
//  javaEbean,
  cache,
  javaWs,
  "org.webjars" %% "webjars-play" % "2.3.0",
  "org.webjars" % "jquery" % "2.1.1",
  "org.webjars" % "bootstrap" % "3.2.0"
)

Add dependency of webjars helper.

Add dependency of webjars helper.


enablePlugins(org.nlogo.build.NetLogoExtension)

netLogoExtName      := "palette"

netLogoClassManager := "PaletteExtension"

netLogoTarget :=
  org.nlogo.build.NetLogoExtension.directoryTarget(baseDirectory.value)

netLogoZipSources   := false

javaSource in Compile <<= baseDirectory(_ / "src")

javacOptions ++= Seq("-g", "-Xlint:deprecation", "-Xlint:all", "-Xlint:-serial", "-Xlint:-path",
  "-encoding", "us-ascii")

netLogoVersion := "6.0-M1"

enablePlugins(org.nlogo.build.NetLogoExtension)

netLogoExtName      := "palette"

netLogoClassManager := "PaletteExtension"

netLogoTarget :=
  org.nlogo.build.NetLogoExtension.directoryTarget(baseDirectory.value)

netLogoZipSources   := false

javaSource in Compile <<= baseDirectory(_ / "src")

javacOptions ++= Seq("-g", "-Xlint:deprecation", "-Xlint:all", "-Xlint:-serial", "-Xlint:-path",
  "-encoding", "us-ascii")

netLogoVersion := "6.0.0-M2"

Update NetLogo version to 6.0.0-M2

Update NetLogo version to 6.0.0-M2


name := "onion"

organization := "org.onion_lang"

version := "0.1-SNAPSHOT"

scalaVersion := "2.11.3"

testOptions in Test += Tests.Argument("-u", "target/scalatest-reports")

Revert "Remove testOptions in Test"

Revert "Remove testOptions in Test"

This reverts commit 4cf2f290631ce8496b1ebddf7c94f50486284152.