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
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ruoyousi.wordcount import java.util.HashMap import org.apache.kafka.clients.producer.{ProducerConfig, KafkaProducer, ProducerRecord} import org.apache.spark.streaming._ import org.apache.spark.streaming.kafka._ import org.apache.spark.SparkConf /** * Consumes messages from one or more topics in Kafka and does wordcount. * Usage: KafkaWordCount <zkQuorum> <group> <topics> <numThreads> * <zkQuorum> is a list of one or more zookeeper servers that make quorum * <group> is the name of kafka consumer group * <topics> is a list of one or more kafka topics to consume from * <numThreads> is the number of threads the kafka consumer should use * * Example: * `$ bin/run-example \ * org.apache.spark.examples.streaming.KafkaWordCount zoo01,zoo02,zoo03 \ * my-consumer-group topic1,topic2 1` */ object KafkaWordCount { def main(args: Array[String]) { if (args.length < 4) { System.err.println("Usage: KafkaWordCount <zkQuorum> <group> <topics> <numThreads>") System.exit(1) } StreamingExamples.setStreamingLogLevels() val Array(zkQuorum, group, topics, numThreads) = args val sparkConf = new SparkConf().setAppName("KafkaWordCount") val ssc = new StreamingContext(sparkConf, Seconds(2)) ssc.checkpoint("checkpoint") val topicMap = topics.split(",").map((_, numThreads.toInt)).toMap val lines = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap).map(_._2) val words = lines.flatMap(_.split(" ")) val wordCounts = words.map(x => (x, 1L)) .reduceByKeyAndWindow(_ + _, _ - _, Minutes(10), Seconds(2), 2) wordCounts.print() ssc.start() ssc.awaitTermination() } } // Produces some random words between 1 and 100. object KafkaWordCountProducer { def main(args: Array[String]) { if (args.length < 4) { System.err.println("Usage: KafkaWordCountProducer <metadataBrokerList> <topic> " + "<messagesPerSec> <wordsPerMessage>") System.exit(1) } val Array(brokers, topic, messagesPerSec, wordsPerMessage) = args // Zookeeper connection properties val props = new HashMap[String, Object]() props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers) props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer") props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer") val producer = new KafkaProducer[String, String](props) // Send some messages while(true) { (1 to messagesPerSec.toInt).foreach { messageNum => val str = (1 to wordsPerMessage.toInt).map(x => scala.util.Random.nextInt(10).toString) .mkString(" ") val message = new ProducerRecord[String, String](topic, null, str) producer.send(message) } Thread.sleep(1000) } } }
ruoyousi/spark-streaming-examples
src/main/scala/com/ruoyousi/wordcount/KafkaWordCount.scala
Scala
apache-2.0
3,703
package chrome.runtime.bindings import scala.scalajs.js import scala.scalajs.js.annotation.JSName object PlatformInfo { type OperatingSystem = String type Architecture = String object OperatingSystems { val MAC: OperatingSystem = "mac" val WIN: OperatingSystem = "win" val ANDROID: OperatingSystem = "android" val CROS: OperatingSystem = "cros" val LINUX: OperatingSystem = "linux" val OPENBSD: OperatingSystem = "openbsd" } object Architectures { val ARM: OperatingSystem = "arm" val X86_32: OperatingSystem = "x86-32" val X86_64: OperatingSystem = "x86-64" } } class PlatformInfo extends js.Object { def os: PlatformInfo.OperatingSystem = js.native def arch: PlatformInfo.Architecture = js.native @JSName("nacl_arch") def naclArch: PlatformInfo.Architecture = js.native }
amsayk/scala-js-chrome
bindings/src/main/scala/chrome/runtime/bindings/PlatformInfo.scala
Scala
mit
847
/* * @author Philip Stutz * * Copyright 2014 University of Zurich * * 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.signalcollect.util import org.scalacheck.Gen import org.scalacheck.Gen._ import org.scalacheck.Arbitrary._ import org.scalatest.FlatSpec import org.scalatest.ShouldMatchers import org.scalatest.prop.Checkers import java.io.DataOutputStream import java.io.ByteArrayOutputStream import org.scalacheck.Arbitrary class BitSetSpec extends FlatSpec with ShouldMatchers with Checkers with TestAnnouncements { implicit lazy val arbInt = Arbitrary(Gen.chooseNum(Int.MinValue, Int.MaxValue)) "BitSet" should "store all ints up to 63" in { val bitSet = new BitSet(BitSet.create(0, 64)) for (i <- 0 to 63) { val inserted = bitSet.insert(i) assert(inserted) } val toSet = bitSet.toSet assert(toSet === (0 to 63).toSet) assert(toSet.size === 64) } it should "should be empty before inserts" in { val bitSet = new BitSet(BitSet.create(0, 64)) val toSet = bitSet.toSet assert(toSet == Set.empty[Int]) assert(bitSet.size == 0) } it should "support an insertion of 192 into an empty set" in { val insertItem = 192 val bitSet = new BitSet(BitSet.create(0, 200)) bitSet.insert(insertItem) val asSet = bitSet.toSet assert(asSet === Set(insertItem)) assert(bitSet.min === insertItem) assert(bitSet.max === insertItem) assert(bitSet.size === 1) } it should "support an insert into an empty set" in { check( (item: Int) => { val insertItem = (item & Int.MaxValue) % 200 val bitSet = new BitSet(BitSet.create(0, 200)) bitSet.insert(insertItem) val asSet = bitSet.toSet assert(asSet === Set(insertItem)) assert(bitSet.min === insertItem) assert(bitSet.max === insertItem) assert(bitSet.size === 1) bitSet.size === 1 }, minSuccessful(100)) } it should "store some Ints" in { val bitIntSet = new BitSet(BitSet.create(5, 200)) var inserted = bitIntSet.insert(6) assert(inserted == true) inserted = bitIntSet.insert(10) assert(inserted == true) inserted = bitIntSet.insert(10) assert(inserted == false) inserted = bitIntSet.insert(13) assert(inserted == true) inserted = bitIntSet.insert(68) assert(inserted == true) inserted = bitIntSet.insert(132) assert(inserted == true) assert(bitIntSet.toSet === Set(6, 10, 13, 68, 132)) } it should "store sets of Ints" in { check( (ints: Array[Int]) => { if (ints.nonEmpty) { val maxSize = 200 val mappedInts = ints.map(i => ((i & Int.MaxValue) % maxSize) + 10) val intSet = mappedInts.toSet val smallest = mappedInts.min val bitIntSet = new BitSet(BitSet.create(10, maxSize)) for (i <- intSet) { val inserted = bitIntSet.insert(i) assert(inserted == true) } intSet === bitIntSet.toSet } else { true } }, minSuccessful(1000)) } it should "support the 'contains' operation for a set that only contains 0" in { val bitSet = BitSet(Array(0)) val didContain = new BitSet(bitSet).contains(0) assert(didContain == true) } it should "support the 'contains' operation" in { check( (ints: Array[Int], item: Int) => { if (ints.nonEmpty) { val mapped = ints.map(_ % 10000000) val intSet = mapped.toSet val bitSet = BitSet(mapped) new BitSet(bitSet).contains(item) == intSet.contains(item) } else { true } }, minSuccessful(1000)) } }
danihegglin/DynDCO
src/test/scala/com/signalcollect/util/BitSetSpec.scala
Scala
apache-2.0
4,239
/* * 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.api import java.time.Duration import java.util import java.util.Properties import org.apache.kafka.clients.consumer._ import org.apache.kafka.clients.producer.{ProducerConfig, ProducerRecord} import org.apache.kafka.common.record.TimestampType import org.apache.kafka.common.TopicPartition import kafka.utils.{ShutdownableThread, TestUtils} import kafka.server.{BaseRequestTest, KafkaConfig} import org.junit.jupiter.api.Assertions._ import org.junit.jupiter.api.BeforeEach import scala.jdk.CollectionConverters._ import scala.collection.mutable.{ArrayBuffer, Buffer} import org.apache.kafka.clients.producer.KafkaProducer import org.apache.kafka.common.errors.WakeupException import scala.collection.mutable /** * Extension point for consumer integration tests. */ abstract class AbstractConsumerTest extends BaseRequestTest { val epsilon = 0.1 override def brokerCount: Int = 3 val topic = "topic" val part = 0 val tp = new TopicPartition(topic, part) val part2 = 1 val tp2 = new TopicPartition(topic, part2) val group = "my-test" val producerClientId = "ConsumerTestProducer" val consumerClientId = "ConsumerTestConsumer" val groupMaxSessionTimeoutMs = 30000L this.producerConfig.setProperty(ProducerConfig.ACKS_CONFIG, "all") this.producerConfig.setProperty(ProducerConfig.CLIENT_ID_CONFIG, producerClientId) this.consumerConfig.setProperty(ConsumerConfig.CLIENT_ID_CONFIG, consumerClientId) this.consumerConfig.setProperty(ConsumerConfig.GROUP_ID_CONFIG, group) this.consumerConfig.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest") this.consumerConfig.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false") this.consumerConfig.setProperty(ConsumerConfig.METADATA_MAX_AGE_CONFIG, "100") this.consumerConfig.setProperty(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, "6000") override protected def brokerPropertyOverrides(properties: Properties): Unit = { properties.setProperty(KafkaConfig.ControlledShutdownEnableProp, "false") // speed up shutdown properties.setProperty(KafkaConfig.OffsetsTopicReplicationFactorProp, "3") // don't want to lose offset properties.setProperty(KafkaConfig.OffsetsTopicPartitionsProp, "1") properties.setProperty(KafkaConfig.GroupMinSessionTimeoutMsProp, "100") // set small enough session timeout properties.setProperty(KafkaConfig.GroupMaxSessionTimeoutMsProp, groupMaxSessionTimeoutMs.toString) properties.setProperty(KafkaConfig.GroupInitialRebalanceDelayMsProp, "10") } @BeforeEach override def setUp(): Unit = { super.setUp() // create the test topic with all the brokers as replicas createTopic(topic, 2, brokerCount) } protected class TestConsumerReassignmentListener extends ConsumerRebalanceListener { var callsToAssigned = 0 var callsToRevoked = 0 def onPartitionsAssigned(partitions: java.util.Collection[TopicPartition]): Unit = { info("onPartitionsAssigned called.") callsToAssigned += 1 } def onPartitionsRevoked(partitions: java.util.Collection[TopicPartition]): Unit = { info("onPartitionsRevoked called.") callsToRevoked += 1 } } protected def createConsumerWithGroupId(groupId: String): KafkaConsumer[Array[Byte], Array[Byte]] = { val groupOverrideConfig = new Properties groupOverrideConfig.setProperty(ConsumerConfig.GROUP_ID_CONFIG, groupId) createConsumer(configOverrides = groupOverrideConfig) } protected def sendRecords(producer: KafkaProducer[Array[Byte], Array[Byte]], numRecords: Int, tp: TopicPartition, startingTimestamp: Long = System.currentTimeMillis()): Seq[ProducerRecord[Array[Byte], Array[Byte]]] = { val records = (0 until numRecords).map { i => val timestamp = startingTimestamp + i.toLong val record = new ProducerRecord(tp.topic(), tp.partition(), timestamp, s"key $i".getBytes, s"value $i".getBytes) producer.send(record) record } producer.flush() records } protected def consumeAndVerifyRecords(consumer: Consumer[Array[Byte], Array[Byte]], numRecords: Int, startingOffset: Int, startingKeyAndValueIndex: Int = 0, startingTimestamp: Long = 0L, timestampType: TimestampType = TimestampType.CREATE_TIME, tp: TopicPartition = tp, maxPollRecords: Int = Int.MaxValue): Unit = { val records = consumeRecords(consumer, numRecords, maxPollRecords = maxPollRecords) val now = System.currentTimeMillis() for (i <- 0 until numRecords) { val record = records(i) val offset = startingOffset + i assertEquals(tp.topic, record.topic) assertEquals(tp.partition, record.partition) if (timestampType == TimestampType.CREATE_TIME) { assertEquals(timestampType, record.timestampType) val timestamp = startingTimestamp + i assertEquals(timestamp.toLong, record.timestamp) } else assertTrue(record.timestamp >= startingTimestamp && record.timestamp <= now, s"Got unexpected timestamp ${record.timestamp}. Timestamp should be between [$startingTimestamp, $now}]") assertEquals(offset.toLong, record.offset) val keyAndValueIndex = startingKeyAndValueIndex + i assertEquals(s"key $keyAndValueIndex", new String(record.key)) assertEquals(s"value $keyAndValueIndex", new String(record.value)) // this is true only because K and V are byte arrays assertEquals(s"key $keyAndValueIndex".length, record.serializedKeySize) assertEquals(s"value $keyAndValueIndex".length, record.serializedValueSize) } } protected def consumeRecords[K, V](consumer: Consumer[K, V], numRecords: Int, maxPollRecords: Int = Int.MaxValue): ArrayBuffer[ConsumerRecord[K, V]] = { val records = new ArrayBuffer[ConsumerRecord[K, V]] def pollAction(polledRecords: ConsumerRecords[K, V]): Boolean = { assertTrue(polledRecords.asScala.size <= maxPollRecords) records ++= polledRecords.asScala records.size >= numRecords } TestUtils.pollRecordsUntilTrue(consumer, pollAction, waitTimeMs = 60000, msg = s"Timed out before consuming expected $numRecords records. " + s"The number consumed was ${records.size}.") records } protected def sendAndAwaitAsyncCommit[K, V](consumer: Consumer[K, V], offsetsOpt: Option[Map[TopicPartition, OffsetAndMetadata]] = None): Unit = { def sendAsyncCommit(callback: OffsetCommitCallback) = { offsetsOpt match { case Some(offsets) => consumer.commitAsync(offsets.asJava, callback) case None => consumer.commitAsync(callback) } } class RetryCommitCallback extends OffsetCommitCallback { var isComplete = false var error: Option[Exception] = None override def onComplete(offsets: util.Map[TopicPartition, OffsetAndMetadata], exception: Exception): Unit = { exception match { case e: RetriableCommitFailedException => sendAsyncCommit(this) case e => isComplete = true error = Option(e) } } } val commitCallback = new RetryCommitCallback sendAsyncCommit(commitCallback) TestUtils.pollUntilTrue(consumer, () => commitCallback.isComplete, "Failed to observe commit callback before timeout", waitTimeMs = 10000) assertEquals(None, commitCallback.error) } /** * Create 'numOfConsumersToAdd' consumers add then to the consumer group 'consumerGroup', and create corresponding * pollers for these consumers. Wait for partition re-assignment and validate. * * Currently, assignment validation requires that total number of partitions is greater or equal to * number of consumers, so subscriptions.size must be greater or equal the resulting number of consumers in the group * * @param numOfConsumersToAdd number of consumers to create and add to the consumer group * @param consumerGroup current consumer group * @param consumerPollers current consumer pollers * @param topicsToSubscribe topics to which new consumers will subscribe to * @param subscriptions set of all topic partitions */ def addConsumersToGroupAndWaitForGroupAssignment(numOfConsumersToAdd: Int, consumerGroup: mutable.Buffer[KafkaConsumer[Array[Byte], Array[Byte]]], consumerPollers: mutable.Buffer[ConsumerAssignmentPoller], topicsToSubscribe: List[String], subscriptions: Set[TopicPartition], group: String = group): (mutable.Buffer[KafkaConsumer[Array[Byte], Array[Byte]]], mutable.Buffer[ConsumerAssignmentPoller]) = { assertTrue(consumerGroup.size + numOfConsumersToAdd <= subscriptions.size) addConsumersToGroup(numOfConsumersToAdd, consumerGroup, consumerPollers, topicsToSubscribe, subscriptions, group) // wait until topics get re-assigned and validate assignment validateGroupAssignment(consumerPollers, subscriptions) (consumerGroup, consumerPollers) } /** * Create 'numOfConsumersToAdd' consumers add then to the consumer group 'consumerGroup', and create corresponding * pollers for these consumers. * * * @param numOfConsumersToAdd number of consumers to create and add to the consumer group * @param consumerGroup current consumer group * @param consumerPollers current consumer pollers * @param topicsToSubscribe topics to which new consumers will subscribe to * @param subscriptions set of all topic partitions */ def addConsumersToGroup(numOfConsumersToAdd: Int, consumerGroup: mutable.Buffer[KafkaConsumer[Array[Byte], Array[Byte]]], consumerPollers: mutable.Buffer[ConsumerAssignmentPoller], topicsToSubscribe: List[String], subscriptions: Set[TopicPartition], group: String = group): (mutable.Buffer[KafkaConsumer[Array[Byte], Array[Byte]]], mutable.Buffer[ConsumerAssignmentPoller]) = { for (_ <- 0 until numOfConsumersToAdd) { val consumer = createConsumerWithGroupId(group) consumerGroup += consumer consumerPollers += subscribeConsumerAndStartPolling(consumer, topicsToSubscribe) } (consumerGroup, consumerPollers) } /** * Wait for consumers to get partition assignment and validate it. * * @param consumerPollers consumer pollers corresponding to the consumer group we are testing * @param subscriptions set of all topic partitions * @param msg message to print when waiting for/validating assignment fails */ def validateGroupAssignment(consumerPollers: mutable.Buffer[ConsumerAssignmentPoller], subscriptions: Set[TopicPartition], msg: Option[String] = None, waitTime: Long = 10000L): Unit = { val assignments = mutable.Buffer[Set[TopicPartition]]() TestUtils.waitUntilTrue(() => { assignments.clear() consumerPollers.foreach(assignments += _.consumerAssignment()) isPartitionAssignmentValid(assignments, subscriptions) }, msg.getOrElse(s"Did not get valid assignment for partitions $subscriptions. Instead, got $assignments"), waitTime) } /** * Subscribes consumer 'consumer' to a given list of topics 'topicsToSubscribe', creates * consumer poller and starts polling. * Assumes that the consumer is not subscribed to any topics yet * * @param consumer consumer * @param topicsToSubscribe topics that this consumer will subscribe to * @return consumer poller for the given consumer */ def subscribeConsumerAndStartPolling(consumer: Consumer[Array[Byte], Array[Byte]], topicsToSubscribe: List[String], partitionsToAssign: Set[TopicPartition] = Set.empty[TopicPartition]): ConsumerAssignmentPoller = { assertEquals(0, consumer.assignment().size) val consumerPoller = if (topicsToSubscribe.nonEmpty) new ConsumerAssignmentPoller(consumer, topicsToSubscribe) else new ConsumerAssignmentPoller(consumer, partitionsToAssign) consumerPoller.start() consumerPoller } protected def awaitRebalance(consumer: Consumer[_, _], rebalanceListener: TestConsumerReassignmentListener): Unit = { val numReassignments = rebalanceListener.callsToAssigned TestUtils.pollUntilTrue(consumer, () => rebalanceListener.callsToAssigned > numReassignments, "Timed out before expected rebalance completed") } protected def ensureNoRebalance(consumer: Consumer[_, _], rebalanceListener: TestConsumerReassignmentListener): Unit = { // The best way to verify that the current membership is still active is to commit offsets. // This would fail if the group had rebalanced. val initialRevokeCalls = rebalanceListener.callsToRevoked sendAndAwaitAsyncCommit(consumer) assertEquals(initialRevokeCalls, rebalanceListener.callsToRevoked) } protected class CountConsumerCommitCallback extends OffsetCommitCallback { var successCount = 0 var failCount = 0 var lastError: Option[Exception] = None override def onComplete(offsets: util.Map[TopicPartition, OffsetAndMetadata], exception: Exception): Unit = { if (exception == null) { successCount += 1 } else { failCount += 1 lastError = Some(exception) } } } protected class ConsumerAssignmentPoller(consumer: Consumer[Array[Byte], Array[Byte]], topicsToSubscribe: List[String], partitionsToAssign: Set[TopicPartition]) extends ShutdownableThread("daemon-consumer-assignment", false) { def this(consumer: Consumer[Array[Byte], Array[Byte]], topicsToSubscribe: List[String]) = { this(consumer, topicsToSubscribe, Set.empty[TopicPartition]) } def this(consumer: Consumer[Array[Byte], Array[Byte]], partitionsToAssign: Set[TopicPartition]) = { this(consumer, List.empty[String], partitionsToAssign) } @volatile var thrownException: Option[Throwable] = None @volatile var receivedMessages = 0 private val partitionAssignment = mutable.Set[TopicPartition]() @volatile private var subscriptionChanged = false private var topicsSubscription = topicsToSubscribe val rebalanceListener: ConsumerRebalanceListener = new ConsumerRebalanceListener { override def onPartitionsAssigned(partitions: util.Collection[TopicPartition]) = { partitionAssignment ++= partitions.toArray(new Array[TopicPartition](0)) } override def onPartitionsRevoked(partitions: util.Collection[TopicPartition]) = { partitionAssignment --= partitions.toArray(new Array[TopicPartition](0)) } } if (partitionsToAssign.isEmpty) { consumer.subscribe(topicsToSubscribe.asJava, rebalanceListener) } else { consumer.assign(partitionsToAssign.asJava) } def consumerAssignment(): Set[TopicPartition] = { partitionAssignment.toSet } /** * Subscribe consumer to a new set of topics. * Since this method most likely be called from a different thread, this function * just "schedules" the subscription change, and actual call to consumer.subscribe is done * in the doWork() method * * This method does not allow to change subscription until doWork processes the previous call * to this method. This is just to avoid race conditions and enough functionality for testing purposes * @param newTopicsToSubscribe */ def subscribe(newTopicsToSubscribe: List[String]): Unit = { if (subscriptionChanged) throw new IllegalStateException("Do not call subscribe until the previous subscribe request is processed.") if (partitionsToAssign.nonEmpty) throw new IllegalStateException("Cannot call subscribe when configured to use manual partition assignment") topicsSubscription = newTopicsToSubscribe subscriptionChanged = true } def isSubscribeRequestProcessed: Boolean = { !subscriptionChanged } override def initiateShutdown(): Boolean = { val res = super.initiateShutdown() consumer.wakeup() res } override def doWork(): Unit = { if (subscriptionChanged) { consumer.subscribe(topicsSubscription.asJava, rebalanceListener) subscriptionChanged = false } try { receivedMessages += consumer.poll(Duration.ofMillis(50)).count() } catch { case _: WakeupException => // ignore for shutdown case e: Throwable => thrownException = Some(e) throw e } } } /** * Check whether partition assignment is valid * Assumes partition assignment is valid iff * 1. Every consumer got assigned at least one partition * 2. Each partition is assigned to only one consumer * 3. Every partition is assigned to one of the consumers * * @param assignments set of consumer assignments; one per each consumer * @param partitions set of partitions that consumers subscribed to * @return true if partition assignment is valid */ def isPartitionAssignmentValid(assignments: Buffer[Set[TopicPartition]], partitions: Set[TopicPartition]): Boolean = { val allNonEmptyAssignments = assignments.forall(assignment => assignment.nonEmpty) if (!allNonEmptyAssignments) { // at least one consumer got empty assignment return false } // make sure that sum of all partitions to all consumers equals total number of partitions val totalPartitionsInAssignments = assignments.foldLeft(0)(_ + _.size) if (totalPartitionsInAssignments != partitions.size) { // either same partitions got assigned to more than one consumer or some // partitions were not assigned return false } // The above checks could miss the case where one or more partitions were assigned to more // than one consumer and the same number of partitions were missing from assignments. // Make sure that all unique assignments are the same as 'partitions' val uniqueAssignedPartitions = assignments.foldLeft(Set.empty[TopicPartition])(_ ++ _) uniqueAssignedPartitions == partitions } }
Chasego/kafka
core/src/test/scala/integration/kafka/api/AbstractConsumerTest.scala
Scala
apache-2.0
19,741
/* * Copyright 2001-2012 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.selenium import org.scalatest.FunSpec import org.scalatest.matchers.ShouldMatchers import java.util.concurrent.TimeUnit import org.scalatest.time.SpanSugar import org.scalatest.ParallelTestExecution import org.openqa.selenium.WebDriver import org.openqa.selenium.htmlunit.HtmlUnitDriver import org.scalatest.time.Span import org.scalatest.time.Seconds import org.scalatest.exceptions.TestFailedException import java.io.File import org.scalatest.Suite import org.scalatest.Args import org.scalatest.ScreenshotOnFailure import org.scalatest.SharedHelpers.SilentReporter import org.scalatest.tagobjects.Slow import org.openqa.selenium.firefox.FirefoxDriver import org.openqa.selenium.firefox.FirefoxProfile import org.openqa.selenium.safari.SafariDriver import org.openqa.selenium.chrome.ChromeDriver import org.openqa.selenium.ie.InternetExplorerDriver import org.openqa.selenium.Cookie import org.openqa.selenium.WebElement class WebBrowserSpec extends JettySpec with ShouldMatchers with SpanSugar with WebBrowser with HtmlUnit { describe("textField") { it("should throw TFE with valid stack depth if specified item not found") { go to (host + "find-textfield.html") val caught = intercept[TestFailedException] { textField("unknown") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should throw TFE with valid stack depth if specified is found but is not a text field") { go to (host + "find-textfield.html") val caught = intercept[TestFailedException] { textField("area1") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should, when a valid text field is found, return a TestField instance") { go to (host + "find-textfield.html") val text1 = textField("text1") text1.value should be ("value1") } it("should, when multiple matching text fields exist, return the first one") { go to (host + "find-textfield.html") val text2 = textField("text2") text2.value should be ("value2") } } describe("pwdField") { it("should throw TFE with valid stack depth if specified item not found") { go to (host + "find-pwdfield.html") val caught = intercept[TestFailedException] { pwdField("unknown") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should throw TFE with valid stack depth if specified is found but is not a password field") { go to (host + "find-pwdfield.html") val caught = intercept[TestFailedException] { pwdField("area1") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should, when a valid password field is found, return a PasswordField instance") { go to (host + "find-pwdfield.html") val secret1 = pwdField("secret1") secret1.value should be ("pwd1") } it("should, when multiple matching password fields exist, return the first one") { go to (host + "find-pwdfield.html") val secret2 = pwdField("secret2") secret2.value should be ("pwd2") } } describe("textArea") { it("should throw TFE with valid stack depth if specified item not found") { go to (host + "find-textarea.html") val caught = intercept[TestFailedException] { textArea("unknown") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should throw TFE with valid stack depth if specified is found but is not a text area") { go to (host + "find-textarea.html") val caught = intercept[TestFailedException] { textArea("opt1") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should, when a valid text area is found, return a TestArea instance") { go to (host + "find-textarea.html") val textarea1 = textArea("textarea1") textarea1.text should be ("value1") } it("should, when multiple matching text areas exist, return the first one") { go to (host + "find-textarea.html") val text2 = textArea("textarea2") text2.text should be ("value2") } } describe("radioButton") { it("should throw TFE with valid stack depth if specified item not found") { go to (host + "find-radio.html") val caught = intercept[TestFailedException] { radioButton("unknown") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should throw TFE with valid stack depth if specified is found but is not a radio button") { go to (host + "find-radio.html") val caught = intercept[TestFailedException] { radioButton("text1") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should, when a valid radio button is found, return a RadioButton instance") { go to (host + "find-radio.html") val radio = radioButton("group1") radio.value should be ("value1") } it("should, when multiple matching radio buttons exist, return the first one") { go to (host + "find-radio.html") val radio = radioButton("group2") radio.value should be ("value2") } } describe("checkbox") { it("should throw TFE with valid stack depth if specified item not found") { go to (host + "find-checkbox.html") val caught = intercept[TestFailedException] { checkbox("unknown") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should throw TFE with valid stack depth if specified is found but is not a checkbox") { go to (host + "find-checkbox.html") val caught = intercept[TestFailedException] { checkbox("text1") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should, when a valid text field is found, return a Checkbox instance") { go to (host + "find-checkbox.html") val checkbox1 = checkbox("opt1") checkbox1.isSelected should be (true) } it("should, when multiple matching checkboxes exist, return the first one") { go to (host + "find-checkbox.html") val checkbox2 = checkbox("opt2") checkbox2.isSelected should be (false) } } describe("singleSel") { it("should throw TFE with valid stack depth if specified item not found") { go to (host + "find-select.html") val caught = intercept[TestFailedException] { singleSel("unknown") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should throw TFE with valid stack depth if specified is found but is not a single-selection list") { go to (host + "find-select.html") val caught = intercept[TestFailedException] { singleSel("select2") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should, when a valid single-selection list is found, return a SingleSel instance") { go to (host + "find-select.html") val select1 = singleSel("select1") select1.value should be ("option2") } it("should, when multiple matching single-selection lists exist, return the first one") { go to (host + "find-select.html") val select3 = singleSel("select3") select3.value should be ("option3") } it("should throw TFE with valid stack depth and cause if invalid option is set") { go to (host + "find-select.html") val select1 = singleSel("select1") val caught = intercept[TestFailedException] { select1.value = "something else" } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) caught.getCause.getClass should be (classOf[org.openqa.selenium.NoSuchElementException]) } } describe("multiSel") { it("should throw TFE with valid stack depth if specified item not found") { go to (host + "find-select.html") val caught = intercept[TestFailedException] { multiSel("unknown") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should throw TFE with valid stack depth if specified is found but is not a multiple-selection list") { go to (host + "find-select.html") val caught = intercept[TestFailedException] { multiSel("select1") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should, when a valid text field is found, return a MultiSel instance") { go to (host + "find-select.html") val select2 = multiSel("select2") select2.values should be (IndexedSeq("option4", "option5")) } it("should, when multiple matching multiple-selection lists exist, return the first one") { go to (host + "find-select.html") val select4 = multiSel("select4") select4.values should be (IndexedSeq("option1", "option3")) } it("should throw TFE with valid stack depth and cause if invalid option is set") { go to (host + "find-select.html") val select2 = multiSel("select2") val caught = intercept[TestFailedException] { select2.values = Seq("option6", "something else") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) caught.getCause.getClass should be (classOf[org.openqa.selenium.NoSuchElementException]) } } describe("click on") { it("should throw TFE with valid stack depth if specified item not found", Slow) { go to (host + "index.html") val caught = intercept[TestFailedException] { click on "unknown" } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should be able to click on element from all query methods") { go to (host + "click.html") click on id("aLink") click on name("aLinkName") click on xpath("//html/body/a") click on className("aClass") click on cssSelector("a[id='aLink']") click on linkText("Test Click") click on partialLinkText("Click") click on tagName("a") } it("should be able to click on Element") { go to (host + "click.html") val element = id("aLink").element click on element } it("should be able to click on WebElement") { go to (host + "click.html") val webElement = id("aLink").webElement click on webElement } } describe("switch to") { it("should switch frame correctly and throw TFE with valid stack depth if specified frame not found", Slow) { go to (host + "frame.html") val win = windowHandle switch to frame("frame1") switch to window(win) switch to frame("frame2") switch to window(win) switch to frame(0) switch to window(win) switch to frame(1) switch to window(win) switch to frame(id("frame1")) switch to window(win) switch to frame(id("frame2")) switch to window(win) switch to frame(id("frame1").element) switch to window(win) switch to frame(id("frame2").element) switch to window(win) val caught1= intercept[TestFailedException] { switch to frame("frame3") } caught1.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught1.failedCodeFileName should be (Some("WebBrowserSpec.scala")) val caught2 = intercept[TestFailedException] { switch to frame(2) } caught2.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught2.failedCodeFileName should be (Some("WebBrowserSpec.scala")) val caught3 = intercept[TestFailedException] { switch to frame(id("text1")) } caught3.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught3.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should throw TFE with valid stack depth if specified window handle not found") { go to (host + "window.html") val handle = windowHandle switch to window(handle) // should be ok val caught = intercept[TestFailedException] { switch to window("Something else") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } } describe("A MultiSelOptionSeq") { it("should allow a string element to be appended with +") { val s = new MultiSelOptionSeq(Vector("1", "2", "3")) s + "4" should be (new MultiSelOptionSeq(Vector("1", "2", "3", "4"))) } it("should return the same MultiSelOptionSeq if an existing element is passed to +") { val s = new MultiSelOptionSeq(Vector("1", "2", "3")) s + "2" should be theSameInstanceAs (s) } it("should allow a string element to be removed with 0") { val s = new MultiSelOptionSeq(Vector("1", "2", "3")) s - "2" should be (new MultiSelOptionSeq(Vector("1", "3"))) } it("should return the same MultiSelOptionSeq if a non-existing element is passed to 0") { val s = new MultiSelOptionSeq(Vector("1", "2", "3")) s - "4" should be theSameInstanceAs (s) } } describe("goBack") { it("should have no effect if already at oldest page") { for (i <- 0 to 1000) goBack() } } describe("goForward") { it("should have no effect if already at newest page") { for (i <- 0 to 1000) goForward() } } describe("cookie") { it("should throw TFE with valid stack depth if specified cookie is not found") { go to (host + "index.html") val caught = intercept[TestFailedException] { cookie("other") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } } describe("find") { it("should return None if specified item not found") { go to (host + "index.html") find("something") should be (None) } it("should return a defined Option[Element] containing an instance of TextField if specified item is found to be a text field") { go to (host + "find-textfield.html") find("text1") match { case Some(textField: TextField) => textField.value should be ("value1") case other => fail("Expected Some(textField: TextField), but got: " + other) } } it("should return a defined Option[Element] containing an instance of TextArea if specified item is found to be a text area") { go to (host + "find-textarea.html") find("textarea1") match { case Some(textArea: TextArea) => textArea.text should be ("value1") case other => fail("Expected Some(textArea: TextArea), but got: " + other) } } it("should return a defined Option[Element] containing an instance of PasswordField if specified item is found to be a password field") { go to (host + "find-pwdfield.html") find("secret1") match { case Some(pwdField: PasswordField) => pwdField.value should be ("pwd1") case other => fail("Expected Some(pwdField: PasswordField), but got: " + other) } } it("should return a defined Option[Element] containing an instance of RadioButton if specified item is found to be a radio button") { go to (host + "find-radio.html") find("group2") match { case Some(radio: RadioButton) => radio.value should be ("value2") case other => fail("Expected Some(radio: RadioButton), but got: " + other) } } it("should return a defined Option[Element] containing an instance of Checkbox if specified item is found to be a checkbox") { go to (host + "find-checkbox.html") find("opt1") match { case Some(checkbox: Checkbox) => checkbox.isSelected should be (true) case other => fail("Expected Some(checkbox: Checkbox), but got: " + other) } } it("should return a defined Option[Element] containing an instance of SingleSel if specified item is found to be a single-selection list") { go to (host + "find-select.html") find("select1") match { case Some(singleSel: SingleSel) => singleSel.value should be ("option2") case other => fail("Expected Some(singleSel: SingleSel), but got: " + other) } } it("should return a defined Option[Element] containing an instance of MultiSel if specified item is found to be a multiple-selection list") { go to (host + "find-select.html") find("select2") match { case Some(multiSel: MultiSel) => multiSel.values should be (IndexedSeq("option4", "option5")) case other => fail("Expected Some(multiSel: MultiSel), but got: " + other) } } it("should return a defined Option[Element] containing an instance of Element if specified item is found but is not one of the items for which we have defined an Element subclass") { go to (host + "image.html") find("anImage") match { case Some(element: Element) => element.tagName should be ("img") case other => fail("Expected Some(element: Element), but got: " + other) } } } describe("findAll") { it("should return an empty Iterator if specified item not found") { go to (host + "index.html") findAll("something").hasNext should be (false) } it("should return a defined Iterator[Element] containing an instance of TextField if specified item is found to be a text field") { go to (host + "find-textfield.html") val text1 = findAll("text1") text1.hasNext should be (true) text1.next match { case textField: TextField => textField.value should be ("value1") case other => fail("Expected TextField, but got: " + other) } } it("should return a defined Iterator[Element] containing an instance of TextArea if specified item is found to be a text area") { go to (host + "find-textarea.html") val textarea1 = findAll("textarea1") textarea1.hasNext should be (true) textarea1.next match { case textArea: TextArea => textArea.text should be ("value1") case other => fail("Expected TextArea, but got: " + other) } } it("should return a defined Iterator[Element] containing an instance of PasswordField if specified item is found to be a password field") { go to (host + "find-pwdfield.html") val secret1 = findAll("secret1") secret1.hasNext should be (true) secret1.next match { case pwdField: PasswordField => pwdField.value should be ("pwd1") case other => fail("Expected PasswordField, but got: " + other) } } it("should return a defined Iterator[Element] containing an instance of RadioButton if specified item is found to be a radio button") { go to (host + "find-radio.html") val group1 = findAll("group1") group1.hasNext should be (true) group1.next match { case radio: RadioButton => radio.value should be ("value1") case other => fail("Expected RadioButton, but got: " + other) } } it("should return a defined Iterator[Element] containing an instance of Checkbox if specified item is found to be a checkbox") { go to (host + "find-checkbox.html") val opt1 = findAll("opt1") opt1.hasNext should be (true) opt1.next match { case checkbox: Checkbox => checkbox.value should be ("Option 1") case other => fail("Expected Checkbox, but got: " + other) } } it("should return a defined Iterator[Element] containing an instance of SingleSel if specified item is found to be a single-selection list") { go to (host + "find-select.html") val select1 = findAll("select1") select1.hasNext should be (true) select1.next match { case singleSel: SingleSel => singleSel.value should be ("option2") case other => fail("Expected SingleSel, but got: " + other) } } it("should return a defined Iterator[Element] containing an instance of MultiSel if specified item is found to be a multiple-selection list") { go to (host + "find-select.html") val select2 = findAll("select2") select2.hasNext should be (true) select2.next match { case multiSel: MultiSel => multiSel.values should be (IndexedSeq("option4", "option5")) case other => fail("Expected MultiSel, but got: " + other) } } it("should return a defined Iterator[Element] containing an instance of Element if specified item is found but is not one of the items for which we have defined an Element subclass") { go to (host + "image.html") val anImage = findAll("anImage") anImage.hasNext should be (true) anImage.next match { case image: Element => image.tagName should be ("img") case other => fail("Expected Element, but got: " + other) } } } describe("executeScript") { it("should execute the passed JavaScript") { go to (host + "index.html") val result1 = executeScript("return document.title;") result1 should be ("Test Title") val result2 = executeScript("return 'Hello ' + arguments[0]", "ScalaTest") result2 should be ("Hello ScalaTest") } } describe("executeAsyncScript") { it("should execute the passed JavaScript with asynchronous call") { go to (host + "index.html") val script = """ var callback = arguments[arguments.length - 1]; window.setTimeout(function() {callback('Hello ScalaTest')}, 500); """ setScriptTimeout(1 second) val result = executeAsyncScript(script) result should be ("Hello ScalaTest") } } describe("Web Browser") { it("should go to web page by using url and get its title correctly.") { go to (host + "index.html") pageTitle should be ("Test Title") } it("should go to web page by using Page and get its title correctly.") { class RadioPage extends Page { val url = host + "radio.html" } val radioPage = new RadioPage go to radioPage pageTitle should be ("Radio Button") } it("should get and set text field value correctly.", Slow) { go to (host + "textfield.html") pageTitle should be ("Text Field") textField("text1").value should be ("") // textField("text1") should have ('value(""), 'attribute("")) textField("text1").attribute("value") should be (Some("")) // textField("text1").attribute("value") should be ("") // ok as is textField("text1").value = "value 1" // set textField "text1" to "value 1" textField("text1").value should be ("value 1") // textField("text1").text should be ("value 1") textField("text1").attribute("value") should be (Some("value 1")) // textField("text1").attribute("value") should be ("value 1") textField("text2").value should be ("") textField("text2").attribute("value") should be (Some("")) textField("text2").value = "value 2" textField("text2").value should be ("value 2") textField("text2").attribute("value") should be (Some("value 2")) } it("should get and set password field value correctly.", Slow) { go to (host + "pwdfield.html") pageTitle should be ("Password Field") pwdField("secret1").value should be ("") pwdField("secret1").attribute("value") should be (Some("")) pwdField("secret1").value = "value 1" pwdField("secret1").value should be ("value 1") pwdField("secret1").attribute("value") should be (Some("value 1")) pwdField("secret2").value should be ("") pwdField("secret2").attribute("value") should be (Some("")) pwdField("secret2").value = "value 2" pwdField("secret2").value should be ("value 2") pwdField("secret2").attribute("value") should be (Some("value 2")) } it("should allow text to be entered in the active element if it is a text field.") { go to (host + "textfield.html") pageTitle should be ("Text Field") textField("text1").value should be ("") click on "text1" enter("value 1A") textField("text1").value should be ("value 1A") enter("value 1B") textField("text1").value should be ("value 1B") enter("") textField("text1").value should be ("") pressKeys("first post!") textField("text1").value should be ("first post!") pressKeys(" second post!") textField("text1").value should be ("first post! second post!") pressKeys(" third post!") textField("text1").value should be ("first post! second post! third post!") } it("should allow text to be entered in the active element if it is a password field.") { go to (host + "pwdfield.html") pageTitle should be ("Password Field") pwdField("secret1").value should be ("") click on "secret1" enter("secret 1A") pwdField("secret1").value should be ("secret 1A") enter("secret 1B") pwdField("secret1").value should be ("secret 1B") enter("") pwdField("secret1").value should be ("") pressKeys("first secret!") pwdField("secret1").value should be ("first secret!") pressKeys(" second secret!") pwdField("secret1").value should be ("first secret! second secret!") pressKeys(" third secret!") pwdField("secret1").value should be ("first secret! second secret! third secret!") } it("should throw TestFailedException with correct stack depth when enter is called currently selected element is neither text field, text area or password field.") { go to (host + "checkbox.html") click on ("opt1") val e = intercept[TestFailedException] { enter("Some text") } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) } it("should clear a text field.") { go to (host + "textfield.html") pageTitle should be ("Text Field") textField("text1").value = "value 1" textField("text1").value should be ("value 1") textField("text1").clear() textField("text1").value should be ("") textField("text1").value = "value 1" textField("text1").value should be ("value 1") } it("should get and set text area value correctly.", Slow) { go to (host + "textarea.html") pageTitle should be ("Text Area") textArea("area1").value should be ("") textArea("area1").attribute("value") should be (Some("")) textArea("area1").value = "area 1 - line 1\\narea 1 - line 2" textArea("area1").value should be ("area 1 - line 1\\narea 1 - line 2") textArea("area1").attribute("value") should be (Some("area 1 - line 1\\narea 1 - line 2")) textArea("area2").value should be ("") textArea("area2").attribute("value") should be (Some("")) textArea("area2").value = "area 2 - line 1\\narea 2 - line 2" textArea("area2").value should be ("area 2 - line 1\\narea 2 - line 2") textArea("area2").attribute("value") should be (Some("area 2 - line 1\\narea 2 - line 2")) } it("should clear a text area.") { go to (host + "textarea.html") pageTitle should be ("Text Area") textArea("area1").value = "area 1 - line 1\\narea 1 - line 2" textArea("area1").value should be ("area 1 - line 1\\narea 1 - line 2") textArea("area1").clear() textArea("area1").value should be ("") } it("should clear a password field.") { go to (host + "pwdfield.html") pageTitle should be ("Password Field") pwdField("secret1").value = "value 1" pwdField("secret1").value should be ("value 1") pwdField("secret1").clear() pwdField("secret1").value should be ("") pwdField("secret1").value = "value 1" pwdField("secret1").value should be ("value 1") } it("should allow text to be entered in the active element if it is a text area.") { go to (host + "textarea.html") pageTitle should be ("Text Area") textArea("area1").value should be ("") click on "area1" enter("area 1 - line 1\\narea 1 - line 2") textArea("area1").value should be ("area 1 - line 1\\narea 1 - line 2") enter("area 1 - line 0\\narea 1 - line 1\\narea 1 - line 2") textArea("area1").value should be ("area 1 - line 0\\narea 1 - line 1\\narea 1 - line 2") enter("") textArea("area1").value should be ("") pressKeys("line 1\\n") textArea("area1").value should be ("line 1\\n") pressKeys("line 2") textArea("area1").value should be ("line 1\\nline 2") pressKeys("b or not 2b") textArea("area1").value should be ("line 1\\nline 2b or not 2b") } it("should get and set radio button group correctly.") { go to (host + "radio.html") pageTitle should be ("Radio Button") radioButtonGroup("group1").selection should be (None) intercept[TestFailedException] { radioButtonGroup("group1").value } radioButtonGroup("group1").value = "Option 1" radioButtonGroup("group1").value should be ("Option 1") radioButtonGroup("group1").value = "Option 2" radioButtonGroup("group1").value should be ("Option 2") radioButtonGroup("group1").value = "Option 3" radioButtonGroup("group1").value should be ("Option 3") } it("should fail with TestFailedException with correct stack depth and cause when invalid value is set") { go to (host + "radio.html") val e = intercept[org.scalatest.exceptions.TestFailedException] { radioButtonGroup("group1").value = "Invalid value" } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) } it("should read, select and clear check box correctly.") { go to (host + "checkbox.html") pageTitle should be ("Check Box") checkbox("opt1").isSelected should be (false) checkbox("opt1").select() checkbox("opt1").isSelected should be (true) checkbox("opt1").clear() checkbox("opt1").isSelected should be (false) checkbox("opt2").isSelected should be (false) checkbox("opt2").select() checkbox("opt2").isSelected should be (true) checkbox("opt2").clear() checkbox("opt1").isSelected should be (false) } it("should read, select and clear dropdown list (select) correctly.", Slow) { go to (host + "select.html") pageTitle should be ("Select") singleSel("select1").value should be ("option1") singleSel("select1").value = "option2" singleSel("select1").value should be ("option2") singleSel("select1").value = "option3" singleSel("select1").value should be ("option3") singleSel("select1").value = "option1" singleSel("select1").value should be ("option1") intercept[TestFailedException] { singleSel("select1").value = "other" } // No options selected // multiSel("select2").selections should be (None) multiSel("select2").values should have size 0 multiSel("select2").values += "option4" multiSel("select2").values should be (IndexedSeq("option4")) multiSel("select2").values += "option5" multiSel("select2").values should be (IndexedSeq("option4", "option5")) multiSel("select2").values should have size 2 multiSel("select2").values(0) should be ("option4") multiSel("select2").values(1) should be ("option5") multiSel("select2").values += "option6" multiSel("select2").values should be (IndexedSeq("option4", "option5", "option6")) multiSel("select2").values should have size 3 multiSel("select2").values(0) should be ("option4") multiSel("select2").values(1) should be ("option5") multiSel("select2").values(2) should be ("option6") // multiSel("select2").selections should be (Some(IndexedSeq("option4", "option5", "option6"))) intercept[TestFailedException] { multiSel("select2").values += "other" } multiSel("select2").values -= "option5" multiSel("select2").values should have size 2 multiSel("select2").values(0) should be ("option4") multiSel("select2").values(1) should be ("option6") multiSel("select2").clearAll() // multiSel("select2").selections should be (None) multiSel("select2").values should have size 0 // Test the alternative way to clear multiSel("select2").values += "option6" multiSel("select2").values should have size 1 multiSel("select2").values(0) should be ("option6") multiSel("select2") clear "option6" // multiSel("select2").selections should be (None) multiSel("select2").values should have size 0 } it("should submit form when submit is called on form's element.") { go to (host + "submit.html") pageTitle should be ("Submit") click on "name" // This set the focus textField("name").value = "Penguin" submit() // submit (name("name")) // This will work as well. } it("should throw TestFailedException with correct stack depth when submit is called on none form's element") { go to (host + "submit.html") pageTitle should be ("Submit") val e = intercept[TestFailedException] { click on "not_form_element" // This set the focus textField("not_form_element").value = "Penguin" submit() } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) } it("should submit form when submit button is clicked.") { go to (host + "submit.html") pageTitle should be ("Submit") textField("name").value = "Penguin" click on "submitButton" } it("should navigate to, back, forward and refresh correctly") { go to (host + "navigate1.html") pageTitle should be ("Navigation 1") go to (host + "navigate2.html") pageTitle should be ("Navigation 2") goBack() // click back button pageTitle should be ("Navigation 1") goForward() // click forward button pageTitle should be ("Navigation 2") reloadPage() // click refreshPage button // click submit button pageTitle should be ("Navigation 2") } it("should support goBack, goForward and reloadPage correctly") { go to (host + "navigate1.html") pageTitle should be ("Navigation 1") go to (host + "navigate2.html") pageTitle should be ("Navigation 2") goBack() pageTitle should be ("Navigation 1") goForward() pageTitle should be ("Navigation 2") reloadPage() pageTitle should be ("Navigation 2") } it("should create, read and delete cookie correctly") { go to (host + "index.html") add cookie("name1", "value1") cookie("name1").value should be ("value1") add cookie("name2", "value2") cookie("name2").value should be ("value2") add cookie("name3", "value3") cookie("name3").value should be ("value3") delete cookie "name2" val e1 = intercept[TestFailedException] { cookie("name2") should be (null) } e1.failedCodeLineNumber should be (Some(thisLineNumber - 2)) e1.failedCodeFileName should be (Some("WebBrowserSpec.scala")) cookie("name1").value should be ("value1") cookie("name3").value should be ("value3") delete all cookies val e2 = intercept[TestFailedException] { cookie("name1") should be (null) } e2.failedCodeLineNumber should be (Some(thisLineNumber - 2)) e2.failedCodeFileName should be (Some("WebBrowserSpec.scala")) val e3 = intercept[TestFailedException] { cookie("name3") should be (null) } e3.failedCodeLineNumber should be (Some(thisLineNumber - 2)) e3.failedCodeFileName should be (Some("WebBrowserSpec.scala")) val e4 = intercept[TestFailedException] { delete cookie ("name1") } e4.failedCodeLineNumber should be (Some(thisLineNumber - 2)) e4.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should create, read and delete cookie correctly using libraryish alternatives") { goTo(host + "index.html") addCookie("name1", "value1") cookie("name1").value should be ("value1") addCookie("name2", "value2") cookie("name2").value should be ("value2") addCookie("name3", "value3") cookie("name3").value should be ("value3") deleteCookie("name2") val e1 = intercept[TestFailedException] { cookie("name2") should be (null) // TODO: This should throw a TFE not return null } e1.failedCodeLineNumber should be (Some(thisLineNumber - 2)) e1.failedCodeFileName should be (Some("WebBrowserSpec.scala")) cookie("name1").value should be ("value1") cookie("name3").value should be ("value3") deleteAllCookies() val e2 = intercept[TestFailedException] { cookie("name1") should be (null) } e2.failedCodeLineNumber should be (Some(thisLineNumber - 2)) e2.failedCodeFileName should be (Some("WebBrowserSpec.scala")) val e3 = intercept[TestFailedException] { cookie("name3") should be (null) } e3.failedCodeLineNumber should be (Some(thisLineNumber - 2)) e3.failedCodeFileName should be (Some("WebBrowserSpec.scala")) val e4 = intercept[TestFailedException] { deleteCookie("name1") } e4.failedCodeLineNumber should be (Some(thisLineNumber - 2)) e4.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should support implicitlyWait method") { implicitlyWait(Span(2, Seconds)) } it("should support capturing screenshot", Slow) { go to "http://www.artima.com" try { capture capture to ("MyScreenShot.png") captureTo("MyScreenShot2.png") } catch { case unsupported: UnsupportedOperationException => cancel(unsupported) } } it("should support setting capture target directory", Slow) { go to "http://www.artima.com" val tempDir = new File(System.getProperty("java.io.tmpdir")) val targetDir1 = new File(tempDir, "scalatest-test-target1") val targetDir2 = new File(tempDir, "scalatest-test-target2") try { setCaptureDir(targetDir1.getAbsolutePath) capture to ("MyScreenShot.png") new File(targetDir1, "MyScreenShot.png").exists should be (true) setCaptureDir(targetDir2.getAbsolutePath) captureTo("MyScreenShot2.png") new File(targetDir2, "MyScreenShot2.png").exists should be (true) } catch { case unsupported: UnsupportedOperationException => cancel(unsupported) } } it("isScreenshotSupported should return false for HtmlUnitDriver") { val driver = try new HtmlUnitDriver catch { case e: Throwable => cancel(e) } try isScreenshotSupported(driver) should be (false) finally close()(driver) } /* This is causing long hang times and left-open Firefox windows. * TODO: fix */ ignore("isScreenshotSupported should return true for FirefoxDriver") { val driver = try { new FirefoxDriver(new FirefoxProfile()) } catch { case e: Throwable => cancel(e) } try isScreenshotSupported(driver) should be (true) finally close()(driver) } /* Safari is blowing up on Bill's Mac leaving windows open and hanging for a long time before finally giving up. Get: [scalatest] Aug 3, 2012 4:39:18 AM org.openqa.selenium.safari.SafariDriverServer start [scalatest] INFO: Server started at http://Mi-Novia.local:38801/ [scalatest] - isScreenshotSupported should return false for SafariDriver !!! CANCELED !!! [scalatest] Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. [scalatest] Build info: version: 'unknown', revision: 'unknown', time: 'unknown' [scalatest] System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.7.4', java.version: '1.6.0_33' [scalatest] Driver info: driver.version: SafariDriver (WebBrowserSpec.scala:732) */ ignore("isScreenshotSupported should return true for SafariDriver") { val driver = try new SafariDriver catch { case e: Throwable => cancel(e) } try isScreenshotSupported(driver) should be (true) finally close()(driver) } it("isScreenshotSupported should return true for ChromeDriver") { val driver = try new ChromeDriver catch { case e: Throwable => cancel(e) } try isScreenshotSupported(driver) should be (true) finally close()(driver) } it("isScreenshotSupported should return true for InternetExplorerDriver") { val driver = try new InternetExplorerDriver catch { case e: Throwable => cancel(e) } try isScreenshotSupported(driver) should be (true) finally close()(driver) } /* ignore("should support wait method") { // This example is taken from http://seleniumhq.org/docs/03_webdriver.html // Visit Google go to "http://www.google.com" // Alternatively the same thing can be done like this // navigate to "http://www.google.com" // Click on the text input element by its name click on "q" // and enter "Cheese!" textField("q").value = "Cheese!" // Now submit the form submit() // Google's search is rendered dynamically with JavaScript. // Wait for the page to load, timeout after 10 seconds wait[Boolean](Span(10, Seconds)) { pageTitle.toLowerCase.startsWith("cheese!") } // Should see: "cheese! - Google Search" pageTitle should be ("Cheese! - Google Search") } */ ignore("should be able to use ScalaTest's eventually in place of Selenium's wait") { import org.scalatest.concurrent.Eventually._ go to "http://www.google.com" click on "q" textField("q").value = "Cheese!" submit() eventually(timeout(10 seconds)) { pageTitle.toLowerCase.startsWith("cheese!") should be (true) } pageTitle should be ("Cheese! - Google Search") } // Some operation not supported in HtmlUnit driver, e.g. switch to alert. // Should be good enough to test the following dsl compiles. ignore("should support switch to") { switch to activeElement switch to alert switch to defaultContent switch to frame(0) switch to frame("name") switch to frame(name("name")) switch to frame(name("name").element) switch to window(windowHandle) } ignore("should support switchTo") { switchTo(activeElement) switchTo(alert) switchTo(defaultContent) switchTo(frame(0)) switchTo(frame("name")) switchTo(frame(name("name"))) switchTo(frame(name("name").element)) switchTo(window(windowHandle)) } } describe("WrappedCookie") { it("should wrap null expiry in an option") { val cookie = new WrappedCookie(new Cookie("name", "value", "path", null)) cookie.expiry should be (None) } } describe("goTo") { it("should go to given url correctly") { goTo(host + "index.html") pageTitle should be ("Test Title") goTo(host + "textfield.html") pageTitle should be ("Text Field") } it("should go to given page correctly") { class IndexPage extends Page { val url = host + "index.html" } class TextFieldPage extends Page { val url = host + "textfield.html" } val indexPage = new IndexPage val textFieldPage = new TextFieldPage goTo(indexPage) pageTitle should be ("Test Title") goTo(textFieldPage) pageTitle should be ("Text Field") } } describe("clickOn") { it("should throw TFE with valid stack depth if specified item not found", Slow) { go to (host + "index.html") val caught = intercept[TestFailedException] { clickOn("unknown") } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should be able to clickOn element from all query methods") { go to (host + "click.html") clickOn(id("aLink")) clickOn(name("aLinkName")) clickOn(xpath("//html/body/a")) clickOn(className("aClass")) clickOn(cssSelector("a[id='aLink']")) clickOn(linkText("Test Click")) clickOn(partialLinkText("Click")) clickOn(tagName("a")) } it("should be able to clickOn Element") { go to (host + "click.html") val element = id("aLink").element clickOn(element) } it("should be able to click on WebElement") { go to (host + "click.html") val webElement = id("aLink").webElement clickOn(webElement) } } describe("Query") { describe("id") { it("should return Element correctly when element method is called with valid id") { go to (host + "click.html") id("aLink").element.isInstanceOf[Element] should be (true) } it("should throw TestFailedException with correct stack depth and cause when element method is called with invalid id", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { id("aInvalidLink").element } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return Some(Element) when findElement method is called with valid id") { go to (host + "click.html") id("aLink").findElement match { case Some(element: Element) => // ok case other => fail("Expected Some(element: Element), but got: " + other) } } it("should return None when findElement method is called with invalid id", Slow) { go to (host + "click.html") id("aInvalidLink").findElement should be (None) } it("should return WebElement correctly when webElement method is called with valid id") { go to (host + "click.html") id("aLink").webElement.isInstanceOf[WebElement] should be (true) } it("should throw TestFailedException with correct stack depth and cause when webElement method is called with invalid id", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { id("aInvalidLink").webElement } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return list Iterator[Element] with size of 1 when findAllElements is called with valid id") { go to (host + "click.html") val itr = id("aLink").findAllElements itr.hasNext should be (true) itr.next.isInstanceOf[Element] should be (true) itr.hasNext should be (false) } it("should return list Iterator[Element] with size of 0 when findAllElements is called with invalid id", Slow) { go to (host + "click.html") val itr = id("aInvalidLink").findAllElements itr.hasNext should be (false) } } describe("name") { it("should return Element correctly when element method is called with valid name") { go to (host + "click.html") name("aLinkName").element.isInstanceOf[Element] should be (true) } it("should throw TestFailedException with correct stack depth and cause when element method is called with invalid name", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { name("aInvalidLinkName").element } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return Some(Element) when findElement method is called with valid name") { go to (host + "click.html") name("aLinkName").findElement match { case Some(element: Element) => // ok case other => fail("Expected Some(element: Element), but got: " + other) } } it("should return None when findElement method is called with invalid name", Slow) { go to (host + "click.html") name("aInvalidLinkName").findElement should be (None) } it("should return WebElement correctly when webElement method is called with valid name") { go to (host + "click.html") name("aLinkName").webElement.isInstanceOf[WebElement] should be (true) } it("should throw TestFailedException with correct stack depth and cause when webElement method is called with invalid name", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { name("aInvalidLinkName").webElement } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return list Iterator[Element] with size of 1 when findAllElements is called with valid name") { go to (host + "click.html") val itr = name("aLinkName").findAllElements itr.hasNext should be (true) itr.next.isInstanceOf[Element] should be (true) itr.hasNext should be (false) } it("should return list Iterator[Element] with size of 0 when findAllElements is called with invalid name", Slow) { go to (host + "click.html") val itr = name("aInvalidLinkName").findAllElements itr.hasNext should be (false) } } describe("xpath") { it("should return Element correctly when element method is called with valid xpath") { go to (host + "click.html") xpath("//html/body/a").element.isInstanceOf[Element] should be (true) } it("should throw TestFailedException with correct stack depth and cause when element method is called with invalid xpath", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { xpath("//html/body/div/a").element } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return Some(Element) when findElement method is called with valid xpath") { go to (host + "click.html") xpath("//html/body/a").findElement match { case Some(element: Element) => // ok case other => fail("Expected Some(element: Element), but got: " + other) } } it("should return None when findElement method is called with invalid xpath", Slow) { go to (host + "click.html") xpath("//html/body/div/a").findElement should be (None) } it("should return WebElement correctly when webElement method is called with valid xpath") { go to (host + "click.html") xpath("//html/body/a").webElement.isInstanceOf[WebElement] should be (true) } it("should throw TestFailedException with correct stack depth and cause when webElement method is called with invalid xpath", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { xpath("//html/body/div/a").webElement } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return list Iterator[Element] with size of 1 when findAllElements is called with valid xpath") { go to (host + "click.html") val itr = xpath("//html/body/a").findAllElements itr.hasNext should be (true) itr.next.isInstanceOf[Element] should be (true) itr.hasNext should be (false) } it("should return list Iterator[Element] with size of 0 when findAllElements is called with invalid xpath", Slow) { go to (host + "click.html") val itr = xpath("//html/body/div/a").findAllElements itr.hasNext should be (false) } } describe("className") { it("should return Element correctly when element method is called with valid className") { go to (host + "click.html") className("aClass").element.isInstanceOf[Element] should be (true) } it("should throw TestFailedException with correct stack depth and cause when element method is called with invalid className", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { className("aInvalidClass").element } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return Some(Element) when findElement method is called with valid className") { go to (host + "click.html") className("aClass").findElement match { case Some(element: Element) => // ok case other => fail("Expected Some(element: Element), but got: " + other) } } it("should return None when findElement method is called with invalid className", Slow) { go to (host + "click.html") className("aInvalidClass").findElement should be (None) } it("should return WebElement correctly when webElement method is called with valid className") { go to (host + "click.html") className("aClass").webElement.isInstanceOf[WebElement] should be (true) } it("should throw TestFailedException with correct stack depth and cause when webElement method is called with invalid className", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { className("aInvalidClass").webElement } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return list Iterator[Element] with size of 1 when findAllElements is called with valid className") { go to (host + "click.html") val itr = className("aClass").findAllElements itr.hasNext should be (true) itr.next.isInstanceOf[Element] should be (true) itr.hasNext should be (false) } it("should return list Iterator[Element] with size of 0 when findAllElements is called with invalid className", Slow) { go to (host + "click.html") val itr = className("aInvalidClass").findAllElements itr.hasNext should be (false) } } describe("cssSelector") { it("should return Element correctly when element method is called with valid cssSelector") { go to (host + "click.html") cssSelector("a[id='aLink']").element.isInstanceOf[Element] should be (true) } it("should throw TestFailedException with correct stack depth and cause when element method is called with invalid cssSelector", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { cssSelector("a[id='aInvalidLink']").element } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return Some(Element) when findElement method is called with valid cssSelector") { go to (host + "click.html") cssSelector("a[id='aLink']").findElement match { case Some(element: Element) => // ok case other => fail("Expected Some(element: Element), but got: " + other) } } it("should return None when findElement method is called with invalid cssSelector", Slow) { go to (host + "click.html") cssSelector("a[id='aInvalidLink']").findElement should be (None) } it("should return WebElement correctly when webElement method is called with valid cssSelector") { go to (host + "click.html") cssSelector("a[id='aLink']").webElement.isInstanceOf[WebElement] should be (true) } it("should throw TestFailedException with correct stack depth and cause when webElement method is called with invalid cssSelector", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { cssSelector("a[id='aInvalidLink']").webElement } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return list Iterator[Element] with size of 1 when findAllElements is called with valid cssSelector") { go to (host + "click.html") val itr = cssSelector("a[id='aLink']").findAllElements itr.hasNext should be (true) itr.next.isInstanceOf[Element] should be (true) itr.hasNext should be (false) } it("should return list Iterator[Element] with size of 0 when findAllElements is called with invalid cssSelector", Slow) { go to (host + "click.html") val itr = cssSelector("a[id='aInvalidLink']").findAllElements itr.hasNext should be (false) } } describe("linkText") { it("should return Element correctly when element method is called with valid linkText") { go to (host + "click.html") linkText("Test Click").element.isInstanceOf[Element] should be (true) } it("should throw TestFailedException with correct stack depth and cause when element method is called with invalid linkText", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { linkText("Test Invalid Click").element } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return Some(Element) when findElement method is called with valid linkText") { go to (host + "click.html") linkText("Test Click").findElement match { case Some(element: Element) => // ok case other => fail("Expected Some(element: Element), but got: " + other) } } it("should return None when findElement method is called with invalid linkText", Slow) { go to (host + "click.html") linkText("Test Invalid Click").findElement should be (None) } it("should return WebElement correctly when webElement method is called with valid linkText") { go to (host + "click.html") linkText("Test Click").webElement.isInstanceOf[WebElement] should be (true) } it("should throw TestFailedException with correct stack depth and cause when webElement method is called with invalid linkText", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { linkText("Test Invalid Click").webElement } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return list Iterator[Element] with size of 1 when findAllElements is called with valid linkText") { go to (host + "click.html") val itr = linkText("Test Click").findAllElements itr.hasNext should be (true) itr.next.isInstanceOf[Element] should be (true) itr.hasNext should be (false) } it("should return list Iterator[Element] with size of 0 when findAllElements is called with invalid linkText", Slow) { go to (host + "click.html") val itr = linkText("Test Invalid Click").findAllElements itr.hasNext should be (false) } } describe("partialLinkText") { it("should return Element correctly when element method is called with valid partialLinkText") { go to (host + "click.html") partialLinkText("Click").element.isInstanceOf[Element] should be (true) } it("should throw TestFailedException with correct stack depth and cause when element method is called with invalid partialLinkText", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { partialLinkText("Click Invalid").element } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return Some(Element) when findElement method is called with valid partialLinkText") { go to (host + "click.html") partialLinkText("Click").findElement match { case Some(element: Element) => // ok case other => fail("Expected Some(element: Element), but got: " + other) } } it("should return None when findElement method is called with invalid partialLinkText", Slow) { go to (host + "click.html") partialLinkText("Click Invalid").findElement should be (None) } it("should return WebElement correctly when webElement method is called with valid partialLinkText") { go to (host + "click.html") partialLinkText("Click").webElement.isInstanceOf[WebElement] should be (true) } it("should throw TestFailedException with correct stack depth and cause when webElement method is called with invalid partialLinkText", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { partialLinkText("Click Invalid").webElement } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return list Iterator[Element] with size of 1 when findAllElements is called with valid partialLinkText") { go to (host + "click.html") val itr = partialLinkText("Click").findAllElements itr.hasNext should be (true) itr.next.isInstanceOf[Element] should be (true) itr.hasNext should be (false) } it("should return list Iterator[Element] with size of 0 when findAllElements is called with invalid partialLinkText", Slow) { go to (host + "click.html") val itr = partialLinkText("Click Invalid").findAllElements itr.hasNext should be (false) } } describe("tagname") { it("should return Element correctly when element method is called with valid tagname") { go to (host + "click.html") tagName("a").element.isInstanceOf[Element] should be (true) } it("should throw TestFailedException with correct stack depth and cause when element method is called with invalid tagname", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { tagName("img").element } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return Some(Element) when findElement method is called with valid tagname") { go to (host + "click.html") tagName("a").findElement match { case Some(element: Element) => // ok case other => fail("Expected Some(element: Element), but got: " + other) } } it("should return None when findElement method is called with invalid tagname", Slow) { go to (host + "click.html") tagName("img").findElement should be (None) } it("should return WebElement correctly when webElement method is called with valid tagname") { go to (host + "click.html") tagName("a").webElement.isInstanceOf[WebElement] should be (true) } it("should throw TestFailedException with correct stack depth and cause when webElement method is called with invalid tagname", Slow) { go to (host + "click.html") val e = intercept[TestFailedException] { tagName("img").webElement } e.failedCodeFileName should be (Some("WebBrowserSpec.scala")) e.failedCodeLineNumber should be (Some(thisLineNumber - 3)) e.getCause.isInstanceOf[org.openqa.selenium.NoSuchElementException] should be (true) } it("should return list Iterator[Element] with size of 1 when findAllElements is called with valid tagname") { go to (host + "click.html") val itr = tagName("a").findAllElements itr.hasNext should be (true) itr.next.isInstanceOf[Element] should be (true) itr.hasNext should be (false) } it("should return list Iterator[Element] with size of 0 when findAllElements is called with invalid tagname", Slow) { go to (host + "click.html") val itr = tagName("img").findAllElements itr.hasNext should be (false) } } } describe("switchTo") { it("should switch frame correctly and throw TFE with valid stack depth if specified frame not found", Slow) { goTo(host + "frame.html") val win = windowHandle switchTo(frame("frame1")) switchTo(window(win)) switchTo(frame("frame2")) switchTo(window(win)) switchTo(frame(0)) switchTo(window(win)) switchTo(frame(1)) switchTo(window(win)) switchTo(frame(id("frame1"))) switchTo(window(win)) switchTo(frame(id("frame2"))) switchTo(window(win)) switchTo(frame(id("frame1").element)) switchTo(window(win)) switchTo(frame(id("frame2").element)) switchTo(window(win)) val caught1= intercept[TestFailedException] { switchTo(frame("frame3")) } caught1.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught1.failedCodeFileName should be (Some("WebBrowserSpec.scala")) val caught2 = intercept[TestFailedException] { switch to frame(2) } caught2.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught2.failedCodeFileName should be (Some("WebBrowserSpec.scala")) val caught3 = intercept[TestFailedException] { switch to frame(id("text1")) } caught3.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught3.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } it("should throw TFE with valid stack depth if specified window handle not found") { goTo(host + "window.html") val handle = windowHandle switchTo(window(handle)) // should be ok val caught = intercept[TestFailedException] { switchTo(window("Something else")) } caught.failedCodeLineNumber should be (Some(thisLineNumber - 2)) caught.failedCodeFileName should be (Some("WebBrowserSpec.scala")) } } def thisLineNumber = { val st = Thread.currentThread.getStackTrace if (!st(2).getMethodName.contains("thisLineNumber")) st(2).getLineNumber else st(3).getLineNumber } } // class ParallelWebBrowserSpec extends WebBrowserSpec with ParallelTestExecution
svn2github/scalatest
src/test/scala/org/scalatest/selenium/WebBrowserSpec.scala
Scala
apache-2.0
72,121
/* * Wire * Copyright (C) 2016 Wire Swiss GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.waz.service.conversation import com.waz.content.UserPreferences.SelectedConvId import com.waz.content.{Preferences, UserPreferences} import com.waz.model.ConvId import com.waz.utils.events.Signal import scala.concurrent.Future trait SelectedConversationService { def selectedConvIdPref: Preferences.Preference[Option[ConvId]] def selectedConversationId: Signal[Option[ConvId]] def selectConversation(id: Option[ConvId]): Future[Unit] } /** * Keeps track of general conversation list stats needed for display of conversations lists. */ class SelectedConversationServiceImpl(userPrefs: UserPreferences) extends SelectedConversationService { val selectedConvIdPref: Preferences.Preference[Option[ConvId]] = userPrefs.preference(SelectedConvId) def selectedConversationId: Signal[Option[ConvId]] = selectedConvIdPref.signal def selectConversation(id: Option[ConvId]): Future[Unit] = selectedConvIdPref := id }
wireapp/wire-android-sync-engine
zmessaging/src/main/scala/com/waz/service/conversation/SelectedConversationService.scala
Scala
gpl-3.0
1,638
package net.tyler.messaging import scala.collection.mutable.ArrayBuffer import scala.collection.mutable.HashMap import com.badlogic.gdx.Gdx import net.tyler.applicationname.Configuration class MessagePassing { private val registeredComponents = new HashMap[Class[_ <: Message], ArrayBuffer[MessagingComponent]] /** * Register a component to receive messages about a given message type. * * @param component * @param messageType */ def register(component : MessagingComponent, messageType : Class[_ <: Message]) { Gdx.app.log(Configuration.LOG, "Registering component " + component.toString + " for message type ") val componentList = registeredComponents.getOrElseUpdate(messageType, new ArrayBuffer[MessagingComponent]) componentList += component Gdx.app.log(Configuration.LOG, "Registered components map: " + registeredComponents.toString) } /** * Send a new message. This will get routed to 0 or more components. * * @param message */ def send(message: Message) { val componentList = registeredComponents.getOrElse(message.getClass, new ArrayBuffer[MessagingComponent]) Gdx.app.log(Configuration.LOG, "Received message -> " + message.toString) componentList.foreach((component: MessagingComponent) => { Gdx.app.log(Configuration.LOG, component.toString + " -> " + message.toString) component.receive(message) }) } }
DaveTCode/LibgdxTemplateProject
LibgdxCoreProject/src/net/tyler/messaging/MessagePassing.scala
Scala
mit
1,521
/* NSC -- new Scala compiler * Copyright 2005-2013 LAMP/EPFL * @author Paul Phillips */ package org.apache.spark.repl import scala.tools.nsc._ import scala.tools.nsc.interpreter._ import scala.reflect.internal.util.Position import scala.util.control.Exception.ignoring import scala.tools.nsc.util.stackTraceString /** * Machinery for the asynchronous initialization of the repl. */ trait SparkILoopInit { self: SparkILoop => /** Print a welcome message */ def printWelcome() { echo("""Welcome to ____ __ / __/__ ___ _____/ /__ _\\ \\/ _ \\/ _ `/ __/ '_/ /___/ .__/\\_,_/_/ /_/\\_\\ version 1.0.0-SNAPSHOT /_/ """) import Properties._ val welcomeMsg = "Using Scala %s (%s, Java %s)".format( versionString, javaVmName, javaVersion) echo(welcomeMsg) echo("Type in expressions to have them evaluated.") echo("Type :help for more information.") } protected def asyncMessage(msg: String) { if (isReplInfo || isReplPower) echoAndRefresh(msg) } private val initLock = new java.util.concurrent.locks.ReentrantLock() private val initCompilerCondition = initLock.newCondition() // signal the compiler is initialized private val initLoopCondition = initLock.newCondition() // signal the whole repl is initialized private val initStart = System.nanoTime private def withLock[T](body: => T): T = { initLock.lock() try body finally initLock.unlock() } // a condition used to ensure serial access to the compiler. @volatile private var initIsComplete = false @volatile private var initError: String = null private def elapsed() = "%.3f".format((System.nanoTime - initStart).toDouble / 1000000000L) // the method to be called when the interpreter is initialized. // Very important this method does nothing synchronous (i.e. do // not try to use the interpreter) because until it returns, the // repl's lazy val `global` is still locked. protected def initializedCallback() = withLock(initCompilerCondition.signal()) // Spins off a thread which awaits a single message once the interpreter // has been initialized. protected def createAsyncListener() = { io.spawn { withLock(initCompilerCondition.await()) asyncMessage("[info] compiler init time: " + elapsed() + " s.") postInitialization() } } // called from main repl loop protected def awaitInitialized(): Boolean = { if (!initIsComplete) withLock { while (!initIsComplete) initLoopCondition.await() } if (initError != null) { println(""" |Failed to initialize the REPL due to an unexpected error. |This is a bug, please, report it along with the error diagnostics printed below. |%s.""".stripMargin.format(initError) ) false } else true } // private def warningsThunks = List( // () => intp.bind("lastWarnings", "" + typeTag[List[(Position, String)]], intp.lastWarnings _), // ) protected def postInitThunks = List[Option[() => Unit]]( Some(intp.setContextClassLoader _), if (isReplPower) Some(() => enablePowerMode(true)) else None ).flatten // ++ ( // warningsThunks // ) // called once after init condition is signalled protected def postInitialization() { try { postInitThunks foreach (f => addThunk(f())) runThunks() } catch { case ex: Throwable => initError = stackTraceString(ex) throw ex } finally { initIsComplete = true if (isAsync) { asyncMessage("[info] total init time: " + elapsed() + " s.") withLock(initLoopCondition.signal()) } } } def initializeSpark() { intp.beQuietDuring { command(""" @transient val sc = org.apache.spark.repl.Main.interp.createSparkContext(); """) command("import org.apache.spark.SparkContext._") } echo("Spark context available as sc.") } // code to be executed only after the interpreter is initialized // and the lazy val `global` can be accessed without risk of deadlock. private var pendingThunks: List[() => Unit] = Nil protected def addThunk(body: => Unit) = synchronized { pendingThunks :+= (() => body) } protected def runThunks(): Unit = synchronized { if (pendingThunks.nonEmpty) logDebug("Clearing " + pendingThunks.size + " thunks.") while (pendingThunks.nonEmpty) { val thunk = pendingThunks.head pendingThunks = pendingThunks.tail thunk() } } }
dotunolafunmiloye/spark
repl/src/main/scala/org/apache/spark/repl/SparkILoopInit.scala
Scala
apache-2.0
4,507
package com.sgtest.services import javax.inject.Singleton import com.swissguard.authentication.thriftscala.{RegistrationRequest, LoginRequest, AuthenticationService => TAuthenticationService} import com.twitter.finagle._ import com.twitter.finagle.service.RetryBudget import com.twitter.finagle.stats.{DefaultStatsReceiver, NullStatsReceiver} import com.twitter.finagle.tracing._ import com.twitter.finagle.zipkin.thrift.ZipkinTracer import com.twitter.finatra.annotations.Flag import com.twitter.util.Future import com.twitter.conversions.time._ @Singleton class UserService { val receiver = DefaultStatsReceiver.get val tracer = ZipkinTracer.mk( host = "localhost", port = 9410, statsReceiver = receiver, sampleRate = 1.0f ) val budget: RetryBudget = RetryBudget( ttl = 10.seconds, minRetriesPerSec = 5, percentCanRetry = 0.1 ) private val client: TAuthenticationService[Future] = ThriftMux.client .withTracer(tracer) .withStatsReceiver(receiver) .withLabel("test-client") .newIface[TAuthenticationService.FutureIface]("localhost:9999") def registerUser(registrationRequest: RegistrationRequest) = client.register(registrationRequest) def login(loginRequest: LoginRequest) = client.login(loginRequest) } //http://localhost:8888/register //{ // "username": "joe", // "password": "bobby123", // "email": "lol" //}
divanvisagie/swiss-guard
test-client/src/main/scala/com/sgtest/services/UserService.scala
Scala
apache-2.0
1,384
package scommons.client.showcase.action.api import org.scalajs.dom import scommons.api.{ApiStatus, StatusResponse} import scala.concurrent.duration._ import scala.concurrent.{Future, Promise} trait Api { def successExample(): Future[SuccessfulResp] = { Future.successful(SuccessfulResp("All good!")) } def timedoutExample(): Future[StatusResponse] = { val promise = Promise[StatusResponse]() var handleId = 0 handleId = dom.window.setTimeout({ () => dom.window.clearTimeout(handleId) promise.failure(new Exception("Request timed out, unable to get timely response")) }, 2.seconds.toMillis.toDouble) promise.future } def failedExample(): Future[StatusResponse] = { Future.successful(StatusResponse( ApiStatus(500, "Internal Server Error", "Some error occurred, try again later)") )) } }
viktor-podzigun/scommons
showcase/src/main/scala/scommons/client/showcase/action/api/Api.scala
Scala
apache-2.0
859
package jitd.codegen.policy import jitd.codegen.Render import jitd.spec._ import jitd.codegen.policy.txt._ object NaivePolicyImplementation extends PolicyImplementation { // Render field definitions for the JITD object def state(ctx:Render): String = "" // Render a block of code to be run when the JITD is initialized def init(ctx:Render, root:String): String = "" // Render two blocks of code to be run just before/after a JITD rewrite // happens. [from] is replaced by [to]. def onRewriteSet(ctx:Render, definition:Definition, mutator: Boolean, handlerefbool:Boolean, from:MatchPattern, to:ConstructorPattern, fromTarget:String, toTarget:String ): (Statement, Statement) = (Comment(s"onRewrite1"), Comment(s"onRewrite2")) def onRewrite(ctx:Render, from:MatchPattern, to:ConstructorPattern, fromTarget:String, toTarget:String ): (Statement, Statement) = (Comment(s"onRewrite1"), Comment(s"onRewrite2")) def utilityFunctions(ctx:Render, rule:PolicyRule): String = { rule match { case TieredPolicy(policies) => policies.map { utilityFunctions(ctx, _) }.mkString case TransformPolicy(name, constraint, scoreFn) => NaivePolicySearch( // Generated via Twirl template ctx, ctx.definition.transform(name), constraint, scoreFn ).toString } } def utilityFunctions(ctx:Render): String = utilityFunctions(ctx, ctx.policy.rule) def doOrganize(ctx:Render, root:String, rule:PolicyRule, onSuccess:String, onFail:String): String = rule match { case TieredPolicy(Seq()) => onFail case TieredPolicy(policies) => doOrganize(ctx, root, policies.head, onSuccess, "")+" "+ doOrganize(ctx, root, TieredPolicy(policies.tail), onSuccess, onFail) case TransformPolicy(name, _, _) => NaivePolicyTryTransform(ctx, root, name, onSuccess, onFail).toString } // Render a block of code to be run when an idle cycle is available. def doOrganize(ctx:Render, root:String): String = doOrganize(ctx, root, ctx.policy.rule, "return true;\n", "return false;\n")+"\n" }
UBOdin/jitd-synthesis
src/main/scala/jitd/codegen/policy/NaivePolicyImplementation.scala
Scala
apache-2.0
2,186
// Copyright © 2011-2012, Jeremy Heiner (github.com/JHeiner). // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of the copyright holder nor the names of any // 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 HOLDER 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 protractor.test import scala.annotation.tailrec import SeqReal.toSeqReal object SeqFloat { type T = Float // BEGIN copy+paste >>>>>>>>>>>>>>>> def dot( one:Array[T], two:Array[T] ) = { @tailrec def dp( i:Int, sum:T ):T = if ( 0 > i ) sum else dp( i - 1, sum + one(i) * two(i) ) dp( one.length - 1, 0 ) } def dotKahan( one:Array[T], two:Array[T] ) = { @tailrec def dp( i:Int, carry:T, sum:T ):T = if ( 0 > i ) sum else { val value = one(i) * two(i) - carry val total = sum + value dp( i - 1, (total - sum) - value, total ) } dp( one.length - 1, 0, 0 ) } // <<<<<<<<<<<<<<<< copy+paste END def dotDouble( one:Array[T], two:Array[T] ):Double = { @tailrec def dp( i:Int, sum:Double ):Double = if ( 0 > i ) sum else dp( i - 1, sum + one(i).toDouble * two(i).toDouble ) dp( one.length - 1, 0 ) } def dotKahanDouble( one:Array[T], two:Array[T] ):Double = { @tailrec def dp( i:Int, carry:Double, sum:Double ):Double = if ( 0 > i ) sum else { val value = one(i).toDouble * two(i).toDouble - carry val total = sum + value dp( i - 1, (total - sum) - value, total ) } dp( one.length - 1, 0, 0 ) } }
JHeiner/Protractor
src/test/scala/protractor/test/SeqFloat.scala
Scala
bsd-3-clause
2,806
package controllers import twentysix.playr._ import twentysix.playr.simple._ import play.api.mvc._ import play.api.libs.json.Json import models._ import play.api.cache.CacheApi import javax.inject.Inject class ColorController @Inject() (colorContainer: ColorContainer) extends Resource[Color] with InjectedController with ResourceRead with ResourceList with ResourceCreate with ResourceWrite { val name = "color" implicit val colorFormat = Json.format[Color] def fromId(sid: String) = toInt(sid).flatMap(id => colorContainer.get(id)) def list = Action { Ok(Json.toJson(colorContainer.list)) } def read(color: Color) = Action { Ok(Json.toJson(color)) } def write(color: Color) = Action(parse.json) { request => val newColor = request.body.as[Color].copy(id = color.id) colorContainer.update(newColor) Ok(Json.toJson(newColor)) } def create = Action(parse.json) { request => val newColor = request.body.as[Color] colorContainer.add(newColor.name, newColor.rgb) Created(Json.toJson(newColor)) } }
26lights/PlayR
samples/playr-tutorial/app/controllers/ColorController.scala
Scala
bsd-3-clause
1,068
/* * Copyright (c) 2014-2018 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, and * you may not use this file except in compliance with the Apache License * Version 2.0. You may obtain a copy of the Apache License Version 2.0 at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the Apache License Version 2.0 is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the Apache License Version 2.0 for the specific language * governing permissions and limitations there under. */ package com.snowplowanalytics.iglu.server package actor // This project import SchemaActor._ // Akka import akka.actor.ActorSystem import akka.pattern.ask import akka.testkit.{ ImplicitSender, TestActorRef, TestKit } import akka.util.Timeout // Scala import scala.concurrent.duration._ import scala.util.Success // Akka Http import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.StatusCodes._ class SchemaActorSpec extends TestKit(ActorSystem()) with SetupAndDestroy with ImplicitSender { implicit val timeout = Timeout(20 seconds) val schema = TestActorRef(new SchemaActor(config)) val owner = "com.unittest" val otherOwner = "com.benfradet" val permission = "write" val isPublic = false val vendor = "com.unittest" val vendors = vendor val otherVendor = "com.benfradet" val otherVendors = otherVendor val faultyVendor = "com.test" val faultyVendors = faultyVendor val name = "unit_test3" val names = name val name2 = "unit_test6" val faultyName = "unit_test4" val faultyNames = faultyName val otherName = "unit_test5" val otherNames = otherName val format = "jsonschema" val notSupportedFormat = "notSupportedFormat" val formats = format val version = "1-0-0" val versions = version val invalidSchema = """{ "some" : "json" }""" val innerSchema = "\\"some\\" : \\"json\\"" val validSchema = """{ "$schema" : "http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#", "self": { "vendor": "com.snowplowanalytics.snowplow", "name": "ad_click", "format": "jsonschema", "version": "1-0-0" }, "description": "Example valid schema", "type": "object", "properties": {} }""" val notJson = "not json" val validInstance = """{ "targetUrl": "somestr" }""" sequential "SchemaActor" should { "for AddSchema" should { "return a 201 if the schema doesnt already exist and is private" in { val future = schema ? AddSchema(vendor, name, format, version, draftNumOfVersionedSchemas, invalidSchema, owner, permission, isPublic, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === Created result must contain("The schema has been successfully added") and contain(vendor) } "return a 201 if the schema doesnt already exist and is public" in { val future = schema ? AddSchema(otherVendor, otherName, format, version, draftNumOfVersionedSchemas, invalidSchema, otherOwner, permission, !isPublic, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === Created result must contain("The schema has been successfully added") and contain(otherVendor) } "return a 401 if the schema already exists" in { val future = schema ? AddSchema(vendor, name, format, version, draftNumOfVersionedSchemas, invalidSchema, owner, permission, isPublic, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === Unauthorized result must contain("This schema already exists") } } "for UpdateSchema" should { "return a 200 if the schema already exists" in { val future = schema ? UpdateSchema(vendor, name, format, version, draftNumOfVersionedSchemas, invalidSchema, owner, permission, isPublic, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain("The schema has been successfully updated") and contain(vendor) } "returns 201 if the schema doesnt already exist" in { val future = schema ? UpdateSchema(vendor, name2, format, version, draftNumOfVersionedSchemas, invalidSchema, owner, permission, isPublic, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === Created result must contain("The schema has been successfully added") and contain(vendor) } } "for GetPublicSchemas" should { "return a 200 if there are public schemas available" in { val future = schema ? GetAllSchemas(owner, permission, includeMetadata = false, isDraft = false, false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain("iglu:com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0") } } "for GetPublicMetadata" should { "return a 200 if there are public schemas available" in { val future = schema ? GetAllMetadata(owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get result must contain(otherVendor) and contain(otherName) and contain(format) and contain(version) } } "for GetSchema" should { "return a 200 if the schema exists and is private" in { val future = schema ? GetSchema(vendors, names, formats, versions, draftNumOfVersionedSchemas, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(innerSchema) } "return a 200 if the schema exists and is public" in { val future = schema ? GetSchema(otherVendors, otherNames, formats, versions, draftNumOfVersionedSchemas, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(innerSchema) } """return a 404 if the owner is not a prefix of the vendor and the schema is private""" in { val future = schema ? GetSchema(vendors, names, formats, versions, draftNumOfVersionedSchemas, otherOwner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } "return a 404 if the schema doesnt exist" in { val future = schema ? GetSchema(vendors, faultyNames, formats, versions, draftNumOfVersionedSchemas, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } } "for GetMetadata" should { "return a 200 if the schema exists" in { val future = schema ? GetMetadata(vendors, names, formats, versions, draftNumOfVersionedSchemas, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(vendor) and contain(name) and contain(format) and contain(version) } "return a 200 if the schema exists and is public" in { val future = schema ? GetMetadata(otherVendors, otherNames, formats, versions, draftNumOfVersionedSchemas, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(otherVendor) and contain(otherName) and contain(format) and contain(version) } """return a 401 if the owner is not a prefix of the vendor and the schema is private""" in { val future = schema ? GetSchema(vendors, names, formats, versions, draftNumOfVersionedSchemas, otherOwner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } "return a 404 if the schema doesnt exist" in { val future = schema ? GetMetadata(vendors, faultyNames, formats, versions, "", owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } } "for GetSchemasFromFormat" should { "return a 200 if there are schemas available" in { val future = schema ? GetSchemasFromFormat(vendors, names, formats, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(innerSchema) } "return a 200 if there are schemas available and they are public" in { val future = schema ? GetSchemasFromFormat(otherVendors, otherNames, formats, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(innerSchema) } """return a 404 if the owner is not a prefix of the vendor and the schemas are private""" in { val future = schema ? GetSchemasFromFormat(vendors, names, formats, otherOwner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } "return a 404 if there are no schemas available" in { val future = schema ? GetSchemasFromFormat(vendors, faultyNames, formats, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } } "for GetMetadataFromFormat" should { "return a 200 if there are schemas available" in { val future = schema ? GetMetadataFromFormat(vendors, names, formats, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(vendor) and contain(name) and contain(format) } "return a 200 if there are schemas available and they are public" in { val future = schema ? GetMetadataFromFormat(otherVendors, otherNames, formats, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(otherVendor) and contain(otherName) and contain(format) } """return a 404 if the owner is not a prefix of the vendor and the schemas are private""" in { val future = schema ? GetMetadataFromFormat(vendors, names, formats, otherOwner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } "return a 404 if there are no schemas available" in { val future = schema ? GetMetadataFromFormat(vendors, faultyNames, formats, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } } "for GetSchemasFromName" should { "return a 200 if there are schemas available" in { val future = schema ? GetSchemasFromName(vendors, names, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(innerSchema) } "return a 200 if there are schemas available and they are public" in { val future = schema ? GetSchemasFromName(otherVendors, otherNames, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(innerSchema) } """return a 404 if the owner is not a prefix of the vendor and the schemas are private""" in { val future = schema ? GetSchemasFromName(vendors, names, otherOwner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } "return a 404 if there are no schemas available" in { val future = schema ? GetSchemasFromName(vendors, faultyNames, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } } "for GetMetadataFromName" should { "return a 200 if there are schemas available" in { val future = schema ? GetMetadataFromName(vendors, names, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(vendor) and contain(name) } "return a 200 if there are schemas available and they are public" in { val future = schema ? GetMetadataFromName(otherVendors, otherNames, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(otherVendor) and contain(otherName) } """return a 404 if the owner is not a prefix of the vendor and the schemas are private""" in { val future = schema ? GetMetadataFromName(vendors, names, otherOwner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } "return a 404 if there are no schemas available" in { val future = schema ? GetMetadataFromName(vendors, faultyNames, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } } "for GetSchemasFromVendor" should { "return a 200 if there are schemas available" in { val future = schema ? GetSchemasFromVendor(vendors, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(innerSchema) } "return a 200 if there are schemas available and they are public" in { val future = schema ? GetSchemasFromVendor(otherVendors, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(innerSchema) } """return a 404 if the owner is not a prefix of the vendor and the schemas are private""" in { val future = schema ? GetSchemasFromVendor(vendors, otherOwner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } "return a 404 if there are no schemas available" in { val future = schema ? GetSchemasFromVendor(faultyVendors, owner, permission, includeMetadata = false, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } } "for GetMetadataFromVendor" should { "return a 200 if there are schemas available" in { val future = schema ? GetMetadataFromVendor(vendors, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(vendor) } "return a 200 if there are schemas available and they are public" in { val future = schema ? GetMetadataFromVendor(otherVendors, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain(otherVendor) } """return a 404 if the owner is not a prefix of the vendor and the schemas are private""" in { val future = schema ? GetMetadataFromVendor(vendors, otherOwner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } "return a 404 if there are no schemas available" in { val future = schema ? GetMetadataFromVendor(faultyVendors, owner, permission, isDraft = false) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("There are no schemas available here") } } "for Validate" should { val vendor = "com.snowplowanalytics.snowplow" val name = "ad_click" "return a 200 if the instance is valid against the schema" in { val future = schema ? Validate(vendor, name, format, version, validInstance) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain("The instance provided is valid against the schema") } "return a 400 if the instance is not valid against the schema" in { val future = schema ? Validate(vendor, name, format, version, invalidSchema) val Success((status: StatusCode, result: String)) = future.value.get status === BadRequest result must contain("The instance provided is not valid against the schema") } "return a 400 if the instance provided is not valid" in { val future = schema ? Validate(vendor, name, format, version, notJson) val Success((status: StatusCode, result: String)) = future.value.get status === BadRequest result must contain("The instance provided is not valid") } "return a 404 if the schema to validate against was not found" in { val future = schema ? Validate("com.unittest", name, format, version, validInstance) val Success((status: StatusCode, result: String)) = future.value.get status === NotFound result must contain("The schema to validate against was not found") } } "for ValidateSchema" should { """return a 200 if the schema provided is self-describing and gives back the schema""" in { val future = schema ? ValidateSchema(validSchema, format) val Success((status: StatusCode, result: String)) = future.value.get status === OK } "return a 200 if the schema provided is self-describing" in { val future = schema ? ValidateSchema(validSchema, format) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain("The schema provided is a valid self-describing schema") } "return a 200 if the schema provided is not self-describing" in { val future = schema ? ValidateSchema(invalidSchema, format) val Success((status: StatusCode, result: String)) = future.value.get status === OK result must contain("Schema is not self-describing") } "return a 400 if the string provided is not valid" in { val future = schema ? ValidateSchema(notJson, format) val Success((status: StatusCode, result: String)) = future.value.get status === BadRequest result must contain("The schema provided is not valid") } "return a 400 if the schema format provided is not supported" in { val future = schema ? ValidateSchema(validSchema, notSupportedFormat) val Success((status: StatusCode, result: String)) = future.value.get status === BadRequest result must contain("The schema format provided is not supported") } } } }
snowplow/iglu
2-repositories/iglu-server/src/test/scala/com.snowplowanalytics.iglu.server/actor/SchemaActorSpec.scala
Scala
apache-2.0
21,575
package com.lge.metr import java.io.ByteArrayInputStream import java.io.File import java.io.FileInputStream import java.io.InputStream import scala.collection.mutable.ListBuffer abstract class Resource { def inputStream: InputStream } class StringResource(src: String) extends Resource { def inputStream = new ByteArrayInputStream(src.getBytes) } class FileResource(f: File) extends Resource { def inputStream = new FileInputStream(f) } class Metric extends MetricCounter { val java = new AntlrJavaProcessor() val inputs = ListBuffer[Resource]() def addSource(src: Resource): Unit = inputs += src def addSource(src: String): Unit = addSource(new StringResource(src)) def addSource(f: File) { inputs ++= FileUtil.gatherFiles(f, ".java").map(new FileResource(_)) } val entries = ListBuffer[StatEntry]() def load: Unit = inputs.foreach { in => val cu = java.process(in.inputStream) entries ++= cu.exes.map(exe => StatEntry(cc(exe), sloc(exe).toInt, dloc(exe))) } def generate(reportFile: File) { new TextGenerator(reportFile).generate(entries) } def stat: StatEntry = StatEntry( entries.map(_.cc - 1).sum + 1, entries.map(_.sloc).sum, entries.map(_.dloc).sum) } object Metric { def apply(src: String): Metric = apply(new StringResource(src)) def apply(src: InputStream): Metric = apply(new Resource() { val inputStream = src; }) def apply(src: File): Metric = { val launcher = new Metric launcher.addSource(src) launcher.load launcher } def apply(src: Resource): Metric = { val launcher = new Metric launcher.addSource(src) launcher.load launcher } }
agiledevteam/metr
src/main/scala/com/lge/metr/Metric.scala
Scala
mit
1,682
/* * * o o o o o * | o | |\\ /| | / * | o-o o--o o-o oo | | O | oo o-o OO o-o o o * | | | | | | | | | | | | | | | | \\ | | \\ / * O---oo-o o--O | o-o o-o-o o o o-o-o o o o-o o * | * o--o * o--o o o--o o o * | | | | o | | * O-Oo oo o-o o-O o-o o-O-o O-o o-o | o-O o-o * | \\ | | | | | | | | | | | | | |-' | | | \\ * o o o-o-o o o-o o-o o o o o | o-o o o-o o-o * * Logical Markov Random Fields (LoMRF). * * */ package lomrf.mln.learning.structure.hypergraph import lomrf.logic.{ AtomSignature, Constant, EvidenceAtom, TRUE } import lomrf.mln.learning.structure.ModeParser import lomrf.mln.model._ import lomrf.mln.model.builders.EvidenceBuilder import org.scalatest.{ FunSpec, Matchers } /** * Specification test for HyperGraph paths. */ final class HPathSpecTest extends FunSpec with Matchers { private val DOMAIN_SIZE = 5 // Predicate schema private val predicateSchema = Map( AtomSignature("PredicateA", 2) -> Vector("Integer", "Integer"), AtomSignature("PredicateB", 2) -> Vector("Integer", "Character")) // Constants domain private val constantsDomain = Map( "Integer" -> ConstantsSet((0 to DOMAIN_SIZE).map(_.toString)), "Character" -> ConstantsSet("A", "B", "C", "D", "E")) // Evidence Builder val builder = EvidenceBuilder(predicateSchema, Set.empty, Set.empty, constantsDomain) // Append evidence atoms for 'PredicateA' val evidenceForPredicateA = (0 until DOMAIN_SIZE).map { integer => EvidenceAtom.asTrue("PredicateA", Vector[Constant](Constant((integer + 1).toString), Constant(integer.toString))) } builder.evidence ++= evidenceForPredicateA // Append evidence atoms for 'PredicateB' builder.evidence += EvidenceAtom.asTrue("PredicateB", Vector[Constant](Constant(0.toString), Constant("A"))) builder.evidence += EvidenceAtom.asTrue("PredicateB", Vector[Constant](Constant(1.toString), Constant("B"))) builder.evidence += EvidenceAtom.asTrue("PredicateB", Vector[Constant](Constant(2.toString), Constant("C"))) builder.evidence += EvidenceAtom.asTrue("PredicateB", Vector[Constant](Constant(3.toString), Constant("D"))) builder.evidence += EvidenceAtom.asTrue("PredicateB", Vector[Constant](Constant(4.toString), Constant("E"))) val evidence = builder.result() // Create MLN val mlnSchema = MLNSchema(predicateSchema, Map.empty, Map.empty, Map.empty) val predicateSpace = PredicateSpace(mlnSchema, Set.empty, constantsDomain) // Parse mode declarations val modes = List("modeP(1, PredicateA(-, +))", "modeP(2, PredicateB(-, #-))") .map(ModeParser.parseFrom).toMap // Identity functions for each atom signature val identities = predicateSpace.identities // Collect all atom ids in the evidence database val atomIDs = predicateSchema.keys.flatMap { signature => val db = evidence.db(signature) val idf = db.identity idf.indices filter (id => db.get(id) == TRUE) map (id => id -> signature) }.toMap it("should exist only 10 true ground atoms") { atomIDs.size shouldBe 10 } // ------------------------------------------------------------------------------------------------------------------ // --- TEST CASE: HyperGraph Path (begin from empty path). // ------------------------------------------------------------------------------------------------------------------ describe("HyperGraph Path starting from an empty path.") { var path = HPath.empty(modes, identities) // Add all ids atomIDs.foreach { case (id, signature) => path += (id, signature) } it("path should have length 10") { path.length shouldBe 10 } it("path should contain all true ground atoms, 2 atom signatures and 10 constants") { atomIDs.keys.forall(path.contains) shouldBe true predicateSchema.keys.forall(path.contains) shouldBe true constantsDomain.values.foreach { set => val iterator = set.valuesIterator while (iterator.hasNext) { iterator.advance() path.contains(iterator.key) shouldBe true } } } it("predicate appearance should contain 2 entries each having 5 appearances") { path.predicates.size shouldBe 2 path.predicateAppearance.values.forall(count => count == 5) shouldBe true } it("constant appearance should contain the correct counts for all constants") { constantsDomain("Integer").foreach { value => if (value == "0") path.constantAppearance(value) shouldBe 2 else if (value == "5") path.constantAppearance(value) shouldBe 1 else path.constantAppearance(value) shouldBe 3 } constantsDomain("Character").foreach(path.constantAppearance(_) shouldBe 0) } it("checking path ordering") { path.ordering.reverse.map { case (id, signature) => id }.toSet shouldEqual atomIDs.keys } } }
anskarl/LoMRF
src/test/scala/lomrf/mln/learning/structure/hypergraph/HPathSpecTest.scala
Scala
apache-2.0
5,071
package models.quiz.question import models.support.{QuizId, UserId, QuestionId} import org.joda.time.DateTime case class Question2Quiz(questionId: QuestionId, quizId: QuizId, ownerId: UserId, creationDate: DateTime, order: Int)
kristiankime/web-education-games
app/models/quiz/question/Question2Quiz.scala
Scala
mit
231
/* * Copyright 2015 Mike Limansky * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.limansky.mongoquery.core import java.io.File import java.net.URLClassLoader import org.scalatest.{ FlatSpec, Matchers } import org.scalatest.prop.TableDrivenPropertyChecks import scala.reflect.runtime.{ universe => ru } import scala.tools.reflect.{ ToolBox, ToolBoxError } abstract class CompileErrorsTest extends FlatSpec with Matchers with TableDrivenPropertyChecks { val cl = getClass.getClassLoader.asInstanceOf[URLClassLoader] val cp = cl.getURLs.map(_.getFile).mkString(File.pathSeparator) val mirror = ru.runtimeMirror(cl) val tb = mirror.mkToolBox(options = s"-cp $cp") def imports = "com.github.limansky.mongoquery.core.TestObjects._" :: Nil def wi(s: String) = imports.map("import " + _).reduceLeft(_ + "\\n" + _) + "\\n" + s val malformed = Table( ("query", "message"), ("""mq"{ a 1 }"""", "`}' expected, but identifier a found"), ("""mq"{ a : 1"""", "end of input"), ("""mq"a : 1}"""", "`{' expected, but a found") //, // ("""mq{a : 1 b : "foo"}""", "`,' expected, but b found") // weird error ) def checkError(q: String, m: String) = { val e = intercept[ToolBoxError] { tb.eval(tb.parse(wi(q))) } e.message should include(m) } "mq" should "fail on malformed BSON" in { forAll(malformed)(checkError) } it should "fail on unknown operators" in { checkError("""mq"{a : { $$exits : true}}"""", "Unknown operator '$exits'. Possible you mean '$exists'") } val unknownField = Table( ("query", "message"), ("""mqt"{a : 'bar'}"[Foo]""", "Class Foo doesn't contain field 'a'"), ("""mqt"{f.a : 'bar'}"[Bar]""", "Class Foo doesn't contain field 'a'"), ("""mqt"{f.a : 'bar'}"[Baz]""", "Class Foo doesn't contain field 'a'"), ("""mqt"{lf.1.a : 'bar'}"[Quux]""", "Class Foo doesn't contain field 'a'"), ("""mqt"{lf.$$.a : 'bar'}"[Quux]""", "Class Foo doesn't contain field 'a'"), ("""mqt"{f.1.s : 'bar'}"[Quux]""", "Class Quux doesn't contain field 'f'") ) "mqt" should "fail if field does not exists" in { forAll(unknownField)(checkError) } val wrongIndexing = Table( ("query", "message"), ("""mqt"{ s.1 : 'test'}"[Foo]""", "Field s of type String cannot be indexed"), ("""mqt"{ i.1 : 42}"[Bar]""", "Field i of type Int cannot be indexed"), ("""mqt"{ f.1 : 42}"[Baz]""", "Field f of type Option[com.github.limansky.mongoquery.core.TestObjects.Foo] cannot be indexed") ) it should "fail on indexing of not Traversable" in { forAll(wrongIndexing)(checkError) } }
limansky/mongoquery
core/src/test/scala/com/github/limansky/mongoquery/core/CompileErrorsTest.scala
Scala
apache-2.0
3,134
/* * Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com> */ package play.api.http import play.api.Logger import play.api.mvc.RequestHeader import scala.collection.BitSet import scala.util.Try import scala.util.parsing.combinator.Parsers import scala.util.parsing.input.CharSequenceReader object ContentEncoding { // Taken from https://www.iana.org/assignments/http-parameters/http-parameters.xhtml val Aes128gcm = "aes128gcm" val Gzip = "gzip" val Brotli = "br" val Compress = "compress" val Deflate = "deflate" val Exi = "exi" val Pack200Gzip = "pack200-gzip" val Identity = "identity" // not official but common val Bzip2 = "bzip2" val Xz = "xz" val `*` = "*" } /** * A representation of an encoding preference as specified in the Accept-Encoding header. This contains an encoding * name (or *), and an optional q-value. */ case class EncodingPreference(name: String = "*", qValue: Option[BigDecimal] = None) { /** * `true` if this is a wildcard `*` preference. */ val matchesAny: Boolean = name == "*" /** * The effective q-value. Defaults to 1 if none is specified. */ val q: BigDecimal = qValue getOrElse 1.0 /** * Check if this encoding preference matches the specified encoding name. */ def matches(contentEncoding: String): Boolean = matchesAny || name.equalsIgnoreCase(contentEncoding) } object EncodingPreference { /** * Ordering for encodings, in order of highest priority to lowest priority. */ implicit val ordering: Ordering[EncodingPreference] = ordering(_ compare _) /** * An ordering for EncodingPreferences with a specific function for comparing names. Useful to allow the server to * provide a preference. */ def ordering(compareByName: (String, String) => Int): Ordering[EncodingPreference] = new Ordering[EncodingPreference] { def compare(a: EncodingPreference, b: EncodingPreference) = { val qCompare = a.q compare b.q val compare = if (qCompare != 0) -qCompare else compareByName(a.name, b.name) if (compare != 0) compare else if (a.matchesAny) 1 else if (b.matchesAny) -1 else 0 } } } /** * A representation of the Accept-Encoding header */ trait AcceptEncoding { /** * The list of Accept-Encoding headers in order of appearance */ def headers: Seq[String] /** * A list of encoding preferences, sorted from most to least preferred, and normalized to lowercase names. */ lazy val preferences: Seq[EncodingPreference] = headers.flatMap(AcceptEncoding.parseHeader).map { e => e.copy(name = e.name.toLowerCase) }.sorted /** * Returns `true` if we can safely fall back to the identity encoding if no supported encoding is found. */ lazy val identityAllowed: Boolean = preferences.find(_.matches(ContentEncoding.Identity)).forall(_.q > 0) /** * Returns `true` if and only if the encoding is accepted by this Accept-Encoding header. */ def accepts(encoding: String): Boolean = { preferences.exists(_.matches(encoding)) } /** * Given a list of encoding names, choose the most preferred by the client. If several encodings are equally * preferred, choose the one first in the list. * * Note that this chooses not to handle the "*" value, since its presence does not tell us if the client supports * the specific encoding. */ def preferred(choices: Seq[String]): Option[String] = { // filter matches to ones in the choices val filteredMatches = preferences.filter(e => e.q > 0 && choices.exists(e.matches)) // get top preference by finding max q and then getting preferred option among those val preference = if (filteredMatches.isEmpty) None else { val maxQ = filteredMatches.maxBy(_.q).q filteredMatches.filter(maxQ == _.q).sortBy { pref => val idx = choices.indexWhere(pref.matches) if (idx == -1) Int.MaxValue else idx }.headOption } // return the name of the encoding if it matches any, otherwise identity if it is accepted by the client preference match { case Some(pref) if !pref.matchesAny => Some(pref.name) case _ if identityAllowed => Some(ContentEncoding.Identity) case _ => None } } } object AcceptEncoding { private val logger = Logger(getClass) /** * Convenience method for creating an AcceptEncoding from varargs of header strings. */ def apply(allHeaders: String*): AcceptEncoding = fromHeaders(allHeaders) /** * Get an [[AcceptEncoding]] for this request. */ def forRequest(request: RequestHeader): AcceptEncoding = fromHeaders(request.headers.getAll(HeaderNames.ACCEPT_ENCODING)) /** * Create an AcceptEncoding from a list of headers. */ def fromHeaders(allHeaders: Seq[String]) = new AcceptEncoding { def headers: Seq[String] = allHeaders } /** * Parse a single Accept-Encoding header and return a list of preferred encodings. */ def parseHeader(acceptEncoding: String): Seq[EncodingPreference] = { AcceptEncodingParser(new CharSequenceReader(acceptEncoding)) match { case AcceptEncodingParser.Success(encs: Seq[EncodingPreference], next) => if (!next.atEnd) { logger.debug(s"Unable to parse part of Accept-Encoding header '${next.source}'") } encs case AcceptEncodingParser.NoSuccess(err, _) => logger.debug(s"Unable to parse Accept-Encoding header '$acceptEncoding': $err") Seq.empty } } /** * Parser for content encodings */ private[http] object AcceptEncodingParser extends Parsers { private val logger = Logger(this.getClass()) val separatorChars = "()<>@,;:\\\\\\"/[]?={} \\t" val separatorBitSet = BitSet(separatorChars.toCharArray.map(_.toInt): _*) val qChars = "Qq" val qBitSet = BitSet(qChars.toCharArray.map(_.toInt): _*) type Elem = Char val any = acceptIf(_ => true)(_ => "Expected any character") val end = not(any) /* * RFC 2616 section 2.2 * * These patterns are translated directly using the same naming */ val ctl = acceptIf { c => (c >= 0 && c <= 0x1F) || c == 0x7F }(_ => "Expected a control character") val char = acceptIf(_ < 0x80)(_ => "Expected an ascii character") val text = not(ctl) ~> any val separators = { acceptIf(c => separatorBitSet(c))(_ => s"Expected one of $separatorChars") } val qParamName = { acceptIf(c => qBitSet(c))(_ => s"Expected one of $qChars") } val token = rep1(not(separators | ctl) ~> any) ^^ charSeqToString def badPart(p: Char => Boolean, msg: => String) = rep1(acceptIf(p)(ignoreErrors)) ^^ { case chars => logger.debug(msg + ": " + charSeqToString(chars)) None } val badQValue = badPart(c => c != ',' && c != ';', "Bad q value format") val badEncoding = badPart(c => c != ',', "Bad encoding") def tolerant[T](p: Parser[T], bad: Parser[Option[T]]) = p.map(Some.apply) | bad val qParameter = qParamName ~> '=' ~> token <~ rep(' ') // Either it's a valid parameter followed immediately by the end, a comma, or it's a bad parameter val tolerantQParameter = tolerant(qParameter <~ guard(end | ','), badQValue) val qValue = opt(';' ~> rep(' ') ~> tolerantQParameter <~ rep(' ')) ^^ (_.flatten) val encoding: Parser[EncodingPreference] = (token <~ rep(' ')) ~ qValue ^^ { case encoding ~ qValue => EncodingPreference(encoding, qValue.flatMap { q => Try(BigDecimal(q)).filter(q => q >= 0 && q <= 1).map(Some.apply).getOrElse { logger.debug(s"Invalid q value: $q") None } }) } val tolerantEncoding = tolerant(encoding <~ guard(end | ','), badEncoding) val encodings = rep1sep(tolerantEncoding, ',' ~ rep(' ')).map(_.flatten) def apply(in: Input): ParseResult[Seq[EncodingPreference]] = encodings(in) def ignoreErrors(c: Char) = "" def charSeqToString(chars: Seq[Char]) = new String(chars.toArray) } }
Shenker93/playframework
framework/src/play/src/main/scala/play/api/http/AcceptEncoding.scala
Scala
apache-2.0
8,020
// Benedict R. Gaster // March 2015 // // GADTs in Scala // // Of course, many will argue these are in fact inductive familes // and clearly Haskell's GADTs came later but as I started there for // this particular exercise I'll stick with it... // // I make no claim for any of this being original or new, rather I // wanted to develop my understanding of implementing GADTs in Scala. // Still early days in that regard :-) //------------------------------------------------------------------------------------ // Use the Leibniz library from scalaz to implement type level equality // see: https://github.com/scalaz/scalaz // Depends on the compile plugin kind-projector, so we get nice type // level lambdas see: https://github.com/non/kind-projector //------------------------------------------------------------------------------------ // Of course, we begin with the standard correctly typed expression // evaluator, and extend it to simply typed lambda calculus afterwards. // As we parametrize only a single type there is no issue with // type refinement in this case package object Exp { sealed trait Exp[A] { def eval: A = Exp.evalAny(this) } case class LitInt(i: Int) extends Exp[Int] case class LitBool(b: Boolean) extends Exp[Boolean] case class Add(e1: Exp[Int], e2: Exp[Int]) extends Exp[Int] case class Mul(e1: Exp[Int], e2: Exp[Int]) extends Exp[Int] case class Cond[A](b: Exp[Boolean], thn: Exp[A], els: Exp[A]) extends Exp[A] case class Eq[A](e1: Exp[A], e2: Exp[A]) extends Exp[Boolean] object Exp { def evalAny[A](e: Exp[A]): A = e match { case LitInt(i) => i case LitBool(b) => b case Add(e1, e2) => e1.eval + e2.eval case Mul(e1, e2) => e1.eval * e2.eval case Cond(b, thn, els) => if (b.eval) { thn.eval } else { els.eval } case Eq(e1, e2) => e1.eval == e2.eval } } val exp10 = LitInt(10) val exp20 = LitInt(20) val exp30 = Add(exp10,exp20) val expF = LitBool(false) val v30 = exp30.eval // next one won't compile, of course... // val expFp20 = Add(expF, exp20) } package object STLam { sealed trait STLam[A] { def eval: A = STLam.evalAny(this) } case class Lift[A] ( a: A ) extends STLam[A] case class Tup[A,B] ( fst: STLam[A], snd: STLam[B] ) extends STLam[(A,B)] case class Lam[A,B]( f: STLam[A] => STLam[B]) extends STLam[A => B] case class App[A,B]( f: STLam[A => B], a : STLam[A]) extends STLam[B] case class Fix[A,B] ( f: STLam[(A=>B) => (A=>B)] ) extends STLam[A=>B] object STLam { // fixed point operator // (http://rosettacode.org/wiki/Y_combinator#Scala) private def Y[A,B](f: (A=>B)=>(A=>B)) = { case class W(wf: W=>A=>B) { def apply(w: W) = wf(w) } val g: W=>A=>B = w => f(w(w))(_) g(W(g)) } def evalAny[A](l: STLam[A]): A = l match { case Lift(a) => a case Tup(e1,e2) => (e1.eval, e2.eval) case Lam(f) => (x) => f(Lift(x)).eval case App(f,e) => f.eval (e.eval) case Fix(f) => Y(f.eval) // note as Scala is strict we can't do a 1:1 mapping with the // Haskell version, i.e. we can't implement fized point // operator inline. at least i don't know how to do it. } } val id = Lam[Int,Int] (x => x) val ten = App(id, Lift(10)).eval // factorial val fact = (x: Int) => App(Fix[Int,Int] ( Lam (f => Lam (v => { val n = v.eval Lift( if (n == 0) 1 else n * f.eval (n - 1)) }))), Lift(x)).eval // fibonacci val fib = (x: Int) => App(Fix[Int,Int] ( Lam (f => Lam (v => { val n = v.eval Lift( if (n < 3) n else f.eval(n - 1) + f.eval (n - 2)) }))), Lift(x)).eval } //------------------------------------------------------------------------------------ // Implementation of SafeList from Haskell's wiki on GADTs: // http://en.wikibooks.org/wiki/Haskell/GADT#Examples This is a // example of usful technique of using "empty" types to index // into a type. // We implement two variants, as per the wiki. The first also // implements the excerise (safeTail) and so is slightly extended // compared to the version documented on the wiki. Note to get a // generic safeTail, as can be seen in the implementation, I had // to change the type slightly. // Of course, this isomorphic lists with a length as are effectively // encoding this in the type. package object SafeList { // import shapeless._ // import syntax.singleton._ final case class Empty() final case class NonEmpty[A]() // A represents the rest of the list, // needed for safeTail sealed trait SafeList[+A,B] final case class SNil[+A]() extends SafeList[A,Empty] final case class SCons[+A,B]( a : A, sl : SafeList[A,B] ) extends SafeList[A,NonEmpty[B]] def safeHead[A,B]( sl: SafeList[A,NonEmpty[B]] ) : A = sl match { case SCons(h,_) => h // no warning for not matching SNil, even though it a sealed class... } def safeTail[A,B]( sl : SafeList[A,NonEmpty[B]] ) : SafeList[A,B] = sl match { case SCons(_,tl) => tl // no warning for not matching SNil, even though it a sealed class... } // Some trivial examples... val nonempty = SCons(10, SCons(20, SNil())) val empty : SafeList[Int,Empty] = SNil[Int]() // scala> safeHead(nonempty) // res1: Int = 10 // next one does not work, giving the expected type error // scala> safeHead(empty) // <console>:11: error: type mismatch; // found : SafeList.SafeList[Int,SafeList.Empty] // required: SafeList.SafeList[?,SafeList.NonEmpty] // safeHead(empty) // Of course, just like the Haskell implementation we can't implement // a function silly that is dependent on a boolean value to construct // either a SNill or SCons list and retain the type information. final case class NotSafe() final case class Safe() sealed trait MarkedList[+A,+B] final case class MNil[+A]() extends MarkedList[A,NotSafe] final case class MCons[+A,+B,+C]( a : A, sl : MarkedList[A,B] ) extends MarkedList[A,C] val mnonempty = MCons(10, MCons(20, MNil())) def safeHead[A]( sl: MarkedList[A,Safe] ) : A = sl match { case MCons(h,_) => h // no warning for not matching SNil, even though it a sealed class... } // Now we can write a function that produces something that can // never be consumed by safeHead!! def silly(b : Boolean) : MarkedList[Unit,NotSafe] = b match { case false => MNil() case true => MCons((),MNil()) } } // Classic dependent type sized lists (aka vectors) based on the ideas // in the excellent talk: // Scala vs. Idris: Dependent types now and in the future" at Strange Loop 2013 // http://www.infoq.com/presentations/scala-idris package object Vector { // Define some natural numbers sealed trait Nat trait Z extends Nat case object Z extends Z case class S[N <: Nat](n: N) extends Nat sealed trait Vector[+A, N <: Nat] case class ZV[+A]() extends Vector[A,Z] implicit class VPlus[A, N <: Nat](xs: Vector[A, N]) { def ++[M <: Nat](ys: Vector[A, M]) (implicit plus: Plus[A, Vector[A, N], Vector[A, M]]): plus.Out = plus(xs, ys) } trait Plus[A, XS, YS] { type Result <: Nat type Out = Vector[A, Result] def apply(xs: XS, ys: YS): Out } // Define plus (concat) for our vectors with our natural numbers object Plus { implicit def plusZ[A, N <: Nat] = new Plus[A, Vector[A,Z], Vector[A,N]] { type Result = N def apply(xs: Vector[A,Z], ys: Vector[A,N]) = ys } implicit def plusS[A, N <: Nat, M <: Nat] (implicit plus: Plus[A, Vector[A, N], Vector[A,M]]) = new Plus[A, Vector[A, S[N]], Vector[A,M]] { type Result = S[plus.Result] def apply(xs: Vector[A, S[N]], ys: Vector[A,M]): Out = SV(vhead(xs), (vtail(xs) ++ ys)) } } case class SV[+A, N <: Nat]( a: A, v: Vector[A,N] ) extends Vector[A, S[N]] def vhead[A,N <: Nat]( v : Vector[A,S[N]] ) : A = v match { case SV(a,_) => a } def vtail[A,N <: Nat]( v: Vector[A,S[N]] ) : Vector[A, N] = v match { case SV(_,v) => v } def vconcat[A, N <: Nat, M <: Nat](xs: Vector[A, N], ys: Vector[A, M]) (implicit plus: Plus[A, Vector[A, N], Vector[A, M]]): plus.Out = xs ++ ys } package object BasicRefinement { import scalaz._ import Leibniz._ // The following example is based a comment from the blog: // http://pchiusano.blogspot.co.uk/2010/06/gadts-in-scala.html An // example is given that does not work in Scala but does in Haskell. // // The solution to handle type refinement is based on the approach blogged here: // http://d.hatena.ne.jp/xuwei/20140706/1404612620 sealed trait Eq[A,B] { def cata[Z](x: (A === B) => Z): Z } sealed case class Refl[A]() extends Eq[A,A] { def cata[Z](x: (A === A) => Z) = x(Leibniz.refl) } def eval[A](a : A, eq : Eq[A,Int]) : Int = eq.cata(x => x.subst[λ[b => b]](a)) + 1 val ex = eval(1, Refl()) // scala> eval(1, Refl()) // res1: Int = 2 // next one does not work, giving the expected type error // scala> val exS = eval('a', Refl()) // <console>:10: error: type mismatch; // found : Refinement.Refl[Int] // required: Refinement.Eq[AnyVal,Int] // Note: Int <: AnyVal (and Refinement.Refl[Int] <: Refinement.Eq[Int,Int]), but trait Eq is invariant in type A. // You may wish to define A as +A instead. (SLS 4.5) } //---------------------------------------------------------------------------------- package object Foo { import scalaz._ import Leibniz._ // The following is a variant on BasicRefinement example, above. It // is a slight differece to the example approach blogged here: // http://d.hatena.ne.jp/xuwei/20140706/1404612620 sealed abstract class Foo[A, B] { def cata[Z](x: (A === B) => Z, y: (A, B) => Z): Z } final case class X[A]() extends Foo[A, A] { def cata[Z](x: (A === A) => Z, y: (A, A) => Z) = x(Leibniz.refl) } final case class Y[A, B](a: A, b: B) extends Foo[A, B] { def cata[Z](x: (A === B) => Z, y: (A, B) => Z) = y(a, b) } def hoge[F[_,_], A, B, C](foo: Foo[A, B], bar: F[A, C]): F[B, C] = foo.cata(x => x.subst[λ[a => F[a,C]]](bar), (_, _) => sys error "nonexhaustive") }
bgaster/scala-intro
GADT/src/main/scala/GADT.scala
Scala
mit
10,478
package poly.collection.impl.specialized import poly.collection.specgroup._ import poly.collection._ import poly.macroutil._ import scala.reflect._ /** * A specialized version for resizable arrays ([[poly.collection.impl.ResizableArray]]). * @author Tongfei Chen * @since 0.1.0 */ class SpResizableArray[@sp(Float, Double, Int, Long, Boolean) T: ClassTag] (private[this] var cap: Int = Settings.ArrayInitialSize) { self => private[this] var data: Array[T] = Array.ofDim[T](math.max(nextPowerOfTwo(cap), Settings.ArrayInitialSize)) def ensureCapacity(minCapacity: Int): Unit = { if (cap < minCapacity) { val newCapacity = nextPowerOfTwo(minCapacity) val newData = Array.ofDim[T](newCapacity) System.arraycopy(data, 0, newData, 0, cap) data = newData cap = newCapacity } } def apply(i: Int) = data(i) def capacity = cap def update(i: Int, x: T) = { if (i >= cap) ensureCapacity(i + 1) data(i) = x } def fillInplace(x: T) = FastLoop.ascending(0, capacity, 1) { i => data(i) = x } } // hand-specialized versions class IntResizableArray(private[this] var cap: Int = Settings.ArrayInitialSize) extends SpResizableArray[Int](cap) class LongResizableArray(private[this] var cap: Int = Settings.ArrayInitialSize) extends SpResizableArray[Long](cap) class FloatResizableArray(private[this] var cap: Int = Settings.ArrayInitialSize) extends SpResizableArray[Float](cap) class DoubleResizableArray(private[this] var cap: Int = Settings.ArrayInitialSize) extends SpResizableArray[Double](cap) class BooleanResizableArray(private[this] var cap: Int = Settings.ArrayInitialSize) extends SpResizableArray[Boolean](cap)
ctongfei/poly-collection
core/src/main/scala/poly/collection/impl/specialized/SpResizableArray.scala
Scala
mit
1,686
package dk.gp.cogp.svi import java.io.File import org.junit.Assert.assertEquals import org.junit.Test import breeze.linalg.csvread import dk.gp.cogp.lb.LowerBound import dk.gp.cogp.testutils.createCogpToyModel import dk.gp.cogp.lb.calcLBLoglik import dk.gp.cogp.testutils.loadToyModelData class stochasticUpdateHypCovGTest { @Test def test_5_data_points = { val data = loadToyModelData(n = 5) val model = createCogpToyModel(data) val (newHypParams, newHypParamsDelta) = stochasticUpdateHypCovG(j = 0, LowerBound(model, data)) val newG = model.g.head.copy(covFuncParams = newHypParams, covFuncParamsDelta = newHypParamsDelta) val newModel = model.copy(g = Array(newG)) val loglik = calcLBLoglik(LowerBound(newModel, data)) assertEquals(-209.55036, loglik, 0.00001) } @Test def test_40_data_points = { val data = loadToyModelData(n = 21) val model = createCogpToyModel(data) val (newHypParams, newHypParamsDelta) = stochasticUpdateHypCovG(j = 0, LowerBound(model, data)) val newG = model.g.head.copy(covFuncParams = newHypParams, covFuncParamsDelta = newHypParamsDelta) val newModel = model.copy(g = Array(newG)) val loglik = calcLBLoglik(LowerBound(newModel, data)) assertEquals(-6660.2501, loglik, 0.0001) } }
danielkorzekwa/bayes-scala-gp
src/test/scala/dk/gp/cogp/svi/stochasticUpdateHypCovGTest.scala
Scala
bsd-2-clause
1,288
class SandBox { def x: Unit = println("Print x") val y = () } trait Meta case class Foo(foo: String) extends Meta case class Bar(bar:String) extends Meta sealed trait Option[+A] { def getOrElse[B >: A](default: => B): B = this match { case Some(v) => v case _ => default } } case class Some[+A](get: A) extends Option[A] //val a: Some[Meta] = Some(Foo("Foo")) //sealed trait OptionB[+A] { // def getOrElse[A](default: => A): A = this match { // case SomeB(v) => v // case NoneB => default // } //} //case class SomeB[+A](get: A) extends OptionB[A] //case object NoneB extends OptionB[Nothing]
ringohub/scala-sandbox
fpis/src/main/scala/SandBox.scala
Scala
mit
625
/** Copyright 2015 TappingStone, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.predictionio.tools.dashboard import com.typesafe.config.ConfigFactory import org.apache.predictionio.authentication.KeyAuthentication import org.apache.predictionio.configuration.SSLConfiguration import org.apache.predictionio.data.storage.Storage import spray.can.server.ServerSettings import spray.routing.directives.AuthMagnet import scala.concurrent.{Future, ExecutionContext} import akka.actor.{ActorContext, Actor, ActorSystem, Props} import akka.io.IO import akka.pattern.ask import akka.util.Timeout import com.github.nscala_time.time.Imports.DateTime import grizzled.slf4j.Logging import spray.can.Http import spray.http._ import spray.http.MediaTypes._ import spray.routing._ import spray.routing.authentication.{Authentication, UserPass, BasicAuth} import scala.concurrent.duration._ case class DashboardConfig( ip: String = "localhost", port: Int = 9000) object Dashboard extends Logging with SSLConfiguration { def main(args: Array[String]): Unit = { val parser = new scopt.OptionParser[DashboardConfig]("Dashboard") { opt[String]("ip") action { (x, c) => c.copy(ip = x) } text("IP to bind to (default: localhost).") opt[Int]("port") action { (x, c) => c.copy(port = x) } text("Port to bind to (default: 9000).") } parser.parse(args, DashboardConfig()) map { dc => createDashboard(dc) } } def createDashboard(dc: DashboardConfig): Unit = { implicit val system = ActorSystem("pio-dashboard") val service = system.actorOf(Props(classOf[DashboardActor], dc), "dashboard") implicit val timeout = Timeout(5.seconds) val settings = ServerSettings(system) val serverConfig = ConfigFactory.load("server.conf") val sslEnforced = serverConfig.getBoolean("org.apache.predictionio.server.ssl-enforced") IO(Http) ? Http.Bind( service, interface = dc.ip, port = dc.port, settings = Some(settings.copy(sslEncryption = sslEnforced))) system.awaitTermination } } class DashboardActor( val dc: DashboardConfig) extends Actor with DashboardService { def actorRefFactory: ActorContext = context def receive: Actor.Receive = runRoute(dashboardRoute) } trait DashboardService extends HttpService with KeyAuthentication with CORSSupport { implicit def executionContext: ExecutionContext = actorRefFactory.dispatcher val dc: DashboardConfig val evaluationInstances = Storage.getMetaDataEvaluationInstances val pioEnvVars = sys.env.filter(kv => kv._1.startsWith("PIO_")) val serverStartTime = DateTime.now val dashboardRoute = path("") { authenticate(withAccessKeyFromFile) { request => get { respondWithMediaType(`text/html`) { complete { val completedInstances = evaluationInstances.getCompleted html.index( dc, serverStartTime, pioEnvVars, completedInstances).toString } } } } } ~ pathPrefix("engine_instances" / Segment) { instanceId => path("evaluator_results.txt") { get { respondWithMediaType(`text/plain`) { evaluationInstances.get(instanceId).map { i => complete(i.evaluatorResults) } getOrElse { complete(StatusCodes.NotFound) } } } } ~ path("evaluator_results.html") { get { respondWithMediaType(`text/html`) { evaluationInstances.get(instanceId).map { i => complete(i.evaluatorResultsHTML) } getOrElse { complete(StatusCodes.NotFound) } } } } ~ path("evaluator_results.json") { get { respondWithMediaType(`application/json`) { evaluationInstances.get(instanceId).map { i => complete(i.evaluatorResultsJSON) } getOrElse { complete(StatusCodes.NotFound) } } } } ~ cors { path("local_evaluator_results.json") { get { respondWithMediaType(`application/json`) { evaluationInstances.get(instanceId).map { i => complete(i.evaluatorResultsJSON) } getOrElse { complete(StatusCodes.NotFound) } } } } } } ~ pathPrefix("assets") { getFromResourceDirectory("assets") } }
alex9311/PredictionIO
tools/src/main/scala/org/apache/predictionio/tools/dashboard/Dashboard.scala
Scala
apache-2.0
5,134
/* * Copyright 2013 Google Inc. * Copyright 2014 Kangmo Kim * * 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.nhnsoft.bitcoin.net; import com.google.common.util.concurrent.Service; import java.net.SocketAddress; /** * <p>A generic interface for an object which keeps track of a set of open client connections, creates new ones and * ensures they are serviced properly.</p> * * <p>When the service is {@link com.google.common.util.concurrent.Service#stop()}ed, all connections will be closed and * the appropriate connectionClosed() calls must be made.</p> */ trait ClientConnectionManager extends Service { /** * Creates a new connection to the given address, with the given parser used to handle incoming data. */ def openConnection(serverAddress : SocketAddress, parser : StreamParser) : Unit /** Gets the number of connected peers */ def getConnectedClientCount() : Int /** Closes n peer connections */ def closeConnections(n : Int) : Unit }
Kangmo/bitcoinj
core/src/main/scala/com/nhnsoft/bitcoin/net/ClientConnectionManager.scala
Scala
apache-2.0
1,517
package physical.flow import locals._ import org.scalatestplus.mockito.MockitoSugar import org.scalatest.{FlatSpec, PrivateMethodTester} import ucar.nc2.dt.GridCoordSystem import ucar.nc2.dt.grid.GeoGrid class FlowGridWrapperTest extends FlatSpec with MockitoSugar with PrivateMethodTester { val depths = List(5.0, 10.0, 15.0, 20.0, 30.0, 40.0, 50.0, 60.0) private val mockDatasets = mock[List[List[(Array[Array[Array[Float]]], GridCoordSystem)]]] "The flow grid wrapper" should "intialise" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) assert(flowGridWrapper != null) } it should "get the correct quadrant position for bicubic integration in the top left" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(TopLeft, 4) assert(result == (-2, -2)) } it should "get the correct quadrant position for bicubic integration in the top right" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(TopRight, 4) assert(result == (-1, -2)) } it should "get the correct quadrant position for bicubic integration in the bottom right" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(BottomRight, 4) assert(result == (-1, -1)) } it should "get the correct quadrant position for bicubic integration in the bottom left" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(BottomLeft, 4) assert(result == (-2, -1)) } it should "get the correct quadrant position for bilinear integration in the top left" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(TopLeft, 2) assert(result == (-1, -1)) } it should "get the correct quadrant position for bilinear integration in the top right" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(TopRight, 2) assert(result == (0, -1)) } it should "get the correct quadrant position for bilinear integration in the bottom right" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(BottomRight, 2) assert(result == (0, 0)) } it should "get the correct quadrant position for bilinear integration in the bottom left" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(BottomLeft, 2) assert(result == (-1, 0)) } it should "get the correct quadrant position for tricubic integration in the top left" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(TopLeft, 8) assert(result == (-4, -4)) } it should "get the correct quadrant position for tricubic integration in the top right" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(TopRight, 8) assert(result == (-3, -4)) } it should "get the correct quadrant position for tricubic integration in the bottom right" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(BottomRight, 8) assert(result == (-3, -3)) } it should "get the correct quadrant position for tricubic integration in the bottom left" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val quadrantPosition = PrivateMethod[(Int, Int)]('quadrantPosition) val result = flowGridWrapper invokePrivate quadrantPosition(BottomLeft, 8) assert(result == (-4, -3)) } it should "get the correct neighbourhood size for tricubic integration" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val neighbourhoodSize = PrivateMethod[Int]('neighbourhoodSize) val result = flowGridWrapper invokePrivate neighbourhoodSize( Tricubic ) assert(result == 8) } it should "get the correct neighbourhood size for bicubic integration" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val neighbourhoodSize = PrivateMethod[Int]('neighbourhoodSize) val result = flowGridWrapper invokePrivate neighbourhoodSize( Bicubic ) assert(result == 4) } it should "get the correct neighbourhood size for bilinear integration" in { val flowGridWrapper = new FlowGridWrapper(depths, mockDatasets) val neighbourhoodSize = PrivateMethod[Int]('neighbourhoodSize) val result = flowGridWrapper invokePrivate neighbourhoodSize( Bilinear ) assert(result == 2) } }
shawes/zissou
src/test/scala/physical/flow/FlowGridWrapperTest.scala
Scala
mit
5,810
import org.specs._ import com.redis._ import org.specs.mock.Mockito import org.mockito.Mock._ import org.mockito.Mockito._ object OperationsSpec extends Specification with Mockito { "Redis Client Operations" should { var client: RedisTestClient = null var connection: Connection = null doBefore{ connection = mock[Connection] client = new RedisTestClient(connection) } "set a key" in { connection.readBoolean returns true client.set("a", "b") mustEqual true connection.write("SET a 1\\r\\nb\\r\\n") was called } "set a key with setKey" in { connection.readBoolean returns true client.setKey("a", "b") mustEqual true connection.write("SET a 1\\r\\nb\\r\\n") was called } "set a key with expiration" in { connection.readBoolean returns true client.set("a", "b", 4) mustEqual true connection.write("SET a 1\\r\\nb\\r\\n") was called connection.write("EXPIRE a 4\\r\\n") was called } "expire a key" in { connection.readBoolean returns true client.expire("a", 4) mustEqual true connection.write("EXPIRE a 4\\r\\n") was called } "get a key" in { connection.readResponse returns Some("b") client.get("a") mustEqual Some("b") connection.write("GET a\\r\\n") was called } "get and set a key" in { connection.readResponse returns Some("old") client.getSet("a", "new") mustEqual Some("old") connection.write("GETSET a 3\\r\\nnew\\r\\n") was called } "delete a key" in { connection.readBoolean returns true client.delete("a") mustEqual true connection.write("DEL a\\r\\n") was called } "tell if a key exists" in { connection.readBoolean returns true client.exists("a") mustEqual true connection.write("EXISTS a\\r\\n") was called } "tell if a key exists" in { connection.readBoolean returns true client.exists("a") mustEqual true connection.write("EXISTS a\\r\\n") was called } "increment a value" in { connection.readInt returns Some(1) client.incr("a") mustEqual Some(1) connection.write("INCR a\\r\\n") was called } "increment a value by N" in { connection.readInt returns Some(27) client.incr("a", 23) mustEqual Some(27) connection.write("INCRBY a 23\\r\\n") was called } "decrement a value" in { connection.readInt returns Some(0) client.decr("a") mustEqual Some(0) connection.write("DECR a\\r\\n") was called } "decrement a value by N" in { connection.readInt returns Some(25) client.decr("a", 2) mustEqual Some(25) connection.write("DECRBY a 2\\r\\n") was called } "return type of key" in { connection.readResponse returns Some("String") client.getType("a") mustEqual Some("String") connection.write("TYPE a\\r\\n") was called } "return the ttl of a key" in { connection.readInt returns Some(19) client.ttl("a") mustEqual Some(19) connection.write("TTL a\\r\\n") was called } } }
272029252/scala-redis
src/test/scala/com/redis/operations/OperationsSpec.scala
Scala
mit
3,153
package com.twitter.finagle.http.compat import com.twitter.finagle.http.netty.Bijections import com.twitter.finagle.http.{Fields, Request, Response, Method, Status, Version} import com.twitter.finagle.netty3.BufChannelBuffer import com.twitter.io.{Buf, BufReader, Reader} import com.twitter.util.Await import java.net.{InetAddress, InetSocketAddress, URI} import org.jboss.netty.handler.codec.http.{HttpVersion, HttpRequest, HttpResponse} import org.junit.runner.RunWith import org.scalacheck.{Arbitrary, Gen} import org.scalatest.FunSuite import org.scalatest.junit.JUnitRunner import org.scalatest.prop.GeneratorDrivenPropertyChecks @RunWith(classOf[JUnitRunner]) class AdaptorsTest extends FunSuite with GeneratorDrivenPropertyChecks { import Arbitrary.arbitrary import Bijections._ val arbMethod = Gen.oneOf( Method.Get, Method.Post, Method.Trace, Method.Delete, Method.Put, Method.Connect, Method.Options) val arbKeys = Gen.oneOf("Foo", "Bar", "Foo-Bar", "Bar-Baz") val arbUri = for { scheme <- Gen.oneOf("http", "https") hostLen <- Gen.choose(1,20) pathLen <- Gen.choose(1,20) tld <- Gen.oneOf(".net",".com", "org", ".edu") host = util.Random.alphanumeric.take(hostLen).mkString path = util.Random.alphanumeric.take(pathLen).mkString } yield (new URI(scheme, host + tld, "/" + path, null)).toASCIIString val arbHeader = for { key <- arbKeys len <- Gen.choose(0, 100) } yield (key, util.Random.alphanumeric.take(len).mkString) val arbResponse = for { code <- Gen.chooseNum(100, 510) version <- Gen.oneOf(Version.Http10, Version.Http11) chunked <- arbitrary[Boolean] headers <- Gen.containerOf[Seq, (String, String)](arbHeader) body <- arbitrary[String] } yield { if (chunked) { val res = Response(version, Status(code), Reader.fromBuf(Buf.Utf8(body))) headers foreach { case (k, v) => res.headerMap.add(k, v) } res.headerMap.set(Fields.TransferEncoding, "chunked") (res, body) } else { val res = Response(version, Status(code)) headers foreach { case (k, v) => res.headerMap.add(k, v) } res.contentString = body (res, body) } } val arbRequest = for { method <- arbMethod uri <- arbUri version <- Gen.oneOf(Version.Http10, Version.Http11) chunked <- arbitrary[Boolean] headers <- Gen.containerOf[Seq, (String, String)](arbHeader) body <- arbitrary[String] } yield { val reqIn = Request(version, method, uri) headers foreach { case (k, v) => reqIn.headers.add(k, v) } val req = Request( reqIn.httpRequest, BufReader(Buf.Utf8(body)), new InetSocketAddress(InetAddress.getLoopbackAddress, 0)) if (chunked) { req.headers.set(Fields.TransferEncoding, "chunked") req.setChunked(chunked) } else req.contentString = body (req, body) } val arbNettyVersion = Gen.oneOf( HttpVersion.HTTP_1_0, HttpVersion.HTTP_1_1, new HttpVersion("SECURE-HTTP/1.4", true) ) val arbNettyResponse = for { (resp, body) <- arbResponse version <- arbNettyVersion } yield { resp.httpResponse.setProtocolVersion(version) (resp.httpResponse, body) } val arbNettyRequest = for { (req, body) <- arbRequest version <- arbNettyVersion } yield { req.setProtocolVersion(version) (req.getHttpRequest, body) } test("netty: http request to netty") { forAll(arbRequest) { case (in: Request, body: String) => if (in.isChunked) { val exc = intercept[Exception] { Await.result(NettyAdaptor.in(in)) } assert(NettyAdaptor.NoStreaming == exc) } else { val out = Await.result(NettyAdaptor.in(in)) assert(out.getProtocolVersion == from(in.version)) assert(out.getMethod == from(in.method)) assert(out.getUri == in.getUri) assert(out.headers == in.headers) assert(out.isChunked == in.isChunked) assert(out.getContent == in.getContent) } } } test("netty: netty response to http") { forAll(arbNettyResponse) { case (in: HttpResponse, body: String) => if (in.isChunked) { val exc = intercept[Exception] { Await.result(NettyAdaptor.out(in)) } assert(NettyAdaptor.NoStreaming == exc) } else { val out = Await.result(NettyAdaptor.out(in)) assert(out.version == from(in.getProtocolVersion)) assert(out.status == from(in.getStatus)) assert(out.headers == in.headers) assert(out.isChunked == in.isChunked) assert(out.getContent == in.getContent) } } } test("http: netty request to http") { forAll(arbNettyRequest) { case (in: HttpRequest, body: String) => if (in.isChunked) { val exc = intercept[Exception] { Await.result(NettyClientAdaptor.in(in)) } assert(NettyClientAdaptor.NoStreaming == exc) } else { val out = Await.result(NettyClientAdaptor.in(in)) assert(out.version == from(in.getProtocolVersion)) assert(out.method == from(in.getMethod)) assert(out.getUri == in.getUri) assert(out.headers == in.headers) assert(out.isChunked == in.isChunked) assert(out.getContent == in.getContent) } } } test("http: http response to netty") { forAll(arbResponse) { case (in: Response, body: String) => if (in.isChunked) { val exc = intercept[Exception] { Await.result(NettyClientAdaptor.out(in)) } assert(NettyClientAdaptor.NoStreaming == exc) } else { val out = Await.result(NettyClientAdaptor.out(in)) assert(out.getProtocolVersion == from(in.version)) assert(out.getStatus == from(in.status)) assert(out.headers == in.headers) assert(out.isChunked == in.isChunked) assert(out.getContent == BufChannelBuffer(in.content)) } } } }
liamstewart/finagle
finagle-http-compat/src/test/scala/com/twitter/finagle/http/compat/AdaptorsTest.scala
Scala
apache-2.0
5,933
/* * Copyright (c) 2016 Bernard Leach * * 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.github.leachbj.newrelic.akka.http.client import akka.http.scaladsl.model.HttpResponse import com.github.leachbj.newrelic.akka.http.scaladsl.InboundHttpHeaders import com.newrelic.agent.bridge.external.ExternalParametersFactory import com.newrelic.agent.bridge.{AgentBridge, TracedActivity} import java.net.URI import java.util.logging.Level import scala.util.{Failure, Success, Try} class TracedActivityCompletion(uriString: String, tracedActivity: TracedActivity) extends ((Try[HttpResponse]) => Unit) { def apply(tryResponse: Try[HttpResponse]) = tryResponse match { case Success(response) => if (tracedActivity != null) { AgentBridge.getAgent.getLogger.log(Level.FINEST, "PoolGateway response {0} {1}", response, tracedActivity) tracedActivity.getTracedMethod.reportAsExternal(ExternalParametersFactory.createForHttp("AkkaHttpClient", new URI(uriString), "sendReceive", InboundHttpHeaders(response))) tracedActivity.finish() } case Failure(e) => AgentBridge.getAgent.getLogger.log(Level.FINEST, "PoolGateway failure {0}", tracedActivity) if (tracedActivity != null) { tracedActivity.getTracedMethod.reportAsExternal(ExternalParametersFactory.createForHttp("AkkaHttpClient", new URI(uriString), "sendReceiveOnFailure")) tracedActivity.finish(e) } } }
leachbj/akka-http-newrelic
src/main/scala/com/github/leachbj/newrelic/akka/http/client/TracedActivityCompletion.scala
Scala
mit
2,468
import scala.language.implicitConversions /** * * @author chaosky */ package object controllers { implicit def optionFoldLeft[A](o: Option[A]) = new { def foldLeft[B](f: A => B)(ifEmpty: => B): B = { o.fold(ifEmpty)(f) } def foldNull[B](f: A => B)(implicit ev: Null <:< B): B = if (o.isDefined) f(o.get) else null } }
chaosky/loom
app/controllers/package.scala
Scala
mit
347
import sbt.Keys._ import sbt._ object ProjectBuild extends Build { import Settings._ lazy val sbtRobot = Project( id = "sbt-robot", base = file("."), settings = defaultSettings ++ Seq(libraryDependencies ++= Dependencies.robotDeps) ) } object Dependencies { import Versions._ object Compile { val tasks = "net.codejitsu" % "tasks-dsl_2.11" % TasksVer } import Compile._ val robotDeps = Seq(tasks) }
codejitsu/sbt-robot
project/ProjectBuild.scala
Scala
apache-2.0
441
/* * 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.keras.layers import com.intel.analytics.bigdl.dllib.nn.{MulConstant => BMulConstant} import com.intel.analytics.bigdl.dllib.keras.layers.{MulConstant => ZMulConstant} import com.intel.analytics.bigdl.dllib.tensor.Tensor import com.intel.analytics.bigdl.dllib.utils.Shape import com.intel.analytics.bigdl.dllib.keras.ZooSpecHelper import com.intel.analytics.bigdl.dllib.keras.serializer.ModuleSerializationTest class MulConstantSpec extends ZooSpecHelper { "MulConstant 0 Zoo" should "be the same as BigDL" in { val blayer = BMulConstant[Float](0f) val zlayer = ZMulConstant[Float](0f, inputShape = Shape(4, 5)) zlayer.build(Shape(-1, 4, 5)) zlayer.getOutputShape().toSingle().toArray should be (Array(-1, 4, 5)) val input = Tensor[Float](Array(3, 4, 5)).rand() compareOutputAndGradInput(blayer, zlayer, input) } "MulConstant -1 Zoo" should "be the same as BigDL" in { val blayer = BMulConstant[Float](-1) val zlayer = ZMulConstant[Float](-1, inputShape = Shape(4, 8, 8)) zlayer.build(Shape(-1, 4, 8, 8)) zlayer.getOutputShape().toSingle().toArray should be (Array(-1, 4, 8, 8)) val input = Tensor[Float](Array(3, 4, 8, 8)).rand() compareOutputAndGradInput(blayer, zlayer, input) } } class MulConstantSerialTest extends ModuleSerializationTest { override def test(): Unit = { val layer = ZMulConstant[Float](-1, inputShape = Shape(4, 8, 8)) layer.build(Shape(2, 4, 8, 8)) val input = Tensor[Float](2, 4, 8, 8).rand() runSerializationTest(layer, input) } }
intel-analytics/BigDL
scala/dllib/src/test/scala/com/intel/analytics/bigdl/dllib/keras/layers/MulConstantSpec.scala
Scala
apache-2.0
2,181
/* * Copyright 2014 The SIRIS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * The SIRIS Project is a cooperation between Beuth University, Berlin and the * HCI Group at the University of Würzburg. The project is funded by the German * Federal Ministry of Education and Research (grant no. 17N4409). */ package simx.core.svaractor.unifiedaccess import simx.core.svaractor.SVarActor import simx.core.svaractor.TimedRingBuffer.{Now, Time} /** * Created by dwiebusch on 04.03.14 */ trait Mutability[B] extends Serializable{ protected[core] def set(value : B, at : Time, forceUpdate : Boolean)(implicit actorContext : SVarActor) : Boolean def set(value : B, at : Time = Now)(implicit actorContext : SVarActor) : Boolean = set(value, at, forceUpdate = false)(actorContext) def isMutable: Boolean = true }
simulator-x/core
src/simx/core/svaractor/unifiedaccess/Mutability.scala
Scala
apache-2.0
1,372
package vultura.util import org.specs2.mutable.Specification import TreeWidth._ import vultura.util.graph.Tree import scala.util.Random /** * Created by thomas on 14.12.15. */ class TreeWidth$Test extends Specification { def makeJunctionTrees(cliques: Iterable[Iterable[Int]]): Seq[Tree[Set[Int]]] = { val allValues = cliques.flatten.toSeq.distinct val cliquesAA: AA[Int] = cliques.map(_.toArray).toArray val order = treeDecomposition(cliquesAA,allValues.map(_ => 2).toArray) junctionTreesFromOrder(cliques.map(c => (c.toSet,())).toSeq,order.get).map(_.map(_._1)) } def treeWidth(trees: Seq[Tree[Set[Int]]]): Int = trees.flatMap(_.flatten.map(_.size)).max + 1 def randomTree(nodes: Int, cliqueSize: Int, seed: Long = 0): Seq[Seq[Int]] = { val r = new Random(seed) Iterator.iterate(Seq[Seq[Int]]()){ t => val maxNode = t.flatten.foldLeft(0)(_ max _) val connection = r.nextInt(maxNode + 1) val newClique = (1 to (cliqueSize-1)).map(_ + maxNode) t :+ (newClique :+ connection) }.drop(nodes).next() } def treeTW(nodes: Int, cliqueSize: Int): Int = treeWidth(makeJunctionTrees(randomTree(nodes,cliqueSize))) "make tree decomposition of a tree must not crash" >> { treeDecomposition(Array(Array(0,1),Array(1,2)),Array(2,2,2)) must beSome } "tree dec of random tree with 10 nodes, cliques size 2 has tw 3" >> {treeTW(10,2) === 3} "tree dec of random tree with 100 nodes, cliques size 2 has tw 3" >> {treeTW(100,2) === 3} "tree dec of random tree with 1000 nodes, cliques size 2 has tw 3" >> {treeTW(1000,2) === 3} "tree dec of random tree with 10 nodes, cliques size 3 has tw 4" >> {treeTW(10,3) === 4} "tree dec of random tree with 100 nodes, cliques size 3 has tw 4" >> {treeTW(100,3) === 4} "tree dec of random tree with 1000 nodes, cliques size 3 has tw 4" >> {treeTW(1000,3) === 4} }
ziggystar/vultura-factor
util/src/test/scala/vultura/util/TreeWidth$Test.scala
Scala
mit
1,881
// see neg/t0764 why this should probably be a pos/ test -- alas something's wrong with existential subtyping (?) // In all cases when calling "prepend" the receiver 'v' // has static type NodeAlias[A] or (equivalently) Node { type T = A }. // Since prepend explicitly returns the singleton type of the receiver, // the return type of prepend in all cases is "v.type", and so the call // to "new Main" can be parameterized with any of the following, in order // of decreasing specificity with a tie for second place: // // new Main[v.type](v.prepend) // new Main[NodeAlias[A]](v.prepend) // new Main[Node { type T = A }](v.prepend) // new Main(v.prepend) // the `fail` comments below denote what didn't compile before scala/bug#8177 fixed all of them package p1 { object t0764 { type NodeAlias[A] = Node { type T = A } trait Node { outer => type T <: Node def prepend: Node { type T = outer.type } = ??? } class Main1[A <: Node](v: NodeAlias[A]) { private[this] def f1 = new Main1(v.prepend) // fail private[this] def f2 = new Main1[NodeAlias[A]](v.prepend) // fail private[this] def f3 = new Main1[Node { type T = A }](v.prepend) // fail private[this] def f4 = new Main1[v.type](v.prepend) // ok } class Main2[A <: Node](v: Node { type T = A }) { private[this] def f1 = new Main2(v.prepend) // fail private[this] def f2 = new Main2[NodeAlias[A]](v.prepend) // fail private[this] def f3 = new Main2[Node { type T = A }](v.prepend) // fail private[this] def f4 = new Main2[v.type](v.prepend) // ok } } } package p2 { object t0764 { type NodeAlias[A] = Node { type T = A } trait Node { outer => type T <: Node def prepend: NodeAlias[outer.type] = ??? } class Main1[A <: Node](v: NodeAlias[A]) { private[this] def f1 = new Main1(v.prepend) // ok! <<========== WOT private[this] def f2 = new Main1[NodeAlias[A]](v.prepend) // fail private[this] def f3 = new Main1[Node { type T = A }](v.prepend) // fail private[this] def f4 = new Main1[v.type](v.prepend) // ok } class Main2[A <: Node](v: Node { type T = A }) { private[this] def f1 = new Main2(v.prepend) // fail private[this] def f2 = new Main2[NodeAlias[A]](v.prepend) // fail private[this] def f3 = new Main2[Node { type T = A }](v.prepend) // fail private[this] def f4 = new Main2[v.type](v.prepend) // ok } } }
scala/scala
test/files/neg/t0764b.scala
Scala
apache-2.0
2,661
package com.sksamuel.elastic4s.requests.searches.aggs.builders import com.sksamuel.elastic4s.EnumConversions import com.sksamuel.elastic4s.json.{XContentBuilder, XContentFactory} import com.sksamuel.elastic4s.requests.script.ScriptBuilderFn import com.sksamuel.elastic4s.requests.searches.aggs.{AggMetaDataFn, ExtendedBoundsBuilderFn, HistogramAggregation, SubAggsBuilderFn} object HistogramAggregationBuilder { def apply(agg: HistogramAggregation): XContentBuilder = { val builder = XContentFactory.jsonBuilder() builder.startObject("histogram") agg.interval.foreach(builder.field("interval", _)) agg.minDocCount.foreach(builder.field("min_doc_count", _)) agg.order.map(EnumConversions.order).foreach(builder.rawField("order", _)) agg.offset.foreach(builder.field("offset", _)) agg.format.foreach(builder.field("format", _)) agg.field.foreach(builder.field("field", _)) agg.keyed.foreach(builder.field("keyed", _)) agg.script.foreach { script => builder.rawField("script", ScriptBuilderFn(script)) } agg.missing.map(_.toString).foreach(builder.field("missing", _)) agg.extendedBounds.foreach { bounds => builder.rawField("extended_bounds", ExtendedBoundsBuilderFn(bounds)) } builder.endObject() SubAggsBuilderFn(agg, builder) AggMetaDataFn(agg, builder) builder.endObject() } }
stringbean/elastic4s
elastic4s-core/src/main/scala/com/sksamuel/elastic4s/requests/searches/aggs/builders/HistogramAggregationBuilder.scala
Scala
apache-2.0
1,372
package com.avsystem.commons package spring import java.lang.reflect.{Constructor, Executable, Method, Modifier} import scala.annotation.nowarn import org.springframework.core.{JdkVersion, ParameterNameDiscoverer} import scala.annotation.tailrec import scala.ref.WeakReference import scala.reflect.api.JavaUniverse import scala.reflect.{ScalaLongSignature, ScalaSignature} object ScalaParameterNameDiscoverer { final val ScalaSignatureClasses = List(classOf[ScalaSignature], classOf[ScalaLongSignature]) @nowarn("msg=deprecated") final val JdkAtLeast8 = JdkVersion.getMajorJavaVersion >= JdkVersion.JAVA_18 // we don't want to keep the universe in memory forever, so we don't use scala.reflect.runtime.universe private var universeRef: WeakReference[JavaUniverse] = _ private def universe: JavaUniverse = { universeRef.option.flatMap(_.get) match { case Some(result) => result case None => val result = new scala.reflect.runtime.JavaUniverse universeRef = new WeakReference[JavaUniverse](result) result } } } @deprecated("this class is useless on JDK >= 1.8, use StandardReflectionParameterNameDiscoverer", "1.46.3") class ScalaParameterNameDiscoverer extends ParameterNameDiscoverer { import ScalaParameterNameDiscoverer._ @tailrec private def isScala(cls: Class[_]): Boolean = cls.getEnclosingClass match { case null => ScalaSignatureClasses.exists(ac => cls.getAnnotation(ac) != null) case encls => isScala(encls) } private def discoverNames(u: JavaUniverse)(executable: Executable, symbolPredicate: u.Symbol => Boolean): Array[String] = { import u._ val declaringClass = executable.getDeclaringClass val mirror = runtimeMirror(declaringClass.getClassLoader) val ownerSymbol = if (Modifier.isStatic(executable.getModifiers)) mirror.moduleSymbol(declaringClass).moduleClass.asType else mirror.classSymbol(declaringClass) def argErasuresMatch(ms: MethodSymbol) = ms.paramLists.flatten.map(s => mirror.runtimeClass(s.typeSignature)) == executable.getParameterTypes.toList def paramNames(ms: MethodSymbol) = ms.paramLists.flatten.map(_.name.toString).toArray ownerSymbol.toType.members .find(s => symbolPredicate(s) && argErasuresMatch(s.asMethod)) .map(s => paramNames(s.asMethod)) .orNull } def getParameterNames(ctor: Constructor[_]): Array[String] = if (JdkAtLeast8 && ctor.getParameters.forall(_.isNamePresent)) ctor.getParameters.map(_.getName) else if (isScala(ctor.getDeclaringClass)) discoverNames(universe)(ctor, s => s.isConstructor) else null def getParameterNames(method: Method): Array[String] = { val declaringCls = method.getDeclaringClass if (JdkAtLeast8 && method.getParameters.forall(_.isNamePresent)) method.getParameters.map(_.getName) else if (isScala(declaringCls)) { // https://github.com/scala/bug/issues/10650 val forStaticForwarder = if (Modifier.isStatic(method.getModifiers)) Class.forName(declaringCls.getName + "$", false, declaringCls.getClassLoader) .recoverToOpt[ClassNotFoundException] .flatMap(_.getMethod(method.getName, method.getParameterTypes: _*).recoverToOpt[NoSuchMethodException]) .map(getParameterNames) else Opt.Empty forStaticForwarder.getOrElse( discoverNames(universe)(method, s => s.isMethod && s.name.toString == method.getName)) } else null } }
AVSystem/scala-commons
commons-spring/src/main/scala/com/avsystem/commons/spring/ScalaParameterNameDiscoverer.scala
Scala
mit
3,521
package io.rout.example.benchmark import io.rout._ import io.routs._ import io.rout.generic.decoding._ object Params extends App { val derivedPayload: ReqRead[Payload] = derive[Payload].fromParams val regularPayload = post(Root).sync(derivedPayload) { payload => Created(payload.toString) } val rOut = mkRoutes(Seq( regularPayload )) serve(rOut.service) }
teodimoff/rOut
examples/src/io/rout/benchmark/Params.scala
Scala
apache-2.0
382
/* * 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.streaming.aliyun.logservice import scala.collection.mutable import com.aliyun.openservices.log.common.Consts import com.aliyun.openservices.loghub.client.config.LogHubCursorPosition import org.apache.spark.{SparkConf, SparkFunSuite} import org.apache.spark.sql.aliyun.logservice.LoghubTestUtils import org.apache.spark.streaming.{Milliseconds, StreamingContext} class DirectLoghubInputDStreamSuite extends SparkFunSuite { private val testUtils = new LoghubTestUtils private var sc: StreamingContext = _ private val zkParas = Map("zookeeper.connect" -> "localhost:2181") private val conf = new SparkConf().setAppName("Test Direct SLS Loghub") .setMaster("local") private var logstore: String = _ test("test checkpoint empty will be filtered") { val stream = new DirectLoghubInputDStream( sc, testUtils.logProject, logstore, "consumergroup", testUtils.accessKeyId, testUtils.accessKeySecret, testUtils.endpoint, zkParas, LogHubCursorPosition.BEGIN_CURSOR ) val client = new LoghubClientAgent(testUtils.endpoint, testUtils.accessKeyId, testUtils.accessKeySecret) stream.setClient(client) val ckpt = new mutable.HashMap[Int, String]() ckpt.put(0, "not-empty-cursor") ckpt.put(1, "") val ckpt1 = stream.findCheckpointOrCursorForShard(0, ckpt) assert(ckpt1 == "not-empty-cursor") val ckpt2 = stream.findCheckpointOrCursorForShard(1, ckpt) val beginCursor = client.GetCursor(testUtils.logProject, logstore, 1, Consts.CursorMode.BEGIN).GetCursor() assert(ckpt2 == beginCursor) } test("test create consumer group") { val cg = "consumerGroup-1" val stream = new DirectLoghubInputDStream( sc, testUtils.logProject, logstore, cg, testUtils.accessKeyId, testUtils.accessKeySecret, testUtils.endpoint, zkParas, LogHubCursorPosition.BEGIN_CURSOR ) val client = new LoghubClientAgent(testUtils.endpoint, testUtils.accessKeyId, testUtils.accessKeySecret) stream.setClient(client) stream.tryToCreateConsumerGroup() assert(stream.getSavedCheckpoints.isEmpty) Thread.sleep(60000) testUtils.client.UpdateCheckPoint(testUtils.logProject, logstore, cg, 0, "MTU3NTUzMDgyMDAzOTA5Mjk0MQ==") testUtils.client.UpdateCheckPoint(testUtils.logProject, logstore, cg, 1, "MTU3NTUzMDgyMDA0MDk4NDQzOQ==") stream.tryToCreateConsumerGroup() val ckpts = stream.getSavedCheckpoints assert(ckpts.size == 2) assert(ckpts.getOrElse(0, "").equals("MTU3NTUzMDgyMDAzOTA5Mjk0MQ==")) assert(ckpts.getOrElse(1, "").equals("MTU3NTUzMDgyMDA0MDk4NDQzOQ==")) } protected override def beforeAll(): Unit = { logstore = testUtils.newLogStore() testUtils.createLogStore(logstore) Thread.sleep(60000) val batchInterval = Milliseconds(5 * 1000) sc = new StreamingContext(conf, batchInterval) } protected override def afterAll(): Unit = { testUtils.deleteLogStore(logstore) } }
aliyun/aliyun-emapreduce-sdk
emr-logservice/src/test/scala/org/apache/spark/streaming/aliyun/logservice/DirectLoghubInputDStreamSuite.scala
Scala
artistic-2.0
3,903
package com.sksamuel.elastic4s.fields.builders import com.sksamuel.elastic4s.fields.AliasField import com.sksamuel.elastic4s.json.{XContentBuilder, XContentFactory} object AliasFieldBuilderFn { def build(field: AliasField): XContentBuilder = { val builder = XContentFactory.jsonBuilder() builder.field("type", field.`type`) field.path.foreach(builder.field("path", _)) builder.endObject() } }
stringbean/elastic4s
elastic4s-core/src/main/scala/com/sksamuel/elastic4s/fields/builders/AliasFieldBuilderFn.scala
Scala
apache-2.0
415
package coursier.cli.complete import caseapp.{ExtraName => Short, HelpMessage => Help, _} import coursier.cli.options.{CacheOptions, OutputOptions, RepositoryOptions} // format: off final case class CompleteOptions( @Recurse cacheOptions: CacheOptions = CacheOptions(), @Recurse repositoryOptions: RepositoryOptions = RepositoryOptions(), @Recurse outputOptions: OutputOptions = OutputOptions(), @Help("Default scala version") @Short("e") scalaVersion: Option[String] = None ) { // format: on lazy val scalaBinaryVersion: Option[String] = scalaVersion .filter(_.nonEmpty) .map(coursier.complete.Complete.scalaBinaryVersion) } object CompleteOptions { implicit val parser = Parser[CompleteOptions] implicit val help = caseapp.core.help.Help[CompleteOptions] }
alexarchambault/coursier
modules/cli/src/main/scala/coursier/cli/complete/CompleteOptions.scala
Scala
apache-2.0
820
/* * Scala.js (https://www.scala-js.org/) * * Copyright EPFL. * * Licensed under Apache License 2.0 * (https://www.apache.org/licenses/LICENSE-2.0). * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package org.scalajs.jsenv.nodejs import org.scalajs.jsenv.test._ import org.junit.runner.RunWith @RunWith(classOf[JSEnvSuiteRunner]) class NodeJSSuite extends JSEnvSuite( JSEnvSuiteConfig(new NodeJSEnv) .withExitJSStatement("process.exit(0);") )
nicolasstucki/scala-js
nodejs-env/src/test/scala/org/scalajs/jsenv/nodejs/NodeJSSuite.scala
Scala
apache-2.0
529
trait IF1 extends (Int ?=> Unit) // error abstract class IF2 extends ((Int, String) ?=> Unit) // error class IF3 extends (ContextFunction3[Int, String, Boolean, Unit]) { // error def apply(using Int, String, Boolean) = () } trait IFXXL extends (( // error Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int) ?=> Unit) val IFOK: ( // OK Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int) ?=> Unit = ()
lampepfl/dotty
tests/neg/implicit-funs.scala
Scala
apache-2.0
492
/* * 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.api.python import java.io._ import java.net._ import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets.UTF_8 import java.util.concurrent.atomic.AtomicBoolean import scala.collection.JavaConverters._ import scala.util.control.NonFatal import org.apache.spark._ import org.apache.spark.internal.Logging import org.apache.spark.internal.config.{BUFFER_SIZE, EXECUTOR_CORES} import org.apache.spark.internal.config.Python._ import org.apache.spark.security.SocketAuthHelper import org.apache.spark.util._ /** * Enumerate the type of command that will be sent to the Python worker */ private[spark] object PythonEvalType { val NON_UDF = 0 val SQL_BATCHED_UDF = 100 val SQL_SCALAR_PANDAS_UDF = 200 val SQL_GROUPED_MAP_PANDAS_UDF = 201 val SQL_GROUPED_AGG_PANDAS_UDF = 202 val SQL_WINDOW_AGG_PANDAS_UDF = 203 val SQL_SCALAR_PANDAS_ITER_UDF = 204 val SQL_MAP_PANDAS_ITER_UDF = 205 val SQL_COGROUPED_MAP_PANDAS_UDF = 206 def toString(pythonEvalType: Int): String = pythonEvalType match { case NON_UDF => "NON_UDF" case SQL_BATCHED_UDF => "SQL_BATCHED_UDF" case SQL_SCALAR_PANDAS_UDF => "SQL_SCALAR_PANDAS_UDF" case SQL_GROUPED_MAP_PANDAS_UDF => "SQL_GROUPED_MAP_PANDAS_UDF" case SQL_GROUPED_AGG_PANDAS_UDF => "SQL_GROUPED_AGG_PANDAS_UDF" case SQL_WINDOW_AGG_PANDAS_UDF => "SQL_WINDOW_AGG_PANDAS_UDF" case SQL_SCALAR_PANDAS_ITER_UDF => "SQL_SCALAR_PANDAS_ITER_UDF" case SQL_MAP_PANDAS_ITER_UDF => "SQL_MAP_PANDAS_ITER_UDF" case SQL_COGROUPED_MAP_PANDAS_UDF => "SQL_COGROUPED_MAP_PANDAS_UDF" } } /** * A helper class to run Python mapPartition/UDFs in Spark. * * funcs is a list of independent Python functions, each one of them is a list of chained Python * functions (from bottom to top). */ private[spark] abstract class BasePythonRunner[IN, OUT]( funcs: Seq[ChainedPythonFunctions], evalType: Int, argOffsets: Array[Array[Int]]) extends Logging { require(funcs.length == argOffsets.length, "argOffsets should have the same length as funcs") private val conf = SparkEnv.get.conf protected val bufferSize: Int = conf.get(BUFFER_SIZE) private val reuseWorker = conf.get(PYTHON_WORKER_REUSE) // each python worker gets an equal part of the allocation. the worker pool will grow to the // number of concurrent tasks, which is determined by the number of cores in this executor. private val memoryMb = conf.get(PYSPARK_EXECUTOR_MEMORY).map(_ / conf.get(EXECUTOR_CORES)) // All the Python functions should have the same exec, version and envvars. protected val envVars: java.util.Map[String, String] = funcs.head.funcs.head.envVars protected val pythonExec: String = funcs.head.funcs.head.pythonExec protected val pythonVer: String = funcs.head.funcs.head.pythonVer // TODO: support accumulator in multiple UDF protected val accumulator: PythonAccumulatorV2 = funcs.head.funcs.head.accumulator // Python accumulator is always set in production except in tests. See SPARK-27893 private val maybeAccumulator: Option[PythonAccumulatorV2] = Option(accumulator) // Expose a ServerSocket to support method calls via socket from Python side. private[spark] var serverSocket: Option[ServerSocket] = None // Authentication helper used when serving method calls via socket from Python side. private lazy val authHelper = new SocketAuthHelper(conf) def compute( inputIterator: Iterator[IN], partitionIndex: Int, context: TaskContext): Iterator[OUT] = { val startTime = System.currentTimeMillis val env = SparkEnv.get val localdir = env.blockManager.diskBlockManager.localDirs.map(f => f.getPath()).mkString(",") // if OMP_NUM_THREADS is not explicitly set, override it with the number of cores if (conf.getOption("spark.executorEnv.OMP_NUM_THREADS").isEmpty) { // SPARK-28843: limit the OpenMP thread pool to the number of cores assigned to this executor // this avoids high memory consumption with pandas/numpy because of a large OpenMP thread pool // see https://github.com/numpy/numpy/issues/10455 conf.getOption("spark.executor.cores").foreach(envVars.put("OMP_NUM_THREADS", _)) } envVars.put("SPARK_LOCAL_DIRS", localdir) // it's also used in monitor thread if (reuseWorker) { envVars.put("SPARK_REUSE_WORKER", "1") } if (memoryMb.isDefined) { envVars.put("PYSPARK_EXECUTOR_MEMORY_MB", memoryMb.get.toString) } envVars.put("SPARK_BUFFER_SIZE", bufferSize.toString) val worker: Socket = env.createPythonWorker(pythonExec, envVars.asScala.toMap) // Whether is the worker released into idle pool or closed. When any codes try to release or // close a worker, they should use `releasedOrClosed.compareAndSet` to flip the state to make // sure there is only one winner that is going to release or close the worker. val releasedOrClosed = new AtomicBoolean(false) // Start a thread to feed the process input from our parent's iterator val writerThread = newWriterThread(env, worker, inputIterator, partitionIndex, context) context.addTaskCompletionListener[Unit] { _ => writerThread.shutdownOnTaskCompletion() if (!reuseWorker || releasedOrClosed.compareAndSet(false, true)) { try { worker.close() } catch { case e: Exception => logWarning("Failed to close worker socket", e) } } } writerThread.start() new MonitorThread(env, worker, context).start() // Return an iterator that read lines from the process's stdout val stream = new DataInputStream(new BufferedInputStream(worker.getInputStream, bufferSize)) val stdoutIterator = newReaderIterator( stream, writerThread, startTime, env, worker, releasedOrClosed, context) new InterruptibleIterator(context, stdoutIterator) } protected def newWriterThread( env: SparkEnv, worker: Socket, inputIterator: Iterator[IN], partitionIndex: Int, context: TaskContext): WriterThread protected def newReaderIterator( stream: DataInputStream, writerThread: WriterThread, startTime: Long, env: SparkEnv, worker: Socket, releasedOrClosed: AtomicBoolean, context: TaskContext): Iterator[OUT] /** * The thread responsible for writing the data from the PythonRDD's parent iterator to the * Python process. */ abstract class WriterThread( env: SparkEnv, worker: Socket, inputIterator: Iterator[IN], partitionIndex: Int, context: TaskContext) extends Thread(s"stdout writer for $pythonExec") { @volatile private var _exception: Throwable = null private val pythonIncludes = funcs.flatMap(_.funcs.flatMap(_.pythonIncludes.asScala)).toSet private val broadcastVars = funcs.flatMap(_.funcs.flatMap(_.broadcastVars.asScala)) setDaemon(true) /** Contains the throwable thrown while writing the parent iterator to the Python process. */ def exception: Option[Throwable] = Option(_exception) /** Terminates the writer thread, ignoring any exceptions that may occur due to cleanup. */ def shutdownOnTaskCompletion() { assert(context.isCompleted) this.interrupt() } /** * Writes a command section to the stream connected to the Python worker. */ protected def writeCommand(dataOut: DataOutputStream): Unit /** * Writes input data to the stream connected to the Python worker. */ protected def writeIteratorToStream(dataOut: DataOutputStream): Unit override def run(): Unit = Utils.logUncaughtExceptions { try { TaskContext.setTaskContext(context) val stream = new BufferedOutputStream(worker.getOutputStream, bufferSize) val dataOut = new DataOutputStream(stream) // Partition index dataOut.writeInt(partitionIndex) // Python version of driver PythonRDD.writeUTF(pythonVer, dataOut) // Init a ServerSocket to accept method calls from Python side. val isBarrier = context.isInstanceOf[BarrierTaskContext] if (isBarrier) { serverSocket = Some(new ServerSocket(/* port */ 0, /* backlog */ 1, InetAddress.getByName("localhost"))) // A call to accept() for ServerSocket shall block infinitely. serverSocket.map(_.setSoTimeout(0)) new Thread("accept-connections") { setDaemon(true) override def run(): Unit = { while (!serverSocket.get.isClosed()) { var sock: Socket = null try { sock = serverSocket.get.accept() // Wait for function call from python side. sock.setSoTimeout(10000) authHelper.authClient(sock) val input = new DataInputStream(sock.getInputStream()) input.readInt() match { case BarrierTaskContextMessageProtocol.BARRIER_FUNCTION => // The barrier() function may wait infinitely, socket shall not timeout // before the function finishes. sock.setSoTimeout(0) barrierAndServe(sock) case _ => val out = new DataOutputStream(new BufferedOutputStream( sock.getOutputStream)) writeUTF(BarrierTaskContextMessageProtocol.ERROR_UNRECOGNIZED_FUNCTION, out) } } catch { case e: SocketException if e.getMessage.contains("Socket closed") => // It is possible that the ServerSocket is not closed, but the native socket // has already been closed, we shall catch and silently ignore this case. } finally { if (sock != null) { sock.close() } } } } }.start() } val secret = if (isBarrier) { authHelper.secret } else { "" } // Close ServerSocket on task completion. serverSocket.foreach { server => context.addTaskCompletionListener[Unit](_ => server.close()) } val boundPort: Int = serverSocket.map(_.getLocalPort).getOrElse(0) if (boundPort == -1) { val message = "ServerSocket failed to bind to Java side." logError(message) throw new SparkException(message) } else if (isBarrier) { logDebug(s"Started ServerSocket on port $boundPort.") } // Write out the TaskContextInfo dataOut.writeBoolean(isBarrier) dataOut.writeInt(boundPort) val secretBytes = secret.getBytes(UTF_8) dataOut.writeInt(secretBytes.length) dataOut.write(secretBytes, 0, secretBytes.length) dataOut.writeInt(context.stageId()) dataOut.writeInt(context.partitionId()) dataOut.writeInt(context.attemptNumber()) dataOut.writeLong(context.taskAttemptId()) val resources = context.resources() dataOut.writeInt(resources.size) resources.foreach { case (k, v) => PythonRDD.writeUTF(k, dataOut) PythonRDD.writeUTF(v.name, dataOut) dataOut.writeInt(v.addresses.size) v.addresses.foreach { case addr => PythonRDD.writeUTF(addr, dataOut) } } val localProps = context.getLocalProperties.asScala dataOut.writeInt(localProps.size) localProps.foreach { case (k, v) => PythonRDD.writeUTF(k, dataOut) PythonRDD.writeUTF(v, dataOut) } // sparkFilesDir PythonRDD.writeUTF(SparkFiles.getRootDirectory(), dataOut) // Python includes (*.zip and *.egg files) dataOut.writeInt(pythonIncludes.size) for (include <- pythonIncludes) { PythonRDD.writeUTF(include, dataOut) } // Broadcast variables val oldBids = PythonRDD.getWorkerBroadcasts(worker) val newBids = broadcastVars.map(_.id).toSet // number of different broadcasts val toRemove = oldBids.diff(newBids) val addedBids = newBids.diff(oldBids) val cnt = toRemove.size + addedBids.size val needsDecryptionServer = env.serializerManager.encryptionEnabled && addedBids.nonEmpty dataOut.writeBoolean(needsDecryptionServer) dataOut.writeInt(cnt) def sendBidsToRemove(): Unit = { for (bid <- toRemove) { // remove the broadcast from worker dataOut.writeLong(-bid - 1) // bid >= 0 oldBids.remove(bid) } } if (needsDecryptionServer) { // if there is encryption, we setup a server which reads the encrypted files, and sends // the decrypted data to python val idsAndFiles = broadcastVars.flatMap { broadcast => if (!oldBids.contains(broadcast.id)) { Some((broadcast.id, broadcast.value.path)) } else { None } } val server = new EncryptedPythonBroadcastServer(env, idsAndFiles) dataOut.writeInt(server.port) logTrace(s"broadcast decryption server setup on ${server.port}") PythonRDD.writeUTF(server.secret, dataOut) sendBidsToRemove() idsAndFiles.foreach { case (id, _) => // send new broadcast dataOut.writeLong(id) oldBids.add(id) } dataOut.flush() logTrace("waiting for python to read decrypted broadcast data from server") server.waitTillBroadcastDataSent() logTrace("done sending decrypted data to python") } else { sendBidsToRemove() for (broadcast <- broadcastVars) { if (!oldBids.contains(broadcast.id)) { // send new broadcast dataOut.writeLong(broadcast.id) PythonRDD.writeUTF(broadcast.value.path, dataOut) oldBids.add(broadcast.id) } } } dataOut.flush() dataOut.writeInt(evalType) writeCommand(dataOut) writeIteratorToStream(dataOut) dataOut.writeInt(SpecialLengths.END_OF_STREAM) dataOut.flush() } catch { case t: Throwable if (NonFatal(t) || t.isInstanceOf[Exception]) => if (context.isCompleted || context.isInterrupted) { logDebug("Exception/NonFatal Error thrown after task completion (likely due to " + "cleanup)", t) if (!worker.isClosed) { Utils.tryLog(worker.shutdownOutput()) } } else { // We must avoid throwing exceptions/NonFatals here, because the thread uncaught // exception handler will kill the whole executor (see // org.apache.spark.executor.Executor). _exception = t if (!worker.isClosed) { Utils.tryLog(worker.shutdownOutput()) } } } } /** * Gateway to call BarrierTaskContext.barrier(). */ def barrierAndServe(sock: Socket): Unit = { require(serverSocket.isDefined, "No available ServerSocket to redirect the barrier() call.") val out = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream)) try { context.asInstanceOf[BarrierTaskContext].barrier() writeUTF(BarrierTaskContextMessageProtocol.BARRIER_RESULT_SUCCESS, out) } catch { case e: SparkException => writeUTF(e.getMessage, out) } finally { out.close() } } def writeUTF(str: String, dataOut: DataOutputStream) { val bytes = str.getBytes(UTF_8) dataOut.writeInt(bytes.length) dataOut.write(bytes) } } abstract class ReaderIterator( stream: DataInputStream, writerThread: WriterThread, startTime: Long, env: SparkEnv, worker: Socket, releasedOrClosed: AtomicBoolean, context: TaskContext) extends Iterator[OUT] { private var nextObj: OUT = _ private var eos = false override def hasNext: Boolean = nextObj != null || { if (!eos) { nextObj = read() hasNext } else { false } } override def next(): OUT = { if (hasNext) { val obj = nextObj nextObj = null.asInstanceOf[OUT] obj } else { Iterator.empty.next() } } /** * Reads next object from the stream. * When the stream reaches end of data, needs to process the following sections, * and then returns null. */ protected def read(): OUT protected def handleTimingData(): Unit = { // Timing data from worker val bootTime = stream.readLong() val initTime = stream.readLong() val finishTime = stream.readLong() val boot = bootTime - startTime val init = initTime - bootTime val finish = finishTime - initTime val total = finishTime - startTime logInfo("Times: total = %s, boot = %s, init = %s, finish = %s".format(total, boot, init, finish)) val memoryBytesSpilled = stream.readLong() val diskBytesSpilled = stream.readLong() context.taskMetrics.incMemoryBytesSpilled(memoryBytesSpilled) context.taskMetrics.incDiskBytesSpilled(diskBytesSpilled) } protected def handlePythonException(): PythonException = { // Signals that an exception has been thrown in python val exLength = stream.readInt() val obj = new Array[Byte](exLength) stream.readFully(obj) new PythonException(new String(obj, StandardCharsets.UTF_8), writerThread.exception.getOrElse(null)) } protected def handleEndOfDataSection(): Unit = { // We've finished the data section of the output, but we can still // read some accumulator updates: val numAccumulatorUpdates = stream.readInt() (1 to numAccumulatorUpdates).foreach { _ => val updateLen = stream.readInt() val update = new Array[Byte](updateLen) stream.readFully(update) maybeAccumulator.foreach(_.add(update)) } // Check whether the worker is ready to be re-used. if (stream.readInt() == SpecialLengths.END_OF_STREAM) { if (reuseWorker && releasedOrClosed.compareAndSet(false, true)) { env.releasePythonWorker(pythonExec, envVars.asScala.toMap, worker) } } eos = true } protected val handleException: PartialFunction[Throwable, OUT] = { case e: Exception if context.isInterrupted => logDebug("Exception thrown after task interruption", e) throw new TaskKilledException(context.getKillReason().getOrElse("unknown reason")) case e: Exception if writerThread.exception.isDefined => logError("Python worker exited unexpectedly (crashed)", e) logError("This may have been caused by a prior exception:", writerThread.exception.get) throw writerThread.exception.get case eof: EOFException => throw new SparkException("Python worker exited unexpectedly (crashed)", eof) } } /** * It is necessary to have a monitor thread for python workers if the user cancels with * interrupts disabled. In that case we will need to explicitly kill the worker, otherwise the * threads can block indefinitely. */ class MonitorThread(env: SparkEnv, worker: Socket, context: TaskContext) extends Thread(s"Worker Monitor for $pythonExec") { /** How long to wait before killing the python worker if a task cannot be interrupted. */ private val taskKillTimeout = env.conf.get(PYTHON_TASK_KILL_TIMEOUT) setDaemon(true) override def run() { // Kill the worker if it is interrupted, checking until task completion. // TODO: This has a race condition if interruption occurs, as completed may still become true. while (!context.isInterrupted && !context.isCompleted) { Thread.sleep(2000) } if (!context.isCompleted) { Thread.sleep(taskKillTimeout) if (!context.isCompleted) { try { // Mimic the task name used in `Executor` to help the user find out the task to blame. val taskName = s"${context.partitionId}.${context.attemptNumber} " + s"in stage ${context.stageId} (TID ${context.taskAttemptId})" logWarning(s"Incomplete task $taskName interrupted: Attempting to kill Python Worker") env.destroyPythonWorker(pythonExec, envVars.asScala.toMap, worker) } catch { case e: Exception => logError("Exception when trying to kill worker", e) } } } } } } private[spark] object PythonRunner { def apply(func: PythonFunction): PythonRunner = { new PythonRunner(Seq(ChainedPythonFunctions(Seq(func)))) } } /** * A helper class to run Python mapPartition in Spark. */ private[spark] class PythonRunner(funcs: Seq[ChainedPythonFunctions]) extends BasePythonRunner[Array[Byte], Array[Byte]]( funcs, PythonEvalType.NON_UDF, Array(Array(0))) { protected override def newWriterThread( env: SparkEnv, worker: Socket, inputIterator: Iterator[Array[Byte]], partitionIndex: Int, context: TaskContext): WriterThread = { new WriterThread(env, worker, inputIterator, partitionIndex, context) { protected override def writeCommand(dataOut: DataOutputStream): Unit = { val command = funcs.head.funcs.head.command dataOut.writeInt(command.length) dataOut.write(command) } protected override def writeIteratorToStream(dataOut: DataOutputStream): Unit = { PythonRDD.writeIteratorToStream(inputIterator, dataOut) dataOut.writeInt(SpecialLengths.END_OF_DATA_SECTION) } } } protected override def newReaderIterator( stream: DataInputStream, writerThread: WriterThread, startTime: Long, env: SparkEnv, worker: Socket, releasedOrClosed: AtomicBoolean, context: TaskContext): Iterator[Array[Byte]] = { new ReaderIterator(stream, writerThread, startTime, env, worker, releasedOrClosed, context) { protected override def read(): Array[Byte] = { if (writerThread.exception.isDefined) { throw writerThread.exception.get } try { stream.readInt() match { case length if length > 0 => val obj = new Array[Byte](length) stream.readFully(obj) obj case 0 => Array.empty[Byte] case SpecialLengths.TIMING_DATA => handleTimingData() read() case SpecialLengths.PYTHON_EXCEPTION_THROWN => throw handlePythonException() case SpecialLengths.END_OF_DATA_SECTION => handleEndOfDataSection() null } } catch handleException } } } } private[spark] object SpecialLengths { val END_OF_DATA_SECTION = -1 val PYTHON_EXCEPTION_THROWN = -2 val TIMING_DATA = -3 val END_OF_STREAM = -4 val NULL = -5 val START_ARROW_STREAM = -6 } private[spark] object BarrierTaskContextMessageProtocol { val BARRIER_FUNCTION = 1 val BARRIER_RESULT_SUCCESS = "success" val ERROR_UNRECOGNIZED_FUNCTION = "Not recognized function call from python side." }
bdrillard/spark
core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala
Scala
apache-2.0
24,374
package com.aurelpaulovic.transaction import com.aurelpaulovic.transaction.config.Configuration import com.aurelpaulovic.transaction.config.TransactionConfig trait Transaction { protected val conf: TransactionConfig } object Transaction { final class TransactionStub private[Transaction] () def transaction: TransactionStub = new TransactionStub() implicit def transactionStubToEmptyTransactionConfig(stub: TransactionStub)(implicit tm: TransactionManager): TransactionConfig = new Configuration(tm, Nil) }
AurelPaulovic/transactions-api
src/main/scala/com/aurelpaulovic/transaction/Transaction.scala
Scala
apache-2.0
523
// Databricks notebook source exported at Sat, 18 Jun 2016 08:46:55 UTC // MAGIC %md // MAGIC // MAGIC # [Scalable Data Science](http://www.math.canterbury.ac.nz/~r.sainudiin/courses/ScalableDataScience/) // MAGIC // MAGIC // MAGIC ### prepared by [Raazesh Sainudiin](https://nz.linkedin.com/in/raazesh-sainudiin-45955845) and [Sivanand Sivaram](https://www.linkedin.com/in/sivanand) // MAGIC // MAGIC *supported by* [![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/databricks_logoTM_200px.png)](https://databricks.com/) // MAGIC and // MAGIC [![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/AWS_logoTM_200px.png)](https://www.awseducate.com/microsite/CommunitiesEngageHome) // COMMAND ---------- // MAGIC %md // MAGIC The [html source url](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/db/week3/05_SparkSQLETLEDA/010_wikipediaClickStream_01ETLEDA.html) of this databricks notebook and its recorded Uji ![Image of Uji, Dogen's Time-Being](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/UjiTimeBeingDogen.png "uji"): // MAGIC // MAGIC [![sds/uji/week3/05_SparkSQLETLEDA/008_DiamondsPipeline](http://img.youtube.com/vi/6NoPvmTBVz0/0.jpg)](https://www.youtube.com/v/6NoPvmTBVz0?rel=0&autoplay=1&modestbranding=1&start=5402) // COMMAND ---------- // MAGIC %md // MAGIC # <img width="300px" src="http://cdn.arstechnica.net/wp-content/uploads/2015/09/2000px-Wikipedia-logo-v2-en-640x735.jpg"/> Clickstream Analysis // MAGIC // MAGIC ** Dataset: 3.2 billion requests collected during the month of February 2015 grouped by (src, dest) ** // MAGIC // MAGIC ** Source: https://datahub.io/dataset/wikipedia-clickstream/ ** // MAGIC // MAGIC <img width="700px" src="https://databricks-prod-cloudfront.s3.amazonaws.com/docs/images/ny.clickstream.png"/> // MAGIC // MAGIC <i>*This notebook requires Spark 1.6+</i> // COMMAND ---------- // MAGIC %md // MAGIC This notebook was originally a data analysis workflow developed with [Databricks Community Edition](https://databricks.com/blog/2016/02/17/introducing-databricks-community-edition-apache-spark-for-all.html), a free version of Databricks designed for learning [Apache Spark](https://spark.apache.org/). // MAGIC // MAGIC Here we elucidate the original python notebook ([also linked here](/#workspace/scalable-data-science/xtraResources/sparkSummitEast2016/Wikipedia Clickstream Data)) used in the talk by Michael Armbrust at Spark Summit East February 2016 // MAGIC shared from [https://twitter.com/michaelarmbrust/status/699969850475737088](https://twitter.com/michaelarmbrust/status/699969850475737088) // MAGIC (watch later) // MAGIC // MAGIC [![Michael Armbrust Spark Summit East](http://img.youtube.com/vi/35Y-rqSMCCA/0.jpg)](https://www.youtube.com/v/35Y-rqSMCCA) // COMMAND ---------- // MAGIC %md // MAGIC // MAGIC ### Data set // MAGIC // MAGIC #![Wikipedia Logo](http://sameerf-dbc-labs.s3-website-us-west-2.amazonaws.com/data/wikipedia/images/w_logo_for_labs.png) // MAGIC // MAGIC The data we are exploring in this lab is the February 2015 English Wikipedia Clickstream data, and it is available here: http://datahub.io/dataset/wikipedia-clickstream/resource/be85cc68-d1e6-4134-804a-fd36b94dbb82. // MAGIC // MAGIC According to Wikimedia: // MAGIC // MAGIC >"The data contains counts of (referer, resource) pairs extracted from the request logs of English Wikipedia. When a client requests a resource by following a link or performing a search, the URI of the webpage that linked to the resource is included with the request in an HTTP header called the "referer". This data captures 22 million (referer, resource) pairs from a total of 3.2 billion requests collected during the month of February 2015." // MAGIC // MAGIC The data is approximately 1.2GB and it is hosted in the following Databricks file: `/databricks-datasets/wikipedia-datasets/data-001/clickstream/raw-uncompressed` // COMMAND ---------- // MAGIC %md // MAGIC // MAGIC ### Let us first understand this Wikimedia data set a bit more // MAGIC Let's read the datahub-hosted link [https://datahub.io/dataset/wikipedia-clickstream](https://datahub.io/dataset/wikipedia-clickstream) in the embedding below. Also click the [blog](http://ewulczyn.github.io/Wikipedia_Clickstream_Getting_Started/) by Ellery Wulczyn, Data Scientist at The Wikimedia Foundation, to better understand how the data was generated (remember to Right-Click and use -> and <- if navigating within the embedded html frame below). // COMMAND ---------- //This allows easy embedding of publicly available information into any other notebook //when viewing in git-book just ignore this block - you may have to manually chase the URL in frameIt("URL"). //Example usage: // displayHTML(frameIt("https://en.wikipedia.org/wiki/Latent_Dirichlet_allocation#Topics_in_LDA",250)) def frameIt( u:String, h:Int ) : String = { """<iframe src=""""+ u+"""" width="95%" height="""" + h + """" sandbox> <p> <a href="http://spark.apache.org/docs/latest/index.html"> Fallback link for browsers that, unlikely, don't support frames </a> </p> </iframe>""" } displayHTML(frameIt("https://datahub.io/dataset/wikipedia-clickstream",500)) // COMMAND ---------- // MAGIC %md // MAGIC Run the next two cells for some housekeeping. // COMMAND ---------- if (org.apache.spark.BuildInfo.sparkBranch < "1.6") sys.error("Attach this notebook to a cluster running Spark 1.6+") // COMMAND ---------- // MAGIC %md // MAGIC ### Loading and Exploring the data // COMMAND ---------- val data = sc.textFile("dbfs:///databricks-datasets/wikipedia-datasets/data-001/clickstream/raw-uncompressed") // COMMAND ---------- // MAGIC %md // MAGIC ##### Looking at the first few lines of the data // COMMAND ---------- data.take(5).foreach(println) // COMMAND ---------- data.take(2) // COMMAND ---------- // MAGIC %md // MAGIC * The first line looks like a header // MAGIC * The second line (separated from the first by ",") contains data organized according to the header, i.e., `prev_id` = 3632887, `curr_id` = 121", and so on. // MAGIC // MAGIC Actually, here is the meaning of each column: // MAGIC // MAGIC - `prev_id`: if the referer does not correspond to an article in the main namespace of English Wikipedia, this value will be empty. Otherwise, it contains the unique MediaWiki page ID of the article corresponding to the referer i.e. the previous article the client was on // MAGIC // MAGIC - `curr_id`: the MediaWiki unique page ID of the article the client requested // MAGIC // MAGIC - `prev_title`: the result of mapping the referer URL to the fixed set of values described below // MAGIC // MAGIC - `curr_title`: the title of the article the client requested // MAGIC // MAGIC - `n`: the number of occurrences of the (referer, resource) pair // MAGIC // MAGIC - `type` // MAGIC - "link" if the referer and request are both articles and the referer links to the request // MAGIC - "redlink" if the referer is an article and links to the request, but the request is not in the production enwiki.page table // MAGIC - "other" if the *referer* and request are both articles but the referer does not link to the request. This can happen when clients search or spoof their refer // COMMAND ---------- // MAGIC %md // MAGIC Referers were mapped to a fixed set of values corresponding to internal traffic or external traffic from one of the top 5 global traffic sources to English Wikipedia, based on this scheme: // MAGIC // MAGIC >- an article in the main namespace of English Wikipedia -> the article title // MAGIC - any Wikipedia page that is not in the main namespace of English Wikipedia -> `other-wikipedia` // MAGIC - an empty referer -> `other-empty` // MAGIC - a page from any other Wikimedia project -> `other-internal` // MAGIC - Google -> `other-google` // MAGIC - Yahoo -> `other-yahoo` // MAGIC - Bing -> `other-bing` // MAGIC - Facebook -> `other-facebook` // MAGIC - Twitter -> `other-twitter` // MAGIC - anything else -> `other-other` // COMMAND ---------- // MAGIC %md // MAGIC In the second line of the file above, we can see there were 121 clicks from Google to the Wikipedia page on "!!" (double exclamation marks). People search for everything! // MAGIC * prev_id = *(nothing)* // MAGIC * curr_id = 3632887 *--> (Wikipedia page ID)* // MAGIC * n = 121 *(People clicked from Google to this page 121 times in this month.)* // MAGIC * prev_title = other-google *(This data record is for referals from Google.)* // MAGIC * curr_title = !! *(This Wikipedia page is about a double exclamation mark.)* // MAGIC * type = other // COMMAND ---------- // MAGIC %md // MAGIC ### Create a DataFrame from this CSV // MAGIC // MAGIC * From the next Spark release - 2.0, CSV as a datasource will be part of Spark's standard release. But, we are using Spark 1.6 // COMMAND ---------- // Load the raw dataset stored as a CSV file val clickstream = sqlContext. read. format("com.databricks.spark.csv"). options(Map("header" -> "true", "delimiter" -> "\\t", "mode" -> "PERMISSIVE", "inferSchema" -> "true")). load("dbfs:///databricks-datasets/wikipedia-datasets/data-001/clickstream/raw-uncompressed") // COMMAND ---------- // MAGIC %md // MAGIC ##### Print the schema // COMMAND ---------- clickstream.printSchema // COMMAND ---------- // MAGIC %md // MAGIC #### Display some sample data // COMMAND ---------- display(clickstream) // COMMAND ---------- // MAGIC %md // MAGIC Display is a utility provided by Databricks. If you are programming directly in Spark, use the show(numRows: Int) function of DataFrame // COMMAND ---------- clickstream.show(5) // COMMAND ---------- // MAGIC %md // MAGIC ### Reading from disk vs memory // MAGIC // MAGIC The 1.2 GB Clickstream file is currently on S3, which means each time you scan through it, your Spark cluster has to read the 1.2 GB of data remotely over the network. // COMMAND ---------- // MAGIC %md Call the `count()` action to check how many rows are in the DataFrame and to see how long it takes to read the DataFrame from S3. // COMMAND ---------- clickstream.cache().count() // COMMAND ---------- // MAGIC %md // MAGIC * It took about several minutes to read the 1.2 GB file into your Spark cluster. The file has 22.5 million rows/lines. // MAGIC * Although we have called cache, remember that it is evaluated (cached) only when an action(count) is called // COMMAND ---------- // MAGIC %md // MAGIC Now call count again to see how much faster it is to read from memory // COMMAND ---------- clickstream.count() // COMMAND ---------- // MAGIC %md // MAGIC * Orders of magnitude faster! // MAGIC * If you are going to be using the same data source multiple times, it is better to cache it in memory // COMMAND ---------- // MAGIC %md // MAGIC // MAGIC ### What are the top 10 articles requested? // MAGIC // MAGIC To do this we also need to order by the sum of column `n`, in descending order. // COMMAND ---------- //Type in your answer here... display(clickstream .select(clickstream("curr_title"), clickstream("n")) .groupBy("curr_title") .sum() .orderBy($"sum(n)".desc) .limit(10)) // COMMAND ---------- // MAGIC %md // MAGIC ### Who sent the most traffic to Wikipedia in Feb 2015? // MAGIC // MAGIC In other words, who were the top referers to Wikipedia? // COMMAND ---------- display(clickstream .select(clickstream("prev_title"), clickstream("n")) .groupBy("prev_title") .sum() .orderBy($"sum(n)".desc) .limit(10)) // COMMAND ---------- // MAGIC %md // MAGIC As expected, the top referer by a large margin is Google. Next comes refererless traffic (usually clients using HTTPS). The third largest sender of traffic to English Wikipedia are Wikipedia pages that are not in the main namespace (ns = 0) of English Wikipedia. Learn about the Wikipedia namespaces here: // MAGIC https://en.wikipedia.org/wiki/Wikipedia:Project_namespace // MAGIC // MAGIC Also, note that Twitter sends 10x more requests to Wikipedia than Facebook. // COMMAND ---------- // MAGIC %md // MAGIC ### What were the top 5 trending articles people from Twitter were looking up in Wikipedia? // COMMAND ---------- //Type in your answer here... display(clickstream .select(clickstream("curr_title"), clickstream("prev_title"), clickstream("n")) .filter("prev_title = 'other-twitter'") .groupBy("curr_title") .sum() .orderBy($"sum(n)".desc) .limit(5)) // COMMAND ---------- // MAGIC %md // MAGIC #### What percentage of page visits in Wikipedia are from other pages in Wikipedia itself? // COMMAND ---------- val allClicks = clickstream.selectExpr("sum(n)").first.getLong(0) val referals = clickstream. filter(clickstream("prev_id").isNotNull). selectExpr("sum(n)").first.getLong(0) (referals * 100.0) / allClicks // COMMAND ---------- // MAGIC %md // MAGIC #### Register the DataFrame to perform more complex queries // COMMAND ---------- clickstream.registerTempTable("clicks") // COMMAND ---------- // MAGIC %md // MAGIC #### Which Wikipedia pages have the most referrals to the Donald Trump page? // COMMAND ---------- // MAGIC %sql // MAGIC SELECT * // MAGIC FROM clicks // MAGIC WHERE // MAGIC curr_title = 'Donald_Trump' AND // MAGIC prev_id IS NOT NULL AND prev_title != 'Main_Page' // MAGIC ORDER BY n DESC // MAGIC LIMIT 20 // COMMAND ---------- // MAGIC %md // MAGIC #### Top referrers to all presidential candidate pages // COMMAND ---------- // MAGIC %sql // MAGIC SELECT // MAGIC prev_title, // MAGIC curr_title, // MAGIC n // MAGIC FROM clicks // MAGIC WHERE // MAGIC curr_title IN ('Donald_Trump', 'Bernie_Sanders', 'Hillary_Rodham_Clinton', 'Ted_Cruz') AND // MAGIC prev_id IS NOT NULL AND prev_title != 'Main_Page' // MAGIC ORDER BY n DESC // MAGIC LIMIT 20 // COMMAND ---------- // MAGIC %md // MAGIC #### Load a visualization library // MAGIC This code is copied after doing a live google search (by Michael Armbrust at Spark Summit East February 2016 // MAGIC shared from [https://twitter.com/michaelarmbrust/status/699969850475737088](https://twitter.com/michaelarmbrust/status/699969850475737088)). // COMMAND ---------- package d3 // We use a package object so that we can define top level classes like Edge that need to be used in other cells import org.apache.spark.sql._ import com.databricks.backend.daemon.driver.EnhancedRDDFunctions.displayHTML case class Edge(src: String, dest: String, count: Long) case class Node(name: String) case class Link(source: Int, target: Int, value: Long) case class Graph(nodes: Seq[Node], links: Seq[Link]) object graphs { val sqlContext = SQLContext.getOrCreate(org.apache.spark.SparkContext.getOrCreate()) import sqlContext.implicits._ def force(clicks: Dataset[Edge], height: Int = 100, width: Int = 960): Unit = { val data = clicks.collect() val nodes = (data.map(_.src) ++ data.map(_.dest)).map(_.replaceAll("_", " ")).toSet.toSeq.map(Node) val links = data.map { t => Link(nodes.indexWhere(_.name == t.src.replaceAll("_", " ")), nodes.indexWhere(_.name == t.dest.replaceAll("_", " ")), t.count / 20 + 1) } showGraph(height, width, Seq(Graph(nodes, links)).toDF().toJSON.first()) } /** * Displays a force directed graph using d3 * input: {"nodes": [{"name": "..."}], "links": [{"source": 1, "target": 2, "value": 0}]} */ def showGraph(height: Int, width: Int, graph: String): Unit = { displayHTML(s""" <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Polish Books Themes - an Interactive Map</title> <meta charset="utf-8"> <style> .node_circle { stroke: #777; stroke-width: 1.3px; } .node_label { pointer-events: none; } .link { stroke: #777; stroke-opacity: .2; } .node_count { stroke: #777; stroke-width: 1.0px; fill: #999; } text.legend { font-family: Verdana; font-size: 13px; fill: #000; } .node text { font-family: "Helvetica Neue","Helvetica","Arial",sans-serif; font-size: 17px; font-weight: 200; } </style> </head> <body> <script src="//d3js.org/d3.v3.min.js"></script> <script> var graph = $graph; var width = $width, height = $height; var color = d3.scale.category20(); var force = d3.layout.force() .charge(-700) .linkDistance(180) .size([width, height]); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); force .nodes(graph.nodes) .links(graph.links) .start(); var link = svg.selectAll(".link") .data(graph.links) .enter().append("line") .attr("class", "link") .style("stroke-width", function(d) { return Math.sqrt(d.value); }); var node = svg.selectAll(".node") .data(graph.nodes) .enter().append("g") .attr("class", "node") .call(force.drag); node.append("circle") .attr("r", 10) .style("fill", function (d) { if (d.name.startsWith("other")) { return color(1); } else { return color(2); }; }) node.append("text") .attr("dx", 10) .attr("dy", ".35em") .text(function(d) { return d.name }); //Now we are giving the SVGs co-ordinates - the force layout is generating the co-ordinates which this code is using to update the attributes of the SVG elements force.on("tick", function () { link.attr("x1", function (d) { return d.source.x; }) .attr("y1", function (d) { return d.source.y; }) .attr("x2", function (d) { return d.target.x; }) .attr("y2", function (d) { return d.target.y; }); d3.selectAll("circle").attr("cx", function (d) { return d.x; }) .attr("cy", function (d) { return d.y; }); d3.selectAll("text").attr("x", function (d) { return d.x; }) .attr("y", function (d) { return d.y; }); }); </script> </html> """) } def help() = { displayHTML(""" <p> Produces a force-directed graph given a collection of edges of the following form:</br> <tt><font color="#a71d5d">case class</font> <font color="#795da3">Edge</font>(<font color="#ed6a43">src</font>: <font color="#a71d5d">String</font>, <font color="#ed6a43">dest</font>: <font color="#a71d5d">String</font>, <font color="#ed6a43">count</font>: <font color="#a71d5d">Long</font>)</tt> </p> <p>Usage:<br/> <tt><font color="#a71d5d">import</font> <font color="#ed6a43">d3._</font></tt><br/> <tt><font color="#795da3">graphs.force</font>(</br> &nbsp;&nbsp;<font color="#ed6a43">height</font> = <font color="#795da3">500</font>,<br/> &nbsp;&nbsp;<font color="#ed6a43">width</font> = <font color="#795da3">500</font>,<br/> &nbsp;&nbsp;<font color="#ed6a43">clicks</font>: <font color="#795da3">Dataset</font>[<font color="#795da3">Edge</font>])</tt> </p>""") } } // COMMAND ---------- d3.graphs.help() // COMMAND ---------- d3.graphs.force( height = 800, width = 1000, clicks = sql(""" SELECT prev_title AS src, curr_title AS dest, n AS count FROM clicks WHERE curr_title IN ('Donald_Trump', 'Bernie_Sanders', 'Hillary_Rodham_Clinton', 'Ted_Cruz') AND prev_id IS NOT NULL AND prev_title != 'Main_Page' ORDER BY n DESC LIMIT 20""").as[d3.Edge]) // COMMAND ---------- // MAGIC %md // MAGIC ### Convert raw data to parquet // MAGIC [Apache Parquet](https://parquet.apache.org/) is a [columnar storage](http://en.wikipedia.org/wiki/Column-oriented_DBMS) format available to any project in the Hadoop ecosystem, regardless of the choice of data processing framework, data model or programming language. It is a more efficient way to store data frames. // MAGIC // MAGIC * To understand the ideas read [Dremel: Interactive Analysis of Web-Scale Datasets, Sergey Melnik, Andrey Gubarev, Jing Jing Long, Geoffrey Romer, Shiva Shivakumar, Matt Tolton and Theo Vassilakis,Proc. of the 36th Int'l Conf on Very Large Data Bases (2010), pp. 330-339](http://research.google.com/pubs/pub36632.html), whose Abstract is as follows: // MAGIC * Dremel is a scalable, interactive ad-hoc query system for analysis of read-only nested data. By combining multi-level execution trees and columnar data layouts it is **capable of running aggregation queries over trillion-row tables in seconds**. The system **scales to thousands of CPUs and petabytes of data, and has thousands of users at Google**. In this paper, we describe the architecture and implementation of Dremel, and explain how it complements MapReduce-based computing. We present a novel columnar storage representation for nested records and discuss experiments on few-thousand node instances of the system. // COMMAND ---------- displayHTML(frameIt("https://parquet.apache.org/documentation/latest/",350)) // COMMAND ---------- // Convert the DatFrame to a more efficent format to speed up our analysis clickstream. write. mode(SaveMode.Overwrite). parquet("/datasets/wiki-clickstream") // warnings are harmless // COMMAND ---------- // MAGIC %md // MAGIC #### Load parquet file efficiently and quickly into a DataFrame // MAGIC // MAGIC Now we can simply load from this parquet file next time instead of creating the RDD from the text file (much slower). // MAGIC // MAGIC Also using parquet files to store DataFrames allows us to go between languages quickly in a a scalable manner. // COMMAND ---------- val clicks = sqlContext.read.parquet("/datasets/wiki-clickstream") // COMMAND ---------- clicks.printSchema // COMMAND ---------- display(clicks) // let's display this DataFrame // COMMAND ---------- // MAGIC %md // MAGIC ##### DataFrame in python // COMMAND ---------- // MAGIC %py // MAGIC clicksPy = sqlContext.read.parquet("/datasets/wiki-clickstream") // COMMAND ---------- // MAGIC %py // MAGIC clicksPy.show() // COMMAND ---------- // MAGIC %md // MAGIC Now you can continue from the original python notebook also linked to this shard from here ([/#workspace/scalable-data-science/xtraResources/sparkSummitEast2016/Wikipedia Clickstream Data](/#workspace/scalable-data-science/xtraResources/sparkSummitEast2016/Wikipedia Clickstream Data)). // MAGIC // MAGIC Recall from the beginning of this notebook that this python databricks notebook was used in the talk by Michael Armbrust at Spark Summit East February 2016 // MAGIC shared from [https://twitter.com/michaelarmbrust/status/699969850475737088](https://twitter.com/michaelarmbrust/status/699969850475737088) // MAGIC // MAGIC (watch now, if you haven't already!) // MAGIC // MAGIC [![Michael Armbrust Spark Summit East](http://img.youtube.com/vi/35Y-rqSMCCA/0.jpg)](https://www.youtube.com/v/35Y-rqSMCCA) // COMMAND ---------- // MAGIC %md // MAGIC **You Try!** // MAGIC // MAGIC Try to laoad a DataFrame in R from the parquet file just as we did for python. // COMMAND ---------- // MAGIC %r // COMMAND ---------- // MAGIC %md // MAGIC // MAGIC # [Scalable Data Science](http://www.math.canterbury.ac.nz/~r.sainudiin/courses/ScalableDataScience/) // MAGIC // MAGIC // MAGIC ### prepared by [Raazesh Sainudiin](https://nz.linkedin.com/in/raazesh-sainudiin-45955845) and [Sivanand Sivaram](https://www.linkedin.com/in/sivanand) // MAGIC // MAGIC *supported by* [![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/databricks_logoTM_200px.png)](https://databricks.com/) // MAGIC and // MAGIC [![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/AWS_logoTM_200px.png)](https://www.awseducate.com/microsite/CommunitiesEngageHome)
lamastex/scalable-data-science
db/week3/05_SparkSQLETLEDA/010_wikipediaClickStream_01ETLEDA.scala
Scala
unlicense
23,774
/* - Coeus web framework ------------------------- * * Licensed under the Apache License, Version 2.0. * * Author: Spiros Tzavellas */ package com.tzavellas.coeus.validation.bean import java.util.Locale import javax.validation.{ Validation => JValidation } /** * Helper methods to bootstrap a JSR-303 validator. */ object Validation { /** * Get the configuration of the default JSR-303 provider and set the * interpolator to {@code LocaleAwareInterpolator}. * * @param offlineLocale the offline locale of {@code LocaleAwareInterpolator} * * @return the changed configuration of the default provider */ def defaultConfig(offlineLocale: Locale) = { val conf = JValidation.byDefaultProvider.configure() conf.messageInterpolator(new LocaleAwareInterpolator(conf.getDefaultMessageInterpolator, offlineLocale)) conf } }
sptz45/coeus
src/main/scala/com/tzavellas/coeus/validation/bean/Validation.scala
Scala
apache-2.0
867
package spinoco.protocol.kafka.codec import scodec.bits.BitVector import scodec.{Attempt, Codec} import scodec.codecs._ import shapeless.{::, HNil} import spinoco.protocol.kafka._ import spinoco.protocol.common.util._ import spinoco.protocol.kafka.Request.{FetchRequest, MetadataRequest, OffsetsRequest, ProduceRequest} object MessageCodec { /** enodes supplied request **/ val requestCodec: Codec[RequestMessage] = variableSizeBytes(int32, impl.requestContentCodec) /** * Decodes response correlation id plus the bytes of the response * Once correlationId is known, then original request may be identified * and then `responseCodecFor` may be used to actually decode the message- */ val responseCorrelationCodec:Codec[(Int,BitVector)] = variableSizeBytes(int32, ("Correlation Id" | int32) ~ bits ) /** decodes concrete response **/ def responseCodecFor(version: ProtocolVersion.Value, apiKey:ApiKey.Value):Codec[Response] = { apiKey match { case ApiKey.FetchRequest => FetchCodec.responseCodec(version).upcast case ApiKey.MetadataRequest => MetadataCodec.metadataResponseCodec.upcast case ApiKey.ProduceRequest => ProduceCodec.produceResponseCodec(version).upcast case ApiKey.OffsetRequest => OffsetCodec.responseCodec(version).upcast } } object impl { val apiKeyCodec:Codec[ApiKey.Value] = int16.exmap( code => attempt(ApiKey(code)) , k => Attempt.successful(k.id) ) type RequestHeader = ApiKey.Value :: Int :: Int :: String :: HNil val requestHeaderCodec : Codec[RequestHeader] = { "Request Header" | ( ("Api Key" | apiKeyCodec) :: ("Api Version" | int16) :: ("Correlation Id" | int32) :: ("Client Id" | kafkaRequiredString) ) } val requestContentCodec: Codec[RequestMessage] = { def encode(rm:RequestMessage):(RequestHeader, Request) = { val key = ApiKey.forRequest(rm.request) val version: Int = rm.request match { case _: ProduceRequest => rm.version match { case ProtocolVersion.Kafka_0_8 => 0 case ProtocolVersion.Kafka_0_9 => 1 case ProtocolVersion.Kafka_0_10 | ProtocolVersion.Kafka_0_10_1 | ProtocolVersion.Kafka_0_10_2 => 2 } case _: FetchRequest => rm.version match { case ProtocolVersion.Kafka_0_8 => 0 case ProtocolVersion.Kafka_0_9 => 1 case ProtocolVersion.Kafka_0_10 | ProtocolVersion.Kafka_0_10_1 => 2 case ProtocolVersion.Kafka_0_10_2 => 3 } case _: MetadataRequest => 0 case _: OffsetsRequest => 0 } (key :: version :: rm.correlationId :: rm.clientId :: HNil, rm.request) } def decode(header:RequestHeader, request:Request): RequestMessage = { val version :: correlation :: clientId :: HNil = header.tail val protocolVersion = request match { case _: ProduceRequest => version match { case 0 => ProtocolVersion.Kafka_0_8 case 1 => ProtocolVersion.Kafka_0_9 case _ => ProtocolVersion.Kafka_0_10 } case _: FetchRequest => version match { case 0 => ProtocolVersion.Kafka_0_8 case 1 => ProtocolVersion.Kafka_0_9 case 2 => ProtocolVersion.Kafka_0_10 case 3 | _ => ProtocolVersion.Kafka_0_10_2 } case _: MetadataRequest => ProtocolVersion.Kafka_0_8 case _: OffsetsRequest => ProtocolVersion.Kafka_0_8 } RequestMessage(protocolVersion, correlation, clientId, request) } requestHeaderCodec.flatZip[Request] { case api :: version :: _ => api match { case ApiKey.ProduceRequest => ProduceCodec.requestCodec.upcast case ApiKey.FetchRequest => FetchCodec.requestCodec(version).upcast case ApiKey.MetadataRequest => MetadataCodec.requestCodec.upcast case ApiKey.OffsetRequest => OffsetCodec.requestCodec(version).upcast } }.xmap(decode _ tupled,encode) } } }
Spinoco/protocol
kafka/src/main/scala/spinoco/protocol/kafka/codec/MessageCodec.scala
Scala
mit
4,187
/* * Copyright (c) 2015 Goldman Sachs. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.eclipse.collections.impl import org.eclipse.collections.impl.factory.Sets class EmptySetScalaTest extends EmptyIterableTestTrait { val classUnderTest = Sets.fixedSize.of[String] }
bhav0904/eclipse-collections
scala-unit-tests/src/test/scala/org/eclipse/collections/impl/EmptySetScalaTest.scala
Scala
bsd-3-clause
659
package forimpatient.chapter11 /** * Created by Iryna Kharaborkina on 8/9/16. * * Solution to the Chapter 11 Exercise 06 'Scala for the Impatient' by Horstmann C.S. * * Provide a class ASCIIArt whose objects contain figures such as * /\\_/\\ * ( ' ' ) * ( - ) * | | | * (__|__) * Supply operators for combining two ASCIIArt figures horizontally * /\\_/\\ ----- * ( ' ' ) / Hello \\ * ( - ) < Scala | * | | | \\ Coder / * (__|__) ----- * * or vertically. Choose operators with appropriate precedence. */ object Exercise06 extends App { println("Chapter 11 Exercise 06") val a = ASCIIArt( """| /\\_/\\ | ( ' ' ) | ( - ) | | | | | (__|__) |""".stripMargin) val b = ASCIIArt( """| ----- | / Hello \\ |< Scala | | \\ Coder / | ----- |""".stripMargin ) val c = new ASCIIArt(" ") println(a + b + c + a + a) class ASCIIArt(val art: String) { def ^(other: ASCIIArt) = new ASCIIArt(art + other.art) def +(other: ASCIIArt) = { val artLines: Array[String] = art.split("\\n") val otherArtLines: Array[String] = other.art.split("\\n") val width = artLines.maxBy(_.length).length + 1 val newArt = artLines.zipAll(otherArtLines, "", "").map(x => x._1 + " " * (width - x._1.length) + x._2) new ASCIIArt(newArt.mkString("\\n")) } override def toString = art } object ASCIIArt { def apply(art: String) = new ASCIIArt(art) } }
Kiryna/Scala-for-the-Impatient
src/forimpatient/chapter11/Exercise06.scala
Scala
apache-2.0
1,557
package gitbucket.core.service import gitbucket.core.model.{Account, GroupMember} import java.util.Date import org.scalatest.FunSuite class AccountServiceSpec extends FunSuite with ServiceSpecBase { val RootMailAddress = "root@localhost" test("getAllUsers") { withTestDB { implicit session => assert(AccountService.getAllUsers() match { case List(Account("root", "root", RootMailAddress, _, true, _, _, _, None, None, false, false, None)) => true case _ => false }) }} test("getAccountByUserName") { withTestDB { implicit session => assert(AccountService.getAccountByUserName("root").get.userName == "root") assert(AccountService.getAccountByUserName("invalid user name").isEmpty) }} test("getAccountByMailAddress") { withTestDB { implicit session => assert(AccountService.getAccountByMailAddress(RootMailAddress).isDefined) }} test("updateLastLoginDate") { withTestDB { implicit session => val root = "root" def user() = AccountService.getAccountByUserName(root).getOrElse(sys.error(s"user $root does not exists")) assert(user().lastLoginDate.isEmpty) val date1 = new Date AccountService.updateLastLoginDate(root) assert(user().lastLoginDate.get.compareTo(date1) > 0) val date2 = new Date Thread.sleep(1000) AccountService.updateLastLoginDate(root) assert(user().lastLoginDate.get.compareTo(date2) > 0) }} test("updateAccount") { withTestDB { implicit session => val root = "root" def user() = AccountService.getAccountByUserName(root).getOrElse(sys.error(s"user $root does not exists")) val newAddress = "new mail address" AccountService.updateAccount(user().copy(mailAddress = newAddress)) assert(user().mailAddress == newAddress) val newUrl = Some("http://new.url.example/path") AccountService.updateAccount(user().copy(url = newUrl)) assert(user().url == newUrl) val newDescription = Some("http://new.url.example/path") AccountService.updateAccount(user().copy(description = newDescription)) assert(user().description == newDescription) }} test("group") { withTestDB { implicit session => val group1 = "group1" val user1 = "root" AccountService.createGroup(group1, None, None) assert(AccountService.getGroupMembers(group1) == Nil) assert(AccountService.getGroupsByUserName(user1) == Nil) AccountService.updateGroupMembers(group1, List((user1, true))) assert(AccountService.getGroupMembers(group1) == List(GroupMember(group1, user1, true))) assert(AccountService.getGroupsByUserName(user1) == List(group1)) AccountService.updateGroupMembers(group1, Nil) assert(AccountService.getGroupMembers(group1) == Nil) assert(AccountService.getGroupsByUserName(user1) == Nil) }} test("createGroup save description") { withTestDB { implicit session => AccountService.createGroup("some-group", Some("some clever description"), None) val maybeGroup = AccountService.getAccountByUserName("some-group") assert(maybeGroup.flatMap(_.description) == Some("some clever description")) }} test("updateGroup save description") { withTestDB { implicit session => AccountService.createGroup("a-group", None, None) AccountService.updateGroup("a-group", Some("new description"), None, false) val group = AccountService.getAccountByUserName("a-group") assert(group.flatMap(_.description) == Some("new description")) }} }
gencer/gitbucket
src/test/scala/gitbucket/core/service/AccountServiceSpec.scala
Scala
apache-2.0
3,444
package org.jetbrains.plugins.scala package lang package psi package api package toplevel package typedef import com.intellij.psi.PsiClass /** * @author Alexander Podkhalyuzin * @since 20.02.2008 */ trait ScTrait extends ScTypeDefinition with ScDerivesClauseOwner with ScConstructorOwner { def fakeCompanionClass: PsiClass }
JetBrains/intellij-scala
scala/scala-impl/src/org/jetbrains/plugins/scala/lang/psi/api/toplevel/typedef/ScTrait.scala
Scala
apache-2.0
329
package com.thetestpeople.trt.webdriver import org.junit.runner.RunWith import com.thetestpeople.trt.model.impl.DummyData import com.thetestpeople.trt.tags.SlowTest import org.scalatest.junit.JUnitRunner @SlowTest @RunWith(classOf[JUnitRunner]) class SystemConfigurationScreenTest extends AbstractBrowserTest { "System configuration screen" should "let you update settings" in { automate { site ⇒ val systemConfigScreen = site.launch().mainMenu.config().system() systemConfigScreen.brokenDurationThreshold = "1 hour" systemConfigScreen.brokenCountThreshold = "1" systemConfigScreen.healthyDurationThreshold = "2 hours" systemConfigScreen.healthyCountThreshold = "2" systemConfigScreen.clickUpdate() systemConfigScreen.waitForSuccessMessage() systemConfigScreen.brokenDurationThreshold should equal("1 hour") systemConfigScreen.brokenCountThreshold should equal("1") systemConfigScreen.healthyDurationThreshold should equal("2 hours") systemConfigScreen.healthyCountThreshold should equal("2") } } it should "not let you enter negative values" in { automate { site ⇒ val systemConfigScreen = site.launch().mainMenu.config().system() systemConfigScreen.brokenDurationThreshold = "-1 hour" systemConfigScreen.brokenCountThreshold = "-1" systemConfigScreen.clickUpdate() systemConfigScreen.waitForValidationError() systemConfigScreen.errorsForBrokenCountThreshold should be('defined) systemConfigScreen.errorsForBrokenDurationThreshold should be('defined) } } }
thetestpeople/trt
test/com/thetestpeople/trt/webdriver/SystemConfigurationScreenTest.scala
Scala
mit
1,600
package justin.db.kryo import java.util.UUID import com.esotericsoftware.kryo.io.{Input, Output} import com.esotericsoftware.kryo.{Kryo, Serializer} import justin.db.actors.protocol.StorageNodeLocalRead object StorageNodeLocalReadSerializer extends Serializer[StorageNodeLocalRead] { override def write(kryo: Kryo, output: Output, localRead: StorageNodeLocalRead): Unit = { output.writeString(localRead.id.toString) } override def read(kryo: Kryo, input: Input, `type`: Class[StorageNodeLocalRead]): StorageNodeLocalRead = { StorageNodeLocalRead(UUID.fromString(input.readString())) } }
speedcom/JustinDB
justin-core/src/main/scala/justin/db/kryo/StorageNodeLocalReadSerializer.scala
Scala
apache-2.0
608
package im.actor.server.model object AvatarData { trait TypeVal { def toInt: Int } object TypeVal { def fromInt(i: Int): TypeVal = i match { case 1 ⇒ OfUser case 2 ⇒ OfGroup } } trait TypeValImpl[T] extends TypeVal implicit object OfUser extends TypeValImpl[User] { def toInt = 1; } implicit object OfGroup extends TypeValImpl[Group] { def toInt = 1; } def typeVal[T]()(implicit impl: TypeValImpl[T]): TypeVal = impl def empty[T](entityId: Long)(implicit impl: TypeValImpl[T]): AvatarData = empty(impl, entityId) def empty(impl: TypeVal, entityId: Long) = AvatarData( impl, entityId = entityId, smallAvatarFileId = None, smallAvatarFileHash = None, smallAvatarFileSize = None, largeAvatarFileId = None, largeAvatarFileHash = None, largeAvatarFileSize = None, fullAvatarFileId = None, fullAvatarFileHash = None, fullAvatarFileSize = None, fullAvatarWidth = None, fullAvatarHeight = None ) } case class AvatarData( entityType: AvatarData.TypeVal, entityId: Long, smallAvatarFileId: Option[Long], smallAvatarFileHash: Option[Long], smallAvatarFileSize: Option[Long], largeAvatarFileId: Option[Long], largeAvatarFileHash: Option[Long], largeAvatarFileSize: Option[Long], fullAvatarFileId: Option[Long], fullAvatarFileHash: Option[Long], fullAvatarFileSize: Option[Long], fullAvatarWidth: Option[Int], fullAvatarHeight: Option[Int] ) { lazy val smallOpt = for ( id ← smallAvatarFileId; hash ← smallAvatarFileHash; size ← smallAvatarFileSize ) yield (id, hash, size) lazy val largeOpt = for ( id ← largeAvatarFileId; hash ← largeAvatarFileHash; size ← largeAvatarFileSize ) yield (id, hash, size) lazy val fullOpt = for ( id ← fullAvatarFileId; hash ← fullAvatarFileHash; size ← fullAvatarFileSize; w ← fullAvatarWidth; h ← fullAvatarHeight ) yield (id, hash, size, w, h) }
EaglesoftZJ/actor-platform
actor-server/actor-models/src/main/scala/im/actor/server/model/AvatarData.scala
Scala
agpl-3.0
2,072
object ObjectApplyCall { def apply(x: Int, y: Int) = 55 } /*start*/ObjectApplyCall(1,2)/*end*/ //Int
ilinum/intellij-scala
testdata/typeInference/methodCall/ObjectApplyCall.scala
Scala
apache-2.0
102
package com.github.ghik.silencer trait SilencerPluginCompat { this: SilencerPlugin => import global._ protected object MaybeNamedArg { def unapply(tree: Tree): OptRef[Tree] = tree match { case NamedArg(_, rhs) => OptRef(rhs) case _ => OptRef(tree) } } }
ghik/silencer
silencer-plugin/src/main/scala-2.13/com/github/ghik/silencer/SilencerPluginCompat.scala
Scala
apache-2.0
283
/* * 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.nn.ops import com.intel.analytics.bigdl.dllib.tensor.Tensor import com.intel.analytics.bigdl.dllib.utils.T import com.intel.analytics.bigdl.dllib.utils.serializer.ModuleSerializationTest import org.scalatest.{FlatSpec, Matchers} class LogicalNotSpec extends FlatSpec with Matchers { "LogicalNot operation" should "works correctly" in { import com.intel.analytics.bigdl.numeric.NumericBoolean val input = Tensor(T(true, false, true)) val expectOutput = Tensor(T(false, true, false)) val output = LogicalNot().forward(input) output should be(expectOutput) } } class LogicalNotSerialTest extends ModuleSerializationTest { override def test(): Unit = { val logicalNot = LogicalNot[Float].setName("logicalNot") val input = Tensor[Boolean](T(true, false)) runSerializationTest(logicalNot, input, logicalNot .asInstanceOf[ModuleToOperation[Float]].module.getClass) } }
intel-analytics/BigDL
scala/dllib/src/test/scala/com/intel/analytics/bigdl/dllib/nn/ops/LogicalNotSpec.scala
Scala
apache-2.0
1,555
package domain import org.joda.time.DateTime case class Review( id: String, author: String, title: String, dateCreated: DateTime, fileCount: Int ) { def updateFileCount(newFileCount: Int): Review = { Review(id, author, title, dateCreated, newFileCount) } }
markdrago/expedition
app/domain/Review.scala
Scala
mit
277
package org.otw.open.listeners import com.badlogic.gdx.scenes.scene2d.{InputEvent, InputListener} import org.otw.open.actors.MovingObjectActor /** * Created by eilievska on 2/18/2016. */ class MovingObjectClickListener(val actor: MovingObjectActor) extends InputListener { override def touchDown(event: InputEvent, x: Float, y: Float, pointer: Int, button: Int): Boolean = { if (!actor.isInMotion) { actor.move actor.playSound() } if (actor.isOnInitialPosition) { actor.decrementMissCount } true } }
danielEftimov/OPEN
core/src/org/otw/open/listeners/MovingObjectClickListener.scala
Scala
apache-2.0
550
/* * Copyright (C) 2010 Romain Reuillon * * 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 org.openmole.core.batch.environment import org.openmole.core.batch.control._ trait BatchService extends UsageControl { def environment: BatchEnvironment }
ISCPIF/PSEExperiments
openmole-src/openmole/core/org.openmole.core.batch/src/main/scala/org/openmole/core/batch/environment/BatchService.scala
Scala
agpl-3.0
882
/** * 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.camel package scala.dsl import builder.RouteBuilder import junit.framework.Assert.assertEquals class RouteIdTest extends ScalaTestSupport { def testRouteA = { "mock:a" expect { _.expectedMessageCount(1)} test { "direct:a" ! "Hello World" } assertMockEndpointsSatisfied assertEquals("route-a", context.getRouteDefinitions.get(0).getId()); } def testRouteB = { "mock:b" expect { _.expectedMessageCount(1)} test { "direct:b" ! "Hello World" } assertMockEndpointsSatisfied assertEquals("route-b", context.getRouteDefinitions.get(1).getId()); } val builder = new RouteBuilder { // java DSL from("direct:a").routeId("route-a").to("mock:a") // scala DSL "direct:b" routeId "route-b" to "mock:b" } }
chicagozer/rheosoft
components/camel-scala/src/test/scala/org/apache/camel/scala/dsl/RouteIdTest.scala
Scala
apache-2.0
1,609
package scoverage.report import java.io.File import java.util.Date import scoverage._ import scala.xml.Node /** @author Stephen Samuel */ class ScoverageHtmlWriter(sourceDirectories: Seq[File], outputDir: File) extends BaseReportWriter(sourceDirectories, outputDir) { def this (sourceDirectory: File, outputDir: File) { this(Seq(sourceDirectory), outputDir); } def write(coverage: Coverage): Unit = { val indexFile = new File(outputDir.getAbsolutePath + "/index.html") val packageFile = new File(outputDir.getAbsolutePath + "/packages.html") val overviewFile = new File(outputDir.getAbsolutePath + "/overview.html") val index = IOUtils.readStreamAsString(getClass.getResourceAsStream("/scoverage/index.html")) IOUtils.writeToFile(indexFile, index) IOUtils.writeToFile(packageFile, packageList(coverage).toString()) IOUtils.writeToFile(overviewFile, overview(coverage).toString()) coverage.packages.foreach(writePackage) } private def writePackage(pkg: MeasuredPackage): Unit = { // package overview files are written out using a filename that respects the package name // that means package com.example declared in a class at src/main/scala/mystuff/MyClass.scala will be written // to com.example.html val file = new File(outputDir, packageOverviewRelativePath(pkg)) file.getParentFile.mkdirs() IOUtils.writeToFile(file, packageOverview(pkg).toString()) pkg.files.foreach(writeFile) } private def writeFile(mfile: MeasuredFile): Unit = { // each highlighted file is written out using the same structure as the original file. val file = new File(outputDir, relativeSource(mfile.source) + ".html") file.getParentFile.mkdirs() IOUtils.writeToFile(file, filePage(mfile).toString()) } private def packageOverviewRelativePath(pkg: MeasuredPackage) = pkg.name.replace("<empty>", "(empty)") + ".html" private def filePage(mfile: MeasuredFile): Node = { val filename = relativeSource(mfile.source) + ".html" val css = "table.codegrid { font-family: monospace; font-size: 12px; width: auto!important; }" + "table.statementlist { width: auto!important; font-size: 13px; } " + "table.codegrid td { padding: 0!important; border: 0!important } " + "table td.linenumber { width: 40px!important; } " <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title id='title'> {filename} </title> {plugins} <style> {css} </style> </head> <body style="font-family: monospace;"> <ul class="nav nav-tabs"> <li> <a href="#codegrid" data-toggle="tab">Codegrid</a> </li> <li> <a href="#statementlist" data-toggle="tab">Statement List</a> </li> </ul> <div class="tab-content"> <div class="tab-pane active" id="codegrid"> {xml.Unparsed(new CodeGrid(mfile).highlighted)} </div> <div class="tab-pane" id="statementlist"> {new StatementWriter(mfile).output} </div> </div> </body> </html> } def header = { val css = """.meter { | height: 14px; | position: relative; | background: #BB2020; |} | |.meter span { | display: block; | height: 100%; | background-color: rgb(43,194,83); | background-image: -webkit-gradient( | linear, | left bottom, | left top, | color-stop(0, rgb(43,194,83)), | color-stop(1, rgb(84,240,84)) | ); | background-image: -webkit-linear-gradient( | center bottom, | rgb(43,194,83) 37%, | rgb(84,240,84) 69% | ); | background-image: -moz-linear-gradient( | center bottom, | rgb(43,194,83) 37%, | rgb(84,240,84) 69% | ); | background-image: -ms-linear-gradient( | center bottom, | rgb(43,194,83) 37%, | rgb(84,240,84) 69% | ); | background-image: -o-linear-gradient( | center bottom, | rgb(43,194,83) 37%, | rgb(84,240,84) 69% | ); | -webkit-box-shadow: | inset 0 2px 9px rgba(255,255,255,0.3), | inset 0 -2px 6px rgba(0,0,0,0.4); | -moz-box-shadow: | inset 0 2px 9px rgba(255,255,255,0.3), | inset 0 -2px 6px rgba(0,0,0,0.4); | position: relative; | overflow: hidden; |}""".stripMargin <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title id='title'>Scoverage Code Coverage</title> {plugins} <style> {css} </style> </head> } def packageOverview(pack: MeasuredPackage): Node = { <html> {header}<body style="font-family: monospace;"> {classesTable(pack.classes, addPath = false)} </body> </html> } def classesTable(classes: Iterable[MeasuredClass], addPath: Boolean): Node = { <table class="tablesorter table table-striped" style="font-size:13px"> <thead> <tr> <th> Class </th> <th> Source file </th> <th> Lines </th> <th> Methods </th> <th> Statements </th> <th> Invoked </th> <th> Coverage </th> <th> </th> <th> Branches </th> <th> Invoked </th> <th> Coverage </th> <th> </th> </tr> </thead> <tbody> {classes.toSeq.sortBy(_.simpleName) map classRow} </tbody> </table> } def classRow(klass: MeasuredClass): Node = { val filename: String = { val fileRelativeToSource = new File(relativeSource(klass.source) + ".html") val path = fileRelativeToSource.getParent val value = fileRelativeToSource.getName if (path.ne("")) { // (Normalise the pathSeparator to "/" in case we are running on Windows) fileRelativeToSource.toString.replace(File.separator, "/") } else { value } } val statement0f = Math.round(klass.statementCoveragePercent).toInt.toString val branch0f = Math.round(klass.branchCoveragePercent).toInt.toString val simpleClassName = klass.name.split('.').last <tr> <td> <a href={filename}> {simpleClassName} </a> </td> <td> {klass.statements.headOption.map(_.source.split(File.separatorChar).last).getOrElse("")} </td> <td> {klass.loc.toString} </td> <td> {klass.methodCount.toString} </td> <td> {klass.statementCount.toString} </td> <td> {klass.invokedStatementCount.toString} </td> <td> <div class="meter"> <span style={s"width: $statement0f%"}></span> </div> </td> <td> {klass.statementCoverageFormatted} % </td> <td> {klass.branchCount.toString} </td> <td> {klass.invokedBranchesCount.toString} </td> <td> <div class="meter"> <span style={s"width: $branch0f%"}></span> </div> </td> <td> {klass.branchCoverageFormatted} % </td> </tr> } def packageList(coverage: Coverage): Node = { <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title id='title'> Scoverage Code Coverage </title> {plugins} </head> <body style="font-family: monospace;"> <table class="tablesorter table table-striped" style="font-size: 13px"> <thead> <tr> <td> <a href="overview.html" target="mainFrame">All packages</a> </td> <td>{coverage.statementCoverageFormatted}%</td> </tr> </thead> <tbody> {coverage.packages.map(arg => <tr> <td> <a href={packageOverviewRelativePath(arg)} target="mainFrame">{arg.name}</a> </td> <td>{arg.statementCoverageFormatted}%</td> </tr> )} </tbody> </table> </body> </html> } def risks(coverage: Coverage, limit: Int) = { <table class="tablesorter table table-striped" style="font-size: 12px"> <thead> <tr> <th> Class </th> <th> Lines </th> <th> Methods </th> <th> Statements </th> <th> Statement Rate </th> <th> Branches </th> <th> Branch Rate </th> </tr> </thead> <tbody> {coverage.risks(limit).map(klass => <tr> <td> {klass.simpleName} </td> <td> {klass.loc.toString} </td> <td> {klass.methodCount.toString} </td> <td> {klass.statementCount.toString} </td> <td> {klass.statementCoverageFormatted} % </td> <td> {klass.branchCount.toString} </td> <td> {klass.branchCoverageFormatted} % </td> </tr>)} </tbody> </table> } def packages2(coverage: Coverage) = { val rows = coverage.packages.map(arg => { <tr> <td> {arg.name} </td> <td> {arg.invokedClasses.toString} / {arg.classCount} ( {arg.classCoverage.toString} %) </td> <td> {arg.invokedStatements.toString()} / {arg.statementCount} ( {arg.statementCoverageFormatted} %) </td> </tr> }) <table> {rows} </table> } def overview(coverage: Coverage): Node = { <html> {header}<body style="font-family: monospace;"> <div class="alert alert-info"> <b> SCoverage </b> generated at {new Date().toString} </div> <div class="overview"> <div class="stats"> {stats(coverage)} </div> <div> {classesTable(coverage.classes, addPath = true)} </div> </div> </body> </html> } def stats(coverage: Coverage): Node = { val statement0f = Math.round(coverage.statementCoveragePercent).toInt.toString val branch0f = Math.round(coverage.branchCoveragePercent).toInt.toString <table class="table"> <tr> <td> Lines of code: </td> <td> {coverage.loc.toString} </td> <td> Files: </td> <td> {coverage.fileCount.toString} </td> <td> Classes: </td> <td> {coverage.classCount.toString} </td> <td> Methods: </td> <td> {coverage.methodCount.toString} </td> </tr> <tr> <td> Lines per file </td> <td> {coverage.linesPerFileFormatted} </td> <td> Packages: </td> <td> {coverage.packageCount.toString} </td> <td> Clases per package: </td> <td> {coverage.avgClassesPerPackageFormatted} </td> <td> Methods per class: </td> <td> {coverage.avgMethodsPerClassFormatted} </td> </tr> <tr> <td> Total statements: </td> <td> {coverage.statementCount.toString} </td> <td> Invoked statements: </td> <td> {coverage.invokedStatementCount.toString} </td> <td> Total branches: </td> <td> {coverage.branchCount.toString} </td> <td> Invoked branches: </td> <td> {coverage.invokedBranchesCount.toString} </td> </tr> <tr> <td> Ignored statements: </td> <td> {coverage.ignoredStatementCount.toString} </td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td> Statement coverage: </td> <td> {coverage.statementCoverageFormatted} % </td> <td colspan="2"> <div class="meter"> <span style={s"width: $statement0f%"}></span> </div> </td> <td> Branch coverage: </td> <td> {coverage.branchCoverageFormatted} % </td> <td colspan="2"> <div class="meter"> <span style={s"width: $branch0f%"}></span> </div> </td> </tr> </table> } def plugins = { <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.20.1/css/theme.default.min.css" type="text/css"/> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.20.1/js/jquery.tablesorter.min.js"></script> <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" type="text/css"/> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script> <script type="text/javascript"> {xml.Unparsed("""$(document).ready(function() {$(".tablesorter").tablesorter();});""")} </script> } }
ssidorenko/scalac-scoverage-plugin
scalac-scoverage-plugin/src/main/scala/scoverage/report/ScoverageHtmlWriter.scala
Scala
apache-2.0
14,660
/* * Copyright 2014 IBM Corp. * * 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.ibm.spark.kernel.protocol.v5.content import com.ibm.spark.kernel.protocol.v5.KernelMessageContent import play.api.libs.json._ case class KernelStatus ( execution_state: String ) extends KernelMessageContent { override def content : String = Json.toJson(this)(KernelStatus.kernelStatusWrites).toString } object KernelStatus extends TypeString { implicit val kernelStatusReads = Json.reads[KernelStatus] implicit val kernelStatusWrites = Json.writes[KernelStatus] /** * Returns the type string associated with this object. * * @return The type as a string */ override def toTypeString: String = "status" } object KernelStatusBusy extends KernelStatus("busy") { override def toString(): String = { Json.toJson(this).toString } } object KernelStatusIdle extends KernelStatus("idle") { override def toString(): String = { Json.toJson(this).toString } }
yeghishe/spark-kernel
protocol/src/main/scala/com/ibm/spark/kernel/protocol/v5/content/KernelStatus.scala
Scala
apache-2.0
1,502
/* * Copyright (C) 2015 Cotiviti Labs (nexgen.admin@cotiviti.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 com.signalcollect.triplerush.sparql import org.scalatest.{ Finders, Matchers } import org.scalatest.fixture.{ FlatSpec, UnitFixture } import com.signalcollect.triplerush.TripleRush import com.signalcollect.triplerush.TestStore class FilterSpec extends FlatSpec with UnitFixture with Matchers { "ARQ FILTER" should "return no result when all variables are bound during an EXISTS check and the checked thing does not exist" in new TestStore { val sparql = """ SELECT ?r { ?r <http://p> "r2" FILTER EXISTS { <http://r1> <http://p> <http://r3> } }""" tr.addStringTriple("http://r1", "http://p", "\\"r2\\"") val results = Sparql(sparql) assert(!results.hasNext) } it should "return a result when all variables are bound during an EXISTS check and the checked thing does exist" in new TestStore { val sparql = """ SELECT ?r { ?r <http://p> "r2" FILTER EXISTS { <http://r1> <http://p> "r2" } }""" tr.addStringTriple("http://r1", "http://p", "\\"r2\\"") val results = Sparql(sparql) assert(results.hasNext) assert(results.next.get("r").toString == "http://r1") } it should "return a result when all variables are bound during a NOT EXISTS check and the checked thing does not exist" in new TestStore { val sparql = """ SELECT ?r { ?r <http://p> "r2" FILTER NOT EXISTS { <http://r1> <http://p> <http://r3> } }""" tr.addStringTriple("http://r1", "http://p", "\\"r2\\"") val results = Sparql(sparql) assert(results.hasNext) assert(results.next.get("r").toString == "http://r1") } it should "return no result when all variables are bound during a NOT EXISTS check and the checked thing does exist" in new TestStore { val sparql = """ SELECT ?r { ?r <http://p> "r2" FILTER NOT EXISTS { <http://r1> <http://p> "r2" } }""" tr.addStringTriple("http://r1", "http://p", "\\"r2\\"") val results = Sparql(sparql) assert(!results.hasNext) } it should "support filtering around dates (negative)" in new TestStore { val sparql = """ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> SELECT ?r ?start { ?r <http://p> ?start FILTER (xsd:dateTime(?start) > xsd:dateTime("2010-01-01T00:00:00")) }""" tr.addStringTriple("http://r1", "http://p", "\\"2009-01-01T00:00:00\\"") val results = Sparql(sparql) assert(!results.hasNext) } it should "support filtering around dates (positive)" in new TestStore { val sparql = """ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> SELECT ?r ?start { ?r <http://p> ?start FILTER (xsd:dateTime(?start) > xsd:dateTime("2010-01-01T00:00:00")) }""" tr.addStringTriple("http://r1", "http://p", "\\"2011-01-01T00:00:00\\"") val results = Sparql(sparql) assert(results.hasNext) } }
uzh/triplerush
src/test/scala/com/signalcollect/triplerush/sparql/FilterSpec.scala
Scala
apache-2.0
3,371
package org.hibernate.cache.rediscala.domain import javax.persistence._ import scala.beans.BeanProperty /** * org.hibernate.cache.rediscala.tests.domain.UuidItem * * @author 배성혁 sunghyouk.bae@gmail.com * @since 2014. 2. 21. 오후 4:12 */ @Entity @Access(AccessType.FIELD) class UuidItem extends Serializable { @Id @GeneratedValue @BeanProperty var id: String = _ @BeanProperty var name: String = _ @BeanProperty var description: String = _ }
debop/debop4s
hibernate-rediscala/src/test/scala/org/hibernate/cache/rediscala/domain/UuidItem.scala
Scala
apache-2.0
477
/* * Copyright 2014 Lars Edenbrandt * * 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 se.nimsa.sbx.app import java.security.KeyStore import java.security.SecureRandom import javax.net.ssl.KeyManagerFactory import javax.net.ssl.SSLContext import javax.net.ssl.TrustManagerFactory import com.typesafe.config.ConfigFactory import java.nio.file.Paths import java.nio.file.Files import akka.http.scaladsl.ConnectionContext // for SSL support (if enabled in config) object SslConfiguration { def sslContext(): SSLContext = try { val config = ConfigFactory.load() val keystorePath = config.getString("slicebox.ssl.keystore.path") val keystorePassword = config.getString("slicebox.ssl.keystore.password") val keyStore = KeyStore.getInstance("jks") keyStore.load(Files.newInputStream(Paths.get(keystorePath)), keystorePassword.toCharArray) val keyManagerFactory = KeyManagerFactory.getInstance("SunX509") keyManagerFactory.init(keyStore, keystorePassword.toCharArray) val trustManagerFactory = TrustManagerFactory.getInstance("SunX509") trustManagerFactory.init(keyStore) val context = SSLContext.getInstance("TLS") context.init(keyManagerFactory.getKeyManagers, trustManagerFactory.getTrustManagers, new SecureRandom) context } catch { case e: Exception => SSLContext.getDefault } def httpsContext = ConnectionContext.https(sslContext()) }
slicebox/slicebox
src/main/scala/se/nimsa/sbx/app/SslConfiguration.scala
Scala
apache-2.0
1,958
/* * 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.eval import java.util.concurrent.{CountDownLatch, TimeUnit} import minitest.SimpleTestSuite import monix.execution.exceptions.{CallbackCalledMultipleTimesException, DummyException} import monix.execution.schedulers.SchedulerService import monix.execution.{Callback, Scheduler, TestUtils} import scala.concurrent.duration._ import scala.util.{Failure, Success} object TaskCallbackSafetyJVMSuite extends SimpleTestSuite with TestUtils { val WORKERS = 10 val RETRIES = if (!isCI) 1000 else 100 test("Task.async has a safe callback") { runConcurrentCallbackTest(Task.async) } test("Task.async0 has a safe callback") { runConcurrentCallbackTest(f => Task.async0((_, cb) => f(cb))) } test("Task.asyncF has a safe callback") { runConcurrentCallbackTest(f => Task.asyncF(cb => Task(f(cb)))) } test("Task.cancelable has a safe callback") { runConcurrentCallbackTest(f => Task.cancelable { cb => f(cb); Task(()) }) } test("Task.cancelable0 has a safe callback") { runConcurrentCallbackTest(f => Task.cancelable0 { (_, cb) => f(cb); Task(()) }) } def runConcurrentCallbackTest(create: (Callback[Throwable, Int] => Unit) => Task[Int]): Unit = { def run(trigger: Callback[Throwable, Int] => Unit): Unit = { implicit val sc: SchedulerService = Scheduler.io("task-callback-safety") try { for (_ <- 0 until RETRIES) { val task = create { cb => runConcurrently(sc)(trigger(cb)) } val latch = new CountDownLatch(1) var effect = 0 task.runAsync { case Right(_) => effect += 1 latch.countDown() case Left(_) => effect += 1 latch.countDown() } await(latch) assertEquals(effect, 1) } } finally { sc.shutdown() assert(sc.awaitTermination(10.seconds), "io.awaitTermination") } } run { cb => cb.tryOnSuccess(1); () } run { cb => cb.tryApply(Right(1)); () } run { cb => cb.tryApply(Success(1)); () } run(cb => try cb.onSuccess(1) catch { case _: CallbackCalledMultipleTimesException => () }) run(cb => try cb(Right(1)) catch { case _: CallbackCalledMultipleTimesException => () }) run(cb => try cb(Success(1)) catch { case _: CallbackCalledMultipleTimesException => () }) val dummy = DummyException("dummy") run { cb => cb.tryOnError(dummy); () } run { cb => cb.tryApply(Left(dummy)); () } run { cb => cb.tryApply(Failure(dummy)); () } run(cb => try cb.onError(dummy) catch { case _: CallbackCalledMultipleTimesException => () }) run(cb => try cb(Left(dummy)) catch { case _: CallbackCalledMultipleTimesException => () }) run(cb => try cb(Failure(dummy)) catch { case _: CallbackCalledMultipleTimesException => () }) } def runConcurrently(sc: Scheduler)(f: => Unit): Unit = { val latchWorkersStart = new CountDownLatch(WORKERS) val latchWorkersFinished = new CountDownLatch(WORKERS) for (_ <- 0 until WORKERS) { sc.execute { () => latchWorkersStart.countDown() try { f } finally { latchWorkersFinished.countDown() } } } await(latchWorkersStart) await(latchWorkersFinished) } def await(latch: CountDownLatch): Unit = { val seconds = 10 assert(latch.await(seconds.toLong, TimeUnit.SECONDS), s"latch.await($seconds seconds)") } }
monifu/monifu
monix-eval/jvm/src/test/scala/monix/eval/TaskCallbackSafetyJVMSuite.scala
Scala
apache-2.0
4,263
import scala.quoted.* object Foo { inline def myMacro(): Unit = ${ aMacroImplementation } def aMacroImplementation(using Quotes): Expr[Unit] = throw new NoClassDefFoundError("this.is.not.a.Class") }
dotty-staging/dotty
tests/neg-macros/macro-class-not-found-2/Foo.scala
Scala
apache-2.0
211
package org.jetbrains.plugins.scala.lang.completion import com.intellij.codeInsight.completion.CompletionConfidence import com.intellij.psi.tree.IElementType import com.intellij.psi.{PsiElement, PsiFile} import com.intellij.util.ThreeState import org.jetbrains.plugins.scala.extensions.PsiFileExt import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes import org.jetbrains.plugins.scala.lang.psi.api.expr.ScReferenceExpression /** * @author Alexander Podkhalyuzin */ class ScalaCompletionConfidence extends CompletionConfidence { override def shouldSkipAutopopup(contextElement: PsiElement, psiFile: PsiFile, offset: Int): ThreeState = { if (offset != 0) { val elementType: IElementType = psiFile.findElementAt(offset - 1).getNode.getElementType elementType match { case ScalaTokenTypes.tINTEGER | ScalaTokenTypes.tFLOAT => return ThreeState.YES case ScalaTokenTypes.tSTRING | ScalaTokenTypes.tMULTILINE_STRING if psiFile.charSequence.charAt(offset - 1) == '$' => return ThreeState.NO case ScalaTokenTypes.tINTERPOLATED_STRING | ScalaTokenTypes.tINTERPOLATED_MULTILINE_STRING if psiFile.charSequence.charAt(offset - 1) == '.' => psiFile.findElementAt(offset).getPrevSibling match { case _: ScReferenceExpression => return ThreeState.NO case _ => } case _ => } } super.shouldSkipAutopopup(contextElement, psiFile, offset) } }
jastice/intellij-scala
scala/scala-impl/src/org/jetbrains/plugins/scala/lang/completion/ScalaCompletionConfidence.scala
Scala
apache-2.0
1,467
package com.outr.arango.api.model import io.circe.Json case class GetAdminTimeRc200(error: Boolean, code: Option[Long] = None, time: Option[Double] = None)
outr/arangodb-scala
api/src/main/scala/com/outr/arango/api/model/GetAdminTimeRc200.scala
Scala
mit
216
package ldap_client import com.unboundid.ldap.sdk._ case class LdapClient(host: String, port: Int) { def using[A, B](s: A)(f: A => B)(implicit ev: A => { def close(): Unit }): B = { try { f(s) } finally { s.close() } } def authenticate(bindDN: String, password: String): Boolean = { val bindResult = using(new LDAPConnection(host, port)) { connection => try { connection.bind(bindDN, password) } catch { case e: LDAPException => new BindResult(e) } } bindResult.getResultCode.equals(ResultCode.SUCCESS) } }
t-mochizuki/scala-study
akka-http-session-example/ldap-client/src/main/scala/ldap_client/LdapClient.scala
Scala
mit
591
/* * Copyright 2012 Sanjin Sehic * * 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.saserr.sleazy package console import java.util.{Collection, List => JList} import scala.collection.JavaConversions._ import scala.collection.immutable.Set import jline.{Completor, ConsoleReader} import jline.Terminal.{getTerminal => Terminal} trait JLine extends Console with Configuration { type Config <: JLineConfig trait JLineConfig { def prompt: String } private val reader = new ConsoleReader Terminal disableEcho() reader setBellEnabled true override def println(s: String): IO[Unit] = IO { reader.printString(s) reader.printNewline().pure[Option] } override def readLine(environment: Environment): IO[String] = IO { def read(): Option[String] = Option(reader.readLine(config.prompt)) val completor = new AutoCompletion(environment) if (reader addCompletor completor) { val result = read() reader removeCompletor completor result } else read() } private class AutoCompletion(environment: Environment) extends Completor { override def complete(buffer: String, cursor: Int, list: JList[_]) = { val candidates = list.asInstanceOf[JList[String]] if (buffer ne null) { val paren = buffer lastIndexOf '(' candidates addAll ( if (paren === -1) variables(buffer) else { val prefix = buffer substring (0, paren + 1) val completion = buffer substring (paren + 1) val space = completion lastIndexOf ' ' (if (space === -1) operations(completion) else { val prefix = completion substring (0, space + 1) val name = completion substring (space + 1) variables(name) map {prefix + _} }) map {prefix + _} } ) } if (candidates.size() === 1) candidates.set(0, s"${candidates.get(0)} ") if (candidates.isEmpty) -1 else 0 } private def variables(prefix: String): Set[String] = for { variable <- environment.names name = variable.name if name startsWith prefix value <- environment.find(variable) if !value.is[Operation[Any]] } yield name private def operations(prefix: String): Set[String] = for { operation <- environment.names name = operation.name if name startsWith prefix value <- environment.find(operation) if value.is[Operation[Any]] } yield name } }
saserr/sleazy
src/scala/console/JLine.scala
Scala
apache-2.0
3,062
package org.mitre.mandolin.mselect.standalone import org.mitre.mandolin.app.AppMain import org.mitre.mandolin.mlp._ import org.mitre.mandolin.mselect._ import org.mitre.mandolin.transform.FeatureExtractor import org.mitre.mandolin.util.LocalIOAssistant class ModelSelector(val msb: MandolinModelSpaceBuilder, trainFile: String, testFile: Option[String], numWorkers: Int, scoreSampleSize: Int, acqFunRelearnSize: Int, totalEvals: Int, appSettings: Option[MandolinMLPSettings with ModelSelectionSettings] = None, useHyperband: Boolean = false, hyperMix: Float = 1.0f, hyperMax: Int = 81) extends ModelSelectionDriver(trainFile, testFile, numWorkers, scoreSampleSize, acqFunRelearnSize, totalEvals, useHyperband, hyperMix, hyperMax) { def this(_msb: MandolinModelSpaceBuilder, appSettings: MandolinMLPSettings with ModelSelectionSettings) = { this(_msb, appSettings.trainFile.get, appSettings.testFile, appSettings.numWorkers, appSettings.scoreSampleSize, appSettings.updateFrequency, appSettings.totalEvals, Some(appSettings), appSettings.useHyperband, appSettings.hyperbandMixParam, appSettings.numEpochs) } val acqFun = appSettings match { case Some(s) => s.acquisitionFunction case None => new ExpectedImprovement } val (fe: FeatureExtractor[String, MMLPFactor], nnet: ANNetwork, numInputs: Int, numOutputs: Int, sparse: Boolean) = { val settings = appSettings.getOrElse((new MandolinMLPSettings).withSets(Seq( ("mandolin.trainer.train-file", trainFile), ("mandolin.trainer.test-file", testFile) ))) val (trainer, nn) = MMLPTrainerBuilder(settings) val featureExtractor = trainer.getFe featureExtractor.getAlphabet.ensureFixed // fix the alphabet val numInputs = nn.inLayer.getNumberOfOutputs // these will then be gathered dynamically from the trainFile val numOutputs = nn.outLayer.getNumberOfOutputs // ditto val isSparse = nn.inLayer.ltype.designate match { case SparseInputLType => true case _ => false } (featureExtractor, nn, numInputs, numOutputs, isSparse) } val ms: ModelSpace = msb.build(numInputs, numOutputs, sparse, appSettings) val ev = { val io = new LocalIOAssistant val trVecs = (io.readLines(trainFile) map { l => fe.extractFeatures(l) } toVector) val tstVecs = testFile map { tf => (io.readLines(tf) map { l => fe.extractFeatures(l) } toVector) } new LocalModelEvaluator(trVecs, tstVecs) } } object ModelSelector extends AppMain { def main(args: Array[String]): Unit = { val appSettings = new MandolinMLPSettings(args) with ModelSelectionSettings val builder = new MandolinModelSpaceBuilder(appSettings.modelSpace) val selector = new ModelSelector(builder, appSettings) selector.search() } }
project-mandolin/mandolin
mandolin-core/src/main/scala/org/mitre/mandolin/mselect/standalone/ModelSelector.scala
Scala
apache-2.0
2,827
/* * ____ ____ _____ ____ ___ ____ * | _ \\ | _ \\ | ____| / ___| / _/ / ___| Precog (R) * | |_) | | |_) | | _| | | | | /| | | _ Advanced Analytics Engine for NoSQL Data * | __/ | _ < | |___ | |___ |/ _| | | |_| | Copyright (C) 2010 - 2013 SlamData, Inc. * |_| |_| \\_\\ |_____| \\____| /__/ \\____| All Rights Reserved. * * 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.precog.bifrost package mongo import com.precog.common._ import com.precog.common.jobs._ import com.precog.common.security._ import com.precog.common.accounts._ import com.precog.standalone._ import com.precog.yggdrasil._ import com.precog.yggdrasil.actor._ import com.precog.yggdrasil.jdbm3._ import com.precog.yggdrasil.metadata._ import com.precog.yggdrasil.serialization._ import com.precog.yggdrasil.table._ import com.precog.yggdrasil.table.mongo._ import com.precog.yggdrasil.util._ import com.precog.mimir._ import com.precog.muspelheim._ import com.precog.util.FilesystemFileOps import com.weiglewilczek.slf4s.Logging import blueeyes.json._ import blueeyes.json.serialization._ import DefaultSerialization._ import akka.actor.ActorSystem import akka.dispatch._ import akka.pattern.ask import akka.util.duration._ import akka.util.Duration import akka.util.Timeout import com.mongodb.{Mongo, MongoURI} import org.streum.configrity.Configuration import org.slf4j.{LoggerFactory, MDC} import java.io.File import java.nio.CharBuffer import scalaz._ import scalaz.Validation._ import scalaz.effect.IO import scalaz.syntax.monad._ import scalaz.syntax.bifunctor._ import scalaz.syntax.std.either._ import scala.collection.JavaConverters._ class MongoQueryExecutorConfig(val config: Configuration) extends StandaloneQueryExecutorConfig with MongoColumnarTableModuleConfig { val logPrefix = "mongo" def mongoServer: String = config[String]("mongo.server", "localhost:27017") def dbAuthParams = config.detach("mongo.dbAuth") def includeIdField: Boolean = config[Boolean]("include_ids", false) } object MongoQueryExecutor { def apply(config: Configuration, jobManager: JobManager[Future], jobActorSystem: ActorSystem)(implicit ec: ExecutionContext, M: Monad[Future]): Platform[Future, StreamT[Future, Slice]] = { new MongoQueryExecutor(new MongoQueryExecutorConfig(config), jobManager, jobActorSystem) } } class MongoQueryExecutor(val yggConfig: MongoQueryExecutorConfig, val jobManager: JobManager[Future], val jobActorSystem: ActorSystem)(implicit val executionContext: ExecutionContext, val M: Monad[Future]) extends StandaloneQueryExecutor with MongoColumnarTableModule with Logging { platform => type YggConfig = MongoQueryExecutorConfig val includeIdField = yggConfig.includeIdField trait TableCompanion extends MongoColumnarTableCompanion object Table extends TableCompanion { var mongo: Mongo = _ val dbAuthParams = yggConfig.dbAuthParams.data } lazy val storage = new MongoStorageMetadataSource(Table.mongo) def userMetadataView(apiKey: APIKey) = storage.userMetadataView(apiKey) Table.mongo = new Mongo(new MongoURI(yggConfig.mongoServer)) def shutdown() = Future { Table.mongo.close() true } val metadataClient = new MetadataClient[Future] { def size(userUID: String, path: Path): Future[Validation[String, JNum]] = Future { path.elements.toList match { case dbName :: collectionName :: Nil => val db = Table.mongo.getDB(dbName) success(JNum(db.getCollection(collectionName).getStats.getLong("count"))) case _ => success(JNum(0)) } }.onFailure { case t => logger.error("Failure during size", t) } def browse(userUID: String, path: Path): Future[Validation[String, JArray]] = Future { path.elements.toList match { case Nil => val dbs = Table.mongo.getDatabaseNames.asScala.toList // TODO: Poor behavior on Mongo's part, returning database+collection names // See https://groups.google.com/forum/#!topic/mongodb-user/HbE5wNOfl6k for details val finalNames = dbs.foldLeft(dbs.toSet) { case (acc, dbName) => acc.filterNot { t => t.startsWith(dbName) && t != dbName } }.toList.sorted Success(finalNames.map {d => d + "/" }.serialize.asInstanceOf[JArray]) case dbName :: Nil => val db = Table.mongo.getDB(dbName) Success(if (db == null) JArray(Nil) else db.getCollectionNames.asScala.map {d => d + "/" }.toList.sorted.serialize.asInstanceOf[JArray]) case dbName :: collectionName :: Nil => Success(JArray(Nil)) case _ => Failure("MongoDB paths have the form /databaseName/collectionName; longer paths are not supported.") } }.onFailure { case t => logger.error("Failure during browse", t) } def structure(userUID: String, path: Path, cpath: CPath): Future[Validation[String, JObject]] = Promise.successful ( Success(JObject(Map("children" -> JArray.empty, "types" -> JObject.empty))) // TODO: How to implement this? ) def currentVersion(apiKey: APIKey, path: Path) = Promise.successful(None) def currentAuthorities(apiKey: APIKey, path: Path) = Promise.successful(None) } } // vim: set ts=4 sw=4 et:
precog/platform
miklagard/mongo/src/main/scala/com/precog/shard/mongo/MongoQueryExecutor.scala
Scala
agpl-3.0
6,014
/* * Copyright 2015-2016 IBM Corporation * * 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 whisk.core.dispatcher import scala.concurrent.Future import whisk.common.TransactionId import whisk.core.connector.{ ActivationMessage => Message } /** * Abstract base class for a handler for a connector (e.g., Kafka) message. */ abstract class MessageHandler(val name: String) { /** * Runs handler for a Kafka message. This method is run inside a future. * If the method fails with an exception, the exception completes * the wrapping future within which the method is run. * * @param msg the Message object to process * @param transid the transaction id for the Kafka message * @return Future that executes the handler */ def onMessage(msg: Message)(implicit transid: TransactionId): Future[Any] }
CrowdFlower/incubator-openwhisk
core/invoker/src/main/scala/whisk/core/dispatcher/MessageHandler.scala
Scala
apache-2.0
1,362
/* * Copyright 2017 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.ct.accounts.frs102.boxes import org.joda.time.LocalDate import org.mockito.Mockito._ import org.scalatest.mock.MockitoSugar import org.scalatest.{BeforeAndAfter, Matchers, WordSpec} import uk.gov.hmrc.ct.accounts.{MockFrs102AccountsRetriever, AccountsMoneyValidationFixture, AC205} import uk.gov.hmrc.ct.accounts.frs102.retriever.Frs102AccountsBoxRetriever import uk.gov.hmrc.ct.box.CtValidation class AC5052CSpec extends WordSpec with MockitoSugar with Matchers with MockFrs102AccountsRetriever with AccountsMoneyValidationFixture[Frs102AccountsBoxRetriever] with BeforeAndAfter { before { when(boxRetriever.ac52).thenReturn(AC52(Some(STANDARD_MAX + 1))) when(boxRetriever.ac53).thenReturn(AC53(Some(STANDARD_MAX + 1))) } testAccountsMoneyValidationWithMin("AC5052C", minValue = 0, AC5052C) "pass the validation if AC52 and AC205 are set" in { when(boxRetriever.ac52()).thenReturn(AC52(Some(123))) when(boxRetriever.ac205()).thenReturn(AC205(Some(LocalDate.parse("2016-01-01")))) AC5052C(Some(4)).validate(boxRetriever) shouldBe Set.empty } "fail validation when greater than AC53" in { when(boxRetriever.ac52()).thenReturn(AC52(Some(123))) when(boxRetriever.ac53()).thenReturn(AC53(Some(30))) AC5052C(Some(35)).validate(boxRetriever) shouldBe Set(CtValidation(Some("AC5052C"), "error.AC5052C.mustBeLessOrEqual.AC53")) } "pass validation when equals AC52" in { when(boxRetriever.ac52()).thenReturn(AC52(Some(123))) when(boxRetriever.ac53()).thenReturn(AC53(Some(30))) AC5052C(Some(30)).validate(boxRetriever) shouldBe Set.empty } "pass validation when less than AC52" in { when(boxRetriever.ac52()).thenReturn(AC52(Some(123))) when(boxRetriever.ac53()).thenReturn(AC53(Some(30))) AC5052C(Some(25)).validate(boxRetriever) shouldBe Set.empty } }
pncampbell/ct-calculations
src/test/scala/uk/gov/hmrc/ct/accounts/frs102/boxes/AC5052CSpec.scala
Scala
apache-2.0
2,457
type Foo given myFoo1 as (Foo { type X = Int }) = ??? type Bar = Foo { type X = Int } given myFoo2 as Bar = ???
som-snytt/dotty
tests/pos/i8284.scala
Scala
apache-2.0
112
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.execution.benchmark import org.apache.spark.benchmark.Benchmark import org.apache.spark.sql.{DataFrame, SaveMode} import org.apache.spark.sql.internal.SQLConf /** * Synthetic benchmark for nested fields predicate push down performance for Parquet datasource. * To run this benchmark: * {{{ * 1. without sbt: * bin/spark-submit --class <this class> --jars <spark core test jar> <sql core test jar> * 2. build/sbt "sql/test:runMain <this class>" * 3. generate result: * SPARK_GENERATE_BENCHMARK_FILES=1 build/sbt "sql/test:runMain <this class>" * Results will be written to "benchmarks/ParquetNestedPredicatePushDownBenchmark-results.txt". * }}} */ object ParquetNestedPredicatePushDownBenchmark extends SqlBasedBenchmark { private val N = 100 * 1024 * 1024 private val NUMBER_OF_ITER = 10 private val df: DataFrame = spark .range(1, N, 1, 4) .toDF("id") .selectExpr("id", "STRUCT(id x, STRUCT(CAST(id AS STRING) z) y) nested") .sort("id") private def addCase( benchmark: Benchmark, inputPath: String, enableNestedPD: String, name: String, withFilter: DataFrame => DataFrame): Unit = { val loadDF = spark.read.parquet(inputPath) benchmark.addCase(name) { _ => withSQLConf((SQLConf.NESTED_PREDICATE_PUSHDOWN_FILE_SOURCE_LIST.key, enableNestedPD)) { withFilter(loadDF).noop() } } } private def createAndRunBenchmark(name: String, withFilter: DataFrame => DataFrame): Unit = { withTempPath { tempDir => val outputPath = tempDir.getCanonicalPath df.write.mode(SaveMode.Overwrite).parquet(outputPath) val benchmark = new Benchmark(name, N, NUMBER_OF_ITER, output = output) addCase( benchmark, outputPath, enableNestedPD = "", "Without nested predicate Pushdown", withFilter) addCase( benchmark, outputPath, enableNestedPD = "parquet", "With nested predicate Pushdown", withFilter) benchmark.run() } } /** * Benchmark for sorted data with a filter which allows to filter out all the row groups * when nested fields predicate push down enabled */ def runLoadNoRowGroupWhenPredicatePushedDown(): Unit = { createAndRunBenchmark("Can skip all row groups", _.filter("nested.x < 0")) } /** * Benchmark with a filter which allows to load only some row groups * when nested fields predicate push down enabled */ def runLoadSomeRowGroupWhenPredicatePushedDown(): Unit = { createAndRunBenchmark("Can skip some row groups", _.filter("nested.x = 100")) } /** * Benchmark with a filter which still requires to * load all the row groups on sorted data to see if we introduce too much * overhead or not if enable nested predicate push down. */ def runLoadAllRowGroupsWhenPredicatePushedDown(): Unit = { createAndRunBenchmark("Can skip no row groups", _.filter(s"nested.x >= 0 and nested.x <= $N")) } override def runBenchmarkSuite(mainArgs: Array[String]): Unit = { runLoadNoRowGroupWhenPredicatePushedDown() runLoadSomeRowGroupWhenPredicatePushedDown() runLoadAllRowGroupsWhenPredicatePushedDown() } }
witgo/spark
sql/core/src/test/scala/org/apache/spark/sql/execution/benchmark/ParquetNestedPredicatePushDownBenchmark.scala
Scala
apache-2.0
4,045
package gr.jkl.playUid import play.api.{ Plugin, Application, UnexpectedException } import gr.jkl.uid.{ Scheme, Generator } import scala.util.{ Try, Success, Failure } /** Plugin for Id generation and handling. */ class UidPlugin(app: Application) extends Plugin { private[this] def getLong(path: String) = Try(app.configuration.underlying.getLong(path)) private[playUid] val (scheme, generator): (Scheme, Generator) = (for { tb <- getLong("uid.timestampBits") nb <- getLong("uid.nodeBits") sb <- getLong("uid.sequenceBits") ep <- getLong("uid.epoch") no <- getLong("uid.node") sc <- Try(Scheme(tb, nb, sb, ep)) ge <- Try(Generator(no)(sc)) } yield (sc, ge)) match { case Success(p) => p case Failure(e) => throw UnexpectedException(Some("Invalid configuration for UidPlugin. Edit your conf/application.conf file with valid values for the following fields: uid.timestampBits, uid.nodeBits, uid.sequenceBits, uid.epoch & uid.node."), Some(e)) } } private[playUid] object UidPlugin { private[playUid] def scheme(implicit app: Application) = current.scheme private[playUid] def generator(implicit app: Application) = current.generator private[this] def current(implicit app: Application): UidPlugin = app.plugin[UidPlugin] match { case Some(plugin) => plugin case _ => throw UnexpectedException(Some("The UidPlugin has not been initialized! Please edit your conf/play.plugins file and add the following line: '1000:gr.jkl.playUid.UidPlugin'.")) } }
nevang/play-uid
src/main/scala/gr/jkl/playUid/UidPlugin.scala
Scala
bsd-2-clause
1,525
package dk.itu.wsq.cases.spanningtree import dk.itu.wsq._ import dk.itu.wsq.queue._ object SpanningTreeBenchmark { import com.typesafe.config._ def apply(workers: Int, seed: Long, conf: Config): Benchmark = { val nodes = conf.getInt("benchmarks.spanning.nodes") val branching = conf.getInt("benchmarks.spanning.branching") SpanningTreeBenchmark(workers, nodes, branching, seed) } } case class SpanningTreeBenchmark(workers: Int, nodes: Int, branching: Int, seed: Long) extends Benchmark { private val in = GraphBuilder(nodes, branching, seed) private def resetGraph(nodes: Set[SpanningTreeNode]) = { nodes.foreach(n => n.reset()) nodes } def name = s"Spanning tree with $workers workers and graph with $nodes nodes and branching factor $branching" def run(queueImpl: QueueImpl): Double = { resetGraph(in) val wp = new SpanningTreeWorkerPool(workers, in.size, queueImpl) val (t, _) = time(wp.run(in.head)) t } def worksWith: Seq[QueueImpl] = allQueueImpls override def toString(): String = "Spanning Tree" }
christianharrington/WorkStealingQueues
Scala/src/main/scala/dk/itu/wsq/cases/spanningtree/SpanningTreeBenchmark.scala
Scala
unlicense
1,086
/* * 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 controllers.businessmatching import javax.inject.{Inject, Singleton} import connectors.DataCacheConnector import controllers.{AmlsBaseController, CommonPlayDependencies} import forms.{EmptyForm, Form2, InvalidForm, ValidForm} import models.Country import models.businesscustomer.ReviewDetails import models.businessmatching.{BusinessMatching, ConfirmPostcode} import play.api.mvc.MessagesControllerComponents import utils.AuthAction import views.html.businessmatching.confirm_postcode import scala.concurrent.Future @Singleton class ConfirmPostCodeController @Inject()(authAction: AuthAction, val ds: CommonPlayDependencies, val dataCacheConnector: DataCacheConnector, val cc: MessagesControllerComponents, confirm_postcode: confirm_postcode) extends AmlsBaseController(ds, cc) { def get() = authAction.async { implicit request => Future.successful(Ok(confirm_postcode(EmptyForm))) } def updateReviewDetails(reviewDetails: Option[ReviewDetails], postCodeModel: ConfirmPostcode): Option[models.businesscustomer.ReviewDetails] = { reviewDetails.fold[Option[ReviewDetails]](None) { dtls => val updatedAddr = dtls.businessAddress.copy(postcode = Some(postCodeModel.postCode), country = Country("United Kingdom", "GB")) Some(dtls.copy(businessAddress = updatedAddr)) } } def post() = authAction.async { implicit request => { Form2[ConfirmPostcode](request.body) match { case f: InvalidForm => Future.successful(BadRequest(confirm_postcode(f))) case ValidForm(_, data) => for { bm <- dataCacheConnector.fetch[BusinessMatching](request.credId, BusinessMatching.key) _ <- dataCacheConnector.save[BusinessMatching](request.credId, BusinessMatching.key, bm.copy(reviewDetails = updateReviewDetails(bm.reviewDetails, data))) } yield { Redirect(routes.BusinessTypeController.get) } } } } }
hmrc/amls-frontend
app/controllers/businessmatching/ConfirmPostCodeController.scala
Scala
apache-2.0
2,769
/* * ****************************************************************************** * * Copyright (C) 2013 Christopher Harris (Itszuvalex) * * Itszuvalex@gmail.com * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************** */ package com.itszuvalex.femtocraft.power.blocks import com.itszuvalex.femtocraft.Femtocraft import cpw.mods.fml.relauncher.{Side, SideOnly} import net.minecraft.block.material.Material import net.minecraft.client.renderer.texture.IIconRegister import net.minecraft.util.IIcon import net.minecraftforge.fluids.BlockFluidClassic /** * Created by Christopher Harris (Itszuvalex) on 8/2/14. */ class BlockFluidCooledMoltenSalt extends BlockFluidClassic(Femtocraft.fluidCooledMoltenSalt, Material.water) { var stillIcon : IIcon = null var flowingIcon: IIcon = null setBlockName("FluidCooledMoltenSalt") setCreativeTab(Femtocraft.femtocraftTab) override def getIcon(side: Int, meta: Int) = if (side == 0 || side == 1) stillIcon else flowingIcon @SideOnly(Side.CLIENT) override def registerBlockIcons(par1IconRegister: IIconRegister) { blockIcon = {stillIcon = par1IconRegister.registerIcon(Femtocraft.ID.toLowerCase + ":" + "BlockCooledMoltenSalt_still"); stillIcon} flowingIcon = par1IconRegister.registerIcon(Femtocraft.ID.toLowerCase + ":" + "BlockCooledMoltenSalt_flow") } }
Itszuvalex/Femtocraft-alpha-1
src/main/java/com/itszuvalex/femtocraft/power/blocks/BlockFluidCooledMoltenSalt.scala
Scala
gpl-2.0
2,122
/* Copyright 2015 David R. Pugh, J. Doyne Farmer, and Dan F. Tang 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 markets.orders trait OrderLike
ScalABM/markets-sandbox
src/main/scala-2.11/markets/orders/OrderLike.scala
Scala
apache-2.0
634
package com.github.jmcs.domain.binaryexpression import com.github.jmcs.domain.Expression import com.github.jmcs.domain.BinaryExpression /** * Created with IntelliJ IDEA. * User: Marcelo * Date: 30/07/13 * Time: 22:46 * To change this template use File | Settings | File Templates. */ class DivisionExpression(override val left: Expression, override val right: Expression) extends BinaryExpression(left, right) { def evaluate(): Any = useCache(() => left.evaluate.asInstanceOf[BigDecimal] / right.evaluate.asInstanceOf[BigDecimal]) def getOperationSymbol = "/" }
MarceloPortilho/jmc-scala
src/main/java/com/github/jmcs/domain/binaryexpression/DivisionExpression.scala
Scala
apache-2.0
596
package org.programmiersportgruppe.redis.protocol import akka.util.ByteString import org.programmiersportgruppe.redis._ trait ReplyReconstructor { def process(data: ByteString)(handleReply: RValue => _): Unit }
programmiersportgruppe/akre
protocol/src/main/scala/org/programmiersportgruppe/redis/protocol/ReplyReconstructor.scala
Scala
mit
217
package com.sksamuel.elastic4s.searches.aggs import com.sksamuel.elastic4s.script.ScriptDefinition import org.elasticsearch.search.aggregations.AggregationBuilders import org.elasticsearch.search.aggregations.bucket.range.date.DateRangeAggregationBuilder case class DateRangeAggregation(name: String) extends AggregationDefinition { type B = DateRangeAggregationBuilder val builder: B = AggregationBuilders.dateRange(name) def field(field: String) = { builder.field(field) this } def script(script: ScriptDefinition) = { builder.script(script.build) this } def missing(missing: String) = { builder.missing(missing) this } def range(from: String, to: String): DateRangeAggregation = { builder.addRange(from, to) this } def range(key: String, from: String, to: String): DateRangeAggregation = { builder.addRange(key, from, to) this } def range(from: Long, to: Long): DateRangeAggregation = { builder.addRange(from, to) this } def range(key: String, from: Long, to: Long): DateRangeAggregation = { builder.addRange(key, from, to) this } def unboundedFrom(from: String): DateRangeAggregation = { builder.addUnboundedFrom(from) this } def unboundedTo(to: String): DateRangeAggregation = { builder.addUnboundedTo(to) this } def unboundedFrom(key: String, from: String): DateRangeAggregation = { builder.addUnboundedFrom(key, from) this } def unboundedTo(key: String, to: String): DateRangeAggregation = { builder.addUnboundedTo(key, to) this } def format(fmt: String): DateRangeAggregation = { builder.format(fmt) this } }
ulric260/elastic4s
elastic4s-core/src/main/scala/com/sksamuel/elastic4s/searches/aggs/DateRangeAggregation.scala
Scala
apache-2.0
1,682
package edu.stanford.graphics.shapenet.common import com.jme3.math.Vector3f import edu.stanford.graphics.shapenet.jme3.loaders.AssetGroups import edu.stanford.graphics.shapenet.{SizeBy, Constants} import edu.stanford.graphics.shapenet.util.StringUtils import scala.collection.mutable case class DefaultModelInfo(unit: Double = Constants.DEFAULT_MODEL_UNIT, up: Vector3f = Constants.DEFAULT_MODEL_UP, front: Vector3f = Constants.DEFAULT_MODEL_FRONT, categories: Seq[String] = Seq()) /** * ModelInfo * * @author Angel Chang */ class ModelInfo( val fullId: String = null, val minPoint: Vector3f = null, val maxPoint: Vector3f = null, var rawbbdims: Vector3f = null, var name: String = null, var tags: Array[String] = null, val allCategory: Array[String] = null, val category0: Array[String] = null, val scenes: Array[String] = null, val datasets: Array[String] = null, val unit0: Option[Double] = None, val up0: Option[Vector3f] = None, val front0: Option[Vector3f] = None, val defaults: DefaultModelInfo// = DefaultModelInfo() ) { var unit = unit0.getOrElse(defaults.unit) var up = up0.getOrElse(defaults.up) var front = front0.getOrElse(defaults.front) // Computed statistics var materials: Seq[(String,Double)] = null // What is this model made of var materialsCategory: String = null // Category used for materials var isContainer: Option[Boolean] = None var solidVolume: Option[Double] = None var surfaceVolume: Option[Double] = None var supportSurfArea: Option[Double] = None var volume: Option[Double] = None var weight: Option[Double] = None var staticFrictionForce: Option[Double] = None // Attributes var attributes = new mutable.ArrayBuffer[(String,String)]() // Text info var description: String = null var uploadDate: String = null var author: String = null lazy val category: Array[String] = allCategory.filterNot(s => s.contains("_")) lazy val modelSets: Array[String] = allCategory.filter(s => s.contains("_")) var metadata: Map[String,String] = null // WordNet var wnsynset: Array[String] = null var wnhypersynset: Array[String] = null def hasCategory(c: String): Option[Boolean] = { var res: Option[Boolean] = None if (category != null && !category.isEmpty) res = Option(category.contains(c)) res } def hasCategoryRelaxed(c: String): Option[Boolean] = { var res: Option[Boolean] = None if (category != null && !category.isEmpty) res = Option(category.contains(StringUtils.toCamelCase(c))) if (!res.getOrElse(false)) { if (category0 != null && !category0.isEmpty) res = Option(category0.contains(StringUtils.toLowercase(c))) } res } def relaxedCategory: Seq[String] = { val cats = if (source == "wss") { category ++ category0.map( x => StringUtils.toCamelCase(x)) } else category cats.distinct } def basicCategory: String = { val cat0 = if (source == "wss" && category0 != null && !category0.isEmpty) category0.head else null val cat1 = if (category != null && !category.isEmpty) category.head else null if (cat0 != null && cat1 != null) { if (cat0.length < cat1.length) cat0 else cat1 } else if (cat0 != null) cat0 else if (cat1 != null) cat1 else null } def hasAttribute(attrType: String, attrValue: String): Option[Boolean] = { var res: Option[Boolean] = None val filtered = getAttributes(attrType) if (!filtered.isEmpty) res = Option(filtered.contains((attrType,attrValue))) res } def getAttributes(attrType:String): Seq[(String,String)] = { attributes.filter( p => attrType.equals(p._1)) } def getAttributes(): Seq[(String,String)] = { attributes } def setMetadata(name: String, value: String): Option[String] = { if (metadata == null) { metadata = Map(name -> value) None } else { val prev = metadata.get(name) metadata = metadata + (name -> value) prev } } def getMetadata(name:String): Option[String] = { metadata.get(name) } def getMetadata(): Map[String,String] = { metadata } def trueunit: Double = { unit } def bbdims: Vector3f = { rawbbdims } def physdims: Vector3f = bbdims.mult(unit.toFloat) def size(sizeBy: SizeBy.Value): Double = { val dims: Vector3f = bbdims unit * SizeBy.sizeWithZUp(sizeBy, dims) } def logSize(sizeBy: SizeBy.Value): Double = { math.log(size(sizeBy)) } def defaultSize(sizeBy: SizeBy.Value): Double = { val dims: Vector3f = bbdims Constants.DEFAULT_MODEL_UNIT * SizeBy.sizeWithZUp(sizeBy, dims) } def source: String = { if (fullId == null) return null val pos = fullId.indexOf('.') if (pos >= 0) fullId.substring(0, pos) else null } def id: String = { if (fullId == null) return null val pos = fullId.indexOf('.') if (pos >= 0) fullId.substring(pos+1) else fullId } def isRoom: Boolean = { hasCategory("Room").getOrElse(false) } def isBad: Boolean = { modelSets.contains("_BAD") } def toDetailedString(): String = { val sb = new StringBuilder() sb.append("fullId: " + fullId + "\\n") if (category != null) { sb.append("category: " + category.mkString(",") + "\\n") } sb.toString } override def toString(): String = { fullId } }
ShapeNet/shapenet-viewer
src/main/scala/edu/stanford/graphics/shapenet/common/ModelInfo.scala
Scala
mit
5,646
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** @author John Miller * @version 1.2 * @date Mon Sep 7 15:05:06 EDT 2009 * @see LICENSE (MIT style license file). */ package scalation.process import scala.collection.mutable.ListBuffer import scalation.animation.CommandType._ import scalation.scala2d.Ellipse import scalation.scala2d.Colors._ import scalation.util.Monitor.trace //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `Sink` class is used to terminate entities `SimActor`s when they are finished. * @param name the name of the sink * @param at the location of the sink (x, y, w, h) */ class Sink (name: String, at: Array [Double]) extends Component { initComponent (name, at) //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Auxiliary constructor that uses defaults for width 'w' and height 'h'. * @param name the name of the sink * @param xy the (x, y) coordinates for the top-left corner of the sink. */ def this (name: String, xy: Tuple2 [Double, Double]) { this (name, Array (xy._1, xy._2, 20.0, 20.0)) } // constructor //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Tell the animation engine to display this Sink. */ def display () { director.animate (this, CreateNode, darkred, Ellipse (), at) } // display //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Leave the model, effectively terminating the entity `SimActor`. */ def leave () { val actor = director.theActor tally (director.clock - actor.arrivalT) trace (this, "terminates", actor, director.clock) director.animate (actor, MoveToken, null, null, Array (at(0) + DIAM, at(1) + at(3) / 2.0 - RAD)) actor.yieldToDirector (true) // yield and terminate } // leave } // Sink class //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `Sink` companion object provides a builder method for sinks. */ object Sink { //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Create a sink using defaults for width 'w' and height 'h'. * @param name the name of the sink * @param xy the (x, y) coordinates for the top-left corner of the sink. */ def apply (name: String, xy: Tuple2 [Int, Int]): Sink = { new Sink (name, Array (xy._1.toDouble, xy._2.toDouble, 20.0, 20.0)) } // apply //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Create a group of related sinks using defaults for width 'w' and height 'h'. * @param xy the (x, y) coordinates for the top-left corner of the reference sink. * @param snk repeated sink specific info: name, offset */ def group (xy: Tuple2 [Int, Int], snk: Tuple2 [String, Tuple2 [Int, Int]]*): List [Sink] = { val sinkGroup = new ListBuffer [Sink] () for (s <- snk) sinkGroup += Sink (s._1, (xy._1 + s._2._1, xy._2 + s._2._2)) sinkGroup.toList } // group } // Sink object
NBKlepp/fda
scalation_1.2/src/main/scala/scalation/process/Sink.scala
Scala
mit
3,267
def isEq[T](x:T,y:T)(implicit e: Eq[T]): Boolean = e.isEq(x,y)
grzegorzbalcerek/scala-exercises
Eq/stepEqIsEq.scala
Scala
bsd-2-clause
63
/* * Scala.js (https://www.scala-js.org/) * * Copyright EPFL. * * Licensed under Apache License 2.0 * (https://www.apache.org/licenses/LICENSE-2.0). * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package org.scalajs.testsuite.compiler import org.junit.Test import org.junit.Assert._ import org.junit.Assume._ import java.{util => ju} import org.scalajs.testsuite.utils.Platform._ class DefaultMethodsTest { @Test def canOverrideDefaultMethod(): Unit = { assumeFalse("Affected by https://github.com/scala/bug/issues/10609", executingInJVM && scalaVersion == "2.11.12") var counter = 0 class SpecialIntComparator extends ju.Comparator[Int] { def compare(o1: Int, o2: Int): Int = o1.compareTo(o2) override def reversed(): ju.Comparator[Int] = { counter += 1 super.reversed() } } val c = new SpecialIntComparator assertTrue(c.compare(5, 7) < 0) assertEquals(0, counter) val reversed = c.reversed() assertEquals(1, counter) assertTrue(reversed.compare(5, 7) > 0) } @Test def reflectiveCallDefaultMethod(): Unit = { import scala.language.reflectiveCalls class ReflectiveCallIntComparator extends ju.Comparator[Int] { def compare(o1: Int, o2: Int): Int = o1.compareTo(o2) } val c = new ReflectiveCallIntComparator val c2: { def reversed(): ju.Comparator[Int] } = c val reversed = c2.reversed() assertTrue(reversed.compare(5, 7) > 0) } }
scala-js/scala-js
test-suite/shared/src/test/scala/org/scalajs/testsuite/compiler/DefaultMethodsTest.scala
Scala
apache-2.0
1,562
package org.clulab.sequences import java.io.{BufferedReader, File, FileInputStream, InputStream} import org.clulab.processors.{Document, Sentence} import org.clulab.struct.Counter import org.clulab.utils.Files /** * Trait for all sequence taggers * User: mihais * Date: 8/25/17 */ trait SequenceTagger[L, F] extends Tagger[L] { def train(docs:Iterator[Document]) def classesOf(sentence: Sentence):Array[L] /** Abstract method that generates the features for the word at the position offset in the given sentence */ def featureExtractor(features:Counter[F], sentence: Sentence, offset:Int) /** Abstract method that extracts the training labels for a given sentence */ def labelExtractor(sentence:Sentence): Array[L] override def find(sentence: Sentence): Array[L] = classesOf(sentence) def save(fn:File) def loadFromFile(fn:File) { val is = Files.loadFile(fn) load(is) } def loadFromResource(rn:String) { val is = Files.loadStreamFromClasspath(rn) load(is) } def load(is:BufferedReader) def addHistoryFeatures(features:Counter[F], order:Int, labels:Seq[L], offset:Int):Unit = { addLeftFeatures(features, order, "", labels, offset) } def addFirstPassFeatures(features:Counter[F], order:Int, labels:Seq[L], offset:Int):Unit = { //addLeftFeatures(features, order, "fp", labels, offset) //addRightFeatures(features, order, "fp", labels, offset) features += mkFeatAtHistory(0, "fp", labels(offset)) } def addLeftFeatures(features:Counter[F], order:Int, prefix:String, labels:Seq[L], offset:Int):Unit = { var reachedBos = false for(o <- 1 to order if ! reachedBos) { if(offset - o >= 0) { features += mkFeatAtHistory(- o, prefix, labels(offset - o)) } else { features += mkFeatAtBeginSent(o, prefix) reachedBos = true } } } def addRightFeatures(features:Counter[F], order:Int, prefix:String, labels:Seq[L], offset:Int):Unit = { var reachedEos = false for(o <- 1 to order if ! reachedEos) { if(offset + o < labels.size) { features += mkFeatAtHistory(o, prefix, labels(offset + o)) } else { features += mkFeatAtEndSent(o, prefix) reachedEos = true } } } def mkFeatAtHistory(position:Int, prefix:String, label:L):F def mkFeatAtBeginSent(position:Int, prefix:String):F def mkFeatAtEndSent(position:Int, prefix:String):F } object SequenceTaggerLoader
sistanlp/processors
main/src/main/scala/org/clulab/sequences/SequenceTagger.scala
Scala
apache-2.0
2,454
package org.example.io import java.net.InetSocketAddress import akka.actor.{Actor, ActorLogging, Props} import akka.io.{IO, Tcp} /** * Created by kailianghe on 1/11/15. */ class EchoService(endPoint: InetSocketAddress) extends Actor with ActorLogging { import context.system IO(Tcp) ! Tcp.Bind(self, endPoint) def receive = { case Tcp.Connected(remote, _) => log.debug("Remote address {} connected", remote) sender ! Tcp.Register(context.actorOf(EchoConnectionHandler.props(remote, sender))) } } object EchoService { def props(endPoint: InetSocketAddress): Props = { Props(new EchoService(endPoint)) } }
hekailiang/akka-play
actor-samples/src/main/scala/org/example/io/EchoService.scala
Scala
apache-2.0
645
package com.norbitltd.spoiwo.natures.html import Model2HtmlConversions._ import com.norbitltd.spoiwo.model.{Sheet, Row} class SS2HTMLConversionsTest { def testImplicits() = { val sheet = Sheet( Row().withCellValues(34, 123, "Italy"), Row().withCellValues(43, 22.9, "Spain") ) sheet.asHtmlTableElem() } }
intracer/spoiwo
src/test/scala/com/norbitltd/spoiwo/natures/html/SS2HTMLConversionsTest.scala
Scala
mit
336
package rest import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives import akka.http.scaladsl.server.directives.Credentials import rest.OAuth2RouteProvider.TokenResponse import spray.json.DefaultJsonProtocol import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.{Failure, Success} import scalaoauth2.provider._ trait OAuth2RouteProvider[U] extends Directives with DefaultJsonProtocol{ import OAuth2RouteProvider.tokenResponseFormat import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ val oauth2DataHandler : DataHandler[U] val tokenEndpoint = new TokenEndpoint { override val handlers = Map( OAuthGrantType.CLIENT_CREDENTIALS -> new ClientCredentials, OAuthGrantType.PASSWORD -> new Password, OAuthGrantType.AUTHORIZATION_CODE -> new AuthorizationCode, OAuthGrantType.REFRESH_TOKEN -> new RefreshToken ) } def grantResultToTokenResponse(grantResult : GrantHandlerResult[U]) : TokenResponse = TokenResponse(grantResult.tokenType, grantResult.accessToken, grantResult.expiresIn.getOrElse(1L), grantResult.refreshToken.getOrElse("")) def oauth2Authenticator(credentials: Credentials): Future[Option[AuthInfo[U]]] = credentials match { case p@Credentials.Provided(token) => oauth2DataHandler.findAccessToken(token).flatMap { case Some(token) => oauth2DataHandler.findAuthInfoByAccessToken(token) case None => Future.successful(None) } case _ => Future.successful(None) } def accessTokenRoute = pathPrefix("oauth") { path("access_token") { post { formFieldMap { fields => onComplete(tokenEndpoint.handleRequest(new AuthorizationRequest(Map(), fields.map(m => m._1 -> Seq(m._2))), oauth2DataHandler)) { case Success(maybeGrantResponse) => maybeGrantResponse.fold(oauthError => complete(Unauthorized), grantResult => complete(tokenResponseFormat.write(grantResultToTokenResponse(grantResult))) ) case Failure(ex) => complete(InternalServerError, s"An error occurred: ${ex.getMessage}") } } } } } } object OAuth2RouteProvider extends DefaultJsonProtocol{ case class TokenResponse(token_type : String, access_token : String, expires_in : Long, refresh_token : String) implicit val tokenResponseFormat = jsonFormat4(TokenResponse) }
cdiniz/slick-akka-http-oauth2
src/main/scala/rest/OAuth2RouteProvider.scala
Scala
apache-2.0
2,474
/** * Copyright 2013-2015 PayPal * * 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.paypal.cascade.common.tests.concurrent import org.specs2.Specification import com.paypal.cascade.common.tests.util.CommonImmutableSpecificationContext import com.paypal.cascade.common.concurrent.NamedThreadFactory /** * Tests for [[com.paypal.cascade.common.concurrent.NamedThreadFactory]] */ class NamedThreadFactorySpecs extends Specification { override def is = s2""" NamedThreadFactory provides a method to get DefaultThreadFactory instances with a specified thread name prefix. NamedThreadFactory should: be able to create NORMAL priority non-daemon threads with given prefix ${thread().normal} be able to create NORMAL priority daemon threads from root with given prefix ${thread().normalDaemonRoot} be able to create NORMAL priority daemon threads with given prefix ${thread().normalDaemon} be able to create multiple threads ${thread().multiple} """ case class thread() extends CommonImmutableSpecificationContext { val factory = new NamedThreadFactory(){} val noopRunnable = new Runnable(){ def run(){} } val prefix = "prefix" def normal = apply { val t = factory.namedThreadFactory(prefix).newThread(noopRunnable) //don't start the thread, just inspect it (t.getName must startWith(prefix)) and (t.isDaemon must beFalse) and (t.getPriority must beEqualTo(Thread.NORM_PRIORITY)) } def normalDaemon = apply { val t = factory.namedDaemonThreadFactory(prefix).newThread(noopRunnable) //don't start the thread, just inspect it (t.getName must startWith(prefix)) and (t.isDaemon must beTrue) and (t.getPriority must beEqualTo(Thread.NORM_PRIORITY)) } def normalDaemonRoot = apply { val t = factory.namedDaemonRootThreadFactory(prefix).newThread(noopRunnable) //don't start the thread, just inspect it (t.getName must startWith(prefix)) and (t.isDaemon must beTrue) and (t.getPriority must beEqualTo(Thread.NORM_PRIORITY)) } def multiple = apply { val f = factory.namedThreadFactory(prefix) val t1 = f.newThread(noopRunnable) val t2 = f.newThread(noopRunnable) (t1.getName must startWith(prefix)) and (t2.getName must startWith(prefix)) } } }
2rs2ts/cascade
common/src/test/scala/com/paypal/cascade/common/tests/concurrent/NamedThreadFactorySpecs.scala
Scala
apache-2.0
2,927
package com.sksamuel.avro4s.schema import com.sksamuel.avro4s.{AvroSchema, FieldMapper, PascalCase, SchemaFor, SnakeCase} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class FieldMapperFieldTest extends AnyWordSpec with Matchers { "fieldMapper" should { "defaultNoChange" in { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/field_mapper_default.json")) val schema = SchemaFor[NamingStrategyTest].schema schema.toString(true) shouldBe expected.toString(true) } "support pascal case" in { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/field_mapper_pascal.json")) val schema = SchemaFor[NamingStrategyTest].withFieldMapper(PascalCase).schema schema.toString(true) shouldBe expected.toString(true) } "support snake case" in { val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/field_mapper_snake.json")) val schema = SchemaFor[NamingStrategyTest].withFieldMapper(SnakeCase).schema schema.toString(true) shouldBe expected.toString(true) } } } case class NamingStrategyTest(camelCase: String, lower: String, multipleWordsInThis: String, StartsWithUpper: String, nested: NamingStrategy2) case class NamingStrategy2(camelCase: String)
sksamuel/avro4s
avro4s-core/src/test/scala/com/sksamuel/avro4s/schema/FieldMapperFieldTest.scala
Scala
apache-2.0
1,374
/* * The MIT License (MIT) * * Copyright (c) 2014 Heiko Blobner * * 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 de.windelknecht.stup.utils.io.pack.archive import de.windelknecht.stup.utils.security.ChecksumTools import de.windelknecht.stup.utils.tools.testing.VFSHelper import org.apache.commons.vfs2.{FileObject, VFS} import org.scalatest.{Matchers, WordSpecLike} import scala.concurrent.Await import scala.concurrent.duration._ /** * Created by Me. * User: Heiko Blobner * Mail: heiko.blobner@gmx.de * * Date: 03.07.14 * Time: 15:39 * */ class ArchiverSpec extends WordSpecLike with Matchers { "An archiver object" when { "fired an erroneous archiveTo" should { "reply an error when unsupported archive extension" in { val ar = new Archiver( List(VFSHelper.createRandomFile("dir01/file01")), VFSHelper.createRandomFile("dir01/file01.tars") ) Await.result(ar.run(), 1 second).fold( error => error, archiveTo => archiveTo ) should be (ArchiveError.UnsupportedArchive) } "reply an error when no files are given" in { val ar = new Archiver( List.empty, VFSHelper.createRandomFile("dir01/file01.tar") ) Await.result(ar.run(), 1 second).fold( error => error, archiveTo => archiveTo ) should be (ArchiveError.NoFilesGiven) } } "archive to a tar archive" should { "return a new file object with tar extension" in { val archiveTo = VFSHelper.createRandomFile("dir01/file01.tar") val ar = new Archiver( List( VFSHelper.createRandomFile("dir01/file01"), VFSHelper.createRandomFile("dir01/file02") ), archiveTo ) Await.result(ar.run(), 1 second).fold( error => error, archiveTo => archiveTo ) should be (archiveTo) } "return a valid archive" in { val file1 = VFSHelper.createRandomFile("dir01/file01") val file2 = VFSHelper.createRandomFile("dir01/file02") val archiveTo = VFSHelper.createRandomFile("dir01/file01.tar") val ar = new Archiver( List( file1, file2 ), archiveTo ) val archive = Await.result(ar.run(), 1 second).fold( error => error, archiveTo => archiveTo ).asInstanceOf[FileObject] val outDir = VFS.getManager.resolveFile("ram://dir002/out/") val (out, fl) = Await.result(new UnArchiver(archive, outDir).run(), 1 second).fold( error => error, unArchiveTo => unArchiveTo ).asInstanceOf[(FileObject, List[FileObject])] val files = fl.map{f=> (f.getName.toString.replace(outDir.getName.toString, "ram://"), f)}.toMap out should be (outDir) files.size should be (2) files.get(file1.getName.toString) should not be None files.get(file2.getName.toString) should not be None ChecksumTools.fromVFSFile(file1) should be (ChecksumTools.fromVFSFile(files(file1.getName.toString))) ChecksumTools.fromVFSFile(file2) should be (ChecksumTools.fromVFSFile(files(file2.getName.toString))) } "return a valid archive when compressed twice" in { val file1 = VFSHelper.createRandomFile("dir01/file01") val file2 = VFSHelper.createRandomFile("dir01/file02") val archiveTo = VFSHelper.createRandomFile("dir01/file01.tar") val ar = new Archiver( List( file1, file2 ), archiveTo ) Await.ready(new Archiver(List(file1, file2), archiveTo).run(), 1 second) VFSHelper.writeToFile(file1, "kk") VFSHelper.writeToFile(file1, "kkddedede") val archive = Await.result(ar.run(), 1 second).fold( error => error, archiveTo => archiveTo ).asInstanceOf[FileObject] val outDir = VFS.getManager.resolveFile("ram://dir002/out/") val (out, fl) = Await.result(new UnArchiver(archive, outDir).run(), 1 second).fold( error => error, unArchiveTo => unArchiveTo ).asInstanceOf[(FileObject, List[FileObject])] val files = fl.map{f=> (f.getName.toString.replace(outDir.getName.toString, "ram://"), f)}.toMap out should be (outDir) files.size should be (2) files.get(file1.getName.toString) should not be None files.get(file2.getName.toString) should not be None ChecksumTools.fromVFSFile(file1) should be (ChecksumTools.fromVFSFile(files(file1.getName.toString))) ChecksumTools.fromVFSFile(file2) should be (ChecksumTools.fromVFSFile(files(file2.getName.toString))) } } } }
windelknecht/stup-utils
src/test/scala/de/windelknecht/stup/utils/io/pack/archive/ArchiverSpec.scala
Scala
mit
5,834
/****************************************************************************** * Copyright © 2017 Maxim Karpov * * * * 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 ru.makkarpov.playutils.slickutils import org.scalatest.FunSuite import scala.concurrent.Await import scala.concurrent.duration._ class MiscSuite extends FunSuite { import MyDriver.api._ case class TestBean(id: Long, str: String) class TestTable(t: Tag) extends Table[TestBean](t, "test") { def id = column[Long]("id", O.AutoInc, O.PrimaryKey) def str = column[String]("str") def * = (id, str) <> ((TestBean.apply _).tupled, TestBean.unapply) } val testQuery = TableQuery[TestTable] val testData = Seq( TestBean(1, "scala"), TestBean(2, "java"), TestBean(3, "groovy") ) test("resultFirst should work") { Await.result(MyDriver.database.run( DBIO.seq( testQuery.schema.create, testQuery.forceInsertAll(testData) ).andThen(DBIO.seq( testQuery.sortBy(_.id).filter(_.id > 1L).map(_.id).resultFirst.map(x => assert(x === Some(2))), testQuery.filter(_.id === 100L).map(_.id).resultFirst.map(x => assert(x === None)) )).andFinally(testQuery.schema.drop).transactionally ), 10 seconds span) } }
makkarpov/play-utils
src/test/scala/ru/makkarpov/playutils/slickutils/MiscSuite.scala
Scala
apache-2.0
2,305
// scalastyle:off /* NSC -- new Scala compiler * Copyright 2005-2013 LAMP/EPFL * @author Paul Phillips */ package org.apache.spark.repl import scala.tools.nsc._ import scala.tools.nsc.interpreter._ import scala.reflect.internal.util.BatchSourceFile import scala.tools.nsc.ast.parser.Tokens.EOF import org.apache.spark.Logging private[repl] trait SparkExprTyper extends Logging { val repl: SparkIMain import repl._ import global.{ reporter => _, Import => _, _ } import definitions._ import syntaxAnalyzer.{ UnitParser, UnitScanner, token2name } import naming.freshInternalVarName object codeParser extends { val global: repl.global.type = repl.global } with CodeHandlers[Tree] { def applyRule[T](code: String, rule: UnitParser => T): T = { reporter.reset() val scanner = newUnitParser(code) val result = rule(scanner) if (!reporter.hasErrors) scanner.accept(EOF) result } def defns(code: String) = stmts(code) collect { case x: DefTree => x } def expr(code: String) = applyRule(code, _.expr()) def stmts(code: String) = applyRule(code, _.templateStats()) def stmt(code: String) = stmts(code).last // guaranteed nonempty } /** Parse a line into a sequence of trees. Returns None if the input is incomplete. */ def parse(line: String): Option[List[Tree]] = debugging(s"""parse("$line")""") { var isIncomplete = false reporter.withIncompleteHandler((_, _) => isIncomplete = true) { val trees = codeParser.stmts(line) if (reporter.hasErrors) { Some(Nil)//列表结尾为Nil } else if (isIncomplete) { None } else { Some(trees) } } } // def parsesAsExpr(line: String) = { // import codeParser._ // (opt expr line).isDefined // } def symbolOfLine(code: String): Symbol = { def asExpr(): Symbol = { val name = freshInternalVarName() // Typing it with a lazy val would give us the right type, but runs // into compiler bugs with things like existentials, so we compile it // behind a def and strip the NullaryMethodType which wraps the expr. val line = "def " + name + " = {\\n" + code + "\\n}" interpretSynthetic(line) match { case IR.Success => val sym0 = symbolOfTerm(name) // drop NullaryMethodType val sym = sym0.cloneSymbol setInfo afterTyper(sym0.info.finalResultType) if (sym.info.typeSymbol eq UnitClass) NoSymbol else sym case _ => NoSymbol } } def asDefn(): Symbol = { val old = repl.definedSymbolList.toSet interpretSynthetic(code) match { case IR.Success => repl.definedSymbolList filterNot old match { case Nil => NoSymbol case sym :: Nil => sym //列表结尾为Nil case syms => NoSymbol.newOverloaded(NoPrefix, syms) } case _ => NoSymbol } } beQuietDuring(asExpr()) orElse beQuietDuring(asDefn()) } private var typeOfExpressionDepth = 0 def typeOfExpression(expr: String, silent: Boolean = true): Type = { if (typeOfExpressionDepth > 2) { logDebug("Terminating typeOfExpression recursion for expression: " + expr) return NoType } typeOfExpressionDepth += 1 // Don't presently have a good way to suppress undesirable success output // while letting errors through, so it is first trying it silently: if there // is an error, and errors are desired, then it re-evaluates non-silently // to induce the error message. try beSilentDuring(symbolOfLine(expr).tpe) match { case NoType if !silent => symbolOfLine(expr).tpe // generate error case tpe => tpe } finally typeOfExpressionDepth -= 1 } }
tophua/spark1.52
repl/scala-2.10/src/main/scala/org/apache/spark/repl/SparkExprTyper.scala
Scala
apache-2.0
3,801