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
|
---|---|---|---|---|---|
abstract class Coroutine[+T] {
def continue: Option[T]
}
object Macros {
import scala.quoted.*
inline def coroutine[T](inline body: Any): Coroutine[T] = ${ coroutineImpl('{body}) }
def coroutineImpl[T: Type](expr: Expr[_ <: Any])(using Quotes): Expr[Coroutine[T]] = {
import quotes.reflect.*
'{
new Coroutine[T] {
var state: Int = 0
def continue: Option[T] = ${
'{
state = 1 //if this line is commented there are no compile errors anymore!!!
None
}
}
}
}
}
}
| dotty-staging/dotty | tests/pos-macros/i8651b.scala | Scala | apache-2.0 | 553 |
/*
* 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.thriftserver
import java.io.IOException
import java.util.{List => JList}
import javax.security.auth.login.LoginException
import scala.collection.JavaConverters._
import scala.util.control.NonFatal
import org.apache.hadoop.hive.conf.HiveConf
import org.apache.hadoop.hive.conf.HiveConf.ConfVars
import org.apache.hadoop.hive.shims.Utils
import org.apache.hadoop.security.{SecurityUtil, UserGroupInformation}
import org.apache.hive.service.{AbstractService, CompositeService, Service, ServiceException}
import org.apache.hive.service.Service.STATE
import org.apache.hive.service.auth.HiveAuthFactory
import org.apache.hive.service.cli._
import org.apache.hive.service.server.HiveServer2
import org.slf4j.Logger
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.hive.thriftserver.ReflectionUtils._
private[hive] class SparkSQLCLIService(hiveServer: HiveServer2, sqlContext: SQLContext)
extends CLIService(hiveServer)
with ReflectedCompositeService {
override def init(hiveConf: HiveConf): Unit = {
setSuperField(this, "hiveConf", hiveConf)
val sparkSqlSessionManager = new SparkSQLSessionManager(hiveServer, sqlContext)
setSuperField(this, "sessionManager", sparkSqlSessionManager)
addService(sparkSqlSessionManager)
var sparkServiceUGI: UserGroupInformation = null
var httpUGI: UserGroupInformation = null
if (UserGroupInformation.isSecurityEnabled) {
try {
val principal = hiveConf.getVar(ConfVars.HIVE_SERVER2_KERBEROS_PRINCIPAL)
val keyTabFile = hiveConf.getVar(ConfVars.HIVE_SERVER2_KERBEROS_KEYTAB)
if (principal.isEmpty || keyTabFile.isEmpty) {
throw new IOException(
"HiveServer2 Kerberos principal or keytab is not correctly configured")
}
val originalUgi = UserGroupInformation.getCurrentUser
sparkServiceUGI = if (HiveAuthFactory.needUgiLogin(originalUgi,
SecurityUtil.getServerPrincipal(principal, "0.0.0.0"), keyTabFile)) {
HiveAuthFactory.loginFromKeytab(hiveConf)
Utils.getUGI()
} else {
originalUgi
}
setSuperField(this, "serviceUGI", sparkServiceUGI)
} catch {
case e @ (_: IOException | _: LoginException) =>
throw new ServiceException("Unable to login to kerberos with given principal/keytab", e)
}
// Try creating spnego UGI if it is configured.
val principal = hiveConf.getVar(ConfVars.HIVE_SERVER2_SPNEGO_PRINCIPAL).trim
val keyTabFile = hiveConf.getVar(ConfVars.HIVE_SERVER2_SPNEGO_KEYTAB).trim
if (principal.nonEmpty && keyTabFile.nonEmpty) {
try {
httpUGI = HiveAuthFactory.loginFromSpnegoKeytabAndReturnUGI(hiveConf)
setSuperField(this, "httpUGI", httpUGI)
} catch {
case e: IOException =>
throw new ServiceException("Unable to login to spnego with given principal " +
s"$principal and keytab $keyTabFile: $e", e)
}
}
}
initCompositeService(hiveConf)
}
/**
* the super class [[CLIService#start]] starts a useless dummy metastore client, skip it and call
* the ancestor [[CompositeService#start]] directly.
*/
override def start(): Unit = startCompositeService()
override def getInfo(sessionHandle: SessionHandle, getInfoType: GetInfoType): GetInfoValue = {
getInfoType match {
case GetInfoType.CLI_SERVER_NAME => new GetInfoValue("Spark SQL")
case GetInfoType.CLI_DBMS_NAME => new GetInfoValue("Spark SQL")
case GetInfoType.CLI_DBMS_VER => new GetInfoValue(sqlContext.sparkContext.version)
case _ => super.getInfo(sessionHandle, getInfoType)
}
}
}
private[thriftserver] trait ReflectedCompositeService { this: AbstractService =>
private val logInfo = (msg: String) => getAncestorField[Logger](this, 3, "LOG").info(msg)
private val logError = (msg: String, e: Throwable) =>
getAncestorField[Logger](this, 3, "LOG").error(msg, e)
def initCompositeService(hiveConf: HiveConf): Unit = {
// Emulating `CompositeService.init(hiveConf)`
val serviceList = getAncestorField[JList[Service]](this, 2, "serviceList")
serviceList.asScala.foreach(_.init(hiveConf))
// Emulating `AbstractService.init(hiveConf)`
invoke(classOf[AbstractService], this, "ensureCurrentState", classOf[STATE] -> STATE.NOTINITED)
setAncestorField(this, 3, "hiveConf", hiveConf)
invoke(classOf[AbstractService], this, "changeState", classOf[STATE] -> STATE.INITED)
logInfo(s"Service: $getName is inited.")
}
def startCompositeService(): Unit = {
// Emulating `CompositeService.start`
val serviceList = getAncestorField[JList[Service]](this, 2, "serviceList")
var serviceStartCount = 0
try {
serviceList.asScala.foreach { service =>
service.start()
serviceStartCount += 1
}
// Emulating `AbstractService.start`
val startTime = new java.lang.Long(System.currentTimeMillis())
setAncestorField(this, 3, "startTime", startTime)
invoke(classOf[AbstractService], this, "ensureCurrentState", classOf[STATE] -> STATE.INITED)
invoke(classOf[AbstractService], this, "changeState", classOf[STATE] -> STATE.STARTED)
logInfo(s"Service: $getName is started.")
} catch {
case NonFatal(e) =>
logError(s"Error starting services $getName", e)
invoke(classOf[CompositeService], this, "stop",
classOf[Int] -> new Integer(serviceStartCount))
throw new ServiceException("Failed to Start " + getName, e)
}
}
}
| shuangshuangwang/spark | sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkSQLCLIService.scala | Scala | apache-2.0 | 6,385 |
package akka.ainterface.remote.epmd.client
import java.nio.charset.StandardCharsets
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen
import org.scalatest.WordSpec
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import scodec.bits.BitVector
import scodec.{Attempt, DecodeResult, Decoder, Err}
class Port2RespSpec extends WordSpec with GeneratorDrivenPropertyChecks {
"codec" should {
"succeeds to decode" when {
"bits is valid" in {
forAll(Gen.chooseNum(0, 0xffff), arbitrary[String]) {
(port: Int, alive: String) =>
val tag = BitVector(119)
val result = BitVector(0)
val portNo = BitVector.fromInt(port, size = 16)
val nodeType = BitVector(77)
val protocol = BitVector(0)
val highestVersion = BitVector.fromInt(5, size = 16)
val lowestVersion = BitVector.fromInt(5, size = 16)
val aliveBytes = alive.getBytes(StandardCharsets.UTF_8)
val nlen = BitVector.fromInt(aliveBytes.length, size = 16)
val nodeName = BitVector(aliveBytes)
val elen = BitVector.fromInt(0, size = 16)
val extra = BitVector.empty
val bits = tag ++ result ++ portNo ++ nodeType ++ protocol ++ highestVersion ++ lowestVersion ++ nlen ++ nodeName ++ elen ++ extra
val actual = Decoder.decode[Port2Resp](bits)
val resp = Port2RespSuccess(port, alive)
val expected = Attempt.Successful(DecodeResult(resp, BitVector.empty))
assert(actual === expected)
}
}
}
"decode and return InsufficientBits" when {
"the response has the successful result but need more bits" in {
val actual = Decoder.decode[Port2Resp](BitVector(119, 0))
val expected = Attempt.failure(Err.InsufficientBits(16, 0, Nil))
assert(actual === expected)
}
}
"fails to decode" when {
"bits is invalid" in {
forAll(Gen.chooseNum(1, 255)) { result: Int =>
val actual = Decoder.decode[Port2Resp](BitVector(119, result))
val expected = Attempt.Successful(DecodeResult(Port2RespFailure(result), BitVector.empty))
assert(actual === expected)
}
}
}
}
}
| ainterface/ainterface | ainterface/src/test/scala/akka/ainterface/remote/epmd/client/Port2RespSpec.scala | Scala | apache-2.0 | 2,269 |
/*
* 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 jp.gihyo.spark.ch08
import jp.gihyo.spark.{SparkFunSuite, TestSparkContext}
class GeneratePurchaseLogExampleSuite extends SparkFunSuite with TestSparkContext {
test("run with RandomSelection") {
implicit val recOpts: RecommendLogOptions = RecommendLogOptions(10, 10, 2)
implicit val pidGenerator = ProductIdGenerator.fromString("RandomSelection")
GeneratePurchaseLogExample.run(sc)
}
test("run with PreferentialAttachment") {
implicit val recOpts: RecommendLogOptions = RecommendLogOptions(10, 10, 2)
implicit val pidGenerator = ProductIdGenerator.fromString("PreferentialAttachment")
GeneratePurchaseLogExample.run(sc)
}
}
| yu-iskw/gihyo-spark-book-example | src/test/scala/jp/gihyo/spark/ch08/GeneratePurchaseLogExampleSuite.scala | Scala | apache-2.0 | 1,505 |
/*
* Copyright 2016 Alexey Kardapoltsev
*
* 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.github.kardapoltsev.astparser.parser
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
import scala.util.parsing.input.CharSequenceReader
class LexerSpec extends AnyWordSpec with Matchers {
import Tokens._
val lexer = new Lexer
def scan(input: String): List[Token] = lexer.scan(input)
def hasError(tokens: List[Token]): Boolean = tokens.exists {
case Error(_) => true
case _ => false
}
"Lexer" should {
"should parse EOF" in {
val in = CharSequenceReader.EofCh
scan(in.toString) shouldBe List(EOF)
}
"should parse single lexeme" in {
val in = "34asd2478sdfg"
scan(in) shouldBe List(Lexeme(in))
}
"shouldn't parse invalid lexeme" in {
val in = "__#$sd_fg"
hasError(scan(in)) shouldBe true
}
"should parse symbols" in {
val in = ":#.{}[]=()-"
scan(in) shouldBe List(
Colon(),
Hash(),
Dot(),
LeftBrace(),
RightBrace(),
LeftBracket(),
RightBracket(),
Eq(),
LeftParen(),
RightParen(),
Dash()
)
}
"shouldn't parse invalid symbols" in {
val in = s"asdf $$a sdfadsf% *"
hasError(scan(in)) shouldBe true
}
"should parse line comments" in {
val commentBody = "comment body"
val in =
s"""
|asdf
|//$commentBody
|adsf
""".stripMargin
scan(in) shouldBe List(Lexeme("asdf"), Lexeme("adsf"))
}
"should parse nested multiline comment" in {
val commentBody =
"""|2line
|3line
| /*
| 4line other level of comments with * and another *
| */
|5line
|""".stripMargin
val in =
s"""
|1line
|/*$commentBody*/
|6line
""".stripMargin
scan(in) should contain theSameElementsInOrderAs List(Lexeme("1line"), Lexeme("6line"))
}
"should parse REST definition" in {
val str = "GET /api/users/{userId}"
val res = scan("@" + str)
res shouldBe List(Http(str))
}
"should lead to the error if comment unclosed" in {
val res = scan("/* asdf ")
hasError(res) shouldBe true
}
"should parse single line doc" in {
val commentSample = " a - sdfads -- adfasdf "
val in = s"asdf --$commentSample"
scan(in) shouldBe List(Lexeme("asdf"), RightDoc(commentSample))
}
"should parse multiline doc" in {
val commentSample =
"""
|asf*
|*a a
|dsf*"""".stripMargin
val in =
s"""
|asdf
|/**$commentSample*/
|asdf
""".stripMargin
scan(in) shouldBe List(Lexeme("asdf"), LeftDoc(commentSample), Lexeme("asdf"))
}
"should parse valid input" in {
val multiDocSample =
"""
| adfasdf
| asd fadsf
""".stripMargin
val lineDocSample = "/ asdf // asdf -- asdf - adsf"
val sample =
List(
Lexeme("ASD"),
LeftBrace(),
LeftDoc(multiDocSample),
Lexeme("abc"),
Dot(),
Lexeme("abc"),
Hash(),
Lexeme("789"),
Colon(),
Lexeme("T"),
LeftBracket(),
Lexeme("B"),
RightBracket(),
RightDoc(lineDocSample),
RightBrace()
)
val in =
s"""
| ASD { //$lineDocSample
| /*$multiDocSample*/
| /**$multiDocSample*/
| abc.abc # 789 : T[B] --$lineDocSample
| }
""".stripMargin
val res = scan(in)
res shouldBe sample
}
"should parse type aliases" in {
val in =
"""
|type MyType = some.other.Type
|type MyType2 = some.other.Type
""".stripMargin
scan(in) shouldBe List(
TypeKeyword(),
Lexeme("MyType"),
Eq(),
Lexeme("some"),
Dot(),
Lexeme("other"),
Dot(),
Lexeme("Type"),
TypeKeyword(),
Lexeme("MyType2"),
Eq(),
Lexeme("some"),
Dot(),
Lexeme("other"),
Dot(),
Lexeme("Type")
)
}
"should parse identifiers containing keywords" in {
val in = "type typeAliasForX"
scan(in) shouldBe List(
TypeKeyword(),
Lexeme("typeAliasForX")
)
}
"should allow escaped keywords" in {
scan("`type`") shouldBe List(
Lexeme("type")
)
}
}
}
| kardapoltsev/astparser | src/test/scala/com/github/kardapoltsev/astparser/parser/LexerSpec.scala | Scala | apache-2.0 | 5,237 |
package spinoco.protocol.mail
import org.scalacheck.Properties
import org.scalacheck.Prop._
import spinoco.protocol.mail.header.codec.EmailAddressCodec
/**
* Created by pach on 18/10/17.
*/
object EmailAddressSpec extends Properties("EmailAddress") {
import SpecUtil._
implicit val codec = EmailAddressCodec.codec
property("plain-email") = protect {
verify("[email protected]", EmailAddress("john.doe", "spinoco.com", None))
}
property ("bracket-only-email") = protect {
verify("<[email protected]>", EmailAddress("john.doe", "spinoco.com", None), "[email protected]")
}
property("bracket-ascii-display") = protect {
verify("John Doe <[email protected]>", EmailAddress("john.doe", "spinoco.com", Some("John Doe")), "\\"John Doe\\" <[email protected]>")
}
property("bracket-quoted-ascii-display") = protect {
verify(
"\\"John Doe\\" <[email protected]>"
, EmailAddress("john.doe", "spinoco.com", Some("John Doe"))
, "\\"John Doe\\" <[email protected]>"
)
}
property("bracket-quoted-ascii-display-tab") = protect {
verify(
"\\"John Doe\\"\\t<[email protected]>"
, EmailAddress("john.doe", "spinoco.com", Some("John Doe"))
, "\\"John Doe\\" <[email protected]>"
)
}
property("bracket-unicode-display") = protect {
verify(
"=?UTF-8?Q?Val=C3=A9rie_Doe?= <[email protected]>"
, EmailAddress("valerie.doe", "spinoco.com", Some("Valérie Doe"))
, "=?UTF-8?Q?Val=C3=A9rie_Doe?= <[email protected]>"
)
}
property("bracket-unicode-display-base64-encoded") = protect {
verify(
"=?UTF-8?B?WiB0w6l0byBrYW5kaWTDoXRreSBzaSB2eWJlcmV0ZQ==?= <[email protected]>"
, EmailAddress("email.address", "spinoco.com", Some("Z této kandidátky si vyberete"))
, "=?UTF-8?Q?Z_t=C3=A9to_kandid=C3=A1tky_si_vyberete?= <[email protected]>"
)
}
property("bracket-quoted-unicode-display") = protect {
verify(
"\\"=?UTF-8?Q?Val=C3=A9rie_Doe?=\\" <[email protected]>"
, EmailAddress("valerie.doe", "spinoco.com", Some("Valérie Doe"))
, "=?UTF-8?Q?Val=C3=A9rie_Doe?= <[email protected]>"
)
}
property("bracket-quoted-unicode-display.contains.equals") = protect {
verify(
"\\"=?UTF-8?Q?Val=C3=A9rie=3DDoe?=\\" <[email protected]>"
, EmailAddress("valerie.doe", "spinoco.com", Some("Valérie=Doe"))
, "=?UTF-8?Q?Val=C3=A9rie=3DDoe?= <[email protected]>"
)
}
}
| Spinoco/protocol | mail/src/test/scala/spinoco/protocol/mail/EmailAddressSpec.scala | Scala | mit | 2,511 |
/*
* Copyright (c) 2014-2018 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
package internal
import scala.concurrent.ExecutionContext
/**
* INTERNAL API — implements [[UncaughtExceptionReporter.default]].
*/
private[execution] object DefaultUncaughtExceptionReporter
extends UncaughtExceptionReporter {
def reportFailure(e: Throwable): Unit =
logger(e)
private[this] lazy val logger =
ExecutionContext.defaultReporter
}
| Wogan/monix | monix-execution/js/src/main/scala/monix/execution/internal/DefaultUncaughtExceptionReporter.scala | Scala | apache-2.0 | 1,067 |
package drt.shared.airportconfig
import uk.gov.homeoffice.drt.auth.Roles.MAN
import drt.shared.PaxTypes.EeaMachineReadable
import drt.shared.PaxTypesAndQueues._
import drt.shared.Queues.{EGate, EeaDesk, NonEeaDesk}
import drt.shared.SplitRatiosNs.{SplitRatio, SplitRatios, SplitSources}
import drt.shared.Terminals.{T1, T2, T3, Terminal}
import drt.shared._
import scala.collection.immutable.SortedMap
object Man extends AirportConfigLike {
import AirportConfigDefaults._
val config: AirportConfig = AirportConfig(
portCode = PortCode("MAN"),
queuesByTerminal = SortedMap(
T1 -> Seq(EeaDesk, EGate, NonEeaDesk),
T2 -> Seq(EeaDesk, EGate, NonEeaDesk),
T3 -> Seq(EeaDesk, EGate, NonEeaDesk)
),
slaByQueue = Map(EeaDesk -> 25, EGate -> 10, NonEeaDesk -> 45),
defaultWalkTimeMillis = Map(T1 -> 180000L, T2 -> 600000L, T3 -> 180000L),
terminalPaxSplits = List(T1, T2, T3).map(t => (t, SplitRatios(
SplitSources.TerminalAverage,
SplitRatio(eeaMachineReadableToDesk, 0.2666),
SplitRatio(eeaMachineReadableToEGate, 0.7333),
SplitRatio(eeaNonMachineReadableToDesk, 0.1625),
SplitRatio(visaNationalToDesk, 0.05),
SplitRatio(nonVisaNationalToDesk, 0.05)
))).toMap,
terminalProcessingTimes = Map(T1 -> defaultProcessingTimes, T2 -> defaultProcessingTimes, T3 -> defaultProcessingTimes),
minMaxDesksByTerminalQueue24Hrs = Map(
T1 -> Map(
Queues.EGate -> (List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), List(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)),
Queues.EeaDesk -> (List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), List(6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6)),
Queues.NonEeaDesk -> (List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), List(5, 5, 5, 5, 5, 5, 7, 7, 7, 7, 5, 6, 6, 6, 6, 6, 5, 5, 5, 6, 5, 5, 5, 5))
),
T2 -> Map(
Queues.EGate -> (List(1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)),
Queues.EeaDesk -> (List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), List(8, 8, 8, 8, 8, 5, 5, 5, 5, 5, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8)),
Queues.NonEeaDesk -> (List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), List(3, 3, 3, 3, 3, 8, 8, 8, 8, 8, 8, 3, 3, 3, 3, 3, 6, 6, 6, 6, 3, 3, 3, 3))
),
T3 -> Map(
Queues.EGate -> (List(1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)),
Queues.EeaDesk -> (List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), List(6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6)),
Queues.NonEeaDesk -> (List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), List(3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3))
)
),
eGateBankSizes = Map(
T1 -> Iterable(10),
T2 -> Iterable(10),
T3 -> Iterable(10),
),
role = MAN,
terminalPaxTypeQueueAllocation = Map(
T1 -> (defaultQueueRatios + (EeaMachineReadable -> List(
EGate -> 0.7968,
EeaDesk -> (1.0 - 0.7968)
))),
T2 -> (defaultQueueRatios + (EeaMachineReadable -> List(
EGate -> 0.7140,
EeaDesk -> (1.0 - 0.7140)
))),
T3 -> (defaultQueueRatios + (EeaMachineReadable -> List(
EGate -> 0.7038,
EeaDesk -> (1.0 - 0.7038)
)))),
flexedQueues = Set(EeaDesk, NonEeaDesk),
desksByTerminal = Map[Terminal, Int](
T1 -> 14,
T2 -> 11,
T3 -> 9
),
feedSources = Seq(ApiFeedSource, LiveBaseFeedSource, LiveFeedSource, AclFeedSource)
)
}
| UKHomeOffice/drt-scalajs-spa-exploration | shared/src/main/scala/drt/shared/airportconfig/Man.scala | Scala | apache-2.0 | 3,956 |
/*
* Copyright 2019 http4s.org
*
* 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.http4s.ember.server
import cats.effect._
import com.comcast.ip4s
import com.comcast.ip4s._
import fs2.Chunk
import fs2.Stream
import fs2.io.net._
import org.http4s._
import org.http4s.ember.core.EmberException
import org.http4s.ember.core.Encoder
import org.http4s.ember.core.Parser
import org.http4s.headers._
import org.http4s.implicits._
import org.http4s.server.Server
import org.typelevel.ci._
import scala.concurrent.duration._
class ConnectionSuite extends Http4sSuite {
import org.http4s.dsl.io._
import org.http4s.client.dsl.io._
def service: HttpApp[IO] =
HttpRoutes
.of[IO] {
case GET -> Root =>
Ok("ok")
case GET -> Root / "keep-alive" =>
Ok("keep-alive") // keep-alive enabled by default
case GET -> Root / "close" =>
Ok("close").map(_.withHeaders(Connection(ci"close")))
case req @ POST -> Root / "echo" =>
Ok(req.body)
case POST -> Root / "unread" =>
Ok("unread")
}
.orNotFound
def serverResource(
idleTimeout: FiniteDuration,
headerTimeout: FiniteDuration,
): Resource[IO, Server] =
EmberServerBuilder
.default[IO]
.withPort(port"0")
.withHttpApp(service)
.withIdleTimeout(idleTimeout)
.withRequestHeaderReceiveTimeout(headerTimeout)
.build
sealed case class TestClient(client: Socket[IO]) {
val clientChunkSize = 32 * 1024
def request(req: Request[IO]): IO[Unit] =
client.writes(Encoder.reqToBytes(req)).compile.drain
def response: IO[Response[IO]] =
Parser.Response
.parser[IO](Int.MaxValue)(Array.emptyByteArray, client.read(clientChunkSize))
.map(_._1)
def responseAndDrain: IO[Unit] =
response.flatMap(_.body.compile.drain)
def readChunk: IO[Option[Chunk[Byte]]] =
client.read(clientChunkSize)
def writes(bytes: Stream[IO, Byte]): IO[Unit] =
client.writes(bytes).compile.drain
}
def clientResource(host: ip4s.SocketAddress[ip4s.Host]): Resource[IO, TestClient] =
for {
socket <- Network[IO].client(host)
} yield new TestClient(socket)
def fixture(
idleTimeout: FiniteDuration = 60.seconds,
headerTimeout: FiniteDuration = 60.seconds,
) = ResourceFixture(
for {
server <- serverResource(idleTimeout, headerTimeout)
client <- clientResource(server.address)
} yield client
)
fixture().test("close connection") { client =>
val request = GET(uri"http://localhost:9000/close")
for {
_ <- client.request(request)
_ <- client.responseAndDrain
chunk <- client.readChunk
} yield assertEquals(chunk, None)
}
fixture().test("keep-alive connection") { client =>
val req1 = GET(uri"http://localhost:9000/keep-alive")
val req2 = GET(uri"http://localhost:9000/close")
for {
_ <- client.request(req1)
_ <- client.responseAndDrain
_ <- client.request(req2)
_ <- client.responseAndDrain
chunk <- client.readChunk
} yield assertEquals(chunk, None)
}
fixture(idleTimeout = 1.seconds)
.test("read timeout during header terminates connection with no response") { client =>
val request = GET(uri"http://localhost:9000/close")
for {
_ <- client.writes(Encoder.reqToBytes(request).take(10))
chunk <- client.readChunk
} yield assertEquals(chunk, None)
}
fixture(idleTimeout = 1.seconds).test("read timeout during body terminates connection") {
client =>
val request = Stream(
"POST /echo HTTP/1.1\r\n",
"Accept: text/plain\r\n",
"Content-Length: 100\r\n\r\n",
"less than 100 bytes",
)
(for {
_ <- client.writes(fs2.text.utf8.encode(request))
_ <- client.responseAndDrain
_ <- client.readChunk
} yield ()).intercept[EmberException.ReachedEndOfStream]
}
fixture(headerTimeout = 1.seconds).test("header timeout terminates connection with no response") {
client =>
val request = GET(uri"http://localhost:9000/close")
for {
_ <- client.writes(Encoder.reqToBytes(request).take(10))
chunk <- client.readChunk
} yield assertEquals(chunk, None)
}
fixture().test("close connection after response when request body stream is partially read") {
client =>
val request = Stream(
"POST /unread HTTP/1.1\r\n",
"Accept: text/plain\r\n",
"Content-Length: 100\r\n\r\n",
"not enough bytes",
)
for {
_ <- client.writes(fs2.text.utf8.encode(request))
_ <- client.responseAndDrain
chunk <- client.readChunk
} yield assertEquals(chunk, None)
}
}
| rossabaker/http4s | ember-server/shared/src/test/scala/org/http4s/ember/server/ConnectionSuite.scala | Scala | apache-2.0 | 5,287 |
import leon.annotation._
import leon.lang._
object Coins {
case class CoinDist(pHead: Rational) {
def pTail: Rational = Rational(1) - pHead
}
def isDist(dist: CoinDist): Boolean =
dist.pHead.isRational && dist.pHead >= Rational(0) && dist.pHead <= Rational(1)
case class CoinsJoinDist(hh: Rational, ht: Rational, th: Rational, tt: Rational)
def isDist(dist: CoinsJoinDist): Boolean =
dist.hh.isRational && dist.hh >= Rational(0) && dist.hh <= Rational(1) &&
dist.ht.isRational && dist.ht >= Rational(0) && dist.ht <= Rational(1) &&
dist.th.isRational && dist.th >= Rational(0) && dist.th <= Rational(1) &&
dist.tt.isRational && dist.tt >= Rational(0) && dist.tt <= Rational(1) &&
(dist.hh + dist.ht + dist.th + dist.tt) ~ Rational(1)
def isUniform(dist: CoinDist): Boolean = {
require(isDist(dist))
dist.pHead ~ Rational(1, 2)
}
def join(c1: CoinDist, c2: CoinDist): CoinsJoinDist =
CoinsJoinDist(
c1.pHead*c2.pHead,
c1.pHead*c2.pTail,
c1.pTail*c2.pHead,
c1.pTail*c2.pTail)
def firstCoin(dist: CoinsJoinDist): CoinDist = {
require(isDist(dist))
CoinDist(dist.hh + dist.ht)
} ensuring(res => res.pTail ~ (dist.th + dist.tt))
def secondCoin(dist: CoinsJoinDist): CoinDist = {
require(isDist(dist))
CoinDist(dist.hh + dist.th)
} ensuring(res => res.pTail ~ (dist.ht + dist.tt))
def isIndependent(dist: CoinsJoinDist): Boolean = {
require(isDist(dist))
join(firstCoin(dist), secondCoin(dist)) == dist
}
def isEquivalent(dist1: CoinsJoinDist, dist2: CoinsJoinDist): Boolean = {
require(isDist(dist1) && isDist(dist2))
(dist1.hh ~ dist2.hh) &&
(dist1.ht ~ dist2.ht) &&
(dist1.th ~ dist2.th) &&
(dist1.tt ~ dist2.tt)
}
//case class CoinCondDist(ifHead: CoinDist, ifTail: CoinDist)
//def condByFirstCoin(dist: CoinsJoinDist): CoinCondDist = {
// CoinCondDist(
// CoinDist(
// dist.hh*(dist.th + dist.tt), //probability of head if head
// dist.ht*(dist.th + dist.tt) //probability of tail if head
// ),
// CoinDist(
// dist.th*(dist.hh + dist.ht), //probability of head if tail
// dist.tt*(dist.hh + dist.ht) //probability of tail if tail
// )
// )
//}
//def combine(cond: CoinCondDist, dist: CoinDist): CoinsJoinDist = {
// require(isDist(dist) && dist.pHead > 0 && dist.pTail > 0)
// val hh = cond.ifHead.pHead * dist.pHead
// val ht = cond.ifHead.pTail * dist.pHead
// val th = cond.ifTail.pHead * dist.pTail
// val tt = cond.ifTail.pTail * dist.pTail
// CoinsJoinDist(hh, ht, th, tt)
//}
//
//def condIsSound(dist: CoinsJoinDist): Boolean = {
// require(isDist(dist) && dist.hh > 0 && dist.ht > 0 && dist.th > 0 && dist.tt > 0)
// val computedDist = combine(condByFirstCoin(dist), firstCoin(dist))
// isEquivalent(dist, computedDist)
//} holds
//should be INVALID
def anyDistributionsNotEquivalent(dist1: CoinsJoinDist, dist2: CoinsJoinDist): Boolean = {
require(isDist(dist1) && isDist(dist2))
isEquivalent(dist1, dist2)
} holds
//sum modulo: face is 0, tail is 1
def sum(coin1: CoinDist, coin2: CoinDist): CoinDist = {
require(isDist(coin1) && isDist(coin2))
CoinDist(coin1.pHead*coin2.pHead + coin1.pTail*coin2.pTail)
} ensuring(res => res.pTail ~ (coin1.pHead*coin2.pTail + coin1.pTail*coin2.pHead))
def sum(dist: CoinsJoinDist): CoinDist = {
require(isDist(dist))
CoinDist(dist.hh + dist.tt)
} ensuring(res => res.pTail ~ (dist.ht + dist.th))
/***************************************************
* properties of sum operation *
***************************************************/
//def sumIsUniform1(coin1: CoinDist, coin2: CoinDist): Boolean = {
// require(isDist(coin1) && isDist(coin2) && isUniform(coin1) && isUniform(coin2))
// val dist = sum(coin1, coin2)
// isUniform(dist)
//} holds
//def sumIsUniform2(coin1: CoinDist, coin2: CoinDist): Boolean = {
// require(isDist(coin1) && isDist(coin2) && isUniform(coin1))
// val dist = sum(coin1, coin2)
// isUniform(dist)
//} holds
//def sumUniform3(coin1: CoinDist, coin2: CoinDist, coin3: CoinDist): Boolean = {
// require(isDist(coin1) && isDist(coin2) && isDist(coin3) && isUniform(coin1))
// val dist = sum(sum(coin1, coin2), coin3)
// isUniform(dist)
//} holds
//def sumUniformWithIndependence(dist: CoinsJoinDist): Boolean = {
// require(isDist(dist) && isIndependent(dist) && (isUniform(firstCoin(dist)) || isUniform(secondCoin(dist))))
// val res = sum(dist)
// isUniform(res)
//} holds
////should find counterexample, indepenence is required
//def sumUniformWithoutIndependence(dist: CoinsJoinDist): Boolean = {
// require(isDist(dist) && (isUniform(firstCoin(dist)) || isUniform(secondCoin(dist))))
// val res = sum(dist)
// isUniform(res)
//} holds
////sum of two non-uniform dices is potentially uniform (no result)
//def sumNonUniform1(coin1: CoinDist, coin2: CoinDist): Boolean = {
// require(isDist(coin1) && isDist(coin2) && !isUniform(coin1) && !isUniform(coin2))
// val dist = sum(coin1, coin2)
// !isUniform(dist)
//} holds
//def sumNonUniform2(coin1: CoinDist, coin2: CoinDist, coin3: CoinDist): Boolean = {
// require(isDist(coin1) && isDist(coin2) && isDist(coin3) && !isUniform(coin1) && !isUniform(coin2) && !isUniform(coin3))
// val dist = sum(sum(coin1, coin2), coin3)
// !isUniform(dist)
//} //holds
//def sumNonUniformWithIndependence(dist: CoinsJoinDist): Boolean = {
// require(isDist(dist) && isIndependent(dist) && !isUniform(firstCoin(dist)) && !isUniform(secondCoin(dist)))
// val res = sum(dist)
// !isUniform(res)
//} holds
////independence is required
//def sumNonUniformWithoutIndependence(dist: CoinsJoinDist): Boolean = {
// require(isDist(dist) && !isUniform(firstCoin(dist)) && !isUniform(secondCoin(dist)))
// val res = sum(dist)
// !isUniform(res)
//} holds
//def sumIsCommutative(coin1: CoinDist, coin2: CoinDist, coin3: CoinDist): Boolean = {
// require(isDist(coin1) && isDist(coin2))
// sum(coin1, coin2) == sum(coin2, coin1)
//} holds
//def sumIsAssociative(coin1: CoinDist, coin2: CoinDist, coin3: CoinDist): Boolean = {
// require(isDist(coin1) && isDist(coin2) && isDist(coin3))
// sum(sum(coin1, coin2), coin3) == sum(coin1, sum(coin2, coin3))
//} //holds
}
| epfl-lara/leon | testcases/proof/proba/rationals/Coins.scala | Scala | gpl-3.0 | 6,457 |
// Copyright (c) 2011-2015 ScalaMock Contributors (https://github.com/paulbutcher/ScalaMock/graphs/contributors)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package org.scalamock.util
import MacroAdapter.Context
/**
* Helper functions to work with Scala macros and to create scala.reflect Trees.
*/
private[scalamock] class MacroUtils[C <: Context](protected val ctx: C) extends MacroAdapter {
import ctx.universe._
final lazy val isScalaJs =
ctx.compilerSettings.exists(o => o.startsWith("-Xplugin:") && o.contains("scalajs-compiler"))
def jsExport(name: String) = q"new _root_.scala.scalajs.js.annotation.JSExport($name)"
// Convert a methodType into its ultimate result type
// For nullary and normal methods, this is just the result type
// For curried methods, this is the final result type of the result type
def finalResultType(methodType: Type): Type = methodType match {
case NullaryMethodType(result) => result
case MethodType(_, result) => finalResultType(result)
case PolyType(_, result) => finalResultType(result)
case _ => methodType
}
// Convert a methodType into a list of lists of params:
// UnaryMethodType => Nil
// Normal method => List(List(p1, p2, ...))
// Curried method => List(List(p1, p2, ...), List(q1, q2, ...), ...)
def paramss(methodType: Type): List[List[Symbol]] = methodType match {
case MethodType(params, result) => params :: paramss(result)
case PolyType(_, result) => paramss(result)
case _ => Nil
}
def paramCount(methodType: Type): Int = methodType match {
case MethodType(params, result) => params.length + paramCount(result)
case PolyType(_, result) => paramCount(result)
case _ => 0
}
def paramTypes(methodType: Type): List[Type] = paramss(methodType).flatten map { _.typeSignature }
def isMemberOfObject(s: Symbol) = {
val res = TypeTag.Object.tpe.member(s.name)
res != NoSymbol && res.typeSignature == s.typeSignature
}
// <|expr|>.asInstanceOf[<|t|>]
def castTo(expr: Tree, t: Type): Tree = TypeApply(selectTerm(expr, "asInstanceOf"), List(TypeTree(t)))
val scalaPredef: Tree = selectTerm(Ident(TermName("scala")), "Predef")
val scalaSymbol: Tree = selectTerm(Ident(TermName("scala")), "Symbol")
val scalaString: Tree = Select(scalaPredef, TypeName("String"))
def literal(str: String): Literal = Literal(Constant(str))
def selectTerm(qualifier: Tree, name: String): Tree = Select(qualifier, TermName(name))
def applyListOn(qualifier: Tree, name: String, args: List[Tree]): Tree = Apply(selectTerm(qualifier, name), args)
def applyOn(qualifier: Tree, name: String, args: Tree*): Tree = applyListOn(qualifier, name, args.toList)
def callConstructor(obj: Tree, args: Tree*): Tree = Apply(selectTerm(obj, "<init>"), args.toList)
def reportError(message: String) = {
// Report with both info and abort so that the user still sees something, even if this is within an
// implicit conversion (see https://issues.scala-lang.org/browse/SI-5902)
ctx.info(ctx.enclosingPosition, message, true)
ctx.abort(ctx.enclosingPosition, message)
}
}
| paulbutcher/ScalaMock | shared/src/main/scala/org/scalamock/util/MacroUtils.scala | Scala | mit | 4,151 |
/**
* 修改前一个函数,返回最大的输出对应的输入。
* 举例来说,largestAt(fun:(Int)=>Int,inputs:Seq[Int])应该返回5。不得使用循环或递归
*/
def largestAt1(fun:(Int)=>Int, inputs:Seq[Int]) = inputs.reduce((a,b)=> if(fun(b)>fun(a)) b else a)
def largestAt2(fun: (Int) => Int, inputs: Seq[Int]) = inputs.map(x => (x, fun(x))).reduceLeft((x,y) => if (x._2 > y._2) x else y)._1
println(largestAt1(x => 10 * x - x * x, 1 to 10))
println(largestAt2(x => 10 * x - x * x, 1 to 10)) | vernonzheng/scala-for-the-Impatient | src/Chapter12/exercise06.scala | Scala | mit | 510 |
package com.github.gdefacci.briscola
package competition
import player._
import com.github.gdefacci.ddd._
import scalaz.{ -\\/, \\/, \\/- }
import java.time.LocalDateTime
import com.github.gdefacci.briscola.game._
trait CompetitionDecider extends Decider[CompetitionState, CompetitionCommand, CompetitionEvent, CompetitionError] {
def nextId: CompetitionId
def playerById(id: PlayerId): Option[Player]
def apply(s: CompetitionState, cmd: CompetitionCommand): CompetitionError \\/ Seq[CompetitionEvent] = {
(s -> cmd) match {
case (EmptyCompetition, CreateCompetition(issuer, gmPlayers, kind, deadLine)) =>
val gamePlayers: GamePlayers = gmPlayers match {
case Players(players) => Players(players + issuer)
case gpls => gpls
}
GamePlayersValidator.withValidPlayersAndTeams(gamePlayers, playerById(_)) { (players, teams) =>
val issr = players.find(_.id == issuer).get
Seq(CreatedCompetition(nextId, issr, Competition(gamePlayers, kind, deadLine)))
} leftMap(CompetioBriscolaError(_))
case (comp: OpenCompetition, AcceptCompetition(playerId)) =>
val players = GamePlayers.getPlayers(comp.competition.players)
if (comp.acceptingPlayers.contains(playerId)) {
-\\/(CompetitionAlreadyAccepted)
} else if (players.contains(playerId)) {
\\/-(Seq(CompetitionAccepted(playerId)))
} else {
-\\/(CompetioBriscolaError(InvalidPlayer(playerId)))
}
case (comp: OpenCompetition, DeclineCompetition(playerId, reason)) =>
val players = GamePlayers.getPlayers(comp.competition.players)
if (comp.decliningPlayers.contains(playerId)) {
-\\/(CompetitionAlreadyDeclined)
} else if (players.contains(playerId)) {
\\/-(Seq(CompetitionDeclined(playerId, reason)))
} else {
-\\/(CompetioBriscolaError(InvalidPlayer(playerId)))
}
case (EmptyCompetition, _) => -\\/(CompetitionNotStarted)
case (comp: OpenCompetition, cmd: CreateCompetition) => -\\/(CompetitionAlreadyStarted)
case (c: DroppedCompetition, _) => -\\/(CompetitionDropped)
case (c: FullfilledCompetition, _) => -\\/(CompetitionAlreadyFinished)
}
}
}
trait CompetitionEvolver extends Evolver[CompetitionState, CompetitionEvent] {
def isFullfilled(comp: Competition, players: Set[PlayerId]) = {
val compPlayers = GamePlayers.getPlayers(comp.players)
comp.deadline match {
case CompetitionStartDeadline.AllPlayers => compPlayers == players
case CompetitionStartDeadline.OnPlayerCount(n) => compPlayers.size == n
}
}
def isDropped(comp: Competition, decliningPlayers: Set[PlayerId]) = {
comp.deadline match {
case CompetitionStartDeadline.AllPlayers => decliningPlayers.nonEmpty
case CompetitionStartDeadline.OnPlayerCount(n) => (GamePlayers.getPlayers(comp.players).size - decliningPlayers.size) < n
}
}
def apply(s: CompetitionState, event: CompetitionEvent): CompetitionState = {
(s -> event) match {
case (EmptyCompetition, CreatedCompetition(id, issuer, comp)) =>
OpenCompetition(id, comp, Set(issuer.id), Set.empty)
case (OpenCompetition(id, competition, acceptingPlayers, decliningPlayers), CompetitionAccepted(pid)) =>
if (isFullfilled(competition, acceptingPlayers + pid))
FullfilledCompetition(id, competition, acceptingPlayers + pid, decliningPlayers - pid)
else
OpenCompetition(id, competition, acceptingPlayers + pid, decliningPlayers - pid)
case (OpenCompetition(id, competition, acceptingPlayers, decliningPlayers), CompetitionDeclined(pid, rsn)) =>
if (isDropped(competition, decliningPlayers + pid))
DroppedCompetition(id, competition, acceptingPlayers - pid, decliningPlayers + pid)
else
OpenCompetition(id, competition, acceptingPlayers - pid, decliningPlayers + pid)
case _ => {
throw new RuntimeException(s"forbidden condition state:${s} event:${event}")
}
}
}
} | gdefacci/briscola | ddd-briscola/src/main/scala/com/github/gdefacci/briscola/competition/competition.scala | Scala | bsd-3-clause | 4,074 |
/**
* 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.controller
import kafka.api.LeaderAndIsr
import kafka.server.KafkaConfig
import kafka.utils.TestUtils
import kafka.zk.KafkaZkClient.UpdateLeaderAndIsrResult
import kafka.zk.{KafkaZkClient, TopicPartitionStateZNode}
import kafka.zookeeper.{GetDataResponse, ResponseMetadata}
import org.apache.kafka.common.TopicPartition
import org.apache.zookeeper.KeeperException.Code
import org.apache.zookeeper.data.Stat
import org.easymock.EasyMock
import org.junit.Assert._
import org.junit.{Before, Test}
import org.scalatest.junit.JUnitSuite
import scala.collection.mutable
class ReplicaStateMachineTest extends JUnitSuite {
private var controllerContext: ControllerContext = null
private var mockZkClient: KafkaZkClient = null
private var mockControllerBrokerRequestBatch: ControllerBrokerRequestBatch = null
private var mockTopicDeletionManager: TopicDeletionManager = null
private var replicaState: mutable.Map[PartitionAndReplica, ReplicaState] = null
private var replicaStateMachine: ReplicaStateMachine = null
private val brokerId = 5
private val config = KafkaConfig.fromProps(TestUtils.createBrokerConfig(brokerId, "zkConnect"))
private val controllerEpoch = 50
private val partition = new TopicPartition("t", 0)
private val partitions = Seq(partition)
private val replica = PartitionAndReplica(partition, brokerId)
private val replicas = Seq(replica)
@Before
def setUp(): Unit = {
controllerContext = new ControllerContext
controllerContext.epoch = controllerEpoch
mockZkClient = EasyMock.createMock(classOf[KafkaZkClient])
mockControllerBrokerRequestBatch = EasyMock.createMock(classOf[ControllerBrokerRequestBatch])
mockTopicDeletionManager = EasyMock.createMock(classOf[TopicDeletionManager])
replicaState = mutable.Map.empty[PartitionAndReplica, ReplicaState]
replicaStateMachine = new ReplicaStateMachine(config, new StateChangeLogger(brokerId, true, None), controllerContext, mockTopicDeletionManager, mockZkClient,
replicaState, mockControllerBrokerRequestBatch)
}
@Test
def testNonexistentReplicaToNewReplicaTransition(): Unit = {
replicaStateMachine.handleStateChanges(replicas, NewReplica)
assertEquals(NewReplica, replicaState(replica))
}
@Test
def testInvalidNonexistentReplicaToOnlineReplicaTransition(): Unit = {
replicaStateMachine.handleStateChanges(replicas, OnlineReplica)
assertEquals(NonExistentReplica, replicaState(replica))
}
@Test
def testInvalidNonexistentReplicaToOfflineReplicaTransition(): Unit = {
replicaStateMachine.handleStateChanges(replicas, OfflineReplica)
assertEquals(NonExistentReplica, replicaState(replica))
}
@Test
def testInvalidNonexistentReplicaToReplicaDeletionStartedTransition(): Unit = {
replicaStateMachine.handleStateChanges(replicas, ReplicaDeletionStarted)
assertEquals(NonExistentReplica, replicaState(replica))
}
@Test
def testInvalidNonexistentReplicaToReplicaDeletionIneligibleTransition(): Unit = {
replicaStateMachine.handleStateChanges(replicas, ReplicaDeletionIneligible)
assertEquals(NonExistentReplica, replicaState(replica))
}
@Test
def testInvalidNonexistentReplicaToReplicaDeletionSuccessfulTransition(): Unit = {
replicaStateMachine.handleStateChanges(replicas, ReplicaDeletionSuccessful)
assertEquals(NonExistentReplica, replicaState(replica))
}
@Test
def testInvalidNewReplicaToNonexistentReplicaTransition(): Unit = {
testInvalidTransition(NewReplica, NonExistentReplica)
}
@Test
def testNewReplicaToOnlineReplicaTransition(): Unit = {
replicaState.put(replica, NewReplica)
controllerContext.updatePartitionReplicaAssignment(partition, Seq(brokerId))
replicaStateMachine.handleStateChanges(replicas, OnlineReplica)
assertEquals(OnlineReplica, replicaState(replica))
}
@Test
def testNewReplicaToOfflineReplicaTransition(): Unit = {
replicaState.put(replica, NewReplica)
EasyMock.expect(mockControllerBrokerRequestBatch.newBatch())
EasyMock.expect(mockControllerBrokerRequestBatch.addStopReplicaRequestForBrokers(EasyMock.eq(Seq(brokerId)),
EasyMock.eq(partition), EasyMock.eq(false), EasyMock.anyObject()))
EasyMock.expect(mockControllerBrokerRequestBatch.sendRequestsToBrokers(controllerEpoch))
EasyMock.replay(mockControllerBrokerRequestBatch)
replicaStateMachine.handleStateChanges(replicas, OfflineReplica)
EasyMock.verify(mockControllerBrokerRequestBatch)
assertEquals(OfflineReplica, replicaState(replica))
}
@Test
def testInvalidNewReplicaToReplicaDeletionStartedTransition(): Unit = {
testInvalidTransition(NewReplica, ReplicaDeletionStarted)
}
@Test
def testInvalidNewReplicaToReplicaDeletionIneligibleTransition(): Unit = {
testInvalidTransition(NewReplica, ReplicaDeletionIneligible)
}
@Test
def testInvalidNewReplicaToReplicaDeletionSuccessfulTransition(): Unit = {
testInvalidTransition(NewReplica, ReplicaDeletionSuccessful)
}
@Test
def testInvalidOnlineReplicaToNonexistentReplicaTransition(): Unit = {
testInvalidTransition(OnlineReplica, NonExistentReplica)
}
@Test
def testInvalidOnlineReplicaToNewReplicaTransition(): Unit = {
testInvalidTransition(OnlineReplica, NewReplica)
}
@Test
def testOnlineReplicaToOnlineReplicaTransition(): Unit = {
replicaState.put(replica, OnlineReplica)
controllerContext.updatePartitionReplicaAssignment(partition, Seq(brokerId))
val leaderIsrAndControllerEpoch = LeaderIsrAndControllerEpoch(LeaderAndIsr(brokerId, List(brokerId)), controllerEpoch)
controllerContext.partitionLeadershipInfo.put(partition, leaderIsrAndControllerEpoch)
EasyMock.expect(mockControllerBrokerRequestBatch.newBatch())
EasyMock.expect(mockControllerBrokerRequestBatch.addLeaderAndIsrRequestForBrokers(Seq(brokerId),
partition, leaderIsrAndControllerEpoch, Seq(brokerId), isNew = false))
EasyMock.expect(mockControllerBrokerRequestBatch.sendRequestsToBrokers(controllerEpoch))
EasyMock.replay(mockZkClient, mockControllerBrokerRequestBatch)
replicaStateMachine.handleStateChanges(replicas, OnlineReplica)
EasyMock.verify(mockZkClient, mockControllerBrokerRequestBatch)
assertEquals(OnlineReplica, replicaState(replica))
}
@Test
def testOnlineReplicaToOfflineReplicaTransition(): Unit = {
val otherBrokerId = brokerId + 1
val replicaIds = List(brokerId, otherBrokerId)
replicaState.put(replica, OnlineReplica)
controllerContext.updatePartitionReplicaAssignment(partition, replicaIds)
val leaderAndIsr = LeaderAndIsr(brokerId, replicaIds)
val leaderIsrAndControllerEpoch = LeaderIsrAndControllerEpoch(leaderAndIsr, controllerEpoch)
controllerContext.partitionLeadershipInfo.put(partition, leaderIsrAndControllerEpoch)
val stat = new Stat(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
EasyMock.expect(mockControllerBrokerRequestBatch.newBatch())
EasyMock.expect(mockControllerBrokerRequestBatch.addStopReplicaRequestForBrokers(EasyMock.eq(Seq(brokerId)),
EasyMock.eq(partition), EasyMock.eq(false), EasyMock.anyObject()))
val adjustedLeaderAndIsr = leaderAndIsr.newLeaderAndIsr(LeaderAndIsr.NoLeader, List(otherBrokerId))
val updatedLeaderAndIsr = adjustedLeaderAndIsr.withZkVersion(adjustedLeaderAndIsr .zkVersion + 1)
val updatedLeaderIsrAndControllerEpoch = LeaderIsrAndControllerEpoch(updatedLeaderAndIsr, controllerEpoch)
EasyMock.expect(mockZkClient.getTopicPartitionStatesRaw(partitions)).andReturn(
Seq(GetDataResponse(Code.OK, null, Some(partition),
TopicPartitionStateZNode.encode(leaderIsrAndControllerEpoch), stat, ResponseMetadata(0, 0))))
EasyMock.expect(mockZkClient.updateLeaderAndIsr(Map(partition -> adjustedLeaderAndIsr), controllerEpoch))
.andReturn(UpdateLeaderAndIsrResult(Map(partition -> updatedLeaderAndIsr), Seq.empty, Map.empty))
EasyMock.expect(mockTopicDeletionManager.isTopicQueuedUpForDeletion(partition.topic)).andReturn(false)
EasyMock.expect(mockControllerBrokerRequestBatch.addLeaderAndIsrRequestForBrokers(Seq(otherBrokerId),
partition, updatedLeaderIsrAndControllerEpoch, replicaIds, isNew = false))
EasyMock.expect(mockControllerBrokerRequestBatch.sendRequestsToBrokers(controllerEpoch))
EasyMock.replay(mockZkClient, mockControllerBrokerRequestBatch, mockTopicDeletionManager)
replicaStateMachine.handleStateChanges(replicas, OfflineReplica)
EasyMock.verify(mockZkClient, mockControllerBrokerRequestBatch, mockTopicDeletionManager)
assertEquals(updatedLeaderIsrAndControllerEpoch, controllerContext.partitionLeadershipInfo(partition))
assertEquals(OfflineReplica, replicaState(replica))
}
@Test
def testInvalidOnlineReplicaToReplicaDeletionStartedTransition(): Unit = {
testInvalidTransition(OnlineReplica, ReplicaDeletionStarted)
}
@Test
def testInvalidOnlineReplicaToReplicaDeletionIneligibleTransition(): Unit = {
testInvalidTransition(OnlineReplica, ReplicaDeletionIneligible)
}
@Test
def testInvalidOnlineReplicaToReplicaDeletionSuccessfulTransition(): Unit = {
testInvalidTransition(OnlineReplica, ReplicaDeletionSuccessful)
}
@Test
def testInvalidOfflineReplicaToNonexistentReplicaTransition(): Unit = {
testInvalidTransition(OfflineReplica, NonExistentReplica)
}
@Test
def testInvalidOfflineReplicaToNewReplicaTransition(): Unit = {
testInvalidTransition(OfflineReplica, NewReplica)
}
@Test
def testOfflineReplicaToOnlineReplicaTransition(): Unit = {
replicaState.put(replica, OfflineReplica)
controllerContext.updatePartitionReplicaAssignment(partition, Seq(brokerId))
val leaderIsrAndControllerEpoch = LeaderIsrAndControllerEpoch(LeaderAndIsr(brokerId, List(brokerId)), controllerEpoch)
controllerContext.partitionLeadershipInfo.put(partition, leaderIsrAndControllerEpoch)
EasyMock.expect(mockControllerBrokerRequestBatch.newBatch())
EasyMock.expect(mockControllerBrokerRequestBatch.addLeaderAndIsrRequestForBrokers(Seq(brokerId),
partition, leaderIsrAndControllerEpoch, Seq(brokerId), isNew = false))
EasyMock.expect(mockControllerBrokerRequestBatch.sendRequestsToBrokers(controllerEpoch))
EasyMock.replay(mockZkClient, mockControllerBrokerRequestBatch)
replicaStateMachine.handleStateChanges(replicas, OnlineReplica)
EasyMock.verify(mockZkClient, mockControllerBrokerRequestBatch)
assertEquals(OnlineReplica, replicaState(replica))
}
@Test
def testOfflineReplicaToReplicaDeletionStartedTransition(): Unit = {
val callbacks = new Callbacks()
replicaState.put(replica, OfflineReplica)
EasyMock.expect(mockControllerBrokerRequestBatch.newBatch())
EasyMock.expect(mockControllerBrokerRequestBatch.addStopReplicaRequestForBrokers(Seq(brokerId),
partition, true, callbacks.stopReplicaResponseCallback))
EasyMock.expect(mockControllerBrokerRequestBatch.sendRequestsToBrokers(controllerEpoch))
EasyMock.replay(mockZkClient, mockControllerBrokerRequestBatch)
replicaStateMachine.handleStateChanges(replicas, ReplicaDeletionStarted, callbacks)
EasyMock.verify(mockZkClient, mockControllerBrokerRequestBatch)
assertEquals(ReplicaDeletionStarted, replicaState(replica))
}
@Test
def testInvalidOfflineReplicaToReplicaDeletionIneligibleTransition(): Unit = {
testInvalidTransition(OfflineReplica, ReplicaDeletionIneligible)
}
@Test
def testInvalidOfflineReplicaToReplicaDeletionSuccessfulTransition(): Unit = {
testInvalidTransition(OfflineReplica, ReplicaDeletionSuccessful)
}
@Test
def testInvalidReplicaDeletionStartedToNonexistentReplicaTransition(): Unit = {
testInvalidTransition(ReplicaDeletionStarted, NonExistentReplica)
}
@Test
def testInvalidReplicaDeletionStartedToNewReplicaTransition(): Unit = {
testInvalidTransition(ReplicaDeletionStarted, NewReplica)
}
@Test
def testInvalidReplicaDeletionStartedToOnlineReplicaTransition(): Unit = {
testInvalidTransition(ReplicaDeletionStarted, OnlineReplica)
}
@Test
def testInvalidReplicaDeletionStartedToOfflineReplicaTransition(): Unit = {
testInvalidTransition(ReplicaDeletionStarted, OfflineReplica)
}
@Test
def testReplicaDeletionStartedToReplicaDeletionIneligibleTransition(): Unit = {
replicaState.put(replica, ReplicaDeletionStarted)
replicaStateMachine.handleStateChanges(replicas, ReplicaDeletionIneligible)
assertEquals(ReplicaDeletionIneligible, replicaState(replica))
}
@Test
def testReplicaDeletionStartedToReplicaDeletionSuccessfulTransition(): Unit = {
replicaState.put(replica, ReplicaDeletionStarted)
replicaStateMachine.handleStateChanges(replicas, ReplicaDeletionSuccessful)
assertEquals(ReplicaDeletionSuccessful, replicaState(replica))
}
@Test
def testReplicaDeletionSuccessfulToNonexistentReplicaTransition(): Unit = {
replicaState.put(replica, ReplicaDeletionSuccessful)
controllerContext.updatePartitionReplicaAssignment(partition, Seq(brokerId))
replicaStateMachine.handleStateChanges(replicas, NonExistentReplica)
assertEquals(Seq.empty, controllerContext.partitionReplicaAssignment(partition))
assertEquals(None, replicaState.get(replica))
}
@Test
def testInvalidReplicaDeletionSuccessfulToNewReplicaTransition(): Unit = {
testInvalidTransition(ReplicaDeletionSuccessful, NewReplica)
}
@Test
def testInvalidReplicaDeletionSuccessfulToOnlineReplicaTransition(): Unit = {
testInvalidTransition(ReplicaDeletionSuccessful, OnlineReplica)
}
@Test
def testInvalidReplicaDeletionSuccessfulToOfflineReplicaTransition(): Unit = {
testInvalidTransition(ReplicaDeletionSuccessful, OfflineReplica)
}
@Test
def testInvalidReplicaDeletionSuccessfulToReplicaDeletionStartedTransition(): Unit = {
testInvalidTransition(ReplicaDeletionSuccessful, ReplicaDeletionStarted)
}
@Test
def testInvalidReplicaDeletionSuccessfulToReplicaDeletionIneligibleTransition(): Unit = {
testInvalidTransition(ReplicaDeletionSuccessful, ReplicaDeletionIneligible)
}
@Test
def testInvalidReplicaDeletionIneligibleToNonexistentReplicaTransition(): Unit = {
testInvalidTransition(ReplicaDeletionIneligible, NonExistentReplica)
}
@Test
def testInvalidReplicaDeletionIneligibleToNewReplicaTransition(): Unit = {
testInvalidTransition(ReplicaDeletionIneligible, NewReplica)
}
@Test
def testReplicaDeletionIneligibleToOnlineReplicaTransition(): Unit = {
replicaState.put(replica, ReplicaDeletionIneligible)
controllerContext.updatePartitionReplicaAssignment(partition, Seq(brokerId))
val leaderIsrAndControllerEpoch = LeaderIsrAndControllerEpoch(LeaderAndIsr(brokerId, List(brokerId)), controllerEpoch)
controllerContext.partitionLeadershipInfo.put(partition, leaderIsrAndControllerEpoch)
EasyMock.expect(mockControllerBrokerRequestBatch.newBatch())
EasyMock.expect(mockControllerBrokerRequestBatch.addLeaderAndIsrRequestForBrokers(Seq(brokerId),
partition, leaderIsrAndControllerEpoch, Seq(brokerId), isNew = false))
EasyMock.expect(mockControllerBrokerRequestBatch.sendRequestsToBrokers(controllerEpoch))
EasyMock.replay(mockZkClient, mockControllerBrokerRequestBatch)
replicaStateMachine.handleStateChanges(replicas, OnlineReplica)
EasyMock.verify(mockZkClient, mockControllerBrokerRequestBatch)
assertEquals(OnlineReplica, replicaState(replica))
}
@Test
def testInvalidReplicaDeletionIneligibleToReplicaDeletionStartedTransition(): Unit = {
testInvalidTransition(ReplicaDeletionIneligible, ReplicaDeletionStarted)
}
@Test
def testInvalidReplicaDeletionIneligibleToReplicaDeletionSuccessfulTransition(): Unit = {
testInvalidTransition(ReplicaDeletionIneligible, ReplicaDeletionSuccessful)
}
private def testInvalidTransition(fromState: ReplicaState, toState: ReplicaState): Unit = {
replicaState.put(replica, fromState)
replicaStateMachine.handleStateChanges(replicas, toState)
assertEquals(fromState, replicaState(replica))
}
}
| Esquive/kafka | core/src/test/scala/unit/kafka/controller/ReplicaStateMachineTest.scala | Scala | apache-2.0 | 16,850 |
package blended.jms.utils.internal
import akka.actor.ActorSystem
import blended.jms.utils.{BlendedJMSConnection, BlendedJMSConnectionConfig}
import javax.jms._
import scala.util.Try
class DummyConnection extends Connection {
var clientId : String = "clientId"
var el : ExceptionListener = _
override def createSession(b: Boolean, i: Int): Session = ???
override def getClientID() : String = clientId
override def setClientID(s: String): Unit = clientId = s
override def getMetaData: ConnectionMetaData = ???
override def getExceptionListener: ExceptionListener = el
override def setExceptionListener(exceptionListener: ExceptionListener): Unit = el = exceptionListener
override def start(): Unit = {}
override def stop(): Unit = {}
override def close(): Unit = {}
override def createConnectionConsumer(destination: Destination, s: String, serverSessionPool: ServerSessionPool, i: Int): ConnectionConsumer = ???
override def createDurableConnectionConsumer(topic: Topic, s: String, s1: String, serverSessionPool: ServerSessionPool, i: Int): ConnectionConsumer = ???
}
class DummyHolder(f : () => Connection)(implicit system: ActorSystem)
extends ConnectionHolder(BlendedJMSConnectionConfig.defaultConfig) {
override val vendor: String = "dummy"
override val provider: String = "dummy"
override def getConnectionFactory(): ConnectionFactory = ???
private[this] var conn : Option[BlendedJMSConnection] = None
override def getConnection(): Option[BlendedJMSConnection] = conn
override def connect(): Connection = conn match {
case Some(c) => c
case None =>
val c = new BlendedJMSConnection(f())
conn = Some(c)
c
}
override def close(): Try[Unit] = Try {
conn.foreach{ c => c.connection.close() }
conn = None
}
}
| lefou/blended | blended.jms.utils/src/test/scala/blended/jms/utils/internal/DummyConnection.scala | Scala | apache-2.0 | 1,810 |
package com.nulabinc.backlog.migration.common.utils
import java.nio.charset.Charset
import better.files.{File => Path}
/**
* @author
* uchida
*/
object IOUtil {
def createDirectory(path: Path): Unit =
path.createDirectories()
def input(path: Path): Option[String] = {
if (!path.isDirectory && path.exists)
Some(path.lines(charset = Charset.forName("UTF-8")).mkString)
else None
}
def output(path: Path, content: String) = {
if (!path.exists) {
path.parent.toJava.mkdirs()
}
path.write(content)(charset = Charset.forName("UTF-8"))
}
def directoryPaths(path: Path): Seq[Path] = {
if (path.isDirectory)
path.list.filter(_.isDirectory).toSeq
else Seq.empty[Path]
}
def isDirectory(path: String): Boolean = {
val filePath: Path = Path(path).path.toAbsolutePath
filePath.isDirectory
}
def rename(from: Path, to: Path) =
from.renameTo(to.name)
}
| nulab/backlog-migration-common | core/src/main/scala/com/nulabinc/backlog/migration/common/utils/IOUtil.scala | Scala | mit | 936 |
package com.sfxcode.sapphire.extension.showcase.controller
import com.sfxcode.sapphire.core.application.ApplicationEnvironment
import com.sfxcode.sapphire.core.controller.ViewController
import com.sfxcode.sapphire.extension.showcase.ApplicationController
trait BaseController extends ViewController {
def applicationController: ApplicationController = ApplicationEnvironment.applicationController[ApplicationController]
def showcaseController: ShowcaseViewController = applicationController.showcaseController
def updateShowcaseContent(controller: ViewController): Unit =
showcaseController.updateShowcaseContent(controller)
}
| sfxcode/sapphire-extension | demos/showcase/src/main/scala/com/sfxcode/sapphire/extension/showcase/controller/BaseController.scala | Scala | apache-2.0 | 642 |
/*
* 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.mxnetexamples.profiler
import org.scalatest.{BeforeAndAfterAll, FunSuite}
import org.slf4j.LoggerFactory
import java.io.File
import org.apache.mxnet.Profiler
import org.apache.mxnet.Context
/**
* Integration test for imageClassifier example.
* This will run as a part of "make scalatest"
*/
class ProfilerSuite extends FunSuite with BeforeAndAfterAll {
private val logger = LoggerFactory.getLogger(classOf[ProfilerSuite])
override def beforeAll(): Unit = {
logger.info("Running profiler test...")
val eray = new ProfilerNDArray
val path = System.getProperty("java.io.tmpdir")
val kwargs = Map("file_name" -> path)
logger.info(s"profile file save to $path")
Profiler.profilerSetState("run")
}
override def afterAll(): Unit = {
Profiler.profilerSetState("stop")
}
test("Profiler Broadcast test") {
ProfilerNDArray.testBroadcast()
}
test("Profiler NDArray Saveload test") {
ProfilerNDArray.testNDArraySaveload()
}
test("Profiler NDArray Copy") {
ProfilerNDArray.testNDArrayCopy()
}
test("Profiler NDArray Negate") {
ProfilerNDArray.testNDArrayNegate()
}
test("Profiler NDArray Scalar") {
ProfilerNDArray.testNDArrayScalar()
}
test("Profiler NDArray Onehot") {
ProfilerNDArray.testNDArrayOnehot()
}
test("Profiler Clip") {
ProfilerNDArray.testClip()
}
test("Profiler Dot") {
ProfilerNDArray.testDot()
}
}
| mbaijal/incubator-mxnet | scala-package/examples/src/test/scala/org/apache/mxnetexamples/profiler/ProfilerSuite.scala | Scala | apache-2.0 | 2,244 |
/**
* Copyright (C) 2010-2011 LShift Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.lshift.diffa.kernel.participants
import net.lshift.diffa.adapter.scanning.ScanConstraint
/**
* Specifies the next action to take when building a digest tree.
*/
trait QueryAction
/**
* The next action should still be an aggregating action
* @param bucketing the names of the bucketing functions to apply on attributes. Any attribute not named should not
* be bucketed
* @param constraints the constraints to apply to the aggregation
*/
case class AggregateQueryAction(bucketing:Seq[CategoryFunction], constraints:Seq[ScanConstraint]) extends QueryAction
/**
* The next action should query on an individual level
*/
case class EntityQueryAction(constraints:Seq[ScanConstraint]) extends QueryAction | lshift/diffa | kernel/src/main/scala/net/lshift/diffa/kernel/participants/QueryAction.scala | Scala | apache-2.0 | 1,348 |
package app.db
import com.datastax.driver.core.Session
import com.outworkers.phantom.connectors.KeySpace
trait RootConnector {
implicit def space: KeySpace
implicit def session: Session
}
| PScopelliti/ProjectTracker | note-service/src/main/scala/app/db/RootConnector.scala | Scala | apache-2.0 | 196 |
/***********************************************************************
* Copyright (c) 2013-2017 Commonwealth Computer Research, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at
* http://www.opensource.org/licenses/apache2.0.php.
***********************************************************************/
package org.locationtech.geomesa.filter
import org.geotools.filter.visitor.DefaultFilterVisitor
import org.opengis.filter.{And, Filter}
import scala.collection.JavaConversions._
// This class helps us split a Filter into pieces if there are ANDs at the top.
class AndSplittingFilter extends DefaultFilterVisitor {
// This function really returns a Seq[Filter].
override def visit(filter: And, data: scala.Any): AnyRef = {
filter.getChildren.flatMap { subfilter =>
this.visit(subfilter, data)
}
}
def visit(filter: Filter, data: scala.Any): Seq[Filter] = {
filter match {
case a: And => visit(a, data).asInstanceOf[Seq[Filter]]
case _ => Seq(filter)
}
}
}
| ronq/geomesa | geomesa-filter/src/main/scala/org/locationtech/geomesa/filter/AndSplittingFilter.scala | Scala | apache-2.0 | 1,173 |
package pl.writeonly.son2.vaadin.servlets
import com.vaadin.annotations.VaadinServletConfiguration
import com.vaadin.server.VaadinServlet
import pl.writeonly.son2.vaadin.ui._
@VaadinServletConfiguration(ui = classOf[UIMain], productionMode = false)
class Servlet extends VaadinServlet
@VaadinServletConfiguration(ui = classOf[UIConverter], productionMode = false)
class ServletConverter extends VaadinServlet
@VaadinServletConfiguration(ui = classOf[UIComparator], productionMode = false)
class ServletComparator extends VaadinServlet
@VaadinServletConfiguration(ui = classOf[UIDiff], productionMode = false)
class ServletDiff extends VaadinServlet
@VaadinServletConfiguration(ui = classOf[UIFormatter], productionMode = false)
class ServletFormatter extends VaadinServlet
@VaadinServletConfiguration(ui = classOf[UIPath], productionMode = false)
class ServletPath extends VaadinServlet
@VaadinServletConfiguration(ui = classOf[UIPatch], productionMode = false)
class ServletPatch extends VaadinServlet | writeonly/scalare | scalare-adin/src/main/scala/pl/writeonly/son2/vaadin/servlets/Servlet.scala | Scala | artistic-2.0 | 1,010 |
package io.config
import locals._
case class Configuration(
settings: SettingsConfig,
spawn: SpawnConfig,
turbulence: TurbulenceConfig,
larva: LarvaConfig,
flow: FlowConfig,
habitat: HabitatConfig,
output: OutputFilesConfig
)
case class SettingsConfig(
randomSeed: Int
)
case class SpawningLocationConfig(
name: String,
patchNumber: Int,
site: SiteConfig,
numberOfLarvae: Int,
releasePeriod: ReleasePeriodConfig,
interval: Int
)
case class SpawnConfig(spawningLocation: List[SpawningLocationConfig])
case class SiteConfig(
longitude: Double,
latitude: Double,
depth: Double,
flowId: Option[Int]
)
case class ReleasePeriodConfig(start: String, end: String)
case class TurbulenceConfig(
horizontalDiffusionCoefficient: Double,
verticalDiffusionCoefficient: Double,
applyTurbulence: Boolean,
interval: Int
)
case class FlowConfig(
netcdfFilePath: String,
period: PeriodConfig,
timeStep: TimeStepConfig,
includeVerticalVelocity: Boolean
)
case class PeriodConfig(start: String, end: String)
case class TimeStepConfig(unit: String, duration: Int)
case class HabitatConfig(shapeFilePath: String, buffer: BufferConfig)
case class BufferConfig(
settlement: Double,
olfactory: Double
)
case class OutputFilesConfig(
includeLarvaeHistory: Boolean,
saveOutputFilePath: String,
percentage: Int,
prefix: String,
logLevel: String,
logFile: String
)
case class LarvaConfig(
species: String,
ontogeny: OntogenyConfig,
swimming: Option[SwimmingConfig],
ovmProbabilities: Option[OntogeneticMigrationConfig],
dielProbabilities: Option[DielMigrationConfig],
pelagicLarvalDuration: PelagicLarvalDurationConfig,
isMortal: Option[Boolean],
mortalityRate: Option[Double]
)
case class OntogenyConfig(
hatching: Int,
preflexion: Int,
flexion: Int,
postflexion: Int
)
case class SwimmingConfig(
strategy: String,
ability: Option[String],
criticalSwimmingSpeed: Option[Double],
inSituSwimmingPotential: Option[Double],
endurance: Option[Double],
reynoldsEffect: Option[Boolean],
hatchSwimmingSpeed: Option[Double]
)
case class PelagicLarvalDurationConfig(
mean: Double,
stdev: Double,
pldType: String,
nonSettlementPeriod: Double
)
case class OntogeneticMigrationConfig(
implementation: String,
depths: List[Int],
hatching: List[Double],
preflexion: List[Double],
flexion: List[Double],
postflexion: List[Double]
)
case class DielMigrationConfig(
depths: List[Double],
day: List[Double],
night: List[Double]
)
| shawes/zissou | src/main/scala/io/config/Configuration.scala | Scala | mit | 2,665 |
/*
* 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.types
import org.apache.spark.{SparkException, SparkFunSuite}
import org.apache.spark.sql.catalyst.parser.CatalystSqlParser
class DataTypeSuite extends SparkFunSuite {
test("construct an ArrayType") {
val array = ArrayType(StringType)
assert(ArrayType(StringType, true) === array)
}
test("construct an MapType") {
val map = MapType(StringType, IntegerType)
assert(MapType(StringType, IntegerType, true) === map)
}
test("construct with add") {
val struct = (new StructType)
.add("a", IntegerType, true)
.add("b", LongType, false)
.add("c", StringType, true)
assert(StructField("b", LongType, false) === struct("b"))
}
test("construct with add from StructField") {
// Test creation from StructField type
val struct = (new StructType)
.add(StructField("a", IntegerType, true))
.add(StructField("b", LongType, false))
.add(StructField("c", StringType, true))
assert(StructField("b", LongType, false) === struct("b"))
}
test("construct with String DataType") {
// Test creation with DataType as String
val struct = (new StructType)
.add("a", "int", true)
.add("b", "long", false)
.add("c", "string", true)
assert(StructField("a", IntegerType, true) === struct("a"))
assert(StructField("b", LongType, false) === struct("b"))
assert(StructField("c", StringType, true) === struct("c"))
}
test("extract fields from a StructType") {
val struct = StructType(
StructField("a", IntegerType, true) ::
StructField("b", LongType, false) ::
StructField("c", StringType, true) ::
StructField("d", FloatType, true) :: Nil)
assert(StructField("b", LongType, false) === struct("b"))
intercept[IllegalArgumentException] {
struct("e")
}
val expectedStruct = StructType(
StructField("b", LongType, false) ::
StructField("d", FloatType, true) :: Nil)
assert(expectedStruct === struct(Set("b", "d")))
intercept[IllegalArgumentException] {
struct(Set("b", "d", "e", "f"))
}
}
test("extract field index from a StructType") {
val struct = StructType(
StructField("a", LongType) ::
StructField("b", FloatType) :: Nil)
assert(struct.fieldIndex("a") === 0)
assert(struct.fieldIndex("b") === 1)
intercept[IllegalArgumentException] {
struct.fieldIndex("non_existent")
}
}
test("fieldsMap returns map of name to StructField") {
val struct = StructType(
StructField("a", LongType) ::
StructField("b", FloatType) :: Nil)
val mapped = StructType.fieldsMap(struct.fields)
val expected = Map(
"a" -> StructField("a", LongType),
"b" -> StructField("b", FloatType))
assert(mapped === expected)
}
test("merge where right is empty") {
val left = StructType(
StructField("a", LongType) ::
StructField("b", FloatType) :: Nil)
val right = StructType(List())
val merged = left.merge(right)
assert(DataType.equalsIgnoreCompatibleNullability(merged, left))
assert(merged("a").metadata.getBoolean(StructType.metadataKeyForOptionalField))
assert(merged("b").metadata.getBoolean(StructType.metadataKeyForOptionalField))
}
test("merge where left is empty") {
val left = StructType(List())
val right = StructType(
StructField("a", LongType) ::
StructField("b", FloatType) :: Nil)
val merged = left.merge(right)
assert(DataType.equalsIgnoreCompatibleNullability(merged, right))
assert(merged("a").metadata.getBoolean(StructType.metadataKeyForOptionalField))
assert(merged("b").metadata.getBoolean(StructType.metadataKeyForOptionalField))
}
test("merge where both are non-empty") {
val left = StructType(
StructField("a", LongType) ::
StructField("b", FloatType) :: Nil)
val right = StructType(
StructField("c", LongType) :: Nil)
val expected = StructType(
StructField("a", LongType) ::
StructField("b", FloatType) ::
StructField("c", LongType) :: Nil)
val merged = left.merge(right)
assert(DataType.equalsIgnoreCompatibleNullability(merged, expected))
assert(merged("a").metadata.getBoolean(StructType.metadataKeyForOptionalField))
assert(merged("b").metadata.getBoolean(StructType.metadataKeyForOptionalField))
assert(merged("c").metadata.getBoolean(StructType.metadataKeyForOptionalField))
}
test("merge where right contains type conflict") {
val left = StructType(
StructField("a", LongType) ::
StructField("b", FloatType) :: Nil)
val right = StructType(
StructField("b", LongType) :: Nil)
intercept[SparkException] {
left.merge(right)
}
}
test("existsRecursively") {
val struct = StructType(
StructField("a", LongType) ::
StructField("b", FloatType) :: Nil)
assert(struct.existsRecursively(_.isInstanceOf[LongType]))
assert(struct.existsRecursively(_.isInstanceOf[StructType]))
assert(!struct.existsRecursively(_.isInstanceOf[IntegerType]))
val mapType = MapType(struct, StringType)
assert(mapType.existsRecursively(_.isInstanceOf[LongType]))
assert(mapType.existsRecursively(_.isInstanceOf[StructType]))
assert(mapType.existsRecursively(_.isInstanceOf[StringType]))
assert(mapType.existsRecursively(_.isInstanceOf[MapType]))
assert(!mapType.existsRecursively(_.isInstanceOf[IntegerType]))
val arrayType = ArrayType(mapType)
assert(arrayType.existsRecursively(_.isInstanceOf[LongType]))
assert(arrayType.existsRecursively(_.isInstanceOf[StructType]))
assert(arrayType.existsRecursively(_.isInstanceOf[StringType]))
assert(arrayType.existsRecursively(_.isInstanceOf[MapType]))
assert(arrayType.existsRecursively(_.isInstanceOf[ArrayType]))
assert(!arrayType.existsRecursively(_.isInstanceOf[IntegerType]))
}
def checkDataTypeJsonRepr(dataType: DataType): Unit = {
test(s"JSON - $dataType") {
assert(DataType.fromJson(dataType.json) === dataType)
}
}
checkDataTypeJsonRepr(NullType)
checkDataTypeJsonRepr(BooleanType)
checkDataTypeJsonRepr(ByteType)
checkDataTypeJsonRepr(ShortType)
checkDataTypeJsonRepr(IntegerType)
checkDataTypeJsonRepr(LongType)
checkDataTypeJsonRepr(FloatType)
checkDataTypeJsonRepr(DoubleType)
checkDataTypeJsonRepr(DecimalType(10, 5))
checkDataTypeJsonRepr(DecimalType.SYSTEM_DEFAULT)
checkDataTypeJsonRepr(DateType)
checkDataTypeJsonRepr(TimestampType)
checkDataTypeJsonRepr(StringType)
checkDataTypeJsonRepr(BinaryType)
checkDataTypeJsonRepr(ArrayType(DoubleType, true))
checkDataTypeJsonRepr(ArrayType(StringType, false))
checkDataTypeJsonRepr(MapType(IntegerType, StringType, true))
checkDataTypeJsonRepr(MapType(IntegerType, ArrayType(DoubleType), false))
val metadata = new MetadataBuilder()
.putString("name", "age")
.build()
val structType = StructType(Seq(
StructField("a", IntegerType, nullable = true),
StructField("b", ArrayType(DoubleType), nullable = false),
StructField("c", DoubleType, nullable = false, metadata)))
checkDataTypeJsonRepr(structType)
def checkDefaultSize(dataType: DataType, expectedDefaultSize: Int): Unit = {
test(s"Check the default size of ${dataType}") {
assert(dataType.defaultSize === expectedDefaultSize)
}
}
checkDefaultSize(NullType, 1)
checkDefaultSize(BooleanType, 1)
checkDefaultSize(ByteType, 1)
checkDefaultSize(ShortType, 2)
checkDefaultSize(IntegerType, 4)
checkDefaultSize(LongType, 8)
checkDefaultSize(FloatType, 4)
checkDefaultSize(DoubleType, 8)
checkDefaultSize(DecimalType(10, 5), 8)
checkDefaultSize(DecimalType.SYSTEM_DEFAULT, 16)
checkDefaultSize(DateType, 4)
checkDefaultSize(TimestampType, 8)
checkDefaultSize(StringType, 20)
checkDefaultSize(BinaryType, 100)
checkDefaultSize(ArrayType(DoubleType, true), 800)
checkDefaultSize(ArrayType(StringType, false), 2000)
checkDefaultSize(MapType(IntegerType, StringType, true), 2400)
checkDefaultSize(MapType(IntegerType, ArrayType(DoubleType), false), 80400)
checkDefaultSize(structType, 812)
def checkEqualsIgnoreCompatibleNullability(
from: DataType,
to: DataType,
expected: Boolean): Unit = {
val testName =
s"equalsIgnoreCompatibleNullability: (from: ${from}, to: ${to})"
test(testName) {
assert(DataType.equalsIgnoreCompatibleNullability(from, to) === expected)
}
}
checkEqualsIgnoreCompatibleNullability(
from = ArrayType(DoubleType, containsNull = true),
to = ArrayType(DoubleType, containsNull = true),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = ArrayType(DoubleType, containsNull = false),
to = ArrayType(DoubleType, containsNull = false),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = ArrayType(DoubleType, containsNull = false),
to = ArrayType(DoubleType, containsNull = true),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = ArrayType(DoubleType, containsNull = true),
to = ArrayType(DoubleType, containsNull = false),
expected = false)
checkEqualsIgnoreCompatibleNullability(
from = ArrayType(DoubleType, containsNull = false),
to = ArrayType(StringType, containsNull = false),
expected = false)
checkEqualsIgnoreCompatibleNullability(
from = MapType(StringType, DoubleType, valueContainsNull = true),
to = MapType(StringType, DoubleType, valueContainsNull = true),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = MapType(StringType, DoubleType, valueContainsNull = false),
to = MapType(StringType, DoubleType, valueContainsNull = false),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = MapType(StringType, DoubleType, valueContainsNull = false),
to = MapType(StringType, DoubleType, valueContainsNull = true),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = MapType(StringType, DoubleType, valueContainsNull = true),
to = MapType(StringType, DoubleType, valueContainsNull = false),
expected = false)
checkEqualsIgnoreCompatibleNullability(
from = MapType(StringType, ArrayType(IntegerType, true), valueContainsNull = true),
to = MapType(StringType, ArrayType(IntegerType, false), valueContainsNull = true),
expected = false)
checkEqualsIgnoreCompatibleNullability(
from = MapType(StringType, ArrayType(IntegerType, false), valueContainsNull = true),
to = MapType(StringType, ArrayType(IntegerType, true), valueContainsNull = true),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = StructType(StructField("a", StringType, nullable = true) :: Nil),
to = StructType(StructField("a", StringType, nullable = true) :: Nil),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = StructType(StructField("a", StringType, nullable = false) :: Nil),
to = StructType(StructField("a", StringType, nullable = false) :: Nil),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = StructType(StructField("a", StringType, nullable = false) :: Nil),
to = StructType(StructField("a", StringType, nullable = true) :: Nil),
expected = true)
checkEqualsIgnoreCompatibleNullability(
from = StructType(StructField("a", StringType, nullable = true) :: Nil),
to = StructType(StructField("a", StringType, nullable = false) :: Nil),
expected = false)
checkEqualsIgnoreCompatibleNullability(
from = StructType(
StructField("a", StringType, nullable = false) ::
StructField("b", StringType, nullable = true) :: Nil),
to = StructType(
StructField("a", StringType, nullable = false) ::
StructField("b", StringType, nullable = false) :: Nil),
expected = false)
def checkCatalogString(dt: DataType): Unit = {
test(s"catalogString: $dt") {
val dt2 = CatalystSqlParser.parseDataType(dt.catalogString)
assert(dt === dt2)
}
}
def createStruct(n: Int): StructType = new StructType(Array.tabulate(n) {
i => StructField(s"col$i", IntegerType, nullable = true)
})
checkCatalogString(BooleanType)
checkCatalogString(ByteType)
checkCatalogString(ShortType)
checkCatalogString(IntegerType)
checkCatalogString(LongType)
checkCatalogString(FloatType)
checkCatalogString(DoubleType)
checkCatalogString(DecimalType(10, 5))
checkCatalogString(BinaryType)
checkCatalogString(StringType)
checkCatalogString(DateType)
checkCatalogString(TimestampType)
checkCatalogString(createStruct(4))
checkCatalogString(createStruct(40))
checkCatalogString(ArrayType(IntegerType))
checkCatalogString(ArrayType(createStruct(40)))
checkCatalogString(MapType(IntegerType, StringType))
checkCatalogString(MapType(IntegerType, createStruct(40)))
}
| gioenn/xSpark | sql/catalyst/src/test/scala/org/apache/spark/sql/types/DataTypeSuite.scala | Scala | apache-2.0 | 13,652 |
/*
* 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.internal.config
import java.util.concurrent.TimeUnit
private[spark] object Network {
private[spark] val NETWORK_CRYPTO_SASL_FALLBACK =
ConfigBuilder("spark.network.crypto.saslFallback")
.version("2.2.0")
.booleanConf
.createWithDefault(true)
private[spark] val NETWORK_CRYPTO_ENABLED =
ConfigBuilder("spark.network.crypto.enabled")
.version("2.2.0")
.booleanConf
.createWithDefault(false)
private[spark] val NETWORK_REMOTE_READ_NIO_BUFFER_CONVERSION =
ConfigBuilder("spark.network.remoteReadNioBufferConversion")
.version("2.4.0")
.booleanConf
.createWithDefault(false)
private[spark] val NETWORK_TIMEOUT =
ConfigBuilder("spark.network.timeout")
.version("1.3.0")
.timeConf(TimeUnit.SECONDS)
.createWithDefaultString("120s")
private[spark] val NETWORK_TIMEOUT_INTERVAL =
ConfigBuilder("spark.network.timeoutInterval")
.version("1.3.2")
.timeConf(TimeUnit.MILLISECONDS)
.createWithDefaultString(STORAGE_BLOCKMANAGER_TIMEOUTINTERVAL.defaultValueString)
private[spark] val RPC_ASK_TIMEOUT =
ConfigBuilder("spark.rpc.askTimeout")
.version("1.4.0")
.stringConf
.createOptional
private[spark] val RPC_CONNECT_THREADS =
ConfigBuilder("spark.rpc.connect.threads")
.version("1.6.0")
.intConf
.createWithDefault(64)
private[spark] val RPC_IO_NUM_CONNECTIONS_PER_PEER =
ConfigBuilder("spark.rpc.io.numConnectionsPerPeer")
.version("1.6.0")
.intConf
.createWithDefault(1)
private[spark] val RPC_IO_THREADS =
ConfigBuilder("spark.rpc.io.threads")
.version("1.6.0")
.intConf
.createOptional
private[spark] val RPC_LOOKUP_TIMEOUT =
ConfigBuilder("spark.rpc.lookupTimeout")
.version("1.4.0")
.stringConf
.createOptional
private[spark] val RPC_MESSAGE_MAX_SIZE =
ConfigBuilder("spark.rpc.message.maxSize")
.version("2.0.0")
.intConf
.createWithDefault(128)
private[spark] val RPC_NETTY_DISPATCHER_NUM_THREADS =
ConfigBuilder("spark.rpc.netty.dispatcher.numThreads")
.version("1.6.0")
.intConf
.createOptional
private[spark] val RPC_NUM_RETRIES =
ConfigBuilder("spark.rpc.numRetries")
.version("1.4.0")
.intConf
.createWithDefault(3)
private[spark] val RPC_RETRY_WAIT =
ConfigBuilder("spark.rpc.retry.wait")
.version("1.4.0")
.timeConf(TimeUnit.MILLISECONDS)
.createWithDefaultString("3s")
}
| maropu/spark | core/src/main/scala/org/apache/spark/internal/config/Network.scala | Scala | apache-2.0 | 3,353 |
package lila.game
import cats.data.Validated
import chess.format.{ FEN, pgn => chessPgn }
import org.joda.time.DateTime
object Rewind {
private def createTags(fen: Option[FEN], game: Game) = {
val variantTag = Some(chessPgn.Tag(_.Variant, game.variant.name))
val fenTag = fen.map(f => chessPgn.Tag(_.FEN, f.value))
chessPgn.Tags(List(variantTag, fenTag).flatten)
}
def apply(game: Game, initialFen: Option[FEN]): Validated[String, Progress] =
chessPgn.Reader
.movesWithSans(
moveStrs = game.pgnMoves,
op = sans => chessPgn.Sans(sans.value.dropRight(1)),
tags = createTags(initialFen, game)
)
.flatMap(_.valid) map { replay =>
val rewindedGame = replay.state
val color = game.turnColor
val newClock = game.clock.map(_.takeback) map { clk =>
game.clockHistory.flatMap(_.last(color)).fold(clk) { t =>
clk.setRemainingTime(color, t)
}
}
def rewindPlayer(player: Player) = player.copy(proposeTakebackAt = 0)
val newGame = game.copy(
whitePlayer = rewindPlayer(game.whitePlayer),
blackPlayer = rewindPlayer(game.blackPlayer),
chess = rewindedGame.copy(clock = newClock),
binaryMoveTimes = game.binaryMoveTimes.map { binary =>
val moveTimes = BinaryFormat.moveTime.read(binary, game.playedTurns)
BinaryFormat.moveTime.write(moveTimes.dropRight(1))
},
loadClockHistory = _ => game.clockHistory.map(_.update(!color, _.dropRight(1))),
movedAt = DateTime.now
)
Progress(game, newGame)
}
}
| luanlv/lila | modules/game/src/main/Rewind.scala | Scala | mit | 1,612 |
package db
import javax.inject.{Inject, Singleton}
import io.flow.dependency.actors.BinaryActor
import io.flow.dependency.v0.models.{Binary, BinaryForm, SyncEvent}
import io.flow.common.v0.models.UserReference
import io.flow.postgresql.{OrderBy, Pager, Query}
import anorm._
import com.google.inject.Provider
import io.flow.util.IdGenerator
import play.api.db._
@Singleton
class BinariesDao @Inject()(
db: Database,
binaryVersionsDaoProvider: Provider[BinaryVersionsDao],
membershipsDaoProvider: Provider[MembershipsDao],
internalTasksDao: InternalTasksDao,
@javax.inject.Named("binary-actor") binaryActor: akka.actor.ActorRef,
) {
private[this] val dbHelpers = DbHelpers(db, "binaries")
private[this] val BaseQuery = Query(s"""
select binaries.id,
binaries.name,
organizations.id as organization_id,
organizations.key as organization_key
from binaries
left join organizations on organizations.id = binaries.organization_id
""")
private[this] val InsertQuery = """
insert into binaries
(id, organization_id, name, updated_by_user_id)
values
({id}, {organization_id}, {name}, {updated_by_user_id})
"""
private[db] def validate(
form: BinaryForm
): Seq[String] = {
if (form.name.toString.trim == "") {
Seq("Name cannot be empty")
} else {
findByName(form.name.toString) match {
case None => Seq.empty
case Some(_) => Seq("Binary with this name already exists")
}
}
}
def upsert(createdBy: UserReference, form: BinaryForm): Either[Seq[String], Binary] = {
findByName(form.name.toString) match {
case Some(binary) => Right(binary)
case None => create(createdBy, form)
}
}
def create(createdBy: UserReference, form: BinaryForm): Either[Seq[String], Binary] = {
validate(form) match {
case Nil => {
val id = IdGenerator("bin").randomId()
db.withConnection { implicit c =>
SQL(InsertQuery).on(
Symbol("id") -> id,
Symbol("organization_id") -> form.organizationId,
Symbol("name") -> form.name.toString.toLowerCase,
Symbol("updated_by_user_id") -> createdBy.id
).execute()
}
val binary = findById(id).getOrElse {
sys.error("Failed to create binary")
}
internalTasksDao.queueBinary(binary)
Right(binary)
}
case errors => Left(errors)
}
}
def delete(deletedBy: UserReference, binary: Binary): Either[Seq[String], Unit] = {
membershipsDaoProvider.get.authorizeOrg(binary.organization, deletedBy) {
Pager.create { offset =>
binaryVersionsDaoProvider.get().findAll(binaryId = Some(binary.id), offset = offset)
}.foreach {
binaryVersionsDaoProvider.get().delete(deletedBy, _)
}
dbHelpers.delete(deletedBy.id, binary.id)
binaryActor ! BinaryActor.Messages.Delete(binary.id)
}
}
def findByName(name: String): Option[Binary] = {
findAll(name = Some(name), limit = 1).headOption
}
def findById(id: String): Option[Binary] = {
findAll(id = Some(id), limit = 1).headOption
}
def findAll(
id: Option[String] = None,
ids: Option[Seq[String]] = None,
projectId: Option[String] = None,
organizationId: Option[String] = None,
name: Option[String] = None,
isSynced: Option[Boolean] = None,
orderBy: OrderBy = OrderBy(s"-lower(binaries.name),binaries.created_at"),
limit: Long = 25,
offset: Long = 0
): Seq[Binary] = {
db.withConnection { implicit c =>
BaseQuery.
equals("binaries.id", id).
optionalIn("binaries.id", ids).
and (
projectId.map { _ =>
s"binaries.id in (select binary_id from project_binaries where binary_id is not null and project_id = {project_id})"
}
).bind("project_id", projectId).
equals("binaries.organization_id", organizationId).
optionalText(
"binaries.name",
name,
columnFunctions = Seq(Query.Function.Lower),
valueFunctions = Seq(Query.Function.Lower, Query.Function.Trim)
).
and(
isSynced.map { value =>
val clause = "select 1 from syncs where object_id = binaries.id and event = {sync_event_completed}"
if (value) {
s"exists ($clause)"
} else {
s"not exists ($clause)"
}
}
).
bind("sync_event_completed", SyncEvent.Completed.toString).
orderBy(orderBy.sql).
limit(limit).
offset(offset).
as(
io.flow.dependency.v0.anorm.parsers.Binary.parser().*
)
}
}
}
| flowcommerce/dependency | api/app/db/BinariesDao.scala | Scala | mit | 4,729 |
package models.daos
import akka.actor.Status.Success
import com.google.inject.Inject
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.api.util.{PasswordHasherRegistry, PasswordInfo}
import com.mohiva.play.silhouette.password.BCryptPasswordHasher
import com.mohiva.play.silhouette.persistence.daos.DelegableAuthInfoDAO
import models.{Password, User}
import scala.collection.mutable
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import com.mohiva.play.silhouette.api.exceptions.AuthenticatorCreationException
import models.tables.{PasswordTableDef, UserTableDef}
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.driver.JdbcProfile
/**
* PasswordInfo dao impl
*/
class PasswordInfoDAO @Inject()(protected val dbConfigProvider: DatabaseConfigProvider,
passwordHasherRegistry: PasswordHasherRegistry)
extends DelegableAuthInfoDAO[PasswordInfo] with HasDatabaseConfigProvider[JdbcProfile] {
import dbConfig.driver.api._
val users = TableQuery[UserTableDef]
val passwords = TableQuery[PasswordTableDef]
override def find(loginInfo: LoginInfo): Future[Option[PasswordInfo]] = {
val usersWithPassword = for {
(u, p) <- users join passwords on (_.id === _.userId)
} yield (u.id, u.username, p.password)
def userHavingUsername(username: String) = usersWithPassword.filter(
_._2 === username)
val password = userHavingUsername(loginInfo.providerKey).map(_._3).result.headOption
val authInfo = password.map {
case Some(password) => Some(PasswordInfo(passwordHasherRegistry.current.id, password))
case None => None
}
db.run(authInfo)
}
override def add(loginInfo: LoginInfo, authInfo: PasswordInfo): Future[PasswordInfo] = {
// I haven't found a way to compose DBIOAction here
// http://tastefulcode.com/2015/03/19/modern-database-access-scala-slick/
val maybeUserid = db.run(
users.filter(_.username === loginInfo.providerKey).map(_.id).result.headOption)
val password = maybeUserid.flatMap {
case Some(userId) => db.run(
passwords returning passwords.map(_.password) += Password(userId, authInfo.password))
case None => throw new Exception("no user for loginInfo " + loginInfo)
}
password.map(PasswordInfo(passwordHasherRegistry.current.id, _))
.recover {
case e: Exception => throw new Exception("failed to create password " + authInfo)
}
}
override def update(loginInfo: LoginInfo, authInfo: PasswordInfo): Future[PasswordInfo] = {
val userWithUsername = users.filter(_.username === loginInfo.providerKey).result.headOption
val update = userWithUsername.flatMap {
case None => throw new Exception("no user for loginInfo " + loginInfo)
case Some(user) =>
val password: Password = Password(user.id, authInfo.password)
passwords.filter(_.userId === user.id).update(password)
}
db.run(update).map {
case 0 => throw new Exception("failed to update password")
case _ => authInfo
}
}
override def save(loginInfo: LoginInfo, authInfo: PasswordInfo): Future[PasswordInfo] = ???
override def remove(loginInfo: LoginInfo): Future[Unit] = ???
}
| agoetschm/linkmanager | server/app/models/daos/PasswordInfoDAO.scala | Scala | gpl-3.0 | 3,300 |
package text.kanji
/**
* @author K.Sakamoto
* Created on 2016/07/26
*/
object JISLevel3KanjiCharacter extends KanjiCharacter {
override val kanji: Seq[String] = readKanjiCSV("jis_level_3")
}
| ktr-skmt/FelisCatusZero | src/main/scala/text/kanji/JISLevel3KanjiCharacter.scala | Scala | apache-2.0 | 208 |
package net.fwbrasil.activate.serialization
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.Output
import com.esotericsoftware.kryo.io.Input
import com.esotericsoftware.kryo.{ Serializer => KryoSerializer }
import org.objenesis.strategy.StdInstantiatorStrategy
import java.nio.ByteBuffer
object kryoSerializer extends Serializer {
def toSerialized[T: Manifest](value: T): Array[Byte] = {
val baos = new ByteArrayOutputStream();
val output = new Output(baos)
newKryo.writeObject(output, value)
output.close
baos.toByteArray()
}
def fromSerialized[T: Manifest](bytes: Array[Byte]): T = {
val bais = new ByteArrayInputStream(bytes);
val input = new Input(bais)
val obj = newKryo.readObject(input, manifest[T].runtimeClass)
input.close
obj.asInstanceOf[T]
}
private def newKryo: com.esotericsoftware.kryo.Kryo = {
val kryo = new Kryo
kryo.setInstantiatorStrategy(new StdInstantiatorStrategy)
kryo.register(None.getClass, noneSerializer)
kryo.register(classOf[Some[_]], someSerializer)
kryo
}
}
object noneSerializer extends KryoSerializer[None.type] {
def read(kryo: Kryo, input: Input, clazz: Class[None.type]): None.type = None
def write(kryo: Kryo, output: Output, clazz: None.type): Unit = {}
}
object someSerializer extends KryoSerializer[Some[_]] {
def read(kryo: Kryo, input: Input, clazz: Class[Some[_]]): Some[_] = Some(kryo.readClassAndObject(input))
def write(kryo: Kryo, output: Output, value: Some[_]): Unit = kryo.writeClassAndObject(output, value.get)
} | xdevelsistemas/activate | activate-core/src/main/scala/net/fwbrasil/activate/serialization/kryoSerializer.scala | Scala | lgpl-2.1 | 1,872 |
/*
* 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.types
import scala.collection.mutable.ArrayBuffer
import org.json4s.JsonDSL._
import org.apache.spark.SparkException
import org.apache.spark.annotation.DeveloperApi
import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference, InterpretedOrdering}
/**
* :: DeveloperApi ::
* A [[StructType]] object can be constructed by
* {{{
* StructType(fields: Seq[StructField])
* }}}
* For a [[StructType]] object, one or multiple [[StructField]]s can be extracted by names.
* If multiple [[StructField]]s are extracted, a [[StructType]] object will be returned.
* If a provided name does not have a matching field, it will be ignored. For the case
* of extracting a single StructField, a `null` will be returned.
* Example:
* {{{
* import org.apache.spark.sql._
* import org.apache.spark.sql.types._
*
* val struct =
* StructType(
* StructField("a", IntegerType, true) ::
* StructField("b", LongType, false) ::
* StructField("c", BooleanType, false) :: Nil)
*
* // Extract a single StructField.
* val singleField = struct("b")
* // singleField: StructField = StructField(b,LongType,false)
*
* // This struct does not have a field called "d". null will be returned.
* val nonExisting = struct("d")
* // nonExisting: StructField = null
*
* // Extract multiple StructFields. Field names are provided in a set.
* // A StructType object will be returned.
* val twoFields = struct(Set("b", "c"))
* // twoFields: StructType =
* // StructType(List(StructField(b,LongType,false), StructField(c,BooleanType,false)))
*
* // Any names without matching fields will be ignored.
* // For the case shown below, "d" will be ignored and
* // it is treated as struct(Set("b", "c")).
* val ignoreNonExisting = struct(Set("b", "c", "d"))
* // ignoreNonExisting: StructType =
* // StructType(List(StructField(b,LongType,false), StructField(c,BooleanType,false)))
* }}}
*
* A [[org.apache.spark.sql.Row]] object is used as a value of the StructType.
* Example:
* {{{
* import org.apache.spark.sql._
*
* val innerStruct =
* StructType(
* StructField("f1", IntegerType, true) ::
* StructField("f2", LongType, false) ::
* StructField("f3", BooleanType, false) :: Nil)
*
* val struct = StructType(
* StructField("a", innerStruct, true) :: Nil)
*
* // Create a Row with the schema defined by struct
* val row = Row(Row(1, 2, true))
* // row: Row = [[1,2,true]]
* }}}
*/
@DeveloperApi
case class StructType(fields: Array[StructField]) extends DataType with Seq[StructField] {
/** No-arg constructor for kryo. */
def this() = this(Array.empty[StructField])
/** Returns all field names in an array. */
def fieldNames: Array[String] = fields.map(_.name)
private lazy val fieldNamesSet: Set[String] = fieldNames.toSet
private lazy val nameToField: Map[String, StructField] = fields.map(f => f.name -> f).toMap
private lazy val nameToIndex: Map[String, Int] = fieldNames.zipWithIndex.toMap
/**
* Creates a new [[StructType]] by adding a new field.
* {{{
* val struct = (new StructType)
* .add(StructField("a", IntegerType, true))
* .add(StructField("b", LongType, false))
* .add(StructField("c", StringType, true))
*}}}
*/
def add(field: StructField): StructType = {
StructType(fields :+ field)
}
/**
* Creates a new [[StructType]] by adding a new nullable field with no metadata.
*
* val struct = (new StructType)
* .add("a", IntegerType)
* .add("b", LongType)
* .add("c", StringType)
*/
def add(name: String, dataType: DataType): StructType = {
StructType(fields :+ new StructField(name, dataType, nullable = true, Metadata.empty))
}
/**
* Creates a new [[StructType]] by adding a new field with no metadata.
*
* val struct = (new StructType)
* .add("a", IntegerType, true)
* .add("b", LongType, false)
* .add("c", StringType, true)
*/
def add(name: String, dataType: DataType, nullable: Boolean): StructType = {
StructType(fields :+ new StructField(name, dataType, nullable, Metadata.empty))
}
/**
* Creates a new [[StructType]] by adding a new field and specifying metadata.
* {{{
* val struct = (new StructType)
* .add("a", IntegerType, true, Metadata.empty)
* .add("b", LongType, false, Metadata.empty)
* .add("c", StringType, true, Metadata.empty)
* }}}
*/
def add(
name: String,
dataType: DataType,
nullable: Boolean,
metadata: Metadata): StructType = {
StructType(fields :+ new StructField(name, dataType, nullable, metadata))
}
/**
* Creates a new [[StructType]] by adding a new nullable field with no metadata where the
* dataType is specified as a String.
*
* {{{
* val struct = (new StructType)
* .add("a", "int")
* .add("b", "long")
* .add("c", "string")
* }}}
*/
def add(name: String, dataType: String): StructType = {
add(name, DataTypeParser.parse(dataType), nullable = true, Metadata.empty)
}
/**
* Creates a new [[StructType]] by adding a new field with no metadata where the
* dataType is specified as a String.
*
* {{{
* val struct = (new StructType)
* .add("a", "int", true)
* .add("b", "long", false)
* .add("c", "string", true)
* }}}
*/
def add(name: String, dataType: String, nullable: Boolean): StructType = {
add(name, DataTypeParser.parse(dataType), nullable, Metadata.empty)
}
/**
* Creates a new [[StructType]] by adding a new field and specifying metadata where the
* dataType is specified as a String.
* {{{
* val struct = (new StructType)
* .add("a", "int", true, Metadata.empty)
* .add("b", "long", false, Metadata.empty)
* .add("c", "string", true, Metadata.empty)
* }}}
*/
def add(
name: String,
dataType: String,
nullable: Boolean,
metadata: Metadata): StructType = {
add(name, DataTypeParser.parse(dataType), nullable, metadata)
}
/**
* Extracts a [[StructField]] of the given name. If the [[StructType]] object does not
* have a name matching the given name, `null` will be returned.
*/
def apply(name: String): StructField = {
nameToField.getOrElse(name,
throw new IllegalArgumentException(s"""Field "$name" does not exist."""))
}
/**
* Returns a [[StructType]] containing [[StructField]]s of the given names, preserving the
* original order of fields. Those names which do not have matching fields will be ignored.
*/
def apply(names: Set[String]): StructType = {
val nonExistFields = names -- fieldNamesSet
if (nonExistFields.nonEmpty) {
throw new IllegalArgumentException(
s"Field ${nonExistFields.mkString(",")} does not exist.")
}
// Preserve the original order of fields.
StructType(fields.filter(f => names.contains(f.name)))
}
/**
* Returns index of a given field
*/
def fieldIndex(name: String): Int = {
nameToIndex.getOrElse(name,
throw new IllegalArgumentException(s"""Field "$name" does not exist."""))
}
private[sql] def getFieldIndex(name: String): Option[Int] = {
nameToIndex.get(name)
}
protected[sql] def toAttributes: Seq[AttributeReference] =
map(f => AttributeReference(f.name, f.dataType, f.nullable, f.metadata)())
def treeString: String = {
val builder = new StringBuilder
builder.append("root\n")
val prefix = " |"
fields.foreach(field => field.buildFormattedString(prefix, builder))
builder.toString()
}
// scalastyle:off println
def printTreeString(): Unit = println(treeString)
// scalastyle:on println
private[sql] def buildFormattedString(prefix: String, builder: StringBuilder): Unit = {
fields.foreach(field => field.buildFormattedString(prefix, builder))
}
override private[sql] def jsonValue =
("type" -> typeName) ~
("fields" -> map(_.jsonValue))
override def apply(fieldIndex: Int): StructField = fields(fieldIndex)
override def length: Int = fields.length
override def iterator: Iterator[StructField] = fields.iterator
/**
* The default size of a value of the StructType is the total default sizes of all field types.
*/
override def defaultSize: Int = fields.map(_.dataType.defaultSize).sum
override def simpleString: String = {
val fieldTypes = fields.map(field => s"${field.name}:${field.dataType.simpleString}")
s"struct<${fieldTypes.mkString(",")}>"
}
/**
* Merges with another schema (`StructType`). For a struct field A from `this` and a struct field
* B from `that`,
*
* 1. If A and B have the same name and data type, they are merged to a field C with the same name
* and data type. C is nullable if and only if either A or B is nullable.
* 2. If A doesn't exist in `that`, it's included in the result schema.
* 3. If B doesn't exist in `this`, it's also included in the result schema.
* 4. Otherwise, `this` and `that` are considered as conflicting schemas and an exception would be
* thrown.
*/
private[sql] def merge(that: StructType): StructType =
StructType.merge(this, that).asInstanceOf[StructType]
override private[spark] def asNullable: StructType = {
val newFields = fields.map {
case StructField(name, dataType, nullable, metadata) =>
StructField(name, dataType.asNullable, nullable = true, metadata)
}
StructType(newFields)
}
override private[spark] def existsRecursively(f: (DataType) => Boolean): Boolean = {
f(this) || fields.exists(field => field.dataType.existsRecursively(f))
}
@transient
private[sql] lazy val interpretedOrdering =
InterpretedOrdering.forSchema(this.fields.map(_.dataType))
}
object StructType extends AbstractDataType {
override private[sql] def defaultConcreteType: DataType = new StructType
override private[sql] def acceptsType(other: DataType): Boolean = {
other.isInstanceOf[StructType]
}
override private[sql] def simpleString: String = "struct"
private[sql] def fromString(raw: String): StructType = DataType.fromString(raw) match {
case t: StructType => t
case _ => throw new RuntimeException(s"Failed parsing StructType: $raw")
}
def apply(fields: Seq[StructField]): StructType = StructType(fields.toArray)
def apply(fields: java.util.List[StructField]): StructType = {
import scala.collection.JavaConverters._
StructType(fields.asScala)
}
protected[sql] def fromAttributes(attributes: Seq[Attribute]): StructType =
StructType(attributes.map(a => StructField(a.name, a.dataType, a.nullable, a.metadata)))
private[sql] def merge(left: DataType, right: DataType): DataType =
(left, right) match {
case (ArrayType(leftElementType, leftContainsNull),
ArrayType(rightElementType, rightContainsNull)) =>
ArrayType(
merge(leftElementType, rightElementType),
leftContainsNull || rightContainsNull)
case (MapType(leftKeyType, leftValueType, leftContainsNull),
MapType(rightKeyType, rightValueType, rightContainsNull)) =>
MapType(
merge(leftKeyType, rightKeyType),
merge(leftValueType, rightValueType),
leftContainsNull || rightContainsNull)
case (StructType(leftFields), StructType(rightFields)) =>
val newFields = ArrayBuffer.empty[StructField]
val rightMapped = fieldsMap(rightFields)
leftFields.foreach {
case leftField @ StructField(leftName, leftType, leftNullable, _) =>
rightMapped.get(leftName)
.map { case rightField @ StructField(_, rightType, rightNullable, _) =>
leftField.copy(
dataType = merge(leftType, rightType),
nullable = leftNullable || rightNullable)
}
.orElse(Some(leftField))
.foreach(newFields += _)
}
val leftMapped = fieldsMap(leftFields)
rightFields
.filterNot(f => leftMapped.get(f.name).nonEmpty)
.foreach(newFields += _)
StructType(newFields)
case (DecimalType.Fixed(leftPrecision, leftScale),
DecimalType.Fixed(rightPrecision, rightScale)) =>
if ((leftPrecision == rightPrecision) && (leftScale == rightScale)) {
DecimalType(leftPrecision, leftScale)
} else if ((leftPrecision != rightPrecision) && (leftScale != rightScale)) {
throw new SparkException("Failed to merge Decimal Tpes with incompatible " +
s"precision $leftPrecision and $rightPrecision & scale $leftScale and $rightScale")
} else if (leftPrecision != rightPrecision) {
throw new SparkException("Failed to merge Decimal Tpes with incompatible " +
s"precision $leftPrecision and $rightPrecision")
} else {
throw new SparkException("Failed to merge Decimal Tpes with incompatible " +
s"scala $leftScale and $rightScale")
}
case (leftUdt: UserDefinedType[_], rightUdt: UserDefinedType[_])
if leftUdt.userClass == rightUdt.userClass => leftUdt
case (leftType, rightType) if leftType == rightType =>
leftType
case _ =>
throw new SparkException(s"Failed to merge incompatible data types $left and $right")
}
private[sql] def fieldsMap(fields: Array[StructField]): Map[String, StructField] = {
import scala.collection.breakOut
fields.map(s => (s.name, s))(breakOut)
}
}
| chenc10/Spark-PAF | sql/catalyst/src/main/scala/org/apache/spark/sql/types/StructType.scala | Scala | apache-2.0 | 14,298 |
/*
* 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.ignite.scalar
/**
* Contains Scala "Pimp" implementations for main Ignite entities.
*/
package object pimps
| irudyak/ignite | modules/scalar/src/main/scala/org/apache/ignite/scalar/pimps/Packet.scala | Scala | apache-2.0 | 934 |
val test1 = Array(
Array(2),
Array(3,4),
Array(6,5,7),
Array(4,1,8,3),
)
def miniTotal(b:Array[Array[Int]], a:Int=0):Int = {
if (b.isEmpty)
a
else {
miniTotal(b.tail, b.head.map(x => x+a).min)
}
}
println(miniTotal(test1))
println(miniTotal(Array(Array(2))))
| ccqpein/Arithmetic-Exercises | Triangle/Triangle.scala | Scala | apache-2.0 | 283 |
/* Copyright 2015 Alessandro Maria Rizzi
* Copyright 2016 Eugenio Gianniti
*
* 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 session
import java.io.File
import scala.io.Source
case class Session(threads: List[Thread]) {
lazy val avgByQuery: Map[String, Long] = threads groupBy { _.query } map {
case (key, list) =>
val durations = list flatMap { _.executions } map { _.duration }
key -> durations.sum / durations.size
}
def validate(queueManager: QueueManager, numContainers: Int): Map[String, Double] =
threads map { x => x.query -> x.validate(queueManager, numContainers) } groupBy
{ _._1 } map { case (key, couples) => key -> couples.map(_._2).sum / couples.size }
def validateUpper(queueManager: QueueManager, numContainers: Int): Map[String, Double] =
threads map { x => x.query -> x.validateUpper(queueManager, numContainers) } groupBy
{ _._1 } map { case (key, couples) => key -> couples.map(_._2).sum / couples.size }
def validateWith(deadline: Long): Map[String, Double] =
threads map { x => x.query -> x.validateWith(deadline) } groupBy
{ _._1 } map { case (key, couples) => key -> couples.map(_._2).sum / couples.size }
}
object Session {
def apply(dir: File, profileDir: File): Session = {
val files = dir.listFiles.toList
val threads = files map { x => Thread(Source.fromFile(x).mkString, x.getName, profileDir) }
Session(threads)
}
def mainEntryPoint(inputDir: File, profilesDir: File, nContainers: Int,
deadline: Int, queues: (String, Double)*): Unit = {
val session = Session(inputDir, profilesDir)
val manager = QueueManager(session, queues:_*)
println("Users:")
manager.queues foreach { case (name, queue) => println(s"$name: ${queue.users}") }
println("Measured times:")
session.avgByQuery foreach println
println("Average:")
session validate (manager, nContainers) foreach println
println("Upper:")
session validateUpper (manager, nContainers) foreach println
println("Deadline:")
session validateWith deadline foreach println
}
}
| deib-polimi/Profiler | src/main/scala-2.11/session/Session.scala | Scala | apache-2.0 | 2,630 |
package se.gigurra.wallace.gamemodel
case class Entity(val id: String,
val isPlayerUnit: Boolean,
var position: WorldVector = new WorldVector(),
// Extensions
var name: Option[String] = None,
var team: Option[String] = None,
var velocity: Option[WorldVector] = None,
var acceleration: Option[WorldVector] = None) {
def isWithin(maxDelta: Int, otherPosition: WorldVector): Boolean = {
position.isWithin(maxDelta, otherPosition)
}
}
| GiGurra/Wall-Ace | game_model/src/main/scala/se/gigurra/wallace/gamemodel/Entity.scala | Scala | gpl-2.0 | 567 |
/*
* Original implementation (C) 2014-2015 Kenji Yoshida and contributors
* Adapted and extended in 2016 by foundweekends project
*
* 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 giter8
import scala.xml.{NodeSeq, XML}
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.DefaultHttpClient
// http://hc.apache.org/httpcomponents-client-4.2.x/httpclient/apidocs/
trait MavenHelper {
def fromMaven(org: String,
name: String)(
process: (String, NodeSeq) => VersionE): VersionE = {
val loc = s"https://repo1.maven.org/maven2/${org.replace('.', '/')}/$name/maven-metadata.xml"
withHttp(loc) { response =>
val status = response.getStatusLine
status.getStatusCode match {
case 200 =>
val elem = XML.load(response.getEntity.getContent)
process(loc, elem)
case 404 =>
Left(s"Maven metadata not found for `maven($org, $name)`\\nTried: $loc")
case status =>
Left(s"Unexpected response status $status fetching metadata from $loc")
}
}
}
def withHttp[A](url: String)(f: HttpResponse => A): A =
{
val httpClient = new DefaultHttpClient
try {
val r = new HttpGet(url)
val response = httpClient.execute(r)
try {
f(response)
} finally {
}
} finally {
}
}
} | wolfendale/giter8 | library/src/main/scala/giter8/MavenHelper.scala | Scala | apache-2.0 | 1,938 |
package tastytest
object TestReader extends Suite("TestReader") {
implicit def mkReaderMonad[Ctx]: Reader[Ctx] = new Reader[Ctx]() {}
def pureToString[F[_], A](fa: F[A])(implicit F: Monad[F]): F[String] =
F.flatMap(fa)(a => F.pure(a.toString))
test {
val f = pureToString((s: Unit) => 101)
assert(f(()) === "101")
}
}
| scala/scala | test/tasty/run/src-2/tastytest/TestReader.scala | Scala | apache-2.0 | 342 |
/**
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package test.http.model
//import java.net.InetAddress
import akka.http.model.Uri._
import akka.scalajs.UTF8
import akka.http.model.{IllegalUriException, Uri}
import utest._
import scala.annotation.tailrec
object UriSpec extends TestSuite {
override def tests = TestSuite {
'UriHost {
'Ipv4Literals {
assert(Host("192.0.2.16") == IPv4Host("192.0.2.16"))
assert(Host("255.0.0.0") == IPv4Host("255.0.0.0"))
assert(Host("0.0.0.0") == IPv4Host("0.0.0.0"))
assert(Host("1.0.0.0") == IPv4Host("1.0.0.0"))
assert(Host("2.0.0.0") == IPv4Host("2.0.0.0"))
assert(Host("3.0.0.0") == IPv4Host("3.0.0.0"))
assert(Host("30.0.0.0") == IPv4Host("30.0.0.0"))
}
'InetAddressRountTrip {
println("Can't test round trip because scala-js does not have access to java.net.InetAddress")
// def roundTrip(ip: String): Unit = {
// val inetAddr = InetAddress.getByName(ip)
// val addr = Host(inetAddr)
// assert( addr == IPv4Host(ip))
// assert(addr.inetAddresses == Seq(inetAddr))
// }
// roundTrip("192.0.2.16")
// roundTrip("192.0.2.16")
// roundTrip("255.0.0.0")
// roundTrip("0.0.0.0")
// roundTrip("1.0.0.0")
// roundTrip("2.0.0.0")
// roundTrip("3.0.0.0")
// roundTrip("30.0.0.0")
// }
}
'IPV6Literals {
// "parse correctly from IPv6 literals (RFC2732)"
// various
assert(Host("[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]") == IPv6Host("FEDCBA9876543210FEDCBA9876543210", "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210"))
assert(Host("[1080:0:0:0:8:800:200C:417A]") == IPv6Host("108000000000000000080800200C417A", "1080:0:0:0:8:800:200C:417A"))
assert(Host("[3ffe:2a00:100:7031::1]") == IPv6Host("3ffe2a00010070310000000000000001", "3ffe:2a00:100:7031::1"))
assert(Host("[1080::8:800:200C:417A]") == IPv6Host("108000000000000000080800200C417A", "1080::8:800:200C:417A"))
assert(Host("[::192.9.5.5]") == IPv6Host("000000000000000000000000C0090505", "::192.9.5.5"))
assert(Host("[::FFFF:129.144.52.38]") == IPv6Host("00000000000000000000FFFF81903426", "::FFFF:129.144.52.38"))
assert(Host("[2010:836B:4179::836B:4179]") == IPv6Host("2010836B4179000000000000836B4179", "2010:836B:4179::836B:4179"))
// Quad length
assert(Host("[abcd::]") == IPv6Host("ABCD0000000000000000000000000000", "abcd::"))
assert(Host("[abcd::1]") == IPv6Host("ABCD0000000000000000000000000001", "abcd::1"))
assert(Host("[abcd::12]") == IPv6Host("ABCD0000000000000000000000000012", "abcd::12"))
assert(Host("[abcd::123]") == IPv6Host("ABCD0000000000000000000000000123", "abcd::123"))
assert(Host("[abcd::1234]") == IPv6Host("ABCD0000000000000000000000001234", "abcd::1234"))
// Full length
assert(Host("[2001:0db8:0100:f101:0210:a4ff:fee3:9566]") == IPv6Host("20010db80100f1010210a4fffee39566", "2001:0db8:0100:f101:0210:a4ff:fee3:9566")) // lower hex
assert(Host("[2001:0DB8:0100:F101:0210:A4FF:FEE3:9566]") == IPv6Host("20010db80100f1010210a4fffee39566", "2001:0DB8:0100:F101:0210:A4FF:FEE3:9566")) // Upper hex
assert(Host("[2001:db8:100:f101:210:a4ff:fee3:9566]") == IPv6Host("20010db80100f1010210a4fffee39566", "2001:db8:100:f101:210:a4ff:fee3:9566"))
assert(Host("[2001:0db8:100:f101:0:0:0:1]") == IPv6Host("20010db80100f1010000000000000001", "2001:0db8:100:f101:0:0:0:1"))
assert(Host("[1:2:3:4:5:6:255.255.255.255]") == IPv6Host("000100020003000400050006FFFFFFFF", "1:2:3:4:5:6:255.255.255.255"))
// Legal IPv4
assert(Host("[::1.2.3.4]") == IPv6Host("00000000000000000000000001020304", "::1.2.3.4"))
assert(Host("[3:4::5:1.2.3.4]") == IPv6Host("00030004000000000000000501020304", "3:4::5:1.2.3.4"))
assert(Host("[::ffff:1.2.3.4]") == IPv6Host("00000000000000000000ffff01020304", "::ffff:1.2.3.4"))
assert(Host("[::0.0.0.0]") == IPv6Host("00000000000000000000000000000000", "::0.0.0.0")) // Min IPv4
assert(Host("[::255.255.255.255]") == IPv6Host("000000000000000000000000FFFFFFFF", "::255.255.255.255")) // Max IPv4
// Zipper position
assert(Host("[::1:2:3:4:5:6:7]") == IPv6Host("00000001000200030004000500060007", "::1:2:3:4:5:6:7"))
assert(Host("[1::1:2:3:4:5:6]") == IPv6Host("00010000000100020003000400050006", "1::1:2:3:4:5:6"))
assert(Host("[1:2::1:2:3:4:5]") == IPv6Host("00010002000000010002000300040005", "1:2::1:2:3:4:5"))
assert(Host("[1:2:3::1:2:3:4]") == IPv6Host("00010002000300000001000200030004", "1:2:3::1:2:3:4"))
assert(Host("[1:2:3:4::1:2:3]") == IPv6Host("00010002000300040000000100020003", "1:2:3:4::1:2:3"))
assert(Host("[1:2:3:4:5::1:2]") == IPv6Host("00010002000300040005000000010002", "1:2:3:4:5::1:2"))
assert(Host("[1:2:3:4:5:6::1]") == IPv6Host("00010002000300040005000600000001", "1:2:3:4:5:6::1"))
assert(Host("[1:2:3:4:5:6:7::]") == IPv6Host("00010002000300040005000600070000", "1:2:3:4:5:6:7::"))
// Zipper length
assert(Host("[1:1:1::1:1:1:1]") == IPv6Host("00010001000100000001000100010001", "1:1:1::1:1:1:1"))
assert(Host("[1:1:1::1:1:1]") == IPv6Host("00010001000100000000000100010001", "1:1:1::1:1:1"))
assert(Host("[1:1:1::1:1]") == IPv6Host("00010001000100000000000000010001", "1:1:1::1:1"))
assert(Host("[1:1::1:1]") == IPv6Host("00010001000000000000000000010001", "1:1::1:1"))
assert(Host("[1:1::1]") == IPv6Host("00010001000000000000000000000001", "1:1::1"))
assert(Host("[1::1]") == IPv6Host("00010000000000000000000000000001", "1::1"))
assert(Host("[::1]") == IPv6Host("00000000000000000000000000000001", "::1")) // == localassert(host
assert(Host("[::]") == IPv6Host("00000000000000000000000000000000", "::")) // == all addresses
// A few more variations
assert(Host("[21ff:abcd::1]") == IPv6Host("21ffabcd000000000000000000000001", "21ff:abcd::1"))
assert(Host("[2001:db8:100:f101::1]") == IPv6Host("20010db80100f1010000000000000001", "2001:db8:100:f101::1"))
assert(Host("[a:b:c::12:1]") == IPv6Host("000a000b000c00000000000000120001", "a:b:c::12:1"))
assert(Host("[a:b::0:1:2:3]") == IPv6Host("000a000b000000000000000100020003", "a:b::0:1:2:3"))
}
'Inet6AddressRoundTrip {
println("Can't test round trip because scala-js does not have access to java.net.InetAddress")
// scalaJs does not have access to Inet6Addressses
// "support inetAddresses round-trip for Inet6Addresses" in {
// def fromAddress(address: String): IPv6Host = Host(s"[$address]").asInstanceOf[IPv6Host]
// def roundTrip(ip: String): Unit = {
// val inetAddr = InetAddress.getByName(ip)
// val addr = Host(inetAddr)
// addr equalsIgnoreCase fromAddress(ip) should be(true)
// addr.inetAddresses shouldEqual Seq(inetAddr)
// }
//
// roundTrip("1:1:1::1:1:1:1")
// roundTrip("::1:2:3:4:5:6:7")
// roundTrip("2001:0DB8:0100:F101:0210:A4FF:FEE3:9566")
// roundTrip("2001:0db8:100:f101:0:0:0:1")
// roundTrip("abcd::12")
// roundTrip("::192.9.5.5")
// }
}
'NamedHostLiterals {
assert(Host("www.spray.io") == NamedHost("www.spray.io"))
assert(Host("localhost") == NamedHost("localhost"))
assert(Host("%2FH%C3%A4ll%C3%B6%5C") == NamedHost( """/hällö\\"""))
}
'IllegalIPv4Literals {
// "not accept illegal IPv4 literals"
assert(Host("01.0.0.0").isInstanceOf[NamedHost])
assert(Host("001.0.0.0").isInstanceOf[NamedHost])
assert(Host("00.0.0.0").isInstanceOf[NamedHost])
assert(Host("000.0.0.0").isInstanceOf[NamedHost])
assert(Host("256.0.0.0").isInstanceOf[NamedHost])
assert(Host("300.0.0.0").isInstanceOf[NamedHost])
assert(Host("1111.0.0.0").isInstanceOf[NamedHost])
assert(Host("-1.0.0.0").isInstanceOf[NamedHost])
assert(Host("0.0.0").isInstanceOf[NamedHost])
assert(Host("0.0.0.").isInstanceOf[NamedHost])
assert(Host("0.0.0.0.").isInstanceOf[NamedHost])
assert(Host("0.0.0.0.0").isInstanceOf[NamedHost])
assert(Host("0.0..0").isInstanceOf[NamedHost])
assert(Host(".0.0.0").isInstanceOf[NamedHost])
}
'IllegalIPv6Literals {
// "not accept illegal IPv6 literals"
// // 5 char quad
val err = intercept[IllegalUriException] {
Host("[::12345]")
}
assert(err == new IllegalUriException("Illegal URI host: Invalid input '5', expected !HEXDIG, ':' or ']' (line 1, column 8)",
"[::12345]\\n" +
" ^"))
// Two zippers
intercept[IllegalUriException] {
Host("[abcd::abcd::abcd]")
}
// Triple-colon zipper
intercept[IllegalUriException] {
Host("[:::1234]")
}
intercept[IllegalUriException] {
Host("[1234:::1234:1234]")
}
intercept[IllegalUriException] {
Host("[1234:1234:::1234]")
}
intercept[IllegalUriException] {
Host("[1234:::]")
}
// No quads, just IPv4
intercept[IllegalUriException] {
Host("[1.2.3.4]")
}
intercept[IllegalUriException] {
Host("[0001.0002.0003.0004]")
}
// Five quads
intercept[IllegalUriException] {
Host("[0000:0000:0000:0000:0000:1.2.3.4]")
}
// Seven quads
intercept[IllegalUriException] {
Host("[0:0:0:0:0:0:0]")
}
intercept[IllegalUriException] {
Host("[0:0:0:0:0:0:0:]")
}
intercept[IllegalUriException] {
Host("[0:0:0:0:0:0:0:1.2.3.4]")
}
// Nine quads
intercept[IllegalUriException] {
Host("[0:0:0:0:0:0:0:0:0]")
}
// Invalid IPv4 part
intercept[IllegalUriException] {
Host("[::ffff:001.02.03.004]")
} // Leading zeros
intercept[IllegalUriException] {
Host("[::ffff:1.2.3.1111]")
} // Four char octet
intercept[IllegalUriException] {
Host("[::ffff:1.2.3.256]")
} // > 255
intercept[IllegalUriException] {
Host("[::ffff:311.2.3.4]")
} // > 155
intercept[IllegalUriException] {
Host("[::ffff:1.2.3:4]")
} // Not a dot
intercept[IllegalUriException] {
Host("[::ffff:1.2.3]")
} // Missing octet
intercept[IllegalUriException] {
Host("[::ffff:1.2.3.]")
} // Missing octet
intercept[IllegalUriException] {
Host("[::ffff:1.2.3a.4]")
} // Hex in octet
intercept[IllegalUriException] {
Host("[::ffff:1.2.3.4:123]")
} // Crap input
// Nonhex
intercept[IllegalUriException] {
Host("[g:0:0:0:0:0:0]")
}
}
}
'UriPath {
import akka.http.model.Uri.Path.Empty
'ParsedCorrectly {
assert(Path("") == Empty)
assert(Path("/") == Path./)
assert(Path("a") == "a" :: Empty)
assert(Path("//") == Path./ / "")
assert(Path("a/") == "a" :: Path./)
assert(Path("/a") == Path / "a")
assert(Path("/abc/de/f") == Path / "abc" / "de" / "f")
assert(Path("abc/de/f/") == "abc" :: '/' :: "de" :: '/' :: "f" :: Path./)
assert(Path("abc///de") == "abc" :: '/' :: '/' :: '/' :: "de" :: Empty)
assert(Path("/abc%2F") == Path / "abc/")
assert(Path("H%C3%A4ll%C3%B6") == """Hällö""" :: Empty)
assert(Path("/%2F%5C") == Path / """/\\""")
assert(Path("/:foo:/") == Path / ":foo:" / "")
assert(Path("%2520").head == "%20")
}
'startsWith {
// "support the `startsWith` predicate"
assert({
Empty startsWith Empty
} == true)
assert({
Path./ startsWith Empty
} == true)
assert({
Path("abc") startsWith Empty
} == true)
assert({
Empty startsWith Path./
} == false)
assert({
Empty startsWith Path("abc")
} == false)
assert({
Path./ startsWith Path./
} == true)
assert({
Path./ startsWith Path("abc")
} == false)
assert({
Path("/abc") startsWith Path./
} == true)
assert({
Path("abc") startsWith Path./
} == false)
assert({
Path("abc") startsWith Path("ab")
} == true)
assert({
Path("abc") startsWith Path("abc")
} == true)
assert({
Path("/abc") startsWith Path("/a")
} == true)
assert({
Path("/abc") startsWith Path("/abc")
} == true)
assert({
Path("/ab") startsWith Path("/abc")
} == false)
assert({
Path("/abc") startsWith Path("/abd")
} == false)
assert({
Path("/abc/def") startsWith Path("/ab")
} == true)
assert({
Path("/abc/def") startsWith Path("/abc/")
} == true)
assert({
Path("/abc/def") startsWith Path("/abc/d")
} == true)
assert({
Path("/abc/def") startsWith Path("/abc/def")
} == true)
assert({
Path("/abc/def") startsWith Path("/abc/def/")
} == false)
}
'dropChars {
// "support the `dropChars` modifier"
assert(Path./.dropChars(0) == Path./)
assert(Path./.dropChars(1) == Empty)
assert(Path("/abc/def/").dropChars(0) == Path("/abc/def/"))
assert(Path("/abc/def/").dropChars(1) == Path("abc/def/"))
assert(Path("/abc/def/").dropChars(2) == Path("bc/def/"))
assert(Path("/abc/def/").dropChars(3) == Path("c/def/"))
assert(Path("/abc/def/").dropChars(4) == Path("/def/"))
assert(Path("/abc/def/").dropChars(5) == Path("def/"))
assert(Path("/abc/def/").dropChars(6) == Path("ef/"))
assert(Path("/abc/def/").dropChars(7) == Path("f/"))
assert(Path("/abc/def/").dropChars(8) == Path("/"))
assert(Path("/abc/def/").dropChars(9) == Empty)
}
}
'UriQueryInstances {
def parser(mode: Uri.ParsingMode): String ⇒ Query = Query(_, mode = mode)
'strictMode {
val test = parser(Uri.ParsingMode.Strict)
assert(test("") == {("", "") +: Query.Empty})
assert(test("a") == {("a", "") +: Query.Empty})
assert(test("a=") == {("a", "") +: Query.Empty})
assert(test("=a") == {("", "a") +: Query.Empty})
assert(test("a&") == {("a", "") +: ("", "") +: Query.Empty})
intercept[IllegalUriException]{ test("a^=b")}
}
'relaxedMode {
val test = parser(Uri.ParsingMode.Relaxed)
assert(test("") == {("", "") +: Query.Empty})
assert(test("a") == {("a", "") +: Query.Empty})
assert(test("a=") == {("a", "") +: Query.Empty})
assert(test("=a") == {("", "a") +: Query.Empty})
assert(test("a&") == {("a", "") +: ("", "") +: Query.Empty})
assert(test("a^=b") == {("a^", "b") +: Query.Empty})
}
'relaxedWithRawQuery {
val test = parser(Uri.ParsingMode.RelaxedWithRawQuery)
assert(test("a^=b&c").toString == "a^=b&c")
assert(test("a%2Fb") == Uri.Query.Raw("a%2Fb"))
}
'retrievalInterface { //"properly support the retrieval interface"
val query = Query("a=1&b=2&c=3&b=4&b")
assert(query.get("a") == Some("1"))
assert(query.get("d") == None)
assert(query.getOrElse("a", "x") == "1")
assert(query.getOrElse("d", "x") == "x")
assert(query.getAll("b") == List("", "4", "2"))
assert(query.getAll("d") == Nil)
assert(query.toMap == Map("a" -> "1", "b" -> "", "c" -> "3"))
assert(query.toMultiMap == Map("a" -> List("1"), "b" -> List("", "4", "2"), "c" -> List("3")))
assert(query.toList == List("a" -> "1", "b" -> "2", "c" -> "3", "b" -> "4", "b" -> ""))
assert(query.toSeq == Seq("a" -> "1", "b" -> "2", "c" -> "3", "b" -> "4", "b" -> ""))
}
'List2NamValPairConversion { // "support conversion from list of name/value pairs"
import akka.http.model.Uri.Query._
val pairs = List("key1" -> "value1", "key2" -> "value2", "key3" -> "value3")
assert(Query(pairs: _*).toList.diff(pairs) == Nil)
assert(Query() == Empty)
assert(Query("k" -> "v") == ("k" -> "v") +: Empty)
}
}
'URI {
// http://tools.ietf.org/html/rfc3986#section-1.1.2
'parseAndRender { //"be correctly parsed from and rendered to simple test examples"
assert(Uri("ftp://ftp.is.co.za/rfc/rfc1808.txt") == Uri.from(scheme = "ftp", host = "ftp.is.co.za", path = "/rfc/rfc1808.txt"))
assert(Uri("http://www.ietf.org/rfc/rfc2396.txt") == Uri.from(scheme = "http", host = "www.ietf.org", path = "/rfc/rfc2396.txt"))
assert(Uri("ldap://[2001:db8::7]/c=GB?objectClass?one") == Uri.from(scheme = "ldap", host = "[2001:db8::7]", path = "/c=GB", query = Query("objectClass?one")))
assert(Uri("mailto:[email protected]") == Uri.from(scheme = "mailto", path = "[email protected]"))
assert(Uri("news:comp.infosystems.www.servers.unix") == Uri.from(scheme = "news", path = "comp.infosystems.www.servers.unix"))
assert(Uri("tel:+1-816-555-1212") == Uri.from(scheme = "tel", path = "+1-816-555-1212"))
assert(Uri("telnet://192.0.2.16:80/") == Uri.from(scheme = "telnet", host = "192.0.2.16", port = 80, path = "/"))
assert(Uri("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") == Uri.from(scheme = "urn", path = "oasis:names:specification:docbook:dtd:xml:4.1.2"))
// more examples
assert(Uri("http://") == Uri(scheme = "http", authority = Authority(host = NamedHost(""))))
assert(Uri("http:?") == Uri.from(scheme = "http", query = Query("")))
assert(Uri("?a+b=c%2Bd") == Uri.from(query = ("a b", "c+d") +: Query.Empty))
// illegal paths
assert(Uri("foo/another@url/[]and{}") == Uri.from(path = "foo/another@url/%5B%5Dand%7B%7D"))
intercept[IllegalUriException] {
Uri("foo/another@url/[]and{}", mode = Uri.ParsingMode.Strict)
}
// handle query parameters with more than percent-encoded character
assert(Uri("?%7Ba%7D=$%7B%7D", UTF8, Uri.ParsingMode.Strict) == Uri(query = Query.Cons("{a}", "${}", Query.Empty)))
// don't double decode
assert(Uri("%2520").path.head == "%20")
assert(Uri("/%2F%5C").path == Path / """/\\""")
// render
assert(Uri("https://server.com/path/to/here?st=12345").toString == "https://server.com/path/to/here?st=12345")
assert(Uri("/foo/?a#b").toString == "/foo/?a#b")
}
'normalization {
// http://tools.ietf.org/html/rfc3986#section-6.2.2
assert(normalize("eXAMPLE://a/./b/../b/%63/%7bfoo%7d") == "example://a/b/c/%7Bfoo%7D")
// more examples
assert(normalize("") == "")
assert(normalize("/") == "/")
assert(normalize("../../") == "../../")
assert(normalize("aBc") == "aBc")
assert(normalize("Http://Localhost") == "http://localhost")
assert(normalize("hTtP://localHost") == "http://localhost")
assert(normalize("https://:443") == "https://")
assert(normalize("ftp://example.com:21") == "ftp://example.com")
assert(normalize("example.com:21") == "example.com:21")
assert(normalize("ftp://example.com:22") == "ftp://example.com:22")
assert(normalize("//user:pass@[::1]:80/segment/index.html?query#frag") == "//user:pass@[::1]:80/segment/index.html?query#frag")
assert(normalize("http://[::1]:80/segment/index.html?query#frag") == "http://[::1]/segment/index.html?query#frag")
assert(normalize("http://user:pass@[::1]/segment/index.html?query#frag") == "http://user:pass@[::1]/segment/index.html?query#frag")
assert(normalize("http://user:pass@[::1]:80?query#frag") == "http://user:pass@[::1]?query#frag")
assert(normalize("http://user:pass@[::1]/segment/index.html#frag") == "http://user:pass@[::1]/segment/index.html#frag")
assert(normalize("http://user:pass@[::1]:81/segment/index.html?query") == "http://user:pass@[::1]:81/segment/index.html?query")
assert(normalize("ftp://host:21/gnu/") == "ftp://host/gnu/")
assert(normalize("one/two/three") == "one/two/three")
assert(normalize("/one/two/three") == "/one/two/three")
assert(normalize("//user:pass@localhost/one/two/three") == "//user:pass@localhost/one/two/three")
assert(normalize("http://www.example.com/") == "http://www.example.com/")
assert(normalize("http://sourceforge.net/projects/uriparser/") == "http://sourceforge.net/projects/uriparser/")
assert(normalize("http://sourceforge.net/project/platformdownload.php?group_id=182840") == "http://sourceforge.net/project/platformdownload.php?group_id=182840")
assert(normalize("mailto:[email protected]") == "mailto:[email protected]")
assert(normalize("file:///bin/bash") == "file:///bin/bash")
assert(normalize("http://www.example.com/name%20with%20spaces/") == "http://www.example.com/name%20with%20spaces/")
assert(normalize("http://examp%4Ce.com/") == "http://example.com/")
assert(normalize("http://example.com/a/b/%2E%2E/") == "http://example.com/a/")
assert(normalize("http://user:[email protected]:123") == "http://user:[email protected]:123")
assert(normalize("HTTP://a:b@HOST:123/./1/2/../%41?abc#def") == "http://a:b@host:123/1/A?abc#def")
// acceptance and normalization of unescaped ascii characters such as {} and []:
assert(normalize("eXAMPLE://a/./b/../b/%63/{foo}/[bar]") == "example://a/b/c/%7Bfoo%7D/%5Bbar%5D")
intercept[IllegalUriException]{ normalize("eXAMPLE://a/./b/../b/%63/{foo}/[bar]", mode = Uri.ParsingMode.Strict)}
// queries
assert(normalize("?") == "?")
assert(normalize("?key") == "?key")
//todo: these two do not work - could it be a bug with plantain2 js
//assert(normalize("?key=") == "?key=")
//assert(normalize("?key=&a=b") == "?key=&a=b")
assert(normalize("?key={}&a=[]") == "?key=%7B%7D&a=%5B%5D")
intercept[IllegalUriException] { normalize("?key={}&a=[]", mode = Uri.ParsingMode.Strict) }
assert(normalize("?=value") == "?=value")
assert(normalize("?key=value") == "?key=value")
assert(normalize("?a+b") == "?a+b")
assert(normalize("?=a+b") == "?=a+b")
assert(normalize("?a+b=c+d") == "?a+b=c+d")
assert(normalize("??") == "??")
assert(normalize("?a=1&b=2") == "?a=1&b=2")
assert(normalize("?a+b=c%2Bd") == "?a+b=c%2Bd")
assert(normalize("?a&a") == "?a&a")
assert(normalize("?&#") == "?&#")
assert(normalize("?#") == "?#")
assert(normalize("#") == "#")
assert(normalize("#{}[]") == "#%7B%7D%5B%5D")
intercept[IllegalUriException] { normalize("#{}[]", mode = Uri.ParsingMode.Strict)}
}
'tunneling {
// "support tunneling a URI through a query param"
val uri = Uri("http://aHost/aPath?aParam=aValue#aFragment")
val q = Query("uri" -> uri.toString)
val uri2 = Uri(path = Path./, query = q, fragment = Some("aFragment")).toString
assert(uri2 == "/?uri=http://ahost/aPath?aParam%3DaValue%23aFragment#aFragment")
assert(Uri(uri2).query == q)
assert(Uri(q.getOrElse("uri", "<nope>")) == uri)
}
'illegalUriErrorMsg {
//"produce proper error messages for illegal URIs"
// illegal scheme
assert(intercept[IllegalUriException] {
Uri("foö:/a")
} ==
new IllegalUriException("Illegal URI reference: Invalid input 'ö', expected scheme-char, ':', path-segment-char, '%', '/', '?', '#' or 'EOI' (line 1, column 3)",
"foö:/a\\n" +
" ^")
)
// illegal userinfo
assert(intercept[IllegalUriException] {
Uri("http://user:ö@host")
} ==
new IllegalUriException("Illegal URI reference: Invalid input 'ö', expected userinfo-char, '%', '@' or DIGIT (line 1, column 13)",
"http://user:ö@host\\n" +
" ^")
)
// illegal percent-encoding
assert(intercept[IllegalUriException] {
Uri("http://use%2G@host")
} ==
new IllegalUriException("Illegal URI reference: Invalid input 'G', expected HEXDIG (line 1, column 13)",
"http://use%2G@host\\n" +
" ^")
)
// illegal path
assert(intercept[IllegalUriException] {
Uri("http://www.example.com/name with spaces/")
} ==
new IllegalUriException("Illegal URI reference: Invalid input ' ', expected path-segment-char, '%', '/', '?', '#' or 'EOI' (line 1, column 28)",
"http://www.example.com/name with spaces/\\n" +
" ^")
)
// illegal path with control character
assert(intercept[IllegalUriException] {
Uri("http:///with\\newline")
} ==
new IllegalUriException("Illegal URI reference: Invalid input '\\\\n', expected path-segment-char, '%', '/', '?', '#' or 'EOI' (line 1, column 13)",
"http:///with\\n" +
" ^")
)
// illegal query
assert(intercept[IllegalUriException] {
Uri("?a=b=c")
} ==
new IllegalUriException("Illegal URI reference: Invalid input '=', expected '+', query-char, '%', '&', '#' or 'EOI' (line 1, column 5)",
"?a=b=c\\n" +
" ^")
)
}
// http://tools.ietf.org/html/rfc3986#section-5.4
'rfc3986referenceResolution {
//"pass the RFC 3986 reference resolution examples"
val base = parseAbsolute("http://a/b/c/d;p?q")
def resolve(uri: String): String = {
parseAndResolve(uri, base).toString
}
'normalExamples {
//todo: can't seem to compile the code below
//check issue https://github.com/lihaoyi/utest/issues/24
// assert( resolve("g:h") == "g:h")
// assert( resolve("g") == "http://a/b/c/g")
// assert( resolve("./g") == "http://a/b/c/g")
// assert( resolve("g/") == "http://a/b/c/g/")
// assert( resolve("/g") == "http://a/g")
// assert( resolve("//g") == "http://g")
// assert( resolve("?y") == "http://a/b/c/d;p?y")
// assert( resolve("g?y") == "http://a/b/c/g?y")
// assert( resolve("#s") == "http://a/b/c/d;p?q#s")
// assert( resolve("g#s") == "http://a/b/c/g#s")
// assert( resolve("g?y#s") == "http://a/b/c/g?y#s")
// assert( resolve(";x") == "http://a/b/c/;x")
// assert( resolve("g;x") == "http://a/b/c/g;x")
// assert( resolve("g;x?y#s") == "http://a/b/c/g;x?y#s")
// assert( resolve("") == "http://a/b/c/d;p?q")
// assert( resolve(".") == "http://a/b/c/")
// assert( resolve("./") == "http://a/b/c/")
// assert( resolve("..") == "http://a/b/")
// assert( resolve("../") == "http://a/b/")
// assert( resolve("../g") == "http://a/b/g")
// assert( resolve("../..") == "http://a/")
// assert( resolve("../../") == "http://a/")
// assert( resolve("../../g") == "http://a/g")
}
'abnormalExamples {
//todo: Can't compile the code below
//check issue https://github.com/lihaoyi/utest/issues/24
// assert(resolve("../../../g") == "http://a/g")
// assert(resolve("../../../../g") == "http://a/g")
//
// assert(resolve("/./g") == "http://a/g")
// assert(resolve("/../g") == "http://a/g")
// assert(resolve("g.") == "http://a/b/c/g.")
// assert(resolve(".g") == "http://a/b/c/.g")
// assert(resolve("g..") == "http://a/b/c/g..")
// assert(resolve("..g") == "http://a/b/c/..g")
//
// assert(resolve("./../g") == "http://a/b/g")
// assert(resolve("./g/.") == "http://a/b/c/g/")
// assert(resolve("g/./h") == "http://a/b/c/g/h")
// assert(resolve("g/../h") == "http://a/b/c/h")
// assert(resolve("g;x=1/./y") == "http://a/b/c/g;x=1/y")
// assert(resolve("g;x=1/../y") == "http://a/b/c/y")
//
// assert(resolve("g?y/./x") == "http://a/b/c/g?y/./x")
// assert(resolve("g?y/../x") == "http://a/b/c/g?y/../x")
// assert(resolve("g#s/./x") == "http://a/b/c/g#s/./x")
// assert(resolve("g#s/../x") == "http://a/b/c/g#s/../x")
//
// assert(resolve("http:g") == "http:g")
}
}
'Copyable {
val uri = Uri("http://host:80/path?query#fragment")
assert (uri.copy() == uri )
}
'FluentTransformationSugar {
// "provide sugar for fluent transformations"
val uri = Uri("http://host:80/path?query#fragment")
val nonDefaultUri = Uri("http://host:6060/path?query#fragment")
assert(uri.withScheme("https") == Uri("https://host/path?query#fragment"))
assert(nonDefaultUri.withScheme("https") == Uri("https://host:6060/path?query#fragment"))
assert(uri.withAuthority(Authority(Host("other"), 3030)) == Uri("http://other:3030/path?query#fragment"))
assert(uri.withAuthority(Host("other"), 3030) == Uri("http://other:3030/path?query#fragment"))
assert(uri.withAuthority("other", 3030) == Uri("http://other:3030/path?query#fragment"))
assert(uri.withHost(Host("other")) == Uri("http://other:80/path?query#fragment"))
assert(uri.withHost("other") == Uri("http://other:80/path?query#fragment"))
assert(uri.withPort(90) == Uri("http://host:90/path?query#fragment"))
assert(uri.withPath(Path("/newpath")) == Uri("http://host/newpath?query#fragment"))
assert(uri.withUserInfo("someInfo") == Uri("http://someInfo@host:80/path?query#fragment"))
assert(uri.withQuery(Query("param1" -> "value1")) == Uri("http://host:80/path?param1=value1#fragment"))
assert(uri.withQuery("param1=value1") == Uri("http://host:80/path?param1=value1#fragment"))
assert(uri.withQuery(("param1", "value1")) == Uri("http://host:80/path?param1=value1#fragment"))
assert(uri.withQuery(Map("param1" -> "value1")) == Uri("http://host:80/path?param1=value1#fragment"))
assert(uri.withFragment("otherFragment") == Uri("http://host:80/path?query#otherFragment"))
}
'effectivePort {
//"return the correct effective port"
assert(80 == Uri("http://host/").effectivePort)
assert(21 == Uri("ftp://host/").effectivePort)
assert(9090 == Uri("http://host:9090/").effectivePort)
assert(443 == Uri("https://host/").effectivePort)
assert(4450 == Uri("https://host/").withPort(4450).effectivePort)
assert(4450 == Uri("https://host:3030/").withPort(4450).effectivePort)
}
}
}
}
| bblfish/akka.http.model.Uri | akka.UriJS/src/test/scala/test/http/model/UriSpec.scala | Scala | apache-2.0 | 31,292 |
/*
* 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
import monix.execution.atomic.PaddingStrategy.NoPadding
import monix.execution.internal.Platform
import monix.execution.atomic.{AtomicAny, PaddingStrategy}
import scala.annotation.tailrec
import scala.collection.immutable.LongMap
import scala.collection.mutable.ListBuffer
import scala.concurrent.Promise
import scala.util.{Failure, Success, Try}
import scala.util.control.NonFatal
/**
* `CancelablePromise` is a [[scala.concurrent.Promise]] implementation that
* allows listeners to unsubscribe from receiving future results.
*
* It does so by:
*
* - adding a low-level [[subscribe]] method, that allows for callbacks
* to be subscribed
* - returning [[CancelableFuture]] in its [[future]] method implementation,
* allowing created future objects to unsubscribe (being the high-level
* [[subscribe]] that should be preferred for most usage)
*
* Being able to unsubscribe listeners helps with avoiding memory leaks
* in case of listeners or futures that are being timed-out due to
* promises that take a long time to complete.
*
* @see [[subscribe]]
* @see [[future]]
*/
sealed abstract class CancelablePromise[A] extends Promise[A] {
/**
* Returns a future that can unsubscribe from this promise's
* notifications via cancelation.
*
* {{{
* val promise = CancelablePromise[Int]()
*
* val future1 = promise.future
* val future2 = promise.future
*
* for (r <- future1) println(s"Future1 completed with: $$r")
* for (r <- future2) println(s"Future2 completed with: $$r")
*
* // Unsubscribing from the future notification, but only for future1
* future1.cancel()
*
* // Completing our promise
* promise.success(99)
*
* //=> Future2 completed with: 99
* }}}
*
* Note that in the above example `future1` becomes non-terminating
* after cancellation. By unsubscribing its listener, it will never
* complete.
*
* This helps with avoiding memory leaks for futures that are being
* timed-out due to promises that take a long time to complete.
*/
def future: CancelableFuture[A]
/** Low-level subscription method that registers a callback to be called
* when this promise will complete.
*
* {{{
* val promise = CancelablePromise[Int]()
*
* def subscribe(n: Int): Cancelable =
* promise.subscribe {
* case Success(str) =>
* println(s"Callback ($$n) completed with: $$str")
* case Failure(e) =>
* println(s"Callback ($$n) completed with: $$e")
* }
*
* val token1 = subscribe(1)
* val token2 = subscribe(2)
*
* // Unsubscribing from the future notification
* token1.cancel()
*
* // Completing our promise
* promise.success(99)
*
* //=> Callback (2) completed with: 99
* }}}
*
* '''UNSAFE PROTOCOL:''' the implementation does not protect
* against stack-overflow exceptions. There's no point in doing it
* for such low level methods, because this is useful as middleware
* and different implementations will have different ways to deal
* with stack safety (e.g. `monix.eval.Task`).
*
* @param cb is a callback that will be called when the promise
* completes with a result, assuming that the returned
* cancelable token isn't canceled
*
* @return a cancelable token that can be used to unsubscribe the
* given callback, in order to prevent memory leaks, at
* which point the callback will never be called (if it
* wasn't called already)
*/
def subscribe(cb: Try[A] => Unit): Cancelable
}
object CancelablePromise {
/**
* Builds an empty [[CancelablePromise]] object.
*
* @tparam A the type of the value in the promise
*
* @param ps is a configurable
* [[monix.execution.atomic.PaddingStrategy PaddingStrategy]]
* to avoid the false sharing problem
*
* @return the newly created promise object
*/
def apply[A](ps: PaddingStrategy = NoPadding): CancelablePromise[A] =
new Async[A](ps)
/** Creates an already completed [[CancelablePromise]] with the specified
* result or exception.
*
* @param value is the [[scala.util.Try]] result to signal to subscribers
* @return the newly created promise object
*/
def fromTry[A](value: Try[A]): CancelablePromise[A] =
new Completed[A](value)
/** Creates a [[CancelablePromise]] that's already completed with the
* given successful result.
*
* @param value is the successful result to signal to subscribers
* @return the newly created promise object
*/
def successful[A](value: A): CancelablePromise[A] =
fromTry(Success(value))
/** Creates a [[CancelablePromise]] that's already completed in error.
*
* @param e is the error to signal to subscribers
* @return the newly created promise object
*/
def failed[A](e: Throwable): CancelablePromise[A] =
fromTry(Failure(e))
/**
* Implements already completed `CancelablePromise` references.
*/
private final class Completed[A](value: Try[A]) extends CancelablePromise[A] {
def future: CancelableFuture[A] =
CancelableFuture.fromTry(value)
def subscribe(cb: Try[A] => Unit): Cancelable = {
cb(value)
Cancelable.empty
}
def isCompleted: Boolean = true
def tryComplete(result: Try[A]): Boolean = false
}
/**
* Actual implementation for `CancelablePromise`.
*/
private final class Async[A](ps: PaddingStrategy) extends CancelablePromise[A] { self =>
// States:
// - Try[A]: completed with a result
// - MapQueue: listeners queue
private[this] val state = AtomicAny.withPadding[AnyRef](emptyMapQueue, ps)
override def subscribe(cb: Try[A] => Unit): Cancelable =
unsafeSubscribe(cb)
override def isCompleted: Boolean =
state.get().isInstanceOf[Try[_]]
override def future: CancelableFuture[A] =
state.get() match {
case ref: Try[A] @unchecked =>
CancelableFuture.fromTry(ref)
case queue: MapQueue[AnyRef] @unchecked =>
// Optimization over straight usage of `unsafeSubscribe`,
// to avoid an extra `ref.get`
val p = Promise[A]()
val (id, update) = queue.enqueue(p)
val cancelable =
if (!state.compareAndSet(queue, update)) unsafeSubscribe(p)
else new IdCancelable(id)
CancelableFuture(p.future, cancelable)
}
@tailrec
override def tryComplete(result: Try[A]): Boolean = {
state.get() match {
case queue: MapQueue[AnyRef] @unchecked =>
if (!state.compareAndSet(queue, result)) {
// Failed, retry...
tryComplete(result)
} else if (queue eq emptyMapQueue) true
else {
var errors: ListBuffer[Throwable] = null
val cursor = queue.iterator
while (cursor.hasNext) {
val cb = cursor.next()
try {
call(cb, result)
} catch {
// Aggregating errors, because we want to throw them all
// as a composite and to prevent listeners from spoiling
// the fun for other listeners by throwing errors
case e if NonFatal(e) =>
if (errors eq null) errors = ListBuffer.empty
errors += e
}
}
if (errors ne null) {
// Throws all errors as a composite
val x :: xs = errors.toList
throw Platform.composeErrors(x, xs: _*)
}
true
}
case _ =>
false
}
}
private def call(cb: AnyRef, result: Try[A]): Unit =
cb match {
case f: (Try[A] => Unit) @unchecked =>
f(result)
case p: Promise[A] =>
p.complete(result)
()
}
@tailrec def unsafeSubscribe(cb: AnyRef): Cancelable =
state.get() match {
case ref: Try[A] @unchecked =>
call(cb, ref)
Cancelable.empty
case queue: MapQueue[Any] @unchecked =>
val (id, update) = queue.enqueue(cb)
if (!state.compareAndSet(queue, update)) unsafeSubscribe(cb)
else new IdCancelable(id)
}
private final class IdCancelable(id: Long) extends Cancelable {
@tailrec def cancel(): Unit =
state.get() match {
case queue: MapQueue[_] =>
if (!state.compareAndSet(queue, queue.dequeue(id)))
cancel()
case _ =>
()
}
}
}
private final case class MapQueue[+A](map: LongMap[A], nextId: Long) extends Iterable[A] {
def enqueue[AA >: A](elem: AA): (Long, MapQueue[AA]) =
(nextId, MapQueue(map.updated(nextId, elem), nextId + 1))
def dequeue(id: Long): MapQueue[A] =
MapQueue(map - id, nextId)
def iterator: Iterator[A] =
map.valuesIterator
}
private[this] val emptyMapQueue: MapQueue[Nothing] =
MapQueue(LongMap.empty, 0)
}
| alexandru/monifu | monix-execution/shared/src/main/scala/monix/execution/CancelablePromise.scala | Scala | apache-2.0 | 9,884 |
package io.peregrine
import io.peregrine.ContentType._
import io.peregrine.test.FlatSpecHelper
class ExampleSpec extends FlatSpecHelper {
/* ###BEGIN_APP### */
class ExampleApp extends Controller {
/**
* Basic Example
*
* curl http://localhost:7070/ => "hello world"
*/
get("/") { request =>
render.static("index.html").toFuture
}
delete("/photos") { request =>
render.plain("deleted!").toFuture
}
/**
* Route parameters
*
* curl http://localhost:7070/user/dave => "hello dave"
*/
get("/user/:username") { request =>
val username = request.routeParams.getOrElse("username", "default_user")
render.plain("hello " + username).toFuture
}
/**
* Setting Headers
*
* curl -I http://localhost:7070/headers => "Foo:Bar"
*/
get("/headers") { request =>
render.plain("look at headers").header("Foo", "Bar").toFuture
}
/**
* Rendering json
*
* curl -I http://localhost:7070/data.json => "{foo:bar}"
*/
get("/data.json") { request =>
render.json(Map("foo" -> "bar")).toFuture
}
/**
* Query params
*
* curl http://localhost:7070/search?q=foo => "no results for foo"
*/
get("/search") { request =>
request.params.get("q") match {
case Some(q) => render.plain("no results for "+ q).toFuture
case None => render.plain("query param q needed").status(500).toFuture
}
}
/**
* Redirects
*
* curl http://localhost:7070/redirect
*/
get("/redirect") { request =>
redirect("http://localhost:7070/", permanent = true).toFuture
}
/**
* Uploading files
*
* curl -F avatar=@/path/to/img http://localhost:7070/profile
*/
post("/profile") { request =>
request.multiParams.get("avatar").foreach { avatar =>
println("content type is " + avatar.contentType)
avatar.writeToFile("/tmp/avatar") //writes uploaded avatar to /tmp/avatar
}
render.plain("ok").toFuture
}
options("/some/resource") { request =>
render.plain("usage description").toFuture
}
/**
* Rendering views
*
* curl http://localhost:7070/template
*/
class AnView extends View("example_test", "mock.test", "Your value is random value here")
get("/template") { request =>
val anView = new AnView
render.view(anView)
}
/**
* Custom Error Handling
*
* curl http://localhost:7070/error
*/
get("/error") { request =>
1234/0
render.plain("we never make it here").toFuture
}
/**
* Custom Error Handling with custom Exception
*
* curl http://localhost:7070/unauthorized
*/
class Unauthorized extends Exception
get("/unauthorized") { request =>
throw new Unauthorized
}
error { request =>
request.error match {
case Some(e:ArithmeticException) =>
render.status(500).plain("whoops, divide by zero!").toFuture
case Some(e:Unauthorized) =>
render.status(401).plain("Not Authorized!").toFuture
case Some(e:UnsupportedMediaType) =>
render.status(415).plain("Unsupported Media Type!").toFuture
case Some(e:Exception) =>
e.printStackTrace
render.status(500).plain("Something went wrong!").toFuture
case _ =>
render.status(500).plain("Something went wrong!").toFuture
}
}
/**
* Custom 404s
*
* curl http://localhost:7070/notfound
*/
notFound { request =>
render.status(404).plain("not found yo").toFuture
}
/**
* Arbitrary Dispatch
*
* curl http://localhost:7070/go_home
*/
get("/go_home") { request =>
route.get("/")
}
get("/search_for_dogs") { request =>
route.get("/search", Map("q" -> "dogs"))
}
get("/delete_photos") { request =>
route.delete("/photos")
}
get("/gif") { request =>
render.static("/dealwithit.gif").toFuture
}
/**
* Dispatch based on Content-Type
*
* curl http://localhost:7070/blog/index.json
* curl http://localhost:7070/blog/index.html
*/
get("/blog/index.:format") { request =>
respondTo(request) {
case _:Html => render.html("<h1>Hello</h1>").toFuture
case _:Json => render.json(Map("value" -> "hello")).toFuture
}
}
/**
* Also works without :format route using browser Accept header
*
* curl -H "Accept: text/html" http://localhost:7070/another/page
* curl -H "Accept: application/json" http://localhost:7070/another/page
* curl -H "Accept: foo/bar" http://localhost:7070/another/page
*/
get("/another/page") { request =>
respondTo(request) {
case _:Html => render.plain("an html response").toFuture
case _:Json => render.plain("an json response").toFuture
case _:All => render.plain("default fallback response").toFuture
}
}
/**
* Metrics are supported out of the box via Twitter's Ostrich library.
* More details here: https://github.com/twitter/ostrich
*
* curl http://localhost:7070/slow_thing
*
* By default a stats server is started on 9990:
*
* curl http://localhost:9990/stats.txt
*
*/
get("/slow_thing") { request =>
stats.counter("slow_thing").incr()
stats.time("slow_thing time") {
Thread.sleep(100)
}
render.plain("slow").toFuture
}
}
/* ###END_APP### */
val server = new PeregrineServer()
server.register(new ExampleApp())
server.registerViewRenderer(new ViewRenderer() {
val format = "example_test"
def render(template: String, view: View): String = s"${view.model}"
})
/* ###BEGIN_SPEC### */
"GET /notfound" should "respond 404" in {
get("/notfound")
response.body should equal ("not found yo")
response.code should equal (404)
}
"GET /error" should "respond 500" in {
get("/error")
response.body should equal ("whoops, divide by zero!")
response.code should equal (500)
}
"GET /unauthorized" should "respond 401" in {
get("/unauthorized")
response.body should equal ("Not Authorized!")
response.code should equal (401)
}
"GET /index.html" should "respond 200" in {
get("/")
response.body.contains("peregrine - The scala web framework") should equal(true)
response.code should equal(200)
}
"GET /user/foo" should "responsd with hello foo" in {
get("/user/foo")
response.body should equal ("hello foo")
}
"GET /headers" should "respond with Foo:Bar" in {
get("/headers")
response.getHeader("Foo") should equal("Bar")
}
"GET /data.json" should """respond with {"foo":"bar"}""" in {
get("/data.json")
response.body should equal("""{"foo":"bar"}""")
}
"GET /search?q=foo" should "respond with no results for foo" in {
get("/search?q=foo")
response.body should equal("no results for foo")
}
"GET /redirect" should "respond with /" in {
get("/redirect")
response.body should equal("Redirecting to <a href=\\"http://localhost:7070/\\">http://localhost:7070/</a>.")
response.code should equal(301)
}
"OPTIONS /some/resource" should "respond with usage description" in {
options("/some/resource")
response.body should equal("usage description")
}
"GET /template" should "respond with a rendered template" in {
get("/template")
response.body should equal("Your value is random value here")
}
"GET /blog/index.json" should "should have json" in {
get("/blog/index.json")
response.body should equal("""{"value":"hello"}""")
}
"GET /blog/index.html" should "should have html" in {
get("/blog/index.html")
response.body should equal("""<h1>Hello</h1>""")
}
"GET /blog/index.rss" should "respond in a 415" in {
get("/blog/index.rss")
response.code should equal(415)
}
"GET /go_home" should "render same as /" in {
get("/go_home")
response.body.contains("peregrine - The scala web framework") should equal(true)
response.code should equal(200)
}
"GET /search_for_dogs" should "render same as /search?q=dogs" in {
get("/search_for_dogs")
response.code should equal(200)
response.body should equal("no results for dogs")
}
"GET /delete_photos" should "render same as DELETE /photos" in {
get("/delete_photos")
response.code should equal(200)
response.body should equal("deleted!")
}
"GET /gif" should "render dealwithit.gif" in {
get("/gif")
response.code should equal(200)
response.originalResponse.getContent().array().head should equal(71) // capital "G", detects the gif
}
"GET /another/page with html" should "respond with html" in {
get("/another/page", Map.empty, Map("Accept" -> "text/html"))
response.body should equal("an html response")
}
"GET /another/page with json" should "respond with json" in {
get("/another/page", Map.empty, Map("Accept" -> "application/json"))
response.body should equal("an json response")
}
"GET /another/page with unsupported type" should "respond with catch all" in {
get("/another/page", Map.empty, Map("Accept" -> "foo/bar"))
response.body should equal("default fallback response")
}
/* ###END_SPEC### */
}
| dvarelap/stilt | src/test/scala/io/peregrine/ExampleSpec.scala | Scala | apache-2.0 | 9,433 |
package controllers
import play.api._
import play.api.mvc._
import com.dropbox.core.{DbxAppInfo, DbxAuthFinish, DbxWebAuth}
object Application extends Controller {
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
}
| vjousse/dropbox-scala-play | app/controllers/Application.scala | Scala | mit | 257 |
package com.rasterfoundry.datamodel
import java.net.URI
import geotrellis.proj4.CRS
import geotrellis.vector.{MultiPolygon, Projected}
import io.circe.generic.extras.{Configuration, ConfiguredJsonCodec}
@ConfiguredJsonCodec
final case class ExportOptions(mask: Option[Projected[MultiPolygon]],
resolution: Int,
crop: Boolean = false,
raw: Boolean = false,
bands: Option[Seq[Int]],
rasterSize: Option[Int],
crs: Option[Int],
source: URI = new URI(""),
operation: String = "id") {
def render = Render(operation, bands)
def getCrs: Option[CRS] = crs.map(CRS.fromEpsgCode)
}
object ExportOptions {
implicit val config: Configuration = Configuration.default.withDefaults
}
| azavea/raster-foundry | app-backend/datamodel/src/main/scala/ExportOptions.scala | Scala | apache-2.0 | 926 |
package soymilky
import soymilky.Configuration._
import soymilky.rally.Story
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.io.Source
import scala.util.{Failure, Success, Try, Random => r}
object Utterances {
def phrase(team: String, story: Story): Future[String] = {
implicit def tryAsFuture[T](attempt: Try[T]) = attempt match {
case Success(v) => Future successful v
case Failure(f) => Future failed f
}
implicit val dictionary: Map[String, String] = Map(
"team" -> team,
"team's" -> (if (team.endsWith("s")) s"$team'" else s"$team's"),
"id" -> story.FormattedID,
"points" -> story.PlanEstimate.map(_.toString).getOrElse("0"),
"forPoints" -> points(story)
)
phrases().flatMap {ps => resolveTokens(ps(r.nextInt(ps.size)))}
}
def resolveTokens(phrase: String)(implicit dict: Map[String, String]): Try[String] = {
val tokens = tokenRegex.findAllMatchIn(phrase).toSeq
val replacements = tokens.map(_.toString()) zip tokens.map(_.group(1))
Try(replacements.foldLeft(phrase){case (acc, (_, after)) =>
acc.replaceFirst("""\\$\\{""" + after + """\\}""", dict(after))
})
}
def phrases(source: Source = Source.fromFile(conf.getString("twitter.utterances.file"))): Future[Array[String]] = Future {
source.getLines().map(_.trim).filter(!_.isEmpty).toArray
}
private val tokenRegex = """\\$\\{(.*?)\\}""".r
private def points(story: Story, ifZero: String = ", although it had no points") = story.PlanEstimate
.map(p => s" for $p point${if (p==1) "" else "s"}")
.getOrElse(ifZero)
}
| Synesso/soymilky | src/main/scala/soymilky/Utterances.scala | Scala | apache-2.0 | 1,646 |
package com.acework.js.components.bootstrap
import com.acework.js.utils.{Mappable, Mergeable}
import japgolly.scalajs.react.Addons.ReactCloneWithProps
import japgolly.scalajs.react._
import scala.scalajs.js
import scala.scalajs.js.UndefOr
/**
* Created by weiyin on 09/03/15.
*/
object Utils {
object ValidComponentChildren {
/**
* mapValidComponents
* Maps children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The mapFunction provided index will be normalised to the components mapped,
* so an invalid component would not increase the index.
*
* @param children children Children tree container.
* @param func mapFunction
* @return Object containing the ordered map of results.
*/
def map(children: PropsChildren, func: (ReactNode, Int) => Any) = {
var index = 0
val f = (child: ReactNode, idx: Int) => {
if (React.isValidElement(child)) {
val lastIndex = index
index += 1
func(child, lastIndex)
}
else
child
}
val res = React.Children.map(children, (f: js.Function).asInstanceOf[js.Function1[ReactNode, js.Any]])
res.get.asInstanceOf[ReactNode]
}
/**
* Iterates through children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*/
def forEach2(children: PropsChildren, func: (ReactNode, Int) => Any) = {
var index = 0
val f = (child: ReactNode) => {
if (React.isValidElement(child)) {
func(child, index)
index += 1
}
}
children.forEach(f)
}
def forEach3(children: PropsChildren, func: (ReactNode, Int, Any) => Any, context: Any) = {
var index = 0
val f = (child: ReactNode) => {
if (React.isValidElement(child)) {
func(child, index, context)
index += 1
}
}
children.forEach(f)
}
/**
* Count the number of "valid components" in the Children container.
*/
def numberOfValidComponents(children: PropsChildren): Int = {
var count = 0
children.forEach { child =>
if (React.isValidElement(child))
count += 1
}
count
}
def hasValidComponents(children: PropsChildren): Boolean = numberOfValidComponents(children) > 0
}
def createChainedFunction0[X](f1: UndefOr[() => X], f2: UndefOr[() => X]): UndefOr[() => X] = {
if (f1.isEmpty && f2.isEmpty)
js.undefined
else if (f1.isEmpty)
f2
else if (f2.isEmpty)
f1
else
() => {
f1.get()
f2.get()
}
}
def createChainedFunction1[X, Y](f1: UndefOr[(X) => Y], f2: UndefOr[(X) => Y]): UndefOr[(X) => Y] = {
if (f1.isEmpty && f2.isEmpty)
js.undefined
else if (f1.isEmpty)
f2
else if (f2.isEmpty)
f1
else
(x: X) => {
f1.get(x)
f2.get(x)
}
}
def createChainedFunction2[X, Y, Z](f1: UndefOr[(X, Y) => Z], f2: UndefOr[(X, Y) => Z]): UndefOr[(X, Y) => Z] = {
if (f1.isEmpty && f2.isEmpty)
js.undefined
else if (f1.isEmpty)
f2
else if (f2.isEmpty)
f1
else
(x: X, y: Y) => {
f1.get(x, y)
f2.get(x, y)
}
}
def getChildKeyAndRef(child: ReactNode, index: Int): Map[String, js.Any] = {
val dynChild = child.asInstanceOf[js.Dynamic]
val ref: UndefOr[js.Any] = if (dynChild.ref == null) js.undefined else dynChild.ref
val key: UndefOr[js.Any] = if (dynChild.key == null) js.undefined else dynChild.key
val newKey: js.Any = if (key.isDefined) key else index
Map("ref" -> ref, "key" -> newKey)
}
def getChildKeyAndRef2(child: ReactNode, index: Int): (UndefOr[String], UndefOr[String]) = {
val childElement = child.asInstanceOf[ReactDOMElement]
val key = childElement.key
val ref = childElement.ref
val newKey: UndefOr[String] = if (key.isDefined) key else index.toString
(newKey, ref)
}
def getChildEventKey(child: ReactNode): UndefOr[js.Any] = {
val dynChild = child.asInstanceOf[js.Dynamic]
if (dynChild.eventKey == null) js.undefined else dynChild.eventKey
}
def getChildProps[P](child: ReactNode): P = {
val childNode = child.asInstanceOf[ReactDOMElement]
childNode.props.asInstanceOf[WrapObj[P]]
}
def cloneWithProps[P <: MergeableProps[P]](child: ReactNode, keyAndRef: (UndefOr[String], UndefOr[String]) = (js.undefined, js.undefined),
propsMap: Map[String, Any] = Map.empty) = {
var newProps = Map[String, js.Any]().empty
if (keyAndRef._1.isDefined)
newProps += ("key" -> keyAndRef._1.get)
if (keyAndRef._2.isDefined)
newProps += ("ref" -> keyAndRef._2.get)
if (isScalaComponent(child)) {
val childElement = child.asInstanceOf[ReactDOMElement]
val childProps: MergeableProps[P] = childElement.props.asInstanceOf[WrapObj[MergeableProps[P]]]
var mergedProps = childProps
if (propsMap.nonEmpty)
mergedProps = mergedProps.merge(propsMap)
val newChild = ReactCloneWithProps(child, newProps)
val dynChild = newChild.asInstanceOf[js.Dynamic]
val newChildProps = dynChild.props
newChildProps.updateDynamic("v")(mergedProps.asInstanceOf[js.Any])
newChild
}
else {
for ((k, v) <- propsMap) {
unwrapUndefOrFunc1(v) match {
case Some(fn) =>
newProps += (k -> fn)
case None =>
newProps += (k -> v.asInstanceOf[js.Any])
}
}
val newChild = ReactCloneWithProps(child, newProps)
newChild
}
}
def unwrapUndefOrFunc1(v: Any): Option[Any => Any] = {
var result: Option[Any => Any] = None
val unwrapped = v.asInstanceOf[UndefOr[Any]]
if (unwrapped.isDefined) {
if (unwrapped.get.isInstanceOf[Function1[_, _]]) {
result = Some(unwrapped.get.asInstanceOf[Any => Any])
}
}
result
}
implicit class MergeableCaseClass[S: Mergeable](v: S) {
def merge(map: Map[String, Any]): S =
implicitly[Mergeable[S]].merge(v, map)
def mergeProps[T: Mappable](t: T): S = {
val m = implicitly[Mappable[T]].toMap(t)
merge(m)
}
}
def caseClass2Map[T: Mappable](t: T): Map[String, Any] = implicitly[Mappable[T]].toMap(t)
def isScalaComponent(node: ReactNode): Boolean = {
var scalaComponent = false
if (React.isValidElement(node)) {
val element = node.asInstanceOf[ReactDOMElement]
val childProps = element.props
// this is a hack, is there better way to find out if it is a
if (childProps.hasOwnProperty("v"))
scalaComponent = true
}
scalaComponent
}
case class Offset(top: Double, left: Double)
def getOffset(node: TopNode) = {
val offset = jQuery(node).offset().asInstanceOf[js.Dynamic]
Offset(offset.top.asInstanceOf[Double], offset.left.asInstanceOf[Double])
}
}
| lvitaly/scalajs-react-bootstrap | core/src/main/scala/com/acework/js/components/bootstrap/Utils.scala | Scala | mit | 7,219 |
trait MatcherYYY {
trait NodeImpl;
trait Matchable extends NodeImpl {
protected def doMatch : Unit = {}
}
}
trait BraceMatcherXXX extends MatcherYYY {
trait NodeImpl extends super.NodeImpl {
def doMatch (braces : BracePair) : Unit
}
trait BracePair {
trait BraceImpl extends NodeImpl with Matchable {
override def doMatch : Unit = {
super.doMatch;
();
}
}
}
}
| yusuke2255/dotty | tests/pending/pos/t805.scala | Scala | bsd-3-clause | 420 |
/*
* Copyright 2016 Alexey Kuzin <[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 choiceroulette.gui.controls.actions
import scaldi.Module
/** Actions package module.
*
* @author Alexey Kuzin <[email protected]>
*/
object ActionModule extends Module {
binding to new ActionController
binding to injected [ActionsPane]
}
| leviathan941/choiceroulette | guiapp/src/main/scala/choiceroulette/gui/controls/actions/ActionModule.scala | Scala | apache-2.0 | 875 |
/*
* 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.carbondata.presto.integrationtest
import java.io.File
import java.util
import org.apache.hadoop.fs.permission.{FsAction, FsPermission}
import org.scalatest.{BeforeAndAfterAll, FunSuiteLike}
import org.apache.carbondata.common.logging.LogServiceFactory
import org.apache.carbondata.core.constants.CarbonCommonConstants
import org.apache.carbondata.core.datastore.impl.FileFactory
import org.apache.carbondata.core.util.{CarbonProperties, CarbonUtil}
import org.apache.carbondata.presto.server.PrestoServer
class PrestoAllDataTypeLocalDictTest extends FunSuiteLike with BeforeAndAfterAll {
private val logger = LogServiceFactory
.getLogService(classOf[PrestoAllDataTypeLocalDictTest].getCanonicalName)
private val rootPath = new File(this.getClass.getResource("/").getPath
+ "../../../..").getCanonicalPath
private val storePath = s"$rootPath/integration/presto/target/store"
private val prestoServer = new PrestoServer
// Table schema:
// +-------------+----------------+-------------+------------+
// | Column name | Data type | Column type | Dictionary |
// +-------------+----------------+--------------+-----------+
// | id | string | dimension | yes |
// +-------------+----------------+-------------+------------+
// | date | date | dimension | yes |
// +-------------+----------------+-------------+------------+
// | country | string | dimension | yes |
// +-------------+----------------+-------------+-------------
// | name | string | dimension | yes |
// +-------------+----------------+-------------+-------------
// | phonetype | string | dimension | yes |
// +-------------+----------------+-------------+-------------
// | serialname | string | dimension | true |
// +-------------+----------------+-------------+-------------
// | bonus |short decimal | measure | false |
// +-------------+----------------+-------------+-------------
// | monthlyBonus| longdecimal | measure | false |
// +-------------+----------------+-------------+-------------
// | dob | timestamp | dimension | true |
// +-------------+----------------+-------------+------------+
// | shortField | shortfield | measure | true |
// +-------------+----------------+-------------+-------------
// |isCurrentEmp | boolean | measure | true |
// +-------------+----------------+-------------+------------+
override def beforeAll: Unit = {
import org.apache.carbondata.presto.util.CarbonDataStoreCreator
CarbonProperties.getInstance().addProperty(CarbonCommonConstants.CARBON_WRITTEN_BY_APPNAME,
"Presto")
val map = new util.HashMap[String, String]()
map.put("hive.metastore", "file")
map.put("hive.metastore.catalog.dir", s"file://$storePath")
prestoServer.startServer("testdb", map)
prestoServer.execute("drop table if exists testdb.testtable")
prestoServer.execute("drop schema if exists testdb")
prestoServer.execute("create schema testdb")
prestoServer.execute(
"create table testdb.testtable(ID int, date date, country varchar, name varchar, " +
"phonetype varchar, serialname varchar,salary double, bonus decimal(10,4), " +
"monthlyBonus decimal(18,4), dob timestamp, shortField smallint, " +
"iscurrentemployee boolean) with(format='CARBON') ")
CarbonDataStoreCreator
.createCarbonStore(storePath,
s"$rootPath/integration/presto/src/test/resources/alldatatype.csv", true)
logger.info(s"\\nCarbon store is created at location: $storePath")
cleanUp
}
override def afterAll(): Unit = {
prestoServer.stopServer()
CarbonUtil.deleteFoldersAndFiles(FileFactory.getCarbonFile(storePath))
}
test("select string type with order by clause") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery("SELECT NAME FROM TESTDB.TESTTABLE ORDER BY NAME")
val expectedResult: List[Map[String, Any]] = List(Map("NAME" -> "akash"),
Map("NAME" -> "anubhav"),
Map("NAME" -> "bhavya"),
Map("NAME" -> "geetika"),
Map("NAME" -> "jatin"),
Map("NAME" -> "jitesh"),
Map("NAME" -> "liang"),
Map("NAME" -> "prince"),
Map("NAME" -> "ravindra"),
Map("NAME" -> "sahil"),
Map("NAME" -> null)
)
assertResult(expectedResult)(actualResult)
}
test("test and filter clause with greater than expression") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery(
"SELECT ID,DATE,COUNTRY,NAME,PHONETYPE,SERIALNAME,SALARY,BONUS FROM TESTDB.TESTTABLE " +
"WHERE BONUS>1234 AND ID>2 GROUP BY ID,DATE,COUNTRY,NAME,PHONETYPE,SERIALNAME,SALARY," +
"BONUS ORDER BY ID")
val expectedResult: List[Map[String, Any]] = List(Map("ID" -> 4,
"NAME" -> "prince",
"BONUS" -> java.math.BigDecimal.valueOf(9999.9990).setScale(4),
"DATE" -> "2015-07-26",
"SALARY" -> 15003.0,
"SERIALNAME" -> "ASD66902",
"COUNTRY" -> "china",
"PHONETYPE" -> "phone2435"),
Map("ID" -> 5,
"NAME" -> "bhavya",
"BONUS" -> java.math.BigDecimal.valueOf(5000.999).setScale(4),
"DATE" -> "2015-07-27",
"SALARY" -> 15004.0,
"SERIALNAME" -> "ASD90633",
"COUNTRY" -> "china",
"PHONETYPE" -> "phone2441"))
assert(actualResult.toString() equals expectedResult.toString())
}
test("test and filter clause with greater than equal to expression") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery(
"SELECT ID,DATE,COUNTRY,NAME,PHONETYPE,SERIALNAME,SALARY,BONUS FROM TESTDB.TESTTABLE " +
"WHERE BONUS>=1234.444 GROUP BY ID,DATE,COUNTRY,NAME,PHONETYPE,SERIALNAME,SALARY," +
"BONUS ORDER BY ID")
val expectedResult: List[Map[String, Any]] = List(Map("ID" -> 1,
"NAME" -> "anubhav",
"BONUS" -> java.math.BigDecimal.valueOf(1234.4440).setScale(4),
"DATE" -> "2015-07-23",
"SALARY" -> "5000000.0",
"SERIALNAME" -> "ASD69643",
"COUNTRY" -> "china",
"PHONETYPE" -> "phone197"),
Map("ID" -> 2,
"NAME" -> "jatin",
"BONUS" -> java.math.BigDecimal.valueOf(1234.5555).setScale(4)
,
"DATE" -> "2015-07-24",
"SALARY" -> java.math.BigDecimal.valueOf(150010.9990).setScale(3),
"SERIALNAME" -> "ASD42892",
"COUNTRY" -> "china",
"PHONETYPE" -> "phone756"),
Map("ID" -> 4,
"NAME" -> "prince",
"BONUS" -> java.math.BigDecimal.valueOf(9999.9990).setScale(4),
"DATE" -> "2015-07-26",
"SALARY" -> java.math.BigDecimal.valueOf(15003.0).setScale(1),
"SERIALNAME" -> "ASD66902",
"COUNTRY" -> "china",
"PHONETYPE" -> "phone2435"),
Map("ID" -> 5,
"NAME" -> "bhavya",
"BONUS" -> java.math.BigDecimal.valueOf(5000.9990).setScale(4),
"DATE" -> "2015-07-27",
"SALARY" -> java.math.BigDecimal.valueOf(15004.0).setScale(1),
"SERIALNAME" -> "ASD90633",
"COUNTRY" -> "china",
"PHONETYPE" -> "phone2441"))
assert(actualResult.toString() equals expectedResult.toString())
}
test("test and filter clause with less than equal to expression") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery(
"SELECT ID,DATE,COUNTRY,NAME,PHONETYPE,SERIALNAME,SALARY,BONUS FROM TESTDB.TESTTABLE " +
"WHERE BONUS<=1234.444 GROUP BY ID,DATE,COUNTRY,NAME,PHONETYPE,SERIALNAME,SALARY," +
"BONUS ORDER BY ID LIMIT 2")
val expectedResult: List[Map[String, Any]] = List(Map("ID" -> 1,
"NAME" -> "anubhav",
"BONUS" -> java.math.BigDecimal.valueOf(1234.4440).setScale(4),
"DATE" -> "2015-07-23",
"SALARY" -> "5000000.0",
"SERIALNAME" -> "ASD69643",
"COUNTRY" -> "china",
"PHONETYPE" -> "phone197"),
Map("ID" -> 3,
"NAME" -> "liang",
"BONUS" -> java.math.BigDecimal.valueOf(600.7770).setScale(4),
"DATE" -> "2015-07-25",
"SALARY" -> java.math.BigDecimal.valueOf(15002.11).setScale(2),
"SERIALNAME" -> "ASD37014",
"COUNTRY" -> "china",
"PHONETYPE" -> "phone1904"))
assert(actualResult.toString() equals expectedResult.toString())
}
test("test equal to expression on decimal value") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery(
"SELECT ID FROM TESTDB.TESTTABLE WHERE BONUS=1234.444")
val expectedResult: List[Map[String, Any]] = List(Map("ID" -> 1))
assert(actualResult equals expectedResult)
}
test("test less than expression with and operator") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery(
"SELECT ID,DATE,COUNTRY,NAME,PHONETYPE,SERIALNAME,SALARY,BONUS FROM TESTDB.TESTTABLE " +
"WHERE BONUS>1234 AND ID<2 GROUP BY ID,DATE,COUNTRY,NAME,PHONETYPE,SERIALNAME,SALARY," +
"BONUS ORDER BY ID")
// scalastyle:off println
actualResult.foreach(println)
// scalastyle:on println
val expectedResult: List[Map[String, Any]] = List(Map("ID" -> 1,
"NAME" -> "anubhav",
"BONUS" -> java.math.BigDecimal.valueOf(1234.4440).setScale(4),
"DATE" -> "2015-07-23",
"SALARY" -> 5000000.0,
"SERIALNAME" -> "ASD69643",
"COUNTRY" -> "china",
"PHONETYPE" -> "phone197"))
assert(actualResult.toString().equals(expectedResult.toString()))
}
test("test the result for in clause") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery("SELECT NAME from testdb.testtable WHERE PHONETYPE IN('phone1848','phone706')")
val expectedResult: List[Map[String, Any]] = List(
Map("NAME" -> "geetika"),
Map("NAME" -> "ravindra"),
Map("NAME" -> "jitesh"))
assert(actualResult.equals(expectedResult))
}
test("test the result for not in clause") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery(
"SELECT NAME from testdb.testtable WHERE PHONETYPE NOT IN('phone1848','phone706')")
val expectedResult: List[Map[String, Any]] = List(Map("NAME" -> "anubhav"),
Map("NAME" -> "jatin"),
Map("NAME" -> "liang"),
Map("NAME" -> "prince"),
Map("NAME" -> "bhavya"),
Map("NAME" -> "akash"),
Map("NAME" -> "sahil"))
assert(actualResult.equals(expectedResult))
}
test("test for null operator on date data type") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery("SELECT ID FROM TESTDB.TESTTABLE WHERE DATE IS NULL")
val expectedResult: List[Map[String, Any]] = List(Map("ID" -> 9), Map("ID" -> null))
assert(actualResult.equals(expectedResult))
}
test("test for not null operator on date data type") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery("SELECT NAME FROM TESTDB.TESTTABLE WHERE DATE IS NOT NULL AND ID=9")
val expectedResult: List[Map[String, Any]] = List(Map("NAME" -> "ravindra"))
assert(actualResult.equals(expectedResult))
}
test("test for not null operator on timestamp type") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery("SELECT NAME FROM TESTDB.TESTTABLE WHERE DOB IS NOT NULL AND ID=9")
val expectedResult: List[Map[String, Any]] = List(Map("NAME" -> "ravindra"),
Map("NAME" -> "jitesh"))
assert(actualResult.equals(expectedResult))
}
test("test timestamp datatype using cast operator") {
val actualResult: List[Map[String, Any]] = prestoServer
.executeQuery(
"SELECT NAME AS RESULT FROM TESTDB.TESTTABLE " +
"WHERE DOB = CAST('2016-04-14 15:00:09' AS TIMESTAMP)")
val expectedResult: List[Map[String, Any]] = List(Map("RESULT" -> "jatin"))
assert(actualResult.equals(expectedResult))
}
private def cleanUp(): Unit = {
FileFactory.deleteFile(s"$storePath/Fact")
FileFactory
.createDirectoryAndSetPermission(s"$storePath/_system",
new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL))
FileFactory
.createDirectoryAndSetPermission(s"$storePath/.DS_Store",
new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL))
FileFactory.createNewFile(s"$storePath/testdb/.DS_STORE")
}
}
| zzcclp/carbondata | integration/presto/src/test/scala/org/apache/carbondata/presto/integrationtest/PrestoAllDataTypeLocalDictTest.scala | Scala | apache-2.0 | 13,254 |
/*
* 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.catalyst.plans.logical.statsEstimation
import org.apache.spark.sql.catalyst.expressions.AttributeMap
import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftSemi}
import org.apache.spark.sql.catalyst.plans.logical
import org.apache.spark.sql.catalyst.plans.logical._
/**
* An [[LogicalPlanVisitor]] that computes a single dimension for plan stats: size in bytes.
*/
object SizeInBytesOnlyStatsPlanVisitor extends LogicalPlanVisitor[Statistics] {
/**
* A default, commonly used estimation for unary nodes. We assume the input row number is the
* same as the output row number, and compute sizes based on the column types.
*/
private def visitUnaryNode(p: UnaryNode): Statistics = {
// There should be some overhead in Row object, the size should not be zero when there is
// no columns, this help to prevent divide-by-zero error.
val childRowSize = p.child.output.map(_.dataType.defaultSize).sum + 8
val outputRowSize = p.output.map(_.dataType.defaultSize).sum + 8
// Assume there will be the same number of rows as child has.
var sizeInBytes = (p.child.stats.sizeInBytes * outputRowSize) / childRowSize
if (sizeInBytes == 0) {
// sizeInBytes can't be zero, or sizeInBytes of BinaryNode will also be zero
// (product of children).
sizeInBytes = 1
}
// Don't propagate rowCount and attributeStats, since they are not estimated here.
Statistics(sizeInBytes = sizeInBytes, hints = p.child.stats.hints)
}
/**
* For leaf nodes, use its computeStats. For other nodes, we assume the size in bytes is the
* sum of all of the children's.
*/
override def default(p: LogicalPlan): Statistics = p match {
case p: LeafNode => p.computeStats()
case _: LogicalPlan => Statistics(sizeInBytes = p.children.map(_.stats.sizeInBytes).product)
}
override def visitAggregate(p: Aggregate): Statistics = {
if (p.groupingExpressions.isEmpty) {
Statistics(
sizeInBytes = EstimationUtils.getOutputSize(p.output, outputRowCount = 1),
rowCount = Some(1),
hints = p.child.stats.hints)
} else {
visitUnaryNode(p)
}
}
override def visitDistinct(p: Distinct): Statistics = default(p)
override def visitExcept(p: Except): Statistics = p.left.stats.copy()
override def visitExpand(p: Expand): Statistics = {
val sizeInBytes = visitUnaryNode(p).sizeInBytes * p.projections.length
Statistics(sizeInBytes = sizeInBytes)
}
override def visitFilter(p: Filter): Statistics = visitUnaryNode(p)
override def visitGenerate(p: Generate): Statistics = default(p)
override def visitGlobalLimit(p: GlobalLimit): Statistics = {
val limit = p.limitExpr.eval().asInstanceOf[Int]
val childStats = p.child.stats
val rowCount: BigInt = childStats.rowCount.map(_.min(limit)).getOrElse(limit)
// Don't propagate column stats, because we don't know the distribution after limit
Statistics(
sizeInBytes = EstimationUtils.getOutputSize(p.output, rowCount, childStats.attributeStats),
rowCount = Some(rowCount),
hints = childStats.hints)
}
override def visitHint(p: ResolvedHint): Statistics = p.child.stats.copy(hints = p.hints)
override def visitIntersect(p: Intersect): Statistics = {
val leftSize = p.left.stats.sizeInBytes
val rightSize = p.right.stats.sizeInBytes
val sizeInBytes = if (leftSize < rightSize) leftSize else rightSize
Statistics(
sizeInBytes = sizeInBytes,
hints = p.left.stats.hints.resetForJoin())
}
override def visitJoin(p: Join): Statistics = {
p.joinType match {
case LeftAnti | LeftSemi =>
// LeftSemi and LeftAnti won't ever be bigger than left
p.left.stats
case _ =>
// Make sure we don't propagate isBroadcastable in other joins, because
// they could explode the size.
val stats = default(p)
stats.copy(hints = stats.hints.resetForJoin())
}
}
override def visitLocalLimit(p: LocalLimit): Statistics = {
val limit = p.limitExpr.eval().asInstanceOf[Int]
val childStats = p.child.stats
if (limit == 0) {
// sizeInBytes can't be zero, or sizeInBytes of BinaryNode will also be zero
// (product of children).
Statistics(sizeInBytes = 1, rowCount = Some(0), hints = childStats.hints)
} else {
// The output row count of LocalLimit should be the sum of row counts from each partition.
// However, since the number of partitions is not available here, we just use statistics of
// the child. Because the distribution after a limit operation is unknown, we do not propagate
// the column stats.
childStats.copy(attributeStats = AttributeMap(Nil))
}
}
override def visitPivot(p: Pivot): Statistics = default(p)
override def visitProject(p: Project): Statistics = visitUnaryNode(p)
override def visitRepartition(p: Repartition): Statistics = default(p)
override def visitRepartitionByExpr(p: RepartitionByExpression): Statistics = default(p)
override def visitSample(p: Sample): Statistics = {
val ratio = p.upperBound - p.lowerBound
var sizeInBytes = EstimationUtils.ceil(BigDecimal(p.child.stats.sizeInBytes) * ratio)
if (sizeInBytes == 0) {
sizeInBytes = 1
}
val sampleRows = p.child.stats.rowCount.map(c => EstimationUtils.ceil(BigDecimal(c) * ratio))
// Don't propagate column stats, because we don't know the distribution after a sample operation
Statistics(sizeInBytes, sampleRows, hints = p.child.stats.hints)
}
override def visitScriptTransform(p: ScriptTransformation): Statistics = default(p)
override def visitUnion(p: Union): Statistics = {
Statistics(sizeInBytes = p.children.map(_.stats.sizeInBytes).sum)
}
override def visitWindow(p: Window): Statistics = visitUnaryNode(p)
}
| minixalpha/spark | sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/SizeInBytesOnlyStatsPlanVisitor.scala | Scala | apache-2.0 | 6,657 |
package ru.wordmetrix.enwiz
import EnWizLookup.{ EnWizStatRequest, EnWizMnemonicRequest, EnWizWords }
//import akka.routing.ActorRefRoutee
import akka.routing.Router
import akka.routing.RoundRobinRouter
//import akka.routing.
//import akka.routing.RoundRobinRoutingLogic
import EnWizParser.EnWizText
import akka.actor.{ Actor, Props, actorRef2Scala }
/**
* Dispatcher of requests that resends time-consuming request
* into special queue.
*/
object EnWizActor {
abstract sealed trait EnWizMessage
def props(lookupprop: Props, parserprop: Props): Props =
Props(new EnWizActor(lookupprop, parserprop))
}
class EnWizActor(lookupprop: Props, parserprop: Props) extends Actor {
val lookup = context.actorOf(lookupprop.withRouter(
RoundRobinRouter(nrOfInstances = 5)
))
val parser = context.actorOf(parserprop, "Parser")
import EnWizParser._
import EnWizLookup._
def receive(): Receive = {
case msg @ EnWizStatRequest() =>
lookup forward msg
case msg @ EnWizWords(word1, word2) =>
lookup forward msg
case msg @ EnWizText(_,_) =>
parser forward msg
case msg @ EnWizStatusRequest() =>
parser forward msg
case msg @ EnWizMnemonicRequest(_) =>
lookup forward msg
case msg @ EnWizAcronymRequest(_) =>
lookup forward msg
case msg @ EnWizPhraseRequest(_) =>
lookup forward msg
case msg @ EnWizGapRequest(_,_) =>
println(msg)
lookup forward msg
}
}
| electricmind/enwiz | src/main/scala/ru/wordmetrix/enwiz/EnWizActor.scala | Scala | apache-2.0 | 1,617 |
/**
* OEML - REST API
* This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\\"https://postman.coinapi.io/\\" target=\\"_blank\\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)
*
* The version of the OpenAPI document: v1
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api
import org.openapitools.client.model.Balance
import org.openapitools.client.model.MessageReject
import org.openapitools.client.core._
import org.openapitools.client.core.CollectionFormats._
import org.openapitools.client.core.ApiKeyLocations._
object BalancesApi {
def apply(baseUrl: String = "https://13d16e9d-d8b1-4ef4-bc4a-ed8156b2b159.mock.pstmn.io") = new BalancesApi(baseUrl)
}
class BalancesApi(baseUrl: String) {
/**
* Get current currency balance from all or single exchange.
*
* Expected answers:
* code 200 : Seq[Balance] (Collection of balances.)
* code 490 : MessageReject (Exchange is unreachable.)
*
* @param exchangeId Filter the balances to the specific exchange.
*/
def v1BalancesGet(exchangeId: Option[String] = None): ApiRequest[Seq[Balance]] =
ApiRequest[Seq[Balance]](ApiMethods.GET, baseUrl, "/v1/balances", "application/json")
.withQueryParam("exchange_id", exchangeId)
.withSuccessResponse[Seq[Balance]](200)
.withErrorResponse[MessageReject](490)
}
| coinapi/coinapi-sdk | oeml-sdk/scala-akka/src/main/scala/org/openapitools/client/api/BalancesApi.scala | Scala | mit | 1,822 |
package mesosphere.marathon
package core.task.update.impl
import java.time.Clock
import javax.inject.Inject
import akka.event.EventStream
import com.google.inject.name.Names
import com.typesafe.scalalogging.StrictLogging
import mesosphere.marathon.core.condition.Condition
import mesosphere.marathon.core.event.UnknownInstanceTerminated
import mesosphere.marathon.core.instance.Instance
import mesosphere.marathon.core.task.termination.{ KillReason, KillService }
import mesosphere.marathon.core.task.tracker.{ InstanceTracker, InstanceStateOpProcessor }
import mesosphere.marathon.core.task.update.TaskStatusUpdateProcessor
import mesosphere.marathon.core.task.{ Task, TaskCondition }
import mesosphere.marathon.metrics.{ Metrics, ServiceMetric, Timer }
import org.apache.mesos.{ Protos => MesosProtos }
import scala.concurrent.Future
/**
* Executes the given TaskStatusUpdateSteps for every update.
*/
class TaskStatusUpdateProcessorImpl @Inject() (
clock: Clock,
instanceTracker: InstanceTracker,
stateOpProcessor: InstanceStateOpProcessor,
driverHolder: MarathonSchedulerDriverHolder,
killService: KillService,
eventStream: EventStream) extends TaskStatusUpdateProcessor with StrictLogging {
import scala.concurrent.ExecutionContext.Implicits.global
private[this] val publishTimer: Timer = Metrics.timer(ServiceMetric, getClass, "publishFuture")
private[this] val killUnknownTaskTimer: Timer = Metrics.timer(ServiceMetric, getClass, "killUnknownTask")
logger.info("Started status update processor")
override def publish(status: MesosProtos.TaskStatus): Future[Unit] = publishTimer {
logger.debug(s"Received status update\\n${status}")
import TaskStatusUpdateProcessorImpl._
// TODO: should be Timestamp.fromTaskStatus(status), but this breaks unit tests as there are invalid stubs
val now = clock.now()
val taskId = Task.Id(status.getTaskId)
val taskCondition = TaskCondition(status)
def taskIsUnknown(instance: Instance, taskId: Task.Id) = {
instance.tasksMap.get(taskId).isEmpty
}
instanceTracker.instance(taskId.instanceId).flatMap {
case Some(instance) if taskIsUnknown(instance, taskId) =>
if (killWhenUnknown(taskCondition)) {
killUnknownTaskTimer {
logger.warn(s"Kill ${taskId} because it's unknown to marathon. " +
s"The related instance ${instance.instanceId} is associated with ${instance.tasksMap.keys}")
Future.successful(killService.killUnknownTask(taskId, KillReason.NotInSync))
}
}
acknowledge(status)
case Some(instance) =>
// TODO(PODS): we might as well pass the taskCondition here
stateOpProcessor.updateStatus(instance, status, now).flatMap(_ => acknowledge(status))
case None if terminalUnknown(taskCondition) =>
logger.warn(s"Received terminal status update for unknown ${taskId}")
eventStream.publish(UnknownInstanceTerminated(taskId.instanceId, taskId.runSpecId, taskCondition))
acknowledge(status)
case None if killWhenUnknown(taskCondition) =>
killUnknownTaskTimer {
logger.warn(s"Kill unknown ${taskId}")
killService.killUnknownTask(taskId, KillReason.Unknown)
acknowledge(status)
}
case maybeTask: Option[Instance] =>
val taskStr = taskKnownOrNotStr(maybeTask)
logger.info(s"Ignoring ${status.getState} update for $taskStr $taskId")
acknowledge(status)
}
}
private[this] def acknowledge(status: MesosProtos.TaskStatus): Future[Unit] = {
driverHolder.driver.foreach{ driver =>
logger.info(s"Acknowledge status update for task ${status.getTaskId.getValue}: ${status.getState} (${status.getMessage})")
driver.acknowledgeStatusUpdate(status)
}
Future.successful(())
}
}
object TaskStatusUpdateProcessorImpl {
lazy val name = Names.named(getClass.getSimpleName)
/** Matches all states that are considered terminal for an unknown task */
def terminalUnknown(condition: Condition): Boolean = condition match {
case t: Condition.Terminal => true
case Condition.Unreachable => true
case _ => false
}
// TODO(PODS): align this with similar extractors/functions
private[this] val ignoreWhenUnknown = Set[Condition](
Condition.Killed,
Condition.Killing,
Condition.Error,
Condition.Failed,
Condition.Finished,
Condition.Unreachable,
Condition.Gone,
Condition.Dropped,
Condition.Unknown
)
// It doesn't make sense to kill an unknown task if it is in a terminal or killing state
// We'd only get another update for the same task
private def killWhenUnknown(condition: Condition): Boolean = {
!ignoreWhenUnknown.contains(condition)
}
private def taskKnownOrNotStr(maybeTask: Option[Instance]): String = if (maybeTask.isDefined) "known" else "unknown"
}
| guenter/marathon | src/main/scala/mesosphere/marathon/core/task/update/impl/TaskStatusUpdateProcessorImpl.scala | Scala | apache-2.0 | 4,900 |
package com.karasiq.bittorrent.protocol
import java.nio.ByteBuffer
import scala.collection.BitSet
import scala.util.Try
import akka.util.ByteString
import com.karasiq.bittorrent.protocol.extensions.PeerExtensions
private[bittorrent] object BitTorrentTcpProtocol {
def int32FromBytes(bytes: ByteString): Int = {
assert(bytes.length <= 4, "Invalid integer length")
BigInt((ByteString(Array.fill[Byte](4 - bytes.length)(0)) ++ bytes).toArray).intValue()
}
implicit class ByteBufferOps(val bb: ByteBuffer) extends AnyVal {
def getByteString(size: Int): ByteString = {
val array = new Array[Byte](Array(size, bb.remaining()).min)
bb.get(array)
ByteString(array)
}
def getByteInt: Int = {
val byte = bb.get()
int32FromBytes(ByteString(byte))
}
}
}
trait BitTorrentTcpProtocol { self: BitTorrentMessages ⇒
import BitTorrentTcpProtocol._
implicit object PeerHandshakeTcpProtocol extends TcpMessageProtocol[PeerHandshake] {
override def toBytes(ph: PeerHandshake): ByteString = {
val protocolBytes = ph.protocol.toCharArray.map(_.toByte)
assert(protocolBytes.length <= Byte.MaxValue)
val byteBuffer = ByteBuffer.allocate(1 + 8 + protocolBytes.length + 20 + 20)
byteBuffer.put(protocolBytes.length.toByte)
byteBuffer.put(protocolBytes)
byteBuffer.put(ph.extensions.toByteArray)
byteBuffer.put(ph.infoHash.toByteBuffer)
byteBuffer.put(ph.peerId.toByteBuffer)
byteBuffer.flip()
ByteString(byteBuffer)
}
override def fromBytes(bs: ByteString): Option[PeerHandshake] = {
Try {
val buffer = bs.toByteBuffer
val length = buffer.getByteInt
assert(length <= buffer.remaining() - 48, "Invalid length")
val protocol = buffer.getByteString(length)
val reserved = buffer.getByteString(8)
val infoHash = buffer.getByteString(20)
val id = buffer.getByteString(20)
PeerHandshake(new String(protocol.toArray, "ASCII"), infoHash, id, PeerExtensions.fromBytes(reserved))
}.toOption
}
}
implicit object PeerMessageTcpProtocol extends TcpMessageProtocol[PeerMessage] {
override def toBytes(pm: PeerMessage): ByteString = {
require(pm.length == pm.payload.length + 1)
val byteBuffer = ByteBuffer.allocate(4 + 1 + pm.payload.length)
byteBuffer.putInt(pm.payload.length + 1)
byteBuffer.put(pm.id.toByte)
byteBuffer.put(pm.payload.toByteBuffer)
byteBuffer.flip()
ByteString(byteBuffer)
}
override def fromBytes(bs: ByteString): Option[PeerMessage] = {
Try {
val buffer = bs.toByteBuffer
val length = buffer.getInt
assert(length > 0 && buffer.remaining() >= length, "Buffer underflow")
val id = buffer.getByteInt
PeerMessage(id, length, ByteString(buffer).take(length - 1))
}.toOption
}
}
implicit object HaveMessageTcpProtocol extends TcpMessageProtocol[PieceIndex] {
override def toBytes(hp: PieceIndex): ByteString = {
val buffer = ByteBuffer.allocate(4)
buffer.putInt(hp.index)
buffer.flip()
ByteString(buffer)
}
override def fromBytes(bs: ByteString): Option[PieceIndex] = {
Try {
val buffer = bs.asByteBuffer
PieceIndex(buffer.getInt)
}.toOption
}
}
implicit object BitFieldMessageTcpProtocol extends TcpMessageProtocol[BitField] {
private def readBitField(values: ByteString): (Int, BitSet) = {
val buffer = values.toByteBuffer
val length = buffer.remaining() * 8
val bitSet = new scala.collection.mutable.BitSet(length)
(0 until length).foreach { i ⇒
bitSet.update(i, (buffer.get(i/8) & (1 << (7 -(i % 8)))) > 0)
}
length → bitSet
}
private def writeBitField(size: Int, values: BitSet): ByteString = {
val bitfield = new Array[Byte](math.ceil(size.toDouble / 8.0).toInt)
for (i <- values) {
bitfield.update(i/8, (bitfield(i/8) | 1 << (7 - (i % 8))).toByte)
}
ByteString(bitfield)
}
override def toBytes(bf: BitField): ByteString = {
writeBitField(bf.pieces, bf.completed)
}
override def fromBytes(bs: ByteString): Option[BitField] = {
Try {
val (size, completed) = readBitField(bs)
BitField(size, completed)
}.toOption
}
}
implicit object PieceBlockRequestTcpProtocol extends TcpMessageProtocol[PieceBlockRequest] {
override def toBytes(pbr: PieceBlockRequest): ByteString = {
val byteBuffer = ByteBuffer.allocate(4 * 3)
byteBuffer.putInt(pbr.index)
byteBuffer.putInt(pbr.offset)
byteBuffer.putInt(pbr.length)
byteBuffer.flip()
ByteString(byteBuffer)
}
override def fromBytes(bs: ByteString): Option[PieceBlockRequest] = {
Try {
val buffer = bs.toByteBuffer
val index = buffer.getInt
val offset = buffer.getInt
val length = buffer.getInt
PieceBlockRequest(index, offset, length)
}.toOption
}
}
implicit object PieceBlockTcpProtocol extends TcpMessageProtocol[PieceBlock] {
override def toBytes(pb: PieceBlock): ByteString = {
val byteBuffer = ByteBuffer.allocate(4 * 2 + pb.data.length)
byteBuffer.putInt(pb.index)
byteBuffer.putInt(pb.offset)
byteBuffer.put(pb.data.toByteBuffer)
byteBuffer.flip()
ByteString(byteBuffer)
}
override def fromBytes(bs: ByteString): Option[PieceBlock] = {
Try {
val buffer = bs.toByteBuffer
val index = buffer.getInt
val offset = buffer.getInt
PieceBlock(index, offset, ByteString(buffer))
}.toOption
}
}
implicit object PortTcpProtocol extends TcpMessageProtocol[Port] {
override def toBytes(p: Port): ByteString = {
val buffer = ByteBuffer.allocate(2)
buffer.putShort(p.port.toShort)
buffer.flip()
ByteString(buffer)
}
override def fromBytes(bs: ByteString): Option[Port] = {
Try {
Port(BitTorrentTcpProtocol.int32FromBytes(bs.take(2)))
}.toOption
}
}
implicit object KeepAliveTcpProtocol extends TcpMessageProtocol[KeepAlive.type] {
private val keepAlive = ByteString(0, 0, 0, 0)
override def toBytes(value: KeepAlive.type): ByteString = {
keepAlive
}
override def fromBytes(bs: ByteString): Option[KeepAlive.type] = {
if (bs.take(4) == keepAlive) Some(KeepAlive) else None
}
}
}
| Karasiq/torrentstream | library/src/main/scala/com/karasiq/bittorrent/protocol/BitTorrentTcpProtocol.scala | Scala | apache-2.0 | 6,482 |
/*
* 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.eval
import cats.laws._
import cats.laws.discipline._
import monix.execution.internal.Platform
import concurrent.duration._
import scala.util.Success
object TaskStartSuite extends BaseTestSuite {
test("task.start.flatMap(_.join) <-> task") { implicit sc =>
check1 { (task: Task[Int]) =>
task.start.flatMap(_.join) <-> task
}
}
test("task.start.flatMap(id) is cancelable, but the source is memoized") { implicit sc =>
var effect = 0
val task = Task { effect += 1; effect }.delayExecution(1.second).start.flatMap(_.join)
val f = task.runToFuture
sc.tick()
f.cancel()
sc.tick(1.second)
assertEquals(f.value, None)
assertEquals(effect, 1)
}
test("task.start is stack safe") { implicit sc =>
var task: Task[Any] = Task.evalAsync(1)
for (_ <- 0 until 5000) task = task.start.flatMap(_.join)
val f = task.runToFuture
sc.tick()
assertEquals(f.value, Some(Success(1)))
}
testAsync("task.start shares Local.Context with fibers") { _ =>
import monix.execution.Scheduler.Implicits.global
implicit val opts = Task.defaultOptions.enableLocalContextPropagation
val task = for {
local <- TaskLocal(0)
_ <- local.write(100)
v1 <- local.read
f <- (Task.shift *> local.read <* local.write(200)).start
// Here, before joining, reads are nondeterministic
v2 <- f.join
v3 <- local.read
} yield (v1, v2, v3)
for (v <- task.runToFutureOpt) yield {
assertEquals(v, (100, 100, 200))
}
}
test("task.start is stack safe") { implicit sc =>
val count = if (Platform.isJVM) 10000 else 1000
def loop(n: Int): Task[Unit] =
if (n > 0)
Task(n - 1).start.flatMap(_.join).flatMap(loop)
else
Task.unit
val f = loop(count).runToFuture; sc.tick()
assertEquals(f.value, Some(Success(())))
}
test("task.start executes asynchronously") { implicit sc =>
val task = Task(1 + 1).start.flatMap(_.join)
val f = task.runToFuture
assertEquals(f.value, None)
sc.tick()
assertEquals(f.value, Some(Success(2)))
}
}
| alexandru/monifu | monix-eval/shared/src/test/scala/monix/eval/TaskStartSuite.scala | Scala | apache-2.0 | 2,802 |
package com.mesosphere.cosmos.rpc.v1.model
import com.mesosphere.cosmos.finch.DispatchingMediaTypedEncoder
import com.mesosphere.cosmos.finch.MediaTypedEncoder
import com.mesosphere.cosmos.rpc.MediaTypes
import com.mesosphere.universe
import io.circe.Decoder
import io.circe.Encoder
import io.circe.JsonObject
import io.circe.generic.semiauto.deriveDecoder
import io.circe.generic.semiauto.deriveEncoder
case class ServiceUpdateResponse(
`package`: universe.v4.model.PackageDefinition,
resolvedOptions: JsonObject,
marathonDeploymentId: String
)
object ServiceUpdateResponse {
implicit val encode: Encoder[ServiceUpdateResponse] = deriveEncoder
implicit val decode: Decoder[ServiceUpdateResponse] = deriveDecoder
implicit val mediaTypedEncoder: MediaTypedEncoder[ServiceUpdateResponse] =
MediaTypedEncoder(MediaTypes.ServiceUpdateResponse)
implicit val dispatchingMediaTypedEncoder: DispatchingMediaTypedEncoder[ServiceUpdateResponse] =
DispatchingMediaTypedEncoder(MediaTypes.ServiceUpdateResponse)
}
| dcos/cosmos | cosmos-common/src/main/scala/com/mesosphere/cosmos/rpc/v1/model/ServiceUpdateResponse.scala | Scala | apache-2.0 | 1,027 |
package example
import scalaz._
import Scalaz._
object SafeVal {
sealed trait SafeVal[+T]
case class Val[T](x:T) extends SafeVal[T]
case class Err(msg:String) extends SafeVal[Nothing]
implicit object safeValMonadPlus extends MonadPlus[SafeVal] {
override def point[A](a: => A):SafeVal[A] = Val(a)
override def bind[A, B](sa: SafeVal[A])(f: A => SafeVal[B]): SafeVal[B] = sa match {
case Err(msg) => Err(msg)
case Val(a) => f(a)
}
override def empty[A]:SafeVal[A] = Err("divided by 0")
override def plus[A](x:SafeVal[A],y: => SafeVal[A]):SafeVal[A] = x match {
case Err(_) => y
case Val(_) => x
}
}
} | luzhuomi/learn_you_a_scala_for_great_good | examples/monad/src/main/scala/example/SafeVal.scala | Scala | apache-2.0 | 638 |
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.tools.nsc.transform.async
import scala.collection.mutable
import scala.tools.nsc.transform.{Transform, TypingTransformers}
import scala.reflect.internal.util.{SourceFile, NoSourceFile}
abstract class AsyncPhase extends Transform with TypingTransformers with AnfTransform with Lifter with LiveVariables {
self =>
import global._
private[async] var currentTransformState: AsyncTransformState = _
private[async] val asyncNames = new AsyncNames[global.type](global)
protected[async] val tracing = new Tracing
val phaseName: String = "async"
override def enabled: Boolean = settings.async
private final case class AsyncAttachment(awaitSymbol: Symbol, postAnfTransform: Block => Block,
stateDiagram: ((Symbol, Tree) => Option[String => Unit]),
allowExceptionsToPropagate: Boolean) extends PlainAttachment
// Optimization: avoid the transform altogether if there are no async blocks in a unit.
private val sourceFilesToTransform = perRunCaches.newSet[SourceFile]()
private val awaits: mutable.Set[Symbol] = perRunCaches.newSet[Symbol]()
/**
* Mark the given method as requiring an async transform.
* Refer to documentation in the public API that forwards to this method in src/reflect/scala/reflect/api/Internals.scala
*/
final def markForAsyncTransform(owner: Symbol, method: DefDef, awaitMethod: Symbol,
config: Map[String, AnyRef]): DefDef = {
val pos = owner.pos
if (!settings.async)
reporter.warning(pos, s"${settings.async.name} must be enabled for async transformation.")
sourceFilesToTransform += pos.source
val postAnfTransform = config.getOrElse("postAnfTransform", (x: Block) => x).asInstanceOf[Block => Block]
val stateDiagram = config.getOrElse("stateDiagram", (sym: Symbol, tree: Tree) => None).asInstanceOf[(Symbol, Tree) => Option[String => Unit]]
val allowExceptionsToPropagate = config.contains("allowExceptionsToPropagate")
method.updateAttachment(new AsyncAttachment(awaitMethod, postAnfTransform, stateDiagram, allowExceptionsToPropagate))
// Wrap in `{ expr: Any }` to force value class boxing before calling `completeSuccess`, see test/async/run/value-class.scala
deriveDefDef(method) { rhs =>
Block(Apply(gen.mkAttributedRef(definitions.Predef_locally), rhs :: Nil), Literal(Constant(())))
}.updateAttachment(ChangeOwnerAttachment(owner))
}
def newTransformer(unit: CompilationUnit): AstTransformer = new AsyncTransformer(unit)
private def compileTimeOnlyPrefix: String = "[async] "
/** Should refchecks defer reporting `@compileTimeOnly` errors for `sym` and instead let this phase issue the warning
* if they survive the async tranform? */
private[scala] def deferCompileTimeOnlyError(sym: Symbol): Boolean = settings.async && {
awaits.contains(sym) || {
val msg = sym.compileTimeOnlyMessage.getOrElse("")
val shouldDefer =
msg.startsWith(compileTimeOnlyPrefix) || (sym.name == nme.await) && msg.contains("must be enclosed") && sym.owner.info.member(nme.async) != NoSymbol
if (shouldDefer) awaits += sym
shouldDefer
}
}
// TOOD: figure out how to make the root-level async built-in macro sufficiently configurable:
// replace the ExecutionContext implicit arg with an AsyncContext implicit that also specifies the type of the Future/Awaitable/Node/...?
final class AsyncTransformer(unit: CompilationUnit) extends TypingTransformer(unit) {
private lazy val liftableMap = new mutable.AnyRefMap[Symbol, (Symbol, List[Tree])]()
override def transformUnit(unit: CompilationUnit): Unit = {
if (settings.async) {
// NoSourceFile can happen for, e.g., toolbox compilation; overestimate by always transforming them. See test/async/jvm/toolbox.scala
val shouldTransform = unit.source == NoSourceFile || sourceFilesToTransform.contains(unit.source)
if (shouldTransform) super.transformUnit(unit)
if (awaits.exists(_.isInitialized)) {
unit.body.foreach {
case tree: RefTree if tree.symbol != null && awaits.contains(tree.symbol) =>
val sym = tree.symbol
val msg = sym.compileTimeOnlyMessage.getOrElse(s"`${sym.decodedName}` must be enclosed in an `async` block").stripPrefix(compileTimeOnlyPrefix)
global.reporter.error(tree.pos, msg)
case _ =>
}
}
}
}
// Together, these transforms below target this tree shaps
// {
// class $STATE_MACHINE extends ... {
// def $APPLY_METHOD(....) = {
// ...
// }.updateAttachment(AsyncAttachment(...))
// }
// }
//
// The RHS of the method is transformed into a state machine with that transformation tailored by the
// attached `FutureSystem`. Local val/var/def/class/object trees that are referred to from multiple states
// are lifted into members of the enclosing class.
override def transform(tree: Tree): Tree =
super.transform(tree) match {
case cd: ClassDef if liftableMap.contains(cd.symbol) =>
val (applySym, liftedTrees) = liftableMap.remove(cd.symbol).get
val liftedSyms = liftedTrees.iterator.map(_.symbol).toSet
val cd1 = atOwner(cd.symbol) {
deriveClassDef(cd)(impl => {
deriveTemplate(impl)(liftedTrees ::: _)
})
}
assert(localTyper.context.owner == cd.symbol.owner, "local typer context's owner must be ClassDef symbol's owner")
val withFields = new UseFields(localTyper, cd.symbol, applySym, liftedSyms, NoSymbol).transform(cd1)
withFields
case dd: DefDef if dd.hasAttachment[AsyncAttachment] =>
val asyncAttachment = dd.getAndRemoveAttachment[AsyncAttachment].get
val asyncBody = (dd.rhs: @unchecked) match {
case blk@Block(Apply(qual, body :: Nil) :: Nil, Literal(Constant(()))) => body
}
atOwner(dd, dd.symbol) {
val trSym = dd.vparamss.head.last.symbol
val selfSym = if (dd.symbol.owner.isTerm) dd.vparamss.head.head.symbol else NoSymbol
val saved = currentTransformState
currentTransformState = new AsyncTransformState(
asyncAttachment.awaitSymbol,
asyncAttachment.postAnfTransform,
asyncAttachment.stateDiagram,
asyncAttachment.allowExceptionsToPropagate,
this,
selfSym,
trSym,
asyncBody.tpe,
asyncNames)
try {
val (newRhs, liftedTrees) = asyncTransform(asyncBody)
liftableMap(currentTransformState.stateMachineClass) = (dd.symbol, liftedTrees)
val liftedSyms = liftedTrees.iterator.map(_.symbol).toSet
val withFields = new UseFields(localTyper, currentTransformState.stateMachineClass, dd.symbol, liftedSyms, selfSym).transform(newRhs)
deriveDefDef(dd)(_ => withFields)
} finally {
currentTransformState = saved
}
}
case tree =>
tree
}
private def asyncTransform(asyncBody: Tree): (Tree, List[Tree]) = {
val transformState = currentTransformState
import transformState.applySym
val asyncPos = asyncBody.pos
// We mark whether each sub-tree of `asyncBody` that do or do not contain an await in thus pre-processing pass.
// The ANF transform can then efficiently query this to selectively transform the tree.
markContainsAwait(asyncBody)
// Transform to A-normal form:
// - no await calls in qualifiers or arguments,
// - if/match only used in statement position.
val anfTree: Block = transformState.postAnfTransform(new AnfTransformer(localTyper).apply(asyncBody))
// The ANF transform re-parents some trees, so the previous traversal to mark ancestors of
// await is no longer reliable. Clear previous results and run it again for use in the `buildAsyncBlock`.
cleanupContainsAwaitAttachments(anfTree)
markContainsAwait(anfTree)
val asyncBlock = buildAsyncBlock(anfTree)
val liftedFields: List[Tree] = liftables(asyncBlock.asyncStates)
// Null out lifted fields become unreachable at each state.
val nullOut = true
if (nullOut) {
for ((state, (preNulls, postNulls)) <- fieldsToNullOut(asyncBlock.asyncStates, asyncBlock.asyncStates.last, liftedFields)) {
val asyncState = asyncBlock.asyncStates.find(_.state == state).get
if (asyncState.hasNonTerminalNextState)
asyncState.insertNullAssignments(preNulls.iterator, postNulls.iterator)
}
}
// Assemble the body of the apply method, which is dispactches on the current state id.
val applyBody = atPos(asyncPos)(asyncBlock.onCompleteHandler)
// Logging
if ((settings.isDebug && shouldLogAtThisPhase))
logDiagnostics(anfTree, asyncBlock, asyncBlock.asyncStates.map(_.toString))
// Offer async frontends a change to produce the .dot diagram
transformState.dotDiagram(applySym, asyncBody).foreach(f => f(asyncBlock.toDot))
cleanupContainsAwaitAttachments(applyBody)
(applyBody, liftedFields)
}
// Adjust the tree to:
// - lifted local variables are entered into the scope of the state machine class
// - references to them are rewritten as referencs to the fields.
// - the rhs of ValDefs that initialize such fields is turned into an assignment to the field
private class UseFields(initLocalTyper: analyzer.Typer, stateMachineClass: Symbol,
applySym: Symbol, liftedSyms: Set[Symbol], selfSym: Symbol) extends explicitOuter.OuterPathTransformer(initLocalTyper) {
private def fieldSel(tree: Tree) = {
assert(currentOwner != NoSymbol, "currentOwner cannot be NoSymbol")
val outerOrThis =
if (selfSym != NoSymbol)
gen.mkAttributedIdent(selfSym)
else if (stateMachineClass == currentClass)
gen.mkAttributedThis(stateMachineClass)
else {
// These references need to be selected from an outer reference, because explicitouter
// has already run we must perform this transform explicitly here.
tree.symbol.makeNotPrivate(tree.symbol.owner)
outerPath(outerValue, currentClass.outerClass, stateMachineClass)
}
atPos(tree.pos)(Select(outerOrThis.setType(stateMachineClass.tpe), tree.symbol).setType(tree.symbol.tpe))
}
override def transform(tree: Tree): Tree = tree match {
case ValDef(_, _, _, rhs) if liftedSyms(tree.symbol) && currentOwner == applySym =>
// Drop the lifted definitions from the apply method
val rhs1 = transform(rhs.changeOwner(tree.symbol, currentOwner))
deriveTree(rhs1, definitions.UnitTpe)(t => treeCopy.Assign(rhs1, fieldSel(tree), adapt(t, tree.symbol.tpe)))
case _: DefTree if liftedSyms(tree.symbol) && currentOwner == applySym =>
// Drop the lifted definitions from the apply method
EmptyTree
case md: MemberDef =>
if (currentOwner == stateMachineClass) {
if (liftedSyms(tree.symbol)) {
stateMachineClass.info.decls.enter(md.symbol)
super.transform(tree)
} else if (md.symbol == applySym || md.symbol == stateMachineClass) {
super.transform(tree)
} else tree
} else super.transform(tree)
case Assign(i @ Ident(name), rhs) if liftedSyms(i.symbol) =>
treeCopy.Assign(tree, fieldSel(i), adapt(transform(rhs), i.symbol.tpe))
case Ident(name) if liftedSyms(tree.symbol) =>
fieldSel(tree).setType(tree.tpe)
case _: TypeTree =>
tree
case _ =>
super.transform(tree)
}
// Use localTyper to adapt () to BoxedUnit in `val ifRes: Object; if (cond) "" else ()`
private def adapt(tree: Tree, pt: Type): Tree = localTyper.typed(tree, pt)
}
private def logDiagnostics(anfTree: Tree, block: AsyncBlock, states: Seq[String]): Unit = {
val pos = currentTransformState.applySym.pos
val location = try pos.source.path catch { case _: UnsupportedOperationException => pos.toString }
inform(s"In file '$location':")
inform(s"ANF transform expands to:\\n $anfTree")
states foreach (s => inform(s))
inform("===== DOT =====")
inform(block.toDot)
}
}
}
| scala/scala | src/compiler/scala/tools/nsc/transform/async/AsyncPhase.scala | Scala | apache-2.0 | 12,957 |
/* Copyright (C) 2008-2014 University of Massachusetts Amherst.
This file is part of "FACTORIE" (Factor graphs, Imperative, Extensible)
http://factorie.cs.umass.edu, http://github.com/factorie
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 cc.factorie.directed
import cc.factorie.infer._
import cc.factorie._
import scala.collection.mutable.{HashMap, HashSet, ArrayBuffer}
import cc.factorie.variable._
import cc.factorie.model.Factor
/** A GibbsSampler that can also collapse some Parameters. */
class CollapsedGibbsSampler(collapse:Iterable[Var], val model:DirectedModel)(implicit val random: scala.util.Random) extends Sampler[Iterable[MutableVar]] {
var debug = false
makeNewDiffList = false // override default in cc.factorie.Sampler
var temperature = 1.0 // TODO Currently ignored?
val handlers = new ArrayBuffer[CollapsedGibbsSamplerHandler]
def defaultHandlers = Seq(
PlatedGateDiscreteCollapsedGibbsSamplerHandler,
PlatedGateGategoricalCollapsedGibbsSamplerHandler,
GateCollapsedGibbsSamplerHandler,
//PlatedMixtureChoiceCollapsedDirichletGibbsSamplerHandler,
GeneratedVarCollapsedGibbsSamplerHandler
)
handlers ++= defaultHandlers
val cacheClosures = true
val closures = new HashMap[Var, CollapsedGibbsSamplerClosure]
private val collapsed = new HashSet[Var] ++ collapse
// Initialize collapsed parameters specified in constructor
val collapser = new Collapse(model)
collapse.foreach(v => collapser(Seq(v)))
// TODO We should provide an interface that handlers can use to query whether or not a particular variable was collapsed or not?
def isCollapsed(v:Var): Boolean = collapsed.contains(v)
def process1(v:Iterable[MutableVar]): DiffList = {
//assert(!v.exists(_.isInstanceOf[CollapsedVar])) // We should never be sampling a CollapsedVariable
val d = newDiffList
// If we have a cached closure, just use it and return
if (cacheClosures && v.size == 1 && closures.contains(v.head)) {
closures(v.head).sample(d)
} else {
// Get factors, no guarantees about their order
val factors: Iterable[Factor] = model.factors(v)
//println("CollapsedGibbsSampler.process1 factors = "+factors.map(_.template.getClass).mkString)
var done = false
val handlerIterator = handlers.iterator
while (!done && handlerIterator.hasNext) {
val closure = handlerIterator.next().sampler(v, factors, this)
if (closure ne null) {
done = true
closure.sample(d)
if (cacheClosures && v.size == 1) {
closures(v.head) = closure
}
}
}
if (!done) throw new Error("CollapsedGibbsSampler: No sampling method found for variable "+v+" with factors "+factors.map(_.factorName).toList.mkString)
}
d
}
/** Convenience for sampling single variable */
def process(v:MutableVar): DiffList = process(Seq(v))
}
trait CollapsedGibbsSamplerHandler {
def sampler(v:Iterable[Var], factors:Iterable[Factor], sampler:CollapsedGibbsSampler)(implicit random: scala.util.Random): CollapsedGibbsSamplerClosure
}
trait CollapsedGibbsSamplerClosure {
def sample(implicit d:DiffList = null): Unit
}
object GeneratedVarCollapsedGibbsSamplerHandler extends CollapsedGibbsSamplerHandler {
def sampler(v:Iterable[Var], factors:Iterable[Factor], sampler:CollapsedGibbsSampler)(implicit random: scala.util.Random): CollapsedGibbsSamplerClosure = {
if (v.size != 1 || factors.size != 1) return null
val pFactor = factors.collectFirst({case f:DirectedFactor => f}) // TODO Yipes! Clean up these tests!
if (pFactor == None) return null
// Make sure all parents are collapsed?
//if (!pFactor.get.variables.drop(1).asInstanceOf[Seq[Parameter]].forall(v => sampler.collapsedMap.contains(v))) return null
new Closure(pFactor.get)
}
class Closure(val factor:DirectedFactor)(implicit random: scala.util.Random) extends CollapsedGibbsSamplerClosure {
def sample(implicit d:DiffList = null): Unit = {
factor.updateCollapsedParents(-1.0)
val variable = factor.child.asInstanceOf[MutableVar]
variable.set(factor.sampledValue.asInstanceOf[variable.Value])
factor.updateCollapsedParents(1.0)
// TODO Consider whether we should be passing values rather than variables to updateChildStats
// TODO What about collapsed children?
}
}
}
// TODO This the "one outcome" and "one outcome parent" case for now.
object GateCollapsedGibbsSamplerHandler extends CollapsedGibbsSamplerHandler {
def sampler(v:Iterable[Var], factors:Iterable[Factor], sampler:CollapsedGibbsSampler)(implicit random: scala.util.Random): CollapsedGibbsSamplerClosure = {
if (v.size != 1 || factors.size != 2) return null
//println("GateCollapsedGibbsSamplerHander: "+factors.map(_.asInstanceOf[Family#Factor].family.getClass).mkString)
//val gFactor = factors.collectFirst({case f:Discrete.Factor if (f.family == Discrete) => f}) // TODO Should be any DiscreteGeneratingFamily#Factor => f
val gFactor = factors.collectFirst({case f:DiscreteGeneratingFactor => f}) // TODO Should be any DiscreteGeneratingFamily#Factor => f
val mFactor = factors.collectFirst({case f:MixtureFactor => f})
if (gFactor == None || mFactor == None) {
//println("GateCollapsedGibbsSamplerHander: "+gFactor+" "+mFactor)
return null
}
//println("GateCollapsedGibbsSamplerHandler gFactor "+gFactor.get.family.getClass)
//println("GateCollapsedGibbsSamplerHandler mFactor "+mFactor.get.family.getClass)
//println("GateCollapsedGibbsSamplerHandler factors equal "+(mFactor.get == gFactor.get))
new Closure(gFactor.get, sampler.isCollapsed(gFactor.get.parents.head), mFactor.get, sampler.isCollapsed(mFactor.get.parents.head))
}
class Closure(val gFactor:DiscreteGeneratingFactor, val gCollapsed:Boolean, val mFactor:MixtureFactor, val mCollapsed:Boolean)(implicit random: scala.util.Random) extends CollapsedGibbsSamplerClosure
{
def sample(implicit d:DiffList = null): Unit = {
val gate = mFactor.gate //family.child(gFactor)
//val gateParent = gFactor._2
// Remove sufficient statistics from collapsed dependencies
if (gCollapsed) gFactor.updateCollapsedParents(-1.0)
if (mCollapsed) mFactor.updateCollapsedParents(-1.0)
// Calculate distribution of new value
val mStat = mFactor.currentStatistics // TODO Are these two still necessary?
val gStat = gFactor.currentStatistics
val domainSize = gate.domain.size
val distribution = new Array[Double](domainSize)
var sum = 0.0
//println("GateCollapsedGibbsSamplerHandler gFactor "+gFactor.family.getClass)
//println("GateCollapsedGibbsSamplerHandler mFactor "+mFactor.family.getClass)
for (i <- 0 until domainSize) {
//throw new Error
distribution(i) = /*gStat.prValue(i) * */
gFactor.prValue(i) // * mFactor.prChoosing(i) // TODO Re-implement these methods so that they don't allocate new Statistics objects with each call
throw new Error("Not yet implemented")
sum += distribution(i)
}
assert(sum == sum, "Distribution sum is NaN")
assert(sum != Double.PositiveInfinity, "Distrubtion sum is infinity.")
// Sample
//println("MixtureChoiceCollapsedGibbsSamplerHandler outcome="+outcome+" sum="+sum+" distribution="+(distribution.mkString(",")))
// sum can be zero for a new word in the domain and a non-collapsed growable Proportions has not yet placed non-zero mass there
if (sum == 0) gate.set(random.nextInt(domainSize))(null)
else gate.set(cc.factorie.maths.nextDiscrete(distribution, sum)(random))(null)
// Put back sufficient statistics of collapsed dependencies
if (gCollapsed) gFactor.updateCollapsedParents(1.0)
if (mCollapsed) mFactor.updateCollapsedParents(1.0)
}
}
}
object PlatedGateDiscreteCollapsedGibbsSamplerHandler extends CollapsedGibbsSamplerHandler {
def sampler(v:Iterable[Var], factors:Iterable[Factor], sampler:CollapsedGibbsSampler)(implicit random: scala.util.Random): CollapsedGibbsSamplerClosure = {
if (v.size != 1 || factors.size != 2) return null
val gFactor = factors.collectFirst({case f:PlatedDiscrete.Factor => f}) // TODO Should be any DiscreteGeneratingFamily#Factor => f
val mFactor = factors.collectFirst({case f:PlatedDiscreteMixture.Factor => f})
if (gFactor == None || mFactor == None) return null
assert(gFactor.get._1 == mFactor.get._3)
new Closure(sampler, gFactor.get, mFactor.get)
}
class Closure(val sampler:CollapsedGibbsSampler, val gFactor:PlatedDiscrete.Factor, val mFactor:PlatedDiscreteMixture.Factor)(implicit random: scala.util.Random) extends CollapsedGibbsSamplerClosure
{
def sample(implicit d:DiffList = null): Unit = {
val gates = mFactor._3.asInstanceOf[DiscreteSeqVariable]
val domainSize = gates(0).dim1 // domain.size
val distribution = new Array[Double](domainSize)
val gParent = gFactor._2.asInstanceOf[ProportionsVariable]
val gParentCollapsed = sampler.isCollapsed(gParent)
val mixture = mFactor._2.asInstanceOf[Mixture[ProportionsVariable]]
val mixtureCollapsed = sampler.isCollapsed(mixture)
for (index <- 0 until gates.length) {
val outcomeIntValue = mFactor._1(index).intValue
// Remove sufficient statistics from collapsed dependencies
var z: Int = gates(index).intValue
if (gParentCollapsed) gParent.incrementMasses(z, -1.0)
if (mixtureCollapsed) mixture(z).incrementMasses(outcomeIntValue, -1.0)
// Calculate distribution of new value
//val mStat = mFactor.statistics
//val gStat = gFactor.statistics
var sum = 0.0
java.util.Arrays.fill(distribution, 0.0)
var i = 0
while (i < domainSize) {
distribution(i) = gParent.value(i) * mixture(i).value(outcomeIntValue)
sum += distribution(i)
i += 1
}
assert(sum == sum, "Distribution sum is NaN")
assert(sum != Double.PositiveInfinity, "Distrubtion sum is infinity.")
// Sample
// sum can be zero for a new word in the domain and a non-collapsed growable Proportions has not yet placed non-zero mass there
if (sum == 0) z = random.nextInt(domainSize)
else z = cc.factorie.maths.nextDiscrete(distribution, sum)(random)
gates.set(index, z)(null)
// Put back sufficient statistics of collapsed dependencies
if (gParentCollapsed) gParent.incrementMasses(z, 1.0)
if (mixtureCollapsed) mixture(z).incrementMasses(outcomeIntValue, 1.0)
}
}
}
}
object PlatedGateGategoricalCollapsedGibbsSamplerHandler extends CollapsedGibbsSamplerHandler {
def sampler(v:Iterable[Var], factors:Iterable[Factor], sampler:CollapsedGibbsSampler)(implicit random: scala.util.Random): CollapsedGibbsSamplerClosure = {
if (v.size != 1 || factors.size != 2) return null
val gFactor = factors.collectFirst({case f:PlatedDiscrete.Factor => f}) // TODO Should be any DiscreteGeneratingFamily#Factor => f
val mFactor = factors.collectFirst({case f:PlatedCategoricalMixture.Factor => f})
if (gFactor == None || mFactor == None) return null
assert(gFactor.get._1 == mFactor.get._3)
new Closure(sampler, gFactor.get, mFactor.get)
}
class Closure(val sampler:CollapsedGibbsSampler, val gFactor:PlatedDiscrete.Factor, val mFactor:PlatedCategoricalMixture.Factor)(implicit random: scala.util.Random) extends CollapsedGibbsSamplerClosure
{
def sample(implicit d:DiffList = null): Unit = {
val gates = mFactor._3.asInstanceOf[DiscreteSeqVariable]
val domainSize = gates(0).dim1 // domain.size
val distribution = new Array[Double](domainSize)
val gParent = gFactor._2.asInstanceOf[ProportionsVariable]
val gParentCollapsed = sampler.isCollapsed(gParent)
val mixture = mFactor._2.asInstanceOf[Mixture[ProportionsVariable]]
val mixtureCollapsed = sampler.isCollapsed(mixture)
for (index <- 0 until gates.length) {
val outcomeIntValue = mFactor._1(index).intValue
// Remove sufficient statistics from collapsed dependencies
var z: Int = gates(index).intValue
if (gParentCollapsed) gParent.incrementMasses(z, -1.0)
if (mixtureCollapsed) mixture(z).incrementMasses(outcomeIntValue, -1.0)
// Calculate distribution of new value
//val mStat = mFactor.statistics
//val gStat = gFactor.statistics
var sum = 0.0
java.util.Arrays.fill(distribution, 0.0)
var i = 0
while (i < domainSize) {
distribution(i) = gParent.value(i) * mixture(i).value(outcomeIntValue)
sum += distribution(i)
i += 1
}
assert(sum == sum, "Distribution sum is NaN")
assert(sum != Double.PositiveInfinity, "Distrubtion sum is infinity.")
// Sample
// sum can be zero for a new word in the domain and a non-collapsed growable Proportions has not yet placed non-zero mass there
if (sum == 0) z = random.nextInt(domainSize)
else z = cc.factorie.maths.nextDiscrete(distribution, sum)(random)
gates.set(index, z)(null)
// Put back sufficient statistics of collapsed dependencies
if (gParentCollapsed) gParent.incrementMasses(z, 1.0)
if (mixtureCollapsed) mixture(z).incrementMasses(outcomeIntValue, 1.0)
}
}
}
}
/*
object PlatedMixtureChoiceCollapsedDirichletGibbsSamplerHandler extends CollapsedGibbsSamplerHandler {
def sampler(v:Iterable[Variable], factors:Seq[Factor], sampler:CollapsedGibbsSampler): CollapsedGibbsSamplerClosure = {
if (v.size != 1) return null
v.head match {
case v: PlatedMixtureChoiceVar => {
require(v.outcomes.size == 1) // TODO write code to handle more outcomes.
if (! v.outcomes.head.isInstanceOf[PlatedDiscreteMixtureVar]) return null
require(factors.size == 2, "factors size = "+factors.size)
//println(factors(0)); println(factors(1))
val choiceFactor = factors(1).copy(sampler.collapsedMap).asInstanceOf[PlatedDiscreteTemplate#Factor]
val outcomeFactor = factors(0).copy(sampler.collapsedMap).asInstanceOf[PlatedDiscreteMixtureTemplate#Factor]
if (! outcomeFactor._2.isInstanceOf[CollapsedFiniteMixture[DirichletMultinomial]]) return null
val choiceParent = choiceFactor._2
require(outcomeFactor.numVariables == 3)
require(outcomeFactor.variable(1).isInstanceOf[Parameter])
require(outcomeFactor.variable(2).isInstanceOf[PlatedMixtureChoiceVar])
val outcomeParent = outcomeFactor.variable(1)
new Closure(v, v.outcomes.head.asInstanceOf[PlatedDiscreteMixtureVar],
choiceParent match { case cp:DirichletMultinomial => cp case _ => null.asInstanceOf[DirichletMultinomial] },
outcomeParent match { case cp:CollapsedFiniteMixture[DirichletMultinomial] => cp case _ => null.asInstanceOf[CollapsedFiniteMixture[DirichletMultinomial]] })
}
case _ => null
}
}
class Closure(val choice:PlatedMixtureChoiceVar, val outcome:PlatedDiscreteMixtureVar,
val collapsedChoiceParent: DirichletMultinomial, val collapsedOutcomeParent:CollapsedFiniteMixture[DirichletMultinomial])
extends CollapsedGibbsSamplerClosure
{
assert(collapsedChoiceParent ne null)
assert(collapsedOutcomeParent ne null)
def sample(implicit d:DiffList = null): Unit = {
val choiceParent = collapsedChoiceParent
// Calculate distribution of new value
val domainSize = choice.domain.elementDomain.size
val seqSize = choice.length
val distribution = new Array[Double](domainSize)
forIndex(seqSize)(seqIndex => {
// Remove sufficient statistics from collapsed dependencies
var choiceIntValue = choice.intValue(seqIndex)
if (collapsedChoiceParent ne null) collapsedChoiceParent.incrementMasses(choiceIntValue, -1.0)
if (collapsedOutcomeParent ne null) collapsedOutcomeParent(choiceIntValue).incrementMasses(outcome.intValue(seqIndex), -1.0)
var sum = 0.0
forIndex(domainSize)(i => {
distribution(i) = collapsedChoiceParent(i) * collapsedOutcomeParent(i).pr(outcome.intValue(seqIndex))
sum += distribution(i)
})
assert(sum == sum, "Distribution sum is NaN")
assert(sum != Double.PositiveInfinity, "Distrubtion sum is infinity.")
// println("MixtureChoiceCollapsedDirichletGibbsSamplerHandler outcome="+outcome+" sum="+sum+" distribution="+(distribution.mkString(",")))
// Sample
// sum can be zero for a new word in the domain and a non-collapsed growable Proportions has not yet placed non-zero mass there
if (sum == 0) choiceIntValue = cc.factorie.random.nextInt(domainSize)
else choiceIntValue = cc.factorie.maths.nextDiscrete(distribution, sum)(cc.factorie.random)
choice.update(seqIndex, choiceIntValue)
// Put back sufficient statitics of collapsed dependencies
if (collapsedChoiceParent ne null) collapsedChoiceParent.incrementMasses(choiceIntValue, 1.0)
if (collapsedOutcomeParent ne null) collapsedOutcomeParent(choiceIntValue).incrementMasses(outcome.intValue(seqIndex), 1.0)
}
)}
}
}
*/
| zxsted/factorie | src/main/scala/cc/factorie/directed/CollapsedGibbsSampler.scala | Scala | apache-2.0 | 17,901 |
/*
* Copyright 2016 The BigDL Authors.
*
* 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.intel.analytics.bigdl.nn
import com.intel.analytics.bigdl.nn.abstractnn.TensorModule
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.utils.RandomGenerator._
import com.intel.analytics.bigdl.utils.{T, Table}
import scala.reflect.ClassTag
/**
* Outputs the Euclidean distance of the input to outputSize centers
* @param inputSize inputSize
* @param outputSize outputSize
* @tparam T Numeric type. Only support float/double now
*/
@SerialVersionUID(1438188993718795033L)
class Euclidean[T: ClassTag](val inputSize: Int, val outputSize: Int,
val fastBackward: Boolean = true)(implicit ev: TensorNumeric[T]) extends TensorModule[T]{
val weight = Tensor(inputSize, outputSize)
val gradWeight = Tensor(inputSize, outputSize)
// buffer
var inputBuffer = Tensor[T]()
var weightBuffer = Tensor[T]()
val repeatBuffer = Tensor[T]()
val divBuffer = Tensor[T]()
val sumBuffer = Tensor[T]()
reset()
override def reset(): Unit = {
val stdv = 1 / math.sqrt(weight.size(1))
weight.apply1(_ => ev.fromType[Double](RNG.uniform(-stdv, stdv)))
}
override def updateOutput(input: Tensor[T]): Tensor[T] = {
require(input.dim() == 1 || input.dim() == 2,
"Euclidean: " + ErrorInfo.constrainInputAsVectorOrBatch)
if (input.dim() == 1) {
if (input.isContiguous()) {
inputBuffer = input.view(inputSize, 1)
} else {
inputBuffer = input.reshape(Array(inputSize, 1))
}
inputBuffer.expandAs(weight)
repeatBuffer.resizeAs(inputBuffer).copy(inputBuffer)
repeatBuffer.add(ev.fromType(-1), weight)
repeatBuffer.norm(output, 2, 1)
output.resize(outputSize)
} else if (input.dim() == 2) {
val batchSize = input.size(1)
if (input.isContiguous()) {
inputBuffer = input.view(batchSize, inputSize, 1)
} else {
inputBuffer = input.reshape(Array(batchSize, inputSize, 1))
}
inputBuffer.expand(Array(batchSize, inputSize, outputSize))
repeatBuffer.resizeAs(inputBuffer).copy(inputBuffer)
weightBuffer = weight.view(1, inputSize, outputSize)
weightBuffer.expandAs(repeatBuffer)
repeatBuffer.add(ev.fromType(-1), weightBuffer)
repeatBuffer.norm(output, 2, 2)
output.resize(batchSize, outputSize)
}
output
}
override def updateGradInput(input: Tensor[T], gradOutput: Tensor[T]): Tensor[T] = {
require(input.dim() == 1 || input.dim() == 2,
"Euclidean: " + ErrorInfo.constrainInputAsVectorOrBatch)
if (!fastBackward) {
updateOutput(input)
}
// to prevent div by zero (NaN) bugs
inputBuffer.resizeAs(output).copy(output).add(ev.fromType(0.0000001))
divBuffer.resizeAs(gradOutput).cdiv(gradOutput, inputBuffer)
if (input.dim() == 1) {
divBuffer.resize(1, outputSize)
divBuffer.expandAs(weight)
repeatBuffer.cmul(divBuffer)
gradInput.sum(repeatBuffer, 2)
gradInput.resizeAs(input)
} else if (input.dim() == 2) {
val batchSize = input.size(1)
divBuffer.resize(batchSize, 1, outputSize)
divBuffer.expand(Array(batchSize, inputSize, outputSize))
repeatBuffer.cmul(divBuffer)
gradInput.sum(repeatBuffer, 3)
gradInput.resizeAs(input)
}
gradInput
}
override def accGradParameters(input: Tensor[T], gradOutput: Tensor[T],
scale: Double = 1.0): Unit = {
require(input.dim() == 1 || input.dim() == 2,
"Euclidean: " + ErrorInfo.constrainInputAsVectorOrBatch)
if (input.dim() == 1) {
gradWeight.add(ev.fromType(-scale), repeatBuffer)
} else if (input.dim() == 2) {
sumBuffer.sum(repeatBuffer, 1)
sumBuffer.resizeAs(weight)
gradWeight.add(ev.fromType(-scale), sumBuffer)
}
}
override def toString(): String = {
s"${getPrintName}($inputSize, $outputSize)"
}
override def zeroGradParameters(): Unit = {
gradWeight.zero()
}
override def clearState() : this.type = {
super.clearState()
inputBuffer.set()
weightBuffer.set()
repeatBuffer.set()
divBuffer.set()
sumBuffer.set()
this
}
override def parameters(): (Array[Tensor[T]], Array[Tensor[T]]) = {
(Array(this.weight), Array(this.gradWeight))
}
override def getParametersTable(): Table = {
T(getName() -> T("weight" -> weight, "gradWeight" -> gradWeight))
}
override def canEqual(other: Any): Boolean = other.isInstanceOf[Euclidean[T]]
override def equals(other: Any): Boolean = other match {
case that: Euclidean[T] =>
super.equals(that) &&
(that canEqual this) &&
weight == that.weight &&
gradWeight == that.gradWeight &&
inputSize == that.inputSize &&
outputSize == that.outputSize &&
fastBackward == that.fastBackward
case _ => false
}
override def hashCode(): Int = {
def getHashCode(a: Any): Int = if (a == null) 0 else a.hashCode()
val state = Seq(super.hashCode(), weight, gradWeight, inputSize, outputSize, fastBackward)
state.map(getHashCode).foldLeft(0)((a, b) => 31 * a + b)
}
}
object Euclidean {
def apply[@specialized(Float, Double) T: ClassTag](
inputSize: Int,
outputSize: Int,
fastBackward: Boolean = true)(implicit ev: TensorNumeric[T]) : Euclidean[T] = {
new Euclidean[T](inputSize, outputSize, fastBackward)
}
}
| psyyz10/BigDL | spark/dl/src/main/scala/com/intel/analytics/bigdl/nn/Euclidean.scala | Scala | apache-2.0 | 6,214 |
package com.tuplejump.calliope.native
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import com.datastax.driver.core.Row
import com.tuplejump.calliope.{NativeCasBuilder, CasBuilder}
import scala.annotation.implicitNotFound
class NativeCassandraSparkContext(self: SparkContext) {
/**
*
* @param host
* @param port
* @param keyspace
* @param columnFamily
* @param unmarshaller
* @param tm
* @tparam T
* @return
*/
@implicitNotFound(
"No transformer found for Row => ${T}. You must have an implicit method defined of type Row => ${T}"
)
def nativeCassandra[T](host: String, port: String, keyspace: String, columnFamily: String, partitionColumns: List[String])
(implicit unmarshaller: Row => T,
tm: Manifest[T]): RDD[T] = {
val cas = CasBuilder.native.withColumnFamilyAndKeyColumns(keyspace, columnFamily).onHost(host).onPort(port)
this.nativeCassandra[T](cas)
}
/**
*
* @param keyspace
* @param columnFamily
* @param unmarshaller
* @param tm
* @tparam T
* @return
*/
@implicitNotFound(
"No transformer found for Row => ${T}. You must have an implicit method defined of type Row => ${T}"
)
def nativeCassandra[T](keyspace: String, columnFamily: String, partitionColumns: List[String])
(implicit unmarshaller: Row => T, tm: Manifest[T]): RDD[T] = {
val cas = CasBuilder.native.withColumnFamilyAndKeyColumns(keyspace, columnFamily, partitionColumns: _*)
nativeCassandra[T](cas)(unmarshaller, tm)
}
/**
*
* @param cas
* @param unmarshaller
* @param tm
* @tparam T
* @return
*/
@implicitNotFound(
"No transformer found for Row => ${T}. You must have an implicit method defined of type Row => ${T}"
)
def nativeCassandra[T](cas: NativeCasBuilder)(implicit unmarshaller: Row => T, tm: Manifest[T]): RDD[T] = {
new NativeCassandraRDD[T](self, cas, unmarshaller)
}
}
| brenttheisen/calliope-public | src/main/scala/com/tuplejump/calliope/native/NativeCassandraSparkContext.scala | Scala | apache-2.0 | 1,994 |
package org.powlab.jeye.utils
import org.powlab.jeye.core._
import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
/**
* TODO here: перенести в core назвать Attributes
*/
object AttributeUtils {
def has[T: TypeTag](attributes: Array[AttributeBaseInfo]): Boolean = attributes.exists(checkType[T])
def find[T: TypeTag](attributes: Array[AttributeBaseInfo]): Option[T] = attributes.find(checkType[T]).map(_.asInstanceOf[T])
def get[T: TypeTag](attributes: Array[AttributeBaseInfo]): T = find[T](attributes).get
private def checkType[T: TypeTag](value: Any): Boolean = currentMirror.reflect(value).symbol.toType <:< typeOf[T]
}
| powlab/jeye | src/main/scala/org/powlab/jeye/utils/AttributeUtils.scala | Scala | apache-2.0 | 686 |
package me.danielpes.spark.datetime
import org.scalatest.FlatSpec
class PeriodSuite extends FlatSpec {
"A Period" should "be created directly by its fields" in {
val input = Period(7, 6, 5, 4, 3, 2, 1)
assert(input == new Period(90, 446582001L))
assert(input == Period(months = 90, milliseconds = 446582001L))
assert(input == Period.apply(7, 6, 5, 4, 3, 2, 1))
assert(Period() == Period(0, 0, 0, 0, 0, 0, 0))
assert(input.years == 7)
assert(input.months == 6)
assert(input.days == 5)
assert(input.hours == 4)
assert(input.minutes == 3)
assert(input.seconds == 2)
assert(input.milliseconds == 1)
}
"canEqual" should "correctly identify if the equality is possible" in {
assert(Period().canEqual(Period(1, 2)))
assert(!Period(1, 2).canEqual(List(1, 2)))
}
"equals" should "correctly identify equal and different periods" in {
val input = Period(1, 1, 1, 1, 1, 1, 2)
assert(input != List(1L, 1L, 1L, 1L, 1L, 1L, 2L))
assert(Period() == Period())
assert(input != Period())
assert(Period() != input)
assert(input == Period(1, 1, 1, 1, 1, 1, 2))
assert(input != Period(1, 1, 1, 1, 1, 1, 1))
assert(input != Period(2, 1, 1, 1, 1, 1, 1))
}
"Plus operator" should "allow adding two period instances" in {
val input = Period(months = 1)
val expected = Period(months = 5, hours = 3)
val result = input + Period(months = 4, hours = 3)
assert(result == expected)
}
it should "allow adding a period to a java.sql.Date" in {
val period = Period(days = 3, hours = 25)
val date = java.sql.Date.valueOf("2010-01-01")
val expected = new RichDate(date) + period
val result = period + date
assert(result == expected)
}
it should "allow adding a period to a java.sql.Timestamp" in {
val period = Period(days = 3, hours = 25)
val timestamp = java.sql.Timestamp.valueOf("2010-01-01 15:00:00")
val expected = new RichDate(timestamp) + period
val result = period + timestamp
assert(result == expected)
}
"The negation symbol" should "invert the signal for all fields" in {
val input = Period(1, 1, -1, -1, 1, 1, 0)
val expected = Period(-1, -1, 1, 1, -1, -1, 0)
val result = -input
assert(result == expected)
}
"toList" should "convert the fields into a list" in {
val period = Period(1, 2, 3, 4, 5, 6, 7)
val expected = List(1, 2, 3, 4, 5, 6, 7)
val result = period.toList
assert(result == expected)
}
"toMap" should "convert the fields into an ordered map" in {
val period = Period(1, 2, 3, 4, 5, 6, 7)
val expected = scala.collection.immutable.ListMap[String, Int] (
"years" -> 1,
"months" -> 2,
"days" -> 3,
"hours" -> 4,
"minutes" -> 5,
"seconds" -> 6,
"milliseconds" -> 7
)
val result = period.toMap
assert(result == expected)
}
"isSingleUnit" should "return true if only one field is defined" in {
assert(Period(months = 1).isSingleUnit)
assert(!Period().isSingleUnit)
assert(!Period(1, 2).isSingleUnit)
assert(!Period(1, 2, 3, 4, 5, 6, 7).isSingleUnit)
}
"toString" should "convert the period object into a readable string" in {
assert(Period().toString == "Empty Period")
assert(Period(months = 3).toString == "3 months")
assert(Period(months = 3, years = 1).toString == "1 year, 3 months")
}
"fromList" should "statically convert a list into a Period" in {
val input: List[Long] = List(1, 2, 3, 4, 5, 6, 7)
assert(Period.fromList(input) == Period(1, 2, 3, 4, 5, 6, 7))
}
}
| danielpes/spark-datetime-lite | src/test/scala/me/danielpes/spark/datetime/PeriodSuite.scala | Scala | apache-2.0 | 3,597 |
package counters.bench
import java.util.concurrent.TimeUnit
import counters.adder.AtomicLongCounter
import org.jctools.counters.Counter
import org.openjdk.jmh.annotations._
@State(Scope.Group)
@BenchmarkMode(Array(Mode.AverageTime))
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(2)
@Warmup(iterations = 10)
@Measurement(iterations = 10)
class AtomicLongCounterBench {
val counter: Counter = new AtomicLongCounter()
@Benchmark
@Group("rw")
def increment(): Unit = counter.increment()
@Benchmark
@Group("rw")
def get(): Long = counter.get()
} | dpsoft/Counters | src/main/scala/counters/bench/AtomicLongCounterBench.scala | Scala | apache-2.0 | 558 |
package shield.transports
import com.amazonaws.services.lambda._
import spray.http.HttpHeaders.RawHeader
import spray.http.{HttpEntity, _}
import spray.json._
import spray.json.JsonParser
import com.amazonaws.handlers.AsyncHandler
import com.amazonaws.services.lambda.model._
import com.google.common.io.BaseEncoding
import spray.http.parser.HttpParser
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, Promise}
import scala.util.Try
object LambdaTransport {
type SendReceive = spray.client.pipelining.SendReceive
val base64 = BaseEncoding.base64()
class LambdaAsyncHandler(promise: Promise[InvokeResult]) extends AsyncHandler[InvokeRequest, InvokeResult] {
def onError(exception: Exception) = promise.failure(exception)
def onSuccess(request: InvokeRequest, result: InvokeResult) = promise.success(result)
}
def lambdaTransport(arn: String): SendReceive = {
val client = AWSLambdaAsyncClientBuilder.defaultClient()
def executeCall(request: HttpRequest): Future[HttpResponse] = {
val req = new InvokeRequest()
.withFunctionName(arn)
.withPayload(LambdaRequest.translate(request).toJson.compactPrint)
val p = Promise[InvokeResult]
client.invokeAsync(req, new LambdaAsyncHandler(p))
p.future.map(req => {
JsonParser(ParserInput(req.getPayload.array)).convertTo[LambdaResponse].toResponse
})
}
executeCall
}
case class LambdaRequest(method: String, headers: List[(String, String)], uri: String, body: Option[String])
object LambdaRequest extends DefaultJsonProtocol {
def translate(request: HttpRequest): LambdaRequest = {
val processedHeaders = request.entity.toOption match {
// No body - leave the content-type header (probably a HEAD request)
case None => request.headers
// Some body - set the content-type based off what spray associated with the entity
// * content-type has probably been filtered by HttpProxyLogic before reaching here, so this likely redundant
// * Adding-content-type from the entity matches Spray's HttpRequest rendering logic
case Some(entity) => HttpHeaders.`Content-Type`(entity.contentType) :: request.headers.filterNot(_.lowercaseName == "content-type")
}
val headers = processedHeaders.map(header => (header.lowercaseName, header.value))
val body = request.entity.toOption.map(e => base64.encode(e.data.toByteArray))
LambdaRequest(request.method.value, headers, request.uri.toString, body)
}
implicit val requestFormat : JsonFormat[LambdaRequest] = jsonFormat4(LambdaRequest.apply)
}
case class LambdaResponse(status: Int, headers: List[(String, String)], body: Option[String]) {
def parseHeaders : List[HttpHeader] = HttpParser.parseHeaders(headers.map(RawHeader.tupled))._2
def toResponse: HttpResponse = {
val parsedContentType = headers.find(_._1.toLowerCase() == "content-type").map(ct => HttpParser.parse(HttpParser.ContentTypeHeaderValue, ct._2))
val entity = body.map(base64.decode)
(parsedContentType, entity) match {
case (None, None) => HttpResponse(status, headers = parseHeaders)
case (None, Some(data)) => HttpResponse(status, HttpEntity(ContentTypes.`application/octet-stream`, data), parseHeaders)
case (Some(Left(err)), _) => HttpResponse(StatusCodes.BadGateway, HttpEntity(s"Upstream supplied an invalid content-type header: ${err.detail}"))
case (Some(Right(contentType)), None) => HttpResponse(status, headers = parseHeaders)
case (Some(Right(contentType)), Some(data)) => HttpResponse(status, HttpEntity(contentType, data), parseHeaders)
}
}
}
object LambdaResponse extends DefaultJsonProtocol {
implicit val responseFormat : JsonFormat[LambdaResponse] = jsonFormat3(LambdaResponse.apply)
}
}
| RetailMeNot/shield | src/main/scala/shield/transports/LambdaTransport.scala | Scala | mit | 3,871 |
import shapeless._
import shapeless.ops.hlist._
object WitnessImp
{
def fn[A, B](a: A, b: B)(implicit ev: A *** B) = ???
fn(Witness(3).value, Witness(4).value)
}
| tek/splain | core/src/test/resources-2.13.7+/latest/splain/plugin/ShapelessSpec/witness-value/code.scala | Scala | mit | 168 |
package net.revenj.storage
import org.specs2.mutable.Specification
class S3Check extends Specification {
"S3 smoke test" >> {
S3 ne null
}
}
| ngs-doo/revenj | scala/revenj-storage/src/test/scala/net/revenj/storage/S3Check.scala | Scala | bsd-3-clause | 151 |
/**
* _____ _____ _____ _____ __ _____ _____ _____ _____
* | __| | | | | | | | | __| | |
* |__ | | | | | | | | | |__| | | | |- -| --|
* |_____|_____|_|_|_|_____| |_____|_____|_____|_____|_____|
*
* UNICORNS AT WARP SPEED SINCE 2010
*
* Copyright (C) 2012 Sumo Logic
*
* 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.sumologic.collector.gae.servlet
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.io.IOException
import java.util.logging.Logger
import scala.throws
;
/**
* User: gorzell
* Date: 9/6/12
*/
class ReceiveTestServlet extends HttpServlet {
private var log = Logger.getLogger(classOf[LogGenServlet].getName)
@throws(classOf[ServletException])
@throws(classOf[IOException])
override protected def doPost(request: HttpServletRequest, response: HttpServletResponse) {
log.info("Request length:" + request.getContentLength)
log.info("Content-Type:" + request.getHeader("Content-Type"))
val builder = new StringBuilder()
val reader = request.getReader
var line = reader.readLine()
while (line != null) {
builder.append(line)
builder.append("\n")
line = reader.readLine()
}
log.info(builder.toString())
}
@throws(classOf[ServletException])
@throws(classOf[IOException])
override protected def doGet(request: HttpServletRequest, response: HttpServletResponse) {
//TODO return error response
}
}
| SumoLogic/sumo-gae-collector | gaeCollector-core/src/main/scala/com/sumologic/collector/gae/servlet/ReceiveTestServlet.scala | Scala | apache-2.0 | 2,361 |
package com.andre_cruz.collection
import org.scalatest.{Matchers, WordSpecLike}
class RichTraversableOnceTest extends WordSpecLike with Matchers {
import TraversableOnceUtils.RichTraversableOnce
"A RichTraversableOnce" when {
/** minOption tests */
"using minOption while empty" should {
"yield None" in {
List.empty[Int].minOption should be (None)
}
}
"using minOption with a single element" should {
"yield the single element" in {
List(1).minOption shouldBe Some(1)
}
}
"using minOption with >1 elements" should {
"yield the minimum element that satisfies the predicate" in {
List(1, 2, 3).minOption shouldBe Some(1)
}
}
/** maxOption tests */
"using maxOption while empty" should {
"yield None" in {
List.empty[Int].maxOption should be (None)
}
}
"using maxOption with a single element" should {
"yield the single element" in {
List(1).maxOption shouldBe Some(1)
}
}
"using maxOption with >1 elements" should {
"yield the maximum element that satisfies the predicate" in {
List(1, 2, 3).maxOption shouldBe Some(3)
}
}
/** minByOption tests */
"using minByOption while empty" should {
"yield None" in {
Map.empty[String, Int].minByOption(_._2) should be (None)
}
}
"using minByOption with a single element" should {
"yield the single element" in {
val pair = "a" -> 1
Map(pair).minByOption(_._2) shouldBe Some(pair)
}
}
"using minByOption with >1 elements" should {
"yield the minimum element that satisfies the predicate" in {
val minPair = "a" -> 1
Map(
minPair,
"b" -> 2,
"c" -> 3
).minByOption(_._2) shouldBe Some(minPair)
}
}
/** maxByOption tests */
"using maxByOption while empty" should {
"yield None" in {
Map.empty[String, Int].maxByOption(_._2) should be (None)
}
}
"using maxByOption with a single element" should {
"yield the single element" in {
val pair = "a" -> 1
Map(pair).maxByOption(_._2) shouldBe Some(pair)
}
}
"using maxByOption with >1 elements" should {
"yield the maximum element that satisfies the predicate" in {
val maxPair = "c" -> 3
Map(
"a" -> 1,
"b" -> 2,
maxPair
).maxByOption(_._2) shouldBe Some(maxPair)
}
}
}
}
| codecruzer/scala-utils | src/test/scala/com/andre_cruz/collection/RichTraversableOnceTest.scala | Scala | apache-2.0 | 2,537 |
package net.hearthstats.modules
import net.hearthstats.modules.upload.DummyFileUploader
import net.hearthstats.modules.upload.FileUploader
class FileUploaderFactory extends ModuleFactory[FileUploader](
"video uploader",
classOf[FileUploader],
classOf[DummyFileUploader]) | HearthStats/HearthStats.net-Uploader | companion/src/main/scala/net/hearthstats/modules/FileUploaderFactory.scala | Scala | bsd-3-clause | 278 |
package nasa.nccs.esgf.utilities
import scala.io.Source
import scala.util.parsing.combinator._
class OperationNotationParser extends JavaTokenParsers {
var key_index = 0
def new_key: String = { key_index += 1; "ivar#" + key_index }
def expr: Parser[Map[String, Any]] = repsep(function, ",") ^^ (Map() ++ _)
def arglist: Parser[List[String]] = "(" ~> repsep(value, ",") <~ ")"
def value: Parser[String] = """[a-zA-Z0-9_ :.*|]*""".r
def name: Parser[String] = """[a-zA-Z0-9_.]*""".r
def fname: Parser[String] = (
name ~ ":" ~ name ^^ { case x ~ ":" ~ y => y + "~" + x }
| name ^^ (y => y + "~" + new_key)
)
def function: Parser[(String, List[String])] = (
fname ~ arglist ^^ { case x ~ y => (x, y) }
| arglist ^^ { y => (new_key, y) }
)
}
object wpsOperationParser extends OperationNotationParser {
def parseOp(operation: String): Map[String, Any] = parseAll(expr, operation.stripPrefix("\"").stripSuffix("\"")).get
}
object wpsNameMatchers {
val yAxis = """^lat\w*""".r
val xAxis = """^lon\w*""".r
val zAxis = """^lev\w*|^plev\w*""".r
val id = """^id\w*|^name\w*""".r
val tAxis = """^tim\w*""".r
def getDimension( axisName: String ): Char = axisName match {
case xAxis() => 'x'
case yAxis() => 'y'
case zAxis() => 'z'
case tAxis() => 't'
case _ => throw new Exception( "Unrecognized axis name: " + axisName )
}
}
//object readTest extends App {
// val filename = "/Users/tpmaxwel/.edas/cache/ncdump.test"
// var timeData = false
// var elem_count: Int = 0
// for (line <- Source.fromFile(filename).getLines) {
// if( line.startsWith(" time = ") ) { timeData = true }
// val elems: Int = if( timeData ) { line.count( _ equals ',' ) } else 0
// elem_count = elem_count + elems
// }
// print( elem_count.toString )
//}
//
| nasa-nccs-cds/EDAS | src/main/scala/nasa/nccs/esgf/utilities/parsers.scala | Scala | gpl-2.0 | 1,826 |
/*
* Copyright 2016 Dennis Vriend
*
* 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.github.dnvriend.component.simpleserver.route
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.{ Directives, Route }
import spray.json.DefaultJsonProtocol
import scala.util.Try
object TryRoute extends Directives with SprayJsonSupport with DefaultJsonProtocol {
def route: Route = {
pathPrefix("try") {
(get & path("failure")) {
complete(Try((1 / 0).toString))
} ~
(get & path("success")) {
complete(Try(1.toString))
}
}
}
}
| dnvriend/akka-http-test | app/com/github/dnvriend/component/simpleserver/route/TryRoute.scala | Scala | apache-2.0 | 1,143 |
package spire.math
import spire.algebra._
import spire.syntax.field._
import spire.syntax.isReal._
import spire.syntax.nroot._
import spire.syntax.order._
import scala.{specialized => spec}
import scala.annotation.tailrec
import scala.math.{ScalaNumber, ScalaNumericConversions, ScalaNumericAnyConversions}
import java.lang.Math
object Complex extends ComplexInstances {
def i[@spec(Float, Double) T](implicit T: Rig[T]) =
new Complex(T.zero, T.one)
def one[@spec(Float, Double) T](implicit T: Rig[T]) =
new Complex(T.one, T.zero)
def zero[@spec(Float, Double) T](implicit T: Semiring[T]) =
new Complex(T.zero, T.zero)
def fromInt[@spec(Float, Double) T](n: Int)(implicit f: Ring[T]) =
new Complex(f.fromInt(n), f.zero)
implicit def intToComplex(n: Int) = new Complex(n.toDouble, 0.0)
implicit def longToComplex(n: Long) = new Complex(n.toDouble, 0.0)
implicit def floatToComplex(n: Float) = new Complex(n, 0.0F)
implicit def doubleToComplex(n: Double) = new Complex(n, 0.0)
implicit def bigIntToComplex(n: BigInt): Complex[BigDecimal] =
bigDecimalToComplex(BigDecimal(n))
implicit def bigDecimalToComplex(n: BigDecimal): Complex[BigDecimal] = {
implicit val mc = n.mc
new Complex(n, BigDecimal(0))
}
def polar[@spec(Float, Double) T: Field: Trig](magnitude: T, angle: T): Complex[T] =
new Complex(magnitude * Trig[T].cos(angle), magnitude * Trig[T].sin(angle))
def apply[@spec(Float, Double) T: Semiring](real: T): Complex[T] =
new Complex(real, Semiring[T].zero)
def rootOfUnity[@spec(Float, Double) T](n: Int, x: Int)(implicit f: Field[T], t: Trig[T], r: IsReal[T]): Complex[T] = {
if (x == 0) return one[T]
if (n % 2 == 0) {
if (x == n / 2) return -one[T]
if (n % 4 == 0) {
if (x == n / 4) return i[T]
if (x == n * 3 / 4) return -i[T]
}
}
polar(f.one, (t.pi * 2 * x) / n)
}
def rootsOfUnity[@spec(Float, Double) T](n: Int)(implicit f: Field[T], t: Trig[T], r: IsReal[T]): Array[Complex[T]] = {
val roots = new Array[Complex[T]](n)
var sum = one[T]
roots(0) = sum
val west = if (n % 2 == 0) n / 2 else -1
val north = if (n % 4 == 0) n / 4 else -1
val south = if (n % 4 == 0) 3 * n / 4 else -1
var x = 1
val last = n - 1
while (x < last) {
val c = x match {
case `north` => i[T]
case `west` => -one[T]
case `south` => -i[T]
case _ => polar(f.one, (t.pi * 2 * x) / n)
}
roots(x) = c
sum += c
x += 1
}
roots(last) = zero[T] - sum
roots
}
}
@SerialVersionUID(0L)
final case class Complex[@spec(Float, Double) T](real: T, imag: T)
extends ScalaNumber with ScalaNumericConversions with Serializable { lhs =>
import spire.syntax.order._
/**
* This returns the sign of `real` if it is not 0, otherwise it returns the
* sign of `imag`.
*/
def signum(implicit o: IsReal[T]): Int = real.signum match {
case 0 => imag.signum
case n => n
}
/**
* This implements sgn(z), which (except for z=0) observes:
*
* `sgn(z) = z / abs(z) = abs(z) / z`
*/
def complexSignum(implicit f: Field[T], o: IsReal[T], n: NRoot[T]): Complex[T] =
if (isZero) this else this / abs
def abs(implicit f: Field[T], o: IsReal[T], n: NRoot[T]): T =
(real * real + imag * imag).sqrt
def arg(implicit f: Field[T], t: Trig[T], o: IsReal[T]): T =
if (isZero) f.zero else t.atan2(imag, real)
def norm(implicit f: Field[T], n: NRoot[T]): T =
(real * real + imag * imag).sqrt
def conjugate(implicit f: Rng[T]): Complex[T] = new Complex(real, -imag)
def asTuple: (T, T) = (real, imag)
def asPolarTuple(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): (T, T) = (abs, arg)
def isZero(implicit o: IsReal[T]): Boolean = real.isZero && imag.isZero
def isImaginary(implicit o: IsReal[T]): Boolean = real.isZero
def isReal(implicit o: IsReal[T]): Boolean = imag.isZero
def eqv(b: Complex[T])(implicit o: Eq[T]): Boolean = real === b.real && imag === b.imag
def neqv(b: Complex[T])(implicit o: Eq[T]): Boolean = real =!= b.real || imag =!= b.imag
def unary_-(implicit r: Rng[T]): Complex[T] = new Complex(-real, -imag)
def +(rhs: T)(implicit r: Semiring[T]): Complex[T] = new Complex(real + rhs, imag)
def -(rhs: T)(implicit r: Rng[T]): Complex[T] = new Complex(real - rhs, imag)
def *(rhs: T)(implicit r: Semiring[T]): Complex[T] = new Complex(real * rhs, imag * rhs)
def /(rhs: T)(implicit r: Field[T]): Complex[T] = new Complex(real / rhs, imag / rhs)
// TODO: instead of floor should be round-toward-zero
def /~(rhs: T)(implicit f: Field[T], o: IsReal[T]): Complex[T] = (this / rhs).floor
def %(rhs: T)(implicit f: Field[T], o: IsReal[T]): Complex[T] = this - (this /~ rhs) * rhs
def /%(rhs: T)(implicit f: Field[T], o: IsReal[T]): (Complex[T], Complex[T]) = {
val q = this /~ rhs
(q, this - q * rhs)
}
def **(e: T)(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] = this pow e
def pow(e: T)(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] =
if (e.isZero) {
Complex.one[T]
} else if (this.isZero) {
if (e < f.zero)
throw new Exception("raising 0 to negative/complex power")
Complex.zero[T]
} else {
Complex.polar(abs fpow e, arg * e)
}
def +(b: Complex[T])(implicit r: Semiring[T]): Complex[T] =
new Complex(real + b.real, imag + b.imag)
def -(b: Complex[T])(implicit r: Rng[T]): Complex[T] =
new Complex(real - b.real, imag - b.imag)
def *(b: Complex[T])(implicit r: Rng[T]): Complex[T] =
new Complex(real * b.real - imag * b.imag, imag * b.real + real * b.imag)
def /(b: Complex[T])(implicit f: Field[T], o: IsReal[T]): Complex[T] = {
val abs_breal = b.real.abs
val abs_bimag = b.imag.abs
if (abs_breal >= abs_bimag) {
if (abs_breal === f.zero) throw new Exception("/ by zero")
val ratio = b.imag / b.real
val denom = b.real + b.imag * ratio
new Complex((real + imag * ratio) / denom, (imag - real * ratio) / denom)
} else {
if (abs_bimag === f.zero) throw new Exception("/ by zero")
val ratio = b.real / b.imag
val denom = b.real * ratio + b.imag
new Complex((real * ratio + imag) / denom, (imag * ratio - real) /denom)
}
}
def /~(b: Complex[T])(implicit f: Field[T], o: IsReal[T]): Complex[T] = {
val d = this / b
new Complex(d.real.floor, d.imag.floor)
}
def %(b: Complex[T])(implicit f: Field[T], o: IsReal[T]): Complex[T] = this - (this /~ b) * b
def /%(b: Complex[T])(implicit f: Field[T], o: IsReal[T]): (Complex[T], Complex[T]) = {
val q = this /~ b
(q, this - q * b)
}
def **(b: Int)(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] = pow(b)
def nroot(k: Int)(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] =
if (isZero) Complex.zero else pow(Complex(f.fromInt(k).reciprocal, f.zero))
def pow(b: Int)(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] =
if (isZero) Complex.zero else Complex.polar(abs.pow(b), arg * b)
def **(b: Complex[T])(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] = pow(b)
def pow(b: Complex[T])(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] =
if (b.isZero) {
Complex.one[T]
} else if (this.isZero) {
if (b.imag =!= f.zero || b.real < f.zero)
throw new Exception("raising 0 to negative/complex power")
Complex.zero[T]
} else if (b.imag =!= f.zero) {
val len = (abs fpow b.real) / t.exp(arg * b.imag)
val phase = arg * b.real + t.log(abs) * b.imag
Complex.polar(len, phase)
} else {
Complex.polar(abs fpow b.real, arg * b.real)
}
// we are going with the "principal value" definition of Log.
def log(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] = {
if (isZero) throw new IllegalArgumentException("log(0) undefined")
new Complex(t.log(abs), arg)
}
def sqrt(implicit f: Field[T], n0: NRoot[T], o: IsReal[T]): Complex[T] = {
if (isZero) {
Complex.zero[T]
} else {
val two = f.fromInt(2)
val a = ((abs + real.abs) / two).sqrt
imag.signum match {
case 0 =>
if (real < f.zero) Complex(f.zero, a) else Complex(a, f.zero)
case n =>
val b = ((abs - real.abs) / two).sqrt
if (n < 0) Complex(a, -b) else Complex(a, b)
}
}
}
def floor(implicit o: IsReal[T]): Complex[T] = new Complex(real.floor, imag.floor)
def ceil(implicit o: IsReal[T]): Complex[T] = new Complex(real.ceil, imag.ceil)
def round(implicit o: IsReal[T]): Complex[T] = new Complex(real.round, imag.round)
// acos(z) = -i*(log(z + i*(sqrt(1 - z*z))))
def acos(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] = {
val z2 = this * this
val s = new Complex(f.one - z2.real, -z2.imag).sqrt
val l = new Complex(real + s.imag, imag + s.real).log
new Complex(l.imag, -l.real)
}
// asin(z) = -i*(log(sqrt(1 - z*z) + i*z))
def asin(implicit f: Field[T], n: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] = {
val z2 = this * this
val s = new Complex(f.one - z2.real, -z2.imag).sqrt
val l = new Complex(s.real + -imag, s.imag + real).log
new Complex(l.imag, -l.real)
}
// atan(z) = (i/2) log((i + z)/(i - z))
def atan(implicit f: Field[T], r: NRoot[T], t: Trig[T], o: IsReal[T]): Complex[T] = {
val n = new Complex(real, imag + f.one)
val d = new Complex(-real, f.one - imag)
val l = (n / d).log
new Complex(l.imag / f.fromInt(-2), l.real / f.fromInt(2))
}
// exp(a+ci) = (exp(a) * cos(c)) + (exp(a) * sin(c))i
def exp(implicit f: Field[T], t: Trig[T]): Complex[T] =
new Complex(t.exp(real) * t.cos(imag), t.exp(real) * t.sin(imag))
// sin(a+ci) = (sin(a) * cosh(c)) + (cos(a) * sinh(c))i
def sin(implicit f: Field[T], t: Trig[T]): Complex[T] =
new Complex(t.sin(real) * t.cosh(imag), t.cos(real) * t.sinh(imag))
// sinh(a+ci) = (sinh(a) * cos(c)) + (cosh(a) * sin(c))i
def sinh(implicit f: Field[T], t: Trig[T]): Complex[T] =
new Complex(t.sinh(real) * t.cos(imag), t.cosh(real) * t.sin(imag))
// cos(a+ci) = (cos(a) * cosh(c)) - (sin(a) * sinh(c))i
def cos(implicit f: Field[T], t: Trig[T]): Complex[T] =
new Complex(t.cos(real) * t.cosh(imag), -t.sin(real) * t.sinh(imag))
// cosh(a+ci) = (cosh(a) * cos(c)) + (sinh(a) * sin(c))i
def cosh(implicit f: Field[T], t: Trig[T]): Complex[T] =
new Complex(t.cosh(real) * t.cos(imag), t.sinh(real) * t.sin(imag))
// tan(a+ci) = (sin(a+a) + sinh(c+c)i) / (cos(a+a) + cosh(c+c))
def tan(implicit f: Field[T], t: Trig[T]): Complex[T] = {
val r2 = real + real
val i2 = imag + imag
val d = t.cos(r2) + t.cosh(i2)
new Complex(t.sin(r2) / d, t.sinh(i2) / d)
}
// tanh(a+ci) = (sinh(a+a) + sin(c+c)i) / (cosh(a+a) + cos(c+c))
def tanh(implicit f: Field[T], t: Trig[T]): Complex[T] = {
val r2 = real + real
val i2 = imag + imag
val d = t.cos(r2) + t.cosh(i2)
new Complex(t.sinh(r2) / d, t.sin(i2) / d)
}
// junky ScalaNumber stuff
def floatValue: Float = doubleValue.toFloat
def doubleValue: Double = anyToDouble(real)
override def byteValue: Byte = longValue.toByte
override def shortValue: Short = longValue.toShort
def intValue: Int = longValue.toInt
override def longValue: Long = anyToLong(real)
def underlying: Object = this
def isWhole: Boolean =
anyIsZero(imag) && anyIsWhole(real)
override final def isValidInt: Boolean =
anyIsZero(imag) && anyIsValidInt(real)
// important to keep in sync with Quaternion[_]
override def hashCode: Int =
if (anyIsZero(imag)) real.##
else (19 * real.##) + (41 * imag.##) + 97
// not typesafe, so this is the best we can do :(
override def equals(that: Any): Boolean = that match {
case that: Complex[_] =>
real == that.real && imag == that.imag
case that: Quaternion[_] =>
real == that.r && imag == that.i && anyIsZero(that.j) && anyIsZero(that.k)
case that =>
anyIsZero(imag) && real == that
}
override def toString: String = s"($real + ${imag}i)"
def toQuaternion(implicit ev: AdditiveMonoid[T]): Quaternion[T] =
Quaternion(real, imag, ev.zero, ev.zero)
}
object FloatComplex {
import FastComplex.{encode}
final def apply(real: Float, imag: Float): FloatComplex =
new FloatComplex(encode(real, imag))
final def apply(real: Double, imag: Double) =
new FloatComplex(encode(real.toFloat, imag.toFloat))
def polar(magnitude: Float, angle: Float) =
new FloatComplex(FastComplex.polar(magnitude, angle))
final val i = new FloatComplex(4575657221408423936L)
final val one = new FloatComplex(1065353216L)
final val zero = new FloatComplex(0L)
}
/**
* Value class which encodes two floating point values in a Long.
*
* We get (basically) unboxed complex numbers using this hack.
* The underlying implementation lives in the FastComplex object.
*/
class FloatComplex(val u: Long) extends AnyVal {
override final def toString: String = "(%s+%si)" format (real, imag)
final def real: Float = FastComplex.real(u)
final def imag: Float = FastComplex.imag(u)
final def repr = "FloatComplex(%s, %s)" format(real, imag)
final def abs: Float = FastComplex.abs(u)
final def angle: Float = FastComplex.angle(u)
final def conjugate = new FloatComplex(FastComplex.conjugate(u))
final def isWhole: Boolean = FastComplex.isWhole(u)
final def signum: Int = FastComplex.signum(u)
final def complexSignum = new FloatComplex(FastComplex.complexSignum(u))
final def negate = new FloatComplex(FastComplex.negate(u))
final def +(b: FloatComplex) = new FloatComplex(FastComplex.add(u, b.u))
final def -(b: FloatComplex) = new FloatComplex(FastComplex.subtract(u, b.u))
final def *(b: FloatComplex) = new FloatComplex(FastComplex.multiply(u, b.u))
final def /(b: FloatComplex) = new FloatComplex(FastComplex.divide(u, b.u))
final def /~(b: FloatComplex) = new FloatComplex(FastComplex.quot(u, b.u))
final def %(b: FloatComplex) = new FloatComplex(FastComplex.mod(u, b.u))
final def /%(b: FloatComplex) = FastComplex.quotmod(u, b.u) match {
case (q, m) => (new FloatComplex(q), new FloatComplex(m))
}
final def pow(b: FloatComplex) = new FloatComplex(FastComplex.pow(u, b.u))
final def **(b: FloatComplex) = pow(b)
final def pow(b: Int) = new FloatComplex(FastComplex.pow(u, FastComplex(b.toFloat, 0.0F)))
final def **(b: Int) = pow(b)
}
/**
* FastComplex is an ugly, beautiful hack.
*
* The basic idea is to encode two 32-bit Floats into a single 64-bit Long.
* The lower-32 bits are the "real" Float and the upper-32 are the "imaginary"
* Float.
*
* Since we're overloading the meaning of Long, all the operations have to be
* defined on the FastComplex object, meaning the syntax for using this is a
* bit ugly. To add to the ugly beauty of the whole thing I could imagine
* defining implicit operators on Long like +@, -@, *@, /@, etc.
*
* You might wonder why it's even worth doing this. The answer is that when
* you need to allocate an array of e.g. 10-20 million complex numbers, the GC
* overhead of using *any* object is HUGE. Since we can't build our own
* "pass-by-value" types on the JVM we are stuck doing an encoding like this.
*
* Here are some profiling numbers for summing an array of complex numbers,
* timed against a concrete case class implementation using Float (in ms):
*
* size | encoded | class
* 1M | 5.1 | 5.8
* 5M | 28.5 | 91.7
* 10M | 67.7 | 828.1
* 20M | 228.0 | 2687.0
*
* Not bad, eh?
*/
object FastComplex {
import java.lang.Math.{atan2, cos, sin, sqrt}
// note the superstitious use of @inline and final everywhere
final def apply(real: Float, imag: Float) = encode(real, imag)
final def apply(real: Double, imag: Double) = encode(real.toFloat, imag.toFloat)
// encode a float as some bits
@inline final def bits(n: Float): Int = java.lang.Float.floatToRawIntBits(n)
// decode some bits into a float
@inline final def bits(n: Int): Float = java.lang.Float.intBitsToFloat(n)
// get the real part of the complex number
@inline final def real(d: Long): Float = bits((d & 0xffffffff).toInt)
// get the imaginary part of the complex number
@inline final def imag(d: Long): Float = bits((d >> 32).toInt)
// define some handy constants
final val i = encode(0.0F, 1.0F)
final val one = encode(1.0F, 0.0F)
final val zero = encode(0.0F, 0.0F)
// encode two floats representing a complex number
@inline final def encode(real: Float, imag: Float): Long = {
(bits(imag).toLong << 32) + bits(real).toLong
}
// encode two floats representing a complex number in polar form
@inline final def polar(magnitude: Float, angle: Float): Long = {
encode(magnitude * cos(angle).toFloat, magnitude * sin(angle).toFloat)
}
// decode should be avoided in fast code because it allocates a Tuple2.
final def decode(d: Long): (Float, Float) = (real(d), imag(d))
// produces a string representation of the Long/(Float,Float)
final def toRepr(d: Long): String = "FastComplex(%s -> %s)" format(d, decode(d))
// get the magnitude/absolute value
final def abs(d: Long): Float = {
val re = real(d)
val im = imag(d)
java.lang.Math.sqrt(re * re + im * im).toFloat
}
// get the angle/argument
final def angle(d: Long): Float = atan2(imag(d), real(d)).toFloat
// get the complex conjugate
final def conjugate(d: Long): Long = encode(real(d), -imag(d))
// see if the complex number is a whole value
final def isWhole(d: Long): Boolean = real(d) % 1.0F == 0.0F && imag(d) % 1.0F == 0.0F
// get the sign of the complex number
final def signum(d: Long): Int = real(d) compare 0.0F
// get the complex sign of the complex number
final def complexSignum(d: Long): Long = {
val m = abs(d)
if (m == 0.0F) zero else divide(d, encode(m, 0.0F))
}
// negation
final def negate(a: Long): Long = encode(-real(a), -imag(a))
// addition
final def add(a: Long, b: Long): Long = encode(real(a) + real(b), imag(a) + imag(b))
// subtraction
final def subtract(a: Long, b: Long): Long = encode(real(a) - real(b), imag(a) - imag(b))
// multiplication
final def multiply(a: Long, b: Long): Long = {
val re_a = real(a)
val im_a = imag(a)
val re_b = real(b)
val im_b = imag(b)
encode(re_a * re_b - im_a * im_b, im_a * re_b + re_a * im_b)
}
// division
final def divide(a: Long, b: Long): Long = {
val re_a = real(a)
val im_a = imag(a)
val re_b = real(b)
val im_b = imag(b)
val abs_re_b = Math.abs(re_b)
val abs_im_b = Math.abs(im_b)
if (abs_re_b >= abs_im_b) {
if (abs_re_b == 0.0F) throw new ArithmeticException("/0")
val ratio = im_b / re_b
val denom = re_b + im_b * ratio
encode((re_a + im_a * ratio) / denom, (im_a - re_a * ratio) / denom)
} else {
if (abs_im_b == 0.0F) throw new ArithmeticException("/0")
val ratio = re_b / im_b
val denom = re_b * ratio + im_b
encode((re_a * ratio + im_a) / denom, (im_a * ratio - re_a) / denom)
}
}
final def quot(a: Long, b: Long): Long =
encode(Math.floor(real(divide(a, b))).toFloat, 0.0F)
final def mod(a: Long, b: Long): Long = subtract(a, multiply(b, quot(a, b)))
final def quotmod(a: Long, b: Long): (Long, Long) = {
val q = quot(a, b)
(q, subtract(a, multiply(b, quot(a, b))))
}
// exponentiation
final def pow(a: Long, b: Long): Long = if (b == zero) {
encode(1.0F, 0.0F)
} else if (a == zero) {
if (imag(b) != 0.0F || real(b) < 0.0F)
throw new Exception("raising 0 to negative/complex power")
zero
} else if (imag(b) != 0.0F) {
val im_b = imag(b)
val re_b = real(b)
val len = (Math.pow(abs(a), re_b) / exp((angle(a) * im_b))).toFloat
val phase = (angle(a) * re_b + log(abs(a)) * im_b).toFloat
polar(len, phase)
} else {
val len = Math.pow(abs(a), real(b)).toFloat
val phase = (angle(a) * real(b)).toFloat
polar(len, phase)
}
}
trait ComplexInstances0 {
implicit def ComplexRing[A: Ring: IsReal]: Ring[Complex[A]] = new ComplexIsRingImpl[A]
}
trait ComplexInstances1 extends ComplexInstances0 {
implicit def ComplexField[A: Field: IsReal]: Field[Complex[A]] = new ComplexIsFieldImpl[A]
}
trait ComplexInstances extends ComplexInstances1 {
implicit def ComplexAlgebra[@spec(Float, Double) A: Fractional: Trig: IsReal] =
new ComplexAlgebra[A]
implicit def ComplexEq[A: Eq]: Eq[Complex[A]] = new ComplexEq[A]
}
private[math] trait ComplexIsRing[@spec(Float, Double) A] extends Ring[Complex[A]] {
implicit def algebra: Ring[A]
implicit def order: IsReal[A]
override def minus(a: Complex[A], b: Complex[A]): Complex[A] = a - b
def negate(a: Complex[A]): Complex[A] = -a
def one: Complex[A] = Complex.one
def plus(a: Complex[A], b: Complex[A]): Complex[A] = a + b
override def times(a: Complex[A], b: Complex[A]): Complex[A] = a * b
def zero: Complex[A] = Complex.zero
override def fromInt(n: Int): Complex[A] = Complex.fromInt[A](n)
}
private[math] trait ComplexIsField[@spec(Float,Double) A] extends ComplexIsRing[A] with Field[Complex[A]] {
implicit def algebra: Field[A]
override def fromDouble(n: Double): Complex[A] = Complex(algebra.fromDouble(n))
def div(a: Complex[A], b: Complex[A]) = a / b
def quot(a: Complex[A], b: Complex[A]) = a /~ b
def mod(a: Complex[A], b: Complex[A]) = a % b
override def quotmod(a: Complex[A], b: Complex[A]) = a /% b
def gcd(a: Complex[A], b: Complex[A]): Complex[A] = {
@tailrec def _gcd(a: Complex[A], b: Complex[A]): Complex[A] =
if (b.isZero) a else _gcd(b, a - (a / b).round * b)
_gcd(a, b)
}
}
private[math] trait ComplexIsTrig[@spec(Float, Double) A] extends Trig[Complex[A]] {
implicit def algebra: Field[A]
implicit def nroot: NRoot[A]
implicit def trig: Trig[A]
implicit def order: IsReal[A]
def e: Complex[A] = new Complex[A](trig.e, algebra.zero)
def pi: Complex[A] = new Complex[A](trig.pi, algebra.zero)
def exp(a: Complex[A]): Complex[A] = a.exp
def expm1(a: Complex[A]): Complex[A] = a.exp - algebra.one
def log(a: Complex[A]): Complex[A] = a.log
def log1p(a: Complex[A]): Complex[A] = (a + algebra.one).log
def sin(a: Complex[A]): Complex[A] = a.sin
def cos(a: Complex[A]): Complex[A] = a.cos
def tan(a: Complex[A]): Complex[A] = a.tan
def asin(a: Complex[A]): Complex[A] = a.sin
def acos(a: Complex[A]): Complex[A] = a.cos
def atan(a: Complex[A]): Complex[A] = a.tan
def atan2(y: Complex[A], x: Complex[A]): Complex[A] =
new Complex(x.real, y.imag).atan
def sinh(x: Complex[A]): Complex[A] = x.sinh
def cosh(x: Complex[A]): Complex[A] = x.cosh
def tanh(x: Complex[A]): Complex[A] = x.tanh
def toRadians(a: Complex[A]): Complex[A] = a
def toDegrees(a: Complex[A]): Complex[A] = a
}
private[math] trait ComplexIsNRoot[A] extends NRoot[Complex[A]] {
implicit def algebra: Field[A]
implicit def nroot: NRoot[A]
implicit def trig: Trig[A]
implicit def order: IsReal[A]
def nroot(a: Complex[A], k: Int): Complex[A] = a.nroot(k)
override def sqrt(a: Complex[A]): Complex[A] = a.sqrt
def fpow(a: Complex[A], b: Complex[A]): Complex[A] = a.pow(b)
}
private[math] trait ComplexIsSigned[A] extends Signed[Complex[A]] {
implicit def algebra: Field[A]
implicit def nroot: NRoot[A]
implicit def order: IsReal[A]
def signum(a: Complex[A]): Int = a.signum
def abs(a: Complex[A]): Complex[A] = Complex[A](a.abs, algebra.zero)
}
@SerialVersionUID(1L)
private[math] class ComplexEq[A: Eq] extends Eq[Complex[A]] with Serializable {
def eqv(x: Complex[A], y: Complex[A]) = x eqv y
override def neqv(x: Complex[A], y: Complex[A]) = x neqv y
}
@SerialVersionUID(1L)
private[math] final class ComplexIsRingImpl[@spec(Float,Double) A](implicit
val algebra: Ring[A], val order: IsReal[A]) extends ComplexIsRing[A] with Serializable
@SerialVersionUID(1L)
private[math] final class ComplexIsFieldImpl[@spec(Float,Double) A](implicit
val algebra: Field[A], val order: IsReal[A]) extends ComplexIsField[A] with Serializable
@SerialVersionUID(1L)
private[math] class ComplexAlgebra[@spec(Float, Double) A](implicit
val algebra: Field[A], val nroot: NRoot[A], val trig: Trig[A], val order: IsReal[A])
extends ComplexIsField[A]
with ComplexIsTrig[A]
with ComplexIsNRoot[A]
with ComplexIsSigned[A]
with InnerProductSpace[Complex[A], A]
with FieldAlgebra[Complex[A], A]
with Serializable {
def scalar = algebra
def timesl(a: A, v: Complex[A]): Complex[A] = Complex(a, scalar.zero) * v
def dot(x: Complex[A], y: Complex[A]): A =
scalar.plus(scalar.times(x.real, y.real), scalar.times(x.imag, y.imag))
override def pow(a: Complex[A], b: Int): Complex[A] = a.pow(b)
}
| lrytz/spire | core/src/main/scala/spire/math/Complex.scala | Scala | mit | 25,046 |
/*
* Copyright (c) 2013-2014 Telefónica Investigación y Desarrollo S.A.U.
*
* 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 es.tid.cosmos.api.controllers.task
import org.scalatest.FlatSpec
import org.scalatest.matchers.MustMatchers
import es.tid.cosmos.api.task.{Failed, Finished, Running}
import play.api.libs.json._
class TaskDetailsTest extends FlatSpec with MustMatchers {
"TaskDetails" must "serialize to JSON correctly when Running" in {
val task = TaskDetails(40, Running, "/cosmos/v1/cluster")
Json.toJson(task) must be (Json.obj(
"id" -> 40,
"status" -> "Running",
"resource" -> "/cosmos/v1/cluster"
))
}
it must "serialize to JSON correctly when Finished" in {
val task = TaskDetails(0, Finished, "")
Json.toJson(task) must be (Json.obj(
"id" -> 0,
"status" -> "Finished",
"resource" -> ""
))
}
it must "serialize to JSON correctly when Failed" in {
val task = TaskDetails(0, Failed("foo"), "bar")
Json.toJson(task) must be (Json.obj(
"id" -> 0,
"status" -> "Failed: foo",
"resource" -> "bar"
))
}
}
| telefonicaid/fiware-cosmos-platform | cosmos-api/test/es/tid/cosmos/api/controllers/task/TaskDetailsTest.scala | Scala | apache-2.0 | 1,641 |
package pl.arapso.scaffoldings.scala.kafka
import akka.actor.Actor
import net.liftweb.json._
import pl.arapso.scaffoldings.scala.kafka.model.Event
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
class Accountant extends Actor {
implicit val formats = DefaultFormats
case class AccountantEvent(bidId: String)
case class Tick(n: Int)
val reportDuration = 3.second
context.system.scheduler.scheduleOnce(reportDuration, self, Tick(1))
var eventsNo: Long = 0l
var totalAmount: Double = 0d
var lastBidId: String = ""
override def receive: Receive = {
case EventMessage(line) => {
val event = parse(line).extract[Event]
lastBidId = event.bidId
totalAmount += event.bid.price
eventsNo += 1
}
case Tick(i) => {
println(s"Accountant have processed $eventsNo [sum=$totalAmount,lasatBidId=$lastBidId]")
context.system.scheduler.scheduleOnce(reportDuration, self, Tick(i + 1))
}
}
}
| arapso-scaffoldings/scala | scala-akka-kafka/events-kafka-producer/src/main/java/pl/arapso/scaffoldings/scala/kafka/Accountant.scala | Scala | apache-2.0 | 997 |
package com.sksamuel.elastic4s.analyzers
import com.sksamuel.elastic4s.anaylzers.AnalyzerDsl
import org.scalatest.{Matchers, WordSpec}
class StandardAnalyzerTest extends WordSpec with AnalyzerDsl with Matchers {
"StandardAnalyzer builder" should {
"set stopwords" in {
standardAnalyzer("testy")
.stopwords("a", "b")
.json
.string shouldBe """{"type":"standard","stopwords":["a","b"],"max_token_length":255}"""
}
"set maxTokenLength" in {
standardAnalyzer("testy")
.maxTokenLength(34)
.json
.string shouldBe """{"type":"standard","stopwords":[],"max_token_length":34}"""
}
}
}
| tototoshi/elastic4s | elastic4s-core-tests/src/test/scala/com/sksamuel/elastic4s/analyzers/StandardAnalyzerTest.scala | Scala | apache-2.0 | 659 |
package com.gjos.scala.swoc
import java.io.{BufferedReader, InputStreamReader}
object Main extends App {
val ioManager = IOManager.runMode
val bot = new Bot(None)
val engine = new Engine(bot, ioManager)
try {
engine.run()
} catch {
case e: RuntimeException => e.printStackTrace()
}
}
| Oduig/swoc2014 | Greedy/src/main/scala/com/gjos/scala/swoc/Main.scala | Scala | apache-2.0 | 307 |
package org.sisioh.aws4s.s3.model
import java.util
import com.amazonaws.services.s3.model.{ S3Event, QueueConfiguration }
import org.sisioh.aws4s.PimpedType
object QueueConfigurationFactory {
def createWithS3Events(queueARN: String, events: Seq[S3Event]): QueueConfiguration =
new QueueConfiguration(queueARN, util.EnumSet.of(events.head, events.tail.toArray: _*))
def createWithStrings(queueARN: String, events: String*): QueueConfiguration =
new QueueConfiguration(queueARN, events: _*)
}
class RichQueueConfiguration(val underlying: QueueConfiguration)
extends AnyVal with PimpedType[QueueConfiguration] {
def queueARN: String = underlying.getQueueARN
}
| everpeace/aws4s | aws4s-s3/src/main/scala/org/sisioh/aws4s/s3/model/RichQueueConfiguration.scala | Scala | mit | 684 |
/*
* OpenURP, Open University Resouce Planning
*
* Copyright (c) 2013-2014, OpenURP Software.
*
* OpenURP is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenURP is distributed in the hope that it will be useful.
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Beangle. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openurp.edu.attendance.ws.domain
import java.lang.Long.valueOf
import java.sql.Date
import java.util.Calendar
import java.util.Calendar.{ DAY_OF_WEEK, SUNDAY, WEEK_OF_YEAR, YEAR }
import org.beangle.commons.lang.Dates.toCalendar
import org.beangle.commons.lang.Strings.repeat
/**
* 周状态构建对象(兼容原有系统的方式)
* @author chaostone
* @version 1.0, 2014/03/22
* @since 0.0.1
*/
object WeekStates {
def build(date: Date): (Int, List[(Int, Long, String)]) = {
val cal = toCalendar(date)
cal.setFirstDayOfWeek(SUNDAY)
val weekday = if (cal.get(DAY_OF_WEEK) == 1) 7 else cal.get(DAY_OF_WEEK) - 1
val year = cal.get(YEAR)
val weekStateBuf = new StringBuilder(repeat('0', 53))
var weekIndex = cal.get(WEEK_OF_YEAR)
weekStateBuf.setCharAt(weekIndex - 1, '1')
var weekStats = new collection.mutable.ListBuffer[(Int, Long, String)]
weekStats += ((cal.get(YEAR), valueOf(weekStateBuf.mkString, 2), weekStateBuf.mkString))
if (weekIndex == 1 && weekday != 7) {
val lastWeekState = repeat('0', 52) + '1'
weekStats += Tuple3((cal.get(Calendar.YEAR) - 1), valueOf(lastWeekState, 2), lastWeekState)
}
(weekday, weekStats.toList)
}
} | openurp/edu-core | attendance/ws/src/main/scala/org/openurp/edu/attendance/ws/domain/WeekStates.scala | Scala | gpl-3.0 | 1,960 |
/*
* 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.scalatest
import Matchers._
import exceptions.TestFailedException
class ShouldEqualNullSpec extends FunSpec {
case class Super(size: Int)
class Sub(sz: Int) extends Super(sz)
val super1: Super = new Super(1)
val sub1: Sub = new Sub(1)
val super2: Super = new Super(2)
val sub2: Sub = new Sub(2)
val nullSuper: Super = null
describe("The should equal syntax") {
it("should work sensibly if null is passed on the left or right hand side") {
val caught1 = intercept[TestFailedException] { super1 should equal (null) }
caught1.getMessage should be ("Super(1) did not equal null")
val caught2 = intercept[TestFailedException] { super1 should (equal (null)) }
caught2.getMessage should be ("Super(1) did not equal null")
val caught1b = intercept[TestFailedException] { super1 shouldEqual null }
caught1b.getMessage should be ("Super(1) did not equal null")
super1 should not equal (null)
super1 should not (equal (null))
super1 should (not (equal (null)))
super1 should (not equal (null))
nullSuper should equal (null)
nullSuper shouldEqual null
nullSuper should (equal (null))
nullSuper should not equal (super1)
nullSuper should not (equal (super1))
nullSuper should (not equal (super1))
nullSuper should (not (equal (super1)))
val caught3 = intercept[TestFailedException] { nullSuper should not equal (null) }
caught3.getMessage should be ("The reference equaled null")
val caught4 = intercept[TestFailedException] { nullSuper should not (equal (null)) }
caught4.getMessage should be ("The reference equaled null")
val caught5 = intercept[TestFailedException] { nullSuper should (not equal (null)) }
caught5.getMessage should be ("The reference equaled null")
val caught6 = intercept[TestFailedException] { nullSuper should (not (equal (null))) }
caught6.getMessage should be ("The reference equaled null")
val caught7 = intercept[TestFailedException] { nullSuper should equal (super1) }
caught7.getMessage should be ("null did not equal Super(1)")
val caught8 = intercept[TestFailedException] { nullSuper should (equal (super1)) }
caught8.getMessage should be ("null did not equal Super(1)")
}
it("should work sensibly if null is passed on the left or right hand side, when used with logical and") {
val caught1 = intercept[TestFailedException] { super1 should (equal (null) and equal (null)) }
caught1.getMessage should be ("Super(1) did not equal null")
val caught2 = intercept[TestFailedException] { super1 should (equal (super1) and equal (null)) }
caught2.getMessage should be ("Super(1) equaled Super(1), but Super(1) did not equal null")
super1 should not (equal (null) and equal (null))
val caught3 = intercept[TestFailedException] { nullSuper should (not equal (null)) }
caught3.getMessage should be ("The reference equaled null")
val caught4 = intercept[TestFailedException] { nullSuper should (equal (null) and not (equal (null))) }
caught4.getMessage should be ("The reference equaled null, but the reference equaled null")
val caught5 = intercept[TestFailedException] { nullSuper should (equal (null) and not equal (null)) }
caught5.getMessage should be ("The reference equaled null, but the reference equaled null")
}
it("should work sensibly if null is passed on the left or right hand side, when used with logical or") {
val caught1 = intercept[TestFailedException] { super1 should (equal (null) or equal (null)) }
caught1.getMessage should be ("Super(1) did not equal null, and Super(1) did not equal null")
val caught2 = intercept[TestFailedException] { super1 should (equal (null) or (equal (null))) }
caught2.getMessage should be ("Super(1) did not equal null, and Super(1) did not equal null")
super1 should not (equal (null) or equal (null))
super1 should not (equal (null) or (equal (null)))
super1 should (equal (null) or equal (super1))
super1 should (equal (super1) or equal (null))
super1 should (equal (null) or (equal (super1)))
super1 should (equal (super1) or (equal (null)))
val caught3 = intercept[TestFailedException] { nullSuper should (not equal (null) or not (equal (null))) }
caught3.getMessage should be ("The reference equaled null, and the reference equaled null")
val caught4 = intercept[TestFailedException] { nullSuper should (not equal (null) or not (equal (null))) }
caught4.getMessage should be ("The reference equaled null, and the reference equaled null")
val caught5 = intercept[TestFailedException] { nullSuper should (not equal (null) or (not equal (null))) }
caught5.getMessage should be ("The reference equaled null, and the reference equaled null")
val caught6 = intercept[TestFailedException] { nullSuper should (not equal (null) or (not (equal (null)))) }
caught6.getMessage should be ("The reference equaled null, and the reference equaled null")
val caught7 = intercept[TestFailedException] { nullSuper should (not equal (null) or not equal (null)) }
caught7.getMessage should be ("The reference equaled null, and the reference equaled null")
}
}
}
| dotty-staging/scalatest | scalatest-test/src/test/scala/org/scalatest/ShouldEqualNullSpec.scala | Scala | apache-2.0 | 5,939 |
package yugioh
import yugioh.action.{ActionModule, NoAction, PlayerCause}
import yugioh.action.monster.{Battle, DeclareAttackOnMonster, DeclareDirectAttack}
import yugioh.card.monster.{Attack, Defense, Monster, Set}
import yugioh.events._
sealed trait Step
trait BattlePhaseModule {
def loop(gameState: GameState)(implicit eventsModule: EventsModule, actionModule: ActionModule)
}
trait BattlePhaseModuleComponent {
implicit def battlePhaseModule: BattlePhaseModule
}
trait DefaultBattlePhaseModuleComponent extends BattlePhaseModuleComponent {
override def battlePhaseModule: BattlePhaseModule = new BattlePhaseModule {
def loop(gameState: GameState)(implicit eventsModule: EventsModule, actionModule: ActionModule): Unit = {
var battlePhaseStep: BattlePhaseStep = StartStep
do {
battlePhaseStep.emitStartEvent()
val nextBattlePhaseStepAndMonster = battlePhaseStep.next(gameState)
battlePhaseStep.emitEndEvent()
battlePhaseStep = nextBattlePhaseStepAndMonster
} while (battlePhaseStep != null)
}
}
}
sealed trait BattlePhaseStep extends Step {
def emitStartEvent()(implicit eventsModule: EventsModule): Unit = eventsModule.emit(BattlePhaseStepStartEvent(this))
def emitEndEvent()(implicit eventsModule: EventsModule): Unit = eventsModule.emit(BattlePhaseStepEndEvent(this))
def next(gameState: GameState)(implicit eventsModule: EventsModule, actionModule: ActionModule): BattlePhaseStep
}
case object StartStep extends BattlePhaseStep {
override def next(gameState: GameState)(implicit eventsModule: EventsModule, actionModule: ActionModule): BattleStep.type = {
FastEffectTiming.loop(gameState.copy(step = this))
BattleStep
}
}
case object BattleStep extends BattlePhaseStep {
override def next(gameState: GameState)(implicit eventsModule: EventsModule, actionModule: ActionModule): BattlePhaseStep = {
var attacker: Monster = null
var target: Monster = null
val subscription = eventsModule.observe {
case ActionEvent(DeclareAttackOnMonster(_, theAttacker, theTarget)) =>
attacker = theAttacker
target = theTarget
case ActionEvent(DeclareDirectAttack(_, theAttacker)) =>
attacker = theAttacker
}
// listen for an attack declaration here
FastEffectTiming.loop(gameState.copy(step = this))
subscription.dispose()
if (attacker != null) {
BattleStepWithPendingAttack(Battle(attacker, Option(target)))
} else {
EndStep
}
}
}
case class BattleStepWithPendingAttack(battle: Battle) extends BattlePhaseStep {
override def next(gameState: GameState)(implicit eventsModule: EventsModule, actionModule: ActionModule): DamageStep = {
FastEffectTiming.loop(gameState.copy(step = this), start = CheckForTrigger(Nil))
// TODO: replays - BattleStepWithPendingAttack -> BattleStep instead of DamageStep
DamageStep(battle)
}
}
case class DamageStep(battle: Battle) extends BattlePhaseStep {
override def next(gameState: GameState)(implicit eventsModule: EventsModule, actionModule: ActionModule): BattleStep.type = {
DamageStepSubStep.loop(battle)(gameState.copy(step = this), eventsModule, actionModule)
BattleStep
}
}
case object EndStep extends BattlePhaseStep {
override def next(gameState: GameState)(implicit eventsModule: EventsModule, actionModule: ActionModule): Null = {
FastEffectTiming.loop(gameState.copy(step = this))
null
}
}
sealed trait DamageStepSubStep extends Step {
def performAndGetNext(battle: Battle)
(implicit gameState: GameState, eventsModule: EventsModule, actionModule: ActionModule): DamageStepSubStep
}
object DamageStepSubStep {
def loop(battle: Battle)(implicit gameState: GameState, eventsModule: EventsModule, actionModule: ActionModule): Unit = {
var subStep: DamageStepSubStep = StartOfTheDamageStep
do {
eventsModule.emit(DamageSubStepStartEvent(subStep))
val nextSubStep = subStep.performAndGetNext(battle)
eventsModule.emit(DamageSubStepEndEvent(subStep))
subStep = nextSubStep
} while (subStep != null)
}
}
// http://www.yugioh-card.com/uk/gameplay/damage.html
case object StartOfTheDamageStep extends DamageStepSubStep {
override def performAndGetNext(battle: Battle)
(implicit gameState: GameState, eventsModule: EventsModule, actionModule: ActionModule): BeforeDamageCalculation.type = {
FastEffectTiming.loop(gameState.copy(step = this))
BeforeDamageCalculation
}
}
case object BeforeDamageCalculation extends DamageStepSubStep {
override def performAndGetNext(battle: Battle)
(implicit gameState: GameState, eventsModule: EventsModule, actionModule: ActionModule): PerformDamageCalculation.type = {
// flip the target if need be
battle match {
case Battle(_, Some(target)) =>
for (controlledState <- target.maybeControlledState)
if (controlledState.position == Set) {
controlledState.position = Defense
eventsModule.emit(FlippedRegular(target, battle))
}
case _ =>
}
FastEffectTiming.loop(gameState.copy(step = this))
PerformDamageCalculation
}
}
case object PerformDamageCalculation extends DamageStepSubStep {
override def performAndGetNext(battle: Battle)
(implicit gameState: GameState, eventsModule: EventsModule, actionModule: ActionModule): AfterDamageCalculation = {
FastEffectTiming.loop(gameState.copy(step = this))
var destroyed: Set[Monster] = collection.immutable.Set()
val subscription = eventsModule.observe {
case ActionEvent(DestroyByBattle(_, monster, _)) =>
destroyed += monster
}
battle match {
case Battle(attacker, None) =>
CauseBattleDamage(PlayerCause(attacker.controller), gameState.turnPlayers.turnPlayer, gameState.turnPlayers.opponent, attacker.attack).execute()
case Battle(attacker, Some(target)) =>
for {
monsterControlledState <- target.maybeControlledState
position = monsterControlledState.position
turnPlayer = gameState.turnPlayers.turnPlayer
}
position match {
case Defense =>
if (attacker.attack > target.defense) {
if (attacker.isPiercing) {
CauseBattleDamage(turnPlayer, gameState.turnPlayers.turnPlayer, gameState.turnPlayers.opponent, attacker.attack - target.defense).execute()
} else {
NoAction(turnPlayer)
}.andThen(DestroyByBattle(turnPlayer, target, attacker)).execute()
}
// TODO: damage from attacking a monster with higher defense
case Attack =>
// if both have 0 attack, nothing happens here
if (attacker.attack != 0 || target.attack != 0) {
val difference = attacker.attack - target.attack
(difference.signum match { // get the sign of the difference
case -1 => // attacker destroyed
CauseBattleDamage(turnPlayer, gameState.turnPlayers.opponent, gameState.turnPlayers.turnPlayer, difference)
.also(DestroyByBattle(turnPlayer, attacker, target))
case 0 =>
DestroyByBattle(turnPlayer, attacker, target)
.also(DestroyByBattle(turnPlayer, target, attacker))
case 1 => // target destroyed
CauseBattleDamage(turnPlayer, gameState.turnPlayers.opponent, gameState.turnPlayers.turnPlayer, difference)
.also(DestroyByBattle(turnPlayer, target, attacker))
}).execute()
}
case Set =>
throw new IllegalStateException("Attacked monster should have been flipped face up.")
}
}
subscription.dispose()
AfterDamageCalculation(destroyed)
}
}
case class AfterDamageCalculation(destroyed: Set[Monster]) extends DamageStepSubStep {
override def performAndGetNext(battle: Battle)
(implicit gameState: GameState, eventsModule: EventsModule, actionModule: ActionModule): EndOfTheDamageStep = {
FastEffectTiming.loop(gameState.copy(step = this))
EndOfTheDamageStep(destroyed)
}
}
case class EndOfTheDamageStep(destroyed: Set[Monster]) extends DamageStepSubStep {
override def performAndGetNext(battle: Battle)
(implicit gameState: GameState, eventsModule: EventsModule, actionModule: ActionModule): Null = {
for (monster <- destroyed) {
monster.sendToGrave(battle.attacker.controller)
DestroyByBattle(monster.controller, monster, battle.attacker).execute()
}
FastEffectTiming.loop(gameState.copy(step = this))
null
}
}
| micseydel/yugioh | src/main/scala/yugioh/BattlePhaseStep.scala | Scala | mit | 8,872 |
package org.jetbrains.plugins.scala
package lang
package psi
package impl
package base
package patterns
import com.intellij.lang.ASTNode
import org.jetbrains.plugins.scala.lang.psi.api.base.patterns._
/**
* @author Alexander Podkhalyuzin
* Date: 28.02.2008
*/
class ScCaseClausesImpl(node: ASTNode) extends ScalaPsiElementImpl (node) with ScCaseClauses{
override def toString: String = "CaseClauses"
} | ilinum/intellij-scala | src/org/jetbrains/plugins/scala/lang/psi/impl/base/patterns/ScCaseClausesImpl.scala | Scala | apache-2.0 | 407 |
/*
* Copyright (C) 2011-2013 org.bayswater
*
* 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.bayswater.musicrest.abc
import net.liftweb.json._
import scalaz.Validation
import scalaz.{ \/, -\/, \/- }
import scalaz.syntax.validation._
import spray.http._
import spray.httpx.marshalling._
import spray.util.LoggingContext
import MediaTypes._
import scala.concurrent.{ ExecutionContext, Future, Promise }
import java.io.{File, BufferedInputStream, FileInputStream}
import org.bayswater.musicrest.typeconversion.Transcoder
import org.bayswater.musicrest.MusicRestSettings
import org.bayswater.musicrest.MusicRestService._
import org.bayswater.musicrest.model.TuneModel
import org.bayswater.musicrest.Util
case class Tune(genre: String, name: String) {
// methods that allow over-riding of content negotiation
// as Html
def asHtml: Validation[String, String] =
Tune.tuneToValidString(this, ContentType(MediaTypes.`text/html`))
// as json
def asJson: Validation[String, String] =
Tune.tuneToValidString(this, ContentTypes.`application/json`)
// as ABC
def asAbc: Validation[String, String] =
Tune.tuneToValidString(this, ContentType(Tune.AbcType))
// as a future binary representation defined by the requested file type extension
def asFutureBinary(contentType: ContentType)(implicit executor: ExecutionContext): Future[Validation[String, BinaryImage]] =
Tune.tuneToFutureBinary(this, contentType)
// as a future binary representation defined by the requested file type extension
def asFutureTemporaryImage()(implicit executor: ExecutionContext): Future[Validation[String, BinaryImage]] =
Tune.tuneToTemporaryPngImage(this)
// as a boolean string value
def exists(): String =
Tune.exists(this).toString
def safeFileName = name.filter(_.isLetterOrDigit)
}
object Tune {
case class WavFile(file: File)
// ABC has its own MIME type
val AbcType = register(
MediaType.custom(
mainType = "text",
subType = "vnd.abc",
compressible = true,
binary = false,
fileExtensions = Seq("abc")))
/** Meta-Marshaller for a Validation. But, we shouldn't throw an exception here! Trouble is, currently
* with Spray, if (say) we're serving binary content, we can't change our mind and provide a
* text/plain error message because we have no access within a marshaller to the response headers - we simply
* have to rely on the content negotiation specified by the top level marshaller.
*
* Need to wait for this fix:
*
* https://github.com/spray/spray/issues/293
*
*/
implicit def validationMarshaller[B](implicit mb: Marshaller[B]) =
Marshaller[Validation[String, B]] { (value, ctx) ⇒
value fold (
e => throw new MusicRestException(e),
s ⇒ mb(s, ctx)
)
}
/* Marshaller for a Binary Image */
implicit val binaryImageMarshaller =
Marshaller.of[BinaryImage] (`application/pdf`,
`application/postscript`,
`image/png`,
`audio/midi`) {
(value, requestedContentType, ctx) ⇒ {
val bytes:Array[Byte] = Util.readInput(value.stream)
ctx.marshalTo(HttpEntity(requestedContentType, bytes))
}
}
/* we over-ride the Spray basic String marshaller because we already represent the
* various string-like content types as Strings. The default behaviour in Spray is to
* represent XML as NodeSeqs, and Json as a binary. I want to simplify the Validation
* containers with just two contained types - String(like) and binary
*/
implicit val stringLikeMarshaller =
Marshaller.of[String] (`text/plain`,
Tune.AbcType,
`text/xml`,
`application/json`) {
(value, requestedContentType, ctx) ⇒ {
ctx.marshalTo(HttpEntity(requestedContentType, value))
}
}
/* doesn't work yet because getFromFile is a directive (only works within routes)
*
* we need instead to wait for this release
* https://groups.google.com/forum/#!topic/spray-user/VKVDspJjIV8
*
implicit val wavFileMarshaller =
Marshaller.of[WavFile] (`audio/wav`) {
(value, requestedContentType, ctx) ⇒ {
val chunks = getFromFile(value.file)
ctx.marshalTo(HttpEntity(requestedContentType, chunks))
}
}
*
*/
// to a Future Binary of type defined by the request fileType extension (from the URL)
def tuneToFutureBinary (tune: Tune, contentType: ContentType) (implicit executor: ExecutionContext): Future[Validation[String, BinaryImage]] = {
val tuneOpt:Option[AbcMongo] = TuneModel().getTune(tune.genre, tune.name)
val futOpt = for {
t <- tuneOpt
} yield { Abc(t).toFutureBinary(contentType.mediaType) }
futOpt.getOrElse(Promise.failed(new MusicRestException(tune.name + " not found in genre " + tune.genre + " for " + contentType.mediaType)).future)
}
/** return the (future) temporary png image of a tune as the result of a 'try tune' transcode attempt */
def tuneToTemporaryPngImage(tune: Tune) (implicit executor: ExecutionContext): Future[Validation[String, BinaryImage]] = Future {
val safeFileName = tune.name.filter(_.isLetterOrDigit)
// val filePath = MusicRestSettings.pdfDirTry + "/" + genre + "/" + safeFileName + "." + "png"
val filePath = Transcoder.fullFilePath(MusicRestSettings.pdfDirTry, tune.genre, safeFileName, "png")
val file = new File(filePath)
println("looking for temporary tune image at path " + filePath)
val content:Validation[String, BinaryImage] = if (file.exists()) {
val bis = new BufferedInputStream(new FileInputStream(file))
val mediaType = ContentType(`image/png`).mediaType
val binaryImage = BinaryImage(mediaType, bis)
binaryImage.success
}
else ("Temporary image for " + tune.name + " not found at path " + filePath).failure[BinaryImage]
content
}
/** return the tune as a wav file
*
* I've not yet bothered to wrap in a Future here but I think I should. Eventually, wav file contents
* are returned via getFromFile which runs asynchronously, but there is still quite a computational cost
* in first doing the file-based transcoding.
*
* But, I think I'll wait for this to hit a mainstream release:
*
* https://groups.google.com/forum/#!searchin/spray-user/getFromFile/spray-user/VKVDspJjIV8/3BMTYoPNc54J
* */
def tuneToWav(tune: Tune, instrument:String, transpose: Int, tempo: String)(implicit log: LoggingContext): Validation[String, File] = {
val tuneOpt:Option[AbcMongo] = TuneModel().getTune(tune.genre, tune.name)
// convert to validated ABC
val safeFileName = tune.name.filter(_.isLetterOrDigit)
val filePath = Transcoder.fullWavPath(MusicRestSettings.wavDirPlay, tune.genre, safeFileName, instrument, transpose, tempo)
val cachedWavFile = new File(filePath)
log.info(s"request for wave file $filePath served from cache? ${cachedWavFile.exists}")
// serve from the cache if we can
if (cachedWavFile.exists) {
cachedWavFile.success
}
else {
val validAbc: Validation[String,Abc] = Abc.validTune(tune, tuneOpt)
(for
{
abc <- validAbc.disjunction
f <- abc.toFile(`audio/wav`, instrument, transpose, tempo).disjunction
} yield f
).validation
}
}
def tuneToValidString(requestedTune: Tune, requestedContentType: ContentType): Validation[String, String] = {
// try to get the requested tune from the database
val tuneOpt:Option[AbcMongo] = TuneModel().getTune(requestedTune.genre, requestedTune.name)
toValidString(Abc.validTune(requestedTune, tuneOpt), requestedContentType)
}
def tuneToValidImage(requestedTune: Tune, requestedContentType: ContentType): Validation[String, BinaryImage] = {
// try to get the requested tune from the database
val tuneOpt:Option[AbcMongo] = TuneModel().getTune(requestedTune.genre, requestedTune.name)
// convert to validated ABC
toValidImage(Abc.validTune(requestedTune, tuneOpt), requestedContentType)
}
def toValidString(validAbc: Validation[String, Abc], requestedContentType: ContentType): Validation[String, String] =
(for
{
abc <- validAbc.disjunction
p <- abc.toStr(requestedContentType.mediaType).disjunction
} yield p
).validation
def toValidImage(validAbc: Validation[String, Abc], requestedContentType: ContentType): Validation[String, BinaryImage] =
(for
{
abc <- validAbc.disjunction
p <- abc.to(requestedContentType.mediaType).disjunction
} yield p
).validation
def exists(requestedTune: Tune): Boolean = {
// try to get the requested tune from the database
// println(s"Existence check for genre: ${requestedTune.genre}, tune: ${requestedTune.name}" )
val tuneOpt:Option[AbcMongo] = TuneModel().getTune(requestedTune.genre, requestedTune.name)
tuneOpt.map(x => true).getOrElse(false)
}
implicit def tuneMarshaller(implicit mBinaryImage: Marshaller[Validation[String, BinaryImage]],
mString: Marshaller[Validation[String, String]]) =
Marshaller.of[Tune](
`text/plain`,
`text/xml`,
Tune.AbcType,
`application/json`,
`application/pdf`,
`application/postscript`,
`image/png`,
`audio/midi`) {
(value, contentType, ctx) ⇒
if (contentType.mediaType.binary && contentType.mediaType != `application/json`) {
// println("tune marshaller requested tune binary content type "+ contentType)
val image = tuneToValidImage(value,contentType)
mBinaryImage(image, ctx)
}
else {
// println("tune marshaller requested tune string content type "+ contentType)
val s = tuneToValidString(value,contentType)
mString(s, ctx)
}
}
}
| newlandsvalley/musicrest | src/main/scala/org/bayswater/musicrest/abc/Tune.scala | Scala | apache-2.0 | 10,739 |
/*
* 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.knockdata.spark.highcharts.model
import com.knockdata.spark.highcharts.base.BaseModel
class Tooltip extends BaseModel with PublicApply {
override def fieldName: String = "tooltip"
def animation(value: Boolean): this.type = {
append("animation", value)
}
def backgroundColor(value: String): this.type = {
append("backgroundColor", value)
}
def borderColor(value: String): this.type = {
append("borderColor", value)
}
def borderRadius(value: Int): this.type = {
append("borderRadius", value)
}
def crosshairs(value: String): this.type = {
throw new Exception("using crosshairs in Axis instead")
}
def dateTimeLabelFormats(value: String): this.type = {
append("dateTimeLabelFormats", value)
}
def enabled(value: Boolean): this.type = {
append("enabled", value)
}
def followPointer(value: Boolean): this.type = {
append("followPointer", value)
}
def followTouchMove(value: String): this.type = {
append("followTouchMove", value)
}
def footerFormat(value: String): this.type = {
append("footerFormat", value)
}
def formatter(value: String): this.type = {
append("formatter", placeholdCode(value))
}
def headerFormat(format: String): this.type = {
append("headerFormat", format)
}
def hideDelay(value: Int): this.type = {
append("hideDelay", value)
}
def pointFormat(format: String): this.type = {
append("pointFormat", format)
}
def pointFormatter(value: String): this.type = {
append("pointFormatter", placeholdCode(value))
}
def positioner(value: String): this.type = {
append("positioner", placeholdCode(value))
}
def shadow(value: Boolean): this.type = {
append("shadow", value)
}
def shape(value: String): this.type = {
append("shape", value)
}
def shared(value: Boolean): this.type = {
append("shared", value)
}
def snap(value: Int): this.type = {
append("snap", value)
}
def style(values: (String, Any)*): this.type = {
append("style", values.toMap)
}
def useHTML(value: Boolean): this.type = {
append("useHTML", value)
}
def valueDecimals(value: Int): this.type = {
append("valueDecimals", value)
}
def valuePrefix(value: String): this.type = {
append("valuePrefix", value)
}
def valueSuffix(value: String): this.type = {
append("valueSuffix", value)
}
def xDateFormat(value: String): this.type = {
append("xDateFormat", value)
}
}
| knockdata/spark-highcharts | src/main/scala/com/knockdata/spark/highcharts/model/Tooltip.scala | Scala | apache-2.0 | 3,272 |
package models.consul
import play.api.libs.json.Json
case class CheckInfo(
Node: String,
CheckID: String,
Name: String,
Status: String,
Notes: String,
Output: String,
ServiceID: String,
ServiceName: String
)
object CheckInfo {
implicit val jsonFormat = Json.format[CheckInfo]
} | leanovate/microzon-web | app/models/consul/CheckInfo.scala | Scala | mit | 480 |
package org.hatdex.hat.she.mappers
import java.util.UUID
import org.hatdex.hat.api.models.{
EndpointQuery,
EndpointQueryFilter,
PropertyQuery
}
import org.hatdex.hat.api.models.applications.{
DataFeedItem,
DataFeedItemContent,
DataFeedItemLocation,
DataFeedItemTitle,
LocationAddress,
LocationGeo
}
import org.hatdex.hat.she.models.StaticDataValues
import org.joda.time.DateTime
import play.api.libs.json.{ JsNull, JsObject, JsValue }
import scala.util.{ Failure, Try }
class TwitterProfileMapper extends DataEndpointMapper with FeedItemComparator {
def dataQueries(
fromDate: Option[DateTime],
untilDate: Option[DateTime]
): Seq[PropertyQuery] = {
Seq(
PropertyQuery(
List(
EndpointQuery(
"twitter/tweets",
None,
dateFilter(fromDate, untilDate).map(f =>
Seq(EndpointQueryFilter("lastUpdated", None, f))
),
None
)
),
Some("lastUpdated"),
Some("descending"),
None
)
)
}
def mapDataRecord(
recordId: UUID,
content: JsValue,
tailRecordId: Option[UUID] = None,
tailContent: Option[JsValue] = None
): Try[DataFeedItem] = {
val comparison =
compare(content, tailContent).filter(
_._1 == false
) // remove all fields that have the same values pre/current
if (comparison.isEmpty) {
Failure(new RuntimeException("Comparision Failure. Data the same"))
} else {
for {
title <- Try(
DataFeedItemTitle("Your Twitter Profile has changed.", None, None)
)
itemContent <- {
val contentText = comparison.map(item => s"${item._2}\\n").mkString
Try(DataFeedItemContent(Some(contentText), None, None, None))
}
} yield {
DataFeedItem(
"twitter",
(tailContent.getOrElse(content) \\ "lastUpdated").as[DateTime],
Seq("profile"),
Some(title),
Some(itemContent),
None
)
}
}
}
def compare(
content: JsValue,
tailContent: Option[JsValue]
): Seq[(Boolean, String)] = {
if (tailContent.isEmpty)
Seq()
else {
Seq(
compareString(content, tailContent.get, "name", "Name", Some("user")),
compareString(
content,
tailContent.get,
"location",
"Location",
Some("user")
),
compareString(
content,
tailContent.get,
"description",
"Description",
Some("user")
),
compareInt(
content,
tailContent.get,
"friends_count",
"Number of Friends",
Some("user")
),
compareInt(
content,
tailContent.get,
"followers_count",
"Number of Followers",
Some("user")
),
compareInt(
content,
tailContent.get,
"favourites_count",
"Number of Favorites",
Some("user")
),
compareInt(
content,
tailContent.get,
"profile_image_url_https",
"Profile Image",
Some("user")
),
compareInt(
content,
tailContent.get,
"statuses_count",
"Number of Tweets",
Some("user")
)
)
}
}
}
class TwitterFeedMapper extends DataEndpointMapper {
def dataQueries(
fromDate: Option[DateTime],
untilDate: Option[DateTime]
): Seq[PropertyQuery] = {
Seq(
PropertyQuery(
List(
EndpointQuery(
"twitter/tweets",
None,
dateFilter(fromDate, untilDate).map(f =>
Seq(EndpointQueryFilter("lastUpdated", None, f))
),
None
)
),
Some("lastUpdated"),
Some("descending"),
None
)
)
}
def mapDataRecord(
recordId: UUID,
content: JsValue,
tailRecordId: Option[UUID] = None,
tailContent: Option[JsValue] = None
): Try[DataFeedItem] = {
for {
title <- Try(if ((content \\ "retweeted").as[Boolean]) {
DataFeedItemTitle("You retweeted", None, Some("repeat"))
} else if ((content \\ "in_reply_to_user_id").isDefined && !((content \\ "in_reply_to_user_id").get == JsNull)) {
DataFeedItemTitle(
s"You replied to @${(content \\ "in_reply_to_screen_name").as[String]}",
None,
None
)
} else {
DataFeedItemTitle("You tweeted", None, None)
})
itemContent <- Try(
DataFeedItemContent((content \\ "text").asOpt[String], None, None, None)
)
date <- Try((content \\ "lastUpdated").as[DateTime])
} yield {
val location = Try(
DataFeedItemLocation(
geo = (content \\ "coordinates")
.asOpt[JsObject]
.map(coordinates =>
LocationGeo(
(coordinates \\ "coordinates" \\ 0).as[Double],
(coordinates \\ "coordinates" \\ 1).as[Double]
)
),
address = (content \\ "place")
.asOpt[JsObject]
.map(address =>
LocationAddress(
(address \\ "country").asOpt[String],
(address \\ "name").asOpt[String],
None,
None,
None
)
),
tags = None
)
).toOption
.filter(l => l.address.isDefined || l.geo.isDefined || l.tags.isDefined)
DataFeedItem(
"twitter",
date,
Seq("post"),
Some(title),
Some(itemContent),
location
)
}
}
}
class TwitterProfileStaticDataMapper extends StaticDataEndpointMapper {
def dataQueries(): Seq[PropertyQuery] = {
Seq(
PropertyQuery(
List(EndpointQuery("twitter/tweets", None, None, None)),
Some("id"),
Some("descending"),
Some(1)
)
)
}
def mapDataRecord(
recordId: UUID,
content: JsValue,
endpoint: String
): Seq[StaticDataValues] = {
val maybeUserData = (content \\ "user").asOpt[Map[String, JsValue]]
val lastPartOfEndpointString = endpoint.split("/").last
maybeUserData match {
case Some(user) =>
Seq(
StaticDataValues(
lastPartOfEndpointString,
user.filterKeys(key => key != "entities")
)
)
case _ => Seq()
}
}
}
| Hub-of-all-Things/HAT2.0 | hat/app/org/hatdex/hat/she/mappers/TwitterMappers.scala | Scala | agpl-3.0 | 6,590 |
/*
* Copyright (c) 2013 Curry Order System authors.
* This file is part of Curry Order System. Please refer to the NOTICE.txt file for license details.
*/
import org.mortbay.jetty.Connector
import org.mortbay.jetty.Server
import org.mortbay.jetty.webapp.WebAppContext
import org.mortbay.jetty.nio._
object RunWebApp extends Application {
val server = new Server
val scc = new SelectChannelConnector
scc.setPort(8080)
server.setConnectors(Array(scc))
val context = new WebAppContext()
context.setServer(server)
context.setContextPath("/")
context.setWar("src/main/webapp")
server.addHandler(context)
try {
println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP")
server.start()
while (System.in.available() == 0) {
Thread.sleep(5000)
}
server.stop()
server.join()
} catch {
case exc : Exception => {
exc.printStackTrace()
System.exit(100)
}
}
}
| scott-abernethy/curry-order-system | src/test/scala/RunWebApp.scala | Scala | gpl-3.0 | 938 |
package io.github.tailhq.dynaml.graphics.charts.highcharts
/**
* User: austin
* Date: 12/12/14
*/
object Stacking {
type Type = String
val (normal, percent) = ("normal", "percent")
def values = Set(normal, percent)
}
| mandar2812/DynaML | dynaml-core/src/main/scala/io/github/tailhq/dynaml/graphics/charts/highcharts/PlotOptionElements.scala | Scala | apache-2.0 | 227 |
package sigmastate.helpers
import scorex.crypto.hash.Digest32
import special.collection.{Coll, CollOverArray, PairOfCols}
import scorex.util.ModifierId
import org.ergoplatform.{ErgoLikeTransactionTemplate, ErgoLikeTransaction, ErgoLikeContext, UnsignedInput, Input, ErgoBox, DataInput, ErgoBoxCandidate}
import sigmastate.Values.ErgoTree
import org.ergoplatform.ErgoBox.{AdditionalRegisters, allZerosModifierId, TokenId}
import org.ergoplatform.validation.SigmaValidationSettings
import sigmastate.AvlTreeData
import sigmastate.eval.CostingSigmaDslBuilder
import sigmastate.eval._
import sigmastate.interpreter.ContextExtension
import special.sigma.{PreHeader, Header}
import scala.collection.mutable.WrappedArray
// TODO refactor: unification is required between two hierarchies of tests
// and as part of it, more methods can be moved to TestingHelpers
/** A collection of helper methods which can be used across test suites. */
object TestingHelpers {
def testBox(value: Long,
ergoTree: ErgoTree,
creationHeight: Int,
additionalTokens: Seq[(TokenId, Long)] = WrappedArray.empty,
additionalRegisters: AdditionalRegisters = Map.empty,
transactionId: ModifierId = allZerosModifierId,
boxIndex: Short = 0): ErgoBox =
new ErgoBox(value, ergoTree,
CostingSigmaDslBuilder.Colls.fromArray(additionalTokens.toArray[(TokenId, Long)]),
additionalRegisters,
transactionId, boxIndex, creationHeight)
def createBox(value: Long,
proposition: ErgoTree,
additionalTokens: Seq[(Digest32, Long)] = WrappedArray.empty,
additionalRegisters: AdditionalRegisters = Map.empty)
= testBox(value, proposition, 0, additionalTokens, additionalRegisters)
/** Creates a new test box with the given parameters. */
def createBox(value: Long,
proposition: ErgoTree,
creationHeight: Int)
= testBox(value, proposition, creationHeight, WrappedArray.empty, Map.empty, ErgoBox.allZerosModifierId)
/** Creates a clone instance of the given collection by recursively cloning all the underlying
* sub-collections.
*/
def cloneColl[A](c: Coll[A]): Coll[A] = (c match {
case c: CollOverArray[_] =>
new CollOverArray(c.toArray.clone())(c.tItem)
case ps: PairOfCols[_,_] =>
new PairOfCols(cloneColl(ps.ls), cloneColl(ps.rs))
}).asInstanceOf[Coll[A]]
/** Copies the given box allowing also to update fields. */
def copyBox(box: ErgoBox)(
value: Long = box.value,
ergoTree: ErgoTree = box.ergoTree,
additionalTokens: Coll[(TokenId, Long)] = box.additionalTokens,
additionalRegisters: AdditionalRegisters = box.additionalRegisters,
transactionId: ModifierId = box.transactionId,
index: Short = box.index,
creationHeight: Int = box.creationHeight): ErgoBox = {
new ErgoBox(value, ergoTree, additionalTokens, additionalRegisters, transactionId, index, creationHeight)
}
/** Copies the given transaction allowing also to update fields.
* NOTE: it can be used ONLY for instances of ErgoLikeTransaction.
* @tparam T used here to limit use of this method to only ErgoLikeTransaction instances
* @return a new instance of [[ErgoLikeTransaction]]. */
def copyTransaction[T >: ErgoLikeTransaction <: ErgoLikeTransaction](tx: T)(
inputs: IndexedSeq[Input] = tx.inputs,
dataInputs: IndexedSeq[DataInput] = tx.dataInputs,
outputCandidates: IndexedSeq[ErgoBoxCandidate] = tx.outputCandidates) = {
new ErgoLikeTransaction(inputs, dataInputs, outputCandidates)
}
/** Copies the given context allowing also to update fields. */
def copyContext(ctx: ErgoLikeContext)(
lastBlockUtxoRoot: AvlTreeData = ctx.lastBlockUtxoRoot,
headers: Coll[Header] = ctx.headers,
preHeader: PreHeader = ctx.preHeader,
dataBoxes: IndexedSeq[ErgoBox] = ctx.dataBoxes,
boxesToSpend: IndexedSeq[ErgoBox] = ctx.boxesToSpend,
spendingTransaction: ErgoLikeTransactionTemplate[_ <: UnsignedInput] = ctx.spendingTransaction,
selfIndex: Int = ctx.selfIndex,
extension: ContextExtension = ctx.extension,
validationSettings: SigmaValidationSettings = ctx.validationSettings,
costLimit: Long = ctx.costLimit,
initCost: Long = ctx.initCost,
activatedScriptVersion: Byte = ctx.activatedScriptVersion): ErgoLikeContext = {
new ErgoLikeContext(
lastBlockUtxoRoot, headers, preHeader, dataBoxes, boxesToSpend,
spendingTransaction, selfIndex, extension, validationSettings,
costLimit, initCost, activatedScriptVersion)
}
/** Creates a new box by updating some of the additional registers with the given new bindings.
* @param newBindings a map of the registers to be updated with new values
*/
def updatedRegisters(box: ErgoBox, newBindings: AdditionalRegisters): ErgoBox = {
copyBox(box)(additionalRegisters = box.additionalRegisters ++ newBindings)
}
/**
* Create fake transaction with provided outputCandidates, but without inputs and data inputs.
* Normally, this transaction will be invalid as far as it will break rule that sum of
* coins in inputs should not be less then sum of coins in outputs, but we're not checking it
* in our test cases
*/
def createTransaction(outputCandidates: IndexedSeq[ErgoBoxCandidate]): ErgoLikeTransaction = {
new ErgoLikeTransaction(WrappedArray.empty, WrappedArray.empty, outputCandidates)
}
def createTransaction(box: ErgoBoxCandidate): ErgoLikeTransaction = createTransaction(Array(box))
def createTransaction(dataInputs: IndexedSeq[ErgoBox],
outputCandidates: IndexedSeq[ErgoBoxCandidate]): ErgoLikeTransaction =
new ErgoLikeTransaction(WrappedArray.empty, dataInputs.map(b => DataInput(b.id)), outputCandidates)
}
| ScorexFoundation/sigmastate-interpreter | sigmastate/src/test/scala/sigmastate/helpers/TestingHelpers.scala | Scala | mit | 5,878 |
package xitrum.view
import scala.util.control.NonFatal
import org.fusesource.scalate.InvalidSyntaxException
import org.fusesource.scalate.Template
import xitrum.Action
/** Additional utility methods. */
trait ScalateEngineRenderTemplate {
this: ScalateEngine =>
def renderTemplateFile(templateUri: String)(implicit currentAction: Action): String =
renderTemplateFile(templateUri, Map.empty)(currentAction)
/**
* Renders Scalate template file.
*
* @param options "date" -> DateFormat, "number" -> NumberFormat
* @param currentAction Will be imported in the template as "helper"
*/
def renderTemplateFile(uri: String, options: Map[String, Any])(implicit currentAction: Action): String = {
val context = createContext(uri, fileEngine, currentAction, options)
try {
fileEngine.layout(uri, context)
context.buffer.toString
} catch {
case e: InvalidSyntaxException =>
throw ScalateEngine.invalidSyntaxExceptionWithErrorLine(e)
case NonFatal(e) =>
throw ScalateEngine.exceptionWithErrorLine(e, uri)
} finally {
context.out.close()
}
}
//----------------------------------------------------------------------------
def renderTemplate(template: Template)(implicit currentAction: Action): String =
renderTemplate(template, "precompiled_template", Map.empty[String, Any])(currentAction)
def renderTemplate(template: Template, options: Map[String, Any])(implicit currentAction: Action): String =
renderTemplate(template, "precompiled_template", options)(currentAction)
def renderTemplate(template: Template, templateUri: String)(implicit currentAction: Action): String =
renderTemplate(template, templateUri, Map.empty[String, Any])(currentAction)
/**
* Renders precompiled Scalate template.
*
* @param template Template object
* @param templateUri URI to identify a template
* @param options "date" -> DateFormat, "number" -> NumberFormat
* @param currentAction Will be imported in the template as "helper"
*/
def renderTemplate(template: Template, templateUri: String, options: Map[String, Any])(implicit currentAction: Action): String = {
val context = createContext(templateUri, fileEngine, currentAction, options)
try {
fileEngine.layout(template, context)
context.buffer.toString
} finally {
context.out.close()
}
}
}
| xitrum-framework/xitrum-scalate | src/main/scala/xitrum/view/ScalateEngineRenderTemplate.scala | Scala | mit | 2,419 |
package me.sgrouples.rogue.naming
import scala.reflect.ClassTag
/** Created by mwielocha on 09/08/16.
*/
sealed trait NamingStrategy {
def apply[T: ClassTag]: String
}
class ClassNamingStrategy(format: Class[_] => String) extends NamingStrategy {
override def apply[T: ClassTag]: String =
format(implicitly[ClassTag[T]].runtimeClass)
}
object LowerCase extends ClassNamingStrategy(_.getSimpleName.toLowerCase())
object PluralLowerCase
extends ClassNamingStrategy(_.getSimpleName.toLowerCase() + "s")
object UpperCase extends ClassNamingStrategy(_.getSimpleName.toUpperCase())
object SnakeCase
extends ClassNamingStrategy(
_.getSimpleName
.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2")
.replaceAll("([a-z\\\\d])([A-Z])", "$1_$2")
.toLowerCase
)
| sgrouples/rogue-fsqio | cc/src/main/scala/me/sgrouples/rogue/naming/NamingStrategy.scala | Scala | apache-2.0 | 798 |
// -----------------------------------------------------------------------------
//
// Scalax - The Scala Community Library
// Copyright (c) 2005-8 The Scalax Project. All rights reserved.
//
// The primary distribution site is http://scalax.scalaforge.org/
//
// This software is released under the terms of the Revised BSD License.
// There is NO WARRANTY. See the file LICENSE for the full text.
//
// -----------------------------------------------------------------------------
package org.json4s.scalap
/** A Rule is a function from some input to a Result. The result may be:
* <ul>
* <li>Success, with a value of some type and an output that may serve as the input to subsequent rules.</li>
* <li>Failure. A failure may result in some alternative rule being applied.</li>
* <li>Error. No further rules should be attempted.</li>
* </ul>
*
* @author Andrew Foggin
*
* Inspired by the Scala parser combinator.
*/
trait Rule[-In, +Out, +A, +X] extends (In => Result[Out, A, X]) {
val factory: Rules
import factory._
def as(name: String) = ruleWithName(name, this)
def flatMap[Out2, B, X2 >: X](fa2ruleb: A => Out => Result[Out2, B, X2]) = mapResult {
case Success(out, a) => fa2ruleb(a)(out)
case Failure => Failure
case err @ Error(_) => err
}
def map[B](fa2b: A => B) = flatMap { a => out => Success(out, fa2b(a)) }
def filter(f: A => Boolean) = flatMap { a => out => if(f(a)) Success(out, a) else Failure }
def mapResult[Out2, B, Y](f: Result[Out, A, X] => Result[Out2, B, Y]) = rule {
in: In => f(apply(in))
}
def orElse[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other: => Rule[In2, Out2, A2, X2]): Rule[In2, Out2, A2, X2] = new Choice[In2, Out2, A2, X2] {
val factory = Rule.this.factory
lazy val choices = Rule.this :: other :: Nil
}
def orError[In2 <: In] = this orElse error[Any]
def |[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other: => Rule[In2, Out2, A2, X2]) = orElse(other)
def ^^[B](fa2b: A => B) = map(fa2b)
def ^^?[B](pf: PartialFunction[A, B]) = filter (pf.isDefinedAt(_)) ^^ pf
def ??(pf: PartialFunction[A, Any]) = filter (pf.isDefinedAt(_))
def -^[B](b: B) = map { any => b }
/** Maps an Error */
def !^[Y](fx2y: X => Y) = mapResult {
case s @ Success(_, _) => s
case Failure => Failure
case Error(x) => Error(fx2y(x))
}
def >>[Out2, B, X2 >: X](fa2ruleb: A => Out => Result[Out2, B, X2]) = flatMap(fa2ruleb)
def >->[Out2, B, X2 >: X](fa2resultb: A => Result[Out2, B, X2]) = flatMap { a => any => fa2resultb(a) }
def >>?[Out2, B, X2 >: X](pf: PartialFunction[A, Rule[Out, Out2, B, X2]]) = filter(pf isDefinedAt _) flatMap pf
def >>&[B, X2 >: X](fa2ruleb: A => Out => Result[Any, B, X2]) = flatMap { a => out => fa2ruleb(a)(out) mapOut { any => out } }
def ~[Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield new ~(a, b)
def ~-[Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield a
def -~[Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield b
def ~++[Out2, B >: A, X2 >: X](next: => Rule[Out, Out2, Seq[B], X2]) = for (a <- this; b <- next) yield a :: b.toList
/** Apply the result of this rule to the function returned by the next rule */
def ~>[Out2, B, X2 >: X](next: => Rule[Out, Out2, A => B, X2]) = for (a <- this; fa2b <- next) yield fa2b(a)
/** Apply the result of this rule to the function returned by the previous rule */
def <~:[InPrev, B, X2 >: X](prev: => Rule[InPrev, In, A => B, X2]) = for (fa2b <- prev; a <- this) yield fa2b(a)
def ~![Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next.orError) yield new ~(a, b)
def ~-![Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next.orError) yield a
def -~![Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next.orError) yield b
def -[In2 <: In](exclude: => Rule[In2, Any, Any, Any]) = !exclude -~ this
/** ^~^(f) is equivalent to ^^ { case b1 ~ b2 => f(b1, b2) }
*/
def ^~^[B1, B2, B >: A <% B1 ~ B2, C](f: (B1, B2) => C) = map { a =>
(a: B1 ~ B2) match { case b1 ~ b2 => f(b1, b2) }
}
/** ^~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 => f(b1, b2, b3) }
*/
def ^~~^[B1, B2, B3, B >: A <% B1 ~ B2 ~ B3, C](f: (B1, B2, B3) => C) = map { a =>
(a: B1 ~ B2 ~ B3) match { case b1 ~ b2 ~ b3 => f(b1, b2, b3) }
}
/** ^~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 => f(b1, b2, b3, b4) }
*/
def ^~~~^[B1, B2, B3, B4, B >: A <% B1 ~ B2 ~ B3 ~ B4, C](f: (B1, B2, B3, B4) => C) = map { a =>
(a: B1 ~ B2 ~ B3 ~ B4) match { case b1 ~ b2 ~ b3 ~ b4 => f(b1, b2, b3, b4) }
}
/** ^~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 => f(b1, b2, b3, b4, b5) }
*/
def ^~~~~^[B1, B2, B3, B4, B5, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5, C](f: (B1, B2, B3, B4, B5) => C) = map { a =>
(a: B1 ~ B2 ~ B3 ~ B4 ~ B5) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 => f(b1, b2, b3, b4, b5) }
}
/** ^~~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) }
*/
def ^~~~~~^[B1, B2, B3, B4, B5, B6, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6, C](f: (B1, B2, B3, B4, B5, B6) => C) = map { a =>
(a: B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) }
}
/** ^~~~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) }
*/
def ^~~~~~~^[B1, B2, B3, B4, B5, B6, B7, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6 ~ B7, C](f: (B1, B2, B3, B4, B5, B6, B7) => C) = map { a =>
(a: B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6 ~ B7) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 ~b7 => f(b1, b2, b3, b4, b5, b6, b7) }
}
/** >~>(f) is equivalent to >> { case b1 ~ b2 => f(b1, b2) }
*/
def >~>[Out2, B1, B2, B >: A <% B1 ~ B2, C, X2 >: X](f: (B1, B2) => Out => Result[Out2, C, X2]) = flatMap { a =>
(a: B1 ~ B2) match { case b1 ~ b2 => f(b1, b2) }
}
/** ^-^(f) is equivalent to ^^ { b2 => b1 => f(b1, b2) }
*/
def ^-^ [B1, B2 >: A, C](f: (B1, B2) => C) = map { b2: B2 => b1: B1 => f(b1, b2) }
/** ^~>~^(f) is equivalent to ^^ { case b2 ~ b3 => b1 => f(b1, b2, b3) }
*/
def ^~>~^ [B1, B2, B3, B >: A <% B2 ~ B3, C](f: (B1, B2, B3) => C) = map { a =>
(a: B2 ~ B3) match { case b2 ~ b3 => b1: B1 => f(b1, b2, b3) }
}
}
trait Choice[-In, +Out, +A, +X] extends Rule[In, Out, A, X] {
def choices: List[Rule[In, Out, A, X]]
def apply(in: In) = {
def oneOf(list: List[Rule[In, Out, A, X]]): Result[Out, A, X] = list match {
case Nil => Failure
case first :: rest => first(in) match {
case Failure => oneOf(rest)
case result => result
}
}
oneOf(choices)
}
override def orElse[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other: => Rule[In2, Out2, A2, X2]): Rule[In2, Out2, A2, X2] = new Choice[In2, Out2, A2, X2] {
val factory = Choice.this.factory
lazy val choices = Choice.this.choices ::: other :: Nil
}
}
| geggo98/json4s | scalap/src/main/scala/org/json4s/scalap/Rule.scala | Scala | apache-2.0 | 7,062 |
package korolev.server
/**
* @author Aleksey Fomkin <[email protected]>
*/
object mimeTypes extends (String => Option[String]) {
def apply(key: String): Option[String] = default.get(key)
// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
val default = Map(
"ez" -> "application/andrew-inset",
"aw" -> "application/applixware",
"atom" -> "application/atom+xml",
"atomcat" -> "application/atomcat+xml",
"atomsvc" -> "application/atomsvc+xml",
"ccxml" -> "application/ccxml+xml",
"cdmia" -> "application/cdmi-capability",
"cdmic" -> "application/cdmi-container",
"cdmid" -> "application/cdmi-domain",
"cdmio" -> "application/cdmi-object",
"cdmiq" -> "application/cdmi-queue",
"cu" -> "application/cu-seeme",
"davmount" -> "application/davmount+xml",
"dbk" -> "application/docbook+xml",
"dssc" -> "application/dssc+der",
"xdssc" -> "application/dssc+xml",
"ecma" -> "application/ecmascript",
"emma" -> "application/emma+xml",
"epub" -> "application/epub+zip",
"exi" -> "application/exi",
"pfr" -> "application/font-tdpfr",
"woff" -> "application/font-woff",
"gml" -> "application/gml+xml",
"gpx" -> "application/gpx+xml",
"gxf" -> "application/gxf",
"stk" -> "application/hyperstudio",
"ink" -> "application/inkml+xml",
"inkml" -> "application/inkml+xml",
"ipfix" -> "application/ipfix",
"jar" -> "application/java-archive",
"ser" -> "application/java-serialized-object",
"class" -> "application/java-vm",
"js" -> "application/javascript",
"json" -> "application/json",
"jsonml" -> "application/jsonml+json",
"lostxml" -> "application/lost+xml",
"hqx" -> "application/mac-binhex40",
"cpt" -> "application/mac-compactpro",
"mads" -> "application/mads+xml",
"mrc" -> "application/marc",
"mrcx" -> "application/marcxml+xml",
"ma" -> "application/mathematica",
"nb" -> "application/mathematica",
"mb" -> "application/mathematica",
"mathml" -> "application/mathml+xml",
"mbox" -> "application/mbox",
"mscml" -> "application/mediaservercontrol+xml",
"metalink" -> "application/metalink+xml",
"meta4" -> "application/metalink4+xml",
"mets" -> "application/mets+xml",
"mods" -> "application/mods+xml",
"m21" -> "application/mp21",
"mp21" -> "application/mp21",
"mp4s" -> "application/mp4",
"doc" -> "application/msword",
"dot" -> "application/msword",
"mxf" -> "application/mxf",
"bin" -> "application/octet-stream",
"dms" -> "application/octet-stream",
"lrf" -> "application/octet-stream",
"mar" -> "application/octet-stream",
"so" -> "application/octet-stream",
"dist" -> "application/octet-stream",
"distz" -> "application/octet-stream",
"pkg" -> "application/octet-stream",
"bpk" -> "application/octet-stream",
"dump" -> "application/octet-stream",
"elc" -> "application/octet-stream",
"deploy" -> "application/octet-stream",
"oda" -> "application/oda",
"opf" -> "application/oebps-package+xml",
"ogx" -> "application/ogg",
"omdoc" -> "application/omdoc+xml",
"onetoc" -> "application/onenote",
"onetoc2" -> "application/onenote",
"onetmp" -> "application/onenote",
"onepkg" -> "application/onenote",
"oxps" -> "application/oxps",
"xer" -> "application/patch-ops-error+xml",
"pdf" -> "application/pdf",
"pgp" -> "application/pgp-encrypted",
"asc" -> "application/pgp-signature",
"sig" -> "application/pgp-signature",
"prf" -> "application/pics-rules",
"p10" -> "application/pkcs10",
"p7m" -> "application/pkcs7-mime",
"p7c" -> "application/pkcs7-mime",
"p7s" -> "application/pkcs7-signature",
"p8" -> "application/pkcs8",
"ac" -> "application/pkix-attr-cert",
"cer" -> "application/pkix-cert",
"crl" -> "application/pkix-crl",
"pkipath" -> "application/pkix-pkipath",
"pki" -> "application/pkixcmp",
"pls" -> "application/pls+xml",
"ai" -> "application/postscript",
"eps" -> "application/postscript",
"ps" -> "application/postscript",
"cww" -> "application/prs.cww",
"pskcxml" -> "application/pskc+xml",
"rdf" -> "application/rdf+xml",
"rif" -> "application/reginfo+xml",
"rnc" -> "application/relax-ng-compact-syntax",
"rl" -> "application/resource-lists+xml",
"rld" -> "application/resource-lists-diff+xml",
"rs" -> "application/rls-services+xml",
"gbr" -> "application/rpki-ghostbusters",
"mft" -> "application/rpki-manifest",
"roa" -> "application/rpki-roa",
"rsd" -> "application/rsd+xml",
"rss" -> "application/rss+xml",
"rtf" -> "application/rtf",
"sbml" -> "application/sbml+xml",
"scq" -> "application/scvp-cv-request",
"scs" -> "application/scvp-cv-response",
"spq" -> "application/scvp-vp-request",
"spp" -> "application/scvp-vp-response",
"sdp" -> "application/sdp",
"setpay" -> "application/set-payment-initiation",
"setreg" -> "application/set-registration-initiation",
"shf" -> "application/shf+xml",
"smi" -> "application/smil+xml",
"smil" -> "application/smil+xml",
"rq" -> "application/sparql-query",
"srx" -> "application/sparql-results+xml",
"gram" -> "application/srgs",
"grxml" -> "application/srgs+xml",
"sru" -> "application/sru+xml",
"ssdl" -> "application/ssdl+xml",
"ssml" -> "application/ssml+xml",
"tei" -> "application/tei+xml",
"teicorpus" -> "application/tei+xml",
"tfi" -> "application/thraud+xml",
"tsd" -> "application/timestamped-data",
"plb" -> "application/vnd.3gpp.pic-bw-large",
"psb" -> "application/vnd.3gpp.pic-bw-small",
"pvb" -> "application/vnd.3gpp.pic-bw-var",
"tcap" -> "application/vnd.3gpp2.tcap",
"pwn" -> "application/vnd.3m.post-it-notes",
"aso" -> "application/vnd.accpac.simply.aso",
"imp" -> "application/vnd.accpac.simply.imp",
"acu" -> "application/vnd.acucobol",
"atc" -> "application/vnd.acucorp",
"acutc" -> "application/vnd.acucorp",
"air" -> "application/vnd.adobe.air-application-installer-package+zip",
"fcdt" -> "application/vnd.adobe.formscentral.fcdt",
"fxp" -> "application/vnd.adobe.fxp",
"fxpl" -> "application/vnd.adobe.fxp",
"xdp" -> "application/vnd.adobe.xdp+xml",
"xfdf" -> "application/vnd.adobe.xfdf",
"ahead" -> "application/vnd.ahead.space",
"azf" -> "application/vnd.airzip.filesecure.azf",
"azs" -> "application/vnd.airzip.filesecure.azs",
"azw" -> "application/vnd.amazon.ebook",
"acc" -> "application/vnd.americandynamics.acc",
"ami" -> "application/vnd.amiga.ami",
"apk" -> "application/vnd.android.package-archive",
"cii" -> "application/vnd.anser-web-certificate-issue-initiation",
"fti" -> "application/vnd.anser-web-funds-transfer-initiation",
"atx" -> "application/vnd.antix.game-component",
"mpkg" -> "application/vnd.apple.installer+xml",
"m3u8" -> "application/vnd.apple.mpegurl",
"swi" -> "application/vnd.aristanetworks.swi",
"iota" -> "application/vnd.astraea-software.iota",
"aep" -> "application/vnd.audiograph",
"mpm" -> "application/vnd.blueice.multipass",
"bmi" -> "application/vnd.bmi",
"rep" -> "application/vnd.businessobjects",
"cdxml" -> "application/vnd.chemdraw+xml",
"mmd" -> "application/vnd.chipnuts.karaoke-mmd",
"cdy" -> "application/vnd.cinderella",
"cla" -> "application/vnd.claymore",
"rp9" -> "application/vnd.cloanto.rp9",
"c4g" -> "application/vnd.clonk.c4group",
"c4d" -> "application/vnd.clonk.c4group",
"c4f" -> "application/vnd.clonk.c4group",
"c4p" -> "application/vnd.clonk.c4group",
"c4u" -> "application/vnd.clonk.c4group",
"c11amc" -> "application/vnd.cluetrust.cartomobile-config",
"c11amz" -> "application/vnd.cluetrust.cartomobile-config-pkg",
"csp" -> "application/vnd.commonspace",
"cdbcmsg" -> "application/vnd.contact.cmsg",
"cmc" -> "application/vnd.cosmocaller",
"clkx" -> "application/vnd.crick.clicker",
"clkk" -> "application/vnd.crick.clicker.keyboard",
"clkp" -> "application/vnd.crick.clicker.palette",
"clkt" -> "application/vnd.crick.clicker.template",
"clkw" -> "application/vnd.crick.clicker.wordbank",
"wbs" -> "application/vnd.criticaltools.wbs+xml",
"pml" -> "application/vnd.ctc-posml",
"ppd" -> "application/vnd.cups-ppd",
"car" -> "application/vnd.curl.car",
"pcurl" -> "application/vnd.curl.pcurl",
"dart" -> "application/vnd.dart",
"rdz" -> "application/vnd.data-vision.rdz",
"uvf" -> "application/vnd.dece.data",
"uvvf" -> "application/vnd.dece.data",
"uvd" -> "application/vnd.dece.data",
"uvvd" -> "application/vnd.dece.data",
"uvt" -> "application/vnd.dece.ttml+xml",
"uvvt" -> "application/vnd.dece.ttml+xml",
"uvx" -> "application/vnd.dece.unspecified",
"uvvx" -> "application/vnd.dece.unspecified",
"uvz" -> "application/vnd.dece.zip",
"uvvz" -> "application/vnd.dece.zip",
"fe_launch" -> "application/vnd.denovo.fcselayout-link",
"dna" -> "application/vnd.dna",
"mlp" -> "application/vnd.dolby.mlp",
"dpg" -> "application/vnd.dpgraph",
"dfac" -> "application/vnd.dreamfactory",
"kpxx" -> "application/vnd.ds-keypoint",
"ait" -> "application/vnd.dvb.ait",
"svc" -> "application/vnd.dvb.service",
"geo" -> "application/vnd.dynageo",
"mag" -> "application/vnd.ecowin.chart",
"nml" -> "application/vnd.enliven",
"esf" -> "application/vnd.epson.esf",
"msf" -> "application/vnd.epson.msf",
"qam" -> "application/vnd.epson.quickanime",
"slt" -> "application/vnd.epson.salt",
"ssf" -> "application/vnd.epson.ssf",
"es3" -> "application/vnd.eszigno3+xml",
"et3" -> "application/vnd.eszigno3+xml",
"ez2" -> "application/vnd.ezpix-album",
"ez3" -> "application/vnd.ezpix-package",
"fdf" -> "application/vnd.fdf",
"mseed" -> "application/vnd.fdsn.mseed",
"seed" -> "application/vnd.fdsn.seed",
"dataless" -> "application/vnd.fdsn.seed",
"gph" -> "application/vnd.flographit",
"ftc" -> "application/vnd.fluxtime.clip",
"fm" -> "application/vnd.framemaker",
"frame" -> "application/vnd.framemaker",
"maker" -> "application/vnd.framemaker",
"book" -> "application/vnd.framemaker",
"fnc" -> "application/vnd.frogans.fnc",
"ltf" -> "application/vnd.frogans.ltf",
"fsc" -> "application/vnd.fsc.weblaunch",
"oas" -> "application/vnd.fujitsu.oasys",
"oa2" -> "application/vnd.fujitsu.oasys2",
"oa3" -> "application/vnd.fujitsu.oasys3",
"fg5" -> "application/vnd.fujitsu.oasysgp",
"bh2" -> "application/vnd.fujitsu.oasysprs",
"ddd" -> "application/vnd.fujixerox.ddd",
"xdw" -> "application/vnd.fujixerox.docuworks",
"xbd" -> "application/vnd.fujixerox.docuworks.binder",
"fzs" -> "application/vnd.fuzzysheet",
"txd" -> "application/vnd.genomatix.tuxedo",
"ggb" -> "application/vnd.geogebra.file",
"ggt" -> "application/vnd.geogebra.tool",
"gex" -> "application/vnd.geometry-explorer",
"gre" -> "application/vnd.geometry-explorer",
"gxt" -> "application/vnd.geonext",
"g2w" -> "application/vnd.geoplan",
"g3w" -> "application/vnd.geospace",
"gmx" -> "application/vnd.gmx",
"kml" -> "application/vnd.google-earth.kml+xml",
"kmz" -> "application/vnd.google-earth.kmz",
"gqf" -> "application/vnd.grafeq",
"gqs" -> "application/vnd.grafeq",
"gac" -> "application/vnd.groove-account",
"ghf" -> "application/vnd.groove-help",
"gim" -> "application/vnd.groove-identity-message",
"grv" -> "application/vnd.groove-injector",
"gtm" -> "application/vnd.groove-tool-message",
"tpl" -> "application/vnd.groove-tool-template",
"vcg" -> "application/vnd.groove-vcard",
"hal" -> "application/vnd.hal+xml",
"zmm" -> "application/vnd.handheld-entertainment+xml",
"hbci" -> "application/vnd.hbci",
"les" -> "application/vnd.hhe.lesson-player",
"hpgl" -> "application/vnd.hp-hpgl",
"hpid" -> "application/vnd.hp-hpid",
"hps" -> "application/vnd.hp-hps",
"jlt" -> "application/vnd.hp-jlyt",
"pcl" -> "application/vnd.hp-pcl",
"pclxl" -> "application/vnd.hp-pclxl",
"sfd-hdstx" -> "application/vnd.hydrostatix.sof-data",
"mpy" -> "application/vnd.ibm.minipay",
"afp" -> "application/vnd.ibm.modcap",
"listafp" -> "application/vnd.ibm.modcap",
"list3820" -> "application/vnd.ibm.modcap",
"irm" -> "application/vnd.ibm.rights-management",
"sc" -> "application/vnd.ibm.secure-container",
"icc" -> "application/vnd.iccprofile",
"icm" -> "application/vnd.iccprofile",
"igl" -> "application/vnd.igloader",
"ivp" -> "application/vnd.immervision-ivp",
"ivu" -> "application/vnd.immervision-ivu",
"igm" -> "application/vnd.insors.igm",
"xpw" -> "application/vnd.intercon.formnet",
"xpx" -> "application/vnd.intercon.formnet",
"i2g" -> "application/vnd.intergeo",
"qbo" -> "application/vnd.intu.qbo",
"qfx" -> "application/vnd.intu.qfx",
"rcprofile" -> "application/vnd.ipunplugged.rcprofile",
"irp" -> "application/vnd.irepository.package+xml",
"xpr" -> "application/vnd.is-xpr",
"fcs" -> "application/vnd.isac.fcs",
"jam" -> "application/vnd.jam",
"rms" -> "application/vnd.jcp.javame.midlet-rms",
"jisp" -> "application/vnd.jisp",
"joda" -> "application/vnd.joost.joda-archive",
"ktz" -> "application/vnd.kahootz",
"ktr" -> "application/vnd.kahootz",
"karbon" -> "application/vnd.kde.karbon",
"chrt" -> "application/vnd.kde.kchart",
"kfo" -> "application/vnd.kde.kformula",
"flw" -> "application/vnd.kde.kivio",
"kon" -> "application/vnd.kde.kontour",
"kpr" -> "application/vnd.kde.kpresenter",
"kpt" -> "application/vnd.kde.kpresenter",
"ksp" -> "application/vnd.kde.kspread",
"kwd" -> "application/vnd.kde.kword",
"kwt" -> "application/vnd.kde.kword",
"htke" -> "application/vnd.kenameaapp",
"kia" -> "application/vnd.kidspiration",
"kne" -> "application/vnd.kinar",
"knp" -> "application/vnd.kinar",
"skp" -> "application/vnd.koan",
"skd" -> "application/vnd.koan",
"skt" -> "application/vnd.koan",
"skm" -> "application/vnd.koan",
"sse" -> "application/vnd.kodak-descriptor",
"lasxml" -> "application/vnd.las.las+xml",
"lbd" -> "application/vnd.llamagraphics.life-balance.desktop",
"lbe" -> "application/vnd.llamagraphics.life-balance.exchange+xml",
"123" -> "application/vnd.lotus-1-2-3",
"apr" -> "application/vnd.lotus-approach",
"pre" -> "application/vnd.lotus-freelance",
"nsf" -> "application/vnd.lotus-notes",
"org" -> "application/vnd.lotus-organizer",
"scm" -> "application/vnd.lotus-screencam",
"lwp" -> "application/vnd.lotus-wordpro",
"portpkg" -> "application/vnd.macports.portpkg",
"mcd" -> "application/vnd.mcd",
"mc1" -> "application/vnd.medcalcdata",
"cdkey" -> "application/vnd.mediastation.cdkey",
"mwf" -> "application/vnd.mfer",
"mfm" -> "application/vnd.mfmp",
"flo" -> "application/vnd.micrografx.flo",
"igx" -> "application/vnd.micrografx.igx",
"mif" -> "application/vnd.mif",
"daf" -> "application/vnd.mobius.daf",
"dis" -> "application/vnd.mobius.dis",
"mbk" -> "application/vnd.mobius.mbk",
"mqy" -> "application/vnd.mobius.mqy",
"msl" -> "application/vnd.mobius.msl",
"plc" -> "application/vnd.mobius.plc",
"txf" -> "application/vnd.mobius.txf",
"mpn" -> "application/vnd.mophun.application",
"mpc" -> "application/vnd.mophun.certificate",
"xul" -> "application/vnd.mozilla.xul+xml",
"cil" -> "application/vnd.ms-artgalry",
"cab" -> "application/vnd.ms-cab-compressed",
"xls" -> "application/vnd.ms-excel",
"xlm" -> "application/vnd.ms-excel",
"xla" -> "application/vnd.ms-excel",
"xlc" -> "application/vnd.ms-excel",
"xlt" -> "application/vnd.ms-excel",
"xlw" -> "application/vnd.ms-excel",
"xlam" -> "application/vnd.ms-excel.addin.macroenabled.12",
"xlsb" -> "application/vnd.ms-excel.sheet.binary.macroenabled.12",
"xlsm" -> "application/vnd.ms-excel.sheet.macroenabled.12",
"xltm" -> "application/vnd.ms-excel.template.macroenabled.12",
"eot" -> "application/vnd.ms-fontobject",
"chm" -> "application/vnd.ms-htmlhelp",
"ims" -> "application/vnd.ms-ims",
"lrm" -> "application/vnd.ms-lrm",
"thmx" -> "application/vnd.ms-officetheme",
"cat" -> "application/vnd.ms-pki.seccat",
"stl" -> "application/vnd.ms-pki.stl",
"ppt" -> "application/vnd.ms-powerpoint",
"pps" -> "application/vnd.ms-powerpoint",
"pot" -> "application/vnd.ms-powerpoint",
"ppam" -> "application/vnd.ms-powerpoint.addin.macroenabled.12",
"pptm" -> "application/vnd.ms-powerpoint.presentation.macroenabled.12",
"sldm" -> "application/vnd.ms-powerpoint.slide.macroenabled.12",
"ppsm" -> "application/vnd.ms-powerpoint.slideshow.macroenabled.12",
"potm" -> "application/vnd.ms-powerpoint.template.macroenabled.12",
"mpp" -> "application/vnd.ms-project",
"mpt" -> "application/vnd.ms-project",
"docm" -> "application/vnd.ms-word.document.macroenabled.12",
"dotm" -> "application/vnd.ms-word.template.macroenabled.12",
"wps" -> "application/vnd.ms-works",
"wks" -> "application/vnd.ms-works",
"wcm" -> "application/vnd.ms-works",
"wdb" -> "application/vnd.ms-works",
"wpl" -> "application/vnd.ms-wpl",
"xps" -> "application/vnd.ms-xpsdocument",
"mseq" -> "application/vnd.mseq",
"mus" -> "application/vnd.musician",
"msty" -> "application/vnd.muvee.style",
"taglet" -> "application/vnd.mynfc",
"nlu" -> "application/vnd.neurolanguage.nlu",
"ntf" -> "application/vnd.nitf",
"nitf" -> "application/vnd.nitf",
"nnd" -> "application/vnd.noblenet-directory",
"nns" -> "application/vnd.noblenet-sealer",
"nnw" -> "application/vnd.noblenet-web",
"ngdat" -> "application/vnd.nokia.n-gage.data",
"n-gage" -> "application/vnd.nokia.n-gage.symbian.install",
"rpst" -> "application/vnd.nokia.radio-preset",
"rpss" -> "application/vnd.nokia.radio-presets",
"edm" -> "application/vnd.novadigm.edm",
"edx" -> "application/vnd.novadigm.edx",
"ext" -> "application/vnd.novadigm.ext",
"odc" -> "application/vnd.oasis.opendocument.chart",
"otc" -> "application/vnd.oasis.opendocument.chart-template",
"odb" -> "application/vnd.oasis.opendocument.database",
"odf" -> "application/vnd.oasis.opendocument.formula",
"odft" -> "application/vnd.oasis.opendocument.formula-template",
"odg" -> "application/vnd.oasis.opendocument.graphics",
"otg" -> "application/vnd.oasis.opendocument.graphics-template",
"odi" -> "application/vnd.oasis.opendocument.image",
"oti" -> "application/vnd.oasis.opendocument.image-template",
"odp" -> "application/vnd.oasis.opendocument.presentation",
"otp" -> "application/vnd.oasis.opendocument.presentation-template",
"ods" -> "application/vnd.oasis.opendocument.spreadsheet",
"ots" -> "application/vnd.oasis.opendocument.spreadsheet-template",
"odt" -> "application/vnd.oasis.opendocument.text",
"odm" -> "application/vnd.oasis.opendocument.text-master",
"ott" -> "application/vnd.oasis.opendocument.text-template",
"oth" -> "application/vnd.oasis.opendocument.text-web",
"xo" -> "application/vnd.olpc-sugar",
"dd2" -> "application/vnd.oma.dd2+xml",
"oxt" -> "application/vnd.openofficeorg.extension",
"pptx" -> "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"sldx" -> "application/vnd.openxmlformats-officedocument.presentationml.slide",
"ppsx" -> "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
"potx" -> "application/vnd.openxmlformats-officedocument.presentationml.template",
"xlsx" -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"xltx" -> "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
"docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"dotx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
"mgp" -> "application/vnd.osgeo.mapguide.package",
"dp" -> "application/vnd.osgi.dp",
"esa" -> "application/vnd.osgi.subsystem",
"pdb" -> "application/vnd.palm",
"pqa" -> "application/vnd.palm",
"oprc" -> "application/vnd.palm",
"paw" -> "application/vnd.pawaafile",
"str" -> "application/vnd.pg.format",
"ei6" -> "application/vnd.pg.osasli",
"efif" -> "application/vnd.picsel",
"wg" -> "application/vnd.pmi.widget",
"plf" -> "application/vnd.pocketlearn",
"pbd" -> "application/vnd.powerbuilder6",
"box" -> "application/vnd.previewsystems.box",
"mgz" -> "application/vnd.proteus.magazine",
"qps" -> "application/vnd.publishare-delta-tree",
"ptid" -> "application/vnd.pvi.ptid1",
"qxd" -> "application/vnd.quark.quarkxpress",
"qxt" -> "application/vnd.quark.quarkxpress",
"qwd" -> "application/vnd.quark.quarkxpress",
"qwt" -> "application/vnd.quark.quarkxpress",
"qxl" -> "application/vnd.quark.quarkxpress",
"qxb" -> "application/vnd.quark.quarkxpress",
"bed" -> "application/vnd.realvnc.bed",
"mxl" -> "application/vnd.recordare.musicxml",
"musicxml" -> "application/vnd.recordare.musicxml+xml",
"cryptonote" -> "application/vnd.rig.cryptonote",
"cod" -> "application/vnd.rim.cod",
"rm" -> "application/vnd.rn-realmedia",
"rmvb" -> "application/vnd.rn-realmedia-vbr",
"link66" -> "application/vnd.route66.link66+xml",
"st" -> "application/vnd.sailingtracker.track",
"see" -> "application/vnd.seemail",
"sema" -> "application/vnd.sema",
"semd" -> "application/vnd.semd",
"semf" -> "application/vnd.semf",
"ifm" -> "application/vnd.shana.informed.formdata",
"itp" -> "application/vnd.shana.informed.formtemplate",
"iif" -> "application/vnd.shana.informed.interchange",
"ipk" -> "application/vnd.shana.informed.package",
"twd" -> "application/vnd.simtech-mindmapper",
"twds" -> "application/vnd.simtech-mindmapper",
"mmf" -> "application/vnd.smaf",
"teacher" -> "application/vnd.smart.teacher",
"sdkm" -> "application/vnd.solent.sdkm+xml",
"sdkd" -> "application/vnd.solent.sdkm+xml",
"dxp" -> "application/vnd.spotfire.dxp",
"sfs" -> "application/vnd.spotfire.sfs",
"sdc" -> "application/vnd.stardivision.calc",
"sda" -> "application/vnd.stardivision.draw",
"sdd" -> "application/vnd.stardivision.impress",
"smf" -> "application/vnd.stardivision.math",
"sdw" -> "application/vnd.stardivision.writer",
"vor" -> "application/vnd.stardivision.writer",
"sgl" -> "application/vnd.stardivision.writer-global",
"smzip" -> "application/vnd.stepmania.package",
"sm" -> "application/vnd.stepmania.stepchart",
"sxc" -> "application/vnd.sun.xml.calc",
"stc" -> "application/vnd.sun.xml.calc.template",
"sxd" -> "application/vnd.sun.xml.draw",
"std" -> "application/vnd.sun.xml.draw.template",
"sxi" -> "application/vnd.sun.xml.impress",
"sti" -> "application/vnd.sun.xml.impress.template",
"sxm" -> "application/vnd.sun.xml.math",
"sxw" -> "application/vnd.sun.xml.writer",
"sxg" -> "application/vnd.sun.xml.writer.global",
"stw" -> "application/vnd.sun.xml.writer.template",
"sus" -> "application/vnd.sus-calendar",
"susp" -> "application/vnd.sus-calendar",
"svd" -> "application/vnd.svd",
"sis" -> "application/vnd.symbian.install",
"sisx" -> "application/vnd.symbian.install",
"xsm" -> "application/vnd.syncml+xml",
"bdm" -> "application/vnd.syncml.dm+wbxml",
"xdm" -> "application/vnd.syncml.dm+xml",
"tao" -> "application/vnd.tao.intent-module-archive",
"pcap" -> "application/vnd.tcpdump.pcap",
"cap" -> "application/vnd.tcpdump.pcap",
"dmp" -> "application/vnd.tcpdump.pcap",
"tmo" -> "application/vnd.tmobile-livetv",
"tpt" -> "application/vnd.trid.tpt",
"mxs" -> "application/vnd.triscape.mxs",
"tra" -> "application/vnd.trueapp",
"ufd" -> "application/vnd.ufdl",
"ufdl" -> "application/vnd.ufdl",
"utz" -> "application/vnd.uiq.theme",
"umj" -> "application/vnd.umajin",
"unityweb" -> "application/vnd.unity",
"uoml" -> "application/vnd.uoml+xml",
"vcx" -> "application/vnd.vcx",
"vsd" -> "application/vnd.visio",
"vst" -> "application/vnd.visio",
"vss" -> "application/vnd.visio",
"vsw" -> "application/vnd.visio",
"vis" -> "application/vnd.visionary",
"vsf" -> "application/vnd.vsf",
"wbxml" -> "application/vnd.wap.wbxml",
"wmlc" -> "application/vnd.wap.wmlc",
"wmlsc" -> "application/vnd.wap.wmlscriptc",
"wtb" -> "application/vnd.webturbo",
"nbp" -> "application/vnd.wolfram.player",
"wpd" -> "application/vnd.wordperfect",
"wqd" -> "application/vnd.wqd",
"stf" -> "application/vnd.wt.stf",
"xar" -> "application/vnd.xara",
"xfdl" -> "application/vnd.xfdl",
"hvd" -> "application/vnd.yamaha.hv-dic",
"hvs" -> "application/vnd.yamaha.hv-script",
"hvp" -> "application/vnd.yamaha.hv-voice",
"osf" -> "application/vnd.yamaha.openscoreformat",
"osfpvg" -> "application/vnd.yamaha.openscoreformat.osfpvg+xml",
"saf" -> "application/vnd.yamaha.smaf-audio",
"spf" -> "application/vnd.yamaha.smaf-phrase",
"cmp" -> "application/vnd.yellowriver-custom-menu",
"zir" -> "application/vnd.zul",
"zirz" -> "application/vnd.zul",
"zaz" -> "application/vnd.zzazz.deck+xml",
"vxml" -> "application/voicexml+xml",
"wgt" -> "application/widget",
"hlp" -> "application/winhlp",
"wsdl" -> "application/wsdl+xml",
"wspolicy" -> "application/wspolicy+xml",
"7z" -> "application/x-7z-compressed",
"abw" -> "application/x-abiword",
"ace" -> "application/x-ace-compressed",
"dmg" -> "application/x-apple-diskimage",
"aab" -> "application/x-authorware-bin",
"x32" -> "application/x-authorware-bin",
"u32" -> "application/x-authorware-bin",
"vox" -> "application/x-authorware-bin",
"aam" -> "application/x-authorware-map",
"aas" -> "application/x-authorware-seg",
"bcpio" -> "application/x-bcpio",
"torrent" -> "application/x-bittorrent",
"blb" -> "application/x-blorb",
"blorb" -> "application/x-blorb",
"bz" -> "application/x-bzip",
"bz2" -> "application/x-bzip2",
"boz" -> "application/x-bzip2",
"cbr" -> "application/x-cbr",
"cba" -> "application/x-cbr",
"cbt" -> "application/x-cbr",
"cbz" -> "application/x-cbr",
"cb7" -> "application/x-cbr",
"vcd" -> "application/x-cdlink",
"cfs" -> "application/x-cfs-compressed",
"chat" -> "application/x-chat",
"pgn" -> "application/x-chess-pgn",
"nsc" -> "application/x-conference",
"cpio" -> "application/x-cpio",
"csh" -> "application/x-csh",
"deb" -> "application/x-debian-package",
"udeb" -> "application/x-debian-package",
"dgc" -> "application/x-dgc-compressed",
"dir" -> "application/x-director",
"dcr" -> "application/x-director",
"dxr" -> "application/x-director",
"cst" -> "application/x-director",
"cct" -> "application/x-director",
"cxt" -> "application/x-director",
"w3d" -> "application/x-director",
"fgd" -> "application/x-director",
"swa" -> "application/x-director",
"wad" -> "application/x-doom",
"ncx" -> "application/x-dtbncx+xml",
"dtb" -> "application/x-dtbook+xml",
"res" -> "application/x-dtbresource+xml",
"dvi" -> "application/x-dvi",
"evy" -> "application/x-envoy",
"eva" -> "application/x-eva",
"bdf" -> "application/x-font-bdf",
"gsf" -> "application/x-font-ghostscript",
"psf" -> "application/x-font-linux-psf",
"otf" -> "application/x-font-otf",
"pcf" -> "application/x-font-pcf",
"snf" -> "application/x-font-snf",
"ttf" -> "application/x-font-ttf",
"ttc" -> "application/x-font-ttf",
"pfa" -> "application/x-font-type1",
"pfb" -> "application/x-font-type1",
"pfm" -> "application/x-font-type1",
"afm" -> "application/x-font-type1",
"arc" -> "application/x-freearc",
"spl" -> "application/x-futuresplash",
"gca" -> "application/x-gca-compressed",
"ulx" -> "application/x-glulx",
"gnumeric" -> "application/x-gnumeric",
"gramps" -> "application/x-gramps-xml",
"gtar" -> "application/x-gtar",
"hdf" -> "application/x-hdf",
"install" -> "application/x-install-instructions",
"iso" -> "application/x-iso9660-image",
"jnlp" -> "application/x-java-jnlp-file",
"latex" -> "application/x-latex",
"lzh" -> "application/x-lzh-compressed",
"lha" -> "application/x-lzh-compressed",
"mie" -> "application/x-mie",
"prc" -> "application/x-mobipocket-ebook",
"mobi" -> "application/x-mobipocket-ebook",
"application" -> "application/x-ms-application",
"lnk" -> "application/x-ms-shortcut",
"wmd" -> "application/x-ms-wmd",
"wmz" -> "application/x-ms-wmz",
"xbap" -> "application/x-ms-xbap",
"mdb" -> "application/x-msaccess",
"obd" -> "application/x-msbinder",
"crd" -> "application/x-mscardfile",
"clp" -> "application/x-msclip",
"exe" -> "application/x-msdownload",
"dll" -> "application/x-msdownload",
"com" -> "application/x-msdownload",
"bat" -> "application/x-msdownload",
"msi" -> "application/x-msdownload",
"mvb" -> "application/x-msmediaview",
"m13" -> "application/x-msmediaview",
"m14" -> "application/x-msmediaview",
"wmf" -> "application/x-msmetafile",
"wmz" -> "application/x-msmetafile",
"emf" -> "application/x-msmetafile",
"emz" -> "application/x-msmetafile",
"mny" -> "application/x-msmoney",
"pub" -> "application/x-mspublisher",
"scd" -> "application/x-msschedule",
"trm" -> "application/x-msterminal",
"wri" -> "application/x-mswrite",
"nc" -> "application/x-netcdf",
"cdf" -> "application/x-netcdf",
"nzb" -> "application/x-nzb",
"p12" -> "application/x-pkcs12",
"pfx" -> "application/x-pkcs12",
"p7b" -> "application/x-pkcs7-certificates",
"spc" -> "application/x-pkcs7-certificates",
"p7r" -> "application/x-pkcs7-certreqresp",
"rar" -> "application/x-rar-compressed",
"ris" -> "application/x-research-info-systems",
"sh" -> "application/x-sh",
"shar" -> "application/x-shar",
"swf" -> "application/x-shockwave-flash",
"xap" -> "application/x-silverlight-app",
"sql" -> "application/x-sql",
"sit" -> "application/x-stuffit",
"sitx" -> "application/x-stuffitx",
"srt" -> "application/x-subrip",
"sv4cpio" -> "application/x-sv4cpio",
"sv4crc" -> "application/x-sv4crc",
"t3" -> "application/x-t3vm-image",
"gam" -> "application/x-tads",
"tar" -> "application/x-tar",
"tcl" -> "application/x-tcl",
"tex" -> "application/x-tex",
"tfm" -> "application/x-tex-tfm",
"texinfo" -> "application/x-texinfo",
"texi" -> "application/x-texinfo",
"obj" -> "application/x-tgif",
"ustar" -> "application/x-ustar",
"src" -> "application/x-wais-source",
"der" -> "application/x-x509-ca-cert",
"crt" -> "application/x-x509-ca-cert",
"fig" -> "application/x-xfig",
"xlf" -> "application/x-xliff+xml",
"xpi" -> "application/x-xpinstall",
"xz" -> "application/x-xz",
"z1" -> "application/x-zmachine",
"z2" -> "application/x-zmachine",
"z3" -> "application/x-zmachine",
"z4" -> "application/x-zmachine",
"z5" -> "application/x-zmachine",
"z6" -> "application/x-zmachine",
"z7" -> "application/x-zmachine",
"z8" -> "application/x-zmachine",
"xaml" -> "application/xaml+xml",
"xdf" -> "application/xcap-diff+xml",
"xenc" -> "application/xenc+xml",
"xhtml" -> "application/xhtml+xml",
"xht" -> "application/xhtml+xml",
"xml" -> "application/xml",
"xsl" -> "application/xml",
"dtd" -> "application/xml-dtd",
"xop" -> "application/xop+xml",
"xpl" -> "application/xproc+xml",
"xslt" -> "application/xslt+xml",
"xspf" -> "application/xspf+xml",
"mxml" -> "application/xv+xml",
"xhvml" -> "application/xv+xml",
"xvml" -> "application/xv+xml",
"xvm" -> "application/xv+xml",
"yang" -> "application/yang",
"yin" -> "application/yin+xml",
"zip" -> "application/zip",
"adp" -> "audio/adpcm",
"au" -> "audio/basic",
"snd" -> "audio/basic",
"mid" -> "audio/midi",
"midi" -> "audio/midi",
"kar" -> "audio/midi",
"rmi" -> "audio/midi",
"m4a" -> "audio/mp4",
"mp4a" -> "audio/mp4",
"mpga" -> "audio/mpeg",
"mp2" -> "audio/mpeg",
"mp2a" -> "audio/mpeg",
"mp3" -> "audio/mpeg",
"m2a" -> "audio/mpeg",
"m3a" -> "audio/mpeg",
"oga" -> "audio/ogg",
"ogg" -> "audio/ogg",
"spx" -> "audio/ogg",
"s3m" -> "audio/s3m",
"sil" -> "audio/silk",
"uva" -> "audio/vnd.dece.audio",
"uvva" -> "audio/vnd.dece.audio",
"eol" -> "audio/vnd.digital-winds",
"dra" -> "audio/vnd.dra",
"dts" -> "audio/vnd.dts",
"dtshd" -> "audio/vnd.dts.hd",
"lvp" -> "audio/vnd.lucent.voice",
"pya" -> "audio/vnd.ms-playready.media.pya",
"ecelp4800" -> "audio/vnd.nuera.ecelp4800",
"ecelp7470" -> "audio/vnd.nuera.ecelp7470",
"ecelp9600" -> "audio/vnd.nuera.ecelp9600",
"rip" -> "audio/vnd.rip",
"weba" -> "audio/webm",
"aac" -> "audio/x-aac",
"aif" -> "audio/x-aiff",
"aiff" -> "audio/x-aiff",
"aifc" -> "audio/x-aiff",
"caf" -> "audio/x-caf",
"flac" -> "audio/x-flac",
"mka" -> "audio/x-matroska",
"m3u" -> "audio/x-mpegurl",
"wax" -> "audio/x-ms-wax",
"wma" -> "audio/x-ms-wma",
"ram" -> "audio/x-pn-realaudio",
"ra" -> "audio/x-pn-realaudio",
"rmp" -> "audio/x-pn-realaudio-plugin",
"wav" -> "audio/x-wav",
"xm" -> "audio/xm",
"cdx" -> "chemical/x-cdx",
"cif" -> "chemical/x-cif",
"cmdf" -> "chemical/x-cmdf",
"cml" -> "chemical/x-cml",
"csml" -> "chemical/x-csml",
"xyz" -> "chemical/x-xyz",
"bmp" -> "image/bmp",
"cgm" -> "image/cgm",
"g3" -> "image/g3fax",
"gif" -> "image/gif",
"ief" -> "image/ief",
"jpeg" -> "image/jpeg",
"jpg" -> "image/jpeg",
"jpe" -> "image/jpeg",
"ktx" -> "image/ktx",
"png" -> "image/png",
"btif" -> "image/prs.btif",
"sgi" -> "image/sgi",
"svg" -> "image/svg+xml",
"svgz" -> "image/svg+xml",
"tiff" -> "image/tiff",
"tif" -> "image/tiff",
"psd" -> "image/vnd.adobe.photoshop",
"uvi" -> "image/vnd.dece.graphic",
"uvvi" -> "image/vnd.dece.graphic",
"uvg" -> "image/vnd.dece.graphic",
"uvvg" -> "image/vnd.dece.graphic",
"djvu" -> "image/vnd.djvu",
"djv" -> "image/vnd.djvu",
"sub" -> "image/vnd.dvb.subtitle",
"dwg" -> "image/vnd.dwg",
"dxf" -> "image/vnd.dxf",
"fbs" -> "image/vnd.fastbidsheet",
"fpx" -> "image/vnd.fpx",
"fst" -> "image/vnd.fst",
"mmr" -> "image/vnd.fujixerox.edmics-mmr",
"rlc" -> "image/vnd.fujixerox.edmics-rlc",
"mdi" -> "image/vnd.ms-modi",
"wdp" -> "image/vnd.ms-photo",
"npx" -> "image/vnd.net-fpx",
"wbmp" -> "image/vnd.wap.wbmp",
"xif" -> "image/vnd.xiff",
"webp" -> "image/webp",
"3ds" -> "image/x-3ds",
"ras" -> "image/x-cmu-raster",
"cmx" -> "image/x-cmx",
"fh" -> "image/x-freehand",
"fhc" -> "image/x-freehand",
"fh4" -> "image/x-freehand",
"fh5" -> "image/x-freehand",
"fh7" -> "image/x-freehand",
"ico" -> "image/x-icon",
"sid" -> "image/x-mrsid-image",
"pcx" -> "image/x-pcx",
"pic" -> "image/x-pict",
"pct" -> "image/x-pict",
"pnm" -> "image/x-portable-anymap",
"pbm" -> "image/x-portable-bitmap",
"pgm" -> "image/x-portable-graymap",
"ppm" -> "image/x-portable-pixmap",
"rgb" -> "image/x-rgb",
"tga" -> "image/x-tga",
"xbm" -> "image/x-xbitmap",
"xpm" -> "image/x-xpixmap",
"xwd" -> "image/x-xwindowdump",
"eml" -> "message/rfc822",
"mime" -> "message/rfc822",
"igs" -> "model/iges",
"iges" -> "model/iges",
"msh" -> "model/mesh",
"mesh" -> "model/mesh",
"silo" -> "model/mesh",
"dae" -> "model/vnd.collada+xml",
"dwf" -> "model/vnd.dwf",
"gdl" -> "model/vnd.gdl",
"gtw" -> "model/vnd.gtw",
"mts" -> "model/vnd.mts",
"vtu" -> "model/vnd.vtu",
"wrl" -> "model/vrml",
"vrml" -> "model/vrml",
"x3db" -> "model/x3d+binary",
"x3dbz" -> "model/x3d+binary",
"x3dv" -> "model/x3d+vrml",
"x3dvz" -> "model/x3d+vrml",
"x3d" -> "model/x3d+xml",
"x3dz" -> "model/x3d+xml",
"appcache" -> "text/cache-manifest",
"ics" -> "text/calendar",
"ifb" -> "text/calendar",
"css" -> "text/css",
"csv" -> "text/csv",
"html" -> "text/html",
"htm" -> "text/html",
"n3" -> "text/n3",
"txt" -> "text/plain",
"text" -> "text/plain",
"conf" -> "text/plain",
"def" -> "text/plain",
"list" -> "text/plain",
"log" -> "text/plain",
"in" -> "text/plain",
"dsc" -> "text/prs.lines.tag",
"rtx" -> "text/richtext",
"sgml" -> "text/sgml",
"sgm" -> "text/sgml",
"tsv" -> "text/tab-separated-values",
"t" -> "text/troff",
"tr" -> "text/troff",
"roff" -> "text/troff",
"man" -> "text/troff",
"me" -> "text/troff",
"ms" -> "text/troff",
"ttl" -> "text/turtle",
"uri" -> "text/uri-list",
"uris" -> "text/uri-list",
"urls" -> "text/uri-list",
"vcard" -> "text/vcard",
"curl" -> "text/vnd.curl",
"dcurl" -> "text/vnd.curl.dcurl",
"mcurl" -> "text/vnd.curl.mcurl",
"scurl" -> "text/vnd.curl.scurl",
"sub" -> "text/vnd.dvb.subtitle",
"fly" -> "text/vnd.fly",
"flx" -> "text/vnd.fmi.flexstor",
"gv" -> "text/vnd.graphviz",
"3dml" -> "text/vnd.in3d.3dml",
"spot" -> "text/vnd.in3d.spot",
"jad" -> "text/vnd.sun.j2me.app-descriptor",
"wml" -> "text/vnd.wap.wml",
"wmls" -> "text/vnd.wap.wmlscript",
"s" -> "text/x-asm",
"asm" -> "text/x-asm",
"c" -> "text/x-c",
"cc" -> "text/x-c",
"cxx" -> "text/x-c",
"cpp" -> "text/x-c",
"h" -> "text/x-c",
"hh" -> "text/x-c",
"dic" -> "text/x-c",
"f" -> "text/x-fortran",
"for" -> "text/x-fortran",
"f77" -> "text/x-fortran",
"f90" -> "text/x-fortran",
"java" -> "text/x-java-source",
"nfo" -> "text/x-nfo",
"opml" -> "text/x-opml",
"p" -> "text/x-pascal",
"pas" -> "text/x-pascal",
"etx" -> "text/x-setext",
"sfv" -> "text/x-sfv",
"uu" -> "text/x-uuencode",
"vcs" -> "text/x-vcalendar",
"vcf" -> "text/x-vcard",
"3gp" -> "video/3gpp",
"3g2" -> "video/3gpp2",
"h261" -> "video/h261",
"h263" -> "video/h263",
"h264" -> "video/h264",
"jpgv" -> "video/jpeg",
"jpm" -> "video/jpm",
"jpgm" -> "video/jpm",
"mj2" -> "video/mj2",
"mjp2" -> "video/mj2",
"mp4" -> "video/mp4",
"mp4v" -> "video/mp4",
"mpg4" -> "video/mp4",
"mpeg" -> "video/mpeg",
"mpg" -> "video/mpeg",
"mpe" -> "video/mpeg",
"m1v" -> "video/mpeg",
"m2v" -> "video/mpeg",
"ogv" -> "video/ogg",
"qt" -> "video/quicktime",
"mov" -> "video/quicktime",
"uvh" -> "video/vnd.dece.hd",
"uvvh" -> "video/vnd.dece.hd",
"uvm" -> "video/vnd.dece.mobile",
"uvvm" -> "video/vnd.dece.mobile",
"uvp" -> "video/vnd.dece.pd",
"uvvp" -> "video/vnd.dece.pd",
"uvs" -> "video/vnd.dece.sd",
"uvvs" -> "video/vnd.dece.sd",
"uvv" -> "video/vnd.dece.video",
"uvvv" -> "video/vnd.dece.video",
"dvb" -> "video/vnd.dvb.file",
"fvt" -> "video/vnd.fvt",
"mxu" -> "video/vnd.mpegurl",
"m4u" -> "video/vnd.mpegurl",
"pyv" -> "video/vnd.ms-playready.media.pyv",
"uvu" -> "video/vnd.uvvu.mp4",
"uvvu" -> "video/vnd.uvvu.mp4",
"viv" -> "video/vnd.vivo",
"webm" -> "video/webm",
"f4v" -> "video/x-f4v",
"fli" -> "video/x-fli",
"flv" -> "video/x-flv",
"m4v" -> "video/x-m4v",
"mkv" -> "video/x-matroska",
"mk3d" -> "video/x-matroska",
"mks" -> "video/x-matroska",
"mng" -> "video/x-mng",
"asf" -> "video/x-ms-asf",
"asx" -> "video/x-ms-asf",
"vob" -> "video/x-ms-vob",
"wm" -> "video/x-ms-wm",
"wmv" -> "video/x-ms-wmv",
"wmx" -> "video/x-ms-wmx",
"wvx" -> "video/x-ms-wvx",
"avi" -> "video/x-msvideo",
"movie" -> "video/x-sgi-movie",
"smv" -> "video/x-smv",
"ice" -> "x-conference/x-cooltalk"
)
}
| PhilAndrew/JumpMicro | JMSangriaGraphql/src/main/scala/korolev/server/mimeTypes.scala | Scala | mit | 40,714 |
package json2caseclass.implementation
import json2caseclass.model.CaseClass.{ClassFieldName, ClassName}
import json2caseclass.model.ScalaType._
import json2caseclass.model.{CaseClass, ScalaObject, ScalaOption, ScalaType}
object CaseClassOperations {
def renameAmbiguous(makeUnique: (Set[String], ClassName) => Option[ClassName], caseClasses: Seq[CaseClass]): Seq[CaseClass] = {
val alternativeNames = findAlternativeNames(makeUnique, caseClasses)
rename(caseClasses, alternativeNames)
}
def addOptionals(caseClasses: Seq[CaseClass], optionals: Seq[(ClassName, ClassFieldName)]): Seq[CaseClass] = {
caseClasses.map {
case o @ CaseClass(_, name, fields) =>
val withOptionals =
fields.map {
case (fName, scalaType) if optionals.contains(name -> fName) =>
(fName, ScalaOption(scalaType))
case other => other
}
o.copy(fields = withOptionals)
}
}
private def findAlternativeNames(makeUnique: (Set[String], ClassName) => Option[ClassName], caseClasses: Seq[CaseClass]): Map[Int, ClassName] = {
def alternativeNamesRec(ccs: Seq[CaseClass], alreadyTakenNames: Set[String], acc: Map[Int, ClassName]): Map[Int, ClassName] = {
ccs match {
case Nil => acc
case CaseClass(id, name, _) :: tail =>
makeUnique(alreadyTakenNames, name) match {
case Some(uniqueName) =>
alternativeNamesRec(tail, alreadyTakenNames + uniqueName, acc + (id -> uniqueName))
case None =>
alternativeNamesRec(tail, alreadyTakenNames + name, acc)
}
}
}
alternativeNamesRec(caseClasses, Set(), Map())
}
private def rename(caseClasses: Seq[CaseClass], alternativeNames: Map[Int, ClassName]): Seq[CaseClass] = {
def renameFieldTypes(fields: Seq[(ClassFieldName, ScalaType)]) = {
fields.map {
case f @ (fName, ScalaObject(id, _)) =>
alternativeNames
.get(id)
.map(altName => (fName, ScalaObject(id, altName.toScalaObjectName)))
.getOrElse(f)
case other => other
}
}
caseClasses.map {
case o @ CaseClass(id, _, fields) =>
alternativeNames
.get(id)
.map(altName => o.copy(name = altName))
.getOrElse(o)
.copy(fields = renameFieldTypes(fields))
}
}
}
| battermann/sbt-json | src/main/scala/json2caseclass/implementation/CaseClassOperations.scala | Scala | mit | 2,378 |
package org.scaladebugger.api.utils
import java.util
import java.util.concurrent._
import java.util.concurrent.atomic.AtomicInteger
import scala.util.Try
import LoopingTaskRunner._
/**
* Contains defaults for the looping task runner.
*/
object LoopingTaskRunner {
/** Default initial workers is equal to number of available processors */
val DefaultInitialWorkers: Int = Runtime.getRuntime.availableProcessors()
/** Default maximum wait time is 100 milliseconds */
val DefaultMaxTaskWaitTime: (Long, TimeUnit) = (100L, TimeUnit.MILLISECONDS)
}
/**
* Represents a queue of tasks that will be executed infinitely in order
* until removed.
*
* @param initialWorkers The total number of works to use for this runner on
* startup (more can be added or removed)
* @param maxTaskWaitTime The maximum time to wait for a task to be pulled off
* of the queue before allowing other tasks to be run
*/
class LoopingTaskRunner(
private val initialWorkers: Int = DefaultInitialWorkers,
private val maxTaskWaitTime: (Long, TimeUnit) = DefaultMaxTaskWaitTime
) {
type TaskId = String
/**
* Represents a task that will execute the next task on the provided queue
* and add it back to the end of the queue when finished.
*
* @param taskQueue The queue containing the ids of the tasks to run
* @param taskMap The mapping of task ids to associated runnable tasks
*/
private class LoopingTask(
private val taskQueue: util.concurrent.BlockingQueue[TaskId],
private val taskMap: util.Map[TaskId, Runnable]
) extends Runnable {
override def run(): Unit = {
// Update tracking information to reflect an active worker
currentActiveWorkers.incrementAndGet()
// Determine the next task to execute (wait for a maximum time duration)
val taskId = nextTaskId()
// If there is a new task, perform the operation
taskId.foreach(executeTask)
// Start next task once this is free (suppress exceptions in the
// situation that this runner has been stopped)
//
// NOTE: Do not add this runner back on our queue if we want to decrease
// the total number of workers via the desired total workers
if (currentActiveWorkers.decrementAndGet() < desiredTotalWorkers.get()) {
Try(runNextTask())
}
}
/**
* Retrieves the id of the next task to execute.
*
* @return Some id if there is a new task to execute, otherwise None
*/
protected def nextTaskId(): Option[TaskId] = Option(taskQueue.poll(
maxTaskWaitTime._1,
maxTaskWaitTime._2
))
/**
* Retrieves and executes the next task, placing it back on the queue
* once finished.
*
* @param taskId The id of the task to execute
*/
protected def executeTask(taskId: TaskId): Unit = {
// Retrieve and execute the next task
val tryTask = Try(taskMap.get(taskId))
tryTask.foreach(task => Try(task.run()))
// Task finished, so add back to end of our queue
// NOTE: Only do so if the map knows about our task (allows removal)
if (tryTask.isSuccess) taskQueue.put(taskId)
}
}
/** Represents the desired number of workers processing and on queue */
private val desiredTotalWorkers = new AtomicInteger(0)
/** Represents the total number of workers processing tasks */
private val currentActiveWorkers = new AtomicInteger(0)
/** Contains the ids of tasks to be executed (in order). */
private val taskQueue = new LinkedBlockingQueue[TaskId]()
/** Contains mapping of task ids to task implementations. */
private val taskMap = new ConcurrentHashMap[TaskId, Runnable]()
/** Represents the executors used to execute the tasks. */
@volatile private var executorService: Option[ExecutorService] = None
/**
* Indicates whether or not the task runner is processing tasks.
*
* @return True if it is running, otherwise false
*/
def isRunning: Boolean = executorService.nonEmpty
/**
* Executing begins the process of executing queued up tasks.
*/
def start(): Unit = {
assert(!isRunning, "Runner already started!")
// Create our thread pool executor to process tasks
executorService = Some(newExecutorService())
// Start X tasks to be run
setDesiredTotalWorkers(initialWorkers)
}
/**
* Prevents the runner from executing any more tasks.
*
* @param removeAllTasks If true, removes all tasks after being stopped
*/
def stop(removeAllTasks: Boolean = true): Unit = {
assert(isRunning, "Runner not started!")
setDesiredTotalWorkers(0)
executorService.foreach(es => {
es.shutdown()
es.awaitTermination(10, TimeUnit.SECONDS)
})
executorService = None
if (removeAllTasks) {
taskQueue.clear()
taskMap.clear()
}
}
/**
* Sets the desired total number of workers to eventually be achieved by
* the task runner.
*
* @param value The new desired total number of workers
*/
def setDesiredTotalWorkers(value: Int): Unit = {
// Determine if this is an increase or decrease in workers
val delta = value - desiredTotalWorkers.getAndSet(value)
// If an increase, we need to spawn new tasks to increase our workers
if (delta > 0) (1 to delta).foreach(_ => runNextTask())
}
/**
* Retrieves the current desired total number of workers.
*
* @return The desired total number of workers
*/
def getDesiredTotalWorkers: Int = desiredTotalWorkers.get()
/**
* Retrieves the total actively-running workers.
*
* @return The total active workers at this point in time
*/
def getCurrentActiveWorkers: Int = currentActiveWorkers.get()
/**
* Adds a task to be executed repeatedly (in a queue with other tasks).
*
* @param task The task to add
* @tparam T The return type of the task
*
* @return The id of the queued task
*/
def addTask[T](task: => T): TaskId = {
val taskId = java.util.UUID.randomUUID().toString
// Add the task to our lookup table, and then queue it up for processing
taskMap.put(taskId, new Runnable {
override def run(): Unit = task
})
taskQueue.put(taskId)
taskId
}
/**
* Removes a task from the repeated execution.
*
* @param taskId The id of the task to remove
*
* @return Task implementation that was removed
*/
def removeTask(taskId: TaskId): Runnable = {
taskQueue.remove(taskId)
taskMap.remove(taskId)
}
/**
* Creates a new executor service for use by the looping task runner.
*
* @return The new executor service instance
*/
protected def newExecutorService(): ExecutorService = {
// TODO: Replace cached thread pool with more optimized thread pool
// executor that scales better for large number of tasks
Executors.newCachedThreadPool()
}
/**
* Executes next available task.
*/
protected def runNextTask(): Unit =
executorService.foreach(_.execute(newLoopingTask()))
/**
* Creates a new looping task to be executed.
*/
protected def newLoopingTask(): Runnable = new LoopingTask(taskQueue, taskMap)
}
| chipsenkbeil/scala-debugger | scala-debugger-api/src/main/scala/org/scaladebugger/api/utils/LoopingTaskRunner.scala | Scala | apache-2.0 | 7,185 |
package astar
package test
import org.scalatest._
import org.scalatest.matchers._
class AStarTest extends FunSpec with Matchers {
// x, y, rotation (0, 1, 2, 3)
type State = (Int, Int, Int)
trait Command
case object Left extends Command
case object Right extends Command
case object Up extends Command
case object Down extends Command
case object RotateLeft extends Command
case object RotateRight extends Command
// Map: 5 x 8
val width = 5
val height = 8
val blocked = List((0, 1), (1, 1), (2, 1), (3, 1))
val engine = new astar.Engine[State, Command] {
def valid(self: State): Boolean = self match {
case (x, y, r) =>
x >= 0 && x < width &&
y >= 0 && y < height && !(blocked contains (x, y))
}
def bisimilar(self: State, other: State): Boolean =
self == other
def hash(self: State): Int = self.hashCode
def transition(state: State, cmd: Command): State = (state, cmd) match {
case ((x, y, r), Left) => (x - 1, y, r)
case ((x, y, r), Right) => (x + 1, y, r)
case ((x, y, r), Up) => (x, y - 1, r)
case ((x, y, r), Down) => (x, y + 1, r)
case ((x, y, r), RotateRight) => (x, y, (r + 1) % 4)
case ((x, y, r), RotateLeft) => (x, y, (r - 1) % 4)
}
def commands = List(Left, Right, Up, Down, RotateLeft, RotateRight)
def distance(fst: State, other: State): Double = heuristic(fst, other)
}
// Here: Manhattan distance that also considers rotation
def heuristic(from: State, to: State): Double = (from, to) match {
case ((x1, y1, r1), (x2, y2, r2)) =>
math.abs(x1 - x2) + math.abs(y1 - y2) + math.abs(r1 - r2)
}
val astarSolver = AStar[State, Command](
(0, 0, 0),
(1, 3, 2),
engine
)
astarSolver.computePath shouldBe
Some(List(RotateRight, RotateRight, Right, Right, Right, Right, Down, Down, Down, Left, Left, Left))
}
| b-studios/parametric-a-star | src/test/scala/astar/AStarTest.scala | Scala | mit | 1,928 |
package org.libss.util
import org.slf4j.LoggerFactory
/**
* Created by Kaa
* on 03.06.2016 at 05:20.
*/
trait Loggable {
@transient lazy val Logger = LoggerFactory.getLogger(this.getClass)
}
| kanischev/libss | libss-utils/src/main/scala/org/libss/util/Loggable.scala | Scala | apache-2.0 | 202 |
package com.sksamuel.scapegoat.inspections.collections
import com.sksamuel.scapegoat.PluginRunner
import org.scalatest.{ FreeSpec, Matchers, OneInstancePerTest }
/** @author Stephen Samuel */
class CollectionNamingConfusionTest extends FreeSpec with Matchers with PluginRunner with OneInstancePerTest {
override val inspections = Seq(new CollectionNamingConfusion)
"collection confusing names" - {
"should report warning" in {
val code = """object Test {
val set = List(1)
val mySet = List(2)
val mySetWithStuff = List(3)
val list = Set(1)
val myList = Set(2)
val myListWithStuff = Set(3)
} """.stripMargin
compileCodeSnippet(code)
compiler.scapegoat.feedback.warnings.size shouldBe 6
}
}
}
| pwwpche/scalac-scapegoat-plugin | src/test/scala/com/sksamuel/scapegoat/inspections/collections/CollectionNamingConfusionTest.scala | Scala | apache-2.0 | 880 |
/* __ *\\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2003-2010, LAMP/EPFL **
** __\\ \\/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\\___/_/ |_/____/_/ | | **
** |/ **
\\* */
package scala
/** Counted iterators keep track of the number of elements seen so far
*
* @since 2.0
*/
@deprecated("use iterator.zipWithIndex instead")
trait CountedIterator[+A] extends Iterator[A] {
/** counts the elements in this iterator; counts start at 0
*/
def count: Int
override def counted : this.type = this
}
| cran/rkafkajars | java/scala/CountedIterator.scala | Scala | apache-2.0 | 865 |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2015-2021 Andre White.
*
* 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
*
* https://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.truthencode.ddo.model.enhancement.enhancements
import io.truthencode.ddo.model.enhancement.enhancements.classbased.BombardierTierThree
trait SwiftAmbition extends BombardierTierThree with ClassEnhancementImpl {
/**
* Some enhancements can be taken multiple times (generally up to three)
*/
override val ranks: Int = 1
/**
* Some enhancements have multiple ranks. This is the cost for each rank. Older versions had
* increasing costs which has been streamlined to a linear progression.
*
* @return
*/
override def apCostPerRank: Int = 2
}
| adarro/ddo-calc | subprojects/common/ddo-core/src/main/scala/io/truthencode/ddo/model/enhancement/enhancements/SwiftAmbition.scala | Scala | apache-2.0 | 1,225 |
import leon.lang._
import leon.annotation._
object AssociativeList {
sealed abstract class KeyValuePairAbs
case class KeyValuePair(key: BigInt, value: BigInt) extends KeyValuePairAbs
sealed abstract class List
case class Cons(head: KeyValuePairAbs, tail: List) extends List
case object Nil extends List
sealed abstract class OptionInt
case class Some(i: BigInt) extends OptionInt
case object None extends OptionInt
def domain(l: List): Set[BigInt] = l match {
case Nil => Set.empty[BigInt]
case Cons(KeyValuePair(k,_), xs) => Set(k) ++ domain(xs)
}
def find(l: List, e: BigInt): OptionInt = l match {
case Nil => None
case Cons(KeyValuePair(k, v), xs) => if (k == e) Some(v) else find(xs, e)
}
def noDuplicates(l: List): Boolean = l match {
case Nil => true
case Cons(KeyValuePair(k, v), xs) => find(xs, k) == None && noDuplicates(xs)
}
def updateList(l1: List, l2: List): List = (l2 match {
case Nil => l1
case Cons(x, xs) => updateList(updateElem(l1, x), xs)
}) ensuring(domain(_) == domain(l1) ++ domain(l2))
def updateElem(l: List, e: KeyValuePairAbs): List = (l match {
case Nil => Cons(e, Nil)
case Cons(KeyValuePair(k, v), xs) => e match {
case KeyValuePair(ek, ev) => if (ek == k) Cons(KeyValuePair(ek, ev), xs) else Cons(KeyValuePair(k, v), updateElem(xs, e))
}
}) ensuring(res => e match {
case KeyValuePair(k, v) => domain(res) == domain(l) ++ Set[BigInt](k)
})
@induct
def readOverWrite(l: List, k1: BigInt, k2: BigInt, e: BigInt) : Boolean = {
find(updateElem(l, KeyValuePair(k2,e)), k1) == (if (k1 == k2) Some(e) else find(l, k1))
} holds
}
| ericpony/scala-examples | testcases/web/verification/02_Associative_List.scala | Scala | mit | 1,667 |
package dao
import java.util.UUID
import base.PostgresDbSpec
import database.RoleDb
import database.helper.LdapUserStatus._
import models.{Authority, Role}
import play.api.inject.guice.GuiceableModule
import security.LWMRole
import security.LWMRole._
import slick.dbio.Effect.Write
import slick.jdbc.PostgresProfile.api._
import scala.concurrent.Future
class RoleDaoSpec extends PostgresDbSpec {
import scala.concurrent.ExecutionContext.Implicits.global
val dao = app.injector.instanceOf(classOf[RoleDao])
val roles = LWMRole.all.map(r => RoleDb(r.label))
def studentRole = roles.find(_.label == StudentRole.label).get
def employeeRole = roles.find(_.label == EmployeeRole.label).get
def adminRole = roles.find(_.label == Admin.label).get
def courseEmployeeRole = roles.find(_.label == CourseEmployee.label).get
def courseStudentRole = roles.find(_.label == CourseAssistant.label).get
"A RoleDaoSpec" should {
"return role which matches user status" in {
runAsyncSequence(
dao.byUserStatusQuery(StudentStatus) map (_.value shouldBe studentRole),
dao.byUserStatusQuery(EmployeeStatus) map (_.value shouldBe employeeRole),
dao.byUserStatusQuery(LecturerStatus) map (_.value shouldBe employeeRole)
)
}
"return role which matches role label" in {
runAsyncSequence(
dao.byRoleLabelQuery(StudentRole.label) map (_.value shouldBe studentRole),
dao.byRoleLabelQuery(EmployeeRole.label) map (_.value shouldBe employeeRole),
dao.byRoleLabelQuery(Admin.label) map (_.value shouldBe adminRole)
)
}
"not return role when not found" in {
runAsyncSequence(
dao.byRoleLabelQuery(God.label) map (_ shouldBe None),
dao.byRoleLabelQuery("other") map (_ shouldBe None)
)
}
"always pass authority validation if the user is an admin" in {
val auths = List(Authority(UUID.randomUUID, adminRole.id))
val results = Future.sequence(LWMRole.all.map(role => dao.isAuthorized(Some(UUID.randomUUID), List(role))(auths)))
async(results)(_.reduce(_ && _) shouldBe true)
}
"always deny authority validation if god is requested" in {
val user = UUID.randomUUID
val auths = roles.map(r => Authority(user, r.id))
async(dao.isAuthorized(None, List(God))(auths))(_ shouldBe false)
}
"check authority validation in different cases" in {
val course1 = UUID.randomUUID
val course2 = UUID.randomUUID
val auths = List(
Authority(UUID.randomUUID, employeeRole.id),
Authority(UUID.randomUUID, courseEmployeeRole.id, Some(course1)),
Authority(UUID.randomUUID, courseStudentRole.id, Some(course2))
)
async(dao.isAuthorized(None, List(EmployeeRole, StudentRole))(auths))(_ shouldBe true)
async(dao.isAuthorized(Some(course1), List(CourseEmployee))(auths))(_ shouldBe true)
async(dao.isAuthorized(Some(course1), List(CourseEmployee, CourseAssistant))(auths))(_ shouldBe true)
async(dao.isAuthorized(Some(course1), List(EmployeeRole, CourseEmployee))(auths))(_ shouldBe true)
async(dao.isAuthorized(Some(course2), List(CourseEmployee, CourseAssistant))(auths))(_ shouldBe true)
async(dao.isAuthorized(Some(course2), List(EmployeeRole, CourseEmployee))(auths))(_ shouldBe false)
async(dao.isAuthorized(Some(UUID.randomUUID), List(CourseEmployee, CourseAssistant))(auths))(_ shouldBe false)
async(dao.isAuthorized(None, List(StudentRole))(auths))(_ shouldBe false)
async(dao.isAuthorized(None, List(CourseManager))(auths))(_ shouldBe false)
async(dao.isAuthorized(None, List(Admin))(auths))(_ shouldBe false)
async(dao.isAuthorized(Some(course1), List(Admin))(auths))(_ shouldBe false)
async(dao.isAuthorized(Some(UUID.randomUUID), List.empty)(auths))(_ shouldBe false)
async(dao.isAuthorized(None, List.empty)(auths))(_ shouldBe false)
async(dao.isAuthorized(None, List(StudentRole))(Seq.empty))(_ shouldBe false)
}
}
override protected def beforeAll(): Unit = {
super.beforeAll()
async(dao.createMany(roles))(_ => Unit)
}
override protected def bindings: Seq[GuiceableModule] = Seq.empty
override protected val dependencies: DBIOAction[Unit, NoStream, Write] = DBIO.seq()
}
| THK-ADV/lwm-reloaded | test/dao/RoleDaoSpec.scala | Scala | mit | 4,300 |