本文整理汇总了Scala中scala.collection.immutable.Iterable类的典型用法代码示例。如果您正苦于以下问题:Scala Iterable类的具体用法?Scala Iterable怎么用?Scala Iterable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Iterable类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ProgressBarUtil
//设置package包名称以及导入依赖的类
package org.argus.jawa.core.util
import hu.ssh.progressbar.ProgressBar
import scala.collection.immutable.Iterable
object ProgressBarUtil {
def withProgressBar[T, R](msg: String, pb: ProgressBar)(tasks: Iterable[T], f: T => R): Iterable[R] = {
println(msg + " Total: " + tasks.size)
val progressBar = pb.withTotalSteps(tasks.size)
progressBar.start()
val result = tasks.map { task =>
progressBar.tickOne()
f(task)
}
progressBar.complete()
result
}
}
示例2: DevicesController
//设置package包名称以及导入依赖的类
package controllers
import model.Device
import play.api.libs.json._
import play.api.mvc._
import services.DataSource
import scala.collection.immutable.Iterable
import scala.concurrent.ExecutionContext.Implicits.global
class DevicesController(cc: ControllerComponents, ds: DataSource) extends AbstractController(cc) {
def getDevicesAsJson: Action[AnyContent] =
result(devices => Ok(Json.toJson(devices)).as(JSON))
def getDevicesAsHTML: Action[AnyContent] =
result(devices => Ok(views.html.devices(devices.toSeq)))
private[this] def result(mapping: Iterable[Device] => Result) = Action.async {
ds.devices.map { devices =>
mapping(devices)
}
}
}
示例3: DataSourceMock
//设置package包名称以及导入依赖的类
package mocks
import model.{Device, Position, Sensor}
import services.DataSource
import scala.collection.immutable.Iterable
import scala.concurrent.{ExecutionContext, Future}
object DataSourceMock {
val mockDevices = new DataSource {
override val executionContext: ExecutionContext = scala.concurrent.ExecutionContext.global
override def devices: Future[Iterable[Device]] = Future.successful(List(
Device(
1,
"CaDani",
Position(51.461999, 0.125753, 0),
List(Sensor(1, "Luz"), Sensor(2, "Hum"))
),
Device(
2,
"Adri house",
Position(51.462485, 0.126115, 0),
List(Sensor(1, "Luz"), Sensor(2, "Hum"))
),
Device(
3,
"Angelote pelote",
Position(40.733362, -3.946101, 0),
List(Sensor(1, "Luz"), Sensor(2, "Hum"))
)
))
}
}
示例4: SinkExample
//设置package包名称以及导入依赖的类
package com.github.jeroenr.tepkin.examples
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import com.github.jeroenr.bson.{Bulk, BsonDocument, BsonDsl}
import BsonDsl._
import com.github.jeroenr.tepkin.MongoClient
import com.github.jeroenr.bson.Bulk
import scala.collection.immutable.Iterable
object SinkExample extends App {
// Connect to Mongo client
val client = MongoClient("mongodb://localhost")
import client.context
// Obtain reference to database "tepkin" using client
val db = client("tepkin")
// Obtain reference to the collection "collection1" using database
val collection1 = db("collection1")
// Obtain reference to the collection "collection2" using database
val collection2 = db("collection2")
implicit val mat = ActorMaterializer()
// Batch document source
def documents(n: Int): Source[List[BsonDocument], akka.NotUsed] = Source {
Iterable.tabulate(n) { _ =>
(1 to 1000).map(i => $document("name" := s"fehmi$i")).toList
}
}
val ref1 = documents(1000).map(Bulk).runWith(collection1.sink())
val ref2 = documents(2000).map(Bulk).runWith(collection2.sink())
client.shutdown(ref1, ref2)
}
示例5: ThriftResponder
//设置package包名称以及导入依赖的类
package io.livingston.ditto.thrift
import com.twitter.finagle.thrift.Protocols
import com.twitter.finagle.{ListeningServer, Service, Thrift}
import com.twitter.util.{Await, Future}
import com.typesafe.scalalogging.LazyLogging
import io.livingston.ditto.Responder
import org.apache.thrift.transport.TMemoryInputTransport
import scala.collection.immutable.Iterable
import scala.util.Try
class ThriftResponder extends Responder with LazyLogging {
val protocol: String = "thrift"
private var _serverConfigs = Seq.empty[ThriftServerConfig]
private var _listeningServers = Iterable.empty[ListeningServer]
def announce(): Unit = {
_serverConfigs.foreach { server =>
super.announce(server.port, server.endpoints.map(_.msg))
}
}
def apply(yaml: String): Unit = {
import ThriftResponsesProtocol._
super.parse[ThriftResponses](yaml, _.convertTo[ThriftResponses]) { responses =>
_serverConfigs = responses.thrift
val thriftServers = responses.thrift.foldLeft(Map.empty[Int, Map[String, ThriftEndpoint]]) { (serverMap, server) =>
serverMap + (server.port -> server.endpoints.foldLeft(Map.empty[String, ThriftEndpoint]) { (endpointMap, endpoint) =>
endpointMap + (endpoint.msg -> endpoint)
})
}
_listeningServers = thriftServers.map { case (port, endpoints) =>
val service = new Service[Array[Byte], Array[Byte]] {
def apply(request: Array[Byte]): Future[Array[Byte]] = {
val inputTransport = new TMemoryInputTransport(request)
val thriftRequest = Protocols.binaryFactory().getProtocol(inputTransport)
Try {
val msg = thriftRequest.readMessageBegin()
endpoints.get(msg.name).map { e =>
val response = e.body.toArray
Thread.sleep(e.latency.sleepTime)
Future.value(response)
}.getOrElse {
Future.exception(new Exception("Invalid Request"))
}
}.getOrElse(Future.exception(new Exception("")))
}
}
Thrift.server.serve(s":$port", service)
}
}
}
def close(): Unit = {
import com.twitter.conversions.time._
Await.all( _listeningServers.map(_.close()).toSeq, 5.seconds )
}
}
示例6: HttpResponder
//设置package包名称以及导入依赖的类
package io.livingston.ditto.http
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finagle.{Http, ListeningServer, Service}
import com.twitter.util.{Await, Future}
import com.typesafe.scalalogging.LazyLogging
import io.livingston.ditto.Responder
import scala.collection.immutable.Iterable
class HttpResponder extends Responder with LazyLogging {
val protocol: String = "http"
private var _serverConfigs = Seq.empty[HttpServerConfig]
private var _listeningServers = Iterable.empty[ListeningServer]
def announce(): Unit = {
_serverConfigs.foreach { server =>
super.announce(server.port, server.endpoints.map(e => s"${e.method} => ${e.uri}"))
}
}
def apply(yaml: String): Unit = {
type MethodAndUri = (String, String)
import HttpResponsesProtocol._
super.parse[HttpResponses](yaml, _.convertTo[HttpResponses]) { responses =>
_serverConfigs = responses.http
val httpServers = responses.http.foldLeft(Map.empty[Int, Map[MethodAndUri, HttpEndpoint]]) { (serverMap, server) =>
serverMap + (server.port -> server.endpoints.foldLeft(Map.empty[MethodAndUri, HttpEndpoint]) { (endpointMap, endpoint) =>
endpointMap + ((endpoint.method -> endpoint.uri) -> endpoint)
})
}
_listeningServers = httpServers.map { case (port, endpoints) =>
val service = new Service[Request, Response] {
def apply(request: Request): Future[Response] = {
endpoints.get(request.method.toString -> request.uri).map { e =>
val response = Response(request.version, Status(e.status))
response.contentString = e.body
Thread.sleep(e.latency.sleepTime)
Future.value(response)
}.getOrElse {
Future.value(Response(request.version, Status.BadRequest))
}
}
}
Http.serve(s":$port", service)
}
}
}
def close(): Unit = {
import com.twitter.conversions.time._
Await.all( _listeningServers.map(_.close()).toSeq, 5.seconds )
}
}
示例7: replaceByState
//设置package包名称以及导入依赖的类
package aima.core.search
import scala.collection.immutable.Iterable
trait Frontier[Node <: SearchNode] {
def replaceByState(childNode: Node): Frontier[Node]
def getNode(state: State): Option[Node]
def removeLeaf: Option[(Node, Frontier[Node])]
def add(node: Node): Frontier[Node]
def addAll(iterable: Iterable[Node]): Frontier[Node]
def contains(state: State): Boolean
}
trait FrontierSearch {
type Node <: SearchNode
def newFrontier(state: State): Frontier[Node]
}
示例8: BotMain
//设置package包名称以及导入依赖的类
package science.wasabi.tini.bot
import scala.collection.immutable.Iterable
import akka.NotUsed
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import science.wasabi.tini._
import science.wasabi.tini.bot.commands._
import science.wasabi.tini.bot.discord.ingestion.{AkkaCordIngestion, Ingestion}
import science.wasabi.tini.bot.kafka.KafkaStreams
import science.wasabi.tini.config.Config
object BotMain extends App {
println(Helper.greeting)
implicit val config = Config.conf
CommandRegistry.configure(config.bot.commands)
case class Ping(override val args: String) extends Command(args) {}
case class NoOp(override val args: String) extends Command(args) {}
val ingestion: Ingestion = new AkkaCordIngestion
import scala.concurrent.ExecutionContext.Implicits.global
implicit val system = akka.actor.ActorSystem("kafka")
implicit val materializer = ActorMaterializer()
val kafka = new KafkaStreams
// pipe to kafka
def string2command(string: String): Iterable[Command] = CommandRegistry.getCommandsFor(string)
val commandStream: Source[Command, NotUsed] = ingestion.source.mapConcat[Command](dmsg => string2command(dmsg.content))
val commandTopicStream = commandStream.map(kafka.toCommandTopic)
commandTopicStream
.runWith(kafka.sink)
.foreach(_ => println("Done Producing"))
// read from kafka
val commandStreamFromKafka = kafka.sourceFromCommandTopic()
commandStreamFromKafka
.map(command => println("out: " + command))
.runWith(Sink.ignore)
.foreach(_ => println("Done Consuming"))
// TODO: add the reply steam thingy
}
示例9: CommandRegistry
//设置package包名称以及导入依赖的类
package science.wasabi.tini.bot.commands
import scala.util.{Failure, Success, Try}
import scala.collection.immutable.Iterable
import science.wasabi.tini.bot.BotMain.{NoOp, Ping}
object CommandRegistry {
private var commandRegistry: Map[String, Class[_ <: Command]] = Map(
"!ping" -> classOf[Ping],
"" -> classOf[NoOp]
)
case class CommandClassNotFound(notUsed: String) extends Command(argsIn = notUsed) with Serializable
def configure(commands: Map[String, String]): Unit = {
def convertToClass(name: String): Class[Command] = Try(Class.forName(name)) match {
case Success(commandClazz) => commandClazz.asInstanceOf[Class[Command]]
case Failure(exception) =>
exception.printStackTrace()
classOf[CommandClassNotFound].asInstanceOf[Class[Command]]
}
commandRegistry = commandRegistry ++ commands.map {
case (prefix: String, clazz: String) => (prefix, convertToClass(clazz))
}
println(s"Commands are: ${CommandRegistry.commandRegistry}")
}
def getCommandsFor(args: String): Iterable[Command] = commandRegistry
.filter { case (string, _) => args.startsWith(string) }
.map { case (string, clazz) => clazz
.getConstructor(classOf[String])
.newInstance(args.drop(string.length).trim)
}
def unapply(args: String): Option[Command] = commandRegistry
.find { case (string, _) => args.startsWith(string) }
.map { case (string, clazz) => clazz
.getConstructor(classOf[String])
.newInstance(args.drop(string.length).trim)
}
}
abstract class Command(argsIn: String) extends Serializable {
val args: String = argsIn
}
示例10: AhcResponseLogger
//设置package包名称以及导入依赖的类
package services
import org.slf4j.LoggerFactory
import play.api.libs.ws.{ WSRequest, WSRequestExecutor, WSRequestFilter, WSResponse }
import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.collection.immutable.Iterable
case class AhcResponseLogger(
headers: Boolean = true,
statusCode: Boolean = true,
body: Boolean = false
) extends WSRequestFilter {
private val logger = LoggerFactory.getLogger(classOf[AhcResponseLogger])
override def apply(executor: WSRequestExecutor): WSRequestExecutor = {
new WSRequestExecutor {
override def execute(request: WSRequest): Future[WSResponse] = {
val futureResponse: Future[WSResponse] = executor.execute(request)
futureResponse.map { response =>
logStatusCode(response)
logHeaders(response)
logBody(response)
response
}
}
private def logStatusCode(response: WSResponse) = if (statusCode) {
logger.info(s"${response.status} ${response.statusText}")
}
private def logHeaders(response: WSResponse) = if (headers) {
val formattedHeaders: Iterable[String] = response.allHeaders.map(header => s"${header._1}: ${header._2.mkString(",")}")
logger.info(formattedHeaders.mkString(start = "\n", sep = "\n", end = "\n"))
}
private def logBody(response: WSResponse) = if (body) {
logger.info(s"${response.body}")
}
}
}
}