libraryDependencies += "org.scala-js" %% "scalajs-env-selenium" % "0.3.0"

addSbtPlugin("org.scala-js"      % "sbt-scalajs" % "0.6.29")
addSbtPlugin("com.jsuereth"      % "sbt-pgp"     % "1.1.2")
addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.12")

// addSbtPlugin("ch.epfl.scala" % "sbt-scalajs-bundler" % "0.10.0")

libraryDependencies += "org.scala-js" %% "scalajs-env-selenium" % "0.3.0"

addSbtPlugin("org.scala-js"      % "sbt-scalajs" % "0.6.31")
addSbtPlugin("com.jsuereth"      % "sbt-pgp"     % "1.1.2")
addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.12")

// addSbtPlugin("ch.epfl.scala" % "sbt-scalajs-bundler" % "0.10.0")

Update sbt-scalajs, scalajs-compiler to 0.6.31


package org.http4s.blaze.channel.nio2

import org.http4s.blaze.pipeline.HeadStage

import java.nio.ByteBuffer
import java.nio.channels.{CompletionHandler, AsynchronousSocketChannel, AsynchronousChannelGroup}
import java.net.SocketAddress

import scala.concurrent.{Future, Promise}

/** A factory for opening TCP connections to remote sockets
  *
  * Provides a way to easily make TCP connections which can then serve as the Head for a pipeline
  *
  * @param bufferSize default buffer size to perform reads
  * @param group the [[java.nio.channels.AsynchronousChannelGroup]] which will manage the connection
  */
class ClientChannelFactory(bufferSize: Int = 8*1024, group: AsynchronousChannelGroup = null) {

  def connect(remoteAddress: SocketAddress, bufferSize: Int = bufferSize): Future[HeadStage[ByteBuffer]] = {
    val p = Promise[HeadStage[ByteBuffer]]

    val ch = AsynchronousSocketChannel.open(group)
    ch.connect(remoteAddress, null: Null, new CompletionHandler[Void, Null] {
      def failed(exc: Throwable, attachment: Null) {
        p.failure(exc)
      }

      def completed(result: Void, attachment: Null) {
        p.success(new ByteBufferHead(ch, bufferSize = bufferSize))
      }
    })

    p.future
  }
}

package org.http4s.blaze.channel.nio2

import org.http4s.blaze.pipeline.HeadStage

import java.nio.ByteBuffer
import java.nio.channels.{CompletionHandler, AsynchronousSocketChannel, AsynchronousChannelGroup}
import java.net.SocketAddress

import scala.concurrent.{Future, Promise}
import scala.util.control.NonFatal

/** A factory for opening TCP connections to remote sockets
  *
  * Provides a way to easily make TCP connections which can then serve as the Head for a pipeline
  *
  * @param bufferSize default buffer size to perform reads
  * @param group the [[java.nio.channels.AsynchronousChannelGroup]] which will manage the connection
  */
class ClientChannelFactory(bufferSize: Int = 8*1024, group: AsynchronousChannelGroup = null) {

  def connect(remoteAddress: SocketAddress, bufferSize: Int = bufferSize): Future[HeadStage[ByteBuffer]] = {
    val p = Promise[HeadStage[ByteBuffer]]

    try {
      val ch = AsynchronousSocketChannel.open(group)
      ch.connect(remoteAddress, null: Null, new CompletionHandler[Void, Null] {
        def failed(exc: Throwable, attachment: Null) {
          p.failure(exc)
        }

        def completed(result: Void, attachment: Null) {
          p.success(new ByteBufferHead(ch, bufferSize = bufferSize))
        }
      })
    }
    catch {case NonFatal(t) => p.tryFailure(t) }

    p.future
  }
}

Handle the error associated with opening a connection

Nonfatal exceptions are caught and used to complete the Future with a
failure.


package uk.ac.wellcome.platform.idminter.utils

import scala.util.Random

object Identifiable {
  private val identifierLength = 8
  private val forbiddenLetters = List('o', 'i', 'l', '1')
  private val letterRange = ('1' to '9') ++ ('a' to 'z')
  private val letterSet = letterRange.filterNot(forbiddenLetters.contains)

  def generate =
    (1 to identifierLength)
      .map(_ => letterSet(Random.nextInt(letterSet.length)))
      .mkString
}

package uk.ac.wellcome.platform.idminter.utils

import scala.util.Random

object Identifiable {
  private val identifierLength = 8

  private val forbiddenLetters = List('o', 'i', 'l', '1')
  private val numberRange = ('1' to '9')
  private val letterRange = ('a' to 'z')

  private val characterSet = numberRange ++ letterRange
  private val allowedCharacterSet = (characterSet).filterNot(forbiddenLetters.contains)
  private val firstCharacterSet = allowedCharacterSet.filterNot(numberRange.contains)

  def generate = {
    (1 to identifierLength)
      .map(x => x match {
        // In certain contexts, IDs are used as a string.  This can cause
        // problems if the first character is a digit, so we have a rule
        // that the first character must be a letter.
        case 1 => firstCharacterSet(Random.nextInt(firstCharacterSet.length))
        case _ => allowedCharacterSet(Random.nextInt(allowedCharacterSet.length))
      })
      .mkString
  }
}

Add a rule that canonical identifiers start with a letter


import sbt._
import sbt.Keys._

object Settings {

  private lazy val build = Seq(
    scalaVersion := "2.11.7",

    autoCompilerPlugins := true,
    addCompilerPlugin("com.github.ghik" % "silencer-plugin" % "0.3"),

    scalacOptions ++= commonScalacOptions,
    organization := "com.github.alexandrnikitin"
  )

  lazy val root = build ++ Testing.settings ++ Publishing.noPublishSettings
  lazy val bloomfilter = build ++ Testing.settings ++ Dependencies.bloomfilter ++ Publishing.settings
  lazy val sandbox = build ++ Testing.settings ++ Dependencies.sandbox
  lazy val tests = build ++ Testing.settings ++ Dependencies.tests
  lazy val benchmark = build ++ Testing.settings ++ Dependencies.benchmark

  lazy val commonScalacOptions = Seq(
    "-deprecation",
    "-encoding", "UTF-8",
    "-feature",
    "-unchecked",
    "-Xfatal-warnings",
    "-Xlint",
    "-Ywarn-unused",
    "-Ywarn-unused-import",
    "-Ywarn-dead-code",
    "-Ywarn-numeric-widen",
    "-Ywarn-value-discard"
  )

}

import sbt._
import sbt.Keys._

object Settings {

  private lazy val build = Seq(
    scalaVersion := "2.11.7",

    autoCompilerPlugins := true,
    addCompilerPlugin("com.github.ghik" % "silencer-plugin" % "0.3"),

    scalacOptions ++= ScalacSettings.base,
    organization := "com.github.alexandrnikitin"
  )

  lazy val root = build ++ Testing.settings ++ Publishing.noPublishSettings
  lazy val bloomfilter = build ++ Testing.settings ++ Dependencies.bloomfilter ++ Publishing.settings ++ (scalacOptions ++= ScalacSettings.strict)
  lazy val sandbox = build ++ Testing.settings ++ Dependencies.sandbox
  lazy val tests = build ++ Testing.settings ++ Dependencies.tests
  lazy val benchmark = build ++ Testing.settings ++ Dependencies.benchmark

  object ScalacSettings {
    val base = Seq(
      "-deprecation",
      "-encoding", "UTF-8",
      "-feature",
      "-unchecked",
      "-optimise"
    )

    val strict = Seq(
      "-Xfatal-warnings",
      "-Xlint",
      "-Ywarn-unused",
      "-Ywarn-unused-import",
      "-Ywarn-dead-code",
      "-Ywarn-numeric-widen",
      "-Ywarn-value-discard"
    )
  }

}

Divide scalac options into base and strict


package defend.game

import defend._
import defend.model._

import scala.util.Random

class TestWaveGenerator(quietPeriod: Long = 20000) extends WaveGenerator {

  val waveWidth = 4
  val maxSpeed = 100
  var lastWaveGeneratedTs = 0l

  override def nextWave(started: Long, currentTime: Long, landScape: LandScape, cities: List[City], defence: List[DefenceTower]): Option[Wave] = {
    {
      if (currentTime - lastWaveGeneratedTs > quietPeriod) {
        lastWaveGeneratedTs = currentTime
        val spaceBetween = 10 + Random.nextInt(10)
        val start = Position(Random.nextInt(landScape.width - spaceBetween * waveWidth), landScape.height)
        val end = start.copy(y = landScape.groundLevel)

        val baseSpeed: Double = 10 + Random.nextInt(10)
        val moveVector: MoveVector = calculateDirection(start, end).copy(speed = baseSpeed)
        val weapons = (0 until waveWidth).map {
          i =>
            val missile: AlienWeapon = AlienMissile(1, 16 + Random.nextInt(16))
            val explodingVelocity = None
            val weaponInAction = WeaponInAction(missile, start.copy(x = start.x + i * spaceBetween), moveVector, explodingVelocity)
            weaponInAction
        }

        Some(Wave("A", weapons.toList))
      } else {
        None
      }
    }

  }
}

package defend.game

import defend._
import defend.model._

import scala.util.Random

class TestWaveGenerator(quietPeriod: Long = 20000) extends WaveGenerator {

  val waveWidth = 4
  val maxSpeed = 100
  var lastWaveGeneratedTs = 0l

  override def nextWave(started: Long, currentTime: Long, landScape: LandScape, cities: List[City], defence: List[DefenceTower]): Option[Wave] = {
    {
      if (currentTime - lastWaveGeneratedTs > quietPeriod) {
        lastWaveGeneratedTs = currentTime
        val spaceBetween = 10 + Random.nextInt(10)
        val start = Position(Random.nextInt(landScape.width - spaceBetween * waveWidth), landScape.height)
        val end = start.copy(y = landScape.groundLevel)

        val baseSpeed: Double = 30 + Random.nextInt(30)
        val moveVector: MoveVector = calculateDirection(start, end).copy(speed = baseSpeed)
        val weapons = (0 until waveWidth).map {
          i =>
            val missile: AlienWeapon = AlienMissile(1, 16 + Random.nextInt(16))
            val explodingVelocity = None
            val weaponInAction = WeaponInAction(missile, start.copy(x = start.x + i * spaceBetween), moveVector, explodingVelocity)
            weaponInAction
        }

        Some(Wave("A", weapons.toList))
      } else {
        None
      }
    }

  }
}

Improve speed in test enemy generator

Improve speed in test enemy generator


package jp.ijufumi.openreports.controller.settings
import jp.ijufumi.openreports.controller.common.ApplicationController
import jp.ijufumi.openreports.service.SettingMemberService

class MemberSettingsController extends ApplicationController {
  val path = rootPath + "/member"
  val viewPath = rootPath + "/member"

  override val activeMenu = "settings/member"
  override val requiredMemberInfo = true

  def index = {
    val members = new SettingMemberService().getMembers()
    set("members", members)
    render(viewPath + "/index")
  }
}

package jp.ijufumi.openreports.controller.settings
import jp.ijufumi.openreports.controller.common.ApplicationController
import jp.ijufumi.openreports.service.SettingMemberService

class MemberSettingsController extends ApplicationController {
  val path = rootPath + "/member"
  val viewPath = rootPath + "/member"

  override val activeMenu = "settings/member"
  override val requiredMemberInfo = true

  def index = {
    val members = new SettingMemberService().getMembers()
    set("members", members)
    render(viewPath + "/index")
  }

  def form = {
    render(viewPath + "/form")
  }

  def register = {
    render(viewPath + "/register-complete")
  }

  def edit() = {
    render(viewPath + "/edit")
  }

  def update() = {
    render(viewPath + "/update-complete")
  }
}

Create managing functions of member.

[WIP] Create managing functions of member.


package play.core.server.servlet25

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import play.core.server.servlet.Play2GenericServletRequestHandler
import play.core.server.servlet.RichHttpServletRequest
import play.core.server.servlet.RichHttpServletResponse
import java.util.concurrent.atomic.AtomicBoolean

class Play2Servlet25RequestHandler(servletRequest: HttpServletRequest, servletResponse: HttpServletResponse)
  extends Play2GenericServletRequestHandler(servletRequest, Option(servletResponse))
  with Helpers {

  val lock = new AtomicBoolean(false);

  protected override def onFinishService() = {
    lock.synchronized {
      if (!lock.get) {
        lock.wait(Play2Servlet.syncTimeout)
      }
    }
  }

  protected override def onHttpResponseComplete() = {
    lock.synchronized {
      lock.set(true)
      lock.notify()
    }
  }

  protected override def getHttpRequest(): RichHttpServletRequest = {
    new RichHttpServletRequest {
      def getRichInputStream(): Option[java.io.InputStream] = {
        Option(servletRequest.getInputStream)
      }
    }
  }

  protected override def getHttpResponse(): RichHttpServletResponse = {
    new RichHttpServletResponse {
      def getRichOutputStream: Option[java.io.OutputStream] = {
        Option(servletResponse.getOutputStream)
      }

      def getHttpServletResponse: Option[HttpServletResponse] = {
        Option(servletResponse)
      }
    }
  }

}

package play.core.server.servlet25

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import play.core.server.servlet.Play2GenericServletRequestHandler
import play.core.server.servlet.RichHttpServletRequest
import play.core.server.servlet.RichHttpServletResponse
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.TimeUnit

class Play2Servlet25RequestHandler(servletRequest: HttpServletRequest, servletResponse: HttpServletResponse)
  extends Play2GenericServletRequestHandler(servletRequest, Option(servletResponse))
  with Helpers {

  val queue = new ArrayBlockingQueue[Boolean](1)

  protected override def onFinishService() = {
    queue.poll(Play2Servlet.syncTimeout, TimeUnit.MILLISECONDS)
  }

  protected override def onHttpResponseComplete() = {
    queue.put(true)
  }

  protected override def getHttpRequest(): RichHttpServletRequest = {
    new RichHttpServletRequest {
      def getRichInputStream(): Option[java.io.InputStream] = {
        Option(servletRequest.getInputStream)
      }
    }
  }

  protected override def getHttpResponse(): RichHttpServletResponse = {
    new RichHttpServletResponse {
      def getRichOutputStream: Option[java.io.OutputStream] = {
        Option(servletResponse.getOutputStream)
      }

      def getHttpServletResponse: Option[HttpServletResponse] = {
        Option(servletResponse)
      }
    }
  }

}

Fix synchronization to use BlockingQueue instead of wait/notify. All dead locking will be solved by this fix.


class Foo[T <: U, U <: T] // error: cycle

class Bar[T >: T] // error: cycle

class A {
  val x: T = ???
  type T <: x.type // error: cycle
}

class B {
  type T <: x.type // error: cycle
  final val x: T = ???
}

class C {
  final val x: D#T = ???
  class D {
    type T <: x.type // error: cycle
    val z: x.type = ???
  }
}

class E {
  class F {
    type T <: x.type // error: not stable
    val z: x.type = ??? // error: not stable
  }
  lazy val x: F#T = ???
}

class T1 {
  type X = (U, U) // error: cycle
  type U = X & Int
}
class T2 {
  type X = (U, U) // error: cycle
  type U = X | Int
}
object T12 {
  ??? : (T1 {})#U // error: conflicting bounds
  ??? : (T2 {})#U // error: conflicting bounds
}

class Foo[T <: U, U <: T] // error: illegal cyclic reference: upper bound U of type T refers back to the type itself

class Bar[T >: T] // error: illegal cyclic reference: lower bound T of type T refers back to the type itself

class A {
  val x: T = ???
  type T <: x.type // error: cyclic reference involving value x
}

class B {
  type T <: x.type // error: illegal cyclic reference: upper bound B.this.T(B.this.x) of type T refers back to the type itself
  val x: T = ???
}

class C {
  final val x: D#T = ???
  class D {
    type T <: x.type // error: cyclic reference involving value x
    val z: x.type = ???
  }
}

class E {
  class F {
    type T <: x.type // error: not stable
    val z: x.type = ??? // error: not stable
  }
  lazy val x: F#T = ???
}

class T1 {
  type X = (U, U) // error: cycle
  type U = X & Int
}
class T2 {
  type X = (U, U) // error: cycle
  type U = X | Int
}
object T12 {
  ??? : (T1 {})#U // error: conflicting bounds
  ??? : (T2 {})#U // error: conflicting bounds
}

Annotate test with // error indications

Annotate test with // error indications

We had same fleyness in number of errors of cycle.scala
which prompted this.


import sbt._, Keys._

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

  val specs2Dep = Def.setting {
    "org.specs2" %% "specs2-core" % "4.13.1" cross CrossVersion.for3Use2_13
  }

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

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

  val commonsCodecVersion = "1.15"
  val scalaXmlVersion = "2.0.1"
  val commonsIoVersion = "2.11.0"
  val commonsFileUploadVersion = "1.4"
  val jettyVersion = "11.0.7"
  val nettyVersion = "4.1.70.Final"
  val scalatestVersion = "3.2.10"
  val scalatestScalacheckVersion = s"${scalatestVersion}.0"
  val json4sVersion = "4.0.3"
  val asyncHttpClientVersion = "1.8.17"
  val javaxActivationVersion = "1.1.1"
}

import sbt._, Keys._

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

  val specs2Dep = Def.setting {
    "org.specs2" %% "specs2-core" % "4.13.1" cross CrossVersion.for3Use2_13
  }

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

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

  val commonsCodecVersion = "1.15"
  val scalaXmlVersion = "2.0.1"
  val commonsIoVersion = "2.11.0"
  val commonsFileUploadVersion = "1.4"
  val jettyVersion = "11.0.7"
  val nettyVersion = "4.1.71.Final"
  val scalatestVersion = "3.2.10"
  val scalatestScalacheckVersion = s"${scalatestVersion}.0"
  val json4sVersion = "4.0.3"
  val asyncHttpClientVersion = "1.8.17"
  val javaxActivationVersion = "1.1.1"
}

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


package k2b6s9j.boatcraft.test.api.registry

import org.junit.runner.RunWith
import org.scalatest._
import org.scalatest.junit.JUnitRunner

import k2b6s9j.boatcraft.api.registry.ModifierRegistry
import k2b6s9j.boatcraft.test.api.traits.examples._
import net.minecraft.init.Blocks
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import scala.collection.JavaConversions._

@RunWith(classOf[JUnitRunner])
class SingleModifierRegistryTest extends FlatSpec with Matchers with BeforeAndAfter
{
	before
	{
		ModifierRegistry addModifier ExampleModifier
	}

	"A Modifier" should "be added to the registered Modifiers map." in
	{
		ModifierRegistry.modifiers.toMap should contain("test", ExampleModifier)
	}

	it should "be returned when searched by name." in
	{
		ModifierRegistry getModifier "test" shouldBe ExampleModifier
	}

	it should "be returned when searched by ItemStack." in
	{
		val stack = new ItemStack(Blocks.bedrock)
		stack.stackTagCompound = new NBTTagCompound
		stack.stackTagCompound setString ("modifier", "test")
		ModifierRegistry getModifier stack shouldBe ExampleModifier
	}

}

package k2b6s9j.boatcraft.test.api.registry

import org.junit.runner.RunWith
import org.scalatest._
import org.scalatest.junit.JUnitRunner

import k2b6s9j.boatcraft.api.registry.ModifierRegistry
import k2b6s9j.boatcraft.test.api.traits.examples._
import net.minecraft.init.Blocks
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import scala.collection.JavaConversions._
import k2b6s9j.boatcraft.core.materials.Empty

@RunWith(classOf[JUnitRunner])
class SingleModifierRegistryTest extends FlatSpec with Matchers with BeforeAndAfter
{
	before
	{
		ModifierRegistry addModifier ExampleModifier
	}

	"A Modifier" should "be added to the registered Modifiers map." in
	{
		ModifierRegistry.modifiers.toMap should contain("test", ExampleModifier)
	}

	it should "be returned when searched by name." in
	{
		ModifierRegistry getModifier "test" shouldBe ExampleModifier
	}

	it should "be returned when searched by ItemStack." in
	{
		val stack = new ItemStack(Blocks.bedrock)
		stack.stackTagCompound = new NBTTagCompound
		stack.stackTagCompound setString ("modifier", "test")
		ModifierRegistry getModifier stack shouldBe ExampleModifier
	}

  it should "fallback to an Empty modifier if no modifier is defined." in {
    val stack = new ItemStack(Blocks.bedrock)
    ModifierRegistry getModifier stack shouldBe Empty
  }

}

Add test for fallback modifier.

Add test for fallback modifier.


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

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

trait StdNames extends tiny.names.StdNames {
  val OBJECT_TYPE_NAME = Name("Object")
  val NULL_NAME        = Name("null")
}

object StdNames extends StdNames

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

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

trait StdNames extends tiny.names.StdNames {
  val JAVA_PACKAGE_NAME = Name("java")
  val LANG_PACKAGE_NAME = Name("lang")
  val OBJECT_TYPE_NAME  = Name("Object")
  val NULL_NAME         = Name("null")
}

object StdNames extends StdNames

Add information for java & java.lang packages


package ophir.search

import ophir.model.Def
import ophir.db.DefRepo
import ophir.parser.SigParser

object Search {

  type Result = Either[String, Iterator[Def]]

  private val mixedRegex = """^([^\:]+)\:(.+)$""".r

  def find(query: String): Result = query match {
    case mixedRegex(text, tpe) => MixedEngine find (text, tpe)
    case tpe if tpe contains "=>" => TypeEngine find tpe
    case text => TextEngine find text
  }

  object TextEngine {

    def find(text: String): Result =
      tokenize(text).right map DefRepo.findByTokens

    def tokenize(text: String): Either[String, List[String]] = Def nameToTokens text match {
      case Nil => Left("Empty text")
      case tokens => Right(tokens)
    }
  }

  object TypeEngine {

    def find(tpe: String): Result =
      normalize(tpe).right map DefRepo.findBySig

    def normalize(tpe: String): Either[String, String] =
      SigParser(tpe).right map (_.normalize.toString)
  }

  object MixedEngine {

    def find(text: String, tpe: String): Result = for {
      tokens <- (TextEngine tokenize text).right
      normalized <- (TypeEngine normalize tpe).right
    } yield DefRepo.findByTokensAndSig(tokens, normalized)
  }
}

package ophir.search

import ophir.model.Def
import ophir.db.DefRepo
import ophir.parser.SigParser

object Search {

  type Result = Either[String, Iterator[Def]]

  private val mixedRegex = """^([^\:]*)\:(.+)$""".r

  def find(query: String): Result = query match {
    case mixedRegex("", tpe) => TypeEngine find tpe
    case mixedRegex(text, tpe) => MixedEngine find (text, tpe)
    case tpe if tpe contains "=>" => TypeEngine find tpe
    case text => TextEngine find text
  }

  object TextEngine {

    def find(text: String): Result =
      tokenize(text).right map DefRepo.findByTokens

    def tokenize(text: String): Either[String, List[String]] = Def nameToTokens text match {
      case Nil => Left("Empty text")
      case tokens => Right(tokens)
    }
  }

  object TypeEngine {

    def find(tpe: String): Result =
      normalize(tpe).right map DefRepo.findBySig

    def normalize(tpe: String): Either[String, String] =
      SigParser(tpe).right map (_.normalize.toString)
  }

  object MixedEngine {

    def find(text: String, tpe: String): Result = for {
      tokens <- (TextEngine tokenize text).right
      normalized <- (TypeEngine normalize tpe).right
    } yield DefRepo.findByTokensAndSig(tokens, normalized)
  }
}

Fix searches starting with ":"

Fix searches starting with ":"


package org.http4s.client.blaze

import scalaz.concurrent.Task

import org.http4s._

import org.specs2.mutable.After

// TODO: this should have a more comprehensive test suite
class ExternalBlazeHttp1ClientSpec extends Http4sSpec {

  private val simpleClient = SimpleHttp1Client()

  "Blaze Simple Http1 Client" should {
    "Make simple https requests" in {
      val resp = simpleClient.getAs[String](uri("https://github.com/")).run
      resp.length mustNotEqual 0
    }
  }

  step {
    simpleClient.shutdown.run
  }

  private val pooledClient = PooledHttp1Client()

  "RecyclingHttp1Client" should {
    def fetchBody = pooledClient.toService(_.as[String]).local { uri: Uri => Request(uri = uri) }

    "Make simple https requests" in {
      val resp = fetchBody.run(uri("https://github.com/")).run
      resp.length mustNotEqual 0
    }

    "Repeat a simple https request" in {
      val f = (0 until 10).map(_ => Task.fork {
        val resp = fetchBody.run(uri("https://github.com/"))
        resp.map(_.length)
      })

      foreach(Task.gatherUnordered(f).run) { length =>
        length mustNotEqual 0
      }
    }
  }

  step {
    pooledClient.shutdown.run
  }
}

package org.http4s.client.blaze

import scalaz.concurrent.Task

import org.http4s._

import org.specs2.mutable.After

// TODO: this should have a more comprehensive test suite
class ExternalBlazeHttp1ClientSpec extends Http4sSpec {

  private val simpleClient = SimpleHttp1Client()

  "Blaze Simple Http1 Client" should {
    "Make simple https requests" in {
      val resp = simpleClient.expect[String](uri("https://github.com/")).run
      resp.length mustNotEqual 0
    }
  }

  step {
    simpleClient.shutdown.run
  }

  private val pooledClient = PooledHttp1Client()

  "RecyclingHttp1Client" should {
    def fetchBody = pooledClient.toService(_.as[String]).local { uri: Uri => Request(uri = uri) }

    "Make simple https requests" in {
      val resp = fetchBody.run(uri("https://github.com/")).run
      resp.length mustNotEqual 0
    }

    "Repeat a simple https request" in {
      val f = (0 until 10).map(_ => Task.fork {
        val resp = fetchBody.run(uri("https://github.com/"))
        resp.map(_.length)
      })

      foreach(Task.gatherUnordered(f).run) { length =>
        length mustNotEqual 0
      }
    }
  }

  step {
    pooledClient.shutdown.run
  }
}

Clean up deprecated `getAs` calls

Clean up deprecated `getAs` calls


/* URLs */
//val urlBase = "http://192.168.10.53:8080/excilys-bank-web"
val urlBase = "http://localhost:8080/excilys-bank-web"
val urlLoginGet = urlBase + "/public/login.html"
val urlLoginPost = urlBase + "/login"
val urlHome = urlBase + "/private/bank/accounts.html"
val urlLogout = urlBase + "/logout"

/* Feeder */
val usersInfos = new TSVFeeder("bank2", List("username", "password", "acc1", "acc2", "acc3", "acc4"))

/* Scenarios */
include("users")

/* Configuration */
val scnConf = configureScenario(scn) withFeeder usersInfos withUsersNumber 1200 withRampOf 300

/* Simulation */
runSimulations(scnConf)

/* URLs */
//val urlBase = "http://192.168.10.53:8080/excilys-bank-web"
val urlBase = "http://localhost:8080/excilys-bank-web"
val urlLoginGet = urlBase + "/public/login.html"
val urlLoginPost = urlBase + "/login"
val urlHome = urlBase + "/private/bank/accounts.html"
val urlLogout = urlBase + "/logout"

/* Feeder */
val usersInfos = new TSVFeeder("bank2", List("username", "password", "acc1", "acc2", "acc3", "acc4"))

/* Scenarios */
include("users")

/* Configuration */
val scnConf = configureScenarioscn feederusers usersNumber 1200 ramp 300

/* Simulation */
runSimulations(scnConf)

Fix according to new DSL format

Fix according to new DSL format


package ammonite.shell

import ammonite.repl.ReplAPI

/**
 * Created by haoyi on 9/1/15.
 */
object Configure {
  def apply(repl: ReplAPI, wd: => ammonite.ops.Path) = {
    repl.frontEnd() = ammonite.repl.AmmoniteFrontEnd(
      ammonite.shell.PathComplete.pathCompleteFilter(wd, repl.colors())
    )

    repl.prompt.bind(
      sys.props("user.name") +
      "-" +
      wd.segments.lastOption.getOrElse("") +
      "@ "
    )
  }
}

package ammonite.shell

import ammonite.repl.ReplAPI

/**
 * Created by haoyi on 9/1/15.
 */
object Configure {
  def apply(repl: ReplAPI, wd: => ammonite.ops.Path) = {
    if (scala.util.Properties.isWin) {
      repl.frontEnd() = ammonite.repl.FrontEnd.JLineWindows
      repl.colors() = ammonite.util.Colors.BlackWhite
    } else {
      repl.frontEnd() = ammonite.repl.AmmoniteFrontEnd(
        ammonite.shell.PathComplete.pathCompleteFilter(wd, repl.colors())
      )
    }

    repl.prompt.bind(
      sys.props("user.name") +
      "-" +
      wd.segments.lastOption.getOrElse("") +
      "@ "
    )
  }
}

Set JLineFrontEnd and Colors.BlackWhite for Windows


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

package org.openmole.ide.misc.widget

import java.awt.Cursor
import scala.swing.Action
import scala.swing.Label
import scala.swing.event.MousePressed

class LinkLabel(textLink: String,
                var action: Action,
                val textSize: Int = 4,
                color: String = "#ffffff") extends Label {
  cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
  link(textLink)

  listenTo(this.mouse.clicks)
  reactions += {
    case e: MousePressed ⇒ action.apply
  }

  def link(t: String) = text = "" + t + ""
}

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

package org.openmole.ide.misc.widget

import java.awt.Cursor
import scala.swing.Action
import scala.swing.Label
import scala.swing.event.MousePressed

class LinkLabel(textLink: String,
                var action: Action,
                val textSize: Int = 4,
                color: String = "#ffffff",
                bold: Boolean = false) extends Label {
  cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
  link(textLink)

  listenTo(this.mouse.clicks)
  reactions += {
    case e: MousePressed ⇒ action.apply
  }

  def link(t: String) = text = "" +
    { if (bold) "" else "" } +
    "" +
    t +
    "" +
    { if (bold) "" else "" } +
    ""

}

Add Bold Option for link labels

Add Bold Option for link labels


package uk.ac.wellcome.finatra.storage

import com.google.inject.Provides
import com.twitter.inject.TwitterModule
import javax.inject.Singleton
import uk.ac.wellcome.storage.dynamo.DynamoConfig
import uk.ac.wellcome.storage.s3.S3Config
import uk.ac.wellcome.storage.vhs.VHSConfig

object VHSConfigModule extends TwitterModule {
  private val tableName = flag[String](
    "aws.vhs.dynamo.tableName",
    "Name of the DynamoDB table holding the VHS index")

  private val bucketName = flag[String](
    "aws.vhs.s3.bucketName",
    "Name of the S3 bucket holding VHS objects")

  private val globalS3Prefix = flag[String](
    name = "aws.vhs.s3.globalPrefix",
    help = "A string prepended to all objects in the VHS"
  )

  @Singleton
  @Provides
  def providesVHSConfig(): VHSConfig = {
    val dynamoConfig = DynamoConfig(table = tableName(), index = None)
    val s3Config = S3Config(bucketName = bucketName())
    VHSConfig(
      dynamoConfig = dynamoConfig,
      s3Config = s3Config,
      globalS3Prefix = globalS3Prefix()
    )
  }
}

package uk.ac.wellcome.finatra.storage

import com.google.inject.Provides
import com.twitter.inject.TwitterModule
import javax.inject.Singleton
import uk.ac.wellcome.storage.dynamo.DynamoConfig
import uk.ac.wellcome.storage.s3.S3Config
import uk.ac.wellcome.storage.vhs.VHSConfig

object VHSConfigModule extends TwitterModule {
  private val tableName = flag[String](
    "aws.vhs.dynamo.tableName",
    "Name of the DynamoDB table holding the VHS index")

  private val bucketName = flag[String](
    "aws.vhs.s3.bucketName",
    "Name of the S3 bucket holding VHS objects")

  private val globalS3Prefix = flag[String](
    name = "aws.vhs.s3.globalPrefix",
    help = "A string prepended to all objects in the VHS"
  )

  @Singleton
  @Provides
  def providesVHSConfig(): VHSConfig = {
    val dynamoConfig = DynamoConfig(table = tableName())
    val s3Config = S3Config(bucketName = bucketName())
    VHSConfig(
      dynamoConfig = dynamoConfig,
      s3Config = s3Config,
      globalS3Prefix = globalS3Prefix()
    )
  }
}

Fix one more instance of the DynamoConfig constructor


package dotty.tools.languageserver

import org.junit.Test

import dotty.tools.dotc.reporting.diagnostic.ErrorMessageID._
import dotty.tools.languageserver.util.Code._
import org.eclipse.lsp4j.DiagnosticSeverity._

class DiagnosticsTest {
  @Test def diagnosticWrongType: Unit =
    code"""object Test {
          |  val x: Int = $m1"foo"$m2
          |}""".withSource
      .diagnostics(m1,
        (m1 to m2, """Found:    String("foo")
                     |Required: Int""".stripMargin, Error, Some(TypeMismatchID))
      )

  @Test def diagnosticMissingLambdaBody: Unit =
    code"""object Test {
          |  Nil.map(x => x).filter(x$m1 =>$m2)$m3
          |}""".withSource
      .diagnostics(m1,
        (m2 to m2, "expression expected", Error, Some(IllegalStartSimpleExprID)),
        (m1 to m1, """Found:    Null
                     |Required: Boolean""".stripMargin, Error, Some(TypeMismatchID))
      )

  @Test def diagnosticPureExpression: Unit =
    code"""object Test {
          |  ${m1}1$m2
          |}""".withSource
     .diagnostics(m1,
       (m1 to m2,
        "A pure expression does nothing in statement position; you may be omitting necessary parentheses",
        Warning, Some(PureExpressionInStatementPositionID)))

  @Test def diagnosticWorksheetPureExpression: Unit =
    ws"""${m1}1""".withSource
     .diagnostics(m1 /* no "pure expression" warning because this is a worksheet */)
}

package dotty.tools.languageserver

import org.junit.Test

import dotty.tools.dotc.reporting.diagnostic.ErrorMessageID._
import dotty.tools.languageserver.util.Code._
import org.eclipse.lsp4j.DiagnosticSeverity._

class DiagnosticsTest {
  @Test def diagnosticWrongType: Unit =
    code"""object Test {
          |  val x: Int = $m1"foo"$m2
          |}""".withSource
      .diagnostics(m1,
        (m1 to m2, """Found:    String("foo")
                     |Required: Int""".stripMargin, Error, Some(TypeMismatchID))
      )

  @Test def diagnosticMissingLambdaBody: Unit =
    code"""object Test {
          |  Nil.map(x => x).filter(x$m1 =>$m2)$m3
          |}""".withSource
      .diagnostics(m1,
        (m2 to m2, "expression expected but ')' found", Error, Some(IllegalStartSimpleExprID)),
        (m1 to m1, """Found:    Null
                     |Required: Boolean""".stripMargin, Error, Some(TypeMismatchID))
      )

  @Test def diagnosticPureExpression: Unit =
    code"""object Test {
          |  ${m1}1$m2
          |}""".withSource
     .diagnostics(m1,
       (m1 to m2,
        "A pure expression does nothing in statement position; you may be omitting necessary parentheses",
        Warning, Some(PureExpressionInStatementPositionID)))

  @Test def diagnosticWorksheetPureExpression: Unit =
    ws"""${m1}1""".withSource
     .diagnostics(m1 /* no "pure expression" warning because this is a worksheet */)
}

Fix error message check string

Fix error message check string


package org.edmcouncil.rdf_serializer

/**
 * Test the XmlSorter
 */
class XmlSorterSpec extends UnitSpec {

  "An XmlSorter" must {

    "sort an XML file" in {

      val file = PotentialFile("src/test/resources/wine.rdf")
      val sorter = RdfXmlSorter(file.Path.get)

      sorter.printIt()
    }
  }
}

package org.edmcouncil.rdf_serializer

/**
 * Test the XmlSorter
 */
class XmlSorterSpec extends UnitSpec {

  "An XmlSorter" must {

    "sort an XML file" in {

      val file = PotentialFile("src/test/resources/wine.rdf")
      val sorter = RdfXmlSorter(file.path.get)

      sorter.printIt()
    }
  }
}

Change everything back to before the superstitious attempts to fix things.


package castalia.matcher

import akka.http.scaladsl.model.Uri
import castalia.matcher.types.Segments

/**
  * Takes a list of endpoint matchers and determines which one matches.
  *
  * Created by Jean-Marc van Leerdam on 2016-01-09
  */
class RequestMatcher(myMatchers: List[Matcher]) {
  val uriParser = new UriParser()

  def matchRequest(uriString: String): Option[RequestMatch] = {
    val parsedUri = uriParser.parse(uriString)

    def findMatch( segments: Segments, matchers: List[Matcher]): Option[RequestMatch] = {
      if (matchers.isEmpty) return None

      val result = matchers.head.matchPath(segments)
      if (result.isDefined) return Some(new RequestMatch(uriString, parsedUri.path, result.get, parsedUri.queryParams, matchers.head.handler))

      // no match yet, look at the rest of the matchers
      findMatch(segments, matchers.tail)
    }

    println( "looking for [" + parsedUri.pathList + "] in [" + myMatchers + "]")
    findMatch(parsedUri.pathList, myMatchers)
  }

  def addOrReplaceMatcher(newMatcher: Matcher): RequestMatcher = {
    new RequestMatcher( newMatcher :: myMatchers.filterNot(_.segments == newMatcher.segments))
  }
}

package castalia.matcher

import akka.http.scaladsl.model.Uri
import castalia.matcher.types.Segments

/**
  * Takes a list of endpoint matchers and determines which one matches.
  *
  * Created by Jean-Marc van Leerdam on 2016-01-09
  */
class RequestMatcher(myMatchers: List[Matcher]) {
  val uriParser = new UriParser()

  def matchRequest(uriString: String): Option[RequestMatch] = {
    val parsedUri = uriParser.parse(uriString)

    def findMatch( segments: Segments, matchers: List[Matcher]): Option[RequestMatch] =
      (segments, matchers) match {
        case (_, Nil) => None
        case (seg, head :: _) if head.matchPath(seg).isDefined =>
          Some(new RequestMatch(uriString, parsedUri.path, head.matchPath(seg).get, parsedUri.queryParams, head.handler))
        case (seg, _ :: tail) => findMatch(seg, tail)
      }

    println( "looking for [" + parsedUri.pathList + "] in [" + myMatchers + "]")
    findMatch(parsedUri.pathList, myMatchers)
  }

  def addOrReplaceMatcher(newMatcher: Matcher): RequestMatcher = {
    new RequestMatcher( newMatcher :: myMatchers.filterNot(_.segments == newMatcher.segments))
  }
}

Refactor findMatch to use pattern matching


package dotty.tools
package dotc
package reporting

import core.Contexts.Context
import collection.mutable
import Reporter.Diagnostic

/**
 * This class implements a Reporter that stores all messages
 */
class StoreReporter extends Reporter {

  val infos = new mutable.ListBuffer[Diagnostic]

  protected def doReport(d: Diagnostic)(implicit ctx: Context): Unit =
    infos += d

  override def flush()(implicit ctx: Context) =
    infos foreach ctx.reporter.report
}

package dotty.tools
package dotc
package reporting

import core.Contexts.Context
import collection.mutable
import Reporter.Diagnostic

/**
 * This class implements a Reporter that stores all messages
 */
class StoreReporter extends Reporter {

  val infos = new mutable.ListBuffer[Diagnostic]

  protected def doReport(d: Diagnostic)(implicit ctx: Context): Unit = {
    println(s">>>> StoredError: ${d.msg}") // !!! DEBUG
    infos += d
  }

  override def flush()(implicit ctx: Context) =
    infos foreach ctx.reporter.report
}

Debug measure: Report all errors when they are first issued


name := "Simple Lift Formality Chat Thingie"

version := "0.0.1"

organization := "net.liftweb"

scalaVersion := "2.9.1"

resolvers ++= Seq("snapshots"     at "http://oss.sonatype.org/content/repositories/snapshots",
                "releases"        at "http://oss.sonatype.org/content/repositories/releases"
                )

seq(webSettings :_*)

unmanagedResourceDirectories in Test <+= (baseDirectory) { _ / "src/main/webapp" }

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

libraryDependencies ++= {
  val liftVersion = "2.5.1"
  Seq(
    "net.liftweb"       %% "lift-webkit"        % liftVersion        % "compile",
    "net.liftmodules"   %% "lift-jquery-module_2.5" % "2.4",
    "org.eclipse.jetty" % "jetty-webapp"        % "8.1.7.v20120910"  % "container,test",
    "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container,test" artifacts Artifact("javax.servlet", "jar", "jar"),
    "ch.qos.logback"    % "logback-classic"     % "1.0.6",
    "org.specs2"        %% "specs2"             % "1.12.1"            % "test"
  )
}

name := "Simple Lift Formality Chat Thingie"

version := "0.0.1"

organization := "net.liftweb"

scalaVersion := "2.9.2"

resolvers ++= Seq("snapshots"     at "http://oss.sonatype.org/content/repositories/snapshots",
                "releases"        at "http://oss.sonatype.org/content/repositories/releases"
                )

seq(webSettings :_*)

unmanagedResourceDirectories in Test <+= (baseDirectory) { _ / "src/main/webapp" }

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

libraryDependencies ++= {
  val liftVersion = "2.6-SNAPSHOT"
  Seq(
    "net.liftweb"       %% "lift-webkit"        % liftVersion        % "compile",
    "net.liftmodules"   %% "lift-jquery-module_2.5" % "2.4",
    "org.eclipse.jetty" % "jetty-webapp"        % "8.1.7.v20120910"  % "container,test",
    "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container,test" artifacts Artifact("javax.servlet", "jar", "jar"),
    "ch.qos.logback"    % "logback-classic"     % "1.0.6",
    "com.hacklanta"     %% "lift-formality"     % "0.1",
    "org.specs2"        %% "specs2"             % "1.12.1"            % "test"
  )
}

Add lift-formality dependency and switch to Lift 2.6-SNAPSHOT.


import sbt._

object Dependencies {
  lazy val logbackClassic      = "ch.qos.logback"             %  "logback-classic"     % "1.2.3"
  lazy val twitterHPACK        = "com.twitter"                %  "hpack"               % "1.0.2"
  lazy val asyncHttpClient     = "org.asynchttpclient"        %  "async-http-client"   % "2.12.3"
  lazy val log4s               = "org.log4s"                  %% "log4s"               % "1.10.0"
  lazy val scalacheck          = "org.scalacheck"             %% "scalacheck"          % "1.15.4"
  lazy val specs2              = "org.specs2"                 %% "specs2-core"         % "4.11.0"
  lazy val specs2Mock          = "org.specs2"                 %% "specs2-mock"         % specs2.revision
  lazy val specs2Scalacheck    = "org.specs2"                 %% "specs2-scalacheck"   % specs2.revision
}

import sbt._

object Dependencies {
  lazy val logbackClassic      = "ch.qos.logback"             %  "logback-classic"     % "1.2.3"
  lazy val twitterHPACK        = "com.twitter"                %  "hpack"               % "1.0.2"
  lazy val asyncHttpClient     = "org.asynchttpclient"        %  "async-http-client"   % "2.12.3"
  lazy val log4s               = "org.log4s"                  %% "log4s"               % "1.10.0"
  lazy val scalacheck          = "org.scalacheck"             %% "scalacheck"          % "1.15.4"
  lazy val specs2              = "org.specs2"                 %% "specs2-core"         % "4.12.0"
  lazy val specs2Mock          = "org.specs2"                 %% "specs2-mock"         % specs2.revision
  lazy val specs2Scalacheck    = "org.specs2"                 %% "specs2-scalacheck"   % specs2.revision
}

Update specs2-core, specs2-mock, ... to 4.12.0


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

package uk.ac.ncl.openlab.intake24.services.foodindex.arabic

import uk.ac.ncl.openlab.intake24.services.foodindex.{AbstractFoodIndex, FoodIndexDataService}

abstract class ArabicFoodIndex(foodData: FoodIndexDataService, locale: String)
  extends AbstractFoodIndex(foodData, None, new ArabicWordOpsImpl(), ArabicFoodIndex.indexFilter,
    ArabicFoodIndex.nonIndexedWords, ArabicFoodIndex.specialFoodNames, locale)

object ArabicFoodIndex {
  val indexFilter = Seq("`", ",", """\/""", """\-""", """\)""", """\(""", """\.""", """e\.g\.""", """e\.g""", """\'s""")
  val nonIndexedWords = Seq("com")
  val specialFoodNames = new ArabicSpecialFoodNames
}

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

package uk.ac.ncl.openlab.intake24.services.foodindex.arabic

import uk.ac.ncl.openlab.intake24.services.foodindex.{AbstractFoodIndex, FoodIndexDataService}

abstract class ArabicFoodIndex(foodData: FoodIndexDataService, locale: String)
  extends AbstractFoodIndex(foodData, None, new ArabicWordOpsImpl(), ArabicFoodIndex.indexFilter,
    ArabicFoodIndex.nonIndexedWords, ArabicFoodIndex.specialFoodNames, locale)

object ArabicFoodIndex {
  val indexFilter = Seq("`", "\\+", "،", ",", "\\/", "\\-", "\\)", "\\(", "\\.")
  val nonIndexedWords = Seq()
  val specialFoodNames = new ArabicSpecialFoodNames
}

Split food descriptions on Arabic commas


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

package me.footlights.api.ajax {

class RichWebRequest(req:WebRequest) {
	def map[T](f:WebRequest => T) = f(req)
}

object RichWebRequest {
	implicit def webReqToRichWebReq(r:WebRequest) = new RichWebRequest(r)
}

}

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

import me.footlights.api.WebRequest

package me.footlights.api.ajax {

/** Represents a URL-encoded string. */
class URLEncoded private (s:String) { override val toString = URLEncoder.encode(s, "utf-8") }

/** Helper functions for encoding and decoding. */
object URLEncoded {
	def apply(s:String) = new URLEncoded(s)
	def unapply(s:String) =
		try { Some(URLDecoder.decode(s, "utf-8")) }
		catch { case ex:Exception => None }
}

class RichWebRequest(req:WebRequest) {
	def map[T](f:WebRequest => T) = f(req)
}

object RichWebRequest {
	implicit def webReqToRichWebReq(r:WebRequest) = new RichWebRequest(r)
}

}

Add the URLEncoded helper class.

Add the URLEncoded helper class.


package io.flow.play.util

import org.joda.time.{DateTime, DateTimeZone}
import org.joda.time.format.DateTimeFormat

/**
  * Helpers for formatting dates for human display
  */
object DateHelper {

  private[this] val EasternTime = DateTimeZone.forID("America/New_York")

  private[this] val DefaultLabel = "N/A"

  def shortDate(
    dateTime: DateTime
  ): String = shortDateOption(Some(dateTime))

  def shortDateOption(
    dateTime: Option[DateTime],
    default: String = DefaultLabel
  ): String = {
    dateTime match {
      case None => default
      case Some(dt) => {
        DateTimeFormat.shortDate.withZone(EasternTime).print(dt)
      }
    }
  }

  def longDateTime(
    dateTime: DateTime
  ): String = longDateTimeOption(Some(dateTime))

  def longDateTimeOption(
    dateTime: Option[DateTime],
    default: String = DefaultLabel
  ): String = {
    dateTime match {
      case None => default
      case Some(dt) => {
        DateTimeFormat.longDateTime.withZone(EasternTime).print(dt)
      }
    }
  }

}

package io.flow.delta.www.lib
//package io.flow.play.util

import org.joda.time.{DateTime, DateTimeZone}
import org.joda.time.format.DateTimeFormat

/**
  * Helpers for formatting dates for human display
  */
object DateHelper {

  private[this] val EasternTime = DateTimeZone.forID("America/New_York")

  private[this] val DefaultLabel = "N/A"

  def shortDate(
    dateTime: DateTime
  ): String = shortDateOption(Some(dateTime))

  def shortDateOption(
    dateTime: Option[DateTime],
    default: String = DefaultLabel
  ): String = {
    dateTime match {
      case None => default
      case Some(dt) => {
        DateTimeFormat.shortDate.withZone(EasternTime).print(dt)
      }
    }
  }

  def shortDateTime(
    dateTime: DateTime
  ): String = shortDateTimeOption(Some(dateTime))

  def shortDateTimeOption(
    dateTime: Option[DateTime],
    default: String = DefaultLabel
  ): String = {
    dateTime match {
      case None => default
      case Some(dt) => {
        DateTimeFormat.forPattern("MM/dd/YY HH:mm:ss z").withZone(EasternTime).print(dt)
      }
    }
  }

  def longDateTime(
    dateTime: DateTime
  ): String = longDateTimeOption(Some(dateTime))

  def longDateTimeOption(
    dateTime: Option[DateTime],
    default: String = DefaultLabel
  ): String = {
    dateTime match {
      case None => default
      case Some(dt) => {
        DateTimeFormat.longDateTime.withZone(EasternTime).print(dt)
      }
    }
  }

  def consoleLongDateTime(
    dateTime: DateTime
  ): String = consoleLongDateTimeOption(Some(dateTime))

  def consoleLongDateTimeOption(
    dateTime: Option[DateTime],
    default: String = DefaultLabel
  ): String = {
    dateTime match {
      case None => default
      case Some(dt) => {
        DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss z").withZone(EasternTime).print(dt)
      }
    }
  }

}

Add a few more date formats

Add a few more date formats


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

import scala.util.Try

import sun.misc.Unsafe

object UnsafeHelper {

	val unsafe: Option[Unsafe] = Try {
		val unsafeField = classOf[Unsafe].getDeclaredField("theUnsafe")
		unsafeField.setAccessible(true)
		unsafeField.get(null).asInstanceOf[Unsafe]
	}.toOption

	val stringValueFieldOffset: Long = unsafe.flatMap(u => Try(u.objectFieldOffset(classOf[String].getDeclaredField("value"))).toOption).getOrElse(-1L)
	val stringOffsetFieldOffset: Long = unsafe.flatMap(u => Try(u.objectFieldOffset(classOf[String].getDeclaredField("offset"))).toOption).getOrElse(-1L)
	val stringCountFieldOffset: Long = unsafe.flatMap(u => Try(u.objectFieldOffset(classOf[String].getDeclaredField("count"))).toOption).getOrElse(-1L)
}

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

import scala.util.Try

import sun.misc.Unsafe

object UnsafeHelper {

	val unsafe: Option[Unsafe] = Try {
		val unsafeField = classOf[Unsafe].getDeclaredField("theUnsafe")
		unsafeField.setAccessible(true)
		unsafeField.get(null).asInstanceOf[Unsafe]
	}.toOption

	val stringValueFieldOffset: Long = unsafe.map(_.objectFieldOffset(classOf[String].getDeclaredField("value"))).getOrElse(-1L)
	val stringOffsetFieldOffset: Long = unsafe.map(_.objectFieldOffset(classOf[String].getDeclaredField("offset"))).getOrElse(-1L)
	val stringCountFieldOffset: Long = unsafe.map(_.objectFieldOffset(classOf[String].getDeclaredField("count"))).getOrElse(-1L)
}

Use map instead of flatMap (function application is also wrapped in a Try)


package controllers

import play.api._
import play.api.mvc._
import play.api.libs.json._

object Application extends Controller {

  def index = Action {
    Ok("Hello World")
  }

  def slack = Action(parse.multipartFormData) { request =>
    val result = request.toString()
    Ok(Json.obj("status" -> "OK", "message" -> result))
  }
}

package controllers

import play.api._
import play.api.mvc._
import play.api.libs.json._

object Application extends Controller {
  def index = Action {
    Ok("Hello World")
  }

  def slack = Action { request =>
    val params = request.body.asFormUrlEncoded
    val teamId = params.get("team_id")(0)
    Ok(Json.obj("status" -> "OK", "message" -> teamId))
  }
}

Add demo endpoint for slack.

Add demo endpoint for slack.


package daytwo

/**
 * Addendum leading up to day two exercises.
 */
class Scrap {
  def run() {

    val list = List("Guts man", "Bubble man", "Proto man")
    list.foreach(man => println(man)) //anonymous functions are pretty neat
    println()
    list.init.foreach(man => println(man))
    println()
    list.tail.foreach(man => println(man))
    println()
    list.drop(2).foreach(man => println(man))

    //and as a set...
    println() //formatting

    val set = Set("Spark man", "Wood man", "Dr. Light")
    set.foreach(man => println(man))

    println()

    val powers = Map("Spark man" -> "Electricity", "Bubble man" -> "Fires Bubbles", "Guts man" -> "No idea")
    println(powers.foreach(man => println(man._2)))

    println() //formatting

    println(list.forall(man => man.contains("man")))
    println(set.forall(man => man.contains("man")))

  }
}

package daytwo

/**
 * Addendum leading up to day two exercises.
 */
class Scrap {
  def run() {

    val list = List("Guts man", "Bubble man", "Proto man")
    list.foreach(man => println(man)) //anonymous functions are pretty neat
    println()
    list.init.foreach(man => println(man))
    println()
    list.tail.foreach(man => println(man))
    println()
    list.drop(2).foreach(man => println(man))

    //and as a set...
    println() //formatting

    val set = Set("Spark man", "Wood man", "Dr. Light")
    set.foreach(man => println(man))

    println()

    val powers = Map("Spark man" -> "Electricity", "Bubble man" -> "Fires Bubbles", "Guts man" -> "No idea")
    println(powers.foreach(man => println(man._2)))

    println() //formatting

    println(list.forall(man => man.contains("man")))
    println(set.forall(man => man.contains("man")))
    println(set.exists(man => man.contains("Dr")))

    println()

    println(stringLengthSum(list))

  }

  //exercise one - use foldLeft to compute the total size of a list of strings
  def stringLengthSum(strings: List[String]): Int = {
    strings.foldLeft(0)((sum, value) => sum + value.length)
  }

}

Work for day two of Scala

Work for day two of Scala

Adds the use of foldLeft to compute the overall length of a list of strings.


package com.softwaremill.codebrag.cache

import com.softwaremill.codebrag.service.config.CommitCacheConfig
import java.util.concurrent.ConcurrentHashMap
import com.softwaremill.codebrag.repository.Repository
import scala.collection.JavaConversions._
import com.softwaremill.codebrag.domain.MultibranchLoadCommitsResult

class RepositoriesCache(backend: PersistentBackendForCache, config: CommitCacheConfig) {

  private val reposCacheMap = new ConcurrentHashMap[String, RepositoryCache]

  def initialize(repos: Seq[Repository]) {
    repos.foreach { repo =>
      val repoCache = new RepositoryCache(repo, backend, config)
      repoCache.initialize()
      reposCacheMap.put(repo.repoName, repoCache)
    }
  }

  def repoNames = reposCacheMap.keySet().toList.sorted

  def getRepo(repoName: String) = reposCacheMap.getOrElse(repoName, throw new IllegalArgumentException(s"Cannot find repository $repoName"))

  def addCommitsToRepo(repoName: String, commits: MultibranchLoadCommitsResult) = getRepo(repoName).addCommits(commits)

  def getBranchCommits(repoName: String, branch: String) = getRepo(repoName).getBranchCommits(branch)

  def getCheckedOutBranchShortName(repoName: String) = getRepo(repoName).getCheckedOutBranchShortName

}

package com.softwaremill.codebrag.cache

import com.softwaremill.codebrag.service.config.CommitCacheConfig
import java.util.concurrent.ConcurrentHashMap
import com.softwaremill.codebrag.repository.Repository
import scala.collection.JavaConversions._
import com.softwaremill.codebrag.domain.MultibranchLoadCommitsResult

class RepositoriesCache(backend: PersistentBackendForCache, config: CommitCacheConfig) {

  private val reposCacheMap = new ConcurrentHashMap[String, RepositoryCache]

  def initialize(repos: Seq[Repository]) {
    repos.foreach { repo =>
      val repoCache = new RepositoryCache(repo, backend, config)
      repoCache.initialize()
      reposCacheMap.put(repo.repoName, repoCache)
    }
  }

  def repoNames = reposCacheMap.keySet().toList.sorted

  def hasRepo(repoName: String) = reposCacheMap.containsKey(repoName)

  def getRepo(repoName: String) = reposCacheMap.getOrElse(repoName, throw new IllegalArgumentException(s"Cannot find repository $repoName"))

  def addCommitsToRepo(repoName: String, commits: MultibranchLoadCommitsResult) = getRepo(repoName).addCommits(commits)

  def getBranchCommits(repoName: String, branch: String) = getRepo(repoName).getBranchCommits(branch)

  def getCheckedOutBranchShortName(repoName: String) = getRepo(repoName).getCheckedOutBranchShortName

}

Add hasRepo method to repositoriesCache

Add hasRepo method to repositoriesCache


// When uncommented this line will be identified as an unused import by -Ywarn-unused-import
// import scala.MatchError

object BadThings {
  // When uncommented, this line will be identified as inferring any by the -Xlint scalac switches when running `compile`.
  // val xLintExample = Seq(1, 2, "3")

  // When uncommented this line will be identified as a compiler error because of -deprecation and -Xfatal-warnings
  // val deprecationExample = Seq(1, 2, 3).toSet()

  // When uncommented, this line will be identifed as an unintentional string concatenation by WartRemover
  // val wartRemoverExample = Seq(1, 2) + 3

  // When uncommented this line will be identified as a bad idea by Foursquare Linter
  // val fourSquareLinterExample = Array(1,2,3).toString

  // When uncommented and an 'n' added to the method name Scalastyle will identify this as writing to stdout
  // printl("Typically we don't want to ship writing to standard out in production code.")
}

// When uncommented this line will be identified as an unused import by -Ywarn-unused-import
// import scala.MatchError

object BadThings {
  // When uncommented, this line will be identified as inferring any by the -Xlint scalac switches when running `compile`.
  // val xLintExample = Seq(1, 2, "3")

  // When uncommented this line will be identified as a compiler error because of -deprecation and -Xfatal-warnings when running `compile`.
  // val deprecationExample = Seq(1, 2, 3).toSet()

  // When uncommented, this line will be identifed as an unintentional string concatenation by WartRemover when running `lint:compile`.
  // val wartRemoverExample = Seq(1, 2) + 3

  // When uncommented this line will be identified as a bad idea by HairyFotr Linter when running `lint:compile`.
  // val hairyFotrLinterExample = Array(1, 2, 3).toString

  // When uncommented and an 'n' added to the method name Scalastyle will identify this as writing to stdout when running `scalastyle`.
  // printl("Typically we don't want to ship writing to standard out in production code.")
}

Rename linter. Add comments explaining which command should trigger error.


package sttp.client

import java.nio.file.Path

import org.scalatest.{FlatSpec, Matchers, Suite}
import sttp.client.internal.SttpFile

trait ToCurlConverterTestExtension { suit: Suite with FlatSpec with Matchers =>
  it should "render multipart form data if content is a file" in {
    basicRequest
      .multipartBody(multipartSttpFile("upload", SttpFile.fromPath(Path.of("myDataSet"))))
      .post(uri"http://localhost")
      .toCurl should include(
      """--form 'upload=@myDataSet'"""
    )
  }
}

package sttp.client

import java.io.File

import org.scalatest.{FlatSpec, Matchers, Suite}
import sttp.client.internal.SttpFile

trait ToCurlConverterTestExtension { suit: Suite with FlatSpec with Matchers =>
  it should "render multipart form data if content is a file" in {
    basicRequest
      .multipartBody(multipartSttpFile("upload", SttpFile.fromPath(new File("myDataSet").toPath)))
      .post(uri"http://localhost")
      .toCurl should include(
      """--form 'upload=@myDataSet'"""
    )
  }
}

Replace Path.of with new File.toPath

Replace Path.of with new File.toPath


name := "ingest"

javaOptions += "-Xmx8G"

fork in run := true

connectInput in run := true

libraryDependencies ++= Seq(
  "com.azavea.geotrellis" %% "geotrellis-spark" % Version.geotrellis,
  "com.azavea.geotrellis" %% "geotrellis-s3" % Version.geotrellis,
  "org.apache.spark" %% "spark-core" % "1.5.2",
  Dependencies.sprayRouting,
  Dependencies.sprayCan,
  "org.scalatest"       %%  "scalatest"      % "2.2.0" % "test"
)

assemblyMergeStrategy in assembly := {
  case "reference.conf" => MergeStrategy.concat
  case "application.conf" => MergeStrategy.concat
  case "META-INF/MANIFEST.MF" => MergeStrategy.discard
  case "META-INF\\MANIFEST.MF" => MergeStrategy.discard
  case "META-INF/ECLIPSEF.RSA" => MergeStrategy.discard
  case "META-INF/ECLIPSEF.SF" => MergeStrategy.discard
  case _ => MergeStrategy.first
}

Revolver.settings
net.virtualvoid.sbt.graph.Plugin.graphSettings

name := "ingest"

javaOptions += "-Xmx8G"

fork in run := true

connectInput in run := true

libraryDependencies ++= Seq(
  "com.azavea.geotrellis" %% "geotrellis-spark" % Version.geotrellis,
  "com.azavea.geotrellis" %% "geotrellis-s3" % Version.geotrellis,
  "org.apache.spark" %% "spark-core" % "1.5.2",
  "org.apache.commons" % "commons-io" % "1.3.2",
  Dependencies.sprayRouting,
  Dependencies.sprayCan,
  "org.scalatest"       %%  "scalatest"      % "2.2.0" % "test"
)

assemblyMergeStrategy in assembly := {
  case "reference.conf" => MergeStrategy.concat
  case "application.conf" => MergeStrategy.concat
  case "META-INF/MANIFEST.MF" => MergeStrategy.discard
  case "META-INF\\MANIFEST.MF" => MergeStrategy.discard
  case "META-INF/ECLIPSEF.RSA" => MergeStrategy.discard
  case "META-INF/ECLIPSEF.SF" => MergeStrategy.discard
  case _ => MergeStrategy.first
}

Revolver.settings
net.virtualvoid.sbt.graph.Plugin.graphSettings

Add reader for HTTP layer and test

Add reader for HTTP layer and test


/**
 * Illustrates flatMap + countByValue for wordcount.
 */
package com.oreilly.learningsparkexamples.scala

import org.apache.spark._
import org.apache.spark.SparkContext._

object WordCount {
    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, "WordCount", System.getenv("SPARK_HOME"))
      val input = args.length match {
        case x: Int if x > 1 => sc.textFile(args(1))
        case _ => sc.parallelize(List("pandas", "i like pandas"))
      }
      val counts = input.flatMap(_.split(" ")).map((_, 1)).reduceByKey(_ + _)
      args.length match {
        case x: Int if x > 2 => counts.saveAsTextFile(args(2))
        case _ => println(counts.collect().mkString(","))
      }
    }
}

/**
 * Illustrates flatMap + countByValue for wordcount.
 */
package com.oreilly.learningsparkexamples.scala

import org.apache.spark._
import org.apache.spark.SparkContext._

object WordCount {
    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, "WordCount", System.getenv("SPARK_HOME"))
      val input = args.length match {
        case x: Int if x > 1 => sc.textFile(args(1))
        case _ => sc.parallelize(List("pandas", "i like pandas"))
      }
      val words = input.flatMap(_.split(" "))
      args.length match {
        case x: Int if x > 2 => {
          val counts = words.map((_, 1)).reduceByKey(_ + _)
          counts.saveAsTextFile(args(2))
        }
        case _ => {
          val wc = words.countByValue()
          println(wc.mkString(","))
        }
      }
    }
}

Make the wordcount example match its description (we didn't use countbyvalue before)


scalacOptions := Seq(
  "-deprecation"
)

// For MimeLoader plugin. Dogfooding and hoping it doesn't clash with
// our other sbt plugins.
libraryDependencies ++= List(
  "com.eed3si9n" %% "treehugger" % "0.4.4",
  "io.circe" %% "circe-generic" % "0.11.2",
  "org.http4s" %% "http4s-blaze-client" % "0.20.16",
  "org.http4s" %% "http4s-circe" % "0.20.16",
)

// Hack around a binary conflict in scalameta's dependency on
// fastparse as specified by sbt-doctest-0.9.5.
libraryDependencies += "org.scalameta" %% "scalameta" % "4.3.0"

scalacOptions := Seq(
  "-deprecation"
)

// For MimeLoader plugin. Dogfooding and hoping it doesn't clash with
// our other sbt plugins.
libraryDependencies ++= List(
  "com.eed3si9n" %% "treehugger" % "0.4.4",
  "io.circe" %% "circe-generic" % "0.11.2",
  "org.http4s" %% "http4s-blaze-client" % "0.20.17",
  "org.http4s" %% "http4s-circe" % "0.20.17",
)

// Hack around a binary conflict in scalameta's dependency on
// fastparse as specified by sbt-doctest-0.9.5.
libraryDependencies += "org.scalameta" %% "scalameta" % "4.3.0"

Update http4s-blaze-client, http4s-circe to 0.20.17


package org.continuumio.bokeh

trait FillProps { self: PlotObject =>
    // object fill_color extends ColorSpec(Color.Gray)
    object fill_alpha extends Field[this.type, Percent](this, 100%%)
}

trait LineProps { self: PlotObject =>
    // object line_color extends ColorSpec(Color.Black)
    object line_width extends Field[this.type, Double](this, 1) // Size
    object line_alpha extends Field[this.type, Percent](this, 100%%)
    object line_join extends Field[this.type, LineJoin](this)
    object line_cap extends Field[this.type, LineCap](this)
    object line_dash extends Field[this.type, LineDash](this)
    object line_dash_offset extends Field[this.type, Int](this, 0)
}

trait TextProps { self: PlotObject =>
    object text_font extends Field[this.type, String](this)
    object text_font_size extends Field[this.type, String](this, "10pt")
    object text_font_style extends Field[this.type, FontStyle](this)
    object text_color extends Field[this.type, Color](this, Color.Black)
    object text_alpha extends Field[this.type, Percent](this, 100%%)
    object text_align extends Field[this.type, TextAlign](this)
    object text_baseline extends Field[this.type, Baseline](this)
}

package org.continuumio.bokeh

trait FillProps { self: PlotObject =>
    object fill_color extends GenericDataSpec[this.type, Color](this, Color.Gray)
    object fill_alpha extends Field[this.type, Percent](this, 100%%)
}

trait LineProps { self: PlotObject =>
    object line_color extends GenericDataSpec[this.type, Color](this, Color.Black)
    object line_width extends Field[this.type, Double](this, 1) // Size
    object line_alpha extends Field[this.type, Percent](this, 100%%)
    object line_join extends Field[this.type, LineJoin](this)
    object line_cap extends Field[this.type, LineCap](this)
    object line_dash extends Field[this.type, LineDash](this)
    object line_dash_offset extends Field[this.type, Int](this, 0)
}

trait TextProps { self: PlotObject =>
    object text_font extends Field[this.type, String](this)
    object text_font_size extends Field[this.type, String](this, "10pt")
    object text_font_style extends Field[this.type, FontStyle](this)
    object text_color extends Field[this.type, Color](this, Color.Black)
    object text_alpha extends Field[this.type, Percent](this, 100%%)
    object text_align extends Field[this.type, TextAlign](this)
    object text_baseline extends Field[this.type, Baseline](this)
}

Enable fill_color and line_color color specs


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

import fm.common.{ImmutableArray, Interner, LoadingCache}

object RichImmutableArray {
  private val interners: LoadingCache[Class[_], Interner[ImmutableArray[_]]] = LoadingCache(
    weakKeys = true,
  ){ _: Class[_] =>
    Interner[ImmutableArray[_]]()
  }
}

final class RichImmutableArray[A](val arr: ImmutableArray[A]) extends AnyVal {
  def intern: ImmutableArray[A] = RichImmutableArray.interners.get(arr.getClass)(arr).asInstanceOf[ImmutableArray[A]]
}

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

import fm.common.{ImmutableArray, Interner, LoadingCache}

object RichImmutableArray {
  private val interners: LoadingCache[Class[_], Interner[ImmutableArray[_]]] = LoadingCache(
    weakKeys = true
  ){ _: Class[_] =>
    Interner[ImmutableArray[_]]()
  }
}

final class RichImmutableArray[A](val arr: ImmutableArray[A]) extends AnyVal {
  def intern: ImmutableArray[A] = RichImmutableArray.interners.get(arr.getClass)(arr).asInstanceOf[ImmutableArray[A]]
}

Fix Scala 2.11 compilation error

Fix Scala 2.11 compilation error


package pl.touk.nussknacker.ui.definition.editor

import pl.touk.nussknacker.engine.api.definition.{CronParameterEditor, DualParameterEditor, ParameterEditor, RawParameterEditor}
import pl.touk.nussknacker.engine.api.editor.DualEditorMode
import pl.touk.nussknacker.engine.api.typed.typing.Typed
import pl.touk.nussknacker.engine.definition.{ParameterEditorDeterminer, ParameterTypeEditorDeterminer}

/**
 * We want to keep package nusskancker-interpreter with as less dependencies as possible - that's why we handle
 * com.cronutils.model.Cron editor here
 */
protected class ParameterTypeEditorDeterminerUiDecorator(determiner: ParameterTypeEditorDeterminer) extends ParameterEditorDeterminer {

  override def determine(): Option[ParameterEditor] = {
    determiner.determine() match {
      case Some(editor) => Some(editor)
      case None if determiner.typ.canBeSubclassOf(Typed[com.cronutils.model.Cron]) => Some(DualParameterEditor(
        simpleEditor = CronParameterEditor,
        defaultMode = DualEditorMode.SIMPLE
      ))
      case _ => Some(RawParameterEditor)
    }
  }
}

package pl.touk.nussknacker.ui.definition.editor

import pl.touk.nussknacker.engine.api.definition.{CronParameterEditor, DualParameterEditor, ParameterEditor, RawParameterEditor}
import pl.touk.nussknacker.engine.api.editor.DualEditorMode
import pl.touk.nussknacker.engine.api.typed.typing.Typed
import pl.touk.nussknacker.engine.definition.{ParameterEditorDeterminer, ParameterTypeEditorDeterminer}

/**
 * We want to keep package nusskancker-interpreter with as less dependencies as possible - that's why we handle
 * com.cronutils.model.Cron editor here
 */
protected class ParameterTypeEditorDeterminerUiDecorator(determiner: ParameterTypeEditorDeterminer) extends ParameterEditorDeterminer {

  override def determine(): Option[ParameterEditor] = {
    determiner.determine() match {
      case Some(editor) => Some(editor)
      case None if determiner.typ == Typed[com.cronutils.model.Cron] => Some(DualParameterEditor(
        simpleEditor = CronParameterEditor,
        defaultMode = DualEditorMode.SIMPLE
      ))
      case _ => Some(RawParameterEditor)
    }
  }
}

Fix for: When parameter's type was Unknown, was picked CronEditor (because of usage of canBeSubclassOf)


package threesixty.persistence.cassandra

import com.websudos.phantom.connectors.{ContactPoints, KeySpace}

/**
  * Created by Stefan Cimander on 19.01.16.
  */
trait CassandraKeyspace {
    implicit val keySpace = KeySpace("threesixity")
}

object CassandraConnector extends CassandraKeyspace {
    val hosts = Seq("137.250.170.136")
    // val hosts = Seq("localhost")
    val keyspace = ContactPoints(hosts).keySpace("threesixty")
}

package threesixty.persistence.cassandra

import com.websudos.phantom.connectors.{ContactPoints, KeySpace}
import threesixty.server.APIHandler

/**
  * Created by Stefan Cimander on 19.01.16.
  */
trait CassandraKeyspace {
    implicit val keySpace = KeySpace("threesixity")
}

object CassandraConnector extends CassandraKeyspace {
    // val hosts = Seq("137.250.170.136")
    // val hosts = Seq("localhost")
    val hosts = Seq(APIHandler.dbAddress)
    val dbKeyspace = APIHandler.dbKeyspace

    val keyspace = ContactPoints(hosts).keySpace(dbKeyspace)
}

Read ip and keyspace from APIHandler

Read ip and keyspace from APIHandler

The ip and keyspace is now read from the APIHandler.

One alternative I've found is to load the information from the config
again but since Thomas Weber does not want the config to be loaded
multiple times this option was neglected.


logLevel := Level.Warn
addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.0")
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.10")
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.1")
addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.2")
addSbtPlugin("org.ensime" % "sbt-ensime" % "2.0.1")

logLevel := Level.Warn
addSbtPlugin("io.get-coursier" % "sbt-coursier" % "1.0.0")
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.11")
addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.1")
addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.2")
addSbtPlugin("org.ensime" % "sbt-ensime" % "2.0.1")

Bump to play framework 2.6.11

Bump to play framework 2.6.11


// Global build settings

// Imports

import scalariform.formatter.preferences._

// Scalariform - source code formatter

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

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

// Scalastyle - Scala style checker
org.scalastyle.sbt.ScalastylePlugin.Settings

// sbt-site - Project website generator
site.settings

site.includeScaladoc()

// site.pamfletSupport() // enable this in specific projects

// sbt-ghpages - GitHub pages uploader
// ghpages.settings

// git.remoteRepo := "git@github.com:{username}/{project}.git"

// Global build settings

// Imports

import scalariform.formatter.preferences._

// Custom settings

cancelable := true

// Scalariform - source code formatter

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

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

// Scalastyle - Scala style checker
org.scalastyle.sbt.ScalastylePlugin.Settings

// sbt-site - Project website generator
site.settings

site.includeScaladoc()

// site.pamfletSupport() // enable this in specific projects

// sbt-ghpages - GitHub pages uploader
// ghpages.settings

// git.remoteRepo := "git@github.com:{username}/{project}.git"

Update SBT config to let Ctrl-c cancel actions


package lila.message

import play.api.libs.json._
import play.api.mvc.Result
import play.api.mvc.Results._
import scala.concurrent.duration._

import lila.common.PimpedJson._
import lila.user.User
import scala.concurrent.{ Future }
import lila.common.paginator._

final class JsonView() {

  def inbox(me: User, threads: Paginator[Thread]): Result =
    Ok(Json.obj(
      "messages" -> threads.currentPageResults.map { thread => inboxItem(me, thread) }
    ).noNull)

  def inboxItem(me: User, thread: Thread): JsValue =
    Json.obj(
      "id" -> thread.id,
      "author" -> thread.otherUserId(me),
      "name" -> thread.name,
      "updateAt" -> thread.updatedAt
    )

  def thread(thread: Thread): Fu[JsValue] =
    fuccess (
      Json.obj(
        "id" -> thread.id,
        "name" -> thread.name,
        "posts" -> thread.posts.map { post => threadPost(thread, post)}
      )
    )

  def threadPost(thread: Thread, post: Post): JsValue =
    Json.obj(
      "sender" -> thread.senderOf(post),
      "receiver" -> thread.receiverOf(post),
      "text" -> post.text,
      "createdAt" -> post.createdAt
    )
}

package lila.message

import play.api.libs.json._
import play.api.mvc.Result
import play.api.mvc.Results._
import scala.concurrent.duration._

import lila.common.PimpedJson._
import lila.user.User
import scala.concurrent.{ Future }
import lila.common.paginator._

final class JsonView() {

  def inbox(me: User, threads: Paginator[Thread]): Result =
    Ok(Json.obj(
      "threads" -> threads.currentPageResults.map { thread => inboxItem(me, thread) }
    ).noNull)

  def inboxItem(me: User, thread: Thread): JsValue =
    Json.obj(
      "id" -> thread.id,
      "author" -> thread.otherUserId(me),
      "name" -> thread.name,
      "updateAt" -> thread.updatedAt
    )

  def thread(thread: Thread): Fu[JsValue] =
    fuccess (
      Json.obj(
        "id" -> thread.id,
        "name" -> thread.name,
        "posts" -> thread.posts.map { post => threadPost(thread, post)}
      )
    )

  def threadPost(thread: Thread, post: Post): JsValue =
    Json.obj(
      "sender" -> thread.senderOf(post),
      "receiver" -> thread.receiverOf(post),
      "text" -> post.text,
      "createdAt" -> post.createdAt
    )
}

Change name of inbox items from 'messages' to 'threads'


package controllers

import play.api._
import cache.Cached
import play.api.Play.current
import libs.concurrent.Akka
import mvc._
import play.api.libs.json._

import impl.lunchInfo._

object LunchInfo extends Controller {

  def index = Action { request =>
    Ok(views.html.lunchInfo.index())
  }

  def todaysLunches = Cached("todaysLunches", 60 * 10) {
    Action { request =>
      val todaysLunchesPromise = Akka.future { LunchInfoFetcher.fetchTodaysLunchInfo }
      Async {
        todaysLunchesPromise.map(todaysLunches => Ok(views.html.lunchInfo.todaysLunches(todaysLunches)))
      }
    }
  }

  def fetchLunchInfo = Action { request =>

    /*
    request.body.asJson.map { json =>
      (json \ "name").asOpt[String].map { name =>
        Ok("Hello " + name)
      }.getOrElse {
        BadRequest("Missing parameter [name]")
      }
    }.getOrElse {
      BadRequest("Expecting Json impl")
    }
    */

    val json = Json.toJson(
      Map("status" -> "OK")
    )

    Ok(json)

  }

  def fetchLunchInfoExample = Action { request =>
    val json = Json.toJson(
      Map("status" -> "OK")
    )

    Ok(json)
  }
}

package controllers

import play.api._
import cache.Cached
import play.api.Play.current
import libs.concurrent.Akka
import mvc._
import play.api.libs.json._

import impl.lunchInfo._

object LunchInfo extends Controller {

  def index = Action { request =>
    Ok(views.html.lunchInfo.index())
  }

  def todaysLunches = Cached("todaysLunches", 60 * 10) {
    Action { request =>
      val todaysLunchesPromise = Akka.future { LunchInfoFetcher.fetchTodaysLunchInfo }
      Async {
        todaysLunchesPromise.map(todaysLunches =>
          Ok(views.html.lunchInfo.todaysLunches(todaysLunches)).withHeaders(PRAGMA -> "no-cache")
        )
      }
    }
  }

  def fetchLunchInfo = Action { request =>

    /*
    request.body.asJson.map { json =>
      (json \ "name").asOpt[String].map { name =>
        Ok("Hello " + name)
      }.getOrElse {
        BadRequest("Missing parameter [name]")
      }
    }.getOrElse {
      BadRequest("Expecting Json impl")
    }
    */

    val json = Json.toJson(
      Map("status" -> "OK")
    )

    Ok(json)

  }

  def fetchLunchInfoExample = Action { request =>
    val json = Json.toJson(
      Map("status" -> "OK")
    )

    Ok(json)
  }
}

Set no-cache on todaysLunches response

Set no-cache on todaysLunches response


// tests that errors are properly propagated for dependsOn, map, and flatMap

lazy val root = (project in file(".")).
  settings(
    a := (baseDirectory map (b =>  if ((b / "succeed").exists) () else sys.error("fail"))).value,
    b := (a.task(at => nop dependsOn(at))).value,
    c := (a map { _ => () }).value,
    d := (a flatMap { _ => task { () } }).value
  )
lazy val a = taskKey[Unit]("")
lazy val b = taskKey[Unit]("")
lazy val c = taskKey[Unit]("")
lazy val d = taskKey[Unit]("")

lazy val input = (project in file("input")).
  settings(
    f := (inputTask { _ map { args => if (args(0) == "succeed") () else sys.error("fail") } }).evaluated,
    j := sys.error("j"),
    g := (f dependsOn(j)).evaluated,
    h := (f map { _ => IO.touch(file("h")) }).evaluated
  )
lazy val f = inputKey[Unit]("")
lazy val g = inputKey[Unit]("")
lazy val h = inputKey[Unit]("")
lazy val j = taskKey[Unit]("")

// tests that errors are properly propagated for dependsOn, map, and flatMap

lazy val root = (project in file(".")).
  settings(
    a := (baseDirectory map (b =>  if ((b / "succeed").exists) () else sys.error("fail"))).value,
    b := (a.task(at => nop dependsOn(at))).value,
    c := (a map { _ => () }).value,
    d := (a flatMap { _ => task { () } }).value
  )
lazy val a = taskKey[Unit]("")
lazy val b = taskKey[Unit]("")
lazy val c = taskKey[Unit]("")
lazy val d = taskKey[Unit]("")

lazy val input = (project in file("input")).
  settings(
    f := (if (Def.spaceDelimited().parsed.head == "succeed") () else sys.error("fail")),
    j := sys.error("j"),
    g := (f dependsOn(j)).evaluated,
    h := (f map { _ => IO.touch(file("h")) }).evaluated
  )
lazy val f = inputKey[Unit]("")
lazy val g = inputKey[Unit]("")
lazy val h = inputKey[Unit]("")
lazy val j = taskKey[Unit]("")

Migrate actions/depends-on to fix it

Migrate actions/depends-on to fix it

Seems following the deprecation warning info and the website
documentation and avoiding the BuildCommon inputTask method avoids
whatever problem was causing it to fail... Strange.. but ok?


package onion.compiler

import org.specs2.mutable.Specification
import org.specs2.mutable.BeforeAfter

class LocalScopeSpecification extends Specification {

  trait fixture extends BeforeAfter {
    val scope = new LocalScope(null)
    val bindings = Array[LocalBinding](
      new LocalBinding(0, IRT.BASIC_TYPE_REF_INT),
      new LocalBinding(1, IRT.BASIC_TYPE_REF_DOUBLE),
      new LocalBinding(2, IRT.BASIC_TYPE_REF_LONG),
      new LocalBinding(3, IRT.BASIC_TYPE_REF_DOUBLE)
    )
    val names = Array("hoge", "foo", "bar", "hogehoge")
    val names2 = Array("a", "b", "c", "d")
  }

  private def putAll(scope: LocalScope, names: Array[String], bindings: Array[LocalBinding]): Boolean = {
    var contains = false
    for (i <- 0 until names.length) {
      if(scope.put(names(i), bindings(i))){
        contains = true
      }
    }
    contains;
  }
}

package onion.compiler

import org.specs2.mutable.Specification
import org.specs2.mutable.BeforeAfter

class LocalScopeSpecification extends Specification {
  sequential

  trait fixture extends BeforeAfter {
    val scope = new LocalScope(null)
    val bindings = Array[LocalBinding](
      new LocalBinding(0, IRT.BASIC_TYPE_REF_INT),
      new LocalBinding(1, IRT.BASIC_TYPE_REF_DOUBLE),
      new LocalBinding(2, IRT.BASIC_TYPE_REF_LONG),
      new LocalBinding(3, IRT.BASIC_TYPE_REF_DOUBLE)
    )
    val names = Array("hoge", "foo", "bar", "hogehoge")
    val names2 = Array("a", "b", "c", "d")

    def before = {
      putAll(scope, names, bindings)
    }
    def after = null
  }

  private def putAll(scope: LocalScope, names: Array[String], bindings: Array[LocalBinding]): Boolean = {
    var contains = false
    for (i <- 0 until names.length) {
      if(scope.put(names(i), bindings(i))){
        contains = true
      }
    }
    contains;
  }

  """LocalScope""" should {
    "can have LocalBindings" in new fixture {
      scope.entries.size() must_== 4
    }
  }
}

Add a small example test

Add a small example test


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.34"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.2",
      "com.ning" % "async-http-client" % "1.9.38",
      "org.scalatest" %% "scalatest" % "2.2.6" % Test
    )
  )

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 com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.35"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.2",
      "com.ning" % "async-http-client" % "1.9.38",
      "org.scalatest" %% "scalatest" % "2.2.6" % Test
    )
  )

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


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

crossScalaVersions := Seq("2.11.8")

version := "0.1.14"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.1",
      "org.scalatest" %% "scalatest" % "2.2.6" % "test",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    )
)

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.1.15"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.1",
      "org.scalatest" %% "scalatest" % "2.2.6" % "test",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    )
)

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


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.5"

lazy val allScalacOptions = Seq(
  "-feature",
  "-Xfatal-warnings",
  "-unchecked",
  "-Xcheckinit",
  "-Xlint:adapted-args",
  "-Ypatmat-exhaust-depth", "100", // Fixes: Exhaustivity analysis reached max recursion depth, not all missing cases are reported.
  "-Wconf:src=generated/.*:silent",
  "-Wconf:src=target/.*:silent", // silence the unused imports errors generated by the Play Routes
)

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.2.9" % Test,
    ),
    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")
  }
}

scalacOptions ++= allScalacOptions

version := "0.2.83"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.5"

lazy val allScalacOptions = Seq(
  "-feature",
  "-Xfatal-warnings",
  "-unchecked",
  "-Xcheckinit",
  "-Xlint:adapted-args",
  "-Ypatmat-exhaust-depth", "100", // Fixes: Exhaustivity analysis reached max recursion depth, not all missing cases are reported.
  "-Wconf:src=generated/.*:silent",
  "-Wconf:src=target/.*:silent", // silence the unused imports errors generated by the Play Routes
)

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.2.9" % Test,
    ),
    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")
  }
}

scalacOptions ++= allScalacOptions

version := "0.2.84"

autocommit: Update configuration to record version 0.2.84


name := "lib-apidoc-json-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.25"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.10",
      "org.scalatest" %% "scalatest" % "3.0.1" % Test
    )
  )

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")
  }
}

name := "lib-apidoc-json-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.26"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.10",
      "org.scalatest" %% "scalatest" % "3.0.1" % Test
    )
  )

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


import sbt._

class BioScalaProject(info: ProjectInfo) extends DefaultProject(info)
{
  override def unmanagedClasspath = super.unmanagedClasspath +++ ("lib" / "scala" / "biojava.jar")

  val scalaToolsSnapshots = "Scala-Tools Maven2 Snapshots Repository" at "http://scala-tools.org/repo-snapshots"
  val scalatest = "org.scalatest" % "scalatest" % "1.0"
}

import sbt._

class BioScalaProject(info: ProjectInfo) extends DefaultProject(info)
{
  override def unmanagedClasspath = super.unmanagedClasspath +++ ("lib" / "scala" / "biojava.jar")

  val scalaToolsSnapshots = "Scala-Tools Maven2 Snapshots Repository" at "http://scala-tools.org/repo-snapshots"
  val scalatest = "org.scalatest" % "scalatest" % "1.0"
  override def testOptions = ExcludeTests("bio.test.FullBioTestSuite" :: Nil) :: super.testOptions.toList
  // Modify this line to run single tests
  override def includeTest(s: String) = { s == "bio.test.BioRubySpec" }
}

Exclude TestSuite Run single test

Exclude TestSuite
Run single test


/**
* Recursive binary search algorithm
* @param lst the integer array which is being searched
* @param l lower value for partition
* @param r upper value for partition
* @param num number which is being searched for
* @return the index of the element that matches the search term, returns -1 if not found
*/
def binary_search(lst:Array[Int],l:Int,r:Int,num:Int):Int={

	if(l <= r){
		val mid = l+(r-1)/2

		if (lst(mid) == num) return mid else
			if (lst(mid) <  num ) return binary_search(lst,mid+1,r,num) else
				return binary_search(lst,l,mid-1,num)

	}

	return -1
}

def test(){

	val l = Array(12,3,4,5,6,7)

	assert(binary_search(l,1,l.length,4) == 2)
}

/**
* Recursive binary search algorithm
* @param list the integer array which is being searched (sorted list)
* @param l lower value for partition
* @param r upper value for partition
* @param num number which is being searched for
* @return the index of the element that matches the search term, returns -1 if not found
*/
def binary_search(list: Array[Int], l: Int, r: Int, num:Int): Int = {
  if (l <= r) {
    val mid = (l+r)/2
    if (list(mid) == num) return mid
    else if (list(mid) <  num ) return binary_search(list, mid + 1, r, num)
    else
      return binary_search(list, l, mid - 1, num)
  }
  return -1
}

def test(){
  val l = Array(12,3,4,5,6,7)
  assert(binary_search(l,1,l.length,4) == 2)
}

Correct code scala for binay_search and restyle


package com.roundeights.shnappy.admin

import scala.concurrent.Promise
import scala.concurrent.ExecutionContext.Implicits.global
import com.roundeights.skene.{Provider, Bundle, Registry}
import com.roundeights.attempt._
import com.roundeights.shnappy.{Env, Templater}

/**
 * An admin template builder that comes prebaked with data
 */
trait AdminTemplate {

    /** Admin Template Builder */
    def template: Templater

    /** {@inheritDoc} */
    override def toString = "AdminTemplate()"
}

/**
 * Builds a Template instance with prebaked admin data
 */
class AdminTemplateProvider (
    private val env: Env,
    private val baseTemplate: Templater
) extends Provider[AdminTemplate] {

    /** {@inheritDoc} */
    override def dependencies: Set[Class[_]] = Set( classOf[Auth] )

    /** {@inheritDoc} */
    override def build( bundle: Bundle, next: Promise[AdminTemplate] ): Unit = {
        next.success( new AdminTemplate {
            override val template = baseTemplate.wrap(
                "admin/page", "content",
                "user" -> bundle.get[Auth].user,
                "enableLogin" -> true,
                "email" -> bundle.get[Auth].user.email,
                "debug" -> env.adminDevMode
            )
        } )
    }
}

package com.roundeights.shnappy.admin

import scala.concurrent.Promise
import scala.concurrent.ExecutionContext.Implicits.global
import com.roundeights.skene.{Provider, Bundle, Registry}
import com.roundeights.attempt._
import com.roundeights.shnappy.{Env, Templater}

/**
 * An admin template builder that comes prebaked with data
 */
trait AdminTemplate {

    /** Admin Template Builder */
    def template: Templater

    /** {@inheritDoc} */
    override def toString = "AdminTemplate()"
}

/**
 * Builds a Template instance with prebaked admin data
 */
class AdminTemplateProvider (
    private val env: Env,
    private val baseTemplate: Templater
) extends Provider[AdminTemplate] {

    /** {@inheritDoc} */
    override def dependencies: Set[Class[_]] = Set( classOf[Auth] )

    /** {@inheritDoc} */
    override def build( bundle: Bundle, next: Promise[AdminTemplate] ): Unit = {
        next.success( new AdminTemplate {
            override val template = baseTemplate.wrap(
                "admin/page", "content",
                "user" -> bundle.get[Auth].user,
                "enableLogin" -> true,
                "email" -> bundle.get[Auth].user.email,
                "debug" -> env.adminDevMode,
                "isAdmin" -> bundle.get[Auth].user.isAdmin
            )
        } )
    }
}

Add isAdmin param to admin templates

Add isAdmin param to admin templates