scala.collection.Iterable Scala Examples
The following examples show how to use scala.collection.Iterable.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: Util.scala From nyaya with GNU Lesser General Public License v2.1 | 5 votes |
package nyaya.util import scala.annotation.tailrec import scala.collection.Iterable object Util { @inline def quickSB(f: StringBuilder => Unit): String = { val sb = new StringBuilder f(sb) sb.toString } @inline def quickSB(start: String, f: StringBuilder => Unit): String = { val sb = new StringBuilder(start) f(sb) sb.toString } def escapeString(s: String): String = s.toCharArray.map { case '\n' => "\\n" case '\r' => "\\r" case '\t' => "\\t" case '\\' => "\\" case '"' => "\\\"" case n if n >= 32 && n <= 127 => n.toString //case n if n < 256 => "\\x%02x" format n.toInt case n => "\\u%04x" format n.toLong }.mkString def asciiTree[N](root: Iterable[N])(leaves: N => Iterable[N], show: N => String, indent: String = ""): String = quickSB(asciiTreeSB(root)(_, leaves, show, indent)) def asciiTreeSB[N](root: Iterable[N])(sb: StringBuilder, leaves: N => Iterable[N], show: N => String, indent: String = ""): Unit = { val pm = "│ " val pl = " " val cm = "├─ " val cl = "└─ " var first = true @inline def loop2 = loop(_, _, _) @tailrec def loop(parentLvlLast: Vector[Boolean], fs: List[N], root: Boolean): Unit = fs match { case Nil => case h :: t => def indentPrefix(): Unit = { sb append indent for (b <- parentLvlLast) sb.append(if (b) pl else pm) } if (first) first = false else sb append '\n' var indentlen = sb.length indentPrefix() val last = t.isEmpty if (!root) sb.append(if (last) cl else cm) indentlen = sb.length - indentlen var firstLine = true for (l <- show(h).split("\n")) { if (firstLine) firstLine = false else { sb append '\n' indentPrefix() sb append " " } sb append l } val nextLvl = if (root) Vector.empty[Boolean] else parentLvlLast :+ last loop2(nextLvl, leaves(h).toList, false) loop(parentLvlLast, t, root) } loop(Vector.empty, root.toList, true) } }
Example 2
Source File: Prop.scala From nyaya with GNU Lesser General Public License v2.1 | 5 votes |
package nyaya.prop import scala.annotation.elidable import scala.collection.Iterable import scalaz.{\/, Equal, Foldable, Contravariant, Need} import scalaz.syntax.equal._ import scala.collection.compat._ final class PropA[A] private[nyaya](val t: A => EvalL) object PropA { implicit val propInstances: Contravariant[PropA] = new Contravariant[PropA] { override def contramap[A, B](r: PropA[A])(f: B => A): PropA[B] = new PropA[B](b => r.t(f(b))) } } object Prop { def pass[A](name: String = "Pass"): Prop[A] = test(name, _ => true) def fail[A](name: => String, reason: String): Prop[A] = evaln(name, a => Eval.fail(name, reason, a)) def atom[A](name: => String, t: A => FailureReasonO): Prop[A] = evaln(name, a => Eval.atom(name, a, t(a))) def eval[A](q: A => EvalL): Prop[A] = Atom[PropA, A](None, new PropA(q)) def evaln[A](name: => String, q: A => EvalL): Prop[A] = Atom[PropA, A](Some(Need(name)), new PropA(q)) def run[A](l: Prop[A])(a: A): Eval = l.run(p => Eval.run(p.t(a))) def test[A](name: => String, t: A => Boolean): Prop[A] = atom(name, a => reasonBool(t(a), a)) def equalSelf[A: Equal](name: => String, f: A => A): Prop[A] = equal[A, A](name, f, identity) def equal[A, B: Equal](name: => String, actual: A => B, expect: A => B): Prop[A] = atom[A](name, a => reasonEq(actual(a), expect(a))) def equal[A](name: => String) = new EqualB[A](name) final class EqualB[A](private val name: String) extends AnyVal { def apply[B: Equal](actual: A => B, expect: A => B): Prop[A] = equal(name, actual, expect) } def either[A, B](name: => String, f: A => String \/ B)(p: Prop[B]): Prop[A] = evaln(name, a => Eval.either(name, a, f(a))(p(_).liftL)) def reason(b: Boolean, r: => String): FailureReasonO = if (b) None else Some(r) def reasonBool(b: Boolean, input: => Any): FailureReasonO = reason(b, s"Invalid input [$input]") def reasonEq[A: Equal](a: A, e: A): FailureReasonO = reason(a ≟ e, s"Actual: $a\nExpect: $e") @elidable(elidable.ASSERTION) def assert[A](l: => Prop[A])(a: => A): Unit = l(a).assertSuccess() def forall[A, F[_]: Foldable, B](f: A => F[B])(prop: A => Prop[B]): Prop[A] = forallS(f)(prop) def forallS[A, F[_]: Foldable, B, C](f: A => F[B])(prop: A => Prop[C])(implicit ev: B <:< C): Prop[A] = eval { a => val p = prop(a) Eval.forall(a, f(a))(p(_).liftL) } def distinctI[A, B](name: => String, f: A => Iterator[B]): Prop[A] = distinct[B](name).contramap(f(_).toList) def distinctC[C[_], A](name: => String)(implicit ev: C[A] <:< Iterable[A]): Prop[C[A]] = distinct(name, ev) def distinct[A, B](name: => String, f: A => Iterable[B]): Prop[A] = distinct[B](name).contramap(f) def distinct[A](name: => String): Prop[Iterable[A]] = evaln(Eval distinctName name, as => Eval.distinct(name, as, as)) @inline def allPresent[A](name: String) = new AllPresentB[A](name) final class AllPresentB[A](private val name: String) extends AnyVal { def apply[B, C](requiredSubset: A => Set[B], testData: A => IterableOnce[C])(implicit ev: B <:< C): Prop[A] = evaln(s"$name allPresent", a => Eval.allPresent(name, a, requiredSubset(a), testData(a))) } }
Example 3
Source File: CycleDetector.scala From nyaya with GNU Lesser General Public License v2.1 | 5 votes |
package nyaya.prop import scala.annotation.tailrec import scala.collection.Iterable import scalaz.{\/-, -\/, \/} final case class CycleFree[A](value: A) case class CycleDetector[A, B](extract: A => Iterator[B], check: (A, Iterator[B]) => Option[(B, B)]) { @inline final def hasCycle(a: A): Boolean = findCycle(a).isDefined @inline final def noCycle(a: A): Boolean = findCycle(a).isEmpty final def findCycle(a: A): Option[(B, B)] = check(a, extract(a)) def cycleFree(a: A): (B, B) \/ CycleFree[A] = findCycle(a).fold[(B, B) \/ CycleFree[A]](\/-(CycleFree(a)))(-\/.apply) def contramap[Z](f: Z => A) = new CycleDetector[Z, B](extract compose f, (z, b) => check(f(z), b)) def noCycleProp(name: => String): Prop[A] = Prop.atom[A](name, findCycle(_).map{ case (b1,b2) => s"Cycle detected: [$b1] → [$b2]" }) } object CycleDetector { object Undirected extends GraphType { override def check[A, B, I](vertices: (A, B) => Iterator[B], id: B => I): (A, Iterator[B]) => Option[(B, B)] = (a, input) => { def outer(prev: B, is0: Set[I]): Set[I] \/ (B, B) = { val it = vertices(a, prev) @tailrec def inner(is: Set[I]): Set[I] \/ (B, B) = if (it.hasNext) { val b = it.next() val i = id(b) if (is contains i) \/-((prev, b)) else outer(b, is + i) match { case -\/(is2) => inner(is2) case r@ \/-(_) => r } } else -\/(is) inner(is0) } input .map(b => outer(b, Set(id(b)))) .collectFirst { case \/-(v) => v } } } object Directed extends GraphType { override def check[A, B, I](vertices: (A, B) => Iterator[B], id: B => I): (A, Iterator[B]) => Option[(B, B)] = (a, input) => { def loop(prev: B, is: Set[I]): Option[(B, B)] = vertices(a, prev) .map { b => val i = id(b) if (is contains i) Some((prev, b)) else loop(b, is + i) } .collectFirst { case Some(v) => v } input .map(b => loop(b, Set(id(b)))) .collectFirst { case Some(v) => v } } } sealed abstract class GraphType { def check[A, B, I](vertices: (A, B) => Iterator[B], id: B => I): (A, Iterator[B]) => Option[(B, B)] def tree[A, I](vertices: A => Iterator[A], id: A => I) = CycleDetector[Iterator[A], A]( identity, check((_, a) => vertices(a), id)) def map[A, I](id: A => I) = CycleDetector[Map[A, A], A]( _.keys.iterator, check(_.get(_).iterator, id)) def multimap[V[_], A, I](id: A => I, empty: V[A])(implicit ev: V[A] <:< Iterable[A]) = CycleDetector[Map[A, V[A]], A]( _.keys.iterator, check(_.getOrElse(_, empty).iterator, id)) } }
Example 4
Source File: LogContainer.scala From Linkis with Apache License 2.0 | 5 votes |
package com.webank.wedatasphere.linkis.engine.spark.common import scala.collection.Iterable import scala.collection.JavaConversions._ import scala.collection.mutable.ArrayBuffer class LogContainer(val logSize: Int) { private final val logs = new Array[String](logSize) private var flag, tail = 0 def putLog(log: String): Unit = { logs.synchronized { val index = (tail + 1) % logSize if(index == flag) { flag = (flag + 1) % logSize } logs(tail) = log tail = index } } def putLogs(logs: Iterable[String]) = synchronized { logs.foreach(putLog) } def reset() = synchronized { flag = 0 tail = 0 } def getLogs: List[String] = { logs.synchronized { if(flag == tail) { return List.empty[String] } val _logs = ArrayBuffer[String]() val _tail = if(flag > tail) tail + logSize else tail for (index <- flag until _tail) { val _index = index % logSize _logs += logs(_index) } flag = tail _logs.toList } } def size = { if(flag == tail) 0 else if(flag > tail) tail + logSize - flag else tail - flag } def getLogList: java.util.List[String] = getLogs }
Example 5
Source File: UserProfileService.scala From asura with MIT License | 5 votes |
package asura.core.es.service import asura.common.exceptions.ErrorMessages.ErrorMessage import asura.common.util.{JsonUtils, StringUtils} import asura.core.ErrorMessages import asura.core.concurrent.ExecutionContextManager.sysGlobal import asura.core.es.model.{DeleteDocResponse, IndexDocResponse, UpdateDocResponse, UserProfile} import asura.core.es.{EsClient, EsResponse} import asura.core.util.JacksonSupport.jacksonJsonIndexable import com.sksamuel.elastic4s.ElasticDsl._ import com.sksamuel.elastic4s.requests.common.RefreshPolicy import scala.collection.Iterable import scala.concurrent.Future object UserProfileService extends CommonService { def index(profile: UserProfile): Future[IndexDocResponse] = { if (null == profile) { ErrorMessages.error_EmptyRequestBody.toFutureFail } else { val error = validate(profile) if (null != error) { error.toFutureFail } else { EsClient.esClient.execute { indexInto(UserProfile.Index).doc(profile).id(profile.username).refresh(RefreshPolicy.WAIT_FOR) }.map(toIndexDocResponse(_)) } } } def deleteDoc(id: String): Future[DeleteDocResponse] = { if (StringUtils.isEmpty(id)) { ErrorMessages.error_EmptyId.toFutureFail } else { EsClient.esClient.execute { delete(id).from(UserProfile.Index).refresh(RefreshPolicy.WAIT_FOR) }.map(toDeleteDocResponse(_)) } } def updateProfile(profile: UserProfile): Future[UpdateDocResponse] = { if (null == profile || null == profile.username) { ErrorMessages.error_EmptyUsername.toFutureFail } else { EsClient.esClient.execute { update(profile.username).in(UserProfile.Index).doc(profile.toUpdateMap) }.map(toUpdateDocResponse(_)) } } def validate(profile: UserProfile): ErrorMessage = { if (StringUtils.isEmpty(profile.username)) { ErrorMessages.error_EmptyUsername } else { null } } def getProfileById(username: String): Future[UserProfile] = { if (StringUtils.isEmpty(username)) { ErrorMessages.error_EmptyUsername.toFutureFail } else { EsClient.esClient.execute { search(UserProfile.Index).query(idsQuery(username)).size(1).sourceExclude(defaultExcludeFields) }.map(response => toSingleClass(response, username)(str => { if (StringUtils.isNotEmpty(str)) { JsonUtils.parse(str, classOf[UserProfile]) } else { null } })) } } def getByIdsAsRawMap(ids: Iterable[String]) = { if (null != ids && ids.nonEmpty) { EsClient.esClient.execute { search(UserProfile.Index).query(idsQuery(ids)).size(ids.size).sourceExclude(defaultExcludeFields) }.map(res => { if (res.isSuccess) EsResponse.toIdMap(res.result) else Map.empty }) } else { Future.successful(Map.empty) } } }
Example 6
Source File: IncrementalSeq.scala From inox with Apache License 2.0 | 5 votes |
package inox.utils import scala.collection.mutable.Builder import scala.collection.mutable.ArrayBuffer import scala.collection.{Iterable, IterableLike} class IncrementalSeq[A] extends IncrementalState with Iterable[A] with IterableLike[A, Seq[A]] with Builder[A, IncrementalSeq[A]] { private[this] var stack: List[ArrayBuffer[A]] = List(new ArrayBuffer()) def clear() : Unit = { stack = List(new ArrayBuffer()) } def reset(): Unit = { clear() } def push(): Unit = { stack ::= stack.head.clone } def pop(): Unit = { stack = stack.tail } def iterator = stack.head.toList.iterator def +=(e: A) = { stack.head += e; this } def -=(e: A) = { stack.head -= e; this } override def newBuilder = new scala.collection.mutable.ArrayBuffer() def result = this }
Example 7
Source File: ParameterMappers.scala From neotypes with MIT License | 5 votes |
package neotypes package implicits.mappers import java.time.{Duration, LocalDate, LocalDateTime, LocalTime, Period, OffsetDateTime, OffsetTime, ZonedDateTime} import java.util.UUID import mappers.ParameterMapper import org.neo4j.driver.v1.Value import org.neo4j.driver.v1.types.{IsoDuration, Point} import scala.collection.Iterable import scala.jdk.CollectionConverters._ trait ParameterMappers { implicit final val BooleanParameterMapper: ParameterMapper[Boolean] = ParameterMapper.fromCast(Boolean.box) implicit final val ByteArrayParameterMapper: ParameterMapper[Array[Byte]] = ParameterMapper.identity implicit final val DoubleParameterMapper: ParameterMapper[Double] = ParameterMapper.fromCast(Double.box) implicit final val DurationParameterMapper: ParameterMapper[Duration] = ParameterMapper.identity implicit final val FloatParameterMapper: ParameterMapper[Float] = ParameterMapper.fromCast(Float.box) implicit final val IntParameterMapper: ParameterMapper[Int] = ParameterMapper.fromCast(Int.box) implicit final val IsoDurationParameterMapper: ParameterMapper[IsoDuration] = ParameterMapper.identity implicit final val LocalDateParameterMapper: ParameterMapper[LocalDate] = ParameterMapper.identity implicit final val LocalDateTimeParameterMapper: ParameterMapper[LocalDateTime] = ParameterMapper.identity implicit final val LocalTimeParameterMapper: ParameterMapper[LocalTime] = ParameterMapper.identity implicit final val LongParameterMapper: ParameterMapper[Long] = ParameterMapper.fromCast(Long.box) implicit final val OffsetDateTimeParameterMapper: ParameterMapper[OffsetDateTime] = ParameterMapper.identity implicit final val OffsetTimeParameterMapper: ParameterMapper[OffsetTime] = ParameterMapper.identity implicit final val PeriodParameterMapper: ParameterMapper[Period] = ParameterMapper.identity implicit final val PointParameterMapper: ParameterMapper[Point] = ParameterMapper.identity implicit final val StringParameterMapper: ParameterMapper[String] = ParameterMapper.identity implicit final val UUIDParameterMapper: ParameterMapper[UUID] = ParameterMapper[String].contramap(_.toString) implicit final val ValueParameterMapper: ParameterMapper[Value] = ParameterMapper.identity implicit final val ZonedDateTimeParameterMapper: ParameterMapper[ZonedDateTime] = ParameterMapper.identity private final def iterableParameterMapper[T](mapper: ParameterMapper[T]): ParameterMapper[Iterable[T]] = ParameterMapper.fromCast { col => col.iterator.map(v => mapper.toQueryParam(v).underlying).asJava } implicit final def collectionParameterMapper[T, C[_]](implicit mapper: ParameterMapper[T], ev: C[T] <:< Iterable[T]): ParameterMapper[C[T]] = iterableParameterMapper(mapper).contramap(ev) private final def iterableMapParameterMapper[V](mapper: ParameterMapper[V]): ParameterMapper[Iterable[(String, V)]] = ParameterMapper.fromCast { col => col.iterator.map { case (key, v) => key -> mapper.toQueryParam(v).underlying }.toMap.asJava } implicit final def mapParameterMapper[V, M[_, _]](implicit mapper: ParameterMapper[V], ev: M[String, V] <:< Iterable[(String, V)]): ParameterMapper[M[String, V]] = iterableMapParameterMapper(mapper).contramap(ev) implicit final def optionAnyRefParameterMapper[T](implicit mapper: ParameterMapper[T]): ParameterMapper[Option[T]] = ParameterMapper.fromCast { optional => optional.map(v => mapper.toQueryParam(v).underlying).orNull } }