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

Scala IndexedSeq类代码示例

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

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



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

示例1: DBAccessWorker

//设置package包名称以及导入依赖的类
package domain

import java.sql.{Connection, ResultSet, Statement}

import scala.collection.immutable.IndexedSeq

case class DBAccessWorker(connection: Connection, sql: String) {

  private def execute(execSql: String) = {
    val stmt: Statement = connection.createStatement
    val rs: ResultSet = stmt.executeQuery(execSql)
    val columnCnt: Int = rs.getMetaData.getColumnCount

    val columns: IndexedSeq[String] = 1 to columnCnt map rs.getMetaData.getColumnName
    val results: Iterator[IndexedSeq[String]] = Iterator.continually(rs).takeWhile(_.next()).map{ rs =>
      columns map rs.getString
    }

    (columns, results)
  }

  def execute(): SqlResults = {
    val (d1, d2) = execute(sql)
    SqlResults(d1, d2)
  }

  def executeStatistics(): Statistics = {
    val (d1, d2) = execute(s"EXPLAIN $sql")
    Statistics(d1, d2)
  }
}

case class SqlResults(columns: IndexedSeq[String], results: Iterator[IndexedSeq[String]])

case class Statistics(columns: IndexedSeq[String], results: Iterator[IndexedSeq[String]]) 
开发者ID:miya5n,项目名称:miyalikejdbc,代码行数:36,代码来源:DBAccessWorker.scala


示例2: BaseStationSource

//设置package包名称以及导入依赖的类
package com.darienmt.airplaneadventures.basestation.collector.streams

import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.scaladsl.{ Framing, Source, Tcp }
import akka.util.ByteString
import com.darienmt.airplaneadventures.basestation.collector.parsing.MessageParser
import com.darienmt.airplaneadventures.basestation.data.BaseStation.Message

import scala.collection.immutable.IndexedSeq

object BaseStationSource {

  def apply(address: String, port: Int)(implicit actorSystem: ActorSystem): Source[Message, NotUsed] =
    Source(IndexedSeq(ByteString.empty))
      .via(
        Tcp().outgoingConnection(address, port)
          .via(Framing.delimiter(ByteString("\n"), 256, allowTruncation = true))
          .map(_.utf8String)
      )
      .map(MessageParser(_))

} 
开发者ID:darienmt,项目名称:airplane-adventures,代码行数:24,代码来源:BaseStationSource.scala


示例3: VerticalBoxBlurRunner

//设置package包名称以及导入依赖的类
package scalashop

import org.scalameter._
import common._

import scala.collection.immutable.IndexedSeq

object VerticalBoxBlurRunner {

  val standardConfig = config(
    Key.exec.minWarmupRuns -> 5,
    Key.exec.maxWarmupRuns -> 10,
    Key.exec.benchRuns -> 10,
    Key.verbose -> true
  ) withWarmer (new Warmer.Default)

  def main(args: Array[String]): Unit = {
    val radius = 3
    val width = 1920
    val height = 1080
    val src = new Img(width, height)
    val dst = new Img(width, height)
    val seqtime = standardConfig measure {
      VerticalBoxBlur.blur(src, dst, 0, width, radius)
    }
    println(s"sequential blur time: $seqtime ms")

    val numTasks = 32
    val partime = standardConfig measure {
      VerticalBoxBlur.parBlur(src, dst, numTasks, radius)
    }
    println(s"fork/join blur time: $partime ms")
    println(s"speedup: ${seqtime / partime}")
  }

}


  def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit = {
    type stripe = (Int, Int)
    val numColinStripe: Int = math.ceil(src.width / numTasks.toDouble).toInt
    val stripes: IndexedSeq[stripe] = (0 until src.width) map { s =>
      if (s + numColinStripe >= src.width) (s, src.width)
      else (s, s + numColinStripe)
    }
    val tasks = stripes.map(s => (task {blur(src, dst, s._1, s._2, radius)}))
    tasks.foreach(_.join)
  }
} 
开发者ID:vincenzobaz,项目名称:Parallelism-and-Concurrency-Assignments,代码行数:50,代码来源:VerticalBoxBlur.scala


示例4: Main

//设置package包名称以及导入依赖的类
package com.darienmt.airplaneadventures.basestation.rawcollector

import java.net.InetSocketAddress

import akka.Done
import akka.io.Inet.SocketOption
import akka.kafka.ProducerSettings
import akka.kafka.scaladsl.Producer
import akka.stream.scaladsl.{ Framing, Source, Tcp }
import akka.util.ByteString
import com.darienmt.keepers.{ Generator, KeepThisUp, MainCommons }
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.common.serialization.{ ByteArraySerializer, StringSerializer }

import scala.collection.immutable
import scala.collection.immutable.IndexedSeq
import scala.util.Success
import scala.concurrent.duration._

object Main extends App with MainCommons {

  implicit def asFiniteDuration(d: java.time.Duration): FiniteDuration =
    scala.concurrent.duration.Duration.fromNanos(d.toNanos)

  val bsAddress = config.getString("station.address")
  val bsPort = config.getInt("station.port")
  val connectTimeout: Duration = config.getDuration("station.connectTimeout")
  val idleTimeout: Duration = config.getDuration("station.idleTimeout")

  val kafkaAddress = config.getString("kafka.address")
  val kafkaPort = config.getInt("kafka.port")
  val kafkaTopic = config.getString("kafka.topic")


  val generator: Generator = () => Source(IndexedSeq(ByteString.empty))
    .via(
      Tcp().outgoingConnection(
        remoteAddress = InetSocketAddress.createUnresolved(bsAddress, bsPort),
        connectTimeout = connectTimeout,
        idleTimeout = idleTimeout
      )
        .via(Framing.delimiter(ByteString("\n"), 256))
        .map(_.utf8String)
    )
    .map(m => new ProducerRecord[Array[Byte], String](kafkaTopic, m))
    .runWith(
      Producer.plainSink(
        ProducerSettings(system, new ByteArraySerializer, new StringSerializer)
          .withBootstrapServers(s"${kafkaAddress}:${kafkaPort}")
      )
    )

  val keeper = KeepThisUp(config)
  keeper(generator)
} 
开发者ID:darienmt,项目名称:airplane-adventures,代码行数:56,代码来源:Main.scala


示例5: WorkloadsTests

//设置package包名称以及导入依赖的类
package drt.client.services

import drt.shared.FlightsApi._
import drt.shared._
import utest._

import scala.collection.immutable.{IndexedSeq, Map}
import scala.scalajs.js.Date

object WorkloadsTests extends TestSuite {

  def tests = TestSuite {

    "Given workloads, " - {
      "we need a label per minute, starting at midnight of today" - {
        val firstTime = Date.parse("2016-11-01T07:20Z").toLong
        val workloads = Workloads(
          Map("T1" ->
            Map("eeaDesk" ->
              (List(WL(firstTime, 99)), List(Pax(firstTime, 10))))))
        val labels: IndexedSeq[TerminalName] = workloads.labels.take(5)
        assert(labels  == List(
          "00:00",
          "00:01",
          "00:02",
          "00:03",
          "00:04"
        ))
      }
      "it doesn't matter what terminal we have in workloads we need a label per minute" - {
        val firstTime = Date.parse("2016-11-01T07:20Z").toLong
        val workloads = Workloads(
          Map("A1" ->
            Map("eeaDesk" ->
              (List(WL(firstTime, 99)), List(Pax(firstTime, 10))))))
        val labels: IndexedSeq[TerminalName] = workloads.labels.take(5)
        assert(labels  == List(
          "00:00",
          "00:01",
          "00:02",
          "00:03",
          "00:04"
        ))
      }
      "the labels are in 24H format" - {
        val firstTime = Date.parse("2016-11-01T14:20Z").toLong
        val workloads = Workloads(
          Map("A1" ->
            Map("eeaDesk" ->
              (List(WL(firstTime, 99)), List(Pax(firstTime, 10))))))
        val labels: IndexedSeq[TerminalName] = workloads.labels.drop(800).take(5)
        assert(labels  == List(
          "13:20", "13:21", "13:22", "13:23", "13:24"
        ))
      }
    }
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-scalajs-spa-exploration,代码行数:59,代码来源:WorkloadsTests.scala


示例6: SubTermsComputer

//设置package包名称以及导入依赖的类
package ru.ispras.atr.features.occurrences

import ru.ispras.atr.datamodel.TermCandidate

import scala.collection.immutable.IndexedSeq


object SubTermsComputer {
  def computeShorter2longerTerms(candidates: Iterable[TermCandidate], minSubTermSize: Int) = {
    computeShorter2longerCollocations(candidates.map(_.lemmas), minSubTermSize)
  }

  def computeLonger2shorterTerms(candidates: Iterable[TermCandidate], minSubTermSize: Int = 1) = {
    computeLonger2shorterCollocations(candidates.map(_.lemmas), minSubTermSize)
  }

  def computeShorter2longerCollocations(candidates: Iterable[Seq[String]], minSubTermSize: Int) = {
    val candidateAndSubCollocations = computeCollocations2SubCollocations(candidates, minSubTermSize)
    val shorter2longerCollocations = new collection.mutable.HashMap[Seq[String], collection.mutable.Set[Seq[String]]]()
      with collection.mutable.MultiMap[Seq[String], Seq[String]]

    candidateAndSubCollocations.foreach(candAndSubCollocation =>
      candAndSubCollocation._2.foreach(st => {
        shorter2longerCollocations.addBinding(st, candAndSubCollocation._1)
      })
    )
    shorter2longerCollocations.toMap
  }

  def computeLonger2shorterCollocations(candidates: Iterable[Seq[String]], minSubTermSize: Int = 1) = {
    val candidateAndSubCollocations = computeCollocations2SubCollocations(candidates, minSubTermSize)
    val longer2shorterCollocations = new collection.mutable.HashMap[Seq[String], collection.mutable.Set[Seq[String]]]()
      with collection.mutable.MultiMap[Seq[String], Seq[String]]

    candidateAndSubCollocations.foreach(candAndSubCollocation =>
      candAndSubCollocation._2.foreach(st => {
        longer2shorterCollocations.addBinding(candAndSubCollocation._1, st)
      })
    )
    longer2shorterCollocations.toMap
  }

  def computeCollocations2SubCollocations(candidates: Iterable[Seq[String]], minSubTermSize: Int) = {
    val existedTermCandidateReprs = candidates.par.toSet

    val candidateAndSubTerms: Iterable[(Seq[String], IndexedSeq[Seq[String]])] = candidates.par.map(words => {
      val termSubWords = (minSubTermSize until words.size)
        .flatMap(l => words.sliding(l))
      val subTerms = termSubWords.filter(existedTermCandidateReprs.contains)
      (words, subTerms)
    }).seq
    candidateAndSubTerms
  }
} 
开发者ID:ispras,项目名称:atr4s,代码行数:55,代码来源:SubTermsComputer.scala


示例7: CollectionsTest

//设置package包名称以及导入依赖的类
import scala.collection.immutable.IndexedSeq


class CollectionsTest {
  (Map[Char,Int]() /: "misss"){
    (m,c)=>m+(c->(m.getOrElse(c,0)+1))
  }


  "misss"./:(Map[Char,Int]()){
    (m,c)=>m+(c->(m.getOrElse(c,0)+1))
  }

  (1 to 10).scanLeft(0)  (_+_)

  Stream.from(1).take(5).force

  import collection.mutable.SortedSet
  def indexes(s : String) = {
    (s zipWithIndex)./:(Map[Char,SortedSet[Int]]()){
      (m,c)=>m+(c._1->(m.getOrElse(c._1,SortedSet[Int]())+ c._2))
    }
  }

  indexes("Mississippi")

  def getMappingValues(keys:Array[String], kvmap: Map[String,Int]) = {
    keys flatMap (kvmap get _)
  }

  val keys = Array("Tom","Fred","Harry")
  val kvmap = Map("Tom"->3,"Dick"->4,"Harry"->5)
  getMappingValues(keys,kvmap)

  val lst = List(1,2,3,4,5)
  println((lst :\ List[Int]())(_ :: _))
  lst./:(List[Int]())(_ :+ _)
  println((List[Int]() /: lst)((a,b) => b :: a))
}

object CollectionsTest{

  def main(args: Array[String]) {
    val fruit:List[String] = "orange" :: "apple" :: "pear" :: Nil
    fruit map (_ + " ") foreach (print)
    print("\n")
    fruit.map(_ + "   ").foreach(print)
    print("\n")
    fruit.init.foreach(print)
    print("\n")

    val ij:IndexedSeq[(Int, Int)] = for{
      i <- 1 to 5
      j <- 6 to 10
    } yield (i,j)
    ij.foreach(print)
    print("\n")
  }
} 
开发者ID:starqiu,项目名称:LearningScala,代码行数:60,代码来源:CollectionsTest.scala


示例8: Activity

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

import scala.collection.immutable.IndexedSeq
import util.Random
import org.joda.time.DateTime
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import collection.JavaConverters._

object Activity extends App {
  val utf8:Charset = StandardCharsets.UTF_8
  val now = new DateTime()
  val lnow: Long = now.getMillis

  val r = new Random()

  val range = 1 to 10000
  val things: IndexedSeq[String] = range.map(n => {
    val randMillis = r.nextInt(60 * 1000)
    val fakeTime = lnow + randMillis
    s"${r.nextInt(25)} $fakeTime ${"x" * r.nextInt(50)}"
  })


  val lines:List[String] = things.toList
  // This seems to expect java.util.List - use JavaConverter to write list items to the file.
  Files.write(Paths.get("activity.txt"), lines.asJava, utf8)

  lines.foreach(println(_))
} 
开发者ID:bradkarels,项目名称:Activity-Generator,代码行数:33,代码来源:Act.scala


示例9: AuthUser

//设置package包名称以及导入依赖的类
package com.dbrsn.auth.model

import java.time.LocalDateTime

import enumeratum.Enum
import enumeratum.EnumEntry

import scala.collection.immutable.IndexedSeq

case class AuthUser[Provider, Profile, UserId](
  provider: Provider,
  email: Option[String],
  profile: Option[Profile],
  createdAt: LocalDateTime,
  lastLoginAt: Option[LocalDateTime],
  userId: Option[UserId]
)

case class ProviderAuthInfo[Provider, AuthInfo](
  provider: Provider,
  authInfo: AuthInfo
)

case class User[UserId](
  id: Option[UserId],
  active: Boolean,
  mergedToUserId: Option[UserId]
)

case class UserRole[UserId, Role](
  userId: UserId,
  role: Role
)

sealed trait CommonRole extends EnumEntry

object CommonRole extends Enum[CommonRole] {
  override def values: IndexedSeq[CommonRole] = findValues

  case object User extends CommonRole

  case object Admin extends CommonRole

} 
开发者ID:dborisenko,项目名称:generic-auth,代码行数:45,代码来源:model.scala


示例10: Stats

//设置package包名称以及导入依赖的类
package models

import java.time.{LocalDate, OffsetDateTime}

import cats.kernel.Semigroup
import enumeratum._

import scala.collection.immutable.IndexedSeq

object Stats {

  case class CommStats(interacted: Int, opened: Int, delivered: Int)

  case class StatsElement(timestamp: OffsetDateTime, commStats: CommStats)

  object CommStats {
    implicit val commStatsSemigroup = new Semigroup[CommStats] {
      override def combine(x: CommStats, y: CommStats): CommStats = {
        CommStats(
          x.interacted + y.interacted,
          x.opened + y.opened,
          x.delivered + y.delivered
        )
      }
    }
  }

  sealed trait TimePeriod extends EnumEntry {
    def getEndDate(start: LocalDate): LocalDate
  }

  object TimePeriod extends PlayEnum[TimePeriod] {
    case object Week extends TimePeriod {
      override def getEndDate(start: LocalDate): LocalDate = start.plusWeeks(1)
    }
    case object Month extends TimePeriod {
      override def getEndDate(start: LocalDate): LocalDate = start.plusMonths(1)
    }
    case object Day extends TimePeriod {
      override def getEndDate(start: LocalDate): LocalDate = start.plusDays(1)
    }

    override def values: IndexedSeq[TimePeriod] = findValues
  }

} 
开发者ID:ovotech,项目名称:comms-audit-log,代码行数:47,代码来源:Stats.scala


示例11: RoutersPart1CustomRoundRobinRouterSpecExercise

//设置package包名称以及导入依赖的类
package jug.workshops.reactive.akka.routing.exercises

import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit}
import common.StopSystemAfterAll
import org.scalatest.{MustMatchers, WordSpecLike}
import jug.workshops.reactive.akka.routing.exercises.RoutersPart1CustomRoundRobinRouterExercise._

import scala.collection.immutable.{IndexedSeq, Seq}

class RoutersPart1CustomRoundRobinRouterSpecExercise extends TestKit(ActorSystem("customRouter"))
with WordSpecLike with MustMatchers with StopSystemAfterAll with ImplicitSender{


  "Custom Round Robin Router" should {
    "route messages to workers in cycles" in {
      val workerProps=Props[CustomWorker]
      val router=system.actorOf(Props(new CustomRouter(5,workerProps)),"customRouter")

      (1 to 10).foreach{_=>
        router ! RoutedJob("someText")
      }

      val results: Seq[AnyRef] =receiveN(10)

      results
        .groupBy(identity)
        .mapValues(_.size).toSeq  must contain allOf(
        "SOMETEXTcustomRouter:worker:1" -> 2,
        "SOMETEXTcustomRouter:worker:2" -> 2,
        "SOMETEXTcustomRouter:worker:3" -> 2,
        "SOMETEXTcustomRouter:worker:4" -> 2,
        "SOMETEXTcustomRouter:worker:5" -> 2
        )
    }
  }

  "Cycle" should {
    "generate cyclic iterator" in {
      val cycle=Cycle.cycleBetween(0,4)

      val result: IndexedSeq[Int] =(1 to 8).map(_ => cycle.next)

      result mustBe  IndexedSeq(0, 1, 2, 3, 0, 1, 2, 3)

    }
  }

} 
开发者ID:PawelWlodarski,项目名称:workshops-reactive,代码行数:50,代码来源:RoutersPart1CustomRoundRobinRouterSpecExercise.scala


示例12: RoutersPart1CustomRoundRobinRouterSpecAnswer

//设置package包名称以及导入依赖的类
package jug.workshops.reactive.akka.routing.answers

import akka.actor.{ActorSystem, Props}
import akka.testkit.{ImplicitSender, TestKit}
import common.StopSystemAfterAll
import jug.workshops.reactive.akka.routing.answers.RoutersPart1CustomRoundRobinRouterAnswer.{CustomRouter, CustomWorker, Cycle, RoutedJob}
import org.scalatest.{MustMatchers, WordSpecLike}

import scala.collection.immutable.{IndexedSeq, Seq}

class RoutersPart1CustomRoundRobinRouterSpecAnswer extends TestKit(ActorSystem("customRouter"))
with WordSpecLike with MustMatchers with StopSystemAfterAll with ImplicitSender{


  "Custom Round Robin Router" should {
    "route messages to workers in cycles" in {
      val workerProps=Props[CustomWorker]
      val router=system.actorOf(Props(new CustomRouter(5,workerProps)),"customRouter")

      (1 to 10).foreach{_=>
        router ! RoutedJob("someText")
      }

      val results: Seq[AnyRef] =receiveN(10)

      results
        .groupBy(identity)
        .mapValues(_.size).toSeq  must contain allOf(
        "SOMETEXTcustomRouter:worker:1" -> 2,
        "SOMETEXTcustomRouter:worker:2" -> 2,
        "SOMETEXTcustomRouter:worker:3" -> 2,
        "SOMETEXTcustomRouter:worker:4" -> 2,
        "SOMETEXTcustomRouter:worker:5" -> 2
        )
    }
  }

  "Cycle" should {
    "generate cyclic iterator" in {
      val cycle=Cycle.cycleBetween(0,4)

      val result: IndexedSeq[Int] =(1 to 8).map(_ => cycle.next)

      result mustBe  IndexedSeq(0, 1, 2, 3, 0, 1, 2, 3)

    }
  }

} 
开发者ID:PawelWlodarski,项目名称:workshops-reactive,代码行数:50,代码来源:RoutersPart1CustomRoundRobinRouterSpecAnswer.scala


示例13: DecoratedIndexedSeqPair

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

import scala.collection.immutable.IndexedSeq

package object sun {

  implicit class DecoratedIndexedSeqPair[K, V](pairs: IndexedSeq[(K, V)]) {
    def trim: IndexedSeq[(K, V)] = {
      def loop(pairs: IndexedSeq[(K, V)]): IndexedSeq[(K, V)] =
        pairs match {
          case head +: body +: tail =>
            if (head._2 == body._2)
              loop(head +: tail)
            else
              head +: loop(body +: tail)
          case _ => pairs
        }

      loop(pairs)
    }

    def merge(that: IndexedSeq[(K, V)])(implicit ordering: Ordering[K]): IndexedSeq[(K, V)] = {
      def loop(left: IndexedSeq[(K, V)], right: IndexedSeq[(K, V)]): IndexedSeq[(K, V)] =
        left match {
          case leftHead +: leftTail =>
            right match {
              case rightHead +: rightTail =>
                if (ordering.compare(leftHead._1, rightHead._1) < 0)
                  leftHead +: loop(leftTail, right)
                else
                  rightHead +: loop(left, rightTail)
              case _ => left
            }
          case _ => right
        }

      loop(pairs, that)
    }
  }

} 
开发者ID:peterpotts,项目名称:sun,代码行数:42,代码来源:package.scala


示例14: Viz

//设置package包名称以及导入依赖的类
import java.io.{File, PrintWriter}

import Tex.{Footer, Header, texString}

import scala.collection.immutable.IndexedSeq
import scala.collection.mutable.ArrayBuffer
import scala.io.Source


object Viz {
  def main(args: Array[String]): Unit = {
    if (args.length < 2) {
      println("Usage:\njava -jar srl2tex.jar INPUT_PRED INPUT_GOLD\nwhere INPUT_PRED is the file containing the " +
        "output of SRL in compact CoNLL format and INPUT_GOLD are the gold SRL annotations in CoNLL2012 format.")
      System.exit(1)
    }

    val inputPred = args(0)
    val inputGold = args(1)
    val inputPredLines = Source.fromFile(inputPred).getLines()

    val outputTexFile = "output.tex"
    val outTexFile = new PrintWriter(new File(outputTexFile))

    // gold as reference
    val corpusGold = new Conll2012(inputGold)
    corpusGold.load()

    val corpusPred = new ConllPredicted(inputPred)
    corpusPred.load()

    assert(corpusGold.getNWords == corpusPred.getNWords)
    assert(corpusGold.getNPropsBio == corpusPred.getNPropsBio)


    val words: ArrayBuffer[ArrayBuffer[String]] = corpusGold.getWords
    val propsBio: ArrayBuffer[IndexedSeq[ArrayBuffer[String]]] = corpusGold.getPropsBio
    val propsBioPred: ArrayBuffer[IndexedSeq[ArrayBuffer[String]]] = corpusPred.getPropsBio
    val texStrings: IndexedSeq[String] = {
      //for ((ws, ps) <- words.zip(propsBio) if ps.nonEmpty; single_ps <- ps) yield texString(ws, single_ps)
      for (i <- words.indices; j <- propsBio(i).indices) yield texString(words(i), propsBio(i)(j), propsBioPred(i)(j))
    }
    outTexFile.write(Header)
    texStrings.foreach(outTexFile.write)
    outTexFile.write(Footer)
    outTexFile.close()

  }
} 
开发者ID:clips,项目名称:srl2tex,代码行数:50,代码来源:Viz.scala


示例15: SingleNodeAllocationStrategy

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

import akka.actor.{ActorRef, ActorSystem, Address}
import akka.cluster.sharding.ShardRegion
import akka.cluster.sharding.ShardRegion.ShardId

import scala.collection.immutable.IndexedSeq
import scala.concurrent.{ExecutionContext, Future}

class SingleNodeAllocationStrategy(
  address: => Option[Address],
  val maxSimultaneousRebalance: Int,
  val nodesToDeallocate: () => Set[Address])(implicit system: ActorSystem, ec: ExecutionContext)
  extends ExtendedShardAllocationStrategy {

  protected def doAllocate(requester: ActorRef, shardId: ShardId, current: Map[ActorRef, IndexedSeq[ShardId]]) = {
    val activeNodes = notIgnoredNodes(current)
    def byAddress(address: Address) = activeNodes find { actor => actor.path.address == address }
    def requesterNode = byAddress(requester.path.address)
    val address = this.address
    def masterNode = for {
      a <- address
      n <- byAddress(a)
    } yield n
    def leastShards(current: Map[ActorRef, IndexedSeq[ShardId]]) = {
      val (regionWithLeastShards, _) = current minBy { case (_, v) => v.size }
      regionWithLeastShards
    }
    def leastShardActive = {
      val currentActiveNodes = current filterKeys { ref => activeNodes contains ref }
      if (currentActiveNodes.isEmpty) None
      else Some(leastShards(currentActiveNodes))
    }

    val result = masterNode orElse requesterNode orElse leastShardActive getOrElse leastShards(current)

    Future successful result
  }

  protected def doRebalance(
    current: Map[ActorRef, IndexedSeq[ShardId]],
    rebalanceInProgress: Set[ShardId]): Future[Set[ShardRegion.ShardId]]= {
    val result = for {
      address <- address.toIterable filterNot nodesToDeallocate().contains
      (actor, shards) <- current if actor.path.address != address
      shard <- shards
    } yield shard

    Future successful result.toSet -- rebalanceInProgress
  }
} 
开发者ID:evolution-gaming,项目名称:akka-tools,代码行数:52,代码来源:SingleNodeAllocationStrategy.scala


示例16: LuceneSearchApi

//设置package包名称以及导入依赖的类
package recipestore.nlp.lucene

import org.apache.lucene.analysis.Analyzer
import org.apache.lucene.index.{DirectoryReader, Terms}
import org.apache.lucene.misc.{HighFreqTerms, TermStats}
import org.apache.lucene.queryparser.simple.SimpleQueryParser
import org.apache.lucene.search.{IndexSearcher, TopDocs}

import scala.collection.JavaConverters._
import scala.collection.immutable.IndexedSeq

protected class LuceneSearchApi(val luceneDAO: LuceneDAO, val analyzer: Analyzer) {
  lazy val indexReader = DirectoryReader.open(luceneDAO.index)
  lazy val indexSearcher = new IndexSearcher(indexReader)

  
  def query(queryStr: String, field: String, numResults: Int = 10): Iterable[Map[String, Iterable[String]]] = {
    val search: TopDocs = indexSearcher.search(new SimpleQueryParser(analyzer, field).parse(queryStr), numResults)
    LuceneSearchResultWrapper.wrapAsSimpleList(search)
  }

  def topFrequencyWords(numTerms: Int, columnName: String): Array[TermStats] = {
    object compareTermStat extends java.util.Comparator[TermStats] {
      override def compare(o1: TermStats, o2: TermStats): Int = o1.docFreq.compare(o2.docFreq)
    }
    val terms = HighFreqTerms.getHighFreqTerms(indexReader, numTerms, columnName, compareTermStat)
    return terms
  }

  def getTermFrequencyVectors(field: String): IndexedSeq[Terms] = {
    (1 to indexReader.numDocs())
      .map(i => indexReader.getTermVector(i, field))

  }


  object LuceneSearchResultWrapper {

    def wrapAsSimpleList(topDocs: TopDocs): Iterable[Map[String, Iterable[String]]] = wrapAsDocument(topDocs)
      .map(document => document.getFields.asScala.map(field => field.name() -> document.getFields(field.name()).map(_.stringValue())
        .toIterable).toMap)
      .toIterable

    private def wrapAsDocument(topDocs: TopDocs) = topDocs.scoreDocs.map(result => indexReader.document(result.doc))
  }

} 
开发者ID:prad-a-RuntimeException,项目名称:semantic-store,代码行数:48,代码来源:LuceneSearchApi.scala


示例17: TestFiveNodesSuite

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

import com.wavesplatform.it.transactions._
import org.scalatest.{BeforeAndAfterAll, FreeSpec, Matchers, Suite}
import scorex.utils.ScorexLogging

import scala.collection.JavaConverters._
import scala.collection.immutable.IndexedSeq
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.util.Random

class TestFiveNodesSuite extends FreeSpec with BeforeAndAfterAll with ScorexLogging with Matchers {
  private val docker = new Docker()
  private val nodesCount = 4
  private val nodeConfigs = Random.shuffle(Docker.NodeConfigs.getConfigList("nodes").asScala).take(nodesCount)
  private val allNodes = nodeConfigs.map(docker.startNode)

  override protected def beforeAll(): Unit = {
    log.debug("Waiting for nodes to start")
    Await.result(Future.traverse(allNodes)(_.status), 1.minute)

    log.debug("Waiting for nodes to connect")
    val peersCounts = Await.result(
      for {
        count <- Future.traverse(allNodes)(_.waitForPeers(nodesCount - 1))
      } yield count, 1.minute
    )

    peersCounts.foreach(c => log.info(s"Connected peers: $c"))

    all(peersCounts.map(_.length)) shouldEqual nodesCount - 1

    log.debug("Starting tests")
  }

  override def nestedSuites: IndexedSeq[Suite] = IndexedSeq(
    new ValidChainGenerationSpec(allNodes),
    new BurnTransactionSpecification(allNodes),
    new IssueTransactionSpecification(allNodes),
    new LeasingTransactionsSpecification(allNodes),
    new MakeAssetNameUniqueTransactionSpecification(allNodes),
    new PaymentTransactionSpecification(allNodes),
    new ReissueTransactionSpecification(allNodes),
    new TransferTransactionSpecification(allNodes),
    new AliasTransactionSpecification(allNodes)
  )

  override protected def afterAll(): Unit = docker.close()
} 
开发者ID:mikepijn,项目名称:wavesnode,代码行数:52,代码来源:TestFiveNodesSuite.scala


示例18: BinarySearchIndexedSeq

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

import scala.collection.immutable.IndexedSeq

object BinarySearchIndexedSeq {
  def indexOf(seq: IndexedSeq[Int], value: Int): Option[Int] = {
    var lower = 0
    var upper = seq.size - 1

    def hasNext = lower < upper

    def next(): Unit = {
      val middle = (lower + upper) / 2

      if (value < seq(middle)) {
        upper = middle - 1
      } else if (value > seq(middle)) {
        lower = middle + 1
      } else {
        lower = middle
        upper = middle
      }
    }

    while (hasNext) next()

    if (value == seq(lower)) Some(lower) else None
  }
} 
开发者ID:peterpotts,项目名称:interview,代码行数:30,代码来源:BinarySearchIndexedSeq.scala


示例19: IndexedSeqPermutation

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

import scala.collection.immutable.IndexedSeq

object IndexedSeqPermutation {
  def permutations[T](seq: IndexedSeq[T]): IndexedSeq[IndexedSeq[T]] = {
    if (seq.isEmpty) {
      IndexedSeq(IndexedSeq.empty[T])
    } else {
      seq.indices.flatMap { index =>
        val (left, middle +: right) = seq.splitAt(index)
        val seqSeq = permutations(left ++ right)
        seqSeq.map(seq => middle +: seq)
      }
    }
  }
} 
开发者ID:peterpotts,项目名称:interview,代码行数:18,代码来源:IndexedSeqPermutation.scala


示例20: BinarySearchIndexedSeqTest

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

import org.scalatest.{Matchers, WordSpec}

import scala.collection.immutable.IndexedSeq

class BinarySearchIndexedSeqTest extends WordSpec with Matchers {
  "A binary search" should {
    "find" in {
      BinarySearchIndexedSeq.indexOf(IndexedSeq(1, 4, 6, 7, 9), 7) shouldEqual Some(3)
    }

    "not find middle" in {
      BinarySearchIndexedSeq.indexOf(IndexedSeq(1, 4, 6, 7, 9), 5) shouldEqual None
    }

    "not find left" in {
      BinarySearchIndexedSeq.indexOf(IndexedSeq(1, 4, 6, 7, 9), 0) shouldEqual None
    }

    "not find right" in {
      BinarySearchIndexedSeq.indexOf(IndexedSeq(1, 4, 6, 7, 9), 10) shouldEqual None
    }

    "find first" in {
      BinarySearchIndexedSeq.indexOf(IndexedSeq(1, 4, 6, 7, 9), 1) shouldEqual Some(0)
    }

    "find last" in {
      BinarySearchIndexedSeq.indexOf(IndexedSeq(1, 4, 6, 7, 9), 9) shouldEqual Some(4)
    }
  }
} 
开发者ID:peterpotts,项目名称:interview,代码行数:34,代码来源:BinarySearchIndexedSeqTest.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Timer类代码示例发布时间:2022-05-23
下一篇:
Scala SprayJsonSupport类代码示例发布时间: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