code
stringlengths 5
1M
| repo_name
stringlengths 5
109
| path
stringlengths 6
208
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1M
|
---|---|---|---|---|---|
/*
* Copyright 2014-2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.atlas.core.model
import com.netflix.atlas.core.stacklang.SimpleWord
import com.netflix.atlas.core.stacklang.StandardVocabulary.Macro
import com.netflix.atlas.core.stacklang.Vocabulary
import com.netflix.atlas.core.stacklang.Word
object FilterVocabulary extends Vocabulary {
import com.netflix.atlas.core.model.ModelExtractors._
import com.netflix.atlas.core.stacklang.Extractors._
val name: String = "filter"
val dependsOn: List[Vocabulary] = List(StatefulVocabulary)
val words: List[Word] = List(
Stat,
StatAvg,
StatMax,
StatMin,
StatLast,
StatCount,
StatTotal,
Filter,
// Legacy operations equivalent to `max,:stat`
Macro("stat-min-mf", List("min", ":stat"), List("42")),
Macro("stat-max-mf", List("max", ":stat"), List("42")),
Macro("stat-avg-mf", List("avg", ":stat"), List("42")),
// Priority operators: https://github.com/Netflix/atlas/issues/1224
PriorityK("bottomk", FilterExpr.BottomK.apply),
PriorityK("bottomk-others-min", FilterExpr.BottomKOthersMin.apply),
PriorityK("bottomk-others-max", FilterExpr.BottomKOthersMax.apply),
PriorityK("bottomk-others-sum", FilterExpr.BottomKOthersSum.apply),
PriorityK("bottomk-others-avg", FilterExpr.BottomKOthersAvg.apply),
PriorityK("topk", FilterExpr.TopK.apply),
PriorityK("topk-others-min", FilterExpr.TopKOthersMin.apply),
PriorityK("topk-others-max", FilterExpr.TopKOthersMax.apply),
PriorityK("topk-others-sum", FilterExpr.TopKOthersSum.apply),
PriorityK("topk-others-avg", FilterExpr.TopKOthersAvg.apply)
)
case object Stat extends SimpleWord {
override def name: String = "stat"
protected def matcher: PartialFunction[List[Any], Boolean] = {
case (_: String) :: TimeSeriesType(_) :: _ => true
case (_: String) :: (_: StyleExpr) :: _ => true
}
protected def executor: PartialFunction[List[Any], List[Any]] = {
case (s: String) :: TimeSeriesType(t) :: stack => FilterExpr.Stat(t, s) :: stack
case (s: String) :: (t: StyleExpr) :: stack =>
t.copy(expr = FilterExpr.Stat(t.expr, s)) :: stack
}
override def signature: String = "TimeSeriesExpr String -- FilterExpr"
override def summary: String =
"""
|Create a summary line showing the value of the specified statistic for the input line.
|Valid statistic values are `avg`, `max`, `min`, `last`, and `total`. For example:
|
|| Input | 0 | 5 | 1 | 3 | 1 | NaN |
||----------------|-----|-----|-----|-----|-----|-----|
|| `avg,:stat` | 2 | 2 | 2 | 2 | 2 | 2 |
|| `max,:stat` | 5 | 5 | 5 | 5 | 5 | 5 |
|| `min,:stat` | 0 | 0 | 0 | 0 | 0 | 0 |
|| `last,:stat` | 1 | 1 | 1 | 1 | 1 | 1 |
|| `total,:stat` | 10 | 10 | 10 | 10 | 10 | 10 |
|| `count,:stat` | 5 | 5 | 5 | 5 | 5 | 5 |
|
|When used with [filter](filter-filter) the corresponding `stat-$(name)` operation can be
|used to simplify filtering based on stats.
|
|```
|name,requestsPerSecond,:eq,:sum,
|:dup,max,:stat,50,:lt,
|:over,min,:stat,100,:gt,
|:or,:filter
|```
|
|Could be rewritten as:
|
|```
|name,requestsPerSecond,:eq,:sum,
|:stat-max,50,:lt,:stat-min,100,:gt,:or,:filter
|```
|
|The `stat-min` and `stat-max` operations will get rewritten to be the corresponding
|call to `stat` on the first expression passed to `filter`.
""".stripMargin.trim
override def examples: List[String] =
List(
"name,sps,:eq,:sum,avg",
"name,sps,:eq,:sum,max",
"name,sps,:eq,:sum,min",
"name,sps,:eq,:sum,last",
"name,sps,:eq,:sum,total",
"name,sps,:eq,:sum,count"
)
}
trait StatWord extends SimpleWord {
protected def matcher: PartialFunction[List[Any], Boolean] = { case _ => true }
protected def executor: PartialFunction[List[Any], List[Any]] = {
case stack => value :: stack
}
override def signature: String = " -- FilterExpr"
override def examples: List[String] = List("", "name,sps,:eq,:sum")
def value: FilterExpr
}
case object StatAvg extends StatWord {
override def name: String = "stat-avg"
def value: FilterExpr = FilterExpr.StatAvg
override def summary: String =
"""
|Represents the `avg,:stat` line when used with the filter operation.
""".stripMargin.trim
}
case object StatMax extends StatWord {
override def name: String = "stat-max"
def value: FilterExpr = FilterExpr.StatMax
override def summary: String =
"""
|Represents the `max,:stat` line when used with the filter operation.
""".stripMargin.trim
}
case object StatMin extends StatWord {
override def name: String = "stat-min"
def value: FilterExpr = FilterExpr.StatMin
override def summary: String =
"""
|Represents the `min,:stat` line when used with the filter operation.
""".stripMargin.trim
}
case object StatLast extends StatWord {
override def name: String = "stat-last"
def value: FilterExpr = FilterExpr.StatLast
override def summary: String =
"""
|Represents the `last,:stat` line when used with the filter operation.
""".stripMargin.trim
}
case object StatCount extends StatWord {
override def name: String = "stat-count"
def value: FilterExpr = FilterExpr.StatCount
override def summary: String =
"""
|Represents the `count,:stat` line when used with the filter operation.
""".stripMargin.trim
}
case object StatTotal extends StatWord {
override def name: String = "stat-total"
def value: FilterExpr = FilterExpr.StatTotal
override def summary: String =
"""
|Represents the `total,:stat` line when used with the filter operation.
""".stripMargin.trim
}
case object Filter extends SimpleWord {
override def name: String = "filter"
protected def matcher: PartialFunction[List[Any], Boolean] = {
case TimeSeriesType(_) :: TimeSeriesType(_) :: _ => true
}
protected def executor: PartialFunction[List[Any], List[Any]] = {
case TimeSeriesType(t2) :: TimeSeriesType(t1) :: stack =>
FilterExpr.Filter(t1, rewriteStatExprs(t1, t2)) :: stack
}
private def rewriteStatExprs(t1: TimeSeriesExpr, t2: TimeSeriesExpr): TimeSeriesExpr = {
val r = t2.rewrite {
case s: FilterExpr.StatExpr => FilterExpr.Stat(t1, s.name)
}
r.asInstanceOf[TimeSeriesExpr]
}
override def signature: String = "TimeSeriesExpr TimeSeriesExpr -- FilterExpr"
override def summary: String =
"""
|Filter the output based on another expression. For example, only show lines that have
|a value greater than 50.
""".stripMargin.trim
override def examples: List[String] =
List("name,sps,:eq,:sum,(,nf.cluster,),:by,:stat-max,30e3,:gt")
}
case class PriorityK(name: String, op: (TimeSeriesExpr, String, Int) => FilterExpr)
extends SimpleWord {
protected def matcher: PartialFunction[List[Any], Boolean] = {
case IntType(_) :: (_: String) :: TimeSeriesType(_) :: _ => true
case IntType(_) :: (_: String) :: (_: StyleExpr) :: _ => true
}
protected def executor: PartialFunction[List[Any], List[Any]] = {
case IntType(k) :: (s: String) :: TimeSeriesType(t) :: stack =>
op(t, s, k) :: stack
case IntType(k) :: (s: String) :: (t: StyleExpr) :: stack =>
t.copy(expr = op(t.expr, s, k)) :: stack
}
override def signature: String = "TimeSeriesExpr stat:String k:Int -- FilterExpr"
override def summary: String =
"""
|Limit the output to the `K` time series with the highest priority values for the
|specified summary statistic.
""".stripMargin.trim
override def examples: List[String] =
List("name,sps,:eq,:sum,(,nf.cluster,),:by,max,5")
override def isStable: Boolean = false
}
}
|
copperlight/atlas
|
atlas-core/src/main/scala/com/netflix/atlas/core/model/FilterVocabulary.scala
|
Scala
|
apache-2.0
| 8,820 |
package com.outr.arango.api
import com.outr.arango.api.model._
import io.youi.client.HttpClient
import io.youi.http.HttpMethod
import io.youi.net._
import io.circe.Json
import scala.concurrent.{ExecutionContext, Future}
object APISimpleAny {
def put(client: HttpClient, body: PutAPISimpleAny)(implicit ec: ExecutionContext): Future[Json] = client
.method(HttpMethod.Put)
.path(path"/_api/simple/any", append = true)
.restful[PutAPISimpleAny, Json](body)
}
|
outr/arangodb-scala
|
api/src/main/scala/com/outr/arango/api/APISimpleAny.scala
|
Scala
|
mit
| 479 |
package zzb.datatype
import org.scalatest.{MustMatchers, WordSpec}
/**
* Created by Simon on 2014/6/19
*/
class StructXorTest extends WordSpec with MustMatchers {
import testuse.path._
import User._
val u1 = User(
name := "Simon",
age := 39,
height := 1.75F,
blood := BloodType.AB,
male := true
) <~ Car(
Car.license := "京GNR110",
Car.vin := "123456789"
)
val u2 = User(
name := "Simon",
age := 40,
height := 1.75F,
blood := BloodType.AB,
male := true
) <~ Car(
Car.license := "京GNR110",
Car.vin := "abcefg"
)
"异或操作" must {
"保留差异字段,剔除相同字段,保留必填字段" in {
val r1 = u1 xor u2
r1(name).get.value mustBe "Simon" //必填项即使相等也保留
r1(age).get.value mustBe 39 //不同项目保留左边的
r1(height) mustBe None // 相同项目被剔除
r1(car().vin()).get.value mustBe "123456789" //异或操作可以对 TStruct 类型的字段嵌套生效
r1(car().license()) mustBe None
val r2 = u2 xor u1
r2(name).get.value mustBe "Simon" //必填项即使相等也保留
r2(age).get.value mustBe 40 //不同项目保留左边的
r2(height) mustBe None // 相同项目被剔除
r2(car().vin()).get.value mustBe "abcefg"
r2(car().license()) mustBe None
}
"一个Struct包含另一个Struct" in {
val u3 = User(
name := "Simon",
age := 39,
height := 1.75F
)
val u4 = User(
name := "Simon",
age := 39,
height := 1.75F,
blood := BloodType.AB,
male := true
) <~ Car(
Car.license := "京GNR110",
Car.vin := "123456789"
)
val diff = u3.xor(u3).isOnlyRequireFields
diff mustBe true
val diff2 = u3.xor(u4).isOnlyRequireFields
diff2 mustBe false
}
}
}
|
xiefeifeihu/zzb
|
zzb-datatype/src/test/scala/zzb/datatype/StructXorTest.scala
|
Scala
|
mit
| 1,909 |
package pl.msitko.xml.printing
final case class PrinterConfig(indent: Indent,
eolAfterXmlDecl: Boolean // controls whether an end of line should be included after XML Declaration
)
object PrinterConfig {
val Default = PrinterConfig(Indent.Remain, true)
}
sealed trait Indent
object Indent {
/** Prints document "as is" - XmlPrinter will not add any extra indentation
*
* Two most probable use cases of that value:
* - when you want to preserve original formatting
* - when you want to print minimized XML - call `NodeOps.minimized` before calling XmlPrinter.print and use Remain
*
*/
case object Remain extends Indent
/** Causes each element to start in new line and intended one level more than its parent.
*
* @param singleIndent
*/
final case class IndentWith(singleIndent: String) extends Indent
}
|
note/xml-lens
|
io/shared/src/main/scala/pl/msitko/xml/printing/PrinterConfig.scala
|
Scala
|
mit
| 915 |
/*
* Copyright 2017 Georgi Krastev
*
* 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 org.apache.flink
package api.scala.derived
import api.common.typeinfo.TypeInformation
import api.scala.derived.typeinfo.MkTypeInfo
import shapeless._
/** Implicit `TypeInformation` instances. */
object auto {
/** Summons an implicit `TypeInformation` instance in scope. */
def typeInfo[A](implicit ti: TypeInformation[A]): TypeInformation[A] = ti
/**
* If type `A` is a (possibly recursive) Algebraic Data Type (ADT), automatically derives a
* `TypeInformation` instance for it.
*
* Other implicit instances in scope take higher priority except those provided by
* [[api.scala.createTypeInformation]] (the macro based approach), because it has a default
* catch-all case based on runtime reflection.
*
* @param ev Evidence that no other implicit instance of `TypeInformation[A]` is in scope.
* @param mk The derived `TypeInformation` provider (`Strict` helps avoid divergence).
* @tparam A A (possibly recursive) Algebraic Data Type (ADT).
* @return The derived `TypeInformation` instance.
*/
// Derive only when no other implicit instance is in scope.
implicit def deriveTypeInfo[A](
implicit
ev: Refute[TypeInformation[A]],
mk: Strict[MkTypeInfo[A]]
): TypeInformation[A] = mk.value()
// Shadow the default macro based TypeInformation providers.
def createTypeInformation: Nothing = ???
def createTuple2TypeInformation: Nothing = ???
}
|
joroKr21/flink-shapeless
|
src/main/scala/org/apache/flink/api/scala/derived/auto.scala
|
Scala
|
apache-2.0
| 2,016 |
/** Copyright 2015 TappingStone, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.predictionio
/** Independent library of code that is useful for engine development and
* evaluation
*/
package object e2 {}
|
alex9311/PredictionIO
|
e2/src/main/scala/org/apache/predictionio/package.scala
|
Scala
|
apache-2.0
| 762 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ml.dmlc.mxnet
import ml.dmlc.mxnet.init.Base._
import ml.dmlc.mxnet.utils.OperatorBuildUtils
import scala.annotation.StaticAnnotation
import scala.collection.mutable.ListBuffer
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
private[mxnet] class AddNDArrayFunctions(isContrib: Boolean) extends StaticAnnotation {
private[mxnet] def macroTransform(annottees: Any*) = macro NDArrayMacro.addDefs
}
private[mxnet] object NDArrayMacro {
case class NDArrayFunction(handle: NDArrayHandle)
// scalastyle:off havetype
def addDefs(c: blackbox.Context)(annottees: c.Expr[Any]*) = {
impl(c)(false, annottees: _*)
}
// scalastyle:off havetype
private val ndarrayFunctions: Map[String, NDArrayFunction] = initNDArrayModule()
private def impl(c: blackbox.Context)(addSuper: Boolean, annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
val isContrib: Boolean = c.prefix.tree match {
case q"new AddNDArrayFunctions($b)" => c.eval[Boolean](c.Expr(b))
}
val newNDArrayFunctions = {
if (isContrib) ndarrayFunctions.filter(_._1.startsWith("_contrib_"))
else ndarrayFunctions.filter(!_._1.startsWith("_contrib_"))
}
val AST_NDARRAY_TYPE = Select(Select(Select(
Ident(TermName("ml")), TermName("dmlc")), TermName("mxnet")), TypeName("NDArray"))
val AST_TYPE_MAP_STRING_ANY = AppliedTypeTree(Ident(TypeName("Map")),
List(Ident(TypeName("String")), Ident(TypeName("Any"))))
val AST_TYPE_ANY_VARARG = AppliedTypeTree(
Select(
Select(Ident(termNames.ROOTPKG), TermName("scala")),
TypeName("<repeated>")
),
List(Ident(TypeName("Any")))
)
val functionDefs = newNDArrayFunctions flatMap { case (funcName, funcProp) =>
val functionScope = {
if (isContrib) Modifiers()
else {
if (funcName.startsWith("_")) Modifiers(Flag.PRIVATE) else Modifiers()
}
}
val newName = {
if (isContrib) funcName.substring(funcName.indexOf("_contrib_") + "_contrib_".length())
else funcName
}
// It will generate definition something like,
Seq(
// def transpose(kwargs: Map[String, Any] = null)(args: Any*)
DefDef(functionScope, TermName(newName), List(),
List(
List(
ValDef(Modifiers(Flag.PARAM | Flag.DEFAULTPARAM), TermName("kwargs"),
AST_TYPE_MAP_STRING_ANY, Literal(Constant(null)))
),
List(
ValDef(Modifiers(), TermName("args"), AST_TYPE_ANY_VARARG, EmptyTree)
)
), TypeTree(),
Apply(
Ident(TermName("genericNDArrayFunctionInvoke")),
List(
Literal(Constant(funcName)),
Ident(TermName("args")),
Ident(TermName("kwargs"))
)
)
),
// def transpose(args: Any*)
DefDef(functionScope, TermName(newName), List(),
List(
List(
ValDef(Modifiers(), TermName("args"), AST_TYPE_ANY_VARARG, EmptyTree)
)
), TypeTree(),
Apply(
Ident(TermName("genericNDArrayFunctionInvoke")),
List(
Literal(Constant(funcName)),
Ident(TermName("args")),
Literal(Constant(null))
)
)
)
)
}
val inputs = annottees.map(_.tree).toList
// pattern match on the inputs
val modDefs = inputs map {
case ClassDef(mods, name, something, template) =>
val q = template match {
case Template(superMaybe, emptyValDef, defs) =>
Template(superMaybe, emptyValDef, defs ++ functionDefs)
case ex =>
throw new IllegalArgumentException(s"Invalid template: $ex")
}
ClassDef(mods, name, something, q)
case ModuleDef(mods, name, template) =>
val q = template match {
case Template(superMaybe, emptyValDef, defs) =>
Template(superMaybe, emptyValDef, defs ++ functionDefs)
case ex =>
throw new IllegalArgumentException(s"Invalid template: $ex")
}
ModuleDef(mods, name, q)
case ex =>
throw new IllegalArgumentException(s"Invalid macro input: $ex")
}
// wrap the result up in an Expr, and return it
val result = c.Expr(Block(modDefs, Literal(Constant())))
result
}
// List and add all the atomic symbol functions to current module.
private def initNDArrayModule(): Map[String, NDArrayFunction] = {
val opNames = ListBuffer.empty[String]
_LIB.mxListAllOpNames(opNames)
opNames.map(opName => {
val opHandle = new RefLong
_LIB.nnGetOpHandle(opName, opHandle)
makeNDArrayFunction(opHandle.value, opName)
}).toMap
}
// Create an atomic symbol function by handle and function name.
private def makeNDArrayFunction(handle: NDArrayHandle, aliasName: String)
: (String, NDArrayFunction) = {
val name = new RefString
val desc = new RefString
val keyVarNumArgs = new RefString
val numArgs = new RefInt
val argNames = ListBuffer.empty[String]
val argTypes = ListBuffer.empty[String]
val argDescs = ListBuffer.empty[String]
_LIB.mxSymbolGetAtomicSymbolInfo(
handle, name, desc, numArgs, argNames, argTypes, argDescs, keyVarNumArgs)
val paramStr = OperatorBuildUtils.ctypes2docstring(argNames, argTypes, argDescs)
val extraDoc: String = if (keyVarNumArgs.value != null && keyVarNumArgs.value.length > 0) {
s"This function support variable length of positional input (${keyVarNumArgs.value})."
} else {
""
}
val realName = if (aliasName == name.value) "" else s"(a.k.a., ${name.value})"
val docStr = s"$aliasName $realName\\n${desc.value}\\n\\n$paramStr\\n$extraDoc\\n"
// scalastyle:off println
if (System.getenv("MXNET4J_PRINT_OP_DEF") != null
&& System.getenv("MXNET4J_PRINT_OP_DEF").toLowerCase == "true") {
println("NDArray function definition:\\n" + docStr)
}
// scalastyle:on println
(aliasName, new NDArrayFunction(handle))
}
}
|
jiajiechen/mxnet
|
scala-package/macros/src/main/scala/ml/dmlc/mxnet/NDArrayMacro.scala
|
Scala
|
apache-2.0
| 6,956 |
/*
* Copyright 2014–2017 SlamData Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package quasar.physical.marklogic.xquery
import slamdata.Predef._
import quasar.{BackendName, Data, TestConfig}
import quasar.physical.marklogic.ErrorMessages
import quasar.physical.marklogic.fs._
import quasar.physical.marklogic.testing
import com.marklogic.xcc.ContentSource
import org.specs2.specification.core.Fragment
import scalaz._, Scalaz._, concurrent.Task
/** A base class for tests of XQuery expressions/functions. */
abstract class XQuerySpec extends quasar.Qspec {
type M[A] = EitherT[Writer[Prologs, ?], ErrorMessages, A]
/** Convenience function for expecting results, i.e. xqy must resultIn(Data._str("foo")). */
def resultIn(expected: Data) = equal(expected.right[ErrorMessages])
/** Convenience function for expecting no results. */
def resultInNothing = equal(noResults.left[Data])
def xquerySpec(desc: BackendName => String)(tests: (M[XQuery] => ErrorMessages \\/ Data) => Fragment): Unit =
TestConfig.fileSystemConfigs(FsType).flatMap(_ traverse_ { case (backend, uri, _) =>
contentSourceConnection[Task](uri).map(cs => desc(backend.name) >> tests(evaluateXQuery(cs, _))).void
}).unsafePerformSync
////
private val noResults = "No results found.".wrapNel
private def evaluateXQuery(cs: ContentSource, xqy: M[XQuery]): ErrorMessages \\/ Data = {
val (prologs, body) = xqy.run.run
val mainModule = body map (MainModule(Version.`1.0-ml`, prologs, _))
mainModule >>= (mm =>
testing.moduleResults[ReaderT[Task, ContentSource, ?]](mm)
.run(cs)
.map(_ >>= (_ \\/> noResults))
.unsafePerformSync)
}
}
|
drostron/quasar
|
marklogicIt/src/test/scala/quasar/physical/marklogic/xquery/XQuerySpec.scala
|
Scala
|
apache-2.0
| 2,207 |
package dawn.flow
trait CloseListener extends Node { self =>
def closePriority: Int = 0
def schedulerClose: Scheduler
def onScheduleClose(): Unit
override def setup() = {
super.setup()
schedulerClose.addCloseListener(self)
}
}
|
rubenfiszel/scala-flow
|
core/src/main/scala/CloseListener.scala
|
Scala
|
mit
| 247 |
package mesosphere.marathon
package core.deployment.impl
import akka.Done
import akka.actor.ActorRef
import akka.testkit.TestProbe
import akka.util.Timeout
import mesosphere.AkkaUnitTest
import mesosphere.marathon.core.condition.Condition
import mesosphere.marathon.core.deployment._
import mesosphere.marathon.core.deployment.impl.DeploymentManagerActor.DeploymentFinished
import mesosphere.marathon.core.event.InstanceChanged
import mesosphere.marathon.core.health.HealthCheckManager
import mesosphere.marathon.core.instance.{ Instance, TestInstanceBuilder }
import mesosphere.marathon.core.launchqueue.LaunchQueue
import mesosphere.marathon.core.readiness.ReadinessCheckExecutor
import mesosphere.marathon.core.task.KillServiceMock
import mesosphere.marathon.core.task.tracker.InstanceTracker
import mesosphere.marathon.state._
import mesosphere.marathon.test.GroupCreation
import org.mockito.Matchers
import org.mockito.Mockito.when
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import scala.concurrent.duration._
import scala.concurrent.{ ExecutionContext, Future, Promise }
import scala.util.Success
// TODO: this is NOT a unit test. the DeploymentActor create child actors that cannot be mocked in the current
// setup which makes the test overly complicated because events etc have to be mocked for these.
// The way forward should be to provide factories that create the child actors with a given context, or
// to use delegates that hide the implementation behind a mockable function call.
class DeploymentActorTest extends AkkaUnitTest with GroupCreation {
implicit val defaultTimeout: Timeout = 5.seconds
class Fixture {
val tracker: InstanceTracker = mock[InstanceTracker]
val queue: LaunchQueue = mock[LaunchQueue]
val killService = new KillServiceMock(system)
val scheduler: SchedulerActions = mock[SchedulerActions]
val hcManager: HealthCheckManager = mock[HealthCheckManager]
val config: DeploymentConfig = mock[DeploymentConfig]
val readinessCheckExecutor: ReadinessCheckExecutor = mock[ReadinessCheckExecutor]
config.killBatchSize returns 100
config.killBatchCycle returns 10.seconds
def instanceChanged(app: AppDefinition, condition: Condition): InstanceChanged = {
val instanceId = Instance.Id.forRunSpec(app.id)
val instance: Instance = mock[Instance]
instance.instanceId returns instanceId
InstanceChanged(instanceId, app.version, app.id, condition, instance)
}
def deploymentActor(manager: ActorRef, plan: DeploymentPlan) = system.actorOf(
DeploymentActor.props(
manager,
killService,
scheduler,
plan,
tracker,
queue,
hcManager,
system.eventStream,
readinessCheckExecutor
)
)
}
"DeploymentActor" should {
"Deploy" in new Fixture {
val managerProbe = TestProbe()
val app1 = AppDefinition(id = PathId("/foo/app1"), cmd = Some("cmd"), instances = 2)
val app2 = AppDefinition(id = PathId("/foo/app2"), cmd = Some("cmd"), instances = 1)
val app3 = AppDefinition(id = PathId("/foo/app3"), cmd = Some("cmd"), instances = 1)
val app4 = AppDefinition(id = PathId("/foo/app4"), cmd = Some("cmd"))
val origGroup = createRootGroup(groups = Set(createGroup(PathId("/foo"), Map(
app1.id -> app1,
app2.id -> app2,
app4.id -> app4))))
val version2 = VersionInfo.forNewConfig(Timestamp(1000))
val app1New = app1.copy(instances = 1, versionInfo = version2)
val app2New = app2.copy(instances = 2, cmd = Some("otherCmd"), versionInfo = version2)
val targetGroup = createRootGroup(groups = Set(createGroup(PathId("/foo"), Map(
app1New.id -> app1New,
app2New.id -> app2New,
app3.id -> app3))))
// setting started at to 0 to make sure this survives
val instance1_1 = {
val instance = TestInstanceBuilder.newBuilder(app1.id, version = app1.version).addTaskRunning(startedAt = Timestamp.zero).getInstance()
val state = instance.state.copy(condition = Condition.Running)
instance.copy(state = state)
}
val instance1_2 = {
val instance = TestInstanceBuilder.newBuilder(app1.id, version = app1.version).addTaskRunning(startedAt = Timestamp(1000)).getInstance()
val state = instance.state.copy(condition = Condition.Running)
instance.copy(state = state)
}
val instance2_1 = {
val instance = TestInstanceBuilder.newBuilder(app2.id, version = app2.version).addTaskRunning().getInstance()
val state = instance.state.copy(condition = Condition.Running)
instance.copy(state = state)
}
val instance3_1 = {
val instance = TestInstanceBuilder.newBuilder(app3.id, version = app3.version).addTaskRunning().getInstance()
val state = instance.state.copy(condition = Condition.Running)
instance.copy(state = state)
}
val instance4_1 = {
val instance = TestInstanceBuilder.newBuilder(app4.id, version = app4.version).addTaskRunning().getInstance()
val state = instance.state.copy(condition = Condition.Running)
instance.copy(state = state)
}
val plan = DeploymentPlan(origGroup, targetGroup)
queue.asyncPurge(any) returns Future.successful(Done)
scheduler.startRunSpec(any) returns Future.successful(Done)
tracker.specInstances(Matchers.eq(app1.id))(any[ExecutionContext]) returns Future.successful(Seq(instance1_1, instance1_2))
tracker.specInstancesSync(app2.id) returns Seq(instance2_1)
tracker.specInstances(Matchers.eq(app2.id))(any[ExecutionContext]) returns Future.successful(Seq(instance2_1))
tracker.specInstances(Matchers.eq(app3.id))(any[ExecutionContext]) returns Future.successful(Seq(instance3_1))
tracker.specInstances(Matchers.eq(app4.id))(any[ExecutionContext]) returns Future.successful(Seq(instance4_1))
when(queue.addAsync(same(app2New), any[Int])).thenAnswer(new Answer[Future[Done]] {
def answer(invocation: InvocationOnMock): Future[Done] = {
for (i <- 0 until invocation.getArguments()(1).asInstanceOf[Int])
system.eventStream.publish(instanceChanged(app2New, Condition.Running))
Future.successful(Done)
}
})
deploymentActor(managerProbe.ref, plan)
plan.steps.zipWithIndex.foreach {
case (step, num) => managerProbe.expectMsg(7.seconds, DeploymentStepInfo(plan, step, num + 1))
}
managerProbe.expectMsg(5.seconds, DeploymentFinished(plan, Success(Done)))
withClue(killService.killed.mkString(",")) {
killService.killed should contain(instance1_2.instanceId) // killed due to scale down
killService.killed should contain(instance2_1.instanceId) // killed due to config change
killService.killed should contain(instance4_1.instanceId) // killed because app4 does not exist anymore
killService.numKilled should be(3)
verify(queue).resetDelay(app4.copy(instances = 0))
}
}
"Restart app" in new Fixture {
val managerProbe = TestProbe()
val promise = Promise[Done]()
val app = AppDefinition(id = PathId("/foo/app1"), cmd = Some("cmd"), instances = 2)
val origGroup = createRootGroup(groups = Set(createGroup(PathId("/foo"), Map(app.id -> app))))
val version2 = VersionInfo.forNewConfig(Timestamp(1000))
val appNew = app.copy(cmd = Some("cmd new"), versionInfo = version2)
val targetGroup = createRootGroup(groups = Set(createGroup(PathId("/foo"), Map(appNew.id -> appNew))))
val instance1_1 = TestInstanceBuilder.newBuilder(app.id, version = app.version).addTaskRunning(startedAt = Timestamp.zero).getInstance()
val instance1_2 = TestInstanceBuilder.newBuilder(app.id, version = app.version).addTaskRunning(startedAt = Timestamp(1000)).getInstance()
tracker.specInstancesSync(app.id) returns Seq(instance1_1, instance1_2)
tracker.specInstances(app.id) returns Future.successful(Seq(instance1_1, instance1_2))
val plan = DeploymentPlan("foo", origGroup, targetGroup, List(DeploymentStep(List(RestartApplication(appNew)))), Timestamp.now())
queue.countAsync(appNew.id) returns Future.successful(appNew.instances)
when(queue.addAsync(same(appNew), any[Int])).thenAnswer(new Answer[Future[Done]] {
def answer(invocation: InvocationOnMock): Future[Done] = {
for (i <- 0 until invocation.getArguments()(1).asInstanceOf[Int])
system.eventStream.publish(instanceChanged(appNew, Condition.Running))
Future.successful(Done)
}
})
deploymentActor(managerProbe.ref, plan)
plan.steps.zipWithIndex.foreach {
case (step, num) => managerProbe.expectMsg(5.seconds, DeploymentStepInfo(plan, step, num + 1))
}
managerProbe.expectMsg(5.seconds, DeploymentFinished(plan, Success(Done)))
killService.killed should contain(instance1_1.instanceId)
killService.killed should contain(instance1_2.instanceId)
verify(queue).addAsync(appNew, 2)
}
"Restart suspended app" in new Fixture {
val managerProbe = TestProbe()
val app = AppDefinition(id = PathId("/foo/app1"), cmd = Some("cmd"), instances = 0)
val origGroup = createRootGroup(groups = Set(createGroup(PathId("/foo"), Map(app.id -> app))))
val version2 = VersionInfo.forNewConfig(Timestamp(1000))
val appNew = app.copy(cmd = Some("cmd new"), versionInfo = version2)
val targetGroup = createRootGroup(groups = Set(createGroup(PathId("/foo"), Map(appNew.id -> appNew))))
val plan = DeploymentPlan("foo", origGroup, targetGroup, List(DeploymentStep(List(RestartApplication(appNew)))), Timestamp.now())
tracker.specInstancesSync(app.id) returns Seq.empty[Instance]
queue.addAsync(app, 2) returns Future.successful(Done)
deploymentActor(managerProbe.ref, plan)
plan.steps.zipWithIndex.foreach {
case (step, num) => managerProbe.expectMsg(5.seconds, DeploymentStepInfo(plan, step, num + 1))
}
managerProbe.expectMsg(5.seconds, DeploymentFinished(plan, Success(Done)))
}
"Scale with tasksToKill" in new Fixture {
val managerProbe = TestProbe()
val app1 = AppDefinition(id = PathId("/foo/app1"), cmd = Some("cmd"), instances = 3)
val origGroup = createRootGroup(groups = Set(createGroup(PathId("/foo"), Map(app1.id -> app1))))
val version2 = VersionInfo.forNewConfig(Timestamp(1000))
val app1New = app1.copy(instances = 2, versionInfo = version2)
val targetGroup = createRootGroup(groups = Set(createGroup(PathId("/foo"), Map(app1New.id -> app1New))))
val instance1_1 = TestInstanceBuilder.newBuilder(app1.id, version = app1.version).addTaskRunning(startedAt = Timestamp.zero).getInstance()
val instance1_2 = TestInstanceBuilder.newBuilder(app1.id, version = app1.version).addTaskRunning(startedAt = Timestamp(500)).getInstance()
val instance1_3 = TestInstanceBuilder.newBuilder(app1.id, version = app1.version).addTaskRunning(startedAt = Timestamp(1000)).getInstance()
val plan = DeploymentPlan(original = origGroup, target = targetGroup, toKill = Map(app1.id -> Seq(instance1_2)))
tracker.specInstances(Matchers.eq(app1.id))(any[ExecutionContext]) returns Future.successful(Seq(instance1_1, instance1_2, instance1_3))
deploymentActor(managerProbe.ref, plan)
plan.steps.zipWithIndex.foreach {
case (step, num) => managerProbe.expectMsg(5.seconds, DeploymentStepInfo(plan, step, num + 1))
}
managerProbe.expectMsg(5.seconds, DeploymentFinished(plan, Success(Done)))
killService.numKilled should be(1)
killService.killed should contain(instance1_2.instanceId)
}
}
}
|
janisz/marathon
|
src/test/scala/mesosphere/marathon/core/deployment/impl/DeploymentActorTest.scala
|
Scala
|
apache-2.0
| 11,836 |
/* Copyright 2009-2018 EPFL, Lausanne */
package inox
package ast
import org.scalatest._
class ExtractorsSuite extends FunSuite {
import inox.trees._
test("Extractors do not simplify basic arithmetic") {
val e1 = Plus(Int32Literal(1), Int32Literal(1))
val e2 = e1 match {
case Operator(es, builder) => builder(es)
}
assert(e1 === e2)
val e3 = Times(Variable.fresh("x", IntegerType()), IntegerLiteral(1))
val e4 = e3 match {
case Operator(es, builder) => builder(es)
}
assert(e3 === e4)
val e5 = Plus(Int8Literal(1), Int8Literal(1))
val e6 = e5 match {
case Operator(es, builder) => builder(es)
}
assert(e5 === e6)
val size = 13
val e7 = Plus(BVLiteral(true, 1, size), BVLiteral(true, 1, size))
val e8 = e7 match {
case Operator(es, builder) => builder(es)
}
assert(e7 === e8)
}
test("Extractors do not magically change the syntax") {
val e1 = Equals(IntegerLiteral(1), IntegerLiteral(1))
val e2 = e1 match {
case Operator(es, builder) => builder(es)
}
assert(e1 === e2)
val e3 = Equals(BooleanLiteral(true), BooleanLiteral(false))
val e4 = e3 match {
case Operator(es, builder) => builder(es)
}
assert(e3 === e4)
val e5 = TupleSelect(Tuple(Seq(IntegerLiteral(1), IntegerLiteral(2))), 2)
val e6 = e5 match {
case Operator(es, builder) => builder(es)
}
assert(e5 === e6)
}
test("Extractors of map operations") {
val x = Variable.fresh("x", IntegerType())
val y = Variable.fresh("y", IntegerType())
val z = Variable.fresh("z", IntegerType())
val a1 = FiniteMap(
Seq(Int32Literal(0) -> x, Int32Literal(3) -> y, Int32Literal(5) -> z),
IntegerLiteral(10),
Int32Type(),
IntegerType())
val a2 = a1 match {
case Operator(es, builder) => {
assert(es === Seq(Int32Literal(0), x, Int32Literal(3), y, Int32Literal(5), z, IntegerLiteral(10)))
builder(es)
}
}
assert(a2 === a1)
val app1 = MapApply(a1, Int32Literal(0))
val app2 = app1 match {
case Operator(es, builder) => {
assert(es === Seq(a1, Int32Literal(0)))
builder(es)
}
}
assert(app1 === app2)
}
}
|
romac/inox
|
src/test/scala/inox/ast/ExtractorsSuite.scala
|
Scala
|
apache-2.0
| 2,253 |
package pictureshow
object Server extends Logging {
import java.net.URL
import java.net.URI
import java.io.{ File => JFile }
import unfiltered.jetty.{ Http, Server }
object Options {
/** flag for path to show */
val Show = """^-s=(.+)$""".r
/** flag for port to listen on */
val Port = """^-p=(\\d{4})$""".r
val Gist = """^-g=(.*)""".r
/** resolves env var SHOW_HOME used as a fall back path for shows */
val ShowHome = System.getenv("SHOW_HOME") match {
case null => ""
case str => str
}
/** parses options tuple (Show, Port) */
def apply(args: Array[String]) =
((".", 3000, (None: Option[URI])) /: args)({ (opts, arg) =>
arg match {
case Show(showPath) => (showPath, opts._2, opts._3)
case Port(port) => (opts._1, Integer.parseInt(port), opts._3)
case Gist(uri) => (opts._1, opts._2, tryUri(uri))
case _ => opts
}
})
/** first tries resolving path then falls back on SHOW_PATH + path */
def tryPath(path: String) = new JFile(path) match {
case f if(f.exists && f.isDirectory) => f
case _ => new JFile(ShowHome, path)
}
def tryUri(uri: String) = try {
Some(new URI(uri))
} catch {
case _ => None
}
}
def instance(args: Array[String]) = {
val (showPath, port, gist) = Options(args)
def serve[T](f: Server => T): T =
f(Http(port).context("/assets") {
_.resources(new URL(getClass.getResource("/js/show.js"), ".."))
})
gist match {
case Some(uri) =>
val p = new Projector(uri)
if(p.sections.isEmpty) Left("Empty show sections")
else {
log("starting show \\"%s\\" @ \\"%s\\" on port %s" format(p.showTitle, uri, port))
Right(serve { _.filter(p) })
}
case _ =>
val show = Options.tryPath(showPath).getCanonicalFile
if (!show.exists || !show.isDirectory) {
Left("The path `%s` is not an accessible directory" format show)
} else if (!new JFile(show, "conf.js").exists) {
Left("conf.js not found under @ `%s`." format show)
} else {
val p = new Projector(show.toURI)
if (p.sections.isEmpty) Left("Empty show sections in %s conf.js" format show)
else {
log("starting show \\"%s\\" @ \\"%s\\" on port %s" format(
p.showTitle, show, port))
Right(serve { _.resources(show.toURI.toURL).filter(p) })
}
}
}
}
def main(args: Array[String]) {
instance(args).fold({ err =>
println("instance failed!")
println(err)
System.exit(1)
}, { svr =>
svr.run(_ => ())
})
}
}
|
softprops/picture-show
|
server/src/main/scala/Server.scala
|
Scala
|
mit
| 2,724 |
/*
* Copyright 2019 HM Revenue & Customs
*
* 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.gov.hmrc.play.graphite
import java.util.concurrent.TimeUnit
import javax.inject.{Inject, Provider}
import com.codahale.metrics.MetricFilter
import com.codahale.metrics.graphite.{Graphite, GraphiteReporter}
import com.kenshoo.play.metrics.Metrics
import com.typesafe.config.ConfigException
import play.api.Configuration
case class GraphiteReporterProviderConfig(
prefix: String,
rates: Option[TimeUnit],
durations: Option[TimeUnit]
)
object GraphiteReporterProviderConfig {
def fromConfig(config: Configuration, graphiteConfiguration : Configuration): GraphiteReporterProviderConfig = {
val appName: Option[String] = config.getString("appName")
val rates: Option[TimeUnit] = graphiteConfiguration.getString("rates").map(TimeUnit.valueOf)
val durations: Option[TimeUnit] = graphiteConfiguration.getString("durations").map(TimeUnit.valueOf)
val prefix: String = graphiteConfiguration.getString("prefix")
.orElse(appName.map(name => s"tax.$name"))
.getOrElse(throw new ConfigException.Generic("`metrics.graphite.prefix` in config or `appName` as parameter required"))
GraphiteReporterProviderConfig(prefix, rates, durations)
}
}
class GraphiteReporterProvider @Inject() (
config: GraphiteReporterProviderConfig,
metrics: Metrics,
graphite: Graphite,
filter: MetricFilter
) extends Provider[GraphiteReporter] {
override def get(): GraphiteReporter =
GraphiteReporter
.forRegistry(metrics.defaultRegistry)
.prefixedWith(s"${config.prefix}.${java.net.InetAddress.getLocalHost.getHostName}")
.convertDurationsTo(config.durations.getOrElse(TimeUnit.SECONDS))
.convertRatesTo(config.rates.getOrElse(TimeUnit.MILLISECONDS))
.filter(filter)
.build(graphite)
}
|
hmrc/play-graphite
|
src/main/scala/uk/gov/hmrc/play/graphite/GraphiteReporterProvider.scala
|
Scala
|
apache-2.0
| 2,747 |
package location
import java.net.URL
import monads.FO.FutureOption
/**
* A trait that can get the URL for a game's google location
* Created by alex on 12/04/15.
*/
trait LocationService {
def location(gameId: Long): FutureOption[URL]
}
|
unclealex72/west-ham-calendar
|
app/location/LocationService.scala
|
Scala
|
apache-2.0
| 246 |
/*
Copyright 2012 Twitter, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.twitter.bijection
import java.lang.{
Short => JShort,
Integer => JInt,
Long => JLong,
Float => JFloat,
Double => JDouble,
Byte => JByte
}
import java.math.BigInteger
import java.util.UUID
trait NumericBijections extends GeneratedTupleBijections {
/**
* Bijections between the numeric types and their java versions.
*/
implicit val byte2Boxed: Bijection[Byte, JByte] =
new AbstractBijection[Byte, JByte] {
def apply(b: Byte) = JByte.valueOf(b)
override def invert(b: JByte) = b.byteValue
}
implicit val short2Boxed: Bijection[Short, JShort] =
new AbstractBijection[Short, JShort] {
def apply(s: Short) = JShort.valueOf(s)
override def invert(s: JShort) = s.shortValue
}
implicit val short2ByteByte: Bijection[Short, (Byte, Byte)] =
new AbstractBijection[Short, (Byte, Byte)] {
def apply(l: Short) = ((l >>> 8).toByte, l.toByte)
override def invert(tup: (Byte, Byte)) = {
val lowbits = tup._2.toInt & 0xff
(((tup._1 << 8) | lowbits)).toShort
}
}
implicit val int2Boxed: Bijection[Int, JInt] =
new AbstractBijection[Int, JInt] {
def apply(i: Int) = JInt.valueOf(i)
override def invert(i: JInt) = i.intValue
}
implicit val int2ShortShort: Bijection[Int, (Short, Short)] =
new AbstractBijection[Int, (Short, Short)] {
def apply(l: Int) = ((l >>> 16).toShort, l.toShort)
override def invert(tup: (Short, Short)) =
((tup._1.toInt << 16) | ((tup._2.toInt << 16) >>> 16))
}
implicit val long2Boxed: Bijection[Long, JLong] =
new AbstractBijection[Long, JLong] {
def apply(l: Long) = JLong.valueOf(l)
override def invert(l: JLong) = l.longValue
}
implicit val long2IntInt: Bijection[Long, (Int, Int)] =
new AbstractBijection[Long, (Int, Int)] {
def apply(l: Long) = ((l >>> 32).toInt, l.toInt)
override def invert(tup: (Int, Int)) =
((tup._1.toLong << 32) | ((tup._2.toLong << 32) >>> 32))
}
implicit val float2Boxed: Bijection[Float, JFloat] =
new AbstractBijection[Float, JFloat] {
def apply(f: Float) = JFloat.valueOf(f)
override def invert(f: JFloat) = f.floatValue
}
implicit val double2Boxed: Bijection[Double, JDouble] =
new AbstractBijection[Double, JDouble] {
def apply(d: Double) = JDouble.valueOf(d)
override def invert(d: JDouble) = d.doubleValue
}
val float2IntIEEE754: Bijection[Float, Int] =
new AbstractBijection[Float, Int] {
def apply(f: Float) = JFloat.floatToIntBits(f)
override def invert(i: Int) = JFloat.intBitsToFloat(i)
}
val double2LongIEEE754: Bijection[Double, Long] =
new AbstractBijection[Double, Long] {
def apply(d: Double) = JDouble.doubleToLongBits(d)
override def invert(l: Long) = JDouble.longBitsToDouble(l)
}
implicit val bigInt2BigInteger: Bijection[BigInt, BigInteger] =
new AbstractBijection[BigInt, BigInteger] {
def apply(bi: BigInt) = bi.bigInteger
override def invert(jbi: BigInteger) = new BigInt(jbi)
}
/* Other types to and from Numeric types */
implicit val uid2LongLong: Bijection[UUID, (Long, Long)] =
new AbstractBijection[UUID, (Long, Long)] { uid =>
def apply(uid: UUID) =
(uid.getMostSignificantBits, uid.getLeastSignificantBits)
override def invert(ml: (Long, Long)) = new UUID(ml._1, ml._2)
}
implicit val date2Long: Bijection[java.util.Date, Long] =
new AbstractBijection[java.util.Date, Long] {
def apply(d: java.util.Date) = d.getTime
override def invert(l: Long) = new java.util.Date(l)
}
}
|
twitter/bijection
|
bijection-core/src/main/scala/com/twitter/bijection/NumericBijections.scala
|
Scala
|
apache-2.0
| 4,206 |
object TestA {
import Macro._
foo"""abc${"123"}xyz${"456"}fgh""" // error // error // error
}
|
som-snytt/dotty
|
tests/neg-macros/i6432b/Test_2.scala
|
Scala
|
apache-2.0
| 98 |
/*
* Copyright 2016 agido GmbH
*
* 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 org.pageobject.core.driver.vnc
import java.util.concurrent.atomic.AtomicInteger
import org.openqa.selenium.net.PortProber
import org.pageobject.core.tools.Logging
import org.pageobject.core.tools.OS
import scala.sys.process.BasicIO
import scala.sys.process.Process
import scala.sys.process.ProcessLogger
private object VncServer {
val threadGroup = new ThreadGroup("VncServer")
def createProcessLogger(stdoutName: () => String, stderrName: () => String,
stdout: String => Unit, stderr: String => Unit): ProcessLogger = {
new ProcessLogger {
def out(s: => String): Unit = {
Thread.currentThread().setName(stdoutName())
stdout(s)
}
def err(s: => String): Unit = {
Thread.currentThread().setName(stderrName())
stderr(s)
}
def buffer[T](f: => T): T = f
}
}
}
/**
* trait to start and stop a VNC Server instance.
*/
trait VncServer extends Logging {
protected def startCommand: Option[String]
protected def checkCommand: Option[String]
protected def stopCommand: Option[String]
protected def onTerminated: Boolean => Unit
protected def id: Int
protected val processLogger: ProcessLogger =
VncServer.createProcessLogger(() => stdoutName(), () => stderrName(),
message => if (log(message)) {
logStdOut(message)
}, message => if (log(message)) {
logStdErr(message)
})
private val traceMessages = Set(
"Executing: ",
"Done: "
)
protected def isTraceMessage(message: String): Boolean = {
traceMessages.exists(m => message.contains(m))
}
protected def logStdOut(message: String): Unit = {
if (isTraceMessage(message)) {
trace(message)
} else {
debug(message)
}
}
protected def logStdErr(message: String): Unit = error(message)
protected def log(message: String): Boolean = true
protected def execute(cmd: String, extraEnv: (String, String)*): Process = {
Process(cmd, None, extraEnv: _*).run(BasicIO(withIn = false, processLogger).daemonized)
}
protected def extraEnv: Seq[(String, String)] = Seq()
def name: String = s"VNC :$id"
def stdoutName(): String = s"$name STDOUT"
def stderrName(): String = s"$name STDERR"
def shutdown(): Unit = {
stopCommand.foreach(execute(_))
}
def checkConnection(): Boolean = {
checkCommand.forall(execute(_).exitValue == 0)
}
def start(): Unit = startCommand match {
case Some(command) =>
val process = execute(command, extraEnv: _*)
val thread = new Thread(VncServer.threadGroup, new Runnable {
override def run(): Unit = {
onTerminated(process.exitValue() != 127)
}
})
thread.setName(s"VncServerThread-$id")
thread.setDaemon(true)
thread.start()
case _ =>
}
}
/**
* You can configure the port range used by VNC,
* the default is to use ports from one upwards.
*/
object CountedId {
private val idCounter = new AtomicInteger
}
trait CountedId {
this: VncServer =>
val id = CountedId.idCounter.incrementAndGet()
}
/**
* A trait providing the URL used to connect to selenium running inside of the VNC Server.
*/
trait SeleniumVncServer extends VncServer {
def seleniumPort: Int
protected def seleniumScript: Option[String] = sys.env.get("PAGEOBJECT_SELENIUM_SCRIPT").orElse(None match {
case _ if OS.isOSX => Some("selenium/osx.sh")
case _ if OS.isWindows => Some("selenium/win.bat")
case _ if OS.isLinux => Some("selenium/linux.sh")
})
protected def seleniumCommand: Option[String] = seleniumScript.map(script => s"$script -port $seleniumPort")
protected override def extraEnv = seleniumCommand.map(command => Seq("SELENIUM_COMMAND" -> command)).getOrElse(Seq())
protected def seleniumProto: String = sys.env.getOrElse("PAGEOBJECT_SELENIUM_PROTO", "http")
protected def seleniumHost: String = sys.env.getOrElse("PAGEOBJECT_SELENIUM_HOST", "localhost")
lazy val url = s"$seleniumProto://$seleniumHost:$seleniumPort/wd/hub"
}
/**
* Tries to find an unused port for selenium server.
*/
trait FindFreeSeleniumPort {
this: SeleniumVncServer =>
val seleniumPort: Int = PortProber.findFreePort()
}
/**
* The default selenium port is just a fixed offset added to the display id
*
* This can cause problems when running multiple tests in different VMs.
* The selenium server started by another process using the same port may be used because
* there is no way to detect if selenium is already running or to decide if it was started by another VM
* trying to use the same port.
*
* This can be fixed by monitoring the output stream of vnc.sh but it is easier to just use random port numbers.
*/
trait FixedSeleniumPort {
this: SeleniumVncServer =>
val seleniumPortOffset: Int = 14000
val seleniumPort: Int = id + seleniumPortOffset
}
|
agido/pageobject
|
core/src/main/scala/org/pageobject/core/driver/vnc/VncServer.scala
|
Scala
|
apache-2.0
| 5,460 |
package de.leanovate.swaggercheck.fixtures.model
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.Json
case class ThingList(
things: Seq[Thing]
)
object ThingList {
implicit val jsonFormat = Json.format[ThingList]
implicit val arbitrary = Arbitrary(for {
things <- Gen.listOf(Arbitrary.arbitrary[Thing])
} yield ThingList(things))
}
|
leanovate/swagger-check
|
swagger-check-core/src/test/scala/de/leanovate/swaggercheck/fixtures/model/ThingList.scala
|
Scala
|
mit
| 406 |
package fr.acinq.eclair.db.migration
import fr.acinq.eclair.db.migration.CompareDb._
import scodec.bits.ByteVector
import java.sql.{Connection, ResultSet}
object CompareNetworkDb {
private def compareNodesTable(conn1: Connection, conn2: Connection): Boolean = {
val table1 = "nodes"
val table2 = "network.nodes"
def hash1(rs: ResultSet): ByteVector = {
bytes(rs, "node_id") ++
bytes(rs, "data")
}
def hash2(rs: ResultSet): ByteVector = {
hex(rs, "node_id") ++
bytes(rs, "data")
}
compareTable(conn1, conn2, table1, table2, hash1, hash2)
}
private def compareChannelsTable(conn1: Connection, conn2: Connection): Boolean = {
val table1 = "channels"
val table2 = "network.public_channels"
def hash1(rs: ResultSet): ByteVector = {
long(rs, "short_channel_id") ++
string(rs, "txid") ++
bytes(rs, "channel_announcement") ++
long(rs, "capacity_sat") ++
bytesnull(rs, "channel_update_1") ++
bytesnull(rs, "channel_update_2")
}
def hash2(rs: ResultSet): ByteVector = {
long(rs, "short_channel_id") ++
string(rs, "txid") ++
bytes(rs, "channel_announcement") ++
long(rs, "capacity_sat") ++
bytesnull(rs, "channel_update_1") ++
bytesnull(rs, "channel_update_2")
}
compareTable(conn1, conn2, table1, table2, hash1, hash2)
}
private def comparePrunedTable(conn1: Connection, conn2: Connection): Boolean = {
val table1 = "pruned"
val table2 = "network.pruned_channels"
def hash1(rs: ResultSet): ByteVector = {
long(rs, "short_channel_id")
}
def hash2(rs: ResultSet): ByteVector = {
long(rs, "short_channel_id")
}
compareTable(conn1, conn2, table1, table2, hash1, hash2)
}
def compareAllTables(conn1: Connection, conn2: Connection): Boolean = {
compareNodesTable(conn1, conn2) &&
compareChannelsTable(conn1, conn2) &&
comparePrunedTable(conn1, conn2)
}
}
|
ACINQ/eclair
|
eclair-core/src/main/scala/fr/acinq/eclair/db/migration/CompareNetworkDb.scala
|
Scala
|
apache-2.0
| 2,004 |
/*
* =========================================================================================
* Copyright © 2015 the khronus project <https://github.com/hotels-tech/khronus>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
* =========================================================================================
*/
package com.searchlight.khronus.influx.parser
import com.searchlight.khronus.model._
import org.scalatest.FunSuite
import org.scalatest.Matchers
import java.util.concurrent.TimeUnit
import scala.concurrent.duration._
import scala.Some
import scala.concurrent.{ Await, Future }
import com.searchlight.khronus.store.MetaStore
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._
class InfluxQueryParserSpec extends FunSuite with Matchers with MockitoSugar {
// TODO - Where con soporte para expresiones regulares: =~ matches against, !~ doesn’t match against
implicit val context = scala.concurrent.ExecutionContext.Implicits.global
val metricName = "metricA"
def buildParser = new InfluxQueryParser() {
override val metaStore: MetaStore = mock[MetaStore]
}
test("basic Influx query should be parsed ok") {
val parser = buildParser
val metricName = """metric:A\\12:3"""
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select count(value) from "$metricName" as aliasTable group by time(2h)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyField(influxCriteria.projections(0), Functions.Count, None, Some("aliasTable"))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, Some("aliasTable"))
verifyGroupBy(influxCriteria.groupBy, 2, TimeUnit.HOURS)
influxCriteria.filters should be(Nil)
influxCriteria.fillValue should be(None)
influxCriteria.limit should be(Int.MaxValue)
}
test("select with many projections should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select x.mean, x.max as maxValue, min(value) from "$metricName" as x group by time(2h)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
influxCriteria.projections.size should be(3)
verifyField(influxCriteria.projections(0), Functions.Mean, None, Some("x"))
verifyField(influxCriteria.projections(1), Functions.Max, Some("maxValue"), Some("x"))
verifyField(influxCriteria.projections(2), Functions.Min, None, Some("x"))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, Some("x"))
verifyGroupBy(influxCriteria.groupBy, 2, TimeUnit.HOURS)
influxCriteria.filters should be(Nil)
influxCriteria.limit should be(Int.MaxValue)
}
test("select * for a timer should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select aliasTimer.* from "$metricName" as aliasTimer group by time (30s)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
influxCriteria.projections.size should be(11)
val sortedProjections = influxCriteria.projections.sortBy(_.asInstanceOf[Field].name)
verifyField(sortedProjections(0), Functions.Count, None, Some("aliasTimer"))
verifyField(sortedProjections(1), Functions.Cpm, None, Some("aliasTimer"))
verifyField(sortedProjections(2), Functions.Max, None, Some("aliasTimer"))
verifyField(sortedProjections(3), Functions.Mean, None, Some("aliasTimer"))
verifyField(sortedProjections(4), Functions.Min, None, Some("aliasTimer"))
verifyField(sortedProjections(5), Functions.Percentile50, None, Some("aliasTimer"))
verifyField(sortedProjections(6), Functions.Percentile80, None, Some("aliasTimer"))
verifyField(sortedProjections(7), Functions.Percentile90, None, Some("aliasTimer"))
verifyField(sortedProjections(8), Functions.Percentile95, None, Some("aliasTimer"))
verifyField(sortedProjections(9), Functions.Percentile99, None, Some("aliasTimer"))
verifyField(sortedProjections(10), Functions.Percentile999, None, Some("aliasTimer"))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, Some("aliasTimer"))
verifyGroupBy(influxCriteria.groupBy, 30, TimeUnit.SECONDS)
influxCriteria.filters should be(Nil)
influxCriteria.limit should be(Int.MaxValue)
}
test("select * for a counter should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Counter)))
val query = s"""select * from "$metricName" as aliasCounter group by time (30s)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
influxCriteria.projections.size should be(2)
verifyField(influxCriteria.projections(0), Functions.Count, None, Some("aliasCounter"))
verifyField(influxCriteria.projections(1), Functions.Cpm, None, Some("aliasCounter"))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, Some("aliasCounter"))
verifyGroupBy(influxCriteria.groupBy, 30, TimeUnit.SECONDS)
influxCriteria.filters should be(Nil)
influxCriteria.limit should be(Int.MaxValue)
}
test("Select fields for a timer should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val queryMax = s"""select max, min, mean, count, p50, p80, p90, p95, p99, p999 from "$metricName" group by time(1m)"""
val projections = await(parser.parse(queryMax)).projections
verifyField(projections(0), Functions.Max, None, Some(s"$metricName"))
verifyField(projections(1), Functions.Min, None, Some(s"$metricName"))
verifyField(projections(2), Functions.Mean, None, Some(s"$metricName"))
verifyField(projections(3), Functions.Count, None, Some(s"$metricName"))
verifyField(projections(4), Functions.Percentile50, None, Some(s"$metricName"))
verifyField(projections(5), Functions.Percentile80, None, Some(s"$metricName"))
verifyField(projections(6), Functions.Percentile90, None, Some(s"$metricName"))
verifyField(projections(7), Functions.Percentile95, None, Some(s"$metricName"))
verifyField(projections(8), Functions.Percentile99, None, Some(s"$metricName"))
verifyField(projections(9), Functions.Percentile999, None, Some(s"$metricName"))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
}
test("Select fields for a counter should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Counter)))
val queryCounter = s"""select count(value) from "$metricName" group by time(1m)"""
val resultedFieldCounter = await(parser.parse(queryCounter)).projections(0)
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyField(resultedFieldCounter, Functions.Count, None, Some(s"$metricName"))
}
test("All Percentiles function should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val queryAllPercentiles = s"""select percentiles from "$metricName" group by time(30s)"""
val projections = await(parser.parse(queryAllPercentiles)).projections.sortBy(_.asInstanceOf[Field].name)
verify(parser.metaStore).searchInSnapshotByRegex(regex)
projections.size should be(6)
verifyField(projections(0), Functions.Percentile50, None, Some(s"$metricName"))
verifyField(projections(1), Functions.Percentile80, None, Some(s"$metricName"))
verifyField(projections(2), Functions.Percentile90, None, Some(s"$metricName"))
verifyField(projections(3), Functions.Percentile95, None, Some(s"$metricName"))
verifyField(projections(4), Functions.Percentile99, None, Some(s"$metricName"))
verifyField(projections(5), Functions.Percentile999, None, Some(s"$metricName"))
}
test("Some Percentiles function should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val queryPercentiles = s"""select percentiles(80 99 50) from "$metricName" group by time(30s)"""
val projections = await(parser.parse(queryPercentiles)).projections
verify(parser.metaStore).searchInSnapshotByRegex(regex)
projections.size should be(3)
verifyField(projections(0), Functions.Percentile80, None, Some(s"$metricName"))
verifyField(projections(1), Functions.Percentile99, None, Some(s"$metricName"))
verifyField(projections(2), Functions.Percentile50, None, Some(s"$metricName"))
}
test("Counts per minute function should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val queryPercentiles = s"""select cpm from "$metricName" group by time(5m)"""
val projections = await(parser.parse(queryPercentiles)).projections
verify(parser.metaStore).searchInSnapshotByRegex(regex)
projections.size should be(1)
verifyField(projections(0), Functions.Cpm, None, Some(s"$metricName"))
}
test("Projecting operations from single metric should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val queryMax = s"""select x.p50 + 90 as op1, x.max - x.min as op2, 35 * x.mean as op3, 3 / 4 as op4 from "$metricName" as x group by time(1m)"""
val projections = await(parser.parse(queryMax)).projections
val firstOperation = projections(0).asInstanceOf[Operation]
verifyField(firstOperation.left, Functions.Percentile50, None, Some("x"))
firstOperation.operator should be(MathOperators.Plus)
firstOperation.right.asInstanceOf[Number].value should be(90L)
firstOperation.alias should be("op1")
val secondOperation = projections(1).asInstanceOf[Operation]
verifyField(secondOperation.left, Functions.Max, None, Some("x"))
secondOperation.operator should be(MathOperators.Minus)
verifyField(secondOperation.right, Functions.Min, None, Some("x"))
secondOperation.alias should be("op2")
val thirdOperation = projections(2).asInstanceOf[Operation]
thirdOperation.left.asInstanceOf[Number].value should be(35L)
thirdOperation.operator should be(MathOperators.Multiply)
verifyField(thirdOperation.right, Functions.Mean, None, Some("x"))
thirdOperation.alias should be("op3")
val fourthOperation = projections(3).asInstanceOf[Operation]
fourthOperation.left.asInstanceOf[Number].value should be(3L)
fourthOperation.operator should be(MathOperators.Divide)
fourthOperation.right.asInstanceOf[Number].value should be(4L)
fourthOperation.alias should be("op4")
verify(parser.metaStore).searchInSnapshotByRegex(regex)
}
test("Projecting operations from different metrics should be parsed ok") {
val parser = buildParser
val timerMetric1 = "timer-1"
val timerMetric2 = "timer-2"
val regexTimer1 = parser.getCaseInsensitiveRegex(timerMetric1)
val regexTimer2 = parser.getCaseInsensitiveRegex(timerMetric2)
when(parser.metaStore.searchInSnapshotByRegex(regexTimer1)).thenReturn(Seq(Metric(timerMetric1, MetricType.Timer)))
when(parser.metaStore.searchInSnapshotByRegex(regexTimer2)).thenReturn(Seq(Metric(timerMetric2, MetricType.Timer)))
val queryMax = s"""select x.max + y.min as operation from "$timerMetric1" as x, "$timerMetric2" as y group by time(1m)"""
val projections = await(parser.parse(queryMax)).projections
val operation = projections(0).asInstanceOf[Operation]
operation.operator should be(MathOperators.Plus)
operation.alias should be("operation")
verifyField(operation.left, Functions.Max, None, Some("x"))
verifyField(operation.right, Functions.Min, None, Some("y"))
verify(parser.metaStore).searchInSnapshotByRegex(regexTimer1)
verify(parser.metaStore).searchInSnapshotByRegex(regexTimer2)
}
test("Query with scalar projection should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val queryScalar = s"""select 1 as positiveValue, -3 as negativeValue, 12.56 as decimalValue from "$metricName" group by time(30s)"""
val projections = await(parser.parse(queryScalar)).projections
val number1 = projections(0).asInstanceOf[Number]
number1.value should be(1L)
number1.alias should be(Some("positiveValue"))
val number2 = projections(1).asInstanceOf[Number]
number2.value should be(-3L)
number2.alias should be(Some("negativeValue"))
val number3 = projections(2).asInstanceOf[Number]
number3.value should be(12.56)
number3.alias should be(Some("decimalValue"))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
}
test("Select from regex matching some metrics should be parsed ok") {
val parser = buildParser
val counterCommonName = "Counter"
val counter1 = s"$counterCommonName-1"
val counter2 = s"$counterCommonName-2"
val regexCommon = s".*$counterCommonName.*"
val regex = parser.getCaseInsensitiveRegex(regexCommon)
val metrics = Seq(Metric(counter1, MetricType.Counter), Metric(counter2, MetricType.Counter))
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(metrics)
val queryRegex = s"""select * from "$regexCommon" group by time(30s)"""
val influxCriteria = await(parser.parse(queryRegex))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
influxCriteria.projections.size should be(4)
verifyField(influxCriteria.projections(0), Functions.Count, None, Some(counter1))
verifyField(influxCriteria.projections(1), Functions.Cpm, None, Some(counter1))
verifyField(influxCriteria.projections(2), Functions.Count, None, Some(counter2))
verifyField(influxCriteria.projections(3), Functions.Cpm, None, Some(counter2))
influxCriteria.sources.size should be(2)
verifySource(influxCriteria.sources(0), counter1, None)
verifySource(influxCriteria.sources(1), counter2, None)
}
test("Select with many regex should be parsed ok") {
val parser = buildParser
val counterCommonName = "Counter"
val counter1 = s"$counterCommonName-1"
val counter2 = s"$counterCommonName-2"
val regexCounterCommon = s".*$counterCommonName.*"
val regexCounter = parser.getCaseInsensitiveRegex(regexCounterCommon)
val timerCommonName = "Timer"
val timer1 = s"$timerCommonName-1"
val timer2 = s"$timerCommonName-2"
val regexTimerCommon = s".*$timerCommonName.*"
val regexTimer = parser.getCaseInsensitiveRegex(regexTimerCommon)
val counters = Seq(Metric(counter1, MetricType.Counter), Metric(counter2, MetricType.Counter))
when(parser.metaStore.searchInSnapshotByRegex(regexCounter)).thenReturn(counters)
val timers = Seq(Metric(timer1, MetricType.Timer), Metric(timer2, MetricType.Timer))
when(parser.metaStore.searchInSnapshotByRegex(regexTimer)).thenReturn(timers)
val queryRegex = s"""select count from "$regexCounterCommon", "$regexTimerCommon" group by time(30s)"""
val influxCriteria = await(parser.parse(queryRegex))
verify(parser.metaStore).searchInSnapshotByRegex(regexCounter)
verify(parser.metaStore).searchInSnapshotByRegex(regexTimer)
influxCriteria.projections.size should be(4)
verifyField(influxCriteria.projections(0), Functions.Count, None, Some(counter1))
verifyField(influxCriteria.projections(1), Functions.Count, None, Some(counter2))
verifyField(influxCriteria.projections(2), Functions.Count, None, Some(timer1))
verifyField(influxCriteria.projections(3), Functions.Count, None, Some(timer2))
influxCriteria.sources.size should be(4)
verifySource(influxCriteria.sources(0), counter1, None)
verifySource(influxCriteria.sources(1), counter2, None)
verifySource(influxCriteria.sources(2), timer1, None)
verifySource(influxCriteria.sources(3), timer2, None)
}
test("Where clause should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select count(value) from "$metricName" where host = 'aHost' group by time(5m)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyField(influxCriteria.projections(0), Functions.Count, None, Some(metricName))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, None)
val stringFilter = influxCriteria.filters(0).asInstanceOf[StringFilter]
stringFilter.identifier should be("host")
stringFilter.operator should be(Operators.Eq)
stringFilter.value should be("aHost")
verifyGroupBy(influxCriteria.groupBy, 5, TimeUnit.MINUTES)
influxCriteria.limit should be(Int.MaxValue)
}
test("Where clause with and should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select max(value) from "$metricName" where time >= 1414508614 and time < 1414509500 group by time(5m)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyField(influxCriteria.projections(0), Functions.Max, None, Some(metricName))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, None)
verifyTimeFilter(influxCriteria.filters(0), "time", Operators.Gte, 1414508614L)
verifyTimeFilter(influxCriteria.filters(1), "time", Operators.Lt, 1414509500L)
verifyGroupBy(influxCriteria.groupBy, 5, TimeUnit.MINUTES)
influxCriteria.limit should be(Int.MaxValue)
}
test("Where clause with time suffix should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select min(value) from "$metricName" where time >= 1414508614s group by time(30s)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyTimeFilter(influxCriteria.filters(0), "time", Operators.Gte, 1414508614000L)
}
test("Where clauses like (now - 1h) should be parsed ok") {
val mockedNow = 1414767928000L
val mockedParser = new InfluxQueryParser() {
override val metaStore: MetaStore = mock[MetaStore]
override def now: Long = mockedNow
}
val regex = mockedParser.getCaseInsensitiveRegex(metricName)
when(mockedParser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val criteriaNow = await(mockedParser.parse(s"""select mean(value) from "$metricName" where time > now() group by time(5m)"""))
verifyTimeFilter(criteriaNow.filters(0), "time", Operators.Gt, mockedNow)
val criteriaNow20s = await(mockedParser.parse(s"""select mean(value) from "$metricName" where time < now() - 20s group by time(5m)"""))
verifyTimeFilter(criteriaNow20s.filters(0), "time", Operators.Lt, mockedNow - TimeUnit.SECONDS.toMillis(20))
val criteriaNow5m = await(mockedParser.parse(s"""select mean(value) from "$metricName" where time <= now() - 5m group by time(5m)"""))
verifyTimeFilter(criteriaNow5m.filters(0), "time", Operators.Lte, mockedNow - TimeUnit.MINUTES.toMillis(5))
val criteriaNow3h = await(mockedParser.parse(s"""select mean(value) from "$metricName" where time >= now() - 3h group by time(5m)"""))
verifyTimeFilter(criteriaNow3h.filters(0), "time", Operators.Gte, mockedNow - TimeUnit.HOURS.toMillis(3))
val criteriaNow10d = await(mockedParser.parse(s"""select mean(value) from "$metricName" where time >= now() - 10d group by time(5m)"""))
verifyTimeFilter(criteriaNow10d.filters(0), "time", Operators.Gte, mockedNow - TimeUnit.DAYS.toMillis(10))
val criteriaNow2w = await(mockedParser.parse(s"""select mean(value) from "$metricName" where time <= now() - 2w group by time(5m)"""))
verifyTimeFilter(criteriaNow2w.filters(0), "time", Operators.Lte, mockedNow - TimeUnit.DAYS.toMillis(14))
verify(mockedParser.metaStore, times(6)).searchInSnapshotByRegex(regex)
}
test("Between clause should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select max(value) from "$metricName" where time between 1414508614 and 1414509500s group by time(2h)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyField(influxCriteria.projections(0), Functions.Max, None, Some(metricName))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, None)
verifyTimeFilter(influxCriteria.filters(0), "time", Operators.Gte, 1414508614L)
verifyTimeFilter(influxCriteria.filters(1), "time", Operators.Lte, 1414509500000L)
verifyGroupBy(influxCriteria.groupBy, 2, TimeUnit.HOURS)
influxCriteria.limit should be(Int.MaxValue)
}
test("Group by clause by any windows should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
// Configured windows should be parsed ok
val influxCriteriaResult30s = await(parser.parse(s"""select count(value) as counter from "$metricName" force group by time(30s)"""))
verifyGroupBy(influxCriteriaResult30s.groupBy, 30, TimeUnit.SECONDS, true)
val influxCriteriaResult1m = await(parser.parse(s"""select min(value) as counter from "$metricName" group by time(1m)"""))
verifyGroupBy(influxCriteriaResult1m.groupBy, 1, TimeUnit.MINUTES)
// Unconfigured window should be parsed ok
val influxCriteriaResult13s = await(parser.parse(s"""select count from "$metricName" group by time(13s)"""))
verifyGroupBy(influxCriteriaResult13s.groupBy, 13, TimeUnit.SECONDS)
// Decimal windows should be truncated
val influxCriteriaResultDecimal = await(parser.parse(s"""select count from "$metricName" group by time(0.1s)"""))
verifyGroupBy(influxCriteriaResultDecimal.groupBy, 0, TimeUnit.SECONDS)
verify(parser.metaStore, times(4)).searchInSnapshotByRegex(regex)
}
test("select with fill option should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select mean from "$metricName" group by time(1m) fill(999)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyField(influxCriteria.projections(0), Functions.Mean, None, Some(metricName))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, None)
verifyGroupBy(influxCriteria.groupBy, 1, TimeUnit.MINUTES)
influxCriteria.fillValue should be(Some(999))
}
test("Limit clause should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select p50(value) from "$metricName" group by time(1m) limit 10"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyField(influxCriteria.projections(0), Functions.Percentile50, None, Some(metricName))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, None)
verifyGroupBy(influxCriteria.groupBy, 1, TimeUnit.MINUTES)
influxCriteria.filters should be(Nil)
influxCriteria.limit should be(10)
}
test("Scale should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select max(value) from "$metricName" group by time(1m) scale(-0.2)"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyField(influxCriteria.projections(0), Functions.Max, None, Some(metricName))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, None)
verifyGroupBy(influxCriteria.groupBy, 1, TimeUnit.MINUTES)
influxCriteria.filters should be(Nil)
influxCriteria.scale should be(Some(-0.2))
}
test("Order clause should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val influxCriteriaAsc = await(parser.parse(s"""select p80(value) from "$metricName" group by time(1m) order asc"""))
influxCriteriaAsc.orderAsc should be(true)
val influxCriteriaDesc = await(parser.parse(s"""select p90(value) from "$metricName" group by time(1m) order desc"""))
influxCriteriaDesc.orderAsc should be(false)
verify(parser.metaStore, times(2)).searchInSnapshotByRegex(regex)
}
test("Full Influx query should be parsed ok") {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metricName, MetricType.Timer)))
val query = s"""select count(value) as counter from "$metricName" where time > 1000 and time <= 5000 and host <> 'aHost' group by time(30s) limit 550 order desc;"""
val influxCriteria = await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
verifyField(influxCriteria.projections(0), Functions.Count, Some("counter"), Some(metricName))
influxCriteria.sources.size should be(1)
verifySource(influxCriteria.sources(0), metricName, None)
verifyTimeFilter(influxCriteria.filters(0), "time", Operators.Gt, 1000L)
verifyTimeFilter(influxCriteria.filters(1), "time", Operators.Lte, 5000L)
val filter3 = influxCriteria.filters(2).asInstanceOf[StringFilter]
filter3.identifier should be("host")
filter3.operator should be(Operators.Neq)
filter3.value should be("aHost")
verifyGroupBy(influxCriteria.groupBy, 30, TimeUnit.SECONDS)
influxCriteria.limit should be(550)
influxCriteria.orderAsc should be(false)
}
test("Search for an inexistent metric throws exception") {
val parser = buildParser
val metricName = "inexistentMetric"
val regex = parser.getCaseInsensitiveRegex(metricName)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq.empty[Metric])
intercept[UnsupportedOperationException] {
await(parser.parse(s"""select * from "$metricName" group by time (30s)"""))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
}
}
test("Query without projection should fail") {
intercept[UnsupportedOperationException] { buildParser.parse(s"""select from "$metricName"""") }
}
test("Query without from clause should fail") {
intercept[UnsupportedOperationException] { buildParser.parse("select max(value) ") }
}
test("Query without table should fail") {
intercept[UnsupportedOperationException] { buildParser.parse("select max(value) from") }
}
test("Query using a table alias that dont exist should fail") {
intercept[UnsupportedOperationException] { buildParser.parse(s"""select a.max from "$metricName" group by time (30s)""") }
}
test("Query with unclosed string literal should fail") {
intercept[UnsupportedOperationException] { buildParser.parse(s"""select max(value) from "$metricName" where host = 'host""") }
}
test("Query with unclosed parenthesis should fail") {
intercept[UnsupportedOperationException] { buildParser.parse(s"""select max(value) from "$metricName" group by time(30s""") }
}
test("Query with invalid time now expression should fail") {
intercept[UnsupportedOperationException] { buildParser.parse(s"""select max(value) from "$metricName" where time > now() - 1j group by time(30s)""") }
}
test("Select * with other projection should fail") {
intercept[UnsupportedOperationException] { buildParser.parse(s"""select * max from "$metricName" group by time(30s)""") }
}
test("Select an invalid field for a counter should fail") {
verifyQueryFail(metricName, s"""select max(value) from "$metricName" group by time(30s)""", MetricType.Counter)
}
test("Select an invalid operator should fail") {
verifyQueryFail(metricName, s"""select max(value) & 3 from "$metricName" group by time(30s)""", MetricType.Timer)
}
test("Select with operation without operator should fail") {
verifyQueryFail(metricName, s"""select max 3 from "$metricName" group by time(30s)""", MetricType.Timer)
}
test("Select with unknown order should fail") {
verifyQueryFail(metricName, s"""select * from "$metricName" group by time(30s) order inexistentOrder""")
}
test("Select with invalid percentile function should fail") {
intercept[UnsupportedOperationException] { buildParser.parse(s"""select percentiles(12) from "$metricName" group by time(30s)""") }
}
test("Repeting table alias should fail") {
verifyQueryFail(metricName, s"""select * from "$metricName" as x, "$metricName" as x group by time(30s)""")
}
test("Projection using inexistent table alias should fail") {
verifyQueryFail(metricName, s"""select y.count from "$metricName" as x group by time(30s)""")
}
test("Operation using inexistent table alias should fail") {
verifyQueryFail(metricName, s"""select y.count + x.max as operation from "$metricName" as x group by time(30s)""")
verifyQueryFail(metricName, s"""select x.count + y.max as operation from "$metricName" as x group by time(30s)""")
}
private def verifyQueryFail(metric: String, query: String, metricType: String = MetricType.Timer) = {
val parser = buildParser
val regex = parser.getCaseInsensitiveRegex(metric)
when(parser.metaStore.searchInSnapshotByRegex(regex)).thenReturn(Seq(Metric(metric, metricType)))
intercept[UnsupportedOperationException] {
await(parser.parse(query))
verify(parser.metaStore).searchInSnapshotByRegex(regex)
}
}
private def verifyField(projection: Projection, expectedFunction: Functions.Function, expectedFieldAlias: Option[String], expectedTableAlias: Option[String]) = {
projection.asInstanceOf[Field].name should be(expectedFunction.name)
projection.asInstanceOf[Field].alias should be(expectedFieldAlias)
projection.asInstanceOf[Field].tableId should be(expectedTableAlias)
}
private def verifySource(source: Source, expectedMetricName: String, expectedTableAlias: Option[String]) = {
source.metric.name should be(expectedMetricName)
source.alias should be(expectedTableAlias)
}
private def verifyTimeFilter(filter: Filter, expectedIdentifier: String, expectedOperator: String, millis: Long) = {
val timeFilter = filter.asInstanceOf[TimeFilter]
timeFilter.identifier should be(expectedIdentifier)
timeFilter.operator should be(expectedOperator)
timeFilter.value should be(millis)
}
private def verifyGroupBy(groupBy: GroupBy, expectedDurationLength: Int, expectedDurationUnit: TimeUnit, expectedForced: Boolean = false) = {
groupBy.duration.length should be(expectedDurationLength)
groupBy.duration.unit should be(expectedDurationUnit)
groupBy.forceResolution should be(expectedForced)
}
private def await[T](f: ⇒ Future[T]): T = Await.result(f, 10 seconds)
}
|
despegar/khronus
|
khronus-influx-api/src/test/scala/com/searchlight/khronus/influx/parser/InfluxQueryParserSpec.scala
|
Scala
|
apache-2.0
| 34,096 |
package com.twitter.zipkin.storage.redis
import com.google.common.base.Charsets._
import com.twitter.finagle.redis.Client
import com.twitter.scrooge.BinaryThriftStructSerializer
import com.twitter.util.{Duration, Future}
import com.twitter.zipkin.common.Span
import com.twitter.zipkin.conversions.thrift.{ThriftSpan, WrappedSpan}
import com.twitter.zipkin.storage.Storage
import com.twitter.zipkin.thriftscala
import org.jboss.netty.buffer.ChannelBuffers._
import org.jboss.netty.buffer.{ChannelBuffer, ChannelBuffers}
/**
* @param client the redis client to use
* @param defaultTtl expires keys older than this many seconds.
*/
class RedisStorage(
val client: Client,
val defaultTtl: Option[Duration]
) extends Storage with ExpirationSupport {
private val serializer = new BinaryThriftStructSerializer[thriftscala.Span] {
def codec = thriftscala.Span
}
private def encodeTraceId(traceId: Long) = copiedBuffer("full_span:" + traceId, UTF_8)
override def close() = client.release()
override def storeSpan(span: Span): Future[Unit] = {
val redisKey = encodeTraceId(span.traceId)
val thrift = new ThriftSpan(span).toThrift
val buf = ChannelBuffers.copiedBuffer(serializer.toBytes(thrift))
client.lPush(redisKey, List(buf)).flatMap(_ => expireOnTtl(redisKey))
}
override def setTimeToLive(traceId: Long, ttl: Duration): Future[Unit] =
expireOnTtl(encodeTraceId(traceId), Some(ttl))
override def getTimeToLive(traceId: Long): Future[Duration] =
client.ttl(encodeTraceId(traceId)) map { ttl =>
if (ttl.isDefined) Duration.fromSeconds(ttl.get.intValue()) else Duration.Top
}
override def getSpansByTraceId(traceId: Long): Future[Seq[Span]] =
client.lRange(encodeTraceId(traceId), 0L, -1L) map
(_.map(decodeSpan).sortBy(timestampOfFirstAnnotation)(Ordering.Long.reverse))
override def getSpansByTraceIds(traceIds: Seq[Long]): Future[Seq[Seq[Span]]] =
Future.collect(traceIds.map(getSpansByTraceId))
.map(_.filter(spans => spans.size > 0)) // prune empties
override def getDataTimeToLive: Int = (defaultTtl map (_.inSeconds)).getOrElse(Int.MaxValue)
override def tracesExist(traceIds: Seq[Long]): Future[Set[Long]] =
Future.collect(traceIds map { id =>
// map the exists result to the trace id or none
client.exists(encodeTraceId(id)) map (exists => if (exists) Some(id) else None)
}).map(_.flatten.toSet)
private def decodeSpan(buf: ChannelBuffer): Span = {
val thrift = serializer.fromBytes(buf.copy().array)
new WrappedSpan(thrift).toSpan
}
private def timestampOfFirstAnnotation(span: Span) =
span.firstAnnotation.map(a => a.timestamp).getOrElse(0L)
}
|
zhoffice/zipkin
|
zipkin-redis/src/main/scala/com/twitter/zipkin/storage/redis/RedisStorage.scala
|
Scala
|
apache-2.0
| 2,688 |
package debop4s.data.slick3.tests
import debop4s.data.slick3._
import debop4s.data.slick3.TestDatabase.driver.api._
import debop4s.data.slick3.AbstractSlickFunSuite
import scala.concurrent.Future
/**
* SequenceFunSuite
* @author [email protected]
*/
class SequenceFunSuite extends AbstractSlickFunSuite {
test("sequence 1") {
ifNotCapF(scap.sequence) {
cancel("Sequence 를 지원하지 않습니다.")
Future {}
}
if (SlickContext.isMySQL) {
cancel("MySQL은 지원하지 않습니다.")
}
if (SlickContext.isHsqlDB) {
cancel("HsqlDB를 지원하지 않습니다.")
}
case class User(id: Int, first: String, last: String)
class Users(tag: Tag) extends Table[Int](tag, "sequence_users_1") {
def id = column[Int]("id", O.PrimaryKey)
def * = id
}
val users = TableQuery[Users]
// 사용자의 Sequence
val mySequence = Sequence[Int]("s1") start 200 inc 10
val schema = users.schema ++ mySequence.schema
db.withPinnedSession(
schema.drop.asTry,
schema.create,
users ++= Seq(1, 2, 3)
)
val q1 = for (u <- users) yield (mySequence.next, u.id)
q1.to[Set].exec shouldEqual Set((200, 1), (210, 2), (220, 3))
schema.drop.exec
}
test("sequence 2") {
ifNotCapF(scap.sequence) {
cancel("Sequence 를 지원하지 않습니다.")
Future {}
}
if (SlickContext.isMySQL) {
cancel("MySQL은 지원하지 않습니다.")
}
val s1 = Sequence[Int]("s1")
val s2 = Sequence[Int]("s2") start 3
val s3 = Sequence[Int]("s3") start 3 inc 2
val s4 = Sequence[Int]("s4").cycle start 3 min 2 max 5
val s5 = Sequence[Int]("s5").cycle start 3 min 2 max 5 inc -1
val s6 = Sequence[Int]("s6") start 3 min 2 max 5
def values(s: Sequence[Int], count: Int = 5, create: Boolean = true) = {
val q = Query(s.next)
(
if (create) { s.schema.drop.asTry >> s.schema.create }
else DBIO.successful()
) >>
DBIO.sequence((1 to count).map { _ => q.result.map(_.head) })
}
db.withPinnedSession(
values(s1).map(_ shouldEqual Seq(1, 2, 3, 4, 5)),
values(s2).map(_ shouldEqual Seq(3, 4, 5, 6, 7)),
values(s3).map(_ shouldEqual Seq(3, 5, 7, 9, 11)),
ifCap(scap.sequenceMin, scap.sequenceMax, scap.sequenceCycle) {
DBIO.seq(
values(s4).map(_ shouldEqual Seq(3, 4, 5, 2, 3)),
values(s5).map(_ shouldEqual Seq(3, 2, 5, 4, 3))
)
},
ifCap(scap.sequenceMin, scap.sequenceMax, scap.sequenceLimited) {
DBIO.seq(
values(s6, 3).map(_ shouldEqual List(3, 4, 5)),
values(s6, 1, false).failed
)
}
)
}
}
|
debop/debop4s
|
debop4s-data-slick3/src/test/scala/debop4s/data/slick3/tests/SequenceFunSuite.scala
|
Scala
|
apache-2.0
| 2,720 |
/* Copyright 2014, 2015 Richard Wiedenhöft <[email protected]>
*
* 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 xyz.wiedenhoeft.scalacrypt.blockciphers
import xyz.wiedenhoeft.scalacrypt._
import scala.util.{ Try, Success, Failure }
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
/** Base class for symmetric block ciphers that are implemented in the java crypto API. */
sealed trait SymmetricJavaBlockCipher[KeyType <: Key] extends BlockCipher[KeyType] {
protected def algo: String
lazy val blockSize: Int = Cipher.getInstance(algo + "/ECB/NoPadding").getBlockSize
private val secretKey: java.security.Key = new SecretKeySpec(key.bytes.toArray, "AES")
private val encryptor: Cipher = Cipher.getInstance(algo + "/ECB/NoPadding")
encryptor.init(Cipher.ENCRYPT_MODE, secretKey)
private val decryptor: Cipher = Cipher.getInstance(algo + "/ECB/NoPadding")
decryptor.init(Cipher.DECRYPT_MODE, secretKey)
private def crypt(block: Seq[Byte], encrypt: Boolean): Try[Seq[Byte]] = {
if (block.length == blockSize) {
if (encrypt) {
Success(encryptor.doFinal(block.toArray))
} else {
Success(decryptor.doFinal(block.toArray))
}
} else {
Failure(
new IllegalBlockSizeException("Expected block of length " + blockSize + ", got " + block.length + " bytes."))
}
}
def encryptBlock(block: Seq[Byte]): Try[Seq[Byte]] = crypt(block, true)
def decryptBlock(block: Seq[Byte]): Try[Seq[Byte]] = crypt(block, false)
}
sealed trait AES128 extends SymmetricJavaBlockCipher[SymmetricKey128] { lazy val algo = "AES" }
sealed trait AES192 extends SymmetricJavaBlockCipher[SymmetricKey192] { lazy val algo = "AES" }
sealed trait AES256 extends SymmetricJavaBlockCipher[SymmetricKey256] { lazy val algo = "AES" }
object AES128 {
implicit val builder = new CanBuildBlockCipher[AES128] {
def build(parameters: Parameters): Try[AES128] = {
Parameters.checkParam[SymmetricKey128](parameters, 'symmetricKey128) match {
case Success(k) ⇒ Success(new AES128 { lazy val key = k; val params = parameters })
case Failure(f) ⇒ Failure(f)
}
}
}
}
object AES192 {
implicit val builder = new CanBuildBlockCipher[AES192] {
def build(parameters: Parameters): Try[AES192] = {
Parameters.checkParam[SymmetricKey192](parameters, 'symmetricKey192) match {
case Success(k) ⇒ Success(new AES192 { lazy val key = k; val params = parameters })
case Failure(f) ⇒ Failure(f)
}
}
}
}
object AES256 {
implicit val builder = new CanBuildBlockCipher[AES256] {
def build(parameters: Parameters): Try[AES256] = {
Parameters.checkParam[SymmetricKey256](parameters, 'symmetricKey256) match {
case Success(k) ⇒ Success(new AES256 { lazy val key = k; val params = parameters })
case Failure(f) ⇒ Failure(f)
}
}
}
}
|
Richard-W/scalacrypt
|
src/main/scala/blockciphers/SymmetricJavaBlockCipher.scala
|
Scala
|
apache-2.0
| 3,419 |
package cz.kamenitxan.jakon.core.database.converters
import java.util
/**
* Created by TPa on 2019-03-19.
*/
abstract class AbstractListConverter[T] extends AbstractConverter[util.List[T]] {
}
|
kamenitxan/Jakon
|
modules/backend/src/main/scala/cz/kamenitxan/jakon/core/database/converters/AbstractListConverter.scala
|
Scala
|
bsd-3-clause
| 200 |
package utils.generator
import utils.NeoDB
import utils.Mode._
object SubNameQueryRunner extends App
with CypherQueryExecutor with MemoryStatsReporter {
def runFor(level: Int, params: Map[String, Any])(implicit neo4j: NeoDB) = {
val visibilityLevel = level - 1
val subNameCql =
"""
|start n = node:Person(name = {name})
|match p = n-[:DIRECTLY_MANAGES*1..%d]->m
|return nodes(p);
""".format(visibilityLevel).stripMargin
val (_, coldCacheExecTime) = execute(subNameCql, params)
val (_, warmCacheExecTime) = execute(subNameCql, params)
val (_, hotCacheExecTime) = execute(subNameCql, params)
val queryName = getClass.getSimpleName.replace("$", "").replace("Runner", "")
val resultString = "%s => For Level %d => %s Cache Exec Time = %d (ms)\\n"
val coldCacheResult = resultString.format(queryName, level, "Cold", coldCacheExecTime)
val warmCacheResult = resultString.format(queryName, level, "Warm", warmCacheExecTime)
val hotCacheResult = resultString.format(queryName, level, "Hot", hotCacheExecTime)
List(coldCacheResult, warmCacheResult, hotCacheResult)
}
override def main(args: Array[String]) {
memStats
// basePath = "D:/rnd/apiary"
val basePath = "/Users/dhavald/Documents/workspace/Apiary_Stable/NEO4J_DATA/apiary_"
val orgSize = "1m"
val level = 8
val orgSizeAndLevel = orgSize + "_l" + level
val completeUrl = basePath + orgSizeAndLevel
val topLevelPerson = TopLevel().names(orgSizeAndLevel)
val params = Map[String, Any]("name" -> topLevelPerson)
info("Top Level Person is ==> %s", topLevelPerson)
implicit val neo4j = NeoDB(completeUrl, Embedded)
val result = runFor(level, params)
neo4j.shutdown
info("RESULTS:\\n%s", result mkString "\\n")
memStats
}
}
|
EqualExperts/Apiary-Neo4j-RDBMS-Comparison
|
src/main/scala/utils/generator/SubNameQueryRunner.scala
|
Scala
|
bsd-2-clause
| 1,820 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.hive.execution
import java.io.File
import java.util.{Locale, TimeZone}
import org.scalatest.BeforeAndAfter
import org.apache.spark.sql.SQLConf
import org.apache.spark.sql.hive.HiveShim
import org.apache.spark.sql.hive.test.TestHive
/**
* Runs the test cases that are included in the hive distribution.
*/
class HiveCompatibilitySuite extends HiveQueryFileTest with BeforeAndAfter {
// TODO: bundle in jar files... get from classpath
private lazy val hiveQueryDir = TestHive.getHiveFile(
"ql/src/test/queries/clientpositive".split("/").mkString(File.separator))
private val originalTimeZone = TimeZone.getDefault
private val originalLocale = Locale.getDefault
private val originalColumnBatchSize = TestHive.conf.columnBatchSize
private val originalInMemoryPartitionPruning = TestHive.conf.inMemoryPartitionPruning
def testCases = hiveQueryDir.listFiles.map(f => f.getName.stripSuffix(".q") -> f)
override def beforeAll() {
TestHive.cacheTables = true
// Timezone is fixed to America/Los_Angeles for those timezone sensitive tests (timestamp_*)
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"))
// Add Locale setting
Locale.setDefault(Locale.US)
// Set a relatively small column batch size for testing purposes
TestHive.setConf(SQLConf.COLUMN_BATCH_SIZE, "5")
// Enable in-memory partition pruning for testing purposes
TestHive.setConf(SQLConf.IN_MEMORY_PARTITION_PRUNING, "true")
}
override def afterAll() {
TestHive.cacheTables = false
TimeZone.setDefault(originalTimeZone)
Locale.setDefault(originalLocale)
TestHive.setConf(SQLConf.COLUMN_BATCH_SIZE, originalColumnBatchSize.toString)
TestHive.setConf(SQLConf.IN_MEMORY_PARTITION_PRUNING, originalInMemoryPartitionPruning.toString)
}
/** A list of tests deemed out of scope currently and thus completely disregarded. */
override def blackList = Seq(
// These tests use hooks that are not on the classpath and thus break all subsequent execution.
"hook_order",
"hook_context_cs",
"mapjoin_hook",
"multi_sahooks",
"overridden_confs",
"query_properties",
"sample10",
"updateAccessTime",
"index_compact_binary_search",
"bucket_num_reducers",
"column_access_stats",
"concatenate_inherit_table_location",
"describe_pretty",
"describe_syntax",
"orc_ends_with_nulls",
// Setting a default property does not seem to get reset and thus changes the answer for many
// subsequent tests.
"create_default_prop",
// User/machine specific test answers, breaks the caching mechanism.
"authorization_3",
"authorization_5",
"keyword_1",
"misc_json",
"load_overwrite",
"alter_table_serde2",
"alter_table_not_sorted",
"alter_skewed_table",
"alter_partition_clusterby_sortby",
"alter_merge",
"alter_concatenate_indexed_table",
"protectmode2",
//"describe_table",
"describe_comment_nonascii",
"create_merge_compressed",
"create_view",
"create_view_partitioned",
"database_location",
"database_properties",
// DFS commands
"symlink_text_input_format",
// Weird DDL differences result in failures on jenkins.
"create_like2",
"partitions_json",
// This test is totally fine except that it includes wrong queries and expects errors, but error
// message format in Hive and Spark SQL differ. Should workaround this later.
"udf_to_unix_timestamp",
// Cant run without local map/reduce.
"index_auto_update",
"index_auto_self_join",
"index_stale.*",
"index_compression",
"index_bitmap_compression",
"index_auto_multiple",
"index_auto_mult_tables_compact",
"index_auto_mult_tables",
"index_auto_file_format",
"index_auth",
"index_auto_empty",
"index_auto_partitioned",
"index_auto_unused",
"index_bitmap_auto_partitioned",
"ql_rewrite_gbtoidx",
"stats1.*",
"stats20",
"alter_merge_stats",
"columnstats.*",
"annotate_stats.*",
"database_drop",
"index_serde",
// Hive seems to think 1.0 > NaN = true && 1.0 < NaN = false... which is wrong.
// http://stackoverflow.com/a/1573715
"ops_comparison",
// Tests that seems to never complete on hive...
"skewjoin",
"database",
// These tests fail and and exit the JVM.
"auto_join18_multi_distinct",
"join18_multi_distinct",
"input44",
"input42",
"input_dfs",
"metadata_export_drop",
"repair",
// Uses a serde that isn't on the classpath... breaks other tests.
"bucketizedhiveinputformat",
// Avro tests seem to change the output format permanently thus breaking the answer cache, until
// we figure out why this is the case let just ignore all of avro related tests.
".*avro.*",
// Unique joins are weird and will require a lot of hacks (see comments in hive parser).
"uniquejoin",
// Hive seems to get the wrong answer on some outer joins. MySQL agrees with catalyst.
"auto_join29",
// No support for multi-alias i.e. udf as (e1, e2, e3).
"allcolref_in_udf",
// No support for TestSerDe (not published afaik)
"alter1",
"input16",
// No support for unpublished test udfs.
"autogen_colalias",
// Hive does not support buckets.
".*bucket.*",
// We have our own tests based on these query files.
".*window.*",
// Fails in hive with authorization errors.
"alter_rename_partition_authorization",
"authorization.*",
// Hadoop version specific tests
"archive_corrupt",
// No support for case sensitivity is resolution using hive properties atm.
"case_sensitivity",
// Flaky test, Hive sometimes returns different set of 10 rows.
"lateral_view_outer",
// After stop taking the `stringOrError` route, exceptions are thrown from these cases.
// See SPARK-2129 for details.
"join_view",
"mergejoins_mixed",
// Returning the result of a describe state as a JSON object is not supported.
"describe_table_json",
"describe_database_json",
"describe_formatted_view_partitioned_json",
// Hive returns the results of describe as plain text. Comments with multiple lines
// introduce extra lines in the Hive results, which make the result comparison fail.
"describe_comment_indent",
// Limit clause without a ordering, which causes failure.
"orc_predicate_pushdown",
// Requires precision decimal support:
"udf_when",
"udf_case",
// Needs constant object inspectors
"udf_round",
// the table src(key INT, value STRING) is not the same as HIVE unittest. In Hive
// is src(key STRING, value STRING), and in the reflect.q, it failed in
// Integer.valueOf, which expect the first argument passed as STRING type not INT.
"udf_reflect",
// Sort with Limit clause causes failure.
"ctas",
"ctas_hadoop20",
// timestamp in array, the output format of Hive contains double quotes, while
// Spark SQL doesn't
"udf_sort_array",
// It has a bug and it has been fixed by
// https://issues.apache.org/jira/browse/HIVE-7673 (in Hive 0.14 and trunk).
"input46",
// These tests were broken by the hive client isolation PR.
"part_inherit_tbl_props",
"part_inherit_tbl_props_with_star",
"nullformatCTAS", // SPARK-7411: need to finish CTAS parser
// The isolated classloader seemed to make some of our test reset mechanisms less robust.
"combine1", // This test changes compression settings in a way that breaks all subsequent tests.
"load_dyn_part14.*", // These work alone but fail when run with other tests...
// the answer is sensitive for jdk version
"udf_java_method"
) ++ HiveShim.compatibilityBlackList
/**
* The set of tests that are believed to be working in catalyst. Tests not on whiteList or
* blacklist are implicitly marked as ignored.
*/
override def whiteList = Seq(
"add_part_exist",
"add_part_multiple",
"add_partition_no_whitelist",
"add_partition_with_whitelist",
"alias_casted_column",
"alter2",
"alter3",
"alter4",
"alter5",
"alter_index",
"alter_merge_2",
"alter_partition_format_loc",
"alter_partition_protect_mode",
"alter_partition_with_whitelist",
"alter_rename_partition",
"alter_table_serde",
"alter_varchar1",
"alter_varchar2",
"alter_view_as_select",
"ambiguous_col",
"annotate_stats_join",
"annotate_stats_limit",
"annotate_stats_part",
"annotate_stats_table",
"annotate_stats_union",
"auto_join0",
"auto_join1",
"auto_join10",
"auto_join11",
"auto_join12",
"auto_join13",
"auto_join14",
"auto_join14_hadoop20",
"auto_join15",
"auto_join17",
"auto_join18",
"auto_join19",
"auto_join2",
"auto_join20",
"auto_join21",
"auto_join22",
"auto_join23",
"auto_join24",
"auto_join25",
"auto_join26",
"auto_join27",
"auto_join28",
"auto_join3",
"auto_join30",
"auto_join31",
"auto_join32",
"auto_join4",
"auto_join5",
"auto_join6",
"auto_join7",
"auto_join8",
"auto_join9",
"auto_join_filters",
"auto_join_nulls",
"auto_join_reordering_values",
"auto_smb_mapjoin_14",
"auto_sortmerge_join_1",
"auto_sortmerge_join_10",
"auto_sortmerge_join_11",
"auto_sortmerge_join_12",
"auto_sortmerge_join_13",
"auto_sortmerge_join_14",
"auto_sortmerge_join_15",
"auto_sortmerge_join_16",
"auto_sortmerge_join_2",
"auto_sortmerge_join_3",
"auto_sortmerge_join_4",
"auto_sortmerge_join_5",
"auto_sortmerge_join_6",
"auto_sortmerge_join_7",
"auto_sortmerge_join_8",
"auto_sortmerge_join_9",
"binary_constant",
"binarysortable_1",
"cast1",
"cluster",
"combine1",
"compute_stats_binary",
"compute_stats_boolean",
"compute_stats_double",
"compute_stats_empty_table",
"compute_stats_long",
"compute_stats_string",
"convert_enum_to_string",
"correlationoptimizer1",
"correlationoptimizer10",
"correlationoptimizer11",
"correlationoptimizer13",
"correlationoptimizer14",
"correlationoptimizer15",
"correlationoptimizer2",
"correlationoptimizer3",
"correlationoptimizer4",
"correlationoptimizer6",
"correlationoptimizer7",
"correlationoptimizer8",
"correlationoptimizer9",
"count",
"cp_mj_rc",
"create_insert_outputformat",
"create_like_tbl_props",
"create_like_view",
"create_nested_type",
"create_skewed_table1",
"create_struct_table",
"create_view_translate",
"cross_join",
"cross_product_check_1",
"cross_product_check_2",
"ct_case_insensitive",
"database_drop",
"database_location",
"database_properties",
"date_1",
"date_2",
"date_3",
"date_4",
"date_comparison",
"date_join1",
"date_serde",
"date_udf",
"decimal_1",
"decimal_4",
"decimal_join",
"default_partition_name",
"delimiter",
"desc_non_existent_tbl",
"describe_formatted_view_partitioned",
"diff_part_input_formats",
"disable_file_format_check",
"disallow_incompatible_type_change_off",
"distinct_stats",
"drop_database_removes_partition_dirs",
"drop_function",
"drop_index",
"drop_index_removes_partition_dirs",
"drop_multi_partitions",
"drop_partitions_filter",
"drop_partitions_filter2",
"drop_partitions_filter3",
"drop_partitions_ignore_protection",
"drop_table",
"drop_table2",
"drop_table_removes_partition_dirs",
"drop_view",
"dynamic_partition_skip_default",
"escape_clusterby1",
"escape_distributeby1",
"escape_orderby1",
"escape_sortby1",
"explain_rearrange",
"fetch_aggregation",
"fileformat_mix",
"fileformat_sequencefile",
"fileformat_text",
"filter_join_breaktask",
"filter_join_breaktask2",
"groupby1",
"groupby11",
"groupby12",
"groupby1_limit",
"groupby_grouping_id1",
"groupby_grouping_id2",
"groupby_grouping_sets1",
"groupby_grouping_sets2",
"groupby_grouping_sets3",
"groupby_grouping_sets4",
"groupby_grouping_sets5",
"groupby1_map",
"groupby1_map_nomap",
"groupby1_map_skew",
"groupby1_noskew",
"groupby2",
"groupby2_limit",
"groupby2_map",
"groupby2_map_skew",
"groupby2_noskew",
"groupby4",
"groupby4_map",
"groupby4_map_skew",
"groupby4_noskew",
"groupby5",
"groupby5_map",
"groupby5_map_skew",
"groupby5_noskew",
"groupby6",
"groupby6_map",
"groupby6_map_skew",
"groupby6_noskew",
"groupby7",
"groupby7_map",
"groupby7_map_multi_single_reducer",
"groupby7_map_skew",
"groupby7_noskew",
"groupby7_noskew_multi_single_reducer",
"groupby8",
"groupby8_map",
"groupby8_map_skew",
"groupby8_noskew",
"groupby9",
"groupby_distinct_samekey",
"groupby_map_ppr",
"groupby_multi_insert_common_distinct",
"groupby_multi_single_reducer2",
"groupby_multi_single_reducer3",
"groupby_mutli_insert_common_distinct",
"groupby_neg_float",
"groupby_ppd",
"groupby_ppr",
"groupby_sort_10",
"groupby_sort_2",
"groupby_sort_3",
"groupby_sort_4",
"groupby_sort_5",
"groupby_sort_6",
"groupby_sort_7",
"groupby_sort_8",
"groupby_sort_9",
"groupby_sort_test_1",
"having",
"implicit_cast1",
"index_serde",
"infer_bucket_sort_dyn_part",
"innerjoin",
"inoutdriver",
"input",
"input0",
"input1",
"input10",
"input11",
"input11_limit",
"input12",
"input12_hadoop20",
"input14",
"input15",
"input19",
"input1_limit",
"input2",
"input21",
"input22",
"input23",
"input24",
"input25",
"input26",
"input28",
"input2_limit",
"input3",
"input4",
"input40",
"input41",
"input49",
"input4_cb_delim",
"input6",
"input7",
"input8",
"input9",
"input_limit",
"input_part0",
"input_part1",
"input_part10",
"input_part10_win",
"input_part2",
"input_part3",
"input_part4",
"input_part5",
"input_part6",
"input_part7",
"input_part8",
"input_part9",
"input_testsequencefile",
"inputddl1",
"inputddl2",
"inputddl3",
"inputddl4",
"inputddl5",
"inputddl6",
"inputddl7",
"inputddl8",
"insert1",
"insert1_overwrite_partitions",
"insert2_overwrite_partitions",
"insert_compressed",
"join0",
"join1",
"join10",
"join11",
"join12",
"join13",
"join14",
"join14_hadoop20",
"join15",
"join16",
"join17",
"join18",
"join19",
"join2",
"join20",
"join21",
"join22",
"join23",
"join24",
"join25",
"join26",
"join27",
"join28",
"join29",
"join3",
"join30",
"join31",
"join32",
"join32_lessSize",
"join33",
"join34",
"join35",
"join36",
"join37",
"join38",
"join39",
"join4",
"join40",
"join41",
"join5",
"join6",
"join7",
"join8",
"join9",
"join_1to1",
"join_array",
"join_casesensitive",
"join_empty",
"join_filters",
"join_hive_626",
"join_map_ppr",
"join_nulls",
"join_nullsafe",
"join_rc",
"join_reorder2",
"join_reorder3",
"join_reorder4",
"join_star",
"lateral_view",
"lateral_view_cp",
"lateral_view_ppd",
"leftsemijoin",
"leftsemijoin_mr",
"limit_pushdown_negative",
"lineage1",
"literal_double",
"literal_ints",
"literal_string",
"load_dyn_part1",
"load_dyn_part10",
"load_dyn_part11",
"load_dyn_part12",
"load_dyn_part13",
"load_dyn_part14",
"load_dyn_part14_win",
"load_dyn_part2",
"load_dyn_part3",
"load_dyn_part4",
"load_dyn_part5",
"load_dyn_part6",
"load_dyn_part7",
"load_dyn_part8",
"load_dyn_part9",
"load_file_with_space_in_the_name",
"loadpart1",
"louter_join_ppr",
"mapjoin_distinct",
"mapjoin_filter_on_outerjoin",
"mapjoin_mapjoin",
"mapjoin_subquery",
"mapjoin_subquery2",
"mapjoin_test_outer",
"mapreduce1",
"mapreduce2",
"mapreduce3",
"mapreduce4",
"mapreduce5",
"mapreduce6",
"mapreduce7",
"mapreduce8",
"merge1",
"merge2",
"merge4",
"mergejoins",
"multiMapJoin1",
"multiMapJoin2",
"multi_insert_gby",
"multi_insert_gby3",
"multi_insert_lateral_view",
"multi_join_union",
"multigroupby_singlemr",
"noalias_subq1",
"nomore_ambiguous_table_col",
"nonblock_op_deduplicate",
"notable_alias1",
"notable_alias2",
"nullformatCTAS",
"nullgroup",
"nullgroup2",
"nullgroup3",
"nullgroup4",
"nullgroup4_multi_distinct",
"nullgroup5",
"nullinput",
"nullinput2",
"nullscript",
"optional_outer",
"orc_dictionary_threshold",
"orc_empty_files",
"order",
"order2",
"outer_join_ppr",
"parallel",
"parenthesis_star_by",
"part_inherit_tbl_props",
"part_inherit_tbl_props_empty",
"part_inherit_tbl_props_with_star",
"partcols1",
"partition_date",
"partition_schema1",
"partition_serde_format",
"partition_type_check",
"partition_varchar1",
"partition_wise_fileformat4",
"partition_wise_fileformat5",
"partition_wise_fileformat6",
"partition_wise_fileformat7",
"partition_wise_fileformat9",
"plan_json",
"ppd1",
"ppd2",
"ppd_clusterby",
"ppd_constant_expr",
"ppd_constant_where",
"ppd_gby",
"ppd_gby2",
"ppd_gby_join",
"ppd_join",
"ppd_join2",
"ppd_join3",
"ppd_join_filter",
"ppd_outer_join1",
"ppd_outer_join2",
"ppd_outer_join3",
"ppd_outer_join4",
"ppd_outer_join5",
"ppd_random",
"ppd_repeated_alias",
"ppd_udf_col",
"ppd_union",
"ppr_allchildsarenull",
"ppr_pushdown",
"ppr_pushdown2",
"ppr_pushdown3",
"progress_1",
"protectmode",
"push_or",
"query_with_semi",
"quote1",
"quote2",
"rcfile_columnar",
"rcfile_lazydecompress",
"rcfile_null_value",
"rcfile_toleratecorruptions",
"rcfile_union",
"reduce_deduplicate",
"reduce_deduplicate_exclude_gby",
"reduce_deduplicate_exclude_join",
"reduce_deduplicate_extended",
"reducesink_dedup",
"rename_column",
"router_join_ppr",
"select_as_omitted",
"select_unquote_and",
"select_unquote_not",
"select_unquote_or",
"semicolon",
"semijoin",
"serde_regex",
"serde_reported_schema",
"set_variable_sub",
"show_columns",
"show_create_table_alter",
"show_create_table_db_table",
"show_create_table_delimited",
"show_create_table_does_not_exist",
"show_create_table_index",
"show_create_table_partitioned",
"show_create_table_serde",
"show_create_table_view",
"show_describe_func_quotes",
"show_functions",
"show_partitions",
"show_tblproperties",
"skewjoinopt13",
"skewjoinopt18",
"skewjoinopt9",
"smb_mapjoin9",
"smb_mapjoin_1",
"smb_mapjoin_10",
"smb_mapjoin_13",
"smb_mapjoin_14",
"smb_mapjoin_15",
"smb_mapjoin_16",
"smb_mapjoin_17",
"smb_mapjoin_2",
"smb_mapjoin_21",
"smb_mapjoin_25",
"smb_mapjoin_3",
"smb_mapjoin_4",
"smb_mapjoin_5",
"smb_mapjoin_6",
"smb_mapjoin_7",
"smb_mapjoin_8",
"sort",
"sort_merge_join_desc_1",
"sort_merge_join_desc_2",
"sort_merge_join_desc_3",
"sort_merge_join_desc_4",
"sort_merge_join_desc_5",
"sort_merge_join_desc_6",
"sort_merge_join_desc_7",
"stats0",
"stats_aggregator_error_1",
"stats_empty_partition",
"stats_publisher_error_1",
"subq2",
"tablename_with_select",
"timestamp_1",
"timestamp_2",
"timestamp_3",
"timestamp_comparison",
"timestamp_lazy",
"timestamp_null",
"timestamp_udf",
"touch",
"transform_ppr1",
"transform_ppr2",
"truncate_table",
"type_cast_1",
"type_widening",
"udaf_collect_set",
"udaf_corr",
"udaf_covar_pop",
"udaf_covar_samp",
"udaf_histogram_numeric",
"udaf_number_format",
"udf2",
"udf5",
"udf6",
"udf7",
"udf8",
"udf9",
"udf_10_trims",
"udf_E",
"udf_PI",
"udf_abs",
"udf_acos",
"udf_add",
"udf_array",
"udf_array_contains",
"udf_ascii",
"udf_asin",
"udf_atan",
"udf_avg",
"udf_bigint",
"udf_bin",
"udf_bitmap_and",
"udf_bitmap_empty",
"udf_bitmap_or",
"udf_bitwise_and",
"udf_bitwise_not",
"udf_bitwise_or",
"udf_bitwise_xor",
"udf_boolean",
"udf_case",
"udf_ceil",
"udf_ceiling",
"udf_concat",
"udf_concat_insert1",
"udf_concat_insert2",
"udf_concat_ws",
"udf_conv",
"udf_cos",
"udf_count",
"udf_date_add",
"udf_date_sub",
"udf_datediff",
"udf_day",
"udf_dayofmonth",
"udf_degrees",
"udf_div",
"udf_double",
"udf_elt",
"udf_equal",
"udf_exp",
"udf_field",
"udf_find_in_set",
"udf_float",
"udf_floor",
"udf_format_number",
"udf_from_unixtime",
"udf_greaterthan",
"udf_greaterthanorequal",
"udf_hash",
"udf_hex",
"udf_if",
"udf_index",
"udf_instr",
"udf_int",
"udf_isnotnull",
"udf_isnull",
"udf_lcase",
"udf_length",
"udf_lessthan",
"udf_lessthanorequal",
"udf_like",
"udf_ln",
"udf_locate",
"udf_log",
"udf_log10",
"udf_log2",
"udf_lower",
"udf_lpad",
"udf_ltrim",
"udf_map",
"udf_minute",
"udf_modulo",
"udf_month",
"udf_named_struct",
"udf_negative",
"udf_not",
"udf_notequal",
"udf_notop",
"udf_nvl",
"udf_or",
"udf_parse_url",
"udf_pmod",
"udf_positive",
"udf_pow",
"udf_power",
"udf_radians",
"udf_rand",
"udf_reflect2",
"udf_regexp",
"udf_regexp_extract",
"udf_regexp_replace",
"udf_repeat",
"udf_rlike",
"udf_round",
"udf_round_3",
"udf_rpad",
"udf_rtrim",
"udf_second",
"udf_sign",
"udf_sin",
"udf_smallint",
"udf_space",
"udf_sqrt",
"udf_std",
"udf_stddev",
"udf_stddev_pop",
"udf_stddev_samp",
"udf_string",
"udf_struct",
"udf_substring",
"udf_subtract",
"udf_sum",
"udf_tan",
"udf_tinyint",
"udf_to_byte",
"udf_to_date",
"udf_to_double",
"udf_to_float",
"udf_to_long",
"udf_to_short",
"udf_translate",
"udf_trim",
"udf_ucase",
"udf_unix_timestamp",
"udf_upper",
"udf_var_pop",
"udf_var_samp",
"udf_variance",
"udf_weekofyear",
"udf_when",
"udf_xpath",
"udf_xpath_boolean",
"udf_xpath_double",
"udf_xpath_float",
"udf_xpath_int",
"udf_xpath_long",
"udf_xpath_short",
"udf_xpath_string",
"unicode_notation",
"union10",
"union11",
"union13",
"union14",
"union15",
"union16",
"union17",
"union18",
"union19",
"union2",
"union20",
"union22",
"union23",
"union24",
"union25",
"union26",
"union27",
"union28",
"union29",
"union3",
"union30",
"union31",
"union33",
"union34",
"union4",
"union5",
"union6",
"union7",
"union8",
"union9",
"union_date",
"union_lateralview",
"union_ppr",
"union_remove_11",
"union_remove_3",
"union_remove_6",
"union_script",
"varchar_2",
"varchar_join1",
"varchar_union1",
"view",
"view_cast",
"view_inputs"
)
}
|
andrewor14/iolap
|
sql/hive/compatibility/src/test/scala/org/apache/spark/sql/hive/execution/HiveCompatibilitySuite.scala
|
Scala
|
apache-2.0
| 24,704 |
package sbt
import sbt.internal.util.{ AttributeKey, Dag, Types }
import sbt.librarymanagement.Configuration
import Types.{ const, idFun }
import Def.Initialize
import java.net.URI
import ScopeFilter.Data
object ScopeFilter {
type ScopeFilter = Base[Scope]
type AxisFilter[T] = Base[ScopeAxis[T]]
type ProjectFilter = AxisFilter[Reference]
type ConfigurationFilter = AxisFilter[ConfigKey]
type TaskFilter = AxisFilter[AttributeKey[_]]
/**
* Constructs a Scope filter from filters for the individual axes.
* If a project filter is not supplied, the enclosing project is selected.
* If a configuration filter is not supplied, global is selected.
* If a task filter is not supplied, global is selected.
* Generally, always specify the project axis.
*/
def apply(projects: ProjectFilter = inProjects(ThisProject), configurations: ConfigurationFilter = globalAxis, tasks: TaskFilter = globalAxis): ScopeFilter =
new ScopeFilter {
private[sbt] def apply(data: Data): Scope => Boolean =
{
val pf = projects(data)
val cf = configurations(data)
val tf = tasks(data)
s => pf(s.project) && cf(s.config) && tf(s.task)
}
}
def debug(delegate: ScopeFilter): ScopeFilter =
new ScopeFilter {
private[sbt] def apply(data: Data): Scope => Boolean =
{
val d = delegate(data)
scope => {
val accept = d(scope)
println((if (accept) "ACCEPT " else "reject ") + scope)
accept
}
}
}
final class SettingKeyAll[T] private[sbt] (i: Initialize[T]) {
/**
* Evaluates the initialization in all scopes selected by the filter. These are dynamic dependencies, so
* static inspections will not show them.
*/
def all(sfilter: => ScopeFilter): Initialize[Seq[T]] = Def.bind(getData) { data =>
data.allScopes.toSeq.filter(sfilter(data)).map(s => Project.inScope(s, i)).join
}
}
final class TaskKeyAll[T] private[sbt] (i: Initialize[Task[T]]) {
/**
* Evaluates the task in all scopes selected by the filter. These are dynamic dependencies, so
* static inspections will not show them.
*/
def all(sfilter: => ScopeFilter): Initialize[Task[Seq[T]]] = Def.bind(getData) { data =>
import std.TaskExtra._
data.allScopes.toSeq.filter(sfilter(data)).map(s => Project.inScope(s, i)).join(_.join)
}
}
private[sbt] val Make = new Make {}
trait Make {
/** Selects the Scopes used in `<key>.all(<ScopeFilter>)`.*/
type ScopeFilter = Base[Scope]
/** Selects Scopes with a global task axis. */
def inGlobalTask: TaskFilter = globalAxis[AttributeKey[_]]
/** Selects Scopes with a global project axis. */
def inGlobalProject: ProjectFilter = globalAxis[Reference]
/** Selects Scopes with a global configuration axis. */
def inGlobalConfiguration: ConfigurationFilter = globalAxis[ConfigKey]
/** Selects all scopes that apply to a single project. Global and build-level scopes are excluded. */
def inAnyProject: ProjectFilter = selectAxis(const { case p: ProjectRef => true; case _ => false })
/** Accepts all values for the task axis except Global. */
def inAnyTask: TaskFilter = selectAny[AttributeKey[_]]
/** Accepts all values for the configuration axis except Global. */
def inAnyConfiguration: ConfigurationFilter = selectAny[ConfigKey]
/**
* Selects Scopes that have a project axis that is aggregated by `ref`, transitively if `transitive` is true.
* If `includeRoot` is true, Scopes with `ref` itself as the project axis value are also selected.
*/
def inAggregates(ref: ProjectReference, transitive: Boolean = true, includeRoot: Boolean = true): ProjectFilter =
byDeps(ref, transitive = transitive, includeRoot = includeRoot, aggregate = true, classpath = false)
/**
* Selects Scopes that have a project axis that is a dependency of `ref`, transitively if `transitive` is true.
* If `includeRoot` is true, Scopes with `ref` itself as the project axis value are also selected.
*/
def inDependencies(ref: ProjectReference, transitive: Boolean = true, includeRoot: Boolean = true): ProjectFilter =
byDeps(ref, transitive = transitive, includeRoot = includeRoot, aggregate = false, classpath = true)
/** Selects Scopes that have a project axis with one of the provided values.*/
def inProjects(projects: ProjectReference*): ProjectFilter = ScopeFilter.inProjects(projects: _*)
/** Selects Scopes that have a task axis with one of the provided values.*/
def inTasks(tasks: Scoped*): TaskFilter = {
val ts = tasks.map(_.key).toSet
selectAxis[AttributeKey[_]](const(ts))
}
/** Selects Scopes that have a task axis with one of the provided values.*/
def inConfigurations(configs: Configuration*): ConfigurationFilter = {
val cs = configs.map(_.name).toSet
selectAxis[ConfigKey](const(c => cs(c.name)))
}
implicit def settingKeyAll[T](key: Initialize[T]): SettingKeyAll[T] = new SettingKeyAll[T](key)
implicit def taskKeyAll[T](key: Initialize[Task[T]]): TaskKeyAll[T] = new TaskKeyAll[T](key)
}
/**
* Information provided to Scope filters. These provide project relationships,
* project reference resolution, and the list of all static Scopes.
*/
private final class Data(val units: Map[URI, LoadedBuildUnit], val resolve: ProjectReference => ProjectRef, val allScopes: Set[Scope])
/** Constructs a Data instance from the list of static scopes and the project relationships.*/
private[this] val getData: Initialize[Data] =
Def.setting {
val build = Keys.loadedBuild.value
val scopes = Def.StaticScopes.value
val thisRef = Keys.thisProjectRef.?.value
val current = thisRef match {
case Some(ProjectRef(uri, _)) => uri
case None => build.root
}
val rootProject = Load.getRootProject(build.units)
val resolve: ProjectReference => ProjectRef = p => (p, thisRef) match {
case (ThisProject, Some(pref)) => pref
case _ => Scope.resolveProjectRef(current, rootProject, p)
}
new Data(build.units, resolve, scopes)
}
private[this] def getDependencies(structure: Map[URI, LoadedBuildUnit], classpath: Boolean, aggregate: Boolean): ProjectRef => Seq[ProjectRef] =
ref => Project.getProject(ref, structure).toList flatMap { p =>
(if (classpath) p.dependencies.map(_.project) else Nil) ++
(if (aggregate) p.aggregate else Nil)
}
private[this] def byDeps(ref: ProjectReference, transitive: Boolean, includeRoot: Boolean, aggregate: Boolean, classpath: Boolean): ProjectFilter =
inResolvedProjects { data =>
val resolvedRef = data.resolve(ref)
val direct = getDependencies(data.units, classpath = classpath, aggregate = aggregate)
if (transitive) {
val full = Dag.topologicalSort(resolvedRef)(direct)
if (includeRoot) full else full dropRight 1
} else {
val directDeps = direct(resolvedRef)
if (includeRoot) resolvedRef +: directDeps else directDeps
}
}
private def inProjects(projects: ProjectReference*): ProjectFilter =
inResolvedProjects(data => projects.map(data.resolve))
private[this] def inResolvedProjects(projects: Data => Seq[ProjectRef]): ProjectFilter =
selectAxis(data => projects(data).toSet)
private[this] def globalAxis[T]: AxisFilter[T] = new AxisFilter[T] {
private[sbt] def apply(data: Data): ScopeAxis[T] => Boolean =
_ == Global
}
private[this] def selectAny[T]: AxisFilter[T] = selectAxis(const(const(true)))
private[this] def selectAxis[T](f: Data => T => Boolean): AxisFilter[T] = new AxisFilter[T] {
private[sbt] def apply(data: Data): ScopeAxis[T] => Boolean = {
val g = f(data)
s => s match {
case Select(t) => g(t)
case _ => false
}
}
}
/** Base functionality for filters on values of type `In` that need access to build data.*/
sealed abstract class Base[In] { self =>
/** Implements this filter. */
private[sbt] def apply(data: Data): In => Boolean
/** Constructs a filter that selects values that match this filter but not `other`.*/
def --(other: Base[In]): Base[In] = this && -other
/** Constructs a filter that selects values that match this filter and `other`.*/
def &&(other: Base[In]): Base[In] = new Base[In] {
private[sbt] def apply(data: Data): In => Boolean = {
val a = self(data)
val b = other(data)
s => a(s) && b(s)
}
}
/** Constructs a filter that selects values that match this filter or `other`.*/
def ||(other: Base[In]): Base[In] = new Base[In] {
private[sbt] def apply(data: Data): In => Boolean = {
val a = self(data)
val b = other(data)
s => a(s) || b(s)
}
}
/** Constructs a filter that selects values that do not match this filter.*/
def unary_- : Base[In] = new Base[In] {
private[sbt] def apply(data: Data): In => Boolean = {
val a = self(data)
s => !a(s)
}
}
}
}
|
mdedetrich/sbt
|
main/src/main/scala/sbt/ScopeFilter.scala
|
Scala
|
bsd-3-clause
| 9,236 |
/*
* Copyright (C) 2016-2017 Lightbend Inc. <https://www.lightbend.com>
*/
package com.lightbend.lagom.internal.javadsl.api
import java.lang.invoke.MethodHandles
import java.lang.reflect.{ InvocationHandler, Method, Modifier, ParameterizedType, Type, Proxy => JProxy }
import com.google.common.reflect.TypeToken
import com.lightbend.lagom.javadsl.api._
import com.lightbend.lagom.javadsl.api.Descriptor._
import com.lightbend.lagom.javadsl.api.deser._
import akka.NotUsed
import org.pcollections.TreePVector
import scala.collection.JavaConverters._
import scala.compat.java8.OptionConverters._
import scala.util.control.NonFatal
import com.lightbend.lagom.javadsl.api.broker.Topic
import com.lightbend.lagom.javadsl.api.broker.Topic.TopicId
import akka.util.ByteString
/**
* Reads a service interface
*/
object ServiceReader {
final val DescriptorMethodName = "descriptor"
/**
* In order to invoke default methods of a proxy in Java 8 reflectively, we need to create a MethodHandles.Lookup
* instance that is allowed to lookup private methods. The only way to do that is via reflection.
*/
private val methodHandlesLookupConstructor = classOf[MethodHandles.Lookup].getDeclaredConstructor(classOf[Class[_]], classOf[Int])
if (!methodHandlesLookupConstructor.isAccessible) {
methodHandlesLookupConstructor.setAccessible(true)
}
def readServiceDescriptor(classLoader: ClassLoader, serviceInterface: Class[_ <: Service]): Descriptor = {
if (Modifier.isPublic(serviceInterface.getModifiers)) {
val invocationHandler = new ServiceInvocationHandler(classLoader, serviceInterface)
val serviceStub = JProxy.newProxyInstance(classLoader, Array(serviceInterface), invocationHandler).asInstanceOf[Service]
serviceStub.descriptor()
} else {
// If the default descriptor method is implemented in a non-public interface, throw an exception.
throw new IllegalArgumentException("Service API must be described in a public interface.")
}
}
def resolveServiceDescriptor(descriptor: Descriptor, classLoader: ClassLoader,
builtInSerializerFactories: Map[PlaceholderSerializerFactory, SerializerFactory],
builtInExceptionSerializers: Map[PlaceholderExceptionSerializer, ExceptionSerializer]): Descriptor = {
val builtInIdSerializers: Map[Type, PathParamSerializer[_]] = Map(
classOf[String] -> PathParamSerializers.STRING,
classOf[java.lang.Long] -> PathParamSerializers.LONG,
classOf[java.lang.Integer] -> PathParamSerializers.INTEGER,
classOf[java.lang.Double] -> PathParamSerializers.DOUBLE,
classOf[java.lang.Boolean] -> PathParamSerializers.BOOLEAN,
classOf[java.util.Optional[_]] -> PathParamSerializers.OPTIONAL
)
val builtInMessageSerializers: Map[Type, MessageSerializer[_, _]] = Map(
classOf[NotUsed] -> MessageSerializers.NOT_USED,
classOf[String] -> MessageSerializers.STRING
)
val serializerFactory = descriptor.serializerFactory() match {
case placeholder: PlaceholderSerializerFactory =>
builtInSerializerFactories.getOrElse(placeholder, {
throw new IllegalArgumentException("PlaceholderSerializerFactory " + placeholder + " not found")
})
case other => other
}
val exceptionSerializer = descriptor.exceptionSerializer() match {
case placeholder: PlaceholderExceptionSerializer =>
builtInExceptionSerializers.getOrElse(placeholder, {
throw new IllegalArgumentException("PlaceholderExceptionSerializer " + placeholder + " not found")
})
case other => other
}
val serviceResolver = new ServiceCallResolver(
builtInIdSerializers ++ descriptor.pathParamSerializers().asScala,
builtInMessageSerializers ++ descriptor.messageSerializers().asScala, serializerFactory
)
val endpoints = descriptor.calls().asScala.map { ep =>
val endpoint = ep.asInstanceOf[Call[Any, Any]]
val methodRefServiceCallHolder = ep.serviceCallHolder() match {
case methodRef: MethodRefServiceCallHolder => methodRef
case other => throw new IllegalArgumentException("Unknown ServiceCallHolder type: " + other)
}
val method = methodRefServiceCallHolder.methodReference match {
case preResolved: Method => preResolved
case lambda =>
try {
MethodRefResolver.resolveMethodRef(lambda)
} catch {
case NonFatal(e) =>
throw new IllegalStateException("Unable to resolve method for service call with ID " + ep.callId() +
". Ensure that the you have passed a method reference (ie, this::someMethod). Passing anything else, " +
"for example lambdas, anonymous classes or actual implementation classes, is forbidden in declaring a " +
"service descriptor.", e)
}
}
val serviceCallType = TypeToken.of(method.getGenericReturnType)
.asInstanceOf[TypeToken[ServiceCall[_, _]]]
.getSupertype(classOf[ServiceCall[_, _]])
.getType match {
case param: ParameterizedType => param
case _ => throw new IllegalStateException("ServiceCall is not a parameterized type?")
}
// Now get the type arguments
val (request, response) = serviceCallType.getActualTypeArguments match {
case Array(request, response) =>
if (method.getReturnType == classOf[ServiceCall[_, _]]) {
(request, response)
} else {
throw new IllegalArgumentException("Service calls must return ServiceCall, subtypes are not allowed")
}
case _ => throw new IllegalStateException("ServiceCall does not have 2 type arguments?")
}
val serviceCallHolder = constructServiceCallHolder(serviceResolver, method)
val endpointWithCallId = endpoint.callId() match {
case named: NamedCallId if named.name() == "__unresolved__" => endpoint.withCallId(new NamedCallId(method.getName))
case other => endpoint // todo validate paths against method arguments
}
val endpointWithCircuitBreaker = if (endpointWithCallId.circuitBreaker().isPresent) {
endpointWithCallId
} else {
endpointWithCallId.withCircuitBreaker(descriptor.circuitBreaker())
}
endpointWithCircuitBreaker
.withServiceCallHolder(serviceCallHolder)
.withRequestSerializer(serviceResolver.resolveMessageSerializer(endpoint.requestSerializer(), request))
.withResponseSerializer(serviceResolver.resolveMessageSerializer(endpoint.responseSerializer(), response))
}
val topicResolver = new TopicCallResolver(
builtInMessageSerializers ++ descriptor.messageSerializers().asScala,
serializerFactory
)
val topics = descriptor.topicCalls().asScala.map { tc =>
val topicCall = tc.asInstanceOf[TopicCall[Any]]
val methodRefTopicSourceHolder = topicCall.topicHolder match {
case methodRef: MethodRefTopicHolder => methodRef
case other => throw new IllegalArgumentException(s"Unknown ${classOf[TopicHolder].getSimpleName} type: " + other)
}
val method = methodRefTopicSourceHolder.methodReference match {
case preResolved: Method => preResolved
case lambda =>
try {
MethodRefResolver.resolveMethodRef(lambda)
} catch {
case NonFatal(e) =>
throw new IllegalStateException("Unable to resolve method for topic call with ID " + topicCall.topicId +
". Ensure that the you have passed a method reference (ie, this::someMethod). Passing anything else, " +
"for example lambdas, anonymous classes or actual implementation classes, is forbidden in declaring a " +
"topic descriptor.", e)
}
}
val topicParametrizedType = TypeToken.of(method.getGenericReturnType)
.asInstanceOf[TypeToken[Topic[_]]]
.getSupertype(classOf[Topic[_]])
.getType match {
case param: ParameterizedType => param
case _ => throw new IllegalStateException("Topic is not a parameterized type?")
}
// Now get the type arguments
val topicMessageType = topicParametrizedType.getActualTypeArguments match {
case Array(messageType) =>
if (method.getReturnType == classOf[Topic[_]]) {
messageType
} else {
throw new IllegalArgumentException("Topic calls must return Topic, subtypes are not allowed")
}
case _ => throw new IllegalStateException("Topic does not have 1 type argument?")
}
val topicHolder = constructTopicHolder(serviceResolver, method, topicCall.topicId)
val resolvedMessageSerializer = topicResolver.resolveMessageSerializer(topicCall.messageSerializer, topicMessageType).asInstanceOf[MessageSerializer[Any, ByteString]]
topicCall
.withTopicHolder(topicHolder)
.withMessageSerializer(resolvedMessageSerializer)
}
val acls = descriptor.acls.asScala ++ endpoints.collect {
case autoAclCall if autoAclCall.autoAcl.asScala.map(_.booleanValue).getOrElse(descriptor.autoAcl) =>
val pathSpec = JavadslPath.fromCallId(autoAclCall.callId).regex.regex
val method = autoAclCall.callId match {
case named: NamedCallId => methodFromSerializer(autoAclCall.requestSerializer, autoAclCall.responseSerializer)
case path: PathCallId => methodFromSerializer(autoAclCall.requestSerializer, autoAclCall.responseSerializer)
case rest: RestCallId => rest.method
}
ServiceAcl.methodAndPath(method, pathSpec)
}
descriptor.replaceAllCalls(TreePVector.from(endpoints.asJava.asInstanceOf[java.util.List[Call[_, _]]]))
.withExceptionSerializer(exceptionSerializer)
.replaceAllAcls(TreePVector.from(acls.asJava))
.replaceAllTopicCalls(TreePVector.from(topics.asJava.asInstanceOf[java.util.List[TopicCall[_]]]))
}
private def constructServiceCallHolder[Request, Response](serviceCallResolver: ServiceCallResolver, method: Method): ServiceCallHolder = {
val serializers = method.getGenericParameterTypes.toSeq.map { arg =>
serviceCallResolver.resolvePathParamSerializer(new UnresolvedTypePathParamSerializer[AnyRef], arg)
}
import scala.collection.JavaConverters._
val theMethod = method
new MethodServiceCallHolder {
override def invoke(arguments: Seq[AnyRef]): Seq[Seq[String]] = {
if (arguments == null) {
Nil
} else {
arguments.zip(serializers).map {
case (arg, serializer) => serializer.serialize(arg).asScala
}
}
}
override def create(service: Any, parameters: Seq[Seq[String]]): ServiceCall[_, _] = {
val args = parameters.zip(serializers).map {
case (params, serializer) => serializer.deserialize(TreePVector.from(params.asJavaCollection))
}
theMethod.invoke(service, args: _*).asInstanceOf[ServiceCall[_, _]]
}
override val method: Method = theMethod
}
}
private def constructTopicHolder(serviceCallResolver: ServiceCallResolver, _method: Method, topicId: TopicId): TopicHolder = {
new MethodTopicHolder {
override val method: Method = _method
override def create(service: Any): Topic[_] = {
method.invoke(service).asInstanceOf[InternalTopic[_]]
}
}
}
class ServiceInvocationHandler(classLoader: ClassLoader, serviceInterface: Class[_ <: Service]) extends InvocationHandler {
override def invoke(proxy: scala.Any, method: Method, args: Array[AnyRef]): AnyRef = {
// If it's a default method, invoke it
if (method.isDefault) {
// This is the way to invoke default methods via reflection, using the JDK7 method handles API
val declaringClass = method.getDeclaringClass
// We create a MethodHandles.Lookup that is allowed to look up private methods
methodHandlesLookupConstructor.newInstance(declaringClass, new Integer(MethodHandles.Lookup.PRIVATE))
// Now using unreflect special, we get the default method from the declaring class, rather than the proxy
.unreflectSpecial(method, declaringClass)
// We bind to the proxy so that we end up invoking on the proxy
.bindTo(proxy)
// And now we actually invoke it
.invokeWithArguments(args: _*)
} else if (method.getName == DescriptorMethodName && method.getParameterCount == 0) {
if (ScalaSig.isScala(serviceInterface)) {
if (serviceInterface.isInterface()) {
val implClass = Class.forName(serviceInterface.getName + "$class", false, classLoader)
val method = implClass.getMethod(DescriptorMethodName, serviceInterface)
method.invoke(null, proxy.asInstanceOf[AnyRef])
} else {
throw new IllegalArgumentException("Service.descriptor must be implemented in a trait")
}
} else {
// If this is the descriptor method, and it doesn't have a default implementation, throw an exception
throw new IllegalArgumentException("Service.descriptor must be implemented as a default method")
}
} else if (classOf[ServiceCall[_, _]].isAssignableFrom(method.getReturnType)) {
throw new IllegalStateException("Service call method " + method + " was invoked on self describing service " +
serviceInterface + " while loading descriptor, which is not allowed.")
} else {
throw new IllegalStateException("Abstract method " + method + " invoked on self describing service " +
serviceInterface + " while loading descriptor, which is not allowed.")
}
}
}
private def methodFromSerializer(requestSerializer: MessageSerializer[_, _], responseSerializer: MessageSerializer[_, _]) = {
if (requestSerializer.isStreamed || responseSerializer.isStreamed) {
com.lightbend.lagom.javadsl.api.transport.Method.GET
} else if (requestSerializer.isUsed) {
com.lightbend.lagom.javadsl.api.transport.Method.POST
} else {
com.lightbend.lagom.javadsl.api.transport.Method.GET
}
}
}
/**
* Internal API.
*
* Service call holder that holds the original method reference that was passed to the descriptor when the service
* descriptor was defined.
*
* @param methodReference The method reference (a lambda object).
*/
private[lagom] case class MethodRefServiceCallHolder(methodReference: Any) extends ServiceCallHolder
/**
* Internal API.
*
* Service call holder that's used by the service router and client implementor to essentially the raw id to and from
* invocations of the service call method.
*/
private[lagom] trait MethodServiceCallHolder extends ServiceCallHolder {
val method: Method
def create(service: Any, parameters: Seq[Seq[String]]): ServiceCall[_, _]
def invoke(arguments: Seq[AnyRef]): Seq[Seq[String]]
}
private[lagom] case class MethodRefTopicHolder(methodReference: Any) extends TopicHolder
private[lagom] trait MethodTopicHolder extends TopicHolder {
val method: Method
def create(service: Any): Topic[_]
}
|
edouardKaiser/lagom
|
service/javadsl/api/src/main/scala/com/lightbend/lagom/internal/javadsl/api/ServiceReader.scala
|
Scala
|
apache-2.0
| 15,348 |
package org.otw.open.util
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.g2d.Animation.PlayMode
import com.badlogic.gdx.graphics.g2d.{Animation, TextureAtlas}
import org.otw.open.controllers.GameState
/**
* Animator class that will handle all texture transitions for game animations
*
* Created by jivanovski on 1/25/2016.
*/
class Animator(val atlasFileName: String, val playMode: PlayMode = PlayMode.LOOP) {
/** global atlas */
private val atlas = new TextureAtlas(Gdx.files.internal("theme/" + GameState.getThemeName + "/" + atlasFileName))
/** animation setup */
private val animation = new Animation(1 / 7f, atlas.getRegions)
animation.setPlayMode(playMode)
/**
*
* @param timePassed time passed since animation started
* @return current texture region for the animation
*/
def getCurrentTexture(timePassed: Float) = animation.getKeyFrame(timePassed, true)
/**
* Disposes all disposable resources.
*
* @return true if the method is implemented.
*/
def dispose(): Boolean = {
atlas.dispose()
true
}
/**
* A private method that will return Animation object. This method is strictly for unit testing purposes.
* @return the used Animation object.
*/
private def getAnimationObject: Animation = animation
}
|
danielEftimov/OPEN
|
core/src/org/otw/open/util/Animator.scala
|
Scala
|
apache-2.0
| 1,314 |
/*
* Copyright 2001-2013 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalactic
import scala.collection.GenTraversable
import scala.collection.mutable.Buffer
import scala.collection.mutable.ListBuffer
class ChainSpec extends UnitSpec {
"A Chain" can "be constructed with one element" in {
val onesie = Chain(3)
onesie.length shouldBe 1
onesie(0) shouldBe 3
}
it can "be constructed with many elements" in {
val twosie = Chain(2, 3)
twosie.length shouldBe 2
twosie(0) shouldBe 2
twosie(1) shouldBe 3
val threesie = Chain(1, 2, 3)
threesie.length shouldBe 3
threesie(0) shouldBe 1
threesie(1) shouldBe 2
threesie(2) shouldBe 3
}
it can "be constructed from a GenTraversable via the from method on Chain singleton" in {
Chain.from(List.empty[String]) shouldBe None
Chain.from(List("1")) shouldBe Some(Chain("1"))
Chain.from(List(1, 2, 3)) shouldBe Some(Chain(1, 2, 3))
// SKIP-SCALATESTJS-START
Chain.from(List.empty[String].par) shouldBe None
Chain.from(List("1").par) shouldBe Some(Chain("1"))
Chain.from(List(1, 2, 3).par) shouldBe Some(Chain(1, 2, 3))
// SKIP-SCALATESTJS-END
}
it can "be constructed with null elements" in {
noException should be thrownBy Chain("hi", null, "ho")
noException should be thrownBy Chain(null)
noException should be thrownBy Chain("ho", null)
}
it can "be constructed using cons-End style" in {
0 :: 1 :: End shouldBe Chain(0, 1)
0 :: 1 :: 2 :: End shouldBe Chain(0, 1, 2)
"zero" :: "one" :: "two" :: End shouldBe Chain("zero", "one", "two")
}
it can "be deconstructed with Chain" in {
Chain(1) match {
case Chain(x) => x shouldEqual 1
case _ => fail()
}
Chain("hi") match {
case Chain(s) => s shouldEqual "hi"
case _ => fail()
}
}
it can "be deconstructed with Many" in {
Chain(1, 2, 3) match {
case Chain(x, y, z) => (x, y, z) shouldEqual (1, 2, 3)
case _ => fail()
}
Chain("hi", "there") match {
case Chain(s, t) => (s, t) shouldEqual ("hi", "there")
case _ => fail()
}
Chain(1, 2, 3) match {
case Chain(x, y, _) => (x, y) shouldEqual (1, 2)
case _ => fail()
}
Chain(1, 2, 3, 4, 5) match {
case Chain(x, y, _*) => (x, y) shouldEqual (1, 2)
case _ => fail()
}
}
it can "be deconstructed with Every" in {
Chain(1, 2, 3) match {
case Chain(x, y, z) => (x, y, z) shouldEqual (1, 2, 3)
case _ => fail()
}
Chain("hi", "there") match {
case Chain(s, t) => (s, t) shouldEqual ("hi", "there")
case _ => fail()
}
Chain(1, 2, 3) match {
case Chain(x, y, _) => (x, y) shouldEqual (1, 2)
case _ => fail()
}
Chain(1, 2, 3, 4, 5) match {
case Chain(x, y, _*) => (x, y) shouldEqual (1, 2)
case _ => fail()
}
Chain(1, 2, 3) match {
case Chain(x, _*) => x shouldEqual 1
case _ => fail()
}
Chain("hi") match {
case Chain(s) => s shouldEqual "hi"
case _ => fail()
}
Chain(1, 2, 3) match {
case Chain(x, y, z) => (x, y, z) shouldEqual (1, 2, 3)
case _ => fail()
}
Chain("hi", "there") match {
case Chain(s, t) => (s, t) shouldEqual ("hi", "there")
case _ => fail()
}
Chain(1, 2, 3) match {
case Chain(x, y, _) => (x, y) shouldEqual (1, 2)
case _ => fail()
}
Chain(1, 2, 3, 4, 5) match {
case Chain(x, y, _*) => (x, y) shouldEqual (1, 2)
case _ => fail()
}
Chain(1, 2, 3) match {
case Chain(x, _*) => x shouldEqual 1
case _ => fail()
}
}
it should "have an apply method" in {
Chain(1, 2, 3)(0) shouldEqual 1
Chain(1, 2, 3)(1) shouldEqual 2
Chain("hi")(0) shouldEqual "hi"
Chain(7, 8, 9)(2) shouldEqual 9
the [IndexOutOfBoundsException] thrownBy {
Chain(1, 2, 3)(3)
} should have message "3"
}
it should "have a length method" in {
Chain(1).length shouldBe 1
Chain(1, 2).length shouldBe 2
Chain(1, 2, 3, 4, 5).length shouldBe 5
}
it should "have a ++ method that takes another Chain" in {
Chain(1, 2, 3) ++ Chain(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ++ Chain(4, 5) shouldEqual Chain(1, 2, 3, 4, 5)
Chain(1, 2, 3) ++ Chain(4, 5, 6) shouldEqual Chain(1, 2, 3, 4, 5, 6)
}
it should "have a ++ method that takes an Every" in {
Chain(1, 2, 3) ++ One(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ++ Every(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ++ Every(4, 5, 6) shouldEqual Chain(1, 2, 3, 4, 5, 6)
Chain(1, 2, 3) ++ One(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ++ One(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ++ Every(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ++ Every(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ++ One(4) shouldEqual Chain(1, 2, 3, 4)
}
it should "have a ++ method that takes a GenTraversableOnce" in {
Chain(1, 2, 3) ++ List(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ++ Vector(4, 5, 6) shouldEqual Chain(1, 2, 3, 4, 5, 6)
Chain(1, 2, 3) ++ GenTraversable(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ++ Set(4, 5) shouldEqual Chain(1, 2, 3, 4, 5)
Chain(1, 2, 3) ++ Set(4, 5).iterator shouldEqual Chain(1, 2, 3, 4, 5)
}
it should "have a +: method" in {
0 +: Chain(1) shouldBe Chain(0, 1)
0 +: Chain(1, 2) shouldBe Chain(0, 1, 2)
"zero" +: Chain("one", "two") shouldBe Chain("zero", "one", "two")
}
it should "have a :: method" in {
0 :: Chain(1) shouldBe Chain(0, 1)
0 :: Chain(1, 2) shouldBe Chain(0, 1, 2)
"zero" :: Chain("one", "two") shouldBe Chain("zero", "one", "two")
}
it should "have a ::: method that takes another Chain" in {
Chain(1, 2, 3) ::: Chain(4) shouldEqual Chain(1, 2, 3, 4)
Chain(1, 2, 3) ::: Chain(4, 5) shouldEqual Chain(1, 2, 3, 4, 5)
Chain(1, 2, 3) ::: Chain(4, 5, 6) shouldEqual Chain(1, 2, 3, 4, 5, 6)
}
it should "have a ::: method that takes an Every" in {
One(1) ::: Chain(2, 3, 4) shouldEqual Chain(1, 2, 3, 4)
Every(1) ::: Chain(2, 3, 4) shouldEqual Chain(1, 2, 3, 4)
Every(1, 2, 3) ::: Chain(4, 5, 6) shouldEqual Chain(1, 2, 3, 4, 5, 6)
One(1) ::: Chain(2, 3, 4) shouldEqual Chain(1, 2, 3, 4)
One(1) ::: Chain(2, 3, 4) shouldEqual Chain(1, 2, 3, 4)
Every(1) ::: Chain(2, 3, 4) shouldEqual Chain(1, 2, 3, 4)
Every(1) ::: Chain(2, 3, 4) shouldEqual Chain(1, 2, 3, 4)
One(1) ::: Chain(2, 3, 4) shouldEqual Chain(1, 2, 3, 4)
}
it should "have a ::: method that takes a GenTraversableOnce" in {
List(1) ::: Chain(2, 3, 4) shouldEqual Chain(1, 2, 3, 4)
Vector(1, 2, 3) ::: Chain(4, 5, 6) shouldEqual Chain(1, 2, 3, 4, 5, 6)
GenTraversable(1) ::: Chain(2, 3, 4) shouldEqual Chain(1, 2, 3, 4)
Set(1, 2) ::: Chain(3, 4, 5) shouldEqual Chain(1, 2, 3, 4, 5)
Set(1, 2).iterator ::: Chain(3, 4, 5) shouldEqual Chain(1, 2, 3, 4, 5)
}
it should "implement PartialFunction[Int, T]" in {
val pf1: PartialFunction[Int, Int] = Chain(1)
pf1.isDefinedAt(0) shouldBe true
pf1.isDefinedAt(1) shouldBe false
}
it should "have a /: method" in {
(0 /: Chain(1))(_ + _) shouldBe 1
(1 /: Chain(1))(_ + _) shouldBe 2
(0 /: Chain(1, 2, 3))(_ + _) shouldBe 6
(1 /: Chain(1, 2, 3))(_ + _) shouldBe 7
}
it should "have a :+ method" in {
Chain(1) :+ 2 shouldBe Chain(1, 2)
Chain(1, 2) :+ 3 shouldBe Chain(1, 2, 3)
}
it should "have a :\\\\ method" in {
(Chain(1) :\\ 0)(_ + _) shouldBe 1
(Chain(1) :\\ 1)(_ + _) shouldBe 2
(Chain(1, 2, 3) :\\ 0)(_ + _) shouldBe 6
(Chain(1, 2, 3) :\\ 1)(_ + _) shouldBe 7
}
it should "have 3 addString methods" in {
Chain("hi").addString(new StringBuilder) shouldBe new StringBuilder("hi")
Chain(1, 2, 3).addString(new StringBuilder) shouldBe new StringBuilder("123")
Chain("hi").addString(new StringBuilder, "#") shouldBe new StringBuilder("hi")
Chain(1, 2, 3).addString(new StringBuilder, "#") shouldBe new StringBuilder("1#2#3")
Chain(1, 2, 3).addString(new StringBuilder, ", ") shouldBe new StringBuilder("1, 2, 3")
Chain("hi").addString(new StringBuilder, "<", "#", ">") shouldBe new StringBuilder("<hi>")
Chain(1, 2, 3).addString(new StringBuilder, "<", "#", ">") shouldBe new StringBuilder("<1#2#3>")
Chain(1, 2, 3).addString(new StringBuilder, " ( ", ", ", " ) ") shouldBe new StringBuilder(" ( 1, 2, 3 ) ")
}
it should "have an andThen method (inherited from PartialFunction)" in {
val pf1 = Chain(1) andThen (_ + 1)
pf1(0) shouldEqual 2
val pf2 = Chain(1, 2, 3) andThen (_ + 1)
pf2(0) shouldEqual 2
pf2(1) shouldEqual 3
pf2(2) shouldEqual 4
}
it should "have an applyOrElse method (inherited from PartialFunction)" in {
Chain(1, 2, 3).applyOrElse(0, (_: Int) * -1) shouldEqual 1
Chain(1, 2, 3).applyOrElse(1, (_: Int) * -1) shouldEqual 2
Chain(1, 2, 3).applyOrElse(2, (_: Int) * -1) shouldEqual 3
Chain(1, 2, 3).applyOrElse(3, (_: Int) * -1) shouldEqual -3
Chain(1, 2, 3).applyOrElse(4, (_: Int) * -1) shouldEqual -4
}
it should "have an canEqual method" is pending
// it should "have an charAt method" is pending
// Could have an implicit conversion from Every[Char] to CharSequence like
// there is for Seq in Predef.
/*
scala> Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).collect { case i if i > 10 == 0 => i / 2 }
res1: scala.collection.immutable.Vector[Int] = Vector()
*/
it should "have an collectFirst method" in {
Chain(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) collectFirst { case i if i > 10 => i / 2 } shouldBe None
Chain(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) collectFirst { case i if i > 10 => i / 2 } shouldBe Some(5)
}
/*
scala> Vector(1).combinations(2).toVector
res2: Vector[scala.collection.immutable.Vector[Int]] = Vector()
*/
/*
companion method not relevant. Has an empty and other GenTraverable stuff.
*/
it should "have an compose method, inherited from PartialFunction" in {
val fn: Int => Int = Chain(1, 2, 3).compose((_: Int) + 1)
fn(-1) shouldBe 1
fn(0) shouldBe 2
fn(1) shouldBe 3
}
it should "have a contains method" in {
val e = Chain(1, 2, 3)
e.contains(-1) shouldBe false
e.contains(0) shouldBe false
e.contains(1) shouldBe true
e.contains(2) shouldBe true
e.contains(3) shouldBe true
e.contains(4) shouldBe false
val es = Chain("one", "two", "three")
es.contains("one") shouldBe true;
es.contains("ONE") shouldBe false;
{
implicit val strEq = StringNormalizations.lowerCased.toEquality
es.contains("one") shouldBe true;
es.contains("ONE") shouldBe false
}
}
// Decided to just overload one for GenSeq and one for Every. Could have done
// what that has a Slicing nature, but that's a bit too fancy pants.
it should "have a containsSlice method that takes GenSeq" in {
val chain = Chain(1, 2, 3, 4, 5)
chain.containsSlice(List(2, 3)) shouldBe true
chain.containsSlice(List(2, 3, 5)) shouldBe false
chain.containsSlice(List.empty) shouldBe true
chain.containsSlice(Vector(2, 3)) shouldBe true
chain.containsSlice(Vector(2, 3, 5)) shouldBe false
chain.containsSlice(Vector.empty) shouldBe true
chain.containsSlice(ListBuffer(2, 3)) shouldBe true
chain.containsSlice(ListBuffer(2, 3, 5)) shouldBe false
chain.containsSlice(ListBuffer.empty) shouldBe true
}
it should "have a containsSlice method that takes an Every" in {
val chain = Chain(1, 2, 3, 4, 5)
chain.containsSlice(Every(2, 3)) shouldBe true
chain.containsSlice(Every(2, 3, 5)) shouldBe false
chain.containsSlice(Every(3)) shouldBe true
}
it should "have a containsSlice method that takes a Chain" in {
val chain = Chain(1, 2, 3, 4, 5)
chain.containsSlice(Chain(2, 3)) shouldBe true
chain.containsSlice(Chain(2, 3, 5)) shouldBe false
chain.containsSlice(Chain(3)) shouldBe true
}
it should "have 3 copyToArray methods" in {
val arr1 = Array.fill(5)(-1)
Chain(1, 2, 3, 4, 5).copyToArray(arr1)
arr1 shouldEqual Array(1, 2, 3, 4, 5)
val arr2 = Array.fill(5)(-1)
Chain(1, 2, 3, 4, 5).copyToArray(arr2, 1)
arr2 shouldEqual Array(-1, 1, 2, 3, 4)
val arr3 = Array.fill(5)(-1)
Chain(1, 2, 3, 4, 5).copyToArray(arr3, 1, 2)
arr3 shouldEqual Array(-1, 1, 2, -1, -1)
}
it should "have a copyToBuffer method" in {
val buf = ListBuffer.fill(3)(-1)
Chain(1, 2, 3, 4, 5).copyToBuffer(buf)
buf shouldEqual Buffer(-1, -1, -1, 1, 2, 3, 4, 5)
}
it should "have a corresponds method that takes a GenSeq" in {
val chain = Chain(1, 2, 3, 4, 5)
chain.corresponds(List(2, 4, 6, 8, 10))(_ * 2 == _) shouldBe true
chain.corresponds(List(2, 4, 6, 8, 11))(_ * 2 == _) shouldBe false
chain.corresponds(List(2, 4, 6, 8))(_ * 2 == _) shouldBe false
chain.corresponds(List(2, 4, 6, 8, 10, 12))(_ * 2 == _) shouldBe false
}
it should "have a corresponds method that takes an Every" in {
val chain = Chain(1, 2, 3, 4, 5)
chain.corresponds(Many(2, 4, 6, 8, 10))(_ * 2 == _) shouldBe true
chain.corresponds(Many(2, 4, 6, 8, 11))(_ * 2 == _) shouldBe false
chain.corresponds(Many(2, 4, 6, 8))(_ * 2 == _) shouldBe false
chain.corresponds(Many(2, 4, 6, 8, 10, 12))(_ * 2 == _) shouldBe false
}
it should "have a corresponds method that takes a Chain" in {
val chain = Chain(1, 2, 3, 4, 5)
chain.corresponds(Chain(2, 4, 6, 8, 10))(_ * 2 == _) shouldBe true
chain.corresponds(Chain(2, 4, 6, 8, 11))(_ * 2 == _) shouldBe false
chain.corresponds(Chain(2, 4, 6, 8))(_ * 2 == _) shouldBe false
chain.corresponds(Chain(2, 4, 6, 8, 10, 12))(_ * 2 == _) shouldBe false
}
it should "have a count method" in {
val chain = Chain(1, 2, 3, 4, 5)
chain.count(_ > 10) shouldBe 0
chain.count(_ % 2 == 0) shouldBe 2
chain.count(_ % 2 == 1) shouldBe 3
}
/*
it should not have a diff method
scala> Vector(1, 2, 3).diff(Vector(1, 2, 3))
res0: scala.collection.immutable.Vector[Int] = Vector()
*/
it should "have a distinct method" in {
Chain(1, 2, 3).distinct shouldBe Chain(1, 2, 3)
Chain(1).distinct shouldBe Chain(1)
Chain(1, 2, 1, 1).distinct shouldBe Chain(1, 2)
Chain(1, 1, 1).distinct shouldBe Chain(1)
}
/*
it should not have an drop method
scala> Vector(1, 2, 3).drop(3)
res1: scala.collection.immutable.Vector[Int] = Vector()
it should not have an dropRight method
scala> Vector(1, 2, 3).dropRight(3)
res0: scala.collection.immutable.Vector[Int] = Vector()
it should not have an dropWhile method
scala> Vector(1, 2, 3).dropWhile(_ < 10)
res2: scala.collection.immutable.Vector[Int] = Vector()
*/
it should "have an endsWith method that takes a GenSeq" in {
Chain(1).endsWith(List(1)) shouldBe true
Chain(1).endsWith(List(1, 2)) shouldBe false
Chain(1, 2).endsWith(List(1, 2)) shouldBe true
Chain(1, 2, 3, 4, 5).endsWith(List(1, 2)) shouldBe false
Chain(1, 2, 3, 4, 5).endsWith(List(5)) shouldBe true
Chain(1, 2, 3, 4, 5).endsWith(List(3, 4, 5)) shouldBe true
}
it should "have an endsWith method that takes an Every" in {
Chain(1).endsWith(Every(1)) shouldBe true
Chain(1).endsWith(Every(1, 2)) shouldBe false
Chain(1, 2).endsWith(Every(1, 2)) shouldBe true
Chain(1, 2, 3, 4, 5).endsWith(Every(1, 2)) shouldBe false
Chain(1, 2, 3, 4, 5).endsWith(Every(5)) shouldBe true
Chain(1, 2, 3, 4, 5).endsWith(Every(3, 4, 5)) shouldBe true
}
it should "have an endsWith method that takes a Chain" in {
Chain(1).endsWith(Chain(1)) shouldBe true
Chain(1).endsWith(Chain(1, 2)) shouldBe false
Chain(1, 2).endsWith(Chain(1, 2)) shouldBe true
Chain(1, 2, 3, 4, 5).endsWith(Chain(1, 2)) shouldBe false
Chain(1, 2, 3, 4, 5).endsWith(Chain(5)) shouldBe true
Chain(1, 2, 3, 4, 5).endsWith(Chain(3, 4, 5)) shouldBe true
}
it should "have an equals method" in {
Chain(1) shouldEqual Chain(1)
Chain(1) should not equal Chain(2)
Chain(1, 2) should not equal Chain(2, 3)
}
it should "have an exists method" in {
Chain(1, 2, 3).exists(_ == 2) shouldBe true
Chain(1, 2, 3).exists(_ == 5) shouldBe false
}
/*
it should not have a filter method
scala> Vector(1, 2, 3).filter(_ > 10)
res12: scala.collection.immutable.Vector[Int] = Vector()
it should not have a filterNot method
scala> Vector(1, 2, 3).filterNot(_ < 10)
res13: scala.collection.immutable.Vector[Int] = Vector()
*/
it should "have a find method" in {
Chain(1, 2, 3).find(_ == 5) shouldBe None
Chain(1, 2, 3).find(_ == 2) shouldBe Some(2)
}
it should "have a flatMap method" in {
Chain(1, 2, 3) flatMap (i => Chain(i + 1)) shouldBe Chain(2, 3, 4)
val ss = Chain("hi", "ho")
val is = Chain(1, 2, 3)
(for (s <- ss; i <- is) yield (s, i)) shouldBe
Chain(
("hi",1), ("hi",2), ("hi",3), ("ho",1), ("ho",2), ("ho",3)
)
Chain(5) flatMap (i => Chain(i + 3)) shouldBe Chain(8)
Chain(8) flatMap (i => Chain(i.toString)) shouldBe Chain("8")
}
/*
Can only flatten Chains
scala> Vector(Set.empty[Int], Set.empty[Int]).flatten
res17: scala.collection.immutable.Vector[Int] = Vector()
*/
// TODO: Actually it would make sense to flatten Everys too
it should "have a flatten method that works on nested Chains" in {
Chain(Chain(1, 2, 3), Chain(1, 2, 3)).flatten shouldBe Chain(1, 2, 3, 1, 2, 3)
Chain(Chain(1)).flatten shouldBe Chain(1)
}
it can "be flattened when in a GenTraversableOnce" in {
Vector(Chain(1, 2, 3), Chain(1, 2, 3)).flatten shouldBe Vector(1, 2, 3, 1, 2, 3)
List(Chain(1, 2, 3), Chain(1, 2, 3)).flatten shouldBe List(1, 2, 3, 1, 2, 3)
List(Chain(1, 2, 3), Chain(1, 2, 3)).toIterator.flatten.toStream shouldBe List(1, 2, 3, 1, 2, 3).toIterator.toStream
// SKIP-SCALATESTJS-START
List(Chain(1, 2, 3), Chain(1, 2, 3)).par.flatten shouldBe List(1, 2, 3, 1, 2, 3).par
// SKIP-SCALATESTJS-END
}
it should "have a fold method" in {
Chain(1).fold(0)(_ + _) shouldBe 1
Chain(1).fold(1)(_ * _) shouldBe 1
Chain(2).fold(0)(_ + _) shouldBe 2
Chain(2).fold(1)(_ * _) shouldBe 2
Chain(3).fold(0)(_ + _) shouldBe 3
Chain(3).fold(1)(_ * _) shouldBe 3
Chain(1, 2, 3).fold(0)(_ + _) shouldBe 6
Chain(1, 2, 3).fold(1)(_ * _) shouldBe 6
Chain(1, 2, 3, 4, 5).fold(0)(_ + _) shouldBe 15
Chain(1, 2, 3, 4, 5).fold(1)(_ * _) shouldBe 120
}
it should "have a foldLeft method" in {
Chain(1).foldLeft(0)(_ + _) shouldBe 1
Chain(1).foldLeft(1)(_ + _) shouldBe 2
Chain(1, 2, 3).foldLeft(0)(_ + _) shouldBe 6
Chain(1, 2, 3).foldLeft(1)(_ + _) shouldBe 7
}
it should "have a foldRight method" in {
Chain(1).foldRight(0)(_ + _) shouldBe 1
Chain(1).foldRight(1)(_ + _) shouldBe 2
Chain(1, 2, 3).foldRight(0)(_ + _) shouldBe 6
Chain(1, 2, 3).foldRight(1)(_ + _) shouldBe 7
}
it should "have a forall method" in {
Chain(1, 2, 3, 4, 5).forall(_ > 0) shouldBe true
Chain(1, 2, 3, 4, 5).forall(_ < 0) shouldBe false
}
it should "have a foreach method" in {
var num = 0
Chain(1, 2, 3) foreach (num += _)
num shouldBe 6
for (i <- Chain(1, 2, 3))
num += i
num shouldBe 12
Chain(5) foreach (num *= _)
num shouldBe 60
}
it should "have a groupBy method" in {
Chain(1, 2, 3, 4, 5).groupBy(_ % 2) shouldBe Map(1 -> Chain(1, 3, 5), 0 -> Chain(2, 4))
Chain(1, 2, 3, 3, 3).groupBy(_ % 2) shouldBe Map(1 -> Chain(1, 3, 3, 3), 0 -> Chain(2))
Chain(1, 1, 3, 3, 3).groupBy(_ % 2) shouldBe Map(1 -> Chain(1, 1, 3, 3, 3))
Chain(1, 2, 3, 5, 7).groupBy(_ % 2) shouldBe Map(1 -> Chain(1, 3, 5, 7), 0 -> Chain(2))
}
it should "have a grouped method" in {
Chain(1, 2, 3).grouped(2).toList shouldBe List(Chain(1, 2), Chain(3))
Chain(1, 2, 3).grouped(1).toList shouldBe List(Chain(1), Chain(2), Chain(3))
an [IllegalArgumentException] should be thrownBy { Chain(1, 2, 3).grouped(0).toList }
Chain(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).grouped(2).toList shouldBe List(Chain(1, 2), Chain(3, 4), Chain(5, 6), Chain(7, 8), Chain(9, 10))
Chain(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).grouped(3).toList shouldBe List(Chain(1, 2, 3), Chain(4, 5, 6), Chain(7, 8, 9), Chain(10))
Chain(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).grouped(4).toList shouldBe List(Chain(1, 2, 3, 4), Chain(5, 6, 7, 8), Chain(9, 10))
Chain(1).grouped(2).toList shouldBe List(Chain(1))
Chain(1).grouped(1).toList shouldBe List(Chain(1))
}
it should "have a hasDefiniteSize method" in {
Chain(1).hasDefiniteSize shouldBe true
Chain(1, 2).hasDefiniteSize shouldBe true
}
it should "have a hashCode method" in {
Chain(1).hashCode shouldEqual Chain(1).hashCode
Chain(1, 2).hashCode shouldEqual Chain(1, 2).hashCode
}
it should "have a head method" in {
Chain("hi").head shouldBe "hi"
Chain(1, 2, 3).head shouldBe 1
}
it should "have a headOption method" in {
Chain("hi").headOption shouldBe Some("hi")
Chain(1, 2, 3).headOption shouldBe Some(1)
}
it should "have 2 indexOf methods" in {
Chain(1, 2, 3, 4, 5).indexOf(3) shouldBe 2
Chain(1, 2, 3, 4, 5).indexOf(1) shouldBe 0
Chain(1, 2, 3, 4, 5).indexOf(1, 2) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOf(6) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOf(5, 3) shouldBe 4
val es = Chain("one", "two", "three")
es.indexOf("one") shouldBe 0;
es.indexOf("one", 1) shouldBe -1
es.indexOf("ONE") shouldBe -1;
{
implicit val strEq = StringNormalizations.lowerCased.toEquality
es.indexOf("one") shouldBe 0;
es.indexOf("ONE") shouldBe -1
}
}
it should "have 2 indexOfSlice methods that take a GenSeq" in {
Chain(1, 2, 3, 4, 5).indexOfSlice(List(2, 3)) shouldBe 1
Chain(1, 2, 3, 4, 5).indexOfSlice(List(2, 3), 3) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(List(2, 3, 5), 3) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(List(2, 3, 5)) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(List(5)) shouldBe 4
Chain(1, 2, 3, 4, 5).indexOfSlice(List(1, 2, 3, 4, 5)) shouldBe 0
Chain(1, 2, 3, 4, 5).indexOfSlice(List(1, 2, 3, 4, 5), 0) shouldBe 0
Chain(1, 2, 3, 4, 5).indexOfSlice(List(1, 2, 3, 4, 5), 1) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(List(1, 2, 3, 4, 5), -1) shouldBe 0
Chain(1, 2, 3, 4, 5).indexOfSlice(List.empty) shouldBe 0
Chain(1, 2, 3, 4, 5).indexOfSlice(List.empty, 6) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(List.empty, 4) shouldBe 4
val es = Chain("one", "two", "three", "four", "five")
es.indexOfSlice(List("one", "two")) shouldBe 0;
es.indexOfSlice(List("one", "two"), 1) shouldBe -1
es.indexOfSlice(List("ONE", "TWO")) shouldBe -1;
{
implicit val strEq = StringNormalizations.lowerCased.toEquality
es.indexOfSlice(List("one", "two")) shouldBe 0;
es.indexOfSlice(List("ONE", "TWO")) shouldBe -1
}
}
it should "have 2 indexOfSlice methods that take an Every" in {
Chain(1, 2, 3, 4, 5).indexOfSlice(Every(2, 3)) shouldBe 1
Chain(1, 2, 3, 4, 5).indexOfSlice(Every(2, 3), 3) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(Every(2, 3, 5), 3) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(Every(2, 3, 5)) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(Every(5)) shouldBe 4
Chain(1, 2, 3, 4, 5).indexOfSlice(Every(1, 2, 3, 4, 5)) shouldBe 0
Chain(1, 2, 3, 4, 5).indexOfSlice(Every(1, 2, 3, 4, 5), 0) shouldBe 0
Chain(1, 2, 3, 4, 5).indexOfSlice(Every(1, 2, 3, 4, 5), 1) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(Every(1, 2, 3, 4, 5), -1) shouldBe 0
val es = Chain("one", "two", "three", "four", "five")
es.indexOfSlice(Every("one", "two")) shouldBe 0;
es.indexOfSlice(Every("one", "two"), 1) shouldBe -1
es.indexOfSlice(Every("ONE", "TWO")) shouldBe -1;
{
implicit val strEq = StringNormalizations.lowerCased.toEquality
es.indexOfSlice(Every("one", "two")) shouldBe 0;
es.indexOfSlice(Every("ONE", "TWO")) shouldBe -1
}
}
it should "have 2 indexOfSlice methods that take a Chain" in {
Chain(1, 2, 3, 4, 5).indexOfSlice(Chain(2, 3)) shouldBe 1
Chain(1, 2, 3, 4, 5).indexOfSlice(Chain(2, 3), 3) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(Chain(2, 3, 5), 3) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(Chain(2, 3, 5)) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(Chain(5)) shouldBe 4
Chain(1, 2, 3, 4, 5).indexOfSlice(Chain(1, 2, 3, 4, 5)) shouldBe 0
Chain(1, 2, 3, 4, 5).indexOfSlice(Chain(1, 2, 3, 4, 5), 0) shouldBe 0
Chain(1, 2, 3, 4, 5).indexOfSlice(Chain(1, 2, 3, 4, 5), 1) shouldBe -1
Chain(1, 2, 3, 4, 5).indexOfSlice(Chain(1, 2, 3, 4, 5), -1) shouldBe 0
val es = Chain("one", "two", "three", "four", "five")
es.indexOfSlice(Chain("one", "two")) shouldBe 0;
es.indexOfSlice(Chain("one", "two"), 1) shouldBe -1
es.indexOfSlice(Chain("ONE", "TWO")) shouldBe -1;
{
implicit val strEq = StringNormalizations.lowerCased.toEquality
es.indexOfSlice(Chain("one", "two")) shouldBe 0;
es.indexOfSlice(Chain("ONE", "TWO")) shouldBe -1
}
}
it should "have 2 indexWhere methods" in {
Chain(1, 2, 3, 4, 5).indexWhere(_ == 3) shouldBe 2
Chain(1, 2, 3, 4, 5).indexWhere(_ == 1) shouldBe 0
Chain(1, 2, 3, 4, 5).indexWhere(_ == 1, 2) shouldBe -1
Chain(1, 2, 3, 4, 5).indexWhere(_ == 6) shouldBe -1
Chain(1, 2, 3, 4, 5).indexWhere(_ == 5, 3) shouldBe 4
}
it should "have an indices method" in {
Chain(1).indices shouldBe List(1).indices
Chain(1, 2, 3).indices shouldBe (0 to 2)
Chain(1, 2, 3, 4, 5).indices shouldBe (0 to 4)
}
/*
it should not have an init method
scala> Vector(1).init
res30: scala.collection.immutable.Vector[Int] = Vector()
it should "have an inits method" is pending
scala> Vector(1).inits.toList
res32: List[scala.collection.immutable.Vector[Int]] = List(Vector(1), Vector())
it should "have an intersect method" is pending
scala> Vector(1, 2, 3) intersect Vector(4, 5)
res33: scala.collection.immutable.Vector[Int] = Vector()
*/
it should "have an isDefinedAt method, inherited from PartialFunction" in {
Chain(1).isDefinedAt(0) shouldBe true
Chain(1).isDefinedAt(1) shouldBe false
Chain(1, 2, 3).isDefinedAt(1) shouldBe true
Chain(1, 2, 3).isDefinedAt(2) shouldBe true
Chain(1, 2, 3).isDefinedAt(3) shouldBe false
Chain(1, 2, 3).isDefinedAt(0) shouldBe true
Chain(1, 2, 3).isDefinedAt(-1) shouldBe false
}
it should "have an isEmpty method" in {
Chain("hi").isEmpty shouldBe false
Chain(1, 2, 3).isEmpty shouldBe false
}
it should "have an isTraversableAgain method" in {
Chain("hi").isTraversableAgain shouldBe true
Chain(1, 2, 3).isTraversableAgain shouldBe true
}
it should "have an iterator method" in {
Chain("hi").iterator.toList shouldBe List("hi")
Chain(1, 2, 3).iterator.toList shouldBe List(1, 2, 3)
}
it should "have a last method" in {
Chain("hi").last shouldBe "hi"
Chain(1, 2, 3).last shouldBe 3
}
it should "have 2 lastIndexOf methods" in {
Chain(1, 2, 3, 4, 5).lastIndexOf(2) shouldBe 1
Chain(1, 2, 3, 4, 5, 1).lastIndexOf(1) shouldBe 5
Chain(1, 2, 3, 4, 5).lastIndexOf(0) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexOf(5) shouldBe 4
Chain(1, 2, 3, 3, 5).lastIndexOf(3) shouldBe 3
Chain(1).lastIndexOf(1) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOf(2, 3) shouldBe 1
Chain(1, 2, 3, 4, 5).lastIndexOf(2, 0) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexOf(2, 1) shouldBe 1
val es = Every("one", "two", "three")
es.lastIndexOf("one") shouldBe 0
es.lastIndexOf("two") shouldBe 1
es.lastIndexOf("three") shouldBe 2
es.lastIndexOf("three", 1) shouldBe -1
es.lastIndexOf("ONE") shouldBe -1;
{
implicit val strEq = StringNormalizations.lowerCased.toEquality
es.lastIndexOf("one") shouldBe 0;
es.lastIndexOf("ONE") shouldBe -1
}
}
it should "have 2 lastIndexOfSlice methods that take a GenSeq" in {
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List(2, 3)) shouldBe 1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List(2, 3), 3) shouldBe 1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List(2, 3, 5), 3) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List(2, 3, 5)) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List(5)) shouldBe 4
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List(1, 2, 3, 4, 5)) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List(1, 2, 3, 4, 5), 0) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List(1, 2, 3, 4, 5), 1) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List(1, 2, 3, 4, 5), -1) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List.empty) shouldBe 5
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List.empty, 6) shouldBe 5
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(List.empty, 4) shouldBe 4
val es = Chain("one", "two", "three", "four", "five")
es.lastIndexOfSlice(List("one", "two")) shouldBe 0;
es.lastIndexOfSlice(List("two", "three"), 0) shouldBe -1
es.lastIndexOfSlice(List("ONE", "TWO")) shouldBe -1;
{
implicit val strEq = StringNormalizations.lowerCased.toEquality
es.lastIndexOfSlice(List("one", "two")) shouldBe 0;
es.lastIndexOfSlice(List("ONE", "TWO")) shouldBe -1
}
}
it should "have 2 lastIndexOfSlice methods that take an Every" in {
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Every(2, 3)) shouldBe 1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Every(2, 3), 3) shouldBe 1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Every(2, 3, 5), 3) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Every(2, 3, 5)) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Every(5)) shouldBe 4
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Every(1, 2, 3, 4, 5)) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Every(1, 2, 3, 4, 5), 0) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Every(1, 2, 3, 4, 5), 1) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Every(1, 2, 3, 4, 5), -1) shouldBe -1
val es = Chain("one", "two", "three", "four", "five")
es.lastIndexOfSlice(Every("one", "two")) shouldBe 0;
es.lastIndexOfSlice(Every("two", "three"), 0) shouldBe -1
es.lastIndexOfSlice(Every("ONE", "TWO")) shouldBe -1;
{
implicit val strEq = StringNormalizations.lowerCased.toEquality
es.lastIndexOfSlice(Every("one", "two")) shouldBe 0;
es.lastIndexOfSlice(Every("ONE", "TWO")) shouldBe -1
}
}
it should "have 2 lastIndexOfSlice methods that take a Chain" in {
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Chain(2, 3)) shouldBe 1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Chain(2, 3), 3) shouldBe 1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Chain(2, 3, 5), 3) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Chain(2, 3, 5)) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Chain(5)) shouldBe 4
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Chain(1, 2, 3, 4, 5)) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Chain(1, 2, 3, 4, 5), 0) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Chain(1, 2, 3, 4, 5), 1) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexOfSlice(Chain(1, 2, 3, 4, 5), -1) shouldBe -1
val es = Chain("one", "two", "three", "four", "five")
es.lastIndexOfSlice(Chain("one", "two")) shouldBe 0;
es.lastIndexOfSlice(Chain("two", "three"), 0) shouldBe -1
es.lastIndexOfSlice(Chain("ONE", "TWO")) shouldBe -1;
{
implicit val strEq = StringNormalizations.lowerCased.toEquality
es.lastIndexOfSlice(Chain("one", "two")) shouldBe 0;
es.lastIndexOfSlice(Chain("ONE", "TWO")) shouldBe -1
}
}
it should "have 2 lastIndexWhere methods" in {
Chain(1, 2, 3, 4, 5).lastIndexWhere(_ == 2) shouldBe 1
Chain(1, 2, 3, 4, 5).lastIndexWhere(_ == 0) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexWhere(_ == 5) shouldBe 4
Chain(1, 2, 3, 3, 5).lastIndexWhere(_ == 3) shouldBe 3
Chain(1).lastIndexWhere(_ == 1) shouldBe 0
Chain(1, 2, 3, 4, 5).lastIndexWhere(_ == 2, 3) shouldBe 1
Chain(1, 2, 3, 4, 5).lastIndexWhere(_ == 2, 0) shouldBe -1
Chain(1, 2, 3, 4, 5).lastIndexWhere(_ == 2, 1) shouldBe 1
}
it should "have an lastOption method" in {
Chain("hi").lastOption shouldBe Some("hi")
Chain(1, 2, 3).lastOption shouldBe Some(3)
}
it should "have an lengthCompare method" in {
Chain("hi").lengthCompare(0) should be > 0
Chain("hi").lengthCompare(1) shouldEqual 0
Chain("hi").lengthCompare(2) should be < 0
Chain(1, 2, 3).lengthCompare(0) should be > 0
Chain(1, 2, 3).lengthCompare(1) should be > 0
Chain(1, 2, 3).lengthCompare(2) should be > 0
Chain(1, 2, 3).lengthCompare(3) shouldEqual 0
Chain(1, 2, 3).lengthCompare(4) should be < 0
}
it should "have an inherited lift method" in {
val liftedOne = Chain("hi").lift
liftedOne(0) shouldBe Some("hi")
liftedOne(1) shouldBe None
liftedOne(-1) shouldBe None
val liftedMany = Chain(1, 2, 3).lift
liftedMany(0) shouldBe Some(1)
liftedMany(1) shouldBe Some(2)
liftedMany(2) shouldBe Some(3)
liftedMany(3) shouldBe None
liftedMany(-1) shouldBe None
}
it should "have a map method" in {
Chain(1, 2, 3) map (_ + 1) shouldBe Chain(2, 3, 4)
(for (ele <- Chain(1, 2, 3)) yield ele * 2) shouldBe Chain(2, 4, 6)
Chain(5) map (_ + 3) shouldBe Chain(8)
Chain(8) map (_.toString) shouldBe Chain("8")
}
it should "have a max method" in {
Chain(1, 2, 3, 4, 5).max shouldBe 5
Chain(1).max shouldBe 1
Chain(-1).max shouldBe -1
Chain("aaa", "ccc", "bbb").max shouldBe "ccc"
}
it should "have a maxBy method" in {
Chain(1, 2, 3, 4, 5).maxBy(_.abs) shouldBe 5
Chain(1, 2, 3, 4, -5).maxBy(_.abs) shouldBe -5
}
it should "have a min method" in {
Chain(1, 2, 3, 4, 5).min shouldBe 1
Chain(1).min shouldBe 1
Chain(-1).min shouldBe -1
Chain("aaa", "ccc", "bbb").min shouldBe "aaa"
}
it should "have a minBy method" in {
Chain(1, 2, 3, 4, 5).minBy(_.abs) shouldBe 1
Chain(-1, -2, 3, 4, 5).minBy(_.abs) shouldBe -1
}
it should "have a mkString method" in {
Chain("hi").mkString shouldBe "hi"
Chain(1, 2, 3).mkString shouldBe "123"
Chain("hi").mkString("#") shouldBe "hi"
Chain(1, 2, 3).mkString("#") shouldBe "1#2#3"
Chain(1, 2, 3).mkString(", ") shouldBe "1, 2, 3"
Chain("hi").mkString("<", "#", ">") shouldBe "<hi>"
Chain(1, 2, 3).mkString("<", "#", ">") shouldBe "<1#2#3>"
Chain(1, 2, 3).mkString(" ( ", ", ", " ) ") shouldBe " ( 1, 2, 3 ) "
}
it should "have an nonEmpty method" in {
Chain("hi").nonEmpty shouldBe true
Chain(1, 2, 3).nonEmpty shouldBe true
}
it should "have an orElse method, inherited from PartialFunction" in {
val pf: PartialFunction[Int, Int] = { case i => -i }
val f = Chain(1, 2, 3) orElse pf
f(0) shouldBe 1
f(1) shouldBe 2
f(2) shouldBe 3
f(3) shouldBe -3
f(-1) shouldBe 1
}
it should "have a padTo method" in {
Chain(1).padTo(0, -1) shouldBe Chain(1)
Chain(1).padTo(1, -1) shouldBe Chain(1)
Chain(1).padTo(2, -1) shouldBe Chain(1, -1)
Chain(1).padTo(3, -1) shouldBe Chain(1, -1, -1)
Chain(1, 2, 3).padTo(3, -1) shouldBe Chain(1, 2, 3)
Chain(1, 2, 3).padTo(4, -1) shouldBe Chain(1, 2, 3, -1)
Chain(1, 2, 3).padTo(5, -1) shouldBe Chain(1, 2, 3, -1, -1)
}
// it should not have a par method, because I don't want to support that. If the user
// needs a parallel collection, they can use a parallel collection: chain.toVector.par...
/*
it should not have an partition method
scala> Vector(1, 2, 3, 4, 5).partition(_ > 10)
res10: (scala.collection.immutable.Vector[Int], scala.collection.immutable.Vector[Int]) = (Vector(),Vector(1, 2, 3, 4, 5))
*/
it should "have a patch method" in {
Chain(1, 2, 3, 4, 5).patch(2, Chain(-3, -4), 2) shouldBe Chain(1, 2, -3, -4, 5)
Chain(1, 2, 3, 4, 5).patch(2, Chain(-3, -4), 5) shouldBe Chain(1, 2, -3, -4)
Chain(1, 2, 3, 4, 5).patch(2, Chain(-3, -4), 1) shouldBe Chain(1, 2, -3, -4, 4, 5)
Chain(1, 2, 3, 4, 5).patch(4, Chain(-3, -4), 2) shouldBe Chain(1, 2, 3, 4, -3, -4)
Chain(1, 2, 3, 4, 5).patch(5, Chain(-3, -4), 2) shouldBe Chain(1, 2, 3, 4, 5, -3, -4)
Chain(1, 2, 3, 4, 5).patch(6, Chain(-3, -4), 2) shouldBe Chain(1, 2, 3, 4, 5, -3, -4)
Chain(1, 2, 3, 4, 5).patch(0, Chain(-3, -4), 2) shouldBe Chain(-3, -4, 3, 4, 5)
Chain(1, 2, 3, 4, 5).patch(0, Chain(-3, -4), 3) shouldBe Chain(-3, -4, 4, 5)
}
it should "have a permutations method" in {
Chain(1, 2, 3).permutations.toStream shouldBe Stream(Chain(1, 2, 3), Chain(1, 3, 2), Chain(2, 1, 3), Chain(2, 3, 1), Chain(3, 1, 2), Chain(3, 2, 1))
Chain(1).permutations.toStream shouldBe Stream(Chain(1))
Chain(1, 2).permutations.toStream shouldBe Stream(Chain(1, 2), Chain(2, 1))
}
it should "have a prefixLength method" in {
Chain(1, 2, 3, 4, 5).prefixLength(_ == 1) shouldBe 1
Chain(1, 2, 3, 4, 5).prefixLength(_ == 2) shouldBe 0
Chain(1, 2, 3, 4, 5).prefixLength(_ <= 2) shouldBe 2
Chain(1, 2, 3, 4, 5).prefixLength(_ <= 10) shouldBe 5
Chain(1, 2, 3, 4, 5).prefixLength(_ <= 4) shouldBe 4
}
it should "have a product method" in {
Chain(1, 2, 3).product shouldBe 6
Chain(3).product shouldBe 3
Chain(3, 4, 5).product shouldBe 60
Chain(3, 4, 5).product shouldBe 60
Chain(3.1, 4.2, 5.3).product shouldBe 69.006
}
it should "have a reduce method" in {
Chain(1, 2, 3, 4, 5).reduce(_ + _) shouldBe 15
Chain(1, 2, 3, 4, 5).reduce(_ * _) shouldBe 120
Chain(5).reduce(_ + _) shouldBe 5
Chain(5).reduce(_ * _) shouldBe 5
}
it should "have a reduceLeft method" in {
Chain(1).reduceLeft(_ + _) shouldBe 1
Chain(1).reduceLeft(_ * _) shouldBe 1
Chain(1, 2, 3).reduceLeft(_ + _) shouldBe 6
Chain(1, 2, 3).reduceLeft(_ * _) shouldBe 6
Chain(1, 2, 3, 4, 5).reduceLeft(_ * _) shouldBe 120
}
it should "have a reduceLeftOption method" in {
Chain(1).reduceLeftOption(_ + _) shouldBe Some(1)
Chain(1).reduceLeftOption(_ * _) shouldBe Some(1)
Chain(1, 2, 3).reduceLeftOption(_ + _) shouldBe Some(6)
Chain(1, 2, 3).reduceLeftOption(_ * _) shouldBe Some(6)
Chain(1, 2, 3, 4, 5).reduceLeftOption(_ * _) shouldBe Some(120)
}
it should "have a reduceOption method" in {
Chain(1, 2, 3, 4, 5).reduceOption(_ + _) shouldBe Some(15)
Chain(1, 2, 3, 4, 5).reduceOption(_ * _) shouldBe Some(120)
Chain(5).reduceOption(_ + _) shouldBe Some(5)
Chain(5).reduceOption(_ * _) shouldBe Some(5)
}
it should "have a reduceRight method" in { One(1).reduceRight(_ + _) shouldBe 1
Chain(1).reduceRight(_ * _) shouldBe 1
Chain(1, 2, 3).reduceRight(_ + _) shouldBe 6
Chain(1, 2, 3).reduceRight(_ * _) shouldBe 6
Chain(1, 2, 3, 4, 5).reduceRight(_ * _) shouldBe 120
}
it should "have a reduceRightOption method" in {
Chain(1).reduceRightOption(_ + _) shouldBe Some(1)
Chain(1).reduceRightOption(_ * _) shouldBe Some(1)
Chain(1, 2, 3).reduceRightOption(_ + _) shouldBe Some(6)
Chain(1, 2, 3).reduceRightOption(_ * _) shouldBe Some(6)
Chain(1, 2, 3, 4, 5).reduceRightOption(_ * _) shouldBe Some(120)
}
it should "have a reverse method" in {
Chain(33).reverse shouldBe Chain(33)
Chain(33, 34, 35).reverse shouldBe Chain(35, 34, 33)
}
it should "have a reverseIterator method" in {
Chain(3).reverseIterator.toStream shouldBe Stream(3)
Chain(1, 2, 3).reverseIterator.toList shouldBe Stream(3, 2, 1)
}
it should "have a reverseMap method" in {
Chain(3).reverseMap(_ + 1) shouldBe Chain(4)
Chain(1, 2, 3).reverseMap(_ + 1) shouldBe Chain(4, 3, 2)
}
it should "have a runWith method, inherited from PartialFunction" in {
// TODO: What is this? Seems to be testing Vector or List instead of Every or Chain.
var x = 0
val f = List(1, 2, 3).runWith(x += _)
f(0) shouldBe true
x shouldBe 1
f(1) shouldBe true
x shouldBe 3
f(2) shouldBe true
x shouldBe 6
f(3) shouldBe false
var y = 0
val g = List(3).runWith(y += _)
g(0) shouldBe true
y shouldBe 3
g(0) shouldBe true
y shouldBe 6
}
it should "have a sameElements method that takes a GenIterable" in {
Chain(1, 2, 3, 4, 5).sameElements(List(1, 2, 3, 4, 5)) shouldBe true
Chain(1, 2, 3, 4, 5).sameElements(List(1, 2, 3, 4)) shouldBe false
Chain(1, 2, 3, 4, 5).sameElements(List(1, 2, 3, 4, 5, 6)) shouldBe false
Chain(1, 2, 3, 4, 5).sameElements(List(1, 2, 3, 4, 4)) shouldBe false
Chain(3).sameElements(List(1, 2, 3, 4, 5)) shouldBe false
Chain(3).sameElements(List(1)) shouldBe false
Chain(3).sameElements(List(3)) shouldBe true
}
it should "have a sameElements method that takes an Every" in {
Chain(1, 2, 3, 4, 5).sameElements(Every(1, 2, 3, 4, 5)) shouldBe true
Chain(1, 2, 3, 4, 5).sameElements(Every(1, 2, 3, 4)) shouldBe false
Chain(1, 2, 3, 4, 5).sameElements(Every(1, 2, 3, 4, 5, 6)) shouldBe false
Chain(1, 2, 3, 4, 5).sameElements(Every(1, 2, 3, 4, 4)) shouldBe false
Chain(3).sameElements(Every(1, 2, 3, 4, 5)) shouldBe false
Chain(3).sameElements(Every(1)) shouldBe false
Chain(3).sameElements(Every(3)) shouldBe true
}
it should "have a sameElements method that takes a Chain" in {
Chain(1, 2, 3, 4, 5).sameElements(Chain(1, 2, 3, 4, 5)) shouldBe true
Chain(1, 2, 3, 4, 5).sameElements(Chain(1, 2, 3, 4)) shouldBe false
Chain(1, 2, 3, 4, 5).sameElements(Chain(1, 2, 3, 4, 5, 6)) shouldBe false
Chain(1, 2, 3, 4, 5).sameElements(Chain(1, 2, 3, 4, 4)) shouldBe false
Chain(3).sameElements(Chain(1, 2, 3, 4, 5)) shouldBe false
Chain(3).sameElements(Chain(1)) shouldBe false
Chain(3).sameElements(Chain(3)) shouldBe true
}
it should "have a scan method" in {
Chain(1).scan(0)(_ + _) shouldBe Chain(0, 1)
Chain(1, 2, 3).scan(0)(_ + _) shouldBe Chain(0, 1, 3, 6)
Chain(1, 2, 3).scan("z")(_ + _.toString) shouldBe Chain("z", "z1", "z12", "z123")
Chain(0).scan("z")(_ + _.toString) shouldBe Chain("z", "z0")
}
it should "have a scanLeft method" in {
Chain(1).scanLeft(0)(_ + _) shouldBe Chain(0, 1)
Chain(1, 2, 3).scanLeft(0)(_ + _) shouldBe Chain(0, 1, 3, 6)
Chain(1, 2, 3).scanLeft("z")(_ + _) shouldBe Chain("z", "z1", "z12", "z123")
Chain(0).scanLeft("z")(_ + _) shouldBe Chain("z", "z0")
}
it should "have a scanRight method" in {
Chain(1).scanRight(0)(_ + _) shouldBe Chain(1, 0)
Chain(1, 2, 3).scanRight(0)(_ + _) shouldBe Chain(6, 5, 3, 0)
Chain(1, 2, 3).scanRight("z")(_ + _) shouldBe Chain("123z", "23z", "3z", "z")
Chain(0).scanRight("z")(_ + _) shouldBe Chain("0z", "z")
}
it should "have a segmentLength method" in {
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ > 7, 0) shouldBe 0
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ == 7, 0) shouldBe 0
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ > 0, 0) shouldBe 10
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ > 1, 0) shouldBe 0
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ > 0, 10) shouldBe 0
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ > 0, 8) shouldBe 2
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ < 3, 0) shouldBe 2
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ < 5, 0) shouldBe 4
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ > 5, 0) shouldBe 0
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ > 5, 5) shouldBe 5
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ > 5, 4) shouldBe 0
Chain(1, 2, 3, 4, 5, 6, 6, 7, 8, 10).segmentLength(_ > 5, 6) shouldBe 4
}
// it should "have a seq method" is pending
it should "have a size method" in {
Chain(5).size shouldBe 1
Chain(1, 2, 3).size shouldBe 3
}
/*
it should not have a slice method
scala> Vector(3).slice(0, 0)
res83: scala.collection.immutable.Vector[Int] = Vector()
scala> Vector(1, 2, 3, 4, 5).slice(2, 1)
res84: scala.collection.immutable.Vector[Int] = Vector()
*/
it should "have 2 sliding methods" in {
Chain(1).sliding(1).toList shouldBe List(Chain(1))
Chain(1).sliding(2).toList shouldBe List(Chain(1))
Chain(1, 2, 3).sliding(2).toList shouldBe List(Chain(1, 2), Chain(2, 3))
Chain(1, 2, 3).sliding(1).toList shouldBe List(Chain(1), Chain(2), Chain(3))
Chain(1, 2, 3).sliding(3).toList shouldBe List(Chain(1, 2, 3))
Chain(1, 2, 3, 4, 5).sliding(3).toList shouldBe List(Chain(1, 2, 3), Chain(2, 3, 4), Chain(3, 4, 5))
Chain(1, 2, 3, 4, 5).sliding(2).toList shouldBe List(Chain(1, 2), Chain(2, 3), Chain(3, 4), Chain(4, 5))
Chain(1, 2, 3, 4, 5).sliding(1).toList shouldBe List(Chain(1), Chain(2), Chain(3), Chain(4), Chain(5))
Chain(1, 2, 3, 4, 5).sliding(4).toList shouldBe List(Chain(1, 2, 3, 4), Chain(2, 3, 4, 5))
Chain(1, 2, 3, 4, 5).sliding(5).toList shouldBe List(Chain(1, 2, 3, 4, 5))
Chain(1).sliding(1, 1).toList shouldBe List(Chain(1))
Chain(1).sliding(1, 2).toList shouldBe List(Chain(1))
Chain(1, 2, 3).sliding(1, 1).toList shouldBe List(Chain(1), Chain(2), Chain(3))
Chain(1, 2, 3).sliding(2, 1).toList shouldBe List(Chain(1, 2), Chain(2, 3))
Chain(1, 2, 3).sliding(2, 2).toList shouldBe List(Chain(1, 2), Chain(3))
Chain(1, 2, 3).sliding(3, 2).toList shouldBe List(Chain(1, 2, 3))
Chain(1, 2, 3).sliding(3, 1).toList shouldBe List(Chain(1, 2, 3))
Chain(1, 2, 3, 4, 5).sliding(3, 1).toList shouldBe List(Chain(1, 2, 3), Chain(2, 3, 4), Chain(3, 4, 5))
Chain(1, 2, 3, 4, 5).sliding(2, 2).toList shouldBe List(Chain(1, 2), Chain(3, 4), Chain(5))
Chain(1, 2, 3, 4, 5).sliding(2, 3).toList shouldBe List(Chain(1, 2), Chain(4, 5))
Chain(1, 2, 3, 4, 5).sliding(2, 4).toList shouldBe List(Chain(1, 2), Chain(5))
Chain(1, 2, 3, 4, 5).sliding(3, 1).toList shouldBe List(Chain(1, 2, 3), Chain(2, 3, 4), Chain(3, 4, 5))
Chain(1, 2, 3, 4, 5).sliding(3, 2).toList shouldBe List(Chain(1, 2, 3), Chain(3, 4, 5))
Chain(1, 2, 3, 4, 5).sliding(3, 3).toList shouldBe List(Chain(1, 2, 3), Chain(4, 5))
Chain(1, 2, 3, 4, 5).sliding(3, 4).toList shouldBe List(Chain(1, 2, 3), Chain(5))
}
it should "have a sortBy method" in {
val regFun: String => Int = {
case "one" => 1
case "two" => 2
case "three" => 3
case "four" => 4
case "five" => 5
case "-one" => -1
case "-two" => -2
case "-three" => -3
case "-four" => -4
case "-five" => -5
}
val absFun: String => Int = {
case "one" => 1
case "two" => 2
case "three" => 3
case "four" => 4
case "five" => 5
case "-one" => 1
case "-two" => 2
case "-three" => 3
case "-four" => 4
case "-five" => 5
}
Chain("five", "four", "three", "two", "one").sortBy(regFun) shouldBe Chain("one", "two", "three", "four", "five")
Chain("two", "one", "four", "five", "three").sortBy(regFun) shouldBe Chain("one", "two", "three", "four", "five")
Chain("two", "-one", "four", "-five", "-three").sortBy(regFun) shouldBe Chain("-five", "-three", "-one", "two", "four")
Chain("two", "-one", "four", "-five", "-three").sortBy(absFun) shouldBe Chain("-one", "two", "-three", "four", "-five")
}
it should "have a sortWith method" in {
Chain(1, 2, 3, 4, 5).sortWith(_ > _) shouldBe Chain(5, 4, 3, 2, 1)
Chain(2, 1, 4, 5, 3).sortWith(_ > _) shouldBe Chain(5, 4, 3, 2, 1)
Chain(2, -1, 4, -5, -3).sortWith(_.abs > _.abs) shouldBe Chain(-5, 4, -3, 2, -1)
Chain(2, -1, 4, -5, -3).sortWith(_.abs < _.abs) shouldBe Chain(-1, 2, -3, 4, -5)
}
it should "have a sorted method" in {
Chain(1, 2, 3, 4, 5).sorted shouldBe Chain(1, 2, 3, 4, 5)
Chain(5, 4, 3, 2, 1).sorted shouldBe Chain(1, 2, 3, 4, 5)
Chain(2, 1, 4, 5, 3).sorted shouldBe Chain(1, 2, 3, 4, 5)
}
/*
it should not have a span method
scala> Vector(1, 2, 3, 4, 5).span(_ > 10)
res105: (scala.collection.immutable.Vector[Int], scala.collection.immutable.Vector[Int]) = (Vector(),Vector(1, 2, 3, 4, 5))
it should not have a splitAt method
scala> Vector(1, 2, 3, 4, 5).splitAt(0)
res106: (scala.collection.immutable.Vector[Int], scala.collection.immutable.Vector[Int]) = (Vector(),Vector(1, 2, 3, 4, 5))
*/
it should "have 2 startsWith methods that take a GenSeq" in {
Chain(1, 2, 3).startsWith(List(1)) shouldBe true
Chain(1, 2, 3).startsWith(List(1, 2)) shouldBe true
Chain(1, 2, 3).startsWith(List(1, 2, 3)) shouldBe true
Chain(1, 2, 3).startsWith(List(1, 2, 3, 4)) shouldBe false
Chain(1).startsWith(List(1, 2, 3, 4)) shouldBe false
Chain(1).startsWith(List(1)) shouldBe true
Chain(1).startsWith(List(2)) shouldBe false
Chain(1).startsWith(List(1), 0) shouldBe true
Chain(1).startsWith(List(1), 1) shouldBe false
Chain(1, 2, 3).startsWith(List(1), 1) shouldBe false
Chain(1, 2, 3).startsWith(List(1), 2) shouldBe false
Chain(1, 2, 3).startsWith(List(2), 2) shouldBe false
Chain(1, 2, 3).startsWith(List(2), 1) shouldBe true
Chain(1, 2, 3).startsWith(List(2, 3), 1) shouldBe true
Chain(1, 2, 3).startsWith(List(1, 2, 3), 1) shouldBe false
Chain(1, 2, 3).startsWith(List(1, 2, 3), 0) shouldBe true
Chain(1, 2, 3, 4, 5).startsWith(List(3, 4), 2) shouldBe true
Chain(1, 2, 3, 4, 5).startsWith(List(3, 4, 5), 2) shouldBe true
Chain(1, 2, 3, 4, 5).startsWith(List(3, 4, 5, 6), 2) shouldBe false
}
it should "have 2 startsWith methods that take an Every" in {
Chain(1, 2, 3).startsWith(Every(1)) shouldBe true
Chain(1, 2, 3).startsWith(Every(1, 2)) shouldBe true
Chain(1, 2, 3).startsWith(Every(1, 2, 3)) shouldBe true
Chain(1, 2, 3).startsWith(Every(1, 2, 3, 4)) shouldBe false
Chain(1).startsWith(Every(1, 2, 3, 4)) shouldBe false
Chain(1).startsWith(Every(1)) shouldBe true
Chain(1).startsWith(Every(2)) shouldBe false
Chain(1).startsWith(Every(1), 0) shouldBe true
Chain(1).startsWith(Every(1), 1) shouldBe false
Chain(1, 2, 3).startsWith(Every(1), 1) shouldBe false
Chain(1, 2, 3).startsWith(Every(1), 2) shouldBe false
Chain(1, 2, 3).startsWith(Every(2), 2) shouldBe false
Chain(1, 2, 3).startsWith(Every(2), 1) shouldBe true
Chain(1, 2, 3).startsWith(Every(2, 3), 1) shouldBe true
Chain(1, 2, 3).startsWith(Every(1, 2, 3), 1) shouldBe false
Chain(1, 2, 3).startsWith(Every(1, 2, 3), 0) shouldBe true
Chain(1, 2, 3, 4, 5).startsWith(Every(3, 4), 2) shouldBe true
Chain(1, 2, 3, 4, 5).startsWith(Every(3, 4, 5), 2) shouldBe true
Chain(1, 2, 3, 4, 5).startsWith(Every(3, 4, 5, 6), 2) shouldBe false
}
it should "have 2 startsWith methods that take a Chain" in {
Chain(1, 2, 3).startsWith(Chain(1)) shouldBe true
Chain(1, 2, 3).startsWith(Chain(1, 2)) shouldBe true
Chain(1, 2, 3).startsWith(Chain(1, 2, 3)) shouldBe true
Chain(1, 2, 3).startsWith(Chain(1, 2, 3, 4)) shouldBe false
Chain(1).startsWith(Chain(1, 2, 3, 4)) shouldBe false
Chain(1).startsWith(Chain(1)) shouldBe true
Chain(1).startsWith(Chain(2)) shouldBe false
Chain(1).startsWith(Chain(1), 0) shouldBe true
Chain(1).startsWith(Chain(1), 1) shouldBe false
Chain(1, 2, 3).startsWith(Chain(1), 1) shouldBe false
Chain(1, 2, 3).startsWith(Chain(1), 2) shouldBe false
Chain(1, 2, 3).startsWith(Chain(2), 2) shouldBe false
Chain(1, 2, 3).startsWith(Chain(2), 1) shouldBe true
Chain(1, 2, 3).startsWith(Chain(2, 3), 1) shouldBe true
Chain(1, 2, 3).startsWith(Chain(1, 2, 3), 1) shouldBe false
Chain(1, 2, 3).startsWith(Chain(1, 2, 3), 0) shouldBe true
Chain(1, 2, 3, 4, 5).startsWith(Chain(3, 4), 2) shouldBe true
Chain(1, 2, 3, 4, 5).startsWith(Chain(3, 4, 5), 2) shouldBe true
Chain(1, 2, 3, 4, 5).startsWith(Chain(3, 4, 5, 6), 2) shouldBe false
}
it should "have a stringPrefix method" in {
Chain(1).stringPrefix shouldBe "Chain"
Chain(1, 2, 3).stringPrefix shouldBe "Chain"
}
it should "have a sum method" in {
Chain(1).sum shouldBe 1
Chain(5).sum shouldBe 5
Chain(1, 2, 3).sum shouldBe 6
Chain(1, 2, 3, 4, 5).sum shouldBe 15
Chain(1.1, 2.2, 3.3).sum shouldBe 6.6
}
/*
it should not have a tail method
scala> Vector(1).tail
res7: scala.collection.immutable.Vector[Int] = Vector()
it should not have a tails method
scala> Vector(1).tails.toList
res8: List[scala.collection.immutable.Vector[Int]] = List(Vector(1), Vector())
it should not have a take method
scala> Vector(1).take(0)
res10: scala.collection.immutable.Vector[Int] = Vector()
scala> Vector(1, 2, 3).take(0)
res11: scala.collection.immutable.Vector[Int] = Vector()
scala> Vector(1, 2, 3).take(-1)
res12: scala.collection.immutable.Vector[Int] = Vector()
it should not have a takeRight method
scala> Vector(1).takeRight(1)
res13: scala.collection.immutable.Vector[Int] = Vector(1)
scala> Vector(1).takeRight(0)
res14: scala.collection.immutable.Vector[Int] = Vector()
scala> Vector(1, 2, 3).takeRight(0)
res15: scala.collection.immutable.Vector[Int] = Vector()
it should not have a takeWhile method
scala> Vector(1, 2, 3).takeWhile(_ > 10)
res17: scala.collection.immutable.Vector[Int] = Vector()
scala> Vector(1).takeWhile(_ > 10)
res18: scala.collection.immutable.Vector[Int] = Vector()
*/
it should "have a to method" in {
Chain(1).to[List] shouldBe List(1)
Chain(1, 2, 3).to[List] shouldBe List(1, 2, 3)
Chain(1, 2, 3).to[scala.collection.mutable.ListBuffer] shouldBe ListBuffer(1, 2, 3)
Chain(1, 2, 3).to[Vector] shouldBe Vector(1, 2, 3)
}
it should "have a toArray method" in {
Chain(1, 2, 3).toArray should === (Array(1, 2, 3))
Chain("a", "b").toArray should === (Array("a", "b"))
Chain(1).toArray should === (Array(1))
}
it should "have a toBuffer method" in {
Chain(1, 2, 3).toBuffer should === (Buffer(1, 2, 3))
Chain("a", "b").toBuffer should === (Buffer("a", "b"))
Chain(1).toBuffer should === (Buffer(1))
}
it should "have a toIndexedSeq method" in {
Chain(1, 2, 3).toIndexedSeq should === (IndexedSeq(1, 2, 3))
Chain("a", "b").toIndexedSeq should === (IndexedSeq("a", "b"))
Chain(1).toIndexedSeq should === (IndexedSeq(1))
}
it should "have a toIterable method" in {
Chain(1, 2, 3).toIterable should === (Iterable(1, 2, 3))
Chain("a", "b").toIterable should === (Iterable("a", "b"))
Chain(1).toIterable should === (Iterable(1))
}
it should "have a toIterator method" in {
Chain(1, 2, 3).toIterator.toList should === (Iterator(1, 2, 3).toList)
Chain("a", "b").toIterator.toList should === (Iterator("a", "b").toList)
Chain(1).toIterator.toList should === (Iterator(1).toList)
Chain(1, 2, 3).toIterator shouldBe an [Iterator[_]]
Chain("a", "b").toIterator shouldBe an [Iterator[_]]
Chain(1).toIterator shouldBe an [Iterator[_]]
}
it should "have a toList method" in {
Chain(1, 2, 3).toList should === (List(1, 2, 3))
Chain("a", "b").toList should === (List("a", "b"))
Chain(1).toList should === (List(1))
}
it should "have a toMap method" in {
Chain("1" -> 1, "2" -> 2, "3" -> 3).toMap should === (Map("1" -> 1, "2" -> 2, "3" -> 3))
Chain('A' -> "a", 'B' -> "b").toMap should === (Map('A' -> "a", 'B' -> "b"))
Chain("1" -> 1).toMap should === (Map("1" -> 1))
}
it should "have a toSeq method" in {
Chain(1, 2, 3).toSeq should === (Seq(1, 2, 3))
Chain("a", "b").toSeq should === (Seq("a", "b"))
Chain(1).toSeq should === (Seq(1))
}
it should "have a toSet method" in {
Chain(1, 2, 3).toSet should === (Set(1, 2, 3))
Chain("a", "b").toSet should === (Set("a", "b"))
Chain(1).toSet should === (Set(1))
}
it should "have a toStream method" in {
Chain(1, 2, 3).toStream should === (Stream(1, 2, 3))
Chain("a", "b").toStream should === (Stream("a", "b"))
Chain(1).toStream should === (Stream(1))
}
it should "have a toString method" in {
Chain(1, 2, 3).toString should === ("Chain(1, 2, 3)")
Chain(1, 2, 3).toString should === ("Chain(1, 2, 3)")
Chain(1).toString should === ("Chain(1)")
}
it should "have a toTraversable method" in {
Chain(1, 2, 3).toTraversable should === (Traversable(1, 2, 3))
Chain("a", "b").toTraversable should === (Traversable("a", "b"))
Chain(1).toTraversable should === (Traversable(1))
}
it should "have a toVector method" in {
Chain(1, 2, 3).toVector should === (Vector(1, 2, 3))
Chain("a", "b").toVector should === (Vector("a", "b"))
Chain(1).toVector should === (Vector(1))
}
it should "have a transpose method" in {
Chain(Chain(1, 2, 3), Chain(4, 5, 6), Chain(7, 8, 9)).transpose shouldBe Chain(Chain(1, 4, 7), Chain(2, 5, 8), Chain(3, 6, 9))
Chain(Chain(1, 2), Chain(3, 4), Chain(5, 6), Chain(7, 8)).transpose shouldBe Chain(Chain(1, 3, 5, 7), Chain(2, 4, 6, 8))
Chain(Chain(1, 2), Chain(3, 4), Chain(5, 6), Chain(7, 8)).transpose.transpose shouldBe Chain(Chain(1, 2), Chain(3, 4), Chain(5, 6), Chain(7, 8))
Chain(Chain(1, 2, 3), Chain(4, 5, 6), Chain(7, 8, 9)).transpose.transpose shouldBe Chain(Chain(1, 2, 3), Chain(4, 5, 6), Chain(7, 8, 9))
}
it should "have a union method that takes a GenSeq" in {
Chain(1) union List(1) shouldBe Chain(1, 1)
Chain(1) union List(1, 2) shouldBe Chain(1, 1, 2)
Chain(1, 2) union List(1, 2) shouldBe Chain(1, 2, 1, 2)
Chain(1, 2) union List(1) shouldBe Chain(1, 2, 1)
Chain(1, 2) union List(3, 4, 5) shouldBe Chain(1, 2, 3, 4, 5)
Chain(1, 2, 3) union List(3, 4, 5) shouldBe Chain(1, 2, 3, 3, 4, 5)
}
it should "have a union method that takes an Every" in {
Chain(1) union Every(1) shouldBe Chain(1, 1)
Chain(1) union Every(1, 2) shouldBe Chain(1, 1, 2)
Chain(1, 2) union Every(1, 2) shouldBe Chain(1, 2, 1, 2)
Chain(1, 2) union Every(1) shouldBe Chain(1, 2, 1)
Chain(1, 2) union Every(3, 4, 5) shouldBe Chain(1, 2, 3, 4, 5)
Chain(1, 2, 3) union Every(3, 4, 5) shouldBe Chain(1, 2, 3, 3, 4, 5)
}
it should "have a union method that takes a Chain" in {
Chain(1) union Chain(1) shouldBe Chain(1, 1)
Chain(1) union Chain(1, 2) shouldBe Chain(1, 1, 2)
Chain(1, 2) union Chain(1, 2) shouldBe Chain(1, 2, 1, 2)
Chain(1, 2) union Chain(1) shouldBe Chain(1, 2, 1)
Chain(1, 2) union Chain(3, 4, 5) shouldBe Chain(1, 2, 3, 4, 5)
Chain(1, 2, 3) union Chain(3, 4, 5) shouldBe Chain(1, 2, 3, 3, 4, 5)
}
it should "have an unzip method" in {
Chain((1, 2)).unzip shouldBe (Chain(1),Chain(2))
Chain((1, 2), (3, 4)).unzip shouldBe (Chain(1, 3), Chain(2, 4))
Chain((1, 2), (3, 4), (5, 6)).unzip shouldBe (Chain(1, 3, 5), Chain(2, 4, 6))
}
it should "have an unzip3 method" in {
Chain((1, 2, 3)).unzip3 shouldBe (Chain(1), Chain(2), Chain(3))
Chain((1, 2, 3), (4, 5, 6)).unzip3 shouldBe (Chain(1, 4), Chain(2, 5), Chain(3, 6))
Chain((1, 2, 3), (4, 5, 6), (7, 8, 9)).unzip3 shouldBe (Chain(1, 4, 7), Chain(2, 5, 8), Chain(3, 6, 9))
}
it should "have an updated method" in {
Chain(1).updated(0, 2) shouldBe Chain(2)
an [IndexOutOfBoundsException] should be thrownBy { Chain(1).updated(1, 2) }
Chain(1, 1, 1).updated(1, 2) shouldBe Chain(1, 2, 1)
Chain(1, 1, 1).updated(2, 2) shouldBe Chain(1, 1, 2)
Chain(1, 1, 1).updated(0, 2) shouldBe Chain(2, 1, 1)
}
/*
it should not have 2 view methods, because I don't want to support views in Every
*/
/*
it should not have a zip method
scala> List(1) zip Nil
res0: List[(Int, Nothing)] = List()
*/
it should "have a zipAll method that takes an Iterable" in {
// Empty on right
Chain(1).zipAll(Nil, -1, -2) shouldBe Chain((1, -2))
Chain(1, 2).zipAll(Nil, -1, -2) shouldBe Chain((1, -2), (2, -2))
// Same length
Chain(1).zipAll(List(1), -1, -2) shouldBe Chain((1, 1))
Chain(1, 2).zipAll(List(1, 2), -1, -2) shouldBe Chain((1, 1), (2, 2))
// Non-empty, longer on right
Chain(1).zipAll(List(10, 20), -1, -2) shouldBe Chain((1,10), (-1,20))
Chain(1, 2).zipAll(List(10, 20, 30), -1, -2) shouldBe Chain((1,10), (2,20), (-1,30))
// Non-empty, shorter on right
Chain(1, 2, 3).zipAll(List(10, 20), -1, -2) shouldBe Chain((1,10), (2,20), (3,-2))
Chain(1, 2, 3, 4).zipAll(List(10, 20, 30), -1, -2) shouldBe Chain((1,10), (2,20), (3,30), (4,-2))
}
it should "have a zipAll method that takes an Every" in {
// Same length
Chain(1).zipAll(Every(1), -1, -2) shouldBe Chain((1, 1))
Chain(1, 2).zipAll(Every(1, 2), -1, -2) shouldBe Chain((1, 1), (2, 2))
// Non-empty, longer on right
Chain(1).zipAll(Every(10, 20), -1, -2) shouldBe Chain((1,10), (-1,20))
Chain(1, 2).zipAll(Every(10, 20, 30), -1, -2) shouldBe Chain((1,10), (2,20), (-1,30))
// Non-empty, shorter on right
Chain(1, 2, 3).zipAll(Every(10, 20), -1, -2) shouldBe Chain((1,10), (2,20), (3,-2))
Chain(1, 2, 3, 4).zipAll(Every(10, 20, 30), -1, -2) shouldBe Chain((1,10), (2,20), (3,30), (4,-2))
}
it should "have a zipAll method that takes a Chain" in {
// Same length
Chain(1).zipAll(Chain(1), -1, -2) shouldBe Chain((1, 1))
Chain(1, 2).zipAll(Chain(1, 2), -1, -2) shouldBe Chain((1, 1), (2, 2))
// Non-empty, longer on right
Chain(1).zipAll(Chain(10, 20), -1, -2) shouldBe Chain((1,10), (-1,20))
Chain(1, 2).zipAll(Chain(10, 20, 30), -1, -2) shouldBe Chain((1,10), (2,20), (-1,30))
// Non-empty, shorter on right
Chain(1, 2, 3).zipAll(Chain(10, 20), -1, -2) shouldBe Chain((1,10), (2,20), (3,-2))
Chain(1, 2, 3, 4).zipAll(Chain(10, 20, 30), -1, -2) shouldBe Chain((1,10), (2,20), (3,30), (4,-2))
}
it should "have a zipWithIndex method" in {
Chain(99).zipWithIndex shouldBe Chain((99,0))
Chain(1, 2, 3, 4, 5).zipWithIndex shouldBe Chain((1,0), (2,1), (3,2), (4,3), (5,4))
}
"End" should "have a pretty toString" in {
End.toString shouldBe "End"
}
}
|
cheeseng/scalatest
|
scalactic-test/src/test/scala/org/scalactic/ChainSpec.scala
|
Scala
|
apache-2.0
| 62,531 |
import akka.actor.{ActorSystem, ActorRef, Props}
import com.jd.scala.selling.actors.Creater
import com.jd.scala.selling.model.Person
import com.typesafe.scalalogging.LazyLogging
/**
* Created by justin on 14/08/2014.
*/
object ActorMain extends LazyLogging {
def main(args: Array[String]): Unit = {
val system = ActorSystem("FlightReservationSystem")
val creater : ActorRef = system.actorOf(Props[Creater])
logger.info("sending .....")
creater ! ("Mr", "Akka", "Akka Street", "Akkavile")
logger.info("sent")
logger.info("sending .....")
val p : Person = ("Mr", "Akka", "Akka Street", "Akkavile")
creater ! p
logger.info("sent")
}
}
|
justindav1s/learning-scala
|
src/main/scala/ActorMain.scala
|
Scala
|
apache-2.0
| 680 |
package ch.descabato.ui
import ch.descabato.core.model.{FileDescription, Size}
import ch.descabato.utils.Utils
import scala.io.Source
import scalafx.beans.binding.Bindings
import scalafx.scene.control._
import scalafx.scene.image.{Image, ImageView}
import scalafx.scene.layout.{BorderPane, FlowPane}
import scalafxml.core.macros.sfxml
trait PreviewControllerI extends ChildController {
def preview(fileDescription: FileDescription): Unit
}
sealed trait PreviewType
case object Image extends PreviewType
case object Text extends PreviewType
case object Unknown extends PreviewType
@sfxml
class PreviewController(
val infoLabel: Label,
val imageView: ImageView,
val borderPane: BorderPane,
val textView: TextArea
) extends PreviewControllerI with Utils {
val imageScrollPane = new ScrollPane()
borderPane.center = imageScrollPane
imageScrollPane.maxWidth = Double.MaxValue
imageScrollPane.maxHeight = Double.MaxValue
imageScrollPane.content = imageView
val textFilesRegex = ("(?i)\\\\.(csv|txt|diff?|patch|svg|asc|cnf|cfg|conf|html?|.html|cfm|cgi|aspx?|ini|pl|py" +
"|md|css|cs|js|jsp|log|htaccess|htpasswd|gitignore|gitattributes|env|json|atom|eml|rss|markdown|sql|xml|xslt?|" +
"sh|rb|as|bat|cmd|cob|for|ftn|frm|frx|inc|lisp|scm|coffee|php[3-6]?|java|c|cbl|go|h|scala|vb|tmpl|lock|go|yml|yaml|tsv|lst)$").r
val isImageFilePattern = "(?i)\\\\.(jpe?g|gif|bmp|png|svg|tiff?)$".r
def preview(fileDescription: FileDescription, contentType: PreviewType): Unit = {
contentType match {
case Text => previewText(fileDescription)
case Image => previewImage(fileDescription)
case Unknown => previewUnknown(fileDescription)
}
}
def previewUnknown(fileDescription: FileDescription) = {
infoLabel.text = s"Can not preview ${fileDescription.path} ${new Size(fileDescription.size)}"
val flowPane = new FlowPane() {
children = Seq(
new Button("Try as Text") {
onAction = { _ =>
preview(fileDescription, Text)
}
},
new Button("Try as Image") {
onAction = { _ =>
preview(fileDescription, Image)
}
}
)
}
borderPane.center = flowPane
}
def preview(fileDescription: FileDescription): Unit = {
l.info(s"Previewing ${fileDescription.path}")
if (textFilesRegex.findFirstIn(fileDescription.path).isDefined) {
preview(fileDescription, Text)
} else if (isImageFilePattern.findFirstIn(fileDescription.path).isDefined) {
preview(fileDescription, Image)
} else {
preview(fileDescription, Unknown)
}
}
private def previewImage(fileDescription: FileDescription) = {
infoLabel.text = s"Previewing ${fileDescription.path} ${new Size(fileDescription.size)} as image"
l.info(s"Previewing as image file")
// image file
FxUtils.runInBackgroundThread {
val stream = BackupViewModel.index.getInputStream(fileDescription)
try {
val image = new Image(stream)
FxUtils.runInUiThread {
imageView.image = image
val property = Bindings.createDoubleBinding( { () =>
val widthProperty: Double = imageScrollPane.width()
Math.min(widthProperty, image.width())
}, imageScrollPane.width)
imageView.fitWidthProperty().bind(property)
borderPane.center = imageScrollPane
}
} finally {
stream.close()
}
}
}
private def previewText(fileDescription: FileDescription) = {
l.info(s"Previewing as text file")
// text file
infoLabel.text = s"Previewing ${fileDescription.path} (${fileDescription.size}) as text file"
FxUtils.runInBackgroundThread {
val stream = Source.fromInputStream(BackupViewModel.index.getInputStream(fileDescription))
val lines = stream.getLines()
val text = lines.take(10000).mkString("\\n")
val cut = !lines.isEmpty
stream.close()
l.info(s"Text loaded in background, displaying")
FxUtils.runInUiThread {
if (cut) {
infoLabel.text = infoLabel.text() + ". Only showing first 10000 lines."
}
textView.text = text
borderPane.center = textView
}
}
}
}
|
Stivo/DeScaBaTo
|
ui/src/main/scala/ch/descabato/ui/PreviewController.scala
|
Scala
|
gpl-3.0
| 4,329 |
package io.datalayer.common
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
object SparkContextManager {
var hasSC = false
var sc:Any = 0
def getSparkContext(workers: Int): SparkContext = {
if (!hasSC) {
val sparkConf = new SparkConf().setMaster("local[" + workers + "]").setAppName("SparkApp")
sc = new SparkContext(sparkConf)
hasSC = true
}
return sc.asInstanceOf[SparkContext]
}
def stopSparkContext() = {
if (hasSC) {
sc.asInstanceOf[SparkContext].stop()
}
}
def restartSparkContext(workers: Int): SparkContext = {
stopSparkContext()
getSparkContext(workers)
}
}
|
0asa/algorithm
|
src/main/scala/io/datalayer/common/SparkManager.scala
|
Scala
|
apache-2.0
| 664 |
/*
* Copyright (c) 2013-2014 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0, and
* you may not use this file except in compliance with the Apache License
* Version 2.0. You may obtain a copy of the Apache License Version 2.0 at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Apache License Version 2.0 is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the Apache License Version 2.0 for the specific language
* governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow
package enrich.kinesis
package bad
// Commons Codec
import org.apache.commons.codec.binary.Base64
// Specs2
import org.specs2.{ScalaCheck, Specification}
import org.specs2.scalaz.ValidationMatchers
// ScalaCheck
import org.scalacheck._
import org.scalacheck.Arbitrary._
// This project
import SpecHelpers._
class CorruptedThriftLinesSpec extends Specification with ScalaCheck with ValidationMatchers {
def is =
"This is a specification to test handling of corrupted Thrift payloads" ^
p ^
"Stream Enrich should return None for any corrupted Thrift raw events" ! e1 ^
end
// A bit of fun: the chances of generating a valid Thrift SnowplowRawEvent at random are
// so low that we can just use ScalaCheck here
def e1 = prop { (raw: String) =>
{
val eventBytes = Base64.decodeBase64(raw)
TestSource.enrichEvents(eventBytes)(0) must beFailing
}
}
}
|
TimothyKlim/snowplow
|
3-enrich/stream-enrich/src/test/scala/com.snowplowanalytics.snowplow.enrich.kinesis/bad/CorruptedThriftLinesSpec.scala
|
Scala
|
apache-2.0
| 1,655 |
package com.aluxian.tweeather.scripts
import org.apache.spark.Logging
/**
* This script is used to count the number of rows that [[TwitterFireCollector]] has collected.
*/
object TwitterFireCounter extends Script with Logging {
override def main(args: Array[String]) {
super.main(args)
// Import data
logInfo("Parsing text files")
val data = sc.textFile("/tw/fire/collected/*.text")
// Print count
logInfo(s"Count = ${data.count()}")
sc.stop()
}
}
|
Aluxian/Tweeather
|
src/main/scala/com/aluxian/tweeather/scripts/TwitterFireCounter.scala
|
Scala
|
apache-2.0
| 490 |
/*
* MatrixValueWindow.scala
* (LucreMatrix)
*
* Copyright (c) 2014-2017 Institute of Electronic Music and Acoustics, Graz.
* Copyright (c) 2014-2017 by Hanns Holger Rutz.
*
* This software is published under the GNU Lesser General Public License v2.1+
*
*
* For further information, please contact Hanns Holger Rutz at
* [email protected]
*/
package de.sciss.fscape
package stream
import akka.stream.{Attributes, SourceShape}
import de.sciss.fscape.stream.impl.{BlockingGraphStage, MatrixValueImpl, NodeImpl}
import de.sciss.lucre.matrix.Matrix
import scala.collection.immutable.{Seq => ISeq}
import scala.concurrent.Future
object MatrixValueWindow {
def apply(matrix: Future[Matrix.Reader], winSize: Int, dims: ISeq[Int])(implicit b: Builder): OutD = {
val source = new Stage(matrix, winSize = winSize, dims = dims.toArray)
val stage = b.add(source)
stage.out
}
private final val name = "MatrixValueWindow"
private type Shape = SourceShape[BufD]
private final class Stage(matrix: Future[Matrix.Reader], winSize: Int, dims: Array[Int])(implicit ctrl: Control)
extends BlockingGraphStage[Shape](s"$name($matrix)") {
val shape = SourceShape(OutD(s"$name.out"))
def createLogic(attr: Attributes): NodeImpl[Shape] =
new Logic(shape, matrix, winSize = winSize, dims = dims)
}
private final class Logic(shape: Shape, matrixF: Future[Matrix.Reader], winSize: Int, dims: Array[Int])
(implicit ctrl: Control)
extends MatrixValueImpl(name, shape, matrixF) {
private[this] val bufSize: Int = ctrl.blockSize
private[this] var winBuf = new Array[Double](winSize)
private[this] var bufOff: Int = winSize
private[this] var framesRead = 0L
override protected def stopped(): Unit = {
super.stopped()
winBuf = null
}
protected def process(matrix: Matrix.Reader): Unit = {
val chunk = math.min(bufSize, matrix.size - framesRead).toInt
if (chunk == 0) {
logStream(s"completeStage() $this")
completeStage()
} else {
val bufOut = ctrl.borrowBufD()
val _out = bufOut.buf
var outOff = 0
var remain = chunk
while (remain > 0) {
val chunk1 = math.min(remain, winSize - bufOff)
if (chunk1 > 0) {
System.arraycopy(winBuf, bufOff, _out, outOff, chunk1)
outOff += chunk1
bufOff += chunk1
remain -= chunk1
}
if (remain > 0) {
assert(bufOff == winSize)
matrix.readWindowDouble1D(dims = dims, buf = winBuf, off = 0)
bufOff = 0
}
}
bufOut.size = chunk // IntelliJ highlight bug
framesRead += chunk
push(shape.out, bufOut)
}
}
}
}
|
iem-projects/LucreMatrix
|
core/src/main/scala/de/sciss/fscape/stream/MatrixValueWindow.scala
|
Scala
|
lgpl-2.1
| 2,804 |
package org.jetbrains.plugins.scala.lang.libraryInjector
import java.io.{BufferedOutputStream, File, FileOutputStream}
import java.util.zip.{ZipEntry, ZipOutputStream}
import com.intellij.compiler.CompilerTestUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.testFramework.ModuleTestCase
import org.jetbrains.plugins.scala.PerfCycleTests
import org.jetbrains.plugins.scala.base.libraryLoaders._
import org.jetbrains.plugins.scala.compiler.CompileServerLauncher
import org.jetbrains.plugins.scala.components.libinjection.LibraryInjectorLoader
import org.jetbrains.plugins.scala.components.libinjection.TestAcknowledgementProvider.TEST_ENABLED_KEY
import org.jetbrains.plugins.scala.debugger._
import org.jetbrains.plugins.scala.lang.libraryInjector.LibraryInjectorTest.InjectorLibraryLoader
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.typedef.SyntheticMembersInjector
import org.jetbrains.plugins.scala.util.ScalaUtil
import org.junit.Assert.assertTrue
import org.junit.experimental.categories.Category
/**
* Created by mucianm on 16.03.16.
*/
@Category(Array(classOf[PerfCycleTests]))
class LibraryInjectorTest extends ModuleTestCase with ScalaSdkOwner {
override implicit val version: ScalaVersion = Scala_2_11
override implicit protected def module: Module = getModule
override protected def librariesLoaders: Seq[LibraryLoader] = Seq(
ScalaLibraryLoader(isIncludeReflectLibrary = true),
JdkLoader(getTestProjectJdk),
SourcesLoader(project.getBasePath),
InjectorLibraryLoader()
)
override protected def getTestProjectJdk: Sdk = DebuggerTestUtil.findJdk8()
override def setUp(): Unit = {
sys.props += (TEST_ENABLED_KEY -> "true")
super.setUp()
CompilerTestUtil.enableExternalCompiler()
DebuggerTestUtil.enableCompileServer(true)
DebuggerTestUtil.forceJdk8ForBuildProcess()
}
protected override def tearDown() {
disposeLibraries()
CompilerTestUtil.disableExternalCompiler(getProject)
CompileServerLauncher.instance.stop()
super.tearDown()
}
def testSimple() {
val injectorLoader = LibraryInjectorLoader.getInstance(getProject)
val classes = injectorLoader.getInjectorClasses(classOf[SyntheticMembersInjector])
assertTrue(classes.nonEmpty)
}
}
object LibraryInjectorTest {
case class InjectorLibraryLoader() extends ThirdPartyLibraryLoader {
override protected val name: String = "injector"
override protected def path(implicit sdkVersion: ScalaVersion): String = {
val tmpDir = ScalaUtil.createTmpDir("injectorTestLib")
InjectorLibraryLoader.simpleInjector.zip(tmpDir).getAbsolutePath
}
}
object InjectorLibraryLoader {
private val simpleInjector: ZDirectory = {
val manifest =
"""
|<intellij-compat>
| <scala-plugin since-version="0.0.0" until-version="9.9.9">
| <psi-injector interface="org.jetbrains.plugins.scala.lang.psi.impl.toplevel.typedef.SyntheticMembersInjector"
| implementation="com.foo.bar.Implementation">
| <source>META-INF/Implementation.scala</source>
| <source>META-INF/Foo.scala</source>
| </psi-injector>
| </scala-plugin>
|</intellij-compat>
|
""".stripMargin
val implementationClass =
"""
|package com.foo.bar
|import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.typedef.SyntheticMembersInjector
|
|class Implementation extends SyntheticMembersInjector { val foo = new Foo }
""".stripMargin
val fooClass =
"""
|package com.foo.bar
|class Foo
""".stripMargin
ZDirectory("META-INF",
Seq(
ZFile(LibraryInjectorLoader.INJECTOR_MANIFEST_NAME, manifest),
ZFile("Implementation.scala", implementationClass),
ZFile("Foo.scala", fooClass)
)
)
}
}
sealed trait Zippable {
val entryName: String
def withParent(name: String): Zippable
def zipTo(implicit outputStream: ZipOutputStream): Unit = {
outputStream.putNextEntry(new ZipEntry(entryName))
withStream
outputStream.closeEntry()
}
protected def withStream(implicit outputStream: ZipOutputStream): Unit
}
case class ZFile(name: String, data: String) extends Zippable {
override val entryName: String = name
override def withParent(parentName: String): ZFile = copy(name = s"$parentName/$name")
override protected def withStream(implicit outputStream: ZipOutputStream): Unit =
outputStream.write(data.getBytes("UTF-8"), 0, data.length)
}
case class ZDirectory(name: String, files: Seq[Zippable]) extends Zippable {
override val entryName: String = s"$name/"
def zip(toDir: File): File = {
val result = new File(toDir, "dummy_lib.jar")
writeTo(result)
result
}
private def writeTo(file: File): Unit = {
val outputStream: ZipOutputStream = null
try {
val outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)))
withStream(outputStream)
} finally {
if (outputStream != null) {
outputStream.close()
}
}
}
override def withParent(parentName: String): ZDirectory = copy(name = s"$parentName/$name")
override protected def withStream(implicit outputStream: ZipOutputStream): Unit =
files.map(_.withParent(name)).foreach(_.zipTo)
}
}
|
triplequote/intellij-scala
|
scala/scala-impl/test/org/jetbrains/plugins/scala/lang/libraryInjector/LibraryInjectorTest.scala
|
Scala
|
apache-2.0
| 5,584 |
package fr.eurecom.dsg.treelib.core
import org.apache.spark._
import org.apache.spark.SparkContext._
import org.apache.spark.rdd._
import scala.collection.immutable.HashMap
import java.io._
import java.io.DataOutputStream
import java.io.FileOutputStream
import java.io.DataInputStream
import java.io.FileInputStream
import scala.util.Random
import fr.eurecom.dsg.treelib.cart._
/**
* Abstract class of tree builder
*
* @param featureSet all features in the training data
* @param usefulFeatureSet the features which we used to build the tree (included the target feature)
*/
abstract class TreeBuilder extends Serializable {
protected val DEBUG: Boolean = true
/**
* Temporary model file
*/
val temporaryModelFile = "/tmp/model.temp"
/********************************************************/
/* REGION OF MAIN COMPONENTS */
/********************************************************/
/**
* Contains raw information about features, which will be used to construct a feature set
*/
//private var metadata: Array[String] = Array[String]()
private var headerOfDataset = Array[String]()
/**
* Contains information of all features in data
*/
var fullFeatureSet = new FeatureSet()
/**
* The number of features which will be used for building tree (include the target feature)
*/
//var usefulFeatureSet = new FeatureSet()
//var usefulFeatures : Set[Int] = null // means all features will be used for building tree
protected var numberOfUsefulFeatures : Int = fullFeatureSet.numberOfFeature
/**
* Tree model
*/
var treeModel: TreeModel = new CARTTreeModel()
/**
* Default value of the index of the target feature.
* Here this value is the index of the last feature
*/
var yIndexDefault = fullFeatureSet.numberOfFeature - 1 // = number_of_feature - 1
/**
* index of target feature,
* default value is the index of the last feature in dataset
*/
protected var yIndex = yIndexDefault
/**
* the indices/indexes of X features, which will be used to predict the target feature
* this variable can be infered from featureSet and yIndex
* but because it will be used in functions processLine, and buidingTree
* so we don't want to calculate it multiple time
* The default value is the index of all features, except the last one
*/
protected var xIndexes = fullFeatureSet.data.map(x => x.index).filter(x => (x != yIndex)).toSet[Int]
/**
* A value , which is used to marked a split point is invalid
*/
protected val ERROR_SPLITPOINT_VALUE = ",,,@,,,"
/**
* The data will be used to build tree
*/
var trainingData: RDD[String] = null;
/**
* In each node split, do we choose splitpoint on the random subset of features ?
* This argument is often used when building tree with Random Forest
*/
var useRandomSubsetFeature = false
/**
* Cache the dataset
*/
var useCache = false
/*****************************************************************/
/* REGION OF PARAMETERS */
/*****************************************************************/
/**
* minimum records to do a splitting, default value is 10
*/
var minsplit = 10
/**
* delimiter of fields in data set, default value is ","
*/
var delimiter = ','
/**
* coefficient of variation, default value is 0.1
*/
var threshold: Double = 0.1
/**
* Max depth of the tree, default value if 30
*/
protected var maxDepth: Int = 62
/**
* The maximum complexity of the tree
*/
protected var maximumComplexity = 0.001
def setDelimiter(c: Char) = {
delimiter = c
}
/**
* Set the minimum records of splitting
* It's mean if a node have the number of records <= minsplit, it can't be splitted anymore
*
* @param xMinSplit new minimum records for splitting
*/
def setMinSplit(xMinSplit: Int) = {
this.minsplit = xMinSplit
this.treeModel.minsplit = xMinSplit
}
/**
* Set threshold for stopping criterion. This threshold is coefficient of variation
* A node will stop expand if Dev(Y)/E(Y) < threshold
* In which:
* Dev(Y) is standard deviation
* E(Y) is medium of Y
*
* @param xThreshold new threshold
*/
def setThreshold(xThreshlod: Double) = {
threshold = xThreshlod
treeModel.threshold = xThreshlod
}
/**
* Set the maximum of depth of tree
*/
def setMaxDepth(value: Int) = {
this.maxDepth = value
this.treeModel.maxDepth = value
}
def setMaximumComplexity(cp: Double) = {
this.maximumComplexity = cp
this.treeModel.maximumComplexity = cp
}
/*****************************************************************/
/* REGION OF UTILITIES FUNCTIONS */
/*****************************************************************/
/**
* Convert feature name (or feature info) to theirs index
* @param xNames Set of feature names or set of FeatureInformation
* @param yName Name of the target feature
* @output A tuple with the first component is the set of indices of predictors, the second
* component is the index of the target feature
*/
private def getXIndexesAndYIndexByNames(xNames: Set[Any], yName: String): (Set[Int], Int) = {
var yindex = fullFeatureSet.getIndex(yName)
if (yName == "" && yindex < 0)
yindex = this.yIndexDefault
if (yindex < 0)
throw new Exception("ERROR: Can not find attribute `" + yName + "` in (" + fullFeatureSet.data.map(f => f.Name).mkString(",") + ")")
// index of features, which will be used to predict the target feature
var xindexes =
if (xNames.isEmpty) // if user didn't specify xFeature, we will process on all feature, exclude Y feature (to check stop criterion)
fullFeatureSet.data.filter(_.index != yindex).map(x => x.index).toSet[Int]
else //xNames.map(x => featureSet.getIndex(x)) //+ yindex
{
xNames.map(x => {
var index = x match {
case Feature(name, ftype, _) => {
val idx = fullFeatureSet.getIndex(name)
fullFeatureSet.update(Feature(name, ftype, idx), idx)
idx
}
case s: String => {
fullFeatureSet.getIndex(s)
}
case _ => { throw new Exception("Invalid feature. Expect as.String(feature_name) or as.Number(feature_name) or \\"feature_name\\"") }
}
if (index < 0)
throw new Exception("Could not find feature " + x)
else
index
})
}
(xindexes, yindex)
}
/**
* From the full training set, remove the unused columns
* @param trainingData the training data
* @param xIndexes the set of indices of predictors
* @param yIndex the index of the target feature
* @param removeInvalidRecord remove line which contains invalid feature values or not
* @output the new RDD which will be use "directly" in building phase
*/
/*
def filterUnusedFeatures(trainingData: RDD[String], xIndexes: Set[Int], yIndex: Int, removeInvalidRecord: Boolean = true): RDD[String] = {
var i = 0
var j = 0
var temp = trainingData.map(line => {
var array = line.split(this.delimiter)
i = 0
j = 0
var newLine = ""
try {
array.foreach(element => {
if (yIndex == i || xIndexes.contains(i)) {
if (newLine.equals(""))
newLine = element
else {
newLine = "%s,%s".format(newLine, element)
}
if (removeInvalidRecord) {
this.usefulFeatureSet.data(j).Type match {
case FeatureType.Categorical => element
case FeatureType.Numerical => element.toDouble
}
}
j = j + 1
}
i = i + 1
})
newLine
} catch {
case _: Throwable => ""
}
})
temp.filter(line => !line.equals(""))
}
*/
/**
* Convert index of the useful features into index in the full feature set
* @param featureSet the full feature set
* @param usefulFeatureSet the useful feature set
* @param a tuple with the first component is the set of indices of predictors
* the second component is the index of the target feature
*/
/*
private def mapFromUsefulIndexToOriginalIndex(featureSet: FeatureSet, usefulFeatureSet: FeatureSet): (Set[Int], Int) = {
var xIndexes = treeModel.xIndexes.map(index => treeModel.fullFeatureSet.getIndex(treeModel.usefulFeatureSet.data(index).Name))
var yIndex = treeModel.fullFeatureSet.getIndex(usefulFeatureSet.data(treeModel.yIndex).Name)
(xIndexes, yIndex)
}
*/
/**
* Get node by nodeID
* @param id node id
* @output node
*/
protected def getNodeByID(id: BigInt): CARTNode = {
if (id != 0) {
val level = (Math.log(id.toDouble) / Math.log(2)).toInt
var i: Int = level - 1
var TWO: BigInt = 2
var parent = treeModel.tree.asInstanceOf[CARTNode]; // start adding from root node
try {
while (i >= 0) {
if ((id / (TWO << i - 1)) % 2 == 0) {
// go to the left
parent = parent.left
} else {
// go go the right
parent = parent.right
}
i -= 1
} // end while
} catch {
case e: Throwable => {
e.printStackTrace()
if (DEBUG) println("currentID:" + id)
if (DEBUG) println("currentTree:\\n" + treeModel.tree)
throw e
}
}
parent
} else {
null
}
}
/*********************************************************************/
/* REGION FUNCTIONS OF BUILDING PHASE */
/*********************************************************************/
/**
* This function is used to build the tree
*
* @param yFeature name of target feature, the feature which we want to predict.
* Default value is the name of the last feature
* @param xFeatures set of names of features which will be used to predict the target feature
* Default value is all features names, except target feature
* @return <code>TreeModel</code> the root of tree
* @see TreeModel
*/
def buildTree(yFeature: String = "",
xFeatures: Set[Any] = Set[Any]()): TreeModel = {
if (this.trainingData == null) {
throw new Exception("ERROR: Dataset can not be null.Set dataset first")
}
if (yIndexDefault < 0) {
throw new Exception("ERROR:Dataset is invalid or invalid feature names")
}
try {
treeModel.tree = null
// These information will be used in Pruning phase
treeModel.xFeatures = xFeatures
treeModel.yFeature = yFeature
var (xIndexes, yIndex) = this.getXIndexesAndYIndexByNames(xFeatures, yFeature)
println("current yIndex=" + yIndex + " xIndex:" + xIndexes.toString)
// SET UP LIST OF USEFUL FEATURES AND THEIR INDEXES //
var usefulFeatureList = List[Feature]()
var i = -1
var usefulIndexes = List[Int]()
var newYIndex = 0
fullFeatureSet.data.foreach(feature => {
if (xIndexes.contains(feature.index) || feature.index == yIndex) {
i = i + 1
if (feature.index == yIndex) {
newYIndex = i
println("new yindex:" + newYIndex)
}
usefulIndexes = usefulIndexes.:+(i)
usefulFeatureList = usefulFeatureList.:+(Feature(feature.Name, feature.Type, i))
}
})
this.yIndex = yIndex
this.xIndexes = xIndexes
treeModel.xIndexes = xIndexes
treeModel.yIndex = yIndex
treeModel.fullFeatureSet = this.fullFeatureSet
treeModel.treeBuilder = this
this.numberOfUsefulFeatures = this.xIndexes.size + 1
println("xIndexes:" + xIndexes + " yIndex:" + yIndex)
println("Building tree with predictors:" + this.xIndexes.map(i => fullFeatureSet.data(i).Name))
println("Target feature:" + fullFeatureSet.data(yIndex).Name)
//this.startBuildTree(this.trainingData, xIndexes, yIndex)
// TODO: the use of cache here is "wrong", should cache RDD only when useful. See also the unpersist method.
if (this.useCache)
this.startBuildTree(this.trainingData.cache, xIndexes, yIndex)
else
this.startBuildTree(this.trainingData, xIndexes, yIndex)
}
catch {
case e: Throwable => {
println("Error:" + e.getStackTraceString)
}
}
this.trainingData.unpersist(true)
this.treeModel
}
/**
* This function is used to build the tree
*
* @param yFeature name of target feature, the feature which we want to predict.
* @param xFeatures set of names of features which will be used to predict the target feature
* @return <code>TreeModel</code> the root of tree
* @see TreeModel
*/
protected def startBuildTree(trainingData: RDD[String],
xIndexes: Set[Int],
yIndex: Int): Unit
protected def getPredictedValue(info: StatisticalInformation): Any = {
info.YValue
}
protected def updateModel(info: Array[(BigInt, SplitPoint, StatisticalInformation)], isStopNode: Boolean = false) = {
info.foreach(stoppedRegion =>
{
var (label, splitPoint, statisticalInformation) = stoppedRegion
if (DEBUG) println("update model with label=%d splitPoint:%s".format(
label,
splitPoint))
var newnode = (
if (isStopNode) {
new CARTLeafNode(splitPoint.point.toString)
} else {
val chosenFeatureInfoCandidate = fullFeatureSet.data.find(f => f.index == splitPoint.index)
chosenFeatureInfoCandidate match {
case Some(chosenFeatureInfo) => {
new CARTNonLeafNode(chosenFeatureInfo,
splitPoint,
new CARTLeafNode("empty.left"),
new CARTLeafNode("empty.right"));
}
case None => { new CARTLeafNode(this.ERROR_SPLITPOINT_VALUE) }
}
}) // end of assign value for new node
if (newnode.value == this.ERROR_SPLITPOINT_VALUE) {
println("Value of job id=" + label + " is invalid")
} else {
if (!isStopNode) { // update predicted value for non-leaf node
newnode.value = getPredictedValue(statisticalInformation)
}
newnode.statisticalInformation = statisticalInformation
if (DEBUG) println("create node with statistical infor:" + statisticalInformation + "\\n new node:" + newnode.value)
// If tree has zero node, create a root node
if (treeModel.isEmpty) {
treeModel.tree = newnode;
} else // add new node to current model
{
var parent = getNodeByID(label >> 1)
if (label % 2 == 0) {
parent.setLeft(newnode)
} else {
parent.setRight(newnode)
}
}
}
})
}
/************************************************************/
/* REGION: SET DATASET AND METADATA */
/************************************************************/
/**
* Set the training dataset to used for building tree
*
* @param trainingData the training dataset
* @throw Exception if the dataset contains less than 2 lines
*/
def setDataset(trainingData: RDD[String]) {
var firstLine = trainingData.take(1)
// If we can not get 2 first line of dataset, it's invalid dataset
if (firstLine.length < 1) {
throw new Exception("ERROR:Invalid dataset")
} else {
this.trainingData = trainingData;
/*
var header = firstLine(0)
var temp_header = header.split(delimiter)
if (hasHeader) {
this.headerOfDataset = temp_header
} else {
var i = -1;
this.headerOfDataset = temp_header.map(v => { i = i + 1; "Column" + i })
}
*/
// determine types of features automatically
// Get the second line of dataset and try to parse each of them to double
// If we can parse, it's a numerical feature, otherwise, it's a categorical feature
var sampleData = firstLine(0).split(delimiter);
var i = -1;
this.headerOfDataset = sampleData.map(v => { i = i + 1; "Column" + i })
i = 0
var listOfFeatures = List[Feature]()
// if we can parse value of a feature into double, this feature may be a numerical feature
sampleData.foreach(v => {
Utility.parseDouble(v.trim()) match {
case Some(d) => { listOfFeatures = listOfFeatures.:+(Feature(headerOfDataset(i), FeatureType.Numerical, i)) }
case None => { listOfFeatures = listOfFeatures.:+(Feature(headerOfDataset(i), FeatureType.Categorical, i)) }
}
i = i + 1
})
// update the dataset
fullFeatureSet = new FeatureSet(listOfFeatures)
updateFeatureSet()
}
}
/**
* Set feature names
*
* @param names a line contains names of features,
* separated by by a delimiter, which you set before (default value is comma ',')
* Example: Temperature,Age,"Type"
* @throw Exception if the training set is never be set before
*/
def setFeatureNames(names: Array[String]) = {
if (this.trainingData == null)
throw new Exception("Trainingset is null. Set dataset first")
else {
if (names.length != fullFeatureSet.data.length) {
throw new Exception("Incorrect names")
}
var i = 0
names.foreach(name => {
fullFeatureSet.data(i).Name = name
fullFeatureSet.update(fullFeatureSet.data(i), i)
i = i + 1
})
updateFeatureSet()
}
}
/**
* Update the feature set based on the information of metadata
*/
private def updateFeatureSet() = {
yIndexDefault = fullFeatureSet.numberOfFeature - 1
println("Set new yIndexDefault = " + yIndexDefault)
//treeBuilder = new ThreadTreeBuilder(featureSet);
//treeBuilder = treeBuilder.createNewInstance(featureSet, usefulFeatureSet)
}
/* END REGION DATASET AND METADATA */
/************************************************/
/* REGION FUNCTIONS OF PREDICTION MAKING */
/************************************************/
/**
* Predict value of the target feature base on the values of input features
*
* @param record an array, which its each element is a value of each input feature (already remove unused features)
* @return predicted value or '???' if input record is invalid
*/
private def predictOnPreciseData(record: Array[String], ignoreBranchIDs: Set[BigInt]): String = {
try {
treeModel.predict(record, ignoreBranchIDs)
} catch {
case e: Exception => { println("Error P: " + e.getStackTraceString); "???" }
}
}
def predictOneInstance(record: Array[String], ignoreBranchIDs: Set[BigInt] = Set[BigInt]()): String = {
if (record.length == 0)
"???"
else {
/*
var (xIndexes, yIndex) = mapFromUsefulIndexToOriginalIndex(fullFeatureSet, usefulFeatureSet)
var newRecord: Array[String] = Array[String]()
var i = 0
for (field <- record) {
if (i == yIndex || xIndexes.contains(i)) {
newRecord = newRecord.:+(field)
}
i = i + 1
}
predictOnPreciseData(newRecord, ignoreBranchIDs)
*
*/
predictOnPreciseData(record, ignoreBranchIDs)
}
}
/**
* Predict value of the target feature base on the values of input features
*
* @param testingData the RDD of testing data
* @return a RDD contain predicted values
*/
def predict(testingData: RDD[String],
delimiter: String = ",",
ignoreBranchIDs: Set[BigInt] = Set[BigInt]()): RDD[String] = {
/*
* var (xIndexes, yIndex) = mapFromUsefulIndexToOriginalIndex(fullFeatureSet, usefulFeatureSet)
var newTestingData = filterUnusedFeatures(testingData, xIndexes, yIndex, false)
newTestingData.map(line => this.predictOnPreciseData(line.split(delimiter), ignoreBranchIDs))
*/
testingData.map(line => this.predictOnPreciseData(line.split(delimiter), ignoreBranchIDs))
}
/***********************************************/
/* REGION WRITING AND LOADING MODEL */
/***********************************************/
/**
* Write the current tree model to file
*
* @param path where we want to write to
*/
def writeModelToFile(path: String) = {
val ois = new ObjectOutputStream(new FileOutputStream(path))
ois.writeObject(treeModel)
ois.close()
}
/**
* Load tree model from file
*
* @param path the location of file which contains tree model
*/
def loadModelFromFile(path: String) = {
//val js = new JavaSerializer(null, null)
val ois = new ObjectInputStream(new FileInputStream(path)) {
override def resolveClass(desc: java.io.ObjectStreamClass): Class[_] = {
try { Class.forName(desc.getName, false, getClass.getClassLoader) }
catch { case ex: ClassNotFoundException => super.resolveClass(desc) }
}
}
var rt = ois.readObject().asInstanceOf[TreeModel]
//treeModel = rt
//this.featureSet = treeModel.featureSet
//this.usefulFeatureSet = treeModel.usefulFeatureSet
setTreeModel(rt)
ois.close()
}
def setTreeModel(tm: TreeModel) = {
this.treeModel = tm
this.fullFeatureSet = tm.fullFeatureSet
//this.usefulFeatureSet = tm.usefulFeatureSet
//this.usefulFeatures = tm.usefulFeatures
updateFeatureSet()
}
/**
* Recover, repair and continue build tree from the last state
*/
def continueFromIncompleteModel(trainingData: RDD[String], path_to_model: String): TreeModel = {
loadModelFromFile(path_to_model)
this.treeModel = treeModel
this.fullFeatureSet = treeModel.fullFeatureSet
//this.usefulFeatureSet = treeModel.usefulFeatureSet
//var (xIndexes, yIndex) = mapFromUsefulIndexToOriginalIndex(fullFeatureSet, usefulFeatureSet)
//var newtrainingData = filterUnusedFeatures(trainingData, xIndexes, yIndex)
if (treeModel == null) {
throw new Exception("The tree model is empty because of no building. Please build it first")
}
if (treeModel.isComplete) {
println("This model is already complete")
} else {
println("Recover from the last state")
/* INITIALIZE */
this.fullFeatureSet = treeModel.fullFeatureSet
//this.usefulFeatureSet = treeModel.usefulFeatureSet
this.xIndexes = treeModel.xIndexes
this.yIndex = treeModel.yIndex
startBuildTree(trainingData, xIndexes, yIndex)
}
treeModel
}
def createNewInstance() : TreeBuilder
}
|
bigfootproject/treelib
|
src/main/scala/fr/eurecom/dsg/treelib/core/TreeBuilder.scala
|
Scala
|
apache-2.0
| 25,326 |
package sbtdynver
import org.scalacheck._, Prop._
object GitDescribeOutputSpec extends Properties("GitDescribeOutputSpec") {
test("v1.0.0", "v1.0.0", 0, "", "" )
test("v1.0.0+20140707-1030", "v1.0.0", 0, "", "+20140707-1030")
test("v1.0.0+3-1234abcd", "v1.0.0", 3, "1234abcd", "" )
test("v1.0.0+3-1234abcd+20140707-1030", "v1.0.0", 3, "1234abcd", "+20140707-1030")
test("v1.0.0+3-1234abcd+20140707-1030\\r\\n", "v1.0.0", 3, "1234abcd", "+20140707-1030", "handles CR+LF (Windows)") // #20, didn't match
test("1234abcd", "1234abcd", 0, "", "" )
test("1234abcd+20140707-1030", "1234abcd", 0, "", "+20140707-1030")
test("HEAD+20140707-1030", "HEAD", 0, "", "+20140707-1030")
def test(v: String, ref: String, dist: Int, sha: String, dirtySuffix: String, propName: String = null) = {
val out = GitDescribeOutput(GitRef(ref), GitCommitSuffix(dist, sha), GitDirtySuffix(dirtySuffix))
val propName1 = if (propName == null) s"parses $v" else propName
property(propName1) = DynVer.parser.parse(v) ?= out
}
}
|
dwijnand/sbt-dynver
|
dynver/src/test/scala/sbtdynver/GitDescribeOutputSpec.scala
|
Scala
|
apache-2.0
| 1,246 |
package com.rydgel.scalagram.responses
import play.api.libs.json.Json
case class Videos(low_bandwith: Option[Video], low_resolution: Video, standard_resolution: Video) {
lazy val lowBandwith = low_bandwith
lazy val lowResolution = low_resolution
lazy val standardResolution = standard_resolution
}
object Videos {
implicit val VideosReads = Json.reads[Videos]
implicit val VideosWrites = Json.writes[Videos]
}
|
Rydgel/scalagram
|
src/main/scala/com/rydgel/scalagram/responses/Videos.scala
|
Scala
|
mit
| 422 |
package yang.flexmapping
import java.util
import org.scalatest.FunSuite
import yang.flexmapping.process.FlemxMappingProcesserCreator
/**
* Created by y28yang on 4/8/2016.
*/
class FlemxMappingProcesserCreatorTest extends FunSuite {
test("testGenerate") {
// val xmlString = xml.XML.loadFile(getClass.getResource("/fmFlexMappingFile_REL6.xml").getFile)
val flemxMappingProcesserCreator=new FlemxMappingProcesserCreator
flemxMappingProcesserCreator.parseXmlFile(page)
val events=new java.util.HashMap[String, String]()
events.put("3gppInstance","field1")
events.put("3gppInstance","field1")
events.put("3gppInstance","field1")
}
val page = <eventMappings
xmlns="http://www.nokia.com/schemas/3gpp/Nbi/FmMapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nokia.com/schemas/3gpp/Nbi/FmMapping c3g_fm_flex_mapping.xsd">
<mapping logName="CREATE ALARM">
<filter>
<checkEvent>alarmNew</checkEvent>
</filter>
<domainName>
<fromEvent attributeName="irpVersion"/>
</domainName>
<typeName>
<fixedValue>x1</fixedValue>
</typeName>
<eventName>
<fromEvent attributeName="3gppEventType"/>
</eventName>
<attribute id="e">
<fromEvent attributeName="3gppInstance"/>
</attribute>
<attribute id="d">
<fromEvent attributeName="3gppClass"/>
</attribute>
<attribute id="a" type="long">
<fromEvent attributeName="consecNbr"/>
</attribute>
<attribute id="b" type="time">
<fromEvent attributeName="alarmTime"/>
</attribute>
<attribute id="c">
<fromEvent attributeName="systemDN"/>
</attribute>
<attribute id="g" type="short">
<fromEvent attributeName="probableCause"/>
</attribute>
<attribute id="h" type="short">
<fromEvent attributeName="3gppSeverity"/>
</attribute>
<attribute id="i" type="string">
<fromEvent attributeName="alarmNumber"/>
</attribute>
<attribute id="j">
<fromEvent attributeName="alarmText"/>
<fixedValue>|</fixedValue>
<fromEvent attributeName="additionalInfo"/>
<fixedValue>|</fixedValue>
<fromEvent attributeName="userAddInfo"/>
<fixedValue>|</fixedValue>
<fromEvent attributeName="diagInfo"/>
</attribute>
<attribute id="additionalInformation">
<fromEvent attributeName="additionalInfo"/>
</attribute>
<attribute id="userAdditionalInformation">
<fromEvent attributeName="userAddInfo"/>
</attribute>
<attribute id="diagnosticInformation">
<fromEvent attributeName="diagInfo"/>
</attribute>
<attribute id="f">
<fromEvent attributeName="alarmId"/>
</attribute>
</mapping>
<mapping logName="ACK">
<filter>
<checkEvent>alarmAck</checkEvent>
</filter>
<domainName>
<fromEvent attributeName="irpVersion"/>
</domainName>
<typeName>
<fixedValue>x3</fixedValue>
</typeName>
<eventName>
<fromEvent attributeName="3gppEventType"/>
</eventName>
<attribute id="e">
<fromEvent attributeName="3gppInstance"/>
</attribute>
<attribute id="d">
<fromEvent attributeName="3gppClass"/>
</attribute>
<attribute id="a" type="long">
<fromEvent attributeName="consecNbr"/>
</attribute>
<attribute id="b" type="time">
<fromEvent attributeName="ackTime"/>
</attribute>
<attribute id="c">
<fromEvent attributeName="systemDN"/>
</attribute>
<attribute id="g" type="short">
<fromEvent attributeName="probableCause"/>
</attribute>
<attribute id="h" type="short">
<fromEvent attributeName="3gppSeverity"/>
</attribute>
<attribute id="l">
<fromEvent attributeName="ackUser"/>
</attribute>
<attribute id="m">
<fromEvent attributeName="ackSystemId"/>
</attribute>
<attribute id="n" type="short">
<fromEvent attributeName="3gppAckStatus"/>
</attribute>
<attribute id="f">
<fromEvent attributeName="alarmId"/>
</attribute>
</mapping>
<mapping logName="UNACK">
<filter>
<checkEvent>alarmUnack</checkEvent>
</filter>
<domainName>
<fromEvent attributeName="irpVersion"/>
</domainName>
<typeName>
<fixedValue>x3</fixedValue>
</typeName>
<eventName>
<fromEvent attributeName="3gppEventType"/>
</eventName>
<attribute id="e">
<fromEvent attributeName="3gppInstance"/>
</attribute>
<attribute id="d">
<fromEvent attributeName="3gppClass"/>
</attribute>
<attribute id="a" type="long">
<fromEvent attributeName="consecNbr"/>
</attribute>
<attribute id="b" type="time">
<fromEvent attributeName="ackTime"/>
</attribute>
<attribute id="c">
<fromEvent attributeName="systemDN"/>
</attribute>
<attribute id="g" type="short">
<fromEvent attributeName="probableCause"/>
</attribute>
<attribute id="h" type="short">
<fromEvent attributeName="3gppSeverity"/>
</attribute>
<attribute id="l">
<fromEvent attributeName="ackUser"/>
</attribute>
<attribute id="m">
<fromEvent attributeName="ackSystemId"/>
</attribute>
<attribute id="n" type="short">
<fromEvent attributeName="3gppAckStatus"/>
</attribute>
<attribute id="f">
<fromEvent attributeName="alarmId"/>
</attribute>
</mapping>
<mapping logName="CHANGE SEVERITY">
<filter>
<checkEvent>alarmSeverityChange</checkEvent>
</filter>
<domainName>
<fromEvent attributeName="irpVersion"/>
</domainName>
<typeName>
<fixedValue>x2</fixedValue>
</typeName>
<eventName>
<fromEvent attributeName="3gppEventType"/>
</eventName>
<attribute id="e">
<fromEvent attributeName="3gppInstance"/>
</attribute>
<attribute id="d">
<fromEvent attributeName="3gppClass"/>
</attribute>
<attribute id="a" type="long">
<fromEvent attributeName="consecNbr"/>
</attribute>
<attribute id="b" type="time">
<fromEvent attributeName="alarmTime"/>
</attribute>
<attribute id="c">
<fromEvent attributeName="systemDN"/>
</attribute>
<attribute id="g" type="short">
<fromEvent attributeName="probableCause"/>
</attribute>
<attribute id="h" type="short">
<fromEvent attributeName="3gppSeverity"/>
</attribute>
<attribute id="f">
<fromEvent attributeName="alarmId"/>
</attribute>
</mapping>
<mapping logName="CANCEL ALARM">
<filter>
<checkEvent>alarmCancel</checkEvent>
</filter>
<domainName>
<fromEvent attributeName="irpVersion"/>
</domainName>
<typeName>
<fixedValue>x5</fixedValue>
</typeName>
<eventName>
<fromEvent attributeName="3gppEventType"/>
</eventName>
<attribute id="e">
<fromEvent attributeName="3gppInstance"/>
</attribute>
<attribute id="d">
<fromEvent attributeName="3gppClass"/>
</attribute>
<attribute id="a" type="long">
<fromEvent attributeName="consecNbr"/>
</attribute>
<attribute id="b" type="time">
<fromEvent attributeName="cancelTime"/>
</attribute>
<attribute id="c">
<fromEvent attributeName="systemDN"/>
</attribute>
<attribute id="g" type="short">
<fromEvent attributeName="probableCause"/>
</attribute>
<attribute id="h" type="short">
<fromEvent attributeName="3gppSeverity"/>
</attribute>
<attribute id="y">
<fromEvent attributeName="cancelUser"/>
</attribute>
<attribute id="z">
<fromEvent attributeName="cancelSystemId"/>
</attribute>
<attribute id="f">
<fromEvent attributeName="alarmId"/>
</attribute>
</mapping>
<mapping logName="UPLOAD ALARM">
<filter>
<checkEvent>alarmList</checkEvent>
</filter>
<domainName>
<fromEvent attributeName="irpVersion"/>
</domainName>
<typeName>
<fromEvent attributeName="uploadedAlarmTypeName"/>
</typeName>
<eventName>
<fromEvent attributeName="3gppEventType"/>
</eventName>
<attribute id="e">
<fromEvent attributeName="3gppInstance"/>
</attribute>
<attribute id="d">
<fromEvent attributeName="3gppClass"/>
</attribute>
<attribute id="a" type="long">
<fromEvent attributeName="consecNbr"/>
</attribute>
<attribute id="b" type="time">
<fromEvent attributeName="alarmTime"/>
</attribute>
<attribute id="c">
<fromEvent attributeName="systemDN"/>
</attribute>
<attribute id="g" type="short">
<fromEvent attributeName="probableCause"/>
</attribute>
<attribute id="h" type="short">
<fromEvent attributeName="3gppSeverity"/>
</attribute>
<attribute id="i" type="string">
<fromEvent attributeName="alarmNumber"/>
</attribute>
<attribute id="j">
<fromEvent attributeName="alarmText"/>
<fixedValue>|</fixedValue>
<fromEvent attributeName="additionalInfo"/>
<fixedValue>|</fixedValue>
<fromEvent attributeName="userAddInfo"/>
<fixedValue>|</fixedValue>
<fromEvent attributeName="diagInfo"/>
</attribute>
<attribute id="additionalInformation">
<fromEvent attributeName="additionalInfo"/>
</attribute>
<attribute id="userAdditionalInformation">
<fromEvent attributeName="userAddInfo"/>
</attribute>
<attribute id="diagnosticInformation">
<fromEvent attributeName="diagInfo"/>
</attribute>
<attribute id="n" type="short">
<fromEvent attributeName="3gppAckStatus"/>
</attribute>
<attribute id="f">
<fromEvent attributeName="alarmId"/>
</attribute>
<conditionalAttributes>
<filter>
<checkEvent>alarmListAck</checkEvent>
</filter>
<attribute id="k" type="time">
<fromEvent attributeName="ackTime"/>
</attribute>
<attribute id="l">
<fromEvent attributeName="ackUser"/>
</attribute>
<attribute id="m">
<fromEvent attributeName="ackSystemId"/>
</attribute>
</conditionalAttributes>
<conditionalAttributes>
<filter>
<checkEvent>alarmListCancel</checkEvent>
</filter>
<attribute id="y">
<fromEvent attributeName="cancelUser"/>
</attribute>
<attribute id="z">
<fromEvent attributeName="cancelSystemId"/>
</attribute>
</conditionalAttributes>
</mapping>
<mapping logName="REBUILT ALARM">
<filter>
<checkEvent>alarmListRebuilt</checkEvent>
</filter>
<domainName>
<fromEvent attributeName="irpVersion"/>
</domainName>
<typeName>
<fixedValue>x6</fixedValue>
</typeName>
<eventName>
<fixedValue></fixedValue>
</eventName>
<attribute id="e">
<fromEvent attributeName="systemDN"/>
<fixedValue>,AlarmIRP=AlarmIRP-1</fixedValue>
</attribute>
<attribute id="d">
<fixedValue>AlarmIRP</fixedValue>
</attribute>
<attribute id="a" type="long">
<fromEvent attributeName="uniqueNumber"/>
</attribute>
<attribute id="b" type="time">
<fromEvent attributeName="alarmTime"/>
</attribute>
<attribute id="c">
<fromEvent attributeName="systemDN"/>
</attribute>
<attribute id="x">
<fromEvent attributeName="alarmText"/>
</attribute>
<attribute id="ff">
<fixedValue>REQUIRED</fixedValue>
</attribute>
</mapping>
<mapping logName="POTENTIAL FAULTY ALARM">
<filter>
<checkEvent>potentialFaultyAlarmList</checkEvent>
</filter>
<domainName>
<fromEvent attributeName="irpVersion"/>
</domainName>
<typeName>
<fixedValue>x7</fixedValue>
</typeName>
<eventName>
<fixedValue></fixedValue>
</eventName>
<attribute id="e">
<fromEvent attributeName="3gppInstance"/>
</attribute>
<attribute id="d">
<fromEvent attributeName="3gppClass"/>
</attribute>
<attribute id="a" type="long">
<fromEvent attributeName="uniqueNumber"/>
</attribute>
<attribute id="b" type="time">
<fromEvent attributeName="alarmTime"/>
</attribute>
<attribute id="c">
<fromEvent attributeName="systemDN"/>
</attribute>
<attribute id="x">
<fixedValue>Maintenance</fixedValue>
</attribute>
</mapping>
</eventMappings>
}
|
wjingyao2008/firsttry
|
NextGenAct/src/test/scala/yang/flexmapping/FlemxMappingProcesserCreatorTest.scala
|
Scala
|
apache-2.0
| 13,183 |
/*
* Copyright 2017 HM Revenue & Customs
*
* 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.gov.hmrc.ct.accounts.frs10x
import play.api.libs.json.{Reads, _}
import uk.gov.hmrc.ct.accounts.approval.boxes._
import uk.gov.hmrc.ct.accounts.frs10x.boxes._
import uk.gov.hmrc.ct.box.formats._
package object formats {
implicit val ac8081Format = new OptionalBooleanFormat(AC8081.apply)
implicit val ac8082Format = new OptionalBooleanFormat(AC8082.apply)
implicit val ac8083Format = new OptionalBooleanFormat(AC8083.apply)
implicit val ac8088Format = new OptionalBooleanFormat(AC8088.apply)
implicit val ac8089Format = new OptionalBooleanFormat(AC8089.apply)
implicit val acq8161Format = new OptionalBooleanFormat[ACQ8161](ACQ8161.apply)
implicit val ac8021Format: Format[AC8021] = new OptionalBooleanFormat[AC8021](AC8021.apply)
implicit val ac8023Format: Format[AC8023] = new OptionalBooleanFormat[AC8023](AC8023.apply)
implicit val ac8051Format: Format[AC8051] = new OptionalStringFormat[AC8051](AC8051.apply)
implicit val ac8052Format: Format[AC8052] = new OptionalStringFormat[AC8052](AC8052.apply)
implicit val ac8053Format: Format[AC8053] = new OptionalStringFormat[AC8053](AC8053.apply)
implicit val ac8054Format: Format[AC8054] = new OptionalStringFormat[AC8054](AC8054.apply)
implicit val ac8899Format: Format[AC8899] = new OptionalBooleanFormat[AC8899](AC8899.apply)
implicit val directorFormat = Json.format[Director]
implicit val directorsFormat: Format[Directors] = Json.format[Directors]
implicit val ac8033Format: Format[AC8033] = new OptionalStringFormat[AC8033](AC8033.apply)
implicit val acq8003Format: Format[ACQ8003] = new OptionalBooleanFormat[ACQ8003](ACQ8003.apply)
implicit val acq8009Format: Format[ACQ8009] = new OptionalBooleanFormat[ACQ8009](ACQ8009.apply)
implicit val acq8991Format: Format[ACQ8991] = new OptionalBooleanFormat[ACQ8991](ACQ8991.apply)
implicit val acq8999Format: Format[ACQ8999] = new OptionalBooleanFormat[ACQ8999](ACQ8999.apply)
implicit val acq8989Format: Format[ACQ8989] = new OptionalBooleanFormat[ACQ8989](ACQ8989.apply)
implicit val acq8990Format: Format[ACQ8990] = new OptionalBooleanFormat[ACQ8990](ACQ8990.apply)
}
|
pncampbell/ct-calculations
|
src/main/scala/uk/gov/hmrc/ct/accounts/frs10x/formats/package.scala
|
Scala
|
apache-2.0
| 2,740 |
package com.github.luzhuomi.regex
// Interface With Java
import com.github.luzhuomi.scalazparsec.NonBacktracking._
import com.github.luzhuomi.regex.pderiv.RE._
import com.github.luzhuomi.regex.pderiv.ExtPattern._
import com.github.luzhuomi.regex.pderiv.IntPattern._
import com.github.luzhuomi.regex.pderiv.Parser._
import com.github.luzhuomi.regex.pderiv.Translate._
import com.github.luzhuomi.regex.PDeriv
import scala.collection.JavaConversions._
class CompiledPattern4J(regex:String)
{
val compiled = PDeriv.compile (regex)
def isSucc:Boolean = compiled match
{
case Some(_) => true
case None => false
}
def exec_(w:String):List[(Int,String)] = compiled match
{
case Some(cp) => PDeriv.exec(cp,w) match
{
case None => Nil
case Some(env) => env
}
case None => Nil
}
def exec(w:String):java.util.List[String] = exec_(w).map(_._2)
}
|
luzhuomi/scala-pderiv
|
src/main/scala/com/github/luzhuomi/regex/CompiledPattern4J.scala
|
Scala
|
apache-2.0
| 878 |
package org.wololo.java2estree
import org.eclipse.jdt.core.dom
import java.io.File
import org.wololo.estree._
import java.nio.file.Path
import java.nio.file.Paths
object importdeclaration {
def makeRelative(path: Path, root: Path, file: Path): String = {
val folder = root.relativize(file.getParent)
val relPath = folder.relativize(path)
if (!relPath.toString().startsWith(".") && !relPath.toString().startsWith("/"))
"./" + relPath.toString
else
relPath.toString
}
def fromImportDeclaration(id: dom.ImportDeclaration, root: Path, file: Path): (String, String) = {
val orgname = id.getName.getFullyQualifiedName
val path = orgname.replace('.', '/')
val name = orgname.split('.').last
//if (path.startsWith("org"))
(name -> makeRelative(Paths.get(path), root, file))
//else
// (name -> path)
}
def createImport(name: String, path: String) = {
new ImportDeclaration(
List(new ImportDefaultSpecifier(new Identifier(name))),
new Literal(s"'${path}.js'", s"'${path}.js'"))
}
def builtinImports(root: Path, file: Path): Map[String, String] = {
Map(
("System" -> "java/lang/System"),
("Comparable" -> "java/lang/Comparable"),
("Cloneable" -> "java/lang/Cloneable"),
("Character" -> "java/lang/Character"),
("Integer" -> "java/lang/Integer"),
("Double" -> "java/lang/Double"),
("StringBuffer" -> "java/lang/StringBuffer"),
("StringBuilder" -> "java/lang/StringBuilder"),
("Exception" -> "java/lang/Exception"),
("RuntimeException" -> "java/lang/RuntimeException"),
("IllegalArgumentException" -> "java/lang/IllegalArgumentException"),
("UnsupportedOperationException" -> "java/lang/UnsupportedOperationException"),
("hasInterface" -> "hasInterface")).transform((name: String, path: String) => makeRelative(Paths.get(path), root, file))
}
def importsFromName(name: String, root: Path, ignore: String = null): Map[String, String] = {
val subpath = name.replace('.', '/')
val subname = name.split('.').last
def isJava(file: File): Boolean = {
val split = file.getName.split('.')
if (split.length != 2) return false
if (split(1) == "java") return true
return false
}
val file = Paths.get(root.toString, "//", subpath)
val files = file.toFile.listFiles
if (files == null) return Map()
val pairs = files.filter({ x => x.getName.split('.')(0) != ignore }).collect {
case x if isJava(x) => {
val name = x.getName.split('.')(0)
val path = subpath + '/' + name
//if (path.startsWith("org"))
(name -> makeRelative(Paths.get(path), root, x.toPath))
//else
// (name -> path)
}
}
Map(pairs: _*)
}
}
|
bjornharrtell/java2estree
|
src/main/scala/org/wololo/java2estree/importdeclaration.scala
|
Scala
|
mit
| 2,789 |
/* Copyright 2009-2016 EPFL, Lausanne */
import leon.lang._
object Termination {
abstract class List
case class Cons(head: Int, tail: List) extends List
case class Nil() extends List
def looping1(list: List) : Int = looping2(list)
def looping2(list: List) : Int = looping1(list)
def calling1(list: List, b: Boolean) : Int = if(b) calling2(list) else looping1(list)
def calling2(list: List) : Int = list match {
case Cons(head, tail) => calling1(tail, true)
case Nil() => 0
}
def ok(list: List) : Int = 0
}
// vim: set ts=4 sw=4 et:
|
regb/leon
|
src/test/resources/regression/termination/looping/Termination_failling1.scala
|
Scala
|
gpl-3.0
| 566 |
/* Copyright 2017-18, Emmanouil Antonios Platanios. All Rights Reserved.
*
* 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 org.platanios.tensorflow.api.io.events
import org.platanios.tensorflow.api.io.DirectoryLoader
import org.platanios.tensorflow.api.utilities.Reservoir
import com.google.protobuf.ByteString
import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory
import org.tensorflow.framework._
import org.tensorflow.util.Event
import org.tensorflow.util.SessionLog.SessionStatus
import java.nio.file.{Files, Path}
import scala.collection.JavaConverters._
import scala.collection.mutable
/** Accumulates event values collected from the provided path.
*
* The [[EventAccumulator]] is intended to provide a convenient interface for loading event data written during a
* TensorFlow run (or otherwise). TensorFlow writes out event ProtoBuf objects, which have a timestamp and step number
* associated with them, and often also contain a [[Summary]]. Summaries can store different kinds of data like a
* scalar value, an image, audio, or a histogram. Each summary also has a tag associated with it, which we use to
* organize logically related data. The [[EventAccumulator]] supports retrieving the event and summary data by their
* tags.
*
* Calling `tags` returns a map from event types to the associated tags for those types, that were found in the loaded
* event files. Then, various functional endpoints (e.g., `scalars(tag)`) allow for the retrieval of all data
* associated with each tag.
*
* The `reload()` method synchronously loads all of the data written so far.
*
* @param path Path to a directory containing TensorFlow events files, or a single TensorFlow
* events file. The accumulator will load events from this path.
* @param sizeGuidance Information on how much data the event accumulator should store in memory. The
* default size guidance tries not to store too much so as to avoid consuming all of
* the client's memory. The `sizeGuidance` should be a map from event types to integers
* representing the number of items to keep in memory, per tag for items of that event
* type. If the size is `0`, then all events are stored. Images, audio, and histograms
* tend to be very large and thus storing all of them is not recommended.
* @param histogramCompressionBps Information on how the event accumulator should compress histogram data for the
* [[CompressedHistogramEventType]] event type.
* @param purgeOrphanedData Boolean value indicating whether to discard any events that were "orphaned" by a
* TensorFlow restart.
*
* @author Emmanouil Antonios Platanios
*/
case class EventAccumulator(
path: Path,
sizeGuidance: Map[EventType, Int] = EventAccumulator.DEFAULT_SIZE_GUIDANCE,
histogramCompressionBps: Seq[Int] = EventAccumulator.DEFAULT_HISTOGRAM_COMPRESSION_BPS,
purgeOrphanedData: Boolean = true) {
private[this] val eventLoader: () => Iterator[Event] = EventAccumulator.eventLoaderFromPath(path)
private[this] object EventLoaderLock
private[this] var _firstEventTimeStamp: Double = -1.0
private[this] var _fileVersion : Float = -1.0f
private[this] var _mostRecentWallTime: Double = -1L
private[this] var _mostRecentStep : Long = -1L
private[this] val _actualSizeGuidance = EventAccumulator.DEFAULT_SIZE_GUIDANCE ++ sizeGuidance
private[this] val _reservoirs: Map[EventType, Reservoir[String, _ <: EventRecord[_]]] = Map(
ScalarEventType -> Reservoir[String, ScalarEventRecord](_actualSizeGuidance(ScalarEventType)),
ImageEventType -> Reservoir[String, ImageEventRecord](_actualSizeGuidance(ImageEventType)),
AudioEventType -> Reservoir[String, AudioEventRecord](_actualSizeGuidance(AudioEventType)),
HistogramEventType -> Reservoir[String, HistogramEventRecord](_actualSizeGuidance(HistogramEventType)),
CompressedHistogramEventType -> Reservoir[String, CompressedHistogramEventRecord](
_actualSizeGuidance(CompressedHistogramEventType), alwaysKeepLast = false)
)
private[this] var _graphDef : ByteString = _
private[this] var _graphFromMetaGraph: Boolean = false
private[this] var _metaGraphDef : ByteString = _
private[this] var _taggedRunMetadata : Map[String, ByteString] = Map.empty[String, ByteString]
private[this] var _summaryMetadata : Map[String, SummaryMetadata] = Map.empty[String, SummaryMetadata]
// Keep a mapping from plugin name to a map from tag to plugin data content obtained from the summary metadata for
// that plugin (this is not the entire summary metadata proto - only the content for that plugin). The summary writer
// only keeps the content on the first event encountered per tag, and so we must store that first instance of content
// for each tag.
private[this] val _pluginTagContent: mutable.Map[String, mutable.Map[String, String]] = mutable.Map.empty
/** Loads all events added since the last call to `reload()` and returns this event accumulator. If `reload()` was
* never called before, then it loads all events in the path. */
def reload(): EventAccumulator = EventLoaderLock synchronized {
eventLoader().foreach(processEvent)
this
}
/** Returns the timestamp (in seconds) of the first event.
*
* If the first event has been loaded (either by this method or by `reload()`, then this method returns immediately.
* Otherwise, it loads the first event and then returns. Note that this means that calling `reload()` will cause this
* method to block until `reload()` has finished. */
def firstEventTimeStamp: Double = {
if (_firstEventTimeStamp >= 0) {
_firstEventTimeStamp
} else {
EventLoaderLock synchronized {
try {
processEvent(eventLoader().next())
_firstEventTimeStamp
} catch {
case t: Throwable => throw new IllegalStateException("No event timestamp could be found.", t)
}
}
}
}
/** Returns all scalar events associated with the provided summary tag. */
def scalars(tag: String): List[ScalarEventRecord] = {
_reservoirs(ScalarEventType).asInstanceOf[Reservoir[String, ScalarEventRecord]].items(tag)
}
/** Returns all image events associated with the provided summary tag. */
def images(tag: String): List[ImageEventRecord] = {
_reservoirs(ImageEventType).asInstanceOf[Reservoir[String, ImageEventRecord]].items(tag)
}
/** Returns all audio events associated with the provided summary tag. */
def audio(tag: String): List[AudioEventRecord] = {
_reservoirs(AudioEventType).asInstanceOf[Reservoir[String, AudioEventRecord]].items(tag)
}
/** Returns all histogram events associated with the provided summary tag. */
def histograms(tag: String): List[HistogramEventRecord] = {
_reservoirs(HistogramEventType).asInstanceOf[Reservoir[String, HistogramEventRecord]].items(tag)
}
/** Returns all compressed histogram events associated with the provided summary tag. */
def compressedHistograms(tag: String): List[CompressedHistogramEventRecord] = {
_reservoirs(CompressedHistogramEventType).asInstanceOf[Reservoir[String, CompressedHistogramEventRecord]].items(tag)
}
/** Returns all tensor events associated with the provided summary tag. */
def tensors(tag: String): List[TensorEventRecord] = {
_reservoirs(TensorEventType).asInstanceOf[Reservoir[String, TensorEventRecord]].items(tag)
}
/** Returns the graph definition, if there is one.
*
* If the graph is stored directly, the method returns it. If no graph is stored directly, but a meta-graph is stored
* containing a graph, the method returns that graph. */
@throws[IllegalStateException]
def graph: GraphDef = {
if (_graphDef != null)
GraphDef.parseFrom(_graphDef)
else
throw new IllegalStateException("There is no graph in this event accumulator.")
}
/** Returns the meta-graph definition, if there is one. */
@throws[IllegalStateException]
def metaGraph: MetaGraphDef = {
if (_metaGraphDef != null)
MetaGraphDef.parseFrom(_metaGraphDef)
else
throw new IllegalStateException("There is no meta-graph in this event accumulator.")
}
/** Returns the run metadata associated with the provided summary tag. */
@throws[IllegalArgumentException]
def runMetadata(tag: String): RunMetadata = {
if (!_taggedRunMetadata.contains(tag))
throw new IllegalArgumentException("There is no run metadata for the provided tag name.")
RunMetadata.parseFrom(_taggedRunMetadata(tag))
}
/** Returns the summary metadata associated with the provided summary tag. */
def summaryMetadata(tag: String): SummaryMetadata = {
_summaryMetadata(tag)
}
/** Returns a map from tags to content specific to the specified plugin. */
def pluginTagToContent(pluginName: String): Option[Map[String, String]] = {
_pluginTagContent.get(pluginName).map(_.toMap)
}
/** Returns a sequence with paths to all the registered assets for the provided plugin name.
*
* If a plugins directory does not exist in the managed directory, then this method returns an empty list. This
* maintains compatibility with old log directories that contain no plugin sub-directories.
*/
def pluginAssets(pluginName: String): Seq[Path] = {
EventPluginUtilities.listPluginAssets(path, pluginName)
}
/** Retrieves a particular plugin asset from the managed directory and returns it as a string. */
def retrievePluginAsset(pluginName: String, assetName: String): String = {
EventPluginUtilities.retrievePluginAsset(path, pluginName, assetName)
}
/** Returns a map from event types to all corresponding tags that have been accumulated. */
def tags: Map[EventType, Seq[String]] = Map(
ScalarEventType -> _reservoirs(ScalarEventType).keys.toSeq,
ImageEventType -> _reservoirs(ImageEventType).keys.toSeq,
AudioEventType -> _reservoirs(AudioEventType).keys.toSeq,
HistogramEventType -> _reservoirs(HistogramEventType).keys.toSeq,
CompressedHistogramEventType -> _reservoirs(CompressedHistogramEventType).keys.toSeq,
TensorEventType -> _reservoirs(TensorEventType).keys.toSeq,
// We use a heuristic here: if a meta-graph is available, but a graph is not, then we assume that the meta-graph
// contains the graph.
// TODO: I don't really get this.
GraphEventType -> Seq((_graphDef != null).toString),
MetaGraphEventType -> Seq((_metaGraphDef != null).toString),
RunMetadataEventType -> _taggedRunMetadata.keys.toSeq
)
/** Processes a newly-loaded event. */
private[this] def processEvent(event: Event): Unit = {
if (_firstEventTimeStamp < 0)
_firstEventTimeStamp = event.getWallTime
if (event.getWhatCase == Event.WhatCase.FILE_VERSION) {
val newFileVersion = {
val tokens = event.getFileVersion.split("brain.Event:")
try {
tokens.last.toFloat
} catch {
// This should never happen according to the definition of the file version field specified in event.proto.
case _: NumberFormatException =>
EventAccumulator.logger.warn(
"Invalid event.proto file_version. Defaulting to use of out-of-order event.step logic " +
"for purging expired events.")
-1f
}
}
if (_fileVersion >= 0 && _fileVersion != newFileVersion) {
// This should not happen.
EventAccumulator.logger.warn(
"Found new file version for event. This will affect purging logic for TensorFlow restarts. " +
s"Old: ${_fileVersion}. New: $newFileVersion.")
}
_fileVersion = newFileVersion
}
maybePurgeOrphanedData(event)
// Process the event.
event.getWhatCase match {
case Event.WhatCase.GRAPH_DEF =>
// GraphDef and MetaGraphDef are handled in a special way: If no GraphDef event is available, but a MetaGraphDef is,
// and it contains a GraphDef, then we use that GraphDef for our graph. If a GraphDef event is available, then we
// always prefer it to the GraphDef inside the MetaGraphDef.
if (_graphDef != null)
EventAccumulator.logger.warn(
"Found more than one graph event per run, or there was a meta-graph containing a graph definition, " +
"as well as one or more graph events. Overwriting the graph with the newest event.")
_graphDef = event.getGraphDef
_graphFromMetaGraph = false
case Event.WhatCase.META_GRAPH_DEF =>
if (_metaGraphDef != null)
EventAccumulator.logger.warn(
"Found more than one meta-graph event per run. Overwriting the meta-graph with the newest event.")
_metaGraphDef = event.getMetaGraphDef
if (_graphDef == null || _graphFromMetaGraph) {
// We may have a GraphDef in the meta-graph. If so, and no GraphDef is directly available, we use this one
// instead.
val metaGraphDef = MetaGraphDef.parseFrom(_metaGraphDef)
if (metaGraphDef.hasGraphDef) {
if (_graphDef != null)
EventAccumulator.logger.warn(
"Found multiple meta-graphs containing graph definitions, but did not find any graph events. " +
"Overwriting the graph with the newest meta-graph version.")
_graphDef = metaGraphDef.getGraphDef.toByteString
_graphFromMetaGraph = true
}
}
case Event.WhatCase.TAGGED_RUN_METADATA =>
val tag = event.getTaggedRunMetadata.getTag
if (_taggedRunMetadata.contains(tag))
EventAccumulator.logger.warn(
s"Found more than one run metadata event with tag '$tag'. Overwriting it with the newest event.")
_taggedRunMetadata += tag -> event.getTaggedRunMetadata.getRunMetadata
case Event.WhatCase.SUMMARY =>
event.getSummary.getValueList.asScala.foreach(value => {
if (value.hasMetadata) {
val tag = value.getTag
// We only store the first instance of the metadata. This check is important: the `FileWriter` does strip
// metadata from all values except the first one per each tag. However, a new `FileWriter` is created every
// time a training job stops and restarts. Hence, we must also ignore non-initial metadata in this logic.
if (!_summaryMetadata.contains(tag)) {
_summaryMetadata += tag -> value.getMetadata
val pluginData = value.getMetadata.getPluginData
if (pluginData.getPluginName != null) {
_pluginTagContent
.getOrElseUpdate(pluginData.getPluginName, mutable.Map.empty[String, String])
.update(tag, pluginData.getContent.toStringUtf8)
} else {
EventAccumulator.logger.warn(s"The summary with tag '$tag' is oddly not associated with any plugin.")
}
}
}
value.getValueCase match {
case Summary.Value.ValueCase.SIMPLE_VALUE =>
val record = ScalarEventRecord(event.getWallTime, event.getStep, value.getSimpleValue)
_reservoirs(ScalarEventType).asInstanceOf[Reservoir[String, ScalarEventRecord]].add(value.getTag, record)
case Summary.Value.ValueCase.IMAGE =>
val image = value.getImage
val imageValue = ImageValue(
image.getEncodedImageString, image.getWidth, image.getHeight, image.getColorspace)
val record = ImageEventRecord(event.getWallTime, event.getStep, imageValue)
_reservoirs(ImageEventType).asInstanceOf[Reservoir[String, ImageEventRecord]].add(value.getTag, record)
case Summary.Value.ValueCase.AUDIO =>
val audio = value.getAudio
val audioValue = AudioValue(
audio.getEncodedAudioString, audio.getContentType, audio.getSampleRate, audio.getNumChannels,
audio.getLengthFrames)
val record = AudioEventRecord(event.getWallTime, event.getStep, audioValue)
_reservoirs(AudioEventType).asInstanceOf[Reservoir[String, AudioEventRecord]].add(value.getTag, record)
case Summary.Value.ValueCase.HISTO =>
val histogram = value.getHisto
val histogramValue = HistogramValue(
histogram.getMin, histogram.getMax, histogram.getNum, histogram.getSum, histogram.getSumSquares,
histogram.getBucketLimitList.asScala.map(_.toDouble), histogram.getBucketList.asScala.map(_.toDouble))
val record = HistogramEventRecord(event.getWallTime, event.getStep, histogramValue)
_reservoirs(HistogramEventType).asInstanceOf[Reservoir[String, HistogramEventRecord]].add(value.getTag, record)
// TODO: [EVENTS] Compress histogram and add to the compressed histograms reservoir.
case Summary.Value.ValueCase.TENSOR =>
val tag = {
if (value.getTag == null) {
// This tensor summary was created using the old method that used plugin assets.
// We must still continue to support it.
value.getNodeName
} else {
value.getTag
}
}
val record = TensorEventRecord(event.getWallTime, event.getStep, value.getTensor)
_reservoirs(TensorEventType).asInstanceOf[Reservoir[String, TensorEventRecord]].add(tag, record)
case _ => EventAccumulator.logger.warn(s"Unrecognized value type (${value.getValueCase}) is ignored.")
}
})
case _ => ()
}
}
//region Purging Methods
/** Purges orphaned data due to a TensorFlow crash, if that is deemed necessary.
*
* When TensorFlow crashes at step `T+O` and restarts at step `T`, any events written after step `T` are now
* "orphaned" and will be at best misleading if they are included. This method attempts to determine if there is
* orphaned data, and purge it if it is found.
*
* @param event Event to use as reference for the purge.
*/
private[this] def maybePurgeOrphanedData(event: Event): Unit = {
if (purgeOrphanedData) {
// Check if the event happened after a crash, and purge expired tags.
if (_fileVersion >= 2) {
// If the file version is recent enough, we can use the session log events to check for restarts.
checkForRestartAndMaybePurge(event)
} else {
// If there is no file version or if the file version is too old, we default to the old logic of checking for
// out of order steps.
checkForOutOfOrderStepAndMaybePurge(event)
}
}
}
/** Checks and discards expired events using `SessionLog.START`.
*
* Checks for a `SessionLog.START` event and purges all previously seen events with larger steps, because they are
* out of date. It is possible that this logic will cause the first few event messages to be discarded because the
* TensorFlow supervisor threading does not guarantee that the `START` message is deterministically written first.
*
* This method is preferred over `checkForOutOfOrderStepAndMaybePurge` which can inadvertently discard events due to
* the TensorFlow supervisor threading behavior.
*
* @param event Event to use as reference for the purge.
*/
private[this] def checkForRestartAndMaybePurge(event: Event): Unit = {
if (event.getSessionLog != null && event.getSessionLog.getStatus == SessionStatus.START)
purge(event, byTags = false)
}
/** Checks for an out-of-order event step and discards any expired events.
*
* Checks if the provided event is out of order relative to the global most recent step. If it is, then the method
* purges ant outdated summaries for tags that the event contains.
*
* @param event Event to use as reference for the purge.
*/
private[this] def checkForOutOfOrderStepAndMaybePurge(event: Event): Unit = {
if (event.getStep < _mostRecentStep && event.getWhatCase == Event.WhatCase.SUMMARY) {
purge(event, byTags = true)
} else {
_mostRecentWallTime = event.getWallTime
_mostRecentStep = event.getStep
}
}
/** Purges all events that have occurred after the provided event step.
*
* If `byTags` is `true`, then the method purges all events that occurred after the provided event step, but only for
* the tags that the event has. Non-sequential event steps suggest that a TensorFlow restart occurred, and we discard
* the out-of-order events in order to obtain a consistent view of the data.
*
* Discarding by tags is the safer method, when we are unsure whether a restart has occurred, given that threading in
* the TensorFlow supervisor can cause events with different tags to arrive with un-synchronized step values.
*
* If `byTags` is `false`, then the method purges all events with step greater than the provided event step. This can
* be used when we are certain that a TensorFlow restart has occurred and these events can be discarded.
*
* @param event Event to use as reference for the purge.
* @param byTags Boolean value indicating whether to purge all out-of-order events or only those that are associated
* with the provided reference event.
*/
private[this] def purge(event: Event, byTags: Boolean): Unit = {
// Keep data that has a step less than the event step in the reservoirs.
val notExpired = (e: EventRecord[_]) => e.step < event.getStep
val expiredPerType = {
if (byTags) {
val tags = event.getSummary.getValueList.asScala.map(_.getTag)
_reservoirs.mapValues(r => tags.map(t => r.filter(notExpired, Some(t))).sum)
} else {
_reservoirs.mapValues(_.filter(notExpired))
}
}
if (expiredPerType.values.sum > 0) {
EventAccumulator.logger.warn(
"Detected out of order event step likely caused by a TensorFlow restart." +
s"Purging expired events between the previous step " +
s"(${_mostRecentStep} - timestamp = ${_mostRecentWallTime}) and the current step " +
s"(${event.getStep} - timestamp = ${event.getWallTime}). " +
s"Removing ${expiredPerType(ScalarEventType)} scalars, ${expiredPerType(ImageEventType)} images, " +
s"${expiredPerType(AudioEventType)} audio, ${expiredPerType(HistogramEventType)} histograms, and " +
s"${expiredPerType(CompressedHistogramEventType)}} compressed histograms.")
}
}
//endregion Purging Methods
}
object EventAccumulator {
private[EventAccumulator] val logger: Logger = Logger(LoggerFactory.getLogger("Event Accumulator"))
/** Default size guidance to use. */
private[events] val DEFAULT_SIZE_GUIDANCE: Map[EventType, Int] = Map(
ScalarEventType -> 10000,
ImageEventType -> 4,
AudioEventType -> 4,
HistogramEventType -> 1,
CompressedHistogramEventType -> 500,
TensorEventType -> 10,
GraphEventType -> 1,
MetaGraphEventType -> 1,
RunMetadataEventType -> 1
)
/** Default histogram compression BPS to use. The Normal CDF for standard deviations:
* (-Inf, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, Inf) naturally gives bands around the median of width 1 std dev, 2 std dev,
* 3 std dev, and then the long tail. */
private[events] val DEFAULT_HISTOGRAM_COMPRESSION_BPS: Seq[Int] = {
Seq(0, 668, 1587, 3085, 5000, 6915, 8413, 9332, 10000)
}
/** Returns an events file reader for the provided path. */
private[EventAccumulator] def eventLoaderFromPath(path: Path): () => Iterator[Event] = {
if (Files.isRegularFile(path) && path.getFileName.toString.contains("tfevents")) {
() => EventFileReader(path).load()
} else {
() => DirectoryLoader(path, EventFileReader(_), p => p.getFileName.toString.contains("tfevents")).load()
}
}
}
|
eaplatanios/tensorflow
|
tensorflow/scala/api/src/main/scala/org/platanios/tensorflow/api/io/events/EventAccumulator.scala
|
Scala
|
apache-2.0
| 24,886 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// scalastyle:off println
package org.apache.spark.examples.mllib
import scala.collection.mutable
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.core.config.Configurator
import scopt.OptionParser
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.mllib.recommendation.{ALS, MatrixFactorizationModel, Rating}
import org.apache.spark.rdd.RDD
/**
* An example app for ALS on MovieLens data (http://grouplens.org/datasets/movielens/).
* Run with
* {{{
* bin/run-example org.apache.spark.examples.mllib.MovieLensALS
* }}}
* A synthetic dataset in MovieLens format can be found at `data/mllib/sample_movielens_data.txt`.
* If you use it as a template to create your own app, please use `spark-submit` to submit your app.
*/
object MovieLensALS {
case class Params(
input: String = null,
kryo: Boolean = false,
numIterations: Int = 20,
lambda: Double = 1.0,
rank: Int = 10,
numUserBlocks: Int = -1,
numProductBlocks: Int = -1,
implicitPrefs: Boolean = false) extends AbstractParams[Params]
def main(args: Array[String]): Unit = {
val defaultParams = Params()
val parser = new OptionParser[Params]("MovieLensALS") {
head("MovieLensALS: an example app for ALS on MovieLens data.")
opt[Int]("rank")
.text(s"rank, default: ${defaultParams.rank}")
.action((x, c) => c.copy(rank = x))
opt[Int]("numIterations")
.text(s"number of iterations, default: ${defaultParams.numIterations}")
.action((x, c) => c.copy(numIterations = x))
opt[Double]("lambda")
.text(s"lambda (smoothing constant), default: ${defaultParams.lambda}")
.action((x, c) => c.copy(lambda = x))
opt[Unit]("kryo")
.text("use Kryo serialization")
.action((_, c) => c.copy(kryo = true))
opt[Int]("numUserBlocks")
.text(s"number of user blocks, default: ${defaultParams.numUserBlocks} (auto)")
.action((x, c) => c.copy(numUserBlocks = x))
opt[Int]("numProductBlocks")
.text(s"number of product blocks, default: ${defaultParams.numProductBlocks} (auto)")
.action((x, c) => c.copy(numProductBlocks = x))
opt[Unit]("implicitPrefs")
.text("use implicit preference")
.action((_, c) => c.copy(implicitPrefs = true))
arg[String]("<input>")
.required()
.text("input paths to a MovieLens dataset of ratings")
.action((x, c) => c.copy(input = x))
note(
"""
|For example, the following command runs this app on a synthetic dataset:
|
| bin/spark-submit --class org.apache.spark.examples.mllib.MovieLensALS \\
| examples/target/scala-*/spark-examples-*.jar \\
| --rank 5 --numIterations 20 --lambda 1.0 --kryo \\
| data/mllib/sample_movielens_data.txt
""".stripMargin)
}
parser.parse(args, defaultParams) match {
case Some(params) => run(params)
case _ => sys.exit(1)
}
}
def run(params: Params): Unit = {
val conf = new SparkConf().setAppName(s"MovieLensALS with $params")
if (params.kryo) {
conf.registerKryoClasses(Array(classOf[mutable.BitSet], classOf[Rating]))
.set("spark.kryoserializer.buffer", "8m")
}
val sc = new SparkContext(conf)
Configurator.setRootLevel(Level.WARN)
val implicitPrefs = params.implicitPrefs
val ratings = sc.textFile(params.input).map { line =>
val fields = line.split("::")
if (implicitPrefs) {
/*
* MovieLens ratings are on a scale of 1-5:
* 5: Must see
* 4: Will enjoy
* 3: It's okay
* 2: Fairly bad
* 1: Awful
* So we should not recommend a movie if the predicted rating is less than 3.
* To map ratings to confidence scores, we use
* 5 -> 2.5, 4 -> 1.5, 3 -> 0.5, 2 -> -0.5, 1 -> -1.5. This mappings means unobserved
* entries are generally between It's okay and Fairly bad.
* The semantics of 0 in this expanded world of non-positive weights
* are "the same as never having interacted at all".
*/
Rating(fields(0).toInt, fields(1).toInt, fields(2).toDouble - 2.5)
} else {
Rating(fields(0).toInt, fields(1).toInt, fields(2).toDouble)
}
}.cache()
val numRatings = ratings.count()
val numUsers = ratings.map(_.user).distinct().count()
val numMovies = ratings.map(_.product).distinct().count()
println(s"Got $numRatings ratings from $numUsers users on $numMovies movies.")
val splits = ratings.randomSplit(Array(0.8, 0.2))
val training = splits(0).cache()
val test = if (params.implicitPrefs) {
/*
* 0 means "don't know" and positive values mean "confident that the prediction should be 1".
* Negative values means "confident that the prediction should be 0".
* We have in this case used some kind of weighted RMSE. The weight is the absolute value of
* the confidence. The error is the difference between prediction and either 1 or 0,
* depending on whether r is positive or negative.
*/
splits(1).map(x => Rating(x.user, x.product, if (x.rating > 0) 1.0 else 0.0))
} else {
splits(1)
}.cache()
val numTraining = training.count()
val numTest = test.count()
println(s"Training: $numTraining, test: $numTest.")
ratings.unpersist()
val model = new ALS()
.setRank(params.rank)
.setIterations(params.numIterations)
.setLambda(params.lambda)
.setImplicitPrefs(params.implicitPrefs)
.setUserBlocks(params.numUserBlocks)
.setProductBlocks(params.numProductBlocks)
.run(training)
val rmse = computeRmse(model, test, params.implicitPrefs)
println(s"Test RMSE = $rmse.")
sc.stop()
}
/** Compute RMSE (Root Mean Squared Error). */
def computeRmse(model: MatrixFactorizationModel, data: RDD[Rating], implicitPrefs: Boolean)
: Double = {
def mapPredictedRating(r: Double): Double = {
if (implicitPrefs) math.max(math.min(r, 1.0), 0.0) else r
}
val predictions: RDD[Rating] = model.predict(data.map(x => (x.user, x.product)))
val predictionsAndRatings = predictions.map{ x =>
((x.user, x.product), mapPredictedRating(x.rating))
}.join(data.map(x => ((x.user, x.product), x.rating))).values
math.sqrt(predictionsAndRatings.map(x => (x._1 - x._2) * (x._1 - x._2)).mean())
}
}
// scalastyle:on println
|
ueshin/apache-spark
|
examples/src/main/scala/org/apache/spark/examples/mllib/MovieLensALS.scala
|
Scala
|
apache-2.0
| 7,324 |
package bad.robot.logging
import java.io.File
import bad.robot.temperature.{FileOps, Files}
object LogFile {
val file: File = Files.path / "temperature-machine.log"
}
|
tobyweston/temperature-machine
|
src/main/scala/bad/robot/logging/LogFile.scala
|
Scala
|
apache-2.0
| 176 |
package debop4s.rediscala.set
import org.springframework.stereotype.Component
@Component
class DefaultRedisZSet extends AbstractRedisZSet {
}
|
debop/debop4s
|
debop4s-rediscala/src/test/scala/debop4s/rediscala/set/DefaultRedisZSet.scala
|
Scala
|
apache-2.0
| 144 |
package core
import spray.json._
import scala.concurrent.duration.FiniteDuration
import spray.can.server.{Stats => SprayStats}
/**
*
*/
object RngJsonProtocol extends DefaultJsonProtocol {
implicit val finiteDurationFormat: RootJsonFormat[FiniteDuration] = new RootJsonFormat[FiniteDuration]{
def write(f: FiniteDuration): JsObject = JsObject("length" -> JsNumber(10))
def read(j: JsValue): FiniteDuration = throw new UnsupportedOperationException
}
implicit val statsFormat = jsonFormat8(SprayStats)
implicit val RngFormatFloat = jsonFormat2(RandomNumbers[Float])
implicit val RngFormatLong = jsonFormat2(RandomNumbers[Long])
}
|
matlockx/rng
|
src/main/scala/core/RngJsonProtocol.scala
|
Scala
|
apache-2.0
| 653 |
package chrome.system.memory.bindings
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName
@JSName("chrome.system.memory")
object Memory extends js.Object {
def getInfo(callback: js.Function1[MemoryInfo, _]): Unit = js.native
}
|
amsayk/scala-js-chrome
|
bindings/src/main/scala/chrome/system/memory/bindings/Memory.scala
|
Scala
|
mit
| 249 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.bwsw.sj.engine.input
import java.io.{BufferedReader, File, InputStreamReader}
import java.util.Date
import java.util.jar.JarFile
import com.bwsw.common.JsonSerializer
import com.bwsw.common.file.utils.FileStorage
import com.bwsw.sj.common.config.BenchmarkConfigNames
import com.bwsw.sj.common.dal.model.instance.{InputTask, InstanceDomain}
import com.bwsw.sj.common.dal.model.provider.ProviderDomain
import com.bwsw.sj.common.dal.model.service.{ServiceDomain, TStreamServiceDomain, ZKServiceDomain}
import com.bwsw.sj.common.dal.model.stream.{StreamDomain, TStreamStreamDomain}
import com.bwsw.sj.common.dal.repository.{ConnectionRepository, GenericMongoRepository}
import com.bwsw.sj.common.si.model.instance.InputInstance
import com.bwsw.sj.common.utils.{ProviderLiterals, _}
import com.bwsw.sj.engine.core.testutils.TestStorageServer
import com.bwsw.sj.engine.input.config.InputEngineConfigNames
import com.bwsw.tstreams.agents.consumer.Consumer
import com.bwsw.tstreams.agents.consumer.Offset.Oldest
import com.bwsw.tstreams.env.{ConfigurationOptions, TStreamsFactory}
import com.typesafe.config.ConfigFactory
import scaldi.Injectable.inject
import scala.collection.mutable
import scala.util.{Failure, Success, Try}
object DataFactory {
import com.bwsw.sj.common.SjModule._
val connectionRepository: ConnectionRepository = inject[ConnectionRepository]
private val config = ConfigFactory.load()
private val zookeeperHosts = config.getString(BenchmarkConfigNames.zkHosts)
private val benchmarkPort = config.getInt(BenchmarkConfigNames.benchmarkPort)
private val testNamespace = "test_namespace_for_input_engine"
private val instanceName = "test-instance-for-input-engine"
private val zookeeperProviderName = "zookeeper-test-provider"
private val tstreamServiceName = "tstream-test-service"
private val zookeeperServiceName = "zookeeper-test-service"
private val tstreamOutputNamePrefix = "tstream-output"
private var instanceOutputs: Array[String] = Array()
private val tasks = mutable.Map[String, InputTask]()
val instancePort = config.getInt(InputEngineConfigNames.entryPort)
tasks.put(s"$instanceName-task0", new InputTask(SjInputModuleBenchmarkConstants.instanceHost, instancePort))
private val partitions = 1
private val serializer = new JsonSerializer()
private val zookeeperProvider = new ProviderDomain(
zookeeperProviderName, zookeeperProviderName, zookeeperHosts.split(","), ProviderLiterals.zookeeperType, new Date())
private val tstrqService = new TStreamServiceDomain(tstreamServiceName, tstreamServiceName, zookeeperProvider,
TestStorageServer.defaultPrefix, TestStorageServer.defaultToken, creationDate = new Date())
private val tstreamFactory = new TStreamsFactory()
setTStreamFactoryProperties()
val storageClient = tstreamFactory.getStorageClient()
val outputCount = 2
private def setTStreamFactoryProperties() = {
setAuthOptions(tstrqService)
setCoordinationOptions(tstrqService)
}
private def setAuthOptions(tStreamService: TStreamServiceDomain) = {
tstreamFactory.setProperty(ConfigurationOptions.Common.authenticationKey, tStreamService.token)
}
private def setCoordinationOptions(tStreamService: TStreamServiceDomain) = {
tstreamFactory.setProperty(ConfigurationOptions.Coordination.endpoints, tStreamService.provider.getConcatenatedHosts())
tstreamFactory.setProperty(ConfigurationOptions.Coordination.path, tStreamService.prefix)
}
def createProviders(providerService: GenericMongoRepository[ProviderDomain]) = {
providerService.save(zookeeperProvider)
}
def deleteProviders(providerService: GenericMongoRepository[ProviderDomain]) = {
providerService.delete(zookeeperProviderName)
}
def createServices(serviceManager: GenericMongoRepository[ServiceDomain], providerService: GenericMongoRepository[ProviderDomain]) = {
val zkService = new ZKServiceDomain(zookeeperServiceName, zookeeperServiceName, zookeeperProvider,
testNamespace, creationDate = new Date())
serviceManager.save(zkService)
serviceManager.save(tstrqService)
}
def deleteServices(serviceManager: GenericMongoRepository[ServiceDomain]) = {
serviceManager.delete(zookeeperServiceName)
serviceManager.delete(tstreamServiceName)
}
def createStreams(sjStreamService: GenericMongoRepository[StreamDomain], serviceManager: GenericMongoRepository[ServiceDomain], outputCount: Int) = {
(1 to outputCount).foreach(x => {
createOutputTStream(sjStreamService, serviceManager, partitions, x.toString)
instanceOutputs = instanceOutputs :+ (tstreamOutputNamePrefix + x)
})
}
def deleteStreams(streamService: GenericMongoRepository[StreamDomain], outputCount: Int) = {
(1 to outputCount).foreach(x => deleteOutputTStream(streamService, x.toString))
}
private def createOutputTStream(sjStreamService: GenericMongoRepository[StreamDomain], serviceManager: GenericMongoRepository[ServiceDomain], partitions: Int, suffix: String) = {
val s2 = new TStreamStreamDomain(
tstreamOutputNamePrefix + suffix,
tstrqService,
partitions,
tstreamOutputNamePrefix + suffix,
false,
Array("output", "some tags"),
creationDate = new Date()
)
sjStreamService.save(s2)
storageClient.createStream(
tstreamOutputNamePrefix + suffix,
partitions,
1000 * 60,
"description of test output tstream")
}
private def deleteOutputTStream(streamService: GenericMongoRepository[StreamDomain], suffix: String) = {
streamService.delete(tstreamOutputNamePrefix + suffix)
storageClient.deleteStream(tstreamOutputNamePrefix + suffix)
}
def createInstance(serviceManager: GenericMongoRepository[ServiceDomain],
instanceService: GenericMongoRepository[InstanceDomain],
checkpointInterval: Int
) = {
val instance = new InputInstance(
name = instanceName,
moduleType = EngineLiterals.inputStreamingType,
moduleName = "input-streaming-stub",
moduleVersion = "1.0",
engine = "com.bwsw.input.streaming.engine-1.0",
coordinationService = zookeeperServiceName,
checkpointMode = EngineLiterals.everyNthMode,
_status = EngineLiterals.started,
description = "some description of test instance",
outputs = instanceOutputs,
checkpointInterval = checkpointInterval,
duplicateCheck = true,
lookupHistory = 100,
queueMaxSize = 500,
defaultEvictionPolicy = EngineLiterals.lruDefaultEvictionPolicy,
evictionPolicy = "expanded-time",
tasks = tasks,
options =
s"""{"totalInputElements":${SjInputModuleBenchmarkConstants.totalInputElements},
|"benchmarkPort":$benchmarkPort,
|"verbose":false}""".stripMargin,
creationDate = new Date().toString)
instanceService.save(instance.to)
}
def deleteInstance(instanceService: GenericMongoRepository[InstanceDomain]) = {
instanceService.delete(instanceName)
}
def loadModule(file: File, storage: FileStorage) = {
val builder = new StringBuilder
val jar = new JarFile(file)
val enu = jar.entries()
while (enu.hasMoreElements) {
val entry = enu.nextElement
if (entry.getName.equals("specification.json")) {
val reader = new BufferedReader(new InputStreamReader(jar.getInputStream(entry), "UTF-8"))
val result = Try {
var line = reader.readLine
while (Option(line).isDefined) {
builder.append(line + "\\n")
line = reader.readLine
}
}
reader.close()
result match {
case Success(_) =>
case Failure(e) => throw e
}
}
}
val specification = serializer.deserialize[Map[String, Any]](builder.toString())
storage.put(file, file.getName, specification, "module")
}
def deleteModule(storage: FileStorage, filename: String) = {
storage.delete(filename)
}
def createOutputConsumer(streamService: GenericMongoRepository[StreamDomain], suffix: String) = {
createConsumer(tstreamOutputNamePrefix + suffix, streamService)
}
private def createConsumer(streamName: String, streamService: GenericMongoRepository[StreamDomain]): Consumer = {
val stream = streamService.get(streamName).get.asInstanceOf[TStreamStreamDomain]
setStreamOptions(stream)
tstreamFactory.getConsumer(
streamName,
(0 until stream.partitions).toSet,
Oldest)
}
protected def setStreamOptions(stream: TStreamStreamDomain) = {
tstreamFactory.setProperty(ConfigurationOptions.Stream.name, stream.name)
tstreamFactory.setProperty(ConfigurationOptions.Stream.partitionsCount, stream.partitions)
tstreamFactory.setProperty(ConfigurationOptions.Stream.description, stream.description)
}
}
|
bwsw/sj-platform
|
core/sj-input-streaming-engine/src/test/scala/com/bwsw/sj/engine/input/DataFactory.scala
|
Scala
|
apache-2.0
| 9,670 |
package edu.nus.systemtesting.hipsleek
import edu.nus.systemtesting.Parser.filterLinesMatchingRegex
import edu.nus.systemtesting.ProgramFlags.{ isFlag, flagsOfProgram }
import edu.nus.systemtesting.ExecutionOutput
import edu.nus.systemtesting.Result
import edu.nus.systemtesting.PreparedSystem
import edu.nus.systemtesting.Testable
import edu.nus.systemtesting.TestCaseConfiguration
import edu.nus.systemtesting.TestCase
import edu.nus.systemtesting.TestCaseResult
import java.nio.file.Path
import java.nio.file.Paths
import edu.nus.systemtesting.ExpectsOutput
object HipTestCase {
implicit def constructTestCase(ps: PreparedSystem, tc: Testable with ExpectsOutput, conf: TestCaseConfiguration): HipTestCase =
new HipTestCase(ps.binDir,
tc.commandName,
ps.corpusDir,
tc.fileName,
tc.arguments,
tc.expectedOutput,
conf.timeout)
}
class HipTestCase(binDir: Path = Paths.get(""),
cmd: Path = Paths.get(""),
corpDir: Path = Paths.get(""),
fn: Path = Paths.get(""),
args: String = "",
val expectedOutput: String = "",
timeout: Int = 300,
regex: String = "Procedure.*FAIL.*|Procedure.*SUCCESS.*")
extends TestCase(binDir, cmd, corpDir, fn, args, timeout) with ExpectsOutput {
def buildExpectedOutputMap(results: String): Map[String, String] = {
// expected output is a string like "proc: SUCCESS, proc: FAIL"
results.split(",").map(result =>
(result.substring(0, result.indexOf(":")).trim,
result.substring(result.indexOf(":") + 1).trim)).toMap
}
// Return (methodname, result)
// Could be static, if we had the regex
def resultFromOutputLine(outputLine: String): (String,String) = {
// e.g. outputLine should look something like:
// Procedure set_next$node~node SUCCESS.
var methodName = outputLine.split(" ")(1)
methodName = methodName.substring(0, methodName.indexOf("$"))
val actual: String =
if (outputLine.contains("FAIL"))
"FAIL"
else
"SUCCESS"
(methodName, actual)
}
override def checkResults(output: ExecutionOutput): Either[List[String], Iterable[Result]] = {
val expectedOutputMap = buildExpectedOutputMap(expectedOutput)
// `parse` is responsible for populating `results` with
// lines which match `builder.regex`.
val results = filterLinesMatchingRegex(output.output, regex)
if (results.isEmpty) {
val testFlags = arguments.split(" ").filter(isFlag)
val SleekFlags = flagsOfProgram(absCmdPath)
val invalidFlags = testFlags.filterNot(SleekFlags.contains)
if (!invalidFlags.isEmpty) {
val flagsStr = invalidFlags.map(f => s"Invalid flag $f").mkString("\n")
return Left(List("Binary failed to execute. Please investigate", flagsStr))
} else {
// Could try searching the output for errors?
return Left(List("Binary failed to execute. Please investigate",
"Output was:") ++
output.stdoutLines ++
output.stderrLines)
}
}
// TODO: check that all the results methods contain the method name.
// If not, then the test is 'under specified' relative to the actual file, and we should note that.
val resultUnits = results.flatMap(outputLine => {
val (methodName, actual) = resultFromOutputLine(outputLine)
expectedOutputMap.get(methodName) match {
case Some(expected) => {
Some(Result(methodName, expected, actual))
}
// If the method name from the actual output is not in the expectedOutputMap,
// it means the expectedOutputMap was under-specified.
// Easier to ignore, for now.
case None => None
}
})
return Right(resultUnits)
}
}
|
rgoulter/system-testing
|
src/main/scala/edu/nus/systemtesting/hipsleek/HipTestCase.scala
|
Scala
|
mit
| 3,945 |
/**
* Copyright (c) 2014-2016 Snowplow Analytics Ltd.
* All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache
* License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied.
*
* See the Apache License Version 2.0 for the specific language
* governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.storage.kinesis.elasticsearch
// Scalaz
import scalaz._
import Scalaz._
// Common Enrich
import com.snowplowanalytics.snowplow.enrich.common.outputs.BadRow
object FailureUtils {
/**
* Due to serialization issues we use List instead of NonEmptyList
* so we need this method to convert the errors back to a NonEmptyList
*
* @param line
* @param errors
* @return Compact bad row JSON string
*/
def getBadRow(line: String, errors: List[String]): String =
BadRow(line, NonEmptyList(errors.head, errors.tail: _*)).toCompactJson
}
|
haensel-ams/snowplow
|
4-storage/kinesis-elasticsearch-sink/src/main/scala/com.snowplowanalytics.snowplow.storage.kinesis/elasticsearch/FailureUtils.scala
|
Scala
|
apache-2.0
| 1,321 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.hive
import org.apache.spark.sql.{DataFrame, QueryTest}
import org.apache.spark.sql.functions._
import org.apache.spark.sql.hive.test.TestHive
import org.apache.spark.sql.hive.test.TestHive._
import org.apache.spark.sql.hive.test.TestHive.implicits._
import org.scalatest.BeforeAndAfterAll
// TODO ideally we should put the test suite into the package `sql`, as
//TODO理想情况下,我们应该将测试套件放入“sql”包中
// `hive` package is optional in compiling, however, `SQLContext.sql` doesn't
// support the `cube` or `rollup` yet. 不支持“cube”或“rollup”
//Hive DataFrame分析套件
class HiveDataFrameAnalyticsSuite extends QueryTest with BeforeAndAfterAll {
private var testData: DataFrame = _
override def beforeAll() {
testData = Seq((1, 2), (2, 4)).toDF("a", "b")
TestHive.registerDataFrameAsTable(testData, "mytable")
}
override def afterAll(): Unit = {
TestHive.dropTempTable("mytable")
}
/**
* group by 后带 rollup 子句的功能可以理解为:先按一定的规则产生多种分组,然后按各种分组统计数据
* (至于统计出的数据是求和还是最大值还是平均值等这就取决于SELECT后的聚合函数)
* group by 后带 rollup 子句所返回的结果集,可以理解为各个分组所产生的结果集的并集且没有去掉重复数据
*/
test("rollup") {
checkAnswer(
//DataFrame.rollup
testData.rollup($"a" + $"b", $"b").agg(sum($"a" - $"b")),
sql("select a + b, b, sum(a - b) from mytable group by a + b, b with rollup").collect()
)
checkAnswer(
testData.rollup("a", "b").agg(sum("b")),
sql("select a, b, sum(b) from mytable group by a, b with rollup").collect()
)
}
/**
* CUBE 运算符在 SELECT 语句的 GROUP BY 子句中指定。该语句的选择列表包含维度列和聚合函数表达式。
* GROUP BY 指定了维度列和关键字 WITH CUBE,结果集包含维度列中各值的所有可能组合,以及与这些维度值组合相匹配的基础行中的聚合值。
*/
test("cube") {
checkAnswer(
testData.cube($"a" + $"b", $"b").agg(sum($"a" - $"b")),
sql("select a + b, b, sum(a - b) from mytable group by a + b, b with cube").collect()
)
checkAnswer(
testData.cube("a", "b").agg(sum("b")),
sql("select a, b, sum(b) from mytable group by a, b with cube").collect()
)
}
}
|
tophua/spark1.52
|
sql/hive/src/test/scala/org/apache/spark/sql/hive/HiveDataFrameAnalyticsSuite.scala
|
Scala
|
apache-2.0
| 3,252 |
package org.jetbrains.plugins.scala.codeInspection.methodSignature
import com.intellij.codeInspection._
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.codeInspection.methodSignature.quickfix.AddEmptyParentheses
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScFunction
/**
* Pavel Fatin
*/
class UnitMethodIsParameterlessInspection extends AbstractMethodSignatureInspection(
"ScalaUnitMethodIsParameterless", "Method with Unit result type is parameterless") {
override def actionFor(implicit holder: ProblemsHolder): PartialFunction[PsiElement, Unit] = {
case f: ScFunction if f.isParameterless && f.hasUnitResultType && f.superMethods.isEmpty =>
holder.registerProblem(f.nameId, getDisplayName, new AddEmptyParentheses(f))
}
}
|
loskutov/intellij-scala
|
src/org/jetbrains/plugins/scala/codeInspection/methodSignature/UnitMethodIsParameterlessInspection.scala
|
Scala
|
apache-2.0
| 784 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.execution
import scala.io.Source
import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, OneRowRelation}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSQLContext
case class QueryExecutionTestRecord(
c0: Int, c1: Int, c2: Int, c3: Int, c4: Int,
c5: Int, c6: Int, c7: Int, c8: Int, c9: Int,
c10: Int, c11: Int, c12: Int, c13: Int, c14: Int,
c15: Int, c16: Int, c17: Int, c18: Int, c19: Int,
c20: Int, c21: Int, c22: Int, c23: Int, c24: Int,
c25: Int, c26: Int)
class QueryExecutionSuite extends SharedSQLContext {
import testImplicits._
def checkDumpedPlans(path: String, expected: Int): Unit = {
assert(Source.fromFile(path).getLines.toList
.takeWhile(_ != "== Whole Stage Codegen ==") == List(
"== Parsed Logical Plan ==",
s"Range (0, $expected, step=1, splits=Some(2))",
"",
"== Analyzed Logical Plan ==",
"id: bigint",
s"Range (0, $expected, step=1, splits=Some(2))",
"",
"== Optimized Logical Plan ==",
s"Range (0, $expected, step=1, splits=Some(2))",
"",
"== Physical Plan ==",
s"*(1) Range (0, $expected, step=1, splits=2)",
""))
}
test("dumping query execution info to a file") {
withTempDir { dir =>
val path = dir.getCanonicalPath + "/plans.txt"
val df = spark.range(0, 10)
df.queryExecution.debug.toFile(path)
checkDumpedPlans(path, expected = 10)
}
}
test("dumping query execution info to an existing file") {
withTempDir { dir =>
val path = dir.getCanonicalPath + "/plans.txt"
val df = spark.range(0, 10)
df.queryExecution.debug.toFile(path)
val df2 = spark.range(0, 1)
df2.queryExecution.debug.toFile(path)
checkDumpedPlans(path, expected = 1)
}
}
test("dumping query execution info to non-existing folder") {
withTempDir { dir =>
val path = dir.getCanonicalPath + "/newfolder/plans.txt"
val df = spark.range(0, 100)
df.queryExecution.debug.toFile(path)
checkDumpedPlans(path, expected = 100)
}
}
test("dumping query execution info by invalid path") {
val path = "1234567890://plans.txt"
val exception = intercept[IllegalArgumentException] {
spark.range(0, 100).queryExecution.debug.toFile(path)
}
assert(exception.getMessage.contains("Illegal character in scheme name"))
}
test("limit number of fields by sql config") {
def relationPlans: String = {
val ds = spark.createDataset(Seq(QueryExecutionTestRecord(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26)))
ds.queryExecution.toString
}
withSQLConf(SQLConf.MAX_TO_STRING_FIELDS.key -> "26") {
assert(relationPlans.contains("more fields"))
}
withSQLConf(SQLConf.MAX_TO_STRING_FIELDS.key -> "27") {
assert(!relationPlans.contains("more fields"))
}
}
test("toString() exception/error handling") {
spark.experimental.extraStrategies = Seq(
new SparkStrategy {
override def apply(plan: LogicalPlan): Seq[SparkPlan] = Nil
})
def qe: QueryExecution = new QueryExecution(spark, OneRowRelation())
// Nothing!
assert(qe.toString.contains("OneRowRelation"))
// Throw an AnalysisException - this should be captured.
spark.experimental.extraStrategies = Seq(
new SparkStrategy {
override def apply(plan: LogicalPlan): Seq[SparkPlan] =
throw new AnalysisException("exception")
})
assert(qe.toString.contains("org.apache.spark.sql.AnalysisException"))
// Throw an Error - this should not be captured.
spark.experimental.extraStrategies = Seq(
new SparkStrategy {
override def apply(plan: LogicalPlan): Seq[SparkPlan] =
throw new Error("error")
})
val error = intercept[Error](qe.toString)
assert(error.getMessage.contains("error"))
}
}
|
mdespriee/spark
|
sql/core/src/test/scala/org/apache/spark/sql/execution/QueryExecutionSuite.scala
|
Scala
|
apache-2.0
| 4,841 |
package info.devartem.funnycommands.commands
import info.devartem.funnycommands.exception.InvalidCommandException
import org.scalatest.{FunSpec, Matchers, TryValues}
class Command$Test extends FunSpec with Matchers with TryValues {
describe("Command object") {
it("should return task command by name") {
Command.commandByName("task").success.value shouldBe a[Task]
}
it("should return link command by name") {
Command.commandByName("link").success.value shouldBe a[Link]
}
it("should return process command by name") {
Command.commandByName("process").success.value shouldBe a[Process]
}
it("should return failed try in command is not found") {
Command.commandByName("dummyCommand").failure.exception shouldBe a[InvalidCommandException]
}
}
}
|
dev-tim/funny-commands
|
src/test/scala/info/devartem/funnycommands/commands/Command$Test.scala
|
Scala
|
mit
| 809 |
package com.socrata.datacoordinator.common.soql.csvreps
import com.socrata.datacoordinator.truth.csv.CsvColumnRep
import com.socrata.soql.types._
object PhoneRep extends CsvColumnRep[SoQLType, SoQLValue] {
val size = 2
val representedType = SoQLPhone
def decode(row: IndexedSeq[String], indices: IndexedSeq[Int]): Option[SoQLValue] = {
assert(indices.size == size)
def optionalVal(s: String) = if (s.isEmpty) None else Some(s)
val phoneNumber = optionalVal(row(indices(0)))
val phoneType = optionalVal(row(indices(1)))
if (phoneNumber.isDefined || phoneType.isDefined) {
Some(SoQLPhone(phoneNumber, phoneType))
} else {
Some(SoQLNull)
}
}
}
|
socrata-platform/data-coordinator
|
coordinatorlib/src/main/scala/com/socrata/datacoordinator/common/soql/csvreps/PhoneRep.scala
|
Scala
|
apache-2.0
| 695 |
object Problem6 {
def sumOfTheSquares (n: Int) = (1 to n).map(x => x*x).sum
def squareOfTheSum (n: Int) = {
val theSum = (1 to n).sum
theSum*theSum
}
def difference(n: Int): Int = {
squareOfTheSum(n) - sumOfTheSquares(n)
}
difference (100)
}
|
FredericJacobs/Project_Euler-Scala
|
ProjectEuler/src/Problem6.scala
|
Scala
|
gpl-2.0
| 266 |
/**
* Copyright 2015 Thomson Reuters
*
* 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 cmwell.fts
import java.net.InetAddress
import java.util
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.{Executors, TimeUnit, TimeoutException}
import akka.NotUsed
import akka.stream.scaladsl.Source
import cmwell.common.formats.JsonSerializer
import cmwell.domain._
import cmwell.util.jmx._
import cmwell.common.exception._
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.{LazyLogging, Logger}
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse
import org.elasticsearch.action.bulk.{BulkItemResponse, BulkResponse}
import org.elasticsearch.action.delete.DeleteResponse
import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse
import org.elasticsearch.action.get.GetResponse
import org.elasticsearch.action.index.{IndexRequest, IndexResponse}
import org.elasticsearch.action.search.{SearchRequestBuilder, SearchResponse, SearchType}
import org.elasticsearch.action.update.UpdateRequest
import org.elasticsearch.action.{ActionListener, ActionRequest, WriteConsistencyLevel}
import org.elasticsearch.client.Client
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.netty.util.{HashedWheelTimer, Timeout, TimerTask}
import org.elasticsearch.common.settings.ImmutableSettings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.common.unit.TimeValue
import org.elasticsearch.index.VersionType
import org.elasticsearch.index.query.{BoolFilterBuilder, BoolQueryBuilder, QueryBuilder, QueryBuilders}
import org.elasticsearch.index.query.FilterBuilders._
import org.elasticsearch.index.query.QueryBuilders._
import org.elasticsearch.node.Node
import org.elasticsearch.node.NodeBuilder._
import org.elasticsearch.search.SearchHit
import org.elasticsearch.search.aggregations._
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram
import org.elasticsearch.search.aggregations.bucket.significant.InternalSignificantTerms
import org.elasticsearch.search.aggregations.bucket.terms.InternalTerms
import org.elasticsearch.search.aggregations.metrics.cardinality.InternalCardinality
import org.elasticsearch.search.aggregations.metrics.stats.InternalStats
import org.elasticsearch.search.sort.SortBuilders._
import org.elasticsearch.search.sort.SortOrder
import org.joda.time.DateTime
import org.slf4j.LoggerFactory
import scala.collection.JavaConverters._
import scala.compat.Platform._
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util._
import scala.language.implicitConversions
/**
* User: Israel
* Date: 11/5/12
* Time: 10:19 AM
*/
object FTSServiceES {
def getOne(classPathConfigFile: String, waitForGreen: Boolean = true) =
new FTSServiceES(classPathConfigFile, waitForGreen)
}
object Settings {
val config = ConfigFactory.load()
val isTransportClient = config.getBoolean("ftsService.isTransportClient")
val transportAddress = config.getString("ftsService.transportAddress")
val transportPort = config.getInt("ftsService.transportPort")
val defPartition = config.getString("ftsService.defaultPartition")
val clusterName = config.getString("ftsService.clusterName")
val scrollTTL = config.getLong("ftsService.scrollTTL")
val scrollLength = config.getInt("ftsService.scrollLength")
val dataCenter = config.getString("dataCenter.id")
}
class FTSServiceES private(classPathConfigFile: String, waitForGreen: Boolean)
extends FTSServiceOps with FTSServiceESMBean {
import cmwell.fts.Settings._
override val defaultPartition = defPartition
override val defaultScrollTTL = scrollTTL
var client:Client = _
var node:Node = null
@volatile var totalRequestedToIndex:Long = 0
val totalIndexed = new AtomicLong(0)
val totalFailedToIndex = new AtomicLong(0)
jmxRegister(this, "cmwell.indexer:type=FTSService")
if(isTransportClient) {
val esSettings = ImmutableSettings.settingsBuilder.put("cluster.name", clusterName).build
// if(transportAddress=="localhost") InetAddress.getLocalHost.getHostName else
val actualTransportAddress = transportAddress
client = new TransportClient(esSettings).addTransportAddress(new InetSocketTransportAddress(actualTransportAddress, transportPort))
loger.info(s"starting es transport client [/$actualTransportAddress:$transportPort]")
} else {
val esSettings = ImmutableSettings.settingsBuilder().loadFromClasspath(classPathConfigFile)
node = nodeBuilder().settings(esSettings).node()
client = node.client()
}
val localHostName = InetAddress.getLocalHost.getHostName
loger.info(s"localhostname: $localHostName")
val nodesInfo = client.admin().cluster().prepareNodesInfo().execute().actionGet()
loger.info (s"nodesInfo: $nodesInfo")
lazy val localNodeId = client.admin().cluster().prepareNodesInfo().execute().actionGet().getNodesMap.asScala.filter{case (id, node) =>
node.getHostname.equals(localHostName) && node.getNode.isDataNode
}.map(_._1).head
val clients:Map[String, Client] = isTransportClient match {
case true =>
nodesInfo.getNodes.filterNot( n => ! n.getNode.dataNode()).map{ node =>
val nodeId = node.getNode.getId
val nodeHostName = node.getNode.getHostName
val clint = nodeHostName.equalsIgnoreCase(localHostName) match {
case true => client
case false =>
val transportAddress = node.getNode.getAddress
val settings = ImmutableSettings.settingsBuilder.
put("cluster.name", node.getSettings.get("cluster.name"))
.put("transport.netty.worker_count", 3)
.put("transport.connections_per_node.recovery", 1)
.put("transport.connections_per_node.bulk", 1)
.put("transport.connections_per_node.reg", 2)
.put("transport.connections_per_node.state", 1)
.put("transport.connections_per_node.ping", 1).build
new TransportClient(settings).addTransportAddress(transportAddress)
}
(nodeId, clint)
}.toMap
case false =>
Map(localNodeId -> client)
}
if(waitForGreen) {
loger info "waiting for ES green status"
// wait for green status
client.admin().cluster()
.prepareHealth()
.setWaitForGreenStatus()
.setTimeout(TimeValue.timeValueMinutes(5))
.execute()
.actionGet()
loger info "got green light from ES"
} else {
loger info "waiting for ES yellow status"
// wait for yellow status
client.admin().cluster()
.prepareHealth()
.setWaitForYellowStatus()
.setTimeout(TimeValue.timeValueMinutes(5))
.execute()
.actionGet()
loger info "got yellow light from ES"
}
def getTotalRequestedToIndex(): Long = totalRequestedToIndex
def getTotalIndexed(): Long = totalIndexed.get()
def getTotalFailedToIndex(): Long = totalFailedToIndex.get()
def close() {
if (client != null)
client.close()
if (node != null && !node.isClosed)
node.close()
jmxUnRegister("cmwell.indexer:type=FTSService")
}
/**
* Add given Infoton to Current index. If previous version of this Infoton passed, it will
* be added to History index
*
* @param infoton
* @param previousInfoton previous version of this infoton
* @param partition logical name of partition. Used for targeting a specific index
*/
def index(infoton: Infoton, previousInfoton: Option[Infoton] = None, partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[Unit] = {
loger debug ("indexing current: " + infoton.uuid)
totalRequestedToIndex += 1
val infotonToIndex = new String(JsonSerializer.encodeInfoton(infoton, toEs = true), "utf-8")
val currentFuture = injectFuture[IndexResponse](client.prepareIndex(partition + "_current", "infoclone", infoton.uuid).setSource(JsonSerializer.encodeInfoton(infoton, toEs = true)).setConsistencyLevel(WriteConsistencyLevel.ALL).execute(_)).map{_ => }
currentFuture.andThen {
case Failure(t) => loger debug ("failed to index infoton uuid: " + infoton.uuid + "\\n" + t.getLocalizedMessage + "\\n" + t.getStackTrace().mkString("", EOL, EOL))
case Success(v) => loger debug ("successfully indexed infoton uuid: " + infoton.uuid); totalIndexed.addAndGet(1)
}
if(previousInfoton.isDefined) {
totalRequestedToIndex += 1
val previousWriteFuture = injectFuture[IndexResponse](client.prepareIndex(partition + "_history", "infoclone", previousInfoton.get.uuid).setSource(JsonSerializer.encodeInfoton(previousInfoton.get, toEs = true)).setConsistencyLevel(WriteConsistencyLevel.ALL).execute(_)).map{_ => }
val previousDeleteFuture = injectFuture[DeleteResponse](client.prepareDelete(partition + "_current", "infoclone", previousInfoton.get.uuid).setConsistencyLevel(WriteConsistencyLevel.ALL).execute(_)).map{ _.isFound }.andThen{case Failure(t) => loger debug ("failed to delete infoton uuid: " + infoton.uuid + "\\n" + t.getLocalizedMessage + "\\n" + t.getStackTrace().mkString("", EOL, EOL)); case Success(v) => loger debug ("successfully deleted infoton uuid: " + infoton.uuid)}.map{ _ => }
currentFuture.flatMap( _ => previousWriteFuture).flatMap(_ => previousDeleteFuture)
} else {
currentFuture.map{ _ => }
}
}
val scheduler = Executors.newSingleThreadScheduledExecutor()
def extractSource[T : EsSourceExtractor](uuid: String, index: String)(implicit executionContext: ExecutionContext) = {
injectFuture[GetResponse](client.prepareGet(index, "infoclone", uuid).execute(_)).map{hit =>
implicitly[EsSourceExtractor[T]].extract(hit) -> hit.getVersion
}
}
def executeBulkActionRequests(actionRequests: Iterable[ActionRequest[_ <: ActionRequest[_ <: AnyRef]]])
(implicit executionContext: ExecutionContext, logger:Logger = loger) = {
val requestedToIndexSize = actionRequests.size
totalRequestedToIndex += actionRequests.size
val bulkRequest = client.prepareBulk()
bulkRequest.request().add(actionRequests.asJava)
val response = injectFuture[BulkResponse](bulkRequest.execute(_))
response.onComplete{
case Success(response) if !response.hasFailures =>
logger debug (s"successfully indexed ${requestedToIndexSize} infotons")
totalIndexed.addAndGet(actionRequests.size)
response.getItems.foreach{r =>
if( !r.getOpType.equalsIgnoreCase("delete") && r.getVersion > 1 ) {
logger error (s"just wrote duplicate infoton: ${r.getId}")
}
}
case Success(response) =>
try {
val failed = response.getItems.filter(_.isFailed).map(_.getId)
// here we get if got response that has failures
logger error (s"failed to index ${failed.size} out of $requestedToIndexSize infotons: ${failed.mkString(",")}")
totalFailedToIndex.addAndGet(failed.size)
totalIndexed.addAndGet(requestedToIndexSize - failed.size)
response.getItems.foreach {
r =>
if (!r.getOpType.equalsIgnoreCase("delete") && r.getVersion > 1) {
logger debug (s"just wrote duplicate infoton: ${r.getId}")
}
if (r.isFailed) {
logger debug (s"failed infoton: ${r.getId}")
}
}
}catch {
case t:Throwable =>
logger error (s"exception while handling ES response errors:\\n ${getStackTrace(t)}")
}
case Failure(t) =>
logger error (s"exception during bulk indexing\\n${getStackTrace(t)}")
totalFailedToIndex.addAndGet(requestedToIndexSize)
}
response
}
def executeBulkIndexRequests(indexRequests:Iterable[ESIndexRequest], numOfRetries: Int = 15,
waitBetweenRetries:Long = 3000)
(implicit executionContext:ExecutionContext, logger:Logger = loger) : Future[SuccessfulBulkIndexResult] = ???
def getMappings(withHistory: Boolean = false, partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[Set[String]] = {
import org.elasticsearch.cluster.ClusterState
implicit class AsLinkedHashMap[K](lhm: Option[AnyRef]) {
def extract(k: K) = lhm match {
case Some(m) => Option(m.asInstanceOf[java.util.LinkedHashMap[K,AnyRef]].get(k))
case None => None
}
def extractKeys: Set[K] = lhm.map(_.asInstanceOf[java.util.LinkedHashMap[K,Any]].keySet().asScala.toSet).getOrElse(Set.empty[K])
def extractOneValueBy[V](selector: K): Map[K,V] = lhm.map(_.asInstanceOf[java.util.LinkedHashMap[K,Any]].asScala.map{ case (k,vs) => k -> vs.asInstanceOf[java.util.LinkedHashMap[K,V]].get(selector) }.toMap).getOrElse(Map[K,V]())
}
val req = client.admin().cluster().prepareState()
val f = injectFuture[ClusterStateResponse](req.execute)
val csf: Future[ClusterState] = f.map(_.getState)
csf.map(_.getMetaData.iterator.asScala.filter(_.index().startsWith("cm")).map{imd =>
val nested = Some(imd.mapping("infoclone").getSourceAsMap.get("properties"))
val flds = nested.extract("fields").extract("properties")
flds.extractOneValueBy[String]("type").map { case (k,v) => s"$k:$v" }
}.flatten.toSet)
}
def bulkIndex(currentInfotons: Seq[Infoton], previousInfotons: Seq[Infoton] = Nil, partition: String = defaultPartition)
(implicit executionContext: ExecutionContext) = {
val bulkRequest = client.prepareBulk()
currentInfotons.foreach{ current =>
val indexSuffix = if(current.isInstanceOf[DeletedInfoton]) "_history" else "_current"
bulkRequest.add(client.prepareIndex(partition + indexSuffix, "infoclone", current.uuid).setSource(JsonSerializer.encodeInfoton(current, toEs = true)))
}
previousInfotons.foreach{ previous =>
bulkRequest.add(client.prepareIndex(partition + "_history", "infoclone", previous.uuid).setSource(JsonSerializer.encodeInfoton(previous, toEs = true)))
bulkRequest.add(client.prepareDelete(partition + "_current", "infoclone", previous.uuid))
}
injectFuture[BulkResponse](bulkRequest.execute)
}
/**
* Deletes given infoton from Current index, save it to the history index and put a tomb stone
* to mark it is deleted
*
* @param deletedInfoton Deleted Infoton (tombstone) to index in history index
* @param previousInfoton last version of this infoton to index in history and remove from current
* @param partition logical name of partition. Used for targeting a specific index
*/
def delete(deletedInfoton: Infoton, previousInfoton: Infoton, partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[Boolean] = {
for {
// index previous Infoton in history index
prev <- injectFuture[IndexResponse](client.prepareIndex(partition + "_history", "infoclone", previousInfoton.uuid).setSource(JsonSerializer.encodeInfoton(previousInfoton, toEs = true)).execute(_))
// index tomb stone in history index
tomb <- injectFuture[IndexResponse](client.prepareIndex(partition + "_history", "infoclone", deletedInfoton.uuid).setSource(JsonSerializer.encodeInfoton(deletedInfoton, toEs = true)).execute(_))
// delete from current index
deleted <- injectFuture[DeleteResponse](client.prepareDelete(partition + "_current", "infoclone", previousInfoton.uuid).execute(_))
} yield true
}
/**
* Completely erase !! infoton of given UUID from History index.
*
* @param uuid
* @param partition logical name of partition. Used for targeting a specific index
*/
def purge(uuid: String, partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[Boolean] = {
injectFuture[DeleteResponse](client.prepareDelete(partition + "_history", "infoclone", uuid).execute(_)).map(x=> true)
}
def purgeByUuids(historyUuids: Seq[String], currentUuid: Option[String], partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[BulkResponse] = {
// empty request -> empty response
if(historyUuids.isEmpty && currentUuid.isEmpty)
Future.successful(new BulkResponse(Array[BulkItemResponse](), 0))
else {
val currentIndices = getIndicesNamesByType("current", partition)
val historyIndices = getIndicesNamesByType("history", partition)
val bulkRequest = client.prepareBulk()
for (uuid <- historyUuids; index <- historyIndices) {
bulkRequest.add(client
.prepareDelete(index, "infoclone", uuid)
.setVersionType(VersionType.FORCE)
.setVersion(1L)
)
}
for (uuid <- currentUuid; index <- currentIndices) {
bulkRequest.add(client
.prepareDelete(index, "infoclone", uuid)
.setVersionType(VersionType.FORCE)
.setVersion(1L)
)
}
injectFuture[BulkResponse](bulkRequest.execute(_))
}
}
def purgeByUuidsAndIndexes(uuidsAtIndexes: Vector[(String,String)], partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[BulkResponse] = {
// empty request -> empty response
if(uuidsAtIndexes.isEmpty)
Future.successful(new BulkResponse(Array[BulkItemResponse](), 0))
else {
val bulkRequest = client.prepareBulk()
uuidsAtIndexes.foreach { case (uuid,index) =>
bulkRequest.add(client
.prepareDelete(index, "infoclone", uuid)
.setVersionType(VersionType.FORCE)
.setVersion(1L)
)
}
injectFuture[BulkResponse](bulkRequest.execute(_))
}
}
def purgeByUuidsFromAllIndexes(uuids: Vector[String], partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[BulkResponse] = {
// empty request -> empty response
if(uuids.isEmpty)
Future.successful(new BulkResponse(Array[BulkItemResponse](), 0))
else {
val currentIndices = getIndicesNamesByType("current", partition)
val historyIndices = getIndicesNamesByType("history", partition)
val bulkRequest = client.prepareBulk()
for (uuid <- uuids; index <- historyIndices) {
bulkRequest.add(client
.prepareDelete(index, "infoclone", uuid)
.setVersionType(VersionType.FORCE)
.setVersion(1L)
)
}
for (uuid <- uuids; index <- currentIndices) {
bulkRequest.add(client
.prepareDelete(index, "infoclone", uuid)
.setVersionType(VersionType.FORCE)
.setVersion(1L)
)
}
injectFuture[BulkResponse](bulkRequest.execute(_))
}
}
/**
*
* ONLY USE THIS IF YOU HAVE NO CHOICE, IF YOU CAN SOMEHOW GET UUIDS - PURGING BY UUIDS HAS BETTER PERFORMANCE
*
* Completely erase all versions of infoton with given path
*
* @param path
* @param isRecursive whether to erase all children of this infoton of all versions (found by path)
* @param partition logical name of partition. Used for targeting a specific index
*/
def purgeAll(path: String, isRecursive: Boolean = true, partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[Boolean] = {
val indices = getIndicesNamesByType("history") ++ getIndicesNamesByType("current")
injectFuture[DeleteByQueryResponse](client.prepareDeleteByQuery((indices):_*)
.setTypes("infoclone").setQuery( termQuery("path" , path) ).execute(_)).map(x => true)
}
/**
*
* ONLY USE THIS IF YOU HAVE NO CHOICE, IF YOU CAN SOMEHOW GET UUIDS - PURGING BY UUIDS HAS BETTER PERFORMANCE
*
*
* Completely erase the current one, but none of historical versions of infoton with given path
* This makes no sense unless you re-index the current one right away. Currently the only usage is by x-fix-dc
*
* @param path
* @param isRecursive whether to erase all children of this infoton of all versions (found by path)
* @param partition logical name of partition. Used for targeting a specific index
*/
def purgeCurrent(path: String, isRecursive: Boolean = true, partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[Boolean] = {
val indices = getIndicesNamesByType("current")
injectFuture[DeleteByQueryResponse](client.prepareDeleteByQuery((indices):_*)
.setTypes("infoclone").setQuery( termQuery("path" , path) ).execute(_)).map(x => true)
}
/**
*
* ONLY USE THIS IF YOU HAVE NO CHOICE, IF YOU CAN SOMEHOW GET UUIDS - PURGING BY UUIDS HAS BETTER PERFORMANCE
*
*
* Completely erase all historical versions of infoton with given path, but not the current one
*
* @param path
* @param isRecursive whether to erase all children of this infoton of all versions (found by path)
* @param partition logical name of partition. Used for targeting a specific index
*/
def purgeHistory(path: String, isRecursive: Boolean = true, partition: String = defaultPartition)
(implicit executionContext: ExecutionContext): Future[Boolean] = {
val indices = getIndicesNamesByType("history")
injectFuture[DeleteByQueryResponse](client.prepareDeleteByQuery((indices):_*)
.setTypes("infoclone").setQuery( termQuery("path" , path) ).execute(_)).map(x => true)
}
def getIndicesNamesByType(suffix : String , partition:String = defaultPartition) = {
val currentAliasRes = client.admin.indices().prepareGetAliases(s"${partition}_${suffix}").execute().actionGet()
val indices = currentAliasRes.getAliases.keysIt().asScala.toSeq
indices
}
private def getValueAs[T](hit: SearchHit, fieldName: String): Try[T] = {
Try[T](hit.field(fieldName).getValue[T])
}
private def tryLongThenInt[V](hit: SearchHit, fieldName: String, f: Long => V, default: V, uuid: String, pathForLog: String): V = try {
getValueAs[Long](hit, fieldName) match {
case Success(l) => f(l)
case Failure(e) => {
e.setStackTrace(Array.empty) // no need to fill the logs with redundant stack trace
loger.trace(s"$fieldName not Long (outer), uuid = $uuid, path = $pathForLog", e)
tryInt(hit,fieldName,f,default,uuid)
}
}
} catch {
case e: Throwable => {
loger.trace(s"$fieldName not Long (inner), uuid = $uuid", e)
tryInt(hit,fieldName,f,default,uuid)
}
}
private def tryInt[V](hit: SearchHit, fieldName: String, f: Long => V, default: V, uuid: String): V = try {
getValueAs[Int](hit, fieldName) match {
case Success(i) => f(i.toLong)
case Failure(e) => {
loger.error(s"$fieldName not Int (outer), uuid = $uuid", e)
default
}
}
} catch {
case e: Throwable => {
loger.error(s"$fieldName not Int (inner), uuid = $uuid", e)
default
}
}
private def esResponseToThinInfotons(esResponse: org.elasticsearch.action.search.SearchResponse, includeScore: Boolean)
(implicit executionContext: ExecutionContext): Seq[FTSThinInfoton] = {
if (esResponse.getHits().hits().nonEmpty) {
val hits = esResponse.getHits().hits()
hits.map { hit =>
val path = hit.field("system.path").value.asInstanceOf[String]
val uuid = hit.field("system.uuid").value.asInstanceOf[String]
val lastModified = hit.field("system.lastModified").value.asInstanceOf[String]
val indexTime = tryLongThenInt[Long](hit,"system.indexTime",identity,-1L,uuid,path)
val score = if(includeScore) Some(hit.score()) else None
FTSThinInfoton(path, uuid, lastModified, indexTime, score)
}.toSeq
} else {
Seq.empty
}
}
private def esResponseToInfotons(esResponse: org.elasticsearch.action.search.SearchResponse, includeScore: Boolean):Vector[Infoton] = {
if (esResponse.getHits().hits().nonEmpty) {
val hits = esResponse.getHits().hits()
hits.map{ hit =>
val path = hit.field("system.path").getValue.asInstanceOf[String]
val lastModified = new DateTime(hit.field("system.lastModified").getValue.asInstanceOf[String])
val id = hit.field("system.uuid").getValue.asInstanceOf[String]
val dc = Try(hit.field("system.dc").getValue.asInstanceOf[String]).getOrElse(Settings.dataCenter)
val indexTime = tryLongThenInt[Option[Long]](hit,"system.indexTime",Some.apply[Long],None,id,path)
val score: Option[Map[String, Set[FieldValue]]] = if(includeScore) Some(Map("$score" -> Set(FExtra(hit.score(), sysQuad)))) else None
hit.field("type").getValue.asInstanceOf[String] match {
case "ObjectInfoton" =>
new ObjectInfoton(path, dc, indexTime, lastModified,score){
override def uuid = id
override def kind = "ObjectInfoton"
}
case "FileInfoton" =>
val contentLength = tryLongThenInt[Long](hit,"content.length",identity,-1L,id,path)
new FileInfoton(path, dc, indexTime, lastModified, score, Some(FileContent(hit.field("content.mimeType").getValue.asInstanceOf[String],contentLength))) {
override def uuid = id
override def kind = "FileInfoton"
}
case "LinkInfoton" =>
new LinkInfoton(path, dc, indexTime, lastModified, score, hit.field("linkTo").getValue.asInstanceOf[String], hit.field("linkType").getValue[Int]) {
override def uuid = id
override def kind = "LinkInfoton"
}
case "DeletedInfoton" =>
new DeletedInfoton(path, dc, indexTime, lastModified) {
override def uuid = id
override def kind = "DeletedInfoton"
}
case unknown => throw new IllegalArgumentException(s"content returned from elasticsearch is illegal [$unknown]") // TODO change to our appropriate exception
}
}.toVector
} else {
Vector.empty
}
}
/**
* Get Infoton's current version children
*
* @param path
* @param partition logical name of partition. Used for targeting a specific index
* @return list of found infotons
*/
def listChildren(path: String, offset: Int = 0, length: Int = 20, descendants: Boolean = false,
partition:String = defaultPartition)
(implicit executionContext:ExecutionContext): Future[FTSSearchResponse] = {
search(pathFilter=Some(PathFilter(path, descendants)), paginationParams = PaginationParams(offset, length))
}
trait FieldType {
def unmapped:String
}
case object DateType extends FieldType {
override def unmapped = "date"
}
case object IntType extends FieldType {
override def unmapped = "integer"
}
case object LongType extends FieldType {
override def unmapped = "long"
}
case object FloatType extends FieldType {
override def unmapped = "float"
}
case object DoubleType extends FieldType {
override def unmapped = "double"
}
case object BooleanType extends FieldType {
override def unmapped = "boolean"
}
case object StringType extends FieldType {
override def unmapped = "string"
}
private def fieldType(fieldName:String) = {
fieldName match {
case "system.lastModified" => DateType
case "type" | "system.parent" | "system.path" | "system.uuid" | "system.dc" | "system.quad" | "content.data" |
"content.base64-data" | "content.mimeType" => StringType
case "content.length" | "system.indexTime" => LongType
case other => other.take(2) match {
case "d$" => DateType
case "i$" => IntType
case "l$" => LongType
case "f$" => FloatType
case "w$" => DoubleType
case "b$" => BooleanType
case _ => StringType
}
}
}
private def applyFiltersToRequest(request: SearchRequestBuilder, pathFilter: Option[PathFilter] = None,
fieldFilterOpt: Option[FieldFilter] = None,
datesFilter: Option[DatesFilter] = None,
withHistory: Boolean = false,
withDeleted: Boolean = false,
preferFilter: Boolean = false) = {
val boolFilterBuilder:BoolFilterBuilder = boolFilter()
pathFilter.foreach{ pf =>
if(pf.path.equals("/")) {
if(!pf.descendants) {
boolFilterBuilder.must(termFilter("parent", "/"))
}
} else {
boolFilterBuilder.must( termFilter(if(pf.descendants)"parent_hierarchy" else "parent", pf.path))
}
}
datesFilter.foreach { df =>
boolFilterBuilder.must(rangeFilter("lastModified")
.from(df.from.map[Any](_.getMillis).orNull)
.to(df.to.map[Any](_.getMillis).orNull))
}
val fieldsOuterQueryBuilder = boolQuery()
fieldFilterOpt.foreach { ff =>
applyFieldFilter(ff, fieldsOuterQueryBuilder)
}
def applyFieldFilter(fieldFilter: FieldFilter, outerQueryBuilder: BoolQueryBuilder): Unit = {
fieldFilter match {
case SingleFieldFilter(fieldOperator, valueOperator, name, valueOpt) =>
if (valueOpt.isDefined) {
val value = valueOpt.get
val exactFieldName = fieldType(name) match {
case StringType if (!name.startsWith("system")) => s"fields.${name}.%exact"
case _ => name
}
val valueQuery = valueOperator match {
case Contains => matchPhraseQuery(name, value)
case Equals => termQuery(exactFieldName, value)
case GreaterThan => rangeQuery(exactFieldName).gt(value)
case GreaterThanOrEquals => rangeQuery(exactFieldName).gte(value)
case LessThan => rangeQuery(exactFieldName).lt(value)
case LessThanOrEquals => rangeQuery(exactFieldName).lte(value)
case Like => fuzzyLikeThisFieldQuery(name).likeText(value)
}
fieldOperator match {
case Must => outerQueryBuilder.must(valueQuery)
case MustNot => outerQueryBuilder.mustNot(valueQuery)
case Should => outerQueryBuilder.should(valueQuery)
}
} else {
fieldOperator match {
case Must => outerQueryBuilder.must(filteredQuery(matchAllQuery(), existsFilter(name)))
case MustNot => outerQueryBuilder.must(filteredQuery(matchAllQuery(), missingFilter(name)))
case _ => outerQueryBuilder.should(filteredQuery(matchAllQuery(), existsFilter(name)))
}
}
case MultiFieldFilter(fieldOperator, filters) =>
val innerQueryBuilder = boolQuery()
filters.foreach{ ff =>
applyFieldFilter(ff, innerQueryBuilder)
}
fieldOperator match {
case Must => outerQueryBuilder.must(innerQueryBuilder)
case MustNot => outerQueryBuilder.mustNot(innerQueryBuilder)
case Should => outerQueryBuilder.should(innerQueryBuilder)
}
}
}
// val preferFilter = false
//
// (fieldFilterOpt.nonEmpty, pathFilter.isDefined || datesFilter.isDefined, preferFilter) match {
// case (true,_, false) =>
// val query = filteredQuery(fieldsOuterQueryBuilder, boolFilterBuilder)
// request.setQuery(query)
// case (true, _, true) =>
// val query = filteredQuery(matchAllQuery(), andFilter(queryFilter(fieldsOuterQueryBuilder), boolFilterBuilder))
// request.setQuery(query)
// case (false, true, _) =>
// request.setQuery(filteredQuery(matchAllQuery(), boolFilterBuilder))
// case (false, false, _) => // this option is not possible due to the validation at the beginning of the method
// }
val query = (fieldsOuterQueryBuilder.hasClauses, boolFilterBuilder.hasClauses) match {
case (true, true) =>
filteredQuery(fieldsOuterQueryBuilder, boolFilterBuilder)
case (false, true) =>
filteredQuery(matchAllQuery(), boolFilterBuilder)
case (true, false) =>
if(preferFilter)
filteredQuery(matchAllQuery(), queryFilter(fieldsOuterQueryBuilder))
else
fieldsOuterQueryBuilder
case _ => matchAllQuery()
}
request.setQuery(query)
}
implicit def sortOrder2SortOrder(fieldSortOrder:FieldSortOrder):SortOrder = {
fieldSortOrder match {
case Desc => SortOrder.DESC
case Asc => SortOrder.ASC
}
}
def aggregate(pathFilter: Option[PathFilter] = None, fieldFilter: Option[FieldFilter],
datesFilter: Option[DatesFilter] = None, paginationParams: PaginationParams = DefaultPaginationParams,
aggregationFilters: Seq[AggregationFilter], withHistory: Boolean = false,
partition: String = defaultPartition, debugInfo: Boolean = false)
(implicit executionContext: ExecutionContext): Future[AggregationsResponse] = {
val indices = (partition + "_current") :: (withHistory match{
case true => partition + "_history" :: Nil
case false => Nil
})
val request = client.prepareSearch(indices:_*).setTypes("infoclone").setFrom(paginationParams.offset).setSize(paginationParams.length).setSearchType(SearchType.COUNT)
if(pathFilter.isDefined || fieldFilter.nonEmpty || datesFilter.isDefined) {
applyFiltersToRequest(request, pathFilter, fieldFilter, datesFilter)
}
var counter = 0
val filtersMap:collection.mutable.Map[String,AggregationFilter] = collection.mutable.Map.empty
def filterToBuilder(filter: AggregationFilter): AbstractAggregationBuilder = {
implicit def fieldValueToValue(fieldValue:Field) = fieldValue.operator match {
case AnalyzedField => fieldValue.value
case NonAnalyzedField => s"infoclone.fields.${fieldValue.value}.%exact"
}
val name = filter.name + "_" + counter
counter += 1
filtersMap.put(name, filter)
val aggBuilder = filter match {
case TermAggregationFilter(_, field, size, _) =>
AggregationBuilders.terms(name).field(field).size(size)
case StatsAggregationFilter(_, field) =>
AggregationBuilders.stats(name).field(field)
case HistogramAggregationFilter(_, field, interval, minDocCount, extMin, extMax, _) =>
val eMin:java.lang.Long = extMin.getOrElse(null).asInstanceOf[java.lang.Long]
val eMax:java.lang.Long = extMax.getOrElse(null).asInstanceOf[java.lang.Long]
AggregationBuilders.histogram(name).field(field).interval(interval).minDocCount(minDocCount).extendedBounds(eMin, eMax)
case SignificantTermsAggregationFilter(_, field, backGroundTermOpt, minDocCount, size, _) =>
val sigTermsBuilder = AggregationBuilders.significantTerms(name).field(field).minDocCount(minDocCount).size(size)
backGroundTermOpt.foreach{ backGroundTerm =>
sigTermsBuilder.backgroundFilter(termFilter(backGroundTerm._1, backGroundTerm._2))
}
sigTermsBuilder
case CardinalityAggregationFilter(_, field, precisionThresholdOpt) =>
val cardinalityAggBuilder = AggregationBuilders.cardinality(name).field(field)
precisionThresholdOpt.foreach{ precisionThreshold =>
cardinalityAggBuilder.precisionThreshold(precisionThreshold)
}
cardinalityAggBuilder
}
if(filter.isInstanceOf[BucketAggregationFilter]) {
filter.asInstanceOf[BucketAggregationFilter].subFilters.foreach{ subFilter =>
aggBuilder.asInstanceOf[AggregationBuilder[_ <: AggregationBuilder[_ <: Any]]].subAggregation(filterToBuilder(subFilter))
}
}
aggBuilder
}
aggregationFilters.foreach{ filter => request.addAggregation(filterToBuilder(filter)) }
val searchQueryStr = if(debugInfo) Some(request.toString) else None
val resFuture = injectFuture[SearchResponse](request.execute(_))
def esAggsToOurAggs(aggregations: Aggregations, debugInfo: Option[String] = None): AggregationsResponse = {
AggregationsResponse(
aggregations.asScala.map {
case ta: InternalTerms =>
TermsAggregationResponse(
filtersMap.get(ta.getName).get.asInstanceOf[TermAggregationFilter],
ta.getBuckets.asScala.map { b =>
val subAggregations:Option[AggregationsResponse] = b.asInstanceOf[HasAggregations].getAggregations match {
case null => None
case subAggs => if(subAggs.asList().size()>0) Some(esAggsToOurAggs(subAggs)) else None
}
Bucket(FieldValue(b.getKey), b.getDocCount, subAggregations)
}.toSeq
)
case sa: InternalStats =>
StatsAggregationResponse(
filtersMap.get(sa.getName).get.asInstanceOf[StatsAggregationFilter],
sa.getCount, sa.getMin, sa.getMax, sa.getAvg, sa.getSum
)
case ca:InternalCardinality =>
CardinalityAggregationResponse(filtersMap.get(ca.getName).get.asInstanceOf[CardinalityAggregationFilter], ca.getValue)
case ha: Histogram =>
HistogramAggregationResponse(
filtersMap.get(ha.getName).get.asInstanceOf[HistogramAggregationFilter],
ha.getBuckets.asScala.map { b =>
val subAggregations:Option[AggregationsResponse] = b.asInstanceOf[HasAggregations].getAggregations match {
case null => None
case subAggs => Some(esAggsToOurAggs(subAggs))
}
Bucket(FieldValue(b.getKeyAsNumber.longValue()), b.getDocCount, subAggregations)
}.toSeq
)
case sta:InternalSignificantTerms =>
val buckets = sta.getBuckets.asScala.toSeq
SignificantTermsAggregationResponse(
filtersMap.get(sta.getName).get.asInstanceOf[SignificantTermsAggregationFilter],
if(!buckets.isEmpty) buckets(0).getSubsetSize else 0,
buckets.map { b =>
val subAggregations:Option[AggregationsResponse] = b.asInstanceOf[HasAggregations].getAggregations match {
case null => None
case subAggs => Some(esAggsToOurAggs(subAggs))
}
SignificantTermsBucket(FieldValue(b.getKey), b.getDocCount, b.getSignificanceScore, b.getSubsetDf, subAggregations)
}.toSeq
)
case _ => ???
}.toSeq
,debugInfo)
}
resFuture.map{searchResponse => esAggsToOurAggs(searchResponse.getAggregations, searchQueryStr)}
}
def search(pathFilter: Option[PathFilter] = None, fieldsFilter: Option[FieldFilter] = None,
datesFilter: Option[DatesFilter] = None, paginationParams: PaginationParams = DefaultPaginationParams,
sortParams: SortParam = SortParam.empty, withHistory: Boolean = false, withDeleted: Boolean = false,
partition: String = defaultPartition, debugInfo: Boolean = false, timeout: Option[Duration] = None)
(implicit executionContext: ExecutionContext, logger:Logger = loger): Future[FTSSearchResponse] = {
logger.debug(s"Search request: $pathFilter, $fieldsFilter, $datesFilter, $paginationParams, $sortParams, $withHistory, $partition, $debugInfo")
if (pathFilter.isEmpty && fieldsFilter.isEmpty && datesFilter.isEmpty) {
throw new IllegalArgumentException("at least one of the filters is needed in order to search")
}
val indices = (partition + "_current") :: (if(withHistory) partition + "_history" :: Nil else Nil )
val fields = "type" :: "system.path" :: "system.uuid" :: "system.lastModified" :: "content.length" ::
"content.mimeType" :: "linkTo" :: "linkType" :: "system.dc" :: "system.indexTime" :: "system.quad" :: Nil
val request = client.prepareSearch(indices:_*).setTypes("infoclone").addFields(fields:_*).setFrom(paginationParams.offset).setSize(paginationParams.length)
sortParams match {
case NullSortParam => // don't sort.
case FieldSortParams(fsp) if fsp.isEmpty => request.addSort("system.lastModified", SortOrder.DESC)
case FieldSortParams(fsp) => fsp.foreach {
case (name,order) => {
val unmapped = name match {
// newly added sys fields should be stated explicitly since not existing in old indices
case "system.indexTime" => "long"
case "system.dc" => "string"
case "system.quad" => "string"
case _ => {
if (name.startsWith("system.") || name.startsWith("content.")) null
else name.take(2) match {
case "d$" => "date"
case "i$" => "integer"
case "l$" => "long"
case "f$" => "float"
case "w$" => "double"
case "b$" => "boolean"
case _ => "string"
}
}
}
val uname = if(unmapped == "string" && name != "type") s"fields.${name}.%exact" else name
request.addSort(fieldSort(uname).order(order).unmappedType(unmapped))
}
}
}
applyFiltersToRequest(request, pathFilter, fieldsFilter, datesFilter, withHistory, withDeleted)
val searchQueryStr = if(debugInfo) Some(request.toString) else None
logger.debug (s"^^^^^^^(**********************\\n\\n request: ${request.toString}\\n\\n")
val resFuture = timeout match {
case Some(t) => injectFuture[SearchResponse](request.execute, t)
case None => injectFuture[SearchResponse](request.execute)
}
resFuture.map { response =>
FTSSearchResponse(response.getHits.getTotalHits, paginationParams.offset, response.getHits.getHits.size,
esResponseToInfotons(response, sortParams eq NullSortParam), searchQueryStr)
}
}
def thinSearch(pathFilter: Option[PathFilter] = None, fieldsFilter: Option[FieldFilter] = None,
datesFilter: Option[DatesFilter] = None, paginationParams: PaginationParams = DefaultPaginationParams,
sortParams: SortParam = SortParam.empty, withHistory: Boolean = false, withDeleted: Boolean,
partition: String = defaultPartition, debugInfo:Boolean = false,
timeout: Option[Duration] = None)
(implicit executionContext: ExecutionContext, logger:Logger = loger) : Future[FTSThinSearchResponse] = {
logger.debug(s"Search request: $pathFilter, $fieldsFilter, $datesFilter, $paginationParams, $sortParams, $withHistory, $partition, $debugInfo")
if (pathFilter.isEmpty && fieldsFilter.isEmpty && datesFilter.isEmpty) {
throw new IllegalArgumentException("at least one of the filters is needed in order to search")
}
val indices = (partition + "_current") :: (withHistory match{
case true => partition + "_history" :: Nil
case false => Nil
})
val fields = "system.path" :: "system.uuid" :: "system.lastModified" ::"system.indexTime" :: Nil
val request = client.prepareSearch(indices:_*).setTypes("infoclone").addFields(fields:_*).setFrom(paginationParams.offset).setSize(paginationParams.length)
sortParams match {
case NullSortParam => // don't sort.
case FieldSortParams(fsp) if fsp.isEmpty => request.addSort("system.lastModified", SortOrder.DESC)
case FieldSortParams(fsp) => fsp.foreach {
case (name,order) => {
val unmapped = name match {
// newly added sys fields should be stated explicitly since not existing in old indices
case "system.indexTime" => "long"
case "system.dc" => "string"
case "system.quad" => "string"
case _ => {
if (name.startsWith("system.") || name.startsWith("content.")) null
else name.take(2) match {
case "d$" => "date"
case "i$" => "integer"
case "l$" => "long"
case "f$" => "float"
case "w$" => "double"
case "b$" => "boolean"
case _ => "string"
}
}
}
request.addSort(fieldSort(name).order(order).unmappedType(unmapped))
}
}
}
applyFiltersToRequest(request, pathFilter, fieldsFilter, datesFilter, withHistory, withDeleted)
var oldTimestamp = 0L
if(debugInfo) {
oldTimestamp = System.currentTimeMillis()
logger.debug(s"thinSearch debugInfo request ($oldTimestamp): ${request.toString}")
}
val resFuture = timeout match {
case Some(t) => injectFuture[SearchResponse](request.execute, t)
case None => injectFuture[SearchResponse](request.execute)
}
val searchQueryStr = if(debugInfo) Some(request.toString) else None
resFuture.map { response =>
if(debugInfo) logger.debug(s"thinSearch debugInfo response: ($oldTimestamp - ${System.currentTimeMillis()}): ${response.toString}")
FTSThinSearchResponse(response.getHits.getTotalHits, paginationParams.offset, response.getHits.getHits.size,
esResponseToThinInfotons(response, sortParams eq NullSortParam), searchQueryStr = searchQueryStr)
}.andThen {
case Failure(err) =>
logger.error(s"thinSearch failed, time took: [$oldTimestamp - ${System.currentTimeMillis()}], request:\\n${request.toString}")
}
}
override def getLastIndexTimeFor(dc: String, withHistory: Boolean, partition: String = defaultPartition, fieldFilters: Option[FieldFilter])
(implicit executionContext: ExecutionContext) : Future[Option[Long]] = {
val partitionsToSearch =
if (withHistory) List(partition + "_current", partition + "_history")
else List(partition + "_current")
val request = client
.prepareSearch(partitionsToSearch:_*)
.setTypes("infoclone")
.addFields("system.indexTime")
.setSize(1)
.addSort("system.indexTime", SortOrder.DESC)
val filtersSeq:List[FieldFilter] = List(
SingleFieldFilter(Must, Equals, "system.dc", Some(dc)), //ONLY DC
SingleFieldFilter(MustNot, Contains, "system.parent.parent_hierarchy", Some("/meta/")) //NO META
)
applyFiltersToRequest(
request,
None,
Some(MultiFieldFilter(Must, fieldFilters.fold(filtersSeq)(filtersSeq.::))),
None,
withHistory = withHistory
)
injectFuture[SearchResponse](request.execute).map{ sr =>
val hits = sr.getHits().hits()
if(hits.length < 1) None
else {
hits.headOption.map(_.field("system.indexTime").getValue.asInstanceOf[Long])
}
}
}
private def startShardScroll(pathFilter: Option[PathFilter] = None, fieldsFilter: Option[FieldFilter] = None,
datesFilter: Option[DatesFilter] = None, withHistory: Boolean, withDeleted: Boolean,
offset: Int, length: Int, scrollTTL:Long = scrollTTL,
index: String, nodeId: String, shard: Int)
(implicit executionContext: ExecutionContext) : Future[FTSStartScrollResponse] = {
val fields = "type" :: "system.path" :: "system.uuid" :: "system.lastModified" :: "content.length" ::
"content.mimeType" :: "linkTo" :: "linkType" :: "system.dc" :: "system.indexTime" :: "system.quad" :: Nil
val request = clients.get(nodeId).getOrElse(client).prepareSearch(index)
.setTypes("infoclone")
.addFields(fields:_*)
.setSearchType(SearchType.SCAN)
.setScroll(TimeValue.timeValueSeconds(scrollTTL))
.setSize(length)
.setFrom(offset)
.setPreference(s"_shards:$shard;_only_node:$nodeId")
if (!pathFilter.isDefined && fieldsFilter.isEmpty && !datesFilter.isDefined) {
request.setPostFilter(matchAllFilter())
} else {
applyFiltersToRequest(request, pathFilter, fieldsFilter, datesFilter, withHistory, withDeleted)
}
val scrollResponseFuture = injectFuture[SearchResponse](request.execute(_))
scrollResponseFuture.map{ scrollResponse => FTSStartScrollResponse(scrollResponse.getHits.totalHits, scrollResponse.getScrollId, Some(nodeId)) }
}
def startSuperScroll(pathFilter: Option[PathFilter] = None, fieldsFilter: Option[FieldFilter] = None,
datesFilter: Option[DatesFilter] = None,
paginationParams: PaginationParams = DefaultPaginationParams, scrollTTL:Long = scrollTTL,
withHistory: Boolean, withDeleted: Boolean)
(implicit executionContext: ExecutionContext) : Seq[() => Future[FTSStartScrollResponse]] = {
val aliases = if(withHistory) List("cmwell_current", "cmwell_history") else List("cmwell_current")
val ssr = client.admin().cluster().prepareSearchShards(aliases :_*).setTypes("infoclone").execute().actionGet()
val targetedShards = ssr.getGroups.flatMap{ shardGroup =>
shardGroup.getShards.filter(_.primary()).map{ shard =>
(shard.index(), shard.currentNodeId(), shard.id())
}
}
targetedShards.map{ case (index, node, shard) =>
() => startShardScroll(pathFilter, fieldsFilter, datesFilter, withHistory, withDeleted, paginationParams.offset,
paginationParams.length, scrollTTL, index, node, shard)
}
}
/**
*
* @param pathFilter
* @param fieldsFilter
* @param datesFilter
* @param paginationParams
* @param scrollTTL
* @param withHistory
* @param indexNames indices to search on, empty means all.
* @param onlyNode ES NodeID to restrict search to ("local" means local node), or None for no restriction
* @return
*/
def startScroll(pathFilter: Option[PathFilter] = None, fieldsFilter: Option[FieldFilter] = None,
datesFilter: Option[DatesFilter] = None, paginationParams: PaginationParams = DefaultPaginationParams,
scrollTTL: Long = scrollTTL, withHistory: Boolean = false, withDeleted: Boolean, indexNames: Seq[String] = Seq.empty,
onlyNode: Option[String] = None, partition: String, debugInfo: Boolean)
(implicit executionContext: ExecutionContext, logger:Logger = loger) : Future[FTSStartScrollResponse] = {
logger.debug(s"StartScroll request: $pathFilter, $fieldsFilter, $datesFilter, $paginationParams, $withHistory")
if(partition != defaultPartition) {
logger.warn("old implementation ignores partition parameter")
}
val indices = {
if (indexNames.nonEmpty) indexNames
else "cmwell_current" :: (withHistory match {
case true => "cmwell_history" :: Nil
case false => Nil
})
}
val fields = "type" :: "system.path" :: "system.uuid" :: "system.lastModified" :: "content.length" ::
"content.mimeType" :: "linkTo" :: "linkType" :: "system.dc" :: "system.indexTime" :: "system.quad" :: Nil
// since in ES scroll API, size is per shard, we need to convert our paginationParams.length parameter to be per shard
// We need to find how many shards are relevant for this query. For that we'll issue a fake search request
val fakeRequest = client.prepareSearch(indices:_*).setTypes("infoclone").addFields(fields:_*)
if (pathFilter.isEmpty && fieldsFilter.isEmpty && datesFilter.isEmpty) {
fakeRequest.setPostFilter(matchAllFilter())
} else {
applyFiltersToRequest(fakeRequest, pathFilter, fieldsFilter, datesFilter)
}
val fakeResponse = fakeRequest.execute().get()
val relevantShards = fakeResponse.getSuccessfulShards
// rounded to lowest multiplacations of shardsperindex or to mimimum of 1
val infotonsPerShard = (paginationParams.length/relevantShards) max 1
val request = client.prepareSearch(indices:_*)
.setTypes("infoclone")
.addFields(fields:_*)
.setSearchType(SearchType.SCAN)
.setScroll(TimeValue.timeValueSeconds(scrollTTL))
.setSize(infotonsPerShard)
.setFrom(paginationParams.offset)
if(onlyNode.isDefined) {
request.setPreference(s"_only_node_primary:${onlyNode.map{case "local" => localNodeId; case n => n}.get}")
}
if (pathFilter.isEmpty && fieldsFilter.isEmpty && datesFilter.isEmpty) {
request.setPostFilter(matchAllFilter())
} else {
applyFiltersToRequest(request, pathFilter, fieldsFilter, datesFilter, withHistory, withDeleted)
}
val scrollResponseFuture = injectFuture[SearchResponse](request.execute(_))
val searchQueryStr = if(debugInfo) Some(request.toString) else None
scrollResponseFuture.map{ scrollResponse => FTSStartScrollResponse(scrollResponse.getHits.totalHits, scrollResponse.getScrollId, searchQueryStr = searchQueryStr) }
}
def startSuperMultiScroll(pathFilter: Option[PathFilter] = None, fieldsFilter: Option[FieldFilter] = None,
datesFilter: Option[DatesFilter] = None,
paginationParams: PaginationParams = DefaultPaginationParams, scrollTTL:Long = scrollTTL,
withHistory: Boolean = false, withDeleted:Boolean, partition: String)
(implicit executionContext:ExecutionContext, logger:Logger) : Seq[Future[FTSStartScrollResponse]] = {
logger.debug(s"StartMultiScroll request: $pathFilter, $fieldsFilter, $datesFilter, $paginationParams, $withHistory")
if(partition != defaultPartition) {
logger.warn("old implementation ignores partition parameter")
}
def indicesNames(indexName: String): Seq[String] = {
val currentAliasRes = client.admin.indices().prepareGetAliases(indexName).execute().actionGet()
val indices = currentAliasRes.getAliases.keysIt().asScala.toSeq
indices
}
def dataNodeIDs = {
client.admin().cluster().prepareNodesInfo().execute().actionGet().getNodesMap.asScala.filter{case (id, node) =>
node.getNode.isDataNode
}.map{_._1}.toSeq
}
val indices = indicesNames("cmwell_current") ++ (if(withHistory) indicesNames("_history") else Nil )
indices.flatMap { indexName =>
dataNodeIDs.map{ nodeId =>
startScroll(pathFilter, fieldsFilter, datesFilter, paginationParams, scrollTTL, withHistory, withDeleted,
Seq(indexName), Some(nodeId))
}
}
}
def startMultiScroll(pathFilter: Option[PathFilter] = None, fieldsFilter: Option[FieldFilter] = None,
datesFilter: Option[DatesFilter] = None,
paginationParams: PaginationParams = DefaultPaginationParams,
scrollTTL: Long = scrollTTL, withHistory: Boolean = false, withDeleted: Boolean, partition: String)
(implicit executionContext:ExecutionContext, logger:Logger = loger): Seq[Future[FTSStartScrollResponse]] = {
logger.debug(s"StartMultiScroll request: $pathFilter, $fieldsFilter, $datesFilter, $paginationParams, $withHistory")
if(partition != defaultPartition) {
logger.warn("old implementation ignores partition parameter")
}
def indicesNames(indexName: String): Seq[String] = {
val currentAliasRes = client.admin.indices().prepareGetAliases(indexName).execute().actionGet()
val indices = currentAliasRes.getAliases.keysIt().asScala.toSeq
indices
}
val indices = indicesNames("cmwell_current") ++ (if(withHistory) indicesNames("_history") else Nil)
indices.map { indexName =>
startScroll(pathFilter, fieldsFilter, datesFilter, paginationParams, scrollTTL, withHistory, withDeleted,
Seq(indexName))
}
}
def scroll(scrollId: String, scrollTTL: Long, nodeId: Option[String])
(implicit executionContext:ExecutionContext, logger:Logger = loger): Future[FTSScrollResponse] = {
logger.debug(s"Scroll request: $scrollId, $scrollTTL")
val clint = nodeId.map{clients(_)}.getOrElse(client)
val scrollResponseFuture = injectFuture[SearchResponse](
clint.prepareSearchScroll(scrollId).setScroll(TimeValue.timeValueSeconds(scrollTTL)).execute(_)
)
val p = Promise[FTSScrollResponse]()
scrollResponseFuture.onComplete {
case Failure(exception) => p.failure(exception)
case Success(scrollResponse) => {
val status = scrollResponse.status().getStatus
if (status >= 400) p.failure(new Exception(s"bad scroll response: $scrollResponse"))
else {
if(status != 200)
logger.warn(s"scroll($scrollId, $scrollTTL, $nodeId) resulted with status[$status] != 200: $scrollResponse")
p.complete(Try(esResponseToInfotons(scrollResponse, includeScore = false)).map { infotons =>
FTSScrollResponse(scrollResponse.getHits.getTotalHits, scrollResponse.getScrollId, infotons)
})
}
}
}
p.future
}
def rInfo(path: String, scrollTTL: Long= scrollTTL, paginationParams: PaginationParams = DefaultPaginationParams, withHistory: Boolean = false, partition: String = defaultPartition)
(implicit executionContext:ExecutionContext): Future[Source[Vector[(Long, String,String)],NotUsed]] = {
val indices = (partition + "_current") :: (if (withHistory) partition + "_history" :: Nil else Nil)
val fields = "system.uuid" :: "system.lastModified" :: Nil // "system.indexTime" :: Nil // TODO: fix should add indexTime, so why not pull it now?
// since in ES scroll API, size is per shard, we need to convert our paginationParams.length parameter to be per shard
// We need to find how many shards are relevant for this query. For that we'll issue a fake search request
val fakeRequest = client.prepareSearch(indices: _*).setTypes("infoclone").addFields(fields: _*)
fakeRequest.setQuery(QueryBuilders.matchQuery("path", path))
injectFuture[SearchResponse](al => fakeRequest.execute(al)).flatMap { fakeResponse =>
val relevantShards = fakeResponse.getSuccessfulShards
// rounded to lowest multiplacations of shardsperindex or to mimimum of 1
val infotonsPerShard = (paginationParams.length / relevantShards) max 1
val request = client.prepareSearch(indices: _*)
.setTypes("infoclone")
.addFields(fields: _*)
.setSearchType(SearchType.SCAN)
.setScroll(TimeValue.timeValueSeconds(scrollTTL))
.setSize(infotonsPerShard)
.setQuery(QueryBuilders.matchQuery("path", path))
val scrollResponseFuture = injectFuture[SearchResponse](al => request.execute(al))
scrollResponseFuture.map { scrollResponse =>
if(scrollResponse.getHits.totalHits == 0) Source.empty[Vector[(Long, String,String)]]
else Source.unfoldAsync(scrollResponse.getScrollId) { scrollID =>
injectFuture[SearchResponse]({ al =>
client
.prepareSearchScroll(scrollID)
.setScroll(TimeValue.timeValueSeconds(scrollTTL))
.execute(al)
}, FiniteDuration(30, SECONDS)).map { scrollResponse =>
val info = rExtractInfo(scrollResponse)
if (info.isEmpty) None
else Some(scrollResponse.getScrollId -> info)
}
}
}
}
}
override def latestIndexNameAndCount(prefix: String): Option[(String, Long)] = ???
private def rExtractInfo(esResponse: org.elasticsearch.action.search.SearchResponse) : Vector[(Long, String, String)] = {
val sHits = esResponse.getHits.hits()
if (sHits.isEmpty) Vector.empty
else {
val hits = esResponse.getHits.hits()
hits.map{ hit =>
val uuid = hit.field("system.uuid").getValue.asInstanceOf[String]
val lastModified = new DateTime(hit.field("system.lastModified").getValue.asInstanceOf[String]).getMillis
val index = hit.getIndex
(lastModified, uuid, index)
}(collection.breakOut)
}
}
def info(path: String , paginationParams: PaginationParams = DefaultPaginationParams, withHistory: Boolean = false,
partition: String = defaultPartition)
(implicit executionContext:ExecutionContext): Future[Vector[(String,String)]] = {
val indices = (partition + "_current") :: (if(withHistory) partition + "_history" :: Nil else Nil)
// val fields = "system.path" :: "system.uuid" :: "system.lastModified" :: Nil
val request = client.prepareSearch(indices:_*).setTypes("infoclone").addFields("system.uuid").setFrom(paginationParams.offset).setSize(paginationParams.length)
val qb : QueryBuilder = QueryBuilders.matchQuery("path", path)
request.setQuery(qb)
val resFuture = injectFuture[SearchResponse](request.execute)
resFuture.map { response => extractInfo(response) }
}
val bo = collection.breakOut[Array[SearchHit],(String,Long,String),Vector[(String,Long,String)]]
def uinfo(uuid: String, partition: String)
(implicit executionContext:ExecutionContext) : Future[Vector[(String, Long, String)]] = {
val indices = (partition + "_current") :: (partition + "_history") :: Nil
val request = client.prepareSearch(indices:_*).setTypes("infoclone").setFetchSource(true).setVersion(true)
val qb : QueryBuilder = QueryBuilders.matchQuery("uuid", uuid)
request.setQuery(qb)
injectFuture[SearchResponse](request.execute).map { response =>
val hits = response.getHits.hits()
hits.map { hit =>
(hit.getIndex, hit.getVersion, hit.getSourceAsString)
}(bo)
}
}
private def extractInfo(esResponse: org.elasticsearch.action.search.SearchResponse) : Vector[(String , String )] = {
if (esResponse.getHits.hits().nonEmpty) {
val hits = esResponse.getHits.hits()
hits.map{ hit =>
val uuid = hit.field("system.uuid").getValue.asInstanceOf[String]
val index = hit.getIndex
( uuid , index)
}.toVector
}
else Vector.empty
}
private def injectFuture[A](f: ActionListener[A] => Unit, timeout : Duration = FiniteDuration(10, SECONDS))
(implicit executionContext: ExecutionContext)= {
val p = Promise[A]()
val timeoutTask = TimeoutScheduler.tryScheduleTimeout(p,timeout)
f(new ActionListener[A] {
def onFailure(t: Throwable): Unit = {
timeoutTask.cancel()
loger error ("Exception from ElasticSearch. %s\\n%s".format(t.getLocalizedMessage, t.getStackTrace().mkString("", EOL, EOL)))
p.tryFailure(t)
}
def onResponse(res: A): Unit = {
timeoutTask.cancel()
loger debug ("Response from ElasticSearch:\\n%s".format(res.toString))
p.trySuccess(res)
}
})
p.future
}
def countSearchOpenContexts(): Array[(String,Long)] = {
val response = client.admin().cluster().prepareNodesStats().setIndices(true).execute().get()
response.getNodes.map{
nodeStats =>
nodeStats.getHostname -> nodeStats.getIndices.getSearch.getOpenContexts
}.sortBy(_._1)
}
}
object TimeoutScheduler {
val timer = new HashedWheelTimer(10, TimeUnit.MILLISECONDS)
def scheduleTimeout(promise: Promise[_], after: Duration) = {
timer.newTimeout(new TimerTask {
override def run(timeout:Timeout) = {
promise.failure(new TimeoutException("Operation timed out after " + after.toMillis + " millis"))
}
}, after.toNanos, TimeUnit.NANOSECONDS)
}
def tryScheduleTimeout[T](promise: Promise[T], after: Duration) = {
timer.newTimeout(new TimerTask {
override def run(timeout:Timeout) = {
promise.tryFailure(new TimeoutException("Operation timed out after " + after.toMillis + " millis"))
}
}, after.toNanos, TimeUnit.NANOSECONDS)
}
}
object TimeoutFuture {
def withTimeout[T](fut: Future[T], after: Duration) (implicit executionContext:ExecutionContext) = {
val prom = Promise[T]()
val timeout = TimeoutScheduler.scheduleTimeout(prom, after)
val combinedFut = Future.firstCompletedOf(List(fut, prom.future))
fut onComplete{case result => timeout.cancel()}
combinedFut
}
}
sealed abstract class InfotonToIndex(val infoton: Infoton)
case class CurrentInfotonToIndex(override val infoton: Infoton) extends InfotonToIndex(infoton)
case class PreviousInfotonToIndex(override val infoton: Infoton) extends InfotonToIndex(infoton)
case class DeletedInfotonToIndex(override val infoton: Infoton) extends InfotonToIndex(infoton)
sealed abstract class FieldSortOrder
case object Desc extends FieldSortOrder
case object Asc extends FieldSortOrder
sealed abstract class SortParam
object SortParam {
type FieldSortParam = (String, FieldSortOrder)
val empty = FieldSortParams(Nil)
def apply(sortParam: (String, FieldSortOrder)*) = new FieldSortParams(sortParam.toList)
}
case class FieldSortParams(fieldSortParams: List[SortParam.FieldSortParam]) extends SortParam
case object NullSortParam extends SortParam
sealed abstract class FieldOperator {
def applyTo(softBoolean: SoftBoolean): SoftBoolean
}
case object Must extends FieldOperator {
override def applyTo(softBoolean: SoftBoolean): SoftBoolean = softBoolean match {
case SoftFalse => False
case unsoftVal => unsoftVal
}
}
case object Should extends FieldOperator {
override def applyTo(softBoolean: SoftBoolean): SoftBoolean = softBoolean match {
case False => SoftFalse
case softOrTrue => softOrTrue
}
}
case object MustNot extends FieldOperator {
override def applyTo(softBoolean: SoftBoolean): SoftBoolean = softBoolean match {
case True => False
case _ => True
}
}
sealed abstract class ValueOperator
case object Contains extends ValueOperator
case object Equals extends ValueOperator
case object GreaterThan extends ValueOperator
case object GreaterThanOrEquals extends ValueOperator
case object LessThan extends ValueOperator
case object LessThanOrEquals extends ValueOperator
case object Like extends ValueOperator
case class PathFilter(path: String, descendants: Boolean)
sealed trait FieldFilter {
def fieldOperator: FieldOperator
def filter(i: Infoton): SoftBoolean
}
case class SingleFieldFilter(override val fieldOperator: FieldOperator = Must, valueOperator: ValueOperator,
name: String, value: Option[String]) extends FieldFilter {
def filter(i: Infoton): SoftBoolean = {
require(valueOperator != Like,s"unsupported ValueOperator: $valueOperator")
val valOp: (FieldValue,String) => Boolean = valueOperator match {
case Contains => (infotonValue,inputValue) => infotonValue.value.toString.contains(inputValue)
case Equals => (infotonValue,inputValue) => infotonValue.compareToString(inputValue).map(0.==).getOrElse(false)
case GreaterThan => (infotonValue,inputValue) => infotonValue.compareToString(inputValue).map(0.<).getOrElse(false)
case GreaterThanOrEquals => (infotonValue,inputValue) => infotonValue.compareToString(inputValue).map(0.<=).getOrElse(false)
case LessThan => (infotonValue,inputValue) => infotonValue.compareToString(inputValue).map(0.>).getOrElse(false)
case LessThanOrEquals => (infotonValue,inputValue) => infotonValue.compareToString(inputValue).map(0.>=).getOrElse(false)
case Like => ???
}
fieldOperator match {
case Must => i.fields.flatMap(_.get(name).map(_.exists(fv => value.forall(v => valOp(fv,v))))).fold[SoftBoolean](False)(SoftBoolean.hard)
case Should => i.fields.flatMap(_.get(name).map(_.exists(fv => value.forall(v => valOp(fv,v))))).fold[SoftBoolean](SoftFalse)(SoftBoolean.soft)
case MustNot => i.fields.flatMap(_.get(name).map(_.forall(fv => !value.exists(v => valOp(fv,v))))).fold[SoftBoolean](True)(SoftBoolean.hard)
}
}
}
/**
* SoftBoolean is a 3-state "boolean" where we need a 2-way mapping
* between regular booleans and this 3-state booleans.
*
* `true` is mapped to `True`
* `false` is mapped to either `False` or `SoftFalse`, depending on business logic.
*
* `True` is mapped to `true`
* `False` & `SoftFalse` are both mapped to `false`.
*
* You may think of `SoftFalse` as an un-commited false,
* where we don't "fail fast" an expression upon `SoftFalse`,
* and may still succeed with `True` up ahead.
*/
object SoftBoolean {
def hard(b: Boolean): SoftBoolean = if(b) True else False
def soft(b: Boolean): SoftBoolean = if(b) True else SoftFalse
def zero: SoftBoolean = SoftFalse
}
sealed trait SoftBoolean {
def value: Boolean
def combine(that: SoftBoolean): SoftBoolean = this match {
case False => this
case SoftFalse => that
case True => that match {
case False => that
case _ => this
}
}
}
case object True extends SoftBoolean { override val value = true }
case object False extends SoftBoolean { override val value = false }
case object SoftFalse extends SoftBoolean { override val value = false }
case class MultiFieldFilter(override val fieldOperator: FieldOperator = Must,
filters: Seq[FieldFilter]) extends FieldFilter {
def filter(i: Infoton): SoftBoolean = {
fieldOperator.applyTo(
filters.foldLeft(SoftBoolean.zero){
case (b,f) => b.combine(f.filter(i))
})
}
}
object FieldFilter {
def apply(fieldOperator: FieldOperator, valueOperator: ValueOperator, name: String, value: String) =
new SingleFieldFilter(fieldOperator, valueOperator, name, Some(value))
}
case class DatesFilter(from: Option[DateTime], to:Option[DateTime])
case class PaginationParams(offset: Int, length: Int)
object DefaultPaginationParams extends PaginationParams(0, 100)
case class FTSSearchResponse(total: Long, offset: Long, length: Long, infotons: Seq[Infoton], searchQueryStr: Option[String] = None)
case class FTSStartScrollResponse(total: Long, scrollId: String, nodeId: Option[String] = None, searchQueryStr: Option[String] = None)
case class FTSScrollResponse(total: Long, scrollId: String, infotons: Seq[Infoton], nodeId: Option[String] = None)
case class FTSScrollThinResponse(total: Long, scrollId: String, thinInfotons: Seq[FTSThinInfoton], nodeId: Option[String] = None)
case object FTSTimeout
case class FTSThinInfoton(path: String, uuid: String, lastModified: String, indexTime: Long, score: Option[Float])
case class FTSThinSearchResponse(total: Long, offset: Long, length: Long, thinInfotons: Seq[FTSThinInfoton], searchQueryStr: Option[String] = None)
|
nruppin/CM-Well
|
server/cmwell-fts/src/main/scala/cmwell/fts/FTSServiceES.scala
|
Scala
|
apache-2.0
| 72,814 |
package no.ap.streaming.event
import spray.json._
case class ProviderNode(providerType: String, id: String, url: String)
object ProviderNodeProtocol extends DefaultJsonProtocol {
implicit object ProviderFormatter extends RootJsonFormat[ProviderNode] {
override def write(provider: ProviderNode): JsValue = {
JsArray(JsString(provider.providerType), JsString(provider.id), JsString(provider.url))
}
override def read(json: JsValue): ProviderNode = {
json.asJsObject.getFields("@type", "@id", "url") match {
case Seq(JsString(tp), JsString(id), JsString(url)) =>
new ProviderNode(tp, id, url)
case _ => throw new DeserializationException("ProviderNode expected")
}
}
}
}
|
przemek1990/spark-streaming
|
src/main/scala/no/ap/streaming/event/ProviderNode.scala
|
Scala
|
apache-2.0
| 739 |
package org.vaadin.addons.rinne.mixins
import com.vaadin.server.Resource
import com.vaadin.ui.AbstractMedia
trait AbstractMediaMixin extends AbstractComponentMixin {
this: AbstractMedia =>
import scala.collection.JavaConverters._
def source: Option[Resource] = getSources.asScala.headOption
def source_=(source: Resource): Unit = setSource(source)
def sources: Seq[Resource] = getSources.asScala
def showControls: Boolean = isShowControls
def showControls_=(showControls: Boolean): Unit = setShowControls(showControls)
def altText: Option[String] = Option(getAltText)
def altText_=(altText: Option[String]): Unit = setAltText(altText.orNull)
def altText_=(altText: String): Unit = setAltText(altText)
def htmlContentAllowed: Boolean = isHtmlContentAllowed
def htmlContentAllowed_=(htmlContentAllowed: Boolean): Unit = setHtmlContentAllowed(htmlContentAllowed)
def autoplay: Boolean = isAutoplay
def autoplay_=(autoplay: Boolean): Unit = setAutoplay(autoplay)
def muted: Boolean = isMuted
def muted_=(muted: Boolean): Unit = setMuted(muted)
}
|
LukaszByczynski/rinne
|
src/main/scala/org/vaadin/addons/rinne/mixins/AbstractMediaMixin.scala
|
Scala
|
apache-2.0
| 1,092 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.execution.command.management
import scala.collection.JavaConverters._
import org.apache.spark.sql.{CarbonEnv, Row, SparkSession}
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.expressions.Expression
import org.apache.spark.sql.execution.command.{AtomicRunnableCommand, Checker, DataCommand}
import org.apache.spark.sql.optimizer.CarbonFilters
import org.apache.carbondata.api.CarbonStore
import org.apache.carbondata.common.exceptions.sql.MalformedCarbonCommandException
import org.apache.carbondata.common.logging.LogServiceFactory
import org.apache.carbondata.core.constants.CarbonCommonConstants
import org.apache.carbondata.core.datamap.DataMapStoreManager
import org.apache.carbondata.core.exception.ConcurrentOperationException
import org.apache.carbondata.core.indexstore.PartitionSpec
import org.apache.carbondata.core.metadata.schema.table.CarbonTable
import org.apache.carbondata.core.statusmanager.SegmentStatusManager
import org.apache.carbondata.events._
import org.apache.carbondata.spark.util.CommonUtil
/**
* Clean data in table
* If table name is specified and forceTableClean is false, it will clean garbage
* segment (MARKED_FOR_DELETE state).
* If table name is specified and forceTableClean is true, it will delete all data
* in the table.
* If table name is not provided, it will clean garbage segment in all tables.
*/
case class CarbonCleanFilesCommand(
databaseNameOp: Option[String],
tableName: Option[String],
forceTableClean: Boolean = false,
isInternalCleanCall: Boolean = false)
extends AtomicRunnableCommand {
var carbonTable: CarbonTable = _
var cleanFileCommands: List[CarbonCleanFilesCommand] = _
override def processMetadata(sparkSession: SparkSession): Seq[Row] = {
carbonTable = CarbonEnv.getCarbonTable(databaseNameOp, tableName.get)(sparkSession)
val dms = carbonTable.getTableInfo.getDataMapSchemaList.asScala.map(_.getDataMapName)
val indexDms = DataMapStoreManager.getInstance.getAllDataMap(carbonTable).asScala
.filter(_.getDataMapSchema.isIndexDataMap)
if (carbonTable.hasAggregationDataMap) {
cleanFileCommands = carbonTable.getTableInfo.getDataMapSchemaList.asScala.map {
dataMapSchema =>
val relationIdentifier = dataMapSchema.getRelationIdentifier
CarbonCleanFilesCommand(
Some(relationIdentifier.getDatabaseName), Some(relationIdentifier.getTableName),
isInternalCleanCall = true)
}.toList
cleanFileCommands.foreach(_.processMetadata(sparkSession))
} else if (carbonTable.isChildDataMap && !isInternalCleanCall) {
throwMetadataException(
carbonTable.getDatabaseName, carbonTable.getTableName,
"Cannot clean files directly for aggregate table.")
}
Seq.empty
}
override def processData(sparkSession: SparkSession): Seq[Row] = {
// if insert overwrite in progress, do not allow delete segment
if (SegmentStatusManager.isOverwriteInProgressInTable(carbonTable)) {
throw new ConcurrentOperationException(carbonTable, "insert overwrite", "clean file")
}
val operationContext = new OperationContext
val cleanFilesPreEvent: CleanFilesPreEvent =
CleanFilesPreEvent(carbonTable,
sparkSession)
OperationListenerBus.getInstance.fireEvent(cleanFilesPreEvent, operationContext)
if (tableName.isDefined) {
Checker.validateTableExists(databaseNameOp, tableName.get, sparkSession)
if (forceTableClean) {
deleteAllData(sparkSession, databaseNameOp, tableName.get)
} else {
cleanGarbageData(sparkSession, databaseNameOp, tableName.get)
}
} else {
cleanGarbageDataInAllTables(sparkSession)
}
if (cleanFileCommands != null) {
cleanFileCommands.foreach(_.processData(sparkSession))
}
val cleanFilesPostEvent: CleanFilesPostEvent =
CleanFilesPostEvent(carbonTable, sparkSession)
OperationListenerBus.getInstance.fireEvent(cleanFilesPostEvent, operationContext)
Seq.empty
}
private def deleteAllData(sparkSession: SparkSession,
databaseNameOp: Option[String], tableName: String): Unit = {
val dbName = CarbonEnv.getDatabaseName(databaseNameOp)(sparkSession)
val databaseLocation = CarbonEnv.getDatabaseLocation(dbName, sparkSession)
val tablePath = databaseLocation + CarbonCommonConstants.FILE_SEPARATOR + tableName
CarbonStore.cleanFiles(
dbName = dbName,
tableName = tableName,
tablePath = tablePath,
carbonTable = null, // in case of delete all data carbonTable is not required.
forceTableClean = forceTableClean)
}
private def cleanGarbageData(sparkSession: SparkSession,
databaseNameOp: Option[String], tableName: String): Unit = {
if (!carbonTable.getTableInfo.isTransactionalTable) {
throw new MalformedCarbonCommandException("Unsupported operation on non transactional table")
}
val partitions: Option[Seq[PartitionSpec]] = CarbonFilters.getPartitions(
Seq.empty[Expression],
sparkSession,
carbonTable)
CarbonStore.cleanFiles(
dbName = CarbonEnv.getDatabaseName(databaseNameOp)(sparkSession),
tableName = tableName,
tablePath = carbonTable.getTablePath,
carbonTable = carbonTable,
forceTableClean = forceTableClean,
currentTablePartitions = partitions)
}
// Clean garbage data in all tables in all databases
private def cleanGarbageDataInAllTables(sparkSession: SparkSession): Unit = {
try {
val databases = sparkSession.sessionState.catalog.listDatabases()
databases.foreach(dbName => {
val databaseLocation = CarbonEnv.getDatabaseLocation(dbName, sparkSession)
CommonUtil.cleanInProgressSegments(databaseLocation, dbName)
})
} catch {
case e: Throwable =>
// catch all exceptions to avoid failure
LogServiceFactory.getLogService(this.getClass.getCanonicalName)
.error(e, "Failed to clean in progress segments")
}
}
}
|
jatin9896/incubator-carbondata
|
integration/spark2/src/main/scala/org/apache/spark/sql/execution/command/management/CarbonCleanFilesCommand.scala
|
Scala
|
apache-2.0
| 6,862 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kafka.server
import java.util.concurrent.locks.ReentrantLock
import kafka.cluster.BrokerEndPoint
import kafka.consumer.PartitionTopicInfo
import kafka.message.{MessageAndOffset, ByteBufferMessageSet}
import kafka.utils.{Pool, ShutdownableThread, DelayedItem}
import kafka.common.{KafkaException, ClientIdAndBroker, TopicAndPartition}
import kafka.metrics.KafkaMetricsGroup
import kafka.utils.CoreUtils.inLock
import org.apache.kafka.common.errors.CorruptRecordException
import org.apache.kafka.common.protocol.Errors
import AbstractFetcherThread._
import scala.collection.{mutable, Set, Map}
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
import com.yammer.metrics.core.Gauge
/**
* Abstract class for fetching data from multiple partitions from the same broker.
*/
abstract class AbstractFetcherThread(name: String,
clientId: String,
sourceBroker: BrokerEndPoint,
fetchBackOffMs: Int = 0,
isInterruptible: Boolean = true)
extends ShutdownableThread(name, isInterruptible) {
type REQ <: FetchRequest
type PD <: PartitionData
private val partitionMap = new mutable.HashMap[TopicAndPartition, PartitionFetchState] // a (topic, partition) -> partitionFetchState map
private val partitionMapLock = new ReentrantLock
private val partitionMapCond = partitionMapLock.newCondition()
private val metricId = new ClientIdAndBroker(clientId, sourceBroker.host, sourceBroker.port)
val fetcherStats = new FetcherStats(metricId)
val fetcherLagStats = new FetcherLagStats(metricId)
/* callbacks to be defined in subclass */
// process fetched data
def processPartitionData(topicAndPartition: TopicAndPartition, fetchOffset: Long, partitionData: PD)
// handle a partition whose offset is out of range and return a new fetch offset
def handleOffsetOutOfRange(topicAndPartition: TopicAndPartition): Long
// deal with partitions with errors, potentially due to leadership changes
def handlePartitionsWithErrors(partitions: Iterable[TopicAndPartition])
protected def buildFetchRequest(partitionMap: Map[TopicAndPartition, PartitionFetchState]): REQ
protected def fetch(fetchRequest: REQ): Map[TopicAndPartition, PD]
override def shutdown(){
initiateShutdown()
inLock(partitionMapLock) {
partitionMapCond.signalAll()
}
awaitShutdown()
}
override def doWork() {
val fetchRequest = inLock(partitionMapLock) {
val fetchRequest = buildFetchRequest(partitionMap)
if (fetchRequest.isEmpty) {
trace("There are no active partitions. Back off for %d ms before sending a fetch request".format(fetchBackOffMs))
partitionMapCond.await(fetchBackOffMs, TimeUnit.MILLISECONDS)
}
fetchRequest
}
if (!fetchRequest.isEmpty)
processFetchRequest(fetchRequest)
}
private def processFetchRequest(fetchRequest: REQ) {
val partitionsWithError = new mutable.HashSet[TopicAndPartition]
var responseData: Map[TopicAndPartition, PD] = Map.empty
try {
trace("Issuing to broker %d of fetch request %s".format(sourceBroker.id, fetchRequest))
responseData = fetch(fetchRequest)
} catch {
case t: Throwable =>
if (isRunning.get) {
warn("Error in fetch %s. Possible cause: %s".format(fetchRequest, t.toString))
inLock(partitionMapLock) {
partitionsWithError ++= partitionMap.keys
// there is an error occurred while fetching partitions, sleep a while
partitionMapCond.await(fetchBackOffMs, TimeUnit.MILLISECONDS)
}
}
}
fetcherStats.requestRate.mark()
if (responseData.nonEmpty) {
// process fetched data
inLock(partitionMapLock) {
responseData.foreach { case (topicAndPartition, partitionData) =>
val TopicAndPartition(topic, partitionId) = topicAndPartition
partitionMap.get(topicAndPartition).foreach(currentPartitionFetchState =>
// we append to the log if the current offset is defined and it is the same as the offset requested during fetch
if (fetchRequest.offset(topicAndPartition) == currentPartitionFetchState.offset) {
Errors.forCode(partitionData.errorCode) match {
case Errors.NONE =>
try {
val messages = partitionData.toByteBufferMessageSet
val validBytes = messages.validBytes
val newOffset = messages.shallowIterator.toSeq.lastOption match {
case Some(m: MessageAndOffset) => m.nextOffset
case None => currentPartitionFetchState.offset
}
partitionMap.put(topicAndPartition, new PartitionFetchState(newOffset))
fetcherLagStats.getFetcherLagStats(topic, partitionId).lag = Math.max(0L, partitionData.highWatermark - newOffset)
fetcherStats.byteRate.mark(validBytes)
// Once we hand off the partition data to the subclass, we can't mess with it any more in this thread
processPartitionData(topicAndPartition, currentPartitionFetchState.offset, partitionData)
} catch {
case ime: CorruptRecordException =>
// we log the error and continue. This ensures two things
// 1. If there is a corrupt message in a topic partition, it does not bring the fetcher thread down and cause other topic partition to also lag
// 2. If the message is corrupt due to a transient state in the log (truncation, partial writes can cause this), we simply continue and
// should get fixed in the subsequent fetches
logger.error("Found invalid messages during fetch for partition [" + topic + "," + partitionId + "] offset " + currentPartitionFetchState.offset + " error " + ime.getMessage)
case e: Throwable =>
throw new KafkaException("error processing data for partition [%s,%d] offset %d"
.format(topic, partitionId, currentPartitionFetchState.offset), e)
}
case Errors.OFFSET_OUT_OF_RANGE =>
try {
val newOffset = handleOffsetOutOfRange(topicAndPartition)
partitionMap.put(topicAndPartition, new PartitionFetchState(newOffset))
error("Current offset %d for partition [%s,%d] out of range; reset offset to %d"
.format(currentPartitionFetchState.offset, topic, partitionId, newOffset))
} catch {
case e: Throwable =>
error("Error getting offset for partition [%s,%d] to broker %d".format(topic, partitionId, sourceBroker.id), e)
partitionsWithError += topicAndPartition
}
case _ =>
if (isRunning.get) {
error("Error for partition [%s,%d] to broker %d:%s".format(topic, partitionId, sourceBroker.id,
partitionData.exception.get))
partitionsWithError += topicAndPartition
}
}
})
}
}
}
if (partitionsWithError.nonEmpty) {
debug("handling partitions with error for %s".format(partitionsWithError))
handlePartitionsWithErrors(partitionsWithError)
}
}
def addPartitions(partitionAndOffsets: Map[TopicAndPartition, Long]) {
partitionMapLock.lockInterruptibly()
try {
for ((topicAndPartition, offset) <- partitionAndOffsets) {
// If the partitionMap already has the topic/partition, then do not update the map with the old offset
if (!partitionMap.contains(topicAndPartition))
partitionMap.put(
topicAndPartition,
if (PartitionTopicInfo.isOffsetInvalid(offset)) new PartitionFetchState(handleOffsetOutOfRange(topicAndPartition))
else new PartitionFetchState(offset)
)}
partitionMapCond.signalAll()
} finally partitionMapLock.unlock()
}
def delayPartitions(partitions: Iterable[TopicAndPartition], delay: Long) {
partitionMapLock.lockInterruptibly()
try {
for (partition <- partitions) {
partitionMap.get(partition).foreach (currentPartitionFetchState =>
if (currentPartitionFetchState.isActive)
partitionMap.put(partition, new PartitionFetchState(currentPartitionFetchState.offset, new DelayedItem(delay)))
)
}
partitionMapCond.signalAll()
} finally partitionMapLock.unlock()
}
def removePartitions(topicAndPartitions: Set[TopicAndPartition]) {
partitionMapLock.lockInterruptibly()
try topicAndPartitions.foreach(partitionMap.remove)
finally partitionMapLock.unlock()
}
def partitionCount() = {
partitionMapLock.lockInterruptibly()
try partitionMap.size
finally partitionMapLock.unlock()
}
}
object AbstractFetcherThread {
trait FetchRequest {
def isEmpty: Boolean
def offset(topicAndPartition: TopicAndPartition): Long
}
trait PartitionData {
def errorCode: Short
def exception: Option[Throwable]
def toByteBufferMessageSet: ByteBufferMessageSet
def highWatermark: Long
}
}
class FetcherLagMetrics(metricId: ClientIdTopicPartition) extends KafkaMetricsGroup {
private[this] val lagVal = new AtomicLong(-1L)
newGauge("ConsumerLag",
new Gauge[Long] {
def value = lagVal.get
},
Map("clientId" -> metricId.clientId,
"topic" -> metricId.topic,
"partition" -> metricId.partitionId.toString)
)
def lag_=(newLag: Long) {
lagVal.set(newLag)
}
def lag = lagVal.get
}
class FetcherLagStats(metricId: ClientIdAndBroker) {
private val valueFactory = (k: ClientIdTopicPartition) => new FetcherLagMetrics(k)
val stats = new Pool[ClientIdTopicPartition, FetcherLagMetrics](Some(valueFactory))
def getFetcherLagStats(topic: String, partitionId: Int): FetcherLagMetrics = {
stats.getAndMaybePut(new ClientIdTopicPartition(metricId.clientId, topic, partitionId))
}
}
class FetcherStats(metricId: ClientIdAndBroker) extends KafkaMetricsGroup {
val tags = Map("clientId" -> metricId.clientId,
"brokerHost" -> metricId.brokerHost,
"brokerPort" -> metricId.brokerPort.toString)
val requestRate = newMeter("RequestsPerSec", "requests", TimeUnit.SECONDS, tags)
val byteRate = newMeter("BytesPerSec", "bytes", TimeUnit.SECONDS, tags)
}
case class ClientIdTopicPartition(clientId: String, topic: String, partitionId: Int) {
override def toString = "%s-%s-%d".format(clientId, topic, partitionId)
}
/**
* case class to keep partition offset and its state(active , inactive)
*/
case class PartitionFetchState(offset: Long, delay: DelayedItem) {
def this(offset: Long) = this(offset, new DelayedItem(0))
def isActive: Boolean = { delay.getDelay(TimeUnit.MILLISECONDS) == 0 }
override def toString = "%d-%b".format(offset, isActive)
}
|
Mszak/kafka
|
core/src/main/scala/kafka/server/AbstractFetcherThread.scala
|
Scala
|
apache-2.0
| 12,010 |
package dit4c.scheduler.domain
import akka.persistence.PersistentActor
import akka.actor.ActorLogging
import scala.concurrent.Future
import java.security.interfaces.RSAPublicKey
import dit4c.scheduler.ssh.RemoteShell
import akka.actor.ActorRef
import java.time.Instant
import akka.actor.Props
import dit4c.scheduler.runner.{RktRunner, RktRunnerImpl}
import java.nio.file.Paths
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import akka.util.Timeout
import scala.util.Random
import akka.pattern.ask
object RktClusterManager {
type RktNodeId = String
type InstanceId = String
type HostKeyChecker = (String, Int) => Future[RSAPublicKey]
type RktRunnerFactory =
(RktNode.ServerConnectionDetails, String) => RktRunner
def props(clusterId: String, config: ConfigProvider)(implicit ec: ExecutionContext): Props = {
def rktRunnerFactory(
connectionDetails: RktNode.ServerConnectionDetails,
rktDir: String) = {
new RktRunnerImpl(
RemoteShell(
connectionDetails.host,
connectionDetails.port,
connectionDetails.username,
config.sshKeys,
Future.successful(
connectionDetails.serverKey.public)),
config.rktRunnerConfig)
}
props(clusterId, rktRunnerFactory, RemoteShell.getHostKey)
}
def props(
clusterId: String,
rktRunnerFactory: RktRunnerFactory,
hostKeyChecker: HostKeyChecker): Props =
Props(classOf[RktClusterManager], clusterId, rktRunnerFactory, hostKeyChecker)
case class ClusterInfo(
instanceNodeMappings: Map[InstanceId, RktNodeId] = Map.empty,
nodeIds: Set[RktNodeId] = Set.empty)
trait Command extends ClusterManager.Command
case object Shutdown extends Command
case class AddRktNode(
nodeId: RktNodeId,
host: String,
port: Int,
username: String,
sshHostKeyFingerprints: Seq[String],
rktDir: String) extends Command
protected[domain] case class GetRktNodeState(nodeId: RktNodeId) extends Command
case class CoolDownRktNodes(sshHostKeyFingerprints: Seq[String]) extends Command
case class DecommissionRktNodes(sshHostKeyFingerprints: Seq[String]) extends Command
case class RegisterRktNode(requester: ActorRef) extends Command
case class StartInstance(
instanceId: String, image: String, portalUri: String) extends Command
case class GetInstanceStatus(id: Instance.Id) extends Command
case class InstanceEnvelope(id: Instance.Id, msg: Instance.Command) extends Command
trait Response extends ClusterManager.Response
case class CurrentClusterInfo(clusterInfo: ClusterInfo) extends Response with ClusterManager.GetStatusResponse
case class StartingInstance(instanceId: InstanceId) extends Response
case class UnableToStartInstance(instanceId: InstanceId, msg: String) extends Response
case class UnknownInstance(instanceId: InstanceId) extends Response
case class RktNodeAdded(nodeId: RktNodeId) extends Response
}
class RktClusterManager(
clusterId: String,
rktRunnerFactory: RktClusterManager.RktRunnerFactory,
hostKeyChecker: RktClusterManager.HostKeyChecker)
extends PersistentActor
with ClusterManager
with ActorLogging {
import BaseDomainEvent._
import dit4c.scheduler.domain.rktclustermanager._
import ClusterManager._
import RktClusterManager._
import akka.pattern.{ask, pipe}
lazy val persistenceId = s"RktClusterManager-$clusterId"
protected var state = ClusterInfo()
protected case class PendingOperation(requester: ActorRef, op: Any)
protected var operationsAwaitingInstanceWorkers =
Map.empty[ActorRef, PendingOperation]
override def receiveCommand = {
case GetStatus =>
sender ! CurrentClusterInfo(state)
case AddRktNode(id, host, port, username, fingerprints, rktDir) =>
processNodeCommand(id,
RktNode.Initialize(host, port, username, fingerprints, rktDir))
case GetRktNodeState(id) =>
processNodeCommand(id, RktNode.GetState)
case CoolDownRktNodes(fingerprints) =>
import context.dispatcher
implicit val timeout = Timeout(1.minute)
val hasMatch = hasMatchingFingerprint(fingerprints) _
state.nodeIds
.map(id => (id, getNodeActor(id)))
.foreach { case (id, ref) =>
(ref ? RktNode.GetState)
.map(_.asInstanceOf[RktNode.GetStateResponse])
.onSuccess {
case RktNode.Exists(c) if hasMatch(c.connectionDetails.serverKey) =>
log.info(s"Cooling down node $id - will accept no further instances")
ref ! RktNode.BecomeInactive
}
}
case DecommissionRktNodes(fingerprints) =>
import dit4c.common.KeyHelpers._
import context.dispatcher
implicit val timeout = Timeout(1.minute)
val hasMatch = hasMatchingFingerprint(fingerprints) _
state.nodeIds
.map(id => (id, getNodeActor(id)))
.foreach { case (id, ref) =>
(ref ? RktNode.GetState)
.map(_.asInstanceOf[RktNode.GetStateResponse])
.collect {
case RktNode.Exists(c) if hasMatch(c.connectionDetails.serverKey) =>
log.info(s"Decommissioning node $id")
ref ! RktNode.Decommission
ref
}
.flatMap(_ ? RktNode.GetState)
.onSuccess {
case RktNode.DoesNotExist =>
log.info(s"Updating state for all instances on decommissioned node $id")
state.instanceNodeMappings.collect {
case (instanceId, `id`) =>
(context.self ? GetInstanceStatus(instanceId)).foreach { _ =>
log.debug(s"Triggered state update for $instanceId")
}
}
}
}
case RegisterRktNode(requester) =>
sender.path.name match {
case RktNodePersistenceId(id) =>
persist(RktNodeRegistered(id, now))(updateState)
requester ! RktNodeAdded(id)
}
case Shutdown =>
context.stop(self)
case op: StartInstance =>
log.info("Requesting instance worker from nodes")
val instanceSchedulerRef =
context.actorOf(Props(classOf[RktInstanceScheduler],
op.instanceId,
state.nodeIds.map(id => (id, getNodeActor(id))).toMap,
1.minute,
false),
"instance-scheduler-"+op.instanceId)
operationsAwaitingInstanceWorkers +=
(instanceSchedulerRef -> PendingOperation(sender,op))
case op @ GetInstanceStatus(instanceId) =>
context.child(InstancePersistenceId(instanceId)) match {
case Some(ref) => ref forward Instance.GetStatus
case None =>
if (state.instanceNodeMappings.contains(instanceId)) {
val instanceSchedulerRef =
context.child("instance-scheduler-"+instanceId).getOrElse {
context.actorOf(Props(classOf[RktInstanceScheduler],
instanceId,
state.instanceNodeMappings.get(instanceId).map(id => (id, getNodeActor(id))).toMap,
1.minute,
true),
"instance-scheduler-"+instanceId)
}
operationsAwaitingInstanceWorkers +=
(instanceSchedulerRef -> PendingOperation(sender,op))
} else {
sender ! UnknownInstance(instanceId)
}
}
case InstanceEnvelope(instanceId, msg: Instance.Command) =>
context.child(InstancePersistenceId(instanceId)) match {
case Some(ref) =>
implicit val timeout = Timeout(10.seconds)
import context.dispatcher
ref forward msg
case None => sender ! UnknownInstance(instanceId)
}
case msg: RktInstanceScheduler.Response =>
operationsAwaitingInstanceWorkers.get(sender).foreach {
case PendingOperation(requester, StartInstance(instanceId, image, portalUri)) =>
import RktInstanceScheduler._
msg match {
case WorkerFound(nodeId, worker) =>
implicit val timeout = Timeout(10.seconds)
import context.dispatcher
persist(InstanceAssignedToNode(instanceId, nodeId, now))(updateState)
val instance = context.actorOf(
Instance.props(worker),
InstancePersistenceId(instanceId))
// Request start, wait for acknowledgement,
(instance ? Instance.Initiate(instanceId, image, portalUri))
.collect { case Instance.Ack => StartingInstance(instanceId) }
.pipeTo(requester)
case NoWorkersAvailable =>
requester ! UnableToStartInstance(instanceId, "No compute nodes available")
}
case PendingOperation(requester, GetInstanceStatus(instanceId)) =>
import RktInstanceScheduler._
msg match {
case WorkerFound(nodeId, worker) =>
implicit val timeout = Timeout(10.seconds)
import context.dispatcher
val instance = context.actorOf(
Instance.props(worker),
InstancePersistenceId(instanceId))
instance.tell(Instance.GetStatus, requester)
case NoWorkersAvailable =>
requester ! UnknownInstance(instanceId)
}
}
operationsAwaitingInstanceWorkers -= sender
}
override def receiveRecover: PartialFunction[Any,Unit] = {
case e: DomainEvent => updateState(e)
}
protected def updateState(e: DomainEvent): Unit = e match {
case RktNodeRegistered(nodeId, _) =>
state = state.copy(nodeIds = state.nodeIds + nodeId)
case InstanceAssignedToNode(instanceId, nodeId, _) =>
state = state.copy(instanceNodeMappings =
state.instanceNodeMappings + (instanceId -> nodeId))
}
object RktNodePersistenceId extends ChildPersistenceId("RktNode")
def processNodeCommand(nodeId: String, command: Any) =
getNodeActor(nodeId) forward command
protected def getNodeActor(nodeId: String): ActorRef =
context.child(RktNodePersistenceId(nodeId))
.getOrElse(createNodeActor(nodeId))
protected def createNodeActor(nodeId: String): ActorRef = {
val node = context.actorOf(
RktNode.props(rktRunnerFactory, hostKeyChecker),
RktNodePersistenceId(nodeId))
context.watch(node)
node
}
private def hasMatchingFingerprint(fingerprints: Seq[String])(serverKey: RktNode.ServerPublicKey) = {
import dit4c.common.KeyHelpers._
fingerprints.contains(serverKey.public.ssh.fingerprint("SHA-256")) ||
fingerprints.contains(serverKey.public.ssh.fingerprint("MD5"))
}
}
|
dit4c/dit4c
|
dit4c-scheduler/src/main/scala/dit4c/scheduler/domain/RktClusterManager.scala
|
Scala
|
mit
| 10,748 |
/*
* Copyright (C) 2007-2008 Artima, Inc. All rights reserved.
*
* 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.
*
* Example code from:
*
* Programming in Scala (First Edition, Version 6)
* by Martin Odersky, Lex Spoon, Bill Venners
*
* http://booksites.artima.com/programming_in_scala
*/
package scells
trait Arithmetic { self: Evaluator =>
operations += (
"add" -> { case List(x, y) => x + y },
"sub" -> { case List(x, y) => x - y },
"div" -> { case List(x, y) => x / y },
"mul" -> { case List(x, y) => x * y },
"mod" -> { case List(x, y) => x % y },
"sum" -> { xs => (0.0 /: xs)(_ + _) },
"prod" -> { xs => (1.0 /: xs)(_ * _) }
)
}
|
peachyy/scalastu
|
scells/src/scells/Arithmetic.scala
|
Scala
|
apache-2.0
| 1,194 |
package test
import Dependency.TopologySorter
import org.scalatest.{FlatSpec, Matchers}
import scalax.collection.GraphEdge.DiEdge
class TopologySorterTests extends FlatSpec with Matchers {
it should "Sort numbers" in {
val pairs = Seq(
(1, 2),
(2, 3),
(3, 4),
(4, 5),
(5, 6),
(6, 7),
(0, 7),
(1, 6))
val edges = pairs.map(x => new DiEdge[Int](x._1, x._2))
val topology = TopologySorter.topologicalSortDeCycle(edges.toList) match {
case topology: List[Int] =>
topology
}
topology should contain theSameElementsInOrderAs Seq(1, 0, 2, 3, 4, 5, 6, 7)
for (pair <- pairs) topology should contain inOrder(pair._1, pair._2)
for (byDependency <- pairs.groupBy(_._1)) topology should contain inOrderElementsOf byDependency._2.map(_._2)
}
it should "Handle cycles gracefully" in {
val pairs = Seq(
(1, 2),
(2, 7),
(7, 1),
(8, 7))
val edges = pairs.map(x => new DiEdge[Int](x._1, x._2))
val topology = TopologySorter.topologicalSortDeCycle(edges.toList) match {
case topology: List[Int] => topology
}
//topology should contain theSameElementsInOrderAs Seq(1, 0, 2, 3, 4, 5, 6, 7)
for (pair <- pairs if pair != (7, 1)) topology should contain inOrder(pair._1, pair._2)
for (byDependency <- pairs.filter(x => x != (7, 1)).groupBy(_._1)) topology should contain inOrderElementsOf byDependency._2.map(_._2)
}
it should "Sort strings" in {
val pairs = Seq(
("forge", "minecraft"),
("minecraft", "opencl"),
("minecraft", "opengl"),
("ae2", "forge"),
("ae2-industrial", "ae2"),
("ae2-industrial", "ic2"),
("ae2-industrial", "railcraft"),
("ic2", "forge"),
("railcraft", "forge"),
("railcraft-addons", "railcraft"))
val edges = pairs.map(x => new DiEdge[String](x._1, x._2))
val topology = TopologySorter.topologicalSortDeCycle(edges.toList)
for (pair <- pairs) topology should contain inOrder(pair._1, pair._2)
for (byDependency <- pairs.groupBy(_._1)) topology should contain inOrderElementsOf byDependency._2.map(_._2)
for (byDependency <- pairs.groupBy(_._1)) topology should contain inOrderElementsOf byDependency._2.map(_._2)
}
}
|
DSTech/MPM
|
src/test/scala-2.12/test/TopologySorterTests.scala
|
Scala
|
mit
| 2,267 |
trait SomeTrait
trait CollBase[A <: SomeTrait, +CC1[A2 <: SomeTrait]] {
val companion: CollCompanion[CC1]
}
trait Coll[A <: SomeTrait] extends CollBase[A, Coll]
trait CollCompanion[+CC2[A <: SomeTrait]]
|
dotty-staging/dotty
|
tests/pos/i10967.scala
|
Scala
|
apache-2.0
| 207 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.deploy.yarn
import java.io.File
import java.net.URL
import java.nio.charset.StandardCharsets
import java.util.{HashMap => JHashMap}
import scala.collection.mutable
import scala.concurrent.duration._
import scala.io.Source
import scala.language.postfixOps
import com.google.common.io.{ByteStreams, Files}
import org.apache.hadoop.yarn.conf.YarnConfiguration
import org.scalatest.Matchers
import org.scalatest.concurrent.Eventually._
import org.apache.spark._
import org.apache.spark.deploy.SparkHadoopUtil
import org.apache.spark.deploy.yarn.config._
import org.apache.spark.internal.Logging
import org.apache.spark.launcher._
import org.apache.spark.scheduler.{SparkListener, SparkListenerApplicationStart,
SparkListenerExecutorAdded}
import org.apache.spark.scheduler.cluster.ExecutorInfo
import org.apache.spark.tags.ExtendedYarnTest
import org.apache.spark.util.Utils
/**
* Integration tests for YARN; these tests use a mini Yarn cluster to run Spark-on-YARN
* applications.
*/
@ExtendedYarnTest
class YarnClusterSuite extends BaseYarnClusterSuite {
override def newYarnConfig(): YarnConfiguration = new YarnConfiguration()
private val TEST_PYFILE = """
|import mod1, mod2
|import sys
|from operator import add
|
|from pyspark import SparkConf , SparkContext
|if __name__ == "__main__":
| if len(sys.argv) != 2:
| print >> sys.stderr, "Usage: test.py [result file]"
| exit(-1)
| sc = SparkContext(conf=SparkConf())
| status = open(sys.argv[1],'w')
| result = "failure"
| rdd = sc.parallelize(range(10)).map(lambda x: x * mod1.func() * mod2.func())
| cnt = rdd.count()
| if cnt == 10:
| result = "success"
| status.write(result)
| status.close()
| sc.stop()
""".stripMargin
private val TEST_PYMODULE = """
|def func():
| return 42
""".stripMargin
test("run Spark in yarn-client mode") {
testBasicYarnApp(true)
}
test("run Spark in yarn-cluster mode") {
testBasicYarnApp(false)
}
test("run Spark in yarn-client mode with different configurations, ensuring redaction") {
testBasicYarnApp(true,
Map(
"spark.driver.memory" -> "512m",
"spark.executor.cores" -> "1",
"spark.executor.memory" -> "512m",
"spark.executor.instances" -> "2",
// Sending some sensitive information, which we'll make sure gets redacted
"spark.executorEnv.HADOOP_CREDSTORE_PASSWORD" -> YarnClusterDriver.SECRET_PASSWORD,
"spark.yarn.appMasterEnv.HADOOP_CREDSTORE_PASSWORD" -> YarnClusterDriver.SECRET_PASSWORD
))
}
test("run Spark in yarn-cluster mode with different configurations, ensuring redaction") {
testBasicYarnApp(false,
Map(
"spark.driver.memory" -> "512m",
"spark.driver.cores" -> "1",
"spark.executor.cores" -> "1",
"spark.executor.memory" -> "512m",
"spark.executor.instances" -> "2",
// Sending some sensitive information, which we'll make sure gets redacted
"spark.executorEnv.HADOOP_CREDSTORE_PASSWORD" -> YarnClusterDriver.SECRET_PASSWORD,
"spark.yarn.appMasterEnv.HADOOP_CREDSTORE_PASSWORD" -> YarnClusterDriver.SECRET_PASSWORD
))
}
test("yarn-cluster should respect conf overrides in SparkHadoopUtil (SPARK-16414, SPARK-23630)") {
// Create a custom hadoop config file, to make sure it's contents are propagated to the driver.
val customConf = Utils.createTempDir()
val coreSite = """<?xml version="1.0" encoding="UTF-8"?>
|<configuration>
| <property>
| <name>spark.test.key</name>
| <value>testvalue</value>
| </property>
|</configuration>
|""".stripMargin
Files.write(coreSite, new File(customConf, "core-site.xml"), StandardCharsets.UTF_8)
val result = File.createTempFile("result", null, tempDir)
val finalState = runSpark(false,
mainClassName(YarnClusterDriverUseSparkHadoopUtilConf.getClass),
appArgs = Seq("key=value", "spark.test.key=testvalue", result.getAbsolutePath()),
extraConf = Map("spark.hadoop.key" -> "value"),
extraEnv = Map("SPARK_TEST_HADOOP_CONF_DIR" -> customConf.getAbsolutePath()))
checkResult(finalState, result)
}
test("run Spark in yarn-client mode with additional jar") {
testWithAddJar(true)
}
test("run Spark in yarn-cluster mode with additional jar") {
testWithAddJar(false)
}
test("run Spark in yarn-cluster mode unsuccessfully") {
// Don't provide arguments so the driver will fail.
val finalState = runSpark(false, mainClassName(YarnClusterDriver.getClass))
finalState should be (SparkAppHandle.State.FAILED)
}
test("run Spark in yarn-cluster mode failure after sc initialized") {
val finalState = runSpark(false, mainClassName(YarnClusterDriverWithFailure.getClass))
finalState should be (SparkAppHandle.State.FAILED)
}
test("run Python application in yarn-client mode") {
testPySpark(true)
}
test("run Python application in yarn-cluster mode") {
testPySpark(false)
}
test("run Python application in yarn-cluster mode using " +
"spark.yarn.appMasterEnv to override local envvar") {
testPySpark(
clientMode = false,
extraConf = Map(
"spark.yarn.appMasterEnv.PYSPARK_DRIVER_PYTHON"
-> sys.env.getOrElse("PYSPARK_DRIVER_PYTHON", "python"),
"spark.yarn.appMasterEnv.PYSPARK_PYTHON"
-> sys.env.getOrElse("PYSPARK_PYTHON", "python")),
extraEnv = Map(
"PYSPARK_DRIVER_PYTHON" -> "not python",
"PYSPARK_PYTHON" -> "not python"))
}
test("user class path first in client mode") {
testUseClassPathFirst(true)
}
test("user class path first in cluster mode") {
testUseClassPathFirst(false)
}
test("monitor app using launcher library") {
val env = new JHashMap[String, String]()
env.put("YARN_CONF_DIR", hadoopConfDir.getAbsolutePath())
val propsFile = createConfFile()
val handle = new SparkLauncher(env)
.setSparkHome(sys.props("spark.test.home"))
.setConf("spark.ui.enabled", "false")
.setPropertiesFile(propsFile)
.setMaster("yarn")
.setDeployMode("client")
.setAppResource(SparkLauncher.NO_RESOURCE)
.setMainClass(mainClassName(YarnLauncherTestApp.getClass))
.startApplication()
try {
eventually(timeout(30 seconds), interval(100 millis)) {
handle.getState() should be (SparkAppHandle.State.RUNNING)
}
handle.getAppId() should not be (null)
handle.getAppId() should startWith ("application_")
handle.stop()
eventually(timeout(30 seconds), interval(100 millis)) {
handle.getState() should be (SparkAppHandle.State.KILLED)
}
} finally {
handle.kill()
}
}
test("timeout to get SparkContext in cluster mode triggers failure") {
val timeout = 2000
val finalState = runSpark(false, mainClassName(SparkContextTimeoutApp.getClass),
appArgs = Seq((timeout * 4).toString),
extraConf = Map(AM_MAX_WAIT_TIME.key -> timeout.toString))
finalState should be (SparkAppHandle.State.FAILED)
}
test("executor env overwrite AM env in client mode") {
testExecutorEnv(true)
}
test("executor env overwrite AM env in cluster mode") {
testExecutorEnv(false)
}
private def testBasicYarnApp(clientMode: Boolean, conf: Map[String, String] = Map()): Unit = {
val result = File.createTempFile("result", null, tempDir)
val finalState = runSpark(clientMode, mainClassName(YarnClusterDriver.getClass),
appArgs = Seq(result.getAbsolutePath()),
extraConf = conf)
checkResult(finalState, result)
}
private def testWithAddJar(clientMode: Boolean): Unit = {
val originalJar = TestUtils.createJarWithFiles(Map("test.resource" -> "ORIGINAL"), tempDir)
val driverResult = File.createTempFile("driver", null, tempDir)
val executorResult = File.createTempFile("executor", null, tempDir)
val finalState = runSpark(clientMode, mainClassName(YarnClasspathTest.getClass),
appArgs = Seq(driverResult.getAbsolutePath(), executorResult.getAbsolutePath()),
extraClassPath = Seq(originalJar.getPath()),
extraJars = Seq("local:" + originalJar.getPath()))
checkResult(finalState, driverResult, "ORIGINAL")
checkResult(finalState, executorResult, "ORIGINAL")
}
private def testPySpark(
clientMode: Boolean,
extraConf: Map[String, String] = Map(),
extraEnv: Map[String, String] = Map()): Unit = {
val primaryPyFile = new File(tempDir, "test.py")
Files.write(TEST_PYFILE, primaryPyFile, StandardCharsets.UTF_8)
// When running tests, let's not assume the user has built the assembly module, which also
// creates the pyspark archive. Instead, let's use PYSPARK_ARCHIVES_PATH to point at the
// needed locations.
val sparkHome = sys.props("spark.test.home")
val pythonPath = Seq(
s"$sparkHome/python/lib/py4j-0.10.8.1-src.zip",
s"$sparkHome/python")
val extraEnvVars = Map(
"PYSPARK_ARCHIVES_PATH" -> pythonPath.map("local:" + _).mkString(File.pathSeparator),
"PYTHONPATH" -> pythonPath.mkString(File.pathSeparator)) ++ extraEnv
val moduleDir = {
val subdir = new File(tempDir, "pyModules")
subdir.mkdir()
subdir
}
val pyModule = new File(moduleDir, "mod1.py")
Files.write(TEST_PYMODULE, pyModule, StandardCharsets.UTF_8)
val mod2Archive = TestUtils.createJarWithFiles(Map("mod2.py" -> TEST_PYMODULE), moduleDir)
val pyFiles = Seq(pyModule.getAbsolutePath(), mod2Archive.getPath()).mkString(",")
val result = File.createTempFile("result", null, tempDir)
val outFile = Some(File.createTempFile("stdout", null, tempDir))
val finalState = runSpark(clientMode, primaryPyFile.getAbsolutePath(),
sparkArgs = Seq("--py-files" -> pyFiles),
appArgs = Seq(result.getAbsolutePath()),
extraEnv = extraEnvVars,
extraConf = extraConf,
outFile = outFile)
checkResult(finalState, result, outFile = outFile)
}
private def testUseClassPathFirst(clientMode: Boolean): Unit = {
// Create a jar file that contains a different version of "test.resource".
val originalJar = TestUtils.createJarWithFiles(Map("test.resource" -> "ORIGINAL"), tempDir)
val userJar = TestUtils.createJarWithFiles(Map("test.resource" -> "OVERRIDDEN"), tempDir)
val driverResult = File.createTempFile("driver", null, tempDir)
val executorResult = File.createTempFile("executor", null, tempDir)
val finalState = runSpark(clientMode, mainClassName(YarnClasspathTest.getClass),
appArgs = Seq(driverResult.getAbsolutePath(), executorResult.getAbsolutePath()),
extraClassPath = Seq(originalJar.getPath()),
extraJars = Seq("local:" + userJar.getPath()),
extraConf = Map(
"spark.driver.userClassPathFirst" -> "true",
"spark.executor.userClassPathFirst" -> "true"))
checkResult(finalState, driverResult, "OVERRIDDEN")
checkResult(finalState, executorResult, "OVERRIDDEN")
}
private def testExecutorEnv(clientMode: Boolean): Unit = {
val result = File.createTempFile("result", null, tempDir)
val finalState = runSpark(clientMode, mainClassName(ExecutorEnvTestApp.getClass),
appArgs = Seq(result.getAbsolutePath),
extraConf = Map(
"spark.yarn.appMasterEnv.TEST_ENV" -> "am_val",
"spark.executorEnv.TEST_ENV" -> "executor_val"
)
)
checkResult(finalState, result, "true")
}
}
private[spark] class SaveExecutorInfo extends SparkListener {
val addedExecutorInfos = mutable.Map[String, ExecutorInfo]()
var driverLogs: Option[collection.Map[String, String]] = None
override def onExecutorAdded(executor: SparkListenerExecutorAdded) {
addedExecutorInfos(executor.executorId) = executor.executorInfo
}
override def onApplicationStart(appStart: SparkListenerApplicationStart): Unit = {
driverLogs = appStart.driverLogs
}
}
private object YarnClusterDriverWithFailure extends Logging with Matchers {
def main(args: Array[String]): Unit = {
val sc = new SparkContext(new SparkConf()
.set("spark.extraListeners", classOf[SaveExecutorInfo].getName)
.setAppName("yarn test with failure"))
throw new Exception("exception after sc initialized")
}
}
private object YarnClusterDriverUseSparkHadoopUtilConf extends Logging with Matchers {
def main(args: Array[String]): Unit = {
if (args.length < 2) {
// scalastyle:off println
System.err.println(
s"""
|Invalid command line: ${args.mkString(" ")}
|
|Usage: YarnClusterDriverUseSparkHadoopUtilConf [hadoopConfKey=value]+ [result file]
""".stripMargin)
// scalastyle:on println
System.exit(1)
}
val sc = new SparkContext(new SparkConf()
.set("spark.extraListeners", classOf[SaveExecutorInfo].getName)
.setAppName("yarn test using SparkHadoopUtil's conf"))
val kvs = args.take(args.length - 1).map { kv =>
val parsed = kv.split("=")
(parsed(0), parsed(1))
}
val status = new File(args.last)
var result = "failure"
try {
kvs.foreach { case (k, v) =>
SparkHadoopUtil.get.conf.get(k) should be (v)
}
result = "success"
} finally {
Files.write(result, status, StandardCharsets.UTF_8)
sc.stop()
}
}
}
private object YarnClusterDriver extends Logging with Matchers {
val WAIT_TIMEOUT_MILLIS = 10000
val SECRET_PASSWORD = "secret_password"
def main(args: Array[String]): Unit = {
if (args.length != 1) {
// scalastyle:off println
System.err.println(
s"""
|Invalid command line: ${args.mkString(" ")}
|
|Usage: YarnClusterDriver [result file]
""".stripMargin)
// scalastyle:on println
System.exit(1)
}
val sc = new SparkContext(new SparkConf()
.set("spark.extraListeners", classOf[SaveExecutorInfo].getName)
.setAppName("yarn \"test app\" 'with quotes' and \\back\\slashes and $dollarSigns"))
val conf = sc.getConf
val status = new File(args(0))
var result = "failure"
try {
val data = sc.parallelize(1 to 4, 4).collect().toSet
sc.listenerBus.waitUntilEmpty(WAIT_TIMEOUT_MILLIS)
data should be (Set(1, 2, 3, 4))
result = "success"
// Verify that the config archive is correctly placed in the classpath of all containers.
val confFile = "/" + Client.SPARK_CONF_FILE
if (conf.getOption(SparkLauncher.DEPLOY_MODE) == Some("cluster")) {
assert(getClass().getResource(confFile) != null)
}
val configFromExecutors = sc.parallelize(1 to 4, 4)
.map { _ => Option(getClass().getResource(confFile)).map(_.toString).orNull }
.collect()
assert(configFromExecutors.find(_ == null) === None)
// verify log urls are present
val listeners = sc.listenerBus.findListenersByClass[SaveExecutorInfo]
assert(listeners.size === 1)
val listener = listeners(0)
val executorInfos = listener.addedExecutorInfos.values
assert(executorInfos.nonEmpty)
executorInfos.foreach { info =>
assert(info.logUrlMap.nonEmpty)
info.logUrlMap.values.foreach { url =>
val log = Source.fromURL(url).mkString
assert(
!log.contains(SECRET_PASSWORD),
s"Executor logs contain sensitive info (${SECRET_PASSWORD}): \n${log} "
)
}
}
// If we are running in yarn-cluster mode, verify that driver logs links and present and are
// in the expected format.
if (conf.get("spark.submit.deployMode") == "cluster") {
assert(listener.driverLogs.nonEmpty)
val driverLogs = listener.driverLogs.get
assert(driverLogs.size === 2)
assert(driverLogs.contains("stderr"))
assert(driverLogs.contains("stdout"))
val urlStr = driverLogs("stderr")
driverLogs.foreach { kv =>
val log = Source.fromURL(kv._2).mkString
assert(
!log.contains(SECRET_PASSWORD),
s"Driver logs contain sensitive info (${SECRET_PASSWORD}): \n${log} "
)
}
val containerId = YarnSparkHadoopUtil.getContainerId
val user = Utils.getCurrentUserName()
assert(urlStr.endsWith(s"/node/containerlogs/$containerId/$user/stderr?start=-4096"))
}
} finally {
Files.write(result, status, StandardCharsets.UTF_8)
sc.stop()
}
}
}
private object YarnClasspathTest extends Logging {
def error(m: String, ex: Throwable = null): Unit = {
logError(m, ex)
// scalastyle:off println
System.out.println(m)
if (ex != null) {
ex.printStackTrace(System.out)
}
// scalastyle:on println
}
def main(args: Array[String]): Unit = {
if (args.length != 2) {
error(
s"""
|Invalid command line: ${args.mkString(" ")}
|
|Usage: YarnClasspathTest [driver result file] [executor result file]
""".stripMargin)
// scalastyle:on println
}
readResource(args(0))
val sc = new SparkContext(new SparkConf())
try {
sc.parallelize(Seq(1)).foreach { x => readResource(args(1)) }
} finally {
sc.stop()
}
}
private def readResource(resultPath: String): Unit = {
var result = "failure"
try {
val ccl = Thread.currentThread().getContextClassLoader()
val resource = ccl.getResourceAsStream("test.resource")
val bytes = ByteStreams.toByteArray(resource)
result = new String(bytes, 0, bytes.length, StandardCharsets.UTF_8)
} catch {
case t: Throwable =>
error(s"loading test.resource to $resultPath", t)
} finally {
Files.write(result, new File(resultPath), StandardCharsets.UTF_8)
}
}
}
private object YarnLauncherTestApp {
def main(args: Array[String]): Unit = {
// Do not stop the application; the test will stop it using the launcher lib. Just run a task
// that will prevent the process from exiting.
val sc = new SparkContext(new SparkConf())
sc.parallelize(Seq(1)).foreach { i =>
this.synchronized {
wait()
}
}
}
}
/**
* Used to test code in the AM that detects the SparkContext instance. Expects a single argument
* with the duration to sleep for, in ms.
*/
private object SparkContextTimeoutApp {
def main(args: Array[String]): Unit = {
val Array(sleepTime) = args
Thread.sleep(java.lang.Long.parseLong(sleepTime))
}
}
private object ExecutorEnvTestApp {
def main(args: Array[String]): Unit = {
val status = args(0)
val sparkConf = new SparkConf()
val sc = new SparkContext(sparkConf)
val executorEnvs = sc.parallelize(Seq(1)).flatMap { _ => sys.env }.collect().toMap
val result = sparkConf.getExecutorEnv.forall { case (k, v) =>
executorEnvs.get(k).contains(v)
}
Files.write(result.toString, new File(status), StandardCharsets.UTF_8)
sc.stop()
}
}
|
guoxiaolongzte/spark
|
resource-managers/yarn/src/test/scala/org/apache/spark/deploy/yarn/YarnClusterSuite.scala
|
Scala
|
apache-2.0
| 19,907 |
package services.onlinetesting.phase1
import config.{ Phase1TestsConfig, PsiTestIds }
import factories.UUIDFactory
import model.ApplicationRoute.ApplicationRoute
import model.ApplicationStatus.ApplicationStatus
import model.EvaluationResults.Result
import model.ProgressStatuses.ProgressStatus
import model.exchange.passmarksettings.{ PassMarkThreshold, Phase1PassMark, Phase1PassMarkSettings, Phase1PassMarkThresholds }
import model.persisted.{ ApplicationReadyForEvaluation, PassmarkEvaluation, SchemeEvaluationResult }
import model.{ ApplicationRoute, ApplicationStatus, SchemeId }
import org.joda.time.DateTime
import org.mockito.Mockito.when
import org.scalatest.prop.{ TableDrivenPropertyChecks, TableFor9 }
import reactivemongo.bson.BSONDocument
import reactivemongo.play.json.ImplicitBSONHandlers
import reactivemongo.play.json.collection.JSONCollection
import repositories.{ CollectionNames, CommonRepository }
import testkit.MongoRepositorySpec
import scala.concurrent.Future
trait Phase1TestEvaluationSpec extends MongoRepositorySpec with CommonRepository
with TableDrivenPropertyChecks {
import ImplicitBSONHandlers._
val collectionName: String = CollectionNames.APPLICATION
override val additionalCollections = List(CollectionNames.PHASE1_PASS_MARK_SETTINGS)
def phase1TestEvaluationService = {
when(mockAppConfig.onlineTestsGatewayConfig).thenReturn(mockOnlineTestsGatewayConfig)
def testIds(idx: Int): PsiTestIds =
PsiTestIds(s"inventoryId$idx", s"assessmentId$idx", s"reportId$idx", s"normId$idx")
val tests = Map[String, PsiTestIds](
"test1" -> testIds(1),
"test2" -> testIds(2),
"test3" -> testIds(3),
"test4" -> testIds(4)
)
val mockPhase1TestsConfig: Phase1TestsConfig = mock[Phase1TestsConfig]
when(mockOnlineTestsGatewayConfig.phase1Tests).thenReturn(mockPhase1TestsConfig)
when(mockPhase1TestsConfig.tests).thenReturn(tests)
when(mockPhase1TestsConfig.gis).thenReturn(List("test1", "test4"))
when(mockPhase1TestsConfig.standard).thenReturn(List("test1", "test2", "test3", "test4"))
new EvaluatePhase1ResultService(
phase1EvaluationRepo,
phase1PassMarkSettingRepo,
mockAppConfig,
UUIDFactory
)
}
trait TestFixture {
// format: OFF
//scalastyle:off
val phase1PassMarkSettingsTable = Table[SchemeId, Double, Double, Double, Double, Double, Double, Double, Double](
("Scheme Name", "Test1 Fail", "Test1 Pass", "Test2 Fail", "Test2 Pass", "Test3 Fail", "Test3 Pass", "Test4 Fail", "Test4 Pass"),
(SchemeId("Commercial"), 20.0, 80.0, 30.0, 70.0, 30.0, 70.0, 20.0, 70.0),
(SchemeId("DigitalDataTechnologyAndCyber"), 20.001, 20.001, 20.01, 20.05, 19.0, 20.0, 19.0, 20.0),
(SchemeId("DiplomaticAndDevelopment"), 20.01, 20.02, 20.01, 20.02, 20.0, 80.0, 20.0, 80.0),
(SchemeId("DiplomaticAndDevelopmentEconomics"), 30.0, 70.0, 30.0, 70.0, 30.0, 70.0, 30.0, 70.0),
(SchemeId("DiplomaticServiceEuropean"), 30.0, 70.0, 30.0, 70.0, 30.0, 70.0, 30.0, 70.0),
(SchemeId("European"), 40.0, 70.0, 30.0, 70.0, 30.0, 70.0, 30.0, 70.0),
(SchemeId("Finance"), 25.01, 25.02, 25.01, 25.02, 25.01, 25.02, 25.01, 25.02),
(SchemeId("Generalist"), 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0),
(SchemeId("GovernmentCommunicationService"), 30.0, 70.0, 30.0, 70.0, 20.0, 80.0, 20.0, 80.0),
(SchemeId("GovernmentEconomicsService"), 30.0, 70.0, 30.0, 70.0, 20.0, 80.0, 20.0, 80.0),
(SchemeId("GovernmentOperationalResearchService"), 30.0, 70.0, 30.0, 70.0, 20.0, 80.0, 20.0, 80.0),
(SchemeId("GovernmentSocialResearchService"), 30.0, 70.0, 30.0, 70.0, 20.0, 80.0, 20.0, 80.0),
(SchemeId("GovernmentStatisticalService"), 30.0, 70.0, 30.0, 70.0, 20.0, 80.0, 20.0, 80.0),
(SchemeId("HousesOfParliament"), 30.0, 79.999, 30.0, 78.08, 20.0, 77.77, 20.0, 76.66),
(SchemeId("HumanResources"), 30.0, 70.0, 30.0, 70.0, 20.0, 80.0, 20.0, 80.0),
(SchemeId("ProjectDelivery"), 30.0, 70.0, 30.0, 70.0, 20.0, 80.0, 20.0, 80.0),
(SchemeId("ScienceAndEngineering"), 69.00, 69.00, 78.99, 78.99, 20.0, 80.0, 20.0, 80.0)
)
//scalastyle:on
// format: ON
val phase1PassMarkSettingWithSdipTable =
getPassMarkSettingWithNewSettings(
phase1PassMarkSettingsTable, (SchemeId("Finance"), 90.00, 90.00, 90.00, 90.00, 90.00, 90.00, 90.00, 90.00)
)
var phase1PassMarkSettings: Phase1PassMarkSettings = _
var applicationReadyForEvaluation: ApplicationReadyForEvaluation = _
var passMarkEvaluation: PassmarkEvaluation = _
def gisApplicationEvaluation(applicationId:String, t1Score: Double, t4Score: Double, selectedSchemes: SchemeId*): TestFixture = {
applicationReadyForEvaluation = insertApplicationWithPhase1TestResults2(
applicationId, t1Score, None, None, t4Score, isGis = true)(selectedSchemes: _*)
phase1TestEvaluationService.evaluate(applicationReadyForEvaluation, phase1PassMarkSettings).futureValue
this
}
def applicationEvaluationWithPassMarks(passmarks: Phase1PassMarkSettings, applicationId:String,
t1Score: Double, t2Score: Double,
t3Score: Double, t4Score: Double, selectedSchemes: SchemeId*)(
implicit applicationRoute: ApplicationRoute = ApplicationRoute.Faststream): TestFixture = {
applicationReadyForEvaluation = insertApplicationWithPhase1TestResults2(
applicationId, t1Score, Some(t2Score), Some(t3Score), t4Score, applicationRoute = applicationRoute)(selectedSchemes: _*)
phase1TestEvaluationService.evaluate(applicationReadyForEvaluation, passmarks).futureValue
this
}
def applicationEvaluation(applicationId: String, t1Score: Double, t2Score: Double,
t3Score: Double, t4Score: Double, selectedSchemes: SchemeId*)
(implicit applicationRoute: ApplicationRoute = ApplicationRoute.Faststream): TestFixture = {
applicationEvaluationWithPassMarks(phase1PassMarkSettings, applicationId, t1Score, t2Score, t3Score, t4Score, selectedSchemes:_*)
}
def mustResultIn(expApplicationStatus: ApplicationStatus, expProgressStatus: Option[ProgressStatus],
expSchemeResults: (SchemeId , Result)*): TestFixture = {
passMarkEvaluation = phase1EvaluationRepo.getPassMarkEvaluation(applicationReadyForEvaluation.applicationId).futureValue
val applicationDetails = applicationRepository.findStatus(applicationReadyForEvaluation.applicationId).futureValue
val applicationStatus = ApplicationStatus.withName(applicationDetails.status)
val progressStatus = applicationDetails.latestProgressStatus
val schemeResults = passMarkEvaluation.result.map {
SchemeEvaluationResult.unapply(_).map {
case (schemeType, resultStr) => schemeType -> Result(resultStr)
}.get
}
phase1PassMarkSettings.version mustBe passMarkEvaluation.passmarkVersion
applicationStatus mustBe expApplicationStatus
progressStatus mustBe expProgressStatus
schemeResults.size mustBe expSchemeResults.size
schemeResults must contain theSameElementsAs expSchemeResults
applicationReadyForEvaluation = applicationReadyForEvaluation.copy(applicationStatus = expApplicationStatus)
this
}
def getPassMarkSettingWithNewSettings(
phase1PassMarkSettingsTable: TableFor9[SchemeId,
Double, Double, Double, Double, Double, Double, Double, Double],
newSchemeSettings: (SchemeId, Double, Double, Double, Double, Double, Double, Double, Double)*) = {
phase1PassMarkSettingsTable.filterNot(schemeSetting =>
newSchemeSettings.map(_._1).contains(schemeSetting._1)) ++ newSchemeSettings
}
def applicationReEvaluationWithOverridingPassmarks(newSchemeSettings: (SchemeId, Double, Double, Double, Double,
Double, Double, Double, Double)*): TestFixture = {
val schemePassMarkSettings = getPassMarkSettingWithNewSettings(phase1PassMarkSettingsTable, newSchemeSettings:_*)
phase1PassMarkSettings = createPhase1PassMarkSettings(schemePassMarkSettings).futureValue
phase1TestEvaluationService.evaluate(applicationReadyForEvaluation, phase1PassMarkSettings).futureValue
this
}
def createPhase1PassMarkSettings(phase1PassMarkSettingsTable: TableFor9[SchemeId, Double, Double, Double, Double,
Double, Double, Double, Double]): Future[Phase1PassMarkSettings] = {
val schemeThresholds = phase1PassMarkSettingsTable.map {
case (schemeName, t1Fail, t1Pass, t2Fail, t2Pass, t3Fail, t3Pass, t4Fail, t4Pass) =>
Phase1PassMark(schemeName,
Phase1PassMarkThresholds(
PassMarkThreshold(t1Fail, t1Pass),
PassMarkThreshold(t2Fail, t2Pass),
PassMarkThreshold(t3Fail, t3Pass),
PassMarkThreshold(t4Fail, t4Pass)
))
}.toList
val phase1PassMarkSettings = Phase1PassMarkSettings(
schemeThresholds,
"version-1",
DateTime.now,
"user-1"
)
phase1PassMarkSettingRepo.create(phase1PassMarkSettings).flatMap { _ =>
phase1PassMarkSettingRepo.getLatestVersion.map(_.get)
}
}
val appCollection = mongo.mongoConnector.db().collection[JSONCollection](collectionName)
def createUser(userId: String, appId: String) = {
appCollection.insert(ordered = false).one(BSONDocument("applicationId" -> appId, "userId" -> userId,
"applicationStatus" -> ApplicationStatus.CREATED))
}
Future.sequence(List(
createUser("user-1", "application-1"),
createUser("user-2", "application-2"),
createUser("user-3", "application-3"),
createPhase1PassMarkSettings(phase1PassMarkSettingsTable).map(phase1PassMarkSettings = _)
)).futureValue
}
}
|
hmrc/fset-faststream
|
it/services/onlinetesting/phase1/Phase1TestEvaluationSpec.scala
|
Scala
|
apache-2.0
| 11,254 |
package com.twitter.finatra
package object conversions {
@deprecated("Use com.twitter.finatra.http.conversions.futureHttp", "")
val futureHttp = com.twitter.finatra.http.conversions.futureHttp
@deprecated("Use com.twitter.finatra.http.conversions.optionHttp", "")
val optionHttp = com.twitter.finatra.http.conversions.optionHttp
}
|
tom-chan/finatra
|
http/src/main/scala/com/twitter/finatra/conversions/package.scala
|
Scala
|
apache-2.0
| 341 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.ml.clustering
import org.apache.spark.SparkFunSuite
import org.apache.spark.ml.param.ParamMap
import org.apache.spark.ml.util.{DefaultReadWriteTest, MLTestingUtils}
import org.apache.spark.mllib.util.MLlibTestSparkContext
import org.apache.spark.sql.Dataset
class BisectingKMeansSuite
extends SparkFunSuite with MLlibTestSparkContext with DefaultReadWriteTest {
final val k = 5
@transient var dataset: Dataset[_] = _
@transient var sparseDataset: Dataset[_] = _
override def beforeAll(): Unit = {
super.beforeAll()
dataset = KMeansSuite.generateKMeansData(spark, 50, 3, k)
sparseDataset = KMeansSuite.generateSparseData(spark, 10, 1000, 42)
}
test("default parameters") {
val bkm = new BisectingKMeans()
assert(bkm.getK === 4)
assert(bkm.getFeaturesCol === "features")
assert(bkm.getPredictionCol === "prediction")
assert(bkm.getMaxIter === 20)
assert(bkm.getMinDivisibleClusterSize === 1.0)
val model = bkm.setMaxIter(1).fit(dataset)
// copied model must have the same parent
MLTestingUtils.checkCopy(model)
assert(model.hasSummary)
val copiedModel = model.copy(ParamMap.empty)
assert(copiedModel.hasSummary)
}
test("SPARK-16473: Verify Bisecting K-Means does not fail in edge case where" +
"one cluster is empty after split") {
val bkm = new BisectingKMeans()
.setK(k)
.setMinDivisibleClusterSize(4)
.setMaxIter(4)
.setSeed(123)
// Verify fit does not fail on very sparse data
val model = bkm.fit(sparseDataset)
val result = model.transform(sparseDataset)
val numClusters = result.select("prediction").distinct().collect().length
// Verify we hit the edge case
assert(numClusters < k && numClusters > 1)
}
test("setter/getter") {
val bkm = new BisectingKMeans()
.setK(9)
.setMinDivisibleClusterSize(2.0)
.setFeaturesCol("test_feature")
.setPredictionCol("test_prediction")
.setMaxIter(33)
.setSeed(123)
assert(bkm.getK === 9)
assert(bkm.getFeaturesCol === "test_feature")
assert(bkm.getPredictionCol === "test_prediction")
assert(bkm.getMaxIter === 33)
assert(bkm.getMinDivisibleClusterSize === 2.0)
assert(bkm.getSeed === 123)
intercept[IllegalArgumentException] {
new BisectingKMeans().setK(1)
}
intercept[IllegalArgumentException] {
new BisectingKMeans().setMinDivisibleClusterSize(0)
}
}
test("fit, transform and summary") {
val predictionColName = "bisecting_kmeans_prediction"
val bkm = new BisectingKMeans().setK(k).setPredictionCol(predictionColName).setSeed(1)
val model = bkm.fit(dataset)
assert(model.clusterCenters.length === k)
val transformed = model.transform(dataset)
val expectedColumns = Array("features", predictionColName)
expectedColumns.foreach { column =>
assert(transformed.columns.contains(column))
}
val clusters =
transformed.select(predictionColName).rdd.map(_.getInt(0)).distinct().collect().toSet
assert(clusters.size === k)
assert(clusters === Set(0, 1, 2, 3, 4))
assert(model.computeCost(dataset) < 0.1)
assert(model.hasParent)
// Check validity of model summary
val numRows = dataset.count()
assert(model.hasSummary)
val summary: BisectingKMeansSummary = model.summary
assert(summary.predictionCol === predictionColName)
assert(summary.featuresCol === "features")
assert(summary.predictions.count() === numRows)
for (c <- Array(predictionColName, "features")) {
assert(summary.predictions.columns.contains(c))
}
assert(summary.cluster.columns === Array(predictionColName))
val clusterSizes = summary.clusterSizes
assert(clusterSizes.length === k)
assert(clusterSizes.sum === numRows)
assert(clusterSizes.forall(_ >= 0))
model.setSummary(None)
assert(!model.hasSummary)
}
test("read/write") {
def checkModelData(model: BisectingKMeansModel, model2: BisectingKMeansModel): Unit = {
assert(model.clusterCenters === model2.clusterCenters)
}
val bisectingKMeans = new BisectingKMeans()
testEstimatorAndModelReadWrite(bisectingKMeans, dataset, BisectingKMeansSuite.allParamSettings,
BisectingKMeansSuite.allParamSettings, checkModelData)
}
}
object BisectingKMeansSuite {
val allParamSettings: Map[String, Any] = Map(
"k" -> 3,
"maxIter" -> 2,
"seed" -> -1L,
"minDivisibleClusterSize" -> 2.0
)
}
|
jianran/spark
|
mllib/src/test/scala/org/apache/spark/ml/clustering/BisectingKMeansSuite.scala
|
Scala
|
apache-2.0
| 5,294 |
/*
* Copyright (c) 2014-2020 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* 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 monix.execution.schedulers
import monix.execution.misc.Local
/** Wraps a `Runnable` into one that restores the given
* [[monix.execution.misc.Local.Context Local.Context]]
* upon execution of `run()`.
*
* Used by [[TracingScheduler]].
*/
final class TracingRunnable(r: Runnable, contextRef: Local.Context = Local.getContext()) extends Runnable {
override def run(): Unit = {
val prev = Local.getContext()
Local.setContext(contextRef)
try r.run()
finally Local.setContext(prev)
}
}
|
alexandru/monifu
|
monix-execution/shared/src/main/scala/monix/execution/schedulers/TracingRunnable.scala
|
Scala
|
apache-2.0
| 1,197 |
package com.nabijaczleweli.fancymagicks.element.caster.aoe
import com.nabijaczleweli.fancymagicks.element.ElementalDamageSource
import com.nabijaczleweli.fancymagicks.element.caster.OneOffElementCaster
import com.nabijaczleweli.fancymagicks.element.elements.Element
import com.nabijaczleweli.fancymagicks.util.EntityUtil
import net.minecraft.entity.Entity
class ElementSprayAOECaster(who: Entity, elems: Seq[Element]) extends OneOffElementCaster {
private lazy val force = elems count elems.head.equals
override protected def cast() {
for(e <- EntityUtil.entitiesInRadius[Entity](who, force * 2.5D)) {
ElementalDamageSource.dispatchDamage(new ElementalDamageSource(who, elems), e, ElementalDamageSource damageAOE elems)
val noElementCaster = ElementAOECaster(who, Nil)
noElementCaster.start()
for(_ <- 0 until force * 30)
noElementCaster.continue()
noElementCaster.end()
}
}
}
|
nabijaczleweli/Magicks
|
src/main/scala/com/nabijaczleweli/fancymagicks/element/caster/aoe/ElementSprayAOECaster.scala
|
Scala
|
mit
| 907 |
package pl.pholda.malpompaaligxilo.util
import utest._
class DateTest(companion: DateCompanion) extends TestSuite {
val tests = TestSuite{
s"Dates: ${companion.getClass.getSimpleName}"-{
'fromString{
'firstDate{
assertDate(1920, 1, 2, companion.fromString("1920-01-02"))
}
// 'secondDate{
// assertDate(100, 12, 31, companion.fromString("100-12-31"))
// }
'thirdDate{
assertDate(2015, 2, 18, companion.fromString("2015-02-18"))
}
'fourthDate{
assertDate(1999, 7, 21, companion.fromString("1999-07-21"))
}
}
'iso8601{
assert(companion.fromString("1991-01-02").iso8601 == "1991-01-02")
}
'compare{
'first{
val d1 = companion.fromString("1999-07-20")
val d2 = companion.fromString("1999-08-01")
assert(d1 < d2)
}
'second{
val d1 = companion.fromString("1999-07-20")
val d2 = companion.fromString("1999-07-20")
assert(d1 <= d2)
}
'third{
val d1 = companion.fromString("2015-01-13")
val d2 = companion.fromString("1999-07-20")
assert(d1 > d2)
}
}
'daysTo{
'first{
val d1 = companion.fromString("1999-07-01")
val d2 = companion.fromString("1999-07-21")
assert((d1 daysTo d2) == 20)
assert((d2 daysTo d1) == -20)
}
'second{
val d1 = companion.fromString("2000-12-30")
val d2 = companion.fromString("2001-01-15")
assert((d1 daysTo d2) == 16)
assert((d2 daysTo d1) == -16)
}
'third{
val d1 = companion.fromString("2015-01-01")
val d2 = companion.fromString("2015-01-02")
assert((d1 daysTo d2) == 1)
assert((d2 daysTo d1) == -1)
}
'fourth{
val d1 = companion.fromString("2015-01-01")
val d2 = companion.fromString("2015-01-01")
assert((d1 daysTo d2) == 0)
assert((d2 daysTo d1) == 0)
}
'fifth{
val d1 = companion.fromString("2015-01-30")
val d2 = companion.fromString("2015-01-15")
assert((d1 daysTo d2) == -15)
assert((d2 daysTo d1) == 15)
}
}
}
}
protected def assertDate(year: Int, month: Int, day: Int, date: Date): Unit = {
assert(date.getYear == year)
assert(date.getMonth == month)
assert(date.getDay == day)
}
}
|
pholda/MalpompaAligxilo
|
core/shared/src/test/scala/pl/pholda/malpompaaligxilo/util/DateTest.scala
|
Scala
|
gpl-3.0
| 2,517 |
package domain.logic
import java.time.LocalDate
import domain.models.{LunchOffer, LunchProvider}
import org.joda.money.Money
import org.scalamock.scalatest.MockFactory
import org.scalatest._
class LunchResolverSchweinestallSpec extends FlatSpec with Matchers with MockFactory {
it should "resolve offers for week of 2015-02-09" in {
val url = getClass.getResource("/mittagsplaene/schweinestall_2015-02-09.html")
val offers = resolver.resolve(url)
offers should have size 5
offers should contain(LunchOffer(0, "Goldmakrelenfilet auf Gurken-Dillsauce mit Salzkartoffeln", date("2015-02-09"), euro("5.80"), Id))
offers should contain(LunchOffer(0, "Pilzgulasch mit Salzkartoffeln", date("2015-02-10"), euro("4.80"), Id))
offers should contain(LunchOffer(0, "Paniertes Hähnchenbrustfilet gefüllt mit Kräuterbutter, dazu Erbsen und Kartoffelpüree", date("2015-02-11"), euro("5.80"), Id))
offers should contain(LunchOffer(0, "Kasselersteak mit Ananas und Käse überbacken, dazu Buttermöhren und Pommes frites", date("2015-02-12"), euro("5.80"), Id))
offers should contain(LunchOffer(0, "Spaghetti Bolognese mit Parmesan", date("2015-02-13"), euro("4.80"), Id))
}
private def resolver = {
val validatorStub = stub[DateValidator]
(validatorStub.isValid _).when(*).returning(true)
new LunchResolverSchweinestall(validatorStub)
}
private val Id = LunchProvider.SCHWEINESTALL.id
private def date(dateString: String): LocalDate = LocalDate.parse(dateString)
private def euro(moneyString: String): Money = Money.parse(s"EUR $moneyString")
}
|
rori-dev/lunchbox
|
backend-play-akka-scala/test/domain/logic/LunchResolverSchweinestallSpec.scala
|
Scala
|
mit
| 1,601 |
package dnd5_dm_db
package model
object Language {
def fromString(str : String) : Language = str.toLowerCase match {
case "common" => Common
case "dwarvish" => Dwarvish
case "elvish" => Elvish
case "giant" => GiantLang
case "gnomish" => Gnomish
case "goblin" => Goblin
case "halfling" => Halfling
case "orc" => OrcLang
case "abyssal" => Abyssal
case "celestial" => CelestialLang
case "draconic" => Draconic
case "deepSpeech" => DeepSpeech
case "infernal" => Infernal
case "primordial" => Primordial
case "sylvan" => Sylvan
case "undercommon" => Undercommon
case "troglodyte" => TroglodyteLang
case _ => error(s"unknown language $str")
}
}
sealed abstract class Language
case object Common extends Language
case object Dwarvish extends Language
case object Elvish extends Language
case object GiantLang extends Language
case object Gnomish extends Language
case object Goblin extends Language
case object Halfling extends Language
case object OrcLang extends Language
case object Abyssal extends Language
case object CelestialLang extends Language
case object Draconic extends Language
case object DeepSpeech extends Language
case object Infernal extends Language
case object Primordial extends Language
case object Sylvan extends Language
case object Undercommon extends Language
case object TroglodyteLang extends Language
//Todo handle case of any X language
//exemple with spy and any 2 language
case class AnyLanguage(num : Int, default : Option[Language]) extends Language
case class UnderstandOnly(lang : Language) extends Language
case class LanguageSpecial(name : Local) extends Language
|
lorilan/dnd5_dm_db
|
src/main/scala/dnd5_dm_db/model/Language.scala
|
Scala
|
gpl-3.0
| 1,680 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.scheduler.cluster.mesos
import java.io.File
import java.nio.charset.StandardCharsets
import java.util.{List => JList}
import java.util.concurrent.CountDownLatch
import scala.collection.JavaConverters._
import scala.collection.mutable.ArrayBuffer
import scala.util.control.NonFatal
import com.google.common.base.Splitter
import com.google.common.io.Files
import org.apache.mesos.{MesosSchedulerDriver, Protos, Scheduler, SchedulerDriver}
import org.apache.mesos.Protos.{SlaveID => AgentID, TaskState => MesosTaskState, _}
import org.apache.mesos.Protos.FrameworkInfo.Capability
import org.apache.mesos.Protos.Resource.ReservationInfo
import org.apache.mesos.protobuf.{ByteString, GeneratedMessageV3}
import org.apache.spark.{SparkConf, SparkContext, SparkException}
import org.apache.spark.TaskState
import org.apache.spark.deploy.mesos.{config => mesosConfig}
import org.apache.spark.internal.Logging
import org.apache.spark.internal.config.{Status => _, _}
import org.apache.spark.util.Utils
/**
* Shared trait for implementing a Mesos Scheduler. This holds common state and helper
* methods and Mesos scheduler will use.
*/
trait MesosSchedulerUtils extends Logging {
// Lock used to wait for scheduler to be registered
private final val registerLatch = new CountDownLatch(1)
private final val ANY_ROLE = "*"
/**
* Creates a new MesosSchedulerDriver that communicates to the Mesos master.
*
* @param masterUrl The url to connect to Mesos master
* @param scheduler the scheduler class to receive scheduler callbacks
* @param sparkUser User to impersonate with when running tasks
* @param appName The framework name to display on the Mesos UI
* @param conf Spark configuration
* @param webuiUrl The WebUI url to link from Mesos UI
* @param checkpoint Option to checkpoint tasks for failover
* @param failoverTimeout Duration Mesos master expect scheduler to reconnect on disconnect
* @param frameworkId The id of the new framework
*/
protected def createSchedulerDriver(
masterUrl: String,
scheduler: Scheduler,
sparkUser: String,
appName: String,
conf: SparkConf,
webuiUrl: Option[String] = None,
checkpoint: Option[Boolean] = None,
failoverTimeout: Option[Double] = None,
frameworkId: Option[String] = None): SchedulerDriver = {
val fwInfoBuilder = FrameworkInfo.newBuilder().setUser(sparkUser).setName(appName)
fwInfoBuilder.setHostname(Option(conf.getenv("SPARK_PUBLIC_DNS")).getOrElse(
conf.get(DRIVER_HOST_ADDRESS)))
webuiUrl.foreach { url => fwInfoBuilder.setWebuiUrl(url) }
checkpoint.foreach { checkpoint => fwInfoBuilder.setCheckpoint(checkpoint) }
failoverTimeout.foreach { timeout => fwInfoBuilder.setFailoverTimeout(timeout) }
frameworkId.foreach { id =>
fwInfoBuilder.setId(FrameworkID.newBuilder().setValue(id).build())
}
conf.get(mesosConfig.ROLE).foreach { role =>
fwInfoBuilder.setRole(role)
}
val maxGpus = conf.get(mesosConfig.MAX_GPUS)
if (maxGpus > 0) {
fwInfoBuilder.addCapabilities(Capability.newBuilder().setType(Capability.Type.GPU_RESOURCES))
}
val credBuilder = buildCredentials(conf, fwInfoBuilder)
if (credBuilder.hasPrincipal) {
new MesosSchedulerDriver(
scheduler, fwInfoBuilder.build(), masterUrl, credBuilder.build())
} else {
new MesosSchedulerDriver(scheduler, fwInfoBuilder.build(), masterUrl)
}
}
def buildCredentials(
conf: SparkConf,
fwInfoBuilder: Protos.FrameworkInfo.Builder): Protos.Credential.Builder = {
val credBuilder = Credential.newBuilder()
conf.get(mesosConfig.CREDENTIAL_PRINCIPAL)
.orElse(Option(conf.getenv("SPARK_MESOS_PRINCIPAL")))
.orElse(
conf.get(mesosConfig.CREDENTIAL_PRINCIPAL_FILE)
.orElse(Option(conf.getenv("SPARK_MESOS_PRINCIPAL_FILE")))
.map { principalFile =>
Files.toString(new File(principalFile), StandardCharsets.UTF_8)
}
).foreach { principal =>
fwInfoBuilder.setPrincipal(principal)
credBuilder.setPrincipal(principal)
}
conf.get(mesosConfig.CREDENTIAL_SECRET)
.orElse(Option(conf.getenv("SPARK_MESOS_SECRET")))
.orElse(
conf.get(mesosConfig.CREDENTIAL_SECRET_FILE)
.orElse(Option(conf.getenv("SPARK_MESOS_SECRET_FILE")))
.map { secretFile =>
Files.toString(new File(secretFile), StandardCharsets.UTF_8)
}
).foreach { secret =>
credBuilder.setSecret(secret)
}
if (credBuilder.hasSecret && !fwInfoBuilder.hasPrincipal) {
throw new SparkException(
s"${mesosConfig.CREDENTIAL_PRINCIPAL} must be configured when " +
s"${mesosConfig.CREDENTIAL_SECRET} is set")
}
credBuilder
}
/**
* Starts the MesosSchedulerDriver and stores the current running driver to this new instance.
* This driver is expected to not be running.
* This method returns only after the scheduler has registered with Mesos.
*/
def startScheduler(newDriver: SchedulerDriver): Unit = {
synchronized {
@volatile
var error: Option[Exception] = None
// We create a new thread that will block inside `mesosDriver.run`
// until the scheduler exists
new Thread(Utils.getFormattedClassName(this) + "-mesos-driver") {
setDaemon(true)
override def run(): Unit = {
try {
val ret = newDriver.run()
logInfo("driver.run() returned with code " + ret)
if (ret != null && ret.equals(Status.DRIVER_ABORTED)) {
error = Some(new SparkException("Error starting driver, DRIVER_ABORTED"))
markErr()
}
} catch {
case e: Exception =>
logError("driver.run() failed", e)
error = Some(e)
markErr()
}
}
}.start()
registerLatch.await()
// propagate any error to the calling thread. This ensures that SparkContext creation fails
// without leaving a broken context that won't be able to schedule any tasks
error.foreach(throw _)
}
}
def getResource(res: JList[Resource], name: String): Double = {
// A resource can have multiple values in the offer since it can either be from
// a specific role or wildcard.
res.asScala.filter(_.getName == name).map(_.getScalar.getValue).sum
}
/**
* Transforms a range resource to a list of ranges
*
* @param res the mesos resource list
* @param name the name of the resource
* @return the list of ranges returned
*/
protected def getRangeResource(res: JList[Resource], name: String): List[(Long, Long)] = {
// A resource can have multiple values in the offer since it can either be from
// a specific role or wildcard.
res.asScala.filter(_.getName == name).flatMap(_.getRanges.getRangeList.asScala
.map(r => (r.getBegin, r.getEnd)).toList).toList
}
/**
* Signal that the scheduler has registered with Mesos.
*/
protected def markRegistered(): Unit = {
registerLatch.countDown()
}
protected def markErr(): Unit = {
registerLatch.countDown()
}
private def setReservationInfo(
reservationInfo: Option[ReservationInfo],
role: Option[String],
builder: Resource.Builder): Unit = {
if (!role.contains(ANY_ROLE)) {
reservationInfo.foreach { res => builder.setReservation(res) }
}
}
def createResource(
name: String,
amount: Double,
role: Option[String] = None,
reservationInfo: Option[ReservationInfo] = None): Resource = {
val builder = Resource.newBuilder()
.setName(name)
.setType(Value.Type.SCALAR)
.setScalar(Value.Scalar.newBuilder().setValue(amount).build())
role.foreach { r => builder.setRole(r) }
setReservationInfo(reservationInfo, role, builder)
builder.build()
}
private def getReservation(resource: Resource): Option[ReservationInfo] = {
if (resource.hasReservation) {
Some(resource.getReservation)
} else {
None
}
}
/**
* Partition the existing set of resources into two groups, those remaining to be
* scheduled and those requested to be used for a new task.
*
* @param resources The full list of available resources
* @param resourceName The name of the resource to take from the available resources
* @param amountToUse The amount of resources to take from the available resources
* @return The remaining resources list and the used resources list.
*/
def partitionResources(
resources: JList[Resource],
resourceName: String,
amountToUse: Double): (List[Resource], List[Resource]) = {
var remain = amountToUse
var requestedResources = new ArrayBuffer[Resource]
val remainingResources = resources.asScala.map {
case r =>
val reservation = getReservation(r)
if (remain > 0 &&
r.getType == Value.Type.SCALAR &&
r.getScalar.getValue > 0.0 &&
r.getName == resourceName) {
val usage = Math.min(remain, r.getScalar.getValue)
requestedResources += createResource(resourceName, usage,
Option(r.getRole), reservation)
remain -= usage
createResource(resourceName, r.getScalar.getValue - usage,
Option(r.getRole), reservation)
} else {
r
}
}
// Filter any resource that has depleted.
val filteredResources =
remainingResources.filter(r => r.getType != Value.Type.SCALAR || r.getScalar.getValue > 0.0)
(filteredResources.toList, requestedResources.toList)
}
/** Helper method to get the key,value-set pair for a Mesos Attribute protobuf */
protected def getAttribute(attr: Attribute): (String, Set[String]) = {
(attr.getName, attr.getText.getValue.split(',').toSet)
}
/**
* Converts the attributes from the resource offer into a Map of name to Attribute Value
* The attribute values are the mesos attribute types and they are
*
* @param offerAttributes the attributes offered
*/
protected def toAttributeMap(offerAttributes: JList[Attribute])
: Map[String, GeneratedMessageV3] = {
offerAttributes.asScala.map { attr =>
val attrValue = attr.getType match {
case Value.Type.SCALAR => attr.getScalar
case Value.Type.RANGES => attr.getRanges
case Value.Type.SET => attr.getSet
case Value.Type.TEXT => attr.getText
}
(attr.getName, attrValue)
}.toMap
}
/**
* Match the requirements (if any) to the offer attributes.
* if attribute requirements are not specified - return true
* else if attribute is defined and no values are given, simple attribute presence is performed
* else if attribute name and value is specified, subset match is performed on agent attributes
*/
def matchesAttributeRequirements(
agentOfferConstraints: Map[String, Set[String]],
offerAttributes: Map[String, GeneratedMessageV3]): Boolean = {
agentOfferConstraints.forall {
// offer has the required attribute and subsumes the required values for that attribute
case (name, requiredValues) =>
offerAttributes.get(name) match {
case None => false
case Some(_) if requiredValues.isEmpty => true // empty value matches presence
case Some(scalarValue: Value.Scalar) =>
// check if provided values is less than equal to the offered values
requiredValues.map(_.toDouble).exists(_ <= scalarValue.getValue)
case Some(rangeValue: Value.Range) =>
val offerRange = rangeValue.getBegin to rangeValue.getEnd
// Check if there is some required value that is between the ranges specified
// Note: We only support the ability to specify discrete values, in the future
// we may expand it to subsume ranges specified with a XX..YY value or something
// similar to that.
requiredValues.map(_.toLong).exists(offerRange.contains(_))
case Some(offeredValue: Value.Set) =>
// check if the specified required values is a subset of offered set
requiredValues.subsetOf(offeredValue.getItemList.asScala.toSet)
case Some(textValue: Value.Text) =>
// check if the specified value is equal, if multiple values are specified
// we succeed if any of them match.
requiredValues.contains(textValue.getValue)
}
}
}
/**
* Parses the attributes constraints provided to spark and build a matching data struct:
* {@literal Map[<attribute-name>, Set[values-to-match]}
* The constraints are specified as ';' separated key-value pairs where keys and values
* are separated by ':'. The ':' implies equality (for singular values) and "is one of" for
* multiple values (comma separated). For example:
* {{{
* parseConstraintString("os:centos7;zone:us-east-1a,us-east-1b")
* // would result in
* <code>
* Map(
* "os" -> Set("centos7"),
* "zone": -> Set("us-east-1a", "us-east-1b")
* )
* }}}
*
* Mesos documentation: http://mesos.apache.org/documentation/attributes-resources/
* https://github.com/apache/mesos/blob/master/src/common/values.cpp
* https://github.com/apache/mesos/blob/master/src/common/attributes.cpp
*
* @param constraintsVal constains string consisting of ';' separated key-value pairs (separated
* by ':')
* @return Map of constraints to match resources offers.
*/
def parseConstraintString(constraintsVal: String): Map[String, Set[String]] = {
/*
Based on mesos docs:
attributes : attribute ( ";" attribute )*
attribute : labelString ":" ( labelString | "," )+
labelString : [a-zA-Z0-9_/.-]
*/
val splitter = Splitter.on(';').trimResults().withKeyValueSeparator(':')
// kv splitter
if (constraintsVal.isEmpty) {
Map()
} else {
try {
splitter.split(constraintsVal).asScala.toMap.mapValues(v =>
if (v == null || v.isEmpty) {
Set.empty[String]
} else {
v.split(',').toSet
}
).toMap
} catch {
case NonFatal(e) =>
throw new IllegalArgumentException(s"Bad constraint string: $constraintsVal", e)
}
}
}
// These defaults copied from YARN
private val MEMORY_OVERHEAD_FRACTION = 0.10
private val MEMORY_OVERHEAD_MINIMUM = 384
/**
* Return the amount of memory to allocate to each executor, taking into account
* container overheads.
*
* @param sc SparkContext to use to get `spark.mesos.executor.memoryOverhead` value
* @return memory requirement as (0.1 * memoryOverhead) or MEMORY_OVERHEAD_MINIMUM
* (whichever is larger)
*/
def executorMemory(sc: SparkContext): Int = {
sc.conf.get(mesosConfig.EXECUTOR_MEMORY_OVERHEAD).getOrElse(
math.max(MEMORY_OVERHEAD_FRACTION * sc.executorMemory, MEMORY_OVERHEAD_MINIMUM).toInt) +
sc.executorMemory
}
def setupUris(uris: Seq[String],
builder: CommandInfo.Builder,
useFetcherCache: Boolean = false): Unit = {
uris.foreach { uri =>
builder.addUris(CommandInfo.URI.newBuilder().setValue(uri.trim()).setCache(useFetcherCache))
}
}
protected def getRejectOfferDuration(conf: SparkConf): Long = {
conf.get(mesosConfig.REJECT_OFFER_DURATION)
}
protected def getRejectOfferDurationForUnmetConstraints(conf: SparkConf): Long = {
conf.get(mesosConfig.REJECT_OFFER_DURATION_FOR_UNMET_CONSTRAINTS)
.getOrElse(getRejectOfferDuration(conf))
}
protected def getRejectOfferDurationForReachedMaxCores(conf: SparkConf): Long = {
conf.get(mesosConfig.REJECT_OFFER_DURATION_FOR_REACHED_MAX_CORES)
.getOrElse(getRejectOfferDuration(conf))
}
/**
* Checks executor ports if they are within some range of the offered list of ports ranges,
*
* @param conf the Spark Config
* @param ports the list of ports to check
* @return true if ports are within range false otherwise
*/
protected def checkPorts(conf: SparkConf, ports: List[(Long, Long)]): Boolean = {
def checkIfInRange(port: Long, ps: List[(Long, Long)]): Boolean = {
ps.exists{case (rangeStart, rangeEnd) => rangeStart <= port & rangeEnd >= port }
}
val portsToCheck = nonZeroPortValuesFromConfig(conf)
val withinRange = portsToCheck.forall(p => checkIfInRange(p, ports))
// make sure we have enough ports to allocate per offer
val enoughPorts =
ports.map{case (rangeStart, rangeEnd) => rangeEnd - rangeStart + 1}.sum >= portsToCheck.size
enoughPorts && withinRange
}
/**
* Partitions port resources.
*
* @param requestedPorts non-zero ports to assign
* @param offeredResources the resources offered
* @return resources left, port resources to be used.
*/
def partitionPortResources(requestedPorts: List[Long], offeredResources: List[Resource])
: (List[Resource], List[Resource]) = {
if (requestedPorts.isEmpty) {
(offeredResources, List[Resource]())
} else {
// partition port offers
val (resourcesWithoutPorts, portResources) = filterPortResources(offeredResources)
val portsAndResourceInfo = requestedPorts.
map { x => (x, findPortAndGetAssignedResourceInfo(x, portResources)) }
val assignedPortResources = createResourcesFromPorts(portsAndResourceInfo)
// ignore non-assigned port resources, they will be declined implicitly by mesos
// no need for splitting port resources.
(resourcesWithoutPorts, assignedPortResources)
}
}
val managedPortNames = List(BLOCK_MANAGER_PORT.key)
/**
* The values of the non-zero ports to be used by the executor process.
*
* @param conf the spark config to use
* @return the ono-zero values of the ports
*/
def nonZeroPortValuesFromConfig(conf: SparkConf): List[Long] = {
managedPortNames.map(conf.getLong(_, 0)).filter( _ != 0)
}
private case class RoleResourceInfo(
role: String,
resInfo: Option[ReservationInfo])
/** Creates a mesos resource for a specific port number. */
private def createResourcesFromPorts(
portsAndResourcesInfo: List[(Long, RoleResourceInfo)])
: List[Resource] = {
portsAndResourcesInfo.flatMap { case (port, rInfo) =>
createMesosPortResource(List((port, port)), Option(rInfo.role), rInfo.resInfo)}
}
/** Helper to create mesos resources for specific port ranges. */
private def createMesosPortResource(
ranges: List[(Long, Long)],
role: Option[String] = None,
reservationInfo: Option[ReservationInfo] = None): List[Resource] = {
// for ranges we are going to use (user defined ports fall in there) create mesos resources
// for each range there is a role associated with it.
ranges.map { case (rangeStart, rangeEnd) =>
val rangeValue = Value.Range.newBuilder()
.setBegin(rangeStart)
.setEnd(rangeEnd)
val builder = Resource.newBuilder()
.setName("ports")
.setType(Value.Type.RANGES)
.setRanges(Value.Ranges.newBuilder().addRange(rangeValue))
role.foreach { r => builder.setRole(r) }
setReservationInfo(reservationInfo, role, builder)
builder.build()
}
}
/**
* Helper to assign a port to an offered range and get the latter's role
* info to use it later on.
*/
private def findPortAndGetAssignedResourceInfo(port: Long, portResources: List[Resource])
: RoleResourceInfo = {
val ranges = portResources.
map { resource =>
val reservation = getReservation(resource)
(RoleResourceInfo(resource.getRole, reservation),
resource.getRanges.getRangeList.asScala.map(r => (r.getBegin, r.getEnd)).toList)
}
val rangePortResourceInfo = ranges
.find { case (resourceInfo, rangeList) => rangeList
.exists{ case (rangeStart, rangeEnd) => rangeStart <= port & rangeEnd >= port}}
// this is safe since we have previously checked about the ranges (see checkPorts method)
rangePortResourceInfo.map{ case (resourceInfo, rangeList) => resourceInfo}.get
}
/** Retrieves the port resources from a list of mesos offered resources */
private def filterPortResources(resources: List[Resource]): (List[Resource], List[Resource]) = {
resources.partition { r => !(r.getType == Value.Type.RANGES && r.getName == "ports") }
}
/**
* spark.mesos.driver.frameworkId is set by the cluster dispatcher to correlate driver
* submissions with frameworkIDs. However, this causes issues when a driver process launches
* more than one framework (more than one SparkContext(, because they all try to register with
* the same frameworkID. To enforce that only the first driver registers with the configured
* framework ID, the driver calls this method after the first registration.
*/
def unsetFrameworkID(sc: SparkContext): Unit = {
sc.conf.remove(mesosConfig.DRIVER_FRAMEWORK_ID)
System.clearProperty(mesosConfig.DRIVER_FRAMEWORK_ID.key)
}
def mesosToTaskState(state: MesosTaskState): TaskState.TaskState = state match {
case MesosTaskState.TASK_STAGING |
MesosTaskState.TASK_STARTING => TaskState.LAUNCHING
case MesosTaskState.TASK_RUNNING |
MesosTaskState.TASK_KILLING => TaskState.RUNNING
case MesosTaskState.TASK_FINISHED => TaskState.FINISHED
case MesosTaskState.TASK_FAILED |
MesosTaskState.TASK_GONE |
MesosTaskState.TASK_GONE_BY_OPERATOR => TaskState.FAILED
case MesosTaskState.TASK_KILLED => TaskState.KILLED
case MesosTaskState.TASK_LOST |
MesosTaskState.TASK_ERROR |
MesosTaskState.TASK_DROPPED |
MesosTaskState.TASK_UNKNOWN |
MesosTaskState.TASK_UNREACHABLE => TaskState.LOST
}
protected def declineOffer(
driver: org.apache.mesos.SchedulerDriver,
offer: Offer,
reason: Option[String] = None,
refuseSeconds: Option[Long] = None): Unit = {
val id = offer.getId.getValue
val offerAttributes = toAttributeMap(offer.getAttributesList)
val mem = getResource(offer.getResourcesList, "mem")
val cpus = getResource(offer.getResourcesList, "cpus")
val ports = getRangeResource(offer.getResourcesList, "ports")
logDebug(s"Declining offer: $id with " +
s"attributes: $offerAttributes " +
s"mem: $mem " +
s"cpu: $cpus " +
s"port: $ports " +
refuseSeconds.map(s => s"for ${s} seconds ").getOrElse("") +
reason.map(r => s" (reason: $r)").getOrElse(""))
refuseSeconds match {
case Some(seconds) =>
val filters = Filters.newBuilder().setRefuseSeconds(seconds).build()
driver.declineOffer(offer.getId, filters)
case _ =>
driver.declineOffer(offer.getId)
}
}
}
|
dbtsai/spark
|
resource-managers/mesos/src/main/scala/org/apache/spark/scheduler/cluster/mesos/MesosSchedulerUtils.scala
|
Scala
|
apache-2.0
| 23,789 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.jdbc.v2
import java.sql.Connection
import org.apache.spark.SparkConf
import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog
import org.apache.spark.sql.jdbc.{DatabaseOnDocker, DockerJDBCIntegrationSuite}
import org.apache.spark.sql.types._
import org.apache.spark.tags.DockerTest
/**
* To run this test suite for a specific version (e.g., ibmcom/db2:11.5.4.0):
* {{{
* DB2_DOCKER_IMAGE_NAME=ibmcom/db2:11.5.4.0
* ./build/sbt -Pdocker-integration-tests "testOnly *v2.DB2IntegrationSuite"
* }}}
*/
@DockerTest
class DB2IntegrationSuite extends DockerJDBCIntegrationSuite with V2JDBCTest {
override val catalogName: String = "db2"
override val db = new DatabaseOnDocker {
override val imageName = sys.env.getOrElse("DB2_DOCKER_IMAGE_NAME", "ibmcom/db2:11.5.4.0")
override val env = Map(
"DB2INST1_PASSWORD" -> "rootpass",
"LICENSE" -> "accept",
"DBNAME" -> "foo",
"ARCHIVE_LOGS" -> "false",
"AUTOCONFIG" -> "false"
)
override val usesIpc = false
override val jdbcPort: Int = 50000
override val privileged = true
override def getJdbcUrl(ip: String, port: Int): String =
s"jdbc:db2://$ip:$port/foo:user=db2inst1;password=rootpass;retrieveMessagesFromServerOnGetMessage=true;" //scalastyle:ignore
}
override def sparkConf: SparkConf = super.sparkConf
.set("spark.sql.catalog.db2", classOf[JDBCTableCatalog].getName)
.set("spark.sql.catalog.db2.url", db.getJdbcUrl(dockerIp, externalPort))
override def dataPreparation(conn: Connection): Unit = {}
override def testUpdateColumnType(tbl: String): Unit = {
sql(s"CREATE TABLE $tbl (ID INTEGER) USING _")
var t = spark.table(tbl)
var expectedSchema = new StructType().add("ID", IntegerType)
assert(t.schema === expectedSchema)
sql(s"ALTER TABLE $tbl ALTER COLUMN id TYPE DOUBLE")
t = spark.table(tbl)
expectedSchema = new StructType().add("ID", DoubleType)
assert(t.schema === expectedSchema)
// Update column type from DOUBLE to STRING
val msg1 = intercept[AnalysisException] {
sql(s"ALTER TABLE $tbl ALTER COLUMN id TYPE VARCHAR(10)")
}.getMessage
assert(msg1.contains("Cannot update alt_table field ID: double cannot be cast to varchar"))
}
override def testCreateTableWithProperty(tbl: String): Unit = {
sql(s"CREATE TABLE $tbl (ID INT) USING _" +
s" TBLPROPERTIES('CCSID'='UNICODE')")
var t = spark.table(tbl)
var expectedSchema = new StructType().add("ID", IntegerType)
assert(t.schema === expectedSchema)
}
}
|
shuangshuangwang/spark
|
external/docker-integration-tests/src/test/scala/org/apache/spark/sql/jdbc/v2/DB2IntegrationSuite.scala
|
Scala
|
apache-2.0
| 3,438 |
package com.twitter.finagle.http2.transport.client
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.transport.{Transport, TransportProxy}
import com.twitter.util.{Await, Future, Time}
import org.mockito.Matchers.{any, anyInt}
import org.mockito.Mockito.{verify, when}
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.funsuite.AnyFunSuite
class RefTransportTest extends AnyFunSuite with MockitoSugar {
// wrapping the transport in a thin proxy provides a correct map
// implementation
private[this] def wrap(trans: Transport[Int, Int]): Transport[Int, Int] =
new TransportProxy(trans) {
override def write(in: Int): Future[Unit] = trans.write(in)
override def read(): Future[Int] = trans.read()
}
// returns None if it updates and hasn't been closed yet
// return Some[Boolean] if it has already been closed. the boolean indicates whether
// close was then called on it or not.
private[this] def updateMap(
trans: RefTransport[Int, Int],
left: Int => Int,
right: Int => Int
): Option[Boolean] = {
var closed = false
val updated = trans.update { transport =>
val underlying = transport.map(left, right)
new TransportProxy(underlying) {
override def read(): Future[Int] = underlying.read()
override def write(msg: Int): Future[Unit] = underlying.write(msg)
override def close(deadline: Time): Future[Unit] = {
closed = true
underlying.close(deadline)
}
}
}
if (updated) None else Some(closed)
}
test("RefTransport proxies to underlying transport") {
val trans = mock[Transport[Int, Int]]
when(trans.write(anyInt)).thenReturn(Future.Done)
when(trans.read()).thenReturn(Future.value(1))
when(trans.onClose).thenReturn(Future.never)
val refTrans = new RefTransport(wrap(trans))
assert(Await.result(refTrans.read(), 5.seconds) == 1)
refTrans.write(7)
verify(trans).write(7)
}
test("RefTransport proxies to underlying transport via a lens") {
val trans = mock[Transport[Int, Int]]
when(trans.write(anyInt)).thenReturn(Future.Done)
when(trans.read()).thenReturn(Future.value(1))
when(trans.onClose).thenReturn(Future.never)
val refTrans = new RefTransport(wrap(trans))
assert(updateMap(refTrans, _ * 2, _ * 3).isEmpty)
assert(Await.result(refTrans.read(), 5.seconds) == 3)
refTrans.write(7)
verify(trans).write(14)
}
test("RefTransport proxies to underlying transport via a lens which can switch") {
val trans = mock[Transport[Int, Int]]
when(trans.write(anyInt)).thenReturn(Future.Done)
when(trans.read()).thenReturn(Future.value(1))
when(trans.onClose).thenReturn(Future.never)
val refTrans = new RefTransport(wrap(trans))
assert(updateMap(refTrans, _ * 2, _ * 3).isEmpty)
assert(Await.result(refTrans.read(), 5.seconds) == 3)
updateMap(refTrans, _ * 8, _ * 1)
refTrans.write(7)
verify(trans).write(56)
}
test("RefTransport will immediately close the updated transport after closing") {
val trans = mock[Transport[Int, Int]]
when(trans.write(anyInt)).thenReturn(Future.Done)
when(trans.read()).thenReturn(Future.value(1))
when(trans.onClose).thenReturn(Future.never)
when(trans.close(any[Time])).thenReturn(Future.never)
val refTrans = new RefTransport(wrap(trans))
refTrans.close()
assert(updateMap(refTrans, _ * 2, _ * 2) == Some(true))
assert(Await.result(refTrans.read(), 5.seconds) == 2)
refTrans.write(7)
verify(trans).write(14)
}
test("RefTransport will immediately close after the underlying transport is closed") {
val trans = mock[Transport[Int, Int]]
when(trans.write(anyInt)).thenReturn(Future.Done)
when(trans.read()).thenReturn(Future.value(1))
when(trans.onClose).thenReturn(Future.value(new Exception("boom!")))
val refTrans = new RefTransport(wrap(trans))
assert(updateMap(refTrans, _ * 2, _ * 2) == Some(true))
assert(Await.result(refTrans.read(), 5.seconds) == 2)
refTrans.write(7)
verify(trans).write(14)
}
}
|
twitter/finagle
|
finagle-http2/src/test/scala/com/twitter/finagle/http2/transport/client/RefTransportTest.scala
|
Scala
|
apache-2.0
| 4,128 |
import sbt._
import sbt.Keys._
import org.scalastyle.sbt.ScalastylePlugin
object $name;format="Camel"$Build extends Build {
lazy val $name;format="camel"$ = Project(
id = "$name;format="Camel"$",
base = file("."),
settings = Project.defaultSettings ++ ScalastylePlugin.Settings ++ Seq(
name := "$name;format="Camel"$",
organization := "$organization$",
version := "0.1-SNAPSHOT",
scalaVersion := "2.11.0",
// add other settings here
libraryDependencies ++= Seq(
"org.scalatest" % "scalatest_2.11" % "2.1.5" % "test" withSources() withJavadoc(),
"org.scalacheck" %% "scalacheck" % "1.11.3" % "test" withSources() withJavadoc()
)
)
)
}
|
ignaciocases/hn-scala-base.g8
|
src/main/g8/project/$name__Camel$Build.scala
|
Scala
|
mit
| 716 |
/**
* Licensed to Big Data Genomics (BDG) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The BDG licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bdgenomics.avocado.algorithms.math
import org.scalatest.FunSuite
import scala.math.log
import scala.util.Random
class LogUtilsSuite extends FunSuite {
test("test our nifty log summer") {
val sumLogs = LogUtils.sumLogProbabilities(Array(0.5, 0.25, 0.125, 0.1, 0.025).map(log(_)))
MathTestUtils.assertAlmostEqual(sumLogs, 0)
}
test("can we compute the sum of logs correctly?") {
val rv = new Random(124235346L)
(0 to 1000).foreach(i => {
val p = rv.nextDouble()
val q = rv.nextDouble()
val logPplusQ = LogUtils.logSum(log(p), log(q))
MathTestUtils.assertAlmostEqual(logPplusQ, log(p + q))
})
}
test("can we compute the additive inverse of logs correctly?") {
val rv = new Random(223344556677L)
(0 to 1000).foreach(i => {
val p = rv.nextDouble()
val log1mP = LogUtils.logAdditiveInverse(log(p))
MathTestUtils.assertAlmostEqual(log1mP, log(1.0 - p))
})
}
}
|
allenday/avocado
|
avocado-core/src/test/scala/org/bdgenomics/avocado/algorithms/math/LogUtilsSuite.scala
|
Scala
|
apache-2.0
| 1,756 |
package tifmo
import dcstree.SemRole
import dcstree.Executor
import dcstree.Selection
import dcstree.DCSTreeNode
import dcstree.DCSTreeEdge
import dcstree.DCSTreeEdgeNormal
import dcstree.RefOutput
import dcstree.Declarative
import dcstree.DeclarativeSubRef
import dcstree.DeclarativeSubsume
import inference.Dimension
import inference.IEngineCore
import inference.IEFunction
import inference.Term
import inference.TermIndex
import inference.RuleArg
import inference.RuleDo
import inference.Debug_SimpleRuleTrace
import inference.IEPredRL
import inference.RAConversion._
import onthefly.AEngine
package document {
case class SelSup(name: String, role: SemRole) extends Selection {
def execute[T](ex: Executor, x: T): T = {
(ex, x) match {
case (ie:IEngineCore, tm:Term) => {
val pitm = if (tm.dim.size == 1) tm else ie.getPI(tm, Set(role))
val spitm = ie.getFunc(SelSupFunc, Seq(null, pitm), name)
val side = if (tm.dim.size == 1) {
spitm
} else {
val tmrs = tm.dim.relabel(null)
val (wdim, wr) = Dimension(tmrs - role)
ie.getCP(Set((spitm, role), (ie.getW(wdim).holder, wr)))
}
ie.getIN(Set(tm, side)).asInstanceOf[T]
}
case (ae:AEngine, toprv:Function1[_, _]) => ((d: Declarative) => d match {
case DeclarativeSubsume(sub, sup) => {
if (sub.selection != null && sub.selection.isInstanceOf[SelSup] &&
sub.selection == sup.selection) {
val toProve = toprv.asInstanceOf[(Declarative) => Unit]
val SelSup(name, role) = sub.selection
val nsub = new DCSTreeNode(
for ((e:DCSTreeEdgeNormal, n) <- sub.children) yield (e, n.copy),
sub.rseq,
sub.token,
sub.sign,
null,
role
)
nsub.upward()
nsub.downward(null)
val nsup = new DCSTreeNode(
for ((e:DCSTreeEdgeNormal, n) <- sup.children) yield (e, n.copy),
sup.rseq,
sup.token,
sup.sign,
null,
role
)
nsup.upward()
nsup.downward(null)
val dec1 = DeclarativeSubRef(RefOutput(nsub), RefOutput(nsup))
ae.maybeHelpful(dec1)
toProve(dec1)
val dec2 = DeclarativeSubRef(RefOutput(nsup), RefOutput(nsub))
ae.maybeHelpful(dec2)
toProve(dec2)
}
}
case _ => {}
}).asInstanceOf[T]
case _ => throw new Exception("unknown executor!!")
}
}
}
private[document] object SelSupFunc extends IEFunction {
def headDim(tms: Seq[Term], param: Any) = tms(1).dim
def applyFunc(ie: IEngineCore, tms: Seq[TermIndex], param: Any) {
val name = param.asInstanceOf[String]
tms match {
case Seq(h, a) => {
ie.claimSubsume(h, a, Debug_SimpleRuleTrace("SelSupFunc", ie.getNewPredID()))
ie.claimRL(h, RelPartialOrder(name), a, Debug_SimpleRuleTrace("SelSupFunc", ie.getNewPredID()))
ie.foreachXRLB(a, Seq(h, name), rSelSupFunc0)
}
case _ => throw new Exception("SelSupFunc error!")
}
}
}
private[document] object rSelSupFunc0 extends RuleDo[IEPredRL] {
def apply(ie: IEngineCore, pred: IEPredRL, args: Seq[RuleArg]) {
args match {
case Seq(RuleArg(h:TermIndex), RuleArg(name:String)) => pred.rl match {
case RelPartialOrder(nm) => if (nm == name) {
ie.claimSubsume(pred.a, h, Debug_SimpleRuleTrace("rSelSupFunc0", ie.getNewPredID()))
}
case _ => {}
}
case _ => throw new Exception("rSelSupFunc0 error!")
}
}
}
}
|
tianran/tifmo
|
src/tifmo/document/SelSup.scala
|
Scala
|
bsd-2-clause
| 3,465 |
import scala.reflect.macros.blackbox.Context
import scala.language.experimental.macros
class Test
object Test {
def foo: Unit = macro fooImpl
def fooImpl(c: Context) = { import c.universe._; c.Expr[Unit](q"()") }
def main(args: Array[String]) {
try {
val method = classOf[Test].getMethod("foo")
sys.error("Static forwarder generated for macro: " + method)
} catch {
case _: NoSuchMethodException => // okay
}
}
}
|
felixmulder/scala
|
test/files/run/t5894.scala
|
Scala
|
bsd-3-clause
| 454 |
package com.mesosphere.cosmos.http
import com.mesosphere.http.MediaType
import com.mesosphere.util.UrlSchemeHeader
import com.twitter.finagle.http.Fields
import com.twitter.finagle.http.Method
import com.twitter.finagle.http.Request
import com.twitter.io.Buf
import io.circe.Encoder
import io.circe.syntax._
import io.finch.Input
final case class HttpRequest(
path: RpcPath,
headers: Map[String, String],
method: HttpRequestMethod
)
object HttpRequest {
def collectHeaders(entries: (String, Option[String])*): Map[String, String] = {
entries
.flatMap { case (key, value) => value.map(key -> _) }
.toMap
}
def get(path: RpcPath, accept: MediaType): HttpRequest = {
get(path, toHeader(accept))
}
def get(path: RpcPath, accept: Option[String]): HttpRequest = {
HttpRequest(path, collectHeaders(Fields.Accept -> accept), Get())
}
def post[A](
path: RpcPath,
body: A,
contentType: MediaType,
accept: MediaType
)(implicit encoder: Encoder[A]): HttpRequest = {
post(path, body.asJson.noSpaces, toHeader(contentType), toHeader(accept))
}
def post(
path: RpcPath,
body: String,
contentType: Option[String],
accept: Option[String]
): HttpRequest = {
val headers = collectHeaders(
Fields.Accept -> accept,
Fields.ContentType -> contentType
)
HttpRequest(path, headers, Post(Buf.Utf8(body)))
}
def post(
path: RpcPath,
body: Buf,
contentType: MediaType,
accept: MediaType,
host: String,
urlScheme: String
): HttpRequest = {
val headers = collectHeaders(
Fields.Accept -> toHeader(accept),
Fields.ContentType -> toHeader(contentType),
Fields.Host -> Some(host),
UrlSchemeHeader -> Some(urlScheme)
)
HttpRequest(path, headers, Post(body))
}
def toFinagle(cosmosRequest: HttpRequest): Request = {
val finagleRequest = cosmosRequest.method match {
case Get(params @ _*) =>
Request(cosmosRequest.path.path, params: _*)
case Post(buf) =>
val req = Request(Method.Post, cosmosRequest.path.path)
req.content = buf
req.contentLength = buf.length.toLong
req
}
finagleRequest.headerMap ++= cosmosRequest.headers
finagleRequest
}
def toFinchInput(cosmosRequest: HttpRequest): Input = {
val finagleRequest = toFinagle(cosmosRequest)
Input(
finagleRequest,
finagleRequest.path.split("/")
)
}
def toHeader(mediaType: MediaType): Option[String] = Some(mediaType.show)
}
|
dcos/cosmos
|
cosmos-test-common/src/main/scala/com/mesosphere/cosmos/http/HttpRequest.scala
|
Scala
|
apache-2.0
| 2,539 |
package com.olegych.scastie.web.routes
import com.olegych.scastie.api._
import com.olegych.scastie.web.oauth2._
import com.olegych.scastie.balancer._
import akka.util.Timeout
import akka.actor.{ActorRef, ActorSystem}
import akka.http.scaladsl.model.StatusCodes.Created
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._
import akka.pattern.ask
import scala.concurrent.duration.DurationInt
// temporary route for the scala-lang frontpage
class ScalaLangRoutes(
dispatchActor: ActorRef,
userDirectives: UserDirectives
)(implicit system: ActorSystem) {
import system.dispatcher
import userDirectives.optionalLogin
implicit val timeout: Timeout = Timeout(5.seconds)
// format: off
val routes: Route =
post(
extractClientIP(remoteAddress ⇒
optionalLogin(user ⇒
path("scala-lang")(
entity(as[String]) { code ⇒
val inputs =
InputsWithIpAndUser(
Inputs.default.copy(code = code),
UserTrace(
remoteAddress.toString,
None
)
)
complete(
(dispatchActor ? RunSnippet(inputs))
.mapTo[SnippetId]
.map(
snippetId =>
(
Created,
snippetId.url
)
)
)
}
)
)
)
)
}
|
OlegYch/scastie
|
server/src/main/scala/com.olegych.scastie.web/routes/ScalaLangRoutes.scala
|
Scala
|
apache-2.0
| 1,539 |
package com.arcusys.valamis.web.servlet.report.response
import com.arcusys.valamis.reports.model.AttemptedLessonsRow
/**
* Created by amikhailov on 23.11.16.
*/
object AttemptedLessonsConverter {
def toResponse(report: Seq[AttemptedLessonsRow]): Seq[AttemptedLessonsResponse] = {
report map { item =>
AttemptedLessonsResponse(item.name, Seq(
StateResponse(
"attempted",
item.countAttempted
),
StateResponse(
"completed",
item.countFinished
)
))
}
}
}
|
arcusys/Valamis
|
valamis-portlets/src/main/scala/com/arcusys/valamis/web/servlet/report/response/AttemptedLessonsConverter.scala
|
Scala
|
gpl-3.0
| 552 |
package com.clarifi.reporting
package relational
import com.clarifi.reporting.{ SortOrder }
import com.clarifi.reporting.Reporting._
import com.clarifi.machines._
import scalaz._
import Scalaz._
abstract class Scanner[G[_]](implicit G: Monad[G], Dist : Distributive[G]) { self =>
/** Scan a relation r, iterating over its records by f in the order specified.
* The order is given by a list of pairs where the first element specifies
* the column name and the second element specifies the order.
*/
def scanRel[A: Monoid](r: Relation[Nothing, Nothing],
f: Process[Record, A],
order: List[(String, SortOrder)] = List()): G[A]
def scanMem[A: Monoid](r: Mem[Nothing, Nothing],
f: Process[Record, A],
order: List[(String, SortOrder)] = List()): G[A]
def scanExt[A: Monoid](r: Ext[Nothing, Nothing],
f: Process[Record, A],
order: List[(String, SortOrder)] = List()): G[A]
def collect(r: Ext[Nothing, Nothing]): G[Vector[Record]] =
scanExt(r, Process.wrapping[Record], List())
val M = G
val D = Dist
}
|
ermine-language/ermine-legacy
|
src/main/scala/com/clarifi/reporting/relational/Scanner.scala
|
Scala
|
bsd-2-clause
| 1,184 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.deploy.rest.mesos
import java.io.File
import java.text.SimpleDateFormat
import java.util.{Date, Locale}
import java.util.concurrent.atomic.AtomicLong
import javax.servlet.http.HttpServletResponse
import org.apache.spark.{SparkConf, SPARK_VERSION => sparkVersion}
import org.apache.spark.deploy.Command
import org.apache.spark.deploy.mesos.MesosDriverDescription
import org.apache.spark.deploy.rest._
import org.apache.spark.scheduler.cluster.mesos.MesosClusterScheduler
import org.apache.spark.security.{ConfigSecurity, VaultHelper}
import org.apache.spark.util.Utils
/**
* A server that responds to requests submitted by the [[RestSubmissionClient]].
* All requests are forwarded to
* [[org.apache.spark.scheduler.cluster.mesos.MesosClusterScheduler]].
* This is intended to be used in Mesos cluster mode only.
* For more details about the REST submission please refer to [[RestSubmissionServer]] javadocs.
*/
private[spark] class MesosRestServer(
host: String,
requestedPort: Int,
masterConf: SparkConf,
scheduler: MesosClusterScheduler)
extends RestSubmissionServer(host, requestedPort, masterConf) {
protected override val submitRequestServlet =
new MesosSubmitRequestServlet(scheduler, masterConf)
protected override val killRequestServlet =
new MesosKillRequestServlet(scheduler, masterConf)
protected override val statusRequestServlet =
new MesosStatusRequestServlet(scheduler, masterConf)
}
private[mesos] class MesosSubmitRequestServlet(
scheduler: MesosClusterScheduler,
conf: SparkConf)
extends SubmitRequestServlet {
private val DEFAULT_SUPERVISE = false
private val DEFAULT_MEMORY = Utils.DEFAULT_DRIVER_MEM_MB // mb
private val DEFAULT_CORES = 1.0
private val nextDriverNumber = new AtomicLong(0)
// For application IDs
private def createDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US)
private def newDriverId(submitDate: Date): String =
f"driver-${createDateFormat.format(submitDate)}-${nextDriverNumber.incrementAndGet()}%04d"
/**
* Build a driver description from the fields specified in the submit request.
*
* This involves constructing a command that launches a mesos framework for the job.
* This does not currently consider fields used by python applications since python
* is not supported in mesos cluster mode yet.
*/
private def buildDriverDescription(request: CreateSubmissionRequest): MesosDriverDescription = {
// Required fields, including the main class because python is not yet supported
val appResource = Option(request.appResource).getOrElse {
throw new SubmitRestMissingFieldException("Application jar 'appResource' is missing.")
}
val mainClass = Option(request.mainClass).getOrElse {
throw new SubmitRestMissingFieldException("Main class 'mainClass' is missing.")
}
val appArgs = Option(request.appArgs).getOrElse {
throw new SubmitRestMissingFieldException("Application arguments 'appArgs' are missing.")
}
val environmentVariables = Option(request.environmentVariables).getOrElse {
throw new SubmitRestMissingFieldException("Environment variables 'environmentVariables' " +
"are missing.")
}
// Optional fields
val sparkProperties = request.sparkProperties
val driverExtraJavaOptions = sparkProperties.get("spark.driver.extraJavaOptions")
val driverExtraClassPath = sparkProperties.get("spark.driver.extraClassPath")
val driverExtraLibraryPath = sparkProperties.get("spark.driver.extraLibraryPath")
val superviseDriver = sparkProperties.get("spark.driver.supervise")
val driverMemory = sparkProperties.get("spark.driver.memory")
val driverCores = sparkProperties.get("spark.driver.cores")
val name = request.sparkProperties.getOrElse("spark.app.name", mainClass)
// Construct driver description
val conf = new SparkConf(false).setAll(sparkProperties)
val extraClassPath = driverExtraClassPath.toSeq.flatMap(_.split(File.pathSeparator))
val extraLibraryPath = driverExtraLibraryPath.toSeq.flatMap(_.split(File.pathSeparator))
val extraJavaOpts = driverExtraJavaOptions.map(Utils.splitCommandString).getOrElse(Seq.empty)
val sparkJavaOpts = Utils.sparkJavaOpts(conf)
val javaOpts = sparkJavaOpts ++ extraJavaOpts
val securitySparkOpts: Map[String, String] = {
if (ConfigSecurity.vaultURI.isDefined) {
val vaultURL = ConfigSecurity.vaultURI.get
(sparkProperties.get("spark.secret.vault.role"),
sys.env.get("VAULT_ROLE"),
sparkProperties.get("spark.secret.vault.token"),
sys.env.get("VAULT_TEMP_TOKEN")) match {
case (roleProp, roleEnv, None, None) if (roleEnv.isDefined || roleProp.isDefined) =>
val role = roleProp.getOrElse(roleEnv.get)
logTrace(s"obtaining vault secretID and role ID using role: $role")
val driverSecretId =
VaultHelper.getSecretIdFromVault(role).get
val driverRoleId =
VaultHelper.getRoleIdFromVault(role).get
Map("spark.mesos.driverEnv.VAULT_ROLE_ID" -> driverRoleId,
"spark.mesos.driverEnv.VAULT_SECRET_ID" -> driverSecretId)
case (None, None, tokenProp, tokenVal) if (tokenProp.isDefined
|| tokenVal.isDefined) =>
val vaultToken = tokenProp.getOrElse(tokenVal.get)
val temporalToken =
VaultHelper.getTemporalToken.get
logDebug(s"Obtained token from One time token; $temporalToken")
Map("spark.secret.vault.tempToken" -> temporalToken) ++ request.sparkProperties
.filter(_._1 != "spark.secret.vault.token")
case _ => Map[String, String]()
}
} else
{
logDebug("Non security options provided, executing Spark without security")
Map[String, String]()
}
}
val sparkPropertiesToSend = request.sparkProperties ++ securitySparkOpts
val command = new Command(
mainClass, appArgs, environmentVariables, extraClassPath, extraLibraryPath, javaOpts)
val actualSuperviseDriver = superviseDriver.map(_.toBoolean).getOrElse(DEFAULT_SUPERVISE)
val actualDriverMemory = driverMemory.map(Utils.memoryStringToMb).getOrElse(DEFAULT_MEMORY)
val actualDriverCores = driverCores.map(_.toDouble).getOrElse(DEFAULT_CORES)
val submitDate = new Date()
val submissionId = newDriverId(submitDate)
new MesosDriverDescription(
name, appResource, actualDriverMemory, actualDriverCores, actualSuperviseDriver,
command, sparkPropertiesToSend, submissionId, submitDate)
}
protected override def handleSubmit(
requestMessageJson: String,
requestMessage: SubmitRestProtocolMessage,
responseServlet: HttpServletResponse): SubmitRestProtocolResponse = {
requestMessage match {
case submitRequest: CreateSubmissionRequest =>
val driverDescription = buildDriverDescription(submitRequest)
val s = scheduler.submitDriver(driverDescription)
s.serverSparkVersion = sparkVersion
val unknownFields = findUnknownFields(requestMessageJson, requestMessage)
if (unknownFields.nonEmpty) {
// If there are fields that the server does not know about, warn the client
s.unknownFields = unknownFields
}
s
case unexpected =>
responseServlet.setStatus(HttpServletResponse.SC_BAD_REQUEST)
handleError(s"Received message of unexpected type ${unexpected.messageType}.")
}
}
}
private[mesos] class MesosKillRequestServlet(scheduler: MesosClusterScheduler, conf: SparkConf)
extends KillRequestServlet {
protected override def handleKill(submissionId: String): KillSubmissionResponse = {
val k = scheduler.killDriver(submissionId)
k.serverSparkVersion = sparkVersion
k
}
}
private[mesos] class MesosStatusRequestServlet(scheduler: MesosClusterScheduler, conf: SparkConf)
extends StatusRequestServlet {
protected override def handleStatus(submissionId: String): SubmissionStatusResponse = {
val d = scheduler.getDriverStatus(submissionId)
d.serverSparkVersion = sparkVersion
d
}
}
|
jlopezmalla/spark
|
resource-managers/mesos/src/main/scala/org/apache/spark/deploy/rest/mesos/MesosRestServer.scala
|
Scala
|
apache-2.0
| 9,143 |
package org.jetbrains.plugins.scala.lang.resolve
import org.jetbrains.plugins.scala.base.ScalaLightCodeInsightFixtureTestAdapter
class CustomCopyMethodResolveTest extends ScalaLightCodeInsightFixtureTestAdapter with SimpleResolveTestBase {
import SimpleResolveTestBase._
def testSCL15809(): Unit = doResolveTest(
s"""
|case class Example(foo: Int) {
| private def co${REFTGT}py(foo: Int = this.foo): Example = {
| Example(foo + 1)
| }
| def increase(value: Int): Example = {
| cop${REFSRC}y(foo = value)
| }
|}
|""".stripMargin
)
}
|
JetBrains/intellij-scala
|
scala/scala-impl/test/org/jetbrains/plugins/scala/lang/resolve/CustomCopyMethodResolveTest.scala
|
Scala
|
apache-2.0
| 618 |
/** MACHINE-GENERATED FROM AVRO SCHEMA. DO NOT EDIT DIRECTLY */
package example.idl
final case class BinaryIdl(data: Array[Byte])
|
julianpeeters/avrohugger
|
avrohugger-core/src/test/expected/standard/example/idl/BinaryIdl.scala
|
Scala
|
apache-2.0
| 130 |
package ch.megard.akka.http.cors.javadsl.settings
import java.util.Optional
import akka.actor.ActorSystem
import akka.annotation.DoNotInherit
import akka.http.javadsl.model.HttpMethod
import ch.megard.akka.http.cors.javadsl.model.{HttpHeaderRange, HttpOriginMatcher}
import ch.megard.akka.http.cors.scaladsl
import ch.megard.akka.http.cors.scaladsl.settings.CorsSettingsImpl
import com.typesafe.config.Config
/** Public API but not intended for subclassing
*/
@DoNotInherit
abstract class CorsSettings { self: CorsSettingsImpl =>
def getAllowGenericHttpRequests: Boolean
def getAllowCredentials: Boolean
def getAllowedOrigins: HttpOriginMatcher
def getAllowedHeaders: HttpHeaderRange
def getAllowedMethods: java.lang.Iterable[HttpMethod]
def getExposedHeaders: java.lang.Iterable[String]
def getMaxAge: Optional[Long]
def withAllowGenericHttpRequests(newValue: Boolean): CorsSettings
def withAllowCredentials(newValue: Boolean): CorsSettings
def withAllowedOrigins(newValue: HttpOriginMatcher): CorsSettings
def withAllowedHeaders(newValue: HttpHeaderRange): CorsSettings
def withAllowedMethods(newValue: java.lang.Iterable[HttpMethod]): CorsSettings
def withExposedHeaders(newValue: java.lang.Iterable[String]): CorsSettings
def withMaxAge(newValue: Optional[Long]): CorsSettings
}
object CorsSettings {
/** Creates an instance of settings using the given Config.
*/
def create(config: Config): CorsSettings = scaladsl.settings.CorsSettings(config)
/** Creates an instance of settings using the given String of config overrides to override
* settings set in the class loader of this class (i.e. by application.conf or reference.conf files in
* the class loader of this class).
*/
def create(configOverrides: String): CorsSettings = scaladsl.settings.CorsSettings(configOverrides)
/** Creates an instance of CorsSettings using the configuration provided by the given ActorSystem.
*/
def create(system: ActorSystem): CorsSettings = scaladsl.settings.CorsSettings(system)
/** Settings from the default loaded configuration.
* Note that application code may want to use the `apply()` methods instead
* to have more control over the source of the configuration.
*/
def defaultSettings: CorsSettings = scaladsl.settings.CorsSettings.defaultSettings
}
|
tarfaa/akka-http-cors
|
akka-http-cors/src/main/scala/ch/megard/akka/http/cors/javadsl/settings/CorsSettings.scala
|
Scala
|
apache-2.0
| 2,334 |
/**
* Copyright 2016, deepsense.io
*
* 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.deepsense.deeplang.refl
import java.io.File
import java.net.{URL, URLClassLoader}
import scala.collection.JavaConversions._
import org.reflections.Reflections
import org.reflections.util.ConfigurationBuilder
import io.deepsense.commons.utils.Logging
import io.deepsense.deeplang.catalogs.doperable.DOperableCatalog
import io.deepsense.deeplang.catalogs.doperations.DOperationsCatalog
import io.deepsense.deeplang.{DOperation, DOperationCategories, TypeUtils}
/**
* Scanner for operations and operables. It scans given jars and additionally a jar containing this
* class.
* @param jarsUrls Jars to scan
*/
class CatalogScanner(jarsUrls: Seq[URL]) extends Logging {
/**
* Scans jars on classpath for classes annotated with [[io.deepsense.deeplang.refl.Register
* Register]]
* annotation and at the same time implementing [[io.deepsense.deeplang.DOperation DOperation]]
* interface. Found classes are then registered in appropriate catalogs.
*
* @see [[io.deepsense.deeplang.refl.Register Register]]
*/
def scanAndRegister(
dOperableCatalog: DOperableCatalog,
dOperationsCatalog: DOperationsCatalog
): Unit = {
logger.info(
s"Scanning registrables. Following jars will be scanned: ${jarsUrls.mkString(";")}.")
for (registrable <- scanForRegistrables()) {
logger.debug(s"Trying to register class $registrable")
registrable match {
case DOperationMatcher(doperation) => registerDOperation(dOperationsCatalog, doperation)
case other => logger.warn(s"Only DOperation can be `@Register`ed")
}
}
}
private def scanForRegistrables(): Set[Class[_]] = {
val urls = thisJarURLOpt ++ jarsUrls
if (urls.nonEmpty) {
val configBuilder = ConfigurationBuilder.build(urls.toSeq: _*)
if (jarsUrls.nonEmpty) {
configBuilder.addClassLoader(URLClassLoader.newInstance(jarsUrls.toArray))
}
new Reflections(configBuilder).getTypesAnnotatedWith(classOf[Register]).toSet
} else {
Set()
}
}
private lazy val thisJarURLOpt: Option[URL] = {
val jarRegex = """jar:(file:.*\\.jar)!.*""".r
val url = getClass.getClassLoader.getResource(
getClass.getCanonicalName.replaceAll("\\\\.", File.separator) + ".class")
url.toString match {
case jarRegex(jar) => Some(new URL(jar))
case _ => None
}
}
private def registerDOperation(
catalog: DOperationsCatalog,
operation: Class[DOperation]
): Unit = TypeUtils.constructorForClass(operation) match {
case Some(constructor) =>
catalog.registerDOperation(
DOperationCategories.UserDefined,
() => TypeUtils.createInstance[DOperation](constructor)
)
case None => logger.error(
s"Class $operation could not be registered." +
"It needs to have parameterless constructor"
)
}
class AssignableFromExtractor[T](targetClass: Class[T]) {
def unapply(clazz: Class[_]): Option[Class[T]] = {
if (targetClass.isAssignableFrom(clazz)) {
Some(clazz.asInstanceOf[Class[T]])
} else {
None
}
}
}
object DOperationMatcher extends AssignableFromExtractor(classOf[DOperation])
}
|
deepsense-io/seahorse-workflow-executor
|
deeplang/src/main/scala/io/deepsense/deeplang/refl/CatalogScanner.scala
|
Scala
|
apache-2.0
| 3,815 |
package lila.api
import akka.actor._
import com.typesafe.config.Config
import lila.common.PimpedConfig._
import lila.simul.Simul
import scala.collection.JavaConversions._
import scala.concurrent.duration._
final class Env(
config: Config,
db: lila.db.Env,
renderer: ActorSelection,
system: ActorSystem,
scheduler: lila.common.Scheduler,
roundJsonView: lila.round.JsonView,
noteApi: lila.round.NoteApi,
forecastApi: lila.round.ForecastApi,
relationApi: lila.relation.RelationApi,
bookmarkApi: lila.bookmark.BookmarkApi,
getTourAndRanks: lila.game.Game => Fu[Option[lila.tournament.TourAndRanks]],
crosstableApi: lila.game.CrosstableApi,
prefApi: lila.pref.PrefApi,
gamePgnDump: lila.game.PgnDump,
gameCache: lila.game.Cached,
userEnv: lila.user.Env,
analyseEnv: lila.analyse.Env,
lobbyEnv: lila.lobby.Env,
setupEnv: lila.setup.Env,
getSimul: Simul.ID => Fu[Option[Simul]],
getSimulName: Simul.ID => Option[String],
getTournamentName: String => Option[String],
pools: List[lila.pool.PoolConfig],
val isProd: Boolean) {
val CliUsername = config getString "cli.username"
val apiToken = config getString "api.token"
object Net {
val Domain = config getString "net.domain"
val Protocol = config getString "net.protocol"
val BaseUrl = config getString "net.base_url"
val Port = config getInt "http.port"
val AssetDomain = config getString "net.asset.domain"
val AssetVersion = config getInt "net.asset.version"
val Email = config getString "net.email"
val Crawlable = config getBoolean "net.crawlable"
}
val PrismicApiUrl = config getString "prismic.api_url"
val EditorAnimationDuration = config duration "editor.animation.duration"
val ExplorerEndpoint = config getString "explorer.endpoint"
val TablebaseEndpoint = config getString "explorer.tablebase.endpoint"
private val InfluxEventEndpoint = config getString "api.influx_event.endpoint"
private val InfluxEventEnv = config getString "api.influx_event.env"
object assetVersion {
import reactivemongo.bson._
import lila.db.dsl._
private val coll = db("flag")
private val cache = lila.memo.MixedCache.single[Int](
name = "asset.version",
f = coll.primitiveOne[BSONNumberLike]($id("asset"), "version").map {
_.fold(Net.AssetVersion)(_.toInt max Net.AssetVersion)
},
timeToLive = 10.seconds,
default = Net.AssetVersion,
logger = lila.log("assetVersion"))
def get = cache get true
}
object Accessibility {
val blindCookieName = config getString "accessibility.blind.cookie.name"
val blindCookieMaxAge = config getInt "accessibility.blind.cookie.max_age"
private val blindCookieSalt = config getString "accessibility.blind.cookie.salt"
def hash(implicit ctx: lila.user.UserContext) = {
import com.roundeights.hasher.Implicits._
(ctx.userId | "anon").salt(blindCookieSalt).md5.hex
}
}
val pgnDump = new PgnDump(
dumper = gamePgnDump,
simulName = getSimulName,
tournamentName = getTournamentName)
val userApi = new UserApi(
jsonView = userEnv.jsonView,
makeUrl = makeUrl,
relationApi = relationApi,
bookmarkApi = bookmarkApi,
crosstableApi = crosstableApi,
gameCache = gameCache,
prefApi = prefApi)
val gameApi = new GameApi(
netBaseUrl = Net.BaseUrl,
apiToken = apiToken,
pgnDump = pgnDump,
gameCache = gameCache)
val userGameApi = new UserGameApi(
bookmarkApi = bookmarkApi,
lightUser = userEnv.lightUser)
val roundApi = new RoundApiBalancer(
api = new RoundApi(
jsonView = roundJsonView,
noteApi = noteApi,
forecastApi = forecastApi,
bookmarkApi = bookmarkApi,
getTourAndRanks = getTourAndRanks,
getSimul = getSimul,
lightUser = userEnv.lightUser),
system = system,
nbActors = math.max(1, math.min(16, Runtime.getRuntime.availableProcessors - 1)))
val lobbyApi = new LobbyApi(
getFilter = setupEnv.filter,
lightUser = userEnv.lightUser,
seekApi = lobbyEnv.seekApi,
pools = pools)
private def makeUrl(path: String): String = s"${Net.BaseUrl}/$path"
lazy val cli = new Cli(system.lilaBus, renderer)
KamonPusher.start(system) {
new KamonPusher(countUsers = () => userEnv.onlineUserIdMemo.count)
}
if (InfluxEventEnv != "dev") system.actorOf(Props(new InfluxEvent(
endpoint = InfluxEventEndpoint,
env = InfluxEventEnv
)), name = "influx-event")
}
object Env {
lazy val current = "api" boot new Env(
config = lila.common.PlayApp.loadConfig,
db = lila.db.Env.current,
renderer = lila.hub.Env.current.actor.renderer,
userEnv = lila.user.Env.current,
analyseEnv = lila.analyse.Env.current,
lobbyEnv = lila.lobby.Env.current,
setupEnv = lila.setup.Env.current,
getSimul = lila.simul.Env.current.repo.find,
getSimulName = lila.simul.Env.current.cached.name,
getTournamentName = lila.tournament.Env.current.cached.name,
roundJsonView = lila.round.Env.current.jsonView,
noteApi = lila.round.Env.current.noteApi,
forecastApi = lila.round.Env.current.forecastApi,
relationApi = lila.relation.Env.current.api,
bookmarkApi = lila.bookmark.Env.current.api,
getTourAndRanks = lila.tournament.Env.current.tourAndRanks,
crosstableApi = lila.game.Env.current.crosstableApi,
prefApi = lila.pref.Env.current.api,
gamePgnDump = lila.game.Env.current.pgnDump,
gameCache = lila.game.Env.current.cached,
system = lila.common.PlayApp.system,
scheduler = lila.common.PlayApp.scheduler,
pools = lila.pool.Env.current.api.configs,
isProd = lila.common.PlayApp.isProd)
}
|
clarkerubber/lila
|
modules/api/src/main/Env.scala
|
Scala
|
agpl-3.0
| 5,708 |
package screact
import scutil.lang.*
import scutil.log.*
/** A final target for events emitted by an Event. Targets always get notified after all other Nodes. */
private final class Target[T](effect:Effect[T], source:Reactive[?,T]) extends Node with AutoCloseable with Logging {
val sinks = NoSinks
val rank = Integer.MAX_VALUE
def update():Update = {
try {
source.msg foreach effect
}
catch { case e:Exception =>
// TODO move logging into the Domain
ERROR("update failed", this.toString, e)
}
Unchanged
}
// TODO deal with overflows
private [screact] def pushDown(rank:Int):Unit = {}
def reset():Unit = {}
def close():Unit = {
source.sinks remove this
}
source.sinks add this
}
|
ritschwumm/screact
|
src/main/scala/screact/Target.scala
|
Scala
|
bsd-2-clause
| 717 |
package com.sksamuel.avro4s.github
import java.io.ByteArrayOutputStream
import com.sksamuel.avro4s.{AvroFixed, AvroInputStream, AvroOutputStream, AvroSchema}
import org.scalatest.{FunSuite, Matchers}
case class Data(uuid: Option[UUID])
case class UUID(@AvroFixed(8) bytes: Array[Byte])
class GithubIssue193 extends FunSuite with Matchers {
test("Converting data with an optional fixed type field to GenericRecord fails #193") {
val baos = new ByteArrayOutputStream()
val output = AvroOutputStream.data[Data].to(baos).build(AvroSchema[Data])
output.write(Data(Some(UUID(Array[Byte](0, 1, 2, 3, 4, 5, 6, 7)))))
output.write(Data(None))
output.write(Data(Some(UUID(Array[Byte](7, 6, 5, 4, 3, 2, 1, 0)))))
output.close()
val input = AvroInputStream.data[Data].from(baos.toByteArray).build
val datas = input.iterator.toList
datas.head.uuid.get.bytes should equal(Array[Byte](0, 1, 2, 3, 4, 5, 6, 7))
datas(1).uuid shouldBe None
datas.last.uuid.get.bytes should equal(Array[Byte](7, 6, 5, 4, 3, 2, 1, 0))
input.close()
}
}
|
51zero/avro4s
|
avro4s-core/src/test/scala/com/sksamuel/avro4s/github/GithubIssue193.scala
|
Scala
|
mit
| 1,077 |
package org.scalatra
package servlet
import javax.servlet.http.HttpSession
/**
* Extension methods to the standard HttpSession.
*/
case class RichSession(session: HttpSession) extends AttributesMap {
def id: String = session.getId
protected def attributes: HttpSession = session
}
|
lightvector/scalatra
|
core/src/main/scala/org/scalatra/servlet/RichSession.scala
|
Scala
|
bsd-2-clause
| 292 |
package com.datastax.spark.connector
import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream}
import java.text.SimpleDateFormat
import org.junit.Assert._
import org.scalatest.{FunSuite, Matchers}
class CassandraRowTest extends FunSuite with Matchers {
test("basicAccessTest") {
val row = new CassandraRow(CassandraRowMetadata(Array("value")), Array("1"))
assertEquals(1, row.size)
assertEquals(Some("1"), row.getStringOption(0))
assertEquals(Some("1"), row.getStringOption("value"))
assertEquals("1", row.getString(0))
assertEquals("1", row.getString("value"))
}
test("nullAccessTest") {
val row = new CassandraRow(CassandraRowMetadata(Array("value")), Array(null))
assertEquals(None, row.getStringOption(0))
assertEquals(None, row.getStringOption("value"))
assertEquals(1, row.size)
}
test("NoneAccessTest") {
val row = new CassandraRow(CassandraRowMetadata(Array("value")), Array(None))
assertEquals(None, row.getStringOption(0))
assertEquals(None, row.getStringOption("value"))
assertEquals(1, row.size)
}
test("nullToStringTest") {
val row = new CassandraRow(CassandraRowMetadata(Array("value")), Array(null))
assertEquals("CassandraRow{value: null}", row.toString())
}
test("nonExistentColumnAccessTest") {
val row = new CassandraRow(CassandraRowMetadata(Array("value")), Array(null))
intercept[ColumnNotFoundException] {
row.getString("wring-column")
}
}
test("primitiveConversionTest") {
val dateStr = "2014-04-08 14:47:00+0100"
val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
val date = dateFormat.parse(dateStr)
val integer = Integer.valueOf(2)
val string = "3"
val row = new CassandraRow(CassandraRowMetadata(Array("date", "integer", "string")), Array(date, integer, string))
assertEquals(3, row.size)
assertEquals(date, row.getDate("date"))
assertEquals(date.getTime, row.getLong("date"))
assertEquals(dateFormat.format(date), row.getString("date"))
assertEquals("2", row.getString("integer"))
assertEquals(2, row.getInt("integer"))
assertEquals(2L, row.getLong("integer"))
assertEquals(2.0, row.getDouble("integer"), 0.0001)
assertEquals(2.0f, row.getFloat("integer"), 0.0001f)
assertEquals(BigInt(2), row.getVarInt("integer"))
assertEquals(BigDecimal(2), row.getDecimal("integer"))
assertEquals("3", row.getString("string"))
assertEquals(3, row.getInt("string"))
assertEquals(3L, row.getLong("string"))
assertEquals(BigInt(3), row.getVarInt("string"))
assertEquals(BigDecimal(3), row.getDecimal("string"))
}
test("collectionConversionTest") {
val list = new java.util.ArrayList[String]() // list<varchar>
list.add("1")
list.add("1")
list.add("2")
val set = new java.util.HashSet[String]() // set<varchar>
set.add("apple")
set.add("banana")
set.add("mango")
val map = new java.util.HashMap[String, Int]() // map<varchar, int>
map.put("a", 1)
map.put("b", 2)
map.put("c", 3)
val row = new CassandraRow(CassandraRowMetadata(Array("list", "set", "map")), Array(list, set, map))
val scalaList = row.getList[Int]("list")
assertEquals(Vector(1, 1, 2), scalaList)
val scalaListAsSet = row.getSet[Int]("list")
assertEquals(Set(1, 2), scalaListAsSet)
val scalaSet = row.getSet[String]("set")
assertEquals(Set("apple", "banana", "mango"), scalaSet)
val scalaMap = row.getMap[String, Long]("map")
assertEquals(Map("a" → 1, "b" → 2, "c" → 3), scalaMap)
val scalaMapAsSet = row.getSet[(String, String)]("map")
assertEquals(Set("a" → "1", "b" → "2", "c" → "3"), scalaMapAsSet)
}
test("serializationTest") {
val row = new CassandraRow(CassandraRowMetadata(Array("value")), Array("1"))
val bs = new ByteArrayOutputStream
val os = new ObjectOutputStream(bs)
os.writeObject(row)
os.close()
val is = new ObjectInputStream(new ByteArrayInputStream(bs.toByteArray))
val row2 = is.readObject().asInstanceOf[CassandraRow]
is.close()
assertEquals("1", row2.getString("value"))
}
}
|
datastax/spark-cassandra-connector
|
driver/src/test/scala/com/datastax/spark/connector/CassandraRowTest.scala
|
Scala
|
apache-2.0
| 4,193 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.predictionio.examples.recommendation
import org.apache.predictionio.controller.PAlgorithm
import org.apache.predictionio.controller.Params
import org.apache.predictionio.data.storage.BiMap
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.rdd.RDD
import org.apache.spark.mllib.recommendation.ALS
import org.apache.spark.mllib.recommendation.{Rating => MLlibRating}
import org.apache.spark.mllib.recommendation.ALSModel
import grizzled.slf4j.Logger
case class ALSAlgorithmParams(
rank: Int,
numIterations: Int,
lambda: Double,
seed: Option[Long]) extends Params
class ALSAlgorithm(val ap: ALSAlgorithmParams)
extends PAlgorithm[PreparedData, ALSModel, Query, PredictedResult] {
@transient lazy val logger = Logger[this.type]
if (ap.numIterations > 30) {
logger.warn(
s"ALSAlgorithmParams.numIterations > 30, current: ${ap.numIterations}. " +
s"There is a chance of running to StackOverflowException." +
s"To remedy it, set lower numIterations or checkpoint parameters.")
}
def train(sc: SparkContext, data: PreparedData): ALSModel = {
// MLLib ALS cannot handle empty training data.
require(!data.ratings.take(1).isEmpty,
s"RDD[Rating] in PreparedData cannot be empty." +
" Please check if DataSource generates TrainingData" +
" and Preparator generates PreparedData correctly.")
// Convert user and item String IDs to Int index for MLlib
val userStringIntMap = BiMap.stringInt(data.ratings.map(_.user))
val itemStringIntMap = BiMap.stringInt(data.ratings.map(_.item))
val mllibRatings = data.ratings.map( r =>
// MLlibRating requires integer index for user and item
MLlibRating(userStringIntMap(r.user), itemStringIntMap(r.item), r.rating)
)
// seed for MLlib ALS
val seed = ap.seed.getOrElse(System.nanoTime)
// Set checkpoint directory
// sc.setCheckpointDir("checkpoint")
// If you only have one type of implicit event (Eg. "view" event only),
// set implicitPrefs to true
// MODIFIED
val implicitPrefs = true
val als = new ALS()
als.setUserBlocks(-1)
als.setProductBlocks(-1)
als.setRank(ap.rank)
als.setIterations(ap.numIterations)
als.setLambda(ap.lambda)
als.setImplicitPrefs(implicitPrefs)
als.setAlpha(1.0)
als.setSeed(seed)
als.setCheckpointInterval(10)
val m = als.run(mllibRatings)
new ALSModel(
rank = m.rank,
userFeatures = m.userFeatures,
productFeatures = m.productFeatures,
userStringIntMap = userStringIntMap,
itemStringIntMap = itemStringIntMap)
}
def predict(model: ALSModel, query: Query): PredictedResult = {
// Convert String ID to Int index for Mllib
model.userStringIntMap.get(query.user).map { userInt =>
// create inverse view of itemStringIntMap
val itemIntStringMap = model.itemStringIntMap.inverse
// recommendProducts() returns Array[MLlibRating], which uses item Int
// index. Convert it to String ID for returning PredictedResult
val itemScores = model.recommendProducts(userInt, query.num)
.map (r => ItemScore(itemIntStringMap(r.product), r.rating))
PredictedResult(itemScores)
}.getOrElse{
logger.info(s"No prediction for unknown user ${query.user}.")
PredictedResult(Array.empty)
}
}
// This function is used by the evaluation module, where a batch of queries is sent to this engine
// for evaluation purpose.
override def batchPredict(model: ALSModel, queries: RDD[(Long, Query)]): RDD[(Long, PredictedResult)] = {
val userIxQueries: RDD[(Int, (Long, Query))] = queries
.map { case (ix, query) => {
// If user not found, then the index is -1
val userIx = model.userStringIntMap.get(query.user).getOrElse(-1)
(userIx, (ix, query))
}}
// Cross product of all valid users from the queries and products in the model.
val usersProducts: RDD[(Int, Int)] = userIxQueries
.keys
.filter(_ != -1)
.cartesian(model.productFeatures.map(_._1))
// Call mllib ALS's predict function.
val ratings: RDD[MLlibRating] = model.predict(usersProducts)
// The following code construct predicted results from mllib's ratings.
// Not optimal implementation. Instead of groupBy, should use combineByKey with a PriorityQueue
val userRatings: RDD[(Int, Iterable[MLlibRating])] = ratings.groupBy(_.user)
userIxQueries.leftOuterJoin(userRatings)
.map {
// When there are ratings
case (userIx, ((ix, query), Some(ratings))) => {
val topItemScores: Array[ItemScore] = ratings
.toArray
.sortBy(_.rating)(Ordering.Double.reverse) // note: from large to small ordering
.take(query.num)
.map { rating => ItemScore(
model.itemStringIntMap.inverse(rating.product),
rating.rating) }
(ix, PredictedResult(itemScores = topItemScores))
}
// When user doesn't exist in training data
case (userIx, ((ix, query), None)) => {
require(userIx == -1)
(ix, PredictedResult(itemScores = Array.empty))
}
}
}
}
|
dszeto/incubator-predictionio
|
examples/scala-parallel-recommendation/train-with-view-event/src/main/scala/ALSAlgorithm.scala
|
Scala
|
apache-2.0
| 5,989 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.