本文整理汇总了Scala中scala.collection.mutable.ArrayBuffer类的典型用法代码示例。如果您正苦于以下问题:Scala ArrayBuffer类的具体用法?Scala ArrayBuffer怎么用?Scala ArrayBuffer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ArrayBuffer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ZipUtils
//设置package包名称以及导入依赖的类
package core
import java.io.Closeable
import java.nio.charset.StandardCharsets._
import java.util.zip.{ZipEntry, ZipInputStream}
import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer
object ZipUtils {
case class UnzippedFileContent(filename: String, content: String)
def usingZip[R <: Closeable, T](unzippedStream: R)(f: (R) => T) = {
try {
f(unzippedStream)
} finally {
unzippedStream.close()
}
}
def unzipAllFilesInStream(unzippedStream: ZipInputStream): Stream[UnzippedFileContent] = {
unzipAllFilesInStream(unzippedStream, Option(unzippedStream.getNextEntry))
}
def unzipAllFilesInStream(unzippedStream: ZipInputStream, ze: Option[ZipEntry]): Stream[UnzippedFileContent] = {
ze match {
case None => Stream.empty
case Some(ze) =>
val name: String = ze.getName
val entry: String = ZipUtils.getZipEntry(unzippedStream)
val maybeEntry1: Option[ZipEntry] = Option(unzippedStream.getNextEntry)
UnzippedFileContent(name, entry) #::
unzipAllFilesInStream(unzippedStream, maybeEntry1)
}
}
def getZipEntry(zis: ZipInputStream): String = {
val buffer = new Array[Byte](4096)
val stringBuffer = new ArrayBuffer[Byte]()
var len: Int = zis.read(buffer)
while (len > 0) {
stringBuffer ++= buffer.take(len)
len = zis.read(buffer)
}
val content: String = new String(stringBuffer.toArray, UTF_8)
(content)
}
}
示例2: list
//设置package包名称以及导入依赖的类
package uk.co.odinconsultants.bitcoin.integration.hadoop
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path
import org.apache.hadoop.hdfs.DistributedFileSystem
import uk.co.odinconsultants.bitcoin.core.Logging
import uk.co.odinconsultants.bitcoin.integration.hadoop.HadoopForTesting.hdfsCluster
import scala.collection.mutable.ArrayBuffer
trait MiniHadoopClusterRunning extends Logging {
val distributedFS: DistributedFileSystem = hdfsCluster.getFileSystem
val conf: Configuration = HadoopForTesting.conf
val dir = s"/${this.getClass.getSimpleName}/"
def list(path: String): List[Path] = {
info(s"Looking in $path")
val files = distributedFS.listFiles(new Path(path), true)
val allPaths = ArrayBuffer[Path]()
while (files.hasNext) {
val file = files.next
allPaths += file.getPath
}
allPaths.toList
}
def copyToHdfs(inputFile: Path): Path = {
val fromFile = inputFile.getName
distributedFS.mkdirs(new Path(dir))
val toFile = new Path(dir + fromFile)
info(s"Copying '$fromFile' to '$toFile' (${toFile.getName})")
distributedFS.copyFromLocalFile(false, true, inputFile, toFile)
toFile
}
def localFile(local: String): Path = {
val classLoader = getClass.getClassLoader
val localFQN = classLoader.getResource(local).getFile
new Path(localFQN)
}
}
示例3: TorrentPiece
//设置package包名称以及导入依赖的类
package com.karasiq.bittorrent.format
import akka.util.ByteString
import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
case class TorrentPiece(index: Int, size: Int, sha1: ByteString, file: TorrentFile)
case class TorrentPieceBlock(piece: TorrentPiece, offset: Int, size: Int)
object TorrentPiece {
def pieces(files: TorrentFiles): IndexedSeq[TorrentPiece] = {
// Total torrent size
val totalSize = files.files.map(_.size).sum
@tailrec
def pieceSequenceRec(buffer: ArrayBuffer[TorrentPiece], offset: Long, fileOffset: Long, pieceIndex: Int, fileSeq: Seq[TorrentFile]): IndexedSeq[TorrentPiece] = fileSeq match {
case Seq(currentFile, fs @ _*) if fs.nonEmpty && fileOffset >= currentFile.size ?
pieceSequenceRec(buffer, offset, 0L, pieceIndex, fs)
case fs @ Seq(currentFile, _*) if offset < totalSize ?
val length = Array(files.pieceLength.toLong, totalSize - offset).min
require(length <= Int.MaxValue)
val sha1 = files.pieces.slice(pieceIndex * 20, (pieceIndex * 20) + 20)
val piece = TorrentPiece(buffer.length, length.toInt, sha1, currentFile)
pieceSequenceRec(buffer :+ piece, offset + length, fileOffset + length, pieceIndex + 1, fs)
case other ?
buffer.result()
}
pieceSequenceRec(new ArrayBuffer[TorrentPiece](files.pieces.length / 20), 0L, 0L, 0, files.files)
}
def blocks(piece: TorrentPiece, sizeLimit: Int): IndexedSeq[TorrentPieceBlock] = {
@tailrec
def pieceBlockRec(buffer: ArrayBuffer[TorrentPieceBlock], offset: Int): IndexedSeq[TorrentPieceBlock] = {
if (offset >= piece.size) {
buffer.result()
} else {
val block = TorrentPieceBlock(piece, offset, Array(sizeLimit, piece.size - offset).min)
pieceBlockRec(buffer :+ block, offset + block.size)
}
}
pieceBlockRec(new ArrayBuffer[TorrentPieceBlock](piece.size / sizeLimit + 1), 0)
}
}
示例4: IntQueue
//设置package包名称以及导入依赖的类
import scala.collection.mutable.ArrayBuffer
abstract class IntQueue {
def get(): Int
def put(x: Int)
}
class BasicIntQueue extends IntQueue {
private val buf = new ArrayBuffer[Int]
def get() = buf.remove(0)
def put(x: Int) {buf += x}
}
trait Doubling extends IntQueue {
abstract override def put(x: Int) {super.put(2 * x)}
}
trait Incrementing extends IntQueue {
abstract override def put(x: Int) {super.put(x + 1)}
}
trait Filtering extends IntQueue {
abstract override def put(x: Int) {if (x >= 0) super.put(x)}
}
val q = new BasicIntQueue with Incrementing with Doubling
for (i <- -3 to 5) {
q.put(i)
}
println(q.get())
println(q.get())
println(q.get())
println(q.get())
示例5: LazyVar
//设置package包名称以及导入依赖的类
package lazyvar2
import scala.collection.mutable.ArrayBuffer
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.atomic.AtomicLong
object LazyVar {
var n = new AtomicLong(0L)
def apply[T](v : T) = new LazyVar[T](v)
}
class LazyVar[T](var value : T) {
val order = LazyVar.n.getAndIncrement
var buffer = ArrayBuffer[T => T]()
val lock = new ReentrantLock()
def force = {
if(buffer.size > 0) {
lock.lock()
for(f <- buffer)
value = f(value)
buffer = ArrayBuffer[T => T]() //clear()
lock.unlock()
}
}
}
示例6: TransformationBenchmark
//设置package包名称以及导入依赖的类
package lazytx.benchmark.transform
import scala.collection.mutable.ArrayBuffer
object TransformationBenchmark {
def benchmark(reporter : TransformationBenchmarkReporter, threadCount : Int, transform : () => Unit, workload : () => Unit, warmupTime : Double, introTime : Double, totalTime : Double) = {
var done = false;
var threads = ArrayBuffer[Thread]()
for(i <- 1 to threadCount) {
threads += new Thread() {
override def run() {
while(!done) {
workload()
reporter.tx()
}
}
}
}
threads.foreach(_.start())
Thread.sleep((warmupTime * 1000).toLong)
System.gc()
val start = System.nanoTime()
reporter.intro()
Thread.sleep((introTime * 1000).toLong)
reporter.beginTransform()
transform()
reporter.endTransform()
val now = System.nanoTime()
val passed = (now - start) / 1000000000.0
val remaining = totalTime - passed
if(remaining > 0)
Thread.sleep((remaining * 1000).toLong)
reporter.end()
done = true;
threads.foreach(_.join())
}
}
示例7: Tile
//设置package包名称以及导入依赖的类
package mcross1882.mahjong
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
case class Tile(category: String, value: String) {
def intValue(): Int = Tile.NUMERALS.indexOf(value) + 1
override def toString(): String = s"$value$category"
}
object Tile {
val NUMERALS = Seq("?", "?", "?", "?", "?", "?", "?", "?", "?")
val DIRECTIONS = Seq("?", "?", "?", "?")
val CATEGORY_TIAO = "?"
val CATEGORY_WAN = "?"
val CATEGORY_TONG = "?"
val CATEGORY_FENG = "?"
def isSuitedTile(tile: Tile): Boolean = {
tile.category == CATEGORY_WAN || tile.category == CATEGORY_FENG || tile.category == CATEGORY_TIAO || tile.category == CATEGORY_TONG
}
def startingTiles(): ArrayBuffer[Tile] = {
val buffer = new ArrayBuffer[Tile]
buffer ++= Seq.fill(4)(Tile("?", "?"))
buffer ++= Seq.fill(4)(Tile("?", "?"))
buffer ++= Seq.fill(4)(Tile("?", "?"))
tileRange(CATEGORY_TIAO, NUMERALS, buffer)
tileRange(CATEGORY_WAN, NUMERALS, buffer)
tileRange(CATEGORY_TONG, NUMERALS, buffer)
tileRange(CATEGORY_FENG, DIRECTIONS, buffer)
Random.shuffle(buffer)
}
private def tileRange(category: String, values: Seq[String], buffer: ArrayBuffer[Tile]) {
for (value <- values) {
for (repeat <- 0 until 4) {
buffer.append(Tile(category, value))
}
}
}
}
示例8: FutureCollector
//设置package包名称以及导入依赖的类
package com.init6.utils
import scala.collection.mutable.ArrayBuffer
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.util.Success
object FutureCollector {
implicit def futureSeqToFutureCollector[A](futures: Iterable[Future[A]])(implicit executor: ExecutionContext): FutureCollector[A] =
new FutureCollector[A](futures)
}
sealed class FutureCollector[A](futures: Iterable[Future[A]])(implicit executor: ExecutionContext) {
def collectResults[B](task: A => Option[B]): Future[Seq[B]] = {
val returnPromise = Promise[Seq[B]]()
if (futures.nonEmpty) {
var counter = futures.size
val returnSeq = new ArrayBuffer[B](counter)
futures.foreach(future => {
future.onComplete(futureState => {
val valueOpt = futureState match {
case Success(action) => task(action)
case _ => None
}
synchronized {
valueOpt.foreach(returnSeq += _)
counter -= 1
if (counter <= 0) {
returnPromise.success(returnSeq)
}
}
})
})
} else {
returnPromise.success(Seq.empty)
}
returnPromise.future
}
}
示例9: UndoSnackbarManager
//设置package包名称以及导入依赖的类
package com.github.shadowsocks.widget
import android.support.design.widget.Snackbar
import android.view.View
import com.github.shadowsocks.R
import scala.collection.mutable.ArrayBuffer
class UndoSnackbarManager[T](view: View, undo: Iterator[(Int, T)] => Unit,
commit: Iterator[(Int, T)] => Unit = null) {
private val recycleBin = new ArrayBuffer[(Int, T)]
private val removedCallback = new Snackbar.Callback {
override def onDismissed(snackbar: Snackbar, event: Int) = {
event match {
case Snackbar.Callback.DISMISS_EVENT_SWIPE | Snackbar.Callback.DISMISS_EVENT_MANUAL |
Snackbar.Callback.DISMISS_EVENT_TIMEOUT =>
if (commit != null) commit(recycleBin.iterator)
recycleBin.clear
case _ =>
}
last = null
}
}
private var last: Snackbar = _
def remove(index: Int, item: T) = {
recycleBin.append((index, item))
val count = recycleBin.length
last = Snackbar
.make(view, view.getResources.getQuantityString(R.plurals.removed, count, count: Integer), Snackbar.LENGTH_LONG)
.setCallback(removedCallback).setAction(R.string.undo, (_ => {
undo(recycleBin.reverseIterator)
recycleBin.clear
}): View.OnClickListener)
last.show
}
def flush = if (last != null) last.dismiss
}
示例10: TrackSplitter
//设置package包名称以及导入依赖的类
package com.esri
import scala.collection.mutable.ArrayBuffer
class TrackSplitter(time: Long, dist: Double) {
private val _tracks = new ArrayBuffer[Seq[Target]]()
private var _targets = new ArrayBuffer[Target]()
private var _last = None: Option[Target]
def +(currTarget: Target) = {
val lastTarget = _last.getOrElse(currTarget)
val timeDel = currTarget.millis - lastTarget.millis
val distDel = currTarget distance lastTarget
if (timeDel > time || distDel > dist) {
_tracks += _targets
_targets = new ArrayBuffer[Target]()
}
_targets += currTarget
_last = Some(currTarget)
this
}
def tracks(): Seq[Seq[Target]] = {
_tracks += _targets
}
}
object TrackSplitter {
def apply(time: Long, dist: Double): TrackSplitter = new TrackSplitter(time, dist)
}
示例11: occurred
//设置package包名称以及导入依赖的类
package scala_programming_2nd
import scala.collection.mutable.ArrayBuffer
trait ListenerSupport {
type S <: Source
type E <: Event
type L <: Listener
trait Event {
var source: S = _
}
trait Listener {
def occurred(e: E): Unit
}
trait Source {
this: S =>
private val listeners = new ArrayBuffer[L]
def add(l: L) = listeners += l
def remove(l: L) = listeners -= l
def fire(e: E): Unit = {
e.source = this
for (l <- listeners) l.occurred(e)
}
}
}
object ButtonModule extends ListenerSupport {
type S = Button
type E = ButtonEvent
type L = ButtonListener
class ButtonEvent extends Event
trait ButtonListener extends Listener
class Button extends Source {
def click() { fire(new ButtonEvent)}
}
}
object main1 {
import ButtonModule._
def main(args: Array[String]):Unit = {
val b = new Button
b.add(new ButtonListener {
override def occurred(e: ButtonEvent): Unit = println(e)
})
b.click()
}
}
示例12: ExperimentData
//设置package包名称以及导入依赖的类
package eu.stratosphere.benchmarks.systemml.cli.command.visualizationUtil
import org.peelframework.core.beans.experiment.Experiment
import scala.collection.mutable.ArrayBuffer
import org.peelframework.core.beans.system.System
class ExperimentData(expPointer: Experiment[System], runsc: ArrayBuffer[RunData]) {
var exp: Experiment[System] = expPointer
var runs: ArrayBuffer[RunData] = runsc
var maxValues: ArrayBuffer[Double] = null
var summedRuns : RunData = new RunData()
def this() {
this(null, scala.collection.mutable.ArrayBuffer.empty[RunData])
}
def this(expPointer: Experiment[System]) {
this(expPointer, scala.collection.mutable.ArrayBuffer.empty[RunData])
}
def insertNewTimeStepForLastInsertedRun(timestampData: TimestampData) {
runs.last.insertNewTimeStepForLastInsertedNode(timestampData)
//TODO: sum over all runs
}
def getMaxRuntime(): Int = {
var runtimeMax: Int = -1
for (r <- runs) {
if (runtimeMax < r.getMaxRuntime()) {
runtimeMax = r.getMaxRuntime()
}
}
runtimeMax
}
}
示例13: TimestampData
//设置package包名称以及导入依赖的类
package eu.stratosphere.benchmarks.systemml.cli.command.visualizationUtil
import scala.collection.mutable.ArrayBuffer
class TimestampData(epochc: Double, metricsValuesc: ArrayBuffer[Double]) {
var epoch: Double = epochc
var metricsValues: ArrayBuffer[Double] = metricsValuesc
//TODO: don't sum up epochs (pass epoch index)
def +=(timestampData: TimestampData) : TimestampData.this.type = {
for (i <- 0 until metricsValues.size) {
metricsValues(i) += timestampData.metricsValues(i)
}
this
}
}
示例14: NodeData
//设置package包名称以及导入依赖的类
package eu.stratosphere.benchmarks.systemml.cli.command.visualizationUtil
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
class NodeData(namec: String, timestepsc: mutable.HashMap[Long,TimestampData]) {
var name: String = namec
var timesteps: mutable.HashMap[Long,TimestampData] = timestepsc
def this() {
this("", new mutable.HashMap[Long,TimestampData]())
}
def this(namec: String) {
this(namec, new mutable.HashMap[Long,TimestampData]())
}
def insertNewTimeStep(timestampData: TimestampData) = {
timesteps.put(timestampData.epoch.toLong, timestampData)
}
def addToTimestamp(timestampData: TimestampData) = {
val timestep = timesteps.getOrElse(timestampData.epoch.toLong, null)
if (timestep != null) {
timestep += timestampData
timesteps.put(timestampData.epoch.toLong, timestep)
} else {
timesteps.put(timestampData.epoch.toLong, timestampData)
}
}
def getMetricTimeseries(metricID: Int): Array[Double] = {
var values: ArrayBuffer[Double] = ArrayBuffer.empty[Double]
for (t <- timesteps.toSeq.sortBy(t => t._1)) {
values += t._2.metricsValues(metricID)
}
values.toArray[Double]
}
}
示例15: Test10
//设置package包名称以及导入依赖的类
package chapter09
import java.io.{FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream}
import scala.collection.mutable.ArrayBuffer
object Test10 extends App {
case class Person(val name: String) extends Serializable {
val friends = new ArrayBuffer[Person]
def addFriend(p: Person) {
friends += p
}
def isFriendOf(p: Person): Boolean = {
friends.contains(p)
}
}
val tom = Person("tom")
val jerry = Person("jerry")
val johnny = Person("johnny")
tom.addFriend(johnny)
jerry.addFriend(johnny)
val persons = Array(tom, jerry, johnny)
val out = new ObjectOutputStream(new FileOutputStream("src/Chapter09/10.obj"))
out.writeObject(persons)
out.close()
val in = new ObjectInputStream(new FileInputStream("src/Chapter09/10.obj"))
val Array(_tom,_jerry,_johnny) = in.readObject().asInstanceOf[Array[Person]]
assert(_tom isFriendOf _johnny)
assert(_jerry isFriendOf _johnny)
// assert(_tom isFriendOf _jerry)
}