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

Scala ArrayBuffer类代码示例

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

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



在下文中一共展示了ArrayBuffer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-passenger-splits,代码行数:50,代码来源:ZipUtils.scala


示例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)
  }
} 
开发者ID:PhillHenry,项目名称:Cryptorigin,代码行数:46,代码来源:MiniHadoopClusterRunning.scala


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


示例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()) 
开发者ID:mhotchen,项目名称:programming-in-scala,代码行数:34,代码来源:IntQueue.scala


示例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()
    }
  }
} 
开发者ID:utwente-fmt,项目名称:lazy-persistent-trie,代码行数:28,代码来源:LazyVar.scala


示例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())
  }
} 
开发者ID:utwente-fmt,项目名称:lazy-persistent-trie,代码行数:44,代码来源:TransformationBenchmark.scala


示例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))
            }
        }
    }
} 
开发者ID:mcross1991,项目名称:mahjong,代码行数:46,代码来源:Tile.scala


示例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
  }
} 
开发者ID:fjaros,项目名称:init6,代码行数:44,代码来源:FutureCollector.scala


示例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
} 
开发者ID:mmmyc,项目名称:ssr-android,代码行数:41,代码来源:UndoSnackbarManager.scala


示例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)
} 
开发者ID:mraad,项目名称:arcgis-alluxio,代码行数:32,代码来源:TrackSplitter.scala


示例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()
  }
} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:53,代码来源:EventListener.scala


示例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
  }
  
} 
开发者ID:fschueler,项目名称:sysml-benchmark,代码行数:42,代码来源:ExperimentData.scala


示例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
  }
} 
开发者ID:fschueler,项目名称:sysml-benchmark,代码行数:18,代码来源:TimestampData.scala


示例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]
  }
} 
开发者ID:fschueler,项目名称:sysml-benchmark,代码行数:40,代码来源:NodeData.scala


示例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)
} 
开发者ID:johnnyqian,项目名称:scala-for-the-impatient,代码行数:40,代码来源:10.scala


示例16: MCWhitelistServer

//设置package包名称以及导入依赖的类
package com.amadornes.modcast.bot.servers

import java.net.InetSocketAddress

import akka.actor.{Actor, ActorRef}
import akka.io.{IO, Tcp}
import akka.util.ByteString
import com.amadornes.modcast.bot.Configuration
import grizzled.slf4j.Logging

import scala.collection.mutable.ArrayBuffer


class MCWhitelistServer extends Actor with Logging {
	
	import Tcp._
	import context.system
	
	IO(Tcp) ! Bind(self, new InetSocketAddress(Configuration.config.getString("mc.host"), Configuration.config.getInt("mc.port")))
	
	val connections = new ArrayBuffer[ActorRef]()
	
	def receive = {
		case str: String =>
		//Ignored
		
		case [email protected](localAddress) =>
			info("MC Whitelist TCP Server is online and listening.")
		
		case CommandFailed(_: Bind) =>
			error("Bind failed. MC Whitelist Server is not functional.")
			context stop self
		
		case [email protected](remote, local) =>
			if (Configuration.config.getStringList("mc.acceptedIPs").contains(remote.getAddress.getHostAddress)) {
				sender() ! Register(self)
				connections += sender()
			} else {
				warn(s"Refusing connection from ${remote.getAddress.getHostAddress}")
				sender() ! Close
			}
		
		case MCWhitelistServer.WhitelistUser(userID) =>
			for (connection <- connections)
				connection ! Write(ByteString(s"W$userID\n"))
		case MCWhitelistServer.UnWhitelistUser(userID) =>
			for (connection <- connections)
				connection ! Write(ByteString(s"U$userID\n"))
	}
}

object MCWhitelistServer {
	
	case class WhitelistUser(id: String)
	
	case class UnWhitelistUser(id: String)
	
} 
开发者ID:Modcast,项目名称:ModcastBot,代码行数:59,代码来源:MCWhitelistServer.scala


示例17: KcqlContext

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

import com.datamountaineer.kcql.{Field, Kcql}

import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer

class KcqlContext(val fields: Seq[Field]) {

  private val cache = FieldsMapBuilder(fields)

  def getFieldsForPath(parents: Seq[String]): Seq[Either[Field, String]] = {
    val key = parents.mkString(".")
    cache.getOrElse(key, Seq.empty)
  }

  private object FieldsMapBuilder {
    private def insertKey(key: String,
                          item: Either[Field, String],
                          map: Map[String, ArrayBuffer[Either[Field, String]]]): Map[String, ArrayBuffer[Either[Field, String]]] = {

      map.get(key) match {
        case None =>
          val buffer = ArrayBuffer.empty[Either[Field, String]]
          buffer += item
          map + (key -> buffer)

        case Some(buffer) =>
          if (!buffer.contains(item)) {
            buffer += item
          }
          map
      }
    }

    def apply(fields: Seq[Field]): Map[String, Seq[Either[Field, String]]] = {
      fields.foldLeft(Map.empty[String, ArrayBuffer[Either[Field, String]]]) { case (map, field) =>
        if (field.hasParents) {
          val (_, m) = field.getParentFields
            .foldLeft((new StringBuilder(), map)) { case ((builder, accMap), p) =>
              val localMap = insertKey(builder.toString(), Right(p), accMap)
              if (builder.isEmpty) builder.append(p)
              builder.append(p) -> localMap
            }
          insertKey(field.getParentFields.mkString("."), Left(field), m)
        } else {
          insertKey("", Left(field), map)
        }
      }
    }

    def apply(kcql: Kcql): Map[String, Seq[Either[Field, String]]] = apply(kcql.getFields)
  }

}


 
开发者ID:datamountaineer,项目名称:json-kcql,代码行数:56,代码来源:KcqlContext.scala


示例18: FlushLog

//设置package包名称以及导入依赖的类
package dcp.business.actors

import BoDaoCommon.Log.LogTool
import akka.actor.Actor
import akka.actor.SupervisorStrategy.Stop
import dcp.common._

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.duration._
import dcp.config.DynConfiguration

case class FlushLog()

class LogActor extends Actor {
  private lazy val logs = ArrayBuffer[LogMsg]()
  
  private def cachelogs(logMsg: LogMsg) = {
    logs += logMsg
  }

  private def stopLoger() = {
    this.flushlogs()  //?????
    context.stop(self)
  }

  def receive = {
    case log @ flushLog() => flushlog(log)  //??????????????

    case log @ cacheLog() => cachelogs(log)

    case DeleteLog(lever, date) =>
      lever match {
        case LogLevelEnum.Info => LogTool.deleteInfoLog(date)
        case LogLevelEnum.Warn => LogTool.deleteWarningLog(date)
        case LogLevelEnum.Err => LogTool.deleteErrorLog(date)
      }

    case DeleteDayLogs(date) => LogTool.deleteDayLog(date)

    case FlushLog() =>
      this.flushlogs()
      if (logs.nonEmpty) logs.clear()  //????

    case Stop => this.stopLoger()
  }

} 
开发者ID:TopSpoofer,项目名称:dcp2.0,代码行数:48,代码来源:LogActor.scala


示例19: setToken

//设置package包名称以及导入依赖的类
package de.htwg.se.menschaergerdichnicht.model.fieldComponent

import de.htwg.se.menschaergerdichnicht.model.playerComponent.{PlayerInterface, PlayersInterface, TokenInterface}

import scala.collection.mutable.ArrayBuffer


trait FieldInterface {
  var tokenId: Int
  def setToken(token: TokenInterface)
  def getToken(): Int
  def removeToken()
}

trait HouseInterface {
  val house: ArrayBuffer[FieldInterface]
  def isFull(player: PlayerInterface): Boolean
}

trait PlayingInterface {
  val playingField: ArrayBuffer[FieldInterface]
  def getField(id: Int): FieldInterface
  def moveToken(token: TokenInterface, num: Int, players: PlayersInterface): Unit
  def kickToken(tokenId: Int, player: PlayerInterface, players: PlayersInterface): Boolean
  def moveToTarget(token: TokenInterface, i: Int): Unit
  def moveToStart(token: TokenInterface): Unit
}

trait TargetInterface {
  val targetField: ArrayBuffer[FieldInterface]
  def isFull(player: PlayerInterface): Boolean
} 
开发者ID:svantja,项目名称:MenschAergerDichNicht,代码行数:33,代码来源:FieldInterface.scala


示例20: Ring

//设置package包名称以及导入依赖的类
package mapgenerator.source.osm.model

import mapdomain.graph.Coordinate
import mapdomain.math.Polygon

import scala.collection.immutable.ListSet
import scala.collection.mutable.ArrayBuffer

case class Ring(nodes: ListSet[OSMNode], vertices: Vector[Coordinate], holes: Vector[Ring] = Vector.empty) {
  val geometry: Polygon = Polygon(vertices)
}

object Ring {
  def apply(nodeIds: List[Long], nodes: ListSet[OSMNode]): Ring = {

    val processedNodes = ArrayBuffer.empty[Long]

    val ringNodes: ListSet[OSMNode] = ListSet((for {
      nodeId ? nodeIds if !processedNodes.contains(nodeId)
    } yield {
      val node: OSMNode = nodes.find(_.id == nodeId).get
      processedNodes += nodeId
      node
    }): _*)

    val vertices: Vector[Coordinate] = nodes.map(_.coordinate).toVector

    new Ring(ringNodes, vertices)
  }
} 
开发者ID:cspinetta,项目名称:footpath-routing,代码行数:31,代码来源:Ring.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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