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 fpinscala.chapter1.original
class Cafe {
def buyCoffees(creditCard: CreditCard, numOfCoffees: Int): (List[Coffee], Charge) = {
val purchases: List[(Coffee, Charge)] =
List.fill(numOfCoffees)(buyCoffee(creditCard))
val (coffees, charges) = purchases.unzip
(coffees, charges.reduce((c1, c2) => c1.combine(c2)))
}
def buyCoffee(creditCard: CreditCard): (Coffee, Charge) = {
val coffee: Coffee = new Coffee()
(coffee, Charge(creditCard, coffee.price))
}
}
|
dandxy89/LearningScala
|
src/main/scala/fpinscala/chapter1/original/Cafe.scala
|
Scala
|
mit
| 498 |
package com.sksamuel.elastic4s.search.queries
import com.sksamuel.elastic4s.RefreshPolicy
import com.sksamuel.elastic4s.testkit.DockerTests
import org.scalatest.{Matchers, WordSpec}
import scala.util.Try
class NestedQueryTest extends WordSpec with DockerTests with Matchers {
Try {
client.execute {
deleteIndex("nested")
}.await
}
client.execute {
createIndex("nested").mappings(
mapping("places").fields(
keywordField("name"),
nestedField("states")
)
)
}
client.execute(
bulk(
indexInto("nested" / "places") fields(
"name" -> "usa",
"states" -> Seq(
Map(
"name" -> "Montana",
"capital" -> "Helena",
"entry" -> 1889
), Map(
"name" -> "South Dakota",
"capital" -> "Pierre",
"entry" -> 1889
)
)
),
indexInto("nested" / "places") fields(
"name" -> "fictional usa",
"states" -> Seq(
Map(
"name" -> "Old Jersey",
"capital" -> "Trenton",
"entry" -> 1889
), Map(
"name" -> "Montana",
"capital" -> "Helena",
"entry" -> 1567
)
)
)
).refresh(RefreshPolicy.Immediate)
).await
"nested query" should {
"match against nested objects" in {
client.execute {
search("nested") query {
nestedQuery("states").query {
boolQuery.must(
matchQuery("states.name", "Montana"),
matchQuery("states.entry", 1889)
)
}
}
}.await.result.totalHits shouldBe 1
}
}
}
|
Tecsisa/elastic4s
|
elastic4s-tests/src/test/scala/com/sksamuel/elastic4s/search/queries/NestedQueryTest.scala
|
Scala
|
apache-2.0
| 1,697 |
/*
* 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.samza.system
import org.junit.Assert._
import org.junit.Test
import org.apache.samza.Partition
import org.apache.samza.serializers._
import org.apache.samza.system.chooser.MessageChooser
import org.apache.samza.system.chooser.DefaultChooser
import org.apache.samza.system.chooser.MockMessageChooser
import org.apache.samza.util.BlockingEnvelopeMap
import scala.collection.JavaConversions._
class TestSystemConsumers {
def testPollIntervalMs {
val numEnvelopes = 1000
val system = "test-system"
val systemStreamPartition0 = new SystemStreamPartition(system, "some-stream", new Partition(0))
val systemStreamPartition1 = new SystemStreamPartition(system, "some-stream", new Partition(1))
val envelope = new IncomingMessageEnvelope(systemStreamPartition0, "1", "k", "v")
val consumer = new CustomPollResponseSystemConsumer(envelope)
var now = 0L
val consumers = new SystemConsumers(new MockMessageChooser, Map(system -> consumer),
new SerdeManager, new SystemConsumersMetrics,
SystemConsumers.DEFAULT_NO_NEW_MESSAGES_TIMEOUT,
SystemConsumers.DEFAULT_DROP_SERIALIZATION_ERROR,
SystemConsumers.DEFAULT_POLL_INTERVAL_MS, clock = () => now)
consumers.register(systemStreamPartition0, "0")
consumers.register(systemStreamPartition1, "1234")
consumers.start
// Tell the consumer to respond with 1000 messages for SSP0, and no
// messages for SSP1.
consumer.setResponseSizes(numEnvelopes)
// Choose to trigger a refresh with data.
assertNull(consumers.choose())
// 2: First on start, second on choose.
assertEquals(2, consumer.polls)
assertEquals(2, consumer.lastPoll.size)
assertTrue(consumer.lastPoll.contains(systemStreamPartition0))
assertTrue(consumer.lastPoll.contains(systemStreamPartition1))
assertEquals(envelope, consumers.choose())
assertEquals(envelope, consumers.choose())
// We aren't polling because we're getting non-null envelopes.
assertEquals(2, consumer.polls)
// Advance the clock to trigger a new poll even though there are still
// messages.
now = SystemConsumers.DEFAULT_POLL_INTERVAL_MS
assertEquals(envelope, consumers.choose())
// We polled even though there are still 997 messages in the unprocessed
// message buffer.
assertEquals(3, consumer.polls)
assertEquals(1, consumer.lastPoll.size)
// Only SSP1 was polled because we still have messages for SSP2.
assertTrue(consumer.lastPoll.contains(systemStreamPartition1))
// Now drain all messages for SSP0. There should be exactly 997 messages,
// since we have chosen 3 already, and we started with 1000.
(0 until (numEnvelopes - 3)).foreach { i =>
assertEquals(envelope, consumers.choose())
}
// Nothing left. Should trigger a poll here.
assertNull(consumers.choose())
assertEquals(4, consumer.polls)
assertEquals(2, consumer.lastPoll.size)
// Now we ask for messages from both again.
assertTrue(consumer.lastPoll.contains(systemStreamPartition0))
assertTrue(consumer.lastPoll.contains(systemStreamPartition1))
}
def testBasicSystemConsumersFunctionality {
val system = "test-system"
val systemStreamPartition = new SystemStreamPartition(system, "some-stream", new Partition(1))
val envelope = new IncomingMessageEnvelope(systemStreamPartition, "1", "k", "v")
val consumer = new CustomPollResponseSystemConsumer(envelope)
var now = 0
val consumers = new SystemConsumers(new MockMessageChooser, Map(system -> consumer),
new SerdeManager, new SystemConsumersMetrics,
SystemConsumers.DEFAULT_NO_NEW_MESSAGES_TIMEOUT,
SystemConsumers.DEFAULT_DROP_SERIALIZATION_ERROR,
SystemConsumers.DEFAULT_POLL_INTERVAL_MS, clock = () => now)
consumers.register(systemStreamPartition, "0")
consumers.start
// Start should trigger a poll to the consumer.
assertEquals(1, consumer.polls)
// Tell the consumer to start returning messages when polled.
consumer.setResponseSizes(1)
// Choose to trigger a refresh with data.
assertNull(consumers.choose())
// Choose should have triggered a second poll, since no messages are available.
assertEquals(2, consumer.polls)
// Choose a few times. This time there is no data.
assertEquals(envelope, consumers.choose())
assertNull(consumers.choose())
assertNull(consumers.choose())
// Return more than one message this time.
consumer.setResponseSizes(2)
// Choose to trigger a refresh with data.
assertNull(consumers.choose())
// Increase clock interval.
now = SystemConsumers.DEFAULT_POLL_INTERVAL_MS
// We get two messages now.
assertEquals(envelope, consumers.choose())
// Should not poll even though clock interval increases past interval threshold.
assertEquals(2, consumer.polls)
assertEquals(envelope, consumers.choose())
assertNull(consumers.choose())
}
@Test
def testSystemConumersShouldRegisterStartAndStopChooser {
val system = "test-system"
val systemStreamPartition = new SystemStreamPartition(system, "some-stream", new Partition(1))
var consumerStarted = 0
var consumerStopped = 0
var consumerRegistered = Map[SystemStreamPartition, String]()
var chooserStarted = 0
var chooserStopped = 0
var chooserRegistered = Map[SystemStreamPartition, String]()
val consumer = Map(system -> new SystemConsumer {
def start = consumerStarted += 1
def stop = consumerStopped += 1
def register(systemStreamPartition: SystemStreamPartition, offset: String) = consumerRegistered += systemStreamPartition -> offset
def poll(systemStreamPartitions: java.util.Set[SystemStreamPartition], timeout: Long) = Map[SystemStreamPartition, java.util.List[IncomingMessageEnvelope]]()
})
val consumers = new SystemConsumers(new MessageChooser {
def update(envelope: IncomingMessageEnvelope) = Unit
def choose = null
def start = chooserStarted += 1
def stop = chooserStopped += 1
def register(systemStreamPartition: SystemStreamPartition, offset: String) = chooserRegistered += systemStreamPartition -> offset
}, consumer, null)
consumers.register(systemStreamPartition, "0")
consumers.start
consumers.stop
assertEquals(1, chooserStarted)
assertEquals(1, chooserStopped)
assertEquals(1, chooserRegistered.size)
assertEquals("0", chooserRegistered(systemStreamPartition))
assertEquals(1, consumerStarted)
assertEquals(1, consumerStopped)
assertEquals(1, consumerRegistered.size)
assertEquals("0", consumerRegistered(systemStreamPartition))
}
@Test
def testThrowSystemConsumersExceptionWhenTheSystemDoesNotHaveConsumer() {
val system = "test-system"
val system2 = "test-system2"
val systemStreamPartition = new SystemStreamPartition(system, "some-stream", new Partition(1))
val systemStreamPartition2 = new SystemStreamPartition(system2, "some-stream", new Partition(1))
var started = 0
var stopped = 0
var registered = Map[SystemStreamPartition, String]()
val consumer = Map(system -> new SystemConsumer {
def start {}
def stop {}
def register(systemStreamPartition: SystemStreamPartition, offset: String) {}
def poll(systemStreamPartitions: java.util.Set[SystemStreamPartition], timeout: Long) = Map[SystemStreamPartition, java.util.List[IncomingMessageEnvelope]]()
})
val consumers = new SystemConsumers(new MessageChooser {
def update(envelope: IncomingMessageEnvelope) = Unit
def choose = null
def start = started += 1
def stop = stopped += 1
def register(systemStreamPartition: SystemStreamPartition, offset: String) = registered += systemStreamPartition -> offset
}, consumer, null)
// it should throw a SystemConsumersException because system2 does not have a consumer
var caughtRightException = false
try {
consumers.register(systemStreamPartition2, "0")
} catch {
case e: SystemConsumersException => caughtRightException = true
case _: Throwable => caughtRightException = false
}
assertTrue("suppose to throw SystemConsumersException, but apparently it did not", caughtRightException)
}
@Test
def testDroppingMsgOrThrowExceptionWhenSerdeFails() {
val system = "test-system"
val systemStreamPartition = new SystemStreamPartition(system, "some-stream", new Partition(1))
val msgChooser = new DefaultChooser
val consumer = Map(system -> new SerializingConsumer)
val systemMessageSerdes = Map(system -> (new StringSerde("UTF-8")).asInstanceOf[Serde[Object]]);
val serdeManager = new SerdeManager(systemMessageSerdes = systemMessageSerdes)
// throw exceptions when the deserialization has error
val consumers = new SystemConsumers(msgChooser, consumer, serdeManager, dropDeserializationError = false)
consumers.register(systemStreamPartition, "0")
consumer(system).putBytesMessage
consumer(system).putStringMessage
consumers.start
var caughtRightException = false
try {
consumers.choose()
} catch {
case e: SystemConsumersException => caughtRightException = true
case _: Throwable => caughtRightException = false
}
assertTrue("suppose to throw SystemConsumersException", caughtRightException);
consumers.stop
// it should not throw exceptions when deserializaion fails if dropDeserializationError is set to true
val consumers2 = new SystemConsumers(msgChooser, consumer, serdeManager, dropDeserializationError = true)
consumers2.register(systemStreamPartition, "0")
consumer(system).putBytesMessage
consumer(system).putStringMessage
consumer(system).putBytesMessage
consumers2.start
var notThrowException = true;
try {
consumers2.choose()
} catch {
case e: Throwable => notThrowException = false
}
assertTrue("it should not throw any exception", notThrowException)
var msgEnvelope = Some(consumers2.choose())
assertTrue("Consumer did not succeed in receiving the second message after Serde exception in choose", msgEnvelope.get != null)
consumers2.stop
// ensure that the system consumer will continue after poll() method ignored a Serde exception
consumer(system).putStringMessage
consumer(system).putBytesMessage
notThrowException = true;
try {
consumers2.start
} catch {
case e: Throwable => notThrowException = false
}
assertTrue("SystemConsumer start should not throw any Serde exception", notThrowException)
msgEnvelope = null
msgEnvelope = Some(consumers2.choose())
assertTrue("Consumer did not succeed in receiving the second message after Serde exception in poll", msgEnvelope.get != null)
consumers2.stop
}
/**
* A simple MockSystemConsumer that keeps track of what was polled, and lets
* you define how many envelopes to return in the poll response. You can
* supply the envelope to use for poll responses through the constructor.
*/
private class CustomPollResponseSystemConsumer(envelope: IncomingMessageEnvelope) extends SystemConsumer {
var polls = 0
var pollResponse = Map[SystemStreamPartition, java.util.List[IncomingMessageEnvelope]]()
var lastPoll: java.util.Set[SystemStreamPartition] = null
def start {}
def stop {}
def register(systemStreamPartition: SystemStreamPartition, offset: String) {}
def poll(systemStreamPartitions: java.util.Set[SystemStreamPartition], timeout: Long) = {
polls += 1
lastPoll = systemStreamPartitions
pollResponse
}
def setResponseSizes(numEnvelopes: Int) {
val q = new java.util.ArrayList[IncomingMessageEnvelope]()
(0 until numEnvelopes).foreach { i => q.add(envelope) }
pollResponse = Map(envelope.getSystemStreamPartition -> q)
pollResponse = Map[SystemStreamPartition, java.util.List[IncomingMessageEnvelope]]()
}
}
/**
* A simple consumer that provides two extra methods: one is to put bytes
* format message and the other to put string format message.
*/
private class SerializingConsumer extends BlockingEnvelopeMap {
val systemStreamPartition = new SystemStreamPartition("test-system", "some-stream", new Partition(1))
def putBytesMessage {
put(systemStreamPartition, new IncomingMessageEnvelope(systemStreamPartition, "0", "0", "test".getBytes()))
}
def putStringMessage {
put(systemStreamPartition, new IncomingMessageEnvelope(systemStreamPartition, "0", "1", "test"))
}
def start {}
def stop {}
def register { super.register(systemStreamPartition, "0") }
}
}
object TestSystemConsumers {
def getSystemConsumers(consumers: java.util.Map[String, SystemConsumer]) : SystemConsumers = {
new SystemConsumers(new DefaultChooser, consumers.toMap)
}
}
|
nickpan47/samza
|
samza-core/src/test/scala/org/apache/samza/system/TestSystemConsumers.scala
|
Scala
|
apache-2.0
| 13,991 |
package org.vaslabs.granger.comms.api
import java.time.ZonedDateTime
import io.circe.{ Decoder, Encoder }
import org.vaslabs.granger.modelv2._
import io.circe.generic.semiauto._
/**
* Created by vnicolaou on 13/06/17.
*/
object model {
case class AddToothInformationRequest(
patientId: PatientId,
toothNumber: Int,
medicament: Option[Medicament],
nextVisit: Option[NextVisit],
roots: Option[List[Root]],
toothNote: Option[TreatmentNote],
obturation: Option[List[Root]],
treatmentStarted: ZonedDateTime)
object AddToothInformationRequest {
import org.vaslabs.granger.v2json._
import io.circe.generic.auto._
implicit val encoder: Encoder[AddToothInformationRequest] = deriveEncoder[AddToothInformationRequest]
implicit val decoder: Decoder[AddToothInformationRequest] = deriveDecoder[AddToothInformationRequest]
}
case class Activity(date: ZonedDateTime, tooth: Int, `type`: String)
object Activity {
implicit val ordering: Ordering[Activity] = (lhsActivity: Activity, rhsActivity: Activity) => {
rhsActivity.date.compareTo(lhsActivity.date)
}
trait Transformer[A] {
def transform(a: A): Activity
}
implicit final class ActivityConverter[A](val `class`: A)(implicit transformer: Transformer[A]) {
def asActivity(): Activity =
transformer.transform(`class`)
}
}
case class PubKey(value: String)
case class RemoteRepo(uri: String)
case class AutocompleteSuggestions(medicamentNames: List[String])
}
|
vaslabs/granger
|
src/main/scala/org/vaslabs/granger/comms/api/model.scala
|
Scala
|
lgpl-3.0
| 1,541 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kafka.cluster
import java.nio.ByteBuffer
import kafka.api.ApiUtils._
import kafka.common.KafkaException
import org.apache.kafka.common.utils.Utils._
object BrokerEndPoint {
private val uriParseExp = """\[?([0-9a-zA-Z\-.:]*)\]?:([0-9]+)""".r
/**
* BrokerEndPoint URI is host:port or [ipv6_host]:port
* Note that unlike EndPoint (or listener) this URI has no security information.
*/
def parseHostPort(connectionString: String): Option[(String, Int)] = {
connectionString match {
case uriParseExp(host, port) => try Some(host, port.toInt) catch { case e: NumberFormatException => None }
case _ => None
}
}
/**
* BrokerEndPoint URI is host:port or [ipv6_host]:port
* Note that unlike EndPoint (or listener) this URI has no security information.
*/
def createBrokerEndPoint(brokerId: Int, connectionString: String): BrokerEndPoint = {
parseHostPort(connectionString).map { case (host, port) => new BrokerEndPoint(brokerId, host, port) }.getOrElse {
throw new KafkaException("Unable to parse " + connectionString + " to a broker endpoint")
}
}
def readFrom(buffer: ByteBuffer): BrokerEndPoint = {
val brokerId = buffer.getInt()
val host = readShortString(buffer)
val port = buffer.getInt()
BrokerEndPoint(brokerId, host, port)
}
}
/**
* BrokerEndpoint is used to connect to specific host:port pair.
* It is typically used by clients (or brokers when connecting to other brokers)
* and contains no information about the security protocol used on the connection.
* Clients should know which security protocol to use from configuration.
* This allows us to keep the wire protocol with the clients unchanged where the protocol is not needed.
*/
case class BrokerEndPoint(id: Int, host: String, port: Int) {
def connectionString(): String = formatAddress(host, port)
def writeTo(buffer: ByteBuffer): Unit = {
buffer.putInt(id)
writeShortString(buffer, host)
buffer.putInt(port)
}
def sizeInBytes: Int =
4 + /* broker Id */
4 + /* port */
shortStringLength(host)
}
|
samaitra/kafka
|
core/src/main/scala/kafka/cluster/BrokerEndPoint.scala
|
Scala
|
apache-2.0
| 2,901 |
package name.denyago.yasc.chat
import akka.actor.{Actor, ActorRef}
import name.denyago.yasc.chat.events.{ConnectionEstablished, MessagePosted, MessageReceived, UserJoined}
/**
* Actor, holding a WebSocket connection of a particular User.
* Will become connected once WebSocket connection is established
*
* @param chatRoom a Chat Room User enters into
*/
class ConnectedUser(chatRoom: ActorRef) extends Actor {
override def receive: Receive = {
case ConnectionEstablished(outgoing) =>
context.become(connected(outgoing))
}
def connected(outgoing: ActorRef): Receive = {
chatRoom ! UserJoined(self.toString(), self)
{
case MessageReceived(text) =>
chatRoom ! MessagePosted(text)
case MessagePosted(text) =>
outgoing ! MessagePosted(text)
}
}
}
|
denyago/yet-another-simple-chat
|
src/main/scala/name/denyago/yasc/chat/ConnectedUser.scala
|
Scala
|
mit
| 817 |
/*
* Copyright 2015-2016 Snowflake Computing
* Copyright 2015 TouchType Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.snowflake.spark.snowflake
import java.sql.{Date, ResultSet, Timestamp}
import java.util.Calendar
import org.apache.spark.sql.{DataFrame, Row}
import org.apache.spark.sql.types._
/**
* Helpers for Snowflake tests that require common mocking
*/
object TestUtils {
/**
* Simple schema that includes all data types we support
*/
val testSchema: StructType = {
// These column names need to be lowercase; see #51
StructType(
Seq(
StructField("testbyte", ByteType),
StructField("testdate", DateType),
StructField("testdec152", DecimalType(15, 2)),
StructField("testdouble", DoubleType),
StructField("testfloat", FloatType),
StructField("testint", IntegerType),
StructField("testlong", LongType),
StructField("testshort", ShortType),
StructField("teststring", StringType),
StructField("testtimestamp", TimestampType)
)
)
}
// scalastyle:off
/**
* Expected parsed output corresponding to snowflake_unload_data.txt
*/
val expectedData: Seq[Row] = Seq(
Row(
1.toByte,
TestUtils.toDate(2015, 6, 1),
BigDecimal(1234567890123.45),
1234152.12312498,
1.0f,
42,
1239012341823719L,
23.toShort,
"Unicode's樂趣",
TestUtils.toTimestamp(2015, 6, 1, 0, 0, 0, 1)
),
Row(
2.toByte,
TestUtils.toDate(1960, 0, 2),
BigDecimal(1.01),
2.0,
3.0f,
4,
5L,
6.toShort,
"\\"",
TestUtils.toTimestamp(2015, 6, 2, 12, 34, 56, 789)
),
Row(
3.toByte,
TestUtils.toDate(2999, 11, 31),
BigDecimal(-1.01),
-2.0,
-3.0f,
-4,
-5L,
-6.toShort,
"\\\\'\\"|",
TestUtils.toTimestamp(1950, 11, 31, 17, 0, 0, 1)
),
Row(List.fill(10)(null): _*)
)
// scalastyle:on
/**
* The same as `expectedData`, but with dates and timestamps converted into string format.
* See #39 for context.
*/
val expectedDataWithConvertedTimesAndDates: Seq[Row] = expectedData.map {
row =>
Row.fromSeq(row.toSeq.map {
case t: Timestamp => Conversions.formatTimestamp(t)
case d: Date => Conversions.formatDate(d)
case other => other
})
}
/**
* Convert date components to a millisecond timestamp
*/
def toMillis(year: Int,
zeroBasedMonth: Int,
date: Int,
hour: Int,
minutes: Int,
seconds: Int,
millis: Int = 0): Long = {
val calendar = Calendar.getInstance()
calendar.set(year, zeroBasedMonth, date, hour, minutes, seconds)
calendar.set(Calendar.MILLISECOND, millis)
calendar.getTime.getTime
}
/**
* Convert date components to a SQL Timestamp
*/
def toTimestamp(year: Int,
zeroBasedMonth: Int,
date: Int,
hour: Int,
minutes: Int,
seconds: Int,
millis: Int): Timestamp = {
new Timestamp(
toMillis(year, zeroBasedMonth, date, hour, minutes, seconds, millis)
)
}
/**
* Convert date components to a SQL [[Date]].
*/
def toDate(year: Int, zeroBasedMonth: Int, date: Int): Date = {
new Date(toTimestamp(year, zeroBasedMonth, date, 0, 0, 0, 0).getTime)
}
/** Compare two JDBC ResultSets for equivalence */
def compareResultSets(rs1: ResultSet, rs2: ResultSet): Boolean = {
val colCount = rs1.getMetaData.getColumnCount
assert(colCount == rs2.getMetaData.getColumnCount)
var col = 1
while (rs1.next && rs2.next) {
while (col <= colCount) {
val res1 = rs1.getObject(col)
val res2 = rs2.getObject(col)
// Check values
if (!(res1 == res2)) return false
// rs1 and rs2 must reach last row in the same iteration
if (rs1.isLast != rs2.isLast) return false
col += 1
}
}
true
}
/** This takes a query in the shape produced by QueryBuilder and
* performs the necessary indentation for pretty printing.
*
* @note Warning: This is a hacky implementation that isn't very 'functional' at all.
* In fact, it's quite imperative.
*
* This is useful for logging and debugging.
*/
def prettyPrint(query: String): String = {
val opener = "\\\\(SELECT"
val closer = "\\\\) AS \\\\\\"SUBQUERY_[0-9]{1,10}\\\\\\""
val breakPoints = "(" + "(?=" + opener + ")" + "|" + "(?=" + closer + ")" +
"|" + "(?<=" + closer + ")" + ")"
var remainder = query
var indent = 0
val str = new StringBuilder
var inSuffix: Boolean = false
while (remainder.length > 0) {
val prefix = "\\n" + "\\t" * indent
val parts = remainder.split(breakPoints, 2)
str.append(prefix + parts.head)
if (parts.length >= 2 && parts.last.length > 0) {
val n: Char = parts.last.head
if (n == '(') {
indent += 1
} else {
if (!inSuffix) {
indent -= 1
inSuffix = true
}
if (n == ')') {
inSuffix = false
}
}
remainder = parts.last
} else remainder = ""
}
str.toString()
}
def createTable(df: DataFrame, options: Map[String, String], name: String): Unit = {
import DefaultJDBCWrapper._
val params = Parameters.mergeParameters(options)
val conn = DefaultJDBCWrapper.getConnector(params)
conn.createTable(name, df.schema, params, true, false)
}
}
|
snowflakedb/spark-snowflake
|
src/test/scala/net/snowflake/spark/snowflake/TestUtils.scala
|
Scala
|
apache-2.0
| 6,183 |
/*
* 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.cep.scala.pattern
import java.lang.reflect.Method
import org.apache.flink.api.scala.completeness.ScalaAPICompletenessTestBase
import org.apache.flink.cep.pattern.{Pattern => JPattern}
import org.junit.Test
import scala.language.existentials
/**
* This checks whether the CEP Scala API is up to feature parity with the Java API.
* Implements the [[ScalaAPICompletenessTestBase]] for CEP.
*/
class PatternScalaAPICompletenessTest extends ScalaAPICompletenessTestBase {
override def isExcludedByName(method: Method): Boolean = {
val name = method.getDeclaringClass.getName + "." + method.getName
val excludedNames = Seq()
excludedNames.contains(name)
}
@Test
override def testCompleteness(): Unit = {
checkMethods("Pattern", "Pattern", classOf[JPattern[_, _]], classOf[Pattern[_, _]])
}
}
|
hequn8128/flink
|
flink-libraries/flink-cep-scala/src/test/scala/org/apache/flink/cep/scala/pattern/PatternScalaAPICompletenessTest.scala
|
Scala
|
apache-2.0
| 1,652 |
package com.twitter.finagle
import java.net.{SocketAddress, InetSocketAddress}
/**
* A SocketAddress with a weight.
*/
object WeightedSocketAddress {
private case class Impl(
addr: SocketAddress,
weight: Double
) extends SocketAddress
/**
* Create a weighted socket address with weight `weight`.
*/
def apply(addr: SocketAddress, weight: Double): SocketAddress =
Impl(addr, weight)
/**
* Destructuring a weighted socket address is liberal: we return a
* weight of 1 if it is unweighted.
*/
def unapply(addr: SocketAddress): Option[(SocketAddress, Double)] =
addr match {
case Impl(addr, weight) => Some(addr, weight)
case addr => Some(addr, 1D)
}
}
object WeightedInetSocketAddress {
/**
* Destructuring a weighted inet socket address is liberal: we
* return a weight of 1 if it is unweighted.
*/
def unapply(addr: SocketAddress): Option[(InetSocketAddress, Double)] =
addr match {
case WeightedSocketAddress(ia: InetSocketAddress, weight) => Some(ia, weight)
case ia: InetSocketAddress => Some(ia, 1D)
case _ => None
}
}
|
JustinTulloss/finagle
|
finagle-core/src/main/scala/com/twitter/finagle/WeightedSocketAddress.scala
|
Scala
|
apache-2.0
| 1,129 |
import sbt._
object Dependencies {
val kafka = "com.typesafe.akka" %% "akka-stream-kafka" % Versions.akka_kafka
val logback = "ch.qos.logback" % "logback-classic" % Versions.logback
val log4j_over_slf4j = "org.slf4j" % "log4j-over-slf4j" % Versions.log4j_over_slf4j
val akka_slf4j = "com.typesafe.akka" %% "akka-slf4j" % Versions.akka
val scalatest = "org.scalatest" %% "scalatest" % Versions.scalatest % "test"
val akka_testkit = "com.typesafe.akka" %% "akka-testkit" % Versions.akka % "test"
val play_json = "com.typesafe.play" % "play-json_2.11" % Versions.play_json
val akka_http_core = "com.typesafe.akka" %% "akka-http-core" % Versions.akka_http
val akka_http_testkit = "com.typesafe.akka" %% "akka-http-testkit" % Versions.akka_http
val io_spray = "io.spray" %% "spray-json" % Versions.io_spray
}
|
omearac/reactive-kafka-microservice-template
|
project/Dependencies.scala
|
Scala
|
apache-2.0
| 834 |
import scala.util.Random
import scala.annotation.tailrec
/**
* "Ants" traverse a graph of locations to produce random tours.
*
* The choice of which location to visit next ("state transition") is
* probabalistic, and weighted by both the distance and amount of pheromone
* deposited between locations.
*/
abstract class Ant {
/**
* Label for locations.
*/
type Node = Int
/**
* Edge weight between locations
*/
case class Weight(distance: Double, pheromone: Double)
/**
* An ant's current location and where it has yet to visit.
*/
case class State(current: Node, remaining: Set[Node]) {
def visit(n: Node): State =
if (remaining.contains(n)) State(n, remaining - n)
else this
}
/**
* Tour the locations in the graph and return to the starting point, producing
* a new solution.
*/
def tour(startingPoint: Node, graph: ConnectedGraph[Node, Weight]): Solution = {
val state = State(startingPoint, graph.nodes.toSet - startingPoint)
// Populated later. A cheap trick.
var lastNode: Option[Node] = None
val steps = unfold(state) { case state =>
if (state.remaining.size == 0) {
lastNode = Some(state.current)
None
} else {
val step = nextStep(state, graph)
Some(((state.current, step), state.visit(step)))
}
}.reverse
Solution(steps ++ List(lastNode.get -> startingPoint), graph.transform(_.distance))
}
/**
* Choose a new location to visit based on the [[travelProbabilities]].
*/
def nextStep(state: State, graph: ConnectedGraph[Node, Weight]): Node =
weightedRandomChoice(travelProbabilities(state, graph))
/**
* Probabilites for determining which location to visit next.
*/
def travelProbabilities(state: State, graph: ConnectedGraph[Node, Weight])
: List[(Node, Double)] =
{
val normalizationFactor = state.remaining.map { node =>
val weight = graph.weight(state.current, node)
Math.pow(weight.pheromone, alpha) / Math.pow(weight.distance, beta)
}.sum
state.remaining.toList.map { node =>
val weight = graph.weight(state.current, node)
val a = Math.pow(weight.pheromone, alpha)
val b = 1.0 / Math.pow(weight.distance, beta)
(node, (a * b) / normalizationFactor)
}
}
/**
* Select an element of type `A` randomly based on selection weights.
*
* The weights need not sum to one (like probabilities); only the relative
* value of the weights matter for selection.
*/
def weightedRandomChoice[A](choices: Seq[(A, Double)]): A = {
val (items, weights) = choices.unzip
val cumulativeWeights = items.zip(weights.scanLeft(0.0)(_ + _).tail)
val x = Random.nextDouble() * weights.sum
cumulativeWeights.find { case (_, bound) => bound > x }.get._1
}
/**
* Beginning with state `z`, iteratively populate a sequence of values and
* update the state.
*
* Termination is indicated when `f` evaluates to [[None]].
*/
def unfold[A, S](z: S)(f: S => Option[(A, S)]): List[A] = {
var result = List.empty[A]
@tailrec
def loop(state: S): Unit =
f(state) match {
case None =>
case Some((e, newS)) =>
result ::= e
loop(newS)
}
loop(z)
result
}
/**
* Higher values relative to [[beta]] will weigh the amount of pheromone on
* an edge more significantly than the distance.
*/
def alpha: Double
/**
* Higher values relative to [[alpha]] will weigh the distance between two
* locations on an edge more significantly than the pheromone that is present.
*/
def beta: Double
}
object Ant {
trait Defaults {
val alpha = 0.5
val beta = 1.2
}
}
|
hakuch/TravellingAnts
|
src/main/scala/Ant.scala
|
Scala
|
mit
| 3,725 |
package sorm.core
sealed trait DbType
object DbType {
case object Mysql extends DbType
case object H2 extends DbType
case object Hsqldb extends DbType
case object Sqlite extends DbType
case object Postgres extends DbType
case object Oracle extends DbType
case object Sqlserver extends DbType
case object Derby extends DbType
case object Sybase extends DbType
case object Db2 extends DbType
def byUrl
( u : String )
: DbType
= u match {
case u if u.startsWith("jdbc:mysql:") => Mysql
case u if u.startsWith("jdbc:h2:") => H2
case u if u.startsWith("jdbc:hsqldb:") => Hsqldb
case u if u.startsWith("jdbc:sqlite:") => Sqlite
case u if u.startsWith("jdbc:postgresql:") => Postgres
case u if u.startsWith("jdbc:oracle:") => Oracle
case u if u.startsWith("jdbc:sqlserver:") => Sqlserver
case u if u.startsWith("jdbc:derby:") => Derby
case u if u.startsWith("jdbc:sybase:") => Sybase
case u if u.startsWith("jdbc:db2:") => Db2
}
def driverClass
( t : DbType )
= t match {
case DbType.Mysql => "com.mysql.jdbc.Driver"
case DbType.Postgres => "org.postgresql.Driver"
case DbType.H2 => "org.h2.Driver"
case DbType.Sqlite => "org.sqlite.JDBC"
case DbType.Hsqldb => "org.hsqldb.jdbcDriver"
case DbType.Derby => "org.apache.derby.jdbc.EmbeddedDriver"
case _ => ???
}
}
|
cllu/sorm2
|
src/main/scala/sorm/core/DbType.scala
|
Scala
|
mit
| 1,482 |
package controllers.namedslices.admin
import controllers.{ CRUDController, OrganizationController }
import models._
import com.escalatesoft.subcut.inject.BindingModule
import play.api.mvc._
import play.api.data.Form
import play.api.data.Forms._
import com.mongodb.casbah.Imports._
import play.api.data.validation.Constraints
import models.NamedSliceQuery
import models.cms.{ ListEntry, CMSPage }
/**
*
* @author Manuel Bernhardt <[email protected]>
*/
class NamedSlices(implicit val bindingModule: BindingModule) extends OrganizationController with CRUDController[NamedSlice, NamedSliceDAO] {
def urlPath: String = "namedSlices"
def menuKey: String = "namedSlice"
def form(implicit mom: Manifest[NamedSlice]): Form[NamedSlice] = Form(
mapping(
"_id" -> of[ObjectId],
"key" -> nonEmptyText.verifying(Constraints.pattern("^[A-Za-z0-9-]{3,40}$".r, "constraint.validSpec", "namedslice.invalidKeyFormat")),
"name" -> nonEmptyText,
"cmsPageKey" -> nonEmptyText,
"query" -> mapping(
"terms" -> text,
"dataSets" -> seq(text)
)(NamedSliceQuery.apply)(NamedSliceQuery.unapply),
"addToMainMenu" -> boolean,
"published" -> boolean
)(NamedSlice.apply)(NamedSlice.unapply)
)
def emptyModel[A](implicit request: MultitenantRequest[A], configuration: OrganizationConfiguration): NamedSlice =
NamedSlice(key = "", name = "", cmsPageKey = "", query = NamedSliceQuery(terms = ""), addToMainMenu = false, published = false)
def dao(implicit configuration: OrganizationConfiguration): NamedSliceDAO = NamedSlice.dao
def list = OrganizationAdmin {
implicit request =>
crudList(customViewLink = Some(("/slices/_key_", Seq("key"))))
}
def add = OrganizationAdmin {
implicit request =>
crudUpdate(None, additionalTemplateData = Some(creationPageTemplateData))
}
def update(id: ObjectId) = OrganizationAdmin {
implicit request =>
crudUpdate(Some(id), additionalTemplateData = Some(creationPageTemplateData))
}
private def creationPageTemplateData(implicit request: MultitenantRequest[AnyContent], configuration: OrganizationConfiguration) = {
val publishedEntries: List[ListEntry] = CMSPage.dao.entryList(getLang, None).filter(_.page.published)
val nonHomepageEntries: List[ListEntry] = publishedEntries.filterNot(_.page.key == "homepage")
val pages = nonHomepageEntries.map(entry => (entry.page.key, entry.page.title))
val dataSets = DataSet.dao.findAll().map { set => (set.spec, set.details.name) }
{
model: Option[NamedSlice] =>
Seq(
'cmsPages -> pages,
'dataSets -> dataSets
)
}
}
}
|
delving/culture-hub
|
modules/namedSlices/app/controllers/namedslices/admin/NamedSlices.scala
|
Scala
|
apache-2.0
| 2,687 |
/*
* Copyright 2001-2015 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest.examples.asyncfreespec.composingwithasyncfixture
import org.scalatest._
import org.scalatest.SuiteMixin
import collection.mutable.ListBuffer
import scala.concurrent.Future
import scala.concurrent.ExecutionContext
// Defining actor messages
sealed abstract class StringOp
case object Clear extends StringOp
case class Append(value: String) extends StringOp
case object GetValue
class StringBuilderActor { // Simulating an actor
private final val sb = new StringBuilder
def !(op: StringOp): Unit =
synchronized {
op match {
case Append(value) => sb.append(value)
case Clear => sb.clear()
}
}
def ?(get: GetValue.type)(implicit c: ExecutionContext): Future[String] =
Future {
synchronized { sb.toString }
}
}
class StringBufferActor {
private final val buf = ListBuffer.empty[String]
def !(op: StringOp): Unit =
synchronized {
op match {
case Append(value) => buf += value
case Clear => buf.clear()
}
}
def ?(get: GetValue.type)(implicit c: ExecutionContext): Future[List[String]] =
Future {
synchronized { buf.toList }
}
}
trait Builder extends AsyncTestSuiteMixin { this: AsyncTestSuite =>
final val builderActor = new StringBuilderActor
abstract override def withFixture(test: NoArgAsyncTest) = {
builderActor ! Append("ScalaTest is ")
// To be stackable, must call super.withFixture
complete {
super.withFixture(test)
} lastly {
builderActor ! Clear
}
}
}
trait Buffer extends AsyncTestSuiteMixin { this: AsyncTestSuite =>
final val bufferActor = new StringBufferActor
abstract override def withFixture(test: NoArgAsyncTest) = {
// To be stackable, must call super.withFixture
complete {
super.withFixture(test)
} lastly {
bufferActor ! Clear
}
}
}
class ExampleSpec extends AsyncFreeSpec with Builder with Buffer {
"Testing" - {
"should be easy" in {
builderActor ! Append("easy!")
val futureString = builderActor ? GetValue
val futureList = bufferActor ? GetValue
val futurePair: Future[(String, List[String])] = futureString zip futureList
futurePair map { case (str, lst) =>
assert(str == "ScalaTest is easy!")
assert(lst.isEmpty)
bufferActor ! Append("sweet")
succeed
}
}
"should be fun" in {
builderActor ! Append("fun!")
val futureString = builderActor ? GetValue
val futureList = bufferActor ? GetValue
val futurePair: Future[(String, List[String])] = futureString zip futureList
futurePair map { case (str, lst) =>
assert(str == "ScalaTest is fun!")
assert(lst.isEmpty)
bufferActor ! Append("awesome")
succeed
}
}
}
}
|
dotty-staging/scalatest
|
examples/src/test/scala/org/scalatest/examples/asyncfreespec/composingwithasyncfixture/ExampleSpec.scala
|
Scala
|
apache-2.0
| 3,404 |
/*
* Licensed to Intel Corporation under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Intel Corporation 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.intel.analytics.bigdl.nn
import com.intel.analytics.bigdl.nn.abstractnn.TensorModule
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric
import scala.reflect.ClassTag
/**
* Subtractive + divisive contrast normalization.
*
* @param nInputPlane
* @param kernel
* @param threshold
* @param thresval
*/
@SerialVersionUID(- 5339890039498187188L)
class SpatialContrastiveNormalization[T: ClassTag](
val nInputPlane: Int = 1,
var kernel: Tensor[T] = null,
val threshold: Double = 1e-4,
val thresval: Double = 1e-4
)(implicit ev: TensorNumeric[T]) extends TensorModule[T] {
if (null == kernel) kernel = Tensor.ones[T](9, 9)
private val kdim = kernel.nDimension()
require(kdim == 1 || kdim == 2, "averaging kernel must be 2D or 1D")
require(kernel.size(1) % 2 != 0, "averaging kernel must have ODD dimensions")
if (kdim == 2) {
require(kernel.size(2) % 2 != 0, "averaging kernel must have ODD dimensions")
}
// instantiate sub+div normalization
private val normalizer = new Sequential[T]()
normalizer.add(new SpatialSubtractiveNormalization(nInputPlane, kernel))
normalizer.add(new SpatialDivisiveNormalization(nInputPlane, kernel, threshold, thresval))
override def updateOutput(input: Tensor[T]): Tensor[T] = {
output = normalizer.forward(input).toTensor[T]
output
}
override def updateGradInput(input: Tensor[T], gradOutput: Tensor[T]): Tensor[T] = {
gradInput = normalizer.backward(input, gradOutput).toTensor[T]
gradInput
}
override def toString(): String = {
s"SpatialContrastiveNormalization($nInputPlane, kernelTensor, $threshold, $thresval)"
}
override def canEqual(other: Any): Boolean = {
other.isInstanceOf[SpatialContrastiveNormalization[T]]
}
override def equals(other: Any): Boolean = other match {
case that: SpatialContrastiveNormalization[T] =>
super.equals(that) &&
(that canEqual this) &&
kdim == that.kdim &&
normalizer == that.normalizer &&
nInputPlane == that.nInputPlane &&
kernel == that.kernel &&
threshold == that.threshold &&
thresval == that.thresval
case _ => false
}
override def hashCode(): Int = {
val state = Seq(super.hashCode(), kdim, normalizer,
nInputPlane, kernel, threshold, thresval)
state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
}
override def clearState() : this.type = {
super.clearState()
normalizer.clearState()
this
}
}
object SpatialContrastiveNormalization {
def apply[@specialized(Float, Double) T: ClassTag](
nInputPlane: Int = 1,
kernel: Tensor[T] = null,
threshold: Double = 1e-4,
thresval: Double = 1e-4)(
implicit ev: TensorNumeric[T]) : SpatialContrastiveNormalization[T] = {
new SpatialContrastiveNormalization[T](nInputPlane, kernel, threshold, thresval)
}
}
|
SeaOfOcean/BigDL
|
dl/src/main/scala/com/intel/analytics/bigdl/nn/SpatialContrastiveNormalization.scala
|
Scala
|
apache-2.0
| 3,731 |
package reaktor.scct.report
import org.specs2.mutable._
import java.io.File
import reaktor.scct.{IO, ClassTypes, Name, CoveredBlock}
import xml.XML
import org.specs2.specification.Scope
class CoberturaReporterSpec extends Specification {
sequential
val tmpDir = new File(System.getProperty("java.io.tmpdir", "/tmp"))
val sourceFile = new File(tmpDir, "CoberturaReportSpec.scala")
val outputFile = new File(tmpDir, "cobertura.xml")
val name = Name(sourceFile.getName, ClassTypes.Class, "reaktor.scct.report", "CoberturaReportSpec", "scct")
"report output" in new CleanEnv {
IO.write(sourceFile, 1.to(4).map((ii:Int) => "0123456789").mkString("\\n").getBytes("utf-8"))
val blocks = List(
new CoveredBlock("c1", 0, name, 0, false).increment,
new CoveredBlock("c1", 1, name, 11, false),
new CoveredBlock("c1", 1, name, 23, false).increment,
new CoveredBlock("c1", 2, name, 28, false).increment
)
val projectData = ProjectData("myProject", tmpDir, tmpDir, blocks.toArray)
val sut = new CoberturaReporter(projectData, new HtmlReportWriter(tmpDir))
sut.report
XML.loadFile(outputFile) must beEqualToIgnoringSpace(
<coverage line-rate="0.75">
<packages>
<package line-rate="0.75" name="reaktor.scct.report">
<classes>
<class line-rate="0.75" name="CoberturaReportSpec" filename="CoberturaReportSpec.scala">
<methods></methods>
<lines>
<line hits="1" number="1"></line>
<line hits="0" number="2"></line>
<line hits="2" number="3"></line>
</lines>
</class>
</classes>
</package>
</packages>
</coverage>
)
}
"tail recursive source line reading" in new CleanEnv {
IO.write(sourceFile, 1.to(4000).mkString("\\n").getBytes("utf-8"))
val projectData = ProjectData("myProject", tmpDir, tmpDir, blocks(4000, name).toArray)
val sut = new CoberturaReporter(projectData, new HtmlReportWriter(tmpDir))
sut.report
outputFile must beAFile
}
trait CleanEnv extends Scope {
if (sourceFile.exists()) sourceFile.delete()
if (outputFile.exists()) outputFile.delete()
}
def blocks(ii: Int, name: Name) = {
1.to(ii).map { ii:Int =>
val b = new CoveredBlock("c1", ii, name, ii, false)
if (ii % 2 == 0) b.increment
b
}.toList
}
}
|
mtkopone/scct
|
src/test/scala/reaktor/scct/report/CoberturaReporterSpec.scala
|
Scala
|
apache-2.0
| 2,443 |
package dotty.tools.backend.jvm
import scala.language.unsafeNulls
import dotty.tools.dotc.CompilationUnit
import dotty.tools.dotc.ast.Trees.{PackageDef, ValDef}
import dotty.tools.dotc.ast.tpd
import dotty.tools.dotc.core.Phases.Phase
import scala.collection.mutable
import scala.collection.JavaConverters._
import dotty.tools.dotc.transform.SymUtils._
import dotty.tools.dotc.interfaces
import dotty.tools.dotc.report
import dotty.tools.dotc.util.SourceFile
import java.util.Optional
import dotty.tools.dotc.core._
import dotty.tools.dotc.sbt.ExtractDependencies
import Contexts._
import Phases._
import Symbols._
import java.io.DataOutputStream
import java.nio.channels.ClosedByInterruptException
import dotty.tools.tasty.{ TastyBuffer, TastyHeaderUnpickler }
import scala.tools.asm
import scala.tools.asm.Handle
import scala.tools.asm.tree._
import tpd._
import StdNames._
import dotty.tools.io._
class GenBCode extends Phase {
override def phaseName: String = GenBCode.name
override def description: String = GenBCode.description
private val superCallsMap = new MutableSymbolMap[Set[ClassSymbol]]
def registerSuperCall(sym: Symbol, calls: ClassSymbol): Unit = {
val old = superCallsMap.getOrElse(sym, Set.empty)
superCallsMap.update(sym, old + calls)
}
private val entryPoints = new mutable.HashSet[String]()
def registerEntryPoint(s: String): Unit = entryPoints += s
private var myOutput: AbstractFile = _
private def outputDir(using Context): AbstractFile = {
if (myOutput eq null)
myOutput = ctx.settings.outputDir.value
myOutput
}
private var myPrimitives: DottyPrimitives = null
def run(using Context): Unit =
if myPrimitives == null then myPrimitives = new DottyPrimitives(ctx)
new GenBCodePipeline(
DottyBackendInterface(outputDir, superCallsMap),
myPrimitives
).run(ctx.compilationUnit.tpdTree)
override def runOn(units: List[CompilationUnit])(using Context): List[CompilationUnit] = {
outputDir match
case jar: JarArchive =>
updateJarManifestWithMainClass(jar, entryPoints.toList)
case _ =>
try super.runOn(units)
finally outputDir match {
case jar: JarArchive =>
if (ctx.run.nn.suspendedUnits.nonEmpty)
// If we close the jar the next run will not be able to write on the jar.
// But if we do not close it we cannot use it as part of the macro classpath of the suspended files.
report.error("Can not suspend and output to a jar at the same time. See suspension with -Xprint-suspension.")
jar.close()
case _ =>
}
}
private def updateJarManifestWithMainClass(jarArchive: JarArchive, entryPoints: List[String])(using Context): Unit =
val mainClass = Option.when(!ctx.settings.XmainClass.isDefault)(ctx.settings.XmainClass.value).orElse {
entryPoints match
case List(mainClass) =>
Some(mainClass)
case Nil =>
report.warning("No Main-Class designated or discovered.")
None
case mcs =>
report.warning(s"No Main-Class due to multiple entry points:\n ${mcs.mkString("\n ")}")
None
}
mainClass.map { mc =>
val manifest = Jar.WManifest()
manifest.mainClass = mc
val file = jarArchive.subdirectoryNamed("META-INF").fileNamed("MANIFEST.MF")
val os = file.output
manifest.underlying.write(os)
os.close()
}
end updateJarManifestWithMainClass
}
object GenBCode {
val name: String = "genBCode"
val description: String = "generate JVM bytecode"
}
class GenBCodePipeline(val int: DottyBackendInterface, val primitives: DottyPrimitives)(using Context) extends BCodeSyncAndTry {
import DottyBackendInterface.symExtensions
private var tree: Tree = _
private val sourceFile: SourceFile = ctx.compilationUnit.source
/** Convert a `dotty.tools.io.AbstractFile` into a
* `dotty.tools.dotc.interfaces.AbstractFile`.
*/
private def convertAbstractFile(absfile: dotty.tools.io.AbstractFile): interfaces.AbstractFile =
new interfaces.AbstractFile {
override def name = absfile.name
override def path = absfile.path
override def jfile = Optional.ofNullable(absfile.file)
}
final class PlainClassBuilder(cunit: CompilationUnit) extends SyncAndTryBuilder(cunit)
// class BCodePhase() {
private var bytecodeWriter : BytecodeWriter = null
private var mirrorCodeGen : JMirrorBuilder = null
/* ---------------- q1 ---------------- */
case class Item1(arrivalPos: Int, cd: TypeDef, cunit: CompilationUnit) {
def isPoison: Boolean = { arrivalPos == Int.MaxValue }
}
private val poison1 = Item1(Int.MaxValue, null, ctx.compilationUnit)
private val q1 = new java.util.LinkedList[Item1]
/* ---------------- q2 ---------------- */
case class SubItem2(classNode: asm.tree.ClassNode,
file: dotty.tools.io.AbstractFile)
case class Item2(arrivalPos: Int,
mirror: SubItem2,
plain: SubItem2) {
def isPoison: Boolean = { arrivalPos == Int.MaxValue }
}
private val poison2 = Item2(Int.MaxValue, null, null)
private val q2 = new _root_.java.util.LinkedList[Item2]
/* ---------------- q3 ---------------- */
/*
* An item of queue-3 (the last queue before serializing to disk) contains three of these
* (one for each of mirror and plain classes).
*
* @param jclassName internal name of the class
* @param jclassBytes bytecode emitted for the class SubItem3 represents
*/
case class SubItem3(
jclassName: String,
jclassBytes: Array[Byte],
jclassFile: dotty.tools.io.AbstractFile
)
case class Item3(arrivalPos: Int,
mirror: SubItem3,
plain: SubItem3) {
def isPoison: Boolean = { arrivalPos == Int.MaxValue }
}
private val i3comparator = new java.util.Comparator[Item3] {
override def compare(a: Item3, b: Item3) = {
if (a.arrivalPos < b.arrivalPos) -1
else if (a.arrivalPos == b.arrivalPos) 0
else 1
}
}
private val poison3 = Item3(Int.MaxValue, null, null)
private val q3 = new java.util.PriorityQueue[Item3](1000, i3comparator)
/*
* Pipeline that takes ClassDefs from queue-1, lowers them into an intermediate form, placing them on queue-2
*/
class Worker1(needsOutFolder: Boolean) {
private val lowerCaseNames = mutable.HashMap.empty[String, Symbol]
private def checkForCaseConflict(javaClassName: String, classSymbol: Symbol) = {
val lowerCaseName = javaClassName.toLowerCase
lowerCaseNames.get(lowerCaseName) match {
case None =>
lowerCaseNames.put(lowerCaseName, classSymbol)
case Some(dupClassSym) =>
// Order is not deterministic so we enforce lexicographic order between the duplicates for error-reporting
val (cl1, cl2) =
if (classSymbol.effectiveName.toString < dupClassSym.effectiveName.toString) (classSymbol, dupClassSym)
else (dupClassSym, classSymbol)
val same = classSymbol.effectiveName.toString == dupClassSym.effectiveName.toString
atPhase(typerPhase) {
if (same)
report.warning( // FIXME: This should really be an error, but then FromTasty tests fail
s"${cl1.show} and ${cl2.showLocated} produce classes that overwrite one another", cl1.sourcePos)
else
report.warning(s"${cl1.show} differs only in case from ${cl2.showLocated}. " +
"Such classes will overwrite one another on case-insensitive filesystems.", cl1.sourcePos)
}
}
}
def run(): Unit = {
while (true) {
val item = q1.poll
if (item.isPoison) {
q2 add poison2
return
}
else {
try { /*withCurrentUnit(item.cunit)*/(visit(item)) }
catch {
case ex: InterruptedException =>
throw ex
case ex: Throwable =>
println(s"Error while emitting ${item.cunit.source.file.name}")
throw ex
}
}
}
}
/*
* Checks for duplicate internal names case-insensitively,
* builds ASM ClassNodes for mirror and plain classes;
* enqueues them in queue-2.
*
*/
def visit(item: Item1): Boolean = {
val Item1(arrivalPos, cd, cunit) = item
val claszSymbol = cd.symbol
// -------------- mirror class, if needed --------------
val mirrorC =
if (claszSymbol.isTopLevelModuleClass) {
if (claszSymbol.companionClass == NoSymbol) {
mirrorCodeGen.genMirrorClass(claszSymbol, cunit)
} else {
report.log(s"No mirror class for module with linked class: ${claszSymbol.showFullName}")
null
}
} else null
// -------------- "plain" class --------------
val pcb = new PlainClassBuilder(cunit)
pcb.genPlainClass(cd)
val outF = if (needsOutFolder) getOutFolder(claszSymbol, pcb.thisName) else null;
val plainC = pcb.cnode
if (claszSymbol.isClass) // @DarkDimius is this test needed here?
for (binary <- ctx.compilationUnit.pickled.get(claszSymbol.asClass)) {
val store = if (mirrorC ne null) mirrorC else plainC
val tasty =
val outTastyFile = getFileForClassfile(outF, store.name, ".tasty")
val outstream = new DataOutputStream(outTastyFile.bufferedOutput)
try outstream.write(binary())
catch case ex: ClosedByInterruptException =>
try
outTastyFile.delete() // don't leave an empty or half-written tastyfile around after an interrupt
catch case _: Throwable =>
throw ex
finally outstream.close()
val uuid = new TastyHeaderUnpickler(binary()).readHeader()
val lo = uuid.getMostSignificantBits
val hi = uuid.getLeastSignificantBits
// TASTY attribute is created but only the UUID bytes are stored in it.
// A TASTY attribute has length 16 if and only if the .tasty file exists.
val buffer = new TastyBuffer(16)
buffer.writeUncompressedLong(lo)
buffer.writeUncompressedLong(hi)
buffer.bytes
val dataAttr = createJAttribute(nme.TASTYATTR.mangledString, tasty, 0, tasty.length)
store.visitAttribute(dataAttr)
}
// ----------- create files
val classNodes = List(mirrorC, plainC)
val classFiles = classNodes.map(cls =>
if (outF != null && cls != null) {
try {
checkForCaseConflict(cls.name, claszSymbol)
getFileForClassfile(outF, cls.name, ".class")
} catch {
case e: FileConflictException =>
report.error(s"error writing ${cls.name}: ${e.getMessage}")
null
}
} else null
)
// ----------- compiler and sbt's callbacks
val (fullClassName, isLocal) = atPhase(sbtExtractDependenciesPhase) {
(ExtractDependencies.classNameAsString(claszSymbol), claszSymbol.isLocal)
}
for ((cls, clsFile) <- classNodes.zip(classFiles)) {
if (cls != null) {
val className = cls.name.replace('/', '.')
if (ctx.compilerCallback != null)
ctx.compilerCallback.onClassGenerated(sourceFile, convertAbstractFile(clsFile), className)
if (ctx.sbtCallback != null) {
if (isLocal)
ctx.sbtCallback.generatedLocalClass(sourceFile.jfile.orElse(null), clsFile.file)
else {
ctx.sbtCallback.generatedNonLocalClass(sourceFile.jfile.orElse(null), clsFile.file,
className, fullClassName)
}
}
}
}
// ----------- hand over to pipeline-2
val item2 =
Item2(arrivalPos,
SubItem2(mirrorC, classFiles(0)),
SubItem2(plainC, classFiles(1)))
q2 add item2 // at the very end of this method so that no Worker2 thread starts mutating before we're done.
} // end of method visit(Item1)
} // end of class BCodePhase.Worker1
/*
* Pipeline that takes ClassNodes from queue-2. The unit of work depends on the optimization level:
*
* (a) no optimization involves:
* - converting the plain ClassNode to byte array and placing it on queue-3
*/
class Worker2 {
// lazy val localOpt = new LocalOpt(new Settings())
private def localOptimizations(classNode: ClassNode): Unit = {
// BackendStats.timed(BackendStats.methodOptTimer)(localOpt.methodOptimizations(classNode))
}
/* Return an array of all serializable lambdas in this class */
private def collectSerializableLambdas(classNode: ClassNode): Array[Handle] = {
val indyLambdaBodyMethods = new mutable.ArrayBuffer[Handle]
for (m <- classNode.methods.asScala) {
val iter = m.instructions.iterator
while (iter.hasNext) {
val insn = iter.next()
insn match {
case indy: InvokeDynamicInsnNode
if indy.bsm == BCodeBodyBuilder.lambdaMetaFactoryAltMetafactoryHandle =>
import java.lang.invoke.LambdaMetafactory.FLAG_SERIALIZABLE
val metafactoryFlags = indy.bsmArgs(3).asInstanceOf[Integer].toInt
val isSerializable = (metafactoryFlags & FLAG_SERIALIZABLE) != 0
if isSerializable then
val implMethod = indy.bsmArgs(1).asInstanceOf[Handle]
indyLambdaBodyMethods += implMethod
case _ =>
}
}
}
indyLambdaBodyMethods.toArray
}
/*
* Add:
*
* private static Object $deserializeLambda$(SerializedLambda l) {
* try return indy[scala.runtime.LambdaDeserialize.bootstrap, targetMethodGroup$0](l)
* catch {
* case i: IllegalArgumentException =>
* try return indy[scala.runtime.LambdaDeserialize.bootstrap, targetMethodGroup$1](l)
* catch {
* case i: IllegalArgumentException =>
* ...
* return indy[scala.runtime.LambdaDeserialize.bootstrap, targetMethodGroup${NUM_GROUPS-1}](l)
* }
*
* We use invokedynamic here to enable caching within the deserializer without needing to
* host a static field in the enclosing class. This allows us to add this method to interfaces
* that define lambdas in default methods.
*
* SI-10232 we can't pass arbitrary number of method handles to the final varargs parameter of the bootstrap
* method due to a limitation in the JVM. Instead, we emit a separate invokedynamic bytecode for each group of target
* methods.
*/
private def addLambdaDeserialize(classNode: ClassNode, implMethodsArray: Array[Handle]): Unit = {
import asm.Opcodes._
import BCodeBodyBuilder._
import bTypes._
import coreBTypes._
val cw = classNode
// Make sure to reference the ClassBTypes of all types that are used in the code generated
// here (e.g. java/util/Map) are initialized. Initializing a ClassBType adds it to
// `classBTypeFromInternalNameMap`. When writing the classfile, the asm ClassWriter computes
// stack map frames and invokes the `getCommonSuperClass` method. This method expects all
// ClassBTypes mentioned in the source code to exist in the map.
val serlamObjDesc = MethodBType(jliSerializedLambdaRef :: Nil, ObjectReference).descriptor
val mv = cw.visitMethod(ACC_PRIVATE + ACC_STATIC + ACC_SYNTHETIC, "$deserializeLambda$", serlamObjDesc, null, null)
def emitLambdaDeserializeIndy(targetMethods: Seq[Handle]): Unit = {
mv.visitVarInsn(ALOAD, 0)
mv.visitInvokeDynamicInsn("lambdaDeserialize", serlamObjDesc, lambdaDeserializeBootstrapHandle, targetMethods: _*)
}
val targetMethodGroupLimit = 255 - 1 - 3 // JVM limit. See See MAX_MH_ARITY in CallSite.java
val groups: Array[Array[Handle]] = implMethodsArray.grouped(targetMethodGroupLimit).toArray
val numGroups = groups.length
import scala.tools.asm.Label
val initialLabels = Array.fill(numGroups - 1)(new Label())
val terminalLabel = new Label
def nextLabel(i: Int) = if (i == numGroups - 2) terminalLabel else initialLabels(i + 1)
for ((label, i) <- initialLabels.iterator.zipWithIndex) {
mv.visitTryCatchBlock(label, nextLabel(i), nextLabel(i), jlIllegalArgExceptionRef.internalName)
}
for ((label, i) <- initialLabels.iterator.zipWithIndex) {
mv.visitLabel(label)
emitLambdaDeserializeIndy(groups(i).toIndexedSeq)
mv.visitInsn(ARETURN)
}
mv.visitLabel(terminalLabel)
emitLambdaDeserializeIndy(groups(numGroups - 1).toIndexedSeq)
mv.visitInsn(ARETURN)
}
def run(): Unit = {
while (true) {
val item = q2.poll
if (item.isPoison) {
q3 add poison3
return
}
else {
try {
val plainNode = item.plain.classNode
localOptimizations(plainNode)
val serializableLambdas = collectSerializableLambdas(plainNode)
if (serializableLambdas.nonEmpty)
addLambdaDeserialize(plainNode, serializableLambdas)
addToQ3(item)
} catch {
case ex: InterruptedException =>
throw ex
case ex: Throwable =>
println(s"Error while emitting ${item.plain.classNode.name}")
throw ex
}
}
}
}
private def addToQ3(item: Item2) = {
def getByteArray(cn: asm.tree.ClassNode): Array[Byte] = {
val cw = new CClassWriter(extraProc)
cn.accept(cw)
cw.toByteArray
}
val Item2(arrivalPos, SubItem2(mirror, mirrorFile), SubItem2(plain, plainFile)) = item
val mirrorC = if (mirror == null) null else SubItem3(mirror.name, getByteArray(mirror), mirrorFile)
val plainC = SubItem3(plain.name, getByteArray(plain), plainFile)
if (AsmUtils.traceSerializedClassEnabled && plain.name.contains(AsmUtils.traceSerializedClassPattern)) {
if (mirrorC != null) AsmUtils.traceClass(mirrorC.jclassBytes)
AsmUtils.traceClass(plainC.jclassBytes)
}
q3 add Item3(arrivalPos, mirrorC, plainC)
}
} // end of class BCodePhase.Worker2
var arrivalPos: Int = 0
/*
* A run of the BCodePhase phase comprises:
*
* (a) set-up steps (most notably supporting maps in `BCodeTypes`,
* but also "the" writer where class files in byte-array form go)
*
* (b) building of ASM ClassNodes, their optimization and serialization.
*
* (c) tear down (closing the classfile-writer and clearing maps)
*
*/
def run(t: Tree): Unit = {
this.tree = t
// val bcodeStart = Statistics.startTimer(BackendStats.bcodeTimer)
// val initStart = Statistics.startTimer(BackendStats.bcodeInitTimer)
arrivalPos = 0 // just in case
// scalaPrimitives.init()
bTypes.intializeCoreBTypes()
// Statistics.stopTimer(BackendStats.bcodeInitTimer, initStart)
// initBytecodeWriter invokes fullName, thus we have to run it before the typer-dependent thread is activated.
bytecodeWriter = initBytecodeWriter()
mirrorCodeGen = new JMirrorBuilder
val needsOutfileForSymbol = bytecodeWriter.isInstanceOf[ClassBytecodeWriter]
buildAndSendToDisk(needsOutfileForSymbol)
// closing output files.
bytecodeWriter.close()
// Statistics.stopTimer(BackendStats.bcodeTimer, bcodeStart)
if (ctx.compilerCallback != null)
ctx.compilerCallback.onSourceCompiled(sourceFile)
/* TODO Bytecode can be verified (now that all classfiles have been written to disk)
*
* (1) asm.util.CheckAdapter.verify()
* public static void verify(ClassReader cr, ClassLoader loader, boolean dump, PrintWriter pw)
* passing a custom ClassLoader to verify inter-dependent classes.
* Alternatively,
* - an offline-bytecode verifier could be used (e.g. Maxine brings one as separate tool).
* - -Xverify:all
*
* (2) if requested, check-java-signatures, over and beyond the syntactic checks in `getGenericSignature()`
*
*/
}
/*
* Sequentially:
* (a) place all ClassDefs in queue-1
* (b) dequeue one at a time from queue-1, convert it to ASM ClassNode, place in queue-2
* (c) dequeue one at a time from queue-2, convert it to byte-array, place in queue-3
* (d) serialize to disk by draining queue-3.
*/
private def buildAndSendToDisk(needsOutFolder: Boolean) = {
feedPipeline1()
// val genStart = Statistics.startTimer(BackendStats.bcodeGenStat)
(new Worker1(needsOutFolder)).run()
// Statistics.stopTimer(BackendStats.bcodeGenStat, genStart)
(new Worker2).run()
// val writeStart = Statistics.startTimer(BackendStats.bcodeWriteTimer)
drainQ3()
// Statistics.stopTimer(BackendStats.bcodeWriteTimer, writeStart)
}
/* Feed pipeline-1: place all ClassDefs on q1, recording their arrival position. */
private def feedPipeline1() = {
def gen(tree: Tree): Unit = {
tree match {
case EmptyTree => ()
case PackageDef(_, stats) => stats foreach gen
case ValDef(name, tpt, rhs) => () // module val not emitted
case cd: TypeDef =>
q1 add Item1(arrivalPos, cd, int.ctx.compilationUnit)
arrivalPos += 1
}
}
gen(tree)
q1 add poison1
}
/* Pipeline that writes classfile representations to disk. */
private def drainQ3() = {
def sendToDisk(cfr: SubItem3): Unit = {
if (cfr != null){
val SubItem3(jclassName, jclassBytes, jclassFile) = cfr
bytecodeWriter.writeClass(jclassName, jclassName, jclassBytes, jclassFile)
}
}
var moreComing = true
// `expected` denotes the arrivalPos whose Item3 should be serialized next
var expected = 0
while (moreComing) {
val incoming = q3.poll
moreComing = !incoming.isPoison
if (moreComing) {
val item = incoming
sendToDisk(item.mirror)
sendToDisk(item.plain)
expected += 1
}
}
// we're done
assert(q1.isEmpty, s"Some ClassDefs remained in the first queue: $q1")
assert(q2.isEmpty, s"Some classfiles remained in the second queue: $q2")
assert(q3.isEmpty, s"Some classfiles weren't written to disk: $q3")
}
//} // end of class BCodePhase
}
|
dotty-staging/dotty
|
compiler/src/dotty/tools/backend/jvm/GenBCode.scala
|
Scala
|
apache-2.0
| 22,852 |
package no.nextgentel.oss.akkatools.persistence.jdbcjournal
import java.time.{OffsetDateTime, ZoneId}
import java.util.Date
import javax.sql.DataSource
import no.nextgentel.oss.akkatools.cluster.ClusterNodeRepo
import org.slf4j.LoggerFactory
import org.sql2o.data.Row
import org.sql2o.quirks.OracleQuirks
import org.sql2o.{Sql2o, Sql2oException}
import scala.concurrent.duration.FiniteDuration
class StorageRepoImpl(sql2o: Sql2o, config:StorageRepoConfig, _errorHandler:Option[JdbcJournalErrorHandler]) extends StorageRepoWithClusterNodeRepo {
def this(dataSource:DataSource, config:StorageRepoConfig = StorageRepoConfig(), _errorHandler:Option[JdbcJournalErrorHandler] = None) = this(new Sql2o(dataSource, new OracleQuirks()), config, _errorHandler)
import scala.collection.JavaConverters._
// wrap it
val errorHandler = new JdbcJournalDetectFatalOracleErrorHandler(_errorHandler.getOrElse(
new JdbcJournalErrorHandler {
override def onError(e: Exception): Unit = LoggerFactory.getLogger(getClass).error("Fatal jdbc-journal-error (custom errorHandler not configured): " + e, e)
}
))
lazy val schemaPrefix = config.schemaName.map( s => s + ".").getOrElse("")
lazy val tableName_journal = s"${schemaPrefix}${config.tableName_journal}"
lazy val sequenceName_journalIndex = s"${schemaPrefix}${config.sequenceName_journalIndex}"
lazy val tableName_snapshot = s"${schemaPrefix}${config.tableName_snapshot}"
def loadJournalEntries(persistenceId: PersistenceId, fromSequenceNr: Long, toSequenceNr: Long, max: Long): List[JournalEntryDto] = {
val sequenceNrColumnName = persistenceId match {
case p:PersistenceIdSingle => "sequenceNr"
case p:PersistenceIdTagsOnly => "journalIndex"
}
val preSql = s"select * from (select typePath, id, $sequenceNrColumnName, persistentRepr, updated from ${tableName_journal} where "
val postSql = s" and $sequenceNrColumnName >= :fromSequenceNr and $sequenceNrColumnName <= :toSequenceNr and persistentRepr is not null order by $sequenceNrColumnName) where rownum <= :max"
// Must use open due to clob/blob
val conn = sql2o.open
try {
val query = persistenceId match {
case p:PersistenceIdSingle =>
conn.createQuery(preSql + " typePath = :typePath and id = :id " + postSql)
.addParameter("typePath", p.tag)
.addParameter("id", p.uniqueId)
case p:PersistenceIdSingleTagOnly =>
conn.createQuery(preSql + " typePath = :typePath " + postSql)
.addParameter("typePath", p.tag)
case p:PersistenceIdMultipleTags =>
conn.createQuery(preSql + " typePath in (" + p.tags.map( s => "'" + s + "'" ).mkString(",") + ") " + postSql)
}
query.addParameter("fromSequenceNr", fromSequenceNr).addParameter("toSequenceNr", toSequenceNr).addParameter("max", max)
val table = query.executeAndFetchTable
table.rows.asScala.toList.map{
r:Row =>
JournalEntryDto(
r.getString("typePath"),
r.getString("id"),
r.getLong(sequenceNrColumnName),
r.getObject("persistentRepr", classOf[Array[Byte]]),
null,
OffsetDateTime.ofInstant(r.getDate("updated").toInstant(), ZoneId.systemDefault()))
}
} finally {
if (conn != null) conn.close()
}
}
def insertPersistentReprList(dtoList: Seq[JournalEntryDto]) {
val sql = s"insert into ${tableName_journal} (typePath, id, sequenceNr, journalIndex, persistentRepr, payload_write_only, updated) " +
s"values (:typePath, :id, :sequenceNr,${sequenceName_journalIndex}.nextval, :persistentRepr, :payload_write_only, sysdate)"
// Insert the whole list in one transaction
val c = sql2o.beginTransaction()
try {
dtoList.foreach {
dto =>
val insert = c.createQuery(sql)
try {
insert.addParameter("typePath", dto.typePath)
.addParameter("id", dto.uniqueId)
.addParameter("sequenceNr", dto.sequenceNr)
.addParameter("persistentRepr", dto.persistentRepr)
.addParameter("payload_write_only", dto.payloadWriteOnly)
.executeUpdate
} catch {
case e: Sql2oException => {
val exception = new Exception(s"Error updating journal for typePath=${dto.typePath}, id=${dto.uniqueId} and sequenceNr=${dto.sequenceNr}: ${e.getMessage}", e)
errorHandler.onError(e)
throw exception
}
} finally {
insert.close()
}
}
c.commit(true)
} catch {
case e:Throwable =>
c.rollback(true)
throw e
}
}
// Since we need to keep track of the highest sequenceNr even after we have deleted an entry,
// This method only clears the columns persistentRepr and payload_write_only to save space
def deleteJournalEntryTo(persistenceId: PersistenceIdSingle, toSequenceNr: Long) {
val sql = s"update ${tableName_journal} set persistentRepr = null, payload_write_only = null where typePath = :typePath and id = :id and sequenceNr <= :toSequenceNr"
val c = sql2o.open()
try {
c.createQuery(sql).addParameter("typePath", persistenceId.tag).addParameter("id", persistenceId.uniqueId).addParameter("toSequenceNr", toSequenceNr).executeUpdate
} finally {
c.close()
}
}
// This one both looks at existing once and 'delete once' (with persistentRepr = null)
def findHighestSequenceNr(persistenceId: PersistenceId, fromSequenceNr: Long): Long = {
val sequenceNrColumnName = persistenceId match {
case p:PersistenceIdSingle => "sequenceNr"
case p:PersistenceIdTagsOnly => "journalIndex"
}
val preSql = s"select max($sequenceNrColumnName) from ${tableName_journal} where "
val postSql = s" and $sequenceNrColumnName>=:fromSequenceNr"
val c = sql2o.open
try {
val query = persistenceId match {
case p:PersistenceIdSingle =>
c.createQuery( preSql + " typePath = :typePath and id = :id " + postSql)
.addParameter("typePath", p.tag)
.addParameter("id", p.uniqueId)
case p:PersistenceIdSingleTagOnly =>
c.createQuery( preSql + " typePath = :typePath " + postSql)
.addParameter("typePath", p.tag)
case p:PersistenceIdMultipleTags =>
c.createQuery( preSql + " typePath in (" + p.tags.map( s => "'" + s + "'").mkString(",") + ") " + postSql)
}
query.addParameter("fromSequenceNr", fromSequenceNr)
val table = query.executeAndFetchTable
if (table.rows.size == 0) {
return Math.max(fromSequenceNr, 0L)
}
val number = Option(table.rows.get(0).getLong(0))
if (number.isEmpty) {
return Math.max(fromSequenceNr, 0L)
}
return Math.max(fromSequenceNr, number.get)
} finally {
c.close()
}
}
def writeSnapshot(e: SnapshotEntry): Unit = {
val sql = s"insert into ${tableName_snapshot} (persistenceId,sequenceNr,timestamp,snapshot,snapshotClassname,serializerId,updated) values (:persistenceId,:sequenceNr,:timestamp,:snapshot,:snapshotClassname,:serializerId,sysdate)"
val c = sql2o.open()
var deleteAndRetry = false
try {
c.createQuery(sql)
.addParameter("persistenceId", e.persistenceId)
.addParameter("sequenceNr", e.sequenceNr)
.addParameter("timestamp", e.timestamp)
.addParameter("snapshot", e.snapshot)
.addParameter("snapshotClassname", e.manifest)
.addParameter("serializerId", e.serializerId.get)
.executeUpdate
} catch {
case ex: Sql2oException => {
errorHandler.onError(ex)
throw ex
}
} finally {
c.close()
}
}
def findSnapshotEntry(persistenceId: String, maxSequenceNr: Long, maxTimestamp: Long): Option[SnapshotEntry] = {
val sql = s"select * from (Select * from ${tableName_snapshot} where persistenceId = :persistenceId and sequenceNr <= :maxSequenceNr and timestamp <= :maxTimestamp order by sequenceNr desc, timestamp desc) where rownum <= 1"
// Must use open due to clob/blob
val conn = sql2o.open
try {
val t = conn.createQuery(sql).addParameter("persistenceId", persistenceId).addParameter("maxSequenceNr", maxSequenceNr).addParameter("maxTimestamp", maxTimestamp).executeAndFetchTable
if (t.rows.isEmpty) {
None
} else {
val row: Row = t.rows.get(0)
val e = SnapshotEntry(
row.getString("persistenceId"),
row.getLong("sequenceNr"),
row.getLong("timestamp"),
Option(row.getObject("snapshot", classOf[Array[Byte]]).asInstanceOf[Array[Byte]]).getOrElse( Array[Byte]() ), // Empty BLOB in Oracle is returned as NULL
row.getString("snapshotClassname"),
Option(row.getInteger("serializerId")).map(_.toInt).filter( i => i != 0))
Some(e)
}
} finally {
if (conn != null) conn.close()
}
}
def deleteSnapshot(persistenceId: String, sequenceNr: Long, timestamp: Long) {
val sql = s"delete from ${tableName_snapshot} where persistenceId = :persistenceId and sequenceNr = :sequenceNr and (:timestamp = 0 OR timestamp = :timestamp)"
val c = sql2o.open()
try {
c.createQuery(sql).addParameter("persistenceId", persistenceId).addParameter("sequenceNr", sequenceNr).addParameter("timestamp", timestamp).executeUpdate
} finally {
c.close()
}
}
def deleteSnapshotsMatching(persistenceId: String, maxSequenceNr: Long, maxTimestamp: Long) {
val sql = s"delete from ${tableName_snapshot} where persistenceId = :persistenceId and sequenceNr <= :maxSequenceNr and timestamp <= :maxTimestamp"
val c = sql2o.open()
try {
c.createQuery(sql).addParameter("persistenceId", persistenceId).addParameter("maxSequenceNr", maxSequenceNr).addParameter("maxTimestamp", maxTimestamp).executeUpdate
} finally {
c.close()
}
}
def writeClusterNodeAlive(nodeName: String, timestamp: OffsetDateTime, joined:Boolean) {
var sql = s"update ${schemaPrefix}t_cluster_nodes set lastSeen = :timestamp, joined = :joined where nodeName = :nodeName"
val c = sql2o.open()
try {
val joinedAsInt:Int = if (joined) 1 else 0
val updatedRows: Int = c.createQuery(sql)
.addParameter("nodeName", nodeName)
.addParameter("timestamp", Date.from(timestamp.toInstant))
.addParameter("joined", joinedAsInt)
.executeUpdate.getResult
if (updatedRows == 0) {
sql = s"insert into ${schemaPrefix}t_cluster_nodes(nodeName, lastSeen, joined) values (:nodeName, :timestamp, :joined)"
c.createQuery(sql)
.addParameter("nodeName", nodeName)
.addParameter("timestamp", Date.from(timestamp.toInstant))
.addParameter("joined", joinedAsInt)
.executeUpdate
}
} finally {
c.close()
}
}
def removeClusterNodeAlive(nodeName: String) {
val sql: String = s"delete from ${schemaPrefix}t_cluster_nodes where nodeName = :nodeName"
val c = sql2o.open()
try {
c.createQuery(sql).addParameter("nodeName", nodeName).executeUpdate.getResult
} finally {
c.close()
}
}
def findAliveClusterNodes(clusterNodesAliveSinceCheck: FiniteDuration, onlyJoined:Boolean): List[String] = {
val aliveAfter = OffsetDateTime.now.minusSeconds(clusterNodesAliveSinceCheck.toSeconds.toInt)
val sql = s"select nodeName from ${schemaPrefix}t_cluster_nodes where lastSeen >= :aliveAfter" + (if (onlyJoined) " and joined = 1" else "") + " order by joined desc, lastSeen desc"
val c = sql2o.open()
try {
c.createQuery(sql).addParameter("aliveAfter", Date.from(aliveAfter.toInstant)).executeScalarList(classOf[String]).asScala.toList
} finally {
c.close()
}
}
}
|
NextGenTel/akka-tools
|
akka-tools-jdbc-journal/src/main/scala/no/nextgentel/oss/akkatools/persistence/jdbcjournal/StorageRepoImpl.scala
|
Scala
|
mit
| 11,993 |
package com.twitter.util
import com.twitter.conversions.time._
import java.util.concurrent.{CancellationException, ExecutorService}
import java.util.concurrent.atomic.AtomicInteger
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.Matchers.any
import org.mockito.Mockito.{never, verify, when}
import org.scalatest.FunSuite
import org.scalatest.concurrent.{IntegrationPatience, Eventually}
import org.scalatest.junit.JUnitRunner
import org.scalatest.mockito.MockitoSugar
@RunWith(classOf[JUnitRunner])
class TimerTest extends FunSuite
with MockitoSugar
with Eventually
with IntegrationPatience
{
private def testTimerRunsWithLocals(timer: Timer): Unit = {
val timerLocal = new AtomicInteger(0)
val local = new Local[Int]
val expectedVal = 99
local.let(expectedVal) {
timer.schedule(Time.now + 10.millis) {
timerLocal.set(local().getOrElse(-1))
}
}
eventually {
assert(expectedVal == timerLocal.get())
}
timer.stop()
}
test("ThreadStoppingTimer should stop timers in a different thread") {
val executor = mock[ExecutorService]
val underlying = mock[Timer]
val timer = new ThreadStoppingTimer(underlying, executor)
verify(executor, never()).submit(any[Runnable])
timer.stop()
verify(underlying, never()).stop()
val runnableCaptor = ArgumentCaptor.forClass(classOf[Runnable])
verify(executor).submit(runnableCaptor.capture())
runnableCaptor.getValue.run()
verify(underlying).stop()
}
test("ReferenceCountingTimer calls the factory when it is first acquired") {
val underlying = mock[Timer]
val factory = mock[() => Timer]
when(factory()).thenReturn(underlying)
val refcounted = new ReferenceCountingTimer(factory)
verify(factory, never()).apply()
refcounted.acquire()
verify(factory).apply()
}
test("ReferenceCountingTimer stops the underlying timer when acquire count reaches 0") {
val underlying = mock[Timer]
val factory = mock[() => Timer]
when(factory()).thenReturn(underlying)
val refcounted = new ReferenceCountingTimer(factory)
refcounted.acquire()
refcounted.acquire()
refcounted.acquire()
verify(factory).apply()
refcounted.stop()
verify(underlying, never()).stop()
refcounted.stop()
verify(underlying, never()).stop()
refcounted.stop()
verify(underlying).stop()
}
test("ReferenceCountingTimer should have Locals") {
val timer = new ReferenceCountingTimer(() => new JavaTimer())
timer.acquire()
testTimerRunsWithLocals(timer)
}
test("ScheduledThreadPoolTimer should initialize and stop") {
val timer = new ScheduledThreadPoolTimer(1)
assert(timer != null)
timer.stop()
}
test("ScheduledThreadPoolTimer should increment a counter") {
val timer = new ScheduledThreadPoolTimer
val counter = new AtomicInteger(0)
timer.schedule(100.millis, 200.millis) {
counter.incrementAndGet()
}
eventually { assert(counter.get() >= 2) }
timer.stop()
}
test("ScheduledThreadPoolTimer should schedule(when)") {
val timer = new ScheduledThreadPoolTimer
val counter = new AtomicInteger(0)
timer.schedule(Time.now + 200.millis) {
counter.incrementAndGet()
}
eventually { assert(counter.get() == 1) }
timer.stop()
}
test("ScheduledThreadPoolTimer should cancel schedule(when)") {
val timer = new ScheduledThreadPoolTimer
val counter = new AtomicInteger(0)
val task = timer.schedule(Time.now + 200.millis) {
counter.incrementAndGet()
}
task.cancel()
Thread.sleep(1.seconds.inMillis)
assert(counter.get() != 1)
timer.stop()
}
test("ScheduledThreadPoolTimer should have Locals") {
testTimerRunsWithLocals(new ScheduledThreadPoolTimer())
}
test("JavaTimer should not stop working when an exception is thrown") {
var errors = 0
var latch = new CountDownLatch(1)
val timer = new JavaTimer {
override def logError(t: Throwable) {
errors += 1
latch.countDown()
}
}
timer.schedule(Time.now) {
throw new scala.MatchError("huh")
}
latch.await(30.seconds)
assert(errors == 1)
var result = 0
latch = new CountDownLatch(1)
timer.schedule(Time.now) {
result = 1 + 1
latch.countDown()
}
latch.await(30.seconds)
assert(result == 2)
assert(errors == 1)
}
test("JavaTimer should schedule(when)") {
val timer = new JavaTimer
val counter = new AtomicInteger(0)
timer.schedule(Time.now + 20.millis) {
counter.incrementAndGet()
}
Thread.sleep(40.milliseconds.inMillis)
eventually { assert(counter.get() == 1) }
timer.stop()
}
test("JavaTimer should cancel schedule(when)") {
val timer = new JavaTimer
val counter = new AtomicInteger(0)
val task = timer.schedule(Time.now + 20.millis) {
counter.incrementAndGet()
}
task.cancel()
Thread.sleep(1.seconds.inMillis)
assert(counter.get() != 1)
timer.stop()
}
test("JavaTimer should have Locals") {
testTimerRunsWithLocals(new JavaTimer())
}
test("Timer should doLater") {
val result = "boom"
Time.withCurrentTimeFrozen { ctl =>
val timer = new MockTimer
val f = timer.doLater(1.millis)(result)
assert(!f.isDefined)
ctl.advance(2.millis)
timer.tick()
assert(f.isDefined)
assert(Await.result(f) == result)
}
}
test("Timer should doLater throws exception") {
Time.withCurrentTimeFrozen { ctl =>
val timer = new MockTimer
val ex = new Exception
def task: String = throw ex
val f = timer.doLater(1.millis)(task)
assert(!f.isDefined)
ctl.advance(2.millis)
timer.tick()
assert(f.isDefined)
intercept[Throwable] { Await.result(f, 0.millis) }
}
}
test("Timer should interrupt doLater") {
val result = "boom"
Time.withCurrentTimeFrozen { ctl =>
val timer = new MockTimer
val f = timer.doLater(1.millis)(result)
assert(!f.isDefined)
f.raise(new Exception)
ctl.advance(2.millis)
timer.tick()
assert(f.isDefined)
intercept[CancellationException] { Await.result(f) }
}
}
test("Timer should doAt") {
val result = "boom"
Time.withCurrentTimeFrozen { ctl =>
val timer = new MockTimer
val f = timer.doAt(Time.now + 1.millis)(result)
assert(!f.isDefined)
ctl.advance(2.millis)
timer.tick()
assert(f.isDefined)
assert(Await.result(f) == result)
}
}
test("Timer should cancel doAt") {
val result = "boom"
Time.withCurrentTimeFrozen { ctl =>
val timer = new MockTimer
val f = timer.doAt(Time.now + 1.millis)(result)
assert(!f.isDefined)
val exc = new Exception
f.raise(exc)
ctl.advance(2.millis)
timer.tick()
assert {
f.poll match {
case Some(Throw(e: CancellationException)) if e.getCause eq exc => true
case _ => false
}
}
}
}
test("Timer should schedule(pre-epoch, negative-period)") {
Time.withCurrentTimeFrozen { ctl =>
val timer = new MockTimer
val counter = new AtomicInteger(0)
timer.schedule(Time.Bottom, Duration.Bottom)(counter.incrementAndGet())
ctl.advance(1.millis)
timer.tick()
assert(counter.get() == 1)
ctl.advance(1.millis)
timer.tick()
assert(counter.get() == 2)
}
}
test("Timer should schedule(when)") {
Time.withCurrentTimeFrozen { ctl =>
val timer = new MockTimer
val counter = new AtomicInteger(0)
timer.schedule(Time.now + 1.millis)(counter.incrementAndGet())
ctl.advance(2.millis)
timer.tick()
assert(counter.get() == 1)
}
}
test("Timer should cancel schedule(when)") {
Time.withCurrentTimeFrozen { ctl =>
val timer = new MockTimer
val counter = new AtomicInteger(0)
val task = timer.schedule(Time.now + 1.millis)(counter.incrementAndGet())
task.cancel()
ctl.advance(2.millis)
timer.tick()
assert(counter.get() == 0)
}
}
test("Timer should cancel schedule(duration)") {
Time.withCurrentTimeFrozen { ctl =>
val timer = new MockTimer
val counter = new AtomicInteger(0)
val task = timer.schedule(1.millis)(counter.incrementAndGet())
ctl.advance(2.millis)
timer.tick()
task.cancel()
ctl.advance(2.millis)
timer.tick()
assert(counter.get() == 1)
}
}
private def mockTimerLocalPropagation(
timer: MockTimer,
localValue: Int
): Int = {
Time.withCurrentTimeFrozen { tc =>
val timerLocal = new AtomicInteger(0)
val local = new Local[Int]
local.let(localValue) {
timer.schedule(Time.now + 10.millis) {
timerLocal.set(local().getOrElse(-1))
}
}
tc.advance(20.millis)
timer.tick()
timerLocal.get()
}
}
test("MockTimer propagateLocals") {
val timer = new MockTimer()
assert(mockTimerLocalPropagation(timer, 99) == 99)
}
private class SomeEx extends Exception
private def testTimerUsesLocalMonitor(timer: Timer): Unit = {
val seen = new AtomicInteger(0)
val monitor = Monitor.mk { case _: SomeEx =>
seen.incrementAndGet()
true
}
Monitor.using(monitor) {
timer.schedule(Time.now + 10.millis) { throw new SomeEx }
}
eventually {
assert(1 == seen.get)
}
timer.stop()
}
test("JavaTimer uses local Monitor") {
val timer = new JavaTimer(true, Some("TimerTest"))
testTimerUsesLocalMonitor(timer)
}
test("ScheduledThreadPoolTimer uses local Monitor") {
val timer = new ScheduledThreadPoolTimer()
testTimerUsesLocalMonitor(timer)
}
}
|
BuoyantIO/twitter-util
|
util-core/src/test/scala/com/twitter/util/TimerTest.scala
|
Scala
|
apache-2.0
| 9,836 |
/*
* Copyright 2009-2010 LinkedIn, 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.linkedin.norbert
package network
import com.google.protobuf.Message
import java.util.concurrent.{TimeoutException, ExecutionException, TimeUnit}
/**
* An iterator over the responses from a network request.
*/
trait ResponseIterator[ResponseMsg] extends Iterator[ResponseMsg] {
/**
* Calculates whether you have iterated over all of the responses. A return value of true indicates
* that there are more responses, it does not indicate that those responses have been received and
* are immediately available for processing.
*
* @return true if there are additional responses, false otherwise
*/
def hasNext: Boolean
/**
* Specifies whether a response is available without blocking.
*
* @return true if a response is available without blocking, false otherwise
*/
def nextAvailable: Boolean
/**
* Retrieves the next response, if necessary waiting until a response is available.
*
* @return a response
* @throws ExecutionException thrown if there was an error
*/
@throws(classOf[ExecutionException])
def next: ResponseMsg
/**
* Retrieves the next response, waiting for the specified time if there are no responses available.
*
* @param timeout how long to wait before giving up, in terms of <code>unit</code>
* @param unit the <code>TimeUnit</code> that <code>timeout</code> should be interpreted in
*
* @return a response
* @throws ExecutionException thrown if there was an error
* @throws TimeoutException thrown if a response wasn't available before the specified timeout
* @throws InterruptedException thrown if the thread was interrupted while waiting for the next response
*/
@throws(classOf[ExecutionException])
@throws(classOf[TimeoutException])
@throws(classOf[InterruptedException])
def next(timeout: Long, unit: TimeUnit): ResponseMsg
}
/**
* Internal-use only
*/
trait DynamicResponseIterator[ResponseMsg] extends ResponseIterator[ResponseMsg] {
/**
* Adjust # of remaining items.
*/
def addAndGet(delta:Int) : Int
}
|
thesiddharth/norbert
|
network/src/main/scala/com/linkedin/norbert/network/ResponseIterator.scala
|
Scala
|
apache-2.0
| 2,656 |
package ee.cone.c4gate
import java.util.UUID
import ee.cone.c4actor.LEvent.{delete, update}
import ee.cone.c4actor._
import ee.cone.c4assemble._
import ee.cone.c4gate.CommonFilterProtocol._
import ee.cone.c4gate.TestTodoProtocol.B_TodoTask
import ee.cone.c4proto._
import ee.cone.c4ui._
import ee.cone.c4vdom.{TagStyles, Tags}
import ee.cone.c4vdom.Types.ViewRes
class TestTodoApp extends ServerApp
with EnvConfigApp with VMExecutionApp
with KafkaProducerApp with KafkaConsumerApp
with ParallelObserversApp with TreeIndexValueMergerFactoryApp
with UIApp
with TestTagsApp
with NoAssembleProfilerApp
with ManagementApp
with FileRawSnapshotApp
with PublicViewAssembleApp
with CommonFilterInjectApp
with CommonFilterPredicateFactoriesApp
with FilterPredicateBuilderApp
with ModelAccessFactoryApp
with AccessViewApp
with DateBeforeAccessViewApp
with ContainsAccessViewApp
with SessionAttrApp
with MortalFactoryApp
with AvailabilityApp
with TestTodoRootViewApp
with BasicLoggingApp
{
override def protocols: List[Protocol] =
CommonFilterProtocol :: TestTodoProtocol :: super.protocols
override def assembles: List[Assemble] =
new FromAlienTaskAssemble("/react-app.html") ::
super.assembles
//override def longTxWarnPeriod: Long = 10L
}
@protocol object TestTodoProtocolBase {
@Id(0x0001) case class B_TodoTask(
@Id(0x0002) srcId: String,
@Id(0x0003) createdAt: Long,
@Id(0x0004) comments: String
)
}
import TestTodoAccess._
@fieldAccess object TestTodoAccessBase {
lazy val comments: ProdLens[B_TodoTask,String] =
ProdLens.of(_.comments, UserLabel en "(comments)")
lazy val createdAt: ProdLens[B_TodoTask,Long] =
ProdLens.of(_.createdAt, UserLabel en "(created at)")
lazy val createdAtFlt =
SessionAttr(Id(0x0006), classOf[B_DateBefore], UserLabel en "(created before)")
lazy val commentsFlt =
SessionAttr(Id(0x0007), classOf[B_Contains], IsDeep, UserLabel en "(comments contain)")
}
trait TestTodoRootViewApp extends ByLocationHashViewsApp {
def testTags: TestTags[Context]
def tags: Tags
def tagStyles: TagStyles
def modelAccessFactory: ModelAccessFactory
def filterPredicateBuilder: FilterPredicateBuilder
def commonFilterConditionChecks: CommonFilterConditionChecks
def sessionAttrAccessFactory: SessionAttrAccessFactory
def accessViewRegistry: AccessViewRegistry
def untilPolicy: UntilPolicy
private lazy val testTodoRootView = TestTodoRootView()(
testTags,
tags,
tagStyles,
modelAccessFactory,
filterPredicateBuilder,
commonFilterConditionChecks,
accessViewRegistry,
untilPolicy
)
override def byLocationHashViews: List[ByLocationHashView] =
testTodoRootView :: super.byLocationHashViews
}
case class TestTodoRootView(locationHash: String = "todo")(
tags: TestTags[Context],
mTags: Tags,
styles: TagStyles,
contextAccess: ModelAccessFactory,
filterPredicates: FilterPredicateBuilder,
commonFilterConditionChecks: CommonFilterConditionChecks,
accessViewRegistry: AccessViewRegistry,
untilPolicy: UntilPolicy
) extends ByLocationHashView {
def view: Context ⇒ ViewRes = untilPolicy.wrap{ local ⇒
import mTags._
import commonFilterConditionChecks._
val filterPredicate = filterPredicates.create[B_TodoTask](local)
.add(commentsFlt, comments)
.add(createdAtFlt, createdAt)
val filterList = for {
access ← filterPredicate.accesses
tag ← accessViewRegistry.view(access)(local)
} yield tag
// filterPredicate.accesses.flatMap { case a if a.initialValue => List(a to sub1, a to sub2) case a => List(a) }
val btnList = List(
divButton("add")(
TxAdd(update(B_TodoTask(UUID.randomUUID.toString,System.currentTimeMillis,"")))
)(List(text("text","+")))
)
val todoTasks = ByPK(classOf[B_TodoTask]).of(local).values
.filter(filterPredicate.condition.check).toList.sortBy(-_.createdAt)
val taskLines = for {
prod ← todoTasks
task ← contextAccess to prod
} yield div(prod.srcId,Nil)(List(
tags.input(task to comments),
div("remove",List(styles.width(100),styles.displayInlineBlock))(List(
divButton("remove")(TxAdd(delete(prod)))(List(text("caption","-")))
))
))
List(filterList,btnList,taskLines).flatten
}
}
/*
branches:
S_BranchResult --> BranchRel-s
S_BranchResult [prev] + BranchRel-s --> BranchTask [decode]
...
BranchHandler + BranchRel-s + MessageFromAlien-s -> TxTransform
ui:
FromAlienState --> BranchRel [encode]
BranchTask --> FromAlienTask [match host etc]
BranchTask + View --> BranchHandler
BranchTask + CanvasHandler --> BranchHandler
custom:
FromAlienTask --> View [match hash]
BranchTask --> CanvasHandler
S_BranchResult --> BranchRel-s --> BranchTask --> [custom] --> BranchHandler --> TxTransform
*/
|
wregs/c4proto
|
c4gate-sse-example/src/main/scala/ee/cone/c4gate/TestTodo.scala
|
Scala
|
apache-2.0
| 4,891 |
package com.github.al.roulette.player.api
import java.util.UUID
import akka.NotUsed
import com.github.al.roulette.player.api.PlayerService.PlayerEventTopicName
import com.lightbend.lagom.scaladsl.api.broker.Topic
import com.lightbend.lagom.scaladsl.api.{Descriptor, Service, ServiceCall}
trait PlayerService extends Service {
def registerPlayer: ServiceCall[Player, PlayerId]
def login: ServiceCall[PlayerCredentials, PlayerAccessToken]
def getPlayer(id: UUID): ServiceCall[NotUsed, Player]
def playerEvents: Topic[PlayerEvent]
final override def descriptor: Descriptor = {
import Service._
named("player").withCalls(
pathCall("/api/player", registerPlayer),
pathCall("/api/player/login", login),
pathCall("/api/player/:id", getPlayer _)
).withTopics(
topic(PlayerEventTopicName, this.playerEvents)
).withAutoAcl(true)
}
}
object PlayerService {
final val PlayerEventTopicName = "player-PlayerEvent"
}
|
andrei-l/reactive-roulette
|
player-api/src/main/scala/com/github/al/roulette/player/api/PlayerService.scala
|
Scala
|
mit
| 965 |
package com.bigjason.semver
trait SemVerTestingSupport {
}
|
bigjason/semver
|
src/test/scala/com/bigjason/semver/SemVerTestingSupport.scala
|
Scala
|
apache-2.0
| 61 |
/*
* Copyright (C) 2014 - 2017 Contributors as noted in the AUTHORS.md file
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.wegtam.tensei.agent.processor
import akka.actor.ActorRef
import com.wegtam.tensei.adt.{ DFASDL, MappingTransformation, Recipe }
import org.w3c.dom.traversal.TreeWalker
/**
* A sealed trait for the messages a mapper actor can send and receive.
*/
sealed trait MapperMessages
/**
* A companion object for the trait to keep the namespace clean.
*/
object MapperMessages {
/**
* Initialise the mapper worker with some basic state data that is needed
* for each mapping.
*
* @param fetcher The actor ref of the data fetcher.
* @param sourceDataTrees A list of source data trees paired with their dfasdl.
* @param targetDfasdl The target DFASDL.
* @param targetTreeWalker A tree walker used to traverse the target dfasdl tree.
* @param writer An actor ref of the data writer actor.
*/
case class Initialise(
fetcher: ActorRef,
sourceDataTrees: List[SourceDataTreeListEntry],
targetDfasdl: DFASDL,
targetTreeWalker: TreeWalker,
writer: ActorRef
) extends MapperMessages
/**
* Reports that a mapping has been processed successfully.
*
* @param lastWriterMessageNumber The number of the last writer message that was sent out.
*/
case class MappingProcessed(
lastWriterMessageNumber: Long
) extends MapperMessages
/**
* Instruct the actor to process the given mapping obeying the given parameters.
*
* @param mapping The mapping that should be processed.
* @param lastWriterMessageNumber The number of the last writer message that was sent out.
* @param maxLoops The number of times the recipe will be executed at most. This value passed down from the [[RecipeWorker]].
* @param recipeMode The mode of the parent recipe which triggers different processing/mapping modes.
* @param sequenceRow An option to the currently processed sequence row.
*/
case class ProcessMapping(
mapping: MappingTransformation,
lastWriterMessageNumber: Long,
maxLoops: Long,
recipeMode: Recipe.RecipeMode,
sequenceRow: Option[Long] = None
) extends MapperMessages
/**
* Process the next element pair in the currently processed mapping.
*/
case object ProcessNextPair extends MapperMessages
/**
* This messages indicates that the actor is ready to process a mapping.
*/
case object Ready extends MapperMessages
/**
* Instruct the actor to stop itself.
*/
case object Stop extends MapperMessages
}
|
Tensei-Data/tensei-agent
|
src/main/scala/com/wegtam/tensei/agent/processor/MapperMessages.scala
|
Scala
|
agpl-3.0
| 3,250 |
/*
* Copyright (C) 2017 Michael Dippery <[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 com.mipadi.jupiter.text
import java.util.regex.{Matcher, Pattern}
/** Provides operations for working with string objects.
*
* Strings can implicitly be converted to a $matcherstring, which allows
* them to use the `~=` operator to check if a string matches a regex:
*
* {{{
* import com.mipadi.jupiter.text.strings._
* val matches = "my string" =~ "string$"
* }}}
*
* @define matcherstring
* `[[com.mipadi.jupiter.text.strings.MatcherString MatcherString]]`
*/
object strings {
/** Implicitly converts Scala strings to $matcherstring objects.
*
* This implicit conversion allows Scala strings to use the `~=` operator
* to check if they match a given regex:
*
* {{{
* import com.mipadi.jupiter.text.strings._
* val matches = "my string" =~ "string$"
* }}}
*
* @define matcherstring
* `[[com.mipadi.jupiter.text.strings.MatcherString MatcherString]]`
*
* @param s
* The wrapped string.
*/
implicit class MatcherString(s: String) {
/** Matches a string against a given regex.
*
* @param needle
* The regex to match against the receiver.
* @return
* `true` if the receiver matches the regex.
*/
def =~ (needle: String): Boolean =
matchesPartial(needle)
private def patternFor(needle: String): Pattern =
Pattern.compile(needle)
private def matcherFor(needle: String): Matcher =
patternFor(needle).matcher(s)
private def matchesPartial(needle: String): Boolean =
matcherFor(needle).find
}
}
|
mdippery/jupiter
|
src/main/scala/com/mipadi/jupiter/text/strings.scala
|
Scala
|
apache-2.0
| 2,203 |
package org.jetbrains.plugins.scala.failed.annotator
import java.io.File
import com.intellij.openapi.util.TextRange
import org.jetbrains.plugins.scala.PerfCycleTests
import org.jetbrains.plugins.scala.projectHighlighting.ScalacTestdataHighlightingTestBase
import org.jetbrains.plugins.scala.util.TestUtils
import org.jetbrains.plugins.scala.util.reporter.ConsoleReporter
import org.junit.experimental.categories.Category
import scala.reflect.NameTransformer
/**
* Nikolay.Tropin
* 14-Aug-17
*/
abstract class FailedScalacTestsBase extends ScalacTestdataHighlightingTestBase {
override lazy val reporter = new ConsoleReporter(filesWithProblems)
def testDataDir: String = s"${TestUtils.getTestDataPath}/scalacTests/$testDirName/"
def testDirName: String
def fileName = getTestName(/*lowercaseFirstLetter*/ false).stripPrefix("_")
def filesWithProblems: Map[String, Set[TextRange]] = {
import org.jetbrains.plugins.scala.projectHighlighting._
getTestName(true) match {
case "_t7232c" => Map("Test.scala" -> Set())
case "_t7364b" => Map("UseIt_2.scala" -> Set((68, 79), (56, 64)))
case "_t4365" => Map("a_1.scala" -> Set((535, 557)))
case "_t5545" => Map("S_2.scala" -> Set((64, 66)), "S_1.scala" -> Set((64, 66)))
case "_t6169" => Map("skinnable.scala" -> Set(), "t6169.scala" -> Set())
case "_t8497" => Map("A_1.scala" -> Set())
case "_t8934a" => Map("Test_2.scala" -> Set((36, 49)))
case "_t8781" => Map("Test_2.scala" -> Set((82, 91)))
case _ => Map((NameTransformer.decode(fileName) + ".scala", Set.empty))
}
}
override def filesToHighlight: Array[File] = {
val decoded = NameTransformer.decode(fileName)
val dirPath = testDataDir + decoded
val dir = new File(dirPath)
val file = new File(dirPath + ".scala")
if (dir.exists())
Array(dir)
else if (file.exists())
Array(file)
else throw new RuntimeException("No file exists")
}
}
@Category(Array(classOf[PerfCycleTests]))
class FailedScalacTests extends FailedScalacTestsBase {
def testDirName = "failed"
//Delete test method and move corresponding .scala file or directory to testdata/scalacTests/pos/ after test passes
def test_t4365(): Unit = doTest()
def test_t5545(): Unit = doTest()
def test_t6169(): Unit = doTest()
def test_t7232c(): Unit = doTest()
def test_t7364b(): Unit = doTest()
def test_t7688(): Unit = doTest()
def test_t8497(): Unit = doTest()
def test_arrays3(): Unit = doTest()
def test_channels(): Unit = doTest()
def test_compound(): Unit = doTest()
def `test_cycle-jsoup`(): Unit = doTest()
def test_depmet_implicit_oopsla_session(): Unit = doTest()
def test_depmet_implicit_oopsla_session_2(): Unit = doTest()
def test_depmet_implicit_oopsla_session_simpler(): Unit = doTest()
def test_fun_undo_eta(): Unit = doTest()
def `test_gadt-gilles`(): Unit = doTest()
def test_gadts2(): Unit = doTest()
def test_hkgadt(): Unit = doTest()
def `test_implicits-new`(): Unit = doTest()
def `test_implicits-old`(): Unit = doTest()
def test_infer_override_def_args(): Unit = doTest()
def test_infersingle(): Unit = doTest()
def `test_native-warning`(): Unit = doTest()
def `test_overloaded-unapply`(): Unit = doTest()
def test_overloaded_ho_fun(): Unit = doTest()
def test_presuperContext(): Unit = doTest()
def `test_reflection-compat-macro-universe`(): Unit = doTest()
def test_sammy_infer_argtype_subtypes(): Unit = doTest()
def `test_scala-singleton`(): Unit = doTest()
def test_t267(): Unit = doTest()
def test_t389(): Unit = doTest()
def test_t482(): Unit = doTest()
def test_t694(): Unit = doTest()
def test_t697(): Unit = doTest()
def test_t762(): Unit = doTest()
def test_t802(): Unit = doTest()
def test_t1085(): Unit = doTest()
def test_t1279a(): Unit = doTest()
def test_t1803(): Unit = doTest()
def test_t1957(): Unit = doTest()
def `test_t2712-5`(): Unit = doTest()
def test_t3177(): Unit = doTest()
def test_t3866(): Unit = doTest()
def test_t3880(): Unit = doTest()
def test_t3999b(): Unit = doTest()
def test_t5313(): Unit = doTest()
def test_t5317(): Unit = doTest()
def test_t5626(): Unit = doTest()
def test_t5683(): Unit = doTest()
def test_t5729(): Unit = doTest()
def test_t5953(): Unit = doTest()
def test_t5958(): Unit = doTest()
def test_t6084(): Unit = doTest()
def test_t6205(): Unit = doTest()
def test_t6221(): Unit = doTest()
def test_t6675(): Unit = doTest()
def test_t6846(): Unit = doTest()
def test_t7228(): Unit = doTest()
def test_t7517(): Unit = doTest()
def test_t7520(): Unit = doTest()
def test_t7668(): Unit = doTest()
def test_t7704(): Unit = doTest()
def test_t7944(): Unit = doTest()
def `test_t8002-nested-scope`(): Unit = doTest()
def test_t8079b(): Unit = doTest()
def test_t8177h(): Unit = doTest()
def test_t8237(): Unit = doTest()
def test_t9008(): Unit = doTest()
def test_t9498(): Unit = doTest()
def test_t9658(): Unit = doTest()
def test_ticket2251(): Unit = doTest()
def `test_typerep-stephane`(): Unit = doTest()
def test_virtpatmat_gadt_array(): Unit = doTest()
def test_z1720(): Unit = doTest()
def test_t7190(): Unit = doTest()
def `test_macro-bundle-disambiguate-bundle`(): Unit = doTest()
def `test_macro-bundle-disambiguate-nonbundle`(): Unit = doTest()
}
@Category(Array(classOf[PerfCycleTests]))
class MacrosFailedScalacTests extends FailedScalacTestsBase {
override def testDirName = "macros"
def test_t8781(): Unit = doTest()
def test_t8934a(): Unit = doTest()
def test_t8523(): Unit = doTest()
}
//these tests pass locally but sometimes fail on teamcity
@Category(Array(classOf[PerfCycleTests]))
class FlakyScalacTests extends FailedScalacTestsBase {
override def testDirName = "flaky"
def test_t7516(): Unit = doTest()
def `test_annotated-treecopy`(): Unit = doTest()
}
|
jastice/intellij-scala
|
scala/scala-impl/test/org/jetbrains/plugins/scala/failed/annotator/FailedScalacTests.scala
|
Scala
|
apache-2.0
| 5,919 |
/*
*
* 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.flaminem.flamy.exec.hive
import com.flaminem.flamy.conf.FlamyContext
import org.apache.hadoop.hive.ql.exec.FunctionRegistry
import scala.util.Try
/**
* Created by fpin on 11/21/16.
*/
class ModelHiveFunctionFetcher(override val context: FlamyContext) extends HiveFunctionFetcher {
def getFunctionClassName(functionName: String): Try[String] = {
Try{
FunctionRegistry.getFunctionInfo(functionName).getFunctionClass.getName
}
}
}
|
flaminem/flamy
|
src/main/scala/com/flaminem/flamy/exec/hive/ModelHiveFunctionFetcher.scala
|
Scala
|
apache-2.0
| 1,036 |
package com.twitter.finagle.netty4
import com.twitter.concurrent.NamedPoolThreadFactory
import com.twitter.finagle._
import com.twitter.finagle.netty4.channel.{ServerBridge, Netty4ChannelInitializer}
import com.twitter.finagle.netty4.transport.ChannelTransport
import com.twitter.finagle.server.Listener
import com.twitter.finagle.ssl.Engine
import com.twitter.finagle.transport.Transport
import com.twitter.util._
import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.UnpooledByteBufAllocator
import io.netty.channel._
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.util.concurrent.GenericFutureListener
import java.lang.{Boolean => JBool, Integer => JInt}
import java.net.SocketAddress
import java.util.concurrent.TimeUnit
/**
* Netty4 TLS configuration.
*
* @param newEngine Creates a new SSL engine
*/
private[finagle] case class Netty4ListenerTLSConfig(newEngine: () => Engine)
private[finagle] object Netty4Listener {
val TrafficClass: ChannelOption[JInt] = ChannelOption.newInstance("trafficClass")
}
private[netty4] case class PipelineInit(cf: ChannelPipeline => Unit) {
def mk(): (PipelineInit, Stack.Param[PipelineInit]) =
(this, PipelineInit.param)
}
private[netty4] object PipelineInit {
implicit val param = Stack.Param(PipelineInit(_ => ()))
}
/**
* Constructs a `Listener[In, Out]` given a ``pipelineInit`` function
* responsible for framing a [[Transport]] stream. The [[Listener]] is configured
* via the passed in [[com.twitter.finagle.Stack.Param Params]].
*
* @see [[com.twitter.finagle.server.Listener]]
* @see [[com.twitter.finagle.transport.Transport]]
* @see [[com.twitter.finagle.param]]
*/
private[finagle] case class Netty4Listener[In, Out](
params: Stack.Params,
transportFactory: SocketChannel => Transport[In, Out] = new ChannelTransport[In, Out](_)
) extends Listener[In, Out] {
private[this] val PipelineInit(pipelineInit) = params[PipelineInit]
// transport params
private[this] val Transport.Liveness(_, _, keepAlive) = params[Transport.Liveness]
private[this] val Transport.BufferSizes(sendBufSize, recvBufSize) = params[Transport.BufferSizes]
private[this] val Transport.Options(noDelay, reuseAddr) = params[Transport.Options]
// listener params
private[this] val Listener.Backlog(backlog) = params[Listener.Backlog]
/**
* Listen for connections and apply the `serveTransport` callback on connected [[Transport transports]].
* @param addr socket address for listening.
* @param serveTransport a call-back for newly created transports which in turn are
* created for new connections.
* @note the ``serveTransport`` implementation is responsible for calling
* [[Transport.close() close]] on [[Transport transports]].
*/
def listen(addr: SocketAddress)(serveTransport: Transport[In, Out] => Unit): ListeningServer =
new ListeningServer with CloseAwaitably {
val newBridge = () => new ServerBridge(
transportFactory,
serveTransport
)
val bossLoop: EventLoopGroup =
new NioEventLoopGroup(
1 /*nThreads*/ ,
new NamedPoolThreadFactory("finagle/netty4/boss", makeDaemons = true)
)
val bootstrap = new ServerBootstrap()
bootstrap.channel(classOf[NioServerSocketChannel])
bootstrap.group(bossLoop, WorkerPool)
bootstrap.childOption[JBool](ChannelOption.TCP_NODELAY, noDelay)
//todo: investigate pooled allocator CSL-2089
bootstrap.option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
bootstrap.childOption(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
bootstrap.option[JBool](ChannelOption.SO_REUSEADDR, reuseAddr)
bootstrap.option[JInt](ChannelOption.SO_LINGER, 0)
backlog.foreach(bootstrap.option[JInt](ChannelOption.SO_BACKLOG, _))
sendBufSize.foreach(bootstrap.childOption[JInt](ChannelOption.SO_SNDBUF, _))
recvBufSize.foreach(bootstrap.childOption[JInt](ChannelOption.SO_RCVBUF, _))
keepAlive.foreach(bootstrap.childOption[JBool](ChannelOption.SO_KEEPALIVE, _))
params[Listener.TrafficClass].value.foreach { tc =>
bootstrap.option[JInt](Netty4Listener.TrafficClass, tc)
bootstrap.childOption[JInt](Netty4Listener.TrafficClass, tc)
}
val initializer = new Netty4ChannelInitializer(pipelineInit, params, newBridge)
bootstrap.childHandler(initializer)
// Block until listening socket is bound. `ListeningServer`
// represents a bound server and if we don't block here there's
// a race between #listen and #boundAddress being available.
val ch = bootstrap.bind(addr).awaitUninterruptibly().channel()
/**
* Immediately close the listening socket then shutdown the netty
* boss threadpool with ``deadline`` timeout for existing tasks.
*
* @return a [[Future]] representing the shutdown of the boss threadpool.
*/
def closeServer(deadline: Time) = closeAwaitably {
// note: this ultimately calls close(2) on
// a non-blocking socket so it should not block.
ch.close().awaitUninterruptibly()
val p = new Promise[Unit]
// The boss loop immediately starts refusing new work.
// Existing tasks have ``deadline`` time to finish executing.
bossLoop
.shutdownGracefully(0 /* quietPeriod */ , deadline.inMillis /* timeout */ , TimeUnit.MILLISECONDS)
.addListener(new GenericFutureListener[Nothing] {
def operationComplete(future: Nothing): Unit = p.setDone()
})
p
}
def boundAddress: SocketAddress = ch.localAddress()
}
}
|
liamstewart/finagle
|
finagle-netty4/src/main/scala/com/twitter/finagle/netty4/Netty4Listener.scala
|
Scala
|
apache-2.0
| 5,799 |
package org.openurp.edu.eams.teach.program.major.service
import org.openurp.edu.base.Adminclass
import org.openurp.edu.base.Course
import org.openurp.edu.base.code.CourseType
import org.openurp.edu.teach.plan.CoursePlan
import org.openurp.edu.teach.plan.PlanCourse
import org.openurp.edu.teach.plan.MajorPlan
import org.openurp.edu.teach.plan.MajorPlanCourse
import org.openurp.edu.teach.plan.MajorCourseGroup
trait MajorPlanService {
def getPlanCourses(plan: MajorPlan): List[MajorPlanCourse]
def getMajorPlanByAdminClass(clazz: Adminclass): MajorPlan
def saveOrUpdateMajorPlan(plan: MajorPlan): Unit
def removeMajorPlan(plan: MajorPlan): Unit
def genMajorPlan(sourcePlan: MajorPlan, genParameter: MajorPlanGenParameter): CoursePlan
def genMajorPlans(sourcePlans: Iterable[MajorPlan], partialParams: MajorPlanGenParameter): List[MajorPlan]
def getUnusedCourseTypes(plan: MajorPlan): List[CourseType]
def statPlanCredits(planId: java.lang.Long): Float
def statPlanCredits(plan: MajorPlan): Float
def hasCourse(cgroup: MajorCourseGroup, course: Course): Boolean
def hasCourse(cgroup: MajorCourseGroup, course: Course, planCourse: PlanCourse): Boolean
}
|
openurp/edu-eams-webapp
|
core/src/main/scala/org/openurp/edu/eams/teach/program/major/service/MajorPlanService.scala
|
Scala
|
gpl-3.0
| 1,191 |
/* SimpleApp.scala */
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
object SimpleApp {
def main(args: Array[String]) {
val logFile = "/opt/spark-1.1.0-bin-hadoop2.4/README.md" // Should be some file on your system
//val logFile = "/Users/ryanlei/code/spark-1.1.0/README.md" // Should be some file on your system
val conf = new SparkConf().setAppName("Simple Application")
val sc = new SparkContext(conf)
val logData = sc.textFile(logFile, 2).cache()
val numAs = logData.filter(line => line.contains("a")).count()
val numBs = logData.filter(line => line.contains("b")).count()
println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
}
}
|
RyanLeiTaiwan/SparkPractice
|
QuickStart/src/main/scala/SimpleApp.scala
|
Scala
|
gpl-3.0
| 748 |
package com.twitter.finagle.zookeeper
import com.twitter.common.zookeeper.ServerSetImpl
import com.twitter.conversions.time._
import com.twitter.finagle.{Addr, Resolver}
import com.twitter.thrift.Status._
import com.twitter.util.{Await, Duration, RandomSocket, Var}
import java.net.InetSocketAddress
import org.junit.runner.RunWith
import org.scalatest.{BeforeAndAfter, FunSuite}
import org.scalatest.concurrent.Eventually._
import org.scalatest.concurrent.Timeouts._
import org.scalatest.junit.JUnitRunner
import org.scalatest.time._
import scala.collection.JavaConverters._
@RunWith(classOf[JUnitRunner])
class ZkResolverTest extends FunSuite with BeforeAndAfter {
val zkTimeout = 100.milliseconds
var inst: ZkInstance = _
val factory = new ZkClientFactory(zkTimeout)
implicit val patienceConfig = PatienceConfig(
timeout = toSpan(1.second),
interval = toSpan(zkTimeout))
before {
inst = new ZkInstance
inst.start()
}
after {
inst.stop()
}
def toSpan(d: Duration): Span = Span(d.inNanoseconds, Nanoseconds)
// Flaky tests. See https://jira.twitter.biz/browse/COORD-437 for details.
if (!sys.props.contains("SKIP_FLAKY")) {
test("represent the underlying ServerSet") {
val serverSet = new ServerSetImpl(inst.zookeeperClient, "/foo/bar/baz")
val clust = new ZkGroup(serverSet, "/foo/bar/baz")
assert(clust().isEmpty)
val ephAddr1 = RandomSocket.nextAddress
val ephAddr2 = RandomSocket.nextAddress
serverSet.join(ephAddr1, Map[String, InetSocketAddress]().asJava, ALIVE)
eventually { assert(clust().size == 1) }
val ep = clust().head.getServiceEndpoint
assert(ep.getHost == "0.0.0.0")
assert(ep.getPort == ephAddr1.getPort)
assert(clust() == clust())
val snap = clust()
serverSet.join(ephAddr2, Map[String, InetSocketAddress]().asJava, ALIVE)
eventually { assert(clust().size == 2) }
assert {
val Seq(fst) = (clust() &~ snap).toSeq
fst.getServiceEndpoint.getPort == ephAddr2.getPort
}
}
test("filter by shardid") {
val path = "/bar/foo/baz"
val serverSet = new ServerSetImpl(inst.zookeeperClient, path)
val clust = new ZkGroup(serverSet, path)
assert(clust().isEmpty)
// assert that 3 hosts show up in an unfiltered cluster
val ephAddr1 = RandomSocket.nextAddress
val ephAddr2 = RandomSocket.nextAddress
val ephAddr3 = RandomSocket.nextAddress
Seq(ephAddr1, ephAddr2, ephAddr3).foreach { sockAddr =>
serverSet.join(
sockAddr,
Map[String, InetSocketAddress]().asJava,
sockAddr.getPort
).update(ALIVE)
}
eventually { assert(clust().size == 3) }
// and 1 in a cluster filtered by shardid (== to the port in this case)
val filteredAddr =
new ZkResolver(factory).resolve(
Set(inst.zookeeperAddress),
path,
shardId = Some(ephAddr2.getPort)
)
eventually {
Var.sample(filteredAddr) match {
case Addr.Bound(addrs, attrs) if addrs.size == 1 && attrs.isEmpty => true
case _ => fail()
}
}
}
test("resolve ALIVE endpoints") {
val res = new ZkResolver(factory)
val va = res.bind("localhost:%d!/foo/bar/baz".format(
inst.zookeeperAddress.getPort))
eventually { Var.sample(va) == Addr.Bound() }
/*
val inetClust = clust collect { case ia: InetSocketAddress => ia }
assert(inetClust() == inetClust())
*/
val serverSet = new ServerSetImpl(inst.zookeeperClient, "/foo/bar/baz")
val port1 = RandomSocket.nextPort()
val port2 = RandomSocket.nextPort()
val sockAddr = new InetSocketAddress("127.0.0.1", port1)
val blahAddr = new InetSocketAddress("10.0.0.1", port2)
val status = serverSet.join(
sockAddr,
Map[String, InetSocketAddress]("blah" -> blahAddr).asJava,
ALIVE
)
eventually { assert(Var.sample(va) == Addr.Bound(sockAddr)) }
status.leave()
eventually { assert(Var.sample(va) == Addr.Neg) }
serverSet.join(
sockAddr,
Map[String, InetSocketAddress]("blah" -> blahAddr).asJava, ALIVE)
eventually { assert(Var.sample(va) == Addr.Bound(sockAddr)) }
val blahVa = res.bind("localhost:%d!/foo/bar/baz!blah".format(
inst.zookeeperAddress.getPort))
eventually { assert(Var.sample(blahVa) == Addr.Bound(blahAddr)) }
}
test("filter by endpoint") {
val path = "/bar/foo/baz"
val serverSet = new ServerSetImpl(inst.zookeeperClient, path)
val clust = new ZkGroup(serverSet, path)
assert(clust().isEmpty)
// assert that 3 hosts show up in an unfiltered cluster
val ephAddr1 = RandomSocket.nextAddress
val ephAddr2 = RandomSocket.nextAddress
val ephAddr3 = RandomSocket.nextAddress
Seq(ephAddr1, ephAddr2, ephAddr3).foreach { sockAddr =>
serverSet.join(
sockAddr,
Map[String, InetSocketAddress](sockAddr.getPort.toString -> sockAddr).asJava
).update(ALIVE)
}
eventually { assert(clust().size == 3) }
val filteredAddr =
new ZkResolver(factory).resolve(
Set(inst.zookeeperAddress),
path,
endpoint = Some(ephAddr1.getPort.toString)
)
eventually {
Var.sample(filteredAddr) match {
case Addr.Bound(addrs, attrs) if addrs.size == 1 && attrs.isEmpty => true
case _ => fail()
}
}
}
test("resolves from the main resolver") {
Resolver.eval("zk!localhost:%d!/foo/bar/baz!blah".format(
inst.zookeeperAddress.getPort))
}
}
}
|
liamstewart/finagle
|
finagle-serversets/src/test/scala/com/twitter/finagle/zookeeper/ZkResolverTest.scala
|
Scala
|
apache-2.0
| 5,726 |
package mytest.casematch
/**
* Created by fqc on 2016/7/23.
* 提取器
*/
class Extractor {
}
trait User {
def name: String
}
class FreeUser(val name: String) extends User
class PremiumUser(val name: String) extends User
object FreeUser {
def unapply(user: FreeUser): Option[String] = Some(user.name)
}
object PremiumUser {
def unapply(user: PremiumUser): Option[String] = Some(user.name) //将name字段提取解构出来
}
object MyTest extends App {
private val name: Option[String] = FreeUser.unapply(new FreeUser("Daniel"))
println(name)
println(name.getClass)
val user = new PremiumUser("kobe")
user match {
case FreeUser(name) => println("hello freeuser" + Some(name) + name)
case PremiumUser(name) => println("hello PremiumUser" + Some(name) + name)
}
//hello PremiumUserSome(kobe)
private val premiumUser: Option[String] = PremiumUser.unapply(new PremiumUser("kobe"))
println(premiumUser)
println(premiumUser.getOrElse(0))
}
|
fqc/Scala_sidepro
|
src/mytest/casematch/Extractor.scala
|
Scala
|
mit
| 986 |
/*
* Beangle, Agile Development Scaffold and Toolkits.
*
* Copyright © 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.maven.plugin.container
import java.io.File
import org.apache.maven.plugin.AbstractMojo
import org.apache.maven.plugins.annotations.{LifecyclePhase, Mojo, Parameter, ResolutionScope}
import org.apache.maven.project.MavenProject
import org.apache.maven.settings.Settings
import org.beangle.commons.file.diff.Bsdiff
import org.beangle.commons.io.Files
import org.beangle.commons.lang.time.Stopwatch
import org.beangle.commons.lang.{Consoles, Strings}
import org.beangle.maven.plugin.util.Projects
import org.beangle.boot.artifact.{Artifact, Diff, Layout, Repo}
@Mojo(name = "diff", defaultPhase = LifecyclePhase.PREPARE_PACKAGE, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME)
class DiffMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true)
private var project: MavenProject = _
@Parameter(defaultValue = "${settings}", readonly = true)
private var settings: Settings = _
def execute(): Unit = {
val packaging = project.getPackaging
if (packaging != "war" && packaging != "jar") {
getLog.info("Diff Generation supports only war/jar projects!")
return
}
val localRepo = Repo.local(settings.getLocalRepository)
val thisArtifact = Artifact(project.getGroupId, project.getArtifactId, project.getVersion, None, packaging)
var format = System.getProperty("VersionRange")
var start, end = ""
if (null == format) {
localRepo.lastestBefore(thisArtifact) match {
case Some(old) => start = old.version
case None => start = Consoles.prompt("Input version range starts with:", null, (_ != project.getVersion))
}
end = project.getVersion
} else {
val rs = Strings.split(format, "_")
if (rs.length != 2) {
println("Version Range should be start_end")
System.exit(1)
} else {
start = rs(0)
end = rs(1)
}
}
val file1 =
Projects.getFile(project.getGroupId, project.getArtifactId, start, packaging, settings.getLocalRepository)
val file2 =
Projects.getFile(project.getGroupId, project.getArtifactId, end, packaging, settings.getLocalRepository)
val diff = Diff(Artifact(project.getGroupId, project.getArtifactId, start, None, project.getPackaging), end)
if (!file1.exists) {
println(s"Cannot find ${file1.getPath}")
System.exit(1)
}
if (!file2.exists) {
println(s"Cannot find ${file2.getPath}")
System.exit(1)
}
val diffFile = new File(settings.getLocalRepository + "/" + Layout.Maven2.path(diff))
println(s"Generating diff file ${diffFile.getPath}")
val watch = new Stopwatch(true)
Bsdiff.diff(file1, file2, diffFile)
Files.copy(diffFile, new File(project.getBuild.getDirectory + "/" + diffFile.getName))
println(s"Generated ${diffFile.getName}(${diffFile.length / 1000.0}KB) using $watch")
}
}
|
beangle/maven
|
src/main/scala/org/beangle/maven/plugin/container/DiffMojo.scala
|
Scala
|
lgpl-3.0
| 3,678 |
package mesosphere.marathon.core.flow
import mesosphere.marathon.MarathonSchedulerDriverHolder
import mesosphere.marathon.core.base.Clock
import mesosphere.marathon.core.flow.impl.{ OfferMatcherLaunchTokensActor, ReviveOffersActor }
import mesosphere.marathon.core.leadership.LeadershipModule
import mesosphere.marathon.core.matcher.manager.OfferMatcherManager
import mesosphere.marathon.core.task.bus.TaskStatusObservables
import rx.lang.scala.Observable
/**
* This module contains code for managing the flow/backpressure of the application.
*/
class FlowModule(leadershipModule: LeadershipModule) {
/**
* Call `reviveOffers` of the `SchedulerDriver` interface whenever there is new interest
* in offers by an OfferMatcher. There is some logic to prevent calling `reviveOffers` to often.
* See [[ReviveOffersConfig]] for configuring this.
*
* @param offersWanted An observable which emits `true` whenever offers are currently wanted or offer interest
* has changed. It should emit `false` when interest in offers is lost.
* @param driverHolder The driverHolder containing the driver on which to call `reviveOffers`.
*/
def reviveOffersWhenOfferMatcherManagerSignalsInterest(
clock: Clock, conf: ReviveOffersConfig,
offersWanted: Observable[Boolean], driverHolder: MarathonSchedulerDriverHolder): Unit = {
lazy val reviveOffersActor = ReviveOffersActor.props(
clock, conf,
offersWanted, driverHolder
)
leadershipModule.startWhenLeader(reviveOffersActor, "reviveOffersWhenWanted")
}
/**
* Refills the launch tokens of the OfferMatcherManager periodically. See [[LaunchTokenConfig]] for configuration.
*
* Also adds a launch token to othe OfferMatcherManager for every update we get about a new running tasks.
*
* The reasoning is that getting infos about running tasks signals that the Mesos infrastructure is working
* and not yet completely overloaded.
*/
def refillOfferMatcherManagerLaunchTokens(
conf: LaunchTokenConfig,
taskStatusObservables: TaskStatusObservables,
offerMatcherManager: OfferMatcherManager): Unit =
{
lazy val offerMatcherLaunchTokensProps = OfferMatcherLaunchTokensActor.props(
conf, taskStatusObservables, offerMatcherManager
)
leadershipModule.startWhenLeader(offerMatcherLaunchTokensProps, "offerMatcherLaunchTokens")
}
}
|
HardikDR/marathon
|
src/main/scala/mesosphere/marathon/core/flow/FlowModule.scala
|
Scala
|
apache-2.0
| 2,425 |
/*
* Copyright 2020 Precog Data
*
* 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.contrib.scalaz
import scala.annotation.unchecked.uncheckedVariance
import scalaz.NonEmptyList
import scalaz.Liskov.{<~<, refl}
object nel {
implicit final class NonEmptyListOps[A](xs: NonEmptyList[A]) {
def widen[B](implicit ev: A <~< B): NonEmptyList[B] =
ev.subst[λ[`-α` => NonEmptyList[α @uncheckedVariance] <~< NonEmptyList[B]]](refl)(xs)
}
}
|
djspiewak/quasar
|
foundation/src/main/scala/quasar/contrib/scalaz/nel.scala
|
Scala
|
apache-2.0
| 978 |
package video.imageUtils
import scala.util.Random
import java.awt.Color
import java.awt.image.BufferedImage
object ImageUtils {
val rand = new Random()
def randColor = {
val r: Float = rand.nextFloat()
val g: Float = rand.nextFloat()
val b: Float = rand.nextFloat()
new Color(r, g, b)
}
def createBufferedImage(width: Int, height: Int, circleProperties: CircleProperties) = {
val circleImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
val graphics = circleImage.createGraphics()
graphics.setColor(circleProperties.color)
graphics.fillOval(0, 0, circleProperties.width, circleProperties.height)
circleImage
}
}
|
retroryan/streams-workshop
|
src/library/video/imageUtils/ImageUtils.scala
|
Scala
|
cc0-1.0
| 682 |
package coursier.clitests
import java.io.File
import utest._
abstract class LaunchTests extends TestSuite {
def launcher: String
val tests = Tests {
test("fork") {
val output = LauncherTestUtil.output(
launcher,
"launch",
"--fork",
"io.get-coursier:echo:1.0.1",
"--",
"foo"
)
val expectedOutput = "foo" + System.lineSeparator()
assert(output == expectedOutput)
}
test("non static main class") {
val output = LauncherTestUtil.output(
args = Seq(
launcher,
"launch",
"--fork",
"org.scala-lang:scala-compiler:2.13.0",
"--main-class",
"scala.tools.nsc.Driver",
"--property",
"user.language=en",
"--property",
"user.country=US"
),
keepErrorOutput = true
)
val expectedInOutput = Seq(
"Main method",
"in class scala.tools.nsc.Driver",
"is not static"
)
assert(expectedInOutput.forall(output.contains))
}
test("java class path in expansion from launch") {
import coursier.dependencyString
val output = LauncherTestUtil.output(
launcher,
"launch",
"--property",
s"foo=$${java.class.path}",
TestUtil.propsDepStr,
"--",
"foo"
)
val expected = TestUtil.propsCp.mkString(File.pathSeparator) + System.lineSeparator()
assert(output == expected)
}
def inlineApp(): Unit = {
val output = LauncherTestUtil.output(
launcher,
"launch",
"""{"dependencies": ["io.get-coursier:echo:1.0.1"], "repositories": ["central"]}""",
"--",
"foo"
)
val expected = "foo" + System.lineSeparator()
assert(output == expected)
}
test("inline app") {
if (LauncherTestUtil.isWindows) "disabled"
else { inlineApp(); "" }
}
def inlineAppWithId(): Unit = {
val output = LauncherTestUtil.output(
launcher,
"launch",
"""echo:{"dependencies": ["io.get-coursier:echo:1.0.1"], "repositories": ["central"]}""",
"--",
"foo"
)
val expected = "foo" + System.lineSeparator()
assert(output == expected)
}
test("inline app with id") {
if (LauncherTestUtil.isWindows) "disabled"
else { inlineAppWithId(); "" }
}
test("no vendor and title in manifest") {
val output = LauncherTestUtil.output(
launcher,
"launch",
"io.get-coursier:coursier-cli_2.12:2.0.16+69-g69cab05e6",
"--",
"launch",
"io.get-coursier:echo:1.0.1",
"--",
"foo"
)
val expectedOutput = "foo" + System.lineSeparator()
assert(output == expectedOutput)
}
}
}
|
alexarchambault/coursier
|
modules/cli-tests/src/main/scala/coursier/clitests/LaunchTests.scala
|
Scala
|
apache-2.0
| 2,821 |
package com.twitter.finagle.kestrel
import _root_.java.net.SocketAddress
import org.jboss.netty.buffer.ChannelBuffer
import com.twitter.finagle.builder.{Server => BuiltServer, ServerBuilder}
import protocol.Kestrel
import _root_.java.util.concurrent.{BlockingDeque, LinkedBlockingDeque}
import com.twitter.util.MapMaker
class Server(address: SocketAddress) {
private[this] val serviceFactory = {
val queues = MapMaker[ChannelBuffer, BlockingDeque[ChannelBuffer]] { config =>
config.compute { key =>
new LinkedBlockingDeque[ChannelBuffer]
}
}
() => {
new InterpreterService(new Interpreter(queues))
}
}
private[this] val serverSpec =
ServerBuilder()
.name("schmestrel")
.codec(Kestrel())
.bindTo(address)
private[this] var server: Option[BuiltServer] = None
def start() {
server = Some(serverSpec.build(serviceFactory))
}
def stop() {
require(server.isDefined, "Server is not open!")
server.foreach { server =>
server.close()
this.server = None
}
}
}
|
enachb/finagle_2.9_durgh
|
finagle-kestrel/src/main/scala/com/twitter/finagle/kestrel/Server.scala
|
Scala
|
apache-2.0
| 1,066 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.types
import java.util.Objects
import org.json4s.JsonAST.JValue
import org.json4s.JsonDSL._
/**
* The data type for User Defined Types (UDTs).
*
* This interface allows a user to make their own classes more interoperable with SparkSQL;
* e.g., by creating a [[UserDefinedType]] for a class X, it becomes possible to create
* a `DataFrame` which has class X in the schema.
*
* For SparkSQL to recognize UDTs, the UDT must be annotated with
* [[SQLUserDefinedType]].
*
* The conversion via `serialize` occurs when instantiating a `DataFrame` from another RDD.
* The conversion via `deserialize` occurs when reading from a `DataFrame`.
*
* Note: This was previously a developer API in Spark 1.x. We are making this private in Spark 2.0
* because we will very likely create a new version of this that works better with Datasets.
*/
private[spark]
abstract class UserDefinedType[UserType >: Null] extends DataType with Serializable {
/** Underlying storage type for this UDT */
def sqlType: DataType
/** Paired Python UDT class, if exists. */
def pyUDT: String = null
/** Serialized Python UDT class, if exists. */
def serializedPyClass: String = null
/**
* Convert the user type to a SQL datum
*/
def serialize(obj: UserType): Any
/** Convert a SQL datum to the user type */
def deserialize(datum: Any): UserType
override private[sql] def jsonValue: JValue = {
("type" -> "udt") ~
("class" -> this.getClass.getName) ~
("pyClass" -> pyUDT) ~
("sqlType" -> sqlType.jsonValue)
}
/**
* Class object for the UserType
*/
def userClass: java.lang.Class[UserType]
override def defaultSize: Int = sqlType.defaultSize
/**
* For UDT, asNullable will not change the nullability of its internal sqlType and just returns
* itself.
*/
override private[spark] def asNullable: UserDefinedType[UserType] = this
override private[sql] def acceptsType(dataType: DataType) = dataType match {
case other: UserDefinedType[_] =>
this.getClass == other.getClass ||
this.userClass.isAssignableFrom(other.userClass)
case _ => false
}
override def sql: String = sqlType.sql
override def hashCode(): Int = getClass.hashCode()
override def equals(other: Any): Boolean = other match {
case that: UserDefinedType[_] => this.acceptsType(that)
case _ => false
}
override def catalogString: String = sqlType.simpleString
}
/**
* The user defined type in Python.
*
* Note: This can only be accessed via Python UDF, or accessed as serialized object.
*/
private[sql] class PythonUserDefinedType(
val sqlType: DataType,
override val pyUDT: String,
override val serializedPyClass: String) extends UserDefinedType[Any] {
/* The serialization is handled by UDT class in Python */
override def serialize(obj: Any): Any = obj
override def deserialize(datam: Any): Any = datam
/* There is no Java class for Python UDT */
override def userClass: java.lang.Class[Any] = null
override private[sql] def jsonValue: JValue = {
("type" -> "udt") ~
("pyClass" -> pyUDT) ~
("serializedClass" -> serializedPyClass) ~
("sqlType" -> sqlType.jsonValue)
}
override def equals(other: Any): Boolean = other match {
case that: PythonUserDefinedType => pyUDT == that.pyUDT
case _ => false
}
override def hashCode(): Int = Objects.hashCode(pyUDT)
}
|
minixalpha/spark
|
sql/catalyst/src/main/scala/org/apache/spark/sql/types/UserDefinedType.scala
|
Scala
|
apache-2.0
| 4,236 |
package org.jetbrains.plugins.scala
package caches
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.atomic.AtomicReference
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util._
import com.intellij.psi._
import com.intellij.psi.impl.compiled.ClsFileImpl
import com.intellij.psi.util._
import com.intellij.util.containers.{ContainerUtil, Stack}
import org.jetbrains.plugins.scala.caches.ProjectUserDataHolder._
import org.jetbrains.plugins.scala.debugger.evaluation.ScalaCodeFragment
import org.jetbrains.plugins.scala.lang.psi.api.ScalaFile
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScModificationTrackerOwner
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScFunction
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScTypeDefinition
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiManager
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.typedef.ScObjectImpl
import org.jetbrains.plugins.scala.lang.psi.types.ScType
import org.jetbrains.plugins.scala.lang.resolve.ScalaResolveResult
import scala.annotation.tailrec
import scala.util.control.ControlThrowable
/**
* User: Alexander Podkhalyuzin
* Date: 08.06.2009
*/
object CachesUtil {
/** This value is used by cache analyzer
*
* @see [[org.jetbrains.plugins.scala.macroAnnotations.CachedMacroUtil.transformRhsToAnalyzeCaches]]
*/
lazy val timeToCalculateForAnalyzingCaches: ThreadLocal[Stack[Long]] = new ThreadLocal[Stack[Long]] {
override def initialValue: Stack[Long] = new Stack[Long]()
}
/**
* Do not delete this type alias, it is used by [[org.jetbrains.plugins.scala.macroAnnotations.CachedWithRecursionGuard]]
*
* @see [[CachesUtil.getOrCreateKey]] for more info
*/
type CachedMap[Data, Result] = CachedValue[ConcurrentMap[Data, Result]]
type CachedRef[Result] = CachedValue[AtomicReference[Result]]
private val keys = ContainerUtil.newConcurrentMap[String, Key[_]]()
/**
* IMPORTANT:
* Cached annotations (CachedWithRecursionGuard, CachedMappedWithRecursionGuard, and CachedInUserData)
* rely on this method, even though it shows that it is unused
*
* If you change this method in any way, please make sure it's consistent with the annotations
*
* Do not use this method directly. You should use annotations instead
*/
def getOrCreateKey[T](id: String): Key[T] = {
keys.get(id) match {
case null =>
val newKey = Key.create[T](id)
val race = keys.putIfAbsent(id, newKey)
if (race != null) race.asInstanceOf[Key[T]]
else newKey
case v => v.asInstanceOf[Key[T]]
}
}
//keys for getUserData
val IMPLICIT_TYPE: Key[ScType] = Key.create("implicit.type")
val IMPLICIT_FUNCTION: Key[ScalaResolveResult] = Key.create("implicit.function")
val IMPLICIT_RESOLUTION: Key[PsiClass] = Key.create("implicit.resolution")
val NAMED_PARAM_KEY: Key[java.lang.Boolean] = Key.create("named.key")
val PACKAGE_OBJECT_KEY: Key[(ScTypeDefinition, java.lang.Long)] = Key.create("package.object.key")
val PROJECT_HAS_DOTTY_KEY: Key[java.lang.Boolean] = Key.create("project.has.dotty")
def libraryAwareModTracker(element: PsiElement): ModificationTracker = {
element.getContainingFile match {
case file: ScalaFile if file.isCompiled =>
val fileIndex = ProjectRootManager.getInstance(element.getProject).getFileIndex
if (fileIndex.isInLibrary(file.getVirtualFile)) ProjectRootManager.getInstance(element.getProject)
else enclosingModificationOwner(element)
case _: ClsFileImpl => ProjectRootManager.getInstance(element.getProject)
case _ => enclosingModificationOwner(element)
}
}
def enclosingModificationOwner(elem: PsiElement): ModificationTracker = {
@tailrec
def calc(element: PsiElement): ModificationTracker = {
PsiTreeUtil.getContextOfType(element, false, classOf[ScModificationTrackerOwner]) match {
case null => ScalaPsiManager.instance(elem.getProject).topLevelModificationTracker
case owner@ScModificationTrackerOwner() =>
new ModificationTracker {
override def getModificationCount: Long = owner.modificationCount
}
case owner => calc(owner.getContext)
}
}
calc(elem)
}
@tailrec
def updateModificationCount(elem: PsiElement): Unit = {
val elementOrContext = PsiTreeUtil.getContextOfType(elem, false,
classOf[ScModificationTrackerOwner], classOf[ScalaCodeFragment], classOf[PsiComment])
elementOrContext match {
case null => ScalaPsiManager.instance(elem.getProject).incModificationCount()
case _: ScalaCodeFragment | _: PsiComment => //do not update on changes in dummy file or comments
case owner@ScModificationTrackerOwner() => owner.incModificationCount()
case owner => updateModificationCount(owner.getContext)
}
}
case class ProbablyRecursionException[Data](elem: PsiElement,
data: Data,
key: Key[_],
set: Set[ScFunction]) extends ControlThrowable
def getOrCreateCachedMap[Dom: ProjectUserDataHolder, Data, Result](elem: Dom,
key: Key[CachedMap[Data, Result]],
dependencyItem: () => Object): ConcurrentMap[Data, Result] = {
val cachedValue = elem.getUserData(key) match {
case null =>
val manager = CachedValuesManager.getManager(elem.getProject)
val provider = new CachedValueProvider[ConcurrentMap[Data, Result]] {
def compute(): CachedValueProvider.Result[ConcurrentMap[Data, Result]] =
new CachedValueProvider.Result(ContainerUtil.newConcurrentMap(), dependencyItem())
}
val newValue = manager.createCachedValue(provider, false)
elem.putUserDataIfAbsent(key, newValue)
case d => d
}
cachedValue.getValue
}
def getOrCreateCachedRef[Dom: ProjectUserDataHolder, Result](elem: Dom,
key: Key[CachedRef[Result]],
dependencyItem: () => Object): AtomicReference[Result] = {
val cachedValue = elem.getUserData(key) match {
case null =>
val manager = CachedValuesManager.getManager(elem.getProject)
val provider = new CachedValueProvider[AtomicReference[Result]] {
def compute(): CachedValueProvider.Result[AtomicReference[Result]] =
new CachedValueProvider.Result(new AtomicReference[Result](), dependencyItem())
}
val newValue = manager.createCachedValue(provider, false)
elem.putUserDataIfAbsent(key, newValue)
case d => d
}
cachedValue.getValue
}
//used in CachedWithRecursionGuard
def handleRecursiveCall[Data, Result](e: PsiElement,
data: Data,
key: Key[_],
defaultValue: => Result): Result = {
ScObjectImpl.checkPackageObject()
PsiTreeUtil.getContextOfType(e, true, classOf[ScFunction]) match {
case null => defaultValue
case fun if fun.isProbablyRecursive => defaultValue
case fun =>
fun.setProbablyRecursive(true)
throw ProbablyRecursionException(e, data, key, Set(fun))
}
}
//Tuple2 class doesn't have half-specialized variants, so (T, Long) almost always have boxed long inside
case class Timestamped[@specialized(Boolean, Int, AnyRef) T](data: T, modCount: Long)
}
|
jastice/intellij-scala
|
scala/scala-impl/src/org/jetbrains/plugins/scala/caches/CachesUtil.scala
|
Scala
|
apache-2.0
| 7,744 |
/*
* 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.streaming.test
import java.io.File
import java.util.ConcurrentModificationException
import java.util.Locale
import java.util.concurrent.TimeUnit
import scala.concurrent.duration._
import org.apache.hadoop.fs.Path
import org.mockito.ArgumentMatchers.{any, eq => meq}
import org.mockito.Mockito._
import org.scalatest.BeforeAndAfter
import org.apache.spark.sql._
import org.apache.spark.sql.execution.streaming._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.sources.{StreamSinkProvider, StreamSourceProvider}
import org.apache.spark.sql.streaming.{OutputMode, StreamingQuery, StreamingQueryException, StreamTest}
import org.apache.spark.sql.streaming.Trigger._
import org.apache.spark.sql.types._
import org.apache.spark.util.Utils
object LastOptions {
var mockStreamSourceProvider = mock(classOf[StreamSourceProvider])
var mockStreamSinkProvider = mock(classOf[StreamSinkProvider])
var parameters: Map[String, String] = null
var schema: Option[StructType] = null
var partitionColumns: Seq[String] = Nil
def clear(): Unit = {
parameters = null
schema = null
partitionColumns = null
reset(mockStreamSourceProvider)
reset(mockStreamSinkProvider)
}
}
/** Dummy provider: returns no-op source/sink and records options in [[LastOptions]]. */
class DefaultSource extends StreamSourceProvider with StreamSinkProvider {
private val fakeSchema = StructType(StructField("a", IntegerType) :: Nil)
override def sourceSchema(
spark: SQLContext,
schema: Option[StructType],
providerName: String,
parameters: Map[String, String]): (String, StructType) = {
LastOptions.parameters = parameters
LastOptions.schema = schema
LastOptions.mockStreamSourceProvider.sourceSchema(spark, schema, providerName, parameters)
("dummySource", fakeSchema)
}
override def createSource(
spark: SQLContext,
metadataPath: String,
schema: Option[StructType],
providerName: String,
parameters: Map[String, String]): Source = {
LastOptions.parameters = parameters
LastOptions.schema = schema
LastOptions.mockStreamSourceProvider.createSource(
spark, metadataPath, schema, providerName, parameters)
new Source {
override def schema: StructType = fakeSchema
override def getOffset: Option[Offset] = Some(new LongOffset(0))
override def getBatch(start: Option[Offset], end: Offset): DataFrame = {
import spark.implicits._
spark.internalCreateDataFrame(spark.sparkContext.emptyRDD, schema, isStreaming = true)
}
override def stop() {}
}
}
override def createSink(
spark: SQLContext,
parameters: Map[String, String],
partitionColumns: Seq[String],
outputMode: OutputMode): Sink = {
LastOptions.parameters = parameters
LastOptions.partitionColumns = partitionColumns
LastOptions.mockStreamSinkProvider.createSink(spark, parameters, partitionColumns, outputMode)
(_: Long, _: DataFrame) => {}
}
}
class DataStreamReaderWriterSuite extends StreamTest with BeforeAndAfter {
private def newMetadataDir =
Utils.createTempDir(namePrefix = "streaming.metadata").getCanonicalPath
after {
spark.streams.active.foreach(_.stop())
}
test("write cannot be called on streaming datasets") {
val e = intercept[AnalysisException] {
spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load()
.write
.save()
}
Seq("'write'", "not", "streaming Dataset/DataFrame").foreach { s =>
assert(e.getMessage.toLowerCase(Locale.ROOT).contains(s.toLowerCase(Locale.ROOT)))
}
}
test("resolve default source") {
spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load()
.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.start()
.stop()
}
test("resolve full class") {
spark.readStream
.format("org.apache.spark.sql.streaming.test.DefaultSource")
.load()
.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.start()
.stop()
}
test("options") {
val map = new java.util.HashMap[String, String]
map.put("opt3", "3")
val df = spark.readStream
.format("org.apache.spark.sql.streaming.test")
.option("opt1", "1")
.options(Map("opt2" -> "2"))
.options(map)
.load()
assert(LastOptions.parameters("opt1") == "1")
assert(LastOptions.parameters("opt2") == "2")
assert(LastOptions.parameters("opt3") == "3")
LastOptions.clear()
df.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("opt1", "1")
.options(Map("opt2" -> "2"))
.options(map)
.option("checkpointLocation", newMetadataDir)
.start()
.stop()
assert(LastOptions.parameters("opt1") == "1")
assert(LastOptions.parameters("opt2") == "2")
assert(LastOptions.parameters("opt3") == "3")
}
test("partitioning") {
val df = spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load()
df.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.start()
.stop()
assert(LastOptions.partitionColumns == Nil)
df.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.partitionBy("a")
.start()
.stop()
assert(LastOptions.partitionColumns == Seq("a"))
withSQLConf("spark.sql.caseSensitive" -> "false") {
df.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.partitionBy("A")
.start()
.stop()
assert(LastOptions.partitionColumns == Seq("a"))
}
intercept[AnalysisException] {
df.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.partitionBy("b")
.start()
.stop()
}
}
test("stream paths") {
val df = spark.readStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.load("/test")
assert(LastOptions.parameters("path") == "/test")
LastOptions.clear()
df.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.start("/test")
.stop()
assert(LastOptions.parameters("path") == "/test")
}
test("test different data types for options") {
val df = spark.readStream
.format("org.apache.spark.sql.streaming.test")
.option("intOpt", 56)
.option("boolOpt", false)
.option("doubleOpt", 6.7)
.load("/test")
assert(LastOptions.parameters("intOpt") == "56")
assert(LastOptions.parameters("boolOpt") == "false")
assert(LastOptions.parameters("doubleOpt") == "6.7")
LastOptions.clear()
df.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("intOpt", 56)
.option("boolOpt", false)
.option("doubleOpt", 6.7)
.option("checkpointLocation", newMetadataDir)
.start("/test")
.stop()
assert(LastOptions.parameters("intOpt") == "56")
assert(LastOptions.parameters("boolOpt") == "false")
assert(LastOptions.parameters("doubleOpt") == "6.7")
}
test("unique query names") {
/** Start a query with a specific name */
def startQueryWithName(name: String = ""): StreamingQuery = {
spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load("/test")
.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.queryName(name)
.start()
}
/** Start a query without specifying a name */
def startQueryWithoutName(): StreamingQuery = {
spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load("/test")
.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.start()
}
/** Get the names of active streams */
def activeStreamNames: Set[String] = {
val streams = spark.streams.active
val names = streams.map(_.name).toSet
assert(streams.length === names.size, s"names of active queries are not unique: $names")
names
}
val q1 = startQueryWithName("name")
// Should not be able to start another query with the same name
intercept[IllegalArgumentException] {
startQueryWithName("name")
}
assert(activeStreamNames === Set("name"))
// Should be able to start queries with other names
val q3 = startQueryWithName("another-name")
assert(activeStreamNames === Set("name", "another-name"))
// Should be able to start queries with auto-generated names
val q4 = startQueryWithoutName()
assert(activeStreamNames.contains(q4.name))
// Should not be able to start a query with same auto-generated name
intercept[IllegalArgumentException] {
startQueryWithName(q4.name)
}
// Should be able to start query with that name after stopping the previous query
q1.stop()
val q5 = startQueryWithName("name")
assert(activeStreamNames.contains("name"))
spark.streams.active.foreach(_.stop())
}
test("trigger") {
val df = spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load("/test")
var q = df.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.trigger(ProcessingTime(10.seconds))
.start()
q.stop()
assert(q.asInstanceOf[StreamingQueryWrapper].streamingQuery.trigger == ProcessingTime(10000))
q = df.writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", newMetadataDir)
.trigger(ProcessingTime(100, TimeUnit.SECONDS))
.start()
q.stop()
assert(q.asInstanceOf[StreamingQueryWrapper].streamingQuery.trigger == ProcessingTime(100000))
}
test("source metadataPath") {
LastOptions.clear()
val checkpointLocation = new Path(newMetadataDir)
val df1 = spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load()
val df2 = spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load()
val q = df1.union(df2).writeStream
.format("org.apache.spark.sql.streaming.test")
.option("checkpointLocation", checkpointLocation.toString)
.trigger(ProcessingTime(10.seconds))
.start()
q.processAllAvailable()
q.stop()
verify(LastOptions.mockStreamSourceProvider).createSource(
any(),
meq(s"${new Path(makeQualifiedPath(checkpointLocation.toString)).toString}/sources/0"),
meq(None),
meq("org.apache.spark.sql.streaming.test"),
meq(Map.empty))
verify(LastOptions.mockStreamSourceProvider).createSource(
any(),
meq(s"${new Path(makeQualifiedPath(checkpointLocation.toString)).toString}/sources/1"),
meq(None),
meq("org.apache.spark.sql.streaming.test"),
meq(Map.empty))
}
private def newTextInput = Utils.createTempDir(namePrefix = "text").getCanonicalPath
test("check foreach() catches null writers") {
val df = spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load()
var w = df.writeStream
var e = intercept[IllegalArgumentException](w.foreach(null))
Seq("foreach", "null").foreach { s =>
assert(e.getMessage.toLowerCase(Locale.ROOT).contains(s.toLowerCase(Locale.ROOT)))
}
}
test("check foreach() does not support partitioning") {
val df = spark.readStream
.format("org.apache.spark.sql.streaming.test")
.load()
val foreachWriter = new ForeachWriter[Row] {
override def open(partitionId: Long, version: Long): Boolean = false
override def process(value: Row): Unit = {}
override def close(errorOrNull: Throwable): Unit = {}
}
var w = df.writeStream.partitionBy("value")
var e = intercept[AnalysisException](w.foreach(foreachWriter).start())
Seq("foreach", "partitioning").foreach { s =>
assert(e.getMessage.toLowerCase(Locale.ROOT).contains(s.toLowerCase(Locale.ROOT)))
}
}
test("prevent all column partitioning") {
withTempDir { dir =>
val path = dir.getCanonicalPath
intercept[AnalysisException] {
spark.range(10).writeStream
.outputMode("append")
.partitionBy("id")
.format("parquet")
.start(path)
}
}
}
private def testMemorySinkCheckpointRecovery(chkLoc: String, provideInWriter: Boolean): Unit = {
import testImplicits._
val ms = new MemoryStream[Int](0, sqlContext)
val df = ms.toDF().toDF("a")
val tableName = "test"
def startQuery: StreamingQuery = {
val writer = df.groupBy("a")
.count()
.writeStream
.format("memory")
.queryName(tableName)
.outputMode("complete")
if (provideInWriter) {
writer.option("checkpointLocation", chkLoc)
}
writer.start()
}
// no exception here
val q = startQuery
ms.addData(0, 1)
q.processAllAvailable()
q.stop()
checkAnswer(
spark.table(tableName),
Seq(Row(0, 1), Row(1, 1))
)
spark.sql(s"drop table $tableName")
// verify table is dropped
intercept[AnalysisException](spark.table(tableName).collect())
val q2 = startQuery
ms.addData(0)
q2.processAllAvailable()
checkAnswer(
spark.table(tableName),
Seq(Row(0, 2), Row(1, 1))
)
q2.stop()
}
test("MemorySink can recover from a checkpoint in Complete Mode") {
val checkpointLoc = newMetadataDir
val checkpointDir = new File(checkpointLoc, "offsets")
checkpointDir.mkdirs()
assert(checkpointDir.exists())
testMemorySinkCheckpointRecovery(checkpointLoc, provideInWriter = true)
}
test("SPARK-18927: MemorySink can recover from a checkpoint provided in conf in Complete Mode") {
val checkpointLoc = newMetadataDir
val checkpointDir = new File(checkpointLoc, "offsets")
checkpointDir.mkdirs()
assert(checkpointDir.exists())
withSQLConf(SQLConf.CHECKPOINT_LOCATION.key -> checkpointLoc) {
testMemorySinkCheckpointRecovery(checkpointLoc, provideInWriter = false)
}
}
test("append mode memory sink's do not support checkpoint recovery") {
import testImplicits._
val ms = new MemoryStream[Int](0, sqlContext)
val df = ms.toDF().toDF("a")
val checkpointLoc = newMetadataDir
val checkpointDir = new File(checkpointLoc, "offsets")
checkpointDir.mkdirs()
assert(checkpointDir.exists())
val e = intercept[AnalysisException] {
df.writeStream
.format("memory")
.queryName("test")
.option("checkpointLocation", checkpointLoc)
.outputMode("append")
.start()
}
assert(e.getMessage.contains("does not support recovering"))
assert(e.getMessage.contains("checkpoint location"))
}
test("SPARK-18510: use user specified types for partition columns in file sources") {
import org.apache.spark.sql.functions.udf
import testImplicits._
withTempDir { src =>
val createArray = udf { (length: Long) =>
for (i <- 1 to length.toInt) yield i.toString
}
spark.range(4).select(createArray('id + 1) as 'ex, 'id, 'id % 4 as 'part).coalesce(1).write
.partitionBy("part", "id")
.mode("overwrite")
.parquet(src.toString)
// Specify a random ordering of the schema, partition column in the middle, etc.
// Also let's say that the partition columns are Strings instead of Longs.
// partition columns should go to the end
val schema = new StructType()
.add("id", StringType)
.add("ex", ArrayType(StringType))
val sdf = spark.readStream
.schema(schema)
.format("parquet")
.load(src.toString)
assert(sdf.schema.toList === List(
StructField("ex", ArrayType(StringType)),
StructField("part", IntegerType), // inferred partitionColumn dataType
StructField("id", StringType))) // used user provided partitionColumn dataType
val sq = sdf.writeStream
.queryName("corruption_test")
.format("memory")
.start()
sq.processAllAvailable()
checkAnswer(
spark.table("corruption_test"),
// notice how `part` is ordered before `id`
Row(Array("1"), 0, "0") :: Row(Array("1", "2"), 1, "1") ::
Row(Array("1", "2", "3"), 2, "2") :: Row(Array("1", "2", "3", "4"), 3, "3") :: Nil
)
sq.stop()
}
}
test("user specified checkpointLocation precedes SQLConf") {
import testImplicits._
withTempDir { checkpointPath =>
withTempPath { userCheckpointPath =>
assert(!userCheckpointPath.exists(), s"$userCheckpointPath should not exist")
withSQLConf(SQLConf.CHECKPOINT_LOCATION.key -> checkpointPath.getAbsolutePath) {
val queryName = "test_query"
val ds = MemoryStream[Int].toDS
ds.writeStream
.format("memory")
.queryName(queryName)
.option("checkpointLocation", userCheckpointPath.getAbsolutePath)
.start()
.stop()
assert(checkpointPath.listFiles().isEmpty,
"SQLConf path is used even if user specified checkpointLoc: " +
s"${checkpointPath.listFiles()} is not empty")
assert(userCheckpointPath.exists(),
s"The user specified checkpointLoc (userCheckpointPath) is not created")
}
}
}
}
test("use SQLConf checkpoint dir when checkpointLocation is not specified") {
import testImplicits._
withTempDir { checkpointPath =>
withSQLConf(SQLConf.CHECKPOINT_LOCATION.key -> checkpointPath.getAbsolutePath) {
val queryName = "test_query"
val ds = MemoryStream[Int].toDS
ds.writeStream.format("memory").queryName(queryName).start().stop()
// Should use query name to create a folder in `checkpointPath`
val queryCheckpointDir = new File(checkpointPath, queryName)
assert(queryCheckpointDir.exists(), s"$queryCheckpointDir doesn't exist")
assert(
checkpointPath.listFiles().size === 1,
s"${checkpointPath.listFiles().toList} has 0 or more than 1 files ")
}
}
}
test("use SQLConf checkpoint dir when checkpointLocation is not specified without query name") {
import testImplicits._
withTempDir { checkpointPath =>
withSQLConf(SQLConf.CHECKPOINT_LOCATION.key -> checkpointPath.getAbsolutePath) {
val ds = MemoryStream[Int].toDS
ds.writeStream.format("console").start().stop()
// Should create a random folder in `checkpointPath`
assert(
checkpointPath.listFiles().size === 1,
s"${checkpointPath.listFiles().toList} has 0 or more than 1 files ")
}
}
}
test("configured checkpoint dir should not be deleted if a query is stopped without errors and" +
" force temp checkpoint deletion enabled") {
import testImplicits._
withTempDir { checkpointPath =>
withSQLConf(SQLConf.CHECKPOINT_LOCATION.key -> checkpointPath.getAbsolutePath,
SQLConf.FORCE_DELETE_TEMP_CHECKPOINT_LOCATION.key -> "true") {
val ds = MemoryStream[Int].toDS
val query = ds.writeStream.format("console").start()
assert(checkpointPath.exists())
query.stop()
assert(checkpointPath.exists())
}
}
}
test("temp checkpoint dir should be deleted if a query is stopped without errors") {
import testImplicits._
val query = MemoryStream[Int].toDS.writeStream.format("console").start()
query.processAllAvailable()
val checkpointDir = new Path(
query.asInstanceOf[StreamingQueryWrapper].streamingQuery.resolvedCheckpointRoot)
val fs = checkpointDir.getFileSystem(spark.sessionState.newHadoopConf())
assert(fs.exists(checkpointDir))
query.stop()
assert(!fs.exists(checkpointDir))
}
testQuietly("temp checkpoint dir should not be deleted if a query is stopped with an error") {
testTempCheckpointWithFailedQuery(false)
}
testQuietly("temp checkpoint should be deleted if a query is stopped with an error and force" +
" temp checkpoint deletion enabled") {
withSQLConf(SQLConf.FORCE_DELETE_TEMP_CHECKPOINT_LOCATION.key -> "true") {
testTempCheckpointWithFailedQuery(true)
}
}
private def testTempCheckpointWithFailedQuery(checkpointMustBeDeleted: Boolean): Unit = {
import testImplicits._
val input = MemoryStream[Int]
val query = input.toDS.map(_ / 0).writeStream.format("console").start()
val checkpointDir = new Path(
query.asInstanceOf[StreamingQueryWrapper].streamingQuery.resolvedCheckpointRoot)
val fs = checkpointDir.getFileSystem(spark.sessionState.newHadoopConf())
assert(fs.exists(checkpointDir))
input.addData(1)
intercept[StreamingQueryException] {
query.awaitTermination()
}
if (!checkpointMustBeDeleted) {
assert(fs.exists(checkpointDir))
} else {
assert(!fs.exists(checkpointDir))
}
}
test("SPARK-20431: Specify a schema by using a DDL-formatted string") {
spark.readStream
.format("org.apache.spark.sql.streaming.test")
.schema("aa INT")
.load()
assert(LastOptions.schema.isDefined)
assert(LastOptions.schema.get === StructType(StructField("aa", IntegerType) :: Nil))
LastOptions.clear()
}
test("SPARK-26586: Streams should have isolated confs") {
import testImplicits._
val input = MemoryStream[Int]
input.addData(1 to 10)
spark.conf.set("testKey1", 0)
val queries = (1 to 10).map { i =>
spark.conf.set("testKey1", i)
input.toDF().writeStream
.foreachBatch { (df: Dataset[Row], id: Long) =>
val v = df.sparkSession.conf.get("testKey1").toInt
if (i != v) {
throw new ConcurrentModificationException(s"Stream $i has the wrong conf value $v")
}
}
.start()
}
try {
queries.foreach(_.processAllAvailable())
} finally {
queries.foreach(_.stop())
}
}
}
|
aosagie/spark
|
sql/core/src/test/scala/org/apache/spark/sql/streaming/test/DataStreamReaderWriterSuite.scala
|
Scala
|
apache-2.0
| 23,374 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.ml.regression
import com.github.fommil.netlib.BLAS.{getInstance => blas}
import org.apache.spark.Logging
import org.apache.spark.annotation.Experimental
import org.apache.spark.ml.{PredictionModel, Predictor}
import org.apache.spark.ml.param.{Param, ParamMap}
import org.apache.spark.ml.tree.{DecisionTreeModel, GBTParams, TreeEnsembleModel, TreeRegressorParams}
import org.apache.spark.ml.util.{Identifiable, MetadataUtils}
import org.apache.spark.mllib.linalg.Vector
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.tree.{GradientBoostedTrees => OldGBT}
import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo}
import org.apache.spark.mllib.tree.loss.{AbsoluteError => OldAbsoluteError, Loss => OldLoss, SquaredError => OldSquaredError}
import org.apache.spark.mllib.tree.model.{GradientBoostedTreesModel => OldGBTModel}
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.DoubleType
/**
* :: Experimental ::
* [[http://en.wikipedia.org/wiki/Gradient_boosting Gradient-Boosted Trees (GBTs)]]
* learning algorithm for regression.
* It supports both continuous and categorical features.
*/
@Experimental
final class GBTRegressor(override val uid: String)
extends Predictor[Vector, GBTRegressor, GBTRegressionModel]
with GBTParams with TreeRegressorParams with Logging {
def this() = this(Identifiable.randomUID("gbtr"))
// Override parameter setters from parent trait for Java API compatibility.
// Parameters from TreeRegressorParams:
override def setMaxDepth(value: Int): this.type = super.setMaxDepth(value)
override def setMaxBins(value: Int): this.type = super.setMaxBins(value)
override def setMinInstancesPerNode(value: Int): this.type =
super.setMinInstancesPerNode(value)
override def setMinInfoGain(value: Double): this.type = super.setMinInfoGain(value)
override def setMaxMemoryInMB(value: Int): this.type = super.setMaxMemoryInMB(value)
override def setCacheNodeIds(value: Boolean): this.type = super.setCacheNodeIds(value)
override def setCheckpointInterval(value: Int): this.type = super.setCheckpointInterval(value)
/**
* The impurity setting is ignored for GBT models.GBT模型忽略杂质设置
* Individual trees are built using impurity "Variance."
*/
override def setImpurity(value: String): this.type = {
logWarning("GBTRegressor.setImpurity should NOT be used")
this
}
// Parameters from TreeEnsembleParams:
override def setSubsamplingRate(value: Double): this.type = super.setSubsamplingRate(value)
override def setSeed(value: Long): this.type = {
logWarning("The 'seed' parameter is currently ignored by Gradient Boosting.")
super.setSeed(value)
}
// Parameters from GBTParams:
override def setMaxIter(value: Int): this.type = super.setMaxIter(value)
override def setStepSize(value: Double): this.type = super.setStepSize(value)
// Parameters for GBTRegressor:
/**
* Loss function which GBT tries to minimize. (case-insensitive)
* Supported: "squared" (L2) and "absolute" (L1)
* (default = squared)
* @group param
*/
val lossType: Param[String] = new Param[String](this, "lossType", "Loss function which GBT" +
" tries to minimize (case-insensitive). Supported options:" +
s" ${GBTRegressor.supportedLossTypes.mkString(", ")}",
(value: String) => GBTRegressor.supportedLossTypes.contains(value.toLowerCase))
setDefault(lossType -> "squared")
/** @group setParam */
def setLossType(value: String): this.type = set(lossType, value)
/** @group getParam */
def getLossType: String = $(lossType).toLowerCase
/** (private[ml]) Convert new loss to old loss. */
override private[ml] def getOldLossType: OldLoss = {
getLossType match {
case "squared" => OldSquaredError
case "absolute" => OldAbsoluteError
case _ =>
// Should never happen because of check in setter method.
throw new RuntimeException(s"GBTRegressorParams was given bad loss type: $getLossType")
}
}
override protected def train(dataset: DataFrame): GBTRegressionModel = {
val categoricalFeatures: Map[Int, Int] =
MetadataUtils.getCategoricalFeatures(dataset.schema($(featuresCol)))
val oldDataset: RDD[LabeledPoint] = extractLabeledPoints(dataset)
val boostingStrategy = super.getOldBoostingStrategy(categoricalFeatures, OldAlgo.Regression)
val oldGBT = new OldGBT(boostingStrategy)
val oldModel = oldGBT.run(oldDataset)
GBTRegressionModel.fromOld(oldModel, this, categoricalFeatures)
}
override def copy(extra: ParamMap): GBTRegressor = defaultCopy(extra)
}
@Experimental
object GBTRegressor {
// The losses below should be lowercase.
/** Accessor for supported loss settings: squared (L2), absolute (L1) */
final val supportedLossTypes: Array[String] = Array("squared", "absolute").map(_.toLowerCase)
}
/**
* :: Experimental ::
*
* [[http://en.wikipedia.org/wiki/Gradient_boosting Gradient-Boosted Trees (GBTs)]]
* model for regression.
* It supports both continuous and categorical features.
* @param _trees Decision trees in the ensemble.
* @param _treeWeights Weights for the decision trees in the ensemble.
*/
@Experimental
final class GBTRegressionModel(
override val uid: String,
private val _trees: Array[DecisionTreeRegressionModel],
private val _treeWeights: Array[Double])
extends PredictionModel[Vector, GBTRegressionModel]
with TreeEnsembleModel with Serializable {
require(numTrees > 0, "GBTRegressionModel requires at least 1 tree.")
require(_trees.length == _treeWeights.length, "GBTRegressionModel given trees, treeWeights of" +
s" non-matching lengths (${_trees.length}, ${_treeWeights.length}, respectively).")
override def trees: Array[DecisionTreeModel] = _trees.asInstanceOf[Array[DecisionTreeModel]]
override def treeWeights: Array[Double] = _treeWeights
override protected def transformImpl(dataset: DataFrame): DataFrame = {
val bcastModel = dataset.sqlContext.sparkContext.broadcast(this)
val predictUDF = udf { (features: Any) =>
bcastModel.value.predict(features.asInstanceOf[Vector])
}
dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
}
override protected def predict(features: Vector): Double = {
// TODO: When we add a generic Boosting class, handle transform there? SPARK-7129
// Classifies by thresholding sum of weighted tree predictions
val treePredictions = _trees.map(_.rootNode.predictImpl(features).prediction)
blas.ddot(numTrees, treePredictions, 1, _treeWeights, 1)
}
override def copy(extra: ParamMap): GBTRegressionModel = {
copyValues(new GBTRegressionModel(uid, _trees, _treeWeights), extra).setParent(parent)
}
override def toString: String = {
s"GBTRegressionModel with $numTrees trees"
}
/** (private[ml]) Convert to a model in the old API */
private[ml] def toOld: OldGBTModel = {
new OldGBTModel(OldAlgo.Regression, _trees.map(_.toOld), _treeWeights)
}
}
private[ml] object GBTRegressionModel {
/** (private[ml]) Convert a model from the old API */
def fromOld(
oldModel: OldGBTModel,
parent: GBTRegressor,
categoricalFeatures: Map[Int, Int]): GBTRegressionModel = {
require(oldModel.algo == OldAlgo.Regression, "Cannot convert GradientBoostedTreesModel" +
s" with algo=${oldModel.algo} (old API) to GBTRegressionModel (new API).")
val newTrees = oldModel.trees.map { tree =>
// parent for each tree is null since there is no good way to set this.
DecisionTreeRegressionModel.fromOld(tree, null, categoricalFeatures)
}
val uid = if (parent != null) parent.uid else Identifiable.randomUID("gbtr")
new GBTRegressionModel(parent.uid, newTrees, oldModel.treeWeights)
}
}
|
tophua/spark1.52
|
mllib/src/main/scala/org/apache/spark/ml/regression/GBTRegressor.scala
|
Scala
|
apache-2.0
| 8,710 |
package io.udash.css
import io.udash.testing.UdashSharedTest
import scala.io.Source
class CssFileRendererTest extends UdashSharedTest {
val stylesheets = Seq(StylesheetExample, SecondStylesheetExample)
val testDir = "target/CssFileRendererTest"
"CssFileRenderer" should {
"render stylesheets to file" in {
implicit val r = scalacss.internal.StringRenderer.defaultPretty
val renderer = new CssFileRenderer(testDir, stylesheets, createMain = true)
renderer.render()
val mainCssLines = Source.fromFile(s"$testDir/main.css").getLines().toSeq
mainCssLines.size should be(2)
mainCssLines(0) should be("@import \"io.udash.css.StylesheetExample$.css\";")
mainCssLines(1) should be("@import \"io.udash.css.SecondStylesheetExample$.css\";")
val firstCss = Source.fromFile(s"$testDir/io.udash.css.StylesheetExample$$.css").getLines().mkString(System.lineSeparator())
firstCss.trim should be(
""".io-udash-css-StylesheetExample-common {
| background-color: red;
|}
|
|@font-face {
| font-family: myFont;
| src: url(font.woff);
| font-stretch: expanded;
| font-style: italic;
| unicode-range: U+0-5;
|}
|
|.io-udash-css-StylesheetExample-kf1 {
| height: 100px;
| width: 30px;
|}
|
|@keyframes io-udash-css-StylesheetExample-animation {
| 0.0% {
| height: 100px;
| width: 30px;
| }
|
| 25.0% {
| height: 150px;
| width: 30px;
| }
|
| 50.0% {
| height: 150px;
| width: 30px;
| }
|
| 75.0% {
| height: 100px;
| width: 30px;
| }
|
| 100.0% {
| height: 200px;
| width: 60px;
| }
|
|}
|
|.io-udash-css-StylesheetExample-test1 {
| background-color: red;
| margin: 12px auto;
| text-align: left;
| cursor: pointer;
|}
|
|.io-udash-css-StylesheetExample-test1:hover {
| cursor: -moz-zoom-in;
| cursor: -o-zoom-in;
| cursor: -webkit-zoom-in;
| cursor: zoom-in;
|}
|
|@media not handheld and (orientation:landscape) and (max-width:540px) {
| .io-udash-css-StylesheetExample-test1 {
| width: 300px;
| }
|}
|
|@media not handheld and (orientation:landscape) and (max-width:640px) {
| .io-udash-css-StylesheetExample-test1 {
| width: 400px;
| }
|}
|
|@media not handheld and (orientation:landscape) and (max-width:740px) {
| .io-udash-css-StylesheetExample-test1 {
| width: 500px;
| }
|}
|
|@media not handheld and (orientation:landscape) and (max-width:840px) {
| .io-udash-css-StylesheetExample-test1 {
| width: 600px;
| }
|}
|
|.io-udash-css-StylesheetExample-test2 {
| background-color: red;
| margin: 12px auto;
| font-family: myFont;
|}
|
|.io-udash-css-StylesheetExample-test2:hover {
| cursor: -moz-zoom-in;
| cursor: -o-zoom-in;
| cursor: -webkit-zoom-in;
| cursor: zoom-in;
|}
|
|.io-udash-css-StylesheetExample-test2 ul,.io-udash-css-StylesheetExample-test2 li {
| margin: 50px;
|}
|
|.extraStyle {
| background-color: red;
| margin: 24px auto;
|}
|
|.StylesheetExample-indent-0 {
| padding-left: 0;
|}
|
|.StylesheetExample-indent-1 {
| padding-left: 2ex;
|}
|
|.StylesheetExample-indent-2 {
| padding-left: 4ex;
|}
|
|.StylesheetExample-indent-3 {
| padding-left: 6ex;
|}
""".stripMargin.trim)
val secondCss = Source.fromFile(s"$testDir/io.udash.css.SecondStylesheetExample$$.css").getLines().mkString(System.lineSeparator())
secondCss.trim should be(
""".io-udash-css-SecondStylesheetExample-test {
| margin: 12px auto;
| text-align: left;
| cursor: pointer;
|}
|
|.io-udash-css-SecondStylesheetExample-test:hover {
| cursor: -moz-zoom-in;
| cursor: -o-zoom-in;
| cursor: -webkit-zoom-in;
| cursor: zoom-in;
|}
|
|@media not handheld and (orientation:landscape) and (max-width:640px) {
| .io-udash-css-SecondStylesheetExample-test {
| width: 400px;
| }
|}
""".stripMargin.trim)
}
}
}
|
UdashFramework/udash-core
|
css/.jvm/src/test/scala/io/udash/css/CssFileRendererTest.scala
|
Scala
|
apache-2.0
| 5,158 |
import sbt._
import Keys._
object SoqlToy {
lazy val settings: Seq[Setting[_]] = BuildSettings.projectSettings(assembly = true) ++ Seq(
name := "soql-toy",
libraryDependencies ++= Seq(
"org.slf4j" % "slf4j-simple" % BuildSettings.slf4jVersion,
"org.scalacheck" %% "scalacheck" % "1.14.0" % "test")
)
}
|
socrata-platform/soql-reference
|
project/SoqlToy.scala
|
Scala
|
apache-2.0
| 327 |
// tests exhaustivity doesn't give warnings (due to its heuristic rewrites kicking in or it backing off)
object Test {
// List() => Nil
List(1) match {
case List() =>
case x :: xs =>
}
// we don't look into guards
val turnOffChecks = true
List(1) match {
case _ if turnOffChecks =>
}
// we back off when there are any user-defined extractors
// in fact this is exhaustive, but we pretend we don't know since List's unapplySeq is not special to the compiler
// to compensate our ignorance, we back off
// well, in truth, we do rewrite List() to Nil, but otherwise we do nothing
// the full rewrite List(a, b) to a :: b :: Nil, for example is planned (but not sure it's a good idea)
List(true, false) match {
case List(_, _, _*) =>
case List(node, _*) =>
case Nil =>
}
}
|
loskutov/intellij-scala
|
testdata/scalacTests/pos/exhaustive_heuristics.scala
|
Scala
|
apache-2.0
| 824 |
/*
* Copyright 2016 The BigDL Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intel.analytics.bigdl.dllib.integration.torch
import com.intel.analytics.bigdl.dllib.nn.ClassSimplexCriterion
import com.intel.analytics.bigdl.dllib.tensor.Tensor
import scala.util.Random
@com.intel.analytics.bigdl.tags.Serial
class ClassSimplexCriterionSpec extends TorchSpec {
"A ClassSimplexCriterion " should "generate correct output and grad with " in {
torchCheck()
val criterion = new ClassSimplexCriterion[Double](5)
val input = Tensor[Double](2, 5).apply1(e => Random.nextDouble())
val target = Tensor[Double](2)
target(Array(1)) = 2.0
target(Array(2)) = 1.0
val start = System.nanoTime()
val output1 = criterion.forward(input, target)
val output2 = criterion.backward(input, target)
val end = System.nanoTime()
val scalaTime = end - start
val code = "criterion = nn.ClassSimplexCriterion(5)\\n" +
"output1 = criterion:forward(input, target)\\n " +
"output2 = criterion:backward(input, target)"
val (luaTime, torchResult) = TH.run(code, Map("input" -> input, "target" -> target),
Array("output1", "output2"))
val luaOutput1 = torchResult("output1").asInstanceOf[Double]
val luaOutput2 = torchResult("output2").asInstanceOf[Tensor[Double]]
luaOutput1 should be(output1)
luaOutput2 should be(output2)
println("Test case : ClassSimplexCriterion, Torch : " + luaTime +
" s, Scala : " + scalaTime / 1e9 + " s")
}
}
|
intel-analytics/BigDL
|
scala/dllib/src/test/scala/com/intel/analytics/bigdl/dllib/integration/torch/ClassSimplexCriterionSpec.scala
|
Scala
|
apache-2.0
| 2,041 |
/*
* (c) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* 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 cogdebugger.ui.components
import scala.swing._
import java.awt.geom.Point2D
import scala.swing.event._
import java.awt.{BasicStroke, Graphics2D}
import javax.swing.SwingConstants
import scala.swing.event.MousePressed
import scala.swing.event.MouseReleased
import scala.swing.event.UIElementResized
import scala.swing.event.MouseDragged
import cogdebugger.ui.fieldvisualizations.Zoomable
/*
* Created with IntelliJ IDEA.
* User: gonztobi
* Date: 7/1/13
* Time: 2:30 PM
*/
/** Augments a panel with mouse pan and zoom capability (sort of like your
* favorite online maps application).
*
* Rather than mixing in this trait directly to some panel displaying the
* visual that you want to pan and zoom, you should wrap that panel in another
* panel and mix in this trait to the wrapper. This helps guarantee clean
* redraws of the panel (otherwise a screen clear can "miss" due to the
* applied pan and zoom). */
trait MousePanAndZoom extends Component with Zoomable {
protected var (panOffsetX, panOffsetY) = (0.0, 0.0) // Pan offset
protected var zoom = 1.0 // Magnification level of image
var preserveLineThickness = true
var stroke = new BasicStroke(1 / zoom.toFloat)
protected val mouseDownLoc = new Point2D.Double() // Location where mouse clicked
protected val lastMouseLoc = new Point2D.Double() // Last location of mouse
protected var rightMouseDown = false // Last mouse down was/wasn't a right-click
//protected val lastSize = new Dimension(-1, -1)
protected var lastSize: Option[Dimension] = None
var zDelta = 1.1f
def zoomLevel = zoom
def zoomLevel_=(zoom: Int) { this.zoom = zoom; stroke = new BasicStroke(1 / zoom.toFloat) }
override def zoomIn() { zoomView(zDelta) }
override def zoomOut() { zoomView(1 / zDelta) }
def changeZoomLevel(delta: Float) {
// Our viewers that don't use mouse pan and zoom usually add or subtract
// the delta to their current zoom level. To zoom in, you use a positive
// delta, and zoom out with negative. This class however, multiplies
// in the delta, so we have to handle the delta a little differently.
// We also don't want to multiply zoom by 0, ever.
if (delta > 0)
zoomView(delta)
else if (delta < 0)
zoomView(1 / (-delta))
// val centerOfZoom = new Point2D.Float(0, 0)
// if (delta > 0)
// zoomView(centerOfZoom, delta)
// else if (delta < 0)
// zoomView(centerOfZoom, 1 / (-delta))
}
def resetView() {
// TODO Center image instead of just setting panX/Y to zero
panOffsetX = 0; panOffsetY = 0
zoom = 1
repaint()
}
/** Sets current zoom factor; zooms about screen center */
def setZoom(zoomFactor: Double) {
zoomView(zoomFactor / zoom)
}
/** Multiplies current zoom level by amt; zooms about screen center */
def zoomView(amt: Double) {
val centerX = size.getWidth / 2
val centerY = size.getHeight / 2
zoomView(new Point2D.Double(centerX, centerY), amt)
}
/** Zooms about last mouse-down location; zoom amount is determined by the
* delta between the current mouse location and the mouse down location. */
def zoomView(newMouseX: Float, newMouseY: Float) {
val dz = if (newMouseY - lastMouseLoc.getY.toFloat > 0)
1.1f
else if (newMouseY - lastMouseLoc.getY.toFloat < 0)
1 / 1.1f
else
1
// Translate mouse coords into image coords
val mousex = mouseDownLoc.getX// - panOffsetX
val mousey = mouseDownLoc.getY// - panOffsetY
zoomView(new Point2D.Double(mousex, mousey), dz)
}
/** Multiplies current zoom level by amt; zooms about the given point in
* image coordinates. */
def zoomView(aboutPoint: Point2D, amt: Double) {
// Effective Panel coords
val px = aboutPoint.getX - panOffsetX
val py = aboutPoint.getY - panOffsetY
// Adjust pan amount to account for zoom
panOffsetX -= px * amt - px
panOffsetY -= py * amt - py
zoom *= amt
repaint()
}
/** Pans the view according to mouse movement. */
def panView(newMouseX: Double, newMouseY: Double) {
panOffsetX += newMouseX - lastMouseLoc.getX
panOffsetY += newMouseY - lastMouseLoc.getY
repaint()
}
listenTo(this, mouse.clicks, mouse.moves)
reactions += {
// Implement mouse pan/zoom ///////////////////////////////////////////////
case e: MousePressed => {
if (e.peer.getButton == java.awt.event.MouseEvent.BUTTON3)
rightMouseDown = true
else if (e.peer.getButton == java.awt.event.MouseEvent.BUTTON2)
resetView()
mouseDownLoc.setLocation(e.point)
lastMouseLoc.setLocation(e.point)
}
case MouseDragged(src, point, mods) => {
if (rightMouseDown)
zoomView(point.x, point.y)
else
panView(point.x, point.y)
lastMouseLoc.setLocation(point)
repaint()
}
case e: MouseReleased => {
if (e.peer.getButton == java.awt.event.MouseEvent.BUTTON3)
rightMouseDown = false
}
// Manage additional/reduced space from window resizing ///////////////////
case UIElementResized(source) if source == this => {
// Keep the view centered in the panel as it resizes.
lastSize match {
case Some(dim) =>
val (dx, dy) = (size.width - dim.width, size.height - dim.height)
dim.setSize(size)
panOffsetX += dx / 2f
panOffsetY += dy / 2f
case None =>
lastSize = Option(new Dimension(size))
}
}
}
/**
* Computes which cells are visible at the current pan and zoom settings
* given a cell size in pixels. Cells are assumed to be square.
* @param cellSize Width (or height) of a the square cell, in pixels
* @param rows Number of rows of cells
* @param cols Number of columns of cells
* @return (firstRow, firstCol, lastRow, lastCol)
*/
def getVisibleCellBounds(cellSize: Int, rows: Int, cols: Int) = {
val x = panOffsetX
val y = panOffsetY
val w = bounds.width
val h = bounds.height
val ecs = cellSize * zoom // effective cell size
val firstRow = scala.math.floor(-y / ecs).toInt
val firstCol = scala.math.floor(-x / ecs).toInt
val lastRow =
if (y <= 0)
scala.math.ceil(h / ecs).toInt + 1 + firstRow
else
scala.math.ceil((h - y) / ecs).toInt
val lastCol =
if (x <= 0)
scala.math.ceil(w / ecs).toInt + 1 + firstCol
else
scala.math.ceil((w - x) / ecs).toInt
// Clamp values before returning
//(firstRow max 0, firstCol max 0, lastRow min rows, lastCol min cols)
// Clamping as above makes it difficult to blit from a BufferedImage
// (a draw buffer) instead of using g.draw* calls.
(firstRow, firstCol, lastRow, lastCol)
}
// /**
// * Classes that implement this trait and override paintComponent should call
// * super.paintComponent immediately to apply the pan and zoom. Alternatively,
// * if you don't want to call super.paintComponent, you can immediately apply
// * the following transforms to the Graphics2D object to do the pan and zoom:
// * <pre>
// * g.translate(panOffsetX, panOffsetY)
// * g.transform(zoomTransform)
// * </pre>
// * @param g Graphics2D object to draw with
// */
// abstract override def paintComponent(g: Graphics2D) {
//
// println(f"in PAINTCOMPONENT! [pan($panOffsetX%.2f, $panOffsetY%.2f), zoom($zoomLevel%.2f)]")
//
// // Clear any previous drawing in this panel
// super.paintComponent(g)
//
// // Apply transforms to the graphics object, which will be passed to child
// // components when they do their painting.
// g.translate(panOffsetX, panOffsetY)
// g.scale(zoom, zoom)
// if (preserveLineThickness) g.setStroke(new BasicStroke(1 / zoom.toFloat))
// }
override def paintChildren(g: Graphics2D) {
// Our translating/zooming means children don't know exactly what part of
// the screen needs clearing, so we have to do it ourselves.
val oldColor = g.getColor
g.setColor(background)
g.fillRect(0, 0, bounds.width, bounds.height) // Clear old drawings
g.setColor(oldColor)
g.translate(panOffsetX, panOffsetY)
g.scale(zoom, zoom)
if (preserveLineThickness) g.setStroke(stroke)
super.paintChildren(g)
}
// TODO: Maybe add scroll bars and things?
// Probably better to just drop your drawing inside a scrollpane in that
// case, no? Just make sure preferredSize is set correctly.
}
object MousePanAndZoom {
def wrap(panel: Panel) = {
val p = new BorderPanel with MousePanAndZoom
p.layout(panel) = BorderPanel.Position.Center
p
}
}
object Test {
def main(args: Array[String]) {
Swing.onEDT {
val frame = top
frame.visible = true
println("Wrapper size after showing: "+frame.wrapper.size)
}
}
lazy val top = new MainFrame() {
title = "Test"
val panel = new Panel {
preferredSize = new Dimension(100, 100)
override def paintComponent(g: Graphics2D) {
super.paintComponent(g)
g.fillRect(10, 10, 80, 80)
}
}
//val wrapper = MousePanAndZoom.wrap(panel)
val wrapper = MousePanAndZoom.wrap(panel) //new PanAndZoomPanel(panel)
println("wrapper size: "+wrapper.size)
contents = wrapper
}
}
object TestingStuff extends SimpleSwingApplication {
lazy val top = new MainFrame() {
println("Creating new MainFrame.")
println(" Using layout manager: "+peer.getLayout)
// val label = new Label("TEST TEXT")
// contents = new CustomPanel(label)
// contents = new ColoredSquarePanel(20, new Color(0, 255, 0))
// contents = new GridPanel(1, 1) with MousePanAndZoom {
// contents += new ColoredSquarePanel(20, new Color(255, 0, 0))
//// contents += new ColoredSquarePanel(20, new Color(0, 255, 0))
// }
//contents = new PanAndZoomPanel(new ColoredSquarePanel(20, new Color(0, 255, 0)))
contents = MousePanAndZoom.wrap(new ColoredSquarePanel(20, new Color(0, 255, 0)))
// contents = new BoxPanel(Orientation.Horizontal) {
// contents += Swing.HGlue
// contents += new ColoredSquarePanel(20, new Color(0, 255, 0))
// contents += Swing.HGlue
// }
}
class CustomPanel(wrapped: Component) extends GridPanel(1, 1) {
background = new Color(255, 0, 0)
contents += wrapped
}
class ColoredSquarePanel(size: Int, color: Color) extends Panel {
println("Creating new ColoredSquarePanel.")
println(" Using layout manager: "+peer.getLayout)
preferredSize = new Dimension(size, size)
//maximumSize = new Dimension(size, size)
println(" Preferred size is: "+preferredSize)
//background = new Color(200, 0, 100) // Pink background for debugging
override def paintComponent(g: Graphics2D) {
super.paintComponent(g)
g.setColor(color)
g.fillRect(0, 0, size, size)
}
}
}
|
hpe-cct/cct-core
|
src/main/scala/cogdebugger/ui/components/MousePanAndZoom.scala
|
Scala
|
apache-2.0
| 11,534 |
/*
* 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
import java.io.{Externalizable, ObjectInput, ObjectOutput}
import java.sql.{Date, Timestamp}
import org.scalatest.Assertions._
import org.scalatest.exceptions.TestFailedException
import org.scalatest.prop.TableDrivenPropertyChecks._
import org.apache.spark.{SparkException, TaskContext}
import org.apache.spark.sql.catalyst.{FooClassWithEnum, FooEnum, ScroogeLikeExample}
import org.apache.spark.sql.catalyst.encoders.{OuterScopes, RowEncoder}
import org.apache.spark.sql.catalyst.plans.{LeftAnti, LeftSemi}
import org.apache.spark.sql.catalyst.util.sideBySide
import org.apache.spark.sql.execution.{LogicalRDD, RDDScanExec, SQLExecution}
import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
import org.apache.spark.sql.execution.exchange.{BroadcastExchangeExec, ShuffleExchangeExec}
import org.apache.spark.sql.execution.streaming.MemoryStream
import org.apache.spark.sql.expressions.UserDefinedFunction
import org.apache.spark.sql.functions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types._
case class TestDataPoint(x: Int, y: Double, s: String, t: TestDataPoint2)
case class TestDataPoint2(x: Int, s: String)
object TestForTypeAlias {
type TwoInt = (Int, Int)
type ThreeInt = (TwoInt, Int)
type SeqOfTwoInt = Seq[TwoInt]
def tupleTypeAlias: TwoInt = (1, 1)
def nestedTupleTypeAlias: ThreeInt = ((1, 1), 2)
def seqOfTupleTypeAlias: SeqOfTwoInt = Seq((1, 1), (2, 2))
}
class DatasetSuite extends QueryTest
with SharedSparkSession
with AdaptiveSparkPlanHelper {
import testImplicits._
private implicit val ordering = Ordering.by((c: ClassData) => c.a -> c.b)
test("checkAnswer should compare map correctly") {
val data = Seq((1, "2", Map(1 -> 2, 2 -> 1)))
checkAnswer(
data.toDF(),
Seq(Row(1, "2", Map(2 -> 1, 1 -> 2))))
}
test("toDS") {
val data = Seq(("a", 1), ("b", 2), ("c", 3))
checkDataset(
data.toDS(),
data: _*)
}
test("toDS should compare map with byte array keys correctly") {
// Choose the order of arrays in such way, that sorting keys of different maps by _.toString
// will not incidentally put equal keys together.
val arrays = (1 to 5).map(_ => Array[Byte](0.toByte, 0.toByte)).sortBy(_.toString).toArray
arrays(0)(1) = 1.toByte
arrays(1)(1) = 2.toByte
arrays(2)(1) = 2.toByte
arrays(3)(1) = 1.toByte
val mapA = Map(arrays(0) -> "one", arrays(2) -> "two")
val subsetOfA = Map(arrays(0) -> "one")
val equalToA = Map(arrays(1) -> "two", arrays(3) -> "one")
val notEqualToA1 = Map(arrays(1) -> "two", arrays(3) -> "not one")
val notEqualToA2 = Map(arrays(1) -> "two", arrays(4) -> "one")
// Comparing map with itself
checkDataset(Seq(mapA).toDS(), mapA)
// Comparing map with equivalent map
checkDataset(Seq(equalToA).toDS(), mapA)
checkDataset(Seq(mapA).toDS(), equalToA)
// Comparing map with it's subset
intercept[TestFailedException](checkDataset(Seq(subsetOfA).toDS(), mapA))
intercept[TestFailedException](checkDataset(Seq(mapA).toDS(), subsetOfA))
// Comparing map with another map differing by single value
intercept[TestFailedException](checkDataset(Seq(notEqualToA1).toDS(), mapA))
intercept[TestFailedException](checkDataset(Seq(mapA).toDS(), notEqualToA1))
// Comparing map with another map differing by single key
intercept[TestFailedException](checkDataset(Seq(notEqualToA2).toDS(), mapA))
intercept[TestFailedException](checkDataset(Seq(mapA).toDS(), notEqualToA2))
}
test("toDS with RDD") {
val ds = sparkContext.makeRDD(Seq("a", "b", "c"), 3).toDS()
checkDataset(
ds.mapPartitions(_ => Iterator(1)),
1, 1, 1)
}
test("emptyDataset") {
val ds = spark.emptyDataset[Int]
assert(ds.count() == 0L)
assert(ds.collect() sameElements Array.empty[Int])
}
test("range") {
assert(spark.range(10).map(_ + 1).reduce(_ + _) == 55)
assert(spark.range(10).map{ case i: java.lang.Long => i + 1 }.reduce(_ + _) == 55)
assert(spark.range(0, 10).map(_ + 1).reduce(_ + _) == 55)
assert(spark.range(0, 10).map{ case i: java.lang.Long => i + 1 }.reduce(_ + _) == 55)
assert(spark.range(0, 10, 1, 2).map(_ + 1).reduce(_ + _) == 55)
assert(spark.range(0, 10, 1, 2).map{ case i: java.lang.Long => i + 1 }.reduce(_ + _) == 55)
}
test("SPARK-12404: Datatype Helper Serializability") {
val ds = sparkContext.parallelize((
new Timestamp(0),
new Date(0),
java.math.BigDecimal.valueOf(1),
scala.math.BigDecimal(1)) :: Nil).toDS()
ds.collect()
}
test("collect, first, and take should use encoders for serialization") {
val item = NonSerializableCaseClass("abcd")
val ds = Seq(item).toDS()
assert(ds.collect().head == item)
assert(ds.collectAsList().get(0) == item)
assert(ds.first() == item)
assert(ds.take(1).head == item)
assert(ds.takeAsList(1).get(0) == item)
assert(ds.toLocalIterator().next() === item)
}
test("coalesce, repartition") {
val data = (1 to 100).map(i => ClassData(i.toString, i))
val ds = data.toDS()
intercept[IllegalArgumentException] {
ds.coalesce(0)
}
intercept[IllegalArgumentException] {
ds.repartition(0)
}
assert(ds.repartition(10).rdd.partitions.length == 10)
checkDatasetUnorderly(
ds.repartition(10),
data: _*)
assert(ds.coalesce(1).rdd.partitions.length == 1)
checkDatasetUnorderly(
ds.coalesce(1),
data: _*)
}
test("as tuple") {
val data = Seq(("a", 1), ("b", 2)).toDF("a", "b")
checkDataset(
data.as[(String, Int)],
("a", 1), ("b", 2))
}
test("as case class / collect") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDF("a", "b").as[ClassData]
checkDataset(
ds,
ClassData("a", 1), ClassData("b", 2), ClassData("c", 3))
assert(ds.collect().head == ClassData("a", 1))
}
test("as case class - reordered fields by name") {
val ds = Seq((1, "a"), (2, "b"), (3, "c")).toDF("b", "a").as[ClassData]
assert(ds.collect() === Array(ClassData("a", 1), ClassData("b", 2), ClassData("c", 3)))
}
test("as case class - take") {
val ds = Seq((1, "a"), (2, "b"), (3, "c")).toDF("b", "a").as[ClassData]
assert(ds.take(2) === Array(ClassData("a", 1), ClassData("b", 2)))
}
test("as case class - tail") {
val ds = Seq((1, "a"), (2, "b"), (3, "c")).toDF("b", "a").as[ClassData]
assert(ds.tail(2) === Array(ClassData("b", 2), ClassData("c", 3)))
}
test("as seq of case class - reorder fields by name") {
val df = spark.range(3).select(array(struct($"id".cast("int").as("b"), lit("a").as("a"))))
val ds = df.as[Seq[ClassData]]
assert(ds.collect() === Array(
Seq(ClassData("a", 0)),
Seq(ClassData("a", 1)),
Seq(ClassData("a", 2))))
}
test("as map of case class - reorder fields by name") {
val df = spark.range(3).select(map(lit(1), struct($"id".cast("int").as("b"), lit("a").as("a"))))
val ds = df.as[Map[Int, ClassData]]
assert(ds.collect() === Array(
Map(1 -> ClassData("a", 0)),
Map(1 -> ClassData("a", 1)),
Map(1 -> ClassData("a", 2))))
}
test("map") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.map(v => (v._1, v._2 + 1)),
("a", 2), ("b", 3), ("c", 4))
}
test("map with type change with the exact matched number of attributes") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.map(identity[(String, Int)])
.as[OtherTuple]
.map(identity[OtherTuple]),
OtherTuple("a", 1), OtherTuple("b", 2), OtherTuple("c", 3))
}
test("map with type change with less attributes") {
val ds = Seq(("a", 1, 3), ("b", 2, 4), ("c", 3, 5)).toDS()
checkDataset(
ds.as[OtherTuple]
.map(identity[OtherTuple]),
OtherTuple("a", 1), OtherTuple("b", 2), OtherTuple("c", 3))
}
test("map and group by with class data") {
// We inject a group by here to make sure this test case is future proof
// when we implement better pipelining and local execution mode.
val ds: Dataset[(ClassData, Long)] = Seq(ClassData("one", 1), ClassData("two", 2)).toDS()
.map(c => ClassData(c.a, c.b + 1))
.groupByKey(p => p).count()
checkDatasetUnorderly(
ds,
(ClassData("one", 2), 1L), (ClassData("two", 3), 1L))
}
test("select") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.select(expr("_2 + 1").as[Int]),
2, 3, 4)
}
test("SPARK-16853: select, case class and tuple") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.select(expr("struct(_2, _2)").as[(Int, Int)]): Dataset[(Int, Int)],
(1, 1), (2, 2), (3, 3))
checkDataset(
ds.select(expr("named_struct('a', _1, 'b', _2)").as[ClassData]): Dataset[ClassData],
ClassData("a", 1), ClassData("b", 2), ClassData("c", 3))
}
test("select 2") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.select(
expr("_1").as[String],
expr("_2").as[Int]) : Dataset[(String, Int)],
("a", 1), ("b", 2), ("c", 3))
}
test("select 2, primitive and tuple") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.select(
expr("_1").as[String],
expr("struct(_2, _2)").as[(Int, Int)]),
("a", (1, 1)), ("b", (2, 2)), ("c", (3, 3)))
}
test("select 2, primitive and class") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.select(
expr("_1").as[String],
expr("named_struct('a', _1, 'b', _2)").as[ClassData]),
("a", ClassData("a", 1)), ("b", ClassData("b", 2)), ("c", ClassData("c", 3)))
}
test("select 2, primitive and class, fields reordered") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.select(
expr("_1").as[String],
expr("named_struct('b', _2, 'a', _1)").as[ClassData]),
("a", ClassData("a", 1)), ("b", ClassData("b", 2)), ("c", ClassData("c", 3)))
}
test("REGEX column specification") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
withSQLConf(SQLConf.SUPPORT_QUOTED_REGEX_COLUMN_NAME.key -> "false") {
var e = intercept[AnalysisException] {
ds.select(expr("`(_1)?+.+`").as[Int])
}.getMessage
assert(e.contains("cannot resolve '`(_1)?+.+`'"))
e = intercept[AnalysisException] {
ds.select(expr("`(_1|_2)`").as[Int])
}.getMessage
assert(e.contains("cannot resolve '`(_1|_2)`'"))
e = intercept[AnalysisException] {
ds.select(ds("`(_1)?+.+`"))
}.getMessage
assert(e.contains("Cannot resolve column name \\"`(_1)?+.+`\\""))
e = intercept[AnalysisException] {
ds.select(ds("`(_1|_2)`"))
}.getMessage
assert(e.contains("Cannot resolve column name \\"`(_1|_2)`\\""))
}
withSQLConf(SQLConf.SUPPORT_QUOTED_REGEX_COLUMN_NAME.key -> "true") {
checkDataset(
ds.select(ds.col("_2")).as[Int],
1, 2, 3)
checkDataset(
ds.select(ds.colRegex("`(_1)?+.+`")).as[Int],
1, 2, 3)
checkDataset(
ds.select(ds("`(_1|_2)`"))
.select(expr("named_struct('a', _1, 'b', _2)").as[ClassData]),
ClassData("a", 1), ClassData("b", 2), ClassData("c", 3))
checkDataset(
ds.alias("g")
.select(ds("g.`(_1|_2)`"))
.select(expr("named_struct('a', _1, 'b', _2)").as[ClassData]),
ClassData("a", 1), ClassData("b", 2), ClassData("c", 3))
checkDataset(
ds.select(ds("`(_1)?+.+`"))
.select(expr("_2").as[Int]),
1, 2, 3)
checkDataset(
ds.alias("g")
.select(ds("g.`(_1)?+.+`"))
.select(expr("_2").as[Int]),
1, 2, 3)
checkDataset(
ds.select(expr("`(_1)?+.+`").as[Int]),
1, 2, 3)
val m = ds.select(expr("`(_1|_2)`"))
checkDataset(
ds.select(expr("`(_1|_2)`"))
.select(expr("named_struct('a', _1, 'b', _2)").as[ClassData]),
ClassData("a", 1), ClassData("b", 2), ClassData("c", 3))
checkDataset(
ds.alias("g")
.select(expr("g.`(_1)?+.+`").as[Int]),
1, 2, 3)
checkDataset(
ds.alias("g")
.select(expr("g.`(_1|_2)`"))
.select(expr("named_struct('a', _1, 'b', _2)").as[ClassData]),
ClassData("a", 1), ClassData("b", 2), ClassData("c", 3))
}
}
test("filter") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.filter(_._1 == "b"),
("b", 2))
}
test("filter and then select") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
checkDataset(
ds.filter(_._1 == "b").select(expr("_1").as[String]),
"b")
}
test("SPARK-15632: typed filter should preserve the underlying logical schema") {
val ds = spark.range(10)
val ds2 = ds.filter(_ > 3)
assert(ds.schema.equals(ds2.schema))
}
test("foreach") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
val acc = sparkContext.longAccumulator
ds.foreach(v => acc.add(v._2))
assert(acc.value == 6)
}
test("foreachPartition") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
val acc = sparkContext.longAccumulator
ds.foreachPartition((it: Iterator[(String, Int)]) => it.foreach(v => acc.add(v._2)))
assert(acc.value == 6)
}
test("reduce") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
assert(ds.reduce((a, b) => ("sum", a._2 + b._2)) == (("sum", 6)))
}
test("joinWith, flat schema") {
val ds1 = Seq(1, 2, 3).toDS().as("a")
val ds2 = Seq(1, 2).toDS().as("b")
val joined = ds1.joinWith(ds2, $"a.value" === $"b.value", "inner")
val expectedSchema = StructType(Seq(
StructField("_1", IntegerType, nullable = false),
StructField("_2", IntegerType, nullable = false)
))
assert(joined.schema === expectedSchema)
checkDataset(
joined,
(1, 1), (2, 2))
}
test("joinWith tuple with primitive, expression") {
val ds1 = Seq(1, 1, 2).toDS()
val ds2 = Seq(("a", 1), ("b", 2)).toDS()
val joined = ds1.joinWith(ds2, $"value" === $"_2")
// This is an inner join, so both outputs fields are non-nullable
val expectedSchema = StructType(Seq(
StructField("_1", IntegerType, nullable = false),
StructField("_2",
StructType(Seq(
StructField("_1", StringType),
StructField("_2", IntegerType, nullable = false)
)), nullable = false)
))
assert(joined.schema === expectedSchema)
checkDataset(
joined,
(1, ("a", 1)), (1, ("a", 1)), (2, ("b", 2)))
}
test("joinWith class with primitive, toDF") {
val ds1 = Seq(1, 1, 2).toDS()
val ds2 = Seq(ClassData("a", 1), ClassData("b", 2)).toDS()
checkAnswer(
ds1.joinWith(ds2, $"value" === $"b").toDF().select($"_1", $"_2.a", $"_2.b"),
Row(1, "a", 1) :: Row(1, "a", 1) :: Row(2, "b", 2) :: Nil)
}
test("multi-level joinWith") {
val ds1 = Seq(("a", 1), ("b", 2)).toDS().as("a")
val ds2 = Seq(("a", 1), ("b", 2)).toDS().as("b")
val ds3 = Seq(("a", 1), ("b", 2)).toDS().as("c")
checkDataset(
ds1.joinWith(ds2, $"a._2" === $"b._2").as("ab").joinWith(ds3, $"ab._1._2" === $"c._2"),
((("a", 1), ("a", 1)), ("a", 1)),
((("b", 2), ("b", 2)), ("b", 2)))
}
test("joinWith join types") {
val ds1 = Seq(1, 2, 3).toDS().as("a")
val ds2 = Seq(1, 2).toDS().as("b")
val e1 = intercept[AnalysisException] {
ds1.joinWith(ds2, $"a.value" === $"b.value", "left_semi")
}.getMessage
assert(e1.contains("Invalid join type in joinWith: " + LeftSemi.sql))
val e2 = intercept[AnalysisException] {
ds1.joinWith(ds2, $"a.value" === $"b.value", "semi")
}.getMessage
assert(e2.contains("Invalid join type in joinWith: " + LeftSemi.sql))
val e3 = intercept[AnalysisException] {
ds1.joinWith(ds2, $"a.value" === $"b.value", "left_anti")
}.getMessage
assert(e3.contains("Invalid join type in joinWith: " + LeftAnti.sql))
val e4 = intercept[AnalysisException] {
ds1.joinWith(ds2, $"a.value" === $"b.value", "anti")
}.getMessage
assert(e4.contains("Invalid join type in joinWith: " + LeftAnti.sql))
}
test("groupBy function, keys") {
val ds = Seq(("a", 1), ("b", 1)).toDS()
val grouped = ds.groupByKey(v => (1, v._2))
checkDatasetUnorderly(
grouped.keys,
(1, 1))
}
test("groupBy function, map") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
val grouped = ds.groupByKey(v => (v._1, "word"))
val agged = grouped.mapGroups { (g, iter) => (g._1, iter.map(_._2).sum) }
checkDatasetUnorderly(
agged,
("a", 30), ("b", 3), ("c", 1))
}
test("groupBy function, flatMap") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
val grouped = ds.groupByKey(v => (v._1, "word"))
val agged = grouped.flatMapGroups { (g, iter) =>
Iterator(g._1, iter.map(_._2).sum.toString)
}
checkDatasetUnorderly(
agged,
"a", "30", "b", "3", "c", "1")
}
test("groupBy function, mapValues, flatMap") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
val keyValue = ds.groupByKey(_._1).mapValues(_._2)
val agged = keyValue.mapGroups { (g, iter) => (g, iter.sum) }
checkDataset(agged, ("a", 30), ("b", 3), ("c", 1))
val keyValue1 = ds.groupByKey(t => (t._1, "key")).mapValues(t => (t._2, "value"))
val agged1 = keyValue1.mapGroups { (g, iter) => (g._1, iter.map(_._1).sum) }
checkDataset(agged1, ("a", 30), ("b", 3), ("c", 1))
}
test("groupBy function, reduce") {
val ds = Seq("abc", "xyz", "hello").toDS()
val agged = ds.groupByKey(_.length).reduceGroups(_ + _)
checkDatasetUnorderly(
agged,
3 -> "abcxyz", 5 -> "hello")
}
test("groupBy single field class, count") {
val ds = Seq("abc", "xyz", "hello").toDS()
val count = ds.groupByKey(s => Tuple1(s.length)).count()
checkDataset(
count,
(Tuple1(3), 2L), (Tuple1(5), 1L)
)
}
test("typed aggregation: expr") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
checkDatasetUnorderly(
ds.groupByKey(_._1).agg(sum("_2").as[Long]),
("a", 30L), ("b", 3L), ("c", 1L))
}
test("typed aggregation: expr, expr") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
checkDatasetUnorderly(
ds.groupByKey(_._1).agg(sum("_2").as[Long], sum($"_2" + 1).as[Long]),
("a", 30L, 32L), ("b", 3L, 5L), ("c", 1L, 2L))
}
test("typed aggregation: expr, expr, expr") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
checkDatasetUnorderly(
ds.groupByKey(_._1).agg(sum("_2").as[Long], sum($"_2" + 1).as[Long], count("*")),
("a", 30L, 32L, 2L), ("b", 3L, 5L, 2L), ("c", 1L, 2L, 1L))
}
test("typed aggregation: expr, expr, expr, expr") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
checkDatasetUnorderly(
ds.groupByKey(_._1).agg(
sum("_2").as[Long],
sum($"_2" + 1).as[Long],
count("*").as[Long],
avg("_2").as[Double]),
("a", 30L, 32L, 2L, 15.0), ("b", 3L, 5L, 2L, 1.5), ("c", 1L, 2L, 1L, 1.0))
}
test("typed aggregation: expr, expr, expr, expr, expr") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
checkDatasetUnorderly(
ds.groupByKey(_._1).agg(
sum("_2").as[Long],
sum($"_2" + 1).as[Long],
count("*").as[Long],
avg("_2").as[Double],
countDistinct("*").as[Long]),
("a", 30L, 32L, 2L, 15.0, 2L), ("b", 3L, 5L, 2L, 1.5, 2L), ("c", 1L, 2L, 1L, 1.0, 1L))
}
test("typed aggregation: expr, expr, expr, expr, expr, expr") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
checkDatasetUnorderly(
ds.groupByKey(_._1).agg(
sum("_2").as[Long],
sum($"_2" + 1).as[Long],
count("*").as[Long],
avg("_2").as[Double],
countDistinct("*").as[Long],
max("_2").as[Long]),
("a", 30L, 32L, 2L, 15.0, 2L, 20L),
("b", 3L, 5L, 2L, 1.5, 2L, 2L),
("c", 1L, 2L, 1L, 1.0, 1L, 1L))
}
test("typed aggregation: expr, expr, expr, expr, expr, expr, expr") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
checkDatasetUnorderly(
ds.groupByKey(_._1).agg(
sum("_2").as[Long],
sum($"_2" + 1).as[Long],
count("*").as[Long],
avg("_2").as[Double],
countDistinct("*").as[Long],
max("_2").as[Long],
min("_2").as[Long]),
("a", 30L, 32L, 2L, 15.0, 2L, 20L, 10L),
("b", 3L, 5L, 2L, 1.5, 2L, 2L, 1L),
("c", 1L, 2L, 1L, 1.0, 1L, 1L, 1L))
}
test("typed aggregation: expr, expr, expr, expr, expr, expr, expr, expr") {
val ds = Seq(("a", 10), ("a", 20), ("b", 1), ("b", 2), ("c", 1)).toDS()
checkDatasetUnorderly(
ds.groupByKey(_._1).agg(
sum("_2").as[Long],
sum($"_2" + 1).as[Long],
count("*").as[Long],
avg("_2").as[Double],
countDistinct("*").as[Long],
max("_2").as[Long],
min("_2").as[Long],
mean("_2").as[Double]),
("a", 30L, 32L, 2L, 15.0, 2L, 20L, 10L, 15.0),
("b", 3L, 5L, 2L, 1.5, 2L, 2L, 1L, 1.5),
("c", 1L, 2L, 1L, 1.0, 1L, 1L, 1L, 1.0))
}
test("cogroup") {
val ds1 = Seq(1 -> "a", 3 -> "abc", 5 -> "hello", 3 -> "foo").toDS()
val ds2 = Seq(2 -> "q", 3 -> "w", 5 -> "e", 5 -> "r").toDS()
val cogrouped = ds1.groupByKey(_._1).cogroup(ds2.groupByKey(_._1)) { case (key, data1, data2) =>
Iterator(key -> (data1.map(_._2).mkString + "#" + data2.map(_._2).mkString))
}
checkDatasetUnorderly(
cogrouped,
1 -> "a#", 2 -> "#q", 3 -> "abcfoo#w", 5 -> "hello#er")
}
test("cogroup with complex data") {
val ds1 = Seq(1 -> ClassData("a", 1), 2 -> ClassData("b", 2)).toDS()
val ds2 = Seq(2 -> ClassData("c", 3), 3 -> ClassData("d", 4)).toDS()
val cogrouped = ds1.groupByKey(_._1).cogroup(ds2.groupByKey(_._1)) { case (key, data1, data2) =>
Iterator(key -> (data1.map(_._2.a).mkString + data2.map(_._2.a).mkString))
}
checkDatasetUnorderly(
cogrouped,
1 -> "a", 2 -> "bc", 3 -> "d")
}
test("sample with replacement") {
val n = 100
val data = sparkContext.parallelize(1 to n, 2).toDS()
checkDataset(
data.sample(withReplacement = true, 0.05, seed = 13),
5, 10, 52, 73)
}
test("sample without replacement") {
val n = 100
val data = sparkContext.parallelize(1 to n, 2).toDS()
checkDataset(
data.sample(withReplacement = false, 0.05, seed = 13),
8, 37, 90)
}
test("sample fraction should not be negative with replacement") {
val data = sparkContext.parallelize(1 to 2, 1).toDS()
val errMsg = intercept[IllegalArgumentException] {
data.sample(withReplacement = true, -0.1, 0)
}.getMessage
assert(errMsg.contains("Sampling fraction (-0.1) must be nonnegative with replacement"))
// Sampling fraction can be greater than 1 with replacement.
checkDataset(
data.sample(withReplacement = true, 1.05, seed = 13),
1, 2)
}
test("sample fraction should be on interval [0, 1] without replacement") {
val data = sparkContext.parallelize(1 to 2, 1).toDS()
val errMsg1 = intercept[IllegalArgumentException] {
data.sample(withReplacement = false, -0.1, 0)
}.getMessage()
assert(errMsg1.contains(
"Sampling fraction (-0.1) must be on interval [0, 1] without replacement"))
val errMsg2 = intercept[IllegalArgumentException] {
data.sample(withReplacement = false, 1.1, 0)
}.getMessage()
assert(errMsg2.contains(
"Sampling fraction (1.1) must be on interval [0, 1] without replacement"))
}
test("SPARK-16686: Dataset.sample with seed results shouldn't depend on downstream usage") {
val a = 7
val simpleUdf = udf((n: Int) => {
require(n != a, s"simpleUdf shouldn't see id=$a!")
a
})
val df = Seq(
(0, "string0"),
(1, "string1"),
(2, "string2"),
(3, "string3"),
(4, "string4"),
(5, "string5"),
(6, "string6"),
(7, "string7"),
(8, "string8"),
(9, "string9")
).toDF("id", "stringData")
val sampleDF = df.sample(false, 0.7, 50)
// After sampling, sampleDF doesn't contain id=a.
assert(!sampleDF.select("id").as[Int].collect.contains(a))
// simpleUdf should not encounter id=a.
checkAnswer(sampleDF.select(simpleUdf($"id")), List.fill(sampleDF.count.toInt)(Row(a)))
}
test("SPARK-11436: we should rebind right encoder when join 2 datasets") {
val ds1 = Seq("1", "2").toDS().as("a")
val ds2 = Seq(2, 3).toDS().as("b")
val joined = ds1.joinWith(ds2, $"a.value" === $"b.value")
checkDataset(joined, ("2", 2))
}
test("self join") {
val ds = Seq("1", "2").toDS().as("a")
val joined = ds.joinWith(ds, lit(true), "cross")
checkDataset(joined, ("1", "1"), ("1", "2"), ("2", "1"), ("2", "2"))
}
test("toString") {
val ds = Seq((1, 2)).toDS()
assert(ds.toString == "[_1: int, _2: int]")
}
test("Kryo encoder") {
implicit val kryoEncoder = Encoders.kryo[KryoData]
val ds = Seq(KryoData(1), KryoData(2)).toDS()
assert(ds.groupByKey(p => p).count().collect().toSet ==
Set((KryoData(1), 1L), (KryoData(2), 1L)))
}
test("Kryo encoder self join") {
implicit val kryoEncoder = Encoders.kryo[KryoData]
val ds = Seq(KryoData(1), KryoData(2)).toDS()
assert(ds.joinWith(ds, lit(true), "cross").collect().toSet ==
Set(
(KryoData(1), KryoData(1)),
(KryoData(1), KryoData(2)),
(KryoData(2), KryoData(1)),
(KryoData(2), KryoData(2))))
}
test("Kryo encoder: check the schema mismatch when converting DataFrame to Dataset") {
implicit val kryoEncoder = Encoders.kryo[KryoData]
val df = Seq((1.0)).toDF("a")
val e = intercept[AnalysisException] {
df.as[KryoData]
}.message
assert(e.contains("cannot cast double to binary"))
}
test("Java encoder") {
implicit val kryoEncoder = Encoders.javaSerialization[JavaData]
val ds = Seq(JavaData(1), JavaData(2)).toDS()
assert(ds.groupByKey(p => p).count().collect().toSet ==
Set((JavaData(1), 1L), (JavaData(2), 1L)))
}
test("Java encoder self join") {
implicit val kryoEncoder = Encoders.javaSerialization[JavaData]
val ds = Seq(JavaData(1), JavaData(2)).toDS()
assert(ds.joinWith(ds, lit(true), "cross").collect().toSet ==
Set(
(JavaData(1), JavaData(1)),
(JavaData(1), JavaData(2)),
(JavaData(2), JavaData(1)),
(JavaData(2), JavaData(2))))
}
test("SPARK-14696: implicit encoders for boxed types") {
assert(spark.range(1).map { i => i : java.lang.Long }.head == 0L)
}
test("SPARK-11894: Incorrect results are returned when using null") {
val nullInt = null.asInstanceOf[java.lang.Integer]
val ds1 = Seq((nullInt, "1"), (java.lang.Integer.valueOf(22), "2")).toDS()
val ds2 = Seq((nullInt, "1"), (java.lang.Integer.valueOf(22), "2")).toDS()
checkDataset(
ds1.joinWith(ds2, lit(true), "cross"),
((nullInt, "1"), (nullInt, "1")),
((nullInt, "1"), (java.lang.Integer.valueOf(22), "2")),
((java.lang.Integer.valueOf(22), "2"), (nullInt, "1")),
((java.lang.Integer.valueOf(22), "2"), (java.lang.Integer.valueOf(22), "2")))
}
test("change encoder with compatible schema") {
val ds = Seq(2 -> 2.toByte, 3 -> 3.toByte).toDF("a", "b").as[ClassData]
assert(ds.collect().toSeq == Seq(ClassData("2", 2), ClassData("3", 3)))
}
test("verify mismatching field names fail with a good error") {
val ds = Seq(ClassData("a", 1)).toDS()
val e = intercept[AnalysisException] {
ds.as[ClassData2]
}
assert(e.getMessage.contains("cannot resolve '`c`' given input columns: [a, b]"), e.getMessage)
}
test("runtime nullability check") {
val schema = StructType(Seq(
StructField("f", StructType(Seq(
StructField("a", StringType, nullable = true),
StructField("b", IntegerType, nullable = true)
)), nullable = true)
))
def buildDataset(rows: Row*): Dataset[NestedStruct] = {
val rowRDD = spark.sparkContext.parallelize(rows)
spark.createDataFrame(rowRDD, schema).as[NestedStruct]
}
checkDataset(
buildDataset(Row(Row("hello", 1))),
NestedStruct(ClassData("hello", 1))
)
// Shouldn't throw runtime exception when parent object (`ClassData`) is null
assert(buildDataset(Row(null)).collect() === Array(NestedStruct(null)))
val message = intercept[RuntimeException] {
buildDataset(Row(Row("hello", null))).collect()
}.getMessage
assert(message.contains("Null value appeared in non-nullable field"))
}
test("SPARK-12478: top level null field") {
val ds0 = Seq(NestedStruct(null)).toDS()
checkDataset(ds0, NestedStruct(null))
checkAnswer(ds0.toDF(), Row(null))
val ds1 = Seq(DeepNestedStruct(NestedStruct(null))).toDS()
checkDataset(ds1, DeepNestedStruct(NestedStruct(null)))
checkAnswer(ds1.toDF(), Row(Row(null)))
}
test("support inner class in Dataset") {
val outer = new OuterClass
OuterScopes.addOuterScope(outer)
val ds = Seq(outer.InnerClass("1"), outer.InnerClass("2")).toDS()
checkDataset(ds.map(_.a), "1", "2")
}
test("grouping key and grouped value has field with same name") {
val ds = Seq(ClassData("a", 1), ClassData("a", 2)).toDS()
val agged = ds.groupByKey(d => ClassNullableData(d.a, null)).mapGroups {
(key, values) => key.a + values.map(_.b).sum
}
checkDataset(agged, "a3")
}
test("cogroup's left and right side has field with same name") {
val left = Seq(ClassData("a", 1), ClassData("b", 2)).toDS()
val right = Seq(ClassNullableData("a", 3), ClassNullableData("b", 4)).toDS()
val cogrouped = left.groupByKey(_.a).cogroup(right.groupByKey(_.a)) {
case (key, lData, rData) => Iterator(key + lData.map(_.b).sum + rData.map(_.b.toInt).sum)
}
checkDataset(cogrouped, "a13", "b24")
}
test("give nice error message when the real number of fields doesn't match encoder schema") {
val ds = Seq(ClassData("a", 1), ClassData("b", 2)).toDS()
val message = intercept[AnalysisException] {
ds.as[(String, Int, Long)]
}.message
assert(message ==
"Try to map struct<a:string,b:int> to Tuple3, " +
"but failed as the number of fields does not line up.")
val message2 = intercept[AnalysisException] {
ds.as[Tuple1[String]]
}.message
assert(message2 ==
"Try to map struct<a:string,b:int> to Tuple1, " +
"but failed as the number of fields does not line up.")
}
test("SPARK-13440: Resolving option fields") {
val df = Seq(1, 2, 3).toDS()
val ds = df.as[Option[Int]]
checkDataset(
ds.filter(_ => true),
Some(1), Some(2), Some(3))
}
test("SPARK-13540 Dataset of nested class defined in Scala object") {
checkDataset(
Seq(OuterObject.InnerClass("foo")).toDS(),
OuterObject.InnerClass("foo"))
}
test("SPARK-14000: case class with tuple type field") {
checkDataset(
Seq(TupleClass((1, "a"))).toDS(),
TupleClass((1, "a"))
)
}
test("isStreaming returns false for static Dataset") {
val data = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
assert(!data.isStreaming, "static Dataset returned true for 'isStreaming'.")
}
test("isStreaming returns true for streaming Dataset") {
val data = MemoryStream[Int].toDS()
assert(data.isStreaming, "streaming Dataset returned false for 'isStreaming'.")
}
test("isStreaming returns true after static and streaming Dataset join") {
val static = Seq(("a", 1), ("b", 2), ("c", 3)).toDF("a", "b")
val streaming = MemoryStream[Int].toDS().toDF("b")
val df = streaming.join(static, Seq("b"))
assert(df.isStreaming, "streaming Dataset returned false for 'isStreaming'.")
}
test("SPARK-14554: Dataset.map may generate wrong java code for wide table") {
val wideDF = spark.range(10).select(Seq.tabulate(1000) {i => ($"id" + i).as(s"c$i")} : _*)
// Make sure the generated code for this plan can compile and execute.
checkDataset(wideDF.map(_.getLong(0)), 0L until 10 : _*)
}
test("SPARK-14838: estimating sizeInBytes in operators with ObjectProducer shouldn't fail") {
val dataset = Seq(
(0, 3, 54f),
(0, 4, 44f),
(0, 5, 42f),
(1, 3, 39f),
(1, 5, 33f),
(1, 4, 26f),
(2, 3, 51f),
(2, 5, 45f),
(2, 4, 30f)
).toDF("user", "item", "rating")
val actual = dataset
.select("user", "item")
.as[(Int, Int)]
.groupByKey(_._1)
.mapGroups { (src, ids) => (src, ids.map(_._2).toArray) }
.toDF("id", "actual")
dataset.join(actual, dataset("user") === actual("id")).collect()
}
test("SPARK-15097: implicits on dataset's spark can be imported") {
val dataset = Seq(1, 2, 3).toDS()
checkDataset(DatasetTransform.addOne(dataset), 2, 3, 4)
}
test("dataset.rdd with generic case class") {
val ds = Seq(Generic(1, 1.0), Generic(2, 2.0)).toDS()
val ds2 = ds.map(g => Generic(g.id, g.value))
assert(ds.rdd.map(r => r.id).count === 2)
assert(ds2.rdd.map(r => r.id).count === 2)
val ds3 = ds.map(g => java.lang.Long.valueOf(g.id))
assert(ds3.rdd.map(r => r).count === 2)
}
test("runtime null check for RowEncoder") {
val schema = new StructType().add("i", IntegerType, nullable = false)
val df = spark.range(10).map(l => {
if (l % 5 == 0) {
Row(null)
} else {
Row(l)
}
})(RowEncoder(schema))
val message = intercept[Exception] {
df.collect()
}.getMessage
assert(message.contains("The 0th field 'i' of input row cannot be null"))
}
test("row nullability mismatch") {
val schema = new StructType().add("a", StringType, true).add("b", StringType, false)
val rdd = spark.sparkContext.parallelize(Row(null, "123") :: Row("234", null) :: Nil)
val message = intercept[Exception] {
spark.createDataFrame(rdd, schema).collect()
}.getMessage
assert(message.contains("The 1th field 'b' of input row cannot be null"))
}
test("createTempView") {
val dataset = Seq(1, 2, 3).toDS()
dataset.createOrReplaceTempView("tempView")
// Overrides the existing temporary view with same name
// No exception should be thrown here.
dataset.createOrReplaceTempView("tempView")
// Throws AnalysisException if temp view with same name already exists
val e = intercept[AnalysisException](
dataset.createTempView("tempView"))
intercept[AnalysisException](dataset.createTempView("tempView"))
assert(e.message.contains("already exists"))
dataset.sparkSession.catalog.dropTempView("tempView")
}
test("SPARK-15381: physical object operator should define `reference` correctly") {
val df = Seq(1 -> 2).toDF("a", "b")
checkAnswer(df.map(row => row)(RowEncoder(df.schema)).select("b", "a"), Row(2, 1))
}
private def checkShowString[T](ds: Dataset[T], expected: String): Unit = {
val numRows = expected.split("\\n").length - 4
val actual = ds.showString(numRows, truncate = 20)
if (expected != actual) {
fail(
"Dataset.showString() gives wrong result:\\n\\n" + sideBySide(
"== Expected ==\\n" + expected,
"== Actual ==\\n" + actual
).mkString("\\n")
)
}
}
test("SPARK-15550 Dataset.show() should show contents of the underlying logical plan") {
val df = Seq((1, "foo", "extra"), (2, "bar", "extra")).toDF("b", "a", "c")
val ds = df.as[ClassData]
val expected =
"""+---+---+-----+
|| b| a| c|
|+---+---+-----+
|| 1|foo|extra|
|| 2|bar|extra|
|+---+---+-----+
|""".stripMargin
checkShowString(ds, expected)
}
test("SPARK-15550 Dataset.show() should show inner nested products as rows") {
val ds = Seq(
NestedStruct(ClassData("foo", 1)),
NestedStruct(ClassData("bar", 2))
).toDS()
val expected =
"""+--------+
|| f|
|+--------+
||{foo, 1}|
||{bar, 2}|
|+--------+
|""".stripMargin
checkShowString(ds, expected)
}
test("SPARK-25108 Fix the show method to display the full width character alignment problem") {
// scalastyle:off nonascii
val df = Seq(
(0, null, 1),
(0, "", 1),
(0, "ab c", 1),
(0, "1098", 1),
(0, "mø", 1),
(0, "γύρ", 1),
(0, "pê", 1),
(0, "ー", 1),
(0, "测", 1),
(0, "か", 1),
(0, "걸", 1),
(0, "à", 1),
(0, "焼", 1),
(0, "羍む", 1),
(0, "뺭ᾘ", 1),
(0, "\\u0967\\u0968\\u0969", 1)
).toDF("b", "a", "c")
// scalastyle:on nonascii
val ds = df.as[ClassData]
val expected =
// scalastyle:off nonascii
"""+---+----+---+
|| b| a| c|
|+---+----+---+
|| 0|null| 1|
|| 0| | 1|
|| 0|ab c| 1|
|| 0|1098| 1|
|| 0| mø| 1|
|| 0| γύρ| 1|
|| 0| pê| 1|
|| 0| ー| 1|
|| 0| 测| 1|
|| 0| か| 1|
|| 0| 걸| 1|
|| 0| à| 1|
|| 0| 焼| 1|
|| 0|羍む| 1|
|| 0| 뺭ᾘ| 1|
|| 0| १२३| 1|
|+---+----+---+
|""".stripMargin
// scalastyle:on nonascii
checkShowString(ds, expected)
}
test(
"SPARK-15112: EmbedDeserializerInFilter should not optimize plan fragment that changes schema"
) {
val ds = Seq(1 -> "foo", 2 -> "bar").toDF("b", "a").as[ClassData]
assertResult(Seq(ClassData("foo", 1), ClassData("bar", 2))) {
ds.collect().toSeq
}
assertResult(Seq(ClassData("bar", 2))) {
ds.filter(_.b > 1).collect().toSeq
}
}
test("mapped dataset should resolve duplicated attributes for self join") {
val ds = Seq(1, 2, 3).toDS().map(_ + 1)
val ds1 = ds.as("d1")
val ds2 = ds.as("d2")
checkDatasetUnorderly(ds1.joinWith(ds2, $"d1.value" === $"d2.value"), (2, 2), (3, 3), (4, 4))
checkDatasetUnorderly(ds1.intersect(ds2), 2, 3, 4)
checkDatasetUnorderly(ds1.except(ds1))
}
test("SPARK-15441: Dataset outer join") {
val left = Seq(ClassData("a", 1), ClassData("b", 2)).toDS().as("left")
val right = Seq(ClassData("x", 2), ClassData("y", 3)).toDS().as("right")
val joined = left.joinWith(right, $"left.b" === $"right.b", "left")
val expectedSchema = StructType(Seq(
StructField("_1",
StructType(Seq(
StructField("a", StringType),
StructField("b", IntegerType, nullable = false)
)),
nullable = false),
// This is a left join, so the right output is nullable:
StructField("_2",
StructType(Seq(
StructField("a", StringType),
StructField("b", IntegerType, nullable = false)
)))
))
assert(joined.schema === expectedSchema)
val result = joined.collect().toSet
assert(result == Set(ClassData("a", 1) -> null, ClassData("b", 2) -> ClassData("x", 2)))
}
test("Dataset should support flat input object to be null") {
checkDataset(Seq("a", null).toDS(), "a", null)
}
test("Dataset should throw RuntimeException if top-level product input object is null") {
val e = intercept[RuntimeException](Seq(ClassData("a", 1), null).toDS())
assert(e.getMessage.contains("Null value appeared in non-nullable field"))
assert(e.getMessage.contains("top level Product or row object"))
}
test("dropDuplicates") {
val ds = Seq(("a", 1), ("a", 2), ("b", 1), ("a", 1)).toDS()
checkDataset(
ds.dropDuplicates("_1"),
("a", 1), ("b", 1))
checkDataset(
ds.dropDuplicates("_2"),
("a", 1), ("a", 2))
checkDataset(
ds.dropDuplicates("_1", "_2"),
("a", 1), ("a", 2), ("b", 1))
}
test("dropDuplicates: columns with same column name") {
val ds1 = Seq(("a", 1), ("a", 2), ("b", 1), ("a", 1)).toDS()
val ds2 = Seq(("a", 1), ("a", 2), ("b", 1), ("a", 1)).toDS()
// The dataset joined has two columns of the same name "_2".
val joined = ds1.join(ds2, "_1").select(ds1("_2").as[Int], ds2("_2").as[Int])
checkDataset(
joined.dropDuplicates(),
(1, 2), (1, 1), (2, 1), (2, 2))
}
test("SPARK-16097: Encoders.tuple should handle null object correctly") {
val enc = Encoders.tuple(Encoders.tuple(Encoders.STRING, Encoders.STRING), Encoders.STRING)
val data = Seq((("a", "b"), "c"), (null, "d"))
val ds = spark.createDataset(data)(enc)
checkDataset(ds, (("a", "b"), "c"), (null, "d"))
}
test("SPARK-16995: flat mapping on Dataset containing a column created with lit/expr") {
val df = Seq("1").toDF("a")
import df.sparkSession.implicits._
checkDataset(
df.withColumn("b", lit(0)).as[ClassData]
.groupByKey(_.a).flatMapGroups { (_, _) => List[Int]() })
checkDataset(
df.withColumn("b", expr("0")).as[ClassData]
.groupByKey(_.a).flatMapGroups { (_, _) => List[Int]() })
}
test("SPARK-18125: Spark generated code causes CompileException") {
val data = Array(
Route("a", "b", 1),
Route("a", "b", 2),
Route("a", "c", 2),
Route("a", "d", 10),
Route("b", "a", 1),
Route("b", "a", 5),
Route("b", "c", 6))
val ds = sparkContext.parallelize(data).toDF.as[Route]
val grped = ds.map(r => GroupedRoutes(r.src, r.dest, Seq(r)))
.groupByKey(r => (r.src, r.dest))
.reduceGroups { (g1: GroupedRoutes, g2: GroupedRoutes) =>
GroupedRoutes(g1.src, g1.dest, g1.routes ++ g2.routes)
}.map(_._2)
val expected = Seq(
GroupedRoutes("a", "d", Seq(Route("a", "d", 10))),
GroupedRoutes("b", "c", Seq(Route("b", "c", 6))),
GroupedRoutes("a", "b", Seq(Route("a", "b", 1), Route("a", "b", 2))),
GroupedRoutes("b", "a", Seq(Route("b", "a", 1), Route("b", "a", 5))),
GroupedRoutes("a", "c", Seq(Route("a", "c", 2)))
)
implicit def ordering[GroupedRoutes]: Ordering[GroupedRoutes] =
(x: GroupedRoutes, y: GroupedRoutes) => x.toString.compareTo(y.toString)
checkDatasetUnorderly(grped, expected: _*)
}
test("SPARK-18189: Fix serialization issue in KeyValueGroupedDataset") {
val resultValue = 12345
val keyValueGrouped = Seq((1, 2), (3, 4)).toDS().groupByKey(_._1)
val mapGroups = keyValueGrouped.mapGroups((k, v) => (k, 1))
val broadcasted = spark.sparkContext.broadcast(resultValue)
// Using broadcast triggers serialization issue in KeyValueGroupedDataset
val dataset = mapGroups.map(_ => broadcasted.value)
assert(dataset.collect() sameElements Array(resultValue, resultValue))
}
test("SPARK-18284: Serializer should have correct nullable value") {
val df1 = Seq(1, 2, 3, 4).toDF
assert(df1.schema(0).nullable == false)
val df2 = Seq(Integer.valueOf(1), Integer.valueOf(2)).toDF
assert(df2.schema(0).nullable)
val df3 = Seq(Seq(1, 2), Seq(3, 4)).toDF
assert(df3.schema(0).nullable)
assert(df3.schema(0).dataType.asInstanceOf[ArrayType].containsNull == false)
val df4 = Seq(Seq("a", "b"), Seq("c", "d")).toDF
assert(df4.schema(0).nullable)
assert(df4.schema(0).dataType.asInstanceOf[ArrayType].containsNull)
val df5 = Seq((0, 1.0), (2, 2.0)).toDF("id", "v")
assert(df5.schema(0).nullable == false)
assert(df5.schema(1).nullable == false)
val df6 = Seq((0, 1.0, "a"), (2, 2.0, "b")).toDF("id", "v1", "v2")
assert(df6.schema(0).nullable == false)
assert(df6.schema(1).nullable == false)
assert(df6.schema(2).nullable)
val df7 = (Tuple1(Array(1, 2, 3)) :: Nil).toDF("a")
assert(df7.schema(0).nullable)
assert(df7.schema(0).dataType.asInstanceOf[ArrayType].containsNull == false)
val df8 = (Tuple1(Array((null: Integer), (null: Integer))) :: Nil).toDF("a")
assert(df8.schema(0).nullable)
assert(df8.schema(0).dataType.asInstanceOf[ArrayType].containsNull)
val df9 = (Tuple1(Map(2 -> 3)) :: Nil).toDF("m")
assert(df9.schema(0).nullable)
assert(df9.schema(0).dataType.asInstanceOf[MapType].valueContainsNull == false)
val df10 = (Tuple1(Map(1 -> (null: Integer))) :: Nil).toDF("m")
assert(df10.schema(0).nullable)
assert(df10.schema(0).dataType.asInstanceOf[MapType].valueContainsNull)
val df11 = Seq(TestDataPoint(1, 2.2, "a", null),
TestDataPoint(3, 4.4, "null", (TestDataPoint2(33, "b")))).toDF
assert(df11.schema(0).nullable == false)
assert(df11.schema(1).nullable == false)
assert(df11.schema(2).nullable)
assert(df11.schema(3).nullable)
assert(df11.schema(3).dataType.asInstanceOf[StructType].fields(0).nullable == false)
assert(df11.schema(3).dataType.asInstanceOf[StructType].fields(1).nullable)
}
Seq(true, false).foreach { eager =>
Seq(true, false).foreach { reliable =>
def testCheckpointing(testName: String)(f: => Unit): Unit = {
test(s"Dataset.checkpoint() - $testName (eager = $eager, reliable = $reliable)") {
if (reliable) {
withTempDir { dir =>
val originalCheckpointDir = spark.sparkContext.checkpointDir
try {
spark.sparkContext.setCheckpointDir(dir.getCanonicalPath)
f
} finally {
// Since the original checkpointDir can be None, we need
// to set the variable directly.
spark.sparkContext.checkpointDir = originalCheckpointDir
}
}
} else {
// Local checkpoints dont require checkpoint_dir
f
}
}
}
testCheckpointing("basic") {
val ds = spark.range(10).repartition($"id" % 2).filter($"id" > 5).orderBy($"id".desc)
val cp = if (reliable) ds.checkpoint(eager) else ds.localCheckpoint(eager)
val logicalRDD = cp.logicalPlan match {
case plan: LogicalRDD => plan
case _ =>
val treeString = cp.logicalPlan.treeString(verbose = true)
fail(s"Expecting a LogicalRDD, but got\\n$treeString")
}
val dsPhysicalPlan = ds.queryExecution.executedPlan
val cpPhysicalPlan = cp.queryExecution.executedPlan
assertResult(dsPhysicalPlan.outputPartitioning) {
logicalRDD.outputPartitioning
}
assertResult(dsPhysicalPlan.outputOrdering) {
logicalRDD.outputOrdering
}
assertResult(dsPhysicalPlan.outputPartitioning) {
cpPhysicalPlan.outputPartitioning
}
assertResult(dsPhysicalPlan.outputOrdering) {
cpPhysicalPlan.outputOrdering
}
// For a lazy checkpoint() call, the first check also materializes the checkpoint.
checkDataset(cp, (9L to 6L by -1L).map(java.lang.Long.valueOf): _*)
// Reads back from checkpointed data and check again.
checkDataset(cp, (9L to 6L by -1L).map(java.lang.Long.valueOf): _*)
}
testCheckpointing("should preserve partitioning information") {
val ds = spark.range(10).repartition($"id" % 2)
val cp = if (reliable) ds.checkpoint(eager) else ds.localCheckpoint(eager)
val agg = cp.groupBy($"id" % 2).agg(count($"id"))
agg.queryExecution.executedPlan.collectFirst {
case ShuffleExchangeExec(_, _: RDDScanExec, _) =>
case BroadcastExchangeExec(_, _: RDDScanExec) =>
}.foreach { _ =>
fail(
"No Exchange should be inserted above RDDScanExec since the checkpointed Dataset " +
"preserves partitioning information:\\n\\n" + agg.queryExecution
)
}
checkAnswer(agg, ds.groupBy($"id" % 2).agg(count($"id")))
}
}
}
test("identity map for primitive arrays") {
val arrayByte = Array(1.toByte, 2.toByte, 3.toByte)
val arrayInt = Array(1, 2, 3)
val arrayLong = Array(1.toLong, 2.toLong, 3.toLong)
val arrayDouble = Array(1.1, 2.2, 3.3)
val arrayString = Array("a", "b", "c")
val dsByte = sparkContext.parallelize(Seq(arrayByte), 1).toDS.map(e => e)
val dsInt = sparkContext.parallelize(Seq(arrayInt), 1).toDS.map(e => e)
val dsLong = sparkContext.parallelize(Seq(arrayLong), 1).toDS.map(e => e)
val dsDouble = sparkContext.parallelize(Seq(arrayDouble), 1).toDS.map(e => e)
val dsString = sparkContext.parallelize(Seq(arrayString), 1).toDS.map(e => e)
checkDataset(dsByte, arrayByte)
checkDataset(dsInt, arrayInt)
checkDataset(dsLong, arrayLong)
checkDataset(dsDouble, arrayDouble)
checkDataset(dsString, arrayString)
}
test ("SPARK-17460: the sizeInBytes in Statistics shouldn't overflow to a negative number") {
// Since the sizeInBytes in Statistics could exceed the limit of an Int, we should use BigInt
// instead of Int for avoiding possible overflow.
val ds = (0 to 10000).map( i =>
(i, Seq((i, Seq((i, "This is really not that long of a string")))))).toDS()
val sizeInBytes = ds.logicalPlan.stats.sizeInBytes
// sizeInBytes is 2404280404, before the fix, it overflows to a negative number
assert(sizeInBytes > 0)
}
test("SPARK-18717: code generation works for both scala.collection.Map" +
" and scala.collection.imutable.Map") {
val ds = Seq(WithImmutableMap("hi", Map(42L -> "foo"))).toDS
checkDataset(ds.map(t => t), WithImmutableMap("hi", Map(42L -> "foo")))
val ds2 = Seq(WithMap("hi", Map(42L -> "foo"))).toDS
checkDataset(ds2.map(t => t), WithMap("hi", Map(42L -> "foo")))
}
test("SPARK-18746: add implicit encoder for BigDecimal, date, timestamp") {
// For this implicit encoder, 18 is the default scale
assert(spark.range(1).map { x => new java.math.BigDecimal(1) }.head ==
new java.math.BigDecimal(1).setScale(18))
assert(spark.range(1).map { x => scala.math.BigDecimal(1, 18) }.head ==
scala.math.BigDecimal(1, 18))
assert(spark.range(1).map { x => java.sql.Date.valueOf("2016-12-12") }.head ==
java.sql.Date.valueOf("2016-12-12"))
assert(spark.range(1).map { x => new java.sql.Timestamp(100000) }.head ==
new java.sql.Timestamp(100000))
}
test("SPARK-19896: cannot have circular references in case class") {
val errMsg1 = intercept[UnsupportedOperationException] {
Seq(CircularReferenceClassA(null)).toDS
}
assert(errMsg1.getMessage.startsWith("cannot have circular references in class, but got the " +
"circular reference of class"))
val errMsg2 = intercept[UnsupportedOperationException] {
Seq(CircularReferenceClassC(null)).toDS
}
assert(errMsg2.getMessage.startsWith("cannot have circular references in class, but got the " +
"circular reference of class"))
val errMsg3 = intercept[UnsupportedOperationException] {
Seq(CircularReferenceClassD(null)).toDS
}
assert(errMsg3.getMessage.startsWith("cannot have circular references in class, but got the " +
"circular reference of class"))
}
test("SPARK-20125: option of map") {
val ds = Seq(WithMapInOption(Some(Map(1 -> 1)))).toDS()
checkDataset(ds, WithMapInOption(Some(Map(1 -> 1))))
}
test("SPARK-20399: do not unescaped regex pattern when ESCAPED_STRING_LITERALS is enabled") {
withSQLConf(SQLConf.ESCAPED_STRING_LITERALS.key -> "true") {
val data = Seq("\\u0020\\u0021\\u0023", "abc")
val df = data.toDF()
val rlike1 = df.filter("value rlike '^\\\\x20[\\\\x20-\\\\x23]+$'")
val rlike2 = df.filter($"value".rlike("^\\\\x20[\\\\x20-\\\\x23]+$"))
val rlike3 = df.filter("value rlike '^\\\\\\\\x20[\\\\\\\\x20-\\\\\\\\x23]+$'")
checkAnswer(rlike1, rlike2)
assert(rlike3.count() == 0)
}
}
test("SPARK-21538: Attribute resolution inconsistency in Dataset API") {
val df = spark.range(3).withColumnRenamed("id", "x")
val expected = Row(0) :: Row(1) :: Row (2) :: Nil
checkAnswer(df.sort("id"), expected)
checkAnswer(df.sort(col("id")), expected)
checkAnswer(df.sort($"id"), expected)
checkAnswer(df.orderBy("id"), expected)
checkAnswer(df.orderBy(col("id")), expected)
checkAnswer(df.orderBy($"id"), expected)
}
test("SPARK-21567: Dataset should work with type alias") {
checkDataset(
Seq(1).toDS().map(_ => ("", TestForTypeAlias.tupleTypeAlias)),
("", (1, 1)))
checkDataset(
Seq(1).toDS().map(_ => ("", TestForTypeAlias.nestedTupleTypeAlias)),
("", ((1, 1), 2)))
checkDataset(
Seq(1).toDS().map(_ => ("", TestForTypeAlias.seqOfTupleTypeAlias)),
("", Seq((1, 1), (2, 2))))
}
test("Check RelationalGroupedDataset toString: Single data") {
val kvDataset = (1 to 3).toDF("id").groupBy("id")
val expected = "RelationalGroupedDataset: [" +
"grouping expressions: [id: int], value: [id: int], type: GroupBy]"
val actual = kvDataset.toString
assert(expected === actual)
}
test("Check RelationalGroupedDataset toString: over length schema ") {
val kvDataset = (1 to 3).map( x => (x, x.toString, x.toLong))
.toDF("id", "val1", "val2").groupBy("id")
val expected = "RelationalGroupedDataset:" +
" [grouping expressions: [id: int]," +
" value: [id: int, val1: string ... 1 more field]," +
" type: GroupBy]"
val actual = kvDataset.toString
assert(expected === actual)
}
test("Check KeyValueGroupedDataset toString: Single data") {
val kvDataset = (1 to 3).toDF("id").as[SingleData].groupByKey(identity)
val expected = "KeyValueGroupedDataset: [key: [id: int], value: [id: int]]"
val actual = kvDataset.toString
assert(expected === actual)
}
test("Check KeyValueGroupedDataset toString: Unnamed KV-pair") {
val kvDataset = (1 to 3).map(x => (x, x.toString))
.toDF("id", "val1").as[DoubleData].groupByKey(x => (x.id, x.val1))
val expected = "KeyValueGroupedDataset:" +
" [key: [_1: int, _2: string]," +
" value: [id: int, val1: string]]"
val actual = kvDataset.toString
assert(expected === actual)
}
test("Check KeyValueGroupedDataset toString: Named KV-pair") {
val kvDataset = (1 to 3).map( x => (x, x.toString))
.toDF("id", "val1").as[DoubleData].groupByKey(x => DoubleData(x.id, x.val1))
val expected = "KeyValueGroupedDataset:" +
" [key: [id: int, val1: string]," +
" value: [id: int, val1: string]]"
val actual = kvDataset.toString
assert(expected === actual)
}
test("Check KeyValueGroupedDataset toString: over length schema ") {
val kvDataset = (1 to 3).map( x => (x, x.toString, x.toLong))
.toDF("id", "val1", "val2").as[TripleData].groupByKey(identity)
val expected = "KeyValueGroupedDataset:" +
" [key: [id: int, val1: string ... 1 more field(s)]," +
" value: [id: int, val1: string ... 1 more field(s)]]"
val actual = kvDataset.toString
assert(expected === actual)
}
test("SPARK-22442: Generate correct field names for special characters") {
withTempPath { dir =>
val path = dir.getCanonicalPath
val data = """{"field.1": 1, "field 2": 2}"""
Seq(data).toDF().repartition(1).write.text(path)
val ds = spark.read.json(path).as[SpecialCharClass]
checkDataset(ds, SpecialCharClass("1", "2"))
}
}
test("SPARK-23627: provide isEmpty in DataSet") {
val ds1 = spark.emptyDataset[Int]
val ds2 = Seq(1, 2, 3).toDS()
assert(ds1.isEmpty)
assert(ds2.isEmpty == false)
}
test("SPARK-22472: add null check for top-level primitive values") {
// If the primitive values are from Option, we need to do runtime null check.
val ds = Seq(Some(1), None).toDS().as[Int]
val e1 = intercept[RuntimeException](ds.collect())
assert(e1.getCause.isInstanceOf[NullPointerException])
val e2 = intercept[SparkException](ds.map(_ * 2).collect())
assert(e2.getCause.isInstanceOf[NullPointerException])
withTempPath { path =>
Seq(Integer.valueOf(1), null).toDF("i").write.parquet(path.getCanonicalPath)
// If the primitive values are from files, we need to do runtime null check.
val ds = spark.read.parquet(path.getCanonicalPath).as[Int]
val e1 = intercept[RuntimeException](ds.collect())
assert(e1.getCause.isInstanceOf[NullPointerException])
val e2 = intercept[SparkException](ds.map(_ * 2).collect())
assert(e2.getCause.isInstanceOf[NullPointerException])
}
}
test("SPARK-23025: Add support for null type in scala reflection") {
val data = Seq(("a", null))
checkDataset(data.toDS(), data: _*)
}
test("SPARK-23614: Union produces incorrect results when caching is used") {
val cached = spark.createDataset(Seq(TestDataUnion(1, 2, 3), TestDataUnion(4, 5, 6))).cache()
val group1 = cached.groupBy("x").agg(min(col("y")) as "value")
val group2 = cached.groupBy("x").agg(min(col("z")) as "value")
checkAnswer(group1.union(group2), Row(4, 5) :: Row(1, 2) :: Row(4, 6) :: Row(1, 3) :: Nil)
}
test("SPARK-23835: null primitive data type should throw NullPointerException") {
val ds = Seq[(Option[Int], Option[Int])]((Some(1), None)).toDS()
val e = intercept[RuntimeException](ds.as[(Int, Int)].collect())
assert(e.getCause.isInstanceOf[NullPointerException])
}
test("SPARK-24569: Option of primitive types are mistakenly mapped to struct type") {
withSQLConf(SQLConf.CROSS_JOINS_ENABLED.key -> "true") {
val a = Seq(Some(1)).toDS
val b = Seq(Some(1.2)).toDS
val expected = Seq((Some(1), Some(1.2))).toDS
val joined = a.joinWith(b, lit(true))
assert(joined.schema == expected.schema)
checkDataset(joined, expected.collect: _*)
}
}
test("SPARK-24548: Dataset with tuple encoders should have correct schema") {
val encoder = Encoders.tuple(newStringEncoder,
Encoders.tuple(newStringEncoder, newStringEncoder))
val data = Seq(("a", ("1", "2")), ("b", ("3", "4")))
val rdd = sparkContext.parallelize(data)
val ds1 = spark.createDataset(rdd)
val ds2 = spark.createDataset(rdd)(encoder)
assert(ds1.schema == ds2.schema)
checkDataset(ds1.select("_2._2"), ds2.select("_2._2").collect(): _*)
}
test("SPARK-24571: filtering of string values by char literal") {
val df = Seq("Amsterdam", "San Francisco", "X").toDF("city")
checkAnswer(df.where($"city" === 'X'), Seq(Row("X")))
checkAnswer(
df.where($"city".contains(java.lang.Character.valueOf('A'))),
Seq(Row("Amsterdam")))
}
test("SPARK-24762: Enable top-level Option of Product encoders") {
val data = Seq(Some((1, "a")), Some((2, "b")), None)
val ds = data.toDS()
checkDataset(
ds,
data: _*)
val schema = new StructType().add(
"value",
new StructType()
.add("_1", IntegerType, nullable = false)
.add("_2", StringType, nullable = true),
nullable = true)
assert(ds.schema == schema)
val nestedOptData = Seq(Some((Some((1, "a")), 2.0)), Some((Some((2, "b")), 3.0)))
val nestedDs = nestedOptData.toDS()
checkDataset(
nestedDs,
nestedOptData: _*)
val nestedSchema = StructType(Seq(
StructField("value", StructType(Seq(
StructField("_1", StructType(Seq(
StructField("_1", IntegerType, nullable = false),
StructField("_2", StringType, nullable = true)))),
StructField("_2", DoubleType, nullable = false)
)), nullable = true)
))
assert(nestedDs.schema == nestedSchema)
}
test("SPARK-24762: Resolving Option[Product] field") {
val ds = Seq((1, ("a", 1.0)), (2, ("b", 2.0)), (3, null)).toDS()
.as[(Int, Option[(String, Double)])]
checkDataset(ds,
(1, Some(("a", 1.0))), (2, Some(("b", 2.0))), (3, None))
}
test("SPARK-24762: select Option[Product] field") {
val ds = Seq(("a", 1), ("b", 2), ("c", 3)).toDS()
val ds1 = ds.select(expr("struct(_2, _2 + 1)").as[Option[(Int, Int)]])
checkDataset(ds1,
Some((1, 2)), Some((2, 3)), Some((3, 4)))
val ds2 = ds.select(expr("if(_2 > 2, struct(_2, _2 + 1), null)").as[Option[(Int, Int)]])
checkDataset(ds2,
None, None, Some((3, 4)))
}
test("SPARK-24762: joinWith on Option[Product]") {
val ds1 = Seq(Some((1, 2)), Some((2, 3)), None).toDS().as("a")
val ds2 = Seq(Some((1, 2)), Some((2, 3)), None).toDS().as("b")
val joined = ds1.joinWith(ds2, $"a.value._1" === $"b.value._2", "inner")
checkDataset(joined, (Some((2, 3)), Some((1, 2))))
}
test("SPARK-24762: typed agg on Option[Product] type") {
val ds = Seq(Some((1, 2)), Some((2, 3)), Some((1, 3))).toDS()
assert(ds.groupByKey(_.get._1).count().collect() === Seq((1, 2), (2, 1)))
assert(ds.groupByKey(x => x).count().collect() ===
Seq((Some((1, 2)), 1), (Some((2, 3)), 1), (Some((1, 3)), 1)))
}
test("SPARK-25942: typed aggregation on primitive type") {
val ds = Seq(1, 2, 3).toDS()
val agg = ds.groupByKey(_ >= 2)
.agg(sum("value").as[Long], sum($"value" + 1).as[Long])
checkDatasetUnorderly(agg, (false, 1L, 2L), (true, 5L, 7L))
}
test("SPARK-25942: typed aggregation on product type") {
val ds = Seq((1, 2), (2, 3), (3, 4)).toDS()
val agg = ds.groupByKey(x => x).agg(sum("_1").as[Long], sum($"_2" + 1).as[Long])
checkDatasetUnorderly(agg, ((1, 2), 1L, 3L), ((2, 3), 2L, 4L), ((3, 4), 3L, 5L))
}
test("SPARK-26085: fix key attribute name for atomic type for typed aggregation") {
val ds = Seq(1, 2, 3).toDS()
assert(ds.groupByKey(x => x).count().schema.head.name == "key")
// Enable legacy flag to follow previous Spark behavior
withSQLConf(SQLConf.NAME_NON_STRUCT_GROUPING_KEY_AS_VALUE.key -> "true") {
assert(ds.groupByKey(x => x).count().schema.head.name == "value")
}
}
test("SPARK-8288: class with only a companion object constructor") {
val data = Seq(ScroogeLikeExample(1), ScroogeLikeExample(2))
val ds = data.toDS
checkDataset(ds, data: _*)
checkAnswer(ds.select("x"), Seq(Row(1), Row(2)))
}
test("SPARK-26233: serializer should enforce decimal precision and scale") {
val s = StructType(Seq(StructField("a", StringType), StructField("b", DecimalType(38, 8))))
val encoder = RowEncoder(s)
implicit val uEnc = encoder
val df = spark.range(2).map(l => Row(l.toString, BigDecimal.valueOf(l + 0.1111)))
checkAnswer(df.groupBy(col("a")).agg(first(col("b"))),
Seq(Row("0", BigDecimal.valueOf(0.1111)), Row("1", BigDecimal.valueOf(1.1111))))
}
test("SPARK-26366: return nulls which are not filtered in except") {
val inputDF = sqlContext.createDataFrame(
sparkContext.parallelize(Seq(Row("0", "a"), Row("1", null))),
StructType(Seq(
StructField("a", StringType, nullable = true),
StructField("b", StringType, nullable = true))))
val exceptDF = inputDF.filter(col("a").isin("0") or col("b") > "c")
checkAnswer(inputDF.except(exceptDF), Seq(Row("1", null)))
}
test("SPARK-26706: Fix Cast.mayTruncate for bytes") {
val thrownException = intercept[AnalysisException] {
spark.range(Long.MaxValue - 10, Long.MaxValue).as[Byte]
.map(b => b - 1)
.collect()
}
assert(thrownException.message.contains("Cannot up cast `id` from bigint to tinyint"))
}
test("SPARK-26690: checkpoints should be executed with an execution id") {
def assertExecutionId: UserDefinedFunction = udf(AssertExecutionId.apply _)
spark.range(10).select(assertExecutionId($"id")).localCheckpoint(true)
}
test("implicit encoder for LocalDate and Instant") {
val localDate = java.time.LocalDate.of(2019, 3, 30)
assert(spark.range(1).map { _ => localDate }.head === localDate)
val instant = java.time.Instant.parse("2019-03-30T09:54:00Z")
assert(spark.range(1).map { _ => instant }.head === instant)
}
val dotColumnTestModes = Table(
("caseSensitive", "colName"),
("true", "field.1"),
("false", "Field.1")
)
test("SPARK-25153: Improve error messages for columns with dots/periods") {
forAll(dotColumnTestModes) { (caseSensitive, colName) =>
val ds = Seq(SpecialCharClass("1", "2")).toDS
withSQLConf(SQLConf.CASE_SENSITIVE.key -> caseSensitive) {
val errorMsg = intercept[AnalysisException] {
ds(colName)
}
assert(errorMsg.getMessage.contains(s"did you mean to quote the `$colName` column?"))
}
}
}
test("groupBy.as") {
val df1 = Seq(DoubleData(1, "one"), DoubleData(2, "two"), DoubleData(3, "three")).toDS()
.repartition($"id").sortWithinPartitions("id")
val df2 = Seq(DoubleData(5, "one"), DoubleData(1, "two"), DoubleData(3, "three")).toDS()
.repartition($"id").sortWithinPartitions("id")
val df3 = df1.groupBy("id").as[Int, DoubleData]
.cogroup(df2.groupBy("id").as[Int, DoubleData]) { case (key, data1, data2) =>
if (key == 1) {
Iterator(DoubleData(key, (data1 ++ data2).foldLeft("")((cur, next) => cur + next.val1)))
} else Iterator.empty
}
checkDataset(df3, DoubleData(1, "onetwo"))
// Assert that no extra shuffle introduced by cogroup.
val exchanges = collect(df3.queryExecution.executedPlan) {
case h: ShuffleExchangeExec => h
}
assert(exchanges.size == 2)
}
test("tail with different numbers") {
Seq(0, 2, 5, 10, 50, 100, 1000).foreach { n =>
assert(spark.range(n).tail(6) === (math.max(n - 6, 0) until n))
}
}
test("tail should not accept minus value") {
val e = intercept[AnalysisException](spark.range(1).tail(-1))
e.getMessage.contains("tail expression must be equal to or greater than 0")
}
test("SparkSession.active should be the same instance after dataset operations") {
val active = SparkSession.getActiveSession.get
val clone = active.cloneSession()
val ds = new Dataset(clone, spark.range(10).queryExecution.logical, Encoders.INT)
ds.queryExecution.analyzed
assert(active eq SparkSession.getActiveSession.get)
}
test("SPARK-30791: sameSemantics and semanticHash work") {
val df1 = Seq((1, 2), (4, 5)).toDF("col1", "col2")
val df2 = Seq((1, 2), (4, 5)).toDF("col1", "col2")
val df3 = Seq((0, 2), (4, 5)).toDF("col1", "col2")
val df4 = Seq((0, 2), (4, 5)).toDF("col0", "col2")
assert(df1.sameSemantics(df2) === true)
assert(df1.sameSemantics(df3) === false)
assert(df3.sameSemantics(df4) === true)
assert(df1.semanticHash === df2.semanticHash)
assert(df1.semanticHash !== df3.semanticHash)
assert(df3.semanticHash === df4.semanticHash)
}
test("SPARK-31854: Invoke in MapElementsExec should not propagate null") {
Seq("true", "false").foreach { wholeStage =>
withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage) {
val ds = Seq(1.asInstanceOf[Integer], null.asInstanceOf[Integer]).toDS()
val expectedAnswer = Seq[(Integer, Integer)]((1, 1), (null, null))
checkDataset(ds.map(v => (v, v)), expectedAnswer: _*)
}
}
}
test("SPARK-32585: Support scala enumeration in ScalaReflection") {
checkDataset(
Seq(FooClassWithEnum(1, FooEnum.E1), FooClassWithEnum(2, FooEnum.E2)).toDS(),
Seq(FooClassWithEnum(1, FooEnum.E1), FooClassWithEnum(2, FooEnum.E2)): _*
)
// test null
checkDataset(
Seq(FooClassWithEnum(1, null), FooClassWithEnum(2, FooEnum.E2)).toDS(),
Seq(FooClassWithEnum(1, null), FooClassWithEnum(2, FooEnum.E2)): _*
)
}
test("SPARK-33390: Make Literal support char array") {
val df = Seq("aa", "bb", "cc", "abc").toDF("zoo")
checkAnswer(df.where($"zoo" === Array('a', 'a')), Seq(Row("aa")))
checkAnswer(
df.where($"zoo".contains(Array('a', 'b'))),
Seq(Row("abc")))
}
test("SPARK-33469: Add current_timezone function") {
val df = Seq(1).toDF("c")
withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "Asia/Shanghai") {
val timezone = df.selectExpr("current_timezone()").collect().head.getString(0)
assert(timezone == "Asia/Shanghai")
}
}
}
object AssertExecutionId {
def apply(id: Long): Long = {
assert(TaskContext.get().getLocalProperty(SQLExecution.EXECUTION_ID_KEY) != null)
id
}
}
case class TestDataUnion(x: Int, y: Int, z: Int)
case class SingleData(id: Int)
case class DoubleData(id: Int, val1: String)
case class TripleData(id: Int, val1: String, val2: Long)
case class WithImmutableMap(id: String, map_test: scala.collection.immutable.Map[Long, String])
case class WithMap(id: String, map_test: scala.collection.Map[Long, String])
case class WithMapInOption(m: Option[scala.collection.Map[Int, Int]])
case class Generic[T](id: T, value: Double)
case class OtherTuple(_1: String, _2: Int)
case class TupleClass(data: (Int, String))
class OuterClass extends Serializable {
case class InnerClass(a: String)
}
object OuterObject {
case class InnerClass(a: String)
}
case class ClassData(a: String, b: Int)
case class ClassData2(c: String, d: Int)
case class ClassNullableData(a: String, b: Integer)
case class NestedStruct(f: ClassData)
case class DeepNestedStruct(f: NestedStruct)
/**
* A class used to test serialization using encoders. This class throws exceptions when using
* Java serialization -- so the only way it can be "serialized" is through our encoders.
*/
case class NonSerializableCaseClass(value: String) extends Externalizable {
override def readExternal(in: ObjectInput): Unit = {
throw new UnsupportedOperationException
}
override def writeExternal(out: ObjectOutput): Unit = {
throw new UnsupportedOperationException
}
}
/** Used to test Kryo encoder. */
class KryoData(val a: Int) {
override def equals(other: Any): Boolean = {
a == other.asInstanceOf[KryoData].a
}
override def hashCode: Int = a
override def toString: String = s"KryoData($a)"
}
object KryoData {
def apply(a: Int): KryoData = new KryoData(a)
}
/** Used to test Java encoder. */
class JavaData(val a: Int) extends Serializable {
override def equals(other: Any): Boolean = {
a == other.asInstanceOf[JavaData].a
}
override def hashCode: Int = a
override def toString: String = s"JavaData($a)"
}
object JavaData {
def apply(a: Int): JavaData = new JavaData(a)
}
/** Used to test importing dataset.spark.implicits._ */
object DatasetTransform {
def addOne(ds: Dataset[Int]): Dataset[Int] = {
import ds.sparkSession.implicits._
ds.map(_ + 1)
}
}
case class Route(src: String, dest: String, cost: Int)
case class GroupedRoutes(src: String, dest: String, routes: Seq[Route])
case class CircularReferenceClassA(cls: CircularReferenceClassB)
case class CircularReferenceClassB(cls: CircularReferenceClassA)
case class CircularReferenceClassC(ar: Array[CircularReferenceClassC])
case class CircularReferenceClassD(map: Map[String, CircularReferenceClassE])
case class CircularReferenceClassE(id: String, list: List[CircularReferenceClassD])
case class SpecialCharClass(`field.1`: String, `field 2`: String)
|
shuangshuangwang/spark
|
sql/core/src/test/scala/org/apache/spark/sql/DatasetSuite.scala
|
Scala
|
apache-2.0
| 72,272 |
package org.kongo.kafka.metrics
import java.util.Collections
import java.util.Properties
import kafka.utils.VerifiableProperties
import org.apache.kafka.common.{MetricName => KMetricName}
import org.apache.kafka.common.Metric
import org.kongo.kafka.metrics.config.KafkaStatsdReporterConfig
import org.kongo.kafka.metrics.config.PropertiesMapBehavior
import org.kongo.kafka.metrics.config.VerifiableConfigBehavior
object TestUtils {
def dummyKafkaMetric: Metric = {
new Metric {
override def metricName(): KMetricName = new KMetricName("name", "group", "description", Collections.emptyMap())
override def value(): Double = 0d
}
}
def singletonVerifiablePropertiesBehavior(key: String, value: AnyRef): VerifiableConfigBehavior =
new VerifiableConfigBehavior(singletonVerifiableProperties(key, value))
def singletonVerifiableProperties(key: String, value: AnyRef): VerifiableProperties = {
val props = new Properties
props.put(key, value)
new VerifiableProperties(props)
}
def emptyVerfiableConfig: KafkaStatsdReporterConfig =
KafkaStatsdReporterConfig(new VerifiableProperties())
def emptyVerifiableConfigBehavior: VerifiableConfigBehavior = {
val props = new VerifiableProperties()
new VerifiableConfigBehavior(props)
}
def singletonMapConfigBehavior(key: String, value: String): PropertiesMapBehavior = {
new PropertiesMapBehavior(Collections.singletonMap(key, value))
}
def emptyMapConfig: KafkaStatsdReporterConfig =
KafkaStatsdReporterConfig(Collections.emptyMap[String, String]())
def emptyMapConfigBehavior: PropertiesMapBehavior = {
new PropertiesMapBehavior(Collections.emptyMap())
}
}
|
kongo2002/kafka-statsd-reporter
|
src/test/scala/org/kongo/kafka/metrics/TestUtils.scala
|
Scala
|
apache-2.0
| 1,690 |
package org.hammerlab.guacamole
import org.apache.spark.rdd.RDD
import org.hammerlab.genomics.reference.{ContigName, NumLoci}
import org.hammerlab.guacamole.reads.MappedRead
import org.hammerlab.guacamole.readsets.ContigLengths
import org.hammerlab.guacamole.readsets.rdd.PartitionedRegions
/**
* This package contains functionality related to processing multiple "sets of reads" (e.g. BAM files) in the context of
* a single analysis.
*
* For example, a standard somatic caller will typically load and analyze separate "normal" and "tumor" samples, each
* corresponding to an [[RDD[MappedRead]]], but which will also share metadata, like the [[ContigLengths]] of the
* reference they are mapped to.
*/
package object readsets {
type PerSample[+A] = IndexedSeq[A]
type ContigLengths = Map[ContigName, NumLoci]
type SampleId = Int
type NumSamples = Int
type SampleName = String
type PartitionedReads = PartitionedRegions[MappedRead]
}
|
hammerlab/guacamole
|
src/main/scala/org/hammerlab/guacamole/readsets/package.scala
|
Scala
|
apache-2.0
| 959 |
package stefansavev.demo.hyperloglog.counters
import org.elasticsearch.common.util.BigArrays
import org.elasticsearch.search.aggregations.metrics.cardinality.HyperLogLogPlusPlus
import stefansavev.demo.hyperloglog.hashing.Hasher
class ElasticSearchHLLPP(hasher: Hasher) extends ApproximateCounter{
//using one bucket
val hllPP = new HyperLogLogPlusPlus(14, BigArrays.NON_RECYCLING_INSTANCE, 1)
override def add(obj: Long): Unit = {
val hash = hasher.hash(obj)
hllPP.collect(0, hash)
}
override def distinctCount(): Double = {
hllPP.cardinality(0)
}
}
|
dvgodoy/HashingAndSketching
|
out/production/hyperloglog/stefansavev/demo/hyperloglog/counters/ElasticSearchHLLPP.scala
|
Scala
|
apache-2.0
| 579 |
package org.inosion.dadagen
import scala.collection.JavaConverters._
/**
* Java Implementation of the RandomDataGenerator
*
* Appending 'J' Little bit code smelly (TODO : resolve a better Java API design)
*
* @tparam A
*/
abstract class RandomDataGeneratorJ[A] extends Dadagenerator[A] {
def generateAllJ(rows: java.lang.Integer) = super.generateAll(rows).asJava
def generateJ(): java.util.Iterator[A] = super.generate().asJava
}
|
inosion/dadagen
|
dadagen-core/src/main/scala/org/inosion/dadagen/RandomDataGeneratorJ.scala
|
Scala
|
apache-2.0
| 447 |
package com.featurefm.metrics
import akka.actor._
import com.codahale.metrics.MetricRegistry
class MetricsExtension(extendedSystem: ExtendedActorSystem) extends Extension {
// Allow access to the extended system
val system = extendedSystem
// The application wide metrics registry.
val metricRegistry = new MetricRegistry()
}
object Metrics extends ExtensionId[MetricsExtension] with ExtensionIdProvider {
//The lookup method is required by ExtensionIdProvider,
// so we return ourselves here, this allows us
// to configure our extension to be loaded when
// the ActorSystem starts up
override def lookup() = Metrics
//This method will be called by Akka
// to instantiate our Extension
override def createExtension(system: ExtendedActorSystem) = new MetricsExtension(system)
def apply()(implicit system: ActorSystem): MetricsExtension = system.registerExtension(this)
}
|
ListnPlay/Kastomer
|
src/main/scala/com/featurefm/metrics/MetricsExtension.scala
|
Scala
|
mit
| 905 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.scheduler
import java.nio.ByteBuffer
import scala.collection.mutable.{ArrayBuffer, HashMap}
import scala.concurrent.duration._
import org.mockito.ArgumentMatchers.{any, anyInt, anyString, eq => meq}
import org.mockito.Mockito.{atLeast, atMost, never, spy, times, verify, when}
import org.scalatest.BeforeAndAfterEach
import org.scalatest.concurrent.Eventually
import org.scalatest.mockito.MockitoSugar
import org.apache.spark._
import org.apache.spark.ResourceName.GPU
import org.apache.spark.internal.Logging
import org.apache.spark.internal.config
import org.apache.spark.util.ManualClock
class FakeSchedulerBackend extends SchedulerBackend {
def start() {}
def stop() {}
def reviveOffers() {}
def defaultParallelism(): Int = 1
def maxNumConcurrentTasks(): Int = 0
}
class TaskSchedulerImplSuite extends SparkFunSuite with LocalSparkContext with BeforeAndAfterEach
with Logging with MockitoSugar with Eventually {
var failedTaskSetException: Option[Throwable] = None
var failedTaskSetReason: String = null
var failedTaskSet = false
var blacklist: BlacklistTracker = null
var taskScheduler: TaskSchedulerImpl = null
var dagScheduler: DAGScheduler = null
val stageToMockTaskSetBlacklist = new HashMap[Int, TaskSetBlacklist]()
val stageToMockTaskSetManager = new HashMap[Int, TaskSetManager]()
override def beforeEach(): Unit = {
super.beforeEach()
failedTaskSet = false
failedTaskSetException = None
failedTaskSetReason = null
stageToMockTaskSetBlacklist.clear()
stageToMockTaskSetManager.clear()
}
override def afterEach(): Unit = {
if (taskScheduler != null) {
taskScheduler.stop()
taskScheduler = null
}
if (dagScheduler != null) {
dagScheduler.stop()
dagScheduler = null
}
super.afterEach()
}
def setupScheduler(confs: (String, String)*): TaskSchedulerImpl = {
setupSchedulerWithMaster("local", confs: _*)
}
def setupScheduler(numCores: Int, confs: (String, String)*): TaskSchedulerImpl = {
setupSchedulerWithMaster(s"local[$numCores]", confs: _*)
}
def setupSchedulerWithMaster(master: String, confs: (String, String)*): TaskSchedulerImpl = {
val conf = new SparkConf().setMaster(master).setAppName("TaskSchedulerImplSuite")
confs.foreach { case (k, v) => conf.set(k, v) }
sc = new SparkContext(conf)
taskScheduler = new TaskSchedulerImpl(sc)
setupHelper()
}
def setupSchedulerWithMockTaskSetBlacklist(confs: (String, String)*): TaskSchedulerImpl = {
blacklist = mock[BlacklistTracker]
val conf = new SparkConf().setMaster("local").setAppName("TaskSchedulerImplSuite")
conf.set(config.BLACKLIST_ENABLED, true)
confs.foreach { case (k, v) => conf.set(k, v) }
sc = new SparkContext(conf)
taskScheduler =
new TaskSchedulerImpl(sc, sc.conf.get(config.TASK_MAX_FAILURES)) {
override def createTaskSetManager(taskSet: TaskSet, maxFailures: Int): TaskSetManager = {
val tsm = super.createTaskSetManager(taskSet, maxFailures)
// we need to create a spied tsm just so we can set the TaskSetBlacklist
val tsmSpy = spy(tsm)
val taskSetBlacklist = mock[TaskSetBlacklist]
when(tsmSpy.taskSetBlacklistHelperOpt).thenReturn(Some(taskSetBlacklist))
stageToMockTaskSetManager(taskSet.stageId) = tsmSpy
stageToMockTaskSetBlacklist(taskSet.stageId) = taskSetBlacklist
tsmSpy
}
override private[scheduler] lazy val blacklistTrackerOpt = Some(blacklist)
}
setupHelper()
}
def setupHelper(): TaskSchedulerImpl = {
taskScheduler.initialize(new FakeSchedulerBackend)
// Need to initialize a DAGScheduler for the taskScheduler to use for callbacks.
dagScheduler = new DAGScheduler(sc, taskScheduler) {
override def taskStarted(task: Task[_], taskInfo: TaskInfo): Unit = {}
override def executorAdded(execId: String, host: String): Unit = {}
override def taskSetFailed(
taskSet: TaskSet,
reason: String,
exception: Option[Throwable]): Unit = {
// Normally the DAGScheduler puts this in the event loop, which will eventually fail
// dependent jobs
failedTaskSet = true
failedTaskSetReason = reason
failedTaskSetException = exception
}
}
taskScheduler
}
test("Scheduler does not always schedule tasks on the same workers") {
val taskScheduler = setupScheduler()
val numFreeCores = 1
val workerOffers = IndexedSeq(new WorkerOffer("executor0", "host0", numFreeCores),
new WorkerOffer("executor1", "host1", numFreeCores))
// Repeatedly try to schedule a 1-task job, and make sure that it doesn't always
// get scheduled on the same executor. While there is a chance this test will fail
// because the task randomly gets placed on the first executor all 1000 times, the
// probability of that happening is 2^-1000 (so sufficiently small to be considered
// negligible).
val numTrials = 1000
val selectedExecutorIds = 1.to(numTrials).map { _ =>
val taskSet = FakeTask.createTaskSet(1)
taskScheduler.submitTasks(taskSet)
val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten
assert(1 === taskDescriptions.length)
taskDescriptions(0).executorId
}
val count = selectedExecutorIds.count(_ == workerOffers(0).executorId)
assert(count > 0)
assert(count < numTrials)
assert(!failedTaskSet)
}
test("Scheduler correctly accounts for multiple CPUs per task") {
val taskCpus = 2
val taskScheduler = setupSchedulerWithMaster(
s"local[$taskCpus]",
config.CPUS_PER_TASK.key -> taskCpus.toString)
// Give zero core offers. Should not generate any tasks
val zeroCoreWorkerOffers = IndexedSeq(new WorkerOffer("executor0", "host0", 0),
new WorkerOffer("executor1", "host1", 0))
val taskSet = FakeTask.createTaskSet(1)
taskScheduler.submitTasks(taskSet)
var taskDescriptions = taskScheduler.resourceOffers(zeroCoreWorkerOffers).flatten
assert(0 === taskDescriptions.length)
// No tasks should run as we only have 1 core free.
val numFreeCores = 1
val singleCoreWorkerOffers = IndexedSeq(new WorkerOffer("executor0", "host0", numFreeCores),
new WorkerOffer("executor1", "host1", numFreeCores))
taskScheduler.submitTasks(taskSet)
taskDescriptions = taskScheduler.resourceOffers(singleCoreWorkerOffers).flatten
assert(0 === taskDescriptions.length)
// Now change the offers to have 2 cores in one executor and verify if it
// is chosen.
val multiCoreWorkerOffers = IndexedSeq(new WorkerOffer("executor0", "host0", taskCpus),
new WorkerOffer("executor1", "host1", numFreeCores))
taskScheduler.submitTasks(taskSet)
taskDescriptions = taskScheduler.resourceOffers(multiCoreWorkerOffers).flatten
assert(1 === taskDescriptions.length)
assert("executor0" === taskDescriptions(0).executorId)
assert(!failedTaskSet)
}
test("Scheduler does not crash when tasks are not serializable") {
val taskCpus = 2
val taskScheduler = setupSchedulerWithMaster(
s"local[$taskCpus]",
config.CPUS_PER_TASK.key -> taskCpus.toString)
val numFreeCores = 1
val taskSet = new TaskSet(
Array(new NotSerializableFakeTask(1, 0), new NotSerializableFakeTask(0, 1)), 0, 0, 0, null)
val multiCoreWorkerOffers = IndexedSeq(new WorkerOffer("executor0", "host0", taskCpus),
new WorkerOffer("executor1", "host1", numFreeCores))
taskScheduler.submitTasks(taskSet)
var taskDescriptions = taskScheduler.resourceOffers(multiCoreWorkerOffers).flatten
assert(0 === taskDescriptions.length)
assert(failedTaskSet)
assert(failedTaskSetReason.contains("Failed to serialize task"))
// Now check that we can still submit tasks
// Even if one of the task sets has not-serializable tasks, the other task set should
// still be processed without error
taskScheduler.submitTasks(FakeTask.createTaskSet(1))
val taskSet2 = new TaskSet(
Array(new NotSerializableFakeTask(1, 0), new NotSerializableFakeTask(0, 1)), 1, 0, 0, null)
taskScheduler.submitTasks(taskSet2)
taskDescriptions = taskScheduler.resourceOffers(multiCoreWorkerOffers).flatten
assert(taskDescriptions.map(_.executorId) === Seq("executor0"))
}
test("concurrent attempts for the same stage only have one active taskset") {
val taskScheduler = setupScheduler()
def isTasksetZombie(taskset: TaskSet): Boolean = {
taskScheduler.taskSetManagerForAttempt(taskset.stageId, taskset.stageAttemptId).get.isZombie
}
val attempt1 = FakeTask.createTaskSet(1, 0)
taskScheduler.submitTasks(attempt1)
// The first submitted taskset is active
assert(!isTasksetZombie(attempt1))
val attempt2 = FakeTask.createTaskSet(1, 1)
taskScheduler.submitTasks(attempt2)
// The first submitted taskset is zombie now
assert(isTasksetZombie(attempt1))
// The newly submitted taskset is active
assert(!isTasksetZombie(attempt2))
val attempt3 = FakeTask.createTaskSet(1, 2)
taskScheduler.submitTasks(attempt3)
// The first submitted taskset remains zombie
assert(isTasksetZombie(attempt1))
// The second submitted taskset is zombie now
assert(isTasksetZombie(attempt2))
// The newly submitted taskset is active
assert(!isTasksetZombie(attempt3))
}
test("don't schedule more tasks after a taskset is zombie") {
val taskScheduler = setupScheduler()
val numFreeCores = 1
val workerOffers = IndexedSeq(new WorkerOffer("executor0", "host0", numFreeCores))
val attempt1 = FakeTask.createTaskSet(10)
// submit attempt 1, offer some resources, some tasks get scheduled
taskScheduler.submitTasks(attempt1)
val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten
assert(1 === taskDescriptions.length)
// now mark attempt 1 as a zombie
taskScheduler.taskSetManagerForAttempt(attempt1.stageId, attempt1.stageAttemptId)
.get.isZombie = true
// don't schedule anything on another resource offer
val taskDescriptions2 = taskScheduler.resourceOffers(workerOffers).flatten
assert(0 === taskDescriptions2.length)
// if we schedule another attempt for the same stage, it should get scheduled
val attempt2 = FakeTask.createTaskSet(10, 1)
// submit attempt 2, offer some resources, some tasks get scheduled
taskScheduler.submitTasks(attempt2)
val taskDescriptions3 = taskScheduler.resourceOffers(workerOffers).flatten
assert(1 === taskDescriptions3.length)
val mgr = Option(taskScheduler.taskIdToTaskSetManager.get(taskDescriptions3(0).taskId)).get
assert(mgr.taskSet.stageAttemptId === 1)
assert(!failedTaskSet)
}
test("if a zombie attempt finishes, continue scheduling tasks for non-zombie attempts") {
val taskScheduler = setupScheduler()
val numFreeCores = 10
val workerOffers = IndexedSeq(new WorkerOffer("executor0", "host0", numFreeCores))
val attempt1 = FakeTask.createTaskSet(10)
// submit attempt 1, offer some resources, some tasks get scheduled
taskScheduler.submitTasks(attempt1)
val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten
assert(10 === taskDescriptions.length)
// now mark attempt 1 as a zombie
val mgr1 = taskScheduler.taskSetManagerForAttempt(attempt1.stageId, attempt1.stageAttemptId).get
mgr1.isZombie = true
// don't schedule anything on another resource offer
val taskDescriptions2 = taskScheduler.resourceOffers(workerOffers).flatten
assert(0 === taskDescriptions2.length)
// submit attempt 2
val attempt2 = FakeTask.createTaskSet(10, 1)
taskScheduler.submitTasks(attempt2)
// attempt 1 finished (this can happen even if it was marked zombie earlier -- all tasks were
// already submitted, and then they finish)
taskScheduler.taskSetFinished(mgr1)
// now with another resource offer, we should still schedule all the tasks in attempt2
val taskDescriptions3 = taskScheduler.resourceOffers(workerOffers).flatten
assert(10 === taskDescriptions3.length)
taskDescriptions3.foreach { task =>
val mgr = Option(taskScheduler.taskIdToTaskSetManager.get(task.taskId)).get
assert(mgr.taskSet.stageAttemptId === 1)
}
assert(!failedTaskSet)
}
test("tasks are not re-scheduled while executor loss reason is pending") {
val taskScheduler = setupScheduler()
val e0Offers = IndexedSeq(new WorkerOffer("executor0", "host0", 1))
val e1Offers = IndexedSeq(new WorkerOffer("executor1", "host0", 1))
val attempt1 = FakeTask.createTaskSet(1)
// submit attempt 1, offer resources, task gets scheduled
taskScheduler.submitTasks(attempt1)
val taskDescriptions = taskScheduler.resourceOffers(e0Offers).flatten
assert(1 === taskDescriptions.length)
// mark executor0 as dead but pending fail reason
taskScheduler.executorLost("executor0", LossReasonPending)
// offer some more resources on a different executor, nothing should change
val taskDescriptions2 = taskScheduler.resourceOffers(e1Offers).flatten
assert(0 === taskDescriptions2.length)
// provide the actual loss reason for executor0
taskScheduler.executorLost("executor0", SlaveLost("oops"))
// executor0's tasks should have failed now that the loss reason is known, so offering more
// resources should make them be scheduled on the new executor.
val taskDescriptions3 = taskScheduler.resourceOffers(e1Offers).flatten
assert(1 === taskDescriptions3.length)
assert("executor1" === taskDescriptions3(0).executorId)
assert(!failedTaskSet)
}
test("scheduled tasks obey task and stage blacklists") {
taskScheduler = setupSchedulerWithMockTaskSetBlacklist()
(0 to 2).foreach {stageId =>
val taskSet = FakeTask.createTaskSet(numTasks = 2, stageId = stageId, stageAttemptId = 0)
taskScheduler.submitTasks(taskSet)
}
// Setup our mock blacklist:
// * stage 0 is blacklisted on node "host1"
// * stage 1 is blacklisted on executor "executor3"
// * stage 0, partition 0 is blacklisted on executor 0
// (mocked methods default to returning false, ie. no blacklisting)
when(stageToMockTaskSetBlacklist(0).isNodeBlacklistedForTaskSet("host1")).thenReturn(true)
when(stageToMockTaskSetBlacklist(1).isExecutorBlacklistedForTaskSet("executor3"))
.thenReturn(true)
when(stageToMockTaskSetBlacklist(0).isExecutorBlacklistedForTask("executor0", 0))
.thenReturn(true)
val offers = IndexedSeq(
new WorkerOffer("executor0", "host0", 1),
new WorkerOffer("executor1", "host1", 1),
new WorkerOffer("executor2", "host1", 1),
new WorkerOffer("executor3", "host2", 10)
)
val firstTaskAttempts = taskScheduler.resourceOffers(offers).flatten
// We should schedule all tasks.
assert(firstTaskAttempts.size === 6)
// Whenever we schedule a task, we must consult the node and executor blacklist. (The test
// doesn't check exactly what checks are made because the offers get shuffled.)
(0 to 2).foreach { stageId =>
verify(stageToMockTaskSetBlacklist(stageId), atLeast(1))
.isNodeBlacklistedForTaskSet(anyString())
verify(stageToMockTaskSetBlacklist(stageId), atLeast(1))
.isExecutorBlacklistedForTaskSet(anyString())
}
def tasksForStage(stageId: Int): Seq[TaskDescription] = {
firstTaskAttempts.filter{_.name.contains(s"stage $stageId")}
}
tasksForStage(0).foreach { task =>
// executors 1 & 2 blacklisted for node
// executor 0 blacklisted just for partition 0
if (task.index == 0) {
assert(task.executorId === "executor3")
} else {
assert(Set("executor0", "executor3").contains(task.executorId))
}
}
tasksForStage(1).foreach { task =>
// executor 3 blacklisted
assert("executor3" != task.executorId)
}
// no restrictions on stage 2
// Finally, just make sure that we can still complete tasks as usual with blacklisting
// in effect. Finish each of the tasksets -- taskset 0 & 1 complete successfully, taskset 2
// fails.
(0 to 2).foreach { stageId =>
val tasks = tasksForStage(stageId)
val tsm = taskScheduler.taskSetManagerForAttempt(stageId, 0).get
val valueSer = SparkEnv.get.serializer.newInstance()
if (stageId == 2) {
// Just need to make one task fail 4 times.
var task = tasks(0)
val taskIndex = task.index
(0 until 4).foreach { attempt =>
assert(task.attemptNumber === attempt)
tsm.handleFailedTask(task.taskId, TaskState.FAILED, TaskResultLost)
val nextAttempts =
taskScheduler.resourceOffers(IndexedSeq(WorkerOffer("executor4", "host4", 1))).flatten
if (attempt < 3) {
assert(nextAttempts.size === 1)
task = nextAttempts(0)
assert(task.index === taskIndex)
} else {
assert(nextAttempts.size === 0)
}
}
// End the other task of the taskset, doesn't matter whether it succeeds or fails.
val otherTask = tasks(1)
val result = new DirectTaskResult[Int](valueSer.serialize(otherTask.taskId), Seq())
tsm.handleSuccessfulTask(otherTask.taskId, result)
} else {
tasks.foreach { task =>
val result = new DirectTaskResult[Int](valueSer.serialize(task.taskId), Seq())
tsm.handleSuccessfulTask(task.taskId, result)
}
}
assert(tsm.isZombie)
}
// the tasksSets complete, so the tracker should be notified of the successful ones
verify(blacklist, times(1)).updateBlacklistForSuccessfulTaskSet(
stageId = 0,
stageAttemptId = 0,
failuresByExec = stageToMockTaskSetBlacklist(0).execToFailures)
verify(blacklist, times(1)).updateBlacklistForSuccessfulTaskSet(
stageId = 1,
stageAttemptId = 0,
failuresByExec = stageToMockTaskSetBlacklist(1).execToFailures)
// but we shouldn't update for the failed taskset
verify(blacklist, never).updateBlacklistForSuccessfulTaskSet(
stageId = meq(2),
stageAttemptId = anyInt(),
failuresByExec = any())
}
test("scheduled tasks obey node and executor blacklists") {
taskScheduler = setupSchedulerWithMockTaskSetBlacklist()
(0 to 2).foreach { stageId =>
val taskSet = FakeTask.createTaskSet(numTasks = 2, stageId = stageId, stageAttemptId = 0)
taskScheduler.submitTasks(taskSet)
}
val offers = IndexedSeq(
new WorkerOffer("executor0", "host0", 1),
new WorkerOffer("executor1", "host1", 1),
new WorkerOffer("executor2", "host1", 1),
new WorkerOffer("executor3", "host2", 10),
new WorkerOffer("executor4", "host3", 1)
)
// setup our mock blacklist:
// host1, executor0 & executor3 are completely blacklisted
// This covers everything *except* one core on executor4 / host3, so that everything is still
// schedulable.
when(blacklist.isNodeBlacklisted("host1")).thenReturn(true)
when(blacklist.isExecutorBlacklisted("executor0")).thenReturn(true)
when(blacklist.isExecutorBlacklisted("executor3")).thenReturn(true)
val stageToTsm = (0 to 2).map { stageId =>
val tsm = taskScheduler.taskSetManagerForAttempt(stageId, 0).get
stageId -> tsm
}.toMap
val firstTaskAttempts = taskScheduler.resourceOffers(offers).flatten
firstTaskAttempts.foreach { task => logInfo(s"scheduled $task on ${task.executorId}") }
assert(firstTaskAttempts.size === 1)
assert(firstTaskAttempts.head.executorId === "executor4")
('0' until '2').foreach { hostNum =>
verify(blacklist, atLeast(1)).isNodeBlacklisted("host" + hostNum)
}
}
test("abort stage when all executors are blacklisted and we cannot acquire new executor") {
taskScheduler = setupSchedulerWithMockTaskSetBlacklist()
val taskSet = FakeTask.createTaskSet(numTasks = 10, stageAttemptId = 0)
taskScheduler.submitTasks(taskSet)
val tsm = stageToMockTaskSetManager(0)
// first just submit some offers so the scheduler knows about all the executors
taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 2),
WorkerOffer("executor1", "host0", 2),
WorkerOffer("executor2", "host0", 2),
WorkerOffer("executor3", "host1", 2)
))
// now say our blacklist updates to blacklist a bunch of resources, but *not* everything
when(blacklist.isNodeBlacklisted("host1")).thenReturn(true)
when(blacklist.isExecutorBlacklisted("executor0")).thenReturn(true)
// make an offer on the blacklisted resources. We won't schedule anything, but also won't
// abort yet, since we know of other resources that work
assert(taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 2),
WorkerOffer("executor3", "host1", 2)
)).flatten.size === 0)
assert(!tsm.isZombie)
// now update the blacklist so that everything really is blacklisted
when(blacklist.isExecutorBlacklisted("executor1")).thenReturn(true)
when(blacklist.isExecutorBlacklisted("executor2")).thenReturn(true)
assert(taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 2),
WorkerOffer("executor3", "host1", 2)
)).flatten.size === 0)
assert(tsm.isZombie)
verify(tsm).abort(anyString(), any())
}
test("SPARK-22148 abort timer should kick in when task is completely blacklisted & no new " +
"executor can be acquired") {
// set the abort timer to fail immediately
taskScheduler = setupSchedulerWithMockTaskSetBlacklist(
config.UNSCHEDULABLE_TASKSET_TIMEOUT.key -> "0")
// We have only 1 task remaining with 1 executor
val taskSet = FakeTask.createTaskSet(numTasks = 1, stageAttemptId = 0)
taskScheduler.submitTasks(taskSet)
val tsm = stageToMockTaskSetManager(0)
// submit an offer with one executor
val firstTaskAttempts = taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 1)
)).flatten
// Fail the running task
val failedTask = firstTaskAttempts.find(_.executorId == "executor0").get
taskScheduler.statusUpdate(failedTask.taskId, TaskState.FAILED, ByteBuffer.allocate(0))
// we explicitly call the handleFailedTask method here to avoid adding a sleep in the test suite
// Reason being - handleFailedTask is run by an executor service and there is a momentary delay
// before it is launched and this fails the assertion check.
tsm.handleFailedTask(failedTask.taskId, TaskState.FAILED, UnknownReason)
when(tsm.taskSetBlacklistHelperOpt.get.isExecutorBlacklistedForTask(
"executor0", failedTask.index)).thenReturn(true)
// make an offer on the blacklisted executor. We won't schedule anything, and set the abort
// timer to kick in immediately
assert(taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 1)
)).flatten.size === 0)
// Wait for the abort timer to kick in. Even though we configure the timeout to be 0, there is a
// slight delay as the abort timer is launched in a separate thread.
eventually(timeout(500.milliseconds)) {
assert(tsm.isZombie)
}
}
test("SPARK-22148 try to acquire a new executor when task is unschedulable with 1 executor") {
taskScheduler = setupSchedulerWithMockTaskSetBlacklist(
config.UNSCHEDULABLE_TASKSET_TIMEOUT.key -> "10")
// We have only 1 task remaining with 1 executor
val taskSet = FakeTask.createTaskSet(numTasks = 1, stageAttemptId = 0)
taskScheduler.submitTasks(taskSet)
val tsm = stageToMockTaskSetManager(0)
// submit an offer with one executor
val firstTaskAttempts = taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 1)
)).flatten
// Fail the running task
val failedTask = firstTaskAttempts.head
taskScheduler.statusUpdate(failedTask.taskId, TaskState.FAILED, ByteBuffer.allocate(0))
// we explicitly call the handleFailedTask method here to avoid adding a sleep in the test suite
// Reason being - handleFailedTask is run by an executor service and there is a momentary delay
// before it is launched and this fails the assertion check.
tsm.handleFailedTask(failedTask.taskId, TaskState.FAILED, UnknownReason)
when(tsm.taskSetBlacklistHelperOpt.get.isExecutorBlacklistedForTask(
"executor0", failedTask.index)).thenReturn(true)
// make an offer on the blacklisted executor. We won't schedule anything, and set the abort
// timer to expire if no new executors could be acquired. We kill the existing idle blacklisted
// executor and try to acquire a new one.
assert(taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 1)
)).flatten.size === 0)
assert(taskScheduler.unschedulableTaskSetToExpiryTime.contains(tsm))
assert(!tsm.isZombie)
// Offer a new executor which should be accepted
assert(taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor1", "host0", 1)
)).flatten.size === 1)
assert(taskScheduler.unschedulableTaskSetToExpiryTime.isEmpty)
assert(!tsm.isZombie)
}
// This is to test a scenario where we have two taskSets completely blacklisted and on acquiring
// a new executor we don't want the abort timer for the second taskSet to expire and abort the job
test("SPARK-22148 abort timer should clear unschedulableTaskSetToExpiryTime for all TaskSets") {
taskScheduler = setupSchedulerWithMockTaskSetBlacklist()
// We have 2 taskSets with 1 task remaining in each with 1 executor completely blacklisted
val taskSet1 = FakeTask.createTaskSet(numTasks = 1, stageId = 0, stageAttemptId = 0)
taskScheduler.submitTasks(taskSet1)
val taskSet2 = FakeTask.createTaskSet(numTasks = 1, stageId = 1, stageAttemptId = 0)
taskScheduler.submitTasks(taskSet2)
val tsm = stageToMockTaskSetManager(0)
// submit an offer with one executor
val firstTaskAttempts = taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 1)
)).flatten
assert(taskScheduler.unschedulableTaskSetToExpiryTime.isEmpty)
// Fail the running task
val failedTask = firstTaskAttempts.head
taskScheduler.statusUpdate(failedTask.taskId, TaskState.FAILED, ByteBuffer.allocate(0))
tsm.handleFailedTask(failedTask.taskId, TaskState.FAILED, UnknownReason)
when(tsm.taskSetBlacklistHelperOpt.get.isExecutorBlacklistedForTask(
"executor0", failedTask.index)).thenReturn(true)
// make an offer. We will schedule the task from the second taskSet. Since a task was scheduled
// we do not kick off the abort timer for taskSet1
val secondTaskAttempts = taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 1)
)).flatten
assert(taskScheduler.unschedulableTaskSetToExpiryTime.isEmpty)
val tsm2 = stageToMockTaskSetManager(1)
val failedTask2 = secondTaskAttempts.head
taskScheduler.statusUpdate(failedTask2.taskId, TaskState.FAILED, ByteBuffer.allocate(0))
tsm2.handleFailedTask(failedTask2.taskId, TaskState.FAILED, UnknownReason)
when(tsm2.taskSetBlacklistHelperOpt.get.isExecutorBlacklistedForTask(
"executor0", failedTask2.index)).thenReturn(true)
// make an offer on the blacklisted executor. We won't schedule anything, and set the abort
// timer for taskSet1 and taskSet2
assert(taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 1)
)).flatten.size === 0)
assert(taskScheduler.unschedulableTaskSetToExpiryTime.contains(tsm))
assert(taskScheduler.unschedulableTaskSetToExpiryTime.contains(tsm2))
assert(taskScheduler.unschedulableTaskSetToExpiryTime.size == 2)
// Offer a new executor which should be accepted
assert(taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor1", "host1", 1)
)).flatten.size === 1)
// Check if all the taskSets are cleared
assert(taskScheduler.unschedulableTaskSetToExpiryTime.isEmpty)
assert(!tsm.isZombie)
}
// this test is to check that we don't abort a taskSet which is not being scheduled on other
// executors as it is waiting on locality timeout and not being aborted because it is still not
// completely blacklisted.
test("SPARK-22148 Ensure we don't abort the taskSet if we haven't been completely blacklisted") {
taskScheduler = setupSchedulerWithMockTaskSetBlacklist(
config.UNSCHEDULABLE_TASKSET_TIMEOUT.key -> "0",
// This is to avoid any potential flakiness in the test because of large pauses in jenkins
config.LOCALITY_WAIT.key -> "30s"
)
val preferredLocation = Seq(ExecutorCacheTaskLocation("host0", "executor0"))
val taskSet1 = FakeTask.createTaskSet(numTasks = 1, stageId = 0, stageAttemptId = 0,
preferredLocation)
taskScheduler.submitTasks(taskSet1)
val tsm = stageToMockTaskSetManager(0)
// submit an offer with one executor
var taskAttempts = taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor0", "host0", 1)
)).flatten
// Fail the running task
val failedTask = taskAttempts.head
taskScheduler.statusUpdate(failedTask.taskId, TaskState.FAILED, ByteBuffer.allocate(0))
tsm.handleFailedTask(failedTask.taskId, TaskState.FAILED, UnknownReason)
when(tsm.taskSetBlacklistHelperOpt.get.isExecutorBlacklistedForTask(
"executor0", failedTask.index)).thenReturn(true)
// make an offer but we won't schedule anything yet as scheduler locality is still PROCESS_LOCAL
assert(taskScheduler.resourceOffers(IndexedSeq(
WorkerOffer("executor1", "host0", 1)
)).flatten.isEmpty)
assert(taskScheduler.unschedulableTaskSetToExpiryTime.isEmpty)
assert(!tsm.isZombie)
}
/**
* Helper for performance tests. Takes the explicitly blacklisted nodes and executors; verifies
* that the blacklists are used efficiently to ensure scheduling is not O(numPendingTasks).
* Creates 1 offer on executor[1-3]. Executor1 & 2 are on host1, executor3 is on host2. Passed
* in nodes and executors should be on that list.
*/
private def testBlacklistPerformance(
testName: String,
nodeBlacklist: Seq[String],
execBlacklist: Seq[String]): Unit = {
// Because scheduling involves shuffling the order of offers around, we run this test a few
// times to cover more possibilities. There are only 3 offers, which means 6 permutations,
// so 10 iterations is pretty good.
(0 until 10).foreach { testItr =>
test(s"$testName: iteration $testItr") {
// When an executor or node is blacklisted, we want to make sure that we don't try
// scheduling each pending task, one by one, to discover they are all blacklisted. This is
// important for performance -- if we did check each task one-by-one, then responding to a
// resource offer (which is usually O(1)-ish) would become O(numPendingTasks), which would
// slow down scheduler throughput and slow down scheduling even on healthy executors.
// Here, we check a proxy for the runtime -- we make sure the scheduling is short-circuited
// at the node or executor blacklist, so we never check the per-task blacklist. We also
// make sure we don't check the node & executor blacklist for the entire taskset
// O(numPendingTasks) times.
taskScheduler = setupSchedulerWithMockTaskSetBlacklist()
// we schedule 500 tasks so we can clearly distinguish anything that is O(numPendingTasks)
val taskSet = FakeTask.createTaskSet(numTasks = 500, stageId = 0, stageAttemptId = 0)
taskScheduler.submitTasks(taskSet)
val offers = IndexedSeq(
new WorkerOffer("executor1", "host1", 1),
new WorkerOffer("executor2", "host1", 1),
new WorkerOffer("executor3", "host2", 1)
)
// We should check the node & exec blacklists, but only O(numOffers), not O(numPendingTasks)
// times. In the worst case, after shuffling, we offer our blacklisted resource first, and
// then offer other resources which do get used. The taskset blacklist is consulted
// repeatedly as we offer resources to the taskset -- each iteration either schedules
// something, or it terminates that locality level, so the maximum number of checks is
// numCores + numLocalityLevels
val numCoresOnAllOffers = offers.map(_.cores).sum
val numLocalityLevels = TaskLocality.values.size
val maxBlacklistChecks = numCoresOnAllOffers + numLocalityLevels
// Setup the blacklist
nodeBlacklist.foreach { node =>
when(stageToMockTaskSetBlacklist(0).isNodeBlacklistedForTaskSet(node)).thenReturn(true)
}
execBlacklist.foreach { exec =>
when(stageToMockTaskSetBlacklist(0).isExecutorBlacklistedForTaskSet(exec))
.thenReturn(true)
}
// Figure out which nodes have any effective blacklisting on them. This means all nodes
// that are explicitly blacklisted, plus those that have *any* executors blacklisted.
val nodesForBlacklistedExecutors = offers.filter { offer =>
execBlacklist.contains(offer.executorId)
}.map(_.host).toSet.toSeq
val nodesWithAnyBlacklisting = (nodeBlacklist ++ nodesForBlacklistedExecutors).toSet
// Similarly, figure out which executors have any blacklisting. This means all executors
// that are explicitly blacklisted, plus all executors on nodes that are blacklisted.
val execsForBlacklistedNodes = offers.filter { offer =>
nodeBlacklist.contains(offer.host)
}.map(_.executorId).toSeq
val executorsWithAnyBlacklisting = (execBlacklist ++ execsForBlacklistedNodes).toSet
// Schedule a taskset, and make sure our test setup is correct -- we are able to schedule
// a task on all executors that aren't blacklisted (whether that executor is a explicitly
// blacklisted, or implicitly blacklisted via the node blacklist).
val firstTaskAttempts = taskScheduler.resourceOffers(offers).flatten
assert(firstTaskAttempts.size === offers.size - executorsWithAnyBlacklisting.size)
// Now check that we haven't made too many calls to any of the blacklist methods.
// We should be checking our node blacklist, but it should be within the bound we defined
// above.
verify(stageToMockTaskSetBlacklist(0), atMost(maxBlacklistChecks))
.isNodeBlacklistedForTaskSet(anyString())
// We shouldn't ever consult the per-task blacklist for the nodes that have been blacklisted
// for the entire taskset, since the taskset level blacklisting should prevent scheduling
// from ever looking at specific tasks.
nodesWithAnyBlacklisting.foreach { node =>
verify(stageToMockTaskSetBlacklist(0), never)
.isNodeBlacklistedForTask(meq(node), anyInt())
}
executorsWithAnyBlacklisting.foreach { exec =>
// We should be checking our executor blacklist, but it should be within the bound defined
// above. Its possible that this will be significantly fewer calls, maybe even 0, if
// there is also a node-blacklist which takes effect first. But this assert is all we
// need to avoid an O(numPendingTask) slowdown.
verify(stageToMockTaskSetBlacklist(0), atMost(maxBlacklistChecks))
.isExecutorBlacklistedForTaskSet(exec)
// We shouldn't ever consult the per-task blacklist for executors that have been
// blacklisted for the entire taskset, since the taskset level blacklisting should prevent
// scheduling from ever looking at specific tasks.
verify(stageToMockTaskSetBlacklist(0), never)
.isExecutorBlacklistedForTask(meq(exec), anyInt())
}
}
}
}
testBlacklistPerformance(
testName = "Blacklisted node for entire task set prevents per-task blacklist checks",
nodeBlacklist = Seq("host1"),
execBlacklist = Seq())
testBlacklistPerformance(
testName = "Blacklisted executor for entire task set prevents per-task blacklist checks",
nodeBlacklist = Seq(),
execBlacklist = Seq("executor3")
)
test("abort stage if executor loss results in unschedulability from previously failed tasks") {
// Make sure we can detect when a taskset becomes unschedulable from a blacklisting. This
// test explores a particular corner case -- you may have one task fail, but still be
// schedulable on another executor. However, that executor may fail later on, leaving the
// first task with no place to run.
val taskScheduler = setupScheduler(
config.BLACKLIST_ENABLED.key -> "true"
)
val taskSet = FakeTask.createTaskSet(2)
taskScheduler.submitTasks(taskSet)
val tsm = taskScheduler.taskSetManagerForAttempt(taskSet.stageId, taskSet.stageAttemptId).get
val firstTaskAttempts = taskScheduler.resourceOffers(IndexedSeq(
new WorkerOffer("executor0", "host0", 1),
new WorkerOffer("executor1", "host1", 1)
)).flatten
assert(Set("executor0", "executor1") === firstTaskAttempts.map(_.executorId).toSet)
// Fail one of the tasks, but leave the other running.
val failedTask = firstTaskAttempts.find(_.executorId == "executor0").get
taskScheduler.handleFailedTask(tsm, failedTask.taskId, TaskState.FAILED, TaskResultLost)
// At this point, our failed task could run on the other executor, so don't give up the task
// set yet.
assert(!failedTaskSet)
// Now we fail our second executor. The other task can still run on executor1, so make an offer
// on that executor, and make sure that the other task (not the failed one) is assigned there.
taskScheduler.executorLost("executor1", SlaveLost("oops"))
val nextTaskAttempts =
taskScheduler.resourceOffers(IndexedSeq(new WorkerOffer("executor0", "host0", 1))).flatten
// Note: Its OK if some future change makes this already realize the taskset has become
// unschedulable at this point (though in the current implementation, we're sure it will not).
assert(nextTaskAttempts.size === 1)
assert(nextTaskAttempts.head.executorId === "executor0")
assert(nextTaskAttempts.head.attemptNumber === 1)
assert(nextTaskAttempts.head.index != failedTask.index)
// Now we should definitely realize that our task set is unschedulable, because the only
// task left can't be scheduled on any executors due to the blacklist.
taskScheduler.resourceOffers(IndexedSeq(new WorkerOffer("executor0", "host0", 1)))
sc.listenerBus.waitUntilEmpty(100000)
assert(tsm.isZombie)
assert(failedTaskSet)
val idx = failedTask.index
assert(failedTaskSetReason === s"""
|Aborting $taskSet because task $idx (partition $idx)
|cannot run anywhere due to node and executor blacklist.
|Most recent failure:
|${tsm.taskSetBlacklistHelperOpt.get.getLatestFailureReason}
|
|Blacklisting behavior can be configured via spark.blacklist.*.
|""".stripMargin)
}
test("don't abort if there is an executor available, though it hasn't had scheduled tasks yet") {
// interaction of SPARK-15865 & SPARK-16106
// if we have a small number of tasks, we might be able to schedule them all on the first
// executor. But if those tasks fail, we should still realize there is another executor
// available and not bail on the job
val taskScheduler = setupScheduler(
config.BLACKLIST_ENABLED.key -> "true"
)
val taskSet = FakeTask.createTaskSet(2, (0 until 2).map { _ => Seq(TaskLocation("host0")) }: _*)
taskScheduler.submitTasks(taskSet)
val tsm = taskScheduler.taskSetManagerForAttempt(taskSet.stageId, taskSet.stageAttemptId).get
val offers = IndexedSeq(
// each offer has more than enough free cores for the entire task set, so when combined
// with the locality preferences, we schedule all tasks on one executor
new WorkerOffer("executor0", "host0", 4),
new WorkerOffer("executor1", "host1", 4)
)
val firstTaskAttempts = taskScheduler.resourceOffers(offers).flatten
assert(firstTaskAttempts.size == 2)
firstTaskAttempts.foreach { taskAttempt => assert("executor0" === taskAttempt.executorId) }
// fail all the tasks on the bad executor
firstTaskAttempts.foreach { taskAttempt =>
taskScheduler.handleFailedTask(tsm, taskAttempt.taskId, TaskState.FAILED, TaskResultLost)
}
// Here is the main check of this test -- we have the same offers again, and we schedule it
// successfully. Because the scheduler first tries to schedule with locality in mind, at first
// it won't schedule anything on executor1. But despite that, we don't abort the job. Then the
// scheduler tries for ANY locality, and successfully schedules tasks on executor1.
val secondTaskAttempts = taskScheduler.resourceOffers(offers).flatten
assert(secondTaskAttempts.size == 2)
secondTaskAttempts.foreach { taskAttempt => assert("executor1" === taskAttempt.executorId) }
assert(!failedTaskSet)
}
test("SPARK-16106 locality levels updated if executor added to existing host") {
val taskScheduler = setupScheduler()
taskScheduler.submitTasks(FakeTask.createTaskSet(2, 0,
(0 until 2).map { _ => Seq(TaskLocation("host0", "executor2")) }: _*
))
val taskDescs = taskScheduler.resourceOffers(IndexedSeq(
new WorkerOffer("executor0", "host0", 1),
new WorkerOffer("executor1", "host1", 1)
)).flatten
// only schedule one task because of locality
assert(taskDescs.size === 1)
val mgr = Option(taskScheduler.taskIdToTaskSetManager.get(taskDescs(0).taskId)).get
assert(mgr.myLocalityLevels.toSet === Set(TaskLocality.NODE_LOCAL, TaskLocality.ANY))
// we should know about both executors, even though we only scheduled tasks on one of them
assert(taskScheduler.getExecutorsAliveOnHost("host0") === Some(Set("executor0")))
assert(taskScheduler.getExecutorsAliveOnHost("host1") === Some(Set("executor1")))
// when executor2 is added, we should realize that we can run process-local tasks.
// And we should know its alive on the host.
val secondTaskDescs = taskScheduler.resourceOffers(
IndexedSeq(new WorkerOffer("executor2", "host0", 1))).flatten
assert(secondTaskDescs.size === 1)
assert(mgr.myLocalityLevels.toSet ===
Set(TaskLocality.PROCESS_LOCAL, TaskLocality.NODE_LOCAL, TaskLocality.ANY))
assert(taskScheduler.getExecutorsAliveOnHost("host0") === Some(Set("executor0", "executor2")))
assert(taskScheduler.getExecutorsAliveOnHost("host1") === Some(Set("executor1")))
// And even if we don't have anything left to schedule, another resource offer on yet another
// executor should also update the set of live executors
val thirdTaskDescs = taskScheduler.resourceOffers(
IndexedSeq(new WorkerOffer("executor3", "host1", 1))).flatten
assert(thirdTaskDescs.size === 0)
assert(taskScheduler.getExecutorsAliveOnHost("host1") === Some(Set("executor1", "executor3")))
}
test("scheduler checks for executors that can be expired from blacklist") {
taskScheduler = setupScheduler()
taskScheduler.submitTasks(FakeTask.createTaskSet(1, 0))
taskScheduler.resourceOffers(IndexedSeq(
new WorkerOffer("executor0", "host0", 1)
)).flatten
verify(blacklist).applyBlacklistTimeout()
}
test("if an executor is lost then the state for its running tasks is cleaned up (SPARK-18553)") {
sc = new SparkContext("local", "TaskSchedulerImplSuite")
val taskScheduler = new TaskSchedulerImpl(sc)
taskScheduler.initialize(new FakeSchedulerBackend)
// Need to initialize a DAGScheduler for the taskScheduler to use for callbacks.
new DAGScheduler(sc, taskScheduler) {
override def taskStarted(task: Task[_], taskInfo: TaskInfo) {}
override def executorAdded(execId: String, host: String) {}
}
val e0Offers = IndexedSeq(WorkerOffer("executor0", "host0", 1))
val attempt1 = FakeTask.createTaskSet(1)
// submit attempt 1, offer resources, task gets scheduled
taskScheduler.submitTasks(attempt1)
val taskDescriptions = taskScheduler.resourceOffers(e0Offers).flatten
assert(1 === taskDescriptions.length)
// mark executor0 as dead
taskScheduler.executorLost("executor0", SlaveLost())
assert(!taskScheduler.isExecutorAlive("executor0"))
assert(!taskScheduler.hasExecutorsAliveOnHost("host0"))
assert(taskScheduler.getExecutorsAliveOnHost("host0").isEmpty)
// Check that state associated with the lost task attempt is cleaned up:
assert(taskScheduler.taskIdToExecutorId.isEmpty)
assert(taskScheduler.taskIdToTaskSetManager.isEmpty)
assert(taskScheduler.runningTasksByExecutors.get("executor0").isEmpty)
}
test("if a task finishes with TaskState.LOST its executor is marked as dead") {
sc = new SparkContext("local", "TaskSchedulerImplSuite")
val taskScheduler = new TaskSchedulerImpl(sc)
taskScheduler.initialize(new FakeSchedulerBackend)
// Need to initialize a DAGScheduler for the taskScheduler to use for callbacks.
new DAGScheduler(sc, taskScheduler) {
override def taskStarted(task: Task[_], taskInfo: TaskInfo) {}
override def executorAdded(execId: String, host: String) {}
}
val e0Offers = IndexedSeq(WorkerOffer("executor0", "host0", 1))
val attempt1 = FakeTask.createTaskSet(1)
// submit attempt 1, offer resources, task gets scheduled
taskScheduler.submitTasks(attempt1)
val taskDescriptions = taskScheduler.resourceOffers(e0Offers).flatten
assert(1 === taskDescriptions.length)
// Report the task as failed with TaskState.LOST
taskScheduler.statusUpdate(
tid = taskDescriptions.head.taskId,
state = TaskState.LOST,
serializedData = ByteBuffer.allocate(0)
)
// Check that state associated with the lost task attempt is cleaned up:
assert(taskScheduler.taskIdToExecutorId.isEmpty)
assert(taskScheduler.taskIdToTaskSetManager.isEmpty)
assert(taskScheduler.runningTasksByExecutors.get("executor0").isEmpty)
// Check that the executor has been marked as dead
assert(!taskScheduler.isExecutorAlive("executor0"))
assert(!taskScheduler.hasExecutorsAliveOnHost("host0"))
assert(taskScheduler.getExecutorsAliveOnHost("host0").isEmpty)
}
test("Locality should be used for bulk offers even with delay scheduling off") {
val conf = new SparkConf()
.set(config.LOCALITY_WAIT.key, "0")
sc = new SparkContext("local", "TaskSchedulerImplSuite", conf)
// we create a manual clock just so we can be sure the clock doesn't advance at all in this test
val clock = new ManualClock()
// We customize the task scheduler just to let us control the way offers are shuffled, so we
// can be sure we try both permutations, and to control the clock on the tasksetmanager.
val taskScheduler = new TaskSchedulerImpl(sc) {
override def shuffleOffers(offers: IndexedSeq[WorkerOffer]): IndexedSeq[WorkerOffer] = {
// Don't shuffle the offers around for this test. Instead, we'll just pass in all
// the permutations we care about directly.
offers
}
override def createTaskSetManager(taskSet: TaskSet, maxTaskFailures: Int): TaskSetManager = {
new TaskSetManager(this, taskSet, maxTaskFailures, blacklistTrackerOpt, clock)
}
}
// Need to initialize a DAGScheduler for the taskScheduler to use for callbacks.
new DAGScheduler(sc, taskScheduler) {
override def taskStarted(task: Task[_], taskInfo: TaskInfo) {}
override def executorAdded(execId: String, host: String) {}
}
taskScheduler.initialize(new FakeSchedulerBackend)
// Make two different offers -- one in the preferred location, one that is not.
val offers = IndexedSeq(
WorkerOffer("exec1", "host1", 1),
WorkerOffer("exec2", "host2", 1)
)
Seq(false, true).foreach { swapOrder =>
// Submit a taskset with locality preferences.
val taskSet = FakeTask.createTaskSet(
1, stageId = 1, stageAttemptId = 0, Seq(TaskLocation("host1", "exec1")))
taskScheduler.submitTasks(taskSet)
val shuffledOffers = if (swapOrder) offers.reverse else offers
// Regardless of the order of the offers (after the task scheduler shuffles them), we should
// always take advantage of the local offer.
val taskDescs = taskScheduler.resourceOffers(shuffledOffers).flatten
withClue(s"swapOrder = $swapOrder") {
assert(taskDescs.size === 1)
assert(taskDescs.head.executorId === "exec1")
}
}
}
test("With delay scheduling off, tasks can be run at any locality level immediately") {
val conf = new SparkConf()
.set(config.LOCALITY_WAIT.key, "0")
sc = new SparkContext("local", "TaskSchedulerImplSuite", conf)
// we create a manual clock just so we can be sure the clock doesn't advance at all in this test
val clock = new ManualClock()
val taskScheduler = new TaskSchedulerImpl(sc) {
override def createTaskSetManager(taskSet: TaskSet, maxTaskFailures: Int): TaskSetManager = {
new TaskSetManager(this, taskSet, maxTaskFailures, blacklistTrackerOpt, clock)
}
}
// Need to initialize a DAGScheduler for the taskScheduler to use for callbacks.
new DAGScheduler(sc, taskScheduler) {
override def taskStarted(task: Task[_], taskInfo: TaskInfo) {}
override def executorAdded(execId: String, host: String) {}
}
taskScheduler.initialize(new FakeSchedulerBackend)
// make an offer on the preferred host so the scheduler knows its alive. This is necessary
// so that the taskset knows that it *could* take advantage of locality.
taskScheduler.resourceOffers(IndexedSeq(WorkerOffer("exec1", "host1", 1)))
// Submit a taskset with locality preferences.
val taskSet = FakeTask.createTaskSet(
1, stageId = 1, stageAttemptId = 0, Seq(TaskLocation("host1", "exec1")))
taskScheduler.submitTasks(taskSet)
val tsm = taskScheduler.taskSetManagerForAttempt(1, 0).get
// make sure we've setup our test correctly, so that the taskset knows it *could* use local
// offers.
assert(tsm.myLocalityLevels.contains(TaskLocality.NODE_LOCAL))
// make an offer on a non-preferred location. Since the delay is 0, we should still schedule
// immediately.
val taskDescs =
taskScheduler.resourceOffers(IndexedSeq(WorkerOffer("exec2", "host2", 1))).flatten
assert(taskDescs.size === 1)
assert(taskDescs.head.executorId === "exec2")
}
test("TaskScheduler should throw IllegalArgumentException when schedulingMode is not supported") {
intercept[IllegalArgumentException] {
val taskScheduler = setupScheduler(
TaskSchedulerImpl.SCHEDULER_MODE_PROPERTY -> SchedulingMode.NONE.toString)
taskScheduler.initialize(new FakeSchedulerBackend)
}
}
test("don't schedule for a barrier taskSet if available slots are less than pending tasks") {
val taskCpus = 2
val taskScheduler = setupSchedulerWithMaster(
s"local[$taskCpus]",
config.CPUS_PER_TASK.key -> taskCpus.toString)
val numFreeCores = 3
val workerOffers = IndexedSeq(
new WorkerOffer("executor0", "host0", numFreeCores, Some("192.168.0.101:49625")),
new WorkerOffer("executor1", "host1", numFreeCores, Some("192.168.0.101:49627")))
val attempt1 = FakeTask.createBarrierTaskSet(3)
// submit attempt 1, offer some resources, since the available slots are less than pending
// tasks, don't schedule barrier tasks on the resource offer.
taskScheduler.submitTasks(attempt1)
val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten
assert(0 === taskDescriptions.length)
}
test("schedule tasks for a barrier taskSet if all tasks can be launched together") {
val taskCpus = 2
val taskScheduler = setupSchedulerWithMaster(
s"local[$taskCpus]",
config.CPUS_PER_TASK.key -> taskCpus.toString)
val numFreeCores = 3
val workerOffers = IndexedSeq(
new WorkerOffer("executor0", "host0", numFreeCores, Some("192.168.0.101:49625")),
new WorkerOffer("executor1", "host1", numFreeCores, Some("192.168.0.101:49627")),
new WorkerOffer("executor2", "host2", numFreeCores, Some("192.168.0.101:49629")))
val attempt1 = FakeTask.createBarrierTaskSet(3)
// submit attempt 1, offer some resources, all tasks get launched together
taskScheduler.submitTasks(attempt1)
val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten
assert(3 === taskDescriptions.length)
}
test("cancelTasks shall kill all the running tasks and fail the stage") {
val taskScheduler = setupScheduler()
taskScheduler.initialize(new FakeSchedulerBackend {
override def killTask(
taskId: Long,
executorId: String,
interruptThread: Boolean,
reason: String): Unit = {
// Since we only submit one stage attempt, the following call is sufficient to mark the
// task as killed.
taskScheduler.taskSetManagerForAttempt(0, 0).get.runningTasksSet.remove(taskId)
}
})
val attempt1 = FakeTask.createTaskSet(10, 0)
taskScheduler.submitTasks(attempt1)
val workerOffers = IndexedSeq(new WorkerOffer("executor0", "host0", 1),
new WorkerOffer("executor1", "host1", 1))
val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten
assert(2 === taskDescriptions.length)
val tsm = taskScheduler.taskSetManagerForAttempt(0, 0).get
assert(2 === tsm.runningTasks)
taskScheduler.cancelTasks(0, false)
assert(0 === tsm.runningTasks)
assert(tsm.isZombie)
assert(taskScheduler.taskSetManagerForAttempt(0, 0).isEmpty)
}
test("killAllTaskAttempts shall kill all the running tasks and not fail the stage") {
val taskScheduler = setupScheduler()
taskScheduler.initialize(new FakeSchedulerBackend {
override def killTask(
taskId: Long,
executorId: String,
interruptThread: Boolean,
reason: String): Unit = {
// Since we only submit one stage attempt, the following call is sufficient to mark the
// task as killed.
taskScheduler.taskSetManagerForAttempt(0, 0).get.runningTasksSet.remove(taskId)
}
})
val attempt1 = FakeTask.createTaskSet(10, 0)
taskScheduler.submitTasks(attempt1)
val workerOffers = IndexedSeq(new WorkerOffer("executor0", "host0", 1),
new WorkerOffer("executor1", "host1", 1))
val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten
assert(2 === taskDescriptions.length)
val tsm = taskScheduler.taskSetManagerForAttempt(0, 0).get
assert(2 === tsm.runningTasks)
taskScheduler.killAllTaskAttempts(0, false, "test")
assert(0 === tsm.runningTasks)
assert(!tsm.isZombie)
assert(taskScheduler.taskSetManagerForAttempt(0, 0).isDefined)
}
test("mark taskset for a barrier stage as zombie in case a task fails") {
val taskScheduler = setupScheduler()
val attempt = FakeTask.createBarrierTaskSet(3)
taskScheduler.submitTasks(attempt)
val tsm = taskScheduler.taskSetManagerForAttempt(0, 0).get
val offers = (0 until 3).map{ idx =>
WorkerOffer(s"exec-$idx", s"host-$idx", 1, Some(s"192.168.0.101:4962$idx"))
}
taskScheduler.resourceOffers(offers)
assert(tsm.runningTasks === 3)
// Fail a task from the stage attempt.
tsm.handleFailedTask(tsm.taskAttempts.head.head.taskId, TaskState.FAILED, TaskKilled("test"))
assert(tsm.isZombie)
}
test("Scheduler correctly accounts for GPUs per task") {
val taskCpus = 1
val taskGpus = 1
val executorGpus = 4
val executorCpus = 4
val taskScheduler = setupScheduler(numCores = executorCpus,
config.CPUS_PER_TASK.key -> taskCpus.toString,
s"${config.SPARK_TASK_RESOURCE_PREFIX}${GPU}${config.SPARK_RESOURCE_AMOUNT_SUFFIX}" ->
taskGpus.toString,
s"${config.SPARK_EXECUTOR_RESOURCE_PREFIX}${GPU}${config.SPARK_RESOURCE_AMOUNT_SUFFIX}" ->
executorGpus.toString,
config.EXECUTOR_CORES.key -> executorCpus.toString)
val taskSet = FakeTask.createTaskSet(3)
val numFreeCores = 2
val resources = Map(GPU -> ArrayBuffer("0", "1", "2", "3"))
val singleCoreWorkerOffers =
IndexedSeq(new WorkerOffer("executor0", "host0", numFreeCores, None, resources))
val zeroGpuWorkerOffers =
IndexedSeq(new WorkerOffer("executor0", "host0", numFreeCores, None, Map.empty))
taskScheduler.submitTasks(taskSet)
// WorkerOffer doesn't contain GPU resource, don't launch any task.
var taskDescriptions = taskScheduler.resourceOffers(zeroGpuWorkerOffers).flatten
assert(0 === taskDescriptions.length)
assert(!failedTaskSet)
// Launch tasks on executor that satisfies resource requirements.
taskDescriptions = taskScheduler.resourceOffers(singleCoreWorkerOffers).flatten
assert(2 === taskDescriptions.length)
assert(!failedTaskSet)
assert(ArrayBuffer("0") === taskDescriptions(0).resources.get(GPU).get.addresses)
assert(ArrayBuffer("1") === taskDescriptions(1).resources.get(GPU).get.addresses)
}
}
|
icexelloss/spark
|
core/src/test/scala/org/apache/spark/scheduler/TaskSchedulerImplSuite.scala
|
Scala
|
apache-2.0
| 58,511 |
/*
* This file is part of AckCord, licensed under the MIT License (MIT).
*
* Copyright (c) 2019 Katrix
*
* 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 ackcord.examplecore
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.util.control.NonFatal
import ackcord._
import ackcord.cachehandlers.CacheTypeRegistry
import ackcord.commands._
import ackcord.examplecore.music.MusicHandler
import ackcord.gateway.{GatewayEvent, GatewaySettings}
import ackcord.requests.{BotAuthentication, Ratelimiter, RequestHelper}
import ackcord.util.{APIGuildRouter, GuildRouter}
import akka.actor.CoordinatedShutdown
import akka.actor.typed._
import akka.actor.typed.scaladsl.AskPattern._
import akka.actor.typed.scaladsl._
import akka.actor.typed.scaladsl.adapter._
import akka.pattern.gracefulStop
import akka.stream.scaladsl.Keep
import akka.stream.typed.scaladsl.ActorSink
import akka.stream.{KillSwitches, SharedKillSwitch, UniqueKillSwitch}
import akka.util.Timeout
import akka.{Done, NotUsed}
import cats.arrow.FunctionK
import org.slf4j.Logger
object Example {
def main(args: Array[String]): Unit = {
if (args.isEmpty) {
println("Please specify a token")
sys.exit()
}
val token = args.head
val settings = GatewaySettings(token = token)
ActorSystem(Behaviors.setup[ExampleMain.Command](ctx => new ExampleMain(ctx, ctx.log, settings)), "ExampleCore")
}
}
class ExampleMain(ctx: ActorContext[ExampleMain.Command], log: Logger, settings: GatewaySettings)
extends AbstractBehavior[ExampleMain.Command](ctx) {
import context.executionContext
implicit val system: ActorSystem[Nothing] = context.system
import ExampleMain._
private val cache = Cache.create
private val wsUri = try {
Await.result(DiscordShard.fetchWsGateway, 30.seconds)
} catch {
case NonFatal(e) =>
println("Could not connect to Discord")
throw e
}
private val shard = context.spawn(
DiscordShard(
wsUri,
settings,
cache,
//We can set some gateway events here that we want AckCord to completely
//ignore. For anything listed here, the JSON will never be deserialized,
//and it will be like as if they weren't sent.
ignoredEvents = Seq(
classOf[GatewayEvent.PresenceUpdate],
classOf[GatewayEvent.TypingStart]
),
//In addition to setting events that will be ignored, we can also
//set data types that we don't want the cache to deal with.
//This will for the most part help us save RAM.
//This will for example kick in the GuildCreate event, which includes
//presences.
cacheTypeRegistry = CacheTypeRegistry.noPresences
),
"DiscordShard"
)
private val ratelimiter = context.spawn(Ratelimiter(), "Ratelimiter")
private val requests: RequestHelper =
new RequestHelper(
BotAuthentication(settings.token),
ratelimiter,
millisecondPrecision = false, //My system is pretty bad at syncing stuff up, so I need to be very generous when it comes to ratelimits
relativeTime = true
)
val genericCmds: Seq[ParsedCmdFactory[_, NotUsed]] = {
import GenericCommands._
Seq(
PingCmdFactory,
SendFileCmdFactory,
InfoChannelCmdFactory,
TimeDiffCmdFactory,
RatelimitTestCmdFactory(
"Ratelimit test",
Seq("ratelimitTest"),
requests.sinkIgnore
),
RatelimitTestCmdFactory(
"Ordered Ratelimit test",
Seq("ratelimitTestOrdered"),
requests.sinkIgnore(RequestHelper.RequestProperties.ordered)
),
KillCmdFactory
)
}
val controllerCommands: Seq[NewCommandsEntry[NotUsed]] = {
val controller = new NewCommandsController(requests)
Seq(
NewCommandsEntry(controller.hello, newcommands.CommandDescription("Hello", "Say hello")),
NewCommandsEntry(controller.copy, newcommands.CommandDescription("Copy", "Make the bot say what you said")),
NewCommandsEntry(
controller.guildInfo,
newcommands.CommandDescription("Guild info", "Prints info about the current guild")
),
NewCommandsEntry(
controller.parsingNumbers,
newcommands.CommandDescription("Parse numbers", "Have the bot parse two numbers")
),
NewCommandsEntry(
controller.adminsOnly,
newcommands.CommandDescription("Elevanted command", "Command only admins can use")
),
NewCommandsEntry(
controller.timeDiff,
newcommands.CommandDescription("Time diff", "Checks the time between sending and seeing a message")
),
NewCommandsEntry(controller.ping, newcommands.CommandDescription("Ping", "Checks if the bot is alive")),
NewCommandsEntry(
controller.maybeFail,
newcommands.CommandDescription("MaybeFail", "A command that sometimes fails and throws an exception")
)
)
}
private val helpMonitor = context.spawn[HelpCmd.HandlerReply](
Behaviors.receiveMessage {
case HelpCmd.CommandTerminated(_) => Behaviors.same
case HelpCmd.NoCommandsRemaining =>
context.self ! CommandsUnregistered
Behaviors.same
},
"HelpMonitor"
)
val helpCmdActor: ActorRef[ExampleHelpCmd.Command] = context.spawn(ExampleHelpCmd(requests, helpMonitor), "HelpCmd")
val helpCmd = ExampleHelpCmdFactory(helpCmdActor)
val killSwitch: SharedKillSwitch = KillSwitches.shared("Commands")
//We set up a commands object, which parses potential commands
//If you wanted to be fancy, you could use a valve here to stop new commands when shutting down
//Here we just shut everything down at once
val cmdObj: Commands =
CoreCommands
.create(
CommandSettings(needsMention = true, prefixes = Set("!", "&")),
cache.subscribeAPI.via(killSwitch.flow),
requests
)
._2
val commandConnector = new newcommands.CommandConnector(
cache.subscribeAPI
.collectType[APIMessage.MessageCreate]
.map(m => m.message -> m.cache.current)
.via(killSwitch.flow),
requests
)
def registerCmd[Mat](parsedCmdFactory: ParsedCmdFactory[_, Mat]): Mat =
ExampleMain.registerCmd(cmdObj, helpCmdActor)(parsedCmdFactory)
def registerNewCommand[Mat](entry: NewCommandsEntry[Mat]): Mat =
ExampleMain.registerNewCommand(commandConnector, helpCmdActor)(entry)
genericCmds.foreach(registerCmd)
controllerCommands.foreach(registerNewCommand)
registerCmd(helpCmd)
//Here is an example for a raw simple command
cmdObj.subscribeRaw
.collect {
case RawCmd(_, "!", "restart", _, _) => println("Restart Starting")
}
.runForeach(_ => context.self ! RestartShard)
private val registerCmdObjMusic = new FunctionK[MusicHandler.MatCmdFactory, cats.Id] {
override def apply[A](fa: MusicHandler.MatCmdFactory[A]): A = registerCmd(fa)
}
val guildRouterMusic: ActorRef[GuildRouter.Command[APIMessage, MusicHandler.Command]] = {
context.spawn(
APIGuildRouter.partitioner(
None,
MusicHandler(requests, registerCmdObjMusic, cache),
None,
GuildRouter.OnShutdownSendMsg(MusicHandler.Shutdown)
),
"MusicHandler"
)
}
val killSwitchMusicHandler: UniqueKillSwitch = cache.subscribeAPI
.viaMat(KillSwitches.single)(Keep.right)
.collect {
case ready: APIMessage.Ready => GuildRouter.EventMessage(ready)
case create: APIMessage.GuildCreate => GuildRouter.EventMessage(create)
}
.to(ActorSink.actorRef(guildRouterMusic, GuildRouter.Shutdown, _ => GuildRouter.Shutdown))
.run()
shard ! DiscordShard.StartShard
private var shutdownCount = 0
private var isShuttingDown = false
private var doneSender: ActorRef[Done] = _
private val shutdown = CoordinatedShutdown(system.toClassic)
shutdown.addTask("before-service-unbind", "begin-deathwatch") { () =>
implicit val timeout: Timeout = Timeout(shutdown.timeout("before-service-unbind"))
context.self.ask[Done](ExampleMain.BeginDeathwatch)
}
shutdown.addTask("service-unbind", "unregister-commands") { () =>
implicit val timeout: Timeout = Timeout(shutdown.timeout("service-unbind"))
context.self.ask[Done](ExampleMain.UnregisterCommands)
}
shutdown.addTask("service-requests-done", "stop-help-command") { () =>
val timeout = shutdown.timeout("service-requests-done")
gracefulStop(helpCmdActor.toClassic, timeout).map(_ => Done)
}
shutdown.addTask("service-requests-done", "stop-music") { () =>
implicit val timeout: Timeout = Timeout(shutdown.timeout("service-requests-done"))
context.self.ask[Done](ExampleMain.StopMusic)
}
shutdown.addTask("service-stop", "stop-discord") { () =>
implicit val timeout: Timeout = Timeout(shutdown.timeout("service-stop"))
context.self.ask[Done](StopShard)
}
override def onMessage(msg: Command): Behavior[Command] = {
msg match {
case RestartShard =>
shard ! DiscordShard.RestartShard
case CommandsUnregistered =>
if (isShuttingDown) {
doneSender ! Done
doneSender = null
}
case ExampleMain.BeginDeathwatch(replyTo) =>
isShuttingDown = true
context.watch(shard)
context.watch(guildRouterMusic)
replyTo ! Done
case ExampleMain.UnregisterCommands(replyTo) =>
doneSender = replyTo
killSwitch.shutdown()
case ExampleMain.StopMusic(replyTo) =>
doneSender = replyTo
killSwitchMusicHandler.shutdown()
case StopShard(replyTo) =>
doneSender = replyTo
shard ! DiscordShard.StopShard
}
Behaviors.same
}
override def onSignal: PartialFunction[Signal, Behavior[Command]] = {
case Terminated(act) if isShuttingDown =>
shutdownCount += 1
log.info("Actor shut down: {} Shutdown count: {}", act.path, shutdownCount)
doneSender ! Done
doneSender = null
if (shutdownCount == 2) {
//context.stop(self)
}
Behaviors.same
}
}
object ExampleMain {
def registerCmd[Mat](commands: Commands, helpActor: ActorRef[ExampleHelpCmd.Command])(
parsedCmdFactory: ParsedCmdFactory[_, Mat]
): Mat = {
val (complete, materialized) = commands.subscribe(parsedCmdFactory)(Keep.both)
(parsedCmdFactory.refiner, parsedCmdFactory.description) match {
case (info: AbstractCmdInfo, Some(description)) =>
helpActor ! ExampleHelpCmd.BaseCommandWrapper(HelpCmd.AddCmd(info, description, complete))
case _ =>
}
import scala.concurrent.ExecutionContext.Implicits.global
complete.foreach { _ =>
println(s"Command completed: ${parsedCmdFactory.description.get.name}")
}
materialized
}
sealed trait Command
case class BeginDeathwatch(replyTo: ActorRef[Done]) extends Command
case class UnregisterCommands(replyTo: ActorRef[Done]) extends Command
case class StopMusic(replyTo: ActorRef[Done]) extends Command
case class StopShard(replyTo: ActorRef[Done]) extends Command
case object RestartShard extends Command
case object CommandsUnregistered extends Command
//Ass of now, you are still responsible for binding the command logic to names and descriptions yourself
case class NewCommandsEntry[Mat](
command: newcommands.NamedComplexCommand[_, Mat],
description: newcommands.CommandDescription
)
def registerNewCommand[Mat](connector: newcommands.CommandConnector, helpActor: ActorRef[ExampleHelpCmd.Command])(
entry: NewCommandsEntry[Mat]
): Mat = {
val (materialized, complete) =
connector.runNewNamedCommand(entry.command)
//Due to the new commands being a complete break from the old ones, being
// completely incompatible with some other stuff, we need to do a bit of
// translation and hackery here
helpActor ! ExampleHelpCmd.BaseCommandWrapper(
HelpCmd.AddCmd(
commands.CmdInfo(entry.command.symbol, entry.command.aliases),
commands.CmdDescription(
entry.description.name,
entry.description.description,
entry.description.usage,
entry.description.extra
),
complete
)
)
import scala.concurrent.ExecutionContext.Implicits.global
complete.foreach { _ =>
println(s"Command completed: ${entry.description.name}")
}
materialized
}
}
|
Katrix-/AckCord
|
exampleCore/src/main/scala/ackcord/examplecore/Example.scala
|
Scala
|
mit
| 13,514 |
/*
* Copyright (c) 2015,
* Ilya Sergey, Christopher Earl, Matthew Might and David Van Horn
* 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 the project "Reachability" 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 PROVIDED 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.
*/
package org.ucombinator.lambdajs.parsing
import org.ucombinator.lambdajs.parsing.LambdaJSTokens._
import org.ucombinator.lambdajs.syntax.LJSyntax._
/**
* @author ilya
*/
class LambdaJSParser {
private var maxSerialNumber = 1
def newStamp(): Int = {
maxSerialNumber += 1
maxSerialNumber
}
type Result[T] = (Either[T, String], List[LJToken])
def success[T](e: T, rest: List[LJToken]): Result[T] = (Left(e), rest)
def failure[T](s: String, rest: List[LJToken]): Result[Nothing] = {
(Right(s), rest)
}
val RESERVED_NAMES: Set[String] = Set(
"$makeException", "@newDirect"
)
def isBound(s: String, map: Map[String, Var]): Boolean = map.keySet.contains(s)
def isFailure[T](r: Result[T]) = r match {
case (Right(_), _) => true
case _ => false
}
/**
* Close parenthesis
*/
def closePar[T](pair: (Either[T, String], List[LJToken])): Result[T] = pair match {
case (r, rest) if r.isRight => pair
case (r, rest) => rest match {
case RPar :: tail => (r, tail)
case x :: tail => {
val msg = "')' expected, but " + x.toString + " is found"
failure(msg, rest)
}
case Nil => {
val msg = "')' expected, but input is empty"
failure(msg, rest)
}
}
}
def extract[T](r: Result[T]): (T, List[LJToken]) = r match {
case (Left(t: T), rest) => (t, rest)
}
def getRest[T](r: Result[T]) = r._2
def params(input: List[LJToken]): Result[List[String]] = input match {
case LPar :: rest => {
val (pre, rest1) = rest.span(_.isInstanceOf[TIdent])
success(pre.map {
case TIdent(s) => s
}, rest1)
}
case _ => failure("'(' expected", input)
}
def lambda(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val psResult = closePar(params(input))
if (isFailure(psResult)) {
failure("Parameters parsing failed", getRest(psResult))
} else {
val (ids, rest) = extract(psResult)
val vars = ids.map {
case s => Var(s, newStamp())
}
val newBound = vars.filter(_.stamp > 0).map(v => (v.name, v)).toSet
val bodyResult = exp(rest, bv ++ newBound)
if (isFailure(bodyResult)) {
bodyResult
} else {
val (body, rest1) = extract(bodyResult)
success(Fun(vars, body, newStamp()), rest1)
}
}
}
def entry(input: List[LJToken], bv: Map[String, Var]): Result[(String, Exp)] = input match {
case Nil => failure("No entry", input)
case LPar :: TString(s) :: rest => {
val result = exp(rest, bv)
if (isFailure(result)) {
failure("Entry expression failed", getRest(result))
} else {
val (e, rest1) = extract(result)
closePar(success((s, e), rest1))
}
}
}
def record(input: List[LJToken], bv: Map[String, Var]): Result[Record] = {
var rest = input
var ets: List[(String, Exp)] = List()
while (!rest.isEmpty && rest.head == LPar &&
!rest.tail.isEmpty && rest.tail.head.isInstanceOf[TString]) {
val result = entry(rest, bv)
if (isFailure(result)) {
return failure("Entry parsing failed", getRest(result))
} else {
val (ent, rr) = extract(result)
ets = ent :: ets
rest = rr
}
}
success(Record(ets.reverse, newStamp()), rest)
}
def isReservedName(name: String): Boolean = {
RESERVED_NAMES.contains(name)
}
def binding(input: List[LJToken], bv: Map[String, Var]): Result[(Var, Exp)] = input match {
case Nil => failure("No binding", input)
case LPar :: TIdent(name) :: rest => {
val result = exp(rest, bv)
if (isFailure(result)) {
failure("Binding expression failed", getRest(result))
} else {
val (e, rest1) = extract(result)
val binder = if (isReservedName(name)) {
Var(name, 0)
} else {
Var(name, newStamp())
}
closePar(success((binder, e), rest1))
}
}
}
def let(in: List[LJToken], bv: Map[String, Var]): Result[Exp] = in match {
case LPar :: input => {
var rest = input
var bindings: List[(Var, Exp)] = List()
while (!rest.isEmpty && rest.head == LPar &&
!rest.tail.isEmpty && rest.tail.head.isInstanceOf[TIdent]) {
val result = binding(rest, bv)
if (isFailure(result)) {
return failure("Binding parsing failed", getRest(result))
} else {
val (bind, rr) = extract(result)
bindings = bind :: bindings
rest = rr
}
}
// done with bindings
val newBound = bindings.map(_._1).filter(_.stamp > 0).map(v => (v.name, v)).toSet
rest match {
case RPar :: rest1 => {
val eres = exp(rest1, bv ++ newBound)
if (isFailure(eres)) {
failure("Faled body parsing expression", input)
} else {
val (body, rest2) = extract(eres)
val letResult = bindings.foldRight(body) {
case ((x, e), acc) => Let(x, e, acc, newStamp())
}
success(letResult, rest2)
}
}
case _ => failure("')' expected", rest)
}
}
case _ => failure("'(' expected", in)
}
def twoExpressions(input: List[LJToken], bv: Map[String, Var]): Result[(Exp, Exp)] = {
val result = exp(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (e1, rest) = extract(result)
val result2 = exp(rest, bv)
if (isFailure(result2)) {
failure("Faled parsing expression", rest)
} else {
val (e2, rest2) = extract(result2)
success((e1, e2), rest2)
}
}
}
def threeExpressions(input: List[LJToken], bv: Map[String, Var]): Result[(Exp, Exp, Exp)] = {
val result = exp(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (e1, rest) = extract(result)
val result2 = exp(rest, bv)
if (isFailure(result2)) {
failure("Faled parsing expression", rest)
} else {
val (e2, rest2) = extract(result2)
val result3 = exp(rest2, bv)
if (isFailure(result2)) {
failure("Faled parsing expression", rest)
} else {
val (e3, rest3) = extract(result3)
success((e1, e2, e3), rest3)
}
}
}
}
def ref(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = exp(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (e, rest) = extract(result)
success(Ref(e, newStamp()), rest)
}
}
def deref(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = exp(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (e, rest) = extract(result)
success(Deref(e, newStamp()), rest)
}
}
def pthrow(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = exp(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (e, rest) = extract(result)
success(Throw(e, newStamp()), rest)
}
}
def asgn(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = twoExpressions(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (ee, rest) = extract(result)
success(Asgn(ee._1, ee._2, newStamp()), rest)
}
}
def lookup(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = twoExpressions(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (ee, rest) = extract(result)
success(Lookup(ee._1, ee._2, newStamp()), rest)
}
}
def delete(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = twoExpressions(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (ee, rest) = extract(result)
success(Del(ee._1, ee._2, newStamp()), rest)
}
}
def label(lab: String, input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = exp(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (e, rest) = extract(result)
success(Labelled(lab, e, newStamp()), rest)
}
}
def break(lab: String, input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = exp(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (e, rest) = extract(result)
success(Break(lab, e, newStamp()), rest)
}
}
def seq(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = twoExpressions(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (ee, rest) = extract(result)
success(Seq(ee._1, ee._2, newStamp()), rest)
}
}
def pwhile(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = twoExpressions(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (ee, rest) = extract(result)
success(While(ee._1, ee._2, newStamp()), rest)
}
}
def tryCatch(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = twoExpressions(input, bv) //parse try-catch and finally as two exprs
if (isFailure(result)) {
failure("Faled parsing try-catch of finally in try-catch-finally", input)
} else {
val ((e1, e2), rest) = extract(result)
e2 match {
case Fun(List(x), body, stamp) => success(TryCatch(e1, x, body, stamp), rest)
case notLambda => {
failure("Catch-clause is not well-formed lambda: " + notLambda, input)
}
}
}
}
def tryFinally(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = twoExpressions(input, bv) //parse try-catch and finally as two exprs
if (isFailure(result)) {
failure("Faled parsing try-catch of finally in try-catch-finally", input)
} else {
val ((e1, e2), rest) = extract(result)
e1 match {
case TryCatch(_, _, _, _) => success(TryFinally(e1, e2, newStamp()), rest)
case notCatch => {
failure("Catch-part is not well-formed: " + notCatch, input)
}
}
}
}
def pif(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = threeExpressions(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (ee, rest) = extract(result)
success(If(ee._1, ee._2, ee._3, newStamp()), rest)
}
}
def update(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = threeExpressions(input, bv)
if (isFailure(result)) {
failure("Faled parsing expression", input)
} else {
val (ee, rest) = extract(result)
success(Update(ee._1, ee._2, ee._3, newStamp()), rest)
}
}
def repExp(input: List[LJToken], bv: Map[String, Var]): Result[List[Exp]] = {
var exprs: List[Exp] = List()
var rest = input
def loop() {
val result = exp(rest, bv)
if (!isFailure(result)) {
val (e, rest1) = extract(result)
exprs = e :: exprs
rest = rest1
loop()
}
}
loop()
success(exprs.reverse, rest)
}
def opApp(op: String, input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = repExp(input, bv)
if (isFailure(result)) {
failure("Faled parsing several expressions", input)
} else {
val (ee, rest) = extract(result)
val stamp = newStamp()
success(OpApp(Op(op, stamp), ee, stamp), rest)
}
}
def app(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
val result = exp(input, bv)
if (isFailure(result)) {
failure("Faled parsing callee", input)
} else {
val (e, rest) = extract(result)
val result1 = repExp(rest, bv)
if (isFailure(result1)) {
failure("Faled parsing arguments", input)
} else {
val (args, rest1) = extract(result1)
success(App(e, args, newStamp()), rest1)
}
}
}
val eval_bomb = "eval-semantic-bomb"
/**
* Parse complex expressions
*/
def realExp(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = input match {
case Nil => failure("Undexpected end of input", input)
case TLambda :: rest => lambda(rest, bv)
case TRec :: rest => record(rest, bv)
case TRef :: rest => ref(rest, bv)
case TDeref :: rest => deref(rest, bv)
case TThrow :: rest => deref(rest, bv)
case TAsgn :: rest => asgn(rest, bv)
case TIndex :: rest => lookup(rest, bv)
case TWhile :: rest => pwhile(rest, bv)
case TTryCatch :: rest => tryCatch(rest, bv)
case TTryFinally :: rest => tryFinally(rest, bv)
case TSeq :: rest => seq(rest, bv)
case TDel :: rest => delete(rest, bv)
case TIf :: rest => pif(rest, bv)
case TUpdate :: rest => update(rest, bv)
case TBreak :: TIdent(l) :: rest => break(l, rest, bv)
case TLabel :: TIdent(l) :: rest => label(l, rest, bv)
case TOp(op) :: rest => opApp(op, rest, bv)
case TLet :: rest => let(rest, bv)
case TIdent(_) :: _ => app(input, bv)
case LPar :: _ => app(input, bv)
case _ => {
failure("Wrong input!", input)
}
}
def exp(input: List[LJToken], bv: Map[String, Var]): Result[Exp] = {
input match {
case Nil => failure("Undexpected end of input", input)
case h :: t => h match {
case TString(s) => success(EString(s), t)
case TFloat(f) => success(EFloat(f), t)
case TTrue => success(EBool(true), t)
case TFalse => success(EBool(false), t)
case TUndef => success(EUndef, t)
case TNull => success(ENull, t)
case TOp("eval-semantic-bomb") => success(EEval, t)
case TNan => success(ENan, t)
case TInfP => success(EInfP, t)
case TInfM => success(EInfM, t)
case TIdent(id) => {
val v = if (isBound(id, bv)) {
bv(id)
} else if (isReservedName(id)) {
Var(id, 0)
} else {
System.err.println("Unbound variable: " + id)
Var(id, 0)
}
success(v, t)
}
case LPar => {
closePar(realExp(t, bv))
}
case _ => failure("NYI", input)
}
}
}
def parseAll(input: List[LJToken]): Exp = {
val (result, rest) = exp(input, Map.empty)
if (result.isLeft && rest.isEmpty) {
val Left(r) = result
r
} else {
throw new Exception("Parsing failed on a token " + rest.head)
}
}
def parseText(text: String): Exp = {
val lexer = new LambdaJSLexer
val input = lexer.parseAll(text)
val (result, rest) = exp(input, Map.empty)
if (result.isLeft && rest.isEmpty) {
val Left(r) = result
r
} else {
throw new Exception("Parsing failed on a token " + rest.head)
}
}
def parseAllIn(filename: String): Exp = {
System.err.println("Reading file...")
val firstTime = (new java.util.Date()).getTime
val lexer = new LambdaJSLexer
val input = lexer.parseAllIn(filename)
val secondTime = (new java.util.Date()).getTime
val delta = secondTime - firstTime
System.err.println("Input read in " + delta + " ms.")
parseAll(input)
}
}
|
ilyasergey/reachability
|
src/org/ucombinator/lambdajs/parsing/LambdaJSParser.scala
|
Scala
|
bsd-3-clause
| 17,245 |
package com.caibowen.webface.gae.store
import java.util.{ArrayList => JArrList, HashMap => JHashMap, HashSet => JHashSet, List => JList, Map => JMap, Set => JSet}
import com.caibowen.gplume.misc.Str.Utils
import com.caibowen.webface.gae.R
import com.caibowen.webface.gae.misc.ReqLocation
import com.google.appengine.api.datastore.Query.GeoRegion.Rectangle
import com.google.appengine.api.datastore.Query._
import com.google.appengine.api.datastore._
import net.liftweb.json.{DefaultFormats, Serialization}
import org.slf4j.LoggerFactory
import scala.beans.BeanProperty
import scala.collection.{Iterable, mutable}
import scala.collection.convert.{wrapAsJava, wrapAsScala}
import scala.collection.mutable.ArrayBuffer
/**
* all data (parameters) coming in to this components are assumed correct and
* no more parameter-check is performed here, i.e., checking is done on upper caller
*
* read operation may throw exceptions whereas write ops will not (report error by return value)
*
* Created by Bowen Cai on 9/5/2015.
*/
class VisitCount extends Serializable {
val LOG = LoggerFactory.getLogger(this.getClass)
val kind = R.db.kind_reqLocation
val ds: DatastoreService = DatastoreServiceFactory.getDatastoreService
@BeanProperty
var bufSize: Int = 10
@BeanProperty
var timeIntervalVisit: Long = 1000L * 60 * 5
@BeanProperty
var fetchSize: Int = 1024
lazy val maxFetch = FetchOptions.Builder.withLimit(fetchSize)
val buf = new JArrList[Entity](64)
val ipMap = new java.util.concurrent.ConcurrentHashMap[String, Long](1024)
/**
* if two or more visits happened within 5 min, ignore the new visits
*
* @param loc
*/
def add(loc: ReqLocation): Unit = {
val lastTime = ipMap.put(loc.ip, loc.timestamp)
if (lastTime != null.asInstanceOf[Long]) {
if (loc.timestamp - lastTime > timeIntervalVisit)
pushBack(loc) // very old visit
} else { // new visit
pushBack(loc)
}
}
/**
* add loc to buffer, flush buffer if size exceeded
*
* @param loc
*/
private def pushBack(loc: ReqLocation): Unit = {
val e = pack(loc)
buf.synchronized {
buf.add(e)
if (buf.size() > bufSize)
flush()
}
}
def flush(): Unit = buf.synchronized{
if (buf.size() > bufSize)
return
try {
ds.put(buf)
} catch {
case e: Exception =>
val json = if (buf != null && buf.size() > 0) {
Serialization.writePretty(buf.get(0))(DefaultFormats)
} else "Empty"
LOG.error("Could not bulk save visit count " + json, e)
}
buf.clear()
// ipMap.clear()
val oldestTime = System.currentTimeMillis() - timeIntervalVisit
val iter = ipMap.entrySet().iterator()
while (iter.hasNext) {
if (iter.next().getValue < oldestTime)
iter.remove()
}
}
/**
* util function, query by time period with processing
*
* @return
*/
private def fetchByTime(startTime: Long, endTime: Long, process: Query=>Unit): Iterable[Entity] = {
val timeRange = CompositeFilterOperator.and(
new FilterPredicate("timestamp", FilterOperator.GREATER_THAN_OR_EQUAL, startTime),
new FilterPredicate("timestamp", FilterOperator.LESS_THAN_OR_EQUAL, endTime))
val q = new Query(kind).setFilter(timeRange)
process(q)
val rs = ds.prepare(q)
wrapAsScala.iterableAsScalaIterable(rs.asIterable(maxFetch))
}
def clearTime(start: Long, end: Long): Boolean = try {
val ls = fetchByTime(start, end, (q: Query) => q.setKeysOnly())
ds delete wrapAsJava.asJavaIterable(ls.map(_.getKey))
// val keys = new JArrList[Key](ls.size)
// for (i <- ls)
// keys.add(i.getKey)
// ds.delete(keys)
LOG.trace(s"deleted visit count by time from $start to $end, count: ${ls.size}")
true
} catch {
case e: Exception =>
LOG.error(s"failed to delete visit count by time from $start to $end", e)
false
}
def clearKind(kname: String): Int = {
var count = 0
var bulkSz = 1
val startTime = System.currentTimeMillis()
try {
while (System.currentTimeMillis() - startTime < 7000 && bulkSz > 0) {
val rs = ds.prepare(new Query(kname).setKeysOnly())
val keys = wrapAsScala.iterableAsScalaIterable(rs.asIterable(maxFetch)).map(_.getKey)
bulkSz = keys.size
ds.delete(wrapAsJava.asJavaIterable(keys))
count += bulkSz
}
LOG.trace(s"try to clear kind [$kname], deleted $count")
} catch {
case e: Exception =>
LOG.trace(s"failed to clear kind [$kname], deleted $count, last bulk size $bulkSz")
}
count
}
def queryByTime(start: Long, end: Long): Iterable[ReqLocation] = {
val ls = fetchByTime(start, end, (q:Query)=> q.addSort("timestamp", SortDirection.DESCENDING))
// ls.map(unpack)
val buf = new ArrayBuffer[ReqLocation](ls.size)
for (i <- ls) {
buf += unpack(i)
}
buf
}
def query(startTime: Long, endTime: Long, qLoc: ReqLocation, sw: (Float, Float), ne: (Float, Float))
: Iterable[ReqLocation] = {
implicit val filters = appendFilters(startTime, endTime)(new ArrayBuffer[Query.Filter](8))
if (qLoc != null)
appendFilters(qLoc)
if (sw != null && ne != null)
appendFilters(sw._1, sw._2, ne._1, ne._2)
// val cf = CompositeFilterOperator.and(wrapAsJava.bufferAsJavaList(filters))
// val q = new Query(kind).setFilter(cf).addSort("timestamp", SortDirection.DESCENDING)
// val rs = ds.prepare(q)
// val ls = wrapAsScala.iterableAsScalaIterable(rs.asIterable(maxFetch))
// val buf = new ArrayBuffer[ReqLocation](ls.size)
// for (i <- ls) {
// buf += unpack(i)
// }
// buf
wrapAsScala.iterableAsScalaIterable(
ds.prepare(new Query(kind).setFilter( // 3
CompositeFilterOperator.and(wrapAsJava.bufferAsJavaList(filters)) // 1
).addSort("timestamp", SortDirection.DESCENDING) // 2
).asIterable(maxFetch)
).map(unpack)
}
private def appendFilters(startTime: Long, endTime: Long)
(implicit filters: ArrayBuffer[Query.Filter]) : ArrayBuffer[Query.Filter] = {
if (startTime >= 0)
filters += new FilterPredicate("timestamp", FilterOperator.GREATER_THAN_OR_EQUAL, startTime)
if (endTime > 0 && endTime > startTime)
filters += new FilterPredicate("timestamp", FilterOperator.LESS_THAN_OR_EQUAL, endTime)
filters
}
/*
<code> Testing for containment within a rectangle
GeoPt southwest = ...
GeoPt northeast = ...
Filter f = new StContainsFilter("location", new Rectangle(southwest, northeast));
Query q = new Query("Kind").setFilter(f); </code>
* @param neLatitude latitude of the north east point
* @param neLongitude longitude of the north east point
*/
/**
*
* @param swLatitude
* @param swLongitude south west point
* @param neLatitude north east point
* @param neLongitude
* @param filters
* @return
*/
private def appendFilters(swLatitude: Float, swLongitude: Float, neLatitude: Float, neLongitude: Float)
(implicit filters: ArrayBuffer[Query.Filter]) : ArrayBuffer[Query.Filter] =
filters += new StContainsFilter("coordinate",
new Rectangle(new GeoPt(swLatitude, swLongitude),
new GeoPt(neLatitude, neLongitude)))
private def appendFilters(qLoc: ReqLocation)(implicit filters: ArrayBuffer[Query.Filter])
: ArrayBuffer[Query.Filter] = {
if (Utils.notBlank(qLoc.region))
filters += new FilterPredicate("region", FilterOperator.EQUAL, qLoc.region)
if (Utils.notBlank(qLoc.country))
filters += new FilterPredicate("country", FilterOperator.EQUAL, qLoc.country)
if (Utils.notBlank(qLoc.city))
filters += new FilterPredicate("city", FilterOperator.EQUAL, qLoc.city)
if (Utils.notBlank(qLoc.ip))
filters += new FilterPredicate("ip", FilterOperator.EQUAL, qLoc.ip)
filters
}
private def pack(loc: ReqLocation): Entity = {
val e = new Entity(kind)
e.setProperty("coordinate", new GeoPt(loc.latitude, loc.longitude))
e.setProperty("timestamp", loc.timestamp)
e.setProperty("region", loc.region)
e.setProperty("country", loc.country)
e.setProperty("city", loc.city)
e.setProperty("ip", loc.ip)
e
}
// case class ReqLocation(timestamp: Long, ip: String,
// country: String, region: String, city: String,
// latitude: Float,
// longitude: Float)
private def unpack(e: Entity): ReqLocation = {
val geo = e.getProperty("coordinate").asInstanceOf[GeoPt]
ReqLocation(e.getProperty("timestamp").asInstanceOf[Long],
e.getProperty("ip").asInstanceOf[String],
e.getProperty("country").asInstanceOf[String],
e.getProperty("region").asInstanceOf[String],
e.getProperty("city").asInstanceOf[String],
latitude = geo.getLatitude, longitude = geo.getLongitude)
}
}
|
xkommando/WebFace
|
src/com/caibowen/webface/gae/store/VisitCount.scala
|
Scala
|
apache-2.0
| 9,241 |
package io.finch.test.json
import argonaut.{CodecJson, DecodeJson, EncodeJson, Parse}
import argonaut.Argonaut.{casecodec3, casecodec5}
import com.twitter.io.Buf.Utf8
import com.twitter.io.Charsets
import com.twitter.util.Return
import io.finch.{Decode, Encode}
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen
import org.scalacheck.Prop.BooleanOperators
import org.scalatest.prop.Checkers
import org.scalatest.Matchers
case class ExampleCaseClass(a: String, b: Int, c: Boolean)
case class ExampleNestedCaseClass(
string: String,
double: Double,
long: Long,
ints: List[Int],
example: ExampleCaseClass
)
object ExampleCaseClass {
implicit val exampleCaseClassArbitrary: Arbitrary[ExampleCaseClass] = Arbitrary(
for {
a <- Gen.alphaStr
b <- arbitrary[Int]
c <- arbitrary[Boolean]
} yield ExampleCaseClass(a, b, c)
)
}
object ExampleNestedCaseClass {
implicit val exampleNestedCaseClassArbitrary: Arbitrary[ExampleNestedCaseClass] = Arbitrary(
for {
s <- Gen.alphaStr
d <- arbitrary[Double]
l <- arbitrary[Long]
i <- arbitrary[List[Int]]
e <- arbitrary[ExampleCaseClass]
} yield ExampleNestedCaseClass(s, d, l, i, e)
)
}
/**
* Provides tests that check properties about a library that provides JSON
* codecs for use in Finch.
*/
trait JsonCodecProviderProperties { self: Matchers with Checkers =>
import ArgonautCodecs._
/**
* Confirm that this encoder can encode instances of our case class.
*/
def encodeNestedCaseClass(implicit ee: Encode.Json[ExampleNestedCaseClass]): Unit =
check { (e: ExampleNestedCaseClass) =>
Parse.decodeOption(Utf8.unapply(ee(e, Charsets.Utf8)).get)(exampleNestedCaseClassCodecJson) ===
Some(e)
}
/**
* Confirm that this encoder can decode instances of our case class.
*/
def decodeNestedCaseClass(implicit decoder: Decode[ExampleNestedCaseClass]): Unit =
check { (e: ExampleNestedCaseClass) =>
decoder(exampleNestedCaseClassCodecJson.encode(e).nospaces) === Return(e)
}
/**
* Confirm that this encoder fails on invalid input (both ill-formed JSON and
* invalid JSON).
*/
def failToDecodeInvalidJson(implicit decoder: Decode[ExampleNestedCaseClass]): Unit = {
check { (badJson: String) =>
Parse.decodeOption(badJson)(exampleNestedCaseClassCodecJson).isEmpty ==>
decoder(badJson).isThrow
}
check { (e: ExampleCaseClass) =>
decoder(exampleCaseClassCodecJson.encode(e).nospaces).isThrow
}
}
/**
* Confirm that this encoder can encode top-level lists of instances of our case class.
*/
def encodeCaseClassList(implicit encoder: Encode.Json[List[ExampleNestedCaseClass]]): Unit =
check { (es: List[ExampleNestedCaseClass]) =>
Parse
.decodeOption(Utf8.unapply(encoder(es, Charsets.Utf8))
.getOrElse(""))(exampleNestedCaseClassListCodecJson) === Some(es)
}
/**
* Confirm that this encoder can decode top-level lists of instances of our case class.
*/
def decodeCaseClassList(implicit decoder: Decode[List[ExampleNestedCaseClass]]): Unit =
check { (es: List[ExampleNestedCaseClass]) =>
decoder(exampleNestedCaseClassListCodecJson.encode(es).nospaces) === Return(es)
}
/**
* Confirm that this encoder has the correct content type.
*/
def checkContentType(implicit ee: Encode.Json[ExampleNestedCaseClass]): Unit = ()
}
/**
* Provides trusted Argonaut codecs for evaluating the codecs provided by the
* target of our tests. Note that we are intentionally not defining the
* instances as implicits.
*/
object ArgonautCodecs {
val exampleCaseClassCodecJson: CodecJson[ExampleCaseClass] =
casecodec3(ExampleCaseClass.apply, ExampleCaseClass.unapply)("a", "b", "c")
val exampleNestedCaseClassCodecJson: CodecJson[ExampleNestedCaseClass] =
casecodec5(ExampleNestedCaseClass.apply, ExampleNestedCaseClass.unapply)(
"string",
"double",
"long",
"ints",
"example"
)(
implicitly,
implicitly,
implicitly,
implicitly,
implicitly,
implicitly,
implicitly,
implicitly,
exampleCaseClassCodecJson,
exampleCaseClassCodecJson
)
val exampleNestedCaseClassListCodecJson: CodecJson[List[ExampleNestedCaseClass]] =
CodecJson.derived(
EncodeJson.fromFoldable[List, ExampleNestedCaseClass](
exampleNestedCaseClassCodecJson,
scalaz.std.list.listInstance
),
DecodeJson.CanBuildFromDecodeJson[ExampleNestedCaseClass, List](
exampleNestedCaseClassCodecJson,
implicitly
)
)
}
|
ilya-murzinov/finch
|
json-test/src/main/scala/io/finch/test/json/JsonCodecProviderProperties.scala
|
Scala
|
apache-2.0
| 4,673 |
package com.github.chawasit.smc.simulator
trait TryWith {
def TryWith[T](guards: Guard*)(block: => T): T = {
guards foreach {_.execute()}
block
}
case class Guard(condition: Boolean, exception: Throwable) {
def execute(): Unit = if (!condition) throw exception
}
}
|
chawasit/Scala-SMC-Simulator
|
src/main/scala/com/github/chawasit/smc/simulator/TryWith.scala
|
Scala
|
unlicense
| 301 |
package scala.generator
import com.bryzek.apidoc.spec.v0.models.{Field, Model}
object PrimitiveWrapper {
val FieldName = "value"
def className(union: ScalaUnion, primitive: ScalaPrimitive): String = {
primitive match {
case ScalaPrimitive.Boolean | ScalaPrimitive.Double | ScalaPrimitive.Integer | ScalaPrimitive.Long | ScalaPrimitive.DateIso8601 | ScalaPrimitive.DateTimeIso8601 | ScalaPrimitive.Decimal | ScalaPrimitive.Object | ScalaPrimitive.String | ScalaPrimitive.Unit | ScalaPrimitive.Uuid => {
ScalaUtil.toClassName(union.name) + ScalaUtil.toClassName(primitive.shortName)
}
case ScalaPrimitive.Model(_, _) | ScalaPrimitive.Enum(_, _) | ScalaPrimitive.Union(_, _) => {
ScalaUtil.toClassName(union.name)
}
}
}
}
case class PrimitiveWrapper(ssd: ScalaService) {
case class Wrapper(model: ScalaModel, union: ScalaUnion)
private[this] val primitives = ssd.unions.flatMap(_.types).map(_.datatype).collect {
case p: ScalaPrimitive => p
}.filter(isBasicType(_)).sortWith(_.shortName < _.shortName)
val wrappers: Seq[Wrapper] = ssd.unions.flatMap { union =>
union.types.map(_.datatype).collect {
case p: ScalaPrimitive => p
}.filter(isBasicType(_)).sortWith(_.shortName < _.shortName).map { p =>
val name = PrimitiveWrapper.className(union, p)
val model = Model(
name = name,
plural = s"${name}s",
description = Some(s"Wrapper class to support the union types containing the datatype[${p.apidocType}]"),
fields = Seq(
Field(
name = PrimitiveWrapper.FieldName,
`type` = p.apidocType,
required = true
)
)
)
new Wrapper(
new ScalaModel(ssd, model),
union
)
}
}
private def isBasicType(primitive: ScalaPrimitive): Boolean = {
primitive match {
case ScalaPrimitive.Model(_, _) | ScalaPrimitive.Enum(_, _) | ScalaPrimitive.Union(_, _) => {
false
}
case ScalaPrimitive.Boolean | ScalaPrimitive.Double | ScalaPrimitive.Integer | ScalaPrimitive.Long | ScalaPrimitive.DateIso8601 | ScalaPrimitive.DateTimeIso8601 | ScalaPrimitive.Decimal | ScalaPrimitive.Object | ScalaPrimitive.String | ScalaPrimitive.Unit | ScalaPrimitive.Uuid => {
true
}
}
}
}
|
movio/movio-apidoc-generator
|
scala-generator/src/main/scala/models/generator/PrimitiveWrapper.scala
|
Scala
|
mit
| 2,329 |
/*
* Copyright 2016 The BigDL Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intel.analytics.bigdl.nn
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.T
import org.scalatest.{FlatSpec, Matchers}
class MeanSpec extends FlatSpec with Matchers {
"mean" should "work correctly" in {
val input = Tensor[Float](T(
T(1.0f, 2.0f),
T(3.0f, 4.0f)
))
val layer = Mean[Float](dimension = 2)
val expect = Tensor[Float](T(1.5f, 3.5f))
layer.forward(input) should be(expect)
}
"mean" should "work correctly without squeeze" in {
val input = Tensor[Float](T(
T(1.0f, 2.0f),
T(3.0f, 4.0f)
))
val layer = Mean[Float](dimension = 2, squeeze = false)
val expect = Tensor[Float](T(T(1.5f), T(3.5f)))
layer.forward(input) should be(expect)
}
}
|
JerryYanWan/BigDL
|
spark/dl/src/test/scala/com/intel/analytics/bigdl/nn/MeanSpec.scala
|
Scala
|
apache-2.0
| 1,378 |
/**
* Copyright 2013 Genome Bridge LLC
*
* 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 edu.berkeley.cs.amplab.adam.util
import java.io.{StringWriter, Writer}
import edu.berkeley.cs.amplab.adam.metrics.aggregators.Aggregated
class Histogram[T](val valueToCount: Map[T, Int]) extends Aggregated[T] with Serializable {
/**
* Counts the total number of elements that went into the histogram
* @return
*/
def count() : Long = valueToCount.values.map(_.toLong).reduce(_ + _)
def countIdentical() : Long = countSubset(defaultFilter)
/**
* Counts the number of values in the Histogram whose keys pass the given predicate function, f.
* @param f Only those keys k for which f(k) == true will be counted.
* @return The sum of the values passed by the predicate.
*/
def countSubset(f : (Any) => Boolean) : Long = valueToCount.filter {
case (k : T, v : Int) => f(k)
}.values.map(_.toLong).reduce(_+_)
private def defaultFilter(x : Any) : Boolean = {
x match {
case (x1 : Any, x2 : Any) => x1 == x2
case i : Int => i == 0
case l : Long => l == 0L
case b : Boolean => b
case _ => false
}
}
def ++(other: Histogram[T]): Histogram[T] = {
val map = collection.mutable.HashMap[T, Int]()
valueToCount foreach map.+=
other.valueToCount foreach(kv => {
val newValue = map.getOrElse(kv._1, 0) + kv._2
map(kv._1) = newValue
})
new Histogram[T](map.toMap)
}
def +(value : T) : Histogram[T] = {
val map =
if(valueToCount.contains(value))
(valueToCount - value) + (value -> (valueToCount(value) + 1))
else
valueToCount ++ Map(value -> 1)
new Histogram[T](map)
}
def write(stream : Writer) {
stream.append("value\\tcount\\n")
for( (value, count) <- valueToCount ) {
stream.append("%s\\t%d\\n".format(value.toString, count))
}
}
override def toString : String = {
val stringWriter : StringWriter = new StringWriter()
write(stringWriter)
stringWriter.toString
}
}
object Histogram {
def apply[T](valueToCount : Map[T,Int]) : Histogram[T] =
new Histogram[T](valueToCount)
def apply[T]() : Histogram[T] =
new Histogram[T](Map())
def apply[T](value: T): Histogram[T] =
new Histogram[T](Map((value, 1)))
def apply[T](values : Seq[T]) : Histogram[T] = {
new Histogram(Map(values.map( v => (v, 1) ) : _*))
}
}
|
fnothaft/adam
|
adam-core/src/main/scala/edu/berkeley/cs/amplab/adam/util/Histogram.scala
|
Scala
|
apache-2.0
| 2,928 |
package org.phasanix.svggraph
import java.awt.Color
import java.awt.geom.{Point2D, Rectangle2D}
import RichColor.color2richcolor
/**
* Configuration options.
*
* Measurements are all in px.
*/
case class Options (
layout: Options.Layout,
font: Options.Font,
draw: Options.Draw
) {
def plotArea: Rectangle2D.Float = layout.plotArea
def strokeWidth: Float = draw.strokeWidth
}
object Options {
/** Basic set of options */
def basic: Options = Options (
Layout.basic(chartWidth = 500, chartHeight = 300),
Font.basic(),
Draw.basic()
)
/**
* Chart layout. Chart regions are expressed as Rectangle2D, with measurements
* in px, and the origin of the coordinate system is at the bottom left of the
* chart area.
*
* @param chartWidth width of graph, in px.
* @param chartHeight height of graph, in px.
* @param xTickMargin height of x axis margin.
* @param yTickMarginLeft width of left y axis margin.
* @param yTickMarginRight width of right y axis margin (if any).
* @param plotMargin reserved space around plot area to accommodate
* points that fall on the x or y axis.
*/
case class Layout (
chartWidth: Int,
chartHeight: Int,
xTickMargin: Int,
yTickMarginLeft: Int,
yTickMarginRight: Int,
plotMargin: Int
) {
/** Area of whole chart */
def chartArea: Rectangle2D.Float = new Rectangle2D.Float(0f, 0f, chartWidth, chartHeight)
/** Area where chart contents are plotted */
def plotArea: Rectangle2D.Float = {
val x = yTickMarginLeft + plotMargin
val y = xTickMargin + plotMargin
new Rectangle2D.Float(x, y, chartWidth - x - plotMargin - yTickMarginRight, chartHeight - y)
}
/** Area of x axis title and tick marks */
def xTickArea: Rectangle2D.Float =
new Rectangle2D.Float(yTickMarginLeft + plotMargin, 0, chartWidth - yTickMarginLeft - yTickMarginRight - (2*plotMargin), xTickMargin)
/** Area of left y axis title and tick marks */
def yTickAreaLeft: Rectangle2D.Float =
new Rectangle2D.Float(0, xTickMargin + plotMargin, yTickMarginLeft, chartHeight - xTickMargin - plotMargin)
/** Area of left y axis title and tick marks */
def yTickAreaRight: Rectangle2D.Float =
new Rectangle2D.Float(chartWidth - yTickMarginRight, xTickMargin + plotMargin, yTickMarginRight, chartHeight - xTickMargin - plotMargin)
def origin: Point2D.Float = new Point2D.Float(yTickMarginLeft + plotMargin, xTickMargin + plotMargin)
}
object Layout {
private def orDefault(value: Int, defaultValue: Int): Int = if (value == -1) defaultValue else value
/** Basic set of layout options */
def basic(chartWidth: Int, chartHeight: Int, xTickMargin: Int = -1, yTickMarginLeft: Int = -1, yTickMarginRight: Int = -1, plotMargin: Int = -1): Layout = {
val xtm = orDefault(xTickMargin, Math.min(chartHeight/5, 50))
val ytml = orDefault(yTickMarginLeft, Math.min(chartWidth/5, 50))
val ytmr = orDefault(yTickMarginRight, 0)
val pm = orDefault(plotMargin, Math.min(chartWidth/10, 5))
Layout(chartWidth, chartHeight, xtm, ytml, ytmr, pm)
}
}
case class Font (
family: String,
baseSize: Float,
sizeIncrement: Float
)
object Font {
def basic(family: String = "Arial", baseSize: Float = 14f, sizeIncrement: Float = 1.5f): Font = {
Font(family, baseSize, sizeIncrement)
}
}
case class Draw (
strokeWidth: Float,
lineSpacing: Float,
pixelsPerTick: Int,
lineColor: Color,
frameColor: Color,
gridColor: Color
)
object Draw {
def basic (
strokeWidth: Float = 1.0f,
lineSpacing: Float = 12.0f,
pixelsPerTick: Int = 50,
lineColor: Color = Color.BLACK,
frameColor: Color = RichColor.Nil,
gridColor: Color = RichColor.Nil): Draw =
Draw(strokeWidth, lineSpacing, pixelsPerTick, lineColor, frameColor.or(lineColor), gridColor.or(lineColor))
}
}
|
richardclose/svggraph
|
src/main/scala/org/phasanix/svggraph/Options.scala
|
Scala
|
mit
| 3,970 |
package ru.smslv.akka.dns
import java.net.InetSocketAddress
import akka.io.AsyncDnsResolver
import org.scalatest.{Matchers, WordSpec}
class NameserverAddressParserSpec extends WordSpec with Matchers {
"Parser" should {
"handle explicit port in IPv4 address" in {
AsyncDnsResolver.parseNameserverAddress("8.8.8.8:153") should equal(new InetSocketAddress("8.8.8.8", 153))
}
"handle explicit port in IPv6 address" in {
AsyncDnsResolver.parseNameserverAddress("[2001:4860:4860::8888]:153") should equal(new InetSocketAddress("2001:4860:4860::8888", 153))
}
"handle default port in IPv4 address" in {
AsyncDnsResolver.parseNameserverAddress("8.8.8.8") should equal(new InetSocketAddress("8.8.8.8", 53))
}
"handle default port in IPv6 address" in {
AsyncDnsResolver.parseNameserverAddress("[2001:4860:4860::8888]") should equal(new InetSocketAddress("2001:4860:4860::8888", 53))
}
}
}
|
ilya-epifanov/akka-dns
|
src/test/scala/ru/smslv/akka/dns/NameserverAddressParserSpec.scala
|
Scala
|
apache-2.0
| 942 |
/***********************************************************************
* Copyright (c) 2013-2017 Commonwealth Computer Research, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at
* http://www.opensource.org/licenses/apache2.0.php.
***********************************************************************/
package org.locationtech.geomesa.accumulo.tools.stats
import com.beust.jcommander.Parameters
import org.locationtech.geomesa.accumulo.data.AccumuloDataStore
import org.locationtech.geomesa.accumulo.tools.{AccumuloDataStoreCommand, AccumuloDataStoreParams}
import org.locationtech.geomesa.tools.stats.{StatsTopKCommand, StatsTopKParams}
class AccumuloStatsTopKCommand extends StatsTopKCommand[AccumuloDataStore] with AccumuloDataStoreCommand {
override val params = new AccumuloStatsTopKParams
}
@Parameters(commandDescription = "Enumerate the most frequent values in a GeoMesa feature type")
class AccumuloStatsTopKParams extends StatsTopKParams with AccumuloDataStoreParams
|
ronq/geomesa
|
geomesa-accumulo/geomesa-accumulo-tools/src/main/scala/org/locationtech/geomesa/accumulo/tools/stats/AccumuloStatsTopKCommand.scala
|
Scala
|
apache-2.0
| 1,145 |
/*
* Copyright 2014-2016 Panavista Technologies, LLC
*
* 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.deftrade
import java.{ time => jt }
import scala.concurrent.Future
import scala.collection.concurrent
import scala.xml
import org.reactivestreams.{ Publisher, Subscriber, Subscription }
trait StreamsComponent {
type CMap <: collection.Map[Int, Subscriber[Any]] // some kind of concurrent map
protected def streams: CMap
}
trait StreamsStub extends StreamsComponent {
type CMap = collection.Map[Int, Subscriber[Any]]
override protected lazy val streams: CMap = new collection.Map[Int, Subscriber[Any]] {
override def get(k: Int): Option[Subscriber[Any]] = None
override def iterator: Iterator[(Int, Subscriber[Any])] = Iterator.empty
override def -(key: Int): CMap = streams // ignored
override def +[B1 >: Subscriber[Any]](kv: (Int, B1)): collection.Map[Int, B1] = streams // ignored
}
}
/*
* prologue:
* connect (?)
* ReqCurrentTime() -> just log diff between this and now()
* ReqIds() -> route response directly to OrderManagementSystem
* ReqOpenOrders() / ReqExecutions()
* SetServerLogLevel (based on config params)
* ReqMarketDataType (based on config params)
* ReqNewsBullitins (based on config params)
* ReqScannerParameters (based on config params) - hold in a well know location as XML
* ReqAccountUpdates() etc (based on config params) - sets up service for Account, Positions etc.
*/
trait Services extends StreamsComponent { self: IbConnectionComponent with OutgoingMessages with IncomingMessages with ConfigSettings =>
import ServerLogLevel.{ ServerLogLevel }
//06:40:35:735 -> Error[eid=Left(OrderId(-1)); errorCode=2103; errorMsg=Market data farm connection is broken:usfarm]
//06:40:36:790 -> Error[eid=Left(OrderId(-1)); errorCode=2104; errorMsg=Market data farm connection is OK:usfarm]
//11:59:42:859 -> Error[eid=Left(OrderId(-1)); errorCode=2103; errorMsg=Market data farm connection is broken:usfarm]
//11:59:43:515 -> Error[eid=Left(OrderId(-1)); errorCode=2103; errorMsg=Market data farm connection is broken:usfarm]
//11:59:48:172 -> Error[eid=Left(OrderId(-1)); errorCode=2104; errorMsg=Market data farm connection is OK:usfarm]
//16:19:58:307 -> Error[eid=Left(OrderId(-1)); errorCode=2103; errorMsg=Market data farm connection is broken:usfarm]
//16:19:59:447 -> Error[eid=Left(OrderId(-1)); errorCode=2104; errorMsg=Market data farm connection is OK:usfarm]
//23:44:43:231 -> Error[eid=Left(OrderId(-1)); errorCode=1100; errorMsg=Connectivity between IB and Trader Workstation has been lost.]
//23:44:45:390 -> Error[eid=Left(OrderId(-1)); errorCode=1102; errorMsg=Connectivity between IB and Trader Workstation has been restored - data maintained.]
//19:54:05:435 -> Error[eid=Left(OrderId(-1)); errorCode=1100; errorMsg=Connectivity between IB and Trader Workstation has been lost.]
//19:54:06:189 -> IbDisconnectError(Exception,None,None,Some(java.io.EOFException))
/**
* A [[org.reactivestreams.Publisher]] for a stream of all system messages for a connection.
*
* The following messages will be published:
* - all connection messages ({connect, disconnect} X {OK, Error})
* - [[io.deftrade.UpdateNewsBullitin]] api messages
* - [[io.deftrade.CurrentTime]] api messages
* - [[io.deftrade.Error]] api messages for which the id == -1, or for which an id cannot be
* found in the id map (which records the ids of all currently outstanding requests). Note:
* [[Error]] messages whose ids map to an outstanding request are routed to the publisher for the
* associated responses; those streams will be terminated with an error.
*
* The stream will complete normally only when an [[IbDisconnectOk]] message is published (this
* will be the last message). This "graceful disconnect" is initiated when the stream is
* `cancel`ed.
*
* The stream is completed with an error when an [[IbDisconnectError]]
* is encountered. // TODO: how to wrap this.
*
* More than one connection cannot be created: subsequent Publishers will
* immediately complete with an error.
*/
def connection(host: String = settings.ibc.host,
port: Int = settings.ibc.port,
clientId: Int = settings.ibc.clientId,
serverLogLevel: ServerLogLevel = ServerLogLevel.ERROR): Publisher[SystemMessage] = {
IbPublisher(IbConnect(host, port, clientId)) {
conn ! SetServerLogLevel(serverLogLevel)
conn ! ReqIds(1) // per IB API manual
conn ! ReqCurrentTime()
conn ! ReqNewsBulletins(allMsgs = true)
}
}
def scannerParameters(implicit mat: akka.stream.Materializer,
ec: scala.concurrent.ExecutionContext): Future[xml.Elem] =
Future { <bright/> }
// news bulletins will go to the connection stream. Can be filtered out / replicated from there.
// def news: Publisher[UpdateNewsBulletin]
// TODO: idea: a message bus for exchanges; subscribe to an exchange and get available / not available
// also: for data farms
/*
* ReferenceData
*/
// Will often be used with .toFuture, but want to allow for streaming directly into DB
/*
* wrz(symbol, secType, expiry, strike, right, multiplier, exchange, currency, localSymbol)
if (serverVersion >= MinServerVer.TradingClass) wrz(tradingClass)
wrz(includeExpired, secIdType, secId)
*/
def contractDetails(contract: Contract): Publisher[ContractDetails] = {
IbPublisher[ContractDetails](ReqContractDetails(ReqId.next, contract)){}
}
// TODO: verify this really has RPC semantics.
// cancel if timeout?
/**
* @param contract
* @param reportType
* @param mat
* @param ec
* @return
*/
def fundamentals(
contract: Contract,
reportType: FundamentalType.Value)(implicit mat: akka.stream.Materializer,
ec: scala.concurrent.ExecutionContext): Future[xml.Elem] = {
import Services.PublisherToFuture
IbPublisher[String](
ReqFundamentalData(ReqId.next, contract, reportType)){}.toFuture map { ss =>
xml.XML.load(ss.head)
}
}
/*
* MarketData
*/
def ticks(contract: Contract,
genericTickList: List[GenericTickType.GenericTickType],
snapshot: Boolean = false): Publisher[RawTickMessage] = {
IbPublisher(ReqMktData(ReqId.next, contract, genericTickList, snapshot)){}
}
import WhatToShow.WhatToShow
def bars(contract: Contract, whatToShow: WhatToShow): Publisher[RealTimeBar] = {
IbPublisher(ReqRealTimeBars(ReqId.next, contract, 5, whatToShow, true)){}
}
def optionPrice(contract: Contract, volatility: Double): Publisher[TickOptionComputation] = ???
def impliedVolatility(contract: Contract, optionPrice: Double): Publisher[TickOptionComputation] = ???
def depth(contract: Contract, rows: Int): Publisher[MarketDepthMessage] = ???
def scan(params: ScannerParameters): Publisher[ScannerData]
// TODO: deal with requesting news. How is news returned?
// See https://www.interactivebrokers.com/en/software/api/apiguide/tables/requestingnews.htm
def mdNews(): Publisher[Null] = ???
/*
* HistoricalData
*/
import BarSize._
import WhatToShow._
/*
* High level historical data service. Lower level API limitations and rate limiting is
* handled within the service; just request what you want.
*/
def hdBars(contract: Contract,
end: jt.ZonedDateTime,
duration: jt.Duration,
barSize: BarSize,
whatToShow: WhatToShow,
regularHoursOnly: Boolean = true): Publisher[HistoricalData] = {
IbPublisher(
ReqHistoricalData(
ReqId.next,
contract,
end.toString, // FIXME LMAO
duration.toString, // FIXME
barSize,
whatToShow,
if (regularHoursOnly) 1 else 0,
DateFormatType.SecondsSinceEpoch)){}
}
// implementation note: the formatDate field is hardwired to 2 (epoch seconds count)
// the HistoricalData responce data should use DateTimes, not strings.
// the connection logic can reply with both (legacy to the EventBus for logging and
// testability; and an "opinionated" version for the higher level interface
// IB measures the effectiveness of client orders through the Order Efficiency Ratio (OER).
// This ratio compares aggregate daily order activity relative to that portion of activity
// which results in an execution and is determined as follows:
// OER = (Order Submissions + Order Revisions + Order Cancellations) / (Executed Orders + 1)
// see http://ibkb.interactivebrokers.com/article/1765
/*
* OrderManager {
*/
/**
* Request that all open orders be canceled.
*
* @return A [[scala.concurrent.Future]] which indicates successful transmission
* if the cancel request if completed successfully,
* or with a failure in the (unlikely) event that the cancel request could not be transmitted.
* Note that a successful completion of the `Future` does 'not' mean that all open
* orders were in fact canceled.
*/
def cancelAll(): Future[Unit] = ???
/*
* Internals. TODO: review scoping
*/
import scala.language.existentials
type CMap = concurrent.Map[Int, Subscriber[Any]]
override protected lazy val streams: CMap = concurrent.TrieMap.empty[Int, Subscriber[Any]]
type Msg = HasRawId with Cancellable
case class IbPublisher[T](msg: Msg)(coda: => Unit) extends Publisher[T] {
import java.util.concurrent.atomic.AtomicBoolean
val subscribed = new AtomicBoolean(false) // no anticipation of race but why take chances
override def subscribe(subscriber: Subscriber[_ >: T]): Unit = {
if (subscriber == null) throw new NullPointerException("null Subscriber")
val first = !subscribed.getAndSet(true)
if (first) subscriber onSubscribe IbSubscription(subscriber.asInstanceOf[Subscriber[Any]], msg, () => coda)
}
}
case class IbSubscription(subscriber: Subscriber[Any], msg: Msg, coda: () => Unit) extends Subscription {
private var r = (n: Long) => {
require(n == Long.MaxValue) // FIXME: log this in production, no assertion
streams + (msg.rawId -> subscriber)
conn ! msg
coda()
}
override def request(n: Long): Unit = { r(n); r = _ => () }
private var c = () => {
streams - msg.rawId
msg.cancelMessage match {
case DummyCancel => ()
case cancelMessage => conn ! msg.cancelMessage
}
}
override def cancel(): Unit = { c(); c = () => () }
}
// object TicksToBar {
// import java.time._
//
// val zdt: ZonedDateTime = ???
// val dur: Duration = ???
// }
}
object Services {
import org.reactivestreams.Publisher
import akka.stream.scaladsl.{ Source, Flow, Sink }
implicit class PublisherToFuture[M](publisher: Publisher[M])(implicit mat: akka.stream.Materializer) {
def toFuture: Future[List[M]] = {
Source.fromPublisher(publisher).fold(List.empty[M]) { (u, t) => t :: u } map (_.reverse) runWith Sink.head
}
// def toFutureSeq: Future[Seq[M]] = Source(publisher).grouped(Int.MaxValue) runWith Sink.head
}
}
|
ndwade/def-trade
|
ib-client/src/main/scala/io/deftrade/services.scala
|
Scala
|
apache-2.0
| 11,778 |
package com.sksamuel.elastic4s.streams
import akka.actor.{Actor, ActorRef, ActorSystem, Props, Cancellable}
import com.sksamuel.elastic4s.{BulkCompatibleDefinition, ElasticClient, ElasticDsl}
import org.elasticsearch.action.bulk.{BulkItemResponse, BulkResponse}
import org.reactivestreams.{Subscriber, Subscription}
import scala.collection.mutable.ArrayBuffer
import scala.concurrent.duration.FiniteDuration
import scala.util.{Failure, Success}
/**
* An implementation of the reactive API Subscriber.
* This subscriber will bulk index received elements. The bulk nature means that the elasticsearch
* index operations are performed as a bulk call, the size of which are controlled by the batchSize param.
*
* The received elements must be converted into an elastic4s bulk compatible definition, such as index or delete.
* This is done by the RequestBuilder.
*
* @param client used to connect to the cluster
* @param builder used to turn elements of T into IndexDefinitions so they can be used in the bulk indexer
* @param listener a listener which is notified on each acknowledge batch item
* @param batchSize the number of elements to group together per batch aside from the last batch
* @param concurrentRequests the number of concurrent batch operations
* @param refreshAfterOp if the index should be refreshed after each bulk operation
* @param completionFn a function which is invoked when all sent requests have been acknowledged and the publisher has completed
* @param errorFn a function which is invoked when there is an error
* @param flushInterval used to schedule periodic bulk indexing. Use it when the publisher will never complete.
* This ensures that all elements are indexed, even if the last batch size is lower than batch size
*
* @tparam T the type of element provided by the publisher this subscriber will subscribe with
*/
class BulkIndexingSubscriber[T] private[streams](client: ElasticClient,
builder: RequestBuilder[T],
listener: ResponseListener,
batchSize: Int,
concurrentRequests: Int,
refreshAfterOp: Boolean,
completionFn: () => Unit,
errorFn: Throwable => Unit,
flushInterval: Option[FiniteDuration])
(implicit system: ActorSystem) extends Subscriber[T] {
private var actor: ActorRef = _
override def onSubscribe(s: Subscription): Unit = {
if (s == null) throw new NullPointerException()
if (actor == null) {
actor = system.actorOf(
Props(new BulkActor(client,
builder,
s,
batchSize,
concurrentRequests,
refreshAfterOp,
listener,
completionFn,
errorFn,
flushInterval))
)
s.request(batchSize * concurrentRequests)
} else {
// rule 2.5, must cancel subscription as onSubscribe has been invoked twice
// https://github.com/reactive-streams/reactive-streams-jvm#2.5
s.cancel()
}
}
override def onNext(t: T): Unit = {
if (t == null) throw new NullPointerException("On next should not be called until onSubscribe has returned")
actor ! t
}
override def onError(t: Throwable): Unit = {
if (t == null) throw new NullPointerException()
actor ! t
}
override def onComplete(): Unit = {
actor ! BulkActor.Completed
}
}
object BulkActor {
case object Completed
case object ForceIndexing
}
class BulkActor[T](client: ElasticClient,
builder: RequestBuilder[T],
subscription: Subscription,
batchSize: Int,
concurrentRequests: Int,
refreshAfterOp: Boolean,
listener: ResponseListener,
completionFn: () => Unit,
errorFn: Throwable => Unit,
flushInterval: Option[FiniteDuration] = None) extends Actor {
import ElasticDsl._
import context.dispatcher
import context.system
private val buffer = new ArrayBuffer[T]()
buffer.sizeHint(batchSize)
private var completed = false
// total number of elements sent and acknowledge at the es cluster level
private var pending: Long = 0l
// Create a scheduler if a flushInterval is provided. This scheduler will be used to force indexing
private val scheduler: Option[Cancellable] = flushInterval.map { interval =>
system.scheduler.schedule(interval, interval, self, BulkActor.ForceIndexing)
}
def receive = {
case t: Throwable =>
handleError(t)
case BulkActor.Completed =>
if (buffer.nonEmpty)
index()
completed = true
shutdownIfAllAcked()
case BulkActor.ForceIndexing =>
if (pending == 0 && buffer.nonEmpty)
index()
case r: BulkResponse =>
pending = pending - r.items.length
r.items.foreach(listener.onAck)
// need to check if we're completed, because if we are then this might be the last pending ack
// and if it is, we can shutdown. Otherwise w can set another batch going.
if (completed) shutdownIfAllAcked()
else subscription.request(batchSize)
case t: T =>
buffer.append(t)
if (buffer.size == batchSize)
index()
}
// Stop the scheduler if it exists
override def postStop() = scheduler.map(_.cancel())
private def shutdownIfAllAcked(): Unit = {
if (pending == 0) {
completionFn()
context.stop(self)
}
}
private def handleError(t: Throwable): Unit = {
// if an error we will cancel the subscription as we cannot for sure handle further elements
// and the error may be from outside the subscriber
subscription.cancel()
errorFn(t)
buffer.clear()
context.stop(self)
}
private def index(): Unit = {
pending = pending + buffer.size
client.execute(bulk(buffer.map(builder.request)).refresh(refreshAfterOp)).onComplete {
case Failure(e) => self ! e
case Success(resp) => self ! resp
}
buffer.clear
}
}
/**
* An implementation of this typeclass must provide a bulk compatible request for the given instance of T.
* @tparam T the type of elements this provider supports
*/
trait RequestBuilder[T] {
def request(t: T): BulkCompatibleDefinition
}
/**
* Notified on each acknowledgement
*/
trait ResponseListener {
def onAck(resp: BulkItemResponse): Unit
}
object ResponseListener {
def noop = new ResponseListener {
override def onAck(resp: BulkItemResponse): Unit = ()
}
}
|
tototoshi/elastic4s
|
elastic4s-streams/src/main/scala/com/sksamuel/elastic4s/streams/BulkIndexingSubscriber.scala
|
Scala
|
apache-2.0
| 6,845 |
package com.greencatsoft.angularjs
import scala.language.experimental.macros
import scala.scalajs.js
class Module private[angularjs] (val module: internal.Module) {
require(module != null, "Missing argument 'module'.")
import internal.{ Angular => angular }
def config[A <: Config](target: A): Module = macro angular.config[A]
def config[A <: Config]: Module = macro angular.configFromClass[A]
def $config(constructor: ServiceDefinition[_ <: Config]): Module = {
module.config(constructor)
this
}
def controller[A <: Controller[_]](target: A): Module = macro angular.controller[A]
def controller[A <: Controller[_]]: Module = macro angular.controllerFromClass[A]
def $controller(name: String, constructor: ServiceDefinition[_ <: Controller[_]]): Module = {
module.controller(name, constructor)
this
}
def directive[A <: Directive](target: A): Module = macro angular.directive[A]
def directive[A <: Directive]: Module = macro angular.directiveFromClass[A]
def $directive(name: String, constructor: ServiceDefinition[_ <: Directive]): Module = {
module.directive(name, constructor)
this
}
def factory[A <: Factory[_]](target: A): Module = macro angular.factory[A]
def factory[A <: Factory[_]]: Module = macro angular.factoryFromClass[A]
def $factory(name: String, constructor: ServiceDefinition[_ <: Factory[_]]): Module = {
module.factory(name, constructor)
this
}
def run[A <: Runnable](target: A): Module = macro angular.run[A]
def run[A <: Runnable]: Module = macro angular.runFromClass[A]
def $run(constructor: ServiceDefinition[_ <: Runnable]): Module = {
module.run(constructor)
this
}
def service[A <: Service](target: A): Module = macro angular.service[A]
def $service(name: String, constructor: ServiceDefinition[_]): Module = {
module.service(name, constructor)
this
}
def filter[A <: Filter[_]](target: A): Module = macro angular.filter[A]
def filter[A <: Filter[_]]: Module = macro angular.filterFromClass[A]
def $filter(name: String, constructor: ServiceDefinition[_ <: Filter[_]]): Module = {
module.filter(name, constructor)
this
}
}
|
svenwiegand/scalajs-angular
|
src/main/scala/com/greencatsoft/angularjs/Module.scala
|
Scala
|
apache-2.0
| 2,185 |
package sharry.restserver.routes.tus
import sharry.common.ByteSize
import org.http4s._
import org.typelevel.ci.CIString
object SharryFileLength {
def apply[F[_]](req: Request[F]): Option[ByteSize] =
sizeHeader(req, "sharry-file-length").orElse(sizeHeader(req, "upload-length"))
private[tus] def sizeHeader[F[_]](req: Request[F], name: String): Option[ByteSize] =
req.headers.get(CIString(name)).flatMap(_.head.value.toLongOption).map(ByteSize.apply)
}
|
eikek/sharry
|
modules/restserver/src/main/scala/sharry/restserver/routes/tus/SharryFileLength.scala
|
Scala
|
gpl-3.0
| 469 |
/*
* Copyright 2011-2017 Chris de Vreeze
*
* 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 eu.cdevreeze.yaidom.queryapitests.indexed
import java.net.URI
import scala.collection.immutable
import eu.cdevreeze.yaidom.indexed
import eu.cdevreeze.yaidom.parse.DocumentParserUsingSax
import eu.cdevreeze.yaidom.queryapi.XmlBaseSupport
import eu.cdevreeze.yaidom.queryapitests.AbstractXmlBaseTest
/**
* XML Base test case for indexed Elems.
*
* @author Chris de Vreeze
*/
class XmlBaseTest extends AbstractXmlBaseTest {
type D = indexed.Document
type E = indexed.Elem
protected def getDocument(path: String, docUri: URI): indexed.Document = {
val docParser = DocumentParserUsingSax.newInstance()
val parsedDocUri = classOf[XmlBaseTest].getResource(path).toURI
val doc = docParser.parse(parsedDocUri)
indexed.Document.from(doc.withUriOption(Some(docUri)))
}
protected def getDocument(path: String): indexed.Document = {
getDocument(path, classOf[XmlBaseTest].getResource(path).toURI)
}
protected def getBaseUri(elem: E): URI = {
elem.baseUri
}
protected def getParentBaseUri(elem: E): URI = {
elem.parentBaseUriOption.getOrElse(new URI(""))
}
protected def getDocumentUri(elem: E): URI = {
elem.docUri
}
protected def getReverseAncestryOrSelf(elem: E): immutable.IndexedSeq[E] = {
elem.reverseAncestryOrSelf
}
// Naive resolveUri method
protected override def resolveUri(uri: URI, baseUriOption: Option[URI]): URI = {
// Note the different behavior for resolving the empty URI!
XmlBaseSupport.JdkUriResolver(uri, baseUriOption)
}
}
|
dvreeze/yaidom
|
jvm/src/test/scala/eu/cdevreeze/yaidom/queryapitests/indexed/XmlBaseTest.scala
|
Scala
|
apache-2.0
| 2,138 |
/*
* 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.server
import slamdata.Predef._
import quasar.api.services._
import quasar.api.{redirectService, staticFileService, FailedResponseOr, FailedResponseT}
import quasar.cli.Cmd
import quasar.config._
import quasar.console.{logErrors, stdout}
import quasar.contrib.scalaz._
import quasar.contrib.scopt._
import quasar.db.DbConnectionConfig
import quasar.effect.{Read, ScopeExecution, TimingRepository, Write}
import quasar.fp._
import quasar.fp.free._
import quasar.fp.numeric.Natural
import quasar.fs.mount.cache.VCache, VCache.{VCacheExpR, VCacheExpW}
import quasar.main._
import quasar.server.Http4sUtils.{openBrowser, waitForUserEnter}
import org.http4s.HttpService
import org.http4s.server._
import org.http4s.server.syntax._
import scalaz.{Failure => _, _}
import Scalaz._
import scalaz.concurrent.Task
object Server {
final case class WebCmdLineConfig(
cmd: Cmd,
staticContent: List[StaticContent],
redirect: Option[String],
port: Option[Int],
configPath: Option[FsFile],
loadConfig: BackendConfig,
openClient: Boolean,
recordedExecutions: Natural) {
def toCmdLineConfig: CmdLineConfig = CmdLineConfig(configPath, loadConfig, cmd)
}
object WebCmdLineConfig {
def fromArgs(args: Vector[String]): MainTask[WebCmdLineConfig] =
CliOptions.parser.safeParse(args, CliOptions.default)
.flatMap(fromCliOptions(_))
def fromCliOptions(opts: CliOptions): MainTask[WebCmdLineConfig] = {
import java.lang.RuntimeException
val loadConfigM: Task[BackendConfig] = opts.loadConfig.fold(
{ plugins =>
val err = Task.fail(new RuntimeException("plugin directory does not exist (or is a file)"))
val check = Task.delay(plugins.exists() && !plugins.isFile())
check.ifM(Task.now(BackendConfig.PluginDirectory(plugins)), err)
},
backends => BackendConfig.fromBackends(IList.fromList(backends)))
(StaticContent.fromCliOptions("/files", opts) ⊛
opts.config.fold(none[FsFile].point[MainTask])(cfg =>
FsPath.parseSystemFile(cfg)
.toRight(s"Invalid path to config file: $cfg")
.map(some)) ⊛
loadConfigM.liftM[MainErrT]) ((content, cfgPath, loadConfig) =>
WebCmdLineConfig(
opts.cmd, content.toList, content.map(_.loc), opts.port, cfgPath, loadConfig, opts.openClient, opts.recordedExecutions))
}
}
def nonApiService(
defaultPort: Int,
reload: Int => Task[String \\/ Unit],
staticContent: List[StaticContent],
redirect: Option[String]
): HttpService = {
val staticRoutes = staticContent map {
case StaticContent(loc, path) => loc -> staticFileService(path)
}
Router(staticRoutes ::: List(
"/" -> redirectService(redirect getOrElse "/welcome"),
"/server/info" -> info.service,
"/server/port" -> control.service(defaultPort, reload)
): _*)
}
def serviceStarter(
defaultPort: Int,
staticContent: List[StaticContent],
redirect: Option[String],
eval: CoreEff ~> QErrs_CRW_TaskM,
persistPortChange: Int => MainTask[Unit],
recordedExecutions: Natural
): Task[PortChangingServer.ServiceStarter] = {
import RestApi._
def interp: Task[CoreEffIORW ~> FailedResponseOr] =
TaskRef(Tags.Min(none[VCache.Expiration])) ∘ (r =>
foldMapNT(
(liftMT[Task, FailedResponseT] compose Read.fromTaskRef(r)) :+:
(liftMT[Task, FailedResponseT] compose Write.fromTaskRef(r)) :+:
liftMT[Task, FailedResponseT] :+:
qErrsToResponseT[Task]
) compose (
injectFT[VCacheExpR, QErrs_CRW_Task] :+:
injectFT[VCacheExpW, QErrs_CRW_Task] :+:
injectFT[Task, QErrs_CRW_Task] :+:
eval))
for {
timingRepo <- TimingRepository.empty(recordedExecutions)
executionIdRef <- TaskRef(0L)
} yield {
implicit val SE = ScopeExecution.forFreeTask[CoreEffIORW, Nothing](timingRepo, _ => ().point[Free[CoreEffIORW, ?]])
(reload: Int => Task[String \\/ Unit]) =>
finalizeServices(
toHttpServicesF[CoreEffIORW](
λ[Free[CoreEffIORW, ?] ~> FailedResponseOr] { fa =>
interp.liftM[FailedResponseT] >>= (fa foldMap _)
},
coreServices[CoreEffIORW, Nothing](executionIdRef, timingRepo)
) ++ additionalServices
) orElse nonApiService(defaultPort, Kleisli(persistPortChange andThen (a => a.run)) >> Kleisli(reload), staticContent, redirect)
}
}
/**
* Start Quasar server
* @return A `Task` that can be used to shutdown the server
*/
def startServer(
quasarInter: CoreEff ~> QErrs_CRW_TaskM,
port: Int,
staticContent: List[StaticContent],
redirect: Option[String],
persistPortChange: Int => MainTask[Unit],
recordedExecutions: Natural
): Task[Task[Unit]] =
for {
starter <- serviceStarter(defaultPort = port, staticContent, redirect, quasarInter, persistPortChange, recordedExecutions)
shutdown <- PortChangingServer.start(initialPort = port, starter)
} yield shutdown
def persistMetaStore(configPath: Option[FsFile]): DbConnectionConfig => MainTask[Unit] =
persistWebConfig(configPath, conn => _.copy(metastore = MetaStoreConfig(conn).some))
def persistPortChange(configPath: Option[FsFile]): Int => MainTask[Unit] =
persistWebConfig(configPath, port => _.copy(server = ServerConfig(port)))
def persistWebConfig[A](configPath: Option[FsFile], modify: A => (WebConfig => WebConfig)): A => MainTask[Unit] = { a =>
for {
diskConfig <- EitherT(ConfigOps[WebConfig].fromOptionalFile(configPath).run.flatMap {
// Great, we were able to load the config file from disk
case \\/-(config) => config.right.point[Task]
// The config file is malformed, let's warn the user and not make any changes
case -\\/([email protected](_,_)) =>
(configErr: ConfigError).shows.left.point[Task]
// There is no config file, so let's create a new one with the default configuration
// to which we will apply this change
case -\\/(ConfigError.FileNotFound(_)) => WebConfig.configOps.default.map(_.right)
})
newConfig = modify(a)(diskConfig)
_ <- EitherT(ConfigOps[WebConfig].toFile(newConfig, configPath).attempt).leftMap(_.getMessage)
} yield ()
}
def safeMain(args: Vector[String]): Task[Unit] = {
logErrors(for {
_ <- stdout(s"Quasar v${quasar.build.BuildInfo.version}").liftM[MainErrT]
webCmdLineCfg <- WebCmdLineConfig.fromArgs(args)
_ <- initMetaStoreOrStart[WebConfig](
webCmdLineCfg.toCmdLineConfig,
(wCfg, quasarInter) => {
val port = webCmdLineCfg.port | wCfg.server.port
val persistPort = persistPortChange(webCmdLineCfg.configPath)
(for {
shutdown <- startServer(
quasarInter,
port,
webCmdLineCfg.staticContent,
webCmdLineCfg.redirect,
persistPort,
webCmdLineCfg.recordedExecutions)
_ <- openBrowser(port).whenM(webCmdLineCfg.openClient)
_ <- stdout("Press Enter to stop.")
// If user pressed enter (after this main thread has been blocked on it),
// then we shutdown, otherwise we just run indefinitely until the JVM is killed
// If we don't call shutdown and this main thread completes, the application will
// continue to run indefinitely as `startServer` uses a non-daemon `ExecutorService`
// TODO: Figure out why it's necessary to use a `Task` that never completes to keep the main thread
// from completing instead of simply relying on the fact that the server is using a pool of
// non-daemon threads to ensure the application doesn't shutdown
_ <- waitForUserEnter.ifM(shutdown, Task.async[Unit](_ => ()))
} yield ()).liftM[MainErrT]
},
persistMetaStore(webCmdLineCfg.configPath))
} yield ())
}
def main(args: Array[String]): Unit =
safeMain(args.toVector).unsafePerformSync
}
|
jedesah/Quasar
|
web/src/main/scala/quasar/server/Server.scala
|
Scala
|
apache-2.0
| 9,114 |
package com.alanjz.meerkat.app.tabs
import java.awt.Dimension
import javax.swing.JPanel
abstract class MCTab {
private val panel = new JPanel()
this.setPreferredSize(new Dimension(300, 650))
def toJPanel = panel
}
object MCTab {
implicit def toJPanel(lhs : MCTab) : JPanel = lhs.toJPanel
}
|
spacenut/meerkat-chess
|
src/com/alanjz/meerkat/app/tabs/MCTab.scala
|
Scala
|
gpl-2.0
| 302 |
/*
* Copyright 2014 Treode, 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.treode.jackson
import java.net.InetSocketAddress
import com.treode.store.Preference
import org.scalatest.FlatSpec
class PreferenceSpec extends FlatSpec with ModuleSpec {
"Serializing a preference" should "work" in {
assertString ("""{"weight":1,"hostId":"0x8BB6E8637E8E0356","addr":"localhost:80","sslAddr":null}""") {
Preference (1, 0x8BB6E8637E8E0356L, Some (new InetSocketAddress ("localhost", 80)), None)
}}
}
|
Treode/store
|
jackson/test/com/treode/jackson/PreferenceSpec.scala
|
Scala
|
apache-2.0
| 1,043 |
package vggames.browser
import org.openqa.selenium.WebDriver
import org.openqa.selenium.firefox.FirefoxDriver
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner
import org.openqa.selenium.By
import org.openqa.selenium.JavascriptExecutor
trait WebBrowser {
var driver = new FirefoxDriver
var baseUrl = "http://localhost:8080";
def task(game: String, numberTask: Int) { driver.get(baseUrl + "/aprenda/" + game + "/task/" + numberTask); }
def solve(response: String): Unit = {
var js = driver.asInstanceOf[JavascriptExecutor];
js.executeScript("""editor.setValue('""" + response + """');""")
}
def verifyOk: Boolean = {
Thread.sleep(200);
driver.findElement(By.cssSelector("BODY")).getText().contains("Ok!") ||
driver.findElement(By.cssSelector("BODY")).getText().contains("Compartilhe a sua conquista")
}
}
|
vidageek/games
|
web/src/test/scala/vggames/browser/WebBrowser.scala
|
Scala
|
gpl-3.0
| 871 |
/*
* 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.mllib.optimization
import scala.collection.JavaConverters._
import scala.util.Random
import org.scalatest.matchers.must.Matchers
import org.apache.spark.SparkFunSuite
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression._
import org.apache.spark.mllib.util.{LocalClusterSparkContext, MLlibTestSparkContext, MLUtils}
import org.apache.spark.mllib.util.TestingUtils._
object GradientDescentSuite {
def generateLogisticInputAsList(
offset: Double,
scale: Double,
nPoints: Int,
seed: Int): java.util.List[LabeledPoint] = {
generateGDInput(offset, scale, nPoints, seed).asJava
}
// Generate input of the form Y = logistic(offset + scale * X)
def generateGDInput(
offset: Double,
scale: Double,
nPoints: Int,
seed: Int): Seq[LabeledPoint] = {
val rnd = new Random(seed)
val x1 = Array.fill[Double](nPoints)(rnd.nextGaussian())
val unifRand = new Random(45)
val rLogis = (0 until nPoints).map { i =>
val u = unifRand.nextDouble()
math.log(u) - math.log1p(-u)
}
val y: Seq[Int] = (0 until nPoints).map { i =>
val yVal = offset + scale * x1(i) + rLogis(i)
if (yVal > 0) 1 else 0
}
(0 until nPoints).map(i => LabeledPoint(y(i), Vectors.dense(x1(i))))
}
}
class GradientDescentSuite extends SparkFunSuite with MLlibTestSparkContext with Matchers {
test("Assert the loss is decreasing.") {
val nPoints = 10000
val A = 2.0
val B = -1.5
val initialB = -1.0
val initialWeights = Array(initialB)
val gradient = new LogisticGradient()
val updater = new SimpleUpdater()
val stepSize = 1.0
val numIterations = 10
val regParam = 0
val miniBatchFrac = 1.0
// Add a extra variable consisting of all 1.0's for the intercept.
val testData = GradientDescentSuite.generateGDInput(A, B, nPoints, 42)
val data = testData.map { case LabeledPoint(label, features) =>
label -> MLUtils.appendBias(features)
}
val dataRDD = sc.parallelize(data, 2).cache()
val initialWeightsWithIntercept = Vectors.dense(initialWeights.toArray :+ 1.0)
val (_, loss) = GradientDescent.runMiniBatchSGD(
dataRDD,
gradient,
updater,
stepSize,
numIterations,
regParam,
miniBatchFrac,
initialWeightsWithIntercept)
assert(loss.last - loss.head < 0, "loss isn't decreasing.")
val lossDiff = loss.init.zip(loss.tail).map { case (lhs, rhs) => lhs - rhs }
assert(lossDiff.count(_ > 0).toDouble / lossDiff.size > 0.8)
}
test("Test the loss and gradient of first iteration with regularization.") {
val gradient = new LogisticGradient()
val updater = new SquaredL2Updater()
// Add a extra variable consisting of all 1.0's for the intercept.
val testData = GradientDescentSuite.generateGDInput(2.0, -1.5, 10000, 42)
val data = testData.map { case LabeledPoint(label, features) =>
label -> Vectors.dense(1.0 +: features.toArray)
}
val dataRDD = sc.parallelize(data, 2).cache()
// Prepare non-zero weights
val initialWeightsWithIntercept = Vectors.dense(1.0, 0.5)
val regParam0 = 0
val (newWeights0, loss0) = GradientDescent.runMiniBatchSGD(
dataRDD, gradient, updater, 1, 1, regParam0, 1.0, initialWeightsWithIntercept)
val regParam1 = 1
val (newWeights1, loss1) = GradientDescent.runMiniBatchSGD(
dataRDD, gradient, updater, 1, 1, regParam1, 1.0, initialWeightsWithIntercept)
assert(
loss1(0) ~= (loss0(0) + (math.pow(initialWeightsWithIntercept(0), 2) +
math.pow(initialWeightsWithIntercept(1), 2)) / 2) absTol 1E-5,
"""For non-zero weights, the regVal should be 0.5 * sum(w_i ^ 2).""")
assert(
(newWeights1(0) ~= (newWeights0(0) - initialWeightsWithIntercept(0)) absTol 1E-5) &&
(newWeights1(1) ~= (newWeights0(1) - initialWeightsWithIntercept(1)) absTol 1E-5),
"The different between newWeights with/without regularization " +
"should be initialWeightsWithIntercept.")
}
test("iteration should end with convergence tolerance") {
val nPoints = 10000
val A = 2.0
val B = -1.5
val initialB = -1.0
val initialWeights = Array(initialB)
val gradient = new LogisticGradient()
val updater = new SimpleUpdater()
val stepSize = 1.0
val numIterations = 10
val regParam = 0
val miniBatchFrac = 1.0
val convergenceTolerance = 5.0e-1
// Add a extra variable consisting of all 1.0's for the intercept.
val testData = GradientDescentSuite.generateGDInput(A, B, nPoints, 42)
val data = testData.map { case LabeledPoint(label, features) =>
label -> MLUtils.appendBias(features)
}
val dataRDD = sc.parallelize(data, 2).cache()
val initialWeightsWithIntercept = Vectors.dense(initialWeights.toArray :+ 1.0)
val (_, loss) = GradientDescent.runMiniBatchSGD(
dataRDD,
gradient,
updater,
stepSize,
numIterations,
regParam,
miniBatchFrac,
initialWeightsWithIntercept,
convergenceTolerance)
assert(loss.length < numIterations, "convergenceTolerance failed to stop optimization early")
}
}
class GradientDescentClusterSuite extends SparkFunSuite with LocalClusterSparkContext {
test("task size should be small") {
val m = 4
val n = 200000
val points = sc.parallelize(0 until m, 2).mapPartitionsWithIndex { (idx, iter) =>
val random = new Random(idx)
iter.map(i => (1.0, Vectors.dense(Array.fill(n)(random.nextDouble()))))
}.cache()
// If we serialize data directly in the task closure, the size of the serialized task would be
// greater than 1MiB and hence Spark would throw an error.
val (weights, loss) = GradientDescent.runMiniBatchSGD(
points,
new LogisticGradient,
new SquaredL2Updater,
0.1,
2,
1.0,
1.0,
Vectors.dense(new Array[Double](n)))
}
}
|
mahak/spark
|
mllib/src/test/scala/org/apache/spark/mllib/optimization/GradientDescentSuite.scala
|
Scala
|
apache-2.0
| 6,783 |
package sh.webserver
object Runner {
def main(args: Array[String]): Unit = {
new Server(1337).start()
}
}
|
stefan-hering/scalaserver
|
src/main/sh/webserver/Runner.scala
|
Scala
|
apache-2.0
| 114 |
package com.lightning.walletapp.ln.wire
import java.net._
import scodec.codecs._
import fr.acinq.eclair.UInt64.Conversions._
import scodec.bits.{BitVector, ByteVector}
import com.lightning.walletapp.ln.crypto.{Mac32, Sphinx}
import fr.acinq.bitcoin.Crypto.{Point, PublicKey, Scalar}
import scodec.{Attempt, Codec, DecodeResult, Decoder, Err}
import com.lightning.walletapp.ln.{LightningException, RevocationInfo}
import org.apache.commons.codec.binary.Base32
import fr.acinq.bitcoin.{Crypto, MilliSatoshi}
import fr.acinq.eclair.UInt64
import scala.reflect.ClassTag
import java.math.BigInteger
import scala.util.Try
object LightningMessageCodecs { me =>
type NodeAddressList = List[NodeAddress]
type BitVectorAttempt = Attempt[BitVector]
type LNMessageVector = Vector[LightningMessage]
// True is sent localy, False is received from remote peer
type LNDirectionalMessage = (LightningMessage, Boolean)
type RedeemScriptAndSig = (ByteVector, ByteVector)
type RGB = (Byte, Byte, Byte)
def serialize(attempt: BitVectorAttempt): ByteVector = attempt match {
case Attempt.Successful(binary) => ByteVector.view(binary.toByteArray)
case Attempt.Failure(err) => throw new LightningException(err.message)
}
def deserialize(raw: ByteVector): LightningMessage =
lightningMessageCodec decode BitVector(raw) match {
case Attempt.Successful(decodedResult) => decodedResult.value
case Attempt.Failure(err) => throw new LightningException(err.message)
}
def discriminatorWithDefault[A](discriminator: Codec[A], fallback: Codec[A]) = new Codec[A] {
def encode(element: A) = discriminator encode element recoverWith { case _ => fallback encode element }
def sizeBound = discriminator.sizeBound | fallback.sizeBound
def decode(bv: BitVector) = discriminator decode bv recoverWith {
case _: KnownDiscriminatorType[_]#UnknownDiscriminator => fallback decode bv
}
}
// RGB <-> ByteVector
private val bv2Rgb: PartialFunction[ByteVector, RGB] = {
case ByteVector(red, green, blue, _*) => (red, green, blue)
}
private val rgb2Bv: PartialFunction[RGB, ByteVector] = {
case (red, green, blue) => ByteVector(red, green, blue)
}
def der2wire(signature: ByteVector): ByteVector =
Crypto decodeSignature signature match { case (r, s) =>
val fixedR = Crypto fixSize ByteVector.view(r.toByteArray dropWhile 0.==)
val fixedS = Crypto fixSize ByteVector.view(s.toByteArray dropWhile 0.==)
fixedR ++ fixedS
}
def wire2der(sig: ByteVector): ByteVector = {
val r = new BigInteger(1, sig.take(32).toArray)
val s = new BigInteger(1, sig.takeRight(32).toArray)
Crypto.encodeSignature(r, s) :+ 1.toByte
}
// Generic codecs
val signature = Codec[ByteVector] (
encoder = (der: ByteVector) => bytes(64).encode(me der2wire der),
decoder = (wire: BitVector) => bytes(64).decode(wire).map(_ map wire2der)
)
val scalar = Codec[Scalar] (
encoder = (scalar: Scalar) => bytes(32).encode(scalar.toBin),
decoder = (wire: BitVector) => bytes(32).decode(wire).map(_ map Scalar.apply)
)
val point = Codec[Point] (
encoder = (point: Point) => bytes(33).encode(point toBin true),
decoder = (wire: BitVector) => bytes(33).decode(wire).map(_ map Point.apply)
)
val publicKey = Codec[PublicKey] (
encoder = (publicKey: PublicKey) => bytes(33).encode(publicKey.value toBin true),
decoder = (wire: BitVector) => bytes(33).decode(wire).map(_ map PublicKey.apply)
)
val ipv6address: Codec[Inet6Address] = bytes(16).exmap(
bv => Attempt fromTry Try(Inet6Address.getByAddress(null, bv.toArray, null)),
inet6Address => Attempt fromTry Try(ByteVector view inet6Address.getAddress)
)
private val ipv4address: Codec[Inet4Address] = bytes(4).xmap(
bv => InetAddress.getByAddress(bv.toArray).asInstanceOf[Inet4Address],
inet4Address => ByteVector.view(inet4Address.getAddress)
)
def base32(size: Int): Codec[String] = bytes(size).xmap(
bv => (new Base32 encodeAsString bv.toArray).toLowerCase,
address => ByteVector.view(new Base32 decode address.toUpperCase)
)
def minimalValue(codec: Codec[UInt64], min: UInt64): Codec[UInt64] = codec.exmap(f = {
case value if value < min => Attempt failure Err("Value is not minimally encoded")
case value => Attempt successful value
}, Attempt.successful)
val uint64Overflow: Codec[Long] = int64.narrow(f = {
case value if value < 0 => Attempt failure Err(s"Overflow $value")
case value => Attempt successful value
}, identity)
val uint64: Codec[UInt64] = bytes(8).xmap(UInt64.apply, _.toByteVector padLeft 8)
val varint: Codec[UInt64] = {
val large = minimalValue(uint64, 0x100000000L)
val medium = minimalValue(uint32.xmap(UInt64.apply, _.toBigInt.toLong), 0x10000)
val small = minimalValue(uint16.xmap(int => UInt64(int), _.toBigInt.toInt), 0xFD)
val default: Codec[UInt64] = uint8L.xmap(int => UInt64(int), _.toBigInt.toInt)
discriminatorWithDefault(discriminated[UInt64].by(uint8L)
.\\(0xFF) { case value if value >= UInt64(0x100000000L) => value } (large)
.\\(0xFE) { case value if value >= UInt64(0x10000) => value } (medium)
.\\(0xFD) { case value if value >= UInt64(0xFD) => value } (small),
default)
}
// This codec can be safely used for values < 2^63 and will fail otherwise.
// It is useful in combination with variableSizeBytesLong to encode/decode TLV lengths because those will always be < 2^63.
val varintoverflow: Codec[Long] = varint.narrow(l => if (l <= UInt64(Long.MaxValue)) Attempt.successful(l.toBigInt.toLong) else Attempt.failure(Err(s"overflow for value $l")), l => UInt64(l))
val bytes32: Codec[ByteVector] = limitedSizeBytes(32, bytesStrict(32))
val zeropaddedstring: Codec[String] = fixedSizeBytes(32, utf8).xmap(_.takeWhile(_ != '\\u0000'), identity)
val varsizebinarydataLong: Codec[ByteVector] = variableSizeBytesLong(uint32, bytes)
val varsizebinarydata: Codec[ByteVector] = variableSizeBytes(uint16, bytes)
val rgb: Codec[RGB] = bytes(3).xmap(bv2Rgb, rgb2Bv)
val txvec = vectorOfN(uint16, varsizebinarydata)
def nodeaddress: Codec[NodeAddress] =
discriminated[NodeAddress].by(uint8)
.typecase(cr = (ipv4address :: uint16).as[IPv4], tag = 1)
.typecase(cr = (ipv6address :: uint16).as[IPv6], tag = 2)
.typecase(cr = (base32(10) :: uint16).as[Tor2], tag = 3)
.typecase(cr = (base32(35) :: uint16).as[Tor3], tag = 4)
.typecase(cr = (zeropaddedstring :: uint16).as[Domain], tag = 5)
def prependmac[A](codec: Codec[A], mac32: Mac32) = Codec[A] (
(a: A) => codec.encode(a).map(bits1 => mac32.mac(bits1.toByteVector).bits ++ bits1),
(encodedMacBits: BitVector) => (bytes32 withContext "mac").decode(encodedMacBits) match {
case Attempt.Successful(dr) if mac32.verify(dr.value, dr.remainder.toByteVector) => codec.decode(dr.remainder)
case Attempt.Successful(invalidDr) => Attempt Failure scodec.Err(s"Invalid mac detected: $invalidDr")
case Attempt.Failure(err) => Attempt Failure err
}
)
// Tlv
private val genericTlv = (varint withContext "tag") :: variableSizeBytesLong(varintoverflow, bytes)
private val genericTlvCodec = genericTlv.as[GenericTlv].exmap(validateGenericTlv, validateGenericTlv)
private def validateGenericTlv(generic: GenericTlv): Attempt[GenericTlv] =
if (generic.tag.toBigInt % 2 == 0) Attempt Failure Err("Unknown even tlv type")
else Attempt Successful generic
private def variableSizeUInt64(size: Int, min: Long): Codec[UInt64] =
minimalValue(bytes(size).xmap(f => UInt64(f), _.toByteVector takeRight size), min)
/**
* Truncated uint64 (0 to 8 bytes unsigned integer).
* The encoder minimally-encodes every value, and the decoder verifies that values are minimally-encoded.
* Note that this codec can only be used at the very end of a TLV record.
*/
val tu64: Codec[UInt64] = Codec(
(u: UInt64) => {
val b = u match {
case u if u < 0x01 => ByteVector.empty
case u if u < 0x0100 => u.toByteVector.takeRight(1)
case u if u < 0x010000 => u.toByteVector.takeRight(2)
case u if u < 0x01000000 => u.toByteVector.takeRight(3)
case u if u < 0x0100000000L => u.toByteVector.takeRight(4)
case u if u < 0x010000000000L => u.toByteVector.takeRight(5)
case u if u < 0x01000000000000L => u.toByteVector.takeRight(6)
case u if u < 0x0100000000000000L => u.toByteVector.takeRight(7)
case u if u <= UInt64.MaxValue => u.toByteVector.takeRight(8)
}
Attempt.successful(b.bits)
},
b => b.length match {
case l if l <= 0 => minimalValue(uint64, UInt64(0x00)).decode(b.padLeft(64))
case l if l <= 8 => minimalValue(uint64, UInt64(0x01)).decode(b.padLeft(64))
case l if l <= 16 => minimalValue(uint64, UInt64(0x0100)).decode(b.padLeft(64))
case l if l <= 24 => minimalValue(uint64, UInt64(0x010000)).decode(b.padLeft(64))
case l if l <= 32 => minimalValue(uint64, UInt64(0x01000000)).decode(b.padLeft(64))
case l if l <= 40 => minimalValue(uint64, UInt64(0x0100000000L)).decode(b.padLeft(64))
case l if l <= 48 => minimalValue(uint64, UInt64(0x010000000000L)).decode(b.padLeft(64))
case l if l <= 56 => minimalValue(uint64, UInt64(0x01000000000000L)).decode(b.padLeft(64))
case l if l <= 64 => minimalValue(uint64, UInt64(0x0100000000000000L)).decode(b.padLeft(64))
case _ => Attempt.failure(Err(s"too many bytes to decode for truncated uint64 (${b.toHex})"))
})
val tu64Overflow: Codec[Long] = tu64.exmap(
u => if (u <= Long.MaxValue) Attempt.Successful(u.toBigInt.toLong) else Attempt.Failure(Err(s"overflow for value $u")),
l => if (l >= 0) Attempt.Successful(UInt64(l)) else Attempt.Failure(Err(s"uint64 must be positive (actual=$l)")))
val tmillisatoshi: Codec[MilliSatoshi] = tu64Overflow.xmap(l => MilliSatoshi(l), m => m.toLong)
/** Truncated uint32 (0 to 4 bytes unsigned integer). */
val tu32: Codec[Long] = tu64.exmap({
case i if i > 0xffffffffL => Attempt.Failure(Err("tu32 overflow"))
case i => Attempt.Successful(i.toBigInt.toLong)
}, l => Attempt.Successful(l))
/** Truncated uint16 (0 to 2 bytes unsigned integer). */
val tu16: Codec[Int] = tu32.exmap({
case i if i > 0xffff => Attempt.Failure(Err("tu16 overflow"))
case i => Attempt.Successful(i.toInt)
}, l => Attempt.Successful(l))
def tlvStream[T <: Tlv](codec: DiscriminatorCodec[T, UInt64]): Codec[TlvStream[T]] = {
val withFallback = discriminatorFallback(genericTlvCodec, codec)
list(withFallback).exmap(
recordsEitherTlvList => {
val knownTags = for (Right(known) <- recordsEitherTlvList) yield known
val unknownTags = for (Left(unknown) <- recordsEitherTlvList) yield unknown
val tags = for (record <- recordsEitherTlvList) yield record match {
case Right(tlv) => codec.encode(tlv).flatMap(varint.decode).require.value
case Left(unknownTlv) => unknownTlv.tag
}
if (tags.length != tags.distinct.length) Attempt Failure Err("Tlv streams must not contain duplicate records")
else if (tags != tags.sorted) Attempt Failure Err("Tlv records must be ordered by monotonically-increasing types")
else Attempt Successful TlvStream(knownTags, unknownTags)
},
stream => {
val knownRecords = for (known <- stream.records) yield Right(known)
val unknownRecords = for (unknown <- stream.unknown) yield Left(unknown)
val records = (knownRecords ++ unknownRecords).toList
val tags = for (record <- records) yield record match {
case Right(tlv) => codec.encode(tlv).flatMap(varint.decode).require.value
case Left(unknownTlv) => unknownTlv.tag
}
if (tags.length != tags.distinct.length) Attempt Failure Err("Tlv streams must not contain duplicate records")
else Attempt Successful tags.zip(records).sortBy { case (tag, _) => tag }.map { case (_, record) => record }
}
)
}
// Onion
def onionRoutingPacketCodec(payloadLength: Int): Codec[OnionRoutingPacket] = (
("version" | uint8) ::
("publicKey" | bytes(33)) ::
("onionPayload" | bytes(payloadLength)) ::
("hmac" | bytes32)).as[OnionRoutingPacket]
val paymentOnionPacketCodec: Codec[OnionRoutingPacket] = onionRoutingPacketCodec(Sphinx.PaymentPacket.PayloadLength)
val payloadLengthDecoder = Decoder[Long]((bits: BitVector) =>
varintoverflow.decode(bits).map(d => DecodeResult(d.value + (bits.length - d.remainder.length) / 8, d.remainder)))
/** Length-prefixed truncated millisatoshi (1 to 9 bytes unsigned). */
val ltmillisatoshi: Codec[MilliSatoshi] = variableSizeBytes(uint8, tmillisatoshi)
private val amountToForward: Codec[OnionTlv.AmountToForward] = ("amount_msat" | ltmillisatoshi).as[OnionTlv.AmountToForward]
/** Length-prefixed truncated uint32 (1 to 5 bytes unsigned integer). */
val ltu32: Codec[Long] = variableSizeBytes(uint8, tu32)
private val outgoingCltv: Codec[OnionTlv.OutgoingCltv] = ("cltv" | ltu32).xmap(cltv => OnionTlv.OutgoingCltv(cltv), (c: OnionTlv.OutgoingCltv) => c.cltv)
private val outgoingChannelId: Codec[OnionTlv.OutgoingChannelId] = variableSizeBytesLong(varintoverflow, "short_channel_id" | int64).as[OnionTlv.OutgoingChannelId]
val paymentData: Codec[OnionTlv.PaymentData] = variableSizeBytesLong(varintoverflow, ("payment_secret" | bytes32) :: ("total_msat" | tmillisatoshi)).as[OnionTlv.PaymentData]
private val onionTlvCodec = discriminated[OnionTlv].by(varint)
.typecase(UInt64(2), amountToForward)
.typecase(UInt64(4), outgoingCltv)
.typecase(UInt64(6), outgoingChannelId)
.typecase(UInt64(8), paymentData)
def lengthPrefixedTlvStream[T <: Tlv](codec: DiscriminatorCodec[T, UInt64]): Codec[TlvStream[T]] = variableSizeBytesLong(varintoverflow, tlvStream(codec))
val tlvPerHopPayloadCodec: Codec[OnionTlv.Stream] = lengthPrefixedTlvStream[OnionTlv](onionTlvCodec).complete
private val legacyRelayPerHopPayloadCodec: Codec[RelayLegacyPayload] = {
(constant(ByteVector fromByte 0) withContext "realm") ::
(uint64Overflow withContext "short_channel_id") ::
(uint64Overflow withContext "amt_to_forward") ::
(uint32 withContext "outgoing_cltv_value") ::
(ignore(8 * 12) withContext "unused_with_v0_version_on_header")
}.as[RelayLegacyPayload]
private val legacyFinalPerHopPayloadCodec: Codec[FinalLegacyPayload] = {
(constant(ByteVector fromByte 0) withContext "realm") ::
(ignore(8 * 8) withContext "short_channel_id") ::
(uint64Overflow withContext "amount") ::
(uint32 withContext "expiry") ::
(ignore(8 * 12) withContext "unused_with_v0_version_on_header")
}.as[FinalLegacyPayload]
case class MissingRequiredTlv(tag: UInt64) extends Err { me =>
override def message = "Onion per-hop payload is invalid"
override def pushContext(ctx: String): Err = me
override def context: List[String] = Nil
}
val relayPerHopPayloadCodec: Codec[RelayPayload] = fallback(tlvPerHopPayloadCodec, legacyRelayPerHopPayloadCodec).narrow({
case Left(tlvs) if tlvs.get[OnionTlv.AmountToForward].isEmpty => Attempt.failure(MissingRequiredTlv(UInt64(2)))
case Left(tlvs) if tlvs.get[OnionTlv.OutgoingCltv].isEmpty => Attempt.failure(MissingRequiredTlv(UInt64(4)))
case Left(tlvs) if tlvs.get[OnionTlv.OutgoingChannelId].isEmpty => Attempt.failure(MissingRequiredTlv(UInt64(6)))
case Left(tlvs) => Attempt.successful(RelayTlvPayload(tlvs))
case Right(legacy) => Attempt.successful(legacy)
}, {
case legacy: RelayLegacyPayload => Right(legacy)
case RelayTlvPayload(tlvs) => Left(tlvs)
})
val finalPerHopPayloadCodec: Codec[FinalPayload] = fallback(tlvPerHopPayloadCodec, legacyFinalPerHopPayloadCodec).narrow({
case Left(tlvs) if tlvs.get[OnionTlv.AmountToForward].isEmpty => Attempt.failure(MissingRequiredTlv(UInt64(2)))
case Left(tlvs) if tlvs.get[OnionTlv.OutgoingCltv].isEmpty => Attempt.failure(MissingRequiredTlv(UInt64(4)))
case Left(tlvs) => Attempt.successful(FinalTlvPayload(tlvs))
case Right(legacy) => Attempt.successful(legacy)
}, {
case legacy: FinalLegacyPayload => Right(legacy)
case FinalTlvPayload(tlvs) => Left(tlvs)
})
// LN messages
private val init = (varsizebinarydata withContext "globalFeatures") :: (varsizebinarydata withContext "localFeatures")
private val ping = (uint16 withContext "pongLength") :: (varsizebinarydata withContext "data")
private val pong = varsizebinarydata withContext "data"
val channelReestablish =
(bytes32 withContext "channelId") ::
(uint64Overflow withContext "nextLocalCommitmentNumber") ::
(uint64Overflow withContext "nextRemoteRevocationNumber") ::
(optional(bitsRemaining, scalar) withContext "yourLastPerCommitmentSecret") ::
(optional(bitsRemaining, point) withContext "myCurrentPerCommitmentPoint")
val channelFlagsCodec = (byte withContext "flags").as[ChannelFlags]
val errorCodec = {
(bytes32 withContext "channelId") ::
(varsizebinarydata withContext "data")
}.as[Error]
private val openChannel =
(bytes32 withContext "chainHash") ::
(bytes32 withContext "temporaryChannelId") ::
(uint64Overflow withContext "fundingSatoshis") ::
(uint64Overflow withContext "pushMsat") ::
(uint64Overflow withContext "dustLimitSatoshis") ::
(uint64 withContext "maxHtlcValueInFlightMsat") ::
(uint64Overflow withContext "channelReserveSatoshis") ::
(uint64Overflow withContext "htlcMinimumMsat") ::
(uint32 withContext "feeratePerKw") ::
(uint16 withContext "toSelfDelay") ::
(uint16 withContext "maxAcceptedHtlcs") ::
(publicKey withContext "fundingPubkey") ::
(point withContext "revocationBasepoint") ::
(point withContext "paymentBasepoint") ::
(point withContext "delayedPaymentBasepoint") ::
(point withContext "htlcBasepoint") ::
(point withContext "firstPerCommitmentPoint") ::
(channelFlagsCodec withContext "channelFlags")
val acceptChannelCodec = {
(bytes32 withContext "temporaryChannelId") ::
(uint64Overflow withContext "dustLimitSatoshis") ::
(uint64 withContext "maxHtlcValueInFlightMsat") ::
(uint64Overflow withContext "channelReserveSatoshis") ::
(uint64Overflow withContext "htlcMinimumMsat") ::
(uint32 withContext "minimumDepth") ::
(uint16 withContext "toSelfDelay") ::
(uint16 withContext "maxAcceptedHtlcs") ::
(publicKey withContext "fundingPubkey") ::
(point withContext "revocationBasepoint") ::
(point withContext "paymentBasepoint") ::
(point withContext "delayedPaymentBasepoint") ::
(point withContext "htlcBasepoint") ::
(point withContext "firstPerCommitmentPoint")
}.as[AcceptChannel]
private val fundingCreated =
(bytes32 withContext "temporaryChannelId") ::
(bytes32 withContext "txid") ::
(uint16 withContext "fundingOutputIndex") ::
(signature withContext "signature")
private val fundingSigned =
(bytes32 withContext "channelId") ::
(signature withContext "signature")
val fundingLockedCodec = {
(bytes32 withContext "channelId") ::
(point withContext "nextPerCommitmentPoint")
}.as[FundingLocked]
val shutdownCodec = {
(bytes32 withContext "channelId") ::
(varsizebinarydata withContext "scriptPubKey")
}.as[Shutdown]
val closingSignedCodec = {
(bytes32 withContext "channelId") ::
(uint64Overflow withContext "feeSatoshis") ::
(signature withContext "signature")
}.as[ClosingSigned]
val updateAddHtlcCodec = {
(bytes32 withContext "channelId") ::
(uint64Overflow withContext "id") ::
(uint64Overflow withContext "amountMsat") ::
(bytes32 withContext "paymentHash") ::
(uint32 withContext "expiry") ::
(paymentOnionPacketCodec withContext "onionRoutingPacket")
}.as[UpdateAddHtlc]
val updateFulfillHtlcCodec = {
(bytes32 withContext "channelId") ::
(uint64Overflow withContext "id") ::
(bytes32 withContext "paymentPreimage")
}.as[UpdateFulfillHtlc]
val updateFailHtlcCodec = {
(bytes32 withContext "channelId") ::
(uint64Overflow withContext "id") ::
(varsizebinarydata withContext "reason")
}.as[UpdateFailHtlc]
private val updateFailMalformedHtlc =
(bytes32 withContext "channelId") ::
(uint64Overflow withContext "id") ::
(bytes32 withContext "onionHash") ::
(uint16 withContext "failureCode")
val commitSigCodec = {
(bytes32 withContext "channelId") ::
(signature withContext "signature") ::
(listOfN(uint16, signature) withContext "htlcSignatures")
}.as[CommitSig]
private val revokeAndAck =
(bytes32 withContext "channelId") ::
(scalar withContext "perCommitmentSecret") ::
(point withContext "nextPerCommitmentPoint")
private val updateFee =
(bytes32 withContext "channelId") ::
(uint32 withContext "feeratePerKw")
private val announcementSignatures =
(bytes32 withContext "channelId") ::
(int64 withContext "shortChannelId") ::
(signature withContext "nodeSignature") ::
(signature withContext "bitcoinSignature")
val channelAnnouncementWitness =
(varsizebinarydata withContext "features") ::
(bytes32 withContext "chainHash") ::
(int64 withContext "shortChannelId") ::
(publicKey withContext "nodeId1") ::
(publicKey withContext "nodeId2") ::
(publicKey withContext "bitcoinKey1") ::
(publicKey withContext "bitcoinKey2") ::
(bytes withContext "unknownFields")
private val channelAnnouncement =
(signature withContext "nodeSignature1") ::
(signature withContext "nodeSignature2") ::
(signature withContext "bitcoinSignature1") ::
(signature withContext "bitcoinSignature2") ::
channelAnnouncementWitness
val nodeAnnouncementWitness =
(varsizebinarydata withContext "features") ::
(uint32 withContext "timestamp") ::
(publicKey withContext "nodeId") ::
(rgb withContext "rgbColor") ::
(zeropaddedstring withContext "alias") ::
(variableSizeBytes(value = list(nodeaddress), size = uint16) withContext "addresses") ::
(bytes withContext "unknownFields")
val channelUpdateWitness =
(bytes32 withContext "chainHash") ::
(int64 withContext "shortChannelId") ::
(uint32 withContext "timestamp") ::
(byte withContext "messageFlags").flatPrepend { messageFlags =>
(byte withContext "channelFlags" ) ::
(uint16 withContext "cltvExpiryDelta") ::
(uint64Overflow withContext "htlcMinimumMsat") ::
(uint32 withContext "feeBaseMsat") ::
(uint32 withContext "feeProportionalMillionths") ::
(conditional(included = (messageFlags & 1) != 0, uint64Overflow) withContext "htlcMaximumMsat") ::
(bytes withContext "unknownFields")
}
val nodeAnnouncementCodec = {
(signature withContext "signature") ::
nodeAnnouncementWitness
}.as[NodeAnnouncement]
val channelUpdateCodec = {
(signature withContext "signature") ::
channelUpdateWitness
}.as[ChannelUpdate]
val queryChannelRangeCodec = {
(bytes32 withContext "chainHash") ::
(uint32 withContext "firstBlockNum") ::
(uint32 withContext "numberOfBlocks")
}.as[QueryChannelRange]
val gossipTimestampFilterCodec = {
(bytes32 withContext "chainHash") ::
(uint32 withContext "firstTimestamp") ::
(uint32 withContext "timestampRange")
}.as[GossipTimestampFilter]
// Hosted messages codecs
val invokeHostedChannelCodec = {
(bytes32 withContext "chainHash") ::
(varsizebinarydata withContext "refundScriptPubKey") ::
(varsizebinarydata withContext "secret")
}.as[InvokeHostedChannel]
val initHostedChannelCodec = {
(uint64 withContext "maxHtlcValueInFlightMsat") ::
(uint64Overflow withContext "htlcMinimumMsat") ::
(uint16 withContext "maxAcceptedHtlcs") ::
(uint64Overflow withContext "channelCapacityMsat") ::
(uint16 withContext "liabilityDeadlineBlockdays") ::
(uint64Overflow withContext "minimalOnchainRefundAmountSatoshis") ::
(uint64Overflow withContext "initialClientBalanceMsat") ::
(varsizebinarydata withContext "features")
}.as[InitHostedChannel]
val lastCrossSignedStateCodec = {
(varsizebinarydata withContext "refundScriptPubKey") ::
(initHostedChannelCodec withContext "initHostedChannel") ::
(uint32 withContext "blockDay") ::
(uint64Overflow withContext "localBalanceMsat") ::
(uint64Overflow withContext "remoteBalanceMsat") ::
(uint32 withContext "localUpdates") ::
(uint32 withContext "remoteUpdates") ::
(listOfN(uint16, updateAddHtlcCodec) withContext "incomingHtlcs") ::
(listOfN(uint16, updateAddHtlcCodec) withContext "outgoingHtlcs") ::
(signature withContext "remoteSigOfLocal") ::
(signature withContext "localSigOfRemote")
}.as[LastCrossSignedState]
val stateUpdateCodec = {
(uint32 withContext "blockDay") ::
(uint32 withContext "localUpdates") ::
(uint32 withContext "remoteUpdates") ::
(signature withContext "localSigOfRemoteLCSS") ::
(bool withContext "isTerminal")
}.as[StateUpdate]
val stateOverrideCodec = {
(uint32 withContext "blockDay") ::
(uint64Overflow withContext "localBalanceMsat") ::
(uint32 withContext "localUpdates") ::
(uint32 withContext "remoteUpdates") ::
(signature withContext "localSigOfRemoteLCSS")
}.as[StateOverride]
val lightningMessageCodec =
discriminated[LightningMessage].by(uint16)
.typecase(cr = init.as[Init], tag = 16)
.typecase(cr = errorCodec, tag = 17)
.typecase(cr = ping.as[Ping], tag = 18)
.typecase(cr = pong.as[Pong], tag = 19)
.typecase(cr = openChannel.as[OpenChannel], tag = 32)
.typecase(cr = acceptChannelCodec, tag = 33)
.typecase(cr = fundingCreated.as[FundingCreated], tag = 34)
.typecase(cr = fundingSigned.as[FundingSigned], tag = 35)
.typecase(cr = fundingLockedCodec, tag = 36)
.typecase(cr = shutdownCodec, tag = 38)
.typecase(cr = closingSignedCodec, tag = 39)
.typecase(cr = updateAddHtlcCodec, tag = 128)
.typecase(cr = updateFulfillHtlcCodec, tag = 130)
.typecase(cr = updateFailHtlcCodec, tag = 131)
.typecase(cr = commitSigCodec, tag = 132)
.typecase(cr = revokeAndAck.as[RevokeAndAck], tag = 133)
.typecase(cr = updateFee.as[UpdateFee], tag = 134)
.typecase(cr = updateFailMalformedHtlc.as[UpdateFailMalformedHtlc], tag = 135)
.typecase(cr = channelReestablish.as[ChannelReestablish], tag = 136)
.typecase(cr = channelAnnouncement.as[ChannelAnnouncement], tag = 256)
.typecase(cr = nodeAnnouncementCodec, tag = 257)
.typecase(cr = channelUpdateCodec, tag = 258)
.typecase(cr = announcementSignatures.as[AnnouncementSignatures], tag = 259)
.typecase(cr = queryChannelRangeCodec, tag = 263)
.typecase(cr = gossipTimestampFilterCodec, tag = 265)
.typecase(cr = invokeHostedChannelCodec, tag = 65535)
.typecase(cr = initHostedChannelCodec, tag = 65533)
.typecase(cr = lastCrossSignedStateCodec, tag = 65531)
.typecase(cr = stateUpdateCodec, tag = 65529)
.typecase(cr = stateOverrideCodec, tag = 65527)
// Not in a spec
val hopCodec = {
(publicKey withContext "nodeId") ::
(int64 withContext "shortChannelId") ::
(uint16 withContext "cltvExpiryDelta") ::
(uint64Overflow withContext "htlcMinimumMsat") ::
(uint32 withContext "feeBaseMsat") ::
(uint32 withContext "feeProportionalMillionths")
}.as[Hop]
val revocationInfoCodec = {
(listOfN(uint16, varsizebinarydata ~ signature) withContext "redeemScriptsToSigs") ::
(optional(bool, signature) withContext "claimMainTxSig") ::
(optional(bool, signature) withContext "claimPenaltyTxSig") ::
(uint64Overflow withContext "feeRate") ::
(uint64Overflow withContext "dustLimit") ::
(varsizebinarydata withContext "finalScriptPubKey") ::
(uint16 withContext "toSelfDelay") ::
(publicKey withContext "localPubKey") ::
(publicKey withContext "remoteRevocationPubkey") ::
(publicKey withContext "remoteDelayedPaymentKey")
}.as[RevocationInfo]
val hostedStateCodec = {
(bytes32 withContext "channelId") ::
(vectorOfN(uint16, lightningMessageCodec) withContext "nextLocalUpdates") ::
(vectorOfN(uint16, lightningMessageCodec) withContext "nextRemoteUpdates") ::
(lastCrossSignedStateCodec withContext "lastCrossSignedState")
}.as[HostedState]
val aesZygoteCodec = {
(uint16 withContext "v") ::
(varsizebinarydataLong withContext "iv") ::
(varsizebinarydataLong withContext "ciphertext")
}.as[AESZygote]
val cerberusPayloadCodec = {
(vectorOfN(uint16, aesZygoteCodec) withContext "payloads") ::
(vectorOfN(uint16, zeropaddedstring) withContext "halfTxIds")
}.as[CerberusPayload]
}
// TLV
trait Tlv
case class GenericTlv(tag: UInt64, value: ByteVector) extends Tlv
case class TlvStream[T <: Tlv](records: Traversable[T], unknown: Traversable[GenericTlv] = Nil) {
def get[R <: T : ClassTag]: Option[R] = records.collectFirst { case record: R => record }
}
object TlvStream {
type BaseStream = TlvStream[Tlv]
val empty: BaseStream = TlvStream[Tlv](records = Nil)
def apply[T <: Tlv](records: T*): TlvStream[T] = TlvStream(records)
}
// Onion
sealed trait OnionTlv extends Tlv
case class OnionRoutingPacket(version: Int, publicKey: ByteVector, payload: ByteVector, hmac: ByteVector)
object OnionTlv {
type Stream = TlvStream[OnionTlv]
case class OutgoingChannelId(shortChannelId: Long) extends OnionTlv // Id of the channel to use to forward a payment to the next node
case class PaymentData(secret: ByteVector, totalAmount: MilliSatoshi) extends OnionTlv // Bolt 11 payment details for the last node
case class AmountToForward(amount: MilliSatoshi) extends OnionTlv // Amount to forward to the next node
case class OutgoingCltv(cltv: Long) extends OnionTlv
}
sealed trait PerHopPayloadFormat
sealed trait PerHopPayload { def encode: ByteVector }
sealed trait FinalPayload extends PerHopPayload with PerHopPayloadFormat { me =>
def encode = LightningMessageCodecs.finalPerHopPayloadCodec.encode(me).require.toByteVector
val paymentSecretOpt: Option[ByteVector]
val totalAmountMsat: Long
val amountMsat: Long
val cltvExpiry: Long
}
sealed trait RelayPayload extends PerHopPayload with PerHopPayloadFormat { me =>
def encode = LightningMessageCodecs.relayPerHopPayloadCodec.encode(me).require.toByteVector
val amountToForwardMsat: Long
val outgoingCltv: Long
}
sealed trait LegacyFormat extends PerHopPayloadFormat
case class RelayLegacyPayload(outgoingChannelId: Long, amountToForwardMsat: Long, outgoingCltv: Long) extends RelayPayload with LegacyFormat
case class RelayTlvPayload(records: OnionTlv.Stream) extends RelayPayload {
override val amountToForwardMsat = records.get[OnionTlv.AmountToForward].get.amount.toLong
override val outgoingCltv = records.get[OnionTlv.OutgoingCltv].get.cltv
}
case class FinalLegacyPayload(amountMsat: Long, cltvExpiry: Long) extends FinalPayload with LegacyFormat {
override val totalAmountMsat = amountMsat
override val paymentSecretOpt = None
}
case class FinalTlvPayload(records: OnionTlv.Stream) extends FinalPayload {
override val paymentSecretOpt = records.get[OnionTlv.PaymentData].map(_.secret)
override val amountMsat = records.get[OnionTlv.AmountToForward].get.amount.toLong
override val cltvExpiry = records.get[OnionTlv.OutgoingCltv].get.cltv
override val totalAmountMsat = records.get[OnionTlv.PaymentData] match {
case Some(paymentData) if paymentData.totalAmount.toLong == 0L => amountMsat
case Some(paymentData) => paymentData.totalAmount.toLong
case None => amountMsat
}
}
|
btcontract/lnwallet
|
app/src/main/java/com/lightning/walletapp/ln/wire/LightningMessageCodecs.scala
|
Scala
|
apache-2.0
| 32,153 |
/*
* Copyright (c) 2014-2021 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monix.reactive.internal.operators
import cats.laws._
import cats.laws.discipline._
import monix.eval.Task
import monix.reactive.{BaseTestSuite, Observable}
import scala.concurrent.duration._
import scala.util.Success
object BufferSlidingSuite extends BaseTestSuite {
test("bufferSliding equivalence with the standard library") { implicit s =>
check3 { (numbers: List[Int], countR: Int, skipR: Int) =>
val count = Math.floorMod(countR, 10) + 1
val skip = Math.floorMod(skipR, 10) + 1
val received = Observable.fromIterable(numbers).bufferSliding(count, skip).map(_.toList).toListL
val expected = Task.now(numbers.sliding(count, skip).map(_.toList).toList)
received <-> expected
}
}
test("issue #275 regression test") { implicit s =>
val received = Observable.interval(1.seconds).bufferSliding(5, 1).take(10L).map(_.toList).toListL.runToFuture
val expected = (0 until 20).sliding(5, 1).take(10).map(_.toList).toList
s.tick(100.seconds)
assertEquals(received.value, Some(Success(expected)))
}
}
|
monixio/monix
|
monix-reactive/shared/src/test/scala/monix/reactive/internal/operators/BufferSlidingSuite.scala
|
Scala
|
apache-2.0
| 1,742 |
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.hmrc.ct.computations
import org.joda.time.LocalDate
import org.scalatest.{Matchers, WordSpec}
import uk.gov.hmrc.ct.box.CtValidation
import uk.gov.hmrc.ct.computations.stubs.StubbedComputationsBoxRetriever
import uk.gov.hmrc.ct._
import uk.gov.hmrc.ct.computations.lowEmissionCars.{Car, LEC01}
class MyStubbedComputationsRetriever(lec01: List[Car] = List(),
cpq8: Option[Boolean] = None,
cp1: LocalDate = new LocalDate("2019-04-02"),
cp78: Option[Int] = None,
cp79: Option[Int] = None,
cp80: Option[Int] = None,
cp82: Option[Int] = None,
cp83: Option[Int] = None,
cp84: Option[Int] = None,
cp87Input: Option[Int] = None,
cp87a: Option[Int] = None,
cp88: Option[Int] = None,
cp89: Option[Int] = None,
cp666: Option[Int] = None,
cp667: Option[Int] = None,
cp668: Option[Int] = None,
cp672: Option[Int] = None,
cp672a: Option[Int] = None,
cp673: Option[Int] = None,
cp674: Option[Int] = None,
cato02: Int = 0,
cato20: Int = 0,
cato21: Int = 0,
cato22: Int = 0,
cpAux1: Int = 0,
cpAux2: Int = 0,
cpAux3: Int = 0
) extends StubbedComputationsBoxRetriever {
override def lec01: LEC01 = lowEmissionCars.LEC01(lec01)
override def cpQ8: CPQ8 = CPQ8(cpq8)
override def cp1: CP1 = CP1(cp1)
override def cp78: CP78 = CP78(cp78)
override def cp79: CP79 = CP79(cp79)
override def cp80: CP80 = CP80(cp80)
override def cp666: CP666 = CP666(cp666)
override def cp82: CP82 = CP82(cp82)
override def cp83: CP83 = CP83(cp83)
override def cp84: CP84 = CP84(cp84)
override def cp667: CP667 = CP667(cp667)
override def cp672: CP672 = CP672(cp672)
override def cp672a: CP672a = CP672a(cp672a)
override def cp673: CP673 = CP673(cp673)
override def cp674: CP674 = CP674(cp674)
override def cp87Input: CP87Input = CP87Input(cp87Input)
override def cp87a: CP87a = CP87a(cp87a)
override def cp88: CP88 = CP88(cp88)
override def cp89: CP89 = CP89(cp89)
override def cp668: CP668 = CP668(cp668)
override def cato02: CATO02 = CATO02(cato02)
override def cato20: CATO20 = CATO20(cato20)
override def cato21: CATO21 = CATO21(cato21)
override def cato22: CATO22 = CATO22(cato22)
override def cpAux1: CPAux1 = CPAux1(cpAux1)
override def cpAux2: CPAux2 = CPAux2(cpAux2)
override def cpAux3: CPAux3 = CPAux3(cpAux3)
override def countryOfRegistration(): CountryOfRegistration = CountryOfRegistration.Scotland
}
class MachineryAndPlantValidationSpec extends WordSpec with Matchers {
val stubBoxRetriever = new MyStubbedComputationsRetriever
"CP78 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP78(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP78(None).validate(stubBoxRetriever) shouldBe Set()
CP78(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP78"), errorMessageKey = "error.CP78.mustBeZeroOrPositive"))
}
}
"CP666 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP666(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP666(None).validate(stubBoxRetriever) shouldBe Set()
CP666(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP666"), errorMessageKey = "error.CP666.mustBeZeroOrPositive"))
}
}
"CP79" should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP79(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP79(None).validate(stubBoxRetriever) shouldBe Set()
CP79(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP79"), errorMessageKey = "error.CP79.mustBeZeroOrPositive"))
}
}
"CP80" should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP80(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP80(None).validate(stubBoxRetriever) shouldBe Set()
CP80(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP80"), errorMessageKey = "error.CP80.mustBeZeroOrPositive"))
}
}
"CP82 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP82(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP82(None).validate(stubBoxRetriever) shouldBe Set()
CP82(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP82"), errorMessageKey = "error.CP82.mustBeZeroOrPositive"))
}
}
"CP83 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP83(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP83(None).validate(stubBoxRetriever) shouldBe Set()
CP83(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP83"), errorMessageKey = "error.CP83.mustBeZeroOrPositive"))
}
}
"CP674 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP674(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP674(None).validate(stubBoxRetriever) shouldBe Set()
CP674(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP674"), errorMessageKey = "error.CP674.mustBeZeroOrPositive"))
}
}
"CP84 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP84(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP84(None).validate(stubBoxRetriever) shouldBe Set()
CP84(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP84"), errorMessageKey = "error.CP84.mustBeZeroOrPositive"))
}
}
"CP252" should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP252(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP252(None).validate(stubBoxRetriever) shouldBe Set()
CP252(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP252"), errorMessageKey = "error.CP252.mustBeZeroOrPositive"))
}
}
"CP673 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP673(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP673(None).validate(stubBoxRetriever) shouldBe Set()
CP673(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP673"), errorMessageKey = "error.CP673.mustBeZeroOrPositive"))
}
}
"CP667 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP667(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP667(None).validate(stubBoxRetriever) shouldBe Set()
CP667(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP667"), errorMessageKey = "error.CP667.mustBeZeroOrPositive"))
}
}
"CP672 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP672(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP672(None).validate(stubBoxRetriever) shouldBe Set()
CP672(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP672"), errorMessageKey = "error.CP672.mustBeZeroOrPositive"))
}
}
"CP672a " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP672a(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP672a(None).validate(stubBoxRetriever) shouldBe Set()
CP672a(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP672a"), errorMessageKey = "error.CP672a.mustBeZeroOrPositive"))
}
}
"CP87Input, given is trading and first Year Allowance Not Greater Than Max FYA" should {
"validate if present and non-negative, otherwise fail" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(false))
CP87Input(Some(0)).validate(stubTestComputationsRetriever) shouldBe Set()
CP87Input(Some(-1)).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP87Input"), errorMessageKey = "error.CP87Input.mustBeZeroOrPositive"))
}
}
"CP87Input, given is non-negative" should {
"validate correctly when not greater than CP81 CPaux1" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cpq8 = Some(false),
cp79 = Some(20),
cpAux1 = 51)
CP87Input(Some(71)).validate(stubTestComputationsRetriever) shouldBe Set()
}
"fail validation when greater than CP81 CPaux1" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cpq8 = Some(false),
cp79 = Some(20),
cpAux1 = 52)
CP87Input(Some(73)).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP87Input"), errorMessageKey = "error.CP87Input.firstYearAllowanceClaimExceedsAllowance", args = Some(Seq("72"))))
}
"validate because FYA defaults to 0 when not entered" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cpq8 = Some(true),
cp79 = Some(20),
cp80 = Some(29),
cpAux1 = 51)
CP87Input(None).validate(stubTestComputationsRetriever) shouldBe Set()
}
"fail validation when trading but no value entered" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(false))
CP87Input(None).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP87Input"), errorMessageKey = "error.CP87Input.fieldMustHaveValueIfTrading"))
}
"validate when ceased trading but no value entered" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(true))
CP87Input(None).validate(stubTestComputationsRetriever) shouldBe Set()
}
"validate when ceased trading not set" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever()
CP87Input(None).validate(stubTestComputationsRetriever) shouldBe Set()
}
"fails validation when negative" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(false))
CP87Input(-1).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP87Input"), errorMessageKey = "error.CP87Input.mustBeZeroOrPositive"))
}
}
"CP87a " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP87a(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP87a(None).validate(stubBoxRetriever) shouldBe Set()
CP87a(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP87a"), errorMessageKey = "error.CP87a.mustBeZeroOrPositive"))
}
}
"CP665 " should {
"validate if present and non-negative or if not present, otherwise fail" in {
CP665(Some(0)).validate(stubBoxRetriever) shouldBe Set()
CP665(None).validate(stubBoxRetriever) shouldBe Set()
CP665(Some(-1)).validate(stubBoxRetriever) shouldBe Set(CtValidation(boxId = Some("CP665"), errorMessageKey = "error.CP665.mustBeZeroOrPositive"))
}
}
"fail validation when greater than CP87Input" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp87Input = Some(60))
CP87a(Some(101)).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP87a"), errorMessageKey = "error.CP87a.exceeds.max", args = Some(Seq("60"))))
}
"fail validation when greater than CP672" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp672 = Some(60))
CP672a(Some(101)).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP672a"), errorMessageKey = "error.CP672a.CP672.exceeds.max", args = Some(Seq("60"))))
}
"pass validation when less than are equal CP87Input" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp87Input = Some(60))
CP87a(Some(60)).validate(stubTestComputationsRetriever) shouldBe Set()
CP87a(Some(50)).validate(stubTestComputationsRetriever) shouldBe Set()
}
"CP88(annual investment allowance claimed)" should {
"fail to validate when negative" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever()
CP88(Some(-1)).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP88"), errorMessageKey = "error.CP88.mustBeZeroOrPositive"))
}
"validate correctly when not greater than the minimum of CATO02 (maxAIA) and CP83 (expenditureQualifyingAnnualInvestmentAllowance)" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp83 = Some(11),
cato02 = 10
)
CP88(Some(10)).validate(stubTestComputationsRetriever) shouldBe Set()
}
"fails validation when greater than the minimum of CATO02 (maxAIA) and CP83 (expenditureQualifyingAnnualInvestmentAllowance)" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp83 = Some(11),
cato02 = 10
)
CP88(Some(11)).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP88"), errorMessageKey = "error.CP88.annualInvestmentAllowanceExceeded", args = Some(Seq("10"))))
}
"fails validation when CATO02 (maxAIA) is the minimum" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp83 = Some(10),
cato02 = 11
)
CP88(Some(11)).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP88"), errorMessageKey = "error.CP88.annualInvestmentAllowanceExceeded", args = Some(Seq("10"))))
}
"fail validation when trading but no value entered" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(false))
CP88(None).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP88"), errorMessageKey = "error.CP88.fieldMustHaveValueIfTrading"))
}
"validate when ceased trading but no value entered" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(true))
CP88(None).validate(stubTestComputationsRetriever) shouldBe Set()
}
"validate when ceased trading not set" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever()
CP88(None).validate(stubTestComputationsRetriever) shouldBe Set()
}
"fails validation when negative" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(false))
CP88(-1).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP88"), errorMessageKey = "error.CP88.mustBeZeroOrPositive"))
}
}
"CP89 (Writing Down Allowance claimed from Main pool)" should {
"validates correctly when not greater than MAX(0, MainPool% * ( CP78 (Main Pool brought forward) " +
"+ CP82 (Additions Qualifying for Main Pool) + MainRatePool - CP672 (Proceed from Disposals from Main Pool) " +
"+ UnclaimedAIA_FYA (Unclaimed FYA and AIA amounts)) - CATO-2730" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp78 = Some(1000), // writtenDownValueBroughtForward
cp79 = Some(20),
// cp80 = Some(30),
// CP81 - calculated // (sum of cp79 and cpAux1) expenditureQualifyingForFirstYearAllowanceInput
cp82 = Some(2000), // additionsQualifyingWritingDownAllowanceMainPool
cp83 = Some(50), // expenditureQualifyingAnnualInvestmentAllowance
cp87Input = Some(40), // firstYearAllowanceClaimedInput
cp88 = Some(10),
cp672 = Some(1000), // proceedsFromDisposalsFromMainPool
cpAux1 = 0,
cpAux2 = 0,
cato21 = 18
)
CP89(369).validate(stubTestComputationsRetriever) shouldBe Set()
CP89(550).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP89"), errorMessageKey = "error.CP89.mainPoolAllowanceExceeded", Some(Seq("373"))))
}
"validates when greater than MAX(0, MainPool% * ( CP78 (Main Pool brought forward) " +
"+ CP82 (Additions Qualifying for Main Pool) + MainRatePool - CP672 (Proceed from Disposals from Main Pool) " +
"+ LEC14 (Unclaimed FYA and AIA amounts)))" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp78 = Some(100), // writtenDownValueBroughtForward
cp79 = Some(30),
cp82 = Some(100), // additionsQualifyingWritingDownAllowanceMainPool
cp83 = Some(10),
cp672 = Some(100), // proceedsFromDisposalsFromMainPool
cpAux1 = 10,
cpAux2 = 50,
cato21 = 10,
cato20 = 50
)
CP89(15).validate(stubTestComputationsRetriever) shouldBe Set()
CP89(16).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP89"), errorMessageKey = "error.CP89.mainPoolAllowanceExceeded", Some(Seq("15"))))
}
"validated when CP672 is large enough to make the total -ve and any +ve claim is made" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp78 = Some(100), // writtenDownValueBroughtForward
cp82 = Some(100), // additionsQualifyingWritingDownAllowanceMainPool
cp672 = Some(1000), // proceedsFromDisposalsFromMainPool
cpAux2 = 100,
cato21 = 10
)
CP89(0).validate(stubTestComputationsRetriever) shouldBe Set()
CP89(1).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP89"), errorMessageKey = "error.CP89.mainPoolAllowanceExceeded", Some(Seq("0"))))
}
"validate when ceased trading but no value entered" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(true))
CP89(None).validate(stubTestComputationsRetriever) shouldBe Set()
}
"validate when ceased trading not set" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever()
CP89(None).validate(stubTestComputationsRetriever) shouldBe Set()
}
"fails validation when negative" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(false))
CP89(-1).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP89"), errorMessageKey = "error.CP89.mustBeZeroOrPositive"))
}
}
"(CP668) Writing Down Allowance claimed from Special rate pool" should {
"validates correctly when not greater than MAX( 0, SpecialPool% * ( CP666 + CPaux3 - CP667) )" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp666 = Some(100), // writtenDownValueOfSpecialRatePoolBroughtForward
cp667 = Some(100), // proceedsFromDisposalsFromSpecialRatePool
cpAux3 = 100,
cato22 = 10
)
CP668(10).validate(stubTestComputationsRetriever) shouldBe Set()
CP668(11).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP668"), errorMessageKey = "error.CP668.specialRatePoolAllowanceExceeded", Some(Seq("10"))))
}
"fails validation when CP667 is large enough to make the total -ve and any +ve claim is made" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(
cp666 = Some(100), // writtenDownValueOfSpecialRatePoolBroughtForward
cp667 = Some(1000), // proceedsFromDisposalsFromSpecialRatePool
cpAux3 = 100,
cato22 = 10
)
CP668(0).validate(stubTestComputationsRetriever) shouldBe Set()
CP668(1).validate(stubTestComputationsRetriever) shouldBe Set(CtValidation(boxId = Some("CP668"), errorMessageKey = "error.CP668.specialRatePoolAllowanceExceeded", Some(Seq("0"))))
}
"validate when ceased trading but no value entered" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever(cpq8 = Some(true))
CP668(None).validate(stubTestComputationsRetriever) shouldBe Set()
}
"validate when ceased trading not set" in {
val stubTestComputationsRetriever = new MyStubbedComputationsRetriever()
CP668(None).validate(stubTestComputationsRetriever) shouldBe Set()
}
}
}
|
hmrc/ct-calculations
|
src/test/scala/uk/gov/hmrc/ct/computations/MachineryAndPlantValidationSpec.scala
|
Scala
|
apache-2.0
| 21,860 |
package models.persistance
import models.LocalDirectory
import models.LocalDirectoryTable
import play.api.db.slick.Config.driver.simple._
object LocalDirectoryDAO {
val localDirectories = TableQuery[LocalDirectoryTable]
def getAllDirectories() = { implicit session: Session =>
localDirectories.list
}
def createLocalDirectory(path: String) = { implicit session: Session =>
localDirectories.insert(new LocalDirectory(None, path, new java.sql.Timestamp(System.currentTimeMillis())))
}
}
|
seqprodbio/restoule
|
app/models/persistance/LocalDirectoryDAO.scala
|
Scala
|
gpl-3.0
| 517 |
#!/bin/bash
scala $0 $@
exit
!#
/*
A demonstration of implicits for embedding
domain-specific languages in Scala. In this
case, the DSL creates an AST for regular expressions.
Exercise: Implement a matchesString method for RegEx
*/
abstract class RegEx {
def ~ (right : RegEx) = Sequence(this,right)
def || (right : RegEx) = Alternation(this,right)
def * = Repetition(this)
def matchesString(s : String) : Boolean =
throw new Exception("An exercise for the reader!")
}
// Charaters:
case class CharEx(val c : Char)
extends RegEx
// Sequences:
case class Sequence (val left : RegEx, val right : RegEx)
extends RegEx
// Alternation:
case class Alternation (val left : RegEx, val right : RegEx)
extends RegEx
// Kleene repetition:
case class Repetition (val exp : RegEx)
extends RegEx
// Empty:
case object Empty extends RegEx
// Building regex's manually is cumbersome:
val rx1 = Sequence(CharEx('f'),Sequence(CharEx('o'),CharEx('o')))
// Automatically convert strings into regexes:
implicit def stringToRegEx(s : String) : RegEx = {
var ex : RegEx = Empty
for (c <- s) {
ex = Sequence(ex,CharEx(c))
}
ex
}
// Implicits + operator overloading makes the syntax terse:
val rx2 = "baz" ~ ("foo" || "bar") * ;
println(rx2)
// Prints:
// Repetition(Sequence(Sequence(Sequence(Sequence(Empty,CharEx(b)),CharEx(a)),CharEx(z)),Alternation(Sequence(Sequence(Sequence(Empty,CharEx(f)),CharEx(o)),CharEx(o)),Sequence(Sequence(Sequence(Empty,CharEx(b)),CharEx(a)),CharEx(r)))))
|
pmsg863/xmgps
|
vertx3test/src/main/resources/twittleschool/read/Implicits.scala
|
Scala
|
apache-2.0
| 1,515 |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2015-2021 Andre White.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.truthencode.ddo.model.feats
import io.truthencode.ddo.model.classes.HeroicCharacterClass
import io.truthencode.ddo.model.classes.HeroicCharacterClass.Artificer
import io.truthencode.ddo.model.feats.ClassFeat.ImprovedConstructEssence
import io.truthencode.ddo.model.race.Race
import io.truthencode.ddo.model.race.Race.Warforged
import io.truthencode.ddo.support.requisite.{RequiresAllOfClass, RequiresAllOfFeat, RequiresNoneOfRace}
/**
* Created by adarr on 4/3/2017.
*/
protected[feats] trait ConstructExemplar
extends ClassRestricted with RequiresAllOfClass with RequiresNoneOfRace with RequiresAllOfFeat
with Passive {
self: EpicFeat =>
override def allOfFeats: Seq[Feat] = List(ImprovedConstructEssence)
override def noneOfRace: Seq[(Race, Int)] = List((Warforged, 1))
override def allOfClass: Seq[(HeroicCharacterClass, Int)] = List((Artificer, 12))
}
|
adarro/ddo-calc
|
subprojects/common/ddo-core/src/main/scala/io/truthencode/ddo/model/feats/ConstructExemplar.scala
|
Scala
|
apache-2.0
| 1,568 |
package nodes.util
import breeze.linalg.SparseVector
import org.apache.spark.rdd.RDD
import workflow.Estimator
import scala.reflect.ClassTag
/**
* An Estimator that chooses the most frequently observed sparse features when training,
* and produces a transformer which builds a sparse vector out of them
*
* Deterministically orders the feature mappings first by decreasing number of appearances,
* then by earliest appearance in the RDD
*
* @param numFeatures The number of features to keep
*/
case class CommonSparseFeatures[T : ClassTag](numFeatures: Int) extends Estimator[Seq[(T, Double)], SparseVector[Double]] {
// Ordering that compares (feature, frequency) pairs according to their frequencies
val ordering = new Ordering[(T, (Int, Long))] {
def compare(x: (T, (Int, Long)), y: (T, (Int, Long))): Int = {
if (x._2._1 == y._2._1) {
x._2._2.compare(y._2._2)
} else {
x._2._1.compare(y._2._1)
}
}
}
override def fit(data: RDD[Seq[(T, Double)]]): SparseFeatureVectorizer[T] = {
val featureOccurrences = data.flatMap(identity).zipWithUniqueId().map(x => (x._1._1, (1, x._2)))
// zip with unique ids and take the smallest unique id for a given feature to get
// a deterministic ordering
val featureFrequenciesWithUniqueId = featureOccurrences.reduceByKey {
(x, y) => (x._1 + y._1, Math.min(x._2, y._2))
}
val mostCommonFeatures = featureFrequenciesWithUniqueId.top(numFeatures)(ordering).map(_._1)
val featureSpace = mostCommonFeatures.zipWithIndex.toMap
new SparseFeatureVectorizer(featureSpace)
}
}
|
o0neup/keystone
|
src/main/scala/nodes/util/CommonSparseFeatures.scala
|
Scala
|
apache-2.0
| 1,605 |
import scala.reflect.runtime.universe._
import scala.reflect.runtime.{currentMirror => cm}
import scala.tools.reflect.{ToolBox, ToolBoxError}
object Test extends dotty.runtime.LegacyApp {
val tb = cm.mkToolBox()
try tb.parse("f(x")
catch {
case ToolBoxError(msg, _) => println(msg)
}
}
|
yusuke2255/dotty
|
tests/pending/run/t7331b.scala
|
Scala
|
bsd-3-clause
| 299 |
package it.jugtofunprog
object Sugar {;import org.scalaide.worksheet.runtime.library.WorksheetSupport._; def main(args: Array[String])=$execute{;$skip(695);
// Given n>0 find all pairs i and j where 1 <= j <= i <= n and i+j is prime
/** Java 8 version (by Mario Fusco)
http://www.slideshare.net/mariofusco/monadic-java
Stream.iterate(1, i -> i+1).limit(n)
.flatMap(i -> Stream.iterate(1, j -> j+1).limit(n)
.map(j -> new int[]{i, j}))
.filter(pair -> isPrime(pair[0] + pair[1]))
.collect(toList());
public boolean isPrime(int n) {
return Stream.iterate(2, i -> i+1)
.limit((long) Math.sqrt(n))
.noneMatch(i -> n % i == 0);
}
*/
/** Scala version */
val n = 10;System.out.println("""n : Int = """ + $show(n ));$skip(70);
val pairs = for {
i <- 1 to n
j <- i to n
} yield (i, j);System.out.println("""pairs : scala.collection.immutable.IndexedSeq[(Int, Int)] = """ + $show(pairs ));$skip(169);
def isPrime(num: Int) = {
val hasDiv = (2 to Math.sqrt(num).toInt) exists (d => num % d == 0)
!hasDiv
};System.out.println("""isPrime: (num: Int)Boolean""");$skip(46); val res$0 =
pairs filter (p => isPrime(p._1 + p._2));System.out.println("""res0: scala.collection.immutable.IndexedSeq[(Int, Int)] = """ + $show(res$0))}
}
|
vraffy/JugToFunProg
|
jtfp-scala/.worksheet/src/it.jugtofunprog.Sugar.scala
|
Scala
|
apache-2.0
| 1,616 |
package blended.jms.bridge.internal
import akka.stream.KillSwitch
import blended.jms.utils.IdAwareConnectionFactory
import blended.streams.message.FlowEnvelope
import blended.testsupport.RequiresForkedJVM
import scala.concurrent.duration._
import org.osgi.framework.BundleActivator
import blended.jms.utils.BlendedSingleConnectionFactory
import blended.jms.utils.BlendedJMSConnectionConfig
import domino.DominoActivator
import blended.akka.ActorSystemWatching
import blended.jms.utils.BlendedJMSConnection
import javax.jms._
import blended.testsupport.BlendedTestSupport
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
@RequiresForkedJVM
class SessionFailRetrySpec extends BridgeSpecSupport {
override def baseDir: String = new File(BlendedTestSupport.projectTestOutput, "brokenExternal").getAbsolutePath()
private val sessionOk: AtomicBoolean = new AtomicBoolean(true)
private val extActivator = new DominoActivator with ActorSystemWatching {
whenBundleActive {
whenActorSystemAvailable { cfg =>
val external = new BlendedSingleConnectionFactory(
config = BlendedJMSConnectionConfig.defaultConfig.copy(
vendor = "activemq",
provider = "external",
keepAliveEnabled = false,
jmxEnabled = false,
cf = Some(new ConnectionFactory {
override def createConnection(): Connection = {
val con = new Connection {
override def createSession(x$1: Boolean, x$2: Int): Session =
if (sessionOk.get()) {
new Session {
override def createBytesMessage(): BytesMessage = throw new JMSException("Boom")
override def createMapMessage(): MapMessage = throw new JMSException("Boom")
override def createMessage(): Message = throw new JMSException("Boom")
override def createObjectMessage(): ObjectMessage = throw new JMSException("Boom")
override def createObjectMessage(x$1: Serializable): ObjectMessage =
throw new JMSException("Boom")
override def createStreamMessage(): StreamMessage = throw new JMSException("Boom")
override def createTextMessage(): TextMessage = throw new JMSException("Boom")
override def createTextMessage(x$1: String): TextMessage = throw new JMSException("Boom")
override def getTransacted(): Boolean = throw new JMSException("Boom")
override def getAcknowledgeMode(): Int = throw new JMSException("Boom")
override def commit(): Unit = throw new JMSException("Boom")
override def rollback(): Unit = throw new JMSException("Boom")
override def close(): Unit = throw new JMSException("Boom")
override def recover(): Unit = throw new JMSException("Boom")
override def getMessageListener(): MessageListener = throw new JMSException("Boom")
override def setMessageListener(x$1: MessageListener): Unit = throw new JMSException("Boom")
override def run(): Unit = throw new JMSException("Boom")
override def createProducer(x$1: Destination): MessageProducer = throw new JMSException("Boom")
override def createConsumer(x$1: Destination): MessageConsumer = throw new JMSException("Boom")
override def createConsumer(x$1: Destination, x$2: String): MessageConsumer =
throw new JMSException("Boom")
override def createConsumer(x$1: Destination, x$2: String, x$3: Boolean): MessageConsumer =
throw new JMSException("Boom")
override def createQueue(x$1: String): Queue = throw new JMSException("Boom")
override def createTopic(x$1: String): Topic = throw new JMSException("Boom")
override def createDurableSubscriber(x$1: Topic, x$2: String): TopicSubscriber =
throw new JMSException("Boom")
override def createDurableSubscriber(x$1: Topic, x$2: String, x$3: String, x$4: Boolean)
: TopicSubscriber = throw new JMSException("Boom")
override def createBrowser(x$1: Queue): QueueBrowser = throw new JMSException("Boom")
override def createBrowser(x$1: Queue, x$2: String): QueueBrowser =
throw new JMSException("Boom")
override def createTemporaryQueue(): TemporaryQueue = throw new JMSException("Boom")
override def createTemporaryTopic(): TemporaryTopic = throw new JMSException("Boom")
override def unsubscribe(x$1: String): Unit = throw new JMSException("Boom")
}
} else {
throw new JMSException("Cant create session")
}
override def getClientID(): String = "foo"
override def setClientID(x$1: String): Unit = {}
override def getMetaData(): ConnectionMetaData = ???
override def getExceptionListener(): ExceptionListener = ???
override def setExceptionListener(x$1: ExceptionListener): Unit = {}
override def start(): Unit = {}
override def stop(): Unit = {}
override def close(): Unit = {}
override def createConnectionConsumer(x$1: Destination, x$2: String, x$3: ServerSessionPool, x$4: Int)
: ConnectionConsumer = ???
override def createDurableConnectionConsumer(
x$1: Topic,
x$2: String,
x$3: String,
x$4: ServerSessionPool,
x$5: Int
): ConnectionConsumer = ???
}
new BlendedJMSConnection("activemq", "external", con)
}
override def createConnection(user: String, password: String): Connection = createConnection()
})
),
Some(bundleContext)
)(cfg.system)
external.providesService[ConnectionFactory, IdAwareConnectionFactory](
Map("vendor" -> "activemq", "provider" -> "external", "brokerName" -> "broker2")
)
}
}
}
override def bundles: Seq[(String, BundleActivator)] = super.bundles ++ Seq(("bridge.external", extActivator))
private def sendOutbound(
cf: IdAwareConnectionFactory,
timeout: FiniteDuration,
msgCount: Int,
track: Boolean
): KillSwitch = {
val msgs: Seq[FlowEnvelope] = generateMessages(msgCount) { env =>
env
.withHeader(destHeader(headerCfg.prefix), s"sampleOut")
.get
.withHeader(headerCfg.headerTrack, track)
.get
}.get
sendMessages("bridge.data.out.activemq.external", cf, timeout)(msgs: _*)
}
"The outbound bridge should " - {
"forward messages to the retry queue in case a session for the outbound jms provider could not be created" in logException {
val timeout: FiniteDuration = 30.seconds
val msgCount = 2
val actorSys = system(registry)
val internal = namedJmsConnectionFactory(registry, mustConnect = true, timeout = timeout)(
vendor = "activemq",
provider = "internal"
).get
val switch = sendOutbound(internal, timeout, msgCount, track = false)
3.until(registry.getBundleContext().getBundles().size).foreach { i =>
registry.getBundleContext().getBundle(i).stop()
}
Thread.sleep(5000)
val messages: List[FlowEnvelope] =
consumeMessages(
cf = internal,
destName = "bridge.data.out.activemq.external",
expected = msgCount,
timeout = timeout
)(actorSys).get
messages should have size (msgCount)
messages.foreach { env =>
env.header[Unit]("UnitProperty") should be(Some(()))
}
switch.shutdown()
}
}
}
|
woq-blended/blended
|
blended.jms.bridge/src/test/scala/blended/jms/bridge/internal/SessionFailRetrySpec.scala
|
Scala
|
apache-2.0
| 8,362 |
/*
Copyright 2014 - 2015 Janek Bogucki
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.scalacraft.domain.v2.internal.ex
/**
* Exception to throw when an element in a list is null.
*
* This is not part of the public API because the public API does not support
* constructor arguments that embed nulls.
* @param paramName The name of the parameter with the null element
* @param index The index of the null element
*/
class NullElementException(val paramName: String, val index: Int)
extends IllegalArgumentException(s"$paramName($index)")
|
janekdb/scalacraft-domain
|
src/main/scala/com/scalacraft/domain/v2/internal/ex/NullElementException.scala
|
Scala
|
apache-2.0
| 1,095 |
/*
* The MIT License
*
* Copyright (c) 2017 Fulcrum Genomics LLC
*
* 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 com.fulcrumgenomics.umi
import com.fulcrumgenomics.FgBioDef._
import com.fulcrumgenomics.bam.Bams
import com.fulcrumgenomics.bam.api.{SamRecord, SamSource}
import com.fulcrumgenomics.cmdline.{ClpGroups, FgBioTool}
import com.fulcrumgenomics.commons.collection.BetterBufferedIterator
import com.fulcrumgenomics.commons.util.{LazyLogging, NumericCounter, SimpleCounter}
import com.fulcrumgenomics.sopt.{arg, clp}
import com.fulcrumgenomics.util.Metric.{Count, Proportion}
import com.fulcrumgenomics.util._
import htsjdk.samtools.util.{Interval, IntervalList, Murmur3, OverlapDetector}
import org.apache.commons.math3.distribution.BinomialDistribution
import scala.collection.mutable
import scala.util.Failure
/**
* Companion object for CollectDuplexSeqMetrics that contains various constants and types,
* including all the various [[com.fulcrumgenomics.util.Metric]] sub-types produced by the program.
*/
object CollectDuplexSeqMetrics {
// File extensions for all the files produced
val FamilySizeMetricsExt: String = ".family_sizes.txt"
val DuplexFamilySizeMetricsExt: String = ".duplex_family_sizes.txt"
val UmiMetricsExt: String = ".umi_counts.txt"
val DuplexUmiMetricsExt: String = ".duplex_umi_counts.txt"
val YieldMetricsExt: String = ".duplex_yield_metrics.txt"
val PlotsExt: String = ".duplex_qc.pdf"
private val PlottingScript = "com/fulcrumgenomics/umi/CollectDuplexSeqMetrics.R"
/** Contains an AB and BA count of reads. */
private case class Pair(ab: Int, ba: Int)
/**
* Metrics produced by `CollectDuplexSeqMetrics` to quantify the distribution of different kinds of read family
* sizes. Three kinds of families are described:
*
* 1. _CS_ or _Coordinate & Strand_: families of reads that are grouped together by their unclipped 5'
* genomic positions and strands just as they are in traditional PCR duplicate marking
* 2. _SS_ or _Single Strand_: single-strand families that are each subsets of a CS family create by
* also using the UMIs to partition the larger family, but not linking up families that are
* created from opposing strands of the same source molecule.
* 3. _DS_ or _Double Strand_: families that are created by combining single-strand families that are from
* opposite strands of the same source molecule. This does **not** imply that all DS families are composed
* of reads from both strands; where only one strand of a source molecule is observed a DS family is
* still counted.
*
* @param family_size The family size, i.e. the number of read pairs grouped together into a family.
* @param cs_count The count of families with `size == family_size` when grouping just by coordinates and strand information.
* @param cs_fraction The fraction of all _CS_ families where `size == family_size`.
* @param cs_fraction_gt_or_eq_size The fraction of all _CS_ families where `size >= family_size`.
* @param ss_count The count of families with `size == family_size` when also grouping by UMI to create single-strand families.
* @param ss_fraction The fraction of all _SS_ families where `size == family_size`.
* @param ss_fraction_gt_or_eq_size The fraction of all _SS_ families where `size >= family_size`.
* @param ds_count The count of families with `size == family_size`when also grouping by UMI and merging single-strand
* families from opposite strands of the same source molecule.
* @param ds_fraction The fraction of all _DS_ families where `size == family_size`.
* @param ds_fraction_gt_or_eq_size The fraction of all _DS_ families where `size >= family_size`.
*/
case class FamilySizeMetric(family_size: Int,
var cs_count: Count = 0,
var cs_fraction: Proportion = 0,
var cs_fraction_gt_or_eq_size: Proportion = 0,
var ss_count: Count = 0,
var ss_fraction: Proportion = 0,
var ss_fraction_gt_or_eq_size: Proportion = 0,
var ds_count: Count = 0,
var ds_fraction: Proportion = 0,
var ds_fraction_gt_or_eq_size: Proportion =0
) extends Metric
/**
* Metrics produced by `CollectDuplexSeqMetrics` to describe the distribution of double-stranded (duplex)
* tag families in terms of the number of reads observed on each strand.
*
* We refer to the two strands as `ab` and `ba` because we identify the two strands by observing the same pair of
* UMIs (A and B) in opposite order (A->B vs B->A). Which strand is `ab` and which is `ba` is largely arbitrary, so
* to make interpretation of the metrics simpler we use a definition here that for a given tag family
* `ab` is the sub-family with more reads and `ba` is the tag family with fewer reads.
*
* @param ab_size The number of reads in the `ab` sub-family (the larger sub-family) for this double-strand tag family.
* @param ba_size The number of reads in the `ba` sub-family (the smaller sub-family) for this double-strand tag family.
* @param count The number of families with the `ab` and `ba` single-strand families of size `ab_size` and `ba_size`.
* @param fraction The fraction of all double-stranded tag families that have `ab_size` and `ba_size`.
* @param fraction_gt_or_eq_size The fraction of all double-stranded tag families that have
* `ab reads >= ab_size` and `ba reads >= ba_size`.
*/
case class DuplexFamilySizeMetric(ab_size: Int,
ba_size: Int,
count: Count = 0,
var fraction: Proportion = 0,
var fraction_gt_or_eq_size: Proportion = 0
) extends Metric with Ordered[DuplexFamilySizeMetric] {
/** Orders by ab_size, then ba_size. */
override def compare(that: DuplexFamilySizeMetric): Int = {
var retval = this.ab_size - that.ab_size
if (retval == 0) retval = this.ba_size - that.ba_size
retval
}
}
/**
* Metrics produced by `CollectDuplexSeqMetrics` that are sampled at various levels of coverage, via random
* downsampling, during the construction of duplex metrics. The downsampling is done in such a way that the
* `fraction`s are approximate, and not exact, therefore the `fraction` field should only be interpreted as a guide
* and the `read_pairs` field used to quantify how much data was used.
*
* See `FamilySizeMetric` for detailed definitions of `CS`, `SS` and `DS` as used below.
*
* @param fraction The approximate fraction of the full dataset that was used to generate the remaining values.
* @param read_pairs The number of read pairs upon which the remaining metrics are based.
* @param cs_families The number of _CS_ (Coordinate & Strand) families present in the data.
* @param ss_families The number of _SS_ (Single-Strand by UMI) families present in the data.
* @param ds_families The number of _DS_ (Double-Strand by UMI) families present in the data.
* @param ds_duplexes The number of _DS_ families that had the minimum number of observations on both strands to be
* called duplexes (default = 1 read on each strand).
* @param ds_fraction_duplexes The fraction of _DS_ families that are duplexes (`ds_duplexes / ds_families`).
* @param ds_fraction_duplexes_ideal The fraction of _DS_ families that should be duplexes under an idealized model
* where each strand, `A` and `B`, have equal probability of being sampled, given
* the observed distribution of _DS_ family sizes.
*/
case class DuplexYieldMetric(fraction: Proportion,
read_pairs: Count,
cs_families: Count,
ss_families: Count,
ds_families: Count,
ds_duplexes: Count,
ds_fraction_duplexes: Proportion,
ds_fraction_duplexes_ideal: Proportion) extends Metric
/**
* Metrics produced by `CollectDuplexSeqMetrics` describing the set of observed UMI sequences and the
* frequency of their observations. The UMI sequences reported may have been corrected using information
* within a double-stranded tag family. For example if a tag family is comprised of three read pairs with
* UMIs `ACGT-TGGT`, `ACGT-TGGT`, and `ACGT-TGGG` then a consensus UMI of `ACGT-TGGT` will be generated,
* and three raw observations counted for each of `ACGT` and `TGGT`, and no observations counted for `TGGG`.
*
* @param umi The UMI sequence, possibly-corrected.
* @param raw_observations The number of read pairs in the input BAM that observe the UMI (after correction).
* @param raw_observations_with_errors The subset of raw-observations that underwent any correction.
* @param unique_observations The number of double-stranded tag families (i.e unique double-stranded molecules)
* that observed the UMI.
* @param fraction_raw_observations The fraction of all raw observations that the UMI accounts for.
* @param fraction_unique_observations The fraction of all unique observations that the UMI accounts for.
*/
case class UmiMetric(umi: String,
var raw_observations: Count = 0,
var raw_observations_with_errors: Count = 0,
var unique_observations: Count = 0,
var fraction_raw_observations: Proportion = 0,
var fraction_unique_observations: Proportion = 0
) extends Metric
/**
* Metrics produced by `CollectDuplexSeqMetrics` describing the set of observed duplex UMI sequences and the
* frequency of their observations. The UMI sequences reported may have been corrected using information
* within a double-stranded tag family. For example if a tag family is comprised of three read pairs with
* UMIs `ACGT-TGGT`, `ACGT-TGGT`, and `ACGT-TGGG` then a consensus UMI of `ACGT-TGGT` will be generated.
*
* UMI pairs are normalized within a tag family so that observations are always reported as if they came
* from a read pair with read 1 on the positive strand (F1R2). Another way to view this is that for FR or RF
* read pairs, the duplex UMI reported is the UMI from the positive strand read followed by the UMI from the
* negative strand read. E.g. a read pair with UMI `AAAA-GGGG` and with R1 on the negative strand and R2 on
* the positive strand, will be reported as `GGGG-AAAA`.
*
* @param umi The duplex UMI sequence, possibly-corrected.
* @param raw_observations The number of read pairs in the input BAM that observe the duplex UMI (after correction).
* @param raw_observations_with_errors The subset of raw observations that underwent any correction.
* @param unique_observations The number of double-stranded tag families (i.e unique double-stranded molecules)
* that observed the duplex UMI.
* @param fraction_raw_observations The fraction of all raw observations that the duplex UMI accounts for.
* @param fraction_unique_observations The fraction of all unique observations that the duplex UMI accounts for.
* @param fraction_unique_observations_expected The fraction of all unique observations that are expected to be
* attributed to the duplex UMI based on the `fraction_unique_observations`
* of the two individual UMIs.
*/
case class DuplexUmiMetric(umi: String,
var raw_observations: Count = 0,
var raw_observations_with_errors: Count = 0,
var unique_observations: Count = 0,
var fraction_raw_observations: Proportion = 0,
var fraction_unique_observations: Proportion = 0,
var fraction_unique_observations_expected: Proportion = 0
) extends Metric
}
@clp(group=ClpGroups.Umi, description=
"""
|Collects a suite of metrics to QC duplex sequencing data.
|
|## Inputs
|
|The input to this tool must be a BAM file that is either:
|
|1. The exact BAM output by the `GroupReadsByUmi` tool (in the sort-order it was produced in)
|2. A BAM file that has MI tags present on all reads (usually set by `GroupReadsByUmi` and has
| been sorted with `SortBam` into `TemplateCoordinate` order.
|
|Calculation of metrics may be restricted to a set of regions using the `--intervals` parameter. This
|can significantly affect results as off-target reads in duplex sequencing experiments often have very
|different properties than on-target reads due to the lack of enrichment.
|
|Several metrics are calculated related to the fraction of tag families that have duplex coverage. The
|definition of "duplex" is controlled by the `--min-ab-reads` and `--min-ba-reads` parameters. The default
|is to treat any tag family with at least one observation of each strand as a duplex, but this could be
|made more stringent, e.g. by setting `--min-ab-reads=3 --min-ba-reads=3`. If different thresholds are
|used then `--min-ab-reads` must be the higher value.
|
|## Outputs
|
|The following output files are produced:
|
|1. **<output>.family_sizes.txt**: metrics on the frequency of different types of families of different sizes
|2. **<output>.duplex_family_sizes.txt**: metrics on the frequency of duplex tag families by the number of
| observations from each strand
|3. **<output>.duplex_yield_metrics.txt**: summary QC metrics produced using 5%, 10%, 15%...100% of the data
|4. **<output>.umi_counts.txt**: metrics on the frequency of observations of UMIs within reads and tag families
|5. **<output>.duplex_qc.pdf**: a series of plots generated from the preceding metrics files for visualization
|6. **<output>.duplex_umi_counts.txt**: (optional) metrics on the frequency of observations of duplex UMIs within
| reads and tag families. This file is only produced _if_ the `--duplex-umi-counts` option is used as it
| requires significantly more memory to track all pairs of UMIs seen when a large number of UMI sequences are present.
|
|Within the metrics files the prefixes `CS`, `SS` and `DS` are used to mean:
|
|* **CS**: tag families where membership is defined solely on matching genome coordinates and strand
|* **SS**: single-stranded tag families where membership is defined by genome coordinates, strand and UMI;
| ie. 50/A and 50/B are considered different tag families.
|* **DS**: double-stranded tag families where membership is collapsed across single-stranded tag families
| from the same double-stranded source molecule; i.e. 50/A and 50/B become one family
|
|## Requirements
|
|For plots to be generated R must be installed and the ggplot2 package installed with suggested
|dependencies. Successfully executing the following in R will ensure a working installation:
|
|```R
|install.packages("ggplot2", repos="http://cran.us.r-project.org", dependencies=TRUE)
|```
""")
class CollectDuplexSeqMetrics
( @arg(flag='i', doc="Input BAM file generated by `GroupReadsByUmi`.") val input: PathToBam,
@arg(flag='o', doc="Prefix of output files to write.") val output: PathPrefix,
@arg(flag='l', doc="Optional set of intervals over which to restrict analysis.") val intervals: Option[PathToIntervals] = None,
@arg(flag='d', doc="Description of data set used to label plots. Defaults to sample/library.") val description: Option[String] = None,
@arg(flag='u', doc="If true, produce the .duplex_umi_counts.txt file with counts of duplex UMI observations.") val duplexUmiCounts: Boolean = false,
@arg(flag='a', doc="Minimum AB reads to call a tag family a 'duplex'.") val minAbReads: Int = 1,
@arg(flag='b', doc="Minimum BA reads to call a tag family a 'duplex'.") val minBaReads: Int = 1,
@arg(flag='t', doc="The tag containing the raw UMI.") val umiTag: String = ConsensusTags.UmiBases,
@arg(flag='T', doc="The output tag for UMI grouping.") val miTag: String = ConsensusTags.MolecularId,
private val generatePlots: Boolean = true // not a CLP arg - here to allow disabling of plots to speed up testing
) extends FgBioTool with LazyLogging {
import CollectDuplexSeqMetrics._
// Validate inputs
Io.assertReadable(input)
Io.assertCanWriteFile(output)
intervals.foreach(Io.assertReadable)
validate(minAbReads >= 1, "min-ab-reads must be >= 1")
validate(minBaReads >= 0, "min-ba-reads must be >= 0")
validate(minBaReads <= minAbReads, "min-ab-reads must be >= min-ba-reads")
// Setup a whole bunch of counters for various things!
private val dsLevels = Range.inclusive(1, 20).toArray.map(_ * 0.05)
private val startStopFamilyCounter = dsLevels.map(f => f -> new NumericCounter[Int]).toMap
private val duplexFamilyCounter = dsLevels.map(f => f -> new SimpleCounter[Pair]).toMap
private val umiMetricsMap = mutable.Map[String,UmiMetric]()
private val duplexUmiMetricsMap = mutable.Map[String,DuplexUmiMetric]()
// A consensus caller used to generate consensus UMI sequences
private val consensusBuilder = new SimpleConsensusCaller()
// A Murmur3 hash used to do the downsampling of the reads by generating an int hash of the read name
// scaling it into the range 0-1 and then storing it a a transient attribute on the SAMRecord
private val hasher = new Murmur3(42)
private val MaxIntAsDouble = Int.MaxValue.toDouble
private val HashKey = "_P".intern()
override def execute(): Unit = {
// Build the iterator we'll use based on whether or not we're restricting to a set of intervals
val in = SamSource(input)
val _filteredIterator = in.iterator.filter(r => r.paired && r.mapped && r.mateMapped && r.firstOfPair && !r.secondary && !r.supplementary)
val iterator = intervals match {
case None => _filteredIterator
case Some(path) =>
val ilist = IntervalList.fromFile(path.toFile).uniqued(false)
val detector = new OverlapDetector[Interval](0,0)
detector.addAll(ilist.getIntervals, ilist.getIntervals)
_filteredIterator.filter { rec =>
val (start, end) = if (rec.refIndex == rec.mateRefIndex) Bams.insertCoordinates(rec) else (rec.start, rec.end)
detector.overlapsAny(new Interval(rec.refName, start, end))
}
}
// Default the decription to something sensible if one wasn't provided
val description = this.description.getOrElse { plotDescription(in, input) }
// Do a bunch of metrics collection
collect(iterator)
in.safelyClose()
// Write the output files
write(description)
}
/** Consumes from the iterator and collects information internally from which to generate metrics. */
def collect(iterator: Iterator[SamRecord]): Unit = {
val buffered = iterator.bufferBetter
val progress = ProgressLogger(logger)
while (buffered.hasNext) {
val group = takeNextGroup(buffered)
// Assign reads a random number between 0 and 1 inclusive based on their read name
group.foreach { rec =>
val intHash = math.abs(this.hasher.hashUnencodedChars(rec.name))
val doubleHash = intHash / MaxIntAsDouble
rec.transientAttrs(HashKey) = doubleHash
}
// Update the counters
this.dsLevels.foreach { fraction =>
val downsampledGroup = group.filter(_.transientAttrs[Double](HashKey) <= fraction)
if (downsampledGroup.nonEmpty) {
this.startStopFamilyCounter(fraction).count(downsampledGroup.size)
val dsGroups = downsampledGroup.groupBy(r => r[String](this.miTag).takeWhile(_ != '/')).values.toSeq
dsGroups.foreach { dsGroup =>
// Family sizes first
val ssGroups = dsGroup.groupBy(r => r[String](this.miTag)).values.toSeq
val counts = ssGroups.map(_.size).sortBy(x => -x)
val ab = counts.head
val ba = if (counts.length == 2) counts(1) else 0
duplexFamilyCounter(fraction).count(Pair(ab, ba))
// Then the UMIs
if (fraction == 1.0) updateUmiMetrics(ssGroups)
}
}
}
// Record progress
group.foreach(progress.record)
}
}
/**
* Updates all the various metrics for the UMIs contained on the given records.
*
* @param ssGroups a Seq of length one or two containing the one or two single-stranded tag families
* that comprise an individual double-stranded tag family. If there are two single-stranded
* tag families, there is no guarantee of their ordering within the Seq.
*/
private[umi] def updateUmiMetrics(ssGroups: Seq[Seq[SamRecord]]): Unit = {
// ab and ba are just names here and _don't_ imply top/bottom strand, just different strands
val (ab, ba) = ssGroups match {
case Seq(a, b) => (a, b)
case Seq(a) => (a, Seq.empty)
case _ => unreachable(s"Found ${ssGroups.size} single strand families in a double strand family!")
}
val umi1s = IndexedSeq.newBuilder[String] // ab UMI 1 (and ba UMI 2) sequences
val umi2s = IndexedSeq.newBuilder[String] // ab UMI 2 (and ba UMI 1) sequences
ab.iterator.map(r => r[String](this.umiTag).split('-')).foreach { case Array(u1, u2) => umi1s += u1; umi2s += u2 }
ba.iterator.map(r => r[String](this.umiTag).split('-')).foreach { case Array(u1, u2) => umi1s += u2; umi2s += u1 }
val Seq(abConsensusUmi, baConsensusUmi) = Seq(umi1s, umi2s).map(_.result()).map{ umis =>
val consensus = this.consensusBuilder.callConsensus(umis)
val metric = this.umiMetricsMap.getOrElseUpdate(consensus, UmiMetric(umi=consensus))
metric.raw_observations += umis.size
metric.unique_observations += 1
metric.raw_observations_with_errors += umis.filterNot(_ == consensus).size
consensus
}
if (this.duplexUmiCounts) {
// Make both possible consensus duplex UMIs. We want to normalize to the pairing/orientation that we'd
// see on an F1R2 read-pair. We can get this either by direct observation in the `ab` set of reads,
// or by seeing an F2R1 in the `ba` set of reads. This logic will pick more or less arbitrarily if the
// group of reads doesn't consist of the expected all F1R2s in one set and all F2R1s in the other set.
val duplexUmis = Seq(s"$abConsensusUmi-$baConsensusUmi", s"$baConsensusUmi-$abConsensusUmi")
val duplexUmi = if (ab.exists(r => r.firstOfPair && r.positiveStrand) || ba.exists(r => r.secondOfPair && r.positiveStrand)) duplexUmis(0) else duplexUmis(1)
val metric = this.duplexUmiMetricsMap.getOrElseUpdate(duplexUmi, DuplexUmiMetric(umi=duplexUmi))
metric.raw_observations += ab.size + ba.size
metric.unique_observations += 1
metric.raw_observations_with_errors += (ab.iterator ++ ba.iterator).map(r => r[String](this.umiTag)).count(umi => !duplexUmis.contains(umi))
}
}
/** Generates the family size metrics from the current observations. */
def familySizeMetrics: Seq[FamilySizeMetric] = {
val map = mutable.Map[Int, FamilySizeMetric]()
val startStopCounter = this.startStopFamilyCounter(1.0)
val duplexCounter = this.duplexFamilyCounter(1.0)
// Add information about families grouped by genomic location alone
startStopCounter.foreach { case (size, count) =>
map.getOrElseUpdate(size, FamilySizeMetric(family_size=size)).cs_count += count
}
// Add information about the families grouped by ss and ds families
duplexCounter.foreach { case (Pair(ab, ba), count) =>
map.getOrElseUpdate(ab, FamilySizeMetric(family_size=ab)).ss_count += count
if (ba > 0) map.getOrElseUpdate(ba, FamilySizeMetric(family_size=ba)).ss_count += count
map.getOrElseUpdate(ab+ba, FamilySizeMetric(family_size=ab+ba)).ds_count += count
}
// Get a sorted Seq of metrics
val metrics = map.values.toIndexedSeq.sortBy(_.family_size)
// Fill in the fractions and cumulative fractions
val csTotal = metrics.map(_.cs_count).sum.toDouble
val ssTotal = metrics.map(_.ss_count).sum.toDouble
val dsTotal = metrics.map(_.ds_count).sum.toDouble
var csInverseCumulativeFraction = 0.0
var ssInverseCumulativeFraction = 0.0
var dsInverseCumulativeFraction = 0.0
metrics.foreach { m =>
m.cs_fraction = m.cs_count / csTotal
m.ss_fraction = m.ss_count / ssTotal
m.ds_fraction = m.ds_count / dsTotal
m.cs_fraction_gt_or_eq_size = 1 - csInverseCumulativeFraction
m.ss_fraction_gt_or_eq_size = 1 - ssInverseCumulativeFraction
m.ds_fraction_gt_or_eq_size = 1 - dsInverseCumulativeFraction
csInverseCumulativeFraction += m.cs_fraction
ssInverseCumulativeFraction += m.ss_fraction
dsInverseCumulativeFraction += m.ds_fraction
}
metrics
}
/** Generates the duplex family size metrics from the current observations. */
def duplexFamilySizeMetrics: Seq[DuplexFamilySizeMetric] = {
val metrics = this.duplexFamilyCounter(1.0)
.map { case (Pair(ab, ba), count) => DuplexFamilySizeMetric(ab_size=ab, ba_size=ba, count=count) }
.toIndexedSeq.sorted
// Set the fractions
val total = metrics.map(_.count).sum.toDouble
metrics.foreach(m => m.fraction = m.count / total)
// Set the cumulative fractions - there's probably a smarter way to do this!
metrics.foreach { m =>
val countGtOrEq = metrics.iterator.filter(n => n.ab_size >= m.ab_size && n.ba_size >= m.ba_size).map(_.count).sum
m.fraction_gt_or_eq_size = countGtOrEq / total
}
metrics
}
/** Generates the duplex yield metrics from the current observations. */
def yieldMetrics: Seq[DuplexYieldMetric] = {
this.dsLevels.sorted.map { fraction =>
val startStopCounter = this.startStopFamilyCounter(fraction)
val duplexCounter = this.duplexFamilyCounter(fraction)
val dsFamilies = duplexCounter.map { case (Pair(a,b), count) => count }.sum
val countOfDuplexes = duplexCounter.map {
case (Pair(a,b), count) if a >= this.minAbReads && b >= this.minBaReads => count
case _ => 0
}.sum
val countOfDuplexesIdeal = duplexCounter.map { case (pair, count) => count * pDuplexIdeal(pair.ab + pair.ba) }.sum
DuplexYieldMetric(
fraction = fraction,
read_pairs = startStopCounter.totalMass.toLong,
cs_families = startStopCounter.total,
ss_families = duplexCounter.map { case (Pair(a,b), count) => if (b>0) count*2 else count }.sum,
ds_families = dsFamilies,
ds_duplexes = countOfDuplexes,
ds_fraction_duplexes = countOfDuplexes / dsFamilies.toDouble,
ds_fraction_duplexes_ideal = countOfDuplexesIdeal / dsFamilies.toDouble
)
}.toIndexedSeq
}
/** Generates the UMI metrics from the current observations. */
def umiMetrics: Seq[UmiMetric] = {
val metrics = this.umiMetricsMap.values.toIndexedSeq.sortBy(_.umi)
val rawTotal = metrics.map(_.raw_observations).sum.toDouble
val uniqueTotal = metrics.map(_.unique_observations).sum.toDouble
metrics.foreach { m =>
m.fraction_raw_observations = m.raw_observations / rawTotal
m.fraction_unique_observations = m.unique_observations / uniqueTotal
}
metrics
}
/** Generates the duplex UMI metrics from the current observations. */
def duplexUmiMetrics(umiMetrics: Seq[UmiMetric]): Seq[DuplexUmiMetric] = {
val singleUmiMetrics = umiMetrics.map(m => m.umi -> m).toMap
val metrics = this.duplexUmiMetricsMap.values.toIndexedSeq.sortBy(x => - x.unique_observations)
val rawTotal = metrics.map(_.raw_observations).sum.toDouble
val uniqueTotal = metrics.map(_.unique_observations).sum.toDouble
metrics.foreach { m =>
val Array(umi1, umi2) = m.umi.split('-')
m.fraction_raw_observations = m.raw_observations / rawTotal
m.fraction_unique_observations = m.unique_observations / uniqueTotal
m.fraction_unique_observations_expected = singleUmiMetrics(umi1).fraction_unique_observations * singleUmiMetrics(umi2).fraction_unique_observations
}
metrics
}
/**
* For a given family size/number of reads computes the probability that we would observed
* at least minAb & minBa reads under a binomial sampling model with p=0.5.
*/
def pDuplexIdeal(reads: Int): Double = {
if (reads < this.minAbReads + this.minBaReads) {
0
}
else {
val minSsReads = math.min(this.minAbReads, this.minBaReads)
// Here we can assert:
// a) reads >= minAbReads + minBaReads
// b) minSsReads <= minAbReads
// c) minSsReads <= minBaReads
// c) reads - minSsReads >= max(minAbReads, minBaReads)
// d) p(duplex == 1 | successes in [minSsReads..reads-minSsReads]
val binom = new BinomialDistribution(reads, 0.5)
Range.inclusive(minSsReads, reads - minSsReads)
.map(successes => binom.probability(successes))
.sum
}
}
/**
* Grabs the next group of records that all share the same start/stop/strand information. This can
* and will contain reads with different MIs!
*/
private def takeNextGroup(iterator: BetterBufferedIterator[SamRecord]): Seq[SamRecord] = {
val rec = iterator.head
val info = GroupReadsByUmi.ReadInfo(rec)
iterator.takeWhile(rec => GroupReadsByUmi.ReadInfo(rec) == info).toIndexedSeq
}
/** Writes out all the metrics and plots. */
private[umi] def write(description: String): Unit = {
val Seq(fsPath, dfsPath, umiPath, duplexUmiPath, yieldPath, pdfPath) =
Seq(FamilySizeMetricsExt, DuplexFamilySizeMetricsExt, UmiMetricsExt, DuplexUmiMetricsExt, YieldMetricsExt, PlotsExt).map { ext =>
output.getParent.resolve(s"${output.getFileName}${ext}")
}
Metric.write(fsPath, familySizeMetrics)
Metric.write(dfsPath, duplexFamilySizeMetrics)
Metric.write(yieldPath, yieldMetrics)
val umiMetricValues = umiMetrics
Metric.write(umiPath, umiMetricValues )
if (this.duplexUmiCounts) Metric.write(duplexUmiPath, duplexUmiMetrics(umiMetricValues))
if (generatePlots) {
Rscript.execIfAvailable(PlottingScript, fsPath.toString, dfsPath.toString, yieldPath.toString, umiPath.toString, pdfPath.toString, description) match {
case Failure(e) => logger.warning(s"Generation of PDF plots failed: ${e.getMessage}")
case _ => ()
}
}
}
}
|
fulcrumgenomics/fgbio
|
src/main/scala/com/fulcrumgenomics/umi/CollectDuplexSeqMetrics.scala
|
Scala
|
mit
| 32,716 |
/* Copyright 2017-19, Emmanouil Antonios Platanios. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.platanios.tensorflow.api.learn
/** Represents the mode that a model is on, while being used by a learner (e.g., training mode, evaluation mode, or
* prediction mode).
*
* @author Emmanouil Antonios Platanios
*/
sealed trait Mode {
val isTraining: Boolean
}
case object TRAINING extends Mode {
override val isTraining: Boolean = true
}
case object EVALUATION extends Mode {
override val isTraining: Boolean = false
}
case object INFERENCE extends Mode {
override val isTraining: Boolean = false
}
|
eaplatanios/tensorflow_scala
|
modules/api/src/main/scala/org/platanios/tensorflow/api/learn/Mode.scala
|
Scala
|
apache-2.0
| 1,164 |
package mgoeminne.scalaggplot.coord
/**
* Polar coordinates.
*
* The polar coordinate system is most commonly used for pie charts, which are a stacked bar chart in polar coordinates.
*
* == Examples ==
*
* TODO
*
* @param thetaFromX determines if the variable to map to angle must be x, or y. If true, x is used.
* @param start offset of starting point from 12 o'clock in radians
* @param clockwiseDirection if true, corresponds to clockwise; corresponds to anti-clockwise otherwise.
*
*/
case class polar( thetaFromX: Boolean = true,
start:Double = 0,
clockwiseDirection: Boolean = true) extends Coordinate
|
mgoeminne/scala-ggplot
|
src/main/scala/mgoeminne/scalaggplot/coord/polar.scala
|
Scala
|
lgpl-3.0
| 666 |
package io.udash.web.guide.views.ext.demo
import io.udash.css.CssView
import io.udash.web.guide.demos.AutoDemo
import io.udash.web.guide.styles.partials.GuideStyles
import scalatags.JsDom.all._
object JQueryCallbacksDemo extends AutoDemo with CssView {
private val (rendered, source) = {
import io.udash.bootstrap.button.UdashButton
import io.udash.wrappers.jquery._
import scalatags.JsDom.all._
import scala.scalajs.js
val callbacks = jQ.callbacks[js.Function1[(Int, Int), js.Any], (Int, Int)]()
callbacks.add((t: (Int, Int)) => {
val (a, b) = t
jQ("#jquery-callbacks-demo #plus").append(li(s"$a + $b = ${a + b}").render)
})
callbacks.add((t: (Int, Int)) => {
val (a, b) = t
jQ("#jquery-callbacks-demo #minus").append(li(s"$a - $b = ${a - b}").render)
})
callbacks.add((t: (Int, Int)) => {
val (a, b) = t
jQ("#jquery-callbacks-demo #mul").append(li(s"$a * $b = ${a * b}").render)
})
callbacks.add((t: (Int, Int)) => {
val (a, b) = t
jQ("#jquery-callbacks-demo #div").append(li(s"$a / $b = ${a / b}").render)
})
div(
"Plus:",
ul(id := "plus"),
"Minus:",
ul(id := "minus"),
"Multiply:",
ul(id := "mul"),
"Divide:",
ul(id := "div"),
br,
UdashButton()(_ => Seq[Modifier](
id := "fire", "Fire",
onclick := (() => {
callbacks.fire((1, 1))
callbacks.fire((3, 3))
callbacks.fire((7, 4))
callbacks.disable()
callbacks.fire((1, 2))
}))
).render
).render
}.withSourceCode
override protected def demoWithSource(): (Modifier, Iterator[String]) = {
(
div(
id := "jquery-callbacks-demo",
GuideStyles.frame,
GuideStyles.useBootstrap
)(rendered),
source.linesIterator
)
}
}
|
UdashFramework/udash-core
|
guide/guide/.js/src/main/scala/io/udash/web/guide/views/ext/demo/JQueryCallbacksDemo.scala
|
Scala
|
apache-2.0
| 1,870 |
/*
* 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.qsu
import slamdata.Predef.{StringContext, Symbol}
import quasar.RenderTree
import monocle.{Lens, PLens, Prism}
import scalaz.{Apply, Equal, Order, Show, Traverse1}
import scalaz.syntax.show._
import scalaz.std.option._
import scalaz.std.tuple._
sealed abstract class Access[A] {
def symbolic(value: A => Symbol): Access[Symbol] =
this match {
case Access.Id(i, a) =>
IdAccess.symbols
.headOption(i)
.fold(Access.id(i, value(a)))(Access.id(i, _))
case Access.Value(a) =>
Access.value(value(a))
}
}
object Access extends AccessInstances {
final case class Id[A](idAccess: IdAccess, src: A) extends Access[A]
final case class Value[A](src: A) extends Access[A]
def id[A]: Prism[Access[A], (IdAccess, A)] =
Prism.partial[Access[A], (IdAccess, A)] {
case Id(i, a) => (i, a)
} { case (i, a) => Id(i, a) }
def value[A]: Prism[Access[A], A] =
Prism.partial[Access[A], A] {
case Value(a) => a
} (Value(_))
def src[A]: Lens[Access[A], A] =
srcP[A, A]
def srcP[A, B]: PLens[Access[A], Access[B], A, B] =
PLens[Access[A], Access[B], A, B] {
case Id(_, a) => a
case Value(a) => a
} { b => {
case Id(i, _) => id(i, b)
case Value(_) => value(b)
}}
}
sealed abstract class AccessInstances extends AccessInstances0 {
implicit val traverse1: Traverse1[Access] =
new Traverse1[Access] {
def traverse1Impl[G[_]: Apply, A, B](fa: Access[A])(f: A => G[B]) =
Access.srcP[A, B].modifyF(f)(fa)
def foldMapRight1[A, B](fa: Access[A])(z: A => B)(f: (A, => B) => B) =
z(Access.src[A] get fa)
}
implicit def order[A: Order]: Order[Access[A]] =
Order.orderBy(generic)
implicit def renderTree[A: Show]: RenderTree[Access[A]] =
RenderTree.fromShowAsType("Access")
implicit def show[A: Show]: Show[Access[A]] =
Show.shows {
case Access.Id(i, a) => s"Id(${i.shows}, ${a.shows})"
case Access.Value(a) => s"Value(${a.shows})"
}
}
sealed abstract class AccessInstances0 {
implicit def equal[A: Equal]: Equal[Access[A]] =
Equal.equalBy(generic)
protected def generic[A](a: Access[A]) =
(Access.id.getOption(a), Access.value.getOption(a))
}
|
slamdata/slamengine
|
qsu/src/main/scala/quasar/qsu/Access.scala
|
Scala
|
apache-2.0
| 2,862 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kafka.server
import kafka.log._
import java.io.File
import org.I0Itec.zkclient.ZkClient
import org.apache.kafka.common.metrics.Metrics
import org.easymock.EasyMock
import org.junit._
import org.junit.Assert._
import kafka.common._
import kafka.cluster.Replica
import kafka.utils.{SystemTime, KafkaScheduler, TestUtils, MockTime, CoreUtils}
import java.util.concurrent.atomic.AtomicBoolean
import org.apache.kafka.common.utils.{MockTime => JMockTime}
class HighwatermarkPersistenceTest {
val configs = TestUtils.createBrokerConfigs(2, TestUtils.MockZkConnect).map(KafkaConfig.fromProps)
val topic = "foo"
val logManagers = configs map { config =>
TestUtils.createLogManager(
logDirs = config.logDirs.map(new File(_)).toArray,
cleanerConfig = CleanerConfig())
}
@After
def teardown() {
for(manager <- logManagers; dir <- manager.logDirs)
CoreUtils.rm(dir)
}
@Test
def testHighWatermarkPersistenceSinglePartition() {
// mock zkclient
val zkClient = EasyMock.createMock(classOf[ZkClient])
EasyMock.replay(zkClient)
// create kafka scheduler
val scheduler = new KafkaScheduler(2)
scheduler.startup
// create replica manager
val replicaManager = new ReplicaManager(configs.head, new Metrics, new MockTime, new JMockTime, zkClient, scheduler,
logManagers(0), new AtomicBoolean(false))
replicaManager.startup()
replicaManager.checkpointHighWatermarks()
var fooPartition0Hw = hwmFor(replicaManager, topic, 0)
assertEquals(0L, fooPartition0Hw)
val partition0 = replicaManager.getOrCreatePartition(topic, 0)
// create leader and follower replicas
val log0 = logManagers(0).createLog(TopicAndPartition(topic, 0), LogConfig())
val leaderReplicaPartition0 = new Replica(configs.head.brokerId, partition0, SystemTime, 0, Some(log0))
partition0.addReplicaIfNotExists(leaderReplicaPartition0)
val followerReplicaPartition0 = new Replica(configs.last.brokerId, partition0, SystemTime)
partition0.addReplicaIfNotExists(followerReplicaPartition0)
replicaManager.checkpointHighWatermarks()
fooPartition0Hw = hwmFor(replicaManager, topic, 0)
assertEquals(leaderReplicaPartition0.highWatermark.messageOffset, fooPartition0Hw)
// set the high watermark for local replica
partition0.getReplica().get.highWatermark = new LogOffsetMetadata(5L)
replicaManager.checkpointHighWatermarks()
fooPartition0Hw = hwmFor(replicaManager, topic, 0)
assertEquals(leaderReplicaPartition0.highWatermark.messageOffset, fooPartition0Hw)
EasyMock.verify(zkClient)
// shutdown the replica manager upon test completion
replicaManager.shutdown(false)
}
@Test
def testHighWatermarkPersistenceMultiplePartitions() {
val topic1 = "foo1"
val topic2 = "foo2"
// mock zkclient
val zkClient = EasyMock.createMock(classOf[ZkClient])
EasyMock.replay(zkClient)
// create kafka scheduler
val scheduler = new KafkaScheduler(2)
scheduler.startup
// create replica manager
val replicaManager = new ReplicaManager(configs.head, new Metrics, new MockTime(), new JMockTime, zkClient,
scheduler, logManagers(0), new AtomicBoolean(false))
replicaManager.startup()
replicaManager.checkpointHighWatermarks()
var topic1Partition0Hw = hwmFor(replicaManager, topic1, 0)
assertEquals(0L, topic1Partition0Hw)
val topic1Partition0 = replicaManager.getOrCreatePartition(topic1, 0)
// create leader log
val topic1Log0 = logManagers(0).createLog(TopicAndPartition(topic1, 0), LogConfig())
// create a local replica for topic1
val leaderReplicaTopic1Partition0 = new Replica(configs.head.brokerId, topic1Partition0, SystemTime, 0, Some(topic1Log0))
topic1Partition0.addReplicaIfNotExists(leaderReplicaTopic1Partition0)
replicaManager.checkpointHighWatermarks()
topic1Partition0Hw = hwmFor(replicaManager, topic1, 0)
assertEquals(leaderReplicaTopic1Partition0.highWatermark.messageOffset, topic1Partition0Hw)
// set the high watermark for local replica
topic1Partition0.getReplica().get.highWatermark = new LogOffsetMetadata(5L)
replicaManager.checkpointHighWatermarks()
topic1Partition0Hw = hwmFor(replicaManager, topic1, 0)
assertEquals(5L, leaderReplicaTopic1Partition0.highWatermark.messageOffset)
assertEquals(5L, topic1Partition0Hw)
// add another partition and set highwatermark
val topic2Partition0 = replicaManager.getOrCreatePartition(topic2, 0)
// create leader log
val topic2Log0 = logManagers(0).createLog(TopicAndPartition(topic2, 0), LogConfig())
// create a local replica for topic2
val leaderReplicaTopic2Partition0 = new Replica(configs.head.brokerId, topic2Partition0, SystemTime, 0, Some(topic2Log0))
topic2Partition0.addReplicaIfNotExists(leaderReplicaTopic2Partition0)
replicaManager.checkpointHighWatermarks()
var topic2Partition0Hw = hwmFor(replicaManager, topic2, 0)
assertEquals(leaderReplicaTopic2Partition0.highWatermark.messageOffset, topic2Partition0Hw)
// set the highwatermark for local replica
topic2Partition0.getReplica().get.highWatermark = new LogOffsetMetadata(15L)
assertEquals(15L, leaderReplicaTopic2Partition0.highWatermark.messageOffset)
// change the highwatermark for topic1
topic1Partition0.getReplica().get.highWatermark = new LogOffsetMetadata(10L)
assertEquals(10L, leaderReplicaTopic1Partition0.highWatermark.messageOffset)
replicaManager.checkpointHighWatermarks()
// verify checkpointed hw for topic 2
topic2Partition0Hw = hwmFor(replicaManager, topic2, 0)
assertEquals(15L, topic2Partition0Hw)
// verify checkpointed hw for topic 1
topic1Partition0Hw = hwmFor(replicaManager, topic1, 0)
assertEquals(10L, topic1Partition0Hw)
EasyMock.verify(zkClient)
// shutdown the replica manager upon test completion
replicaManager.shutdown(false)
}
def hwmFor(replicaManager: ReplicaManager, topic: String, partition: Int): Long = {
replicaManager.highWatermarkCheckpoints(new File(replicaManager.config.logDirs(0)).getAbsolutePath).read.getOrElse(TopicAndPartition(topic, partition), 0L)
}
}
|
robort/kafka
|
core/src/test/scala/unit/kafka/server/HighwatermarkPersistenceTest.scala
|
Scala
|
apache-2.0
| 6,998 |
package models.domain.redis
import redis.clients.jedis.Jedis
import play.api.libs.json._
/**
* @author kamekoopa
*/
case class Record(key: Key, value: RedisValue, ttl: Long){
val isNoExpiration: Boolean = ttl == -1
}
object Record {
lazy val strArr: Array[String] = Array[String]()
def apply(keyName: String)(implicit client: Jedis) = {
import KeyType._
import scala.collection.JavaConversions._
Key(keyName).map({ key =>
val ttl = client.ttl(key.name)
val value = key.keyType match {
case STRING => StringValue(client.get (key.name ))
case LIST => ListValue (client.lrange (key.name, 0L, -1L).toArray(strArr).toList)
case SET => SetValue (client.smembers(key.name ).toArray(strArr).toSet)
case ZSET => ZSetValue (client.zrange (key.name, 0L, -1L).toArray(strArr).toSet)
case HASH => HashValue (client.hgetAll (key.name ).toMap[String, String])
}
new Record(key, value, ttl)
})
}
}
import models.domain.redis.RedisValueWrites._
object RecordWrites {
implicit object DefaultRecordWrites extends Writes[Record] {
def writes(o: Record): JsValue = {
Json.obj(
"key" -> JsString(o.key.name),
"type" -> JsString(o.key.keyType.keyType),
"value" -> Json.toJson(o.value),
"ttl" -> JsNumber(o.ttl)
)
}
}
}
|
kamekoopa/redis-miruo
|
app/models/domain/redis/Record.scala
|
Scala
|
apache-2.0
| 1,402 |
package org.jetbrains.plugins.scala.lang.scaladoc.psi.api
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.javadoc.PsiDocTag
import org.jetbrains.plugins.scala.lang.psi.api.ScalaPsiElement
trait ScDocTag extends ScalaPsiElement with PsiDocTag
|
JetBrains/intellij-scala
|
scala/scala-impl/src/org/jetbrains/plugins/scala/lang/scaladoc/psi/api/ScDocTag.scala
|
Scala
|
apache-2.0
| 275 |
package fpinscala.ch03_datastructures
import annotation.tailrec
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
object List {
def apply[A](as: A*): List[A] =
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
// Exercise 3.1
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
case Cons(x,xs) => x + sum(xs)
}
val cascadingMatch = List(1,2,3,4,5) match {
case Cons(x, Cons(2, Cons(4, _))) => x
case Nil => 42
case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y
case Cons(h, t) => h + sum(t)
case _ => 101
}
def cascadingMatchAssert() {
val answer: Int = ???
assert(cascadingMatch == answer)
}
// Exercise 3.2
def tail[A](l: List[A]): List[A] =
???
// Exercise 3.3
def drop[A](l: List[A], n: Int): List[A] =
???
// Exercise 3.4
def dropWhile[A](l: List[A])(f: A => Boolean): List[A] =
???
// Exercise 3.5
def setHead[A](l: List[A])(h: A): List[A] =
???
// Exercise 3.6
def init[A](l: List[A]): List[A] =
???
// Exercise 3.7
/* Evaluation of foldRight(Cons(1, Cons(2, Cons(3, Nil))), 0)(_ + _):
*
* TODO: write out the evaluation line by line
*/
// Exercise 3.8
/* TODO: Is short circuiting possible?
*/
// Exercise 3.9
def foldRight[A,B](l: List[A], z: B)(f: (A, B) => B): B =
l match {
case Nil => z
case Cons(x, xs) => f(x, foldRight(xs, z)(f))
}
def foldRightConsAssert() {
val someList = List(1, 2, 3)
val evaluated = foldRight(someList, Nil: List[Int]) { Cons(_, _) }
val answer: List[Int] = ???
assert(evaluated == answer)
}
// Exercise 3.10
def length[A](l: List[A]): Int =
???
// Exercise 3.11
def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B =
???
// Exercise 3.12
object AggregatesUsingFoldLeft {
def sum(ints: List[Int]) =
???
def product(ints: List[Double]) =
???
def length[A](l: List[A]): Int =
???
}
// Exercise 3.13
def reverse[A](l: List[A]): List[A] =
???
// Exercise 3.14
object FoldsWithFolds {
def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B =
???
def foldRight[A,B](l: List[A], z: B)(f: (A, B) => B): B =
???
}
// Exercise 3.15
def append[A](l: List[A], r: List[A]): List[A] =
???
// Exercise 3.16
def concat[A](l: List[List[A]]): List[A] =
???
// Exercise 3.17
def add1(l: List[Int]): List[Int] =
???
// Exercise 3.18
def doubles2Strings(l: List[Double]): List[String] =
???
// Exercise 3.19
def map[A,B](l: List[A])(f: A => B): List[B] =
???
// Exercise 3.20
def filter[A](l: List[A])(f: A => Boolean): List[A] =
???
// Exercises 3.21
def flatMap[A,B](l: List[A])(f: A => List[B]): List[B] =
???
object FilterWithFlatMap {
// Exercises 3.22
def filter[A](l: List[A])(f: A => Boolean): List[A] =
???
}
// Exercises 3.23
def addPairwise(as: List[Int], bs: List[Int]): List[Int] =
???
// Exercises 3.24
def zipWith[A,B,C](a: List[A], b: List[B])(f: (A,B) => C): List[C] =
???
// Exercise 3.25
def hasSubsequence[A](l: List[A], sub: List[A]): Boolean =
???
}
|
shajra/fpinscala-exercises-shajra
|
exercises/src/main/scala/fpinscala/ch03_datastructures/List.scala
|
Scala
|
mit
| 3,302 |
package org.bfn.ninetynineprobs
import org.scalatest._
class P26Spec extends UnitSpec {
"combinations" should "return one empty list when N=0" in {
assert(P26.combinations(0, List(1, 2, 3)) == List(List()))
}
it should "return one list per item when N=1" in {
val myList = List(3, 2, 1, 5)
assert(P26.combinations(1, myList) == myList.map((x) => List(x)))
}
it should "return lists of length N" in {
assert(P26.combinations(4, List(1, 2, 3, 5, 4))(0).length == 4)
}
it should "return C(list.length, N) lists" in {
val myList = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
assert(P26.combinations(3, myList).length == 220)
}
it should "not remove duplicates" in {
val myList = List(2, 2, 2)
assert(P26.combinations(2, myList) ==
List(List(2, 2), List(2, 2), List(2, 2)))
}
}
|
bfontaine/99Scala
|
src/test/scala/P26Spec.scala
|
Scala
|
mit
| 839 |
/**
* Copyright (C) 2017 Orbeon, Inc.
*
* 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
* 2.1 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.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.fr.persistence.relational.rest
import java.io.{InputStream, OutputStream, OutputStreamWriter}
import org.orbeon.dom.Document
import org.orbeon.oxf.util
import org.orbeon.io.IOUtils.useAndClose
import org.orbeon.oxf.externalcontext.UserAndGroup
import org.orbeon.oxf.xml.TransformerUtils
import org.orbeon.scaxon.NodeConversions
import org.orbeon.scaxon.SimplePath._
import scala.xml.Elem
case class LockInfo(userAndGroup: UserAndGroup)
object LockInfo {
def elem(lockInfo: LockInfo): Elem =
<d:lockinfo xmlns:d="DAV:" xmlns:fr="http://orbeon.org/oxf/xml/form-runner">
<d:lockscope><d:exclusive/></d:lockscope>
<d:locktype><d:write/></d:locktype>
<d:owner>
<fr:username>{lockInfo.userAndGroup.username}</fr:username>
<fr:groupname>{lockInfo.userAndGroup.groupname.getOrElse("")}</fr:groupname>
</d:owner>
</d:lockinfo>
def toOrbeonDom(lockInfo: LockInfo): Document =
NodeConversions.elemToOrbeonDom(elem(lockInfo))
def serialize(lockInfo: LockInfo, outputStream: OutputStream): Unit = {
val el = elem(lockInfo)
val writer = new OutputStreamWriter(outputStream)
useAndClose(writer)(_.write(el.toString()))
}
def parse(lockInfo: InputStream): LockInfo = {
val document = TransformerUtils.readTinyTree(util.XPath.GlobalConfiguration, lockInfo, "", false, false)
val owner = document / "lockinfo" / "owner"
val username = owner / "username"
val groupname = owner / "groupname"
LockInfo(
UserAndGroup.fromStringsOrThrow(username.stringValue, groupname.stringValue)
)
}
}
|
orbeon/orbeon-forms
|
form-runner/jvm/src/main/scala/org/orbeon/oxf/fr/persistence/relational/rest/LockInfo.scala
|
Scala
|
lgpl-2.1
| 2,277 |
package org.phenoscape.scowl.ofn
import org.phenoscape.scowl.converters.{SWRLArgs, SWRLDArgish, SWRLIArgish}
import org.semanticweb.owlapi.apibinding.OWLManager
import org.semanticweb.owlapi.model._
import scala.jdk.CollectionConverters._
trait SWRL {
private val factory = OWLManager.getOWLDataFactory
object DLSafeRule {
def apply(annotations: Set[OWLAnnotation], body: Set[_ <: SWRLAtom], head: Set[_ <: SWRLAtom]): SWRLRule =
factory.getSWRLRule(body.asJava, head.asJava, annotations.asJava)
def apply(body: Set[_ <: SWRLAtom], head: Set[_ <: SWRLAtom]): SWRLRule =
DLSafeRule(Set.empty, body, head)
def apply(annotations: OWLAnnotation*)(body: Set[_ <: SWRLAtom], head: Set[_ <: SWRLAtom]): SWRLRule =
DLSafeRule(annotations.toSet, body, head)
def unapply(rule: SWRLRule): Option[(Set[OWLAnnotation], Set[SWRLAtom], Set[SWRLAtom])] =
Option(rule.getAnnotations.asScala.toSet, rule.getBody.asScala.toSet, rule.getHead.asScala.toSet)
}
object ClassAtom {
def apply[T: SWRLIArgish](classExpression: OWLClassExpression, arg: T): SWRLClassAtom = {
val argish = implicitly[SWRLIArgish[T]]
factory.getSWRLClassAtom(classExpression, argish.toArgument(arg))
}
def unapply(atom: SWRLClassAtom): Option[(OWLClassExpression, SWRLIArgument)] =
Option(atom.getPredicate, atom.getArgument)
}
object DataRangeAtom {
def apply[T: SWRLDArgish](dataRange: OWLDataRange, arg: T): SWRLDataRangeAtom = {
val argish = implicitly[SWRLDArgish[T]]
factory.getSWRLDataRangeAtom(dataRange, argish.toArgument(arg))
}
def unapply(atom: SWRLDataRangeAtom): Option[(OWLDataRange, SWRLDArgument)] =
Option(atom.getPredicate, atom.getArgument)
}
object ObjectPropertyAtom {
def apply[S: SWRLIArgish, O: SWRLIArgish](property: OWLObjectPropertyExpression, subj: S, obj: O): SWRLObjectPropertyAtom = {
val sArgish = implicitly[SWRLIArgish[S]]
val oArgish = implicitly[SWRLIArgish[O]]
factory.getSWRLObjectPropertyAtom(property, sArgish.toArgument(subj), oArgish.toArgument(obj))
}
def unapply(atom: SWRLObjectPropertyAtom): Option[(OWLObjectPropertyExpression, SWRLIArgument, SWRLIArgument)] =
Option(atom.getPredicate, atom.getFirstArgument, atom.getSecondArgument)
}
object DataPropertyAtom {
def apply[S: SWRLIArgish, V: SWRLDArgish](property: OWLDataPropertyExpression, subj: S, value: V): SWRLDataPropertyAtom = {
val sArgish = implicitly[SWRLIArgish[S]]
val vArgish = implicitly[SWRLDArgish[V]]
factory.getSWRLDataPropertyAtom(property, sArgish.toArgument(subj), vArgish.toArgument(value))
}
def unapply(atom: SWRLDataPropertyAtom): Option[(OWLDataPropertyExpression, SWRLIArgument, SWRLDArgument)] =
Option(atom.getPredicate, atom.getFirstArgument, atom.getSecondArgument)
}
object BuiltInAtom {
def apply[T: SWRLDArgish](iri: IRI, args: T*): SWRLBuiltInAtom = {
val argish = implicitly[SWRLDArgish[T]]
factory.getSWRLBuiltInAtom(iri, args.map(argish.toArgument).asJava)
}
def unapply(atom: SWRLBuiltInAtom): Option[(IRI, Seq[SWRLDArgument])] = {
Option((atom.getPredicate, atom.getArguments.asScala.toSeq))
}
}
object SameIndividualAtom {
def apply[S: SWRLIArgish, O: SWRLIArgish](subj: S, obj: O): SWRLSameIndividualAtom = {
val sArgish = implicitly[SWRLIArgish[S]]
val oArgish = implicitly[SWRLIArgish[O]]
factory.getSWRLSameIndividualAtom(sArgish.toArgument(subj), oArgish.toArgument(obj))
}
def unapply(atom: SWRLSameIndividualAtom): Option[(SWRLIArgument, SWRLIArgument)] = {
Option(atom.getFirstArgument, atom.getSecondArgument)
}
}
object DifferentIndividualsAtom {
def apply[S: SWRLIArgish, O: SWRLIArgish](subj: S, obj: O): SWRLDifferentIndividualsAtom = {
val sArgish = implicitly[SWRLIArgish[S]]
val oArgish = implicitly[SWRLIArgish[O]]
factory.getSWRLDifferentIndividualsAtom(sArgish.toArgument(subj), oArgish.toArgument(obj))
}
def unapply(atom: SWRLDifferentIndividualsAtom): Option[(SWRLIArgument, SWRLIArgument)] = {
Option(atom.getFirstArgument, atom.getSecondArgument)
}
}
object Variable {
private object argish extends SWRLArgs
def apply(iri: IRI): SWRLVariable = factory.getSWRLVariable(iri)
def apply(symbol: Symbol): SWRLVariable =
argish.SymbolArgish.toArgument(symbol)
def unapply(variable: SWRLVariable): Option[IRI] =
Option(variable.getIRI)
}
}
|
phenoscape/scowl
|
src/main/scala/org/phenoscape/scowl/ofn/SWRL.scala
|
Scala
|
mit
| 4,546 |
/*******************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013,2014 by Peter Pilgrim, Addiscombe, Surrey, XeNoNiQUe UK
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU GPL v3.0
* which accompanies this distribution, and is available at:
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Developers:
* Peter Pilgrim -- design, development and implementation
* -- Blog: http://www.xenonique.co.uk/blog/
* -- Twitter: @peter_pilgrim
*
* Contributors:
*
*******************************************************************************/
package uk.co.xenonique.digitalone
import java.io.{FileNotFoundException, File}
/**
* The type GradleDependency
*
* @author Peter Pilgrim
*/
object GradleDependency {
def find( dir: File, name: String): Option[File] = {
val file = new File(dir, name )
if ( file.exists) {
Some(file)
}
else {
for ( e <- dir.listFiles() ) {
if ( e.isDirectory() && !e.getName().equals(".")) {
val f = find(e, name)
if ( f.isDefined) {
return f
}
}
}
None
}
}
def resolve( gav: String ): File = {
// ls ~/.gradle/caches/modules-2/files-2.1/
val gradleCache = new File(
System.getProperty("user.home") +
File.separator + ".gradle" + File.separator + "caches" + File.separator + "modules-2" +
File.separator +"files-2.1")
if ( !gradleCache.exists()) {
throw new FileNotFoundException("Gradle cache does not exist ")
}
val list = gav.split(":")
val group = list(0)
val artifactId = list(1)
val version = list(2)
println(gradleCache)
find(gradleCache, artifactId + "-" + version + ".jar") match {
case Some(f) => f
case _ => throw new FileNotFoundException(s"unable to resolve $gav")
}
}
}
|
peterpilgrim/digital-scala-javaone-2014
|
src/test/scala/uk/co/xenonique/digitalone/GradleDependency.scala
|
Scala
|
gpl-3.0
| 2,011 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.