• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Queue类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中scala.collection.immutable.Queue的典型用法代码示例。如果您正苦于以下问题:Scala Queue类的具体用法?Scala Queue怎么用?Scala Queue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Queue类的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
    }

} 
开发者ID:ioaccept,项目名称:pizza,代码行数:36,代码来源:Stove.scala


示例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
  }

} 
开发者ID:rmzoni,项目名称:algorithm-training,代码行数:43,代码来源:BFSTraverseTree.scala


示例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))

      }
    })
  }
} 
开发者ID:Saverin-lab,项目名称:culverin,代码行数:45,代码来源:TimeAgg.scala


示例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 _ => ()
        }
    }
} 
开发者ID:jlagarden,项目名称:dhbw-project-app,代码行数:54,代码来源:Item.scala


示例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)
  }
} 
开发者ID:scalacenter,项目名称:scastie,代码行数:60,代码来源:LoadBalancerTestUtils.scala


示例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 
开发者ID:scalacenter,项目名称:scastie,代码行数:57,代码来源:StatusProgress.scala


示例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))
  }
} 
开发者ID:crystal-project-inc,项目名称:streaming_user_segmentation,代码行数:51,代码来源:User.scala


示例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))

} 
开发者ID:pfcoperez,项目名称:algorithmaday,代码行数:48,代码来源:BFSAndApps.scala


示例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 }
  }
} 
开发者ID:NthPortal,项目名称:future-queue,代码行数:60,代码来源:FutureQueueTestDeprecated.scala


示例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)
} 
开发者ID:atemerev,项目名称:mi,代码行数:57,代码来源:Window.scala


示例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()
  }
} 
开发者ID:outr,项目名称:hyperscala,代码行数:45,代码来源:AjaxManager.scala


示例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))
  }
} 
开发者ID:everyevery,项目名称:Koroutine,代码行数:47,代码来源:ChannelActor.scala


示例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
        })
    }
  }

} 
开发者ID:Thulebona,项目名称:hashpvtapi,代码行数:51,代码来源:KeyService.scala


示例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: _*)
  }
} 
开发者ID:atemerev,项目名称:mi,代码行数:45,代码来源:RunHistorical.scala


示例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)))
} 
开发者ID:tlegutko,项目名称:traffic-sim,代码行数:39,代码来源:ConstantLightsStrategy.scala


示例16: RandomLightsStrategy

//设置package包名称以及导入依赖的类
package system.simulation.strategy

import akka.actor.ActorRef
import shared.map.Road
import system.simulation.Car

import scala.collection.immutable.Queue

case class RandomLightsStrategy(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, RandomLightsStrategy.randDuration)
      case _ => roads
    }
  }
}

object RandomLightsStrategy {
  def randDuration = scala.util.Random.nextInt(100) + 25

  def apply(allowedRoads: List[ActorRef]): ConstantLightsStrategy = new ConstantLightsStrategy(Queue.empty, allowedRoads.map(ref => (ref, randDuration)))
} 
开发者ID:tlegutko,项目名称:traffic-sim,代码行数:39,代码来源:RandomLightsStrategy.scala


示例17: FirstInFirstOutStrategy

//设置package包名称以及导入依赖的类
package system.simulation.strategy

import shared.map.Road
import system.simulation.Car

import scala.collection.immutable.Queue

case class FirstInFirstOutStrategy(waitingCars: Queue[Car]) extends CrossingStrategy {
  override def addCar(car: Car): CrossingStrategy =
    copy(waitingCars = waitingCars enqueue car)

  override def nextCar(blockedRoads: Set[Road]): (Option[Car], CrossingStrategy) = {
    if (waitingCars.nonEmpty) {
      waitingCars.dequeue match {
        case ([email protected](_, _, _, _, _, nextRoad :: _), newQueue) if blockedRoads contains nextRoad =>
          (None, copy(waitingCars = newQueue enqueue car))
        case (car, newQueue) =>
          (Some(car), copy(waitingCars = newQueue))
      }
    } else {
      (None, this)
    }
  }
}

object FirstInFirstOutStrategy {
  def apply(): FirstInFirstOutStrategy = new FirstInFirstOutStrategy(Queue.empty)
} 
开发者ID:tlegutko,项目名称:traffic-sim,代码行数:29,代码来源:FirstInFirstOutStrategy.scala


示例18: LogUnreachable

//设置package包名称以及导入依赖的类
package com.evolutiongaming.cluster

import akka.actor.{Actor, ActorLogging, ExtendedActorSystem, Extension, ExtensionId, Props}
import akka.cluster.ClusterEvent._
import akka.cluster.{Cluster, Member}

import scala.collection.immutable.Queue

class LogUnreachable(system: ExtendedActorSystem) extends Extension {

  private lazy val ref = system.actorOf(Props(new Listener))

  def start(): Unit = ref


  private class Listener extends Actor with ActorLogging {
    private val cluster = Cluster(context.system)

    private var queue = Queue.empty[ClusterDomainEvent]


    override def preStart() = {
      super.preStart()

      cluster.subscribe(self, initialStateMode = InitialStateAsEvents, classOf[ClusterDomainEvent])
    }

    def receive = {
      case x: ClusterDomainEvent => x match {
        case x: UnreachableMember  => onUnreachableMember(x.member); enqueue(x)
        case x: MemberEvent        => enqueue(x)
        case x: ReachabilityEvent  => enqueue(x)
        case x: LeaderChanged      => enqueue(x)
        case [email protected] => enqueue(x)
        case _                     =>
      }
    }

    def enqueue(event: ClusterDomainEvent) = {
      queue = queue enqueue event takeRight 20
    }

    def onUnreachableMember(member: Member) = {
      log.warning(s"node ${member.address} is Unreachable, cluster: ${cluster.state}, events: ${queue mkString ","}")
    }
  }
}

object LogUnreachable extends ExtensionId[LogUnreachable] {
  def createExtension(system: ExtendedActorSystem) = new LogUnreachable(system)
} 
开发者ID:evolution-gaming,项目名称:akka-tools,代码行数:52,代码来源:LogUnreachable.scala


示例19: SagaTest

//设置package包名称以及导入依赖的类
package fp.saga

import fp.saga.Saga.{Next, Stop}
import monix.eval.Coeval
import org.scalatest.{Matchers, WordSpec}

import scala.collection.immutable.Queue
import scala.util.{Failure, Success, Try}

class SagaTest extends WordSpec with Matchers {

  var start = 1

  case class Sum(a: Int)
  case class Rest(a: Int)

  def sumStart(b: Int): Saga[Int, Int] = {
    Saga.next({start -= b; start}, {start += b; start})
  }

  //last step: there is no mutation of start but it depends on its state.
  //To give an example of a stateless operation in a saga.
  def trySum(a: String) = Try(a.toInt + start) match {
    case Success(r) => Next(Queue.empty[Coeval[Unit]], r)
    case Failure(ex) => Stop(Queue.empty[Coeval[Unit]])
  }

  "Saga" should {

    "Revert" in {
      val res = for {
        a <- sumStart(2)
        b <- sumStart(2)
        z <- trySum("s")
      } yield z
      //state changes how it should, no recovery until run
      start shouldBe 5
      val done: Either[Queue[Try[AnyVal]], Int] = res.run
      println(s"DONE $done")
      //revert is applied and state should be the original
      start shouldBe 1
    }

    "End successfuly" in {
      val res = for {
        a <- sumStart(2)
        b <- sumStart(2)
        z <- trySum("2")
      } yield z
      start shouldBe 5 //to state lazyness
      val done: Either[Queue[Try[AnyVal]], Int] = res.run
      done shouldBe Right(7)
      start shouldBe 5
    }
  }

} 
开发者ID:leandrob13,项目名称:fp-examples,代码行数:58,代码来源:SagaTest.scala



注:本文中的scala.collection.immutable.Queue类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala KafkaStream类代码示例发布时间:2022-05-23
下一篇:
Scala SimpleUpdater类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap