本文整理汇总了Scala中scala.collection.immutable.Queue类的典型用法代码示例。如果您正苦于以下问题:Scala Queue类的具体用法?Scala Queue怎么用?Scala Queue使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Queue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Stove
//设置package包名称以及导入依赖的类
package models
import scala.collection.immutable.Queue
class Stove(capacity: Int = 1) {
private var queue = Queue[List[Pizza]]()
def +=(pizza: Pizza): Stove = {
if (queue.isEmpty) {
queue = Queue(List(pizza))
} else {
val last: List[Pizza] = queue.last
queue = if (last.length < capacity) {
queue.init :+ (pizza :: last)
} else {
queue :+ List(pizza)
}
}
this
}
def +=(listOfPizza: List[Pizza]): Stove =
listOfPizza.foldLeft(this) { (stove, pizza) => stove += pizza }
def next(): List[Pizza] =
if (queue.isEmpty) {
List()
} else {
val first = queue.head
queue = queue.tail
first
}
}
示例2: BFSTraverseTree
//设置package包名称以及导入依赖的类
package ai.bfs_dfs
import scala.collection.immutable.Queue
class BFSTraverseTree {
class Tree[T](x: T) {
var value: T = x
var left: Option[Tree[T]] = None
var right: Option[Tree[T]] = None
}
def traverse(t: Option[Tree[Int]]): Array[Int] = {
var q = Queue.empty[Tree[Int]]
var ls = List.empty[Int]
t match {
case Some(x) => {
q = q :+ x
while (!q.isEmpty) {
val current = q.head
q = q.tail
ls = ls ::: List(current.value)
current.left match {
case Some(l) => q = q :+ l
case _ =>
}
current.right match {
case Some(r) => q = q :+ r
case _ =>
}
}
}
case _ =>
}
ls.toArray
}
}
示例3: TimeAgg
//设置package包名称以及导入依赖的类
package co.saverin.culverin.engine.aggregator
import akka.stream.stage.{GraphStageLogic, InHandler, OutHandler}
import akka.stream.{Attributes, FlowShape, Inlet, Outlet}
import akka.stream.stage.GraphStage
import scala.collection.immutable.Queue
import scala.concurrent.duration._
class TimeAgg[T](timeSpan: FiniteDuration, aggregate: (Queue[T]) => T) extends GraphStage[FlowShape[T, T]] {
private val span: Long = timeSpan.toMillis
val in = Inlet[T]("Input")
val out = Outlet[T]("Output")
override val shape = FlowShape.of(in, out)
override def createLogic(attr: Attributes): GraphStageLogic = new GraphStageLogic(shape) {
private var q = Queue[T]()
private var timeQ = Queue[Long]()
private def cleanup() {}
setHandler(in, new InHandler {
override def onPush(): Unit = {
cleanup()
val b = grab(in)
timeQ :+ System.currentTimeMillis()
q :+ b
pull(in)
}
})
setHandler(out, new OutHandler {
override def onPull(): Unit = {
cleanup()
push(out, aggregate(q))
}
})
}
}
示例4: ItemData
//设置package包名称以及导入依赖的类
package com.project.production
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.FSM
import akka.actor.FSM._
import akka.actor.Props
import scala.collection.immutable.Queue
case class ItemData(val erpData: ERPData, val specData: SpecData, val prodData: Queue[_])
class Item extends Actor {
val fsm: ActorRef = context.actorOf(Props[ItemFSM])
var erpData: Option[ERPData] = None
var specData: Option[SpecData] = None
var prodData: Option[Queue[_]] = None
implicit val formats = Serialization.formats(NoTypeHints)
def receive = {
case (x: ProdEvent, y: ProdData) => fsm ! (x, y)
case x: ERPData => erpData = Some(x)
case x: SpecData => {
specData = Some(x)
trySubmit()
}
case x: Queue[_] => prodData = Some(x)
}
def itemData: ItemData = {
val item = for {
e <- erpData
s <- specData
p <- prodData
} yield ItemData(e, s, p)
item.get
}
def serialize(item: ItemData): String = {
write(item)
}
def trySubmit() {
erpData.isDefined && specData.isDefined && prodData.isDefined match {
case true => context.parent ! serialize(itemData)
case _ => ()
}
}
}
示例5: add
//设置package包名称以及导入依赖的类
package com.olegych.scastie.balancer
import com.olegych.scastie.api._
import com.olegych.scastie.balancer.utils._
import org.scalatest.{FunSuite, Assertion}
import scala.collection.immutable.Queue
trait LoadBalancerTestUtils extends FunSuite with TestUtils {
type TestLoadBalancer = LoadBalancer[String, String]
private var taskId = 1000
def add(balancer: TestLoadBalancer, config: String): TestLoadBalancer = {
val (_, balancer0) =
balancer.add(
Task(config, nextIp, SbtRunTaskId(SnippetId(taskId.toString, None)))
)
taskId += 1
balancer0
}
def assertConfigs(
balancer: TestLoadBalancer
)(columns: Seq[String]*): Assertion = {
assertMultiset(
balancer.servers.map(_.currentConfig),
columns.flatten
)
}
def assertMultiset[T: Ordering](xs: Seq[T], ys: Seq[T]): Assertion =
assert(Multiset(xs) == Multiset(ys))
private var serverId = 0
def server(config: String): Server[String, String] = {
val t = Server("s" + serverId, config)
serverId += 1
t
}
def servers(columns: Seq[String]*): Vector[Server[String, String]] = {
columns.to[Vector].flatten.map(server)
}
private var currentIp = 0
def nextIp: Ip = {
val t = Ip("ip" + currentIp)
currentIp += 1
t
}
def history(columns: Seq[String]*): History[String] = {
val records =
columns.to[Vector].flatten.map(config => Record(config, nextIp)).reverse
History(Queue(records: _*), size = 20)
}
}
示例6: Runner
//设置package包名称以及导入依赖的类
package com.olegych.scastie
package api
import play.api.libs.json._
import scala.collection.immutable.Queue
object Runner {
implicit val formatRunner = Json.format[Runner]
}
case class Runner(tasks: Queue[TaskId])
object StatusProgress {
implicit object StatusProgressFormat extends Format[StatusProgress] {
private val formatStatusInfo = Json.format[StatusInfo]
def writes(status: StatusProgress): JsValue = {
status match {
case StatusKeepAlive => {
JsObject(Seq("$type" -> JsString("StatusKeepAlive")))
}
case si: StatusInfo => {
formatStatusInfo.writes(si).asInstanceOf[JsObject] ++
JsObject(Seq("$type" -> JsString("StatusInfo")))
}
}
}
def reads(json: JsValue): JsResult[StatusProgress] = {
json match {
case obj: JsObject => {
val vs = obj.value
vs.get("$type") match {
case Some(tpe) => {
tpe match {
case JsString("StatusKeepAlive") => JsSuccess(StatusKeepAlive)
case JsString("StatusInfo") => formatStatusInfo.reads(json)
case _ => JsError(Seq())
}
}
case None => JsError(Seq())
}
}
case _ => JsError(Seq())
}
}
}
}
sealed trait StatusProgress
case object StatusKeepAlive extends StatusProgress
case class StatusInfo(runners: Vector[Runner]) extends StatusProgress
示例7: User
//设置package包名称以及导入依赖的类
package com.crystal
package models
// Scala
import scala.collection.immutable.Queue
import scala.collection.JavaConversions._
// Persistent Storage
import stores.DynamoDB
case class User(val id: String, persistedActions: Queue[UserAction] = Queue(), newActions: Queue[UserAction] = Queue()) {
import User._
val actions = persistedActions ++ newActions
def performedAction(action: Map[String, Any]): User = {
val newAction = UserAction(
userID = id,
category = action.get("se_category").getOrElse("N/A").asInstanceOf[String],
action = action.get("se_action").getOrElse("N/A").asInstanceOf[String],
label = action.get("se_label").getOrElse("N/A").asInstanceOf[String],
property = action.get("se_property").getOrElse("N/A").asInstanceOf[String],
value = action.get("se_value").getOrElse("N/A").asInstanceOf[String],
tstamp = action.get("collector_tstamp").get.asInstanceOf[String]
)
User(id, persistedActions, newActions :+ newAction)
}
def save() = {
newActions.map { action => action.save() }
}
def toMap(): Map[String, Any] = {
Map(
"id" -> id,
"actions" -> actions.map(_.toMap)
)
}
}
object User {
def withID(id: String): User = {
if (id == null || id.isEmpty) {
return User("")
}
User(id, Queue[UserAction]() ++ UserAction.allFor(id))
}
}
示例8: BFSAndApps
//设置package包名称以及导入依赖的类
package org.pfcoperez.dailyalgorithm.applications
import scala.collection.immutable.Queue
import org.pfcoperez.dailyalgorithm.datastructures.Graphs.BinaryTrees._
object BFSAndApps extends App {
def bfsWithAccFunction[T, R](acc: R, h: Int = 0)(
toVisit: Queue[BinaryTree[T]]
)(update: (R, Int, T) => R)(
inLevelOrder: (BinaryTree[T], BinaryTree[T]) => (BinaryTree[T], BinaryTree[T])
): R =
if(toVisit.isEmpty) acc
else {
val (currentNode, remToVisit) = toVisit.dequeue
val (newToVisit: Queue[BinaryTree[T]], newAcc) = currentNode match {
case Node(left, v, right) =>
val (a,b) = inLevelOrder(left, right)
(remToVisit ++ Seq(a,b), update(acc, h, v))
case _ => remToVisit -> acc
}
bfsWithAccFunction[T, R](newAcc, h+1)(newToVisit)(update)(inLevelOrder)
}
val o = Node(Empty, 15, Empty)
val n = Node(Empty, 14, Empty)
val m = Node(Empty, 13, Empty)
val l = Node(Empty, 12, Empty)
val k = Node(Empty, 11, Empty)
val j = Node(Empty, 10, Empty)
val i = Node(Empty, 9, Empty)
val h = Node(Empty, 8, Empty)
val g = Node(n, 7, o)
val f = Node(l, 6, m)
val e = Node(j, 5, k)
val d = Node(h, 4, i)
val b = Node(d, 2, e)
val c = Node(f, 3, g)
val a = Node(b, 1, c)
println(levelOrderTreeTraversal(a))
}
示例9: FutureQueueTestDeprecated
//设置package包名称以及导入依赖的类
package com.nthportal.collection.concurrent
import com.nthportal.testing.concurrent.ManualExecutor
import org.scalatest.{FlatSpec, Matchers}
import scala.collection.immutable.Queue
import scala.concurrent.Await
import scala.concurrent.duration.Duration
@deprecated("testing deprecated methods", since = "now")
class FutureQueueTestDeprecated extends FlatSpec with Matchers {
"implicit conversion from FutureQueue to Queue (deprecated)" should "convert properly" in {
import FutureQueue.Implicits._
val q = Queue("some", "elements")
val fq = FutureQueue(q)
fq.seq should be theSameInstanceAs q
}
behavior of "FutureQueue (deprecated)"
it should "enqueue multiple elements" in {
val fq = FutureQueue.empty[String]
val list = List("some", "test", "strings")
fq enqueue list
fq.queued shouldEqual list
fq should have size list.size
}
it should "drain to another `FutureQueue`" in {
val executor = ManualExecutor()
import executor.Implicits._
val q1 = FutureQueue.empty[String]
val q2 = FutureQueue.empty[String]
q1 drainToContinually q2
q1.promiseCount shouldBe 1
q1 += "1"
executor.executeAll()
q2 should have size 1
Await.result(q2.dequeue(), Duration.Zero) shouldBe "1"
q1.promiseCount shouldBe 1
q1 ++= Seq("2", "3")
executor.executeAll()
q2 should have size 2
Await.result(q2.dequeue(), Duration.Zero) shouldBe "2"
Await.result(q2.dequeue(), Duration.Zero) shouldBe "3"
q1.promiseCount shouldBe 1
an [IllegalArgumentException] should be thrownBy { q2 drainToContinually q2 }
}
}
示例10: Window
//设置package包名称以及导入依赖的类
package com.temerev.mi.analytics
import java.time.{Instant, Duration}
import com.miriamlaurel.fxcore.market.Quote
import com.miriamlaurel.fxcore._
import scala.annotation.tailrec
import scala.collection.immutable.Queue
case class Window(period: Duration,
maxGap: Duration,
mainQueue: Queue[Quote] = Queue(),
minQueue: Queue[Quote] = Queue(),
maxQueue: Queue[Quote] = Queue(),
full: Boolean = false) {
def addQuote(quote: Quote): Window = {
val (newMainQueue, newMinQueue, newMaxQueue) = {
if (mainQueue.nonEmpty && Duration.between(mainQueue.last.timestamp, quote.timestamp).compareTo(maxGap) > 0) {
(Queue(), Queue(), Queue())
} else (trimOld(mainQueue, quote.timestamp), trimMin(trimOld(minQueue, quote.timestamp), quote), trimMax(trimOld(maxQueue, quote.timestamp), quote))
}
val newFull = mainQueue.nonEmpty && newMainQueue.nonEmpty && mainQueue.head.timestamp != newMainQueue.head.timestamp
copy(mainQueue = newMainQueue :+ quote, minQueue = newMinQueue :+ quote, maxQueue = newMaxQueue :+ quote, full = newFull)
}
lazy val size: Int = mainQueue.size
lazy val min: BigDecimal = minQueue.head.bid.get
lazy val max: BigDecimal = maxQueue.head.ask.get
lazy val heightPips: BigDecimal = asPips(mainQueue.head, max - min)
lazy val minuteIndex: Int = ((mainQueue.last.timestamp.toEpochMilli / 60000 - 5760) % (7 * 24 * 60)).toInt
lazy val deltaBidPips = asPips(mainQueue.head.instrument, mainQueue.last.bid.get - mainQueue.head.bid.get)
lazy val deltaAskPips = asPips(mainQueue.head.instrument, mainQueue.last.ask.get - mainQueue.head.ask.get)
@tailrec
private def trimOld(queue: Queue[Quote], now: Instant): Queue[Quote] = if (queue.isEmpty || Duration.between(queue.head.timestamp, now).compareTo(period) < 0)
queue else trimOld(queue.tail, now)
@tailrec
private def trimMin(queue: Queue[Quote], quote: Quote): Queue[Quote] =
if (queue.isEmpty || queue.last.bid.get <= quote.bid.get) queue
else trimMin(queue.dropRight(1), quote)
@tailrec
private def trimMax(queue: Queue[Quote], quote: Quote): Queue[Quote] =
if (queue.isEmpty || queue.last.ask.get >= quote.ask.get) queue else trimMax(queue.dropRight(1), quote)
private def distance(queue: Queue[Quote]): Duration = Duration.between(queue.head.timestamp, queue.last.timestamp)
}
示例11: AjaxManager
//设置package包名称以及导入依赖的类
package org.hyperscala.ajax
import com.outr.scribe.Logging
import org.scalajs.dom.XMLHttpRequest
import org.scalajs.dom.raw.FormData
import scala.collection.immutable.Queue
import scala.concurrent.Future
class AjaxManager(val maxConcurrent: Int) extends Logging {
private var queue = Queue.empty[AjaxAction]
private var running = Set.empty[AjaxAction]
def enqueue(url: String,
data: FormData,
timeout: Int = 0,
headers: Map[String, String] = Map.empty,
withCredentials: Boolean = true,
responseType: String = ""): AjaxAction = {
val request = new AjaxRequest(url, data, timeout, headers, withCredentials, responseType)
val action = new AjaxAction(request)
enqueue(action)
action
}
def enqueue(action: AjaxAction): Future[XMLHttpRequest] = {
queue = queue.enqueue(action)
action._state := ActionState.Enqueued
checkQueue()
action.future
}
def checkQueue(): Unit = if (running.size < maxConcurrent && queue.nonEmpty) {
val (action, updated) = queue.dequeue
queue = updated
running += action
action.start(this)
}
private[ajax] def remove(action: AjaxAction): Unit = {
running -= action
checkQueue()
}
}
示例12: GetMessage
//设置package包名称以及导入依赖的类
package net.everyevery.koroutine.channel
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import scala.collection.immutable.Queue
sealed trait ChannelMessage
case object GetMessage extends ChannelMessage
case class PutMessage[A](value: A) extends ChannelMessage
case object AckMessage extends ChannelMessage
case class AnsMessage[A](value: A) extends ChannelMessage
private[channel] class ChannelActor[A](val size: Int) extends Actor {
var buffer: Queue[(ActorRef,A)] = Queue.empty
var receivers: Queue[ActorRef] = Queue.empty
override def receive: Receive = {
case GetMessage =>
receivers = receivers :+ sender
if (buffer.nonEmpty)
publish()
case m: PutMessage[A] =>
buffer = buffer :+ (sender, m.value)
if (receivers.nonEmpty)
publish()
}
private def publish(): Unit = {
if (buffer.nonEmpty && receivers.nonEmpty) {
val ((s,v),svq) = buffer.dequeue
val (w,wq) = receivers.dequeue
buffer = svq
receivers = wq
s.tell(AckMessage, self)
w.tell(AnsMessage(v), self)
}
}
}
object ChannelActor {
def apply[A](size: Int)(implicit system: ActorSystem): ActorRef = {
system.actorOf(Props(classOf[ChannelActor[A]], size))
}
}
示例13: createKey
//设置package包名称以及导入依赖的类
package services.util
import java.util.UUID
import conf.util.Util
import domain.util.Keys
import repository.util.KeysRepository
import scala.collection.immutable.Queue
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
trait KeyService {
def createKey(): Future[String]
def getKey(): Future[Seq[Keys]]
}
object KeyService {
def apply(): KeyService = new KeyServiceImpl
private class KeyServiceImpl extends KeyService {
override def createKey(): Future[String] = {
val key = getKey() map (keyvalues =>
if (keyvalues != Nil) {
keyvalues.head
KeysRepository.deleteKey(keyvalues.head.id)
val newKey = Util.md5Hash(UUID.randomUUID().toString)
KeysRepository.save(Keys(newKey, newKey))
newKey
} else {
val generateKey = Util.md5Hash(UUID.randomUUID().toString)
KeysRepository.save(Keys(generateKey, generateKey))
generateKey
}
)
key
}
override def getKey(): Future[Seq[Keys]] = {
KeysRepository.getAllkeys map (keys =>
keys match {
case Queue(x, _*) => keys
case Queue() => Nil
})
}
}
}
示例14: RunHistorical
//设置package包名称以及导入依赖的类
package com.temerev.mi.run
import java.io.{FileWriter, File}
import java.time.format.DateTimeFormatter
import java.time.{ZoneId, Duration, LocalDate, Month}
import com.miriamlaurel.fxcore._
import com.miriamlaurel.fxcore.market.Quote
import com.miriamlaurel.fxcore.portfolio.StrictPortfolio
import com.temerev.mi.analytics.{FutureView, Window}
import com.temerev.mi.io.TickReader
import com.temerev.mi.strategy.BreakoutStrategy
import scala.collection.immutable.Queue
import scala.io.Source
object RunHistorical extends App {
val TZ = ZoneId.of("UTC")
val reader = new TickReader(new File("/opt/data"))
val startDate = LocalDate.of(2015, Month.OCTOBER, 1)
val endDate = LocalDate.of(2015, Month.OCTOBER, 30)
val format = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")
println("Loading ticks...")
val startTs = System.currentTimeMillis()
val ticks = reader.getTicks(EURUSD, startDate, endDate).map(_.best)
val smap = readSeasonalityMap(new File(args(0)))
val outDir = new File(args(1))
var view = FutureView(500, Window(Duration.ofHours(1), Duration.ofMinutes(5)), Queue.empty)
var candidates = Vector.empty[FutureView]
var count = 0
var ts = 0L
val strategy = BreakoutStrategy(new StrictPortfolio(), view.window, smap)
val result = ticks.foldLeft(strategy)((s: BreakoutStrategy, q: Quote) => s.apply(q))
result.deals.foreach(println)
def readSeasonalityMap(file: File): Map[Int, BigDecimal] = {
val pairs = Source.fromFile(file).getLines().map(s => {
val tokens = s.split(",")
(tokens(0).toInt, BigDecimal(tokens(1)))
})
Map(pairs.toSeq: _*)
}
}
示例15: ConstantLightsStrategy
//设置package包名称以及导入依赖的类
package system.simulation.strategy
import akka.actor.ActorRef
import shared.map.Road
import system.simulation.Car
import scala.collection.immutable.Queue
case class ConstantLightsStrategy(waitingCars: Queue[Car], allowedRoads: List[(ActorRef, Int)]) extends CrossingStrategy {
override def addCar(car: Car): CrossingStrategy =
copy(waitingCars = waitingCars enqueue car)
override def nextCar(blockedRoads: Set[Road]): (Option[Car], CrossingStrategy) = {
val waitingCar = waitingCars.find(car => car.supervisor == allowedRoads.head._1 && (car.route.isEmpty || !blockedRoads.contains(car.route.head)))
waitingCar match {
case Some(car) =>
(Some(car), copy(waitingCars.filterNot(_ == waitingCar.get), iterateLights(allowedRoads)))
case None =>
(None, copy(allowedRoads = iterateLights(allowedRoads)))
}
}
def iterateLights(roads: List[(ActorRef, Int)]): List[(ActorRef, Int)] = {
roads match {
case (actorRef, lightsTick) :: tail if lightsTick > 0 =>
(actorRef, lightsTick - 1) :: tail
case (actorRef, lightsTick) :: tail if lightsTick == 0 =>
tail :+(actorRef, ConstantLightsStrategy.LIGHTS_DURATION)
case _ => roads
}
}
}
object ConstantLightsStrategy {
val LIGHTS_DURATION = 50
def apply(allowedRoads: List[ActorRef]): ConstantLightsStrategy = new ConstantLightsStrategy(Queue.empty, allowedRoads.map(ref => (ref, LIGHTS_DURATION)))
}