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
|
---|---|---|---|---|---|
package rpm4s.data
sealed trait Distribution extends Product with Serializable
object Distribution {
def fromString(value: String): Distribution = value match {
case "openSUSE Leap 42.3" => OpenSUSELeap42_3
case x => Unknown(x)
}
case object OpenSUSELeap42_3 extends Distribution
case class Unknown(value: String) extends Distribution
}
|
lucidd/rpm4s
|
shared/src/main/scala/rpm4s/data/Distribution.scala
|
Scala
|
mit
| 373 |
//
// StandardInvocationBehavior.scala -- Scala trait StandardInvocationBehavior
// Project OrcScala
//
// Created by dkitchin on Jan 24, 2011.
//
// Copyright (c) 2017 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//
package orc.run
import orc.InvocationBehavior
import orc.run.extensions._
import orc.OrcRuntime
/** @author dkitchin
*/
/* The first behavior in the trait list will be tried last */
trait StandardInvocationBehavior extends InvocationBehavior
with ErrorOnUndefinedInvocation
with SupportForJavaObjectInvocation
with SupportForSiteInvocation {
this: OrcRuntime =>
}
|
orc-lang/orc
|
OrcScala/src/orc/run/StandardInvocationBehavior.scala
|
Scala
|
bsd-3-clause
| 815 |
// during development of late delambdafying there was a problem where
// specialization would undo some of the work done in uncurry if the body of the
// lambda had a constant type. That would result in a compiler crash as
// when the delambdafy phase got a tree shape it didn't understand
class X[@specialized(Int) A] {
val f = { x: A => false }
}
object Test {
def main(args: Array[String]) {
val xInt = new X[Int]
println(xInt.f(42))
val xString = new X[String]
println(xString.f("hello"))
}
}
|
felixmulder/scala
|
test/files/specialized/constant_lambda.scala
|
Scala
|
bsd-3-clause
| 519 |
/**
* Copyright (c) 2010, Stefan Langer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Element34 nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS ROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import sbt._
import java.io.File
import java.nio.charset.Charset._
import scala.xml._
/**
* Defines the structure for a .project file.
*/
class ProjectFile(project: Project, log: Logger) {
/**
* Writes the .project file to the file system
* @return <code>Some(error)</code> when an error occurred else returns <code>None</code>
*/
def writeFile: Option[String] = {
import Utils._
val scalaBuilder = "ch.epfl.lamp.sdt.core.scalabuilder"
val manifestBuilder = "org.eclipse.pde.ManifestBuilder"
val schemaBuilder = "org.eclipse.pde.SchemaBuilder"
val scalaNature = "ch.epfl.lamp.sdt.core.scalanature"
val javaNature = "org.eclipse.jdt.core.javanature"
val pluginNature = "org.eclipse.pde.PluginNature"
lazy val projectFile: File = project.info.projectPath / ".project" asFile;
lazy val projectContent = "<?xml version=\\"1.0\\" encoding=\\"utf-8\\" ?>\\n" +
<projectDescription>
<name>{getProjectName}</name>
<comment>{getProjectDescription}</comment>
<projects>{createSubProjects}</projects>
<buildSpec>
<buildCommand>
<name>{scalaBuilder}</name>
</buildCommand>
{getPluginXml}
</buildSpec>
<natures>
<nature>{scalaNature}</nature>
<nature>{javaNature}</nature>
{getPluginNature}
</natures>
</projectDescription>
def getPluginNature: NodeSeq = writeNodeSeq(get(_.pluginProject)){ _ =>
<nature>{pluginNature}</nature>
}
def getPluginXml: NodeSeq = writeNodeSeq(get(_.pluginProject)){ _ =>
<buildCommand>
<name>{manifestBuilder}</name>
</buildCommand>
<buildCommand>
<name>{schemaBuilder}</name>
</buildCommand>
}
def getProjectName: String = get(_.eclipseName)
def getProjectDescription: String = get(_.projectDescription)
implicit def sbtProject: Project = project
/**
* Creates dependent sub projects
*/
def createSubProjects = {
for (sub <- getSubProjects(project)) yield
<project>{sub.name}</project>
}
def getSubProjects(project: Project) = project.dependencies //Utils.getAllDependencies(project)
FileUtilities.touch(projectFile, log) match {
case Some(error) =>
Some("Unable to write project file " + projectFile+ ": " + error)
case None =>
FileUtilities.write(projectFile, projectContent, forName("UTF-8"), log)
}
}
}
/**
* Factory for creating <code>ProjectFile</code> instances
*/
object ProjectFile {
def apply(project: Project, log: Logger) = new ProjectFile(project, log)
}
|
emarsys/dyson
|
project/build/ProjectFile.scala
|
Scala
|
gpl-3.0
| 4,100 |
package mesosphere.marathon
import akka.actor.{Actor, ActorRef, Props}
/**
* An actor which forwards all its messages
* to the given destination. Useful for testing.
*/
class ForwardingActor(destination: ActorRef) extends Actor {
override def receive: Receive = {
case msg => destination.forward(msg)
}
}
object ForwardingActor {
def props(destination: ActorRef): Props = {
Props(classOf[ForwardingActor], destination)
}
}
|
gsantovena/marathon
|
src/test/scala/mesosphere/marathon/ForwardingActor.scala
|
Scala
|
apache-2.0
| 448 |
package glasskey.play.client
import glasskey.model.AuthCodeAccessTokenHelper
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits._
object AuthCodeController extends SampleController {
override def env: PlayClientRuntimeEnvironment = PlayClientRuntimeEnvironment("hello-authcode-client")
override def index(name: String) = Action.async { implicit request =>
env.tokenHelper.asInstanceOf[AuthCodeAccessTokenHelper].redirectUri = routes.AuthCodeController.index(name).absoluteURL()
doAction(
request,
"http://localhost:9000/secure_hello?name=" + name,
httpMethod,
doSomethingWithResult)
}
}
|
MonsantoCo/glass-key
|
samples/glass-key-play-client/app/glasskey/play/client/AuthCodeController.scala
|
Scala
|
bsd-3-clause
| 652 |
/*
* The MIT License
*
* Copyright (c) 2016 Zhixun Tan
*
* 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 arrow.repr
trait NodeUntyped
|
phisiart/arrow
|
src/main/scala/arrow/repr/NodeUntyped.scala
|
Scala
|
mit
| 1,176 |
/*
* Copyright 2013 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
import cats.Eq
import cats.effect.IO
import cats.effect.testkit.TestContext
import fs2.Chunk
import org.http4s.laws.discipline.EntityCodecTests
import org.http4s.testing.fs2Arbitraries._
class EntityCodecSuite extends Http4sSuite with Http4sLawSuite {
implicit val testContext: TestContext = TestContext()
implicit def eqArray[A](implicit ev: Eq[Vector[A]]): Eq[Array[A]] =
Eq.by(_.toVector)
implicit def eqChunk[A](implicit ev: Eq[Vector[A]]): Eq[Chunk[A]] =
Eq.by(_.toVector)
checkAllF("EntityCodec[IO, String]", EntityCodecTests[IO, String].entityCodecF)
checkAllF("EntityCodec[IO, Array[Char]]", EntityCodecTests[IO, Array[Char]].entityCodecF)
checkAllF("EntityCodec[IO, Chunk[Byte]]", EntityCodecTests[IO, Chunk[Byte]].entityCodecF)
checkAllF("EntityCodec[IO, Array[Byte]]", EntityCodecTests[IO, Array[Byte]].entityCodecF)
checkAllF("EntityCodec[IO, Unit]", EntityCodecTests[IO, Unit].entityCodecF)
}
|
http4s/http4s
|
tests/shared/src/test/scala/org/http4s/EntityCodecSuite.scala
|
Scala
|
apache-2.0
| 1,551 |
/*
* MilmSearch is a mailing list searching system.
*
* Copyright (C) 2013 MilmSearch Project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
* You can contact MilmSearch Project at mailing list
* [email protected].
*/
package org.milmsearch.core.api
import net.liftweb.json.Serialization
import net.liftweb.json.DefaultFormats
/**
* ML็ป้ฒ็ณ่ซๆค็ดข็ตๆใฎๅคๆ็จใชใใธใงใฏใ
*
* D ใฎๅใฏๅ
ๅ
ใใใขใคใใ ใฎDTOใฎๅใๆๅฎใใพใใ
*/
case class SearchResultDto[D](
totalResults: Long,
startIndex: Long,
itemsPerPage: Long,
items: List[D]) {
// for lift-json
implicit val formats = DefaultFormats
def toJson(): String = Serialization.write(this)
}
|
mzkrelx/milm-search-core
|
src/main/scala/org/milmsearch/core/api/SearchResultDto.scala
|
Scala
|
gpl-3.0
| 1,325 |
/*
* Copyright 2015 Heiko Seeberger
*
* 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 de.heikoseeberger.akkasse
import akka.http.scaladsl.model.{ HttpCharsets, MediaType }
/**
* Media types for Server-Sent Events.
*/
object MediaTypes {
/**
* Media type for Server-Sent Events as required by the
* [[http://www.w3.org/TR/eventsource/#event-stream-interpretation SSE specification]].
*/
val `text/event-stream`: MediaType = MediaType.custom(
"text",
"event-stream",
MediaType.Encoding.Fixed(HttpCharsets.`UTF-8`)
)
}
|
jasonchaffee/akka-sse
|
akka-sse/src/main/scala/de/heikoseeberger/akkasse/MediaTypes.scala
|
Scala
|
apache-2.0
| 1,070 |
package org.scalajs.openui5.sap.ui.layout.form
import org.scalajs.openui5.sap.ui.core.Control
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName
@JSName("sap.ui.layout.form.Form")
@js.native
class Form extends Control {
}
|
lastsys/scalajs-openui5
|
src/main/scala/org/scalajs/openui5/sap/ui/layout/form/Form.scala
|
Scala
|
mit
| 241 |
package io.buoyant.linkerd.protocol.http
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.stats.InMemoryStatsReceiver
import com.twitter.finagle.{Service, ServiceFactory, Stack, param}
import com.twitter.util.Future
import io.buoyant.test.Awaits
import org.scalatest.FunSuite
class StatusCodeStatsFilterTest extends FunSuite with Awaits {
object Thrown extends Throwable
test("increments http status code stats on success") {
val stats = new InMemoryStatsReceiver()
val svc = Service.mk[Request, Response] { _ =>
val rep = Response()
rep.statusCode = 404
Future.value(rep)
}
val stk = StatusCodeStatsFilter.module.toStack(
Stack.leaf(StatusCodeStatsFilter.role, ServiceFactory.const(svc))
)
val service = await(stk.make(Stack.Params.empty + param.Stats(stats))())
await(service(Request()))
assert(stats.counters(Seq("status", "404")) == 1)
assert(stats.counters(Seq("status", "4XX")) == 1)
assert(stats.stats.isDefinedAt(Seq("time", "4XX")))
}
test("treats exceptions as 500 failures") {
val stats = new InMemoryStatsReceiver()
val svc = Service.mk[Request, Response] { _ => Future.exception(Thrown) }
val stk = StatusCodeStatsFilter.module.toStack(
Stack.leaf(StatusCodeStatsFilter.role, ServiceFactory.const(svc))
)
val service = await(stk.make(Stack.Params.empty + param.Stats(stats))())
intercept[Throwable] { await(service(Request())) }
assert(stats.counters(Seq("status", "error")) == 1)
assert(stats.stats.isDefinedAt(Seq("time", "error")))
}
}
|
linkerd/linkerd
|
linkerd/protocol/http/src/test/scala/io/buoyant/linkerd/protocol/http/StatusCodeStatsFilterTest.scala
|
Scala
|
apache-2.0
| 1,601 |
// Copyright 2010 Twitter, Inc.
//
// An easy to use thrift client interface.
package com.twitter.rpcclient
import scala.reflect.Manifest
import org.apache.thrift.protocol.TProtocol
import com.twitter.xrayspecs.TimeConversions._
import com.twitter.xrayspecs.Duration
class ThriftClient[Intf <: AnyRef, Cli <: Intf]
(host: String, port: Int, framed: Boolean, soTimeout: Duration, val name: String)
(implicit manifestIntf: Manifest[Intf], manifestCli: Manifest[Cli])
extends PooledClient[Intf]()(manifestIntf)
{
def this(host: String, port: Int)
(implicit manifestIntf: Manifest[Intf], manifestCli: Manifest[Cli]) =
this(host, port, true, 5.seconds, manifestIntf.erasure.getName)
def createConnection =
new ThriftConnection[Cli](host, port, framed) {
override def SO_TIMEOUT = soTimeout
}
}
|
kmonkeyjam/rpc-client
|
src/main/scala/com/twitter/rpcclient/ThriftClient.scala
|
Scala
|
apache-2.0
| 823 |
package com.scala.exercises.impatient.chapter10
/**
* Created by Who on 14-7-12.
*/
trait LoggedException extends Logged {
this: Exception =>
def log() {
log(getMessage)
}
}
|
laonawuli/scalalearning
|
src/com/scala/exercises/impatient/chapter10/LoggedException.scala
|
Scala
|
mit
| 187 |
package uk.gov.gds.ier.transaction.crown.previousAddress
import uk.gov.gds.ier.transaction.crown.CrownControllers
import com.google.inject.{Inject, Singleton}
import uk.gov.gds.ier.config.Config
import uk.gov.gds.ier.model._
import uk.gov.gds.ier.security.EncryptionService
import uk.gov.gds.ier.serialiser.JsonSerialiser
import uk.gov.gds.ier.step.CrownStep
import uk.gov.gds.ier.step.Routes
import uk.gov.gds.ier.validation.ErrorTransformForm
import uk.gov.gds.ier.transaction.crown.InprogressCrown
import uk.gov.gds.ier.service.AddressService
import uk.gov.gds.ier.assets.RemoteAssets
@Singleton
class PreviousAddressManualStep @Inject() (
val serialiser: JsonSerialiser,
val config: Config,
val addressService: AddressService,
val remoteAssets: RemoteAssets,
val encryptionService: EncryptionService,
val crown: CrownControllers
) extends CrownStep
with PreviousAddressManualMustache
with PreviousAddressForms {
val validation = manualStepForm
val routing = Routes(
get = routes.PreviousAddressManualStep.get,
post = routes.PreviousAddressManualStep.post,
editGet = routes.PreviousAddressManualStep.editGet,
editPost = routes.PreviousAddressManualStep.editPost
)
def nextStep(currentState: InprogressCrown) = {
crown.NationalityStep
}
override val onSuccess = TransformApplication { currentState =>
val addressWithClearedSelectedOne = currentState.previousAddress.map { prev =>
prev.copy(
previousAddress = prev.previousAddress.map(
_.copy(
uprn = None,
addressLine = None)))
}
currentState.copy(
previousAddress = addressWithClearedSelectedOne,
possibleAddresses = None
)
} andThen GoToNextIncompleteStep()
}
|
michaeldfallen/ier-frontend
|
app/uk/gov/gds/ier/transaction/crown/previousAddress/PreviousAddressManualStep.scala
|
Scala
|
mit
| 1,759 |
package com.twitter.finagle.service
import com.twitter.conversions.time._
import com.twitter.finagle._
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.util.{Duration, Future, Stopwatch, Time, TokenBucket}
object DeadlineFilter {
val role = new Stack.Role("DeadlineAdmissionControl")
private[this] val DefaultTolerance = 170.milliseconds // max empirically measured clock skew
private[this] val DefaultRejectPeriod = 10.seconds
// In the case of large delays, don't want to reject too many requests
private[this] val DefaultMaxRejectPercentage = 0.2
// Token Bucket is integer-based, so use a scale factor to facilitate
// usage with the Double `maxRejectPercentage`
private[service] val RejectBucketScaleFactor = 1000.0
/**
* A class eligible for configuring a [[com.twitter.finagle.Stackable]]
* [[com.twitter.finagle.service.DeadlineFilter]] module.
*
* @param tolerance The max elapsed time since a request's deadline when it
* will be considered for rejection. Used to account for unreasonable clock
* skew.
*
* @param maxRejectPercentage Maximum percentage of requests that can be
* rejected over `rejectPeriod`. Must be between 0.0 and 1.0.
*/
case class Param(
tolerance: Duration,
maxRejectPercentage: Double)
{
require(tolerance >= Duration.Zero,
"tolerance must be greater than zero")
require(maxRejectPercentage >= 0.0 && maxRejectPercentage <= 1.0,
s"maxRejectPercentage must be between 0.0 and 1.0: $maxRejectPercentage")
def mk(): (Param, Stack.Param[Param]) =
(this, Param.param)
}
object Param {
implicit val param = Stack.Param(
Param(DefaultTolerance, DefaultMaxRejectPercentage))
}
/**
* Creates a [[com.twitter.finagle.Stackable]]
* [[com.twitter.finagle.service.DeadlineFilter]].
*/
def module[Req, Rep]: Stackable[ServiceFactory[Req, Rep]] =
new Stack.Module2[param.Stats, DeadlineFilter.Param, ServiceFactory[Req, Rep]] {
val role = DeadlineFilter.role
val description = "Reject requests when their deadline has passed"
def make(
_stats: param.Stats,
_param: DeadlineFilter.Param,
next: ServiceFactory[Req, Rep]
) = {
val Param(tolerance, maxRejectPercentage) = _param
val param.Stats(statsReceiver) = _stats
val scopedStatsReceiver = statsReceiver.scope("admission_control", "deadline")
new ServiceFactoryProxy[Req, Rep](next) {
override def apply(conn: ClientConnection): Future[Service[Req, Rep]] =
next(conn).map { service =>
if (maxRejectPercentage <= 0.0) service
else
new DeadlineFilter(
tolerance,
DefaultRejectPeriod,
maxRejectPercentage,
scopedStatsReceiver).andThen(service)
}
}
}
}
}
/**
* A [[com.twitter.finagle.Filter]] that rejects requests when their deadline
* has passed.
*
* @param tolerance The max elapsed time since a request's deadline when it will
* be considered for rejection. Used to account for unreasonable clock skew.
*
* @param rejectPeriod No more than `maxRejectPercentage` of requests will be
* discarded over the `rejectPeriod`. Must be `>= 1 second` and `<= 60 seconds`.
*
* @param maxRejectPercentage Maximum percentage of requests that can be
* rejected over `rejectPeriod`. Must be between 0.0 and 1.0.
*
* @param statsReceiver for stats reporting, typically scoped to
* ".../admission_control/deadline/"
*
* @param nowMillis current time in milliseconds
*
* @see The [[https://twitter.github.io/finagle/guide/Servers.html#request-deadline user guide]]
* for more details.
*/
private[finagle] class DeadlineFilter[Req, Rep](
tolerance: Duration,
rejectPeriod: Duration,
maxRejectPercentage: Double,
statsReceiver: StatsReceiver,
nowMillis: () => Long = Stopwatch.systemMillis)
extends SimpleFilter[Req, Rep] {
require(tolerance >= Duration.Zero,
"tolerance must be greater than zero")
require(rejectPeriod.inSeconds >= 1 && rejectPeriod.inSeconds <= 60,
s"rejectPeriod must be [1 second, 60 seconds]: $rejectPeriod")
require(maxRejectPercentage <= 1.0,
s"maxRejectPercentage must be between 0.0 and 1.0: $maxRejectPercentage")
private[this] val exceededStat = statsReceiver.counter("exceeded")
private[this] val beyondToleranceStat =
statsReceiver.counter("exceeded_beyond_tolerance")
private[this] val rejectedStat = statsReceiver.counter("rejected")
private[this] val transitTimeStat = statsReceiver.stat("transit_latency_ms")
private[this] val budgetTimeStat = statsReceiver.stat("deadline_budget_ms")
private[this] val serviceDeposit =
DeadlineFilter.RejectBucketScaleFactor.toInt
private[this] val rejectWithdrawal =
(DeadlineFilter.RejectBucketScaleFactor / maxRejectPercentage).toInt
private[this] val rejectBucket = TokenBucket.newLeakyBucket(
rejectPeriod, 0, nowMillis)
private[this] def deadlineExceeded(
deadline: Deadline,
elapsed: Duration,
now: Time
) = s"exceeded request deadline of ${deadline.deadline - deadline.timestamp} " +
s"by $elapsed. Deadline expired at ${deadline.deadline} and now it is $now."
// The request is rejected if the set deadline has expired, the elapsed time
// since expiry is less than `tolerance`, and there are at least
// `rejectWithdrawal` tokens in `rejectBucket`. Otherwise, the request is
// serviced and `serviceDeposit` tokens are added to `rejectBucket`.
//
// Note: While in the testing stages, requests are never rejected, but
// the admission_control/deadline/rejected stat is incremented.
def apply(request: Req, service: Service[Req, Rep]): Future[Rep] =
Deadline.current match {
case Some(deadline) =>
val now = Time.now
val remaining = deadline.deadline - now
transitTimeStat.add((now - deadline.timestamp).max(Duration.Zero).inMilliseconds)
budgetTimeStat.add(remaining.inMilliseconds)
// Exceeded the deadline within tolerance, and there are enough
// tokens to reject the request
if (remaining < Duration.Zero
&& -remaining <= tolerance
&& rejectBucket.tryGet(rejectWithdrawal)) {
exceededStat.incr()
rejectedStat.incr()
service(request) // When turned on this will be Future.exception
} else {
if (-remaining > tolerance) beyondToleranceStat.incr()
else if (remaining < Duration.Zero) exceededStat.incr()
rejectBucket.put(serviceDeposit)
service(request)
}
case None =>
rejectBucket.put(serviceDeposit)
service(request)
}
}
|
lukiano/finagle
|
finagle-core/src/main/scala/com/twitter/finagle/service/DeadlineFilter.scala
|
Scala
|
apache-2.0
| 6,802 |
package org.scalatra.util
package io
import scala.io.Source
import java.io._
import org.scalatest.WordSpec
import org.scalatest.matchers.ShouldMatchers
class IoSpec extends WordSpec with ShouldMatchers {
"copy" should {
"copy an input stream smaller than the buffer size to the output stream" in {
testCopy(100, 256)
}
"copy an input stream smaller equal to the buffer size to the output stream" in {
testCopy(256, 256)
}
"copy an input stream smaller greater than the buffer size to the output stream" in {
testCopy(300, 256)
}
"copy an empty input stream to the output stream" in {
testCopy(0, 256)
}
"not blow the stack" in {
testCopy(10000, 10000)
}
def testCopy(len: Int, bufferSize: Int) {
val bytes: Array[Byte] = (0 until len) map { x => x.toByte } toArray
val in = new ByteArrayInputStream(bytes)
val out = new ByteArrayOutputStream
copy(in, out, bufferSize)
out.toByteArray should equal (bytes)
}
"close the input stream even if copying throws" in {
var isClosed = false
val in = new InputStream {
def read() = throw new RuntimeException
override def close() = isClosed = true
}
try {
copy(in, new ByteArrayOutputStream)
}
catch { case ignore => }
isClosed should equal (true)
}
"throw any exception during copy" in {
val e = new RuntimeException
val in = new InputStream {
def read() = throw e
}
val caught = try {
copy(in, new ByteArrayOutputStream)
None
}
catch { case ex => Some(ex) }
caught should equal (Some(e))
}
}
"withTempFile" should {
val content = "content"
"create a temp file with the specified contents" in {
withTempFile(content) { f =>
Source.fromFile(f).mkString should equal (content)
}
}
"remove the temp file on completion of the block" in {
var f: File = null
withTempFile(content) { myF =>
f = myF
f.exists() should be (true)
}
f.exists() should be (false)
}
"remove the temp file even if the block throws" in {
var f: File = null
try {
withTempFile(content) { myF =>
f = myF
throw new RuntimeException()
}
}
catch {
case _ => f.exists() should be (false)
}
}
}
}
|
louk/scalatra
|
core/src/test/scala/org/scalatra/util/io/IoSpec.scala
|
Scala
|
bsd-2-clause
| 2,438 |
package org.mysql.employee.utils
object Companion {
def companion[R, T](m: Manifest[T]) = {
val classOfT = m.runtimeClass
Class.forName(classOfT.getName + "$").getField("MODULE$").get(null).asInstanceOf[R]
}
}
|
matyb/spark-employee
|
src/test/scala/org/mysql/employee/utils/Companion.scala
|
Scala
|
mit
| 224 |
/*
* 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.flink.table.plan.optimize.program
import org.apache.calcite.plan.Convention
import org.apache.calcite.plan.hep.{HepMatchOrder, HepProgramBuilder}
import org.apache.calcite.rel.RelNode
import org.apache.calcite.rel.rules._
import org.apache.calcite.tools.RuleSets
import org.junit.Assert._
import org.junit.Test
import scala.collection.JavaConversions._
/**
* Tests for [[FlinkChainedProgram]].
*/
class FlinkChainedProgramTest {
@Test
def testAddGetRemovePrograms(): Unit = {
val programs = new FlinkChainedProgram
assertTrue(programs.getProgramNames.isEmpty)
assertTrue(programs.get("o1").isEmpty)
// test addFirst
val builder = new HepProgramBuilder()
builder
.addMatchLimit(10)
.addMatchOrder(HepMatchOrder.ARBITRARY)
.addRuleInstance(SubQueryRemoveRule.FILTER)
.addRuleInstance(SubQueryRemoveRule.PROJECT)
.addRuleInstance(SubQueryRemoveRule.JOIN)
.addMatchLimit(100)
.addMatchOrder(HepMatchOrder.BOTTOM_UP)
.addRuleCollection(Array(
TableScanRule.INSTANCE,
ValuesReduceRule.FILTER_INSTANCE
).toList)
val program1 = FlinkHepProgram(builder.build())
assertTrue(programs.addFirst("o2", program1))
assertEquals(List("o2"), programs.getProgramNames.toList)
assertTrue(programs.get("o2").isDefined)
assertTrue(program1 eq programs.get("o2").get)
val program2 = FlinkHepRuleSetProgramBuilder.newBuilder
.add(RuleSets.ofList(
ReduceExpressionsRule.FILTER_INSTANCE,
ReduceExpressionsRule.PROJECT_INSTANCE,
ReduceExpressionsRule.CALC_INSTANCE,
ReduceExpressionsRule.JOIN_INSTANCE
)).build()
assertTrue(programs.addFirst("o1", program2))
assertEquals(List("o1", "o2"), programs.getProgramNames.toList)
assertTrue(programs.get("o1").isDefined)
assertTrue(program2 eq programs.get("o1").get)
// test addLast
val program3 = FlinkHepRuleSetProgramBuilder.newBuilder
.add(RuleSets.ofList(
FilterCalcMergeRule.INSTANCE,
ProjectCalcMergeRule.INSTANCE,
FilterToCalcRule.INSTANCE,
ProjectToCalcRule.INSTANCE,
CalcMergeRule.INSTANCE))
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION)
.setMatchLimit(10000)
.setHepMatchOrder(HepMatchOrder.ARBITRARY)
.build()
assertTrue(programs.addLast("o4", program3))
assertEquals(List("o1", "o2", "o4"), programs.getProgramNames.toList)
assertTrue(programs.get("o4").isDefined)
assertTrue(program3 eq programs.get("o4").get)
// test addBefore
val TEST = new Convention.Impl("TEST", classOf[RelNode])
val program4 = FlinkVolcanoProgramBuilder.newBuilder
.add(RuleSets.ofList(
FilterJoinRule.FILTER_ON_JOIN,
FilterJoinRule.JOIN))
.setRequiredOutputTraits(Array(TEST))
.build()
assertTrue(programs.addBefore("o4", "o3", program4))
assertEquals(List("o1", "o2", "o3", "o4"), programs.getProgramNames.toList)
assertTrue(programs.get("o3").isDefined)
assertTrue(program4 eq programs.get("o3").get)
// test remove
val p2 = programs.remove("o2")
assertTrue(p2.isDefined)
assertTrue(p2.get eq program1)
assertEquals(List("o1", "o3", "o4"), programs.getProgramNames.toList)
assertTrue(programs.remove("o0").isEmpty)
assertEquals(List("o1", "o3", "o4"), programs.getProgramNames.toList)
// program already exists
assertFalse(programs.addFirst("o3", program1))
assertFalse(programs.addLast("o4", program1))
assertFalse(programs.addBefore("o0", "o4", program1))
assertEquals(List("o1", "o3", "o4"), programs.getProgramNames.toList)
}
@Test
def testGetFlinkRuleSetProgram(): Unit = {
val programs = new FlinkChainedProgram
assertTrue(programs.getProgramNames.isEmpty)
val program1 = FlinkHepRuleSetProgramBuilder.newBuilder
.add(RuleSets.ofList(ReduceExpressionsRule.FILTER_INSTANCE))
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.build()
programs.addFirst("o1", program1)
assertTrue(programs.get("o1").isDefined)
assertTrue(program1 eq programs.get("o1").get)
val builder = new HepProgramBuilder()
builder
.addMatchLimit(10)
.addRuleInstance(SubQueryRemoveRule.FILTER)
.addRuleInstance(SubQueryRemoveRule.JOIN)
.addMatchOrder(HepMatchOrder.BOTTOM_UP)
val program2 = FlinkHepProgram(builder.build())
programs.addLast("o2", program2)
assertTrue(programs.get("o2").isDefined)
assertTrue(program2 eq programs.get("o2").get)
assertTrue(programs.getFlinkRuleSetProgram("o2").isEmpty)
assertTrue(programs.getFlinkRuleSetProgram("o3").isEmpty)
val p1 = programs.getFlinkRuleSetProgram("o1")
assertTrue(p1.isDefined)
p1.get.add(RuleSets.ofList(SubQueryRemoveRule.PROJECT))
assertTrue(p1.get eq programs.getFlinkRuleSetProgram("o1").get)
}
@Test(expected = classOf[NullPointerException])
def testAddNullProgram(): Unit = {
val programs = new FlinkChainedProgram[BatchOptimizeContext]
programs.addLast("o1", null)
}
}
|
ueshin/apache-flink
|
flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/optimize/program/FlinkChainedProgramTest.scala
|
Scala
|
apache-2.0
| 5,899 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.deploy.history
import java.io._
import java.nio.charset.StandardCharsets
import java.util.{Date, Locale}
import java.util.concurrent.TimeUnit
import java.util.zip.{ZipInputStream, ZipOutputStream}
import scala.collection.JavaConverters._
import scala.concurrent.duration._
import com.google.common.io.{ByteStreams, Files}
import org.apache.commons.io.FileUtils
import org.apache.hadoop.fs.{FileStatus, FileSystem, FSDataInputStream, Path}
import org.apache.hadoop.hdfs.{DFSInputStream, DistributedFileSystem}
import org.apache.hadoop.security.AccessControlException
import org.json4s.jackson.JsonMethods._
import org.mockito.ArgumentMatchers.{any, argThat}
import org.mockito.Mockito.{doThrow, mock, spy, verify, when}
import org.scalatest.Matchers
import org.scalatest.concurrent.Eventually._
import org.apache.spark.{SecurityManager, SPARK_VERSION, SparkConf, SparkFunSuite}
import org.apache.spark.internal.Logging
import org.apache.spark.internal.config.DRIVER_LOG_DFS_DIR
import org.apache.spark.internal.config.History._
import org.apache.spark.internal.config.UI.{ADMIN_ACLS, ADMIN_ACLS_GROUPS, USER_GROUPS_MAPPING}
import org.apache.spark.io._
import org.apache.spark.scheduler._
import org.apache.spark.scheduler.cluster.ExecutorInfo
import org.apache.spark.security.GroupMappingServiceProvider
import org.apache.spark.status.AppStatusStore
import org.apache.spark.status.KVUtils.KVStoreScalaSerializer
import org.apache.spark.status.api.v1.{ApplicationAttemptInfo, ApplicationInfo}
import org.apache.spark.util.{Clock, JsonProtocol, ManualClock, Utils}
import org.apache.spark.util.logging.DriverLogger
class FsHistoryProviderSuite extends SparkFunSuite with Matchers with Logging {
private var testDir: File = null
override def beforeEach(): Unit = {
super.beforeEach()
testDir = Utils.createTempDir(namePrefix = s"a b%20c+d")
}
override def afterEach(): Unit = {
try {
Utils.deleteRecursively(testDir)
} finally {
super.afterEach()
}
}
/** Create a fake log file using the new log format used in Spark 1.3+ */
private def newLogFile(
appId: String,
appAttemptId: Option[String],
inProgress: Boolean,
codec: Option[String] = None): File = {
val ip = if (inProgress) EventLogFileWriter.IN_PROGRESS else ""
val logUri = SingleEventLogFileWriter.getLogPath(testDir.toURI, appId, appAttemptId, codec)
val logPath = new Path(logUri).toUri.getPath + ip
new File(logPath)
}
Seq(true, false).foreach { inMemory =>
test(s"Parse application logs (inMemory = $inMemory)") {
testAppLogParsing(inMemory)
}
}
private def testAppLogParsing(inMemory: Boolean): Unit = {
val clock = new ManualClock(12345678)
val conf = createTestConf(inMemory = inMemory)
val provider = new FsHistoryProvider(conf, clock)
// Write a new-style application log.
val newAppComplete = newLogFile("new1", None, inProgress = false)
writeFile(newAppComplete, None,
SparkListenerApplicationStart(newAppComplete.getName(), Some("new-app-complete"), 1L, "test",
None),
SparkListenerApplicationEnd(5L)
)
// Write a new-style application log.
val newAppCompressedComplete = newLogFile("new1compressed", None, inProgress = false,
Some("lzf"))
writeFile(newAppCompressedComplete, Some(CompressionCodec.createCodec(conf, "lzf")),
SparkListenerApplicationStart(newAppCompressedComplete.getName(), Some("new-complete-lzf"),
1L, "test", None),
SparkListenerApplicationEnd(4L))
// Write an unfinished app, new-style.
val newAppIncomplete = newLogFile("new2", None, inProgress = true)
writeFile(newAppIncomplete, None,
SparkListenerApplicationStart(newAppIncomplete.getName(), Some("new-incomplete"), 1L, "test",
None)
)
// Force a reload of data from the log directory, and check that logs are loaded.
// Take the opportunity to check that the offset checks work as expected.
updateAndCheck(provider) { list =>
list.size should be (3)
list.count(_.attempts.head.completed) should be (2)
def makeAppInfo(
id: String,
name: String,
start: Long,
end: Long,
lastMod: Long,
user: String,
completed: Boolean): ApplicationInfo = {
val duration = if (end > 0) end - start else 0
new ApplicationInfo(id, name, None, None, None, None,
List(ApplicationAttemptInfo(None, new Date(start),
new Date(end), new Date(lastMod), duration, user, completed, SPARK_VERSION)))
}
// For completed files, lastUpdated would be lastModified time.
list(0) should be (makeAppInfo("new-app-complete", newAppComplete.getName(), 1L, 5L,
newAppComplete.lastModified(), "test", true))
list(1) should be (makeAppInfo("new-complete-lzf", newAppCompressedComplete.getName(),
1L, 4L, newAppCompressedComplete.lastModified(), "test", true))
// For Inprogress files, lastUpdated would be current loading time.
list(2) should be (makeAppInfo("new-incomplete", newAppIncomplete.getName(), 1L, -1L,
clock.getTimeMillis(), "test", false))
// Make sure the UI can be rendered.
list.foreach { info =>
val appUi = provider.getAppUI(info.id, None)
appUi should not be null
appUi should not be None
}
}
}
test("SPARK-3697: ignore files that cannot be read.") {
// setReadable(...) does not work on Windows. Please refer JDK-6728842.
assume(!Utils.isWindows)
class TestFsHistoryProvider extends FsHistoryProvider(createTestConf()) {
var mergeApplicationListingCall = 0
override protected def mergeApplicationListing(
reader: EventLogFileReader,
lastSeen: Long,
enableSkipToEnd: Boolean): Unit = {
super.mergeApplicationListing(reader, lastSeen, enableSkipToEnd)
mergeApplicationListingCall += 1
}
}
val provider = new TestFsHistoryProvider
val logFile1 = newLogFile("new1", None, inProgress = false)
writeFile(logFile1, None,
SparkListenerApplicationStart("app1-1", Some("app1-1"), 1L, "test", None),
SparkListenerApplicationEnd(2L)
)
val logFile2 = newLogFile("new2", None, inProgress = false)
writeFile(logFile2, None,
SparkListenerApplicationStart("app1-2", Some("app1-2"), 1L, "test", None),
SparkListenerApplicationEnd(2L)
)
logFile2.setReadable(false, false)
updateAndCheck(provider) { list =>
list.size should be (1)
}
provider.mergeApplicationListingCall should be (1)
}
test("history file is renamed from inprogress to completed") {
val provider = new FsHistoryProvider(createTestConf())
val logFile1 = newLogFile("app1", None, inProgress = true)
writeFile(logFile1, None,
SparkListenerApplicationStart("app1", Some("app1"), 1L, "test", None),
SparkListenerApplicationEnd(2L)
)
updateAndCheck(provider) { list =>
list.size should be (1)
provider.getAttempt("app1", None).logPath should endWith(EventLogFileWriter.IN_PROGRESS)
}
logFile1.renameTo(newLogFile("app1", None, inProgress = false))
updateAndCheck(provider) { list =>
list.size should be (1)
provider.getAttempt("app1", None).logPath should not endWith(EventLogFileWriter.IN_PROGRESS)
}
}
test("Parse logs that application is not started") {
val provider = new FsHistoryProvider(createTestConf())
val logFile1 = newLogFile("app1", None, inProgress = true)
writeFile(logFile1, None,
SparkListenerLogStart("1.4")
)
updateAndCheck(provider) { list =>
list.size should be (0)
}
}
test("SPARK-5582: empty log directory") {
val provider = new FsHistoryProvider(createTestConf())
val logFile1 = newLogFile("app1", None, inProgress = true)
writeFile(logFile1, None,
SparkListenerApplicationStart("app1", Some("app1"), 1L, "test", None),
SparkListenerApplicationEnd(2L))
val oldLog = new File(testDir, "old1")
oldLog.mkdir()
provider.checkForLogs()
val appListAfterRename = provider.getListing()
appListAfterRename.size should be (1)
}
test("apps with multiple attempts with order") {
val provider = new FsHistoryProvider(createTestConf())
val attempt1 = newLogFile("app1", Some("attempt1"), inProgress = true)
writeFile(attempt1, None,
SparkListenerApplicationStart("app1", Some("app1"), 1L, "test", Some("attempt1"))
)
updateAndCheck(provider) { list =>
list.size should be (1)
list.head.attempts.size should be (1)
}
val attempt2 = newLogFile("app1", Some("attempt2"), inProgress = true)
writeFile(attempt2, None,
SparkListenerApplicationStart("app1", Some("app1"), 2L, "test", Some("attempt2"))
)
updateAndCheck(provider) { list =>
list.size should be (1)
list.head.attempts.size should be (2)
list.head.attempts.head.attemptId should be (Some("attempt2"))
}
val attempt3 = newLogFile("app1", Some("attempt3"), inProgress = false)
writeFile(attempt3, None,
SparkListenerApplicationStart("app1", Some("app1"), 3L, "test", Some("attempt3")),
SparkListenerApplicationEnd(4L)
)
updateAndCheck(provider) { list =>
list.size should be (1)
list.head.attempts.size should be (3)
list.head.attempts.head.attemptId should be (Some("attempt3"))
}
val app2Attempt1 = newLogFile("app2", Some("attempt1"), inProgress = false)
writeFile(app2Attempt1, None,
SparkListenerApplicationStart("app2", Some("app2"), 5L, "test", Some("attempt1")),
SparkListenerApplicationEnd(6L)
)
updateAndCheck(provider) { list =>
list.size should be (2)
list.head.attempts.size should be (1)
list.last.attempts.size should be (3)
list.head.attempts.head.attemptId should be (Some("attempt1"))
list.foreach { app =>
app.attempts.foreach { attempt =>
val appUi = provider.getAppUI(app.id, attempt.attemptId)
appUi should not be null
}
}
}
}
test("log urls without customization") {
val conf = createTestConf()
val executorInfos = (1 to 5).map(createTestExecutorInfo("app1", "user1", _))
val expected: Map[ExecutorInfo, Map[String, String]] = executorInfos.map { execInfo =>
execInfo -> execInfo.logUrlMap
}.toMap
testHandlingExecutorLogUrl(conf, expected)
}
test("custom log urls, including FILE_NAME") {
val conf = createTestConf()
.set(CUSTOM_EXECUTOR_LOG_URL, getCustomExecutorLogUrl(includeFileName = true))
// some of available attributes are not used in pattern which should be OK
val executorInfos = (1 to 5).map(createTestExecutorInfo("app1", "user1", _))
val expected: Map[ExecutorInfo, Map[String, String]] = executorInfos.map { execInfo =>
val attr = execInfo.attributes
val newLogUrlMap = attr("LOG_FILES").split(",").map { file =>
val newLogUrl = getExpectedExecutorLogUrl(attr, Some(file))
file -> newLogUrl
}.toMap
execInfo -> newLogUrlMap
}.toMap
testHandlingExecutorLogUrl(conf, expected)
}
test("custom log urls, excluding FILE_NAME") {
val conf = createTestConf()
.set(CUSTOM_EXECUTOR_LOG_URL, getCustomExecutorLogUrl(includeFileName = false))
// some of available attributes are not used in pattern which should be OK
val executorInfos = (1 to 5).map(createTestExecutorInfo("app1", "user1", _))
val expected: Map[ExecutorInfo, Map[String, String]] = executorInfos.map { execInfo =>
val attr = execInfo.attributes
val newLogUrl = getExpectedExecutorLogUrl(attr, None)
execInfo -> Map("log" -> newLogUrl)
}.toMap
testHandlingExecutorLogUrl(conf, expected)
}
test("custom log urls with invalid attribute") {
// Here we are referring {{NON_EXISTING}} which is not available in attributes,
// which Spark will fail back to provide origin log url with warning log.
val conf = createTestConf()
.set(CUSTOM_EXECUTOR_LOG_URL, getCustomExecutorLogUrl(includeFileName = true) +
"/{{NON_EXISTING}}")
val executorInfos = (1 to 5).map(createTestExecutorInfo("app1", "user1", _))
val expected: Map[ExecutorInfo, Map[String, String]] = executorInfos.map { execInfo =>
execInfo -> execInfo.logUrlMap
}.toMap
testHandlingExecutorLogUrl(conf, expected)
}
test("custom log urls, LOG_FILES not available while FILE_NAME is specified") {
// For this case Spark will fail back to provide origin log url with warning log.
val conf = createTestConf()
.set(CUSTOM_EXECUTOR_LOG_URL, getCustomExecutorLogUrl(includeFileName = true))
val executorInfos = (1 to 5).map(
createTestExecutorInfo("app1", "user1", _, includingLogFiles = false))
val expected: Map[ExecutorInfo, Map[String, String]] = executorInfos.map { execInfo =>
execInfo -> execInfo.logUrlMap
}.toMap
testHandlingExecutorLogUrl(conf, expected)
}
test("custom log urls, app not finished, applyIncompleteApplication: true") {
val conf = createTestConf()
.set(CUSTOM_EXECUTOR_LOG_URL, getCustomExecutorLogUrl(includeFileName = true))
.set(APPLY_CUSTOM_EXECUTOR_LOG_URL_TO_INCOMPLETE_APP, true)
// ensure custom log urls are applied to incomplete application
val executorInfos = (1 to 5).map(createTestExecutorInfo("app1", "user1", _))
val expected: Map[ExecutorInfo, Map[String, String]] = executorInfos.map { execInfo =>
val attr = execInfo.attributes
val newLogUrlMap = attr("LOG_FILES").split(",").map { file =>
val newLogUrl = getExpectedExecutorLogUrl(attr, Some(file))
file -> newLogUrl
}.toMap
execInfo -> newLogUrlMap
}.toMap
testHandlingExecutorLogUrl(conf, expected, isCompletedApp = false)
}
test("custom log urls, app not finished, applyIncompleteApplication: false") {
val conf = createTestConf()
.set(CUSTOM_EXECUTOR_LOG_URL, getCustomExecutorLogUrl(includeFileName = true))
.set(APPLY_CUSTOM_EXECUTOR_LOG_URL_TO_INCOMPLETE_APP, false)
// ensure custom log urls are NOT applied to incomplete application
val executorInfos = (1 to 5).map(createTestExecutorInfo("app1", "user1", _))
val expected: Map[ExecutorInfo, Map[String, String]] = executorInfos.map { execInfo =>
execInfo -> execInfo.logUrlMap
}.toMap
testHandlingExecutorLogUrl(conf, expected, isCompletedApp = false)
}
private def getCustomExecutorLogUrl(includeFileName: Boolean): String = {
val baseUrl = "http://newhost:9999/logs/clusters/{{CLUSTER_ID}}/users/{{USER}}/containers/" +
"{{CONTAINER_ID}}"
if (includeFileName) baseUrl + "/{{FILE_NAME}}" else baseUrl
}
private def getExpectedExecutorLogUrl(
attributes: Map[String, String],
fileName: Option[String]): String = {
val baseUrl = s"http://newhost:9999/logs/clusters/${attributes("CLUSTER_ID")}" +
s"/users/${attributes("USER")}/containers/${attributes("CONTAINER_ID")}"
fileName match {
case Some(file) => baseUrl + s"/$file"
case None => baseUrl
}
}
private def testHandlingExecutorLogUrl(
conf: SparkConf,
expectedLogUrlMap: Map[ExecutorInfo, Map[String, String]],
isCompletedApp: Boolean = true): Unit = {
val provider = new FsHistoryProvider(conf)
val attempt1 = newLogFile("app1", Some("attempt1"), inProgress = true)
val executorAddedEvents = expectedLogUrlMap.keys.zipWithIndex.map { case (execInfo, idx) =>
SparkListenerExecutorAdded(1 + idx, s"exec$idx", execInfo)
}.toList.sortBy(_.time)
val allEvents = List(SparkListenerApplicationStart("app1", Some("app1"), 1L,
"test", Some("attempt1"))) ++ executorAddedEvents ++
(if (isCompletedApp) List(SparkListenerApplicationEnd(1000L)) else Seq())
writeFile(attempt1, None, allEvents: _*)
updateAndCheck(provider) { list =>
list.size should be (1)
list.head.attempts.size should be (1)
list.foreach { app =>
app.attempts.foreach { attempt =>
val appUi = provider.getAppUI(app.id, attempt.attemptId)
appUi should not be null
val executors = appUi.get.ui.store.executorList(false).iterator
executors should not be null
val iterForExpectation = expectedLogUrlMap.iterator
var executorCount = 0
while (executors.hasNext) {
val executor = executors.next()
val (expectedExecInfo, expectedLogs) = iterForExpectation.next()
executor.hostPort should startWith(expectedExecInfo.executorHost)
executor.executorLogs should be(expectedLogs)
executorCount += 1
}
executorCount should be (expectedLogUrlMap.size)
}
}
}
}
test("log cleaner") {
val maxAge = TimeUnit.SECONDS.toMillis(10)
val clock = new ManualClock(maxAge / 2)
val provider = new FsHistoryProvider(
createTestConf().set(MAX_LOG_AGE_S.key, s"${maxAge}ms"), clock)
val log1 = newLogFile("app1", Some("attempt1"), inProgress = false)
writeFile(log1, None,
SparkListenerApplicationStart("app1", Some("app1"), 1L, "test", Some("attempt1")),
SparkListenerApplicationEnd(2L)
)
log1.setLastModified(0L)
val log2 = newLogFile("app1", Some("attempt2"), inProgress = false)
writeFile(log2, None,
SparkListenerApplicationStart("app1", Some("app1"), 3L, "test", Some("attempt2")),
SparkListenerApplicationEnd(4L)
)
log2.setLastModified(clock.getTimeMillis())
updateAndCheck(provider) { list =>
list.size should be (1)
list.head.attempts.size should be (2)
}
// Move the clock forward so log1 exceeds the max age.
clock.advance(maxAge)
updateAndCheck(provider) { list =>
list.size should be (1)
list.head.attempts.size should be (1)
list.head.attempts.head.attemptId should be (Some("attempt2"))
}
assert(!log1.exists())
// Do the same for the other log.
clock.advance(maxAge)
updateAndCheck(provider) { list =>
list.size should be (0)
}
assert(!log2.exists())
}
test("should not clean inprogress application with lastUpdated time less than maxTime") {
val firstFileModifiedTime = TimeUnit.DAYS.toMillis(1)
val secondFileModifiedTime = TimeUnit.DAYS.toMillis(6)
val maxAge = TimeUnit.DAYS.toMillis(7)
val clock = new ManualClock(0)
val provider = new FsHistoryProvider(
createTestConf().set(MAX_LOG_AGE_S, maxAge / 1000), clock)
val log = newLogFile("inProgressApp1", None, inProgress = true)
writeFile(log, None,
SparkListenerApplicationStart(
"inProgressApp1", Some("inProgressApp1"), 3L, "test", Some("attempt1"))
)
clock.setTime(firstFileModifiedTime)
log.setLastModified(clock.getTimeMillis())
provider.checkForLogs()
writeFile(log, None,
SparkListenerApplicationStart(
"inProgressApp1", Some("inProgressApp1"), 3L, "test", Some("attempt1")),
SparkListenerJobStart(0, 1L, Nil, null)
)
clock.setTime(secondFileModifiedTime)
log.setLastModified(clock.getTimeMillis())
provider.checkForLogs()
clock.setTime(TimeUnit.DAYS.toMillis(10))
writeFile(log, None,
SparkListenerApplicationStart(
"inProgressApp1", Some("inProgressApp1"), 3L, "test", Some("attempt1")),
SparkListenerJobStart(0, 1L, Nil, null),
SparkListenerJobEnd(0, 1L, JobSucceeded)
)
log.setLastModified(clock.getTimeMillis())
provider.checkForLogs()
// This should not trigger any cleanup
updateAndCheck(provider) { list =>
list.size should be(1)
}
}
test("log cleaner for inProgress files") {
val firstFileModifiedTime = TimeUnit.SECONDS.toMillis(10)
val secondFileModifiedTime = TimeUnit.SECONDS.toMillis(20)
val maxAge = TimeUnit.SECONDS.toMillis(40)
val clock = new ManualClock(0)
val provider = new FsHistoryProvider(
createTestConf().set(MAX_LOG_AGE_S.key, s"${maxAge}ms"), clock)
val log1 = newLogFile("inProgressApp1", None, inProgress = true)
writeFile(log1, None,
SparkListenerApplicationStart(
"inProgressApp1", Some("inProgressApp1"), 3L, "test", Some("attempt1"))
)
clock.setTime(firstFileModifiedTime)
provider.checkForLogs()
val log2 = newLogFile("inProgressApp2", None, inProgress = true)
writeFile(log2, None,
SparkListenerApplicationStart(
"inProgressApp2", Some("inProgressApp2"), 23L, "test2", Some("attempt2"))
)
clock.setTime(secondFileModifiedTime)
provider.checkForLogs()
// This should not trigger any cleanup
updateAndCheck(provider) { list =>
list.size should be(2)
}
// Should trigger cleanup for first file but not second one
clock.setTime(firstFileModifiedTime + maxAge + 1)
updateAndCheck(provider) { list =>
list.size should be(1)
}
assert(!log1.exists())
assert(log2.exists())
// Should cleanup the second file as well.
clock.setTime(secondFileModifiedTime + maxAge + 1)
updateAndCheck(provider) { list =>
list.size should be(0)
}
assert(!log1.exists())
assert(!log2.exists())
}
test("Event log copy") {
val provider = new FsHistoryProvider(createTestConf())
val logs = (1 to 2).map { i =>
val log = newLogFile("downloadApp1", Some(s"attempt$i"), inProgress = false)
writeFile(log, None,
SparkListenerApplicationStart(
"downloadApp1", Some("downloadApp1"), 5000L * i, "test", Some(s"attempt$i")),
SparkListenerApplicationEnd(5001L * i)
)
log
}
provider.checkForLogs()
(1 to 2).foreach { i =>
val underlyingStream = new ByteArrayOutputStream()
val outputStream = new ZipOutputStream(underlyingStream)
provider.writeEventLogs("downloadApp1", Some(s"attempt$i"), outputStream)
outputStream.close()
val inputStream = new ZipInputStream(new ByteArrayInputStream(underlyingStream.toByteArray))
var totalEntries = 0
var entry = inputStream.getNextEntry
entry should not be null
while (entry != null) {
val actual = new String(ByteStreams.toByteArray(inputStream), StandardCharsets.UTF_8)
val expected =
Files.toString(logs.find(_.getName == entry.getName).get, StandardCharsets.UTF_8)
actual should be (expected)
totalEntries += 1
entry = inputStream.getNextEntry
}
totalEntries should be (1)
inputStream.close()
}
}
test("driver log cleaner") {
val firstFileModifiedTime = TimeUnit.SECONDS.toMillis(10)
val secondFileModifiedTime = TimeUnit.SECONDS.toMillis(20)
val maxAge = TimeUnit.SECONDS.toSeconds(40)
val clock = new ManualClock(0)
val testConf = new SparkConf()
testConf.set(HISTORY_LOG_DIR, Utils.createTempDir(namePrefix = "eventLog").getAbsolutePath())
testConf.set(DRIVER_LOG_DFS_DIR, testDir.getAbsolutePath())
testConf.set(DRIVER_LOG_CLEANER_ENABLED, true)
testConf.set(DRIVER_LOG_CLEANER_INTERVAL, maxAge / 4)
testConf.set(MAX_DRIVER_LOG_AGE_S, maxAge)
val provider = new FsHistoryProvider(testConf, clock)
val log1 = FileUtils.getFile(testDir, "1" + DriverLogger.DRIVER_LOG_FILE_SUFFIX)
createEmptyFile(log1)
clock.setTime(firstFileModifiedTime)
log1.setLastModified(clock.getTimeMillis())
provider.cleanDriverLogs()
val log2 = FileUtils.getFile(testDir, "2" + DriverLogger.DRIVER_LOG_FILE_SUFFIX)
createEmptyFile(log2)
val log3 = FileUtils.getFile(testDir, "3" + DriverLogger.DRIVER_LOG_FILE_SUFFIX)
createEmptyFile(log3)
clock.setTime(secondFileModifiedTime)
log2.setLastModified(clock.getTimeMillis())
log3.setLastModified(clock.getTimeMillis())
// This should not trigger any cleanup
provider.cleanDriverLogs()
provider.listing.view(classOf[LogInfo]).iterator().asScala.toSeq.size should be(3)
// Should trigger cleanup for first file but not second one
clock.setTime(firstFileModifiedTime + TimeUnit.SECONDS.toMillis(maxAge) + 1)
provider.cleanDriverLogs()
provider.listing.view(classOf[LogInfo]).iterator().asScala.toSeq.size should be(2)
assert(!log1.exists())
assert(log2.exists())
assert(log3.exists())
// Update the third file length while keeping the original modified time
Files.write("Add logs to file".getBytes(), log3)
log3.setLastModified(secondFileModifiedTime)
// Should cleanup the second file but not the third file, as filelength changed.
clock.setTime(secondFileModifiedTime + TimeUnit.SECONDS.toMillis(maxAge) + 1)
provider.cleanDriverLogs()
provider.listing.view(classOf[LogInfo]).iterator().asScala.toSeq.size should be(1)
assert(!log1.exists())
assert(!log2.exists())
assert(log3.exists())
// Should cleanup the third file as well.
clock.setTime(secondFileModifiedTime + 2 * TimeUnit.SECONDS.toMillis(maxAge) + 2)
provider.cleanDriverLogs()
provider.listing.view(classOf[LogInfo]).iterator().asScala.toSeq.size should be(0)
assert(!log3.exists())
}
test("SPARK-8372: new logs with no app ID are ignored") {
val provider = new FsHistoryProvider(createTestConf())
// Write a new log file without an app id, to make sure it's ignored.
val logFile1 = newLogFile("app1", None, inProgress = true)
writeFile(logFile1, None,
SparkListenerLogStart("1.4")
)
updateAndCheck(provider) { list =>
list.size should be (0)
}
}
test("provider correctly checks whether fs is in safe mode") {
val provider = spy(new FsHistoryProvider(createTestConf()))
val dfs = mock(classOf[DistributedFileSystem])
// Asserts that safe mode is false because we can't really control the return value of the mock,
// since the API is different between hadoop 1 and 2.
assert(!provider.isFsInSafeMode(dfs))
}
test("provider waits for safe mode to finish before initializing") {
val clock = new ManualClock()
val provider = new SafeModeTestProvider(createTestConf(), clock)
val initThread = provider.initialize()
try {
provider.getConfig().keys should contain ("HDFS State")
clock.setTime(5000)
provider.getConfig().keys should contain ("HDFS State")
provider.inSafeMode = false
clock.setTime(10000)
eventually(timeout(3.second), interval(10.milliseconds)) {
provider.getConfig().keys should not contain ("HDFS State")
}
} finally {
provider.stop()
}
}
testRetry("provider reports error after FS leaves safe mode") {
testDir.delete()
val clock = new ManualClock()
val provider = new SafeModeTestProvider(createTestConf(), clock)
val errorHandler = mock(classOf[Thread.UncaughtExceptionHandler])
provider.startSafeModeCheckThread(Some(errorHandler))
try {
provider.inSafeMode = false
clock.setTime(10000)
eventually(timeout(3.second), interval(10.milliseconds)) {
verify(errorHandler).uncaughtException(any(), any())
}
} finally {
provider.stop()
}
}
test("ignore hidden files") {
// FsHistoryProvider should ignore hidden files. (It even writes out a hidden file itself
// that should be ignored).
// write out one totally bogus hidden file
val hiddenGarbageFile = new File(testDir, ".garbage")
Utils.tryWithResource(new PrintWriter(hiddenGarbageFile)) { out =>
// scalastyle:off println
out.println("GARBAGE")
// scalastyle:on println
}
// also write out one real event log file, but since its a hidden file, we shouldn't read it
val tmpNewAppFile = newLogFile("hidden", None, inProgress = false)
val hiddenNewAppFile = new File(tmpNewAppFile.getParentFile, "." + tmpNewAppFile.getName)
tmpNewAppFile.renameTo(hiddenNewAppFile)
// and write one real file, which should still get picked up just fine
val newAppComplete = newLogFile("real-app", None, inProgress = false)
writeFile(newAppComplete, None,
SparkListenerApplicationStart(newAppComplete.getName(), Some("new-app-complete"), 1L, "test",
None),
SparkListenerApplicationEnd(5L)
)
val provider = new FsHistoryProvider(createTestConf())
updateAndCheck(provider) { list =>
list.size should be (1)
list(0).name should be ("real-app")
}
}
test("support history server ui admin acls") {
def createAndCheck(conf: SparkConf, properties: (String, String)*)
(checkFn: SecurityManager => Unit): Unit = {
// Empty the testDir for each test.
if (testDir.exists() && testDir.isDirectory) {
testDir.listFiles().foreach { f => if (f.isFile) f.delete() }
}
var provider: FsHistoryProvider = null
try {
provider = new FsHistoryProvider(conf)
val log = newLogFile("app1", Some("attempt1"), inProgress = false)
writeFile(log, None,
SparkListenerApplicationStart("app1", Some("app1"), System.currentTimeMillis(),
"test", Some("attempt1")),
SparkListenerEnvironmentUpdate(Map(
"Spark Properties" -> properties.toSeq,
"Hadoop Properties" -> Seq.empty,
"JVM Information" -> Seq.empty,
"System Properties" -> Seq.empty,
"Classpath Entries" -> Seq.empty
)),
SparkListenerApplicationEnd(System.currentTimeMillis()))
provider.checkForLogs()
val appUi = provider.getAppUI("app1", Some("attempt1"))
assert(appUi.nonEmpty)
val securityManager = appUi.get.ui.securityManager
checkFn(securityManager)
} finally {
if (provider != null) {
provider.stop()
}
}
}
// Test both history ui admin acls and application acls are configured.
val conf1 = createTestConf()
.set(HISTORY_SERVER_UI_ACLS_ENABLE, true)
.set(HISTORY_SERVER_UI_ADMIN_ACLS, Seq("user1", "user2"))
.set(HISTORY_SERVER_UI_ADMIN_ACLS_GROUPS, Seq("group1"))
.set(USER_GROUPS_MAPPING, classOf[TestGroupsMappingProvider].getName)
createAndCheck(conf1, (ADMIN_ACLS.key, "user"), (ADMIN_ACLS_GROUPS.key, "group")) {
securityManager =>
// Test whether user has permission to access UI.
securityManager.checkUIViewPermissions("user1") should be (true)
securityManager.checkUIViewPermissions("user2") should be (true)
securityManager.checkUIViewPermissions("user") should be (true)
securityManager.checkUIViewPermissions("abc") should be (false)
// Test whether user with admin group has permission to access UI.
securityManager.checkUIViewPermissions("user3") should be (true)
securityManager.checkUIViewPermissions("user4") should be (true)
securityManager.checkUIViewPermissions("user5") should be (true)
securityManager.checkUIViewPermissions("user6") should be (false)
}
// Test only history ui admin acls are configured.
val conf2 = createTestConf()
.set(HISTORY_SERVER_UI_ACLS_ENABLE, true)
.set(HISTORY_SERVER_UI_ADMIN_ACLS, Seq("user1", "user2"))
.set(HISTORY_SERVER_UI_ADMIN_ACLS_GROUPS, Seq("group1"))
.set(USER_GROUPS_MAPPING, classOf[TestGroupsMappingProvider].getName)
createAndCheck(conf2) { securityManager =>
// Test whether user has permission to access UI.
securityManager.checkUIViewPermissions("user1") should be (true)
securityManager.checkUIViewPermissions("user2") should be (true)
// Check the unknown "user" should return false
securityManager.checkUIViewPermissions("user") should be (false)
// Test whether user with admin group has permission to access UI.
securityManager.checkUIViewPermissions("user3") should be (true)
securityManager.checkUIViewPermissions("user4") should be (true)
// Check the "user5" without mapping relation should return false
securityManager.checkUIViewPermissions("user5") should be (false)
}
// Test neither history ui admin acls nor application acls are configured.
val conf3 = createTestConf()
.set(HISTORY_SERVER_UI_ACLS_ENABLE, true)
.set(USER_GROUPS_MAPPING, classOf[TestGroupsMappingProvider].getName)
createAndCheck(conf3) { securityManager =>
// Test whether user has permission to access UI.
securityManager.checkUIViewPermissions("user1") should be (false)
securityManager.checkUIViewPermissions("user2") should be (false)
securityManager.checkUIViewPermissions("user") should be (false)
// Test whether user with admin group has permission to access UI.
// Check should be failed since we don't have acl group settings.
securityManager.checkUIViewPermissions("user3") should be (false)
securityManager.checkUIViewPermissions("user4") should be (false)
securityManager.checkUIViewPermissions("user5") should be (false)
}
}
test("mismatched version discards old listing") {
val conf = createTestConf()
val oldProvider = new FsHistoryProvider(conf)
val logFile1 = newLogFile("app1", None, inProgress = false)
writeFile(logFile1, None,
SparkListenerLogStart("2.3"),
SparkListenerApplicationStart("test", Some("test"), 1L, "test", None),
SparkListenerApplicationEnd(5L)
)
updateAndCheck(oldProvider) { list =>
list.size should be (1)
}
assert(oldProvider.listing.count(classOf[ApplicationInfoWrapper]) === 1)
// Manually overwrite the version in the listing db; this should cause the new provider to
// discard all data because the versions don't match.
val meta = new FsHistoryProviderMetadata(FsHistoryProvider.CURRENT_LISTING_VERSION + 1,
AppStatusStore.CURRENT_VERSION, conf.get(LOCAL_STORE_DIR).get)
oldProvider.listing.setMetadata(meta)
oldProvider.stop()
val mistatchedVersionProvider = new FsHistoryProvider(conf)
assert(mistatchedVersionProvider.listing.count(classOf[ApplicationInfoWrapper]) === 0)
}
test("invalidate cached UI") {
val provider = new FsHistoryProvider(createTestConf())
val appId = "new1"
// Write an incomplete app log.
val appLog = newLogFile(appId, None, inProgress = true)
writeFile(appLog, None,
SparkListenerApplicationStart(appId, Some(appId), 1L, "test", None)
)
provider.checkForLogs()
// Load the app UI.
val oldUI = provider.getAppUI(appId, None)
assert(oldUI.isDefined)
intercept[NoSuchElementException] {
oldUI.get.ui.store.job(0)
}
// Add more info to the app log, and trigger the provider to update things.
writeFile(appLog, None,
SparkListenerApplicationStart(appId, Some(appId), 1L, "test", None),
SparkListenerJobStart(0, 1L, Nil, null)
)
provider.checkForLogs()
// Manually detach the old UI; ApplicationCache would do this automatically in a real SHS
// when the app's UI was requested.
provider.onUIDetached(appId, None, oldUI.get.ui)
// Load the UI again and make sure we can get the new info added to the logs.
val freshUI = provider.getAppUI(appId, None)
assert(freshUI.isDefined)
assert(freshUI != oldUI)
freshUI.get.ui.store.job(0)
}
test("clean up stale app information") {
withTempDir { storeDir =>
val conf = createTestConf().set(LOCAL_STORE_DIR, storeDir.getAbsolutePath())
val clock = new ManualClock()
val provider = spy(new FsHistoryProvider(conf, clock))
val appId = "new1"
// Write logs for two app attempts.
clock.advance(1)
val attempt1 = newLogFile(appId, Some("1"), inProgress = false)
writeFile(attempt1, None,
SparkListenerApplicationStart(appId, Some(appId), 1L, "test", Some("1")),
SparkListenerJobStart(0, 1L, Nil, null),
SparkListenerApplicationEnd(5L)
)
val attempt2 = newLogFile(appId, Some("2"), inProgress = false)
writeFile(attempt2, None,
SparkListenerApplicationStart(appId, Some(appId), 1L, "test", Some("2")),
SparkListenerJobStart(0, 1L, Nil, null),
SparkListenerApplicationEnd(5L)
)
updateAndCheck(provider) { list =>
assert(list.size === 1)
assert(list(0).id === appId)
assert(list(0).attempts.size === 2)
}
// Load the app's UI.
val ui = provider.getAppUI(appId, Some("1"))
assert(ui.isDefined)
// Delete the underlying log file for attempt 1 and rescan. The UI should go away, but since
// attempt 2 still exists, listing data should be there.
clock.advance(1)
attempt1.delete()
updateAndCheck(provider) { list =>
assert(list.size === 1)
assert(list(0).id === appId)
assert(list(0).attempts.size === 1)
}
assert(!ui.get.valid)
assert(provider.getAppUI(appId, None) === None)
// Delete the second attempt's log file. Now everything should go away.
clock.advance(1)
attempt2.delete()
updateAndCheck(provider) { list =>
assert(list.isEmpty)
}
}
}
test("SPARK-21571: clean up removes invalid history files") {
val clock = new ManualClock()
val conf = createTestConf().set(MAX_LOG_AGE_S.key, s"2d")
val provider = new FsHistoryProvider(conf, clock)
// Create 0-byte size inprogress and complete files
var logCount = 0
var validLogCount = 0
val emptyInProgress = newLogFile("emptyInprogressLogFile", None, inProgress = true)
emptyInProgress.createNewFile()
emptyInProgress.setLastModified(clock.getTimeMillis())
logCount += 1
val slowApp = newLogFile("slowApp", None, inProgress = true)
slowApp.createNewFile()
slowApp.setLastModified(clock.getTimeMillis())
logCount += 1
val emptyFinished = newLogFile("emptyFinishedLogFile", None, inProgress = false)
emptyFinished.createNewFile()
emptyFinished.setLastModified(clock.getTimeMillis())
logCount += 1
// Create an incomplete log file, has an end record but no start record.
val corrupt = newLogFile("nonEmptyCorruptLogFile", None, inProgress = false)
writeFile(corrupt, None, SparkListenerApplicationEnd(0))
corrupt.setLastModified(clock.getTimeMillis())
logCount += 1
provider.checkForLogs()
provider.cleanLogs()
assert(new File(testDir.toURI).listFiles().size === logCount)
// Move the clock forward 1 day and scan the files again. They should still be there.
clock.advance(TimeUnit.DAYS.toMillis(1))
provider.checkForLogs()
provider.cleanLogs()
assert(new File(testDir.toURI).listFiles().size === logCount)
// Update the slow app to contain valid info. Code should detect the change and not clean
// it up.
writeFile(slowApp, None,
SparkListenerApplicationStart(slowApp.getName(), Some(slowApp.getName()), 1L, "test", None))
slowApp.setLastModified(clock.getTimeMillis())
validLogCount += 1
// Move the clock forward another 2 days and scan the files again. This time the cleaner should
// pick up the invalid files and get rid of them.
clock.advance(TimeUnit.DAYS.toMillis(2))
provider.checkForLogs()
provider.cleanLogs()
assert(new File(testDir.toURI).listFiles().size === validLogCount)
}
test("always find end event for finished apps") {
// Create a log file where the end event is before the configure chunk to be reparsed at
// the end of the file. The correct listing should still be generated.
val log = newLogFile("end-event-test", None, inProgress = false)
writeFile(log, None,
Seq(
SparkListenerApplicationStart("end-event-test", Some("end-event-test"), 1L, "test", None),
SparkListenerEnvironmentUpdate(Map(
"Spark Properties" -> Seq.empty,
"Hadoop Properties" -> Seq.empty,
"JVM Information" -> Seq.empty,
"System Properties" -> Seq.empty,
"Classpath Entries" -> Seq.empty
)),
SparkListenerApplicationEnd(5L)
) ++ (1 to 1000).map { i => SparkListenerJobStart(i, i, Nil) }: _*)
val conf = createTestConf().set(END_EVENT_REPARSE_CHUNK_SIZE.key, s"1k")
val provider = new FsHistoryProvider(conf)
updateAndCheck(provider) { list =>
assert(list.size === 1)
assert(list(0).attempts.size === 1)
assert(list(0).attempts(0).completed)
}
}
test("parse event logs with optimizations off") {
val conf = createTestConf()
.set(END_EVENT_REPARSE_CHUNK_SIZE, 0L)
.set(FAST_IN_PROGRESS_PARSING, false)
val provider = new FsHistoryProvider(conf)
val complete = newLogFile("complete", None, inProgress = false)
writeFile(complete, None,
SparkListenerApplicationStart("complete", Some("complete"), 1L, "test", None),
SparkListenerApplicationEnd(5L)
)
val incomplete = newLogFile("incomplete", None, inProgress = true)
writeFile(incomplete, None,
SparkListenerApplicationStart("incomplete", Some("incomplete"), 1L, "test", None)
)
updateAndCheck(provider) { list =>
list.size should be (2)
list.count(_.attempts.head.completed) should be (1)
}
}
test("SPARK-24948: blacklist files we don't have read permission on") {
val clock = new ManualClock(1533132471)
val provider = new FsHistoryProvider(createTestConf(), clock)
val accessDenied = newLogFile("accessDenied", None, inProgress = false)
writeFile(accessDenied, None,
SparkListenerApplicationStart("accessDenied", Some("accessDenied"), 1L, "test", None))
val accessGranted = newLogFile("accessGranted", None, inProgress = false)
writeFile(accessGranted, None,
SparkListenerApplicationStart("accessGranted", Some("accessGranted"), 1L, "test", None),
SparkListenerApplicationEnd(5L))
var isReadable = false
val mockedFs = spy(provider.fs)
doThrow(new AccessControlException("Cannot read accessDenied file")).when(mockedFs).open(
argThat((path: Path) => path.getName.toLowerCase(Locale.ROOT) == "accessdenied" &&
!isReadable))
val mockedProvider = spy(provider)
when(mockedProvider.fs).thenReturn(mockedFs)
updateAndCheck(mockedProvider) { list =>
list.size should be(1)
}
// Doing 2 times in order to check the blacklist filter too
updateAndCheck(mockedProvider) { list =>
list.size should be(1)
}
val accessDeniedPath = new Path(accessDenied.getPath)
assert(mockedProvider.isBlacklisted(accessDeniedPath))
clock.advance(24 * 60 * 60 * 1000 + 1) // add a bit more than 1d
isReadable = true
mockedProvider.cleanLogs()
updateAndCheck(mockedProvider) { list =>
assert(!mockedProvider.isBlacklisted(accessDeniedPath))
assert(list.exists(_.name == "accessDenied"))
assert(list.exists(_.name == "accessGranted"))
list.size should be(2)
}
}
test("check in-progress event logs absolute length") {
val path = new Path("testapp.inprogress")
val provider = new FsHistoryProvider(createTestConf())
val mockedProvider = spy(provider)
val mockedFs = mock(classOf[FileSystem])
val in = mock(classOf[FSDataInputStream])
val dfsIn = mock(classOf[DFSInputStream])
when(mockedProvider.fs).thenReturn(mockedFs)
when(mockedFs.open(path)).thenReturn(in)
when(in.getWrappedStream).thenReturn(dfsIn)
when(dfsIn.getFileLength).thenReturn(200)
// FileStatus.getLen is more than logInfo fileSize
var fileStatus = new FileStatus(200, false, 0, 0, 0, path)
when(mockedFs.getFileStatus(path)).thenReturn(fileStatus)
var logInfo = new LogInfo(path.toString, 0, LogType.EventLogs, Some("appId"),
Some("attemptId"), 100, None, false)
var reader = EventLogFileReader(mockedFs, path)
assert(reader.isDefined)
assert(mockedProvider.shouldReloadLog(logInfo, reader.get))
fileStatus = new FileStatus()
fileStatus.setPath(path)
when(mockedFs.getFileStatus(path)).thenReturn(fileStatus)
// DFSInputStream.getFileLength is more than logInfo fileSize
logInfo = new LogInfo(path.toString, 0, LogType.EventLogs, Some("appId"),
Some("attemptId"), 100, None, false)
reader = EventLogFileReader(mockedFs, path)
assert(reader.isDefined)
assert(mockedProvider.shouldReloadLog(logInfo, reader.get))
// DFSInputStream.getFileLength is equal to logInfo fileSize
logInfo = new LogInfo(path.toString, 0, LogType.EventLogs, Some("appId"),
Some("attemptId"), 200, None, false)
reader = EventLogFileReader(mockedFs, path)
assert(reader.isDefined)
assert(!mockedProvider.shouldReloadLog(logInfo, reader.get))
// in.getWrappedStream returns other than DFSInputStream
val bin = mock(classOf[BufferedInputStream])
when(in.getWrappedStream).thenReturn(bin)
reader = EventLogFileReader(mockedFs, path)
assert(reader.isDefined)
assert(!mockedProvider.shouldReloadLog(logInfo, reader.get))
// fs.open throws exception
when(mockedFs.open(path)).thenThrow(new IOException("Throwing intentionally"))
reader = EventLogFileReader(mockedFs, path)
assert(reader.isDefined)
assert(!mockedProvider.shouldReloadLog(logInfo, reader.get))
}
test("log cleaner with the maximum number of log files") {
val clock = new ManualClock(0)
(5 to 0 by -1).foreach { num =>
val log1_1 = newLogFile("app1", Some("attempt1"), inProgress = false)
writeFile(log1_1, None,
SparkListenerApplicationStart("app1", Some("app1"), 1L, "test", Some("attempt1")),
SparkListenerApplicationEnd(2L)
)
log1_1.setLastModified(2L)
val log2_1 = newLogFile("app2", Some("attempt1"), inProgress = false)
writeFile(log2_1, None,
SparkListenerApplicationStart("app2", Some("app2"), 3L, "test", Some("attempt1")),
SparkListenerApplicationEnd(4L)
)
log2_1.setLastModified(4L)
val log3_1 = newLogFile("app3", Some("attempt1"), inProgress = false)
writeFile(log3_1, None,
SparkListenerApplicationStart("app3", Some("app3"), 5L, "test", Some("attempt1")),
SparkListenerApplicationEnd(6L)
)
log3_1.setLastModified(6L)
val log1_2_incomplete = newLogFile("app1", Some("attempt2"), inProgress = false)
writeFile(log1_2_incomplete, None,
SparkListenerApplicationStart("app1", Some("app1"), 7L, "test", Some("attempt2"))
)
log1_2_incomplete.setLastModified(8L)
val log3_2 = newLogFile("app3", Some("attempt2"), inProgress = false)
writeFile(log3_2, None,
SparkListenerApplicationStart("app3", Some("app3"), 9L, "test", Some("attempt2")),
SparkListenerApplicationEnd(10L)
)
log3_2.setLastModified(10L)
val provider = new FsHistoryProvider(createTestConf().set(MAX_LOG_NUM.key, s"$num"), clock)
updateAndCheck(provider) { list =>
assert(log1_1.exists() == (num > 4))
assert(log1_2_incomplete.exists()) // Always exists for all configurations
assert(log2_1.exists() == (num > 3))
assert(log3_1.exists() == (num > 2))
assert(log3_2.exists() == (num > 2))
}
}
}
test("backwards compatibility with LogInfo from Spark 2.4") {
case class LogInfoV24(
logPath: String,
lastProcessed: Long,
appId: Option[String],
attemptId: Option[String],
fileSize: Long)
val oldObj = LogInfoV24("dummy", System.currentTimeMillis(), Some("hello"),
Some("attempt1"), 100)
val serializer = new KVStoreScalaSerializer()
val serializedOldObj = serializer.serialize(oldObj)
val deserializedOldObj = serializer.deserialize(serializedOldObj, classOf[LogInfo])
assert(deserializedOldObj.logPath === oldObj.logPath)
assert(deserializedOldObj.lastProcessed === oldObj.lastProcessed)
assert(deserializedOldObj.appId === oldObj.appId)
assert(deserializedOldObj.attemptId === oldObj.attemptId)
assert(deserializedOldObj.fileSize === oldObj.fileSize)
// SPARK-25118: added logType: LogType.Value - expected 'null' on old format
assert(deserializedOldObj.logType === null)
// SPARK-28869: added lastIndex: Option[Long], isComplete: Boolean - expected 'None' and
// 'false' on old format. The default value for isComplete is wrong value for completed app,
// but the value will be corrected once checkForLogs is called.
assert(deserializedOldObj.lastIndex === None)
assert(deserializedOldObj.isComplete === false)
}
test("SPARK-29755 LogInfo should be serialized/deserialized by jackson properly") {
def assertSerDe(serializer: KVStoreScalaSerializer, info: LogInfo): Unit = {
val infoAfterSerDe = serializer.deserialize(serializer.serialize(info), classOf[LogInfo])
assert(infoAfterSerDe === info)
assertOptionAfterSerde(infoAfterSerDe.lastIndex, info.lastIndex)
}
val serializer = new KVStoreScalaSerializer()
val logInfoWithIndexAsNone = LogInfo("dummy", 0, LogType.EventLogs, Some("appId"),
Some("attemptId"), 100, None, false)
assertSerDe(serializer, logInfoWithIndexAsNone)
val logInfoWithIndex = LogInfo("dummy", 0, LogType.EventLogs, Some("appId"),
Some("attemptId"), 100, Some(3), false)
assertSerDe(serializer, logInfoWithIndex)
}
test("SPARK-29755 AttemptInfoWrapper should be serialized/deserialized by jackson properly") {
def assertSerDe(serializer: KVStoreScalaSerializer, attempt: AttemptInfoWrapper): Unit = {
val attemptAfterSerDe = serializer.deserialize(serializer.serialize(attempt),
classOf[AttemptInfoWrapper])
assert(attemptAfterSerDe.info === attempt.info)
// skip comparing some fields, as they've not triggered SPARK-29755
assertOptionAfterSerde(attemptAfterSerDe.lastIndex, attempt.lastIndex)
}
val serializer = new KVStoreScalaSerializer()
val appInfo = new ApplicationAttemptInfo(None, new Date(1), new Date(1), new Date(1),
10, "spark", false, "dummy")
val attemptInfoWithIndexAsNone = new AttemptInfoWrapper(appInfo, "dummyPath", 10, None,
None, None, None, None)
assertSerDe(serializer, attemptInfoWithIndexAsNone)
val attemptInfoWithIndex = new AttemptInfoWrapper(appInfo, "dummyPath", 10, Some(1),
None, None, None, None)
assertSerDe(serializer, attemptInfoWithIndex)
}
private def assertOptionAfterSerde(opt: Option[Long], expected: Option[Long]): Unit = {
if (expected.isEmpty) {
assert(opt.isEmpty)
} else {
// The issue happens only when the value in Option is being unboxed. Here we ensure unboxing
// to Long succeeds: even though IDE suggests `.toLong` is redundant, direct comparison
// doesn't trigger unboxing and passes even without SPARK-29755, so don't remove
// `.toLong` below. Please refer SPARK-29755 for more details.
assert(opt.get.toLong === expected.get.toLong)
}
}
/**
* Asks the provider to check for logs and calls a function to perform checks on the updated
* app list. Example:
*
* updateAndCheck(provider) { list =>
* // asserts
* }
*/
private def updateAndCheck(provider: FsHistoryProvider)
(checkFn: Seq[ApplicationInfo] => Unit): Unit = {
provider.checkForLogs()
provider.cleanLogs()
checkFn(provider.getListing().toSeq)
}
private def writeFile(file: File, codec: Option[CompressionCodec],
events: SparkListenerEvent*) = {
val fstream = new FileOutputStream(file)
val cstream = codec.map(_.compressedContinuousOutputStream(fstream)).getOrElse(fstream)
val bstream = new BufferedOutputStream(cstream)
val metadata = SparkListenerLogStart(org.apache.spark.SPARK_VERSION)
val eventJson = JsonProtocol.logStartToJson(metadata)
val metadataJson = compact(eventJson) + "\\n"
bstream.write(metadataJson.getBytes(StandardCharsets.UTF_8))
val writer = new OutputStreamWriter(bstream, StandardCharsets.UTF_8)
Utils.tryWithSafeFinally {
events.foreach(e => writer.write(compact(render(JsonProtocol.sparkEventToJson(e))) + "\\n"))
} {
writer.close()
}
}
private def createEmptyFile(file: File) = {
new FileOutputStream(file).close()
}
private def createTestConf(inMemory: Boolean = false): SparkConf = {
val conf = new SparkConf()
.set(HISTORY_LOG_DIR, testDir.getAbsolutePath())
.set(FAST_IN_PROGRESS_PARSING, true)
if (!inMemory) {
conf.set(LOCAL_STORE_DIR, Utils.createTempDir().getAbsolutePath())
}
conf
}
private def createTestExecutorInfo(
appId: String,
user: String,
executorSeqNum: Int,
includingLogFiles: Boolean = true): ExecutorInfo = {
val host = s"host$executorSeqNum"
val container = s"container$executorSeqNum"
val cluster = s"cluster$executorSeqNum"
val logUrlPrefix = s"http://$host:8888/$appId/$container/origin"
val executorLogUrlMap = Map("stdout" -> s"$logUrlPrefix/stdout",
"stderr" -> s"$logUrlPrefix/stderr")
val extraAttributes = if (includingLogFiles) Map("LOG_FILES" -> "stdout,stderr") else Map.empty
val executorAttributes = Map("CONTAINER_ID" -> container, "CLUSTER_ID" -> cluster,
"USER" -> user) ++ extraAttributes
new ExecutorInfo(host, 1, executorLogUrlMap, executorAttributes)
}
private class SafeModeTestProvider(conf: SparkConf, clock: Clock)
extends FsHistoryProvider(conf, clock) {
@volatile var inSafeMode = true
// Skip initialization so that we can manually start the safe mode check thread.
private[history] override def initialize(): Thread = null
private[history] override def isFsInSafeMode(): Boolean = inSafeMode
}
}
class TestGroupsMappingProvider extends GroupMappingServiceProvider {
private val mappings = Map(
"user3" -> "group1",
"user4" -> "group1",
"user5" -> "group")
override def getGroups(username: String): Set[String] = {
mappings.get(username).map(Set(_)).getOrElse(Set.empty)
}
}
|
caneGuy/spark
|
core/src/test/scala/org/apache/spark/deploy/history/FsHistoryProviderSuite.scala
|
Scala
|
apache-2.0
| 54,959 |
/*
* Copyright (c) 2013 Scott Abernethy.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import db._
import play.api.{Play, Application, GlobalSettings, Logger}
import play.api.Play.current
import model.Environment
object Global extends GlobalSettings {
var db: Option[Db] = None
override def beforeStart(app: Application) {
super.beforeStart(app)
Logger.info("*It* is coming...")
}
override def onStart(app: Application) {
super.onStart(app)
val data = if (Play.isTest) {
new TestDb
}
else {
new Db{}
}
data.init
if (Play.isDev || Play.isTest) {
data.clear
data.populate
}
db = Some(data)
Environment.start
Logger.info("*It* is here")
}
override def onStop(app: Application) {
super.onStop(app)
Logger.info("*It* has gone")
Environment.dispose
db.foreach{_.close}
db = None
}
}
|
scott-abernethy/opener-of-the-way
|
app/Global.scala
|
Scala
|
gpl-3.0
| 1,512 |
package com.socrata.querycoordinator
import java.util.concurrent.TimeUnit
import com.socrata.http.server.livenesscheck.LivenessCheckConfig
import com.socrata.curator.{CuratorConfig, DiscoveryConfig}
import com.socrata.querycoordinator.caching.cache.config.CacheConfig
import com.socrata.thirdparty.metrics.MetricsOptions
import com.socrata.thirdparty.typesafeconfig.ConfigClass
import com.typesafe.config.Config
import scala.concurrent.duration._
class QueryCoordinatorConfig(config: Config, root: String)
extends ConfigClass(config, root) with SecondarySelectorConfig {
val log4j = getRawConfig("log4j")
val curator = new CuratorConfig(config, path("curator"))
val discovery = new DiscoveryConfig(config, path("service-advertisement"))
val livenessCheck = new LivenessCheckConfig(config, path("liveness-check"))
val network = new NetworkConfig(config, path("network"))
val metrics = MetricsOptions(config.getConfig(path("metrics")))
val connectTimeout = config.getDuration(path("connect-timeout"), TimeUnit.MILLISECONDS).millis
val schemaTimeout = config.getDuration(path("get-schema-timeout"), TimeUnit.MILLISECONDS).millis
val receiveTimeout = config.getDuration(path("query-timeout"), TimeUnit.MILLISECONDS).millis // http query (not db query)
val maxDbQueryTimeout = config.getDuration(path("max-db-query-timeout"), TimeUnit.MILLISECONDS).millis
val maxRows = optionally(getInt("max-rows"))
val defaultRowsLimit = getInt("default-rows-limit")
val cache = getConfig("cache", new CacheConfig(_, _))
val threadpool = getRawConfig("threadpool")
}
|
socrata-platform/query-coordinator
|
query-coordinator/src/main/scala/com/socrata/querycoordinator/QueryCoordinatorConfig.scala
|
Scala
|
apache-2.0
| 1,585 |
package peregin.gpv.model
import org.specs2.mutable.Specification
import MinMax._
class MinMaxSpec extends Specification {
stopOnFail
"an instance" should {
val mm = MinMax(0, 3)
"match if value is inside the range" in {
mm.includes(-0.1) must beFalse
mm.includes(0) must beTrue
mm.includes(1.2) must beTrue
mm.includes(2.99) must beTrue
mm.includes(3) must beFalse
mm.includes(32) must beFalse
}
}
"rounder" should {
"round up to nearest tenth" in {
27.2.roundUpToTenth === 30
21.5.roundUpToTenth === 30
30.roundUpToTenth === 30
0.roundUpToTenth === 0
-11.roundUpToTenth === -10
}
"round down to nearest tenth" in {
27.2.roundDownToTenth === 20
21.5.roundDownToTenth === 20
30.roundDownToTenth === 30
0.roundDownToTenth === 0
-11.roundDownToTenth === -20
}
"round up to nearest hundredth" in {
27.2.roundUpToHundredth === 100
210.5.roundUpToHundredth === 300
301.roundUpToHundredth === 400
0.roundUpToHundredth === 0
-11.roundUpToHundredth === 0
}
"round down to nearest hundredth" in {
210.5.roundDownToHundredth === 200
301.roundDownToHundredth === 300
0.roundDownToHundredth === 0
-11.roundDownToHundredth === -100
}
}
}
|
peregin/gps-overlay-on-video
|
src/test/scala/peregin/gpv/model/MinMaxSpec.scala
|
Scala
|
mit
| 1,345 |
package org.gentoo.jenport
case class D(atom: String, groupId: String, artifactId: String, mversion: String)
|
gentoo/jenport
|
src/main/scala/org/gentoo/jenport/D.scala
|
Scala
|
bsd-3-clause
| 111 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.execution.bucketing
import org.apache.spark.sql.catalyst.catalog.BucketSpec
import org.apache.spark.sql.catalyst.expressions.Expression
import org.apache.spark.sql.catalyst.plans.physical.{HashPartitioning, Partitioning}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.execution.{FileSourceScanExec, FilterExec, ProjectExec, SparkPlan}
import org.apache.spark.sql.execution.joins.SortMergeJoinExec
import org.apache.spark.sql.internal.SQLConf
/**
* This rule coalesces one side of the `SortMergeJoin` if the following conditions are met:
* - Two bucketed tables are joined.
* - Join keys match with output partition expressions on their respective sides.
* - The larger bucket number is divisible by the smaller bucket number.
* - COALESCE_BUCKETS_IN_SORT_MERGE_JOIN_ENABLED is set to true.
* - The ratio of the number of buckets is less than the value set in
* COALESCE_BUCKETS_IN_SORT_MERGE_JOIN_MAX_BUCKET_RATIO.
*/
case class CoalesceBucketsInSortMergeJoin(conf: SQLConf) extends Rule[SparkPlan] {
private def mayCoalesce(numBuckets1: Int, numBuckets2: Int, conf: SQLConf): Option[Int] = {
assert(numBuckets1 != numBuckets2)
val (small, large) = (math.min(numBuckets1, numBuckets2), math.max(numBuckets1, numBuckets2))
// A bucket can be coalesced only if the bigger number of buckets is divisible by the smaller
// number of buckets because bucket id is calculated by modding the total number of buckets.
if (large % small == 0 &&
large / small <= conf.getConf(SQLConf.COALESCE_BUCKETS_IN_SORT_MERGE_JOIN_MAX_BUCKET_RATIO)) {
Some(small)
} else {
None
}
}
private def updateNumCoalescedBuckets(plan: SparkPlan, numCoalescedBuckets: Int): SparkPlan = {
plan.transformUp {
case f: FileSourceScanExec =>
f.copy(optionalNumCoalescedBuckets = Some(numCoalescedBuckets))
}
}
def apply(plan: SparkPlan): SparkPlan = {
if (!conf.getConf(SQLConf.COALESCE_BUCKETS_IN_SORT_MERGE_JOIN_ENABLED)) {
return plan
}
plan transform {
case ExtractSortMergeJoinWithBuckets(smj, numLeftBuckets, numRightBuckets)
if numLeftBuckets != numRightBuckets =>
mayCoalesce(numLeftBuckets, numRightBuckets, conf).map { numCoalescedBuckets =>
if (numCoalescedBuckets != numLeftBuckets) {
smj.copy(left = updateNumCoalescedBuckets(smj.left, numCoalescedBuckets))
} else {
smj.copy(right = updateNumCoalescedBuckets(smj.right, numCoalescedBuckets))
}
}.getOrElse(smj)
case other => other
}
}
}
/**
* An extractor that extracts `SortMergeJoinExec` where both sides of the join have the bucketed
* tables and are consisted of only the scan operation.
*/
object ExtractSortMergeJoinWithBuckets {
private def isScanOperation(plan: SparkPlan): Boolean = plan match {
case f: FilterExec => isScanOperation(f.child)
case p: ProjectExec => isScanOperation(p.child)
case _: FileSourceScanExec => true
case _ => false
}
private def getBucketSpec(plan: SparkPlan): Option[BucketSpec] = {
plan.collectFirst {
case f: FileSourceScanExec if f.relation.bucketSpec.nonEmpty &&
f.optionalNumCoalescedBuckets.isEmpty =>
f.relation.bucketSpec.get
}
}
/**
* The join keys should match with expressions for output partitioning. Note that
* the ordering does not matter because it will be handled in `EnsureRequirements`.
*/
private def satisfiesOutputPartitioning(
keys: Seq[Expression],
partitioning: Partitioning): Boolean = {
partitioning match {
case HashPartitioning(exprs, _) if exprs.length == keys.length =>
exprs.forall(e => keys.exists(_.semanticEquals(e)))
case _ => false
}
}
private def isApplicable(s: SortMergeJoinExec): Boolean = {
isScanOperation(s.left) &&
isScanOperation(s.right) &&
satisfiesOutputPartitioning(s.leftKeys, s.left.outputPartitioning) &&
satisfiesOutputPartitioning(s.rightKeys, s.right.outputPartitioning)
}
def unapply(plan: SparkPlan): Option[(SortMergeJoinExec, Int, Int)] = {
plan match {
case s: SortMergeJoinExec if isApplicable(s) =>
val leftBucket = getBucketSpec(s.left)
val rightBucket = getBucketSpec(s.right)
if (leftBucket.isDefined && rightBucket.isDefined) {
Some(s, leftBucket.get.numBuckets, rightBucket.get.numBuckets)
} else {
None
}
case _ => None
}
}
}
|
spark-test/spark
|
sql/core/src/main/scala/org/apache/spark/sql/execution/bucketing/CoalesceBucketsInSortMergeJoin.scala
|
Scala
|
apache-2.0
| 5,367 |
trait Contravariant[F[_]] {
def contramap[A, B](f: B => A)(fa: F[A]): F[B]
}
|
hmemcpy/milewski-ctfp-pdf
|
src/content/1.8/code/scala/snippet25.scala
|
Scala
|
gpl-3.0
| 78 |
/*
* Copyright DataGenerator Contributors
*
* 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.finra.datagenerator.common.Graph
import org.finra.datagenerator.common.NodeData.DisplayableData
import scala.beans.BeanProperty
/**
* Describes the creation of a link between one node and another existing node as its parent
* @param childNodeIndex Child node index
* @param parentNodeIndex Parent node index
* @tparam T Type of node data
*/
class AddParentToExistingNodeDescription[+T <: DisplayableData](@BeanProperty val childNodeIndex: Int, @BeanProperty val parentNodeIndex: Int)
extends EdgeCreationDescription[T]
|
mibrahim/DataGenerator
|
dg-common/src/main/scala/org/finra/datagenerator/common/Graph/AddParentToExistingNodeDescription.scala
|
Scala
|
apache-2.0
| 1,148 |
/**
* Copyright (C) 2015-2016 DANS - Data Archiving and Networked Services ([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 nl.knaw.dans.easy.stage.fileitem
object EasyItemContainerMd {
def apply(path: String): String = {
<icmd:item-container-md xmlns:icmd="http://easy.dans.knaw.nl/easy/item-container-md/" version="0.1">
<name>{path.split("/").last}</name>
<path>{path}</path>
</icmd:item-container-md>.toString()
}
}
|
PaulBoon/easy-stage-dataset
|
src/main/scala/nl/knaw/dans/easy/stage/fileitem/EasyItemContainerMd.scala
|
Scala
|
apache-2.0
| 992 |
/*
* Copyright 2012-2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.edda
case class RequestId(id: String = Utils.uuid) {
override def toString = "[" + id + "] "
}
|
Netflix/edda
|
src/main/scala/com/netflix/edda/RequestId.scala
|
Scala
|
apache-2.0
| 720 |
package implementationVoteSimple
import Gvote.SystemGeneralDecomptage
import Gvote.Eligible
import GUIAbstractComponent.GUIComponentCST
import Gvote.Candidat
import Gvote.AbstractElecteur
abstract class SystemeDecomptageSimple(_election : Election , _nom : String) extends SystemGeneralDecomptage(_nom){
type ImplElection = Election
type ImplElecteur = Electeur
type ImplVote = Vote
type Candidate = Candidat
var GUIType = GUIComponentCST.radio
override protected val election = _election
def ajouterCandidat(candidat : Eligible) : Boolean = {
candidat match{
case cand : Candidat => return election.addCandidat(cand)
}
return false
}
protected def ajouterVoteByGUIElecteur(electeur : Electeur, candidats : List[(Int,Eligible)]*):Boolean = {
candidats.apply(0) match{
case candidat : List[(Int,Candidat)] =>
if(candidat.length == 1){
return electeur.voter(this, candidat.apply(0)._2)
}
}
return false
}
}
|
DoumbiaAmadou/FrameworkVote
|
src/implementationVoteSimple/SystemeDecomptageSimple.scala
|
Scala
|
mit
| 1,078 |
package com.twitter.io
import java.lang.{Double => JDouble, Float => JFloat}
import java.nio.charset.StandardCharsets
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks
import org.scalatest.funsuite.AnyFunSuite
final class BufByteWriterTest extends AnyFunSuite with ScalaCheckDrivenPropertyChecks {
import ByteWriter.OverflowException
private[this] def assertIndex(bw: ByteWriter, index: Int): Unit = bw match {
case bw: AbstractBufByteWriterImpl => assert(bw.index == index)
case other => fail(s"Unexpected ByteWriter representation: $other")
}
def testWriteString(name: String, bwFactory: Int => BufByteWriter, overflowOK: Boolean): Unit = {
test(s"$name: writeString")(forAll { (str1: String, str2: String) =>
val byteCount1 = str1.getBytes(StandardCharsets.UTF_8).length
val byteCount2 = str2.getBytes(StandardCharsets.UTF_8).length
val bw = bwFactory(byteCount1 + byteCount2)
val buf =
bw.writeString(str1, StandardCharsets.UTF_8)
.writeString(str2, StandardCharsets.UTF_8)
.owned()
if (!overflowOK) intercept[OverflowException] { bw.writeByte(0xff) }
val result = Buf.Utf8.unapply(buf)
assert(result == Some(str1 + str2))
assertIndex(bw, byteCount1 + byteCount2)
})
}
def testWriteByte(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit =
test(s"$name: writeByte")(forAll { (byte: Byte) =>
val bw = bwFactory()
val buf = bw.writeByte(byte).owned()
if (!overflowOK) intercept[OverflowException] { bw.writeByte(byte) }
assert(buf == Buf.ByteArray.Owned(Array(byte)))
})
def testWriteShort(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit =
test(s"$name: writeShort{BE,LE}")(forAll { (s: Short) =>
val be = bwFactory().writeShortBE(s)
val le = bwFactory().writeShortLE(s)
if (!overflowOK) {
intercept[OverflowException] { be.writeByte(0xff) }
intercept[OverflowException] { be.writeByte(0xff) }
}
val arr = Array[Byte](
((s >> 8) & 0xff).toByte,
((s) & 0xff).toByte
)
assert(be.owned() == Buf.ByteArray.Owned(arr))
assert(le.owned() == Buf.ByteArray.Owned(arr.reverse))
assertIndex(be, 2)
assertIndex(le, 2)
})
def testWriteMedium(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit =
test(s"$name: writeMedium{BE,LE}")(forAll { (m: Int) =>
val be = bwFactory().writeMediumBE(m)
val le = bwFactory().writeMediumLE(m)
if (!overflowOK) {
intercept[OverflowException] { be.writeByte(0xff) }
intercept[OverflowException] { be.writeByte(0xff) }
}
val arr = Array[Byte](
((m >> 16) & 0xff).toByte,
((m >> 8) & 0xff).toByte,
((m) & 0xff).toByte
)
assert(be.owned() == Buf.ByteArray.Owned(arr))
assert(le.owned() == Buf.ByteArray.Owned(arr.reverse))
assertIndex(be, 3)
assertIndex(le, 3)
})
def testWriteInt(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit =
test(s"$name: writeInt{BE,LE}")(forAll { (i: Int) =>
val be = bwFactory().writeIntBE(i)
val le = bwFactory().writeIntLE(i)
if (!overflowOK) {
intercept[OverflowException] { be.writeByte(0xff) }
intercept[OverflowException] { be.writeByte(0xff) }
}
val arr = Array[Byte](
((i >> 24) & 0xff).toByte,
((i >> 16) & 0xff).toByte,
((i >> 8) & 0xff).toByte,
((i) & 0xff).toByte
)
assert(be.owned() == Buf.ByteArray.Owned(arr))
assert(le.owned() == Buf.ByteArray.Owned(arr.reverse))
assertIndex(be, 4)
assertIndex(le, 4)
})
def testWriteLong(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit =
test(s"$name: writeLong{BE,LE}")(forAll { (l: Long) =>
val be = bwFactory().writeLongBE(l)
val le = bwFactory().writeLongLE(l)
if (!overflowOK) {
intercept[OverflowException] { be.writeByte(0xff) }
intercept[OverflowException] { be.writeByte(0xff) }
}
val arr = Array[Byte](
((l >> 56) & 0xff).toByte,
((l >> 48) & 0xff).toByte,
((l >> 40) & 0xff).toByte,
((l >> 32) & 0xff).toByte,
((l >> 24) & 0xff).toByte,
((l >> 16) & 0xff).toByte,
((l >> 8) & 0xff).toByte,
((l) & 0xff).toByte
)
assert(be.owned() == Buf.ByteArray.Owned(arr))
assert(le.owned() == Buf.ByteArray.Owned(arr.reverse))
assertIndex(be, 8)
assertIndex(le, 8)
})
def testWriteFloat(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit =
test(s"$name: writeFloat{BE,LE}")(forAll { (f: Float) =>
val be = bwFactory().writeFloatBE(f)
val le = bwFactory().writeFloatLE(f)
if (!overflowOK) {
intercept[OverflowException] { be.writeByte(0xff) }
intercept[OverflowException] { be.writeByte(0xff) }
}
val i = JFloat.floatToIntBits(f)
val arr = Array[Byte](
((i >> 24) & 0xff).toByte,
((i >> 16) & 0xff).toByte,
((i >> 8) & 0xff).toByte,
((i) & 0xff).toByte
)
assert(be.owned() == Buf.ByteArray.Owned(arr))
assert(le.owned() == Buf.ByteArray.Owned(arr.reverse))
assertIndex(be, 4)
assertIndex(le, 4)
})
def testWriteDouble(name: String, bwFactory: () => BufByteWriter, overflowOK: Boolean): Unit =
test(s"$name: writeDouble{BE,LE}")(forAll { (d: Double) =>
val be = bwFactory().writeDoubleBE(d)
val le = bwFactory().writeDoubleLE(d)
if (!overflowOK) {
intercept[OverflowException] { be.writeByte(0xff) }
intercept[OverflowException] { be.writeByte(0xff) }
}
val l = JDouble.doubleToLongBits(d)
val arr = Array[Byte](
((l >> 56) & 0xff).toByte,
((l >> 48) & 0xff).toByte,
((l >> 40) & 0xff).toByte,
((l >> 32) & 0xff).toByte,
((l >> 24) & 0xff).toByte,
((l >> 16) & 0xff).toByte,
((l >> 8) & 0xff).toByte,
((l) & 0xff).toByte
)
assert(be.owned() == Buf.ByteArray.Owned(arr))
assert(le.owned() == Buf.ByteArray.Owned(arr.reverse))
assertIndex(be, 8)
assertIndex(le, 8)
})
// FIXED
test("index initialized to zero") {
assertIndex(BufByteWriter.fixed(1), 0)
}
test("trims unwritten bytes") {
assert(BufByteWriter.fixed(5).owned().length == 0)
assert(BufByteWriter.fixed(5).writeIntBE(1).owned().length == 4)
assert(BufByteWriter.fixed(4).writeIntBE(1).owned().length == 4)
}
testWriteString("fixed", size => BufByteWriter.fixed(size), overflowOK = false)
testWriteByte("fixed", () => BufByteWriter.fixed(1), overflowOK = false)
testWriteShort("fixed", () => BufByteWriter.fixed(2), overflowOK = false)
testWriteMedium("fixed", () => BufByteWriter.fixed(3), overflowOK = false)
testWriteInt("fixed", () => BufByteWriter.fixed(4), overflowOK = false)
testWriteLong("fixed", () => BufByteWriter.fixed(8), overflowOK = false)
testWriteFloat("fixed", () => BufByteWriter.fixed(4), overflowOK = false)
testWriteDouble("fixed", () => BufByteWriter.fixed(8), overflowOK = false)
test("fixed: writeBytes(Array[Byte])")(forAll { (bytes: Array[Byte]) =>
val bw = BufByteWriter.fixed(bytes.length)
val buf = bw.writeBytes(bytes).owned()
intercept[OverflowException] { bw.writeByte(0xff) }
assert(buf == Buf.ByteArray.Owned(bytes))
assertIndex(bw, bytes.length)
})
test("fixed: writeBytes(Array[Byte]) 2 times")(forAll { (bytes: Array[Byte]) =>
val bw = BufByteWriter.fixed(bytes.length * 2)
val buf = bw.writeBytes(bytes).writeBytes(bytes).owned()
intercept[OverflowException] { bw.writeByte(0xff) }
assert(buf == Buf.ByteArray.Owned(bytes ++ bytes))
assertIndex(bw, bytes.length * 2)
})
test("fixed: writeBytes(Buf)")(forAll { (arr: Array[Byte]) =>
val bytes = Buf.ByteArray.Owned(arr)
val bw = BufByteWriter.fixed(bytes.length)
val buf = bw.writeBytes(bytes).owned()
intercept[OverflowException] { bw.writeByte(0xff) }
assert(buf == bytes)
assertIndex(bw, bytes.length)
})
test("fixed: writeBytes(Buf) 2 times")(forAll { (arr: Array[Byte]) =>
val bytes = Buf.ByteArray.Owned(arr)
val bw = BufByteWriter.fixed(bytes.length * 2)
val buf = bw.writeBytes(bytes).writeBytes(bytes).owned()
intercept[OverflowException] { bw.writeByte(0xff) }
assert(buf == bytes.concat(bytes))
assertIndex(bw, bytes.length * 2)
})
// DYNAMIC
test("dynamic: writeByte with initial size 0 should throw exception") {
intercept[IllegalArgumentException] { BufByteWriter.dynamic(0) }
}
testWriteString("dynamic", _ => BufByteWriter.dynamic(1), overflowOK = true)
testWriteByte("dynamic", () => BufByteWriter.dynamic(1), overflowOK = true)
testWriteShort("dynamic", () => BufByteWriter.dynamic(1), overflowOK = true)
testWriteMedium("dynamic", () => BufByteWriter.dynamic(2), overflowOK = true)
testWriteInt("dynamic", () => BufByteWriter.dynamic(3), overflowOK = true)
testWriteLong("dynamic", () => BufByteWriter.dynamic(20), overflowOK = true)
testWriteFloat("dynamic", () => BufByteWriter.dynamic(4), overflowOK = true)
testWriteDouble("dynamic", () => BufByteWriter.dynamic(), overflowOK = true)
testWriteLong(
"dynamic, must grow multiple times",
() => BufByteWriter.dynamic(1),
overflowOK = true
)
test("dynamic: writeBytes(Array[Byte])")(forAll { (bytes: Array[Byte]) =>
val bw = BufByteWriter.dynamic()
val buf = bw.writeBytes(bytes).owned()
assert(buf == Buf.ByteArray.Owned(bytes))
})
test("dynamic: writeBytes(Buf)")(forAll { (arr: Array[Byte]) =>
val bytes = Buf.ByteArray.Owned(arr)
val bw = BufByteWriter.dynamic()
val buf = bw.writeBytes(bytes).owned()
assert(buf == bytes)
})
test("dynamic: writeBytes(Array[Byte]) 3 times")(forAll { (bytes: Array[Byte]) =>
val bw = BufByteWriter.dynamic()
val buf = bw
.writeBytes(bytes)
.writeBytes(bytes)
.writeBytes(bytes)
.owned()
assert(buf == Buf.ByteArray.Owned(bytes ++ bytes ++ bytes))
})
test("dynamic: writeBytes(Buf) 3 times")(forAll { (arr: Array[Byte]) =>
val bytes = Buf.ByteArray.Owned(arr)
val bw = BufByteWriter.dynamic()
val buf = bw
.writeBytes(bytes)
.writeBytes(bytes)
.writeBytes(bytes)
.owned()
assert(buf == bytes.concat(bytes).concat(bytes))
})
// Requires additional heap space to run.
// Pass JVM option '-Xmx8g'.
/*test("dynamic: try to write more than Int.MaxValue -2 bytes") {
val bw = ByteWriter.dynamic()
val bytes = new Array[Byte](Int.MaxValue - 2)
bw.writeBytes(bytes)
intercept[OverflowException] { bw.writeByte(0xff) }
}*/
}
|
twitter/util
|
util-core/src/test/scala/com/twitter/io/BufByteWriterTest.scala
|
Scala
|
apache-2.0
| 10,897 |
package views.json.ImportJob
import java.time.Instant
import org.specs2.mock.Mockito
import com.overviewdocs.models.ImportJob
class showSpec extends views.ViewSpecification with Mockito {
trait BaseScope extends JsonViewSpecificationScope {
val importJob = smartMock[ImportJob]
importJob.documentSetId returns 1L
importJob.progress returns Some(0.24)
importJob.description returns Some(("foo", Seq()))
importJob.estimatedCompletionTime returns Some(Instant.ofEpochMilli(1234567L))
override def result = show(importJob)
}
"show" should {
"show documentSetId" in new BaseScope {
json must /("documentSetId" -> 1)
}
"show progress when it exists" in new BaseScope {
json must /("progress" -> 0.24)
}
"show null progress" in new BaseScope {
importJob.progress returns None
json must contain(""""progress":null""")
}
"show description when it exists" in new BaseScope {
json must /("description" -> "foo")
}
"show null description" in new BaseScope {
importJob.description returns None
json must contain(""""description":null""")
}
"show completion time" in new BaseScope {
json must /("estimatedCompletionTime" -> 1234567)
}
"show null completion time" in new BaseScope {
importJob.estimatedCompletionTime returns None
json must contain(""""estimatedCompletionTime":null""")
}
}
}
|
overview/overview-server
|
web/test/views/ImportJob/showSpec.scala
|
Scala
|
agpl-3.0
| 1,436 |
package amora.ui
import scala.scalajs.js.JSApp
object Main extends JSApp {
val ui = new Ui
override def main(): Unit = {
ui.authenticate()
ui.setupUI3()
}
}
|
sschaef/scalajs-test
|
ui/src/main/scala/amora/ui/Main.scala
|
Scala
|
mit
| 176 |
package day2
import scala.io.Source
object DayOfCode2 {
def smallestSide(l: Int, w:Int, h:Int):Int = List(l, w, h).combinations(2).map(side => side.reduce(_ * _)).min
def surfaceArea(l: Int, w: Int, h: Int):Int = 2 * l * w + 2 * w * h + 2 * h * l
def parse(s: String): List[Int] = s.split("x").toList.map { x => x.toInt }
def bow(l:Int, w:Int, h:Int) = l * w * h
def ribbon(l:Int, w:Int, h:Int) = List(l, w, h).combinations(2).map(side =>
side.foldLeft(0)((total:Int, l:Int) => total + l + l)).min
def main(args: Array[String]) {
val part1answer:List[Int] = Source.fromFile("day2input").getLines().toList map { line =>
parse(line) match {
case l :: w :: h :: Nil => surfaceArea(l, w, h) + smallestSide(l,w,h)
case _ => 0
}
}
println(part1answer.reduce(_+_))
val part2answer:List[Int] = Source.fromFile("day2input").getLines().toList map { line =>
parse(line) match {
case l :: w :: h :: Nil => ribbon(l, w, h) + bow(l,w,h)
case _ => 0
}
}
println(part2answer.reduce(_+_))
}
}
|
aeffrig/adventofcode15
|
src/main/scala/day2/DayOfCode2.scala
|
Scala
|
apache-2.0
| 1,084 |
/*
* 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.rpc.netty
import java.util.concurrent.{ThreadPoolExecutor, ConcurrentHashMap, LinkedBlockingQueue, TimeUnit}
import javax.annotation.concurrent.GuardedBy
import scala.collection.JavaConverters._
import scala.concurrent.Promise
import scala.util.control.NonFatal
import org.apache.spark.{SparkException, Logging}
import org.apache.spark.network.client.RpcResponseCallback
import org.apache.spark.rpc._
import org.apache.spark.util.ThreadUtils
/**
* A message dispatcher, responsible for routing RPC messages to the appropriate endpoint(s).
*/
private[netty] class Dispatcher(nettyEnv: NettyRpcEnv) extends Logging {
private class EndpointData(
val name: String,
val endpoint: RpcEndpoint,
val ref: NettyRpcEndpointRef) {
val inbox = new Inbox(ref, endpoint)
}
private val endpoints = new ConcurrentHashMap[String, EndpointData]
private val endpointRefs = new ConcurrentHashMap[RpcEndpoint, RpcEndpointRef]
// Track the receivers whose inboxes may contain messages.
private val receivers = new LinkedBlockingQueue[EndpointData]
/**
* True if the dispatcher has been stopped. Once stopped, all messages posted will be bounced
* immediately.
*/
@GuardedBy("this")
private var stopped = false
def registerRpcEndpoint(name: String, endpoint: RpcEndpoint): NettyRpcEndpointRef = {
val addr = new RpcEndpointAddress(nettyEnv.address.host, nettyEnv.address.port, name)
val endpointRef = new NettyRpcEndpointRef(nettyEnv.conf, addr, nettyEnv)
synchronized {
if (stopped) {
throw new IllegalStateException("RpcEnv has been stopped")
}
if (endpoints.putIfAbsent(name, new EndpointData(name, endpoint, endpointRef)) != null) {
throw new IllegalArgumentException(s"There is already an RpcEndpoint called $name")
}
val data = endpoints.get(name)
endpointRefs.put(data.endpoint, data.ref)
receivers.put(data) // for the OnStart message
}
endpointRef
}
def getRpcEndpointRef(endpoint: RpcEndpoint): RpcEndpointRef = endpointRefs.get(endpoint)
def removeRpcEndpointRef(endpoint: RpcEndpoint): Unit = endpointRefs.remove(endpoint)
// Should be idempotent
private def unregisterRpcEndpoint(name: String): Unit = {
val data = endpoints.remove(name)
if (data != null) {
data.inbox.stop()
receivers.put(data) // for the OnStop message
}
// Don't clean `endpointRefs` here because it's possible that some messages are being processed
// now and they can use `getRpcEndpointRef`. So `endpointRefs` will be cleaned in Inbox via
// `removeRpcEndpointRef`.
}
def stop(rpcEndpointRef: RpcEndpointRef): Unit = {
synchronized {
if (stopped) {
// This endpoint will be stopped by Dispatcher.stop() method.
return
}
unregisterRpcEndpoint(rpcEndpointRef.name)
}
}
/**
* Send a message to all registered [[RpcEndpoint]]s in this process.
*
* This can be used to make network events known to all end points (e.g. "a new node connected").
*/
def postToAll(message: InboxMessage): Unit = {
val iter = endpoints.keySet().iterator()
while (iter.hasNext) {
val name = iter.next
postMessage(
name,
_ => message,
() => { logWarning(s"Drop $message because $name has been stopped") })
}
}
/** Posts a message sent by a remote endpoint. */
def postRemoteMessage(message: RequestMessage, callback: RpcResponseCallback): Unit = {
def createMessage(sender: NettyRpcEndpointRef): InboxMessage = {
val rpcCallContext =
new RemoteNettyRpcCallContext(
nettyEnv, sender, callback, message.senderAddress, message.needReply)
ContentMessage(message.senderAddress, message.content, message.needReply, rpcCallContext)
}
def onEndpointStopped(): Unit = {
callback.onFailure(
new SparkException(s"Could not find ${message.receiver.name} or it has been stopped"))
}
postMessage(message.receiver.name, createMessage, onEndpointStopped)
}
/** Posts a message sent by a local endpoint. */
def postLocalMessage(message: RequestMessage, p: Promise[Any]): Unit = {
def createMessage(sender: NettyRpcEndpointRef): InboxMessage = {
val rpcCallContext =
new LocalNettyRpcCallContext(sender, message.senderAddress, message.needReply, p)
ContentMessage(message.senderAddress, message.content, message.needReply, rpcCallContext)
}
def onEndpointStopped(): Unit = {
p.tryFailure(
new SparkException(s"Could not find ${message.receiver.name} or it has been stopped"))
}
postMessage(message.receiver.name, createMessage, onEndpointStopped)
}
/**
* Posts a message to a specific endpoint.
*
* @param endpointName name of the endpoint.
* @param createMessageFn function to create the message.
* @param callbackIfStopped callback function if the endpoint is stopped.
*/
private def postMessage(
endpointName: String,
createMessageFn: NettyRpcEndpointRef => InboxMessage,
callbackIfStopped: () => Unit): Unit = {
val shouldCallOnStop = synchronized {
val data = endpoints.get(endpointName)
if (stopped || data == null) {
true
} else {
data.inbox.post(createMessageFn(data.ref))
receivers.put(data)
false
}
}
if (shouldCallOnStop) {
// We don't need to call `onStop` in the `synchronized` block
callbackIfStopped()
}
}
def stop(): Unit = {
synchronized {
if (stopped) {
return
}
stopped = true
}
// Stop all endpoints. This will queue all endpoints for processing by the message loops.
endpoints.keySet().asScala.foreach(unregisterRpcEndpoint)
// Enqueue a message that tells the message loops to stop.
receivers.put(PoisonPill)
threadpool.shutdown()
}
def awaitTermination(): Unit = {
threadpool.awaitTermination(Long.MaxValue, TimeUnit.MILLISECONDS)
}
/**
* Return if the endpoint exists
*/
def verify(name: String): Boolean = {
endpoints.containsKey(name)
}
/** Thread pool used for dispatching messages. */
private val threadpool: ThreadPoolExecutor = {
val numThreads = nettyEnv.conf.getInt("spark.rpc.netty.dispatcher.numThreads",
Runtime.getRuntime.availableProcessors())
val pool = ThreadUtils.newDaemonFixedThreadPool(numThreads, "dispatcher-event-loop")
for (i <- 0 until numThreads) {
pool.execute(new MessageLoop)
}
pool
}
/** Message loop used for dispatching messages. */
private class MessageLoop extends Runnable {
override def run(): Unit = {
try {
while (true) {
try {
val data = receivers.take()
if (data == PoisonPill) {
// Put PoisonPill back so that other MessageLoops can see it.
receivers.put(PoisonPill)
return
}
data.inbox.process(Dispatcher.this)
} catch {
case NonFatal(e) => logError(e.getMessage, e)
}
}
} catch {
case ie: InterruptedException => // exit
}
}
}
/** A poison endpoint that indicates MessageLoop should exit its message loop. */
private val PoisonPill = new EndpointData(null, null, null)
}
|
pronix/spark
|
core/src/main/scala/org/apache/spark/rpc/netty/Dispatcher.scala
|
Scala
|
apache-2.0
| 8,169 |
package org.jetbrains.plugins.scala
package runner
import com.intellij.openapi.project.Project
import com.intellij.execution.configurations.{JavaParameters, RunConfigurationModule, ModuleBasedConfiguration, ConfigurationFactory}
import com.intellij.openapi.module.{ModuleUtilCore, Module}
import org.jetbrains.plugins.scala.config.{Libraries, CompilerLibraryData, ScalaFacet}
import scala.collection.JavaConverters._
import org.jdom.Element
import com.intellij.openapi.util.JDOMExternalizer
import com.intellij.execution.{CantRunException, ExecutionException}
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.projectRoots.{Sdk, JdkUtil, JavaSdkType}
import org.jetbrains.plugins.scala.compiler.ScalacSettings
import com.intellij.util.PathUtil
import org.consulo.java.module.extension.JavaModuleExtension
/**
*/
abstract class BaseRunConfiguration(val project: Project, val configurationFactory: ConfigurationFactory, val name: String)
extends ModuleBasedConfiguration[RunConfigurationModule](name, new RunConfigurationModule(project), configurationFactory) {
def mainClass:String
val defaultJavaOptions = "-Djline.terminal=NONE"
val useJavaCp = "-usejavacp"
def ensureUsesJavaCpByDefault(s: String) = if (s == null || s.isEmpty) useJavaCp else s
private var myConsoleArgs = ""
def consoleArgs = ensureUsesJavaCpByDefault(this.myConsoleArgs)
def consoleArgs_=(s: String) = this.myConsoleArgs = ensureUsesJavaCpByDefault(s)
var javaOptions = defaultJavaOptions
var workingDirectory = Option(getProject.getBaseDir) map (_.getPath) getOrElse ""
def getModule: Module = getConfigurationModule.getModule
def getValidModules: java.util.List[Module] = ScalaFacet.findModulesIn(getProject).toList.asJava
override def writeExternal(element: Element) {
super.writeExternal(element)
writeModule(element)
JDOMExternalizer.write(element, "vmparams4", javaOptions)
JDOMExternalizer.write(element, "workingDirectory", workingDirectory)
}
override def readExternal(element: Element) {
super.readExternal(element)
readModule(element)
javaOptions = JDOMExternalizer.readString(element, "vmparams4")
if (javaOptions == null) {
javaOptions = JDOMExternalizer.readString(element, "vmparams")
if (javaOptions != null) javaOptions += s" $defaultJavaOptions"
}
val str = JDOMExternalizer.readString(element, "workingDirectory")
if (str != null)
workingDirectory = str
}
def createParams: JavaParameters = {
val module = getModule
if (module == null) throw new ExecutionException("Module is not specified")
val facet = ScalaFacet.findIn(module).getOrElse {
throw new ExecutionException("No Scala facet configured for module " + module.getName)
}
val sdk : Sdk = ModuleUtilCore.getSdk(module, classOf[JavaModuleExtension[_]])
if (sdk == null) {
throw CantRunException.noJdkForModule(module)
}
val params = new JavaParameters()
params.getVMParametersList.addParametersString(javaOptions)
val files =
if (facet.fsc) {
val settings = ScalacSettings.getInstance(getProject)
val lib: Option[CompilerLibraryData] = Libraries.findBy(settings.COMPILER_LIBRARY_NAME,
settings.COMPILER_LIBRARY_LEVEL, getProject)
lib match {
case Some(compilerLib) => compilerLib.files
case _ => facet.files
}
} else facet.files
params.getClassPath.addAllFiles(files.asJava)
params.setUseDynamicClasspath(JdkUtil.useDynamicClasspath(getProject))
params.setUseDynamicVMOptions(JdkUtil.useDynamicVMOptions())
params.getClassPath.add(PathUtil.getJarPathForClass(classOf[_root_.org.jetbrains.plugins.scala.worksheet.MyWorksheetRunner]))
params.setWorkingDirectory(workingDirectory)
params.setMainClass(mainClass)
params.configureByModule(module, JavaParameters.JDK_AND_CLASSES_AND_TESTS)
params
}
}
|
consulo/consulo-scala
|
src/org/jetbrains/plugins/scala/runner/BaseRunConfiguration.scala
|
Scala
|
apache-2.0
| 3,945 |
/*
* Copyright 2014โ2018 SlamData Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package quasar.mimir
import quasar.yggdrasil._
import quasar.precog.common._
import scalaz._
trait MathLibSpecs[M[+_]] extends EvaluatorSpecification[M]
with LongIdMemoryDatasetConsumer[M] { self =>
import dag._
import instructions._
import library._
val homn4 = "/hom/numbers4"
def inputOp2(op: Op2, loadFrom: String, const: RValue) = {
Join(BuiltInFunction2Op(op), Cross(None),
dag.AbsoluteLoad(Const(CString(loadFrom))),
Const(const))
}
def testEval(graph: DepGraph): Set[SEvent] = {
consumeEval(graph, defaultEvaluationContext) match {
case Success(results) => results
case Failure(error) => throw error
}
}
"for sets with numeric values inside arrays and objects" should {
"compute cos only of the numeric value" in {
val input = dag.Operate(BuiltInFunction1Op(cos),
dag.AbsoluteLoad(Const(CString("/het/numbers7"))))
val result = testEval(input)
result must haveSize(1)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1)
}
}
"for homogeneous sets, the appropriate math function" should { //todo test in particular cases when functions are not defined!!
"compute sinh" in {
val input = dag.Operate(BuiltInFunction1Op(sinh),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set[BigDecimal](0, 1.1752011936438014, -1.1752011936438014, 8.696374707602505E17, -4.872401723124452E9)
}
"compute sinh on two large(ish) values" in {
val input = dag.Operate(BuiltInFunction1Op(sinh),
dag.AbsoluteLoad(Const(CString("/hom/number"))))
val result = testEval(input)
result must haveSize(0)
}
"compute toDegrees" in {
val input = dag.Operate(BuiltInFunction1Op(toDegrees),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 57.29577951308232, -57.29577951308232, 2406.4227395494577, -1317.8029288008934)
}
"compute expm1" in {
val input = dag.Operate(BuiltInFunction1Op(expm1),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (Seq(_), SDecimal(d)) => d
}
result2.toSet must_=== Set(0.0, 1.718281828459045, -0.6321205588285577, 1.73927494152050099E18, -0.9999999998973812)
}
"compute expm1 on two large(ish) values" in {
val input = dag.Operate(BuiltInFunction1Op(expm1),
dag.AbsoluteLoad(Const(CString("/hom/number"))))
val result = testEval(input)
result must haveSize(1)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(-1.0)
}
"compute getExponent" in {
val input = dag.Operate(BuiltInFunction1Op(getExponent),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(3)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5)
}
"compute asin" in {
val input = dag.Operate(BuiltInFunction1Op(asin),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(4)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.5707963267948966, -1.5707963267948966)
}
"compute log10" in {
val input = dag.Operate(BuiltInFunction1Op(log10),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(3)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.6232492903979006)
}
"compute cos" in {
val input = dag.Operate(BuiltInFunction1Op(cos),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.0, 0.5403023058681398, 0.5403023058681398, -0.39998531498835127, -0.5328330203333975)
}
"compute exp" in {
val input = dag.Operate(BuiltInFunction1Op(exp),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (Seq(_), SDecimal(d)) => d
}
result2.toSet must_== Set[BigDecimal](1.0, 2.718281828459045, 0.36787944117144233, 1.73927494152050099E18, 1.026187963170189E-10)
}
"compute exp on two large(ish) values" in {
val input = dag.Operate(BuiltInFunction1Op(exp),
dag.AbsoluteLoad(Const(CString("/hom/number"))))
val result = testEval(input)
result must haveSize(1)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0)
}
"compute cbrt" in {
val input = dag.Operate(BuiltInFunction1Op(cbrt),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 3.4760266448864496, -2.8438669798515654)
}
"compute atan" in {
val input = dag.Operate(BuiltInFunction1Op(atan),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.7853981633974483, -0.7853981633974483, 1.5469913006098266, -1.5273454314033659)
}
"compute ceil" in {
val input = dag.Operate(BuiltInFunction1Op(ceil),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 42.0, -23.0)
}
"compute rint" in {
val input = dag.Operate(BuiltInFunction1Op(rint),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 42.0, -23.0)
}
"compute log1p" in {
val input = dag.Operate(BuiltInFunction1Op(log1p),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(4)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.6931471805599453, 3.7612001156935624)
}
"compute sqrt" in {
val input = dag.Operate(BuiltInFunction1Op(sqrt),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(4)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, 6.48074069840786)
}
"compute floor" in {
val input = dag.Operate(BuiltInFunction1Op(floor),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 42.0, -23.0)
}
"compute toRadians" in {
val input = dag.Operate(BuiltInFunction1Op(toRadians),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.017453292519943295, -0.017453292519943295, 0.7330382858376184, -0.40142572795869574)
}
"compute tanh" in {
val input = dag.Operate(BuiltInFunction1Op(tanh),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.7615941559557649, -0.7615941559557649, 1.0, -1.0)
}
"compute round" in {
val input = dag.Operate(BuiltInFunction1Op(round),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 1, -1, 42, -23)
}
"compute cosh" in {
val input = dag.Operate(BuiltInFunction1Op(cosh),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.0, 1.543080634815244, 1.543080634815244, 8.696374707602505E17, 4.872401723124452E9)
}
"compute cosh on two large(ish) values" in {
val input = dag.Operate(BuiltInFunction1Op(cosh),
dag.AbsoluteLoad(Const(CString("/hom/number"))))
val result = testEval(input)
result must haveSize(0)
}
"compute tan" in {
val input = dag.Operate(BuiltInFunction1Op(tan),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.5574077246549023, -1.5574077246549023, 2.2913879924374863, -1.5881530833912738)
}
"compute abs" in {
val input = dag.Operate(BuiltInFunction1Op(abs),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 1, 42, 23)
}
"compute sin" in {
val input = dag.Operate(BuiltInFunction1Op(sin),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.8414709848078965, -0.8414709848078965, -0.9165215479156338, 0.8462204041751706)
}
"compute log" in {
val input = dag.Operate(BuiltInFunction1Op(mathlog),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(3)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 3.7376696182833684)
}
"compute signum" in {
val input = dag.Operate(BuiltInFunction1Op(signum),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0)
}
"compute acos" in {
val input = dag.Operate(BuiltInFunction1Op(acos),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(4)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.5707963267948966, 0.0, 3.141592653589793)
}
"compute ulp" in {
val input = dag.Operate(BuiltInFunction1Op(ulp),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(4.9E-324, 2.220446049250313E-16, 2.220446049250313E-16, 7.105427357601002E-15, 3.552713678800501E-15)
}
"compute hypot" in {
val input = Join(BuiltInFunction2Op(hypot), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(7.0, 7.0710678118654755, 7.0710678118654755, 42.579337712087536, 24.041630560342615)
}
"compute pow" in {
val input = Join(BuiltInFunction2Op(pow), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 2.30539333248E11, -3.404825447E9)
}
"compute maxOf" in {
val input = Join(BuiltInFunction2Op(maxOf), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(7, 42)
}
"compute atan2" in {
val input = Join(BuiltInFunction2Op(atan2), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.1418970546041639, -0.1418970546041639, 1.4056476493802699, -1.2753554896511767)
}
"compute copySign" in {
val input = Join(BuiltInFunction2Op(copySign), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, 42.0, 23.0)
}
"compute IEEEremainder" in {
val input = Join(BuiltInFunction2Op(IEEEremainder), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, -2.0)
}
"compute roundTo" in {
val input = inputOp2(roundTo, "/hom/decimals", CLong(2))
val result = testEval(input)
result must haveSize(5)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set[Double](1.24, 123.19, 100.00, 0, 0.50)
}
"round to evenly in the face of repeating decimals" in {
val input =
Operate(BuiltInFunction1Op(numToString),
Join(BuiltInFunction2Op(roundTo), Cross(None),
Join(Mul, Cross(None),
Join(Div, Cross(None),
Const(CLong(15)),
Const(CLong(3168))),
Const(CLong(100))),
Const(CLong(2))))
val result = testEval(input)
result must haveSize(1)
val result2 = result collect {
case (ids, SString(str)) if ids.isEmpty => str
}
result2.toSet must_== Set("0.47")
}
}
"for heterogeneous sets, the appropriate math function" should {
"compute sinh" in {
val input = dag.Operate(BuiltInFunction1Op(sinh),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (Seq(_), SDecimal(d)) => d
}
result2.toSet must_=== Set[BigDecimal](0, 1.1752011936438014, -1.1752011936438014, 8.696374707602505E17, -4.872401723124452E9)
}
"compute toDegrees" in {
val input = dag.Operate(BuiltInFunction1Op(toDegrees),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 57.29577951308232, -57.29577951308232, 2406.4227395494577, -1317.8029288008934)
}
"compute expm1" in {
val input = dag.Operate(BuiltInFunction1Op(expm1),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (Seq(_), SDecimal(d)) => d
}
result2.toSet must_=== Set(0.0, 1.718281828459045, -0.6321205588285577, 1.73927494152050099E18, -0.9999999998973812)
}
"compute getExponent" in {
val input = dag.Operate(BuiltInFunction1Op(getExponent),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(3)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5)
}
"compute asin" in {
val input = dag.Operate(BuiltInFunction1Op(asin),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(4)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.5707963267948966, -1.5707963267948966)
}
"compute log10" in {
val input = dag.Operate(BuiltInFunction1Op(log10),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(3)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.6232492903979006)
}
"compute cos" in {
val input = dag.Operate(BuiltInFunction1Op(cos),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.0, 0.5403023058681398, 0.5403023058681398, -0.39998531498835127, -0.5328330203333975)
}
"compute exp" in {
val input = dag.Operate(BuiltInFunction1Op(exp),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set[BigDecimal](1.0, 2.718281828459045, 0.36787944117144233, 1.73927494152050099E18, 1.026187963170189E-10)
}
"compute cbrt" in {
val input = dag.Operate(BuiltInFunction1Op(cbrt),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 3.4760266448864496, -2.8438669798515654)
}
"compute atan" in {
val input = dag.Operate(BuiltInFunction1Op(atan),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.7853981633974483, -0.7853981633974483, 1.5469913006098266, -1.5273454314033659)
}
"compute ceil" in {
val input = dag.Operate(BuiltInFunction1Op(ceil),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 42.0, -23.0)
}
"compute rint" in {
val input = dag.Operate(BuiltInFunction1Op(rint),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 42.0, -23.0)
}
"compute log1p" in {
val input = dag.Operate(BuiltInFunction1Op(log1p),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(4)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.6931471805599453, 3.7612001156935624)
}
"compute sqrt" in {
val input = dag.Operate(BuiltInFunction1Op(sqrt),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(4)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, 6.48074069840786)
}
"compute floor" in {
val input = dag.Operate(BuiltInFunction1Op(floor),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 42.0, -23.0)
}
"compute toRadians" in {
val input = dag.Operate(BuiltInFunction1Op(toRadians),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.017453292519943295, -0.017453292519943295, 0.7330382858376184, -0.40142572795869574)
}
"compute tanh" in {
val input = dag.Operate(BuiltInFunction1Op(tanh),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.7615941559557649, -0.7615941559557649, 1.0, -1.0)
}
"compute round" in {
val input = dag.Operate(BuiltInFunction1Op(round),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 1, -1, 42, -23)
}
"compute cosh" in {
val input = dag.Operate(BuiltInFunction1Op(cosh),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.0, 1.543080634815244, 1.543080634815244, 8.696374707602505E17, 4.872401723124452E9)
}
"compute tan" in {
val input = dag.Operate(BuiltInFunction1Op(tan),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.5574077246549023, -1.5574077246549023, 2.2913879924374863, -1.5881530833912738)
}
"compute abs" in {
val input = dag.Operate(BuiltInFunction1Op(abs),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 1, 42, 23)
}
"compute sin" in {
val input = dag.Operate(BuiltInFunction1Op(sin),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.8414709848078965, -0.8414709848078965, -0.9165215479156338, 0.8462204041751706)
}
"compute log" in {
val input = dag.Operate(BuiltInFunction1Op(mathlog),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(3)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 3.7376696182833684)
}
"compute signum" in {
val input = dag.Operate(BuiltInFunction1Op(signum),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0)
}
"compute acos" in {
val input = dag.Operate(BuiltInFunction1Op(acos),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(4)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.5707963267948966, 0.0, 3.141592653589793)
}
"compute ulp" in {
val input = dag.Operate(BuiltInFunction1Op(ulp),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(4.9E-324, 2.220446049250313E-16, 2.220446049250313E-16, 7.105427357601002E-15, 3.552713678800501E-15)
}
"compute hypot" in {
val input = Join(BuiltInFunction2Op(hypot), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(7.0, 7.0710678118654755, 7.0710678118654755, 42.579337712087536, 24.041630560342615)
}
"compute pow" in {
val input = Join(BuiltInFunction2Op(pow), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, 2.30539333248E11, -3.404825447E9)
}
"compute maxOf" in {
val input = Join(BuiltInFunction2Op(maxOf), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(7, 42)
}
"compute maxOf over numeric arrays (doesn't map over arrays)" in {
val input = Join(BuiltInFunction2Op(maxOf), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/arrays"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(1)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(47)
}
"compute maxOf over numeric arrays and numeric objects (doesn't map over arrays or objects)" in {
val input = Join(BuiltInFunction2Op(maxOf), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbers7"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(1)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(7)
}
"compute maxOf over numeric arrays and numeric objects (using Map2)" in {
val input = Join(BuiltInFunction2Op(maxOf), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbers7"))),
dag.AbsoluteLoad(Const(CString("/het/arrays"))))
val result = testEval(input)
result must haveSize(1)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 2 => d
}
result2.toSet must_== Set(47)
}
"compute atan2" in {
val input = Join(BuiltInFunction2Op(atan2), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.1418970546041639, -0.1418970546041639, 1.4056476493802699, -1.2753554896511767)
}
"compute copySign" in {
val input = Join(BuiltInFunction2Op(copySign), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, 42.0, 23.0)
}
"compute IEEEremainder" in {
val input = Join(BuiltInFunction2Op(IEEEremainder), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbers4"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.0, -1.0, -2.0)
}
"compute roundTo" in {
val input = inputOp2(roundTo, "/het/numbers4", CLong(-1))
val result = testEval(input)
result must haveSize(6)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 0, 40, -20)
}
}
"for homogeneous sets across two slice boundaries (22 elements)" should {
"compute sinh" in {
val input = dag.Operate(BuiltInFunction1Op(sinh),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 601302.1420819727, -601302.1420819727, 29937.07084924806, -221206.6960033301, 221206.6960033301, 548.3161232732465, -548.3161232732465, -74.20321057778875, -10.017874927409903, 11013.232874703393, 201.71315737027922, -4051.54190208279, 1634508.6862359024, -81377.39570642984)
}
"compute toDegrees" in {
val input = dag.Operate(BuiltInFunction1Op(toDegrees),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 630.2535746439056, 572.9577951308232, -401.07045659157626, 401.07045659157626, 802.1409131831525, -802.1409131831525, 859.4366926962349, -515.662015617741, -687.5493541569879, -744.8451336700703, 744.8451336700703, 343.77467707849394, -286.4788975654116, -171.88733853924697)
}
"compute expm1" in {
val input = dag.Operate(BuiltInFunction1Op(expm1),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, -0.9999991684712809, -0.9932620530009145, 3269016.3724721107, 22025.465794806718, -0.950212931632136, 402.4287934927351, -0.9999938557876467, 1095.6331584284585, -0.999997739670593, 59873.14171519782, -0.9998765901959134, 442412.3920089205, -0.9990881180344455, 1202603.2841647768)
}
"compute getExponent" in {
val input = dag.Operate(BuiltInFunction1Op(getExponent),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(10)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(3, 2)
}
"compute asin" in {
val input = dag.Operate(BuiltInFunction1Op(asin),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(1)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0)
}
"compute log10" in {
val input = dag.Operate(BuiltInFunction1Op(log10),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(10)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.146128035678238, 0.8450980400142568, 1.0, 1.1139433523068367, 1.1760912590556813, 0.7781512503836436, 1.0413926851582251)
}
"compute cos" in {
val input = dag.Operate(BuiltInFunction1Op(cos),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.9601702866503661, -0.8390715290764524, 1.0, -0.9111302618846769, 0.1367372182078336, 0.7539022543433046, 0.8438539587324921, -0.9899924966004454, 0.9074467814501962, -0.7596879128588213, 0.28366218546322625, 0.004425697988050785)
}
"compute exp" in {
val input = dag.Operate(BuiltInFunction1Op(exp),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.00000614421235332821, 1.0, 0.049787068367863944, 1096.6331584284585, 3269017.3724721107, 442413.3920089205, 0.0000022603294069810542, 1202604.2841647768, 403.4287934927351, 0.0009118819655545162, 8.315287191035679E-7, 0.00012340980408667956, 59874.14171519782, 22026.465794806718, 0.006737946999085467)
}
"compute cbrt" in {
val input = dag.Operate(BuiltInFunction1Op(cbrt),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, -1.709975946676697, -1.4422495703074083, -2.2894284851066637, 1.8171205928321397, -1.9129311827723892, 1.9129311827723892, -2.3513346877207573, 2.154434690031884, 2.3513346877207573, 2.4662120743304703, 2.2239800905693157, -2.41014226417523, 2.41014226417523, -2.080083823051904)
}
"compute atan" in {
val input = dag.Operate(BuiltInFunction1Op(atan),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, -1.4876550949064553, -1.4994888620096063, 1.4994888620096063, -1.460139105621001, 1.5042281630190728, 1.4288992721907328, -1.4288992721907328, 1.4711276743037347, 1.4056476493802699, -1.4940244355251187, 1.4940244355251187, 1.4801364395941514, -1.2490457723982544, -1.373400766945016)
}
"compute ceil" in {
val input = dag.Operate(BuiltInFunction1Op(ceil),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 10, -7, 14, -3, -12, 6, 13, -5, 7, -14, 11, -9, -13, 15)
}
"compute rint" in {
val input = dag.Operate(BuiltInFunction1Op(rint),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 10, -7, 14, -3, -12, 6, 13, -5, 7, -14, 11, -9, -13, 15)
}
"compute log1p" in {
val input = dag.Operate(BuiltInFunction1Op(log1p),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(11)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(2.70805020110221, 0.0, 1.9459101490553132, 2.4849066497880004, 2.3978952727983707, 2.0794415416798357, 2.639057329615259, 2.772588722239781)
}
"compute sqrt" in {
val input = dag.Operate(BuiltInFunction1Op(sqrt),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(11)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 3.3166247903554, 2.449489742783178, 2.6457513110645907, 3.7416573867739413, 3.872983346207417, 3.1622776601683795, 3.605551275463989)
}
"compute floor" in {
val input = dag.Operate(BuiltInFunction1Op(floor),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 10, -7, 14, -3, -12, 6, 13, -5, 7, -14, 11, -9, -13, 15)
}
"compute toRadians" in {
val input = dag.Operate(BuiltInFunction1Op(toRadians),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, -0.08726646259971647, -0.20943951023931953, 0.19198621771937624, 0.22689280275926282, 0.10471975511965977, -0.22689280275926282, 0.17453292519943295, -0.12217304763960307, 0.12217304763960307, -0.05235987755982988, -0.15707963267948966, -0.24434609527920614, 0.24434609527920614, 0.2617993877991494)
}
"compute tanh" in {
val input = dag.Operate(BuiltInFunction1Op(tanh),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.9999999999998128, -0.9950547536867305, -0.9999999999244973, 0.9999877116507956, -0.9999092042625951, 0.9999999958776927, 0.9999999994421064, 0.9999999999986171, -0.9999999999986171, -0.999999969540041, -0.9999983369439447, 0.9999983369439447, -0.9999999999897818, 0.9999999999897818)
}
"compute round" in {
val input = dag.Operate(BuiltInFunction1Op(round),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 10, -7, 14, -3, -12, 6, 13, -5, 7, -14, 11, -9, -13, 15)
}
"compute cosh" in {
val input = dag.Operate(BuiltInFunction1Op(cosh),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1634508.6862362083, 4051.5420254925943, 29937.070865949758, 221206.6960055904, 10.067661995777765, 1.0, 81377.39571257407, 548.317035155212, 74.20994852478785, 11013.232920103324, 201.7156361224559, 601302.1420828041)
}
"compute tan" in {
val input = dag.Operate(BuiltInFunction1Op(tan),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, -0.8559934009085188, -0.4630211329364896, 0.4630211329364896, -7.2446066160948055, 7.2446066160948055, 0.6483608274590866, 3.380515006246586, -0.8714479827243187, 0.8714479827243187, 0.1425465430742778, 0.45231565944180985, 0.6358599286615808, -0.29100619138474915, -225.95084645419513)
}
"compute abs" in {
val input = dag.Operate(BuiltInFunction1Op(abs),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5, 10, 14, 6, 9, 13, 12, 7, 3, 11, 15)
}
"compute sin" in {
val input = dag.Operate(BuiltInFunction1Op(sin),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.5365729180004349, -0.4121184852417566, -0.6569865987187891, 0.6569865987187891, -0.9999902065507035, 0.9906073556948704, -0.9906073556948704, -0.5440211108893698, 0.6502878401571168, 0.9589242746631385, 0.4201670368266409, -0.4201670368266409, -0.1411200080598672, -0.27941549819892586)
}
"compute log" in {
val input = dag.Operate(BuiltInFunction1Op(mathlog),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(10)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(2.70805020110221, 1.9459101490553132, 2.6390573296152584, 2.3978952727983707, 2.5649493574615367, 2.302585092994046, 1.791759469228055)
}
"compute signum" in {
val input = dag.Operate(BuiltInFunction1Op(signum),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 1, -1)
}
"compute acos" in {
val input = dag.Operate(BuiltInFunction1Op(acos),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(1)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.5707963267948966)
}
"compute ulp" in {
val input = dag.Operate(BuiltInFunction1Op(ulp),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.7763568394002505E-15, 8.881784197001252E-16, 4.440892098500626E-16, 4.9E-324)
}
"compute hypot" in {
val input = Join(BuiltInFunction2Op(hypot), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(13.892443989449804, 11.40175425099138, 8.602325267042627, 12.206555615733702, 16.55294535724685, 9.219544457292887, 15.652475842498529, 14.7648230602334, 7.0, 7.615773105863909, 13.038404810405298, 9.899494936611665)
}
"compute pow" in {
val input = Join(BuiltInFunction2Op(pow), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 170859375, 62748517, 19487171, -2187.0, -35831808, -4782969.0, 823543.0, -62748517, 279936.0, -105413504, 1.0E+7, -78125.0, -823543.0, 105413504)
}
"compute maxOf" in {
val input = Join(BuiltInFunction2Op(maxOf), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(10, 14, 13, 7, 11, 15)
}
"compute atan2" in {
val input = Join(BuiltInFunction2Op(atan2), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.1341691669813554, -0.6202494859828215, 1.1071487177940904, -1.1071487177940904, -0.9097531579442097, 1.0040671092713902, 0.7086262721276703, -0.4048917862850834, 1.0768549578753155, -1.0768549578753155, 0.960070362405688, -1.042721878368537, 0.7853981633974483, -0.7853981633974483)
}
"compute copySign" in {
val input = Join(BuiltInFunction2Op(copySign), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5, 10, 14, 6, 9, 13, 12, 7, 3, 11, 15)
}
"compute IEEEremainder" in {
val input = Join(BuiltInFunction2Op(IEEEremainder), Cross(None),
dag.AbsoluteLoad(Const(CString("/hom/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (Seq(_), SDecimal(d)) => d
}
result2.toVector.sorted must_== Vector(0, -3, 1, 2, -1, -2).sorted
}.pendingUntilFixed
"compute roundTo" in {
val input = inputOp2(roundTo, "/hom/numbersAcrossSlices", CLong(0))
val result = testEval(input)
result must haveSize(22)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(-7, 15, -13, 11, 7, 11, -7, 0, 14, -3, 6, -12, 10, -9, 15, -5, -13, -14, 11, -5, -5, 13)
}
}
"for heterogeneous sets across two slice boundaries (22 elements)" should {
"compute sinh" in {
val input = dag.Operate(BuiltInFunction1Op(sinh),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set[Double](0.0, 3.626860407847019, 74.20321057778875, -10.017874927409903, 81377.39570642984, 1.1752011936438014, -1.1752011936438014)
}
"compute toDegrees" in {
val input = dag.Operate(BuiltInFunction1Op(toDegrees),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 114.59155902616465, -57.29577951308232, 57.29577951308232, 687.5493541569879, 286.4788975654116, -171.88733853924697)
}
"compute expm1" in {
val input = dag.Operate(BuiltInFunction1Op(expm1),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(6.38905609893065, 0.0, 147.4131591025766, 1.718281828459045, -0.950212931632136, 162753.79141900392, -0.6321205588285577)
}
"compute getExponent" in {
val input = dag.Operate(BuiltInFunction1Op(getExponent),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(5)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1, 0, 3, 2)
}
"compute asin" in {
val input = dag.Operate(BuiltInFunction1Op(asin),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(5)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.5707963267948966, -1.5707963267948966)
}
"compute log10" in {
val input = dag.Operate(BuiltInFunction1Op(log10),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(5)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.6989700043360189, 1.0791812460476249, 0.3010299956639812)
}
"compute cos" in {
val input = dag.Operate(BuiltInFunction1Op(cos),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.0, 0.5403023058681398, 0.8438539587324921, -0.9899924966004454, -0.4161468365471424, 0.28366218546322625)
}
"compute exp" in {
val input = dag.Operate(BuiltInFunction1Op(exp),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.0, 0.049787068367863944, 2.718281828459045, 162754.79141900392, 148.4131591025766, 0.36787944117144233, 7.38905609893065)
}
"compute cbrt" in {
val input = dag.Operate(BuiltInFunction1Op(cbrt),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.709975946676697, 1.0, -1.4422495703074083, 2.2894284851066637, 1.2599210498948732, -1.0)
}
"compute atan" in {
val input = dag.Operate(BuiltInFunction1Op(atan),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.4876550949064553, 1.1071487177940904, -1.2490457723982544, 0.7853981633974483, -0.7853981633974483, 1.373400766945016)
}
"compute ceil" in {
val input = dag.Operate(BuiltInFunction1Op(ceil),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5, -3, 1, 2, 12, -1)
}
"compute rint" in {
val input = dag.Operate(BuiltInFunction1Op(rint),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5, -3, 1, 2, 12, -1)
}
"compute log1p" in {
val input = dag.Operate(BuiltInFunction1Op(log1p),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(7)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.6931471805599453, 2.5649493574615367, 1.0986122886681096, 1.791759469228055)
}
"compute sqrt" in {
val input = dag.Operate(BuiltInFunction1Op(sqrt),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(7)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 1.4142135623730951, 1.0, 3.4641016151377544, 2.23606797749979)
}
"compute floor" in {
val input = dag.Operate(BuiltInFunction1Op(floor),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5, -3, 1, 2, 12, -1)
}
"compute toRadians" in {
val input = dag.Operate(BuiltInFunction1Op(toRadians),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, 0.08726646259971647, 0.20943951023931953, -0.05235987755982988, 0.03490658503988659, 0.017453292519943295, -0.017453292519943295)
}
"compute tanh" in {
val input = dag.Operate(BuiltInFunction1Op(tanh),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, -0.9950547536867305, 0.9999999999244973, -0.7615941559557649, 0.7615941559557649, 0.9999092042625951, 0.9640275800758169)
}
"compute round" in {
val input = dag.Operate(BuiltInFunction1Op(round),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5, -3, 1, 2, 12, -1)
}
"compute cosh" in {
val input = dag.Operate(BuiltInFunction1Op(cosh),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(10.067661995777765, 1.0, 81377.39571257407, 74.20994852478785, 3.7621956910836314, 1.543080634815244)
}
"compute tan" in {
val input = dag.Operate(BuiltInFunction1Op(tan),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, -2.185039863261519, -3.380515006246586, 1.5574077246549023, -1.5574077246549023, 0.1425465430742778, -0.6358599286615808)
}
"compute abs" in {
val input = dag.Operate(BuiltInFunction1Op(abs),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5, 1, 2, 12, 3)
}
"compute sin" in {
val input = dag.Operate(BuiltInFunction1Op(sin),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.0, -0.5365729180004349, 0.8414709848078965, -0.8414709848078965, 0.9092974268256817, -0.9589242746631385, -0.1411200080598672)
}
"compute log" in {
val input = dag.Operate(BuiltInFunction1Op(mathlog),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(5)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.6931471805599453, 0.0, 2.4849066497880004, 1.6094379124341003)
}
"compute signum" in {
val input = dag.Operate(BuiltInFunction1Op(signum),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 1, -1)
}
"compute acos" in {
val input = dag.Operate(BuiltInFunction1Op(acos),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(5)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(1.5707963267948966, 0.0, 3.141592653589793)
}
"compute ulp" in {
val input = dag.Operate(BuiltInFunction1Op(ulp),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(2.220446049250313E-16, 4.9E-324, 1.7763568394002505E-15, 8.881784197001252E-16, 4.440892098500626E-16)
}
"compute hypot" in {
val input = Join(BuiltInFunction2Op(hypot), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(13.892443989449804, 8.602325267042627, 7.280109889280518, 7.0710678118654755, 7.0, 7.615773105863909)
}
"compute pow" in {
val input = Join(BuiltInFunction2Op(pow), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 1, -2187, 78125, 35831808, 128, -1)
}
"compute maxOf" in {
val input = Join(BuiltInFunction2Op(maxOf), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(7, 12)
}
"compute atan2" in {
val input = Join(BuiltInFunction2Op(atan2), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0.1418970546041639, 0.0, -0.1418970546041639, 0.6202494859828215, 0.27829965900511133, -0.4048917862850834, 1.042721878368537)
}
"compute copySign" in {
val input = Join(BuiltInFunction2Op(copySign), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, 5, 1, 2, 12, 3)
}
"compute IEEEremainder" in {
val input = Join(BuiltInFunction2Op(IEEEremainder), Cross(None),
dag.AbsoluteLoad(Const(CString("/het/numbersAcrossSlices"))),
Const(CLong(7)))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(0, -3, 1, 2, -1, -2)
}
"compute roundTo" in {
val input = inputOp2(roundTo, "/het/numbersAcrossSlices", CLong(0))
val result = testEval(input)
result must haveSize(9)
val result2 = result collect {
case (ids, SDecimal(d)) if ids.length == 1 => d
}
result2.toSet must_== Set(5, 0, 1, -1, 1, 12, 0, 2, -3)
}
}
}
object MathLibSpecs extends MathLibSpecs[Need]
|
jedesah/Quasar
|
mimir/src/test/scala/quasar/mimir/MathLibSpecs.scala
|
Scala
|
apache-2.0
| 63,843 |
/* 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.app.nlp
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable
import cc.factorie.util.{Cubbie, Attr}
import cc.factorie.variable.CategoricalVar
import cc.factorie.util.UniqueId
import cc.factorie.app.nlp.coref.WithinDocCoref
/** A portion of the string contents of a Document.
@author Andrew McCallum */
trait DocumentSubstring {
/** The Document of which this DocumentSubstring is a part. */
def document: Document
/** The character offset into the Document.string at which this DocumentSubstring begins. */
def stringStart: Int
/** The character offset into the Document.string at which this DocumentSubstring is over.
In other words, the last character of the DocumentSubstring is Document.string(this.stringEnd-1). */
def stringEnd: Int
/** The substring of the Document encompassed by this DocumentSubstring. */
def string: String
}
/** A Document holds a String containing the original raw string contents
of a natural language document to be processed. The Document also holds
a sequence of Sections, each of which is delineated by character offsets
into the Document's string, and each of which contains a sequence of Tokens,
Sentences and other TokenSpans which may be annotated.
Documents may be constructed with their full string contents, or they may
have their string contents augmented by the appendString method.
Documents also have an optional "name" which can be set by Document.setName.
This is typically used to hold a filename in the file system, or some other similar identifier.
The Document.stringLength method may be a faster alternative to Document.string.length
when you are in the middle of multiple appendString calls because it will
efficiently use the underlying string buffer length, rather than flushing the buffer
to create a string.
The canonical sequence of Sections in the Document is available through
the Document.sections method.
By default the canonical sequence of Sections holds a single Section that covers the
entire string contents of the Document (even as the Document grows). This canonical sequence
of Sections may be modified by the user, but this special all-encompassing Section
instance will always be available as Document.asSection.
Even though Tokens, Sentences and TokenSpans are really stored in the Sections,
Document has basic convenience methods for obtaining iterable collections of these
by concatenating them from the canonical sequence of Sections. These iterable
collections are of type Iterable[Token], not Seq[Token], however.
If you need the Tokens as a Seq[Token] rather than an Iterable[Token], or you need
more advanced queries for TokenSpan types, you should use methods on a Section,
not on the Document. In this case typical processing looks like:
"for (section <- document.sections) section.tokens.someMethodOnSeq()...".
@author Andrew McCallum */
class Document extends DocumentSubstring with Attr with UniqueId {
/** Create a new Document, initializing it to have contents given by the argument. */
def this(stringContents:String) = { this(); _string = stringContents }
/** Return the "name" assigned to this Document by the 'setName' method.
This may be any String, but is typically a filename or other similar identifier. */
def name: String = { val dn = this.attr[DocumentName]; if (dn ne null) dn.string else null }
/** Set the value that will be returned by the 'name' method.
It accomplishes this by setting the DocumentName attr on Document.
If the String argument is null, it will remove DocumentName attr if present. */
def setName(s:String): this.type = { if (s ne null) this.attr += DocumentName(s) else this.attr.remove[DocumentName]; this }
/** The unique identifier for this Document, e.g. used for database lookup, etc.
Defined to be the Document's name; we are relying on the user to set the name to a unique value. */
def uniqueId = name
// One of the following two is always null, the other non-null. The later is used while multiple appendString() method calls are made.
private var _string: String = ""
private var _stringbuf: StringBuffer = null
/** Append the string 's' to this Document.
@return the length of the Document's string before string 's' was appended. */
def appendString(s:String): Int = this.synchronized {
if (_stringbuf eq null) _stringbuf = new StringBuffer(_string)
val result = _stringbuf.length
_stringbuf.append(s)
_string = null
result
}
/** The string contents of this Document. */
def string: String = {
this.synchronized {
if (_string eq null) _string = _stringbuf.toString
_stringbuf = null
}
_string
}
/** The number of characters in this Document's string.
Use this instead of Document.string.length because it is more efficient when the Document's string is growing with appendString. */
def stringLength: Int = if (_string ne null) _string.length else _stringbuf.length
// For the DocumentSubstring trait
/** A method required by the DocumentSubstring trait, which in this case simply returns this Document itself. */
def document: Document = this
/** A method required by the DocumentSubstring trait, which in this case simply returns 0. */
def stringStart: Int = 0
/** A method required by the DocumentSubstring trait, which in this case simply returns Document.stringLength. */
def stringEnd: Int = stringLength
// Managing sections. These are the canonical Sections, but alternative Sections can be attached as Attr's.
/** A predefined Section that covers the entirety of the Document string, and even grows as the length of this Document may grow.
If the user does not explicitly add Sections to the document, this Section is the only one returned by the "sections" method. */
lazy val asSection: Section = new Section { def document: Document = Document.this; def stringStart = 0; def stringEnd = document.stringEnd }
private lazy val _sections: mutable.Buffer[Section] = new ArrayBuffer[Section] += asSection
/** The canonical list of Sections containing the tokens of the document.
The user may create and add Sections covering various substrings within the Document.
If the user does not explicitly add any Sections, by default there will be one Section that covers the entire Document string;
this one Section is the one returned by "Document.asSection".
Note that Sections may overlap with each other, representing alternative tokenizations or annotations. */
def sections: Seq[Section] = _sections // if (_sections.length == 0) Seq(asSection) else _sections
/** Add a new Section to this Document's canonical list of Sections.
If the only previously existing Section is the default (asSection), then remove it before adding the argument. */
def +=(s: Section) = { if (_sections.length == 1 && _sections(0) == asSection) _sections.clear(); _sections += s }
/** Remove a Section from this Document's canonical list of Sections. */
def -=(s: Section) = _sections -= s
/** Remove all Section from this Document's canonical list of Sections. */
def clearSections(): Unit = _sections.clear()
// A few iterators that combine the results from the Sections
/** Return an Iterable collection of all Tokens in all canonical Sections of this Document. */
def tokens: Iterable[Token] = if (sections.length == 1) sections.head.tokens else new Iterable[Token] { def iterator = for (section <- sections.iterator; token <- section.tokens.iterator) yield token }
/** Return an Iterable collection of all Sentences in all canonical Sections of this Document. */
def sentences: Iterable[Sentence] = if (sections.length == 1) sections.head.sentences else new Iterable[Sentence] { def iterator = for (section <- sections.iterator; sentence <- section.sentences.iterator) yield sentence }
/** An efficient way to get the total number of Tokens in the canonical Sections of this Document. */
def tokenCount: Int = if (sections.length == 0) sections.head.length else sections.foldLeft(0)((result, section) => result + section.length)
/** An efficient way to get the total number of Sentences in the canonical Sections of this Document. */
def sentenceCount: Int = if (sections.length == 0) sections.head.sentences.length else sections.foldLeft(0)((result, section) => result + section.sentences.length)
/** The collection of DocumentAnnotators that have been run on this Document,
For keeping records of which DocumentAnnotators have been run on this document, producing which annotations.
A Map from the annotation class to the DocumentAnnotator that produced it,
for example from classOf[cc.factorie.app.nlp.pos.PennPos] to classOf[cc.factorie.app.nlp.pos.ChainPosTagger].
Note that this map records annotations placed not just on the Document itself, but also its constituents,
such as NounPhraseNumberLabel on NounPhrase, PennPos on Token, ParseTree on Sentence, etc. */
lazy val annotators = new collection.mutable.LinkedHashMap[Class[_], Class[_]]
/** Return true if an annotation of class 'c' been placed somewhere within this Document. */
def hasAnnotation(c:Class[_]): Boolean = annotators.keys.exists(k => c.isAssignableFrom(k))
/** Optionally return the DocumentAnnotator that produced the annotation of class 'c' within this Document. */
def annotatorFor(c:Class[_]): Option[Class[_]] = annotators.keys.find(k => c.isAssignableFrom(k)).collect({case k:Class[_] => annotators(k)})
// /** Return a String containing the Token strings in the document, with sentence and span boundaries indicated with SGML. */
// def sgmlString(spanLists:SpanList[_,_,_]*): String = {
// val buf = new StringBuffer
// for (section <- sections; token <- section.tokens) {
// if (token.isSentenceStart) buf.append("<sentence>")
// token.startsSpans.foreach(span => buf.append("<"+span.name+">"))
// buf.append(token.string)
// token.endsSpans.foreach(span => buf.append("</"+span.name+">"))
// if (token.isSentenceEnd) buf.append("</sentence>")
// buf.append(" ")
// }
// buf.toString
// }
// Common attributes, will return null if not present
def coref: WithinDocCoref = this.attr[WithinDocCoref]
def targetCoref: WithinDocCoref = { val coref = this.attr[WithinDocCoref]; if (coref eq null) null else coref.target }
/** Return the WithinDocCoref solution for this Document. If not already present create it. */
def getCoref: WithinDocCoref = this.attr.getOrElseUpdate[WithinDocCoref](new WithinDocCoref(this))
/** Return the gold-standard WithinDocCoref.target solution for this Document. If not already present create it. */
def getTargetCoref: WithinDocCoref = { val coref = this.getCoref; if (coref.target eq null) coref.target = new WithinDocCoref(this); coref.target }
/** Return a String containing the Token strings in the document, formatted with one-word-per-line
and various tab-separated attributes appended on each line, generated as specified by the argument. */
def owplString(attributes:Iterable[(Token)=>Any]): String = {
val buf = new StringBuffer
for (section <- sections; token <- section.tokens) {
if (token.isSentenceStart) buf.append("\\n")
buf.append("%d\\t%d\\t%s\\t".format(token.position+1, token.positionInSentence+1, token.string))
//buf.append(token.stringStart); buf.append("\\t")
//buf.append(token.stringEnd)
for (af <- attributes) {
buf.append("\\t")
af(token) match {
case cv:CategoricalVar[String @unchecked] => buf.append(cv.categoryValue.toString)
case null => {}
case v:Any => buf.append(v.toString)
}
}
buf.append("\\n")
}
buf.toString
}
/** Return a String containing the Token strings in the document, formatted with one-word-per-line
and various tab-separated attributes appended on each line, generated from the 'annotator.tokenAnnotationString' method. */
def owplString(annotator:DocumentAnnotator): String = annotator match {
case pipeline:DocumentAnnotationPipeline => owplString(pipeline.annotators.map(a => a.tokenAnnotationString(_)))
case annotator:DocumentAnnotator => owplString(Seq(annotator.tokenAnnotationString(_)))
}
/** Return the Section that contains the pair of string offsets into the document. */
def getSectionByOffsets(strStart:Int, strEnd:Int):Option[Section] =
this.sections.map(sec => (sec.stringStart, sec.stringEnd, sec)).sortBy(_._1)
.find{case(start, end, _) => start <= strStart && end >= strEnd}.map(_._3)
}
/** Used as an attribute on Document to hold the document's name. */
case class DocumentName(string:String) {
override def toString: String = string
}
// TODO Consider removing DocumentCubbie because this implementation is inefficient,
// and it isn't sensible that everyone would want the same selection of saved items.
/** A Cubbie for serializing a Document, with separate slots for the Tokens, Sentences, and TokenSpans.
Note that it does not yet serialize Sections, and relies on Document.asSection being the only Section. */
//class DocumentCubbie[TC<:TokenCubbie,SC<:SentenceCubbie,TSC<:TokenSpanCubbie](val tc:()=>TC, val sc:()=>SC, val tsc:()=>TSC) extends Cubbie with AttrCubbieSlots {
// val name = StringSlot("name")
// val string = StringSlot("string")
// val tokens = CubbieListSlot("tokens", tc)
// val sentences = CubbieListSlot("sentences", sc)
// val spans = CubbieListSlot("spans", tsc)
// def storeDocument(doc:Document): this.type = {
// name := doc.name
// string := doc.string
// if (doc.asSection.length > 0) tokens := doc.tokens.toSeq.map(t => tokens.constructor().storeToken(t))
//// if (doc.spans.length > 0) spans := doc.spans.map(s => spans.constructor().store(s))
// if (doc.asSection.sentences.length > 0) sentences := doc.sentences.toSeq.map(s => sentences.constructor().storeSentence(s))
// storeAttr(doc)
// this
// }
// def fetchDocument: Document = {
// val doc = new Document(string.value).setName(name.value)
// if (tokens.value ne null) tokens.value.foreach(tc => doc.asSection += tc.fetchToken)
// //if (spans.value ne null) spans.value.foreach(sc => doc += sc.fetch(doc))
// if (sentences.value ne null) sentences.value.foreach(sc => sc.fetchSentence(doc.asSection))
// fetchAttr(doc)
// doc
// }
//}
// TODO Consider moving this to file util/Attr.scala
//trait AttrCubbieSlots extends Cubbie {
// val storeHooks = new cc.factorie.util.Hooks1[Attr]
// val fetchHooks = new cc.factorie.util.Hooks1[AnyRef]
// def storeAttr(a:Attr): this.type = { storeHooks(a); this }
// def fetchAttr(a:Attr): Attr = { fetchHooks(a); a }
//}
//
//trait DateAttrCubbieSlot extends AttrCubbieSlots {
// val date = DateSlot("date")
// storeHooks += ((a:Attr) => date := a.attr[java.util.Date])
// //fetchHooks += ((a:Attr) => a.attr += date.value)
// fetchHooks += { case a:Attr => a.attr += date.value }
//}
|
iesl/fuse_ttl
|
src/factorie-factorie_2.11-1.1/src/main/scala/cc/factorie/app/nlp/Document.scala
|
Scala
|
apache-2.0
| 15,970 |
object Solutionex3_7 extends App {
val ar = Array(12, 323, 2, 2, 12, 323, 10)
ar.distinct
}
|
koenighotze/scalafortheimpatient
|
src/main/scala/chapter3/ex3_7.scala
|
Scala
|
apache-2.0
| 96 |
/** MACHINE-GENERATED FROM AVRO SCHEMA. DO NOT EDIT DIRECTLY */
package avro.examples.baseball
final case class Player(number: Int, first_name: String, last_name: String, nicknames: Seq[Nickname])
|
julianpeeters/avrohugger
|
avrohugger-tools/src/test/compiler/output/Player.scala
|
Scala
|
apache-2.0
| 197 |
package mesosphere.mesos.scale
import mesosphere.AkkaIntegrationTest
import mesosphere.marathon.IntegrationTest
import mesosphere.marathon.integration.facades.MarathonFacade._
import mesosphere.marathon.integration.facades.{ITDeploymentResult, MarathonFacade, MesosFacade}
import mesosphere.marathon.integration.setup._
import mesosphere.marathon.raml.{App, AppUpdate}
import mesosphere.marathon.state.PathId
import org.scalatest.concurrent.Eventually
import play.api.libs.json._
import scala.collection.immutable.Seq
import scala.concurrent.duration._
import scala.concurrent.Future
object SingleAppScalingTest {
val metricsFile = "scaleUp20s-metrics"
val appInfosFile = "scaleUp20s-appInfos"
}
trait SimulatedMesosTest extends MesosTest {
def mesos: MesosFacade = {
require(false, "No access to mesos")
???
}
val mesosMasterUrl = ""
}
@IntegrationTest
class SingleAppScalingTest extends AkkaIntegrationTest with ZookeeperServerTest with SimulatedMesosTest with MarathonTest with Eventually {
import PathId._
val maxInstancesPerOffer = Option(System.getenv("MARATHON_MAX_INSTANCES_PER_OFFER")).getOrElse("1")
lazy val marathonServer = LocalMarathon(suiteName = suiteName, "localhost:5050", zkUrl = s"zk://${zkServer.connectUri}/marathon", conf = Map(
"max_instances_per_offer" -> maxInstancesPerOffer,
"task_launch_timeout" -> "20000",
"task_launch_confirm_timeout" -> "1000"),
mainClass = "mesosphere.mesos.simulation.SimulateMesosMain")
override lazy val leadingMarathon = Future.successful(marathonServer)
override lazy val marathonUrl: String = s"http://localhost:${marathonServer.httpPort}"
override lazy val testBasePath: PathId = PathId.empty
override lazy val marathon: MarathonFacade = new MarathonFacade(marathonUrl, testBasePath)
override def beforeAll(): Unit = {
super.beforeAll()
marathonServer.start().futureValue
val sseStream = startEventSubscriber()
system.registerOnTermination(sseStream.cancel())
waitForSSEConnect()
}
override def afterAll(): Unit = {
// intentionally cleaning up before we print out the stats.
super.afterAll()
marathonServer.close()
println()
DisplayAppScalingResults.displayMetrics(SingleAppScalingTest.metricsFile)
println()
DisplayAppScalingResults.displayAppInfoScaling(SingleAppScalingTest.appInfosFile)
}
private[this] def createStopApp(instances: Int): Unit = {
Given("a new app")
val appIdPath: PathId = testBasePath / "/test/app"
val app = appProxy(appIdPath, "v1", instances = instances, healthCheck = None)
When("the app gets posted")
val createdApp: RestResult[App] = marathon.createAppV2(app)
createdApp.code should be(201) // created
val deploymentIds: Seq[String] = extractDeploymentIds(createdApp)
deploymentIds.length should be(1)
val deploymentId = deploymentIds.head
Then("the deployment should finish eventually")
waitForDeploymentId(deploymentId, (30 + instances).seconds)
When("deleting the app")
val deleteResult: RestResult[ITDeploymentResult] = marathon.deleteApp(appIdPath, force = true)
Then("the delete should finish eventually")
waitForDeployment(deleteResult)
}
"SingleAppScaling" should {
"create/stop app with 1 instance (does it work?)" in {
createStopApp(1)
}
"create/stop app with 100 instances (warm up)" in {
createStopApp(100)
}
"application scaling" in {
// This test has a lot of logging output. Thus all log statements are prefixed with XXX
// for better grepability.
val appIdPath = testBasePath / "/test/app"
val appWithManyInstances = appProxy(appIdPath, "v1", instances = 100000, healthCheck = None)
val response = marathon.createAppV2(appWithManyInstances)
logger.info(s"XXX ${response.originalResponse.status}: ${response.originalResponse.entity}")
val startTime = System.currentTimeMillis()
var metrics = Seq.newBuilder[JsValue]
var appInfos = Seq.newBuilder[JsValue]
for (i <- 1 to 20) {
val waitTime: Long = startTime + i * 1000 - System.currentTimeMillis()
if (waitTime > 0) {
Thread.sleep(waitTime)
}
// val currentApp = marathon.app(appIdPath)
val appJson =
(marathon.listAppsInBaseGroup.entityJson \\ "apps")
.as[Seq[JsObject]]
.filter { appJson => (appJson \\ "id").as[String] == appIdPath.toString }
.head
val instances = (appJson \\ "instances").as[Int]
val tasksRunning = (appJson \\ "tasksRunning").as[Int]
val tasksStaged = (appJson \\ "tasksStaged").as[Int]
logger.info(s"XXX (starting) Current instance count: staged $tasksStaged, running $tasksRunning / $instances")
appInfos += ScalingTestResultFiles.addTimestamp(startTime)(appJson)
metrics += ScalingTestResultFiles.addTimestamp(startTime)(marathon.metrics().entityJson)
}
ScalingTestResultFiles.writeJson(SingleAppScalingTest.appInfosFile, appInfos.result())
ScalingTestResultFiles.writeJson(SingleAppScalingTest.metricsFile, metrics.result())
logger.info("XXX suspend")
val result = marathon.updateApp(appWithManyInstances.id.toPath, AppUpdate(instances = Some(0)), force = true).originalResponse
logger.info(s"XXX ${result.status}: ${result.entity}")
eventually {
val currentApp = marathon.app(appIdPath)
val instances = (currentApp.entityJson \\ "app" \\ "instances").as[Int]
val tasksRunning = (currentApp.entityJson \\ "app" \\ "tasksRunning").as[Int]
val tasksStaged = (currentApp.entityJson \\ "app" \\ "tasksStaged").as[Int]
logger.info(s"XXX (suspendSuccessfully) Current instance count: staged $tasksStaged, running $tasksRunning / $instances")
require(instances == 0)
}
eventually {
logger.info("XXX deleting")
val deleteResult: RestResult[ITDeploymentResult] = marathon.deleteApp(appWithManyInstances.id.toPath, force = true)
waitForDeployment(deleteResult)
}
}
}
}
|
gsantovena/marathon
|
mesos-simulation/src/test/scala/mesosphere/mesos/scale/SingleAppScalingTest.scala
|
Scala
|
apache-2.0
| 6,107 |
/*
* Copyright (c) 2011-14 Miles Sabin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import sbt._
import Keys._
import com.typesafe.sbt.osgi.SbtOsgi._
import sbtbuildinfo.Plugin._
import com.typesafe.sbt.SbtGit._
import GitKeys._
import com.typesafe.tools.mima.plugin.MimaPlugin.mimaDefaultSettings
import com.typesafe.tools.mima.plugin.MimaKeys
import MimaKeys.{previousArtifact, binaryIssueFilters}
object ShapelessBuild extends Build {
lazy val shapeless = (project in file(".")
aggregate (core, examples)
dependsOn (core, examples, scratch)
settings (commonSettings: _*)
settings (
moduleName := "shapeless-root",
(unmanagedSourceDirectories in Compile) := Nil,
(unmanagedSourceDirectories in Test) := Nil,
publish := (),
publishLocal := (),
// Add back mima-report-binary-issues once 2.3.0 final is released
addCommandAlias("validate", ";test;doc")
)
)
lazy val core = (project
settings(
commonSettings ++ Publishing.settings ++ osgiSettings ++
buildInfoSettings ++ mimaDefaultSettings: _*
)
settings(
moduleName := "shapeless",
managedSourceDirectories in Test := Nil,
libraryDependencies ++= Seq(
"org.scala-lang" % "scala-compiler" % scalaVersion.value % "provided",
"org.scala-lang" % "scala-reflect" % scalaVersion.value % "provided",
"com.novocode" % "junit-interface" % "0.7" % "test"
),
(sourceGenerators in Compile) <+= (sourceManaged in Compile) map Boilerplate.gen,
(sourceGenerators in Compile) <+= buildInfo,
mappings in (Compile, packageSrc) <++=
(sourceManaged in Compile, managedSources in Compile) map { (base, srcs) =>
(srcs pair (Path.relativeTo(base) | Path.flat))
},
mappings in (Compile, packageSrc) <++=
(mappings in (Compile, packageSrc) in LocalProject("examples")),
previousArtifact := {
val Some((major, minor)) = CrossVersion.partialVersion(scalaVersion.value)
if (major == 2 && minor == 11)
Some(organization.value %% moduleName.value % "2.3.0")
else
None
},
binaryIssueFilters ++= {
import com.typesafe.tools.mima.core._
import com.typesafe.tools.mima.core.ProblemFilters._
// Filtering the methods that were added since the checked version
// (these only break forward compatibility, not the backward one)
Seq(
ProblemFilters.exclude[MissingMethodProblem]("shapeless.ops.hlist#LowPriorityRotateLeft.hlistRotateLeft"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.ops.hlist#LowPriorityRotateRight.hlistRotateRight"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.ops.coproduct#LowPriorityRotateLeft.coproductRotateLeft"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.ops.coproduct#LowPriorityRotateRight.coproductRotateRight"),
ProblemFilters.exclude[IncompatibleResultTypeProblem]("shapeless.GenericMacros.shapeless$GenericMacros$$mkCoproductCases$1"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.Generic1Macros.shapeless$Generic1Macros$$mkCoproductCases$1"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.SingletonTypeUtils.isValueClass"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.CaseClassMacros.mkHListTypTree"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.CaseClassMacros.reprTypTree"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.CaseClassMacros.mkCompoundTypTree"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.CaseClassMacros.mkCoproductTypTree"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.CaseClassMacros.isAnonOrRefinement"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.CaseClassMacros.mkTypTree"),
ProblemFilters.exclude[MissingMethodProblem]("shapeless.CaseClassMacros.isAccessible"),
ProblemFilters.exclude[IncompatibleMethTypeProblem]("shapeless.ProductMacros.mkProductImpl"),
ProblemFilters.exclude[IncompatibleMethTypeProblem]("shapeless.ProductMacros.forward")
)
},
OsgiKeys.exportPackage := Seq("shapeless.*;version=${Bundle-Version}"),
OsgiKeys.importPackage := Seq("""scala.*;version="$<range;[==,=+);$<@>>""""),
OsgiKeys.additionalHeaders := Map("-removeheaders" -> "Include-Resource,Private-Package"),
buildInfoPackage := "shapeless",
buildInfoKeys := Seq[BuildInfoKey](version, scalaVersion),
buildInfoKeys ++= Seq[BuildInfoKey](
version,
scalaVersion,
gitHeadCommit,
BuildInfoKey.action("buildTime") {
System.currentTimeMillis
}
)
)
)
lazy val scratch = (project
dependsOn core
settings (commonSettings: _*)
settings (
moduleName := "shapeless-scratch",
libraryDependencies ++= Seq(
// needs compiler for `scala.tools.reflect.Eval`
"org.scala-lang" % "scala-compiler" % scalaVersion.value % "provided",
"com.novocode" % "junit-interface" % "0.7" % "test"
),
publish := (),
publishLocal := ()
)
)
lazy val examples = (project
dependsOn core
settings (commonSettings: _*)
settings (
moduleName := "shapeless-examples",
libraryDependencies ++= Seq(
// needs compiler for `scala.tools.reflect.Eval`
"org.scala-lang" % "scala-compiler" % scalaVersion.value % "provided",
"com.novocode" % "junit-interface" % "0.7" % "test"
),
runAllIn(Compile),
publish := (),
publishLocal := ()
)
)
lazy val runAll = TaskKey[Unit]("run-all")
def runAllIn(config: Configuration) = {
runAll in config <<= (discoveredMainClasses in config, runner in run, fullClasspath in config, streams) map {
(classes, runner, cp, s) => classes.foreach(c => runner.run(c, Attributed.data(cp), Seq(), s.log))
}
}
def commonSettings =
Seq(
organization := "com.chuusai",
scalaVersion := "2.11.7",
crossScalaVersions := Seq("2.11.7", "2.12.0-M2"),
(unmanagedSourceDirectories in Compile) <<= (scalaSource in Compile)(Seq(_)),
(unmanagedSourceDirectories in Test) <<= (scalaSource in Test)(Seq(_)),
scalacOptions := Seq(
"-feature",
"-language:higherKinds",
"-language:implicitConversions",
"-Xfatal-warnings",
"-deprecation",
"-unchecked"),
initialCommands in console := """import shapeless._"""
)
}
|
TomasMikula/shapeless
|
project/Build.scala
|
Scala
|
apache-2.0
| 7,298 |
/*
* Copyright (c) 2012-2022 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.iglu.schemaddl.redshift
/**
* column_attributes are:
* [ DEFAULT default_expr ]
* [ IDENTITY ( seed, step ) ]
* [ ENCODE encoding ]
* [ DISTKEY ]
* [ SORTKEY ]
*/
sealed trait ColumnAttribute extends Ddl
case class Default(value: String) extends ColumnAttribute {
def toDdl = s"DEFAULT $value"
}
case class Identity(seed: Int, step: Int) extends ColumnAttribute {
def toDdl = s"IDENTITY ($seed, $step)"
}
case object DistKey extends ColumnAttribute {
def toDdl = "DISTKEY"
}
case object SortKey extends ColumnAttribute {
def toDdl = "SORTKEY"
}
/**
* Compression encodings
* http://docs.aws.amazon.com/redshift/latest/dg/c_Compression_encodings.html
*/
case class CompressionEncoding(value: CompressionEncodingValue) extends ColumnAttribute {
def toDdl = s"ENCODE ${value.toDdl}"
}
sealed trait CompressionEncodingValue extends Ddl
case object RawEncoding extends CompressionEncodingValue { def toDdl = "RAW" }
case object ByteDictEncoding extends CompressionEncodingValue { def toDdl = "BYTEDICT" }
case object DeltaEncoding extends CompressionEncodingValue { def toDdl = "DELTA" }
case object Delta32kEncoding extends CompressionEncodingValue { def toDdl = "DELTA32K" }
case object LzoEncoding extends CompressionEncodingValue { def toDdl = "LZO" }
case object Mostly8Encoding extends CompressionEncodingValue { def toDdl = "MOSTLY8ENCODING" }
case object Mostly16Encoding extends CompressionEncodingValue { def toDdl = "MOSTLY16ENCODING" }
case object Mostly32Encoding extends CompressionEncodingValue { def toDdl = "MOSTLY32ENCODING" }
case object RunLengthEncoding extends CompressionEncodingValue { def toDdl = "RUNLENGTH" }
case object Text255Encoding extends CompressionEncodingValue { def toDdl = "TEXT255" }
case object Text32KEncoding extends CompressionEncodingValue { def toDdl = "TEXT32K" }
case object ZstdEncoding extends CompressionEncodingValue { def toDdl = "ZSTD"}
|
snowplow/schema-ddl
|
modules/core/src/main/scala/com.snowplowanalytics/iglu.schemaddl/redshift/ColumnAttribute.scala
|
Scala
|
apache-2.0
| 2,659 |
package nl.soqua.lcpi.repl.lib
import nl.soqua.lcpi.interpreter.Context
sealed trait TraceModePosition
sealed trait AsciiModeToggle
case object Enabled extends TraceModePosition with AsciiModeToggle
case object Disabled extends TraceModePosition with AsciiModeToggle
object ReplState {
val empty: ReplState = ReplState(CombinatorLibrary.loadIn(Context()), traceMode = Disabled, asciiMode = Disabled,
terminated = false, contextIsMutable = false, List.empty)
}
case class ReplState(context: Context, traceMode: TraceModePosition, asciiMode: AsciiModeToggle, terminated: Boolean,
contextIsMutable: Boolean, reloadableFiles: List[String])
|
kevinvandervlist/lcpi
|
repl/src/main/scala/nl/soqua/lcpi/repl/lib/ReplState.scala
|
Scala
|
mit
| 670 |
package scala.collection.mutable
import scala.collection._
import scala.collection.generic.CanBuildFrom
trait Bag[A]
extends scala.collection.Bag[A]
with mutable.BagLike[A, mutable.Bag[A]]
with generic.GrowableBag[A] {
def update(elem: A, count: Int): this.type = setMultiplicity(elem, count)
def setMultiplicity(elem: A, count: Int): this.type = {
val b = bagConfiguration.newBuilder(elem)
b.add(elem, count)
updateBucket(b.result())
this
}
protected def updateBucket(bucket: mutable.BagBucket[A]): this.type
def add(elem: A, count: Int): this.type = {
this.getBucket(elem) match {
case Some(b) => updateBucket(b add(elem, count))
case None => updateBucket((bagConfiguration.newBuilder(elem) add(elem, count)).result())
}
this
}
def addBucket(bucket: scala.collection.BagBucket[A]): this.type = {
this.getBucket(bucket.sentinel) match {
case Some(b) => updateBucket(b addBucket bucket)
case None => updateBucket((bagConfiguration.newBuilder(bucket.sentinel) addBucket bucket).result())
}
this
}
def -=(elem: A): this.type = this -= (elem -> 1)
def -=(elemCount: (A, Int)): this.type = remove(elemCount._1, elemCount._2)
def remove(elem: A, count: Int): this.type = {
val amount = Math.min(this.multiplicity(elem), count)
if (amount > 0)
this.getBucket(elem) match {
case Some(b) => updateBucket(b.remove(elem, amount))
case None =>
}
this
}
def removeAll(elem: A): this.type = {
this.getBucket(elem) match {
case Some(b) => updateBucket(b.removeAll(elem))
case None =>
}
this
}
}
object Bag extends generic.MutableHashedBagFactory[mutable.Bag] {
implicit def canBuildFrom[A](implicit bagConfiguration: mutable.HashedBagConfiguration[A]): CanBuildFrom[Coll, A, mutable.Bag[A]] = bagCanBuildFrom[A]
def empty[A](implicit bagConfiguration: mutable.HashedBagConfiguration[A]): mutable.Bag[A] = mutable.HashBag.empty[A]
}
|
nicolasstucki/multisets
|
src/main/scala/scala/collection/mutable/Bag.scala
|
Scala
|
bsd-3-clause
| 2,001 |
package pd
// When two players, are matched against each other, they play a series of rounds.
import Tournament._
import scalaz._
import scalaz.std.AllInstances._
import scalaz.syntax.foldable._
case class BattleResult(a: (Player, Score), b: (Player, Score))
trait Rules {
def score(plays: (Play, Play)): (Score, Score) = plays match {
case (Cooperate, Cooperate) => (bothCooperate, bothCooperate)
case (Cooperate, Defect) => (loneCooperator, loneDefector)
case (Defect, Cooperate) => (loneDefector, loneCooperator)
case (Defect, Defect) => (bothDefect, bothDefect)
}
def bothCooperate: Score
def bothDefect: Score
def loneDefector: Score
def loneCooperator: Score
}
trait OneSetOfRules extends Rules {
val bothCooperate = 300
val bothDefect = -300
val loneCooperator = -500
val loneDefector = 500
}
class Battle(numberOfRounds: Int) {
self: Rules =>
def pit(a: Player, b: Player): BattleResult = {
val res = Stream.continually(score(singleRound(a,b))).take(numberOfRounds).concatenate
val (aScore, bScore) = res
a.resetHistory
b.resetHistory
BattleResult((a, aScore), (b, bScore))
}
private def singleRound(a: Player, b:Player): (Play, Play) = {
val bMove = b.play
val aMove = a.play
// ew, a side effect.
a.addToHistory(Round(aMove,bMove))
b.addToHistory( Round(bMove,aMove))
(aMove, bMove)
}
}
object GiantFightOfDoom {
def everybodyFight(players: Seq[Player])(implicit battleConstructor: () => Battle): Map[Player,Score] = {
val battleResults =
for { p1 <- players
p2 <- players
if p1 != p2 }
yield {
battleConstructor().pit(p1,p2)
}
val playerToScores:List[Map[Player,Score]] = battleResults.map(t => Map(t.a, t.b)).toList
playerToScores.concatenate
}
def declareAWinner(scores: Map[Player, Score]): Seq[Player] = {
val MaxScore = scores.map(_._2).max
scores.toSeq.collect{ case(p, MaxScore) => p } // dirty little piece of pattern-matching IMO
}
}
|
marioaquino/prisoners_dilemma
|
src/main/scala/Battle.scala
|
Scala
|
mit
| 2,057 |
/*
* Copyright 2014 Michael Krolikowski
*
* 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.mkroli.dns4s.section.resource
import com.github.mkroli.dns4s._
import com.github.mkroli.dns4s.section.ResourceRecord
import org.scalatest.funspec.AnyFunSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import scala.language.implicitConversions
class NAPTRResourceSpec extends AnyFunSpec with ScalaCheckPropertyChecks {
describe("NAPTRResource") {
describe("validation") {
describe("order") {
it("should fail if it is out of bounds") {
intercept[IllegalArgumentException](NAPTRResource(-1, 0, "", "", "", ""))
intercept[IllegalArgumentException](NAPTRResource(maxInt(16) + 1, 0, "", "", "", ""))
}
it("should not fail if it is within bounds") {
NAPTRResource(0, 0, "", "", "", "")
NAPTRResource(maxInt(16), 0, "", "", "", "")
}
}
describe("preference") {
it("should fail if it is out of bounds") {
intercept[IllegalArgumentException](NAPTRResource(0, -1, "", "", "", ""))
intercept[IllegalArgumentException](NAPTRResource(0, maxInt(16) + 1, "", "", "", ""))
}
it("should not fail if it is within bounds") {
NAPTRResource(0, 0, "", "", "", "")
NAPTRResource(0, maxInt(16), "", "", "", "")
}
}
}
describe("encoding/decoding") {
it("decode(encode(resource)) should be the same as resource") {
forAll(uintGen(16), uintGen(16), csGen, csGen, csGen, dnGen) { (order, preference, flags, services, regexp, replacement) =>
val mr = NAPTRResource(order, preference, flags, services, regexp, replacement)
assert(mr === NAPTRResource(mr(MessageBuffer()).flipped()))
}
}
it("should be decoded wrapped in ResourceRecord") {
val rr = ResourceRecord("test", ResourceRecord.typeNAPTR, 0, 0, NAPTRResource(123, 456, "ABC", "DEF", "GHI", "abc.def.ghi"))
val a = rr(MessageBuffer()).flipped()
val b = bytes("""04 74 65 73 74 00 0023 0000 00000000 001D
00 7B
01 C8
03 41 42 43
03 44 45 46
03 47 48 49
03 61 62 63 03 64 65 66 03 67 68 69 00""")
assert(b === a.getBytes(a.remaining()))
assert(rr === ResourceRecord(MessageBuffer().put(b.toArray).flipped()))
}
}
}
}
|
mkroli/dns4s
|
core/src/test/scala/com/github/mkroli/dns4s/section/resource/NAPTRResourceSpec.scala
|
Scala
|
apache-2.0
| 3,028 |
package com.v_standard.vsp.compiler
import com.v_standard.utils.ResourceUtil.using
import java.io.{ByteArrayOutputStream, File, OutputStreamWriter}
import java.util.Date
import javax.script.{Compilable, CompiledScript, ScriptEngine, ScriptEngineManager}
import scala.io.Source
/**
* ในใฏใชใใใใผใฟใ
*/
case class ScriptData(cscript: Option[CompiledScript], text: Option[String], compileDate: Date, includeFiles: Set[File], debugSource: String)
/**
* ในใฏใชใใใณใณใใคใฉใผใชใใธใงใฏใใ
*/
object ScriptCompiler {
/** ในใฏใชใใใจใณใธใณใใใผใธใฃ */
val engineManager = new ScriptEngineManager()
/** ใณใณใใคใซ็จในใฏใชใใใจใณใธใณ */
val compileEngine = createScriptEngine().asInstanceOf[Compilable]
/**
* ในใฏใชใใใจใณใธใณ็ๆใ
* ๅใใใผใธใฃใใ็ๆใฎใใ GLOBAL_SCOPE ใๅใใ
*
* @return ในใฏใชใใใจใณใธใณ
*/
def createScriptEngine(): ScriptEngine = engineManager.getEngineByName("JavaScript")
/**
* ๅคๆใ
*
* @param source ใใณใใฌใผใใฝใผใน
* @param config ใใผใฏใณ่งฃๆ่จญๅฎ
* @param deep ๆทฑใ
* @return ในใฏใชใใใใผใฟ
*/
def compile(source: Source, config: TokenParseConfig): ScriptData = {
var debugSource = ""
var includeFiles = Set.empty[File]
try {
val (script, textOnly, incFiles) = ScriptConverter.convert(source, config)
debugSource = using(Source.fromString(script)) { r =>
var count = 0
val sb = new StringBuilder("\\n")
r.getLines.foreach { l =>
count += 1
sb.append("%04d".format(count)).append(": ").append(l).append("\\n")
}
sb.toString
}
includeFiles = incFiles.toSet
val cscript = compileEngine.compile(script)
if (textOnly) {
val out = new ByteArrayOutputStream()
val context = createScriptEngine().getContext()
context.setWriter(new OutputStreamWriter(out))
cscript.eval(context)
ScriptData(None, Option(out.toString()), new Date(), includeFiles, debugSource)
}
else ScriptData(Option(cscript), None, new Date(), includeFiles, debugSource)
} catch {
case e: Exception =>
ScriptData(None, Option(e.getMessage + debugSource), new Date(), includeFiles, debugSource)
}
}
}
|
VanishStandard/vsp
|
src/main/scala/com/v_standard/vsp/compiler/ScriptCompiler.scala
|
Scala
|
bsd-3-clause
| 2,262 |
package com.frontier45
/**
* Created by du on 4/6/16.
*/
package object sparktemplate {
val appName = "SparkTemplate"
case class RunArgs(
fname: String = "",
out: String = "",
spark_master: Option[String] = None,
n_partitions: Int = 1
)
}
|
lucidfrontier45/SparkTemplate
|
src/main/scala/com/frontier45/sparktemplate/package.scala
|
Scala
|
mit
| 268 |
/**
* ยฉ 2019 Refinitiv. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the โLicenseโ); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an โAS ISโ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmwell.tools.data.downloader
import akka.stream.scaladsl._
import akka.util.{ByteString, ByteStringBuilder}
import cmwell.tools.data.utils.akka._
import cmwell.tools.data.utils.chunkers.GroupChunker
import cmwell.tools.data.utils.logging.DataToolsLogging
import scala.collection.mutable
object DataPostProcessor extends DataToolsLogging {
def postProcessByFormat(format: String, dataBytes: Source[ByteString, _]) = format match {
case "ntriples" | "nquads" => sortBySubjectOfNTuple(dataBytes)
case _ => splitByLines(dataBytes)
}
private def splitByLines(dataBytes: Source[ByteString, _]) = {
dataBytes
.via(lineSeparatorFrame)
.map(_ ++ endl)
}
private def sortBySubjectOfNTuple(dataBytes: Source[ByteString, _]): Source[ByteString, _] = {
dataBytes
.via(lineSeparatorFrame)
.filter {
case line if line.startsWith("_") =>
badDataLogger.debug("was filtered: {}", line.utf8String)
false
case _ => true
}
.fold(mutable.Map.empty[ByteString, ByteStringBuilder]) { (agg, line) =>
// aggregate each line according to its subject (i.e., bucket)
val subject = GroupChunker.extractSubject(line)
val builder = agg.getOrElse(subject, new ByteStringBuilder)
builder ++= (line ++ endl)
agg + (subject -> builder)
}
.map(_.toMap)
.mapConcat(_.map { case (_, ntupleBuilder) => ntupleBuilder.result })
}
}
|
dudi3001/CM-Well
|
server/cmwell-data-tools/src/main/scala/cmwell/tools/data/downloader/DataPostProcessor.scala
|
Scala
|
apache-2.0
| 2,107 |
package org.flowpaint.raster.tile
/**
*
*/
object TileService {
// Tilesize of 1 << 6 == 64
val tileWidthShift = 6
val tileHeightShift = 6
val tileWidth = 1 << tileWidthShift
val tileHeight = 1 << tileHeightShift
val tilePixels: Int = tileWidth * tileHeight
def tileIdForLocation(canvasX: Int, canvasY: Int): TileId = TileId.forLocation(canvasX, canvasY)
// TODO: Implement tile pooling
def allocateDataTile(): DataTile = new DataTile()
def freeDataTile(tile: DataTile) = {}
def allocateDataTile(sourceTile: Tile): DataTile = {
val newTile = allocateDataTile()
sourceTile match {
case dataTile: DataTile =>
newTile.copyDataFrom(dataTile)
case valueTile: SingleValueTile =>
val v = valueTile.value
var i = newTile.data.length - 1
while (i >= 0) {
newTile.data(i) = v
i -= 1
}
}
newTile
}
}
|
zzorn/flowpaint
|
src/main/scala/org/flowpaint/raster/tile/TileService.scala
|
Scala
|
gpl-2.0
| 913 |
/*
* Copyright 2014 - 2015 SlamData Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package slamdata.engine.std
import slamdata.Predef._
import scalaz._
import slamdata.engine.{Func, LogicalPlan, Type, SemanticError}
import slamdata.engine.analysis.fixplate._
import slamdata.engine.fp._
import Validation.{success, failure}
trait Library {
protected val noSimplification: Func.Simplifier = ฮบ(None)
protected def partialSimplifier(
f: PartialFunction[List[Term[LogicalPlan]], Term[LogicalPlan]]):
Func.Simplifier =
f.lift
protected def constTyper(codomain: Type): Func.Typer = { args =>
Validation.success(codomain)
}
private def partialTyperOV(f: List[Type] => Option[ValidationNel[SemanticError, Type]]):
Func.Typer = {
args =>
f(args).getOrElse(Validation.failure(NonEmptyList(SemanticError.GenericError("Unknown arguments: " + args))))
}
protected def partialTyperV(f: PartialFunction[List[Type], ValidationNel[SemanticError, Type]]):
Func.Typer =
partialTyperOV(f.lift)
protected def partialTyper(f: PartialFunction[List[Type], Type]): Func.Typer =
partialTyperOV(f.lift(_).map(success))
private def partialUntyperOV(codomain: Type)(f: Type => Option[ValidationNel[SemanticError, List[Type]]]):
Func.Untyper = rez => {
f(rez).getOrElse(failure(NonEmptyList(SemanticError.TypeError(codomain, rez, None))))
}
protected def partialUntyperV(
codomain: Type)(
f: PartialFunction[Type, ValidationNel[SemanticError, List[Type]]]):
Func.Untyper =
partialUntyperOV(codomain)(f.lift)
protected def partialUntyper(
codomain: Type)(
f: PartialFunction[Type, List[Type]]):
Func.Untyper =
partialUntyperOV(codomain)(f.lift(_).map(success))
protected def reflexiveTyper: Func.Typer = {
case Type.Const(data) :: Nil => success(data.dataType)
case x :: Nil => success(x)
case _ => failure(NonEmptyList(SemanticError.GenericError("Wrong number of arguments for reflexive typer")))
}
protected val numericWidening = {
def mapFirst[A, B](f: A => A, p: PartialFunction[A, B]) = new PartialFunction[A, B] {
def isDefinedAt(a: A) = p.isDefinedAt(f(a))
def apply(a: A) = p(f(a))
}
val half: PartialFunction[List[Type], Type] = {
case t1 :: t2 :: Nil if t1 contains t2 => t1
case Type.Dec :: t2 :: Nil if Type.Int contains t2 => Type.Dec
case Type.Int :: t2 :: Nil if Type.Dec contains t2 => Type.Dec
}
partialTyper(half orElse mapFirst[List[Type], Type](_.reverse, half))
}
protected implicit class TyperW(self: Func.Typer) {
def ||| (that: Func.Typer): Func.Typer = { args =>
self(args) ||| that(args)
}
}
def functions: List[Func]
}
|
wemrysi/quasar
|
core/src/main/scala/slamdata/engine/std/library.scala
|
Scala
|
apache-2.0
| 3,274 |
/*
* Copyright (C) 2016-2019 Lightbend Inc. <https://www.lightbend.com>
*/
package com.lightbend.lagom.internal.testkit
import java.nio.file.Files
import java.util.concurrent.TimeUnit
import akka.persistence.cassandra.testkit.CassandraLauncher
import com.google.common.io.MoreFiles
import com.google.common.io.RecursiveDeleteOption
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
import scala.util.Try
private[lagom] object CassandraTestServer {
private val LagomTestConfigResource: String = "lagom-test-embedded-cassandra.yaml"
private lazy val log = Logger(getClass)
def run(cassandraDirectoryPrefix: String, lifecycle: ApplicationLifecycle): Int = {
val cassandraPort = CassandraLauncher.randomPort
val cassandraDirectory = Files.createTempDirectory(cassandraDirectoryPrefix)
// Shut down Cassandra and delete its temporary directory when the application shuts down
lifecycle.addStopHook { () =>
import scala.concurrent.ExecutionContext.Implicits.global
Try(CassandraLauncher.stop())
// The ALLOW_INSECURE option is required to remove the files on OSes that don't support SecureDirectoryStream
// See http://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/io/MoreFiles.html#deleteRecursively-java.nio.file.Path-com.google.common.io.RecursiveDeleteOption...-
Future(MoreFiles.deleteRecursively(cassandraDirectory, RecursiveDeleteOption.ALLOW_INSECURE))
}
val t0 = System.nanoTime()
CassandraLauncher.start(
cassandraDirectory.toFile,
LagomTestConfigResource,
clean = false,
port = cassandraPort,
CassandraLauncher.classpathForResources(LagomTestConfigResource)
)
log.debug(s"Cassandra started in ${TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t0)} ms")
cassandraPort
}
}
|
rcavalcanti/lagom
|
testkit/core/src/main/scala/com/lightbend/lagom/internal/testkit/CassandraTestServer.scala
|
Scala
|
apache-2.0
| 1,879 |
/*
* Copyright 2013 - 2020 Outworkers 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 com.outworkers.phantom.builder.query
import com.outworkers.phantom.CassandraTable
import com.outworkers.phantom.builder._
import com.outworkers.phantom.builder.query.execution.ExecutableCqlQuery
import com.outworkers.phantom.connectors.SessionAugmenterImplicits
abstract class RootQuery[
Table <: CassandraTable[Table, _],
Record,
Status <: ConsistencyBound
] extends SessionAugmenterImplicits {
def queryString: String = executableQuery.qb.terminate.queryString
def executableQuery: ExecutableCqlQuery
}
trait Batchable {
def executableQuery: ExecutableCqlQuery
}
|
outworkers/phantom
|
phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/Query.scala
|
Scala
|
apache-2.0
| 1,196 |
/*
* Copyright 2021 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.kythe.analyzers.scala
import com.google.devtools.kythe.proto.Schema.{
EdgeKind,
FactName,
NodeKind,
Subkind
}
import com.google.devtools.kythe.util.schema.Schema
import scala.tools.nsc
import scala.tools.nsc.{Global, Phase}
import scala.tools.nsc.plugins.{Plugin, PluginComponent}
/**
* Plugin for the scalac compiler that generates kythe data
*/
class Kythe(val global: Global) extends Plugin with AddSigs {
import global._
val name = "kythe"
val description = "Emits kythe data in json format"
val components = List[PluginComponent](NamedComponent)
// If the user sets an output directory then write json files to that directory.
// Otherwise write protos to stdout
var OUT_DIR = sys.env.get("KYTHE_OUTPUT_DIRECTORY").getOrElse("index")
/**
* Main interface for defining a compiler plugin component.
*
* @see http://www.scala-lang.org/old/node/140
*/
private object NamedComponent extends PluginComponent {
val global: Kythe.this.global.type = Kythe.this.global
val runsAfter = List[String]("refchecks");
val phaseName = Kythe.this.name
// TODO(rbraunstein): find the right way to write this in scala
// if (OUT_DIR == "-") ProtoEmitter[global.type](global) else JsonEmitter[global.type](global)
val emitter = ProtoEmitter[global.type](global)
def newPhase(_prev: Phase) = new KythePhase(_prev)
class KythePhase(prev: Phase) extends StdPhase(prev) {
override def name = Kythe.this.name
def apply(unit: CompilationUnit): Unit = processUnit(unit)
// TODO(rbraunstein): do we ever get called for java units (class files?)
def processUnit(unit: CompilationUnit) =
if (!unit.isJava) processScalaUnit(unit)
def processScalaUnit(unit: CompilationUnit): Unit = {
emitter.init(unit.source.file, OUT_DIR)
val fileVName =
emitter.emitFileFacts(unit.source.file.path, unit.source.content)
DefinitionTraverser(fileVName).apply(unit.body)
emitter.flush
}
/**
* Determine the kythe node kind for the tree
*/
private def kytheType(tree: Tree): NodeKind = tree match {
case _: ModuleDef => NodeKind.FUNCTION
case _: ClassDef => NodeKind.RECORD
case _: ValDef => NodeKind.VARIABLE
case _: DefDef =>
if (tree.symbol.accessedOrSelf.isMethod) NodeKind.FUNCTION
else NodeKind.VARIABLE
case _: PackageDef =>
NodeKind.PACKAGE // TODO(rbraunstein): fix packages
}
/**
* Determine if a Def exists in source code or if it is generated.
* Most generated methods have the Synthetic flag on the symbol.
* The one exception I found so far is <init>
* I've special cased for the name "<init>" until we find a better solution.
* TODO(rbraunstein): We may be able to get rid of this now.
*/
private def isNotGeneratedDef(tree: Tree) =
!tree.symbol.isSynthetic && tree.symbol.nameString != "<init>"
/**
* Emit the right subkinds and facts for variables nodes.
* i.e. is it a 'param' or a 'field.
* And write the ChildOf or Param edge back to its owner.
*/
private def emitVariableExtras(tree: ValOrDefDef): Unit = {
val vName = emitter.nodeVName(
generateSignature(tree.symbol),
tree.pos.source.file.path
)
val symbol = tree.symbol.accessedOrSelf
if (symbol.hasFlag(scala.reflect.internal.Flags.LOCAL)) {
emitter.emitFact(
vName,
FactName.SUBKIND,
Schema.subkindString(Subkind.FIELD)
)
emitter.emitEdge(
vName,
EdgeKind.CHILD_OF,
emitter.nodeVName(
generateSignature(symbol.owner),
tree.pos.source.file.path
)
)
} else if (symbol.isParameter) {
emitter.emitFact(
vName,
FactName.SUBKIND,
Schema.subkindString(Subkind.LOCAL_PARAMETER)
)
emitter.emitParamEdge(
emitter.nodeVName(
generateSignature(symbol.owner),
tree.pos.source.file.path
),
vName,
tree.symbol.paramPos
)
} else
emitter.emitFact(
vName,
FactName.SUBKIND,
Schema.subkindString(Subkind.LOCAL)
)
}
/**
* For the current variable, method, class, param, etc. definition, emit an edge to its type.
* If the type is a compound type, we only point to the parent type
* In the type visitor, we create the compound type
* For compound types, we should emit a 'typed' edge from the given symbol defintion to a
* 'tapp' node.
* We should also emit a name node for tapp, which might already exist.
*
* Given the example:
* var foo: Map[String, List[String]]
*
* We want to write that the type of foo is the Node
* "Map[String,List[String]"
*
* That Node has kind Tapp
* has [named] edge to name: "java.util.Map[java.lang.String,java.util.List[java.lang.String]]
* has param edges to:
* Map [abs]
* String [tbuiltin]
* List [tapp]
*
* For method definitions, its type is a tuple of:
* |function|
* return type
* parameter types.
*
* Given the example:
* var foo: Integer
*
* The type is simply "builtin#Integer"
*
* For the example:
* var foo: MyClass
* The type points to the record for MyClass.
*
* NOTE that we will emit type nodes multiple times.
* For the example:
* val s: Map[String, List[String]]
* val t: Map[String, List[String]]
* We will emit the tapp node and its subgraph for "Map[String, List[String]]" twice.
*/
private def emitTypeEdgesForDefinition(
tree: Tree,
sourceNode: emitter.NODE
): Unit = {
tree match {
// method, macro
// TODO(rbraunstein): implement method types, this is just anchors
case defdef: DefDef =>
emitAnchorForType(
defdef,
makeNodeForType(defdef.tpt.tpe, tree.pos.source.file.path)
)
// vals, vars, params
case vd: ValDef =>
emitTypeEdgesForVariable(vd, sourceNode, tree.pos.source.file.path)
// classes, traits
case _: ClassDef =>
emitTypeEdgesForClassDef(
tree.symbol,
sourceNode,
tree.pos.source.file.path
)
// object
// TODO(rbraunstein): verify that objects have the correct type
// especially when extending a class.
case _: ModuleDef => ()
// packages have no types
case _: PackageDef => ()
}
}
/*
* The location of the type is no longer stored in the current tree.
* We need to look at the original tree.
*/
private def emitAnchorForType(
tree: ValOrDefDef,
typeNode: emitter.NODE
): Unit = {
tree.tpt match {
case tt: TypeTree =>
if (tt.original != null)
emitter.emitAnchor(tt.original, EdgeKind.REF)
case _ => ()
}
}
/**
* Given a Type, make a VName for it.
* It should be either:
* - a tapp node
* - a tbuiltin
* - the vname for a class node
* - an absvar node)
*
* NOTE: If its a tapp node, we make the new node and construct the subgraph too.
* If not tapp node, just return the vname for the type. Assume someone else created it.
*/
private def makeNodeForType(
symbolType: Type,
path: String
): emitter.NODE = {
// Tapp nodes need to be created in case they don't exist
if (symbolType.typeArguments.nonEmpty) {
val varTypeNode =
emitter.nodeVName(makeSigForTappNode(symbolType), path)
emitter.emitNodeKind(varTypeNode, NodeKind.TAPP)
emitTappSubGraph(varTypeNode, symbolType, path)
varTypeNode
} else {
val varTypeNode =
emitter.nodeVName(generateSignature(symbolType.typeSymbol), path)
// primitive and class nodes should already exist, just return the VName of the type.
emitter.emitNodeKind(
varTypeNode,
if (symbolType.typeSymbol.isPrimitiveValueClass) NodeKind.TBUILTIN
else if (symbolType.typeSymbol.isTypeParameter) NodeKind.ABSVAR
else NodeKind.RECORD
)
varTypeNode
}
}
/**
* Recursively emit a tapp type.
* For Map[String, List[String]]
* The initial tapp node has three params.
* The first is the abs type (Map)
* The next params are the top level types: String (primitive), List[String]: (tapp)
*
* We need to:
* create vnames for each param,
* emit edges from this tapp to each param
* recursively visit any tapp node (creating new node as well)
*/
def emitTappSubGraph(
typeNode: emitter.NODE,
thisType: Type,
path: String
): Unit = {
// monomorphic
if (thisType.typeArguments.isEmpty) {
val rootVName =
emitter.nodeVName(generateSignature(thisType.typeSymbol), path)
emitter.emitNodeKind(rootVName, NodeKind.RECORD)
emitter.emitParamEdge(typeNode, rootVName, 0)
} else {
// polymorphic
val rootVName = emitter.nodeVName(makeAbsSig(thisType), path)
emitter.emitNodeKind(rootVName, NodeKind.ABS)
emitter.emitParamEdge(typeNode, rootVName, 0)
}
for ((typeArg, index) <- thisType.typeArguments.zipWithIndex) {
emitter.emitParamEdge(
typeNode,
makeNodeForType(typeArg, path),
index + 1
)
}
}
/**
* Decide if the type is complex or simple by checking typeArguments.
* If complex, emit a tapp node and its subgraph
* If simple, emit a type edge to the primitive or class node.
*/
private def emitTypeEdgesForVariable(
valdef: ValDef,
sourceNode: emitter.NODE,
path: String
): Unit = {
// TODO(rbraunstein): look for aliases and try typeSymbolDirect instead o typeSymbol
val typeNode = makeNodeForType(valdef.symbol.typeOfThis, path)
emitter.emitEdge(sourceNode, EdgeKind.TYPED, typeNode)
emitAnchorForType(valdef, typeNode)
}
/**
* If a class is not parameterized, there is nothing to do.
* If a class is parameterized, then we need to create a NodeKind.Abs tree.
* i.e. for List[A]:
* emit Abs node for List[A]
* emit Absvar node for A
* Link them with param.x edge
*/
private def emitTypeEdgesForClassDef(
symbol: Symbol,
sourceNode: emitter.NODE,
path: String
): Unit = {
if (!symbol.isMonomorphicType) {
val symbolType = symbol.typeOfThis
val classTypeNode = emitter.nodeVName(makeAbsSig(symbolType), path)
emitter.emitNodeKind(classTypeNode, NodeKind.ABS)
emitter.emitEdge(sourceNode, EdgeKind.CHILD_OF, classTypeNode)
for ((typeParam, index) <- symbol.typeParams.zipWithIndex) {
val paramVName =
emitter.nodeVName(generateSignature(typeParam), path)
emitter.emitNodeKind(paramVName, NodeKind.ABSVAR)
emitter.emitParamEdge(classTypeNode, paramVName, index)
}
}
}
/**
* Abs nodes should have signature that is distinct from the class node signature.
* Specifically, we try and add the param argument names, i.e. "List[A]", not "List"
*/
def makeAbsSig(symbolType: Type) =
s"scala_type:${symbolType.typeSymbol.typeOfThis.toLongString}"
/**
* Main interface for traversing the scala ast.
*/
private case class DefinitionTraverser(fileNode: emitter.NODE)
extends Traverser {
// Always traverse the whole tree, but only emit anchors (links)
// when we aren't somewhere beneath a synthetic scope.
var isInsideSyntheticMethod = false
var kytheScopeNode = fileNode
/*
* For the class, emit extends edges to any classes, interfaces or traits it
* directly implements.
*/
def emitExtendsEdges(
tree: global.Tree,
classVName: emitter.NODE
): Unit =
for (parent <- tree.symbol.parentSymbols)
emitter.emitEdge(
classVName,
EdgeKind.EXTENDS,
emitter.nodeVName(
generateSignature(parent),
tree.pos.source.file.path
)
)
/*
* If this method overrides one in the parent class or trait, emit an override edges.
* If it overrides some other ancestor, emit an override/transitive edge
*/
def emitMethodOverrides(
tree: global.Tree,
methodVName: emitter.NODE
): Unit = {
// If this class has traits, and this method is in those traits, it should
// be an override
val directParentClasses = tree.symbol.owner.parentSymbols
for (orig <- tree.symbol.allOverriddenSymbols)
if (orig != tree.symbol) // first member is self, need to ignore it.
emitter.emitEdge(
methodVName,
if (directParentClasses.contains(orig.owner)) EdgeKind.OVERRIDES
else EdgeKind.OVERRIDES_TRANSITIVE,
emitter.nodeVName(
generateSignature(orig),
tree.pos.source.file.path
)
)
}
def withTraversalState[T](work: => T): Unit = {
val oldSyntheticState = isInsideSyntheticMethod
val oldScopeNode = kytheScopeNode
try {
work
} catch {
// Don't let an exception break the whole compile
case e: Exception => {
e.printStackTrace()
emitter.emitFact(fileNode, FactName.MESSAGE, e.toString)
}
} finally {
isInsideSyntheticMethod = oldSyntheticState
kytheScopeNode = oldScopeNode
}
}
override def traverse(tree: Tree): Unit = withTraversalState {
tree match {
// defs and decls
case _: LabelDef => () // n/a
case _: TypeDef =>
emitter.emitAnchor(tree, EdgeKind.DEFINES_BINDING)
case _: Bind => () // Ignore, causes problems for DefTree below
case _: DefTree if (!tree.symbol.isAnonymousFunction) => {
// Common for all Defs
val vName = emitter.nodeVName(
generateSignature(tree.symbol),
tree.pos.source.file.path
)
kytheScopeNode = vName
val kind = kytheType(tree)
emitter.emitNodeKind(vName, kind)
emitNameNode(tree, vName)
emitTypeEdgesForDefinition(tree, vName)
// emit anchors if we aren't in synthetic methods
if (isNotGeneratedDef(tree) && !isInsideSyntheticMethod) {
emitter.emitAnchor(tree, EdgeKind.DEFINES_BINDING)
if (
tree.symbol
.isInstanceOf[ModuleSymbol] && !tree.symbol.hasPackageFlag
) {
emitter.emitAnchor(
tree,
tree.symbol.tpe.typeSymbol,
EdgeKind.DEFINES_BINDING
)
}
if (
!tree.symbol.hasFlag(
nsc.symtab.Flags.PACKAGE | nsc.symtab.Flags.MODULE
)
)
emitter.emitAnchor(tree, EdgeKind.DEFINES)
} else isInsideSyntheticMethod = true
// Extra edges for each Def type
tree match {
case _: ClassDef => emitExtendsEdges(tree, vName)
case defdef: DefDef => {
if (tree.symbol.accessedOrSelf.isVariable)
emitVariableExtras(defdef)
emitMethodOverrides(defdef, vName)
}
case vd: ValDef => emitVariableExtras(vd)
case _: ModuleDef => ()
case _: PackageDef => ()
}
}
// edges for calls
case Apply(sym, t) => {
// don't emit Call edges for calls to implicit set routines.
if (!sym.symbol.isSetter) {
val anchor = emitRef(tree, EdgeKind.REF_CALL)
if (anchor.isDefined)
emitter.emitEdge(
anchor.get,
EdgeKind.CHILD_OF,
kytheScopeNode
)
}
}
// refs to fields, methods
case _: Select => emitRef(tree, EdgeKind.REF)
// We don't get AppliedTypeTrees unless we follow the 'original' tree in TypeTree
case tt: TypeTree =>
if (tt.original.isInstanceOf[AppliedTypeTree])
traverse(tt.original)
case AppliedTypeTree(tpt, args) =>
emitRef(tpt, EdgeKind.REF)
for (arg <- args) {
emitRef(arg, EdgeKind.REF)
traverse(arg)
}
case _: Ident => emitRef(tree, EdgeKind.REF)
case TypeApply(_, args) =>
for (arg <- args) {
emitRef(arg, EdgeKind.REF)
}
case _ => ()
}
super.traverse(tree)
}
/**
* Helper func for emitting anchors.
* Does extra work to prevent references that aren't explicit in the original code.
*
* @return anchor node if available
*/
def emitRef(tree: Tree, edgeKind: EdgeKind): Option[emitter.NODE] = {
// Labels are weird.
// For Packages we have trouble finding original binding.
if (
isNotGeneratedDef(tree)
&& !tree.symbol.isLabel
&& !tree.symbol.isPackageObjectOrClass
) {
// For java, emit xrefs to name nodes, not VNames.
emitter.emitAnchor(tree, edgeKind)
} else None
}
// All definition nodes have a 'name' node as well. For scala, it looks like
// Try and use a mirror to generate the name instead of fullNameString. That
// should help with overloads.
// NOTE: It is perfectly reasonable to not emit names for locals and params.
def emitNameNode(tree: Tree, vName: emitter.NODE) = {
val nodeVName = emitter.nodeVName(
tree.symbol.fullNameString,
""
)
emitter.emitNodeKind(nodeVName, NodeKind.NAME)
emitter.emitEdge(vName, EdgeKind.NAMED, nodeVName)
}
}
}
}
}
/* *
* Add a main to make debugging in intellij easier.
* This simply calls the normal scalac main and passes
* the plugin jar as an option.
*
* You still need to setup the run configuration.
* The two main thigs to set are:
* 1) Program options, set the glob of files to analyze
* 2) CLASSPATH env variable.
* CLASSPATH=$SCALA_HOME/lib/akka-actor_2.11-2.3.10.jar:$SCALA_HOME/lib/config-1.2.1.jar:$SCALA_HOME/lib/java_indexer.jar:$SCALA_HOME/lib/jline-2.12.1.jar:$SCALA_HOME/lib/scala-actors-2.11.0.jar:$SCALA_HOME/lib/scala-actors-migration_2.11-1.1.0.jar:$SCALA_HOME/lib/scala-compiler.jar:$SCALA_HOME/lib/scala-continuations-library_2.11-1.0.2.jar:$SCALA_HOME/lib/scala-continuations-plugin_2.11.8-1.0.2.jar:$SCALA_HOME/lib/scala-library.jar:$SCALA_HOME/lib/scalap-2.11.8.jar:$SCALA_HOME/lib/scala-parser-combinators_2.11-1.0.4.jar:$SCALA_HOME/lib/scala-reflect.jar:$SCALA_HOME/lib/scala-swing_2.11-1.0.2.jar:$SCALA_HOME/lib/scala-xml_2.11-1.0.4.jar
* */
object ScalacWrapper extends scala.tools.nsc.Driver {
override def newCompiler(): Global = {
var s = settings.copy()
// You have to create a .jar file with scalac-plugin.xml in it.
// But it doesn't need any .class files.
val myArgs = List("-Xplugin:kythe/scala/com/google/devtools/kythe/analyzers/scala/kythe-plugin.jar", "-Yrangepos")
s.processArguments(myArgs, true) match {
case (false, rest) => {
println("error processing arguments (unprocessed: %s)".format(rest))
}
case _ => println("read args okay")
}
Global(s, reporter)
}
}
|
kythe/kythe-contrib
|
kythe/scala/com/google/devtools/kythe/analyzers/scala/KythePlugin.scala
|
Scala
|
apache-2.0
| 21,870 |
package io.getquill.context.sql
import java.util.{ Date, UUID }
import scala.BigDecimal
import io.getquill.Spec
case class EncodingTestType(value: String)
trait EncodingSpec extends Spec {
val context: SqlContext[_, _]
import context._
case class EncodingTestEntity(
v1: String,
v2: BigDecimal,
v3: Boolean,
v4: Byte,
v5: Short,
v6: Int,
v7: Long,
v8: Float,
v9: Double,
v10: Array[Byte],
v11: Date,
v12: EncodingTestType,
o1: Option[String],
o2: Option[BigDecimal],
o3: Option[Boolean],
o4: Option[Byte],
o5: Option[Short],
o6: Option[Int],
o7: Option[Long],
o8: Option[Float],
o9: Option[Double],
o10: Option[Array[Byte]],
o11: Option[Date],
o12: Option[EncodingTestType]
)
val delete = quote {
query[EncodingTestEntity].delete
}
val insert = quote {
(e: EncodingTestEntity) => query[EncodingTestEntity].insert(e)
}
val insertValues =
List(
EncodingTestEntity(
"s",
BigDecimal(1.1),
true,
11.toByte,
23.toShort,
33,
431L,
34.4f,
42d,
Array(1.toByte, 2.toByte),
new Date(31200000),
EncodingTestType("s"),
Some("s"),
Some(BigDecimal(1.1)),
Some(true),
Some(11.toByte),
Some(23.toShort),
Some(33),
Some(431L),
Some(34.4f),
Some(42d),
Some(Array(1.toByte, 2.toByte)),
Some(new Date(31200000)),
Some(EncodingTestType("s"))
),
EncodingTestEntity(
"",
BigDecimal(0),
false,
0.toByte,
0.toShort,
0,
0L,
0F,
0D,
Array(),
new Date(0),
EncodingTestType(""),
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None
)
)
def verify(result: List[EncodingTestEntity]) =
result match {
case List(e1, e2) =>
e1.v1 mustEqual "s"
e1.v2 mustEqual BigDecimal(1.1)
e1.v3 mustEqual true
e1.v4 mustEqual 11.toByte
e1.v5 mustEqual 23.toShort
e1.v6 mustEqual 33
e1.v7 mustEqual 431L
e1.v8 mustEqual 34.4f
e1.v9 mustEqual 42d
e1.v10.toList mustEqual List(1.toByte, 2.toByte)
e1.v11 mustEqual new Date(31200000)
e1.v12 mustEqual EncodingTestType("s")
e1.o1 mustEqual Some("s")
e1.o2 mustEqual Some(BigDecimal(1.1))
e1.o3 mustEqual Some(true)
e1.o4 mustEqual Some(11.toByte)
e1.o5 mustEqual Some(23.toShort)
e1.o6 mustEqual Some(33)
e1.o7 mustEqual Some(431L)
e1.o8 mustEqual Some(34.4f)
e1.o9 mustEqual Some(42d)
e1.o10.map(_.toList) mustEqual Some(List(1.toByte, 2.toByte))
e1.o11 mustEqual Some(new Date(31200000))
e1.o12 mustEqual Some(EncodingTestType("s"))
e2.v1 mustEqual ""
e2.v2 mustEqual BigDecimal(0)
e2.v3 mustEqual false
e2.v4 mustEqual 0.toByte
e2.v5 mustEqual 0.toShort
e2.v6 mustEqual 0
e2.v7 mustEqual 0L
e2.v8 mustEqual 0f
e2.v9 mustEqual 0d
e2.v10.toList mustEqual Nil
e2.v11 mustEqual new Date(0)
e2.v12 mustEqual EncodingTestType("")
e2.o1 mustEqual None
e2.o2 mustEqual None
e2.o3 mustEqual None
e2.o4 mustEqual None
e2.o5 mustEqual None
e2.o6 mustEqual None
e2.o7 mustEqual None
e2.o8 mustEqual None
e2.o9 mustEqual None
e2.o10 mustEqual None
e2.o11 mustEqual None
e2.o12 mustEqual None
}
case class BarCode(description: String, uuid: Option[UUID] = None)
val insertBarCode = quote((b: BarCode) => query[BarCode].insert(b).returning(_.uuid))
val barCodeEntry = BarCode("returning UUID")
def findBarCodeByUuid(uuid: UUID)(implicit enc: Encoder[UUID]) = quote(query[BarCode].filter(_.uuid == lift(Option(uuid))))
def verifyBarcode(barCode: BarCode) = barCode.description mustEqual "returning UUID"
}
|
jcranky/quill
|
quill-sql/src/test/scala/io/getquill/context/sql/EncodingSpec.scala
|
Scala
|
apache-2.0
| 4,193 |
/** MACHINE-GENERATED FROM AVRO SCHEMA. DO NOT EDIT DIRECTLY */
package test
import scala.annotation.switch
/**
* Auto-Generated Schema
* @param name Auto-Generated Field
*/
case class Pet(var name: String) extends org.apache.avro.specific.SpecificRecordBase {
def this() = this("")
def get(field$: Int): AnyRef = {
(field$: @switch) match {
case 0 => {
name
}.asInstanceOf[AnyRef]
case _ => new org.apache.avro.AvroRuntimeException("Bad index")
}
}
def put(field$: Int, value: Any): Unit = {
(field$: @switch) match {
case 0 => this.name = {
value.toString
}.asInstanceOf[String]
case _ => new org.apache.avro.AvroRuntimeException("Bad index")
}
()
}
def getSchema: org.apache.avro.Schema = Pet.SCHEMA$
}
object Pet {
val SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\\"type\\":\\"record\\",\\"name\\":\\"Pet\\",\\"namespace\\":\\"test\\",\\"doc\\":\\"Auto-Generated Schema\\",\\"fields\\":[{\\"name\\":\\"name\\",\\"type\\":\\"string\\",\\"doc\\":\\"Auto-Generated Field\\"}]}")
}
|
julianpeeters/avrohugger
|
avrohugger-core/src/test/expected/schemagen/test/Pet.scala
|
Scala
|
apache-2.0
| 1,053 |
/*
* Copyright (C) 2014-2015 Really Inc. <http://really.io>
*/
package io.really.gorilla
import akka.actor.Props
import akka.testkit.{ EventFilter, TestProbe, TestActorRef }
import com.typesafe.config.ConfigFactory
import io.really._
import _root_.io.really.Request.SubscribeOnObjects
import _root_.io.really.gorilla.SubscriptionManager.{ SubscriptionDone, SubscribeOnR }
import _root_.io.really.protocol.{ SubscriptionFailure, SubscriptionBody, SubscriptionOp }
import _root_.io.really.Result.SubscribeResult
import _root_.io.really.protocol.SubscriptionOpResult
import scala.concurrent.duration._
class SubscribeAggregatorSpec(config: ReallyConfig) extends BaseActorSpec(config) {
def this() = this(new ReallyConfig(ConfigFactory.parseString("""
really.core.gorilla.wait-for-subscriptions-aggregation = 1s
really.core.akka.loggers = ["akka.testkit.TestEventListener"],
really.core.akka.loglevel = WARNING
""").withFallback(TestConf.getConfig().getRawConfig)))
val r1 = R / 'users / 201
val r2 = R / 'users / 202
val r3 = R / 'users / 203
val r4 = R / 'users / 204
val r5 = R / 'users / 205
"Subscribe Aggregator" should "respond to the WrappedSubscribe correctly only once request then dies" in {
val probe = TestProbe()
val manager = TestActorRef[WorkingSubscriptionManagerMock](Props(new WorkingSubscriptionManagerMock(globals)))
val pushChannel = TestProbe()
val delegate = TestProbe()
val body = SubscriptionBody(List(SubscriptionOp(r1, 1)))
val rSub = SubscribeOnObjects(ctx, body, pushChannel.ref)
val aggregator = TestActorRef[SubscribeAggregator](Props(new SubscribeAggregator(rSub, delegate.ref, manager,
globals)))
probe.watch(aggregator)
delegate.expectMsg(SubscribeResult(Set(SubscriptionOpResult(r1, body.subscriptions(0).fields))))
probe.expectTerminated(aggregator)
}
it should "respond to client with only succeeded subscriptions" in {
val manager = TestActorRef[WorkingSubscriptionManagerMock](Props(new HalfWorkingSubscriptionManagerMock(globals)))
val pushChannel = TestProbe()
val delegate = TestProbe()
val body = SubscriptionBody(List(SubscriptionOp(r1, 1), SubscriptionOp(r2, 1), SubscriptionOp(r3, 1),
SubscriptionOp(r4, 1), SubscriptionOp(r5, 1)))
val rSub = SubscribeOnObjects(ctx, body, pushChannel.ref)
TestActorRef[SubscribeAggregator](Props(new SubscribeAggregator(rSub, delegate.ref, manager,
globals)))
delegate.expectMsg(SubscribeResult(Set(
SubscriptionOpResult(r2, body.subscriptions(0).fields),
SubscriptionOpResult(r4, body.subscriptions(1).fields)
)))
}
it should "return empty response if the Subscription back-end is failing the requests" in {
val manager = TestActorRef[WorkingSubscriptionManagerMock](Props(new DisabledSubscriptionManagerMock(globals)))
val pushChannel = TestProbe()
val delegate = TestProbe()
val body = SubscriptionBody(List(SubscriptionOp(r1, 1), SubscriptionOp(r2, 1), SubscriptionOp(r3, 1),
SubscriptionOp(r4, 1), SubscriptionOp(r5, 1)))
val rSub = SubscribeOnObjects(ctx, body, pushChannel.ref)
TestActorRef[SubscribeAggregator](Props(new SubscribeAggregator(rSub, delegate.ref, manager, globals)))
delegate.expectMsg(SubscribeResult(Set.empty))
}
it should "return empty response if the Subscription back-end is unresponsive after Timeout" in {
val manager = TestActorRef[WorkingSubscriptionManagerMock](Props(new UnresponsiveSubscriptionManagerMock(globals)))
val pushChannel = TestProbe()
val delegate = TestProbe()
val body = SubscriptionBody(List(SubscriptionOp(r1, 1), SubscriptionOp(r2, 1), SubscriptionOp(r3, 1),
SubscriptionOp(r4, 1), SubscriptionOp(r5, 1)))
val rSub = SubscribeOnObjects(ctx, body, pushChannel.ref)
EventFilter.warning(
message = s"Subscribe Aggregator timed out while waiting the subscriptions to be fulfilled for requester:" +
s" ${delegate.ref}",
occurrences = 1
).intercept {
TestActorRef[SubscribeAggregator](Props(new SubscribeAggregator(rSub, delegate.ref, manager, globals)))
}
delegate.expectMsg(SubscribeResult(Set.empty))
}
}
class WorkingSubscriptionManagerMock(globals: ReallyGlobals) extends SubscriptionManager(globals) {
override def receive = {
case SubscribeOnR(subData) =>
sender() ! SubscriptionDone(subData.r)
}
}
class HalfWorkingSubscriptionManagerMock(globals: ReallyGlobals) extends SubscriptionManager(globals) {
var counter = 0
override def receive = {
case SubscribeOnR(subData) =>
counter += 1
if (counter % 2 == 0)
sender() ! SubscriptionDone(subData.r)
else
sender() ! SubscriptionFailure(subData.r, 500, "Mocked Failure")
}
}
class DisabledSubscriptionManagerMock(globals: ReallyGlobals) extends SubscriptionManager(globals) {
override def receive = {
case SubscribeOnR(subData) =>
sender() ! SubscriptionFailure(subData.r, 500, "Mocked Failure")
}
}
class UnresponsiveSubscriptionManagerMock(globals: ReallyGlobals) extends SubscriptionManager(globals) {
override def receive = {
case SubscribeOnR(subData) =>
}
}
|
reallylabs/really
|
modules/really-core/src/test/scala/io/really/gorilla/SubscribeAggregatorSpec.scala
|
Scala
|
apache-2.0
| 5,252 |
/*
* Copyright (C) 2005, The Beangle Software.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.beangle.commons {
package object lang {
type JLong = java.lang.Long
type JDouble = java.lang.Double
type JFloat = java.lang.Double
type JInt = java.lang.Integer
type JShort = java.lang.Short
type JByte = java.lang.Byte
type JBoolean = java.lang.Boolean
type JChar = java.lang.Character
}
}
|
beangle/commons
|
core/src/main/scala/org/beangle/commons/lang/types.scala
|
Scala
|
lgpl-3.0
| 1,059 |
package edu.gemini.seqexec.server
import java.util.concurrent.{ScheduledExecutorService, ScheduledThreadPoolExecutor}
import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
import scalaz._
import Scalaz._
import edu.gemini.pot.sp.SPObservationID
import edu.gemini.seqexec.server.Executor._
import edu.gemini.seqexec.server.SeqexecFailure._
import edu.gemini.spModel.config2.{Config, ConfigSequence, ItemKey}
import edu.gemini.spModel.obscomp.InstConstants.INSTRUMENT_NAME_PROP
import edu.gemini.spModel.seqcomp.SeqConfigNames.INSTRUMENT_KEY
import scalaz.concurrent.Task
/** An executor that maintains state in a pair of `TaskRef`s. */
class ExecutorImpl private (cancelRef: TaskRef[Set[SPObservationID]], stateRef: TaskRef[Map[SPObservationID, Executor.ExecState]]) {
private def recordState(id: SPObservationID)(s: ExecState): Task[Unit] =
stateRef.modify(_ + (id -> s))
private def go(id: SPObservationID): Task[Boolean] =
cancelRef.get.map(!_(id))
private def initialExecState(sequenceConfig: ConfigSequence): ExecState =
ExecState.initial(sequenceConfig.getAllSteps.toList.map(Step.step))
// todo: it is an error to run a sequence with an existing ExecState != s
private def runSeq(id: SPObservationID, s: ExecState): Task[(ExecState, NonEmptyList[SeqexecFailure] \\/ Unit)] =
cancelRef.modify(_ - id) *> recordState(id)(s) *> run(go(id), recordState(id))(s)
def start(id: SPObservationID, sequenceConfig: ConfigSequence): Task[(ExecState, NonEmptyList[SeqexecFailure] \\/ Unit)] =
runSeq(id, initialExecState(sequenceConfig))
def continue(id: SPObservationID): Task[(Option[ExecState], NonEmptyList[SeqexecFailure] \\/ Unit)] =
getState(id) >>= {
case -\\/(e) => Task.now((None, NonEmptyList(e).left))
case \\/-(s) => runSeq(id, s).map(_.leftMap(_.some))
}
def getState(id: SPObservationID): Task[SeqexecFailure \\/ ExecState] =
stateRef.get.map(_.get(id) \\/> InvalidOp("Sequence has not started."))
def stop(id: SPObservationID): Task[SeqexecFailure \\/ Unit] =
getState(id) >>= {
case \\/-(s) => cancelRef.modify(s => s + id).as(\\/-(()))
case -\\/(e) => Task.now(-\\/(e))
}
def stateDescription(state: ExecState): String = {
"Completed " + state.completed.length + " steps out of " + (state.completed.length + state.remaining.length) +
( state.completed.zipWithIndex.map(a => (a._1, a._2+1)) map {
case (Ok(StepResult(_,ObserveResult(label))), idx) => s"Step $idx completed with label $label"
case (Failed(result), idx) => s"Step $idx failed with error " + result.map(SeqexecFailure.explain).toList.mkString("\\n", "\\n", "")
case (Skipped, idx) => s"Step $idx skipped"
}
).mkString("\\n", "\\n", "")
}
}
object ExecutorImpl {
def newInstance: Task[ExecutorImpl] =
for {
cancel <- TaskRef.newTaskRef[Set[SPObservationID]](Set.empty)
state <- TaskRef.newTaskRef[Map[SPObservationID, Executor.ExecState]](Map.empty)
} yield new ExecutorImpl(cancel, state)
}
|
arturog8m/ocs
|
bundle/edu.gemini.seqexec.server/src/main/scala/edu/gemini/seqexec/server/ExecutorImpl.scala
|
Scala
|
bsd-3-clause
| 3,043 |
package io.github.binaryfoo.lagotto
import org.joda.time.DateTime
import scala.collection.mutable
case class JstackLogEntry(private val _fields: mutable.LinkedHashMap[String, String], private val timeFormat: Option[TimeExpr] = None, lines: String, source: SourceRef = null) extends LogEntry {
val timestamp: DateTime = {
timeFormat.map { case TimeExpr(expr, formatter) =>
_fields.get(expr)
.map(formatter.parseDateTime)
.getOrElse(throw new IAmSorryDave(s"Missing 'timestamp' in ${_fields}"))
}.orNull
}
private val Frame = """frame\\((\\d+)\\)""".r
val fields = _fields.withDefault {
case "depth" => frames.length.toString
case Frame(Index(index)) if index < frames.length => frames(index).replaceFirst("\\\\s*at ", "")
case _ => null
}
lazy val frames: Array[String] = {
lines.split('\\n').filter(_.trim.startsWith("at "))
}
def apply(id: String) = fields(id)
override def exportAsSeq: Seq[(String, String)] = _fields.toSeq
}
private object Index {
def unapply(s: String): Option[Int] = Some(s.toInt)
}
|
binaryfoo/lagotto
|
src/main/scala/io/github/binaryfoo/lagotto/JstackLogEntry.scala
|
Scala
|
mit
| 1,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 com.bwsw.sj.engine.core.testutils.benchmark.loader.tstreams
import com.bwsw.sj.engine.core.testutils.benchmark.loader.BenchmarkDataSenderParameters
/**
* Contains parameters of data that sends into T-Streams
*
* @param transactionSize count of messages per transaction
* @param messageSize size of one message
* @param messagesCount count of messages
* @author Pavel Tomskikh
*/
case class TStreamsBenchmarkDataSenderParameters(transactionSize: Long, messageSize: Long, messagesCount: Long)
extends BenchmarkDataSenderParameters {
override def toSeq: Seq[Any] = Seq(transactionSize, messageSize, messagesCount)
}
|
bwsw/sj-platform
|
core/sj-engine-core/src/main/scala/com/bwsw/sj/engine/core/testutils/benchmark/loader/tstreams/TStreamsBenchmarkDataSenderParameters.scala
|
Scala
|
apache-2.0
| 1,456 |
/*start*/"aB".groupBy(_.isUpper)/*end*/
//Map[Boolean, String]
|
LPTK/intellij-scala
|
testdata/typeInference/bugs/SCL2123.scala
|
Scala
|
apache-2.0
| 62 |
/* sbt -- Simple Build Tool
* Copyright 2010 Mark Harrah
*/
package xsbt.api
import Predef.{implicitly => ??, _}
import sbt.Using
import xsbti.api._
import sbinary._
import DefaultProtocol._
import java.io.File
import scala.collection.mutable
trait FormatExtra
{
def p2[A,B,R](unapply: R => (A,B))( apply: (A,B) => R)(implicit fa: Format[A], fb: Format[B]): Format[R] =
asProduct2(apply)(unapply)(fa, fb)
def p3[A,B,C,R](unapply: R => (A,B,C))( apply: (A,B,C) => R)(implicit fa: Format[A], fb: Format[B], fc: Format[C]): Format[R] =
asProduct3(apply)(unapply)(fa, fb, fc)
def p4[A,B,C,D,R](unapply: R => (A,B,C,D))( apply: (A,B,C,D) => R)(implicit fa: Format[A], fb: Format[B], fc: Format[C], fd: Format[D]): Format[R] =
asProduct4(apply)(unapply)(fa, fb, fc, fd)
def p5[A,B,C,D,E,R](unapply: R => (A,B,C,D,E))( apply: (A,B,C,D,E) => R)(implicit fa: Format[A], fb: Format[B], fc: Format[C], fd: Format[D], fe: Format[E]): Format[R] =
asProduct5(apply)(unapply)(fa, fb, fc, fd, fe)
def p6[A,B,C,D,E,F,R](unapply: R => (A,B,C,D,E,F))( apply: (A,B,C,D,E,F) => R)(implicit fa: Format[A], fb: Format[B], fc: Format[C], fd: Format[D], fe: Format[E], ff: Format[F]): Format[R] =
asProduct6(apply)(unapply)(fa, fb, fc, fd, fe, ff)
def p7[A,B,C,D,E,F,G,R](unapply: R => (A,B,C,D,E,F,G))( apply: (A,B,C,D,E,F,G) => R)(implicit fa: Format[A], fb: Format[B], fc: Format[C], fd: Format[D], fe: Format[E], ff: Format[F], fg: Format[G]): Format[R] =
asProduct7(apply)(unapply)(fa, fb, fc, fd, fe, ff, fg)
def p8[A,B,C,D,E,F,G,H,R](unapply: R => (A,B,C,D,E,F,G,H))( apply: (A,B,C,D,E,F,G,H) => R)(implicit fa: Format[A], fb: Format[B], fc: Format[C], fd: Format[D], fe: Format[E], ff: Format[F], fg: Format[G], fh: Format[H]): Format[R] =
asProduct8(apply)(unapply)(fa, fb, fc, fd, fe, ff, fg, fh)
}
trait APIFormats extends FormatExtra
{
implicit def formatStructure(implicit fi: Format[Int], references: References): Format[Structure] =
wrap(references.id, references.structure)
implicit def formatClassLike(implicit fi: Format[Int], references: References): Format[ClassLike] =
wrap(references.id, references.classLike)
// cyclic with formatSuper, so it is not implicit by default
def formatPath(implicit pc: Format[Array[PathComponent]]): Format[Path] =
wrap[Path, Array[PathComponent]]( _.components, x => new Path(x))(pc)
implicit def formatComponent(implicit t: Format[This], s: Format[Super], i: Format[Id]): Format[PathComponent] =
asUnion(t, s, i)
def formatSuper(implicit p: Format[Path]): Format[Super] =
wrap[Super, Path](_.qualifier, q => new Super(q))(p)
implicit def formatId(implicit s: Format[String]): Format[Id] =
wrap[Id, String](_.id, i => new Id(i))(s)
implicit val formatThis: Format[This] = asSingleton(new This)
implicit def formatSource(implicit pa: Format[Array[Package]], da: Format[Array[Definition]]): Format[SourceAPI] =
p2( (s: SourceAPI) => (s.packages, s.definitions))( (p, d) => new SourceAPI(p, d) )(pa, da)
implicit def formatAnnotated(implicit t: Format[Type], as: Format[Array[Annotation]]): Format[Annotated] =
p2( (a: Annotated) => (a.baseType,a.annotations))(new Annotated(_,_))(t,as)
implicit def formatPolymorphic(implicit t: Format[Type], tps: Format[Array[TypeParameter]]): Format[Polymorphic] =
p2( (p: Polymorphic) => (p.baseType, p.parameters) )( new Polymorphic(_,_) )(t, tps)
implicit def formatConstant(implicit t: Format[Type], fs: Format[String]): Format[Constant] =
p2( (c: Constant) => (c.baseType, c.value) )( new Constant(_,_) )(t,fs)
implicit def formatExistential(implicit t: Format[Type], tps: Format[Array[TypeParameter]]): Format[Existential] =
p2( (e: Existential) => (e.baseType, e.clause) )( new Existential(_,_) )(t,tps)
implicit def formatParameterRef(implicit i: Format[String]): Format[ParameterRef] =
wrap[ParameterRef, String](_.id, new ParameterRef(_))(i)
// cyclic with many formats
def formatType(implicit s: Format[SimpleType], a: Format[Annotated], st: Format[Structure], e: Format[Existential], po: Format[Polymorphic]): Format[Type] =
asUnion(s, a, st, e, po)
implicit def formatDef(implicit acs: Format[Access], ms: Format[Modifiers], ans: Format[Array[Annotation]], tp: Format[Array[TypeParameter]], vp: Format[Array[ParameterList]], t: Format[Type], fs: Format[String]): Format[Def] =
p7( (d: Def) => (d.valueParameters, d.returnType, d.typeParameters, d.name, d.access, d.modifiers, d.annotations))( new Def(_,_,_,_,_,_,_) )(vp, t, tp, fs, acs, ms, ans)
implicit def formatVal(implicit acs: Format[Access], ms: Format[Modifiers], ans: Format[Array[Annotation]], t: Format[Type], ts: Format[String]): Format[Val] =
fieldLike( new Val(_,_,_,_,_) )(acs, ms, ans, ts, t)
implicit def formatVar(implicit acs: Format[Access], ms: Format[Modifiers], ans: Format[Array[Annotation]], t: Format[Type], ts: Format[String]): Format[Var] =
fieldLike( new Var(_,_,_,_,_) )(acs, ms, ans, ts, t)
def fieldLike[F <: FieldLike](construct: (Type, String, Access, Modifiers, Array[Annotation]) => F)(implicit acs: Format[Access], ms: Format[Modifiers], ans: Format[Array[Annotation]], nme: Format[String], tpe: Format[Type]): Format[F] =
asProduct5(construct)( d => (d.tpe, d.name, d.access, d.modifiers, d.annotations))(tpe, nme, acs, ms, ans)
def formatDefinition(implicit vl: Format[Val], vr: Format[Var], ds: Format[Def], cl: Format[ClassLike], ta: Format[TypeAlias], td: Format[TypeDeclaration]): Format[Definition] =
asUnion(vl, vr, ds, cl, ta, td)
def formatSimpleType(implicit pr: Format[Projection], pa: Format[ParameterRef], si: Format[Singleton], et: Format[EmptyType], p: Format[Parameterized]): Format[SimpleType] =
asUnion(pr, pa, si, et, p)
implicit def formatEmptyType: Format[EmptyType] = asSingleton(new EmptyType)
implicit def formatSingleton(implicit p: Format[Path]): Format[Singleton] = wrap[Singleton, Path](_.path, new Singleton(_))
def formatProjection(implicit t: Format[SimpleType], s: Format[String]): Format[Projection] =
p2( (p: Projection) => (p.prefix, p.id))(new Projection(_,_))(t, s)
def formatParameterized(implicit t: Format[SimpleType], tps: Format[Array[Type]]): Format[Parameterized] =
p2( (p: Parameterized) => (p.baseType, p.typeArguments))(new Parameterized(_,_))(t, tps)
implicit def formatTypeAlias(implicit acs: Format[Access], ms: Format[Modifiers], ans: Format[Array[Annotation]], tps: Format[Array[TypeParameter]], t: Format[Type], n: Format[String]): Format[TypeAlias] =
p6( (ta: TypeAlias) => (ta.tpe, ta.typeParameters, ta.name, ta.access, ta.modifiers, ta.annotations))( new TypeAlias(_,_,_,_,_,_) )(t, tps, n, acs, ms, ans)
implicit def formatTypeDeclaration(implicit acs: Format[Access], ms: Format[Modifiers], ans: Format[Array[Annotation]], tps: Format[Array[TypeParameter]], t: Format[Type], n: Format[String]): Format[TypeDeclaration] =
p7( (td: TypeDeclaration) => (td.lowerBound, td.upperBound, td.typeParameters, td.name, td.access, td.modifiers, td.annotations))( new TypeDeclaration(_,_,_,_,_,_,_))(t,t,tps,n,acs,ms,ans)
// cyclic with SimpleType
def formatAnnotation(implicit t: Format[Type], af: Format[Array[AnnotationArgument]]): Format[Annotation] =
p2( (a: Annotation) => (a.base, a.arguments) )( (a,b) => new Annotation(a,b) )(t, af)
implicit def formatAnnotationArgument(implicit sf: Format[String]): Format[AnnotationArgument] =
p2( (aa: AnnotationArgument) => (aa.name, aa.value))( (a,b) => new AnnotationArgument(a,b))(sf, sf)
implicit def formatVariance(implicit b: Format[Byte]): Format[Variance] =
wrap[Variance, Byte]( v => v.ordinal.toByte, b => Variance.values.apply(b.toInt) )(b)
implicit def formatDefinitionType(implicit b: Format[Byte]): Format[DefinitionType] =
wrap[DefinitionType, Byte]( dt => dt.ordinal.toByte, b => DefinitionType.values.apply(b.toInt) )(b)
implicit def formatPackage(implicit fs: Format[String]): Format[Package] =
wrap[Package, String]( _.name, n => new Package(n) )(fs)
implicit def formatAccess(implicit fs: Format[String]): Format[Access] =
new Format[Access]
{
val unqualified = new Unqualified
val ths = new ThisQualifier
val public = new Public
val privateUn = new Private(unqualified)
val protectedUn = new Protected(unqualified)
val privateThis = new Private(ths)
val protectedThis = new Protected(ths)
def reads(in: Input): Access =
{
def qualifier() = new IdQualifier(fs.reads(in))
import AccessIDs._
AccessIDs(in.readByte) match
{
case PublicID => public
case PrivateID => privateUn
case ProtectedID => protectedUn
case PrivateThisID => privateThis
case ProtectedThisID => protectedThis
case QPrivateID => new Private(qualifier())
case QProtectedID => new Protected(qualifier())
}
}
def writes(out: Output, a: Access)
{
import AccessIDs._
def w(id: AccessIDs.Value) = out.writeByte(id.id.toByte)
def qualified(un: Value, ths: Value, qual: Value, qualifier: Qualifier): Unit =
qualifier match
{
case _: Unqualified => w(un)
case _: ThisQualifier => w(ths)
case i: IdQualifier => w(qual); fs.writes(out, i.value)
}
a match
{
case _: Public => w(PublicID)
case q: Qualified => q match {
case p: Private => qualified(PrivateID, PrivateThisID, QPrivateID, p.qualifier)
case p: Protected => qualified(ProtectedID, ProtectedThisID, QProtectedID, p.qualifier)
}
}
}
}
import APIUtil._
implicit def formatModifiers(implicit bf: Format[Byte]): Format[Modifiers] =
wrap[Modifiers, Byte]( modifiersToByte, byteToModifiers )
def formatTypeParameter(tps: Format[TypeParameter] => Format[Array[TypeParameter]])(implicit as: Format[Array[Annotation]], t: Format[Type], v: Format[Variance], i: Format[String]): Format[TypeParameter] =
{
lazy val ltps: Format[Array[TypeParameter]] = lazyFormat( tps(ltp) )
lazy val ltp = p6( (tp: TypeParameter) => (tp.id, tp.annotations, tp.typeParameters, tp.variance, tp.lowerBound, tp.upperBound))(new TypeParameter(_,_,_,_,_,_))(i, as, ltps, v, t, t)
ltp
}
implicit def formatParameterList(implicit mp: Format[Array[MethodParameter]], bf: Format[Boolean]): Format[ParameterList] =
p2( (pl: ParameterList) => (pl.parameters, pl.isImplicit) )( (ps, impl) => new ParameterList(ps, impl) )
implicit def formatMethodParameter(implicit s: Format[String], b: Format[Boolean], m: Format[ParameterModifier], t: Format[Type]): Format[MethodParameter] =
p4( (mp: MethodParameter) => (mp.name, mp.tpe, mp.hasDefault, mp.modifier) )( new MethodParameter(_,_,_,_) )(s,t,b,m)
implicit def formatParameterModifier(implicit bf: Format[Byte]): Format[ParameterModifier] =
wrap[ParameterModifier, Byte]( dt => dt.ordinal.toByte, b => ParameterModifier.values.apply(b.toInt) )(bf)
}
private object AccessIDs extends Enumeration
{
val PublicID, PrivateID, ProtectedID, QPrivateID, QProtectedID, PrivateThisID, ProtectedThisID = Value
}
// construct a concrete Format[Source], handling cycles
// ?? (Predef.implicitly) is used for implicits the compiler should infer
class DefaultAPIFormats(implicit val references: References) extends APIFormats
{
import sbinary.DefaultProtocol._
implicit lazy val tpf: Format[TypeParameter] = formatTypeParameter(array)
// SimpleType is cyclic with Projection and Parameterized
implicit lazy val stf: Format[SimpleType] = lazyFormat(formatSimpleType(projf, ??, ??, ??, paramf))
// Type is cyclic with a lot, including SimpleType and TypeParameter
implicit lazy val tf: Format[Type] = lazyFormat( formatType(stf, ??, ??, ??, ??) )
implicit lazy val df: Format[Definition] = lazyFormat( formatDefinition )
// Projection, Annotation, and Parameterized are cyclic with SimpleType
// Parameterized and Annotation are also cyclic with Type
implicit lazy val projf: Format[Projection] = formatProjection(stf, ??)
implicit lazy val af: Format[Annotation] = formatAnnotation(tf, ??)
implicit lazy val paramf: Format[Parameterized] = formatParameterized(stf, array(tf))
// Super and Path are cyclic
implicit lazy val sf: Format[Super] = lazyFormat(formatSuper(pathf))
implicit lazy val pathf: Format[Path] = formatPath
implicit val srcFormat: Format[SourceAPI] = formatSource(??, array(df))
private[this] def array[T](format: Format[T])(implicit mf: Manifest[T]): Format[Array[T]] = arrayFormat(format, mf)
}
|
harrah/xsbt
|
compile/persist/src/main/scala/xsbt/api/APIFormats.scala
|
Scala
|
bsd-3-clause
| 12,407 |
package rspactors.vocab
import rdftools.rdf.Vocab
import rdftools.rdf._
import rdftools.rdf.RdfTools._
object LDP extends Vocab {
override val iri: Iri = "http://www.w3.org/ns/ldp#"
val Page = clazz("Page")
val PageSortCriterion = clazz("PageSortCriterion")
val IndirectContainer = clazz("IndirectContainer")
val DirectContainer = clazz("DirectContainer")
val BasicContainer = clazz("BasicContainer")
val Container = clazz("Container")
val NonRDFSource = clazz("NonRDFSource")
val RDFSource = clazz("RDFSource")
val Resource = clazz("Resource")
val constrainedBy = prop("constrainedBy")
val hasMemberRelation = prop("hasMemberRelation")
val pageSortCollation = prop("pageSortCollation")
val contains = prop("contains")
val insertedContentRelation = prop("insertedContentRelation")
val pageSortCriteria = prop("pageSortCriteria")
val inbox = prop("inbox")
val membershipResource = prop("membershipResource")
val pageSequence = prop("pageSequence")
val member = prop("member")
val isMemberOfRelation = prop("isMemberOfRelation")
val pageSortPredicate = prop("pageSortPredicate")
val pageSortOrder = prop("pageSortOrder")
}
|
jpcik/ldn-streams
|
src/main/scala/rspactors/vocab/LDP.scala
|
Scala
|
mit
| 1,170 |
package org.sgine.ui
import android.os.Bundle
import com.badlogic.gdx.backends.android.{AndroidApplicationConfiguration, AndroidApplication}
/**
* @author Matt Hicks <[email protected]>
*/
class ImageTestActivity extends AndroidApplication {
override def onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
val config = new AndroidApplicationConfiguration()
config.useWakelock = true
initialize(ImageExample.applicationListener, config)
}
}
|
Axiometry/sgine
|
ui/example/src/main/scala/org/sgine/ui/ImageTestActivity.scala
|
Scala
|
bsd-3-clause
| 488 |
/*
* 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.optimizer
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan}
import org.apache.spark.sql.catalyst.rules.Rule
/**
* This rule ensures that [[Aggregate]] nodes contain all required [[GroupingExprRef]]
* references for optimization phase.
*/
object EnforceGroupingReferencesInAggregates extends Rule[LogicalPlan] {
override def apply(plan: LogicalPlan): LogicalPlan = {
plan transform {
case a: Aggregate =>
Aggregate.withGroupingRefs(a.groupingExpressions, a.aggregateExpressions, a.child)
}
}
}
|
BryanCutler/spark
|
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/EnforceGroupingReferencesInAggregates.scala
|
Scala
|
apache-2.0
| 1,390 |
package org.bitcoins.server
import akka.actor.ActorSystem
import com.typesafe.config.{Config, ConfigFactory}
import grizzled.slf4j.Logging
import org.bitcoins.chain.config.ChainAppConfig
import org.bitcoins.commons.config.{AppConfig, ConfigOps}
import org.bitcoins.commons.util.ServerArgParser
import org.bitcoins.core.config.NetworkParameters
import org.bitcoins.core.util.{StartStopAsync, TimeUtil}
import org.bitcoins.dlc.node.config.DLCNodeAppConfig
import org.bitcoins.dlc.wallet.DLCAppConfig
import org.bitcoins.keymanager.config.KeyManagerAppConfig
import org.bitcoins.node.config.NodeAppConfig
import org.bitcoins.rpc.config.BitcoindRpcAppConfig
import org.bitcoins.tor.config.TorAppConfig
import org.bitcoins.wallet.config.WalletAppConfig
import java.nio.file.{Files, Path, Paths}
import java.util.concurrent.TimeUnit
import scala.concurrent.Future
import scala.concurrent.duration.{DurationInt, FiniteDuration}
/** A unified config class for all submodules of Bitcoin-S
* that accepts configuration. Thanks to implicit definitions
* in this case class' companion object an instance
* of this class can be passed in anywhere a wallet,
* chain or node config is required.
*
* @param directory The data directory of this app configuration
* @param confs A sequence of optional configuration overrides
*/
case class BitcoinSAppConfig(
baseDatadir: Path,
configOverrides: Vector[Config])(implicit system: ActorSystem)
extends StartStopAsync[Unit]
with Logging {
import system.dispatcher
lazy val walletConf: WalletAppConfig =
WalletAppConfig(baseDatadir, configOverrides)
lazy val nodeConf: NodeAppConfig = NodeAppConfig(baseDatadir, configOverrides)
lazy val chainConf: ChainAppConfig =
ChainAppConfig(baseDatadir, configOverrides)
lazy val dlcConf: DLCAppConfig = DLCAppConfig(baseDatadir, configOverrides)
lazy val torConf: TorAppConfig =
TorAppConfig(baseDatadir, None, configOverrides)
lazy val dlcNodeConf: DLCNodeAppConfig =
DLCNodeAppConfig(baseDatadir, configOverrides)
def copyWithConfig(newConfs: Vector[Config]): BitcoinSAppConfig = {
val configs = newConfs ++ configOverrides
BitcoinSAppConfig(baseDatadir, configs)
}
lazy val kmConf: KeyManagerAppConfig =
KeyManagerAppConfig(baseDatadir, configOverrides)
lazy val bitcoindRpcConf: BitcoindRpcAppConfig =
BitcoindRpcAppConfig(baseDatadir, configOverrides)
lazy val network: NetworkParameters = chainConf.network
/** Initializes the wallet, node and chain projects */
override def start(): Future[Unit] = {
val start = TimeUtil.currentEpochMs
//configurations that don't depend on tor startup
//start these in parallel as an optimization
val nonTorConfigs = Vector(kmConf, chainConf, walletConf)
val torConfig = torConf.start()
val torDependentConfigs = Vector(nodeConf, bitcoindRpcConf, dlcConf)
val startedTorDependentConfigsF = for {
_ <- torConfig
_ <- Future.sequence(torDependentConfigs.map(_.start()))
} yield ()
val startedNonTorConfigs = Future.sequence(nonTorConfigs.map(_.start()))
for {
_ <- startedNonTorConfigs
_ <- startedTorDependentConfigsF
} yield {
logger.info(
s"Done starting BitcoinSAppConfig, it took=${TimeUtil.currentEpochMs - start}ms")
()
}
}
override def stop(): Future[Unit] = {
for {
_ <- nodeConf.stop()
_ <- walletConf.stop()
_ <- chainConf.stop()
_ <- bitcoindRpcConf.stop()
_ <- torConf.stop()
} yield ()
}
/** The underlying config the result of our fields derive from */
lazy val config: Config = {
val finalConfig =
AppConfig.getBaseConfig(baseDatadir = baseDatadir, configOverrides)
val resolved = finalConfig.resolve()
resolved.checkValid(ConfigFactory.defaultReference(), "bitcoin-s")
resolved
}
def rpcPort: Int = config.getInt("bitcoin-s.server.rpcport")
def wsPort: Int = config.getIntOrElse("bitcoin-s.server.wsport", 19999)
/** How long until we forcefully terminate connections to the server
* when shutting down the server
*/
def terminationDeadline: FiniteDuration = {
val opt = config.getDurationOpt("bitcoin-s.server.termination-deadline")
opt match {
case Some(duration) =>
if (duration.isFinite) {
new FiniteDuration(duration.toNanos, TimeUnit.NANOSECONDS)
} else {
sys.error(
s"Can only have a finite duration for termination deadline, got=$duration")
}
case None => 5.seconds //5 seconds by default
}
}
def rpcBindOpt: Option[String] = {
if (config.hasPath("bitcoin-s.server.rpcbind")) {
Some(config.getString("bitcoin-s.server.rpcbind"))
} else {
None
}
}
def wsBindOpt: Option[String] = {
if (config.hasPath("bitcoin-s.server.wsbind")) {
Some(config.getString("bitcoin-s.server.wsbind"))
} else {
None
}
}
def rpcPassword: String = config.getString("bitcoin-s.server.password")
def exists(): Boolean = {
baseDatadir.resolve("bitcoin-s.conf").toFile.isFile
}
def withOverrides(configs: Vector[Config]): BitcoinSAppConfig = {
BitcoinSAppConfig(baseDatadir, configs ++ configOverrides)
}
}
/** Implicit conversions that allow a unified configuration
* to be passed in wherever a specializes one is required
*/
object BitcoinSAppConfig extends Logging {
def fromConfig(config: Config)(implicit
system: ActorSystem): BitcoinSAppConfig = {
val configDataDir: Path = Paths.get(config.getString("bitcoin-s.datadir"))
BitcoinSAppConfig(configDataDir, Vector(config))
}
def fromClassPathConfig()(implicit system: ActorSystem): BitcoinSAppConfig = {
fromConfig(ConfigFactory.load())
}
def fromDatadir(datadir: Path, confs: Config*)(implicit
system: ActorSystem): BitcoinSAppConfig = {
BitcoinSAppConfig(datadir, confs.toVector)
}
def fromDatadirWithServerArgs(
datadir: Path,
serverArgsParser: ServerArgParser)(implicit
system: ActorSystem): BitcoinSAppConfig = {
fromDatadir(datadir, serverArgsParser.toConfig)
}
/** Constructs an app configuration from the default Bitcoin-S
* data directory and given list of configuration overrides.
*/
def fromDefaultDatadir(confs: Config*)(implicit
system: ActorSystem): BitcoinSAppConfig =
BitcoinSAppConfig(AppConfig.DEFAULT_BITCOIN_S_DATADIR, confs.toVector)
def fromDefaultDatadirWithBundleConf(confs: Vector[Config] = Vector.empty)(
implicit system: ActorSystem): BitcoinSAppConfig = {
fromDatadirWithBundleConf(AppConfig.DEFAULT_BITCOIN_S_DATADIR, confs)
}
def fromDatadirWithBundleConf(
datadir: Path,
confs: Vector[Config] = Vector.empty)(implicit
system: ActorSystem): BitcoinSAppConfig = {
val baseConf: BitcoinSAppConfig =
fromDatadir(datadir, confs: _*)
// Grab saved bundle config
val bundleConfFile =
toChainConf(baseConf).baseDatadir.resolve("bitcoin-s-bundle.conf")
val extraConfig = if (Files.isReadable(bundleConfFile)) {
ConfigFactory.parseFile(bundleConfFile.toFile)
} else {
logger.debug("No saved bundle config found")
ConfigFactory.empty()
}
baseConf.copyWithConfig(extraConfig +: confs)
}
/** Resolve BitcoinSAppConfig in the following order of precedence
* 1. Server args
* 2. bitcoin-s-bundle.conf
* 3. bitcoin-s.conf
* 4. application.conf
* 5. reference.conf
*/
def fromDatadirWithBundleConfWithServerArgs(
datadir: Path,
serverArgParser: ServerArgParser)(implicit
system: ActorSystem): BitcoinSAppConfig = {
fromDatadirWithBundleConf(datadir, Vector(serverArgParser.toConfig))
}
/** Creates a BitcoinSAppConfig the the given daemon args to a server */
def fromDefaultDatadirWithServerArgs(serverArgParser: ServerArgParser)(
implicit system: ActorSystem): BitcoinSAppConfig = {
val config = serverArgParser.toConfig
fromConfig(config)
}
/** Converts the given config to a wallet config */
def toWalletConf(conf: BitcoinSAppConfig): WalletAppConfig = {
conf.walletConf
}
/** Converts the given config to a chain config */
def toChainConf(conf: BitcoinSAppConfig): ChainAppConfig = {
conf.chainConf
}
/** Converts the given config to a node config */
def toNodeConf(conf: BitcoinSAppConfig): NodeAppConfig = {
conf.nodeConf
}
/** Converts the given config to a bitcoind rpc config */
def toBitcoindRpcConf(conf: BitcoinSAppConfig): BitcoindRpcAppConfig = {
conf.bitcoindRpcConf
}
}
|
bitcoin-s/bitcoin-s
|
app/server/src/main/scala/org/bitcoins/server/BitcoinSAppConfig.scala
|
Scala
|
mit
| 8,629 |
/**
* Created by akorovin on 21.12.2016.
* NOTE: THEY ARE NOT PRIMITIVE TYPES
* NOTE: THEY ARE CLASSES!
* JUST SYNTACTICAL SUGAR
* NOTE: MAX 22 TUPLES AVAILABLE (max 22 PARAMETERS)
* NOTE: can change values only by copying
*/
object TestTuples {
def main(args: Array[String]): Unit = {
// INSTANTIATE TUPLE. TUPLE3 type (3 PARAMETERS)
val tupleMarge: (Int, String, Double) = (103, "Marge Simpson", 10.25)
// SAME AS
val tupleMarge2: (Int, String, Double) = Tuple3(103, "Marge Simpson", 10.25)
// ACCESS TUPLE by underscore
printf("%s owes us $%.2f\\n", tupleMarge._2, tupleMarge._3)
// ITERATE through each element in tuple
tupleMarge.productIterator.foreach{i => println(i)}
}
}
|
aw3s0me/scala-tuts
|
scala_tuts/src/TestTuples.scala
|
Scala
|
apache-2.0
| 730 |
package im.actor.server.dialog
import akka.actor.ActorSystem
import im.actor.server.db.DbExtension
import im.actor.server.model.Peer
import im.actor.server.persist.social.RelationRepo
import scala.concurrent.Future
trait UserAcl {
protected val system: ActorSystem
// TODO: clarify names of params.
protected def withNonBlockedPeer[A](
contactUserId: Int,
peer: Peer
)(default: โ Future[A], failed: โ Future[A]): Future[A] = {
if (peer.`type`.isGroup) {
default
} else {
withNonBlockedUser(contactUserId, peer.id)(default, failed)
}
}
protected def withNonBlockedUser[A](
userId: Int,
ownerUserId: Int
)(default: โ Future[A], failed: โ Future[A]): Future[A] = {
import system.dispatcher
for {
isBlocked โ checkIsBlocked(userId, ownerUserId)
result โ if (isBlocked) failed else default
} yield result
}
// check that `userId` is blocked by `ownerUserId`
protected def checkIsBlocked(userId: Int, ownerUserId: Int): Future[Boolean] =
DbExtension(system).db.run(RelationRepo.isBlocked(ownerUserId, userId))
}
|
EaglesoftZJ/actor-platform
|
actor-server/actor-core/src/main/scala/im/actor/server/dialog/UserAcl.scala
|
Scala
|
agpl-3.0
| 1,127 |
package pureconfig
import org.scalatest.EitherValues
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks
class BaseSuite
extends AnyFlatSpec
with Matchers
with EitherValues
with ScalaCheckDrivenPropertyChecks
with ConfigConvertChecks
with ConfigReaderMatchers
|
melrief/pureconfig
|
testkit/src/main/scala/pureconfig/BaseSuite.scala
|
Scala
|
mpl-2.0
| 389 |
package filodb.memory.format.vectors
import java.nio.ByteBuffer
import com.typesafe.scalalogging.StrictLogging
import debox.Buffer
import org.agrona.{DirectBuffer, ExpandableArrayBuffer, MutableDirectBuffer}
import org.agrona.concurrent.UnsafeBuffer
import scalaxy.loops._
import filodb.memory.{BinaryRegion, MemFactory}
import filodb.memory.format._
import filodb.memory.format.BinaryVector.BinaryVectorPtr
/**
* BinaryHistogram is the binary format for a histogram binary blob included in BinaryRecords and sent over the wire.
* It fits the BinaryRegionMedium protocol.
* Format:
* +0000 u16 2-byte total length of this BinaryHistogram (excluding this length)
* +0002 u8 1-byte combined histogram buckets and values format code
* 0x00 Empty/null histogram
* 0x03 geometric + NibblePacked delta Long values
* 0x04 geometric_1 + NibblePacked delta Long values (see [[HistogramBuckets]])
* 0x05 custom LE/bucket values + NibblePacked delta Long values
*
* +0003 u16 2-byte length of Histogram bucket definition
* +0005 [u8] Histogram bucket definition, see [[HistogramBuckets]]
* First two bytes of definition is always the number of buckets, a u16
* +(5+n) remaining values according to format above
*
* NOTE: most of the methods below actually expect a pointer to the +2 hist bucket definition, not the length field
*/
object BinaryHistogram extends StrictLogging {
// Pass in a buffer which includes the length bytes. Value class - no allocations.
case class BinHistogram(buf: DirectBuffer) extends AnyVal {
def totalLength: Int = buf.getShort(0).toInt + 2
def numBuckets: Int = buf.getShort(5).toInt
def formatCode: Byte = buf.getByte(2)
def bucketDefNumBytes: Int = buf.getShort(3).toInt
def bucketDefOffset: Long = buf.addressOffset + 5
def valuesIndex: Int = 2 + 3 + bucketDefNumBytes // pointer to values bytes
def valuesNumBytes: Int = totalLength - valuesIndex
def valuesByteSlice: DirectBuffer = {
UnsafeUtils.wrapDirectBuf(buf.byteArray, buf.addressOffset + valuesIndex, valuesNumBytes, valuesBuf)
valuesBuf
}
override def toString: String = s"<BinHistogram: ${toHistogram}>"
def debugStr: String = s"totalLen=$totalLength numBuckets=$numBuckets formatCode=$formatCode " +
s"bucketDef=$bucketDefNumBytes bytes valuesIndex=$valuesIndex values=$valuesNumBytes bytes"
/**
* Converts this BinHistogram to a Histogram object. May not be the most efficient.
* Intended for slower paths such as high level (lower # samples) aggregation and HTTP/CLI materialization
* by clients. Materializes/deserializes everything.
* Ingestion ingests BinHistograms directly without conversion to Histogram first.
*/
def toHistogram: Histogram = formatCode match {
case HistFormat_Geometric_Delta =>
val bucketDef = HistogramBuckets.geometric(buf.byteArray, bucketDefOffset, false)
LongHistogram.fromPacked(bucketDef, valuesByteSlice).getOrElse(Histogram.empty)
case HistFormat_Geometric1_Delta =>
val bucketDef = HistogramBuckets.geometric(buf.byteArray, bucketDefOffset, true)
LongHistogram.fromPacked(bucketDef, valuesByteSlice).getOrElse(Histogram.empty)
case HistFormat_Custom_Delta =>
val bucketDef = HistogramBuckets.custom(buf.byteArray, bucketDefOffset - 2)
LongHistogram.fromPacked(bucketDef, valuesByteSlice).getOrElse(Histogram.empty)
case x =>
logger.debug(s"Unrecognizable histogram format code $x, returning empty histogram")
Histogram.empty
}
}
// Thread local buffer used as read-only byte slice
private val tlValuesBuf = new ThreadLocal[DirectBuffer]()
def valuesBuf: DirectBuffer = tlValuesBuf.get match {
case UnsafeUtils.ZeroPointer => val buf = new UnsafeBuffer(Array.empty[Byte])
tlValuesBuf.set(buf)
buf
case b: DirectBuffer => b
}
// Thread local buffer used as temp buffer for writing binary histograms
private val tlHistBuf = new ThreadLocal[MutableDirectBuffer]()
def histBuf: MutableDirectBuffer = tlHistBuf.get match {
case UnsafeUtils.ZeroPointer => val buf = new ExpandableArrayBuffer(4096)
tlHistBuf.set(buf)
buf
case b: MutableDirectBuffer => b
}
val empty2DSink = NibblePack.DeltaDiffPackSink(Array[Long](), histBuf)
val emptySectSink = UnsafeUtils.ZeroPointer.asInstanceOf[NibblePack.DeltaSectDiffPackSink]
val HistFormat_Null = 0x00.toByte
val HistFormat_Geometric_Delta = 0x03.toByte
val HistFormat_Geometric1_Delta = 0x04.toByte
val HistFormat_Custom_Delta = 0x05.toByte
def isValidFormatCode(code: Byte): Boolean =
(code == HistFormat_Null) || (code == HistFormat_Geometric1_Delta) || (code == HistFormat_Geometric_Delta) ||
(code == HistFormat_Custom_Delta)
/**
* Writes binary histogram with geometric bucket definition and data which is non-increasing, but will be
* decoded as increasing. Intended only for specific use cases when the source histogram are non increasing
* buckets, ie each bucket has a count that is independent.
* @param buf the buffer to write the histogram to. Highly recommended this be an ExpandableArrayBuffer or equiv.
* so it can grow.
* @return the number of bytes written, including the length prefix
*/
def writeNonIncreasing(buckets: GeometricBuckets, values: Array[Long], buf: MutableDirectBuffer): Int = {
require(buckets.numBuckets == values.size, s"Values array size of ${values.size} != ${buckets.numBuckets}")
val formatCode = if (buckets.minusOne) HistFormat_Geometric1_Delta else HistFormat_Geometric_Delta
buf.putByte(2, formatCode)
val valuesIndex = buckets.serialize(buf, 3)
val finalPos = NibblePack.packNonIncreasing(values, buf, valuesIndex)
require(finalPos <= 65535, s"Histogram data is too large: $finalPos bytes needed")
buf.putShort(0, (finalPos - 2).toShort)
finalPos
}
def writeDelta(buckets: HistogramBuckets, values: Array[Long]): Int =
writeDelta(buckets, values, histBuf)
/**
* Encodes binary histogram with geometric bucket definition and data which is strictly increasing and positive.
* All histograms after ingestion are expected to be increasing.
* Delta encoding is applied for compression.
* @param buf the buffer to write the histogram to. Highly recommended this be an ExpandableArrayBuffer or equiv.
* so it can grow.
* @return the number of bytes written, including the length prefix
*/
def writeDelta(buckets: HistogramBuckets, values: Array[Long], buf: MutableDirectBuffer): Int = {
require(buckets.numBuckets == values.size, s"Values array size of ${values.size} != ${buckets.numBuckets}")
val formatCode = buckets match {
case g: GeometricBuckets if g.minusOne => HistFormat_Geometric1_Delta
case g: GeometricBuckets => HistFormat_Geometric_Delta
case c: CustomBuckets => HistFormat_Custom_Delta
}
buf.putByte(2, formatCode)
val valuesIndex = buckets.serialize(buf, 3)
val finalPos = NibblePack.packDelta(values, buf, valuesIndex)
require(finalPos <= 65535, s"Histogram data is too large: $finalPos bytes needed")
buf.putShort(0, (finalPos - 2).toShort)
finalPos
}
}
object HistogramVector {
type HistIterator = Iterator[Histogram] with TypedIterator
val OffsetNumHistograms = 6
val OffsetFormatCode = 8 // u8: BinHistogram format code/bucket type
val OffsetBucketDefSize = 9 // # of bytes of bucket definition
val OffsetBucketDef = 11 // Start of bucket definition
val OffsetNumBuckets = 11
// After the bucket area are regions for storing the counter values or pointers to them
final def getNumBuckets(addr: Ptr.U8): Int = addr.add(OffsetNumBuckets).asU16.getU16
final def getNumHistograms(addr: Ptr.U8): Int = addr.add(OffsetNumHistograms).asU16.getU16
final def resetNumHistograms(addr: Ptr.U8): Unit = addr.add(OffsetNumHistograms).asU16.asMut.set(0)
final def incrNumHistograms(addr: Ptr.U8): Unit =
addr.add(OffsetNumHistograms).asU16.asMut.set(getNumHistograms(addr) + 1)
// Note: the format code defines bucket definition format + format of each individual compressed histogram
final def formatCode(addr: Ptr.U8): Byte = addr.add(OffsetFormatCode).getU8.toByte
final def afterBucketDefAddr(addr: Ptr.U8): Ptr.U8 = addr + OffsetBucketDef + bucketDefNumBytes(addr)
final def bucketDefNumBytes(addr: Ptr.U8): Int = addr.add(OffsetBucketDefSize).asU16.getU16
final def bucketDefAddr(addr: Ptr.U8): Ptr.U8 = addr + OffsetBucketDef
// Matches the bucket definition whose # bytes is at (base, offset)
final def matchBucketDef(hist: BinaryHistogram.BinHistogram, addr: Ptr.U8): Boolean =
(hist.formatCode == formatCode(addr)) &&
(hist.bucketDefNumBytes == bucketDefNumBytes(addr)) && {
UnsafeUtils.equate(UnsafeUtils.ZeroPointer, bucketDefAddr(addr).addr, hist.buf.byteArray, hist.bucketDefOffset,
hist.bucketDefNumBytes)
}
def appending(factory: MemFactory, maxBytes: Int): AppendableHistogramVector = {
val addr = factory.allocateOffheap(maxBytes)
new AppendableHistogramVector(factory, Ptr.U8(addr), maxBytes)
}
def appending2D(factory: MemFactory, maxBytes: Int): AppendableHistogramVector = {
val addr = factory.allocateOffheap(maxBytes)
new Appendable2DDeltaHistVector(factory, Ptr.U8(addr), maxBytes)
}
def appendingSect(factory: MemFactory, maxBytes: Int): AppendableHistogramVector = {
val addr = factory.allocateOffheap(maxBytes)
new AppendableSectDeltaHistVector(factory, Ptr.U8(addr), maxBytes)
}
def apply(buffer: ByteBuffer): HistogramReader = apply(UnsafeUtils.addressFromDirectBuffer(buffer))
import WireFormat._
def apply(p: BinaryVectorPtr): HistogramReader = BinaryVector.vectorType(p) match {
case x if x == WireFormat(VECTORTYPE_HISTOGRAM, SUBTYPE_H_SIMPLE) => new RowHistogramReader(Ptr.U8(p))
case x if x == WireFormat(VECTORTYPE_HISTOGRAM, SUBTYPE_H_SECTDELTA) => new SectDeltaHistogramReader(Ptr.U8(p))
}
// Thread local buffer used as temp buffer for histogram vector encoding ONLY
private val tlEncodingBuf = new ThreadLocal[MutableDirectBuffer]()
private[memory] def encodingBuf: MutableDirectBuffer = tlEncodingBuf.get match {
case UnsafeUtils.ZeroPointer => val buf = new ExpandableArrayBuffer(4096)
tlEncodingBuf.set(buf)
buf
case b: MutableDirectBuffer => b
}
}
/**
* A HistogramVector appender storing compressed histogram values for less storage space.
* This is a Section-based vector - sections of up to 64 histograms are stored at a time.
* It stores histograms up to a maximum allowed size (since histograms are variable length)
* Note that the bucket schema is not set until getting the first item.
* This one stores the compressed histograms as-is, with no other transformation.
*
* Read/Write/Lock semantics: everything is gated by the number of elements.
* When it is 0, nothing is initialized so the reader guards against that.
* When it is > 0, then all structures are initialized.
*/
class AppendableHistogramVector(factory: MemFactory,
vectPtr: Ptr.U8,
val maxBytes: Int) extends BinaryAppendableVector[DirectBuffer] with SectionWriter {
import HistogramVector._
import BinaryHistogram._
protected def vectSubType: Int = WireFormat.SUBTYPE_H_SIMPLE
// Initialize header
BinaryVector.writeMajorAndSubType(addr, WireFormat.VECTORTYPE_HISTOGRAM, vectSubType)
reset()
final def addr: BinaryVectorPtr = vectPtr.addr
def maxElementsPerSection: IntU8 = IntU8(64)
val dispose = () => {
// free our own memory
factory.freeMemory(addr)
}
final def numBytes: Int = vectPtr.asI32.getI32 + 4
final def length: Int = getNumHistograms(vectPtr)
final def isAvailable(index: Int): Boolean = true
final def isAllNA: Boolean = (length == 0)
final def noNAs: Boolean = (length > 0)
private def setNumBytes(len: Int): Unit = {
require(len >= 0)
vectPtr.asI32.asMut.set(len)
}
// NOTE: to eliminate allocations, re-use the DirectBuffer and keep passing the same instance to addData
final def addData(buf: DirectBuffer): AddResponse = {
val h = BinHistogram(buf)
// Validate it's a valid bin histogram
if (buf.capacity < 5 || !isValidFormatCode(h.formatCode) ||
h.formatCode == HistFormat_Null) {
return InvalidHistogram
}
if (h.bucketDefNumBytes > h.totalLength) return InvalidHistogram
val numItems = getNumHistograms(vectPtr)
val numBuckets = h.numBuckets
if (numItems == 0) {
// Copy the bucket definition and set the bucket def size
UnsafeUtils.unsafe.copyMemory(buf.byteArray, h.bucketDefOffset,
UnsafeUtils.ZeroPointer, bucketDefAddr(vectPtr).addr, h.bucketDefNumBytes)
UnsafeUtils.setShort(addr + OffsetBucketDefSize, h.bucketDefNumBytes.toShort)
UnsafeUtils.setByte(addr + OffsetFormatCode, h.formatCode)
// Initialize the first section
val firstSectPtr = afterBucketDefAddr(vectPtr)
initSectionWriter(firstSectPtr, ((vectPtr + maxBytes).addr - firstSectPtr.addr).toInt)
} else {
// check the bucket schema is identical. If not, return BucketSchemaMismatch
if (!matchBucketDef(h, vectPtr)) return BucketSchemaMismatch
}
val res = appendHist(buf, h, numItems)
if (res == Ack) {
// set new number of bytes first. Remember to exclude initial 4 byte length prefix
setNumBytes(maxBytes - bytesLeft - 4)
// Finally, increase # histograms which is the ultimate safe gate for access by readers
incrNumHistograms(vectPtr)
}
res
}
// Inner method to add the histogram to this vector
protected def appendHist(buf: DirectBuffer, h: BinHistogram, numItems: Int): AddResponse = {
appendBlob(buf.byteArray, buf.addressOffset + h.valuesIndex, h.valuesNumBytes)
}
final def addNA(): AddResponse = Ack // TODO: Add a 0 to every appender
def addFromReaderNoNA(reader: RowReader, col: Int): AddResponse = addData(reader.blobAsBuffer(col))
def copyToBuffer: Buffer[DirectBuffer] = ???
def apply(index: Int): DirectBuffer = ???
def finishCompaction(newAddress: BinaryRegion.NativePointer): BinaryVectorPtr = newAddress
// NOTE: do not access reader below unless this vect is nonempty. TODO: fix this, or don't if we don't use this class
lazy val reader: VectorDataReader = new RowHistogramReader(vectPtr)
def reset(): Unit = {
resetNumHistograms(vectPtr)
setNumBytes(OffsetNumBuckets + 2)
}
// We don't optimize -- for now. Histograms are already stored compressed.
// In future, play with other optimization strategies, such as delta encoding.
}
/**
* An appender for Prom-style histograms that increase over time.
* It stores deltas between successive histograms to save space, but the histograms are assumed to be always
* increasing. If they do not increase, then that is considered a "reset" and recorded as such for
* counter correction during queries.
* Great for compression but recovering original value means summing up all the diffs :(
*/
class Appendable2DDeltaHistVector(factory: MemFactory,
vectPtr: Ptr.U8,
maxBytes: Int) extends AppendableHistogramVector(factory, vectPtr, maxBytes) {
import BinaryHistogram._
import HistogramVector._
override def vectSubType: Int = WireFormat.SUBTYPE_H_2DDELTA
private var repackSink = BinaryHistogram.empty2DSink
// TODO: handle corrections correctly. :D
override def appendHist(buf: DirectBuffer, h: BinHistogram, numItems: Int): AddResponse = {
// Must initialize sink correctly at beg once the actual # buckets are known
// Also, we need to write repacked diff histogram to a temporary buffer, as appendBlob needs to know the size
// before writing.
if (repackSink == BinaryHistogram.empty2DSink)
repackSink = NibblePack.DeltaDiffPackSink(new Array[Long](h.numBuckets), encodingBuf)
// Recompress hist based on delta from last hist, write to temp storage. Note that no matter what
// we HAVE to feed each incoming hist through the sink, to properly seed the last hist values.
repackSink.writePos = 0
NibblePack.unpackToSink(h.valuesByteSlice, repackSink, h.numBuckets)
// See if we are at beginning of section. If so, write the original histogram. If not, repack and write diff
if (repackSink.valueDropped) {
repackSink.reset()
newSectionWithBlob(buf.byteArray, buf.addressOffset + h.valuesIndex, h.valuesNumBytes, Section.TypeDrop)
} else if (numItems == 0 || needNewSection(h.valuesNumBytes)) {
repackSink.reset()
appendBlob(buf.byteArray, buf.addressOffset + h.valuesIndex, h.valuesNumBytes)
} else {
val repackedLen = repackSink.writePos
repackSink.reset()
appendBlob(encodingBuf.byteArray, encodingBuf.addressOffset, repackedLen)
}
}
}
/**
* Appender for Prom-style increasing counter histograms of fixed buckets.
* Unlike 2DDelta, it stores deltas from the first (original) histogram of a section, so that the original
* histogram can easily be recovered just by one add.
*/
class AppendableSectDeltaHistVector(factory: MemFactory,
vectPtr: Ptr.U8,
maxBytes: Int) extends AppendableHistogramVector(factory, vectPtr, maxBytes) {
import BinaryHistogram._
import HistogramVector._
override def vectSubType: Int = WireFormat.SUBTYPE_H_SECTDELTA
private var repackSink = BinaryHistogram.emptySectSink
// Default to smaller section sizes to maximize compression
override final def maxElementsPerSection: IntU8 = IntU8(16)
override def appendHist(buf: DirectBuffer, h: BinHistogram, numItems: Int): AddResponse = {
// Initial histogram: set up new sink with first=true flag / just init with # of buckets
if (repackSink == BinaryHistogram.emptySectSink)
repackSink = new NibblePack.DeltaSectDiffPackSink(h.numBuckets, encodingBuf)
// Recompress hist based on original delta. Do this for ALL histograms so drop detection works correctly
repackSink.writePos = 0
NibblePack.unpackToSink(h.valuesByteSlice, repackSink, h.numBuckets)
// If need new section, append blob. Reset state for originalDeltas as needed.
if (repackSink.valueDropped) {
repackSink.reset()
repackSink.setOriginal()
newSectionWithBlob(buf.byteArray, buf.addressOffset + h.valuesIndex, h.valuesNumBytes, Section.TypeDrop)
} else if (numItems == 0 || needNewSection(h.valuesNumBytes)) {
repackSink.reset()
repackSink.setOriginal()
appendBlob(buf.byteArray, buf.addressOffset + h.valuesIndex, h.valuesNumBytes)
} else {
val repackedLen = repackSink.writePos
repackSink.reset()
appendBlob(encodingBuf.byteArray, encodingBuf.addressOffset, repackedLen)
}
}
override lazy val reader: VectorDataReader = new SectDeltaHistogramReader(vectPtr)
}
trait HistogramReader extends VectorDataReader {
def buckets: HistogramBuckets
def apply(index: Int): HistogramWithBuckets
def sum(start: Int, end: Int): MutableHistogram
}
/**
* A reader for row-based Histogram vectors. Mostly contains logic to skip around the vector to find the right
* record pointer.
*/
class RowHistogramReader(histVect: Ptr.U8) extends HistogramReader with SectionReader {
import HistogramVector._
final def length: Int = getNumHistograms(histVect)
val numBuckets = if (length > 0) getNumBuckets(histVect) else 0
val buckets = HistogramBuckets(bucketDefAddr(histVect).add(-2), formatCode(histVect))
val returnHist = LongHistogram(buckets, new Array[Long](buckets.numBuckets))
val endAddr = histVect + histVect.asI32.getI32 + 4
def firstSectionAddr: Ptr.U8 = afterBucketDefAddr(histVect)
/**
* Iterates through each histogram. Note this is expensive due to materializing the Histogram object
* every time. Using higher level functions such as sum is going to be a much better bet usually.
*/
def iterate(vector: BinaryVectorPtr, startElement: Int): TypedIterator =
new Iterator[Histogram] with TypedIterator {
var elem = startElement
def hasNext: Boolean = elem < getNumHistograms(histVect)
def next: Histogram = {
val h = apply(elem)
elem += 1
h
}
}
def length(addr: BinaryVectorPtr): Int = length
protected val dSink = NibblePack.DeltaSink(returnHist.values)
// WARNING: histogram returned is shared between calls, do not reuse!
def apply(index: Int): HistogramWithBuckets = {
require(length > 0)
val histPtr = locate(index)
val histLen = histPtr.asU16.getU16
val buf = BinaryHistogram.valuesBuf
buf.wrap(histPtr.add(2).addr, histLen)
dSink.reset()
NibblePack.unpackToSink(buf, dSink, numBuckets)
returnHist
}
// sum_over_time returning a Histogram with sums for each bucket. Start and end are inclusive row numbers
// NOTE: for now this is just a dumb implementation that decompresses each histogram fully
final def sum(start: Int, end: Int): MutableHistogram = {
require(length > 0 && start >= 0 && end < length)
val summedHist = MutableHistogram.empty(buckets)
for { i <- start to end optimized } {
summedHist.addNoCorrection(apply(i).asInstanceOf[HistogramWithBuckets])
}
summedHist
}
}
/**
* A reader for SectDelta encoded histograms
*/
class SectDeltaHistogramReader(histVect: Ptr.U8) extends RowHistogramReader(histVect) {
// baseHist is section base histogram; summedHist used to compute base + delta or other sums
private val summedHist = MutableHistogram.empty(buckets)
private val baseHist = LongHistogram(buckets, new Array[Long](buckets.numBuckets))
private val baseSink = NibblePack.DeltaSink(baseHist.values)
// override setSection: also set the base histogram for getting real value
override def setSection(sectAddr: Ptr.U8, newElemNo: Int = 0): Unit = {
super.setSection(sectAddr, newElemNo)
// unpack to baseHist
baseSink.reset()
val buf = BinaryHistogram.valuesBuf
buf.wrap(curHist.add(2).addr, curHist.asU16.getU16)
NibblePack.unpackToSink(buf, baseSink, numBuckets)
}
override def apply(index: Int): HistogramWithBuckets = {
require(length > 0)
val histPtr = locate(index)
// Just return the base histogram if we are at start of section
if (index == sectStartingElemNo) baseHist
else {
val histLen = histPtr.asU16.getU16
val buf = BinaryHistogram.valuesBuf
buf.wrap(histPtr.add(2).addr, histLen)
dSink.reset()
NibblePack.unpackToSink(buf, dSink, numBuckets)
summedHist.populateFrom(baseHist)
summedHist.add(returnHist)
summedHist
}
}
// TODO: optimized summing. It's wasteful to apply the base + delta math so many times ...
// instead add delta + base * n if possible. However, do we care about sum performance on increasing histograms?
}
|
velvia/FiloDB
|
memory/src/main/scala/filodb.memory/format/vectors/HistogramVector.scala
|
Scala
|
apache-2.0
| 23,463 |
// Exercise 11: An external DSL, using Scala's Parser Combinator Library.
// Here's the grammar definition with productions from the slides.
import scala.util.parsing.combinator._
object RepeatParser extends JavaTokenParsers {
var count = 0 // set by โnโ
def repeat = "repeat" ~> n <~ "times" ~ block
def n = wholeNumber ^^ {
reps => count = reps.toInt
}
def block = "{" ~> lines <~ "}"
def lines = rep(line)
def line = "say" ~> message ^^ {
msg => for (i <- 1 to count) println(msg)
}
def message = stringLiteral
}
val input =
"""repeat 10 times {
say "hello"
}"""
RepeatParser.parseAll(RepeatParser.repeat, input)
|
deanwampler/SeductionsOfScalaTutorial
|
tutorial-exercises/ex11-external-dsl.scala
|
Scala
|
apache-2.0
| 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.openwhisk.core.entity.test
import org.scalatest.Matchers
import org.scalatest.Suite
import common.StreamLogging
import common.WskActorSystem
import org.apache.openwhisk.core.WhiskConfig
import org.apache.openwhisk.core.entity._
import org.apache.openwhisk.core.entity.ArgNormalizer.trim
import org.apache.openwhisk.core.entity.ExecManifest._
import org.apache.openwhisk.core.entity.size._
import spray.json._
import spray.json.DefaultJsonProtocol._
trait ExecHelpers extends Matchers with WskActorSystem with StreamLogging {
self: Suite =>
private val config = new WhiskConfig(ExecManifest.requiredProperties)
ExecManifest.initialize(config) should be a 'success
protected val NODEJS10 = "nodejs:10"
protected val SWIFT4 = "swift:4.2"
protected val BLACKBOX = "blackbox"
protected val JAVA_DEFAULT = "java"
private def attFmt[T: JsonFormat] = Attachments.serdes[T]
protected def imageName(name: String) =
ExecManifest.runtimesManifest.runtimes.flatMap(_.versions).find(_.kind == name).get.image
protected def js10Old(code: String, main: Option[String] = None) = {
CodeExecAsString(
RuntimeManifest(
NODEJS10,
imageName(NODEJS10),
default = Some(true),
deprecated = Some(false),
stemCells = Some(List(StemCell(2, 256.MB)))),
trim(code),
main.map(_.trim))
}
protected def js10(code: String, main: Option[String] = None) = {
val attachment = attFmt[String].read(code.trim.toJson)
val manifest = ExecManifest.runtimesManifest.resolveDefaultRuntime(NODEJS10).get
CodeExecAsAttachment(manifest, attachment, main.map(_.trim), Exec.isBinaryCode(code))
}
protected def jsDefault(code: String, main: Option[String] = None) = {
js10(code, main)
}
protected def js10MetaDataOld(main: Option[String] = None, binary: Boolean) = {
CodeExecMetaDataAsString(
RuntimeManifest(
NODEJS10,
imageName(NODEJS10),
default = Some(true),
deprecated = Some(false),
stemCells = Some(List(StemCell(2, 256.MB)))),
binary,
main.map(_.trim))
}
protected def js10MetaData(main: Option[String] = None, binary: Boolean) = {
val manifest = ExecManifest.runtimesManifest.resolveDefaultRuntime(NODEJS10).get
CodeExecMetaDataAsAttachment(manifest, binary, main.map(_.trim))
}
protected def javaDefault(code: String, main: Option[String] = None) = {
val attachment = attFmt[String].read(code.trim.toJson)
val manifest = ExecManifest.runtimesManifest.resolveDefaultRuntime(JAVA_DEFAULT).get
CodeExecAsAttachment(manifest, attachment, main.map(_.trim), Exec.isBinaryCode(code))
}
protected def javaMetaData(main: Option[String] = None, binary: Boolean) = {
val manifest = ExecManifest.runtimesManifest.resolveDefaultRuntime(JAVA_DEFAULT).get
CodeExecMetaDataAsAttachment(manifest, binary, main.map(_.trim))
}
protected def swift(code: String, main: Option[String] = None) = {
val attachment = attFmt[String].read(code.trim.toJson)
val manifest = ExecManifest.runtimesManifest.resolveDefaultRuntime(SWIFT4).get
CodeExecAsAttachment(manifest, attachment, main.map(_.trim), Exec.isBinaryCode(code))
}
protected def sequence(components: Vector[FullyQualifiedEntityName]) = SequenceExec(components)
protected def sequenceMetaData(components: Vector[FullyQualifiedEntityName]) = SequenceExecMetaData(components)
protected def bb(image: String) = BlackBoxExec(ExecManifest.ImageName(trim(image)), None, None, false, false)
protected def bb(image: String, code: String, main: Option[String] = None) = {
val (codeOpt, binary) =
if (code.trim.nonEmpty) (Some(attFmt[String].read(code.toJson)), Exec.isBinaryCode(code))
else (None, false)
BlackBoxExec(ExecManifest.ImageName(trim(image)), codeOpt, main, false, binary)
}
protected def blackBoxMetaData(image: String, main: Option[String] = None, binary: Boolean) = {
BlackBoxExecMetaData(ExecManifest.ImageName(trim(image)), main, false, binary)
}
protected def actionLimits(memory: ByteSize, concurrency: Int): ActionLimits =
ActionLimits(memory = MemoryLimit(memory), concurrency = ConcurrencyLimit(concurrency))
}
|
houshengbo/openwhisk
|
tests/src/test/scala/org/apache/openwhisk/core/entity/test/ExecHelpers.scala
|
Scala
|
apache-2.0
| 5,039 |
// scalac: -deprecation -Xfatal-warnings
//
abstract class Foo {
def bar {}
def baz
def boo(i: Int, l: Long)
def boz(i: Int, l: Long) {}
def this(i: Int) { this() } // Don't complain here!
def foz: Unit // Don't complain here!
}
|
martijnhoekstra/scala
|
test/files/neg/procedure-deprecation.scala
|
Scala
|
apache-2.0
| 255 |
package uk.co.mattthomson.coursera.ggp.gresley.moveselector.statistical
case class MonteCarloCount(total: Int, count: Int) {
lazy val value = if (count == 0) 0 else total.toDouble / count.toDouble
def update(score: Int) = MonteCarloCount(total + score, count + 1)
override def toString = s"$value ($total / $count)"
}
object MonteCarloCount {
def apply(): MonteCarloCount = MonteCarloCount(0, 0)
}
|
matt-thomson/gresley
|
src/main/scala/uk/co/mattthomson/coursera/ggp/gresley/moveselector/statistical/MonteCarloCount.scala
|
Scala
|
mit
| 410 |
package org.jetbrains.plugins.scala
package lang
package psi
package api
package expr
/**
* @author Alexander Podkhalyuzin
*/
trait ScTryStmt extends ScExpression {
def tryBlock = findChildByClassScala(classOf[ScTryBlock])
def catchBlock = findChild(classOf[ScCatchBlock])
def finallyBlock = findChild(classOf[ScFinallyBlock])
override def accept(visitor: ScalaElementVisitor) = visitor.visitTryExpression(this)
}
|
consulo/consulo-scala
|
src/org/jetbrains/plugins/scala/lang/psi/api/expr/ScTryStmt.scala
|
Scala
|
apache-2.0
| 426 |
package org.openurp.edu.eams.teach.service.wrapper
import org.openurp.base.CourseUnit
import org.beangle.commons.lang.time.WeekDays.WeekDay
class TimeZone {
var weekStates: Array[String] = _
var units: List[CourseUnit] = _
var weeks: List[WeekDay] = _
}
|
openurp/edu-eams-webapp
|
core/src/main/scala/org/openurp/edu/eams/teach/service/wrapper/TimeZone.scala
|
Scala
|
gpl-3.0
| 275 |
package edu.cmu.lti.oaqa.cse.space.scala
package object test {
}
|
oaqa/bagpipes-old
|
src/test/java/edu/cmu/lti/oaqa/cse/space/scala/test/package.scala
|
Scala
|
apache-2.0
| 72 |
package org.jetbrains.plugins.scala
package testingSupport.test.specs2
import com.intellij.execution.configurations._
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import org.jetbrains.plugins.scala.testingSupport.ScalaTestingConfiguration
import org.jetbrains.plugins.scala.testingSupport.test._
/**
* @author Ksenia.Sautina
* @since 5/17/12
*/
class Specs2RunConfiguration(override val project: Project,
override val configurationFactory: ConfigurationFactory,
override val name: String)
extends AbstractTestRunConfiguration(project, configurationFactory, name)
with ScalaTestingConfiguration {
override def getAdditionalTestParams(testName: String): Seq[String] = Seq("-Dspecs2.ex=\\"\\\\A" + testName + "\\\\Z\\"")
override def suitePaths = List("org.specs2.specification.SpecificationStructure",
"org.specs2.specification.core.SpecificationStructure")
override def mainClass = "org.jetbrains.plugins.scala.testingSupport.specs2.JavaSpecs2Runner"
override def reporterClass = "org.jetbrains.plugins.scala.testingSupport.specs2.JavaSpecs2Notifier"
override def errorMessage: String = "Specs2 is not specified"
override def currentConfiguration = Specs2RunConfiguration.this
protected[test] override def isInvalidSuite(clazz: PsiClass): Boolean = Specs2RunConfiguration.isInvalidSuite(clazz)
}
object Specs2RunConfiguration extends SuiteValidityChecker {
private def isScalaObject(clazz: PsiClass) = clazz.getQualifiedName.endsWith("$")
override protected[test] def lackSuitableConstructor(clazz: PsiClass): Boolean =
!isScalaObject(clazz) && AbstractTestRunConfiguration.lackSuitableConstructor(clazz)
}
|
triggerNZ/intellij-scala
|
src/org/jetbrains/plugins/scala/testingSupport/test/specs2/Specs2RunConfiguration.scala
|
Scala
|
apache-2.0
| 1,747 |
package sss.ancillary
import us.monoid.web.Resty
object MainClient {
def main(args: Array[String]): Unit = {
Resty.ignoreAllCerts()
val defaultHttpConfig = DynConfig[ServerConfig]("httpServerConfig")
val b = new Resty().text(s"http://127.0.0.1:${defaultHttpConfig.httpPort}/testhttp/ping")
println(s"${b.location}")
val a = new Resty().text(s"https://127.0.0.1:${defaultHttpConfig.httpsPort}/testhttp/ping").toString
println("asdasd")
}
}
|
mcsherrylabs/sss.ancillary
|
src/test/scala/sss/ancillary/MainClient.scala
|
Scala
|
gpl-3.0
| 474 |
package sangria.starWars
import sangria.execution.deferred.{Deferred, DeferredResolver}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try
object TestData {
object Episode extends Enumeration {
val NEWHOPE, EMPIRE, JEDI = Value
}
trait Character {
def id: String
def name: Option[String]
def friends: List[String]
def appearsIn: List[Episode.Value]
}
case class Human(
id: String,
name: Option[String],
friends: List[String],
appearsIn: List[Episode.Value],
homePlanet: Option[String])
extends Character
case class Droid(
id: String,
name: Option[String],
friends: List[String],
appearsIn: List[Episode.Value],
primaryFunction: Option[String])
extends Character
case class DeferFriends(friends: List[String]) extends Deferred[List[Option[Character]]]
val characters = List[Character](
Human(
id = "1000",
name = Some("Luke Skywalker"),
friends = List("1002", "1003", "2000", "2001"),
appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI),
homePlanet = Some("Tatooine")
),
Human(
id = "1001",
name = Some("Darth Vader"),
friends = List("1004"),
appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI),
homePlanet = Some("Tatooine")),
Human(
id = "1002",
name = Some("Han Solo"),
friends = List("1000", "1003", "2001"),
appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI),
homePlanet = None),
Human(
id = "1003",
name = Some("Leia Organa"),
friends = List("1000", "1002", "2000", "2001"),
appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI),
homePlanet = Some("Alderaan")
),
Human(
id = "1004",
name = Some("Wilhuff Tarkin"),
friends = List("1001"),
appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI),
homePlanet = None),
Droid(
id = "2000",
name = Some("C-3PO"),
friends = List("1000", "1002", "1003", "2001"),
appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI),
primaryFunction = Some("Protocol")
),
Droid(
id = "2001",
name = Some("R2-D2"),
friends = List("1000", "1002", "1003"),
appearsIn = List(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI),
primaryFunction = Some("Astromech")
)
)
class FriendsResolver extends DeferredResolver[Any] {
override def resolve(deferred: Vector[Deferred[Any]], ctx: Any, queryState: Any)(implicit
ec: ExecutionContext) = deferred.map { case DeferFriends(friendIds) =>
Future.fromTry(Try(friendIds.map(id => characters.find(_.id == id))))
}
}
class CharacterRepo {
def getHero(episode: Option[Episode.Value]) =
episode.flatMap(_ => getHuman("1000")).getOrElse(characters.last)
def getHuman(id: String): Option[Human] =
characters.find(c => c.isInstanceOf[Human] && c.id == id).asInstanceOf[Option[Human]]
def getDroid(id: String): Option[Droid] =
characters.find(c => c.isInstanceOf[Droid] && c.id == id).asInstanceOf[Option[Droid]]
def getCharacters(ids: Seq[String]): Seq[Character] =
ids.flatMap(id => characters.find(_.id == id))
}
}
|
sangria-graphql/sangria
|
modules/core/src/test/scala/sangria/starWars/TestData.scala
|
Scala
|
apache-2.0
| 3,307 |
package sri.universal.navigation
import scala.scalajs.js
package object reducer {
type ReducerFunc = js.Function1[NavigationState,NavigationState]
def defaultReducerFunc(defaultValue : NavigationState): ReducerFunc = {
(state: NavigationState) => if(state != null) state else defaultValue
}
}
|
chandu0101/sri
|
universal/src/main/scala/sri/universal/navigation/reducer/package.scala
|
Scala
|
apache-2.0
| 307 |
package edu.gemini.pit.ui.util
import edu.gemini.pit.ui.ShellAdvisor
import swing._
import edu.gemini.pit.model.Model
import edu.gemini.pit.ui.binding.BoundView
import edu.gemini.model.p1.immutable.Proposal
import scalaz._
import Scalaz._
class StatusBar(shellAdvisor: ShellAdvisor) extends Label with BoundView[Boolean] { panel =>
val lens = Model.rolled
val fromSemester = Model.fromSemester
horizontalAlignment = Alignment.Left
shellAdvisor.catalogHandler.addListener {
cs =>
if (cs.exists(_._2 == None)) {
icon = SharedIcons.ICON_SPINNER_BLUE
text = "Performing catalog lookup..."
} else {
icon = null
text = readyText
}
}
def readyText: String = {
shellAdvisor.context.shell.model.map {
case m: Model if lens.get(m) => val semester = fromSemester.get(m);s"Ready - This proposal has been converted from the semester ${semester.display}"
case _ => "Ready"
}.getOrElse("Ready")
}
}
|
arturog8m/ocs
|
bundle/edu.gemini.pit/src/main/scala/edu/gemini/pit/ui/util/StatusBar.scala
|
Scala
|
bsd-3-clause
| 1,011 |
package io.github.p3trur0
import org.scalatest.Matchers
import org.scalatest.FlatSpec
class HelloTestSpec extends FlatSpec with Matchers {
it should "flat spec test" in {
true shouldBe true
}
}
|
P3trur0/hackerrank
|
src/test/scala/io/github/p3trur0/HelloTestSpec.scala
|
Scala
|
mit
| 218 |
package uscala.util
import scala.concurrent.duration._
/**
* Class that allows to query if a specific amount of time has
* elapsed or not.
*
* As an example, it can be useful when some polling mechanism
* is needed to verify if an operation is successful or not.
*
* It can also be used as a replacement for a stopwatch, if the
* only thing you need is to check the time elapsed every so on.
*
* @param length the duration of the timeout
* @param ticker the ticker to use to count the time elapsed
*/
case class Timeout(length: Duration, ticker: Ticker = Timeout.DefaultTicker) {
val start = ticker.read
/**
* Returns a new timeout with the same length, ticker
* and the start time reset to the current time.
*/
def reset: Timeout = this.copy(length, ticker)
/**
* Returns true if the timeout has elapsed or false otherwise.
*/
def hasElapsed: Boolean = ticker.read - start >= length
/**
* Returns the time elapsed since the timeout was started.
*/
def elapsed: Duration = ticker.read - start
}
object Timeout {
/**
* Default ticker that uses `System.currentTimeMillis`
*/
val DefaultTicker = new Ticker {
def read: Duration = System.currentTimeMillis.millis
}
}
trait Ticker {
def read: Duration
}
|
albertpastrana/uscala
|
timeout/src/main/scala/uscala/util/Timeout.scala
|
Scala
|
mit
| 1,296 |
package scalanlp.optimize.linear
import scalala.tensor._;
import collection.mutable.ArrayBuffer
import dense.{DenseMatrix, DenseVector}
import sparse.SparseVector
/**
* DSL for LinearPrograms. Not thread-safe per instance. Make multiple instances
*
* Basic example:
* {{{
* val lp = new LP;
* import lp._;
* val x = new Positive("x");
* val y = new Positive("y");
*
* val result = maximize ( (3 * x+ 4 * y)
* subjectTo( x <= 3, y <= 1))
*
* result.valueOf(x) // 3
*
* }}}
* @author dlwh
*/
class LinearProgram {
private var _nextId = 0;
private def nextId = {
_nextId += 1
_nextId - 1
}
private val variables = new ArrayBuffer[Variable]();
sealed trait Problem { outer =>
def objective: Expression;
def constraints: IndexedSeq[Constraint];
def subjectTo(constraints : Constraint*):Problem = {
val cons = constraints;
new Problem {
def objective = outer.objective;
def constraints = outer.constraints ++ cons;
}
}
override def toString = (
"maximize " + objective + {
if(constraints.nonEmpty) {
"\\nsubject to " + constraints.mkString("\\n" + " " * "subject to ".length)
} else ""
}
)
}
/**
* Anything that can be built up from adding/subtracting/dividing and multiplying by constants
*/
sealed trait Expression extends Problem{ outer =>
private[LinearProgram] def coefficients: Vector[Double];
private[LinearProgram] def scalarComponent: Double = 0;
def objective = this;
def constraints: IndexedSeq[Constraint] = IndexedSeq.empty;
def +(other: Expression):Expression = new Expression {
private[LinearProgram] def coefficients: Vector[Double] = outer.coefficients + other.coefficients;
private[LinearProgram] override def scalarComponent: Double = outer.scalarComponent + other.scalarComponent
override def toString = outer.toString + " + " + other
}
def -(other: Expression):Expression = new Expression {
private[LinearProgram] def coefficients: Vector[Double] = outer.coefficients - other.coefficients;
private[LinearProgram] override def scalarComponent: Double = outer.scalarComponent - other.scalarComponent
override def toString = outer.toString + " - " + other
}
def <=(rhs_ : Expression):Constraint = new Constraint {
def lhs = outer;
def rhs = rhs_;
}
def <=(c: Double):Constraint = new Constraint {
def lhs = outer;
def rhs = new Expression {
private[LinearProgram] def coefficients = SparseVector.zeros[Double](variables.length);
private[LinearProgram] override def scalarComponent = c;
override def toString = c.toString
}
}
def *(c: Double) = new Expression {
private[LinearProgram] def coefficients = outer.coefficients * c;
private[LinearProgram] override def scalarComponent = outer.scalarComponent * c;
override def toString = outer.toString + " * " + c
}
def *:(c: Double) = new Expression {
private[LinearProgram] def coefficients = outer.coefficients * c;
private[LinearProgram] override def scalarComponent = outer.scalarComponent * c;
override def toString = outer.toString + " * " + c
}
}
sealed trait Constraint { outer =>
def lhs: Expression
def rhs: Expression
override def toString() = lhs.toString + " <= " + rhs;
def standardize: Constraint = new Constraint {
def lhs = new Expression {
private[LinearProgram] def coefficients = outer.lhs.coefficients - outer.rhs.coefficients;
private[LinearProgram] override def scalarComponent = 0.0
}
def rhs = new Expression {
private[LinearProgram] def coefficients = SparseVector.zeros[Double](variables.length);
private[LinearProgram] override def scalarComponent = outer.rhs.scalarComponent - outer.lhs.scalarComponent;
}
}
}
sealed trait Variable extends Expression {
def name: String
def id : Int
def size: Int = 1
override def toString = name
}
case class Positive(name: String = "x_" + nextId) extends Variable { variable =>
val id = variables.length
variables += this;
private[LinearProgram] def coefficients = {
val v = SparseVector.zeros[Double](variables.length)
for(i <- 0 until size) v(id + i) = 1.0
v
}
}
case class Real(name: String="x_" + nextId) extends Variable {
val id = variables.length
variables += this;
variables += this;
private[LinearProgram] def coefficients = {
val v = SparseVector.zeros[Double](variables.length)
v(id) = 1
v(id+1) = -1
v
}
}
case class Result private[LinearProgram] (result: DenseVector[Double], problem: Problem) {
def valueOf(x: Expression) = {(x.coefficients dot result) + x.scalarComponent};
def value = valueOf(problem.objective);
}
def maximize(objective: Problem) = {
val c = DenseVector.zeros[Double](variables.size) + objective.objective.coefficients;
val A = DenseMatrix.zeros[Double](objective.constraints.length,variables.length);
val b = DenseVector.zeros[Double](objective.constraints.length)
for( (c,i) <- objective.constraints.zipWithIndex) {
val cs = c.standardize
A(i,::) := cs.lhs.coefficients;
b(i) = cs.rhs.scalarComponent;
}
val result = InteriorPoint.minimize(A,b,-c, DenseVector.zeros[Double](variables.size) + 1.0);
Result(result,objective)
}
}
|
MLnick/scalanlp-core
|
learn/src/main/scala/scalanlp/optimize/linear/LinearProgram.scala
|
Scala
|
apache-2.0
| 5,506 |
package app.models
import scala.concurrent.Future
import com.mohiva.play.silhouette.api.{ Identity, LoginInfo }
import app.models.ldap.UserConnection
import app.services.cache.{ LDAPConnectionCache, UserAuthenticationCache }
import app.utils.config.LDAPConfig
import app.utils.Logger
import app.utils.types.UserId
/**
* Give access to the user object.
*/
class UserDAO extends UserDAOTrait with Logger {
def find(loginInfo: LoginInfo) = {
LDAPConnectionCache.cache.get[UserConnection](loginInfo.providerKey) match {
case Some(uc) => {
UserAuthenticationCache.cache.get[UserIdentify](loginInfo.providerKey) match {
case Some(user) => {
LDAPConnectionCache.cache.get[UserConnection](loginInfo.providerKey) match {
case Some(conn) => Future.successful(Option(user))
case None => {
logger.info(securityMaker, s"Can not find authenticated users LDAP connection cache : ${loginInfo.providerKey}")
Future.successful(None)
}
}
}
case None => {
logger.info(securityMaker, s"Can not find authenticated information : ${loginInfo.providerKey}")
Future.successful(None)
}
}
}
case None => {
logger.info(securityMaker, s"Can not find LDAP connection : ${loginInfo.providerKey}")
Future.successful(None)
}
}
}
def find(userID: UserId) = Future.successful(UserAuthenticationCache.cache.get[UserIdentify](userID.value.toString))
def save(user: UserIdentify) = {
UserAuthenticationCache.cache.set(user.userID.value.toString, user, LDAPConfig.expiryDuration)
Future.successful(user)
}
}
trait UserDAOTrait {
def find(loginInfo: LoginInfo): Future[Option[UserIdentify]]
def find(userID: UserId): Future[Option[UserIdentify]]
def save(user: UserIdentify): Future[UserIdentify]
}
case class UserIdentify(
userID: UserId,
loginInfo: LoginInfo,
isAdmin: Boolean
) extends Identity
|
YoshinoriN/Credentiam
|
src/app/models/User.scala
|
Scala
|
apache-2.0
| 2,027 |
/**
* TABuddy-Model - a human-centric K,V framework
*
* Copyright (c) 2012-2014 Alexey Aksenov [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 org.digimead.tabuddy.model.graph
import java.net.URI
import java.util.UUID
import java.util.concurrent.atomic.AtomicReference
import org.digimead.digi.lib.api.XDependencyInjection
import org.digimead.digi.lib.log.api.XLoggable
import org.digimead.tabuddy.model.Model
import org.digimead.tabuddy.model.element.{ Coordinate, Element, Reference }
import org.digimead.tabuddy.model.serialization.{ Mechanism, SData, Serialization }
import org.digimead.tabuddy.model.serialization.transport.Transport
import scala.language.implicitConversions
/**
* ElementBox class holds element instance.
* It is suitable for lazy loading or for SoftReference containers.
*
* @param coordinate element coordinate
* @param elementUniqueId identifier which is uniquely identify the specific element
* @param initial initial element location or value, which is erased after save
* @param node container of the element box
* @param serialization type of the serialization mechanism
* @param unmodified the modification timestamp of the original element
* @param elementType manifest with an element type
*/
/*
* please, note => on 'initial' field
* this is allow to pass AtomicReference as forward reference:
*
* val ref = new AtomicReference[MyElement](null)
* ElementBox(..., ref, ...)
* ref.set(element)
*
* ref.get or any other accessor will trigger an initialization of lazy 'initial' value
*/
/*
* ElementBox contains strong reference to Node.
* It's looks like: Node (<- ElementBox <-> Element)
* (<- ElementBox <-> Element) is CG'ed part.
*/
abstract class ElementBox[A <: Element](val coordinate: Coordinate, val elementUniqueId: UUID, initial: โ Either[SData, A],
val node: Node[A], val serialization: Serialization.Identifier, unmodified: Element.Timestamp) extends Modifiable.Read with ConsumerData with Equals {
def this(coordinate: Coordinate, elementUniqueId: UUID, initial: Either[SData, AtomicReference[A]], node: Node[A],
serialization: Serialization.Identifier, unmodified: Element.Timestamp) =
this(coordinate, elementUniqueId, initial match {
case initial @ Left(serializationState) โ Left(serializationState)
case Right(explicitElement) โ Right(explicitElement.get)
}, node, serialization, unmodified)
/** Copy current element box. */
def copy(coordinate: Coordinate = this.coordinate,
elementUniqueId: UUID = this.elementUniqueId,
node: Node[A] = this.node,
serialization: Serialization.Identifier = this.serialization): ElementBox[A] = {
val element = this.e
val elementForwardReference = new AtomicReference[A](null.asInstanceOf[A])
val elementBox = ElementBox[A](coordinate, elementUniqueId, Right(elementForwardReference),
element.modified)(elementType = node.elementType, node = node, serialization = serialization)
val elementCopy = Element[A](elementBox, element.eStash.asInstanceOf[A#StashType])(node.elementType)
elementForwardReference.set(elementCopy)
elementBox.e
elementBox
}
/** Get element. */
def e: A
/** Set element. */
def e_=(arg: Option[A])
/** Get modified element. Returns only if value was modified. */
def getModified(): Option[A]
/** Get unmodified element. */
def getUnmodified(): A
/** (Re)Load element. */
def load(): A
/** Get modification timestamp. */
def modified: Element.Timestamp = getModified.map(_.modified) getOrElse unmodified
/**
* Save element.
*
* @param sData serialization data with parameters
*/
def save(sData: SData)
override def canEqual(that: Any): Boolean = that.isInstanceOf[ElementBox[_]]
override def equals(that: Any): Boolean = that match {
case that: ElementBox[_] โ (that eq this) ||
((that canEqual this) && this.## == that.## && this.modified == that.modified && this.node.elementType == that.node.elementType)
case _ โ false
}
override def hashCode() = java.util.Arrays.hashCode(Array[Int](lazyHashCode))
protected lazy val lazyHashCode = java.util.Arrays.hashCode(Array[AnyRef](this.coordinate, this.elementUniqueId,
this.node, this.serialization))
override def toString = s"graph.Box[${coordinate}/${node.elementType};${node.id}]"
}
object ElementBox extends XLoggable {
implicit def box2interface(g: ElementBox.type): Interface = DI.implementation
/**
* Element box companion interface
*/
trait Interface {
/**
* Create element box with specific parameters.
*
* @param coordinate element coordinate
* @param elementUniqueId identifier which is uniquely identify the specific element
* @param initial initial element value, which is erased after save
* @param unmodified the modification timestamp of unmodified element
* @param elementType manifest with element type
* @param node container of the element box
* @param serialization type of the serialization mechanism
*/
def apply[A <: Element](coordinate: Coordinate, elementUniqueId: UUID, initial: Either[SData, AtomicReference[A]],
unmodified: Element.Timestamp)(implicit elementType: Manifest[A], node: Node[A], serialization: Serialization.Identifier): ElementBox[A] = {
val boxClass = DI.elementBoxClass
val newBoxCtor = boxClass.getConstructor(
classOf[Coordinate],
classOf[UUID],
classOf[Either[_, _]],
classOf[Node[_]],
classOf[Serialization.Identifier],
classOf[Element.Timestamp],
classOf[Manifest[_]])
newBoxCtor.newInstance(coordinate, elementUniqueId, initial, node, serialization, unmodified, elementType).asInstanceOf[ElementBox[A]]
}
/** Create element box except element and assign it to node. */
def apply[A <: Element](coordinate: Coordinate, elementUniqueId: UUID, node: Node.ThreadUnsafe[A], serialization: Serialization.Identifier,
sData: SData, unmodified: Element.Timestamp)(implicit m: Manifest[A]): ElementBox[A] =
apply[A](coordinate, elementUniqueId, Left(sData), unmodified)(m, node, serialization)
/** Create element, element box with specific parameters. */
def apply[A <: Element](coordinate: Coordinate, created: Element.Timestamp, elementNode: Node.ThreadUnsafe[A],
modified: Element.Timestamp, scope: A#StashType#ScopeType, serialization: Serialization.Identifier)(implicit m: Manifest[A],
stashClass: Class[_ <: A#StashType]): ElementBox[A] = {
// create root or projection element box
val elementElementForwardReference = new AtomicReference[A](null.asInstanceOf[A])
val elementBox = apply[A](coordinate, UUID.randomUUID(), Right(elementElementForwardReference), modified)(m, elementNode, serialization)
// create element.
val element = Element.apply[A](elementBox, created, modified, new org.digimead.tabuddy.model.element.Stash.Data, scope)
elementElementForwardReference.set(element)
if (elementBox.e == null)
throw new IllegalStateException(s"${element} element is absent.")
elementBox
}
/** Create element, element box with specific stash. */
def apply[A <: Element](coordinate: Coordinate, elementNode: Node.ThreadUnsafe[A],
serialization: Serialization.Identifier, stash: A#StashType)(implicit m: Manifest[A]): ElementBox[A] = {
// create root or projection element box
val elementElementForwardReference = new AtomicReference[A](null.asInstanceOf[A])
val elementBox = apply[A](coordinate, UUID.randomUUID(), Right(elementElementForwardReference), stash.modified)(m, elementNode, serialization)
// create element.
val element = Element.apply[A](elementBox, stash)
elementElementForwardReference.set(element)
if (elementBox.e == null)
throw new IllegalStateException(s"${element} element is absent.")
elementBox
}
/** Get or create new element box at specific coordinates. */
def getOrCreate[A <: Element](coordinate: Coordinate, node: Node.ThreadUnsafe[A], scope: A#StashType#ScopeType,
serialization: Serialization.Identifier)(implicit m: Manifest[A], stashClass: Class[_ <: A#StashType]): A = {
val requiredBox = if (coordinate == Coordinate.root)
Option(node.rootBox)
else
node.projectionBoxes.get(coordinate)
requiredBox.map(box โ box.e.eAs[A].
getOrElse { throw new IllegalAccessException(s"Found ${box.e}, but it type isn't ${m.runtimeClass}.") }).
getOrElse {
val timestamp = Element.timestamp()
val elementBox = for {
parent โ node.parentNodeReference.get
} yield {
// create root element before projection one
if (node.rootBox == null && coordinate != Coordinate.root) {
val root = ElementBox[A](Coordinate.root, timestamp, node, timestamp, scope, serialization)
val projection = ElementBox[A](coordinate, timestamp, node, timestamp, scope, serialization)
node.updateState(node.state.copy(projectionBoxes = node.state.projectionBoxes +
(coordinate -> projection) + (Coordinate.root -> root)), timestamp)
projection
} else {
val box = ElementBox[A](coordinate, timestamp, node, timestamp, scope, serialization)
node.updateBox(coordinate, box, timestamp)
box
}
}
elementBox match {
case Some(box) โ box.e
case None โ throw new IllegalStateException("Unable to create element box.")
}
}
}
}
/**
* Hard element reference that always contains element instance.
*/
class Hard[A <: Element](coordinate: Coordinate, elementUniqueId: UUID, initial: โ Either[SData, A], node: Node[A],
serialization: Serialization.Identifier, unmodified: Element.Timestamp)(implicit elementType: Manifest[A])
extends ElementBox[A](coordinate, elementUniqueId, initial, node, serialization, unmodified) {
def this(coordinate: Coordinate, elementUniqueId: UUID, initial: Either[SData, AtomicReference[A]], node: Node[A],
serialization: Serialization.Identifier, unmodified: Element.Timestamp)(implicit elementType: Manifest[A]) =
this(coordinate, elementUniqueId, initial match {
case initial @ Left(serializationState) โ Left(serializationState)
case Right(explicitElement) โ Right(explicitElement.get)
}, node, serialization, unmodified)(elementType)
/** Modified element object. */
@volatile protected var modifiedCache: Option[A] = None
/** Unmodified element object. */
@volatile protected var unmodifiedCache: Option[A] = None
def e: A = getModified getOrElse getUnmodified
def e_=(arg: Option[A]) {
modifiedCache = arg
arg match {
case Some(element) โ node.updateModification(element.modified)
case None โ node.updateModification(unmodified)
}
}
def getModified(): Option[A] = modifiedCache orElse
// if there is unsaved initial value
{ if (unmodifiedCache.isEmpty) initial.right.toOption else None }
def getUnmodified(): A = unmodifiedCache getOrElse load()
def load(): A = synchronized {
initial match {
case Right(element) โ
// Element is explicitly passed to this box
unmodifiedCache = Some(element)
element
case Left(sData) โ
unmodifiedCache = None
// Base URI that is passed instead of element.
val element = Serialization.perIdentifier.get(serialization) match {
case Some(mechanism) โ
val sources = sData(SData.Key.sources)
for (source โ sources if unmodifiedCache.isEmpty)
if (source.storageURI.isAbsolute()) {
try {
Serialization.perScheme.get(source.storageURI.getScheme()) match {
case Some(transport) โ
unmodifiedCache = Some(mechanism.load(this, source.transport, sData))
case None โ
log.warn(s"Transport for the specified scheme '${source.storageURI.getScheme()}' not found.")
}
} catch {
case e: SecurityException โ log.debug(e.getMessage)
case e: Throwable โ log.error(s"Unable to load element ${node.id} ${modified}: " + e.getMessage(), e)
}
} else {
log.fatal(s"Unable to process relative storage URI as base: ${source.storageURI}.")
}
case None โ
throw new IllegalStateException(s"Serialization for the specified ${serialization} not found.")
}
unmodifiedCache getOrElse { throw new IllegalStateException(s"Unable to load ${this}.") }
}
}
// get modified timestamp or get unmodified timestamp or get unmodified if not loaded
override def modified: Element.Timestamp = modifiedCache.map(_.modified) orElse
unmodifiedCache.map(_.modified) getOrElse unmodified
/**
* Save element.
*
* @param sData serialization data with parameters
*/
def save(sData: SData) =
synchronized {
Serialization.perIdentifier.get(sData.get(SData.Key.explicitSerializationType) getOrElse serialization) match {
case Some(mechanism) โ
save(e, mechanism, sData)
case None โ
throw new IllegalStateException(s"Serialization mechanism for ${serialization} not found.")
}
}
/** Save element to storage. */
protected def save(element: A, mechanism: Mechanism, sData: SData) {
val storageURI = sData(SData.Key.storageURI)
Serialization.perScheme.get(storageURI.getScheme()) match {
case Some(transport) โ
mechanism.save(this, transport, sData)
case None โ
throw new IllegalArgumentException(s"Transport for the specified scheme '${storageURI.getScheme()}' not found.")
}
unmodifiedCache = Some(element)
modifiedCache = None
}
override def toString() = s"graph.Box$$Hard[${coordinate}/${elementType};${node.id}]"
}
/**
* Soft element reference that contains element only while there is enough memory available.
* And reload it if required.
*/
// Implement if needed with SoftReference
/**
* Dependency injection routines.
*/
private object DI extends XDependencyInjection.PersistentInjectable {
/** Class for new element boxes by default. */
lazy val elementBoxClass = injectOptional[Class[_ <: ElementBox[_]]] getOrElse classOf[Hard[_]]
/** ElementBox implementation. */
lazy val implementation = injectOptional[Interface] getOrElse new AnyRef with Interface {}
}
}
|
digimead/digi-TABuddy-model
|
src/main/scala/org/digimead/tabuddy/model/graph/ElementBox.scala
|
Scala
|
apache-2.0
| 15,437 |
package com.blinkbox.books.marvin.magrathea.api
import java.util.UUID
import java.util.concurrent.ForkJoinPool
import com.blinkbox.books.elasticsearch.client.ElasticClientApi._
import com.blinkbox.books.elasticsearch.client._
import com.blinkbox.books.json.DefaultFormats
import com.blinkbox.books.logging.DiagnosticExecutionContext
import com.blinkbox.books.marvin.magrathea.message._
import com.blinkbox.books.marvin.magrathea.{ElasticConfig, JsonDoc}
import com.blinkbox.books.spray.Page
import com.blinkbox.books.spray.v2.ListPage
import com.sksamuel.elastic4s.ElasticDsl._
import com.sksamuel.elastic4s.source.DocumentSource
import com.typesafe.scalalogging.StrictLogging
import org.json4s.JsonAST.JValue
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods
import spray.http.StatusCodes
import spray.httpx.Json4sJacksonSupport
import scala.concurrent.{ExecutionContext, Future}
trait IndexService {
def searchInCurrent(query: String, page: Page): Future[ListPage[JValue]]
def searchInHistory(query: String, page: Page): Future[ListPage[JValue]]
def indexCurrentDocument(docId: UUID, doc: JValue): Future[IndexResponse]
def indexHistoryDocument(docId: UUID, doc: JValue): Future[IndexResponse]
def deleteCurrentIndex(docIds: List[UUID]): Future[BulkResponse]
def deleteHistoryIndex(docIds: List[UUID]): Future[BulkResponse]
def reIndexCurrentDocument(docId: UUID, schema: String): Future[Boolean]
def reIndexHistoryDocument(docId: UUID, schema: String): Future[Boolean]
def reIndexCurrent(): Future[Unit]
def reIndexHistory(): Future[Unit]
}
class DefaultIndexService(elasticClient: ElasticClient, config: ElasticConfig, documentDao: DocumentDao)
extends IndexService with StrictLogging with Json4sJacksonSupport with JsonMethods {
case class Json4sSource(root: JValue) extends DocumentSource {
val json = compact(render(root))
}
private implicit val ec = DiagnosticExecutionContext(ExecutionContext.fromExecutor(new ForkJoinPool()))
override implicit val json4sJacksonFormats = DefaultFormats ++ Formats.all
override def searchInCurrent(queryText: String, page: Page): Future[ListPage[JValue]] =
searchDocument(queryText, "current", page)
override def searchInHistory(queryText: String, page: Page): Future[ListPage[JValue]] =
searchDocument(queryText, "history", page)
override def indexCurrentDocument(docId: UUID, doc: JValue): Future[IndexResponse] =
indexDocument(docId, doc, "current")
override def indexHistoryDocument(docId: UUID, doc: JValue): Future[IndexResponse] =
indexDocument(docId, doc, "history")
override def deleteHistoryIndex(docIds: List[UUID]): Future[BulkResponse] = deleteFromIndex(docIds, "history")
override def deleteCurrentIndex(docIds: List[UUID]): Future[BulkResponse] = deleteFromIndex(docIds, "current")
override def reIndexCurrentDocument(docId: UUID, schema: String): Future[Boolean] =
reIndexDocument(docId, "current", schema)(documentDao.getCurrentDocumentById)
override def reIndexHistoryDocument(docId: UUID, schema: String): Future[Boolean] =
reIndexDocument(docId, "history", schema)(documentDao.getHistoryDocumentById)
override def reIndexCurrent(): Future[Unit] =
reIndexTable("current")(documentDao.countCurrentDocuments, documentDao.getCurrentDocuments)
override def reIndexHistory(): Future[Unit] =
reIndexTable("history")(documentDao.countHistoryDocuments, documentDao.getHistoryDocuments)
private def searchDocument(queryText: String, docType: String, page: Page): Future[ListPage[JValue]] =
elasticClient.execute {
search in s"${config.index}/$docType" query queryText start page.offset limit page.count
} map { resp =>
val lastPage = (page.offset + page.count) >= resp.hits.total
val hits = resp.hits.hits.map { hit =>
val idField: JValue = "id" -> hit._id
idField merge hit._source
}.toList
ListPage(hits, lastPage)
} recover {
case UnsuccessfulResponse(StatusCodes.NotFound, _) => ListPage(List.empty, lastPage = true)
}
private def indexDocument(docId: UUID, doc: JValue, docType: String): Future[IndexResponse] =
elasticClient.execute {
index into s"${config.index}/$docType" doc Json4sSource(DocumentAnnotator.deAnnotate(doc)) id docId
}
private def deleteFromIndex(docIds: List[UUID], docType: String): Future[BulkResponse] =
elasticClient.execute {
bulk(
docIds.map { docId =>
delete id docId from s"${config.index}/$docType"
}: _*
)
}
private def deleteEntireIndex(): Future[AcknowledgedResponse] =
elasticClient.execute {
delete index config.index
} recover {
case UnsuccessfulResponse(StatusCodes.NotFound, _) => AcknowledgedResponse(acknowledged = false)
}
private def reIndexDocument(docId: UUID, docType: String, schema: String)
(getDocumentById: => (UUID, Option[String]) => Future[Option[JsonDoc]]): Future[Boolean] =
getDocumentById(docId, Option(schema)).flatMap {
case Some(doc) => indexDocument(docId, doc.toJson, docType).map(_ => true)
case None => Future.successful(false)
}
private def reIndexTable(table: String)
(count: => () => Future[Int], index: => (Int, Int) => Future[List[JsonDoc]]): Future[Unit] =
for {
totalDocs <- count()
_ <- deleteEntireIndex()
_ <- reIndexChunks(totalDocs, table, index)
} yield ()
private def reIndexChunks(totalDocs: Int, table: String, index: => (Int, Int) => Future[List[JsonDoc]]): Future[Unit] =
(0 to totalDocs by config.reIndexChunks).foldLeft(Future.successful(())) { (acc, offset) =>
acc.flatMap { _ =>
index(config.reIndexChunks, offset).flatMap { docs =>
indexBulkDocuments(docs, table).map(_ => ())
}
}
}
private def indexBulkDocuments(docs: List[JsonDoc], docType: String): Future[BulkResponse] =
elasticClient.execute {
bulk(
docs.map { doc =>
index into s"${config.index}/$docType" doc Json4sSource(DocumentAnnotator.deAnnotate(doc.toJson)) id doc.id
}: _*
)
}
}
|
blinkboxbooks/magrathea
|
src/main/scala/com/blinkbox/books/marvin/magrathea/api/IndexService.scala
|
Scala
|
mit
| 6,133 |
// Copyright: 2010 - 2016 https://github.com/ensime/ensime-server/graphs
// License: http://www.gnu.org/licenses/gpl-3.0.en.html
package org.ensime.util
import com.typesafe.config.ConfigFactory
import java.util.concurrent.TimeUnit
import org.scalatest._
import org.scalatest.time._
import org.scalatest.concurrent.Eventually
import org.scalactic.TypeCheckedTripleEquals
import org.slf4j.LoggerFactory
import org.slf4j.bridge.SLF4JBridgeHandler
import scala.concurrent.duration._
/**
* Indicates a test that requires launching a JVM under debug mode.
*
* These are typically very unstable on Windows.
*/
object Debugger extends Tag("Debugger")
/**
* Boilerplate remover and preferred testing style in ENSIME.
*/
trait EnsimeSpec extends FlatSpec
with Matchers
with Inside
with Retries
with Eventually
with TryValues
with Inspectors
with TypeCheckedTripleEquals {
SLF4JBridgeHandler.removeHandlersForRootLogger()
SLF4JBridgeHandler.install()
val log = LoggerFactory.getLogger(this.getClass)
private val akkaTimeout: Duration = ConfigFactory.load().getDuration("akka.test.default-timeout", TimeUnit.MILLISECONDS).milliseconds
override val spanScaleFactor: Double = ConfigFactory.load().getDouble("akka.test.timefactor")
implicit override val patienceConfig: PatienceConfig = PatienceConfig(
timeout = scaled(akkaTimeout),
interval = scaled(Span(5, Millis))
)
// taggedAs(org.scalatest.tagobject.Retryable)
// will be retried (don't abuse it)
override def withFixture(test: NoArgTest) = {
if (isRetryable(test)) withRetry { super.withFixture(test) }
else super.withFixture(test)
}
}
|
espinhogr/ensime-server
|
testutil/src/main/scala/org/ensime/util/EnsimeSpec.scala
|
Scala
|
gpl-3.0
| 1,658 |
package se.gigurra.renderer.glimpl.uniforms
import java.nio.FloatBuffer
import javax.media.opengl.GL3ES3
import se.gigurra.renderer.Mat4x4
import se.gigurra.renderer.glimpl.GlShaderProgram
class SimpleUniform(_gl_init: GL3ES3, program: GlShaderProgram, name: String) {
val location = program.getUniformLocation(_gl_init, name)
def setInt(gl: GL3ES3, value: Int) {
gl.glUniform1i(location, value)
}
def setFloat(gl: GL3ES3, value: Float) {
gl.glUniform1f(location, value)
}
def setMatrix(gl: GL3ES3, m: Mat4x4) {
setMatrix(gl, m.buffer)
}
def setMatrix(gl: GL3ES3, m: FloatBuffer) {
gl.glUniformMatrix4fv(location, 1, false, m)
}
def setMatrix(gl: GL3ES3, m: Array[Float], nMatrixOffs: Int) {
gl.glUniformMatrix4fv(location, 1, false, m, nMatrixOffs * 16)
}
def setMatrices(gl: GL3ES3, matrices: FloatBuffer, nMatrices: Int) {
gl.glUniformMatrix4fv(location, nMatrices, false, matrices)
}
def setMatrices(gl: GL3ES3, matrices: Array[Float], nMatrixOffs: Int, nMatrices: Int) {
gl.glUniformMatrix4fv(location, nMatrices, false, matrices, nMatrixOffs * 16)
}
def setVector(gl: GL3ES3, vector: Array[Float]) {
gl.glUniform4fv(location, 1, vector, 0)
}
def setVectors(gl: GL3ES3, vectors: FloatBuffer, nVectors: Int) {
gl.glUniform4fv(location, nVectors, vectors)
}
}
|
GiGurra/gigurra-scala-2drenderer
|
src/main/scala/se/gigurra/renderer/glimpl/uniforms/SimpleUniform.scala
|
Scala
|
mit
| 1,353 |
package org.powlab.jeye.tests
import org.powlab.jeye.tests.anonymous._
import org.powlab.jeye.decompile._
package anonymous {
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest1Test extends DecompileTestClass(classOf[AnonymousInnerClassTest1]) {}
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest2Test extends DecompileTestClass(classOf[AnonymousInnerClassTest2]) {}
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest3Test extends DecompileTestClass(classOf[AnonymousInnerClassTest3]) {}
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest4Test extends DecompileTestClass(classOf[AnonymousInnerClassTest4]) {}
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest5Test extends DecompileTestClass(classOf[AnonymousInnerClassTest5]) {}
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest6Test extends DecompileTestClass(classOf[AnonymousInnerClassTest6]) {}
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest7Test extends DecompileTestClass(classOf[AnonymousInnerClassTest7]) {}
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest8Test extends DecompileTestClass(classOf[AnonymousInnerClassTest8]) {}
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest9Test extends DecompileTestClass(classOf[AnonymousInnerClassTest9]) {}
//TODO fail
@org.junit.Ignore
class AnonymousInnerClassTest10Test extends DecompileTestClass(classOf[AnonymousInnerClassTest10]) {}
}
|
powlab/jeye
|
src/test/scala/org/powlab/jeye/tests/AnonymousTests.scala
|
Scala
|
apache-2.0
| 1,502 |
package com.sksamuel.elastic4s.api
import com.sksamuel.elastic4s.Indexes
import com.sksamuel.elastic4s.requests.settings.{GetSettingsRequest, UpdateSettingsRequest}
trait SettingsApi {
def getSettings(index: String, indexes: String*): GetSettingsRequest = getSettings(index +: indexes)
def getSettings(indexes: Indexes): GetSettingsRequest = GetSettingsRequest(indexes)
def updateSettings(index: String, indexes: String*): UpdateSettingsRequest = updateSettings(index +: indexes)
def updateSettings(indexes: Indexes): UpdateSettingsRequest = UpdateSettingsRequest(indexes)
def updateSettings(indexes: Indexes, settings: Map[String, String]) =
UpdateSettingsRequest(indexes, settings = settings)
}
|
sksamuel/elastic4s
|
elastic4s-core/src/main/scala/com/sksamuel/elastic4s/api/SettingsApi.scala
|
Scala
|
apache-2.0
| 716 |
/*
* Copyright 2011 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twitter.scrooge.ast
import scala.util.parsing.input.Positional
sealed abstract class Node extends Positional
abstract class ValueNode extends Node
abstract class TypeNode extends Node
abstract class DocumentNode extends Node
abstract class HeaderNode extends Node
abstract class DefinitionNode extends Node
abstract class IdNode extends Node
sealed abstract class Requiredness extends Node {
/**
* Indicates that the field is marked as optional in the IDL
* and does not have a default value defined.
*/
def isOptional: Boolean = this eq Requiredness.Optional
/**
* Indicates that the field is marked as required in the IDL.
*/
def isRequired: Boolean = this eq Requiredness.Required
/**
* Indicates that the field is marked with neither optional
* or required in the IDL (or optional with a default value).
*/
def isDefault: Boolean = this eq Requiredness.Default
}
object Requiredness {
/** @see [[Requiredness.isOptional]] */
case object Optional extends Requiredness
/** @see [[Requiredness.isRequired]] */
case object Required extends Requiredness
/** @see [[Requiredness.isDefault]] */
case object Default extends Requiredness
}
case class Field(
index: Int,
sid: SimpleID,
originalName: String,
fieldType: FieldType,
default: Option[RHS] = None,
requiredness: Requiredness = Requiredness.Default,
typeAnnotations: Map[String, String] = Map.empty,
fieldAnnotations: Map[String, String] = Map.empty,
docstring: Option[String] = None)
extends Node
case class Function(
funcName: SimpleID,
originalName: String,
funcType: FunctionType,
args: Seq[Field],
throws: Seq[Field],
docstring: Option[String])
extends Node
|
nkhuyu/scrooge
|
scrooge-generator/src/main/scala/com/twitter/scrooge/AST/Node.scala
|
Scala
|
apache-2.0
| 2,349 |
/*
* Copyright 2016 rdbc contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rdbc.implbase
import io.rdbc.sapi.{Connection, ConnectionFactory, Timeout}
import io.rdbc.util.Futures._
import io.rdbc.util.Logging
import io.rdbc.util.Preconditions.checkNotNull
import scala.concurrent.{ExecutionContext, Future}
trait ConnectionFactoryPartialImpl
extends ConnectionFactory
with Logging {
implicit protected def ec: ExecutionContext
override def withConnection[A](body: Connection => Future[A])
(implicit timeout: Timeout): Future[A] = {
checkNotNull(body)
checkNotNull(timeout)
connection().flatMap { conn =>
body(conn).andThenF { case _ =>
conn.release()
}
}
}
override def withTransaction[A](body: Connection => Future[A])
(implicit timeout: Timeout): Future[A] = {
checkNotNull(body)
checkNotNull(timeout)
withConnection { conn =>
conn.withTransaction {
body(conn)
}
}
}
}
|
rdbc-io/rdbc
|
rdbc-implbase/src/main/scala/io/rdbc/implbase/ConnectionFactoryPartialImpl.scala
|
Scala
|
apache-2.0
| 1,569 |
package com.lrs.common.models
import com.lrs.common.logging.Logging
import com.lrs.common.utils.Testing
/**
* Created by vagrant on 10/16/17.
*/
class TestAddLane extends Testing with Logging{
val TEST_ROAD = Road("Test", 1, "E")
val direction_1 = Direction("E")
val RP1 = ReferencePoint("RP1", TEST_ROAD.name, direction_1.dir, 1.3, 2.0)
val RP2 = ReferencePoint("RP2", TEST_ROAD.name, direction_1.dir, 3.3, 2.5)
val RP3 = ReferencePoint("RP3", TEST_ROAD.name, direction_1.dir, 5.8, 0)
val RP4 = ReferencePoint("RP4", TEST_ROAD.name, direction_1.dir, 11.5 , 2.2)
val RP5 = ReferencePoint("RP5", TEST_ROAD.name, direction_1.dir, 13.7, 2.3)
val RP6 = ReferencePoint("RP6", TEST_ROAD.name, direction_1.dir, 16.0, 0)
val RP8 = ReferencePoint("RP8", TEST_ROAD.name, direction_1.dir, 16.0, 0)
val direction1 = direction_1.addSegmentString(TEST_ROAD.name,"1.3,RP1,2.0,RP2,2.5,RP3,3.6", None,false, None,false)
val direction2 = direction1.addSegmentString(TEST_ROAD.name,"2.1,RP4,2.2,RP5,2.3,RP6,2.7", Some(RP3), false, None, false)
val direction3 = direction2.updateLane("RP1,-0.1,RP3,0.5,3")
val direction4 = direction3.updateLane("RP1,0.2,RP2,0.3,2")
//direction_1.addSegment( segment_1, )
override def beforeEach(): Unit = {
}
it("should add lane properly") {
val start = SegmentPoint("start", RP1.ID, -0.9)
val end = SegmentPoint("end", RP3.ID, 3.0)
val lane = Lane.fromString(direction2.rps, "RP1,-0.1,RP3,0.5,[1 2 3]").get
val direction3 = direction2.updateLane("RP1,-0.1,RP3,0.5,3")
direction3.lanes shouldBe List(lane)
}
it("should add lane properly 2") {
val lanes = List(
Lane.fromString(direction4.rps, "RP1,-0.1,RP1,0.2,[1 2 3]").get,
Lane.fromString(direction4.rps, "RP1,0.2,RP2,0.3,[1 2 3 4 5]").get,
Lane.fromString(direction4.rps, "RP2,0.3,RP3,0.5,[1 2 3]").get
)
direction4.lanes should contain theSameElementsAs lanes
}
it("should remove lane properly 2") {
val direction5 = direction4.updateLane("RP2,0.2,RP3,0.3,-1")
val lanes = List(
Lane.fromString(direction4.rps, "RP1,-0.1,RP1,0.2,[1 2 3]").get,
Lane.fromString(direction4.rps, "RP1,0.2,RP2,0.2,[1 2 3 4 5]").get,
Lane.fromString(direction4.rps, "RP2,0.2,RP2,0.3,[1 2 3 4]").get,
Lane.fromString(direction4.rps, "RP2,0.3,RP3,0.3,[1 2]").get,
Lane.fromString(direction4.rps, "RP3,0.3,RP3,0.5,[1 2 3]").get
)
direction5.lanes should contain theSameElementsAs lanes
}
}
|
edmundgmail/HighwaySystem
|
highway-common/src/test/scala/com/lrs/common/models/TestAddLane.scala
|
Scala
|
apache-2.0
| 2,497 |
package de.berlin.arzt.neotrainer
class DefaultCharProvider(chars: Iterable[Char]) extends CharProvider {
var charSource: DiscreteDistribution[Char] = null
var lastChar: Char = 0
setChars(chars)
def getNextChar: Char = {
var newChar = charSource.getSample
while (newChar == lastChar) {
newChar = charSource.getSample
}
lastChar = newChar
newChar
}
def setChars(chars: Iterable[Char]) {
charSource = new DiscreteDistribution[Char]()
for (c <- chars) {
charSource.put(c, 1d)
}
charSource.normalize
}
def penalize(c: Char) {
charSource.muliply(c, 2)
charSource.uniformize(0.05)
//System.out.println("Penalized: " + c)
//System.out.println(charSource)
}
def reward(c: Char) {
charSource.muliply(c, 0.8)
charSource.uniformize(0.05)
//System.out.println("Rewarded: " + c)
//System.out.println(charSource)
}
}
|
arzt/type-neo
|
src/main/scala/de/berlin/arzt/neotrainer/DefaultCharProvider.scala
|
Scala
|
gpl-2.0
| 910 |
/*
* 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.openwhisk.core.containerpool.docker.test
import common.StreamLogging
import common.WskActorSystem
import java.nio.charset.StandardCharsets
import java.time.Instant
import org.apache.http.HttpRequest
import org.apache.http.HttpResponse
import org.apache.http.entity.StringEntity
import org.apache.http.localserver.LocalServerTestBase
import org.apache.http.protocol.HttpContext
import org.apache.http.protocol.HttpRequestHandler
import org.junit.runner.RunWith
import org.scalatest.BeforeAndAfter
import org.scalatest.BeforeAndAfterAll
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import scala.concurrent.Await
import scala.concurrent.TimeoutException
import scala.concurrent.duration._
import spray.json.JsObject
import org.apache.openwhisk.common.TransactionId
import org.apache.openwhisk.core.containerpool.AkkaContainerClient
import org.apache.openwhisk.core.containerpool.ContainerHealthError
import org.apache.openwhisk.core.entity.ActivationResponse._
import org.apache.openwhisk.core.entity.size._
/**
* Unit tests for AkkaContainerClientTests which communicate with containers.
*/
@RunWith(classOf[JUnitRunner])
class AkkaContainerClientTests
extends FlatSpec
with Matchers
with BeforeAndAfter
with BeforeAndAfterAll
with StreamLogging
with WskActorSystem {
implicit val transid = TransactionId.testing
implicit val ec = actorSystem.dispatcher
var testHang: FiniteDuration = 0.second
var testStatusCode: Int = 200
var testResponse: String = null
var testConnectionFailCount: Int = 0
val mockServer = new LocalServerTestBase {
var failcount = 0
override def setUp() = {
super.setUp()
this.serverBootstrap
.registerHandler(
"/init",
new HttpRequestHandler() {
override def handle(request: HttpRequest, response: HttpResponse, context: HttpContext) = {
if (testHang.length > 0) {
Thread.sleep(testHang.toMillis)
}
if (testConnectionFailCount > 0 && failcount < testConnectionFailCount) {
failcount += 1
println("failing in test")
throw new RuntimeException("failing...")
}
response.setStatusCode(testStatusCode);
if (testResponse != null) {
response.setEntity(new StringEntity(testResponse, StandardCharsets.UTF_8))
}
}
})
}
}
mockServer.setUp()
val httpHost = mockServer.start()
val hostWithPort = s"${httpHost.getHostName}:${httpHost.getPort}"
before {
testHang = 0.second
testStatusCode = 200
testResponse = null
testConnectionFailCount = 0
stream.reset()
}
override def afterAll = {
mockServer.shutDown()
}
behavior of "AkkaContainerClient"
it should "not wait longer than set timeout" in {
val timeout = 5.seconds
val connection = new AkkaContainerClient(httpHost.getHostName, httpHost.getPort, timeout, 1.B, 1.B, 100)
testHang = timeout * 2
val start = Instant.now()
val result = Await.result(connection.post("/init", JsObject.empty, retry = true), 10.seconds)
val end = Instant.now()
val waited = end.toEpochMilli - start.toEpochMilli
result shouldBe 'left
waited should be > timeout.toMillis
waited should be < (timeout * 2).toMillis
}
it should "handle empty entity response" in {
val timeout = 5.seconds
val connection = new AkkaContainerClient(httpHost.getHostName, httpHost.getPort, timeout, 1.B, 1.B, 100)
testStatusCode = 204
val result = Await.result(connection.post("/init", JsObject.empty, retry = true), 10.seconds)
result shouldBe Left(NoResponseReceived())
}
it should "retry till timeout on StreamTcpException" in {
val timeout = 5.seconds
val connection = new AkkaContainerClient("0.0.0.0", 12345, timeout, 1.B, 1.B, 100)
val start = Instant.now()
val result = Await.result(connection.post("/init", JsObject.empty, retry = true), 10.seconds)
val end = Instant.now()
val waited = end.toEpochMilli - start.toEpochMilli
result match {
case Left(Timeout(_: TimeoutException)) => // good
case _ => fail(s"$result was not a Timeout(TimeoutException)")
}
waited should be > timeout.toMillis
waited should be < (timeout * 2).toMillis
}
it should "throw ContainerHealthError on HttpHostConnectException if reschedule==true" in {
val timeout = 5.seconds
val connection = new AkkaContainerClient("0.0.0.0", 12345, timeout, 1.B, 1.B, 100)
assertThrows[ContainerHealthError] {
Await.result(connection.post("/run", JsObject.empty, retry = false, reschedule = true), 10.seconds)
}
}
it should "retry till success within timeout limit" in {
val timeout = 5.seconds
val retryInterval = 500.milliseconds
val connection =
new AkkaContainerClient(httpHost.getHostName, httpHost.getPort, timeout, 1.B, 1.B, 100, retryInterval)
val start = Instant.now()
testConnectionFailCount = 5
testResponse = ""
val result = Await.result(connection.post("/init", JsObject.empty, retry = true), 10.seconds)
val end = Instant.now()
val waited = end.toEpochMilli - start.toEpochMilli
result shouldBe Right {
ContainerResponse(true, "", None)
}
waited should be > (testConnectionFailCount * retryInterval).toMillis
waited should be < timeout.toMillis
}
it should "not truncate responses within limit" in {
val timeout = 1.minute.toMillis
val connection = new AkkaContainerClient(httpHost.getHostName, httpHost.getPort, timeout.millis, 50.B, 50.B, 100)
Seq(true, false).foreach { success =>
Seq(null, "", "abc", """{"a":"B"}""", """["a", "b"]""").foreach { r =>
testStatusCode = if (success) 200 else 500
testResponse = r
val result = Await.result(connection.post("/init", JsObject.empty, retry = true), 10.seconds)
result shouldBe Right {
ContainerResponse(okStatus = success, if (r != null) r else "", None)
}
}
}
}
it should "truncate responses that exceed limit" in {
val timeout = 1.minute.toMillis
val limit = 2.B
val truncationLimit = 1.B
val connection =
new AkkaContainerClient(httpHost.getHostName, httpHost.getPort, timeout.millis, limit, truncationLimit, 100)
Seq(true, false).foreach { success =>
Seq("abc", """{"a":"B"}""", """["a", "b"]""").foreach { r =>
testStatusCode = if (success) 200 else 500
testResponse = r
val result = Await.result(connection.post("/init", JsObject.empty, retry = true), 10.seconds)
result shouldBe Right {
ContainerResponse(okStatus = success, r.take(truncationLimit.toBytes.toInt), Some((r.length.B, limit)))
}
}
}
}
it should "truncate large responses that exceed limit" in {
val timeout = 1.minute.toMillis
//use a limit large enough to not fit into a single ByteString as response entity is parsed into multiple ByteStrings
//seems like this varies, but often is ~64k or ~128k
val limit = 300.KB
val truncationLimit = 299.B
val connection =
new AkkaContainerClient(httpHost.getHostName, httpHost.getPort, timeout.millis, limit, truncationLimit, 100)
Seq(true, false).foreach { success =>
// Generate a response that's 1MB
val response = "0" * 1024 * 1024
testStatusCode = if (success) 200 else 500
testResponse = response
val result = Await.result(connection.post("/init", JsObject.empty, retry = true), 10.seconds)
result shouldBe Right {
ContainerResponse(
okStatus = success,
response.take(truncationLimit.toBytes.toInt),
Some((response.length.B, limit)))
}
}
}
}
|
jeremiaswerner/openwhisk
|
tests/src/test/scala/org/apache/openwhisk/core/containerpool/docker/test/AkkaContainerClientTests.scala
|
Scala
|
apache-2.0
| 8,695 |
package texteditor
import scala.language.implicitConversions
class LineIterator(it: Iterator[Char]) extends Iterator[String] {
private var blank = !it.hasNext
private var ch: Option[Char] = None
private def nextChar = if (ch.nonEmpty) { val c = ch.get; ch = None; c } else it.next
def hasNext = blank || !ch.isEmpty || it.hasNext
def next: String = {
if (blank) { blank = false; return "" }
val sb = new StringBuilder
while (hasNext)
nextChar match {
case '\\r' =>
if (hasNext)
it.next match {
case '\\n' => blank = !hasNext; return sb.toString + "\\r\\n"
case c => ch = Some(c)
}
blank = !hasNext; return sb.toString + '\\r'
case '\\n' =>
blank = !hasNext; return sb.toString + '\\n'
case ch =>
sb += ch
}
return sb.toString
}
}
object LineIterator {
def apply(it: Iterator[Char]) = new LineIterator(it)
def apply(it: Iterable[Char]) = new LineIterator(it.iterator)
}
case class Position(row: Int, col: Int)
object Position {
implicit def fromTuple(tuple: (Int, Int)): Position = Position(tuple._1, tuple._2)
}
object LineOffset {
def position(it: Iterator[Char], offset: Int): Position = {
var (row, col, prev) = (0, 0, ' ')
for (ch <- it.slice(0, offset)) {
if (ch != '\\n' || prev != '\\r')
ch match {
case '\\n' | '\\r' => col = 0; row += 1
case _ => col += 1
}
prev = ch
}
Position(row, col)
}
def position(it: Iterable[Char], offset: Int): Position =
position(it.iterator, offset)
def offset(it: Iterator[Char], position: Position): Int = {
var (row, col, off, prev) = (0, 0, 0, ' ')
for (ch <- it) {
if (ch != '\\n' || prev != '\\r') {
if (position == Position(row, col) || (position.row == row && (ch == '\\n' || ch == '\\r')))
return off
ch match {
case '\\n' | '\\r' => col = 0; row += 1
case _ => col += 1
}
}
prev = ch
off += 1
}
return off
}
def offset(it: Iterable[Char], position: Position): Int =
offset(it.iterator, position)
}
|
volkc/REScala
|
Examples/Editor/src/main/scala/texteditor/LineOffset.scala
|
Scala
|
apache-2.0
| 2,182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.