本文整理汇总了Scala中scala.collection.mutable.Buffer类的典型用法代码示例。如果您正苦于以下问题:Scala Buffer类的具体用法?Scala Buffer怎么用?Scala Buffer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Buffer类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: HTMLElementOps
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.client
import com.thoughtworks.binding
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding._
import org.scalajs.dom
import org.scalajs.dom.raw._
import scala.collection.mutable.Buffer
import scala.scalajs.js
import walfie.gbf.raidfinder.client.ViewModel.ImageQuality
import walfie.gbf.raidfinder.protocol._
import js.Dynamic.global
package object syntax {
implicit class HTMLElementOps[T <: HTMLElement](val elem: T) extends AnyVal {
def :=(elements: TraversableOnce[T]): Buffer[T] = {
buffer.clear()
buffer ++= elements
}
}
implicit class StringOps(val string: String) extends AnyVal {
def addIf(condition: Boolean, s: String): String =
if (condition) s"$string $s" else string
}
implicit class LanguageOps(val language: Language) extends AnyVal {
def shortName: Option[String] = language match {
case Language.JAPANESE => Some("JP")
case Language.ENGLISH => Some("EN")
case _ => None
}
}
}
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:37,代码来源:package.scala
示例2: CollectionExample
//设置package包名称以及导入依赖的类
package com.chapter3.ScalaFP
import scala.collection._
import scala.collection.mutable.Buffer
import scala.collection.mutable.HashMap
object CollectionExample {
def main(args: Array[String]) {
val x = 10
val y = 15
val z = 19
Traversable(1, 2, 3)
Iterable("x", "y", "z")
Map("x" -> 10, "y" -> 13, "z" -> 17)
Set("Red", "Green", "Blue")
SortedSet("Hello,", "world!")
Buffer(x, y, z)
IndexedSeq(0.0, 1.0, 2.0)
LinearSeq(x, y, z)
List(2, 6, 10)
HashMap("x" -> 20, "y" -> 19, "z" -> 16)
val list = List(1, 2, 3) map (_ + 1)
println(list)
val set = Set(1, 2, 3) map (_ * 2)
println(set)
val list2 = List(x, y, z).map(x => x * 3)
println(list2)
}
}
开发者ID:PacktPublishing,项目名称:Scala-and-Spark-for-Big-Data-Analytics,代码行数:33,代码来源:CollectionExample.scala
示例3: ChanTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle.util
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import java.util.concurrent.CyclicBarrier
import scala.collection.mutable.Buffer
import java.util.concurrent.CountDownLatch
@RunWith(classOf[JUnitRunner])
class ChanTest extends FunSuite {
test("Proc should admit one at a time, in the order received, queueing items") {
val threads = Buffer[Thread]()
val l = new CountDownLatch(1)
val b = new CyclicBarrier(2)
val p = Proc[Thread] { t => threads += t; l.countDown(); b.await() }
val t0 = new Thread {
override def run() {
p ! this
}
}
val t1 = new Thread {
override def run() {
l.await()
p ! this
b.await()
b.await()
}
}
t0.start();
t1.start()
t0.join();
t1.join()
assert(threads.toSeq == Seq(t0, t1))
}
test("Proc should swallow exceptions") {
val p = Proc[Int] { _ => throw new RuntimeException }
assert((p ! 4) ===((): Unit))
}
}
开发者ID:wenkeyang,项目名称:finagle,代码行数:48,代码来源:ChanTest.scala
示例4: notify
//设置package包名称以及导入依赖的类
package se.lu.nateko.cp.doi.gui.redux
import scala.collection.mutable.Buffer
trait Redux{
type State
type Action
type Reducer = Function2[Action, State, State]
trait StateListener{
def notify(newState: State, oldState: State): Unit
}
trait Dispatcher{
def getState: State
def dispatch(action: ThunkAction): Unit
def dispatch(action: Action): Unit
}
type ThunkAction = Function1[Dispatcher, Unit]
class Store(reducer: Reducer, init: State) extends Dispatcher{
private[this] val subscribers = Buffer.empty[StateListener]
private[this] var state : State = init
def getState: State = state
def subscribe(listener: StateListener): Boolean = {
if(subscribers.indexOf(listener) < 0) {
subscribers += listener
true
} else false
}
def unsubscribe(listener: StateListener): Boolean = {
val idx = subscribers.indexOf(listener)
if(idx >= 0) {
subscribers.remove(idx)
true
} else false
}
def dispatch(action: Action): Unit = schedule{
val oldState = state
state = reducer(action, oldState)
subscribers.foreach(s => schedule(s.notify(state, oldState)))
}
def dispatch(thunk: ThunkAction): Unit = schedule(thunk(this))
private def schedule(work: => Unit): Unit = scala.scalajs.concurrent.JSExecutionContext
.Implicits.queue.execute(
new Runnable{
override def run(): Unit = work
}
)
}
}
开发者ID:ICOS-Carbon-Portal,项目名称:doi,代码行数:61,代码来源:Redux.scala
示例5: MultiEntitiesEditWidget
//设置package包名称以及导入依赖的类
package se.lu.nateko.cp.doi.gui.widgets.generic
import scalatags.JsDom.all._
import scala.collection.mutable.Buffer
import org.scalajs.dom.Event
import se.lu.nateko.cp.doi.gui.views.Bootstrap
abstract class MultiEntitiesEditWidget[E, W <: EntityWidget[E]](initValues: Seq[E], cb: Seq[E] => Unit){
protected val title: String
protected def makeWidget(value: E, updateCb: E => Unit): W
protected def defaultValue: E
protected val minAmount: Int
private val widgets = Buffer.empty[RemovableEntityWidget[E]]
private def setRemovability(): Unit = if(minAmount > 0) {
widgets.foreach(_.setRemovability(widgets.length > minAmount))
}
private def notifyUpstream(): Unit = cb(widgets.map(_.entityValue))
private val widgetsParent = div(cls := "col-md-11").render
private def produceWidget(value: E): Unit = {
val widgetFactory: (E => Unit) => W = makeWidget(value, _)
val newWidget = new RemovableEntityWidget[E](widgetFactory, value, _ => notifyUpstream(), widget => {
widgets -= widget
widgetsParent.removeChild(widget.element)
setRemovability()
notifyUpstream()
})
widgetsParent.appendChild(newWidget.element)
widgets += newWidget
}
initValues.foreach(produceWidget)
setRemovability()
private val addWidget: Event => Unit = (_: Event) => {
produceWidget(defaultValue)
setRemovability()
notifyUpstream()
}
val element = Bootstrap.basicPanel(
div(cls := "row")(
div(cls := "col-md-1")(
span(strong(title)),
raw(" "),
button(tpe := "button", cls := "btn btn-success", onclick := addWidget, marginBottom := 5)(
span(cls := "glyphicon glyphicon-plus")
)
),
widgetsParent
)
)
}
开发者ID:ICOS-Carbon-Portal,项目名称:doi,代码行数:60,代码来源:MultiEntitiesEditWidget.scala
示例6: Cell
//设置package包名称以及导入依赖的类
package mechanics
import scala.collection.mutable.Buffer
class Cell(val terrainType: Terrain.Value) {
private val charBuffer = Buffer[Character]()
private var buildingOption: Option[Building] = None
private var buildingPartOption: Option[(Int, Int)] = None
private val itemBuffer = Buffer[Item]()
def add(character: Character) = {
charBuffer += character
}
def add(building: Building, part: (Int, Int))= {
buildingOption = Some(building)
buildingPartOption = Some(part)
}
def add(item: Item) = {
itemBuffer += item
}
def characters = charBuffer.toVector
def building = buildingOption
def buildingPart = buildingPartOption
def items = itemBuffer.toVector
def isEmpty = characters.isEmpty && building.isEmpty && items.isEmpty
}
object Cell {
def apply() = new Cell(Terrain.PLAIN)
}
开发者ID:Berthur,项目名称:AgeOfLords,代码行数:37,代码来源:Cell.scala
示例7: es
//设置package包名称以及导入依赖的类
package dbpedia.dataparsers.ontology
import scala.collection.mutable.{ArrayBuffer, Buffer}
import dbpedia.dataparsers.DBpediaNamespace
import dbpedia.dataparsers.util.{Language, RdfNamespace}
lazy val relatedClasses: Seq[OntologyClass] = {
val classes = new ArrayBuffer[OntologyClass]()
collectClasses(classes)
classes
}
private def collectClasses(classes: Buffer[OntologyClass]): Unit = {
// Note: If this class was already collected, we do nothing, so we silently skip cycles in
// class relations here. Some cycles are allowed (for example between equivalent classes,
// but there are other cases), others aren't. At this point, it's not easy to distinguish valid
// and invalid cycles, so we ignore them all. Cycles should be checked when classes are loaded.
// Note: a set would be nicer than a buffer to check contains(), but we want to keep the order.
if (! classes.contains(this)) {
classes += this
equivalentClasses.foreach(_.collectClasses(classes))
baseClasses.foreach(_.collectClasses(classes))
}
}
override val uri = RdfNamespace.fullUri(DBpediaNamespace.ONTOLOGY, name)
val isExternalClass = ! uri.startsWith(DBpediaNamespace.ONTOLOGY.namespace)
}
开发者ID:FnOio,项目名称:dbpedia-parsing-functions-scala,代码行数:31,代码来源:OntologyClass.scala
示例8: attach
//设置package包名称以及导入依赖的类
package com.olegych.scastie.api
package runtime
import org.scalajs.dom.raw.HTMLElement
import scala.scalajs.js
import scala.collection.mutable.Buffer
import java.util.UUID
trait DomHook {
private val elements = Buffer.empty[HTMLElement]
def attach(element: HTMLElement): UUID = {
val uuid = UUID.randomUUID()
element.setAttribute("uuid", uuid.toString)
elements += element
uuid
}
def attachedElements(): js.Array[HTMLElement] = elements.to[js.Array]
}
开发者ID:scalacenter,项目名称:scastie,代码行数:23,代码来源:DomHook.scala
示例9: ChanSpec
//设置package包名称以及导入依赖的类
package com.twitter.finagle.util
import org.specs.SpecificationWithJUnit
import java.util.concurrent.CyclicBarrier
import scala.collection.mutable.Buffer
import java.util.concurrent.CountDownLatch
class ChanSpec extends SpecificationWithJUnit {
"Proc" should {
"admit one at a time, in the order received, queueing items" in {
val threads = Buffer[Thread]()
val l = new CountDownLatch(1)
val b = new CyclicBarrier(2)
val p = Proc[Thread] { t => threads += t; l.countDown(); b.await() }
val t0 = new Thread {
override def run() {
p ! this
}
}
val t1 = new Thread {
override def run() {
l.await()
p ! this
b.await()
b.await()
}
}
t0.start(); t1.start()
t0.join(); t1.join()
threads.toSeq mustEqual Seq(t0, t1)
}
}
}
开发者ID:deenar,项目名称:fintest,代码行数:39,代码来源:ChanSpec.scala
示例10: Suunta
//设置package包名称以及导入依赖的类
package siirrot
import scala.collection.mutable.Buffer
case class Suunta(kohde: Koordinaatti) extends Siirto(Koordinaatti(0,0), kohde) {
def muutaSiirroksi(lahto: Koordinaatti) = new Siirto(lahto, lahto+this.kohde)
override def toString() = this.kohde.toString()
}
object Suunta {
//Luo Suunnan, joka on tiettyä vaihdetta ja mahdollisimman lähellä annettua kulmaa
def apply(vaihde: Int, kulma: Double): Suunta = {
val vaihtoehdot = suunnatVaihteella(vaihde)
Suunta(kulma, vaihtoehdot)
}
//Valitsee annetuista Suunnista sen, joka on lähimpänä annettua kulmaa
def apply(kulma: Double, vaihtoehdot: Vector[Suunta]): Suunta = {
if (vaihtoehdot.length > 0) {
vaihtoehdot.reduce{(suunta1, suunta2) =>
if (Math.abs(suunta1.kulma - kulma) <= Math.abs(suunta2.kulma - kulma)) suunta1
else suunta2
}
} else {
Suunta(Koordinaatti(0,0)) //Virhelliseen syötteeseen vastataan 0-suunnalla
}
}
//Listaa kaikki mahdolliset suunnaat, joihin tietyllä vaihteella pääsee.
def suunnatVaihteella(vaihde: Int): Vector[Suunta] = {
val suunnat = Buffer[Suunta]()
for (i <- -vaihde to vaihde; j <- -vaihde to vaihde) { //Pisin edettävä suunta on vaihteen arvo
if ( Math.max( Math.abs(i), Math.abs(j) ) == vaihde ) suunnat.append(Suunta(Koordinaatti(i,j)))
}
suunnat.toVector
}
}
开发者ID:MrAurela,项目名称:Formula,代码行数:42,代码来源:Suunta.scala
示例11: BackgroundTaskSchedulerImpl
//设置package包名称以及导入依赖的类
package ch.loewenfels.jira.plugin.synchronisation
import java.util.Date
import scala.collection.JavaConverters.asScalaBufferConverter
import scala.collection.mutable.Buffer
import org.slf4j.LoggerFactory
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.fields.config.FieldConfig
import com.atlassian.sal.api.lifecycle.LifecycleAware
import com.atlassian.sal.api.scheduling.PluginScheduler
import ch.loewenfels.jira.plugin.config.VertecConfig
import ch.loewenfels.jira.plugin.customfields.CustomFieldProvider
class BackgroundTaskSchedulerImpl(pluginScheduler: PluginScheduler, config: VertecConfig, customFieldProvider: CustomFieldProvider, syncService: SyncService) extends LifecycleAware with BackgroundTaskScheduler {
val logger = LoggerFactory.getLogger(classOf[BackgroundTaskSchedulerImpl])
val name = classOf[BackgroundTaskSchedulerImpl].getName.concat(":job")
def onStart(): Unit = {
logger.trace("Starting SyncServiceMonitor")
reschedule(config.syncIntervalInMs.getOrElse("3600000").toLong)
}
def reschedule(interval: Long): Unit = {
var map = new java.util.HashMap[String, Object]()
map.put(BackgroundTaskConfig.SERVICE, syncService)
map.put(BackgroundTaskConfig.FIELD_CONFIG, collectFieldConfigs)
pluginScheduler.scheduleJob(name, classOf[BackgroundTask], map, new Date(), interval)
logger.info("Synchronisation task scheduled to run every {}ms", interval)
}
private def collectFieldConfigs: Seq[FieldConfig] = {
for {
customField <- customFieldProvider.filter(CustomFieldProvider.VertecKey)
scheme <- customField.getConfigurationSchemes.asScala
} yield {
scheme.getOneAndOnlyConfig
}
}
}
开发者ID:loewenfels,项目名称:jira-vertec-plugin,代码行数:42,代码来源:BackgroundTaskSchedulerImpl.scala
示例12: AnormUtil
//设置package包名称以及导入依赖的类
package anorm
import scala.collection.mutable.Buffer
import java.sql.Connection
import org.slf4j.LoggerFactory
object AnormUtil {
private val logger = LoggerFactory.getLogger("uk.ac.ncl.openlab.intake24.AnormUtil")
def escapeLike(s: String) = s.replace("\\", "\\\\").replace("_", "\\_").replace("%", "\\%")
def isNull(row: Row, columnName: String): Boolean = row.get(columnName).get._1 == null
@deprecated("Create a pull request for anorm instead...")
def batchKeys(sql: BatchSql)(implicit conn: Connection): Seq[Long] = {
val stmt = sql.getFilledStatement(conn, true)
val result = stmt.executeBatch()
val keys = stmt.getGeneratedKeys()
try {
if (result.exists(_ != 1))
throw new RuntimeException("Failed batch update")
val buf = Buffer[Long]()
while (keys.next()) {
buf += keys.getLong("id")
}
buf
} catch {
case e: Throwable => throw e
} finally {
keys.close()
stmt.close()
}
}
}
开发者ID:digitalinteraction,项目名称:intake24,代码行数:42,代码来源:AnormUtil.scala
示例13: Boot
//设置package包名称以及导入依赖的类
package jp.kenichi.lrcon
package server
import java.io.{File, FileInputStream, InputStreamReader, BufferedReader}
import java.nio.file.{Path, Paths}
import scala.collection.mutable.Buffer
import loader.ChildFirstClassLoader
object Boot extends App {
val serverClasspath = Buffer[Path]()
val serverArgs = Buffer[String]()
def parseArgs(args: List[String]): Unit = args match {
case "-serverClasspath" :: arg :: rest =>
serverClasspath ++= arg.split(File.pathSeparator).map(Paths.get(_))
parseArgs(rest)
// parameter file (non-empty lines become arguments)
case arg :: rest if (arg.startsWith("@")) =>
val in = new BufferedReader(new InputStreamReader(new FileInputStream(arg.drop(1)), "UTF-8"))
val fileArgs = Buffer[String]()
try {
Iterator.continually(in.readLine).takeWhile(_ != null).map(_.trim).filter(_.nonEmpty).foreach { line =>
if (!line.startsWith("#"))
fileArgs += line
}
} finally {
in.close
}
parseArgs(fileArgs.toList ++ rest)
case arg :: rest =>
serverArgs += arg
parseArgs(rest)
case Nil =>
}
parseArgs(args.toList)
if (serverClasspath.isEmpty) {
// TODO: complement
System.err.println("specify -serverClasspath")
System.exit(255)
}
// println("systemClassLoader = " + ClassLoader.getSystemClassLoader)
// println("contextClassLoader = " + Thread.currentThread.getContextClassLoader)
ChildFirstClassLoader.toplevelClassLoader = ClassLoader.getSystemClassLoader // same as Thread.currentThread.getContextClassLoader when launched by java command
val serverClassLoader = new ChildFirstClassLoader(serverClasspath, ClassLoader.getSystemClassLoader, Some("server"))
val serverCls = serverClassLoader.loadClass(getClass.getPackage.getName + ".Server")
Thread.currentThread.setContextClassLoader(serverClassLoader)
serverCls.getMethod("main", classOf[Array[String]]).invoke(null, serverArgs.toArray)
}
开发者ID:ken1ma,项目名称:lrcon,代码行数:57,代码来源:Boot.scala
注:本文中的scala.collection.mutable.Buffer类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论