repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day10/SolverSpec.scala
package se.parwen.adoc.day10 import org.scalatest.{FlatSpec, Matchers} class SolverSpec extends FlatSpec with Matchers { "The solver" should "handle 1" in { import Solver._ val r = swap(List(0, 1, 2, 3, 4), 0, 3) r should be (List(2, 1, 0, 3, 4)) } "The solver" should "handle 2" in { import Solver._ val r = swap(List(2, 1, 0, 3, 4), 3, 4) r should be (List(4, 3, 0, 1, 2)) } "The solver" should "handle 3" in { import Solver._ val r = swap(List(4, 3, 0, 1, 2), 8, 1) r should be (List(4, 3, 0, 1, 2)) } "The solver" should "handle 4" in { import Solver._ val r = swap(List(4, 3, 0, 1, 2), 11, 5) r should be (List(3, 4, 2, 1, 0)) } "The solver" should "return for list 0,1,2,3,4 and lengths 3,4,1,5" in { import Solver._ val list = List(0,1,2,3,4) val lengths = List(3,4,1,5) val r = solveStep1(list, lengths) r should be (12) } "The solver" should "return for list 0,1,2,3,4 and lengths 3,4,0,5" in { import Solver._ val list = List(0,1,2,3,4) val lengths = List(3,4,0,5) val r = solveStep1(list, lengths) r should be (2) } "" should "" in { import Solver._ val r = toAscii("1,2,3") r should be (List(49,44,50,44,51)) } "The solver step2" should "return a2582a3a0e66e6e86e3812dcb672a272 for empty string" in { import Solver._ val r = solveStep2("") r should be ("a2582a3a0e66e6e86e3812dcb672a272") } "The solver step2" should "return 33efeb34ea91902bb2f59c9920caa6cd for AoC 2017g" in { import Solver._ val r = solveStep2("AoC 2017") r should be ("33efeb34ea91902bb2f59c9920caa6cd") } "The solver step2" should "return 3efbe78a8d82f29979031a4aa0b16a9d for 1,2,3" in { import Solver._ val r = solveStep2("1,2,3") r should be ("3efbe78a8d82f29979031a4aa0b16a9d") } "The solver step2" should "return 63960835bcdc130f0b66d7ff4f6a5a8e for 1,2,4" in { import Solver._ val r = solveStep2("1,2,4") r should be ("63960835bcdc130f0b66d7ff4f6a5a8e") } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day10/Solver.scala
<reponame>parwen68/advent-of-code-2017 package se.parwen.adoc.day10 import se.parwen.adoc.day10.Solver.solveForList import scala.annotation.tailrec object Solver { def swap(l: List[Int], from: Int, length: Int) : List[Int] = { val nFrom = from % l.length val nTo = (from + length) % l.length if (length == 0) { l } else if (nFrom < nTo) { l.take(nFrom) ++ l.slice(nFrom, nTo).reverse ++ l.takeRight(l.length - nTo) } else { val a = (l.takeRight(l.length - nFrom) ++ l.take(nTo)).reverse a.takeRight(nTo) ++ l.slice(nTo, nFrom) ++ a.take(l.length - nFrom) } } def solveForList(list: List[Int], lengths: List[Int], cp : Int = 0, skip: Int = 0) : (List[Int], Int, Int) = { @tailrec def loop(innerList: List[Int], innerLengths: List[Int], cp : Int, skip: Int): (List[Int], Int, Int) = { innerLengths match { case Nil => (innerList, cp, skip) case length :: tail => loop(swap(innerList, cp, length), tail, cp + length + skip, skip + 1) } } loop(list, lengths, cp, skip) } def solveStep1(list: List[Int], lengths: List[Int]) : Int = { val (r, _, _) = solveForList(list, lengths) r.head * r(1) } def toAscii(s: String): List[Int] = { s.map(_.toInt).toList } def solveStep2(input: String) : String = { val lengths = toAscii(input) ++ List(17, 31, 73, 47, 23) val list = (0 to 255).toList val cnt = 64 def loop(innerList: List[Int], cp : Int, skip: Int, cnt: Int): List[Int] = { if (cnt == 0) innerList else { val (newList, newCp, newSkipskip) = solveForList(innerList, lengths, cp, skip) loop(newList, newCp, newSkipskip, cnt -1) } } loop(list, 0, 0, 64).grouped(16).map(l => l.fold(0)(_ ^ _)).map(v => f"$v%02x").mkString } } trait Solver10 { def solve10(): Unit = { println("Day 10:") val result1 = Solver.solveStep1((0 to 255).toList, Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.inputAsStr) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day8/Solver.scala
<reponame>parwen68/advent-of-code-2017 package se.parwen.adoc.day8 object Solver { val pattern = raw"(\w+) (\w+) ([-\d]+) if (\w+ [!><=]+ [-\d]+)".r val patternCond = raw"(\w+) ([!><=]+) ([-\d]+)".r case class Exp(reg: String, cmd: String, amount: Int, cond: String) def parse(input: String) = { val rows = input.split('\n').toList for (row <- rows) yield row match { case pattern(reg, cmd, amount, cond) => Exp(reg, cmd, amount.toInt, cond) } } def eval(cond: String, ctx: Map[String, Int]): Boolean = { cond match { case patternCond(reg, ">", v) => ctx.getOrElse(reg, 0) > v.toInt case patternCond(reg, "<", v) => ctx.getOrElse(reg, 0) < v.toInt case patternCond(reg, ">=", v) => ctx.getOrElse(reg, 0) >= v.toInt case patternCond(reg, "<=", v) => ctx.getOrElse(reg, 0) <= v.toInt case patternCond(reg, "==", v) => ctx.getOrElse(reg, 0) == v.toInt case patternCond(reg, "!=", v) => ctx.getOrElse(reg, 0) != v.toInt } } def add(reg: String, v: Int, ctx: Map[String, Int]) = { ctx.updated(reg, ctx.getOrElse(reg, 0) + v) } def sub(reg: String, v: Int, ctx: Map[String, Int]) = { ctx.updated(reg, ctx.getOrElse(reg, 0) - v) } def solveStep1(input: String): (String, Int) = { val exps = parse(input) def loop(exps: List[Exp], ctx: Map[String, Int] = Map()): Map[String, Int] = exps match { case Nil => ctx case Exp(reg, cmd, amount, cond) :: tail => val newCtx = if (eval(cond, ctx)) if (cmd == "inc") add(reg, amount, ctx) else sub(reg, amount, ctx) else ctx loop(tail, newCtx) } loop(exps).max((x: (String, Int), y: (String, Int)) => x._2.compareTo(y._2)) } def solveStep2(input: String): Int = { val exps = parse(input) def loop(exps: List[Exp], ctx: Map[String, Int] = Map(), mx: Int = Int.MinValue): (Map[String, Int], Int) = exps match { case Nil => (ctx, mx) case Exp(reg, cmd, amount, cond) :: tail => val newCtx = if (eval(cond, ctx)) if (cmd == "inc") add(reg, amount, ctx) else sub(reg, amount, ctx) else ctx val newMax = if (newCtx.values.nonEmpty && newCtx.values.max > mx) newCtx.values.max else mx loop(tail, newCtx, newMax) } loop(exps)._2 } } trait Solver8 { def solve8(): Unit = { println("Day 8:") val result1 = Solver.solveStep1(Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.input) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day14/Solver.scala
package se.parwen.adoc.day14 import scala.annotation.tailrec object Solver { def toAscii(s: String): List[Int] = { s.map(_.toInt).toList } def swap(l: List[Int], from: Int, length: Int) : List[Int] = { val nFrom = from % l.length val nTo = (from + length) % l.length if (length == 0) { l } else if (nFrom < nTo) { l.take(nFrom) ++ l.slice(nFrom, nTo).reverse ++ l.takeRight(l.length - nTo) } else { val a = (l.takeRight(l.length - nFrom) ++ l.take(nTo)).reverse a.takeRight(nTo) ++ l.slice(nTo, nFrom) ++ a.take(l.length - nFrom) } } def solveForList(list: List[Int], lengths: List[Int], cp : Int = 0, skip: Int = 0) : (List[Int], Int, Int) = { @tailrec def loop(innerList: List[Int], innerLengths: List[Int], cp : Int, skip: Int): (List[Int], Int, Int) = { innerLengths match { case Nil => (innerList, cp, skip) case length :: tail => loop(swap(innerList, cp, length), tail, cp + length + skip, skip + 1) } } loop(list, lengths, cp, skip) } def knotHash(input: String) : List[Int] = { val lengths = toAscii(input) ++ List(17, 31, 73, 47, 23) val list = (0 to 255).toList val cnt = 64 def loop(innerList: List[Int], cp : Int, skip: Int, cnt: Int): List[Int] = { if (cnt == 0) innerList else { val (newList, newCp, newSkipskip) = solveForList(innerList, lengths, cp, skip) loop(newList, newCp, newSkipskip, cnt -1) } } loop(list, 0, 0, 64).grouped(16).map(l => l.fold(0)(_ ^ _)).toList //.map(v => f"$v%02x").mkString } def solveStep1(input: String): Int = { (0 to 127).map(v => s"$input-$v").map(knotHash).toList.flatten.flatMap(v => v.toBinaryString).count(_ == '1') } def solveStep2(input: String): Int = { val s = (0 to 127) .map(v => s"$input-$v") .map(knotHash) .map(v => v.flatMap(v => f"${v.toBinaryString}%8s".replace(' ', '0')).toArray ).toArray val v = (for { x <- 0 to 127 y <- 0 to 127 if s(x)(y) == '1' } yield (x, y)).toSet def getNeighbors(c: (Int,Int), rest: Set[(Int,Int)]): List[(Int,Int)] = { val deltas = for { dx <- -1 to 1 dy <- -1 to 1 if Math.abs(dy + dx) == 1 } yield (dx,dy) deltas.map(d => (c._1 + d._1, c._2 + d._2)).filter(rest(_)).toList } @tailrec def findGroup(next: List[(Int,Int)], cells: Set[(Int, Int)], acc: Set[(Int, Int)]) : (Set[(Int,Int)], Set[(Int,Int)])= { next match { case Nil => (cells, acc) case head :: tail => val neighbors = getNeighbors(head, cells) findGroup(tail ++ neighbors, cells -- neighbors, acc ++ neighbors) } } @tailrec def loop(all: Set[(Int, Int)], cnt: Int): Int = if (all.isEmpty) cnt else loop(findGroup(List(all.head), all - all.head, Set())._1, cnt + 1) loop(v, 0) } } trait Solver14 { def solve14(): Unit = { println("Day 14:") val result1 = Solver.solveStep1(Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.input) println(s"step 2 result is $result2") } } object Main extends Solver14 { def main(args: Array[String]): Unit = { solve14() } }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day19/SolverSpec.scala
package se.parwen.adoc.day19 import org.scalatest._ class SolverSpec extends FlatSpec with Matchers { "Solver parse" should "return 14x6 array" in { val a = Solver.parse(""" | $ | +--+ $ A | C $ F---|----E|--+ $ | | | D $ +B-+ +--+ $""".stripMargin('$')) a(0,0) should be (' ') a(5,0) should be ('|') } "" should "" in { val a = Solver.solveStep1(""" | $ | +--+ $ A | C $ F---|----E|--+ $ | | | D $ +B-+ +--+ $""".stripMargin('$')) a should be ("ABCDEF") } }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day5/SolverSpec.scala
package se.parwen.adoc.day5 import org.scalatest._ class SolverSpec extends FlatSpec with Matchers { import Solver._ "The solver step1" should "return 5 for 0 3 0 1 -3" in { solveStep1(Array(0,3,0,1,-3)) should be (5) } "The solver step2" should "return 10 for 0 3 0 1 -3" in { solveStep2(Array(0,3,0,1,-3)) should be (10) } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day14/Input.scala
<reponame>parwen68/advent-of-code-2017 package se.parwen.adoc.day14 object Input { val input = "nbysizxe" }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day12/Solver.scala
package se.parwen.adoc.day12 import scala.annotation.tailrec object Solver { case class Program(name: String, programs: List[Program]) private def parse(input: String) = { val rows = input.split('\n').map { v => val e = v.split("<->") (e(0).trim.toInt, e(1).split(',').map(s => s.trim.toInt).toList) } val c = rows.toList.flatMap { case (k, v) => v.map((k, _)) } val b = c.flatMap { case (k, v) => List((k, v), (v, k)) } b.toSet } private def getGroup(c: Int, m: Set[(Int, Int)]) = { @tailrec def loop(c: Set[Int], m: Set[(Int, Int)], acc: Set[Int] = Set()): Set[Int] = { val x = m .filter { case (k, v) => c.contains(k) || c.contains(v) } .flatMap { case (k, v) => Set(k, v) } .filter(s => !c.contains(s) && !acc.contains(s)) if (x.nonEmpty) { loop(x, m, acc ++ c) } else acc ++ c } loop(Set(c), m) } def solveStep1(input: String): Int = { getGroup(0, parse(input)).size } def solveStep2(input: String): Int = { val inp = parse(input) val all = inp.map(_._1) @tailrec def loop(start: Int, acc: List[Set[Int]], remaning: Set[Int]): List[Set[Int]] = { val group = getGroup(start,inp) val rest = remaning.diff(group) if(rest.isEmpty) acc :+ group else loop(rest.head, acc :+ group, rest) } loop(0, List(), all).size } } trait Solver12 { def solve12(): Unit = { println("Day 12:") val result1 = Solver.solveStep1(Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.input) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day12/SolverSpec.scala
package se.parwen.adoc.day12 import org.scalatest.{FlatSpec, Matchers} class SolverSpec extends FlatSpec with Matchers { "The solver step 1" should "return 6" in { import Solver._ val r = solveStep1("""0 <-> 2 |1 <-> 1 |2 <-> 0, 3, 4 |3 <-> 2, 4 |4 <-> 2, 3, 6 |5 <-> 6 |6 <-> 4, 5""".stripMargin) r should be (6) } "The solver step 2" should "return 2" in { import Solver._ val r = solveStep2("""0 <-> 2 |1 <-> 1 |2 <-> 0, 3, 4 |3 <-> 2, 4 |4 <-> 2, 3, 6 |5 <-> 6 |6 <-> 4, 5""".stripMargin) r should be (2) } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day11/Solver.scala
<reponame>parwen68/advent-of-code-2017<filename>shared/src/main/scala/se/parwen/adoc/day11/Solver.scala package se.parwen.adoc.day11 /* s + ne = se s + nw = sw n + se = ne n + sw = nw --- se + sw = s ne + nw = n --- s + n = 0 sw + ne = 0 se + nw = 0 --- s,sw,se = s, s s,sw,nw = sw, sw s,ne,se = se, se s,ne,nw = s, n n,sw,se = n, s n,sw,nw = nw, nw n,ne,se = ne, ne n,ne,nw = n, n */ object Solver { def reduce1(g: Map[String,Int]): Map[String, Int] = { val ns = g("n") - g("s") val swne = g("sw") - g("ne") val senw = g("se") - g("nw") ( (if (ns > 0) List(("n", ns), ("s", 0)) else List(("n", 0), ("s", -ns))) ++ (if (swne > 0) List(("sw", swne), ("ne", 0)) else List(("sw", 0), ("ne", -swne))) ++ (if (senw > 0) List(("se", senw), ("nw", 0)) else List(("se", 0), ("nw", -senw))) ).toMap } def p(v: Int) = if (v > 0) v else 0 def reduce2(g: List[(String, Int)]): List[(String, Int)] = { import Math._ g match { case List(("n",0), ("ne",0), ("nw",0), ("s",a), ("se",c), ("sw",b)) => List(("n",0), ("ne",0), ("nw",0), ("s",a + min(c,b)), ("se",p(c - b)), ("sw",p(b - c))) case List(("n",0), ("ne",0), ("nw",c), ("s",a), ("se",0), ("sw",b)) => List(("n",0), ("ne",0), ("nw",p(c - a)), ("s",p(a - c)), ("se",0), ("sw",b + min(a,c))) case List(("n",0), ("ne",b), ("nw",0), ("s",a), ("se",c), ("sw",0)) => List(("n",0), ("ne",p(b-a)), ("nw",0), ("s",p(a-b)), ("se",c + min(a, b)), ("sw",0)) case List(("n",0), ("ne",b), ("nw",c), ("s",a), ("se",0), ("sw",0)) => List(("n",p(abs(b-c)-a)), ("ne",p(b-c)), ("nw",p(c-b)), ("s",p(a-abs(b-c))), ("se",0), ("sw",0)) case List(("n",a), ("ne",0), ("nw",0), ("s",0), ("se",c), ("sw",b)) => List(("n",p(a-abs(b-c))), ("ne",0), ("nw",0), ("s",p(abs(b-c)-a)), ("se",p(c-b)), ("sw",p(b-c))) case List(("n",a), ("ne",0), ("nw",c), ("s",0), ("se",0), ("sw",b)) => List(("n",p(a-b)), ("ne",0), ("nw",c + min(a,b)), ("s",0), ("se",0), ("sw",p(b-a))) case List(("n",a), ("ne",b), ("nw",0), ("s",0), ("se",c), ("sw",0)) => List(("n",p(a-c)), ("ne",b + min(a,c)), ("nw",0), ("s",0), ("se",p(c-a)), ("sw",0)) case List(("n",a), ("ne",b), ("nw",c), ("s",0), ("se",0), ("sw",0)) => List(("n",a + min(b,c)), ("ne",p(b-c)), ("nw",p(c-b)), ("s",0), ("se",0), ("sw",0)) } } def solve(input: Array[String]): List[(String, Int)] = { val map1 = List("s", "n", "nw", "ne", "sw", "se").map(v => (v, 0)).toMap val map2 = input.toList.groupBy(identity).mapValues(_.size) val m = map1.map{ case (k,v) => k -> (v + map2.getOrElse(k,0)) } reduce2(reduce1(m).toList.sortWith(_._1 < _._1)) } def solveStep1(input: String): Int = { solve(input.split(',')).map(_._2).sum } def solveStep2(input: String): Int = { val list: Array[String] = input.split(',') val len = list.length (1 to len).map(list.take(_)).foldLeft(0)((acc,v) => Math.max(acc,solve(v).map(_._2).sum)) } } trait Solver11 { def solve11(): Unit = { println("Day 11:") val result1 = Solver.solveStep1(Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.input) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day8/SolverSpec.scala
package se.parwen.adoc.day8 import org.scalatest.{FlatSpec, Matchers} class SolverSpec extends FlatSpec with Matchers { "The solver" should "return a and 1" in { import Solver._ val (reg, v) = solveStep1("""b inc 5 if a > 1 |a inc 1 if b < 5 |c dec -10 if a >= 1 |c inc -20 if c == 10""".stripMargin) reg should be ("a") v should be (1) } "The solver" should "return max value 10" in { import Solver._ val mx = solveStep2("""b inc 5 if a > 1 |a inc 1 if b < 5 |c dec -10 if a >= 1 |c inc -20 if c == 10""".stripMargin) mx should be (10) } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day5/Solver.scala
package se.parwen.adoc.day5 object Solver { def solveStep1(list: Array[Int]): Int = { var ptr = 0 var prevPtr = ptr import scala.util.control.Breaks._ var cnt = 0 breakable { while (true) { cnt += 1 val v = list(ptr) ptr += v list(prevPtr) = list(prevPtr) + 1 prevPtr = ptr if (ptr < 0 || ptr >= list.length) { //println(s"$cnt $ptr ${list.toList}") break } } } cnt } def solveStep2(list: Array[Int]): Int = { var ptr = 0 var prevPtr = ptr import scala.util.control.Breaks._ var cnt = 0 breakable { while (true) { cnt += 1 val v = list(ptr) ptr += v list(prevPtr) = list(prevPtr) + (if (v >= 3) -1 else 1) prevPtr = ptr if (ptr < 0 || ptr >= list.length) { //println(s"$cnt $ptr ${list.toList}") break } } } cnt } } trait Solver5 { def solve5(): Unit = { println("Day 5:") val result1 = Solver.solveStep1(Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.input) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day15/SolverSpec.scala
<reponame>parwen68/advent-of-code-2017<filename>shared/src/test/scala/se/parwen/adoc/day15/SolverSpec.scala<gh_stars>0 package se.parwen.adoc.day15 import org.scalatest.{FlatSpec, Matchers} class SolverSpec extends FlatSpec with Matchers { "Solver step1" should "return 588" in { Solver.solveStep1(65, 8921) should be (588) } "Solver step2" should "return 309" in { Solver.solveStep2(65, 8921) should be (309) } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day10/Input.scala
<reponame>parwen68/advent-of-code-2017 package se.parwen.adoc.day10 object Input { val input = List(18,1,0,161,255,137,254,252,14,95,165,33,181,168,2,188) val inputAsStr = "18,1,0,161,255,137,254,252,14,95,165,33,181,168,2,188" }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day7/Solver.scala
<filename>shared/src/main/scala/se/parwen/adoc/day7/Solver.scala package se.parwen.adoc.day7 import se.parwen.adoc.day7.Solver.{solveStep1, solveStep2} import scala.annotation.tailrec object Solver { val pattern = raw"(\w+) \((\d+)\)[-> ]*([\w, ]*)".r case class Program(name: String, weight: Int = -1, ontopof: Option[Program] = None) def parse(str: String): (List[Program], Map[String, Program]) = { val rows = str.split('\n') val p = for(row <- rows) yield row match { case pattern(name, weight, "") => (Program(name, weight.toInt), Map[String, Program]()) case pattern(name, weight, other) => val p = Program(name, weight.toInt) val m = other.split(',').map(s => s.trim).zip(Stream.continually(p)).toMap (p, m) } p.foldLeft((List[Program](), Map[String, Program]())){ case ((programs, map), (pp,m)) => (programs :+ pp, map ++ m)} } def connect(programs: List[Program], map: Map[String, Program]): List[Program] = { def loop(p: List[Program], acc: List[Program] = Nil): List[Program] = p match { case Nil => acc case head :: tail => loop(tail, acc :+ head.copy(ontopof = map.get(head.name))) } loop(programs) } def solveStep1(input: String): List[String] = { (connect _ tupled parse(input)).filter(p => p.ontopof.isEmpty).map(_.name) } def solveStep2(input: String): Int = { val connected = connect _ tupled parse(input) case class P(name: String, weight: Int, ontop: List[P] = Nil) { def weights: List[Int] = { if (ontop.isEmpty) List(weight) else weight :: ontop.flatMap(_.weights) } def weightsSum: Int = weights.sum } val bottom = connected.filter(_.ontopof.isEmpty).map(p => P(p.name, p.weight)).head def loop(c: P, connected: List[Program]) : P = { val ontop = connected.filter(_.ontopof.exists(e => e.name == c.name)).map(p => P(p.name, p.weight)) if (ontop.isEmpty) c else c.copy(ontop = ontop.map(t => loop(t, connected))) } val b2 = loop(bottom, connected) //println(b2.ontop.map(_.weightsSum)) //println(b2.ontop(1).ontop.map(_.weightsSum)) //println(b2.ontop(1).ontop.head.ontop.map(_.weightsSum)) //println(b2.ontop(1).ontop.head.ontop(2).ontop.map(_.weightsSum)) //println(b2.ontop(1).ontop.head.ontop(2).weight) //println(b2.ontop(1).ontop.head.ontop(2).weight - 9) b2.ontop(1).ontop.head.ontop(2).weight - 9 } } trait Solver7 { def solve7(): Unit = { println("Day 7:") val result1 = solveStep1(Input.input) println(s"step 1 result is $result1") val result2 = solveStep2(Input.input) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day16/Solver.scala
<gh_stars>0 package se.parwen.adoc.day16 import scala.annotation.tailrec object Solver { def spin(inp: Array[Char], steps: Int) : Array[Char] = { inp.takeRight(steps) ++ inp.dropRight(steps) } def exchange(inp: Array[Char], pos1: Int, pos2: Int) : Array[Char] = { inp.updated(pos1, inp(pos2)).updated(pos2, inp(pos1)) } def partner(inp: Array[Char], n1: Char, n2: Char) : Array[Char] = { exchange(inp, inp.indexOf(n1), inp.indexOf(n2)) } def parse(input: String): List[Command] = { input.split(',').map(s => (s(0), s.substring(1))).toList.map { case ('s', p) => Spin(p.toInt) case ('x', p) => val s = p.split('/').map(_.toInt) Exchange(s(0), s(1)) case ('p', p) => val s = p.split('/').map(_ (0)) Partner(s(0), s(1)) case _ => throw new RuntimeException } } sealed trait Command case class Spin(steps: Int) extends Command case class Exchange(p1: Int, p2: Int) extends Command case class Partner(c1: Char, c2: Char) extends Command def solve(start: Array[Char], commands: List[Command]): Array[Char] = { @tailrec def loop(inp: Array[Char], commands: List[Command]) : Array[Char] = { commands match { case Nil => inp case Spin(steps) :: tail => loop(spin(inp, steps), tail) case Exchange(p1,p2) :: tail => loop(exchange(inp, p1,p2), tail) case Partner(c1,c2) :: tail => loop(partner(inp, c1, c2), tail) } } loop(start, commands) } def solveStep1(input: String, commandStr: String): String = { val start = input.toCharArray val commands = parse(commandStr) solve(start, commands).mkString } def solveStep2(input: String, commandStr: String) : String = { val commands = parse(commandStr) @tailrec def loop(s: Array[Char], cnt: Int = 0, acc: List[String] = List()) : List[String] = { if(acc contains s.mkString) { acc } else { loop(solve(s, commands), cnt + 1, acc :+ s.mkString) } } val cycle = loop(input.toCharArray) cycle(1000000000 % cycle.length) } } trait Solver16 { def solve16(): Unit = { println("Day 16:") val result1 = Solver.solveStep1("abcdefghijklmnop", Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2("abcdefghijklmnop", Input.input) println(s"step 2 result is $result2") } } object Main extends Solver16 { def main(args: Array[String]): Unit = { solve16() } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day9/Solver.scala
<filename>shared/src/main/scala/se/parwen/adoc/day9/Solver.scala<gh_stars>0 package se.parwen.adoc.day9 object Solver { def solveStep1(input: String): Int = { case class Context(ingarbage: Boolean = false, score: Int = 0, started: Int = 0){ def startGroup() = this.copy(started = started + 1) def endGroup() = this.copy(started = started - 1, score = score + started) } def loop(str: List[Char], ctx: Context = Context()): Context = { str match { case Nil => ctx case '<' :: tail => loop(tail, ctx.copy(ingarbage = true)) case '>' :: tail => loop(tail, ctx.copy(ingarbage = false)) case '!' :: _ :: tail if ctx.ingarbage => loop(tail, ctx) case '{' :: tail if !ctx.ingarbage => loop(tail, ctx.startGroup()) case '}' :: tail if !ctx.ingarbage => loop(tail, ctx.endGroup()) case _ :: tail => loop(tail, ctx) } } loop(input.toList).score } def solveStep2(input: String): Int = { case class Context(ingarbage: Boolean = false, score: Int = 0, started: Int = 0){ def startGroup() = this.copy(started = started + 1) def endGroup() = this.copy(started = started - 1, score = score + started) } def loop(str: List[Char], count: Int, ctx: Context = Context()): Int = { str match { case Nil => count case '<' :: tail if !ctx.ingarbage => loop(tail, count, ctx.copy(ingarbage = true)) case '>' :: tail if ctx.ingarbage => loop(tail, count, ctx.copy(ingarbage = false)) case '!' :: _ :: tail if ctx.ingarbage => loop(tail, count, ctx) case '{' :: tail if !ctx.ingarbage => loop(tail, count,ctx.startGroup()) case '}' :: tail if !ctx.ingarbage => loop(tail, count,ctx.endGroup()) case _ :: tail if !ctx.ingarbage => loop(tail, count,ctx) case _ :: tail if ctx.ingarbage => loop(tail, count+1,ctx) } } loop(input.toList, 0) } } trait Solver9 { def solve9(): Unit ={ println("Day 9:") val result1 = Solver.solveStep1(Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.input) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day16/SolverSpec.scala
<filename>shared/src/test/scala/se/parwen/adoc/day16/SolverSpec.scala package se.parwen.adoc.day16 import org.scalatest._ import se.parwen.adoc.day16.Solver.{Exchange, Partner, Spin} class SolverSpec extends FlatSpec with Matchers { "Solver spin 3" should "return cdeab for abcde" in { Solver.spin("abcde".toArray, 3) should be ("cdeab".toArray) } "Solver exchange 1,3" should "return adcbe for abcde" in { Solver.exchange("abcde".toArray, 1, 3) should be ("adcbe".toArray) } "Solver exchange 3,4" should "return abced for abcde" in { Solver.exchange("eabcd".toArray, 3, 4) should be ("eabdc".toArray) } "Solver partner b,d" should "return adcbe for abcde" in { Solver.partner("abcde".toArray, 'b', 'd') should be ("adcbe".toArray) } "Solver partner e,b" should "return baedc for eabdc" in { Solver.partner("eabdc".toArray, 'e', 'b') should be ("baedc".toArray) } "Solver parse" should "return list for x5/15,s15,x1/3,pn/f" in { Solver.parse("x5/15,s15,x1/3,pn/f") should be (List(Exchange(5,15), Spin(15), Exchange(1,3), Partner('n','f'))) } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day17/Solver.scala
package se.parwen.adoc.day17 object Solver { def move(currPos: Int, steps: Int, bufferSize: Int): Int = { val laps = steps / bufferSize val reminder = steps % bufferSize if(currPos + reminder >= bufferSize) { currPos + reminder - bufferSize } else { currPos + reminder } } def insert(pos: Int, value: Int, buffer: List[Int]) : List[Int] = { buffer.patch(pos, List(value), 0) } def solve(steps: Int, turns: Int) : (List[Int], Int) = { def loop(cnt: Int = 0, pos: Int = 0, buffer: List[Int] = List(0)): (List[Int], Int) = { if (cnt == turns) { (buffer, pos) } else { val newPos = move(pos, steps, buffer.size) loop(cnt + 1, newPos + 1, insert(newPos + 1, cnt + 1, buffer)) } } loop() } def solveStep1(steps: Int, turns: Int): Int = { val (buffer, pos) = solve(steps, turns) buffer(pos+1) } def solveStep2(steps: Int, turns: Int): Int = { def loop(cnt: Int = 0, pos: Int = 0, bufferSize: Int = 1, value: Int = -1): Int = { if (cnt == turns) { value } else { val newPos = move(pos, steps, bufferSize) loop(cnt + 1, newPos + 1, bufferSize + 1, if(newPos == 0) cnt +1 else value) } } loop() } } trait Solver17 { def solve17(): Unit = { println("Day 17:") val result1 = Solver.solveStep1(371, 2017) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(371, 50000000) println(s"step 2 result is $result2") } } object Main extends Solver17 { def main(args: Array[String]): Unit = { solve17() } }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day14/SolverSpec.scala
package se.parwen.adoc.day14 import org.scalatest.{FlatSpec, Matchers} class SolverSpec extends FlatSpec with Matchers { /* ##.#.#.. d4 .#.#.#.# 55 ....#.#. 0c #.#.##.# .##.#... ##..#..# .#...#.. ##.#.##. */ "a" should "b" in { val a = Solver.solveStep1("flqrgnkx") } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day8/Input.scala
<reponame>parwen68/advent-of-code-2017 package se.parwen.adoc.day8 object Input { val input = """js inc 257 if wn < 9 |jq dec -586 if esb != -3 |gcf inc -603 if i >= -9 |gcf dec -300 if d != 1 |g inc -973 if gy > -1 |epp dec -79 if rjx < 9 |x dec 796 if esb == 0 |d inc -526 if rf < 3 |qc inc -610 if dma > -8 |gcf dec 831 if aqr > 5 |wow dec -705 if jq >= 583 |gcf dec 135 if esb < 10 |gcf inc -777 if aqr != 8 |esb inc 262 if rjx > -10 |x inc 259 if dma > 3 |g dec -784 if rjx != -2 |rjx inc -969 if yzp > -3 |wow inc -401 if g < -182 |dma inc 995 if rjx <= -962 |vyy inc 290 if g >= -194 |vyy inc 4 if gy == 0 |vyy dec -295 if wow >= 314 |j dec 476 if j >= -8 |u inc 84 if g < -195 |g inc -422 if gy == -4 |yzp dec -523 if cty == 0 |cn dec -938 if g > -195 |u dec -652 if g <= -193 |aqr dec 829 if qc < -601 |u dec 199 if wow < 309 |aqr dec -409 if rf >= 9 |dma dec -556 if dma > 990 |qc inc 134 if i != 0 |qc inc 238 if j >= -476 |yzp dec 810 if js < 255 |i dec 898 if i == 0 |g inc 898 if tyg <= -5 |j dec -130 if aqr == -832 |tyg inc -504 if l > -7 |aqr dec 465 if l >= -9 |gcf dec 64 if jq != 595 |wow inc -102 if yzp >= 515 |rf inc -433 if i == -898 |rjx inc -334 if l >= -6 |rf inc -395 if cn <= 947 |u inc -724 if qc < -376 |epp inc 309 if gcf >= -1281 |zp dec -367 if cty >= -5 |aqr dec 265 if aqr <= -1287 |u inc 359 if wn == 0 |vyy inc 587 if aqr != -1550 |uxa inc -541 if u <= 162 |js inc 720 if wow >= 195 |d inc -857 if wn > -3 |cty inc 958 if gcf == -1279 |rf dec 153 if x >= -804 |cn dec -921 if dma <= 1560 |zp inc -554 if qc > -381 |jq dec 83 if x < -799 |qc dec 912 if cty < 968 |i inc -636 if tyg == -504 |rjx dec 113 if aqr >= -1566 |js inc -184 if wow > 198 |qc inc -519 if cty != 958 |aqr dec 281 if u > 166 |aqr inc 392 if vyy <= 887 |cn inc -179 if rjx > -1420 |g inc -16 if cn != 1680 |d inc 260 if uxa != -541 |j inc -873 if yzp < 522 |rjx inc 737 if g >= -191 |wow inc 288 if qc >= -1287 |j inc -844 if wn > 5 |i inc 91 if uxa > -546 |yzp inc -12 if d == -1383 |cn dec -247 if zp >= -189 |i dec -246 if dma == 1551 |qc inc -919 if gy >= -3 |cn dec -804 if esb < 270 |uxa inc 593 if qc != -2197 |yzp inc -562 if esb <= 264 |rjx inc 850 if zp < -181 |u dec 944 if j != -486 |vyy inc 970 if vyy >= 881 |gy inc 659 if u < -779 |aqr dec 145 if esb == 262 |yzp inc 346 if gcf == -1282 |wow inc 112 if gcf != -1279 |vyy inc -120 if rjx == 171 |esb dec -795 if qc >= -2210 |cty inc -282 if zp == -187 |uxa dec -683 if l == 0 |epp inc -185 if jq >= 589 |js inc 542 if cn != 2741 |gy inc 591 if d == -1383 |wow inc -734 if rf != -987 |wow dec 482 if vyy <= 1739 |uxa dec 231 if u >= -785 |gy dec -153 if d != -1385 |dma inc 682 if js > 1330 |wn dec -173 if i < -1196 |tyg dec -510 if dma > 2230 |aqr inc 309 if gcf <= -1289 |gcf inc 831 if g > -190 |g dec -457 if qc == -2203 |aqr dec -682 if gcf != -447 |cn dec 75 if js > 1328 |vyy inc -639 if cn >= 2666 |j dec 119 if uxa != 499 |i inc -312 if gy > 1399 |rjx dec 145 if aqr != -634 |cty dec -600 if wow == -726 |dma inc 79 if zp < -179 |vyy inc 285 if jq <= 586 |tyg inc 34 if d < -1379 |u dec -320 if yzp != -44 |esb inc -229 if wow >= -730 |gy dec 175 if cn != 2659 |gy inc 87 if js <= 1334 |wn dec 725 if rjx < 35 |cty dec -64 if gy == 1228 |tyg inc 809 if gcf != -438 |zp dec -526 if uxa > 500 |rjx inc -520 if wow > -727 |gy inc 608 if cty > 1345 |u inc -847 if cn == 2656 |dma inc -728 if zp < 343 |qc dec -722 if wow > -734 |gy inc -864 if wn != -552 |l dec -53 if cn == 2656 |rjx dec -674 if gcf > -446 |i dec 647 if jq == 586 |dma inc -109 if cty <= 1349 |d dec -263 if j == -595 |rf dec 835 if rf < -972 |esb inc 504 if js >= 1332 |uxa dec -215 if wow > -732 |l dec 240 if qc != -1472 |tyg inc 754 if aqr > -639 |d dec -784 if d > -1129 |u dec 528 if dma == 1482 |x dec 569 if aqr != -636 |uxa dec -163 if yzp < -49 |qc inc -88 if x != -1365 |gy inc -966 if yzp <= -43 |cn inc 870 if gy == 262 |x dec -511 if gy > 263 |qc dec -245 if epp >= 380 |rf dec -718 if vyy >= 2018 |aqr inc 494 if u != -1302 |esb dec 211 if wow < -734 |esb dec -284 if epp > 379 |x inc 354 if x >= -1372 |g dec 378 if cty != 1349 |wow dec -405 if js < 1338 |tyg dec 615 if yzp != -51 |rf inc 475 if dma == 1475 |gy dec 15 if aqr <= -132 |zp inc 915 if zp != 335 |d dec 323 if wn >= -553 |g dec -525 if cn != 3517 |l dec -13 if gy <= 248 |gy dec -687 if i != -2147 |tyg inc -487 if gy == 934 |rjx dec 444 if vyy == 2014 |wn inc 449 if yzp < -46 |cn inc 651 if rf != -1337 |zp dec 888 if jq >= 578 |uxa dec 966 if esb > 1616 |wn dec -219 if tyg != 1109 |dma inc 599 if cn > 4176 |x inc -486 if epp >= 387 |l inc -404 if yzp != -43 |rjx dec -996 if aqr > -142 |g dec 215 if dma == 2079 |aqr dec -746 if i > -2159 |gcf dec -301 if cn >= 4174 |qc inc -700 if vyy == 2016 |rjx dec 289 if d >= -661 |vyy inc 278 if gcf < -138 |g inc 659 if wn != 118 |zp inc 622 if l <= -579 |zp inc 644 if zp >= 373 |aqr inc 468 if gy >= 931 |wn inc 608 if zp > 359 |js dec 985 if gy <= 942 |uxa dec 509 if epp > 383 |tyg inc 134 if cty <= 1340 |jq dec 677 if dma < 2073 |yzp dec -146 if j >= -600 |l inc -500 if dma == 2072 |cn inc 399 if cty <= 1341 |rf inc 521 if wow != -321 |gcf dec -70 if wn > 718 |gcf dec 946 if tyg == 1250 |cty dec 398 if qc == -1936 |qc dec -105 if qc > -1936 |g dec -16 if g != 1082 |cty dec 932 if vyy > 2288 |gcf dec -293 if esb != 1616 |cn dec 244 if esb >= 1610 |rf inc -790 if cn != 4338 |dma dec -87 if wn == 724 |cn dec -191 if j > -598 |aqr inc -246 if d <= -658 |cn inc 786 if vyy <= 2297 |g dec 211 if qc < -1932 |x inc -473 if l >= -587 |rjx inc -686 if jq <= 589 |dma inc -411 if gcf <= -1019 |u inc -596 if qc <= -1933 |l inc -60 if rjx > -476 |wow dec 910 if zp == 366 |gy inc -854 if u != -1916 |jq inc -698 if wn <= 729 |zp inc 456 if d != -665 |x dec -853 if x >= -1964 |aqr inc -282 if rjx < -478 |tyg inc 975 if cty == 10 |js inc -684 if wow >= -1239 |uxa dec 702 if g == 879 |g inc -602 if tyg <= 2231 |cty inc 987 if dma > 1742 |gy dec -57 if cn == 5317 |zp dec -527 if qc > -1941 |tyg dec 689 if g != 282 |gcf inc -11 if rjx > -478 |epp dec 44 if uxa < -325 |aqr dec 936 if i < -2156 |i dec -119 if aqr >= 841 |yzp dec 46 if uxa > -330 |u inc 549 if esb == 1619 |zp dec 412 if j >= -598 |cn dec -865 if gy < 89 |yzp dec 366 if g > 283 |j dec 372 if j <= -595 |zp inc 879 if tyg > 1532 |wow dec 30 if x > -1974 |dma dec 288 if j < -966 |zp inc -419 if epp == 344 |tyg inc 304 if x < -1964 |zp dec 77 if j < -960 |cty inc -586 if wn < 728 |wow inc 271 if wow == -1261 |u inc -751 if dma != 1470 |wow dec -64 if wn != 727 |esb inc 294 if gy <= 75 |jq inc -559 if wow > -918 |cty inc -283 if gy != 73 |cty dec 792 if g != 274 |l inc 589 if rjx >= -482 |gy inc -659 if jq < -116 |cn dec -817 if aqr <= 839 |l inc 682 if rjx < -467 |l dec -285 if rf <= -2125 |qc inc -370 if x < -1961 |l dec 582 if yzp >= 47 |dma inc -365 if js == -334 |js inc 397 if d == -659 |g inc 902 if aqr <= 840 |x inc 129 if rf >= -2139 |g dec -704 if gcf < -1041 |cn inc 207 if uxa > -332 |epp dec 517 if js < 70 |cn dec 125 if qc <= -2305 |x inc -187 if tyg > 1844 |gy dec -1 if cty < -661 |js inc -224 if qc != -2306 |x inc -627 if gcf <= -1025 |yzp inc -426 if g < 1186 |uxa dec -839 if wow >= -933 |u inc 688 if gy <= 87 |jq dec -453 if aqr < 834 |tyg inc -370 if d >= -660 |l dec 81 if gy != 89 |zp dec -184 if uxa == 510 |gcf dec -97 if gcf == -1034 |tyg inc -508 if x != -2468 |cty inc 89 if j < -960 |jq dec 416 if rf >= -2132 |rf inc -846 if cty >= -577 |uxa dec -315 if vyy <= 2294 |g inc -191 if vyy == 2294 |js dec -557 if wow == -934 |u dec 382 if qc >= -2313 |dma dec -841 if wow > -929 |u dec 6 if dma < 1932 |aqr inc 75 if js == 63 |jq inc 640 if gcf < -928 |wn inc -992 if j != -967 |uxa dec -577 if wn != 726 |g inc -458 if rjx < -467 |epp dec 141 if x == -2468 |l inc 617 if cty < -576 |gy dec 542 if yzp != -377 |cty dec -99 if uxa < 1410 |tyg inc -358 if g > 521 |wn dec 514 if uxa <= 1401 |dma inc 110 if j > -960 |js inc -359 if jq <= 569 |epp dec 266 if epp < -312 |x inc -473 if jq > 557 |vyy inc 890 if wn == 730 |zp dec 379 if gcf != -932 |u dec 46 if jq == 565 |tyg inc -410 if l != 256 |i inc -320 if js != -303 |l dec 670 if i >= -2482 |i inc 788 if u < -2391 |l inc 23 if cty == -476 |tyg inc -364 if rf <= -2969 |gy dec 394 if epp >= -584 |esb dec 645 if aqr != 907 |epp inc -842 if x < -2935 |js dec -289 if l == -392 |tyg inc -405 if gcf == -937 |vyy dec -58 if epp == -1419 |gy dec 110 if u == -2398 |vyy dec -789 if epp > -1426 |qc dec 463 if zp >= 1117 |gcf inc 859 if esb == 1616 |u inc -99 if js < 2 |epp inc 111 if tyg == -67 |jq inc -536 if d < -661 |js inc 506 if dma <= 1936 |rjx dec -58 if j >= -971 |wn dec -513 if tyg <= -64 |wow dec 816 if aqr >= 902 |gcf inc -957 if x == -2941 |uxa dec -39 if yzp <= -377 |wn inc 824 if g <= 531 |gcf dec 927 if l >= -394 |x dec -655 if l == -392 |g inc 767 if tyg > -59 |dma inc -493 if epp != -1318 |esb inc -587 if epp >= -1318 |wow inc 996 if cty >= -479 |l dec 119 if epp != -1311 |gy dec -935 if uxa < 1444 |gcf dec -428 if zp >= 1121 |js inc -999 if x > -2293 |uxa dec 438 if epp != -1305 |gcf dec -623 if yzp <= -380 |j inc -256 if gcf < -1530 |l inc -183 if d >= -662 |wn dec 945 if x < -2279 |i inc 953 if epp == -1311 |vyy inc -434 if js > -1016 |yzp dec -695 if epp < -1308 |d inc 975 if l == -575 |uxa dec -218 if j < -1216 |gcf inc 413 if tyg == -67 |wow inc -380 if zp != 1125 |cn dec 166 if wn > 1113 |rjx dec 878 if l != -581 |esb inc -745 if g <= 531 |aqr dec 14 if esb < 292 |j inc 405 if jq == 565 |vyy inc 657 if wn == 1124 |j dec -624 if qc > -2763 |rf inc -711 if esb < 289 |uxa inc 453 if gy >= 512 |i inc 593 if js >= -1009 |qc inc -413 if j > -826 |tyg inc -395 if epp == -1311 |cty dec -911 if g >= 524 |yzp inc -259 if esb >= 277 |dma dec -812 if vyy > 2643 |wow inc 887 if gcf >= -1121 |uxa inc 906 if rf < -3686 |l inc -816 if js > -1002 |aqr inc -123 if tyg >= -462 |x inc 413 if uxa < 2590 |tyg dec -141 if wow <= 142 |cn inc -138 if gcf > -1118 |i inc 665 if wn < 1117 |wow inc -250 if gy > 505 |wow inc 751 if l != -569 |j inc 334 if x >= -1879 |i inc -963 if uxa >= 2575 |uxa dec -395 if wn == 1106 |dma dec 130 if esb != 290 |l inc 171 if zp > 1122 |esb inc 288 if uxa < 2576 |wn inc -672 if i > -445 |uxa inc -593 if jq == 565 |cty inc -247 if yzp >= 52 |vyy inc 480 if cn == 6907 |js dec -402 if uxa <= 1982 |l dec -121 if cn < 6913 |rjx dec 692 if i <= -433 |g inc 827 if cty >= 186 |d inc -333 if i >= -449 |zp inc 438 if u > -2502 |gy dec -418 if cn >= 6902 |x dec 665 if uxa != 1980 |zp dec 497 if l == -283 |i inc -51 if rf >= -3694 |dma dec -792 if gy < 931 |dma dec -189 if wn <= 435 |cty dec 337 if g != 1347 |zp inc -436 if dma == 2919 |yzp dec -184 if rjx <= -1980 |gcf inc 688 if qc <= -3174 |u inc -536 if zp <= 636 |d dec 31 if rjx != -1989 |esb dec 523 if wow >= 651 |gy inc 566 if zp >= 632 |vyy dec 190 if zp == 630 |tyg inc 53 if i < -486 |x dec -543 if i < -482 |uxa dec 403 if epp != -1319 |i inc 880 if u == -3033 |wn dec 172 if gcf < -428 |qc dec 316 if cn > 6904 |gcf dec 864 if rf == -3688 |esb inc -344 if uxa <= 1583 |i inc -234 if js >= -1006 |x dec -306 if d < -45 |vyy inc -256 if rjx >= -1983 |u dec -498 if epp > -1309 |esb inc -915 if u == -3033 |i inc 910 if esb < -624 |l dec 781 if qc > -3505 |g dec 803 if u < -3032 |dma dec 392 if u == -3033 |cty inc 216 if vyy != 2929 |zp dec 12 if gy == 930 |gy dec -35 if tyg >= -269 |wow inc 824 if wow != 642 |js inc 974 if epp >= -1319 |gcf inc 883 if dma != 2527 |jq inc 339 if cty != 72 |yzp dec 751 if zp != 627 |tyg inc 90 if x < -1679 |vyy inc -212 if rjx < -1976 |wow dec -642 if epp <= -1302 |d dec -643 if x <= -1689 |i dec -25 if vyy != 2728 |js inc -522 if tyg == -178 |js dec -880 if epp == -1311 |l inc -899 if x == -1689 |u dec 459 if g < 563 |tyg dec -485 if i > 1083 |zp dec -944 if dma < 2537 |cn inc 867 if cty > 57 |i dec -95 if jq == 904 |gcf dec 548 if d == 595 |gcf inc 35 if aqr >= 766 |x inc -420 if yzp != -501 |x inc -308 if yzp == -500 |vyy inc -407 if l <= -1961 |gy inc -623 if j < -476 |u inc -932 if g > 547 |zp dec 18 if js > 324 |g dec 776 if cn > 7771 |jq dec 581 if cn == 7764 |zp inc 392 if g < -215 |vyy inc -266 if i < 1185 |tyg inc 600 if jq < 906 |wow dec 480 if aqr != 770 |yzp dec -97 if j <= -488 |cn dec 212 if wow == 1284 |vyy dec -247 if rjx == -1992 |x dec -13 if uxa != 1584 |wow inc 929 if vyy < 2330 |qc inc 515 if vyy != 2313 |wow dec -484 if u <= -4424 |wn dec -251 if wow > 2699 |dma inc 128 if d > 585 |epp inc -429 if cn > 7564 |tyg inc 401 if gy < 344 |dma inc -757 if qc == -2975 |rjx inc 124 if tyg == 1308 |j dec -258 if wn < 279 |zp inc 265 if u != -4431 |epp dec -850 if epp <= -1308 |jq inc 875 if cty > 64 |esb dec -585 if yzp <= -509 |qc inc -663 if vyy != 2313 |cn dec 194 if rf < -3682 |i inc -821 if rjx > -1862 |qc dec -768 if i != 354 |rf inc 949 if gcf != -1805 |wow inc -350 if gcf == -1807 |l dec -72 if dma <= 2663 |qc inc -201 if x <= -2106 |cty dec -576 if esb == -631 |uxa dec 387 if i >= 358 |uxa inc 189 if uxa >= 1193 |i dec 193 if qc > -3089 |gcf inc -164 if wow == 2697 |aqr inc -154 if cn < 7364 |dma inc 145 if j < -228 |cn inc -314 if rf > -2749 |qc dec 976 if yzp > -509 |tyg dec -277 if j == -226 |l dec -339 if yzp < -501 |qc dec -615 if js > 320 |x inc -678 if rf >= -2743 |rjx inc -777 if g > -228 |rf dec 151 if vyy <= 2320 |js dec 591 if u <= -4422 |i inc 166 if d != 585 |cn inc -615 if esb < -634 |qc dec -148 if dma > 2649 |gy dec -93 if d == 595 |esb dec 265 if js < -256 |wn inc 784 if x != -2795 |rf inc 123 if yzp < -499 |tyg inc 51 if rf <= -2777 |dma inc 273 if tyg != 1575 |g dec 546 if uxa == 1386 |j inc 787 if l < -1546 |rf inc 97 if qc <= -3289 |x inc 621 if uxa <= 1388 |cn inc -760 if esb <= -894 |jq inc -89 if zp <= 2197 |uxa dec -485 if wow == 2697 |j inc 971 if rjx == -2638 |rjx inc 117 if l != -1552 |yzp inc -335 if wn < 1059 |gy dec -871 if j <= 1541 |tyg dec -602 if yzp != -852 |rjx dec -852 if cn > 6293 |g dec 893 if cn > 6293 |uxa inc -524 if cn > 6297 |yzp inc 389 if i < 347 |epp dec -502 if rf > -2667 |dma dec 323 if yzp > -453 |l inc -921 if wow <= 2706 |yzp dec -534 if jq > 1777 |yzp dec 94 if rjx != -1784 |uxa inc 254 if vyy != 2320 |i dec 224 if gy <= 1313 |u inc -466 if vyy < 2318 |epp dec -751 if cn <= 6299 |qc dec -316 if tyg >= 2197 |d inc -666 if epp == 290 |g dec -398 if js != -274 |rf dec 482 if cn == 6304 |vyy inc 295 if cty == 643 |wn dec -540 if i != 108 |qc inc -334 if wow != 2691 |d dec 315 if dma < 2935 |qc dec -860 if d != -385 |qc dec -202 if gy > 1296 |wow dec -67 if vyy > 2610 |esb dec 880 if vyy != 2621 |cn inc -985 if d <= -383 |epp inc -435 if g == -1263 |gcf dec 559 if u != -4419 |aqr dec 979 if yzp >= -23 |jq inc 905 if wn < 1597 |cn inc -679 if x >= -2165 |rf inc -590 if j != 1532 |l dec -73 if wn <= 1598 |qc dec 804 if d > -388 |j inc 42 if zp < 2198 |tyg dec -636 if qc < -3366 |gy inc 209 if vyy != 2613 |l inc -725 if x < -2158 |qc inc -54 if j >= 1531 |cty inc 896 if js < -258 |u dec -718 if d <= -377 |l dec 654 if esb >= -1785 |dma dec 912 if i <= 120 |uxa inc 827 if cty <= 1543 |rf dec -871 if g >= -1271 |uxa inc -77 if tyg > 2814 |d inc -59 if i <= 121 |dma dec 792 if cn == 5309 |zp inc 930 if yzp >= -15 |gy inc -956 if d == -435 |wn dec -205 if j <= 1540 |d dec -830 if cty >= 1536 |tyg inc -552 if u != -3700 |rf inc -616 if gcf != -2533 |yzp dec -87 if rf >= -1793 |uxa inc -886 if dma <= 1226 |g inc 278 if uxa < 1741 |j dec 1 if vyy > 2614 |d dec 899 if rjx == -1786 |rjx dec 238 if vyy >= 2606 |cn inc -663 if d <= -505 |rjx inc -805 if l != -3785 |tyg dec 610 if aqr != -206 |gcf inc 842 if yzp <= -12 |tyg dec 361 if l <= -3772 |wow inc 717 if dma != 1219 |vyy dec 182 if gcf != -1695 |l inc -972 if vyy >= 2428 |cn dec -106 if gy <= 1517 |g dec 598 if cn >= 4749 |l dec 653 if rf <= -1808 |epp dec -768 if esb != -1781 |rf dec -566 if uxa != 1740 |aqr inc 639 if cn == 4752 |wn inc -877 if u == -3699 |uxa dec -7 if vyy >= 2427 |yzp dec -107 if qc != -3430 |yzp inc -426 if esb <= -1776 |epp inc 102 if x < -2164 |u dec 396 if jq == 2684 |dma dec -6 if jq <= 2686 |cn inc -739 if gcf > -1698 |gcf inc 470 if cty == 1539 |gy inc 781 if vyy != 2433 |vyy dec 238 if dma < 1236 |wow inc 670 if wn != 1801 |i dec -230 if jq < 2686 |wn dec -500 if wow == 3481 |wow dec 865 if j < 1536 |x inc -733 if jq == 2684 |cty dec 531 if gy >= 1513 |g inc 399 if esb < -1768 |x inc 201 if rf == -1233 |cn inc 394 if d < -515 |epp inc -953 if wow >= 2615 |qc inc -639 if u != -4095 |i inc 935 if vyy > 2191 |g inc 846 if gcf != -1218 |epp dec 89 if yzp > -334 |qc dec -143 if epp >= -317 |gy dec 256 if zp != 3132 |tyg inc 545 if rjx > -2831 |cn dec 913 if gcf != -1226 |esb inc -410 if d == -514 |rjx dec -71 if tyg <= 1849 |rjx inc -127 if yzp > -336 |jq inc -206 if gcf >= -1221 |i dec -800 if gcf > -1225 |aqr inc 98 if gy < 1263 |gcf dec 163 if gcf <= -1213 |cty dec -965 if zp == 3131 |rjx dec -969 if cty < 1976 |uxa inc 51 if x == -2698 |u dec -380 if wow == 2616 |tyg dec -715 if rjx >= -1922 |zp inc -825 if yzp >= -323 |zp dec 292 if x > -2702 |esb inc -415 if d <= -505 |wn inc -240 if esb > -2609 |gy inc 882 if rf == -1233 |vyy dec -638 if gcf <= -1384 |tyg dec -63 if jq <= 2479 |dma inc -38 if uxa < 1797 |qc inc 289 if wow < 2619 |d inc 342 if yzp >= -330 |cty inc 650 if js < -271 |l inc -129 if esb == -2601 |jq inc 453 if j > 1531 |esb dec 11 if i > 2084 |wow inc -729 if wow < 2620 |x inc 132 if uxa <= 1796 |l dec 818 if vyy <= 2832 |tyg dec 804 if yzp != -334 |wow inc 285 if rf != -1233 |zp dec -329 if wn != 2061 |u inc 720 if js == -265 |gcf inc 85 if aqr != 528 |wow dec -303 if jq != 2472 |vyy inc -366 if cty < 1965 |yzp inc 598 if cty == 1973 |rf inc 685 if jq >= 2471 |vyy inc -385 if jq <= 2487 |aqr inc 103 if esb >= -2598 |d inc 427 if uxa == 1793 |rjx inc -736 if zp < 2849 |x dec -991 if esb <= -2600 |gy inc 642 if gcf <= -1391 |yzp dec -726 if wow < 2195 |zp dec -582 if u == -3002 |rf dec -354 if cn > 3093 |g inc -150 if g != -342 |uxa inc -381 if wn >= 2060 |wow inc -145 if qc < -3628 |g inc 589 if qc <= -3626 |jq dec -643 if js == -265 |yzp dec -768 if cty == 1973 |vyy dec 448 if aqr <= 533 |uxa dec 507 if cn <= 3103 |gy dec 134 if aqr >= 521 |x dec 868 if rf != -194 |gcf inc 355 if cn >= 3093 |rf dec 639 if tyg == 1822 |gcf inc -671 if wow >= 2048 |jq inc 615 if gy != 2012 |zp dec -910 if cn < 3096 |rjx inc 949 if wow < 2055 |esb dec 623 if jq != 3731 |g dec -799 if qc != -3634 |uxa inc -352 if rf >= -196 |gcf dec 229 if jq != 3729 |zp inc 785 if rf > -200 |i dec 150 if gcf < -1251 |gcf inc -463 if dma != 1189 |j inc -424 if wn == 2061 |l inc 412 if gcf <= -1715 |aqr inc -646 if u <= -2994 |i inc 195 if l <= -4471 |rjx inc 291 if cty < 1982 |epp dec 459 if dma != 1198 |u inc -909 if vyy > 1998 |uxa dec -208 if vyy > 1994 |u dec 727 if i == 1928 |x inc -402 if l == -4468 |u inc -459 if cn > 3095 |j inc 253 if jq < 3733 |vyy dec -143 if rf > -204 |rjx dec -560 if tyg < 1822 |cn dec -602 if jq > 3732 |wow dec -231 if wn >= 2066 |js inc -40 if x > -1972 |gcf dec 591 if rjx >= -842 |wn inc -612 if u <= -5090 |vyy inc 60 if j >= 1100 |cty dec -207 if tyg == 1819 |wow dec -862 if dma < 1197 |cn dec 534 if i <= 1936 |d dec 380 if wow == 2907 |x inc 48 if dma < 1199 |yzp inc 955 if dma != 1191 |dma inc -372 if l <= -4467 |uxa dec 83 if wow != 2909 |u dec 383 if u > -5102 |cn dec 691 if cn <= 3169 |vyy inc 952 if jq == 3733 |j dec -231 if wn < 1444 |i dec -988 if x >= -1931 |cn dec -459 if x > -1936 |js inc -714 if epp != -779 |gy dec 751 if cn <= 2936 |epp inc -45 if vyy != 2203 |aqr dec -251 if i != 2916 |zp dec -248 if x == -1929 |vyy dec -917 if tyg > 1814 |l inc 906 if rjx > -855 |wn dec -262 if aqr >= -120 |js inc -293 if j >= 1108 |g inc -507 if uxa < 671 |tyg dec 848 if uxa < 680 |tyg inc 449 if cn != 2931 |jq inc 43 if d >= -474 |uxa dec 510 if rjx != -852 |u dec -15 if cn <= 2936 |rf dec 467 if uxa < 688 |dma dec 40 if j < 1114 |cn inc 256 if l > -3564 |uxa dec -193 if cty <= 2173 |cn inc 472 if epp <= -773 |g dec 509 if qc != -3621 |x dec -909 if wow >= 2902 |j inc 809 if rf > -663 |epp inc 458 if x > -1028 |cty dec -210 if wn > 1707 |wn dec 778 if rjx <= -848 |zp inc 745 if l == -3570 |dma inc -86 if rjx != -852 |dma inc -964 if aqr > -126 |x inc -741 if wow == 2909 |cn inc -751 if esb <= -3217 |cty dec 910 if qc >= -3636 |gcf inc 496 if epp >= -321 |rf dec -516 if epp >= -322 |dma inc -112 if dma <= -187 |yzp dec -376 if zp >= 4451 |js dec -829 if qc >= -3629 |rf inc -310 if dma > -188 |gy inc -312 if wow >= 2899 |cn dec 889 if dma > -186 |g inc 667 if uxa > 682 |u inc 201 if u != -5462 |cty dec 589 if yzp > 3082 |gy inc -274 if wow != 2907 |u dec -533 if tyg == 1420 |zp inc 937 if d >= -469 |jq dec 18 if cn == 2024 |cn dec -59 if rjx <= -850 |dma dec -172 if x > -1026 |jq dec 129 if gcf > -1231 |wn dec 957 if jq < 3627 |uxa dec -989 if wn <= 939 |jq inc -390 if x != -1013 |js inc 251 if g < 385 |jq inc -572 if tyg <= 1424 |g inc -265 if vyy > 3122 |rjx inc 789 if x > -1025 |gcf dec -838 if d < -465 |g dec -564 if gcf != -387 |vyy dec -188 if yzp != 3087 |i dec 912 if x < -1015 |cty inc -768 if x <= -1019 |wn dec 175 if wow == 2906 |wow inc 534 if qc > -3627 |js inc 247 if x >= -1026 |vyy dec 894 if gy == 944 |x inc -150 if rf != -445 |dma dec 766 if wn < 932 |gcf dec -53 if zp >= 5383 |g dec 9 if u >= -4740 |yzp dec -425 if vyy < 2423 |aqr inc 407 if vyy > 2406 |gcf inc -244 if tyg != 1429 |i inc 120 if i <= 2010 |cty dec -40 if rf == -455 |x dec -433 if wow <= 2900 |u dec -553 if cty != 162 |jq dec 329 if u <= -4177 |aqr dec -319 if g > 387 |esb dec 259 if wow > 2904 |jq dec -590 if vyy < 2415 |tyg dec -211 if d == -467 |rjx dec -209 if l != -3561 |tyg inc -564 if aqr >= 281 |aqr dec -860 if u != -4186 |wn inc -298 if g >= 387 |x inc -951 if i < 2122 |j inc -141 if cty >= 163 |l inc 780 if wow != 2910 |zp dec 796 if esb > -3491 |j dec 652 if qc < -3628 |cn dec 101 if i <= 2128 |cty inc -169 if gcf < -573 |dma dec -544 if epp <= -309 |vyy dec -261 if zp <= 4598 |rf inc 166 if esb == -3487 |aqr dec 865 if rf == -455 |u dec -14 if rjx <= 148 |vyy inc -518 if dma < 538 |aqr dec -30 if cn <= 1988 |rf dec 818 if wow <= 2912 |js inc 116 if l > -2786 |jq inc 707 if gy > 939 |jq dec -673 if x < -1176 |wow dec 94 if rjx >= 141 |esb inc -654 if esb > -3488 |jq inc 982 if i != 2127 |cn inc 479 if i > 2122 |js dec 530 if rjx >= 144 |wn dec -37 if gcf != -578 |esb dec -917 if cn > 2458 |l dec 519 if wn > 923 |uxa dec 671 if wn == 933 |zp inc -269 if cn >= 2457 |esb inc -329 if wn == 933 |tyg inc -490 if d <= -468 |dma dec 817 if wn > 930 |cty inc -650 if u != -4164 |rf inc 804 if l >= -3309 |dma dec 629 if esb == -3549 |l dec -588 if epp < -317 |zp dec 738 if zp >= 4318 |l dec -772 if wn != 924 |epp dec -423 if js <= -317 |g dec 781 if qc != -3637 |uxa inc -540 if tyg > 1062 |gcf dec 120 if j != 1127 |d inc 294 if wow >= 2819 |i inc 108 if u >= -4169 |x dec -117 if zp > 3581 |i inc -434 if gy > 950 |jq dec -749 if zp >= 3587 |gcf dec -342 if tyg != 1063 |j inc -910 if wn != 932 |u inc -353 if rjx > 142 |qc inc -478 if esb == -3549 |uxa inc -992 if wn != 933 |cty dec -628 if gcf == -356 |u dec -527 if dma != -916 |aqr inc -354 if j >= 211 |d dec 633 if x >= -1062 |l dec 920 if js != -326 |wn dec -122 if j > 203 |x dec 907 if gcf == -356 |epp inc 112 if epp != 105 |wn dec 322 if u >= -3988 |j inc 934 if wn != 1055 |g inc -366 if uxa >= 448 |uxa dec -720 if wn <= 1063 |zp inc 8 if gy <= 947 |esb dec -199 if epp <= 110 |cn dec -122 if j != 220 |l dec -810 if g <= -763 |cty inc -435 if yzp < 3521 |zp dec 615 if i >= 2230 |jq dec -445 if uxa != 1170 |gy inc -654 if u > -3994 |tyg dec 48 if dma == -914 |gcf inc -346 if dma < -905 |wn inc -660 if zp >= 2980 |x inc -242 if esb >= -3359 |gy inc 28 if rjx < 154 |tyg dec 602 if esb <= -3341 |jq dec 380 if l > -2061 |i inc 502 if js <= -308 |uxa inc -255 if qc < -4109 |u dec -617 if l == -2051 |rjx inc -864 if esb <= -3347 |u dec -465 if vyy == 2157 |tyg dec 629 if i < 2740 |d inc -28 if u < -2907 |epp inc -430 if cn <= 2585 |vyy dec -740 if yzp == 3515 |js inc 387 if gy > 315 |vyy dec 792 if gy >= 310 |l inc -89 if wn > 389 |qc dec -149 if wow > 2810 |gy inc 510 if cn == 2583 |d inc 381 if g != -757 |x inc 633 if gcf != -694 |wn dec -677 if j > 222 |wn inc -605 if i >= 2729 |zp dec 794 if rf < -474 |dma inc -560 if js >= 61 |rjx dec -364 if wow <= 2819 |jq inc 429 if g != -774 |rjx dec -305 if j <= 215 |epp inc -254 if tyg <= -219 |i dec -106 if qc < -3955 |g inc -514 if zp < 2983 |dma inc 617 if u >= -2911 |gy dec -81 if aqr > -40 |g inc -722 if wn < -201 |zp dec -46 if tyg >= -210 |yzp dec 720 if gy <= 830 |cty inc 675 if epp >= -318 |qc dec 727 if cn >= 2574 |zp dec -458 if wow != 2811 |jq inc -547 if yzp <= 2800 |uxa dec 443 if l == -2140 |x dec 76 if tyg == -212 |x inc 11 if aqr != -36 |x dec 1000 if aqr <= -37 |l dec -384 if gy != 822 |u dec -329 if aqr == -40 |x inc 432 if wn > -202 |uxa inc 530 if tyg < -202 |i dec -798 if js < 71 |dma inc -503 if i == 3645 |dma inc 69 if uxa <= 1264 |d dec 571 if js != 70 |wn inc 134 if u >= -2588 |i dec -813 if rjx > -48 |epp inc -735 if cn < 2585 |aqr dec -223 if dma >= -790 |uxa dec -86 if dma >= -789 |cty inc 127 if aqr < 188 |cty inc 472 if uxa == 1349 |cn inc 780 if cty >= 791 |cn dec -528 if rjx == -49 |l inc 669 if d != -754 |gcf dec 427 if epp != -1052 |rf inc 465 if dma >= -797 |epp inc 452 if g != -2005 |epp dec -922 if i != 3648 |wow inc -516 if js != 72 |esb dec -623 if epp == 314 |wn inc 434 if cn == 3111 |rjx inc 698 if yzp == 2794 |vyy dec -150 if epp < 319 |rjx inc 343 if yzp != 2797 |jq inc -390 if gy <= 831 |yzp dec 296 if l >= -1093 |yzp dec 676 if esb > -2730 |js dec 320 if epp < 318 |jq inc 44 if g < -1996 |esb inc 425 if zp >= 3444 |i inc -817 if esb == -2727 |cty inc -336 if esb != -2727 |epp inc -90 if uxa < 1341 |zp dec 554 if epp != 312 |js dec -299 if epp != 319 |zp dec 92 if wn <= 366 |wow dec -443 if rf > -12 |gy dec -962 if i < 2825 |vyy inc 381 if d > -748 |wn dec -212 if js <= 54 |esb dec -944 if gcf != -1127 |cty dec 985 if j != 211 |aqr dec 697 if uxa >= 1340 |wow dec 459 if gcf < -1120 |i inc 728 if dma >= -796 |cty inc -277 if tyg >= -216 |rjx inc 279 if aqr == -505 |yzp inc -38 if zp >= 2793 |zp dec 221 if epp == 314 |d dec -628 if x <= -2630 |uxa dec -846 if esb == -1783 |rjx dec 154 if x <= -2625 |l inc 541 if wow >= 2290 |wow inc -777 if vyy < 2636 |rjx dec -492 if uxa >= 2195 |gy inc 881 if yzp < 1791 |x dec 24 if l >= -1095 |jq inc -82 if x >= -2658 |tyg dec 763 if aqr > -519 |wn dec -242 if esb < -1773 |tyg inc 574 if d == -119 |d dec 423 if i > 3540 |""".stripMargin }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day13/SolverSpec.scala
<reponame>parwen68/advent-of-code-2017 package se.parwen.adoc.day13 import org.scalatest.{FlatSpec, Matchers} import Solver._ class SolverSpec extends FlatSpec with Matchers { "The layer" should "return 0,1,2,3,2,1,0,1,2,3 in 0,1,2,3,4,5,6,7,8,9" in { val layer = Layer.parse("0 : 4") List(0,1,2,3,4,5,6,7,8,9).map(layer.getForPicoSec) should be (List(0, 1, 2, 3, 2, 1, 0, 1, 2, 3)) } "The layer" should "return 3 in pico 3" in { val layer = Layer.parse("0 : 6") layer.getForPicoSec(3) should be (3) } // 0,1,2,3,4,5,4,3,2,1,0,1,2,3,4,5 "The layer" should "return 2 in pico 15" in { val layer = Layer.parse("0 : 6") layer.getForPicoSec(15) should be (5) } "Layers in pico 0" should "0,0,0,0" in { val r = Pico(parse("""0: 3 |1: 2 |4: 4 |6: 4""".stripMargin)).getForPicoSec(0) r should be (Map(0 -> (3,0), 1 -> (2,0), 4 -> (4,0), 6 -> (4,0))) } "Layers in pico 3" should "1,1,3,3" in { val r = Pico(parse("""0: 3 |1: 2 |4: 4 |6: 4""".stripMargin)).getForPicoSec(3) r should be (Map(0 -> (3,1), 1 -> (2,1), 4 -> (4,3), 6 -> (4,3))) } "The solver parse" should "return list" in { val r = parse("""0: 3 |1: 2 |4: 4 |6: 4""".stripMargin) r should be (Layer(0,3) :: Layer(1,2) :: Layer(4,4) :: Layer(6,4) :: Nil) } "The solver solveStep1" should "return 24" in { val r = solveStep1("""0: 3 |1: 2 |4: 4 |6: 4""".stripMargin) r should be (24) } "The solver solveStep2" should "return 10" in { val r = solveStep2("""0: 3 |1: 2 |4: 4 |6: 4""".stripMargin) r should be (10) } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day4/Input.scala
<filename>shared/src/main/scala/se/parwen/adoc/day4/Input.scala package se.parwen.adoc.day4 object Input { val input = """ |kvvfl kvvfl olud wjqsqa olud frc |slhm rdfm yxb rsobyt rdfm |pib wzfr xyoakcu zoapeze rtdxt rikc jyeps wdyo hawr xyoakcu hawr |ismtq qwoi kzt ktgzoc gnxblp dzfayil ftfx asscba ionxi dzfayil qwoi |dzuhys kfekxe nvdhdtj hzusdy xzhehgc dhtvdnj oxwlvef |gxg qahl aaipx tkmckn hcsuhy jsudcmy kcefhpn kiasaj tkmckn |roan kqnztj edc zpjwb |yzc roc qrygby rsvts nyijgwr xnpqz |jqgj hhgtw tmychia whkm vvxoq tfbzpe ska ldjmvmo |nyeeg omn geyen ngyee rcjt rjuxh |qpq udci tnp fdfk kffd eyzvmg ufppf wfuodj toamfn tkze jzsb |rrcgxyp rbufd tfjmok vpyhej hcnz ftkojm |jnmomfc jnmomfc bkluz izn ovvm flsch bkluz |odisl hzwv hiasrhi hez ihihsra qpbmi ltwjj iknkwxf nbdtq gbo |gjtszl gjtszl fruo fruo |rdapv gaik cqboix sxnizhh uxmpali jdd usqnz advrp dze |flooz flooz qad tcrq yze bnoijff qpqu vup hyagwll |lnazok dze foi tqwjsk hpx qcql euzpj mwfrk |ilb fmviby ivybmf gtx xtg |rpauuu timere gyg wcolt ireetm safi |croe szwmq bbhd lciird vhcci pdax |hnc ykswt qqqmei goe bri wmyai hnc qpgqc pberqf bzs |hsnrb wdvh iezzrq iezzrq rdbmpta iezzrq kemnptg alkjnp wymmz |ngw don ddvyds nlhkoa aaf gptumum ugtpmmu |vmccke qbpag kvf kvf tgrfghb kvf bhpd sglgx |obomgk bkcgo yso ttft vbw ckl wjgk |fli qvw zhin dfpgfjb udsin nihz ovr tiewo |tgmzmph hauzieo jmg tdbtl lvfr qpaayq qapaqy ausioeu jun piygx |jkp guqrnx asdqmxf vmfvtqb tloqgyo ioix gajowri tmek ilc puhipb |uycn zxqm znft ayal znacus kvcyd ekv qqfpnh |fqghur xtbtdd ztjrylr bpuikb ziyk |rvakn uqbl ozitpdh uqbl dsej xehj |laxp haz jyd xnkrb ijldth woy xapl iqgg alpx gnupa ukptmmh |dyiy dyiy ihb qcyxr |wbwkd hdwu zvgkn hdwu wjc sakwhn zxujdo npllzp uyr uyr |fxczpmn cininu akcxs ggslxr riyxe ojisxe |ppbch sampq dnct afikor dnct edsqy pnzyzmc afikor |jnvygtn hijqjxl vsd jnvygtn nqcqv zns odq gkboxrv kolnq wrvd |mroq mroq flsbu flsbu |fyshor xvpaunj qmktlo xoce wkiyfu ukcl srndc ugwylwm ozcwdw mtqcste kpokr |cfh cxjvx cfh cfh uewshh |bpspbap bpspbap fquj mxmn bwls iirhvuk dmpkyt exrn mxmn |tvyvzk ezszod ntxr xtnr och |knfxhy kbnyl knfxhy xhkssx lxru uprh nkxpbx oodolxr tpvyf |nblmysu iwoffs upgof tyagwf aan vovji ajk ywzq oyfi sfulz |aushzkm lcaeki mkuzsah ynxvte rsntd refk pcm |mgguob gobmug dzenpty gmogbu |yvq eepof rgnree nerger fpb stfrln ernger |hrgkbl mzwvswk rsrsbk ieru holco pajvvn ztgsr qkyp fyeg owpcmoj |fowda gmsqdca yugj mcrroxv mqcbojd fjnqfji qdfsc jqs |qnc rvjfz vvxk sjd xrma ucdjvq sbw zydyt dfzww |ocajazv cozaajv tqunkla udwf ecnnmbz lsakqg bki njnda zsdu ccfqw rxpc |qqm qdfya qxyx qmq qfday uqnfttt |rnbirb iapor qet iapor hxkhz dfvzig pedl ybyb |mkgamxg xkniv meb hbzmxjn dhbj zhbxjmn hdjb |ilteux pyutyfx mau lrr bacak |sjjonmn dbbbgs crxyuu jztstgd ezb uiabyaa |tra fle ufzlvf nnaw kec hiwnnlj tei wld iyt syk hjdczb |qmd jtlud dgh dbanock fzp dsjgqru wwvo jwvxwgv xlemfij jcacd |rpkx oxesil snazcgx fly miiyc ikmtmp oefyyn egbw |ypfpeu wldnyd acchppb yqwcaw wldnyd turbz megci nbgxq xkc ypfpeu |iqqv iqqv neui iqqv |ypsxm icqyup zyetrwq nbisrv |viommi toszx dpueq eyy cunjou ffcjc jaeez djefra pxvkj liudlig yye |fhnacbg jghchh ghjhhc iue hwqmo |vbjw lpn cizba ltnsfpz tzoweml irewlc uzckhpd mszal obd |yeos utxkft hflxkfe fxczge qpgigkc ksgr vuumql vhlvv |xzmkv xzmkv krecdi klpem jsbu nwcmik emfzxf cjmpgnj |vtkjo pmiv zou gxo qdiyxsf hwyinjk jhkgf rjq |dyuoc ywiyvch irfgl ywiyvch fxb fxb |tuz onhr syu rqya abkaf bcfx mbknex juwoor zmksl |oheg spjorx ksdy vwtq fxz phvtazk tcze lrxg |hew lbup botaj ltr jpd |dxgc tzinkej gnz hxvvub adsqmc dxgc asgpp rqbdcra goy pmamdua bhiacva |xqv ygb kihxqz vyv pjcny vmyvsdv cgsi nfyx |tqga ssshrw ndq qlbvwh huyd pxbgj qbxk dkkbf jxy chsobw pph |hxl iwph iwph xnr otifm ljhre |zlgvpd kapxpoc dve rklk ogh hgnp rbrmc zzkz hhmcx aklmo |sar gfor nkf hek nkf aql shc aql |dtcrw kfjzcjx qyhi bldson whwdayo mqtgt xhqzp ttqmg |omspdml isze jdl nvwo qrkm wztfg ssfgyh dryj jhp unsmty |jxt cszylng ifht ixtuna azoi xutqlv jtx tjx |usgm azuayp fgkby ezpyq jqwl ezofj |tnhvil nrvg moyrpqs sldx qymoff megflxh pyhqwms xmdw |zomy zcquwnv lzx bvcna yods mjp dgsez |blklyf xokd gpit tiysj yrwfhm tofx |dtig vhdp omuj vhpd |fogwxim qvdwig emdiv jvhl euwbzkg xvxb hwmqo ujdmlp epmykj |sjxll sjxll pedvgb sjxll |drvay gtzhgtx yrt okz nqf |haxfazn pvkovwb pgu tgshw mxcjf pbe nwoymzc mxcjf pbe hydwy jradcr |prjsloa ahylvj okbsj qbdcdjt pmfo pagyoeg vkmhjzt khzmjvt opfm xfrji gyjqyel |lzypt jdbtrad ogr jdbtrad heink |rcoucuq gdxewa rcoucuq whlw zhhm rcoucuq azaqohe mzyli rdvaf |yuag ebcf yuag nsotg qqzuxr jfmao vyucw wmoye |qwvk xemm hgqrr wyxkpp tojndm xlvzypw jus bgnu bgnu nklfwhs |daqi knenmku ccm xkiuy vkexsbc kvvdagx umopitw yaocnx yoakqql mllmsp |mrxgl gywit mfopia ncnsvw vdxek axuiot rsejua nei prndudz mnu |egqn gaa qgen urs mix zbn rhn |ewharq aihy udkdaob kgrdd kgrdd kugbjtj fcef llqb pduxaq wcexmm |dwtiw nelq hppad algxgf gcc upou akm efnb mxmhrud |yxqaa ups okbhgt iet qns tqn rnjqxgp |npmhdm cgds ldexvr typi jyivoqk zkgq vfyxu xgfo |dkwnmr umm dkwnmr okpjw wqx jpztebl eqsib dkwnmr |dxbild wpbup evscivq dxbild dxbild geqp ojfbpl jshvqej |cxdntxs csfocjd pyy tuhws teb boyloz xfw scxh pxhonky |lteucke xrgwy hszgzu hnyrcvb |pfgsgwg dxzh fworek qbstod |usemcrf psczxu gcjtr brls |hjol efxczux bqdn gvrnpey yyoqse gbam ndzyj lbwb bhzn unsezg |bapw xifz blupk qqdk bofvqpp wnbuwyt rnwocu lzwgtt zucag pov |xkre lqvd juf lqvd xio xyg xyg |tzdao ztheib aymcf aorg iyawrch hetcxa iyawrch czdymc ccv |ucgl azlppu jvxqlj pest |dvwlw fuuy mnhmm okrp ualnqlm uyuznba fzyejk yaq crl ctprp |odfq knox mkbcku pxucmuf lpjpol phl |ixongh hfs ruorbd auy qyssl kykwcix aytsm rlj aytsm duq segpqhk |izufsk wedpzh podjkor eamo vqvev ifnz podjkor xrnuqe |twyfps bmdbgtu qye qkwjms |wlav htym vhsnu cocphsj mdsuq vhsnu jflgmrp |opajag itwjhfu purnnvk opajag |hpkopqp vnj aialpt lzrkzfs nwucez nwuezc |mcx hzcjxq zbxr dsx tpknx fva |rlvgm xrejsvn ghawxb efyos xty wdzdgh olahbtn rga efyos vhtm nsr |cni mbab qtgeiow ulttn rckc kmiaju jvbq emyvpew cdlxldn ulttn brhkprx |eykpffp rapik qki fhjgdyu tome ehjuy bibjk htxd vexvag |wrk dpxt gwkuiov gbkif ike gbkif pcd wpj toywyf qzsa aol |yqwzh uujn ujun ujnu |srs ralwxrz yxvvmgp sjhbhk waasid cqtxoxf whcladv jkmaq khjbsh dlavcwh |mdvsjh xaj etvxlsy fxgiy rgjesel rlegesj ptriz ebdyhkp kugxm dxv egljser |lhehwrs mqevb ygmv gri izop qgb ivm |loqqam alojlwg hgen hbyw qlwpun loqqam worgnwk kope |phozre todsknr todsknr ibj mvllsar |wuripy ruwlfbh wukbkey qhq iishw tvtvci xawvxc vxacwx hsiwi ogq |xryq vxwupqa zhqex aquxpwv bnvxrba dtbxki |yvvwh zvsm vqskhp vqskhp ggqqlw bpn wbuv |kqz tdy goqwge ygn jgd |szjjhdk zkpoo nxexz ebicc |wzuemcj oyd qupulju iaakzmt vzkvz |nppahov umm wpzev wxkgfxd owgekp bhhb bbhh dgviiw kdfgxwx wryb |bnc rhes lmbuhhy kwbefga bnc rtxnvz bnc |ani mggxf mcoixh zdd nai hbhzl mes bdpqr |mjn uinoty jjegvze bjgqg yhqsxbt coj obylb hddude xqi rhfbhha alood |cbjzj drmihy tfkrhsd nuhav hihzx bvblqpl tdd szmp gjgfv box |uumhdxd cmwgyf vepr rwqdkj exwk |hwvr ydvw bqefu kghes gvbhp awms iqsqes khgse |mrey jqfw fwvzhps komj dayvs fbui zmtd cofn mrey |dsjds fdpx irjj usndok qcctsvf fgk wvg txwxcl dxs llp zyilwtq |xmkelgk fdukc cye legkxkm wwly |enlny eynln cccku brkz dpof mwfoxcd yftmnqh wpebvyc |ggdn jnysl dsacffw ukj hdae cmzxku |uqhm gcachmn kxndfrl htmfis jfnajz fiqiypr kekho kekho ndcw ckrndub dejfna |keazuq ertql rauwl keazuq obmh rauwl ksrotm |jppp poigqhv repfsje grjk xwkyuh pkx ayzcj hoxzv |yhjw pcuyad icie icie icie hwcsuy wcd yihjh jnrxs |gaug ivvx ceb xujonak hbtfkeb ttciml cctoz |dggyyi dggyyi gqlyumf yasu fwdfa cbb nncn verhq |rhgcw gpcyct kiuhbg kiuhbg gpcyct jlmleo nhumm |wulxxu jyjek hclcp ogob viex wiqcupq |tthu nxgzpid kcnj mss ukapgkp nnc bxjocv qwxs oejwsif aywqtu brahkb |dtde bgvb smu vbbg zhlu |lyo nwjjmep ldbok wgxhto wwuh qfgjknk wnsl |lleyr onha hkwulbm jfg |bybjwd uoxvbh mvj iqfpnxs bybjwd zqtszp wvc lbazjr zkzenja cev |rbuyyr divtslq yuqmyt ajyveb smxsjb nlk tzqhq ims fewg wpjhr gqh |kpewfd beq klilis klisli eeezut |euqh hueq ldoo crqurv lvrwh tmaewp oodl |bqi lzrf jyhvxfh bqi jyhvxfh nbztd lwpdn cuzi |srjylou phavzjd wost uxkaq byh sluryoj |ihrdk bcegkpq nygrs qbcq wyjg dvzme pgzhjl vibg kvv |ijsx iedemek ktlz gtga tbal lbki gtga |vmiaxn kefig kefig vngxz |vrdmfvi qts vlvhq vlvhq dihmq |cfz dyrz zlw qnt vok fwvahg skshbqf hbwozdc ntana jdb uflp |rimbj bxemw sfps krtk umta vnk ewmbx nrlje ymrtqrz mxewb kjxunbt |egnuti ozat eltl ngueti |qtcwoxq rmaf qtcwoxq qtcwoxq |zws gcoa pydruw qsrk lrkybdf ugr wkrxoj nyvf vitwn |tmr hhd dojid zwrj bhsim righ keqlep flzunou |lwoquvy acjowxk tqudk oenvioh nyavyl |rgh dfhgyke iff cpxhuz hui koe iff hui dmukrei |bjiumig lcbmbgh vleipx sfawua rnf |gftfh qwb tfdroe xbno qhgofm vqfoe mux |ljdrr gyfggai iun nju xrucbis mhrcrh fukr obvuqc whlalfe xrucbis nju |nxjmjr egqwg arllu xqaahri lzc ivt uhsti |sqiepba rcmts kvesv nvp |tiksw tiksw rjni gbhvzm ctbq zuqfyvz |ibsnm kfka aoqigwo sqouih rxz |jmymq lxio adtmk umyu sxvzquq bporqnb heol fow |mepa eckq rqviawv dkqoei ifmngpp jiava rtklseu |yuycd jiufjci yuycd uowg yuycd udq izkicbr csxobh |nwu tfsjavb rruoxbn oepcov elxf rruoxbn rruoxbn azglwth jcjm ksqiqpv |dthfwip zqnwa zqnwa zqnwa |gso wruece ufl crgnlxv vllsm dpyfm wpa ctxko |wvpze seodz lpq lpq pmtp wsxs ffppx |yfxquj phvjn rtwieq rtwieq kgxztyu vbjvkc prqqd lyzmdo ojbrt ojbrt qiqjz |esaezr rpggiy jey kbzrhu uthus osr xxaiijd qfxlf auhzbx gkigoqw |yfhcj uvgck cds gjhhrg cmempgj yfhcj cjb |yxi voxvtuw unwg jqqm |igvjr ljz rus sru gbjtjt qfeg ztu zjl |leof ocxns hbkoysh hbkoysh leof |hab lyxmf yhh qeks fwhfxki xmbcak okqjii nfgzyg bhtfgdj lpmjn |mgognh tad herere lvwnzx ixwqs zphmuuc etdjz kczsf |mtej rlolsnn zbl uykek dpkan gmz etxtgj |mihuieo emjgbp jgks mihuieo iexrfw mjdnr bvp mcuzea xkbusvi |jvqpj bwt jvqpj bwt gxr |qpnd fpt tpor bibbpcg hmvguez wqc afl ckviua gpi |dntmcg jglm sxtnu sxtnu sxtnu |fzkbptw cbfwo ozvwov wbv gcdd izqo ovwzov lolewo xikqpw |nkxyxzd kpn datf fki werq mwidqx oiibor zizcjph |xvgyxym zor ijoy lvwsf fjuara idvvq rreit mqyyy ctio tzwqqhj rnpee |maqkfpk maqkfpk xukg sfdmnlg xjopvr xjopvr irf |liujcd vnlkouy dxkwc gto vhjvtw |swhqhj cas aupsd swhqhj cas bvbooii jquck dtdm |igh iqicicf ghi pcxt srcrjx gmf gyscphv |drplj drplj wopgpnk wytag wopgpnk |zexe ilcqoh qiefb txkuv lirfzv |ovvpn ovvpn uqeurqx uwzn hgmucj ovvpn sjxulms |rox silka irhsvym kutus otasof tdneav pcagds |mkja omu tyshbfq onp trxs lxa tftbv bnpl djhnc zdqfs muo |tjj rmmqas cbbkxs qio pikk ykyew gxlxt nhsyl ykyew |frcprg njrz oaxcmhc qben pedm ecvtga nzxwpb ior gaklot dpem |zyt kncau spoe qlchg sqys wkpbng yflju qlchg vkve bzadbpa |qtq pkaicl qtq mfkfqvr dnleiq brrjxsx uoyxh pkaicl yvmlug |firwy imtlp ywl qfa dqrbazz ztzb pcsbwhn zesmlag |ivey ivey mtvc mtvc |lhize acwf moa cdeoazd voktshy qmvqq jvmuvk ljfmq tsanygc |xreiqkc aawrovl pofcsg xreiqkc xreiqkc |cjbzvn ozds iniqu sdoz gqmki bablvll krs vjzcbn |izsod htkeqz entxn qtns prpcwu omfnmoy |kwfb tctzda aztctd tadtcz gyt wunbcub ydiwdin xxk |epnl ijcp giq ltfk zjcabve zfksmz epnl giq xxxbsom |ulyukpa mdjsbn dydko uhkdt qms aaaj hustlwu |zlsbu ohx jcwovf egf zlvpqgx qhejm wrywdmw |uhxqrzr mmu kjxcalj unuohiq rri yzngnb ikvlxry mfiym qbksdx |khqciz som yklmm jceb khqciz jspy jceb |ncwggv njvi nqox krtsn lnm |bgtqme xaxcoq qbtgme obqual vorfk baoqul lgrb |jli tsbb nlxjc pkwzmz dlxrj hmho gzguko ilj iyaasm |wlmw grkumg dynwtyo emxhhqr huluk slpqu uhqcmd absmr ufirmwr |pbs pcammxv dplfr tzvmav nccyy blvyq ffhnz bccutq |hgge ghge vxmvz hqxgjdg zab guo gheg |ylj bucoyoq udndc wpgyrbx ueh udndc gxdsdh hdoz wwgqlg |cjdeh gttyqe kdkm ltzd lfeozse quvjq mnwhokm kdv oojxm nxt |mfkzus knqxt saxkqww njx zumsfk sbmcyad cpt agvbuv |tukn vyco yobvsn bzgnn klrnzy kea thzk pxpwq ryfff nxzm |ylbm lxlz lybm lzxl |wgtxoij zad slgsi cvnxfg iomswwl vmx |hkm yinhnkj kmh kwkw kayknck chur styjif yknakck |rtfwhkq rtfwhkq zsf zsf |sldq zlntr ueegiw kajivqc ozcbm ceft snvugom pdyc elppeed nnqrp prwwf |lhk xjonc muc tudag tsafx mmivb dvrjbp qgrew |hnzer fbgqp aazta aazta lxaz lmgv aazta |victgxu victgxu mlpd ummrnbx cazjgnw isxcyp efy zfa cyusj |gyojxo onzq gyojxo uxufp awi ilhl wefwfxr gcjlt tmliynw uxufp pdcnxah |wjwachn xkuhfbp oky oky ybaeqkr rbuix yreoaw wepmye brvon aasb |kiidorw vxtxiqx wtqvbrv efdth isel qbom vcssyc vxtxiqx wtqvbrv riafzsw mqzsj |eurpjd vkhdamt tmfx czeoot hiz ykz lmixzq tfur jhzr |ipuftpj qbll sqkkdw fwncmiv bri oeeh lehd ioh wag |suima nanngc imrmc krq atxdo woy atxdo akev qlr aezco qlr |cfc efwbzck ozkmcxv moczkvx ccf |bnekky iakrk sask uwgnjp iyi rynev bdnas ldh kass |sicmw vvjbvv cap nsumc xgvrlm wsoo uoqdu psykckm |ugg mtr wnzhmmh tjxc ehwnji lwhu mdsckk yvmk enubrqo |grb oxmxz ohu ytetedv ssx apzlppg fdkamm sxofc jdt ynmu wyejok |umoep rbyqm eqfk twqnog cptbbi dragna ngqs ffb cexxnc rbyqm |utizi ormkel wvwur bdx ecelqbv xiccama aag glfvmj |znb rsuqoa uxo svc |obs lbifa cffi catpd |qkxwian ajlzjz wewduzp bbyv qmt fsr qgiu epinp ghmf |hatg bfgmb aght ghat |kuq inp dun cknbun wmwsu drlmmg kyxc bdl |bddybth swdbf jhi fva qpobio bjwm wjaztp jywi |mgckz vhveu zkemhp zdf xtiqqew mlx wazgd |umbjq pya lvvxf jeavij rhrxvew bwjqgpr piz |xaycpwo vjcuc qksc yuixhni sfbfb dydyaq gdfvb tggg xidphvf bpjdrl goskxym |agxfoip gguif wvo agxfoip ntkbaw fbyggy ooft zxih |nzvsu ffwq uxvfbl qrql olhmhom qhdltg ymwz krtndtx olhmhom nfsv krtndtx |qdp jqk ustz xjripzv mnk grnodk pjwdsj uug zqxjqj |mufrcox zunisfs ocvcge acamm xua vor bsde kxr vor kxr orccxx |ncycbp anvcxay bmm wndmeaw oso knmk mmb wamenwd kmkv ppdd |motdcn xzagzwu vuzt utffrn yuqxzrh uvzt ujttq |tauoqy coiy ybesz tauoqy wpmr trquyne ahxbj jzhems dsdy |aczq ypw pgmzz srfn quatjgf |cih ypapk bfxvr euvhkk gugru auhqui |vyf pssgfvy dnhvbfl xpacme dnhvbfl mzdv iynq hcqu |lbzvbu hhxiq hdfyiiz iyzihfd xhqih uzdqyxr |iapbdll vdr cprmrkk vdr dfjqse mlry flpqk vdr |grrfkq xcpxd grrfkq dxc bjpr prvwh swoc swoc |bopo chvwuhf qhd ieesl xey ieesl fnjcbe |kic fyq hsucnu agwyl pzzmd hqksh psw |mxf uau iti lcoz lpg zbu ocre wqlocmh mxf nidqj lcoz |bypmix ptzxgmf xmtzgpf hrvzzq |lbfw zwusma lbfw tuyyy |lrf uej unswvh obgsb npbl zajr kenea uej qnyjcu wzufim qpzkgya |qcrxj llyu kligt hlm ehwtbx dda lgsvhdt xewfcv uikn |nfzjx izqdbq mfbxs imiuc yqxb xlmvix izqdbq eflqfq wku omgtuu izqdbq |lasdwg hiy btzt eefd eyoep icn nnmhg otml rek luixac nyzgn |vekteds utsuxdx utsuxdx vekteds |feyov qrij zbebwg ijrq seplram wttkwm zewbgb kzuhuh |dmkgtv wohgqo ddtqmv zatahx mym hqowog tkmvdg |vhha wjrmuyx kqh vyyrj xzchbi ejsdq orlxg vyyrj dlrc |yetngqn zdtuqox hkarjei fqpsgh eaqwbg zsssog ghb gddqqzr hbg |obldb zsrhz zxp uxphnev mwnbc pfjft fms xwslk vjm fxy |nfij dbfykv ttq gyjgac igxuyqi gtiioqx ilhdex dbfykv uyp bdiwya gqf |pffzruz vogfosh dcs wje |pohhf fhpoh oon yyz |xxuam afwm qxl lnt syyr bwxhhf sozauq shlhfmz kwnn milav ochq |wefcqrt gejw cwerqtf fttf gjew |jfsvnmr osca epwtle pgfif sxom |exlfzmq nakp rgdnx rrcvth vhrrct aajjdrt ryyg dsozd jdqlqj pakn iruv |rmcvo txszcs xxhyxz hbsozk wshkocf rmcvo rcbnt |kitz yjgney yvkymef nauj hmllsgl kyhm kqr pzsu rcf pzsu qpte |cdinpx bfur mkj naz ihkheyr nohhoe |ylris xeqcgup wap bbfih tgfoj |ina gnlnm zyeqhij cudfuf ipufae bvkdzni aat teqsg cudfuf bjokrbl teqsg |aedx edax dnfwq qndwf |rdngdy jde wvgkhto bdvngf mdup eskuvg ezli opibo mppoc mdup zrasc |qcnc iaw grjfsxe gnf gnf |zbjm snznt zelswrk gkhlnx dqxqn qqxnd dmro |zisecvx ztezof uzbq otnrtj qsjzkwm ewvcp rlir bfghlq tgapdr qxmr |ipnqj opjf vabyoe wkwnd |wyf mfqxnrf apm snarf jqu aaghx pwecbv lvghayg |acncv jmmbwlg oiphlm ifuo cvt |pvmb egansnd zmh gcuzzci rrxpslv ubith |uoleptg xbouzn xbmg cfh cpn wpqi xbouzn xtxis sxzpns |rilybri kurbpq vfmjpck tjyogho hfyxad svfofx lfbbhxj khaerfs iqr |seaebgz wlmtkre qguv qguv wlmtkre |sgo edkxya zdqgwtt gxu nibuu rairqoq mzxli dci qsv |tsol mdhzqr rmaqnru ggvcq arbwkn hlkcnj ljkcuof |mmliphp ocup puoc eijjv |gmajqpb ijki ijki kvz |pmqss unhlpcj dlkll nuhlcjp expe tlurzmv nsy vlumtzr tgseozl |gkvaoni hsba hsba viuedv phyoclp fdq phyoclp febld nqfs |rxvdtw abn pntv qrqfzz slsvv abn lrxix mnu npot |ghlfjp woy xwkbmv bkahpkj jve cncvk jvdype fwgvoju yrkwjp gwfvln mvkv |kmluh mie bby fwer chsinb ojglqr nqk mie |yzmiu igkgca ybnsqja jpfejtp yjddy xsosxfi ingx qwuhb emrkwpx idqjmmm |btrllw mphm dkvo ewdl dchcul yah btrllw kmqi mtvgk wtb |hxsgard yuikc lykt tdee adprp gpougod klnzk mzsmlb |hdn znblw ifoblur bwzln dbv |smofpbs vjuyiro llk lfzesga tybu tybu |gffnpug xaup iqiyz fjkpnkz drrk fwyxw lwzfskz gslwpmv vjxylva tbkyo nib |evydmb nhwuiiu fkerq nkgbuyy uclrs ydjgglh xhotwbm riirgzt |bsub eavbt uvd dpzwyt rhn khrbptt xszckc djnfxju axofhat powmso nvdffrv |xtuykl fjz mbikc xpnx hmey fjz fjz |rkls nwdcsyx rkls rkls |tygml untequ ybdfumz nqffbq uipc sove hfnqj |ytecew vven koqn royynd qsn ksl qsn sdw |hknlw qwho whoq oqwh |lzmmtqu qvhyeo cnofuj utpwkjz gnirz yhhu aodbnd |zsr axw kwtzcv tydzo kwtzcv lkxsm |rbjtqe nihifd gvdxd bpxzy rxteky vgcgllv vbbua anygiup rqo |dpd wblfwp wblfwp wblfwp ygahc tqjbaq |gsw gsw pacgj xmrcz zmxhmch xmrcz |pdq rhe xqmq lgpkhg fyffrot ovnqh wle |tbjavke ypzzrj jizx gdxoh icjsat otfh fmygumv |snch nxlgjgp jeyn sxoqfj jtage jtage iuice |rtb coefuj grwg grwg rtb krhqnma vfhgbr |vhegtl btorwxg szcev kbvkx itsk nlzpbed |hiukrf ilzkm yllhh xsgwkdp zyy kjbv |rfcg tdorci zcj wzftlv rfcg rfcg |lgbc lzizat vsno pau nvv vsno bbr lzizat qhtb gwp |sfwnio tcugjk bsfsz ykyfwg ibkap fsrvy mygk kzunawx zyhyh |mpavlh qps bylh lttjkz rqabgk vewb bwev tlzkjt gzrbxga ktmso prpkj |gpf ims ynh ffrs vpa iemp gofh cgbauje |secys qks mcnfhwh drog kqs pajy zoltkw lfihnb myb ioxptu |ytq nrta ouk ajqblf yuwwcd zdy blyoxbw dakk nvgi bzrhzaa |nkoych sufiia xkdvw crtldee zycl qblab egqhr qblab |nllno muxaf vds qjnitmw zkpj wskyhft kmqct xamuzpw qcai cdjtbt kaxv |qzdytpe osr fuw osr qzdytpe whperd rydwdcl knoa |zkdznhd peh duoygr zamrgl irnvj otpe pltpq jdkecg |byzgw rece iigdug ehif tpgje |ccnn foqdran gbctca tefdjxh ntcr rjciii xip xlss crl wvvhzqm twyohf |dqyii milqqc qjgkojp qjgkojp ryde |tdkyj tbrcud tsba vqtmb cjwxnf |hqhmq wemvrce nagig pwnw nagig epg nagig vlsi |tqgvw luoplw hccti npjm rytdruq cylrsun rytdruq vjsbjl rytdruq ppti |itgt tuwc itgt rvp itgt tigns eipl ksmru |pdw wdhtkn nbdbpn wff zhuuipg rvemv qxr |qgkwdq cjilayh ymeks mrpuzai dwgs stfstgz ucvqhb yout oiq |vpxik ypfr qytimvu qms oxbmw ppyfx |fwwidn gdhd pyuexk snsz iwndfw |lfcb sllxjna lfcb hpzahfg mmvgaa svny jhuzd |unyg gicmzd fwc spkciy toyq wjupckd vzzx iuqgka ytqycb pxsufj |goj tnrcml eyizngj txa xrkiw zvu igduz |wek xrrlkna clyof rrlnxak |cjm rmyuku vjom gtf |buk cfae awstd dywgqp hxo wcxvf laihqw xdqfes wdbh qceh uzlwj |sudguo dxwplto rlebdh bkamu dxwplto |crwkyxm yuz kjtdhom crwkyxm |trhc sduorxr aizfryh rsudxor gbyc |pczkyl bptp qnn nxmpwsx udrg hhlb rubtrmx twzodlp xygnht |jmqct cden yfajtkz fevcw sxonbxz sxonbxz qkzkm hhngr fbv |sdsnm mwvicr wypfi cty ndbowr woiz mrauwzd qlno mwvicr |vteyo fng lvr lxytn txpj milg |wjx ahtmgo cgwcaj kaxae fhlvlqf |ezj eetqhzu upwda iiefwlk vyvby |imalvy yeghqe jwcu mvrod cwju |bxnmsa yhfu npsdar tsbri hfuy sirbt oofxmy |fkndt elbjtn vepqtxt elvpf fpelv bzkgag qttexpv prblwb |rmq iqs yvprnyy iezqrzm wlqsrr |yviovq lekxghj oey qwhzj lxknxw qiyovv ksnt jptz |tyrg cifxt hugqf tyrg ffuiv jmax qyw fozfosq ffuiv |nmg rsl jpzazd qbtlf yxqtsj czwmdfd bamge lbjdof uqy jssc |cbx boozjip pwgvzlq rjz kxy kxy hszacok fvsq jhnir cnsba gafz |sbcuxb wfur nnnfqjj fdwg huhe sbcuxb |icwk qelbxs uevp qped zsnhh wpuok wddxsln ftnzupr ruxol cgxjb jbhh |izcp htykj xxmndoq amnspe htykj |vverol oixwlny vqd tvfzu henc gnyrwr |ytxio etytsx choynep zqapo hfjit |lkvgr oyzfa taiqr jok djatvy ckif tmdw oyzfa zroy |jlgpyp kkqysg oqjki hjohoug hbhta muilz zft |sumfyu wftcu bwwdcy lezimwa qwvxv zwh mqyv bmfot aii torcol rnt |tpdj xrw ccsbnh fhptv fwkxjfm dmqaokd bjci |zxi vmf vmf dpyg |sfzxysw lcms bkojtv bkojtv |opywo qll ipkitr mtwp tudrr svhyp huz bxsdpn xomfy |gkod luo qrosbp orbd rpsjzyd rlh gdok tze |nusiuq nusiuq zeys ahufexc |veno jntg avtmtdn qojxru zegdcql odfcetz pgehau |uqun vigjm ykac ozlelj danmji bibugox |rpuozh ajwru rbvuevv uhzsq |iawoe tyb aewio ymf byt inijv ctu fcys micsgzl pbby alt |gktyxp ris mqpfm bkqsfl nrg idbbcxg jhcf |qibt invvv qibt luitx rnm eby hrfbmwl wnap sgkzvb qlwc hrfbmwl |jwkv qecsjbw lycgldd wjvk tjcp dycldgl pzrvr zrlcf kji |nzsrmiq nmhse ilivrk kqv |besmyzi imkgpt iekbjax abxeijk uvzs wwv |jdocl uki ltswp tjkljc ymce iuepze qygqxzs tei lkry |hhyfy gvzd mqksxlq czn afe mesnag eep frwgekg mqksxlq phpy |ehg connnza ekt ddgokw |mpbsoms uzhzl xevww ztt uzhzl |lftybr firc awsud dsxdkk ltf ipjv dtx lcymth |vkcpb gxtxq yioeq fexj xxgqt |srvca fslnnvf nfmkpvt egw wemumq jie vznf dzsjw cukf kcvyir |yxjkl lyjkx jyxlk kgc xtz |tpoe xzov csp leleoqo noyre tdhf cyib sjgtdx raehdw nmcxp |qvt uhznqe bpvos vtq ddlebtd tqv |xlw utsxs gpia rvlvnts elkxr dddihy tnrslvv ibf wlx bxg |cwqnnrt rkkqyf dye yde fzl pthanj |boc rqjenpp xjqte jteqx pvoofc pidqe ruoucy gvnro ognrv |qhalb gnazwc fhl iuti |clnbjfo nnfs nnfs heymvr oarew oarew nxu |lwtrotg hiaxwj ymzbly nvhzjhj zlsaheg nvhzjhj ymzbly |rrvi tsjp tsjp tsjp killji |rpx hiclj cmwq ibhj nfd |pvwymn iebkd xmpw vuhhkap ksw zigzy mzzyyxy rmuh iwwhea cglfq |rlwelgy sffml jin qsdzro xlsty mgqzuu etxjuo emzd jgnoyq tkjuy vfvb |tkctdj hhkuc viskmy obw |zvjkuj akeky ikj jqd hfhzbwe bkc |btev nrdo hcyiuph stf qharfg vpmel mpfz nvs ytgbbc |ieepn ndueuw svmdr tcvumw mceyrn mrjwhyl tbdj mgrgvz |uxrs ckyi xpmqm czzrkl cjp |nlliwd wrqkrkz yjmng nlliwd zirde hcjjn wco ysf mgl |dxti lcahe ommare izlwf ramsfb nzgfvo ijvm fwymrdu bndq |isxy jpvuzu tdduyhw dixp cfa fkzbteg ytoi kepk ysf yqcpi |qmeprfj soqo ncgeor cqsuuj grzy wogxy vyblnbg slvtry vdols kka |ltykfp gtzl olrp gxend vapee deq |emywfbn dbfiut rkt wvwe dbfiut bwffhea yuzcxv gogpicp wvwe |vqvmrp ofbk dlfabd jwllzxk obx vqpwjj umvng tqwis fstxy fstxy |miha zgvyux rmraszo xwf |kjaagk btm kjaagk wkewjrg kjaagk |lbmli aizs omrdr gzktnx asiz ptanzpa xlo ljre ckyb wob |svz dlk rijagg avxmg fkzwhk uro gegm |dzplum temdw jqnm tvxcww bmg tftttpp deuw comxey xfimzjx caluczi nqn |uwvhxa ztkd nlsdyt vihl julkwwv uzch dwakhs |wkhuihh ycrc cxff vzcfhpp uegfd gaok kcnvz lhzogq lwa tyrypvu |idp zmrrzp zmrrzp nktp xsnx rjsxn |eybrnib ivgntl vaxsbpi eybrnib |nzvnq xvbfa pbhwwh ylju runvsj imlx vztesn |nfdohd nfdohd gtevnky pivjyct ihvd fzcsrq lko fmqk |kwpkks ecikxu bcxswlt qvrxm sbcqmh |kdjrmj piuh kdjrmj vnaf gyedkg vptxgm xezssxx zsg qjzpo zsg |oqo sley aqx qmpqb fgmylbj egd zivj kepxizv kuakyn lunbnd |hmcf hmcf xlhgc hmcf cdlm buofnx |onjcj yluonz kzmk phqo phqo phqo |ohaafy efl bnkkjww wwjnyoj dxeaig ywnjjwo slk hrbebw ohlyju elf |msohiqz aunk njki bfktdgi htmyrj mgx |numlzrl rmnlulz glb ltt fhbajz gqxpu |gko hco oai ryq xwy sdqosft spjkiu cxfhg ycwpglh noy rah |btzpjem brpk vqr atxu rhlh rqv jmg fvyus |phmxxgj ejx xje qtk hsb kqt npwj gqt |hujyjp nwmsd ant zipuya lrkahww uwqal vzlo qmbo twkjkse ufivi |zfbnyz fwvh xrnrw usn zin daq iwjzj |yykyg iwypfy hehqnl cjvk cevdrec |gui muuto wsta glqmx gfo rdmbv mxwz gffzt eejpw gion |lpng nduid iqbpu nduid knrqd |xwxn oefpckv gjaua ugaaj gjuaa |qxk aeql trqdmqc crzlinj crzlinj trqdmqc rijcne ewyf |rfv qmbe fvr bmeq |upqyfw lowzq wpen upqyfw gfskbil sljuzh wpen |bdcara qyhx rtaez qyq gbyr |evzls qxtxq clzd svbgqi zxlzgss vtrre fko eebo qjyl |zaapeo kpwhz tygknau nyd pch trp xqe |ypzcafg rnqmbh qtteg sncu ssojhhm zonfym thir xmgheb wqj gpjg ssojhhm |wvcwyn xrf muozyya lasdp xpjgu kpqv zkiihiv ifje cbdlavg xbied hfnaa |qqqb rettz rycukl ihpkhh |dnxzxqv znb znb fbxj azxtezb xvxa |peqkd xlzqkov esgnw ucku hrwpfxd xtd vnig vlmfp ajte qswr kqoj |dpwy oavzkk dwyp ehij upqxgii pydw |amfc hfv xmqa nqvn cal rqmcq oej amqx cla ntxj |hqhhe qkbhwli wmhlcq xaczs peywuo |vcr xfv xfv kymo qpszwzo xfv |nmrbur tswo xbo ljlrzo bmhpgc pev zovkznz lok wbbhtkk |tojj lxqgr rhjavrm ndsdup gdbjwaq cqpnl wfaxivl rfry ryfr udspnd |beffod sknlph amb feobdf |mldgn jxovw yuawcvz kzgzwht rxqhzev fsdnvu vluuo eycoh cugf qjugo |tlnd qcxj ker fdir cgkpo nrqhyq raef uqadf iahy rxx |mhvisju lhmdbs tcxied xeidtc ujry cditex gvqpqm |cgc jazrp crgnna uvuokl uvuokl uoiwl sknmc sknmc |rvbu czwpdit vmlihg spz lfaxxev zslfuto oog dvoksub""".stripMargin }
parwen68/advent-of-code-2017
jvm/src/main/scala/se/parwen/adoc/AdocJVM.scala
<filename>jvm/src/main/scala/se/parwen/adoc/AdocJVM.scala package se.parwen.adoc import se.parwen.adoc.day10.Solver10 import se.parwen.adoc.day11.Solver11 import se.parwen.adoc.day12.Solver12 import se.parwen.adoc.day13.Solver13 import se.parwen.adoc.day14.Solver14 import se.parwen.adoc.day15.Solver15 import se.parwen.adoc.day16.Solver16 import se.parwen.adoc.day17.Solver17 import se.parwen.adoc.day18.Solver18 import se.parwen.adoc.day19.Solver19 import se.parwen.adoc.day20.Solver20 import se.parwen.adoc.day3.Solver3 import se.parwen.adoc.day4.Solver4 import se.parwen.adoc.day5.Solver5 import se.parwen.adoc.day6.Solver6 import se.parwen.adoc.day7.Solver7 import se.parwen.adoc.day8.Solver8 import se.parwen.adoc.day9.Solver9 object AdocJVM extends Solver3 with Solver4 with Solver5 with Solver6 with Solver7 with Solver8 with Solver9 with Solver10 with Solver11 with Solver12 with Solver13 with Solver14 with Solver15 with Solver16 with Solver17 with Solver18 with Solver19 with Solver20 { def main(args: Array[String]): Unit = { solve3() solve4() solve5() solve6() solve7() solve8() solve9() solve10() solve11() solve12() solve13() solve14() solve15() solve16() solve17() solve18() solve19() solve20() } }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day11/SolverSpec.scala
package se.parwen.adoc.day11 import org.scalatest.{FlatSpec, Matchers} class SolverSpec extends FlatSpec with Matchers { "The solver step 1" should "return 3 for ne,ne,ne" in { import Solver._ val r = solveStep1("ne,ne,ne") r should be (3) } "The solver step 1" should "return 0 for ne,ne,sw,sw" in { import Solver._ val r = solveStep1("ne,ne,sw,sw") r should be (0) } "The solver step 1" should "return 2 for ne,ne,s,s" in { import Solver._ val r = solveStep1("ne,ne,s,s") r should be (2) } "The solver step 1" should "return 3 for se,sw,se,sw,sw" in { import Solver._ val r = solveStep1("se,sw,se,sw,sw") r should be (3) } }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day4/SolverSpec.scala
<filename>shared/src/test/scala/se/parwen/adoc/day4/SolverSpec.scala package se.parwen.adoc.day4 import org.scalatest._ class SolverSpec extends FlatSpec with Matchers { import Solver._ "The solver step 1" should "return valid for aa bb cc dd ee" in { solveStep1("aa bb cc dd ee") should be(1) } "The solver step 1" should "return invalid for aa bb cc dd aa" in { solveStep1("aa bb cc dd aa") should be(0) } "The solver step 1" should "return valid for aa bb cc dd aaa" in { solveStep1("aa bb cc dd aaa") should be(1) } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day15/Input.scala
package se.parwen.adoc.day15 object Input { val input = Map('A' -> 722, 'B' -> 354) }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day13/Solver.scala
package se.parwen.adoc.day13 import scala.annotation.tailrec object Solver { case class Layer(pos: Int, depth: Int) { val stream: List[Int] = (0 until depth-1).toList ++ (depth-1 until 0 by -1).toList def getForPicoSec(pico: Int): Int = { stream(pico % stream.length) } } object Layer { def parse(s: String): Layer = { val r = s.split(':') Layer(r(0).trim.toInt, r(1).trim.toInt) } } def parse(input: String): List[Layer] = { input.split('\n').map(Layer.parse).toList } case class Pico(layers: List[Layer]) { def getForPicoSec(pico: Int): Map[Int, (Int, Int)] = { layers.map(layer => (layer.pos, (layer.depth, layer.getForPicoSec(pico)))).toMap } def getMaxLayer: Int = layers.map(_.pos).max } def solveStep1(input: String): Int = { val picos = Pico(parse(input)) @tailrec def loop(pico: Int, pos: Int, acc: Int): Int = { if (pos > picos.getMaxLayer) acc else { val state = picos.getForPicoSec(pico) val a = state.get(pos).exists(_._2 == 0) loop(pico+1, pos+1, acc + (if (a) state.get(pos).map(_._1 * pos).getOrElse(0) else 0)) } } loop(0, 0, 0) } def solveStep2(input: String): Int = { val picos = Pico(parse(input)) @tailrec def outerLoop(delay: Int): Int = { @tailrec def loop(pico: Int, pos: Int): Boolean = { if (pos > picos.getMaxLayer) true else { val state = picos.getForPicoSec(pico + delay) if (state.get(pos).exists(_._2 == 0)) false else loop(pico + 1, pos + 1) } } if(loop(0,0)) delay else outerLoop(delay + 1) } outerLoop(0) } } trait Solver13 { def solve13(): Unit = { println("Day 13:") val result1 = Solver.solveStep1(Input.input) println(s"step 1 result is $result1") println(s"step 2 might take some time...") val result2 = Solver.solveStep2(Input.input) println(s"step 2 result is $result2") } } object Main extends Solver13 { def main(args: Array[String]): Unit = { solve13() } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day20/Input.scala
<reponame>parwen68/advent-of-code-2017 package se.parwen.adoc.day20 object Input { val input1 = """p=<1199,-2918,1457>, v=<-13,115,-8>, a=<-7,8,-10> |p=<2551,2418,-1471>, v=<-106,-108,39>, a=<-6,-5,6> |p=<-73,1626,1321>, v=<58,-118,-8>, a=<-6,2,-9> |p=<-3297,-894,-551>, v=<183,31,-61>, a=<3,3,11> |p=<-1425,4298,617>, v=<32,-166,-32>, a=<7,-12,-1> |p=<-3718,877,1043>, v=<114,7,-20>, a=<10,-6,-4> |p=<-2089,-239,1142>, v=<52,12,3>, a=<7,0,-7> |p=<782,994,3311>, v=<16,-28,-32>, a=<-6,-3,-16> |p=<-937,2596,-109>, v=<-12,-117,-13>, a=<7,-3,2> |p=<-865,-2930,-1387>, v=<60,76,-56>, a=<-1,9,14> |p=<1196,-3308,2564>, v=<-26,59,0>, a=<-4,13,-15> |p=<-271,1957,-2944>, v=<8,-15,40>, a=<1,-10,13> |p=<-964,1228,1583>, v=<18,16,-12>, a=<4,-9,-8> |p=<-1639,1174,1970>, v=<84,-114,-138>, a=<1,5,3> |p=<-1840,1679,-1764>, v=<44,-20,91>, a=<8,-10,2> |p=<1104,-233,140>, v=<-21,-11,-28>, a=<-6,3,2> |p=<1136,-361,-3100>, v=<-40,14,98>, a=<-4,1,11> |p=<1480,-265,-1412>, v=<-36,42,18>, a=<-7,-3,8> |p=<144,-1217,-660>, v=<39,25,56>, a=<-6,6,-2> |p=<360,295,276>, v=<-51,-95,-11>, a=<3,9,-1> |p=<-2656,487,1228>, v=<78,12,-11>, a=<10,-5,-8> |p=<-1400,2295,-204>, v=<-9,-67,53>, a=<11,-9,-5> |p=<-1016,-769,-52>, v=<1,14,120>, a=<7,4,-14> |p=<1536,4167,-940>, v=<-99,-201,82>, a=<0,-7,-3> |p=<2398,3917,2412>, v=<-69,-51,-81>, a=<-3,-10,-2> |p=<-3283,536,733>, v=<46,72,-32>, a=<8,-8,0> |p=<-247,1180,-2901>, v=<46,-52,-18>, a=<-3,0,12> |p=<-2984,-499,-1475>, v=<-3,57,-8>, a=<11,-3,6> |p=<-431,2008,-3890>, v=<54,-40,49>, a=<-3,-4,10> |p=<2904,-775,-3614>, v=<5,-3,97>, a=<-11,3,5> |p=<2697,-1074,3401>, v=<38,70,-28>, a=<-13,-2,-10> |p=<-1259,1456,595>, v=<42,8,34>, a=<1,-6,-5> |p=<-1293,5020,-2110>, v=<-12,-199,93>, a=<7,-5,1> |p=<-1753,-1520,-320>, v=<-10,44,14>, a=<9,3,0> |p=<-2143,1040,-2220>, v=<83,-42,109>, a=<2,-1,0> |p=<-203,3210,-530>, v=<-56,-98,35>, a=<6,-6,-1> |p=<3017,-3820,290>, v=<-154,96,-6>, a=<0,9,-1> |p=<-1195,-180,-289>, v=<93,-30,-2>, a=<1,6,4> |p=<371,1368,953>, v=<-18,-16,-125>, a=<-2,-16,7> |p=<-1777,-426,-523>, v=<187,-16,24>, a=<-6,7,3> |p=<-2635,690,-1177>, v=<148,-83,59>, a=<11,3,6> |p=<431,-366,-1333>, v=<-62,18,124>, a=<4,1,-2> |p=<-2311,-750,143>, v=<147,11,-51>, a=<7,7,6> |p=<-151,354,-85>, v=<97,-29,-84>, a=<-13,-1,14> |p=<-325,-1602,779>, v=<-25,56,-13>, a=<8,11,-8> |p=<-385,-204,467>, v=<-7,37,0>, a=<6,-4,-6> |p=<665,-1272,-1195>, v=<-10,35,80>, a=<-7,10,3> |p=<-2525,7592,-6216>, v=<43,-14,0>, a=<1,-9,8> |p=<-68,4433,8721>, v=<-120,-113,-63>, a=<6,0,-8> |p=<-6971,-91,-561>, v=<-43,3,15>, a=<11,0,0> |p=<-2876,806,-8478>, v=<72,-60,58>, a=<0,2,8> |p=<-7907,4004,258>, v=<61,-42,-46>, a=<7,-3,2> |p=<-4358,6773,5523>, v=<50,-73,39>, a=<3,-5,-9> |p=<1941,1823,224>, v=<-102,-73,-54>, a=<1,-1,4> |p=<-1440,-1768,224>, v=<70,87,67>, a=<0,0,-7> |p=<-1776,3125,2870>, v=<20,-58,-4>, a=<6,-8,-12> |p=<1437,-697,-5635>, v=<-12,25,115>, a=<-5,1,14> |p=<-3603,-151,2366>, v=<30,-89,31>, a=<13,9,-13> |p=<-264,4805,3857>, v=<3,-105,-40>, a=<1,-11,-13> |p=<-831,-823,140>, v=<52,-35,5>, a=<-1,7,-1> |p=<2970,-634,1085>, v=<-52,110,-18>, a=<-8,-7,-3> |p=<1755,-4503,-1198>, v=<-18,102,8>, a=<-4,6,3> |p=<-4945,572,1727>, v=<42,-101,-5>, a=<12,6,-5> |p=<-70,5047,-2023>, v=<3,45,54>, a=<0,-19,2> |p=<-2845,4372,-2598>, v=<75,-110,116>, a=<3,-5,-1> |p=<-345,-228,-1898>, v=<-38,61,88>, a=<4,-4,-1> |p=<-2720,3622,1727>, v=<109,-2,-83>, a=<0,-11,1> |p=<-4045,-3228,-2448>, v=<-7,116,-7>, a=<13,1,8> |p=<580,3347,802>, v=<-10,48,19>, a=<-1,-14,-4> |p=<-1910,2875,1236>, v=<71,-54,88>, a=<-1,-1,-6> |p=<-2963,-6485,2406>, v=<-102,86,-42>, a=<9,4,-1> |p=<-18875,7633,-7890>, v=<86,-76,82>, a=<20,-6,6> |p=<391,9505,4980>, v=<-8,76,-108>, a=<0,-16,-1> |p=<-935,5800,-1533>, v=<-114,-129,59>, a=<7,-1,-1> |p=<-272,-7733,12858>, v=<69,18,10>, a=<-3,9,-17> |p=<-7292,613,12741>, v=<49,-116,-47>, a=<7,5,-14> |p=<3550,-518,-15339>, v=<51,33,73>, a=<-7,-1,16> |p=<4213,-8123,-2157>, v=<14,88,55>, a=<-6,6,0> |p=<-7721,418,-17250>, v=<80,69,2>, a=<6,-4,22> |p=<1738,-2831,-158>, v=<40,35,8>, a=<-12,10,0> |p=<2598,399,782>, v=<-66,10,45>, a=<-6,-3,-8> |p=<3068,129,-1558>, v=<-58,13,57>, a=<-9,-2,2> |p=<-1782,4139,-3628>, v=<-99,-93,171>, a=<18,-11,1> |p=<-1082,-3161,-498>, v=<55,83,67>, a=<0,7,-4> |p=<-5302,-1291,772>, v=<98,42,-70>, a=<16,2,3> |p=<808,979,232>, v=<-50,2,-1>, a=<1,-5,-1> |p=<-152,1479,-8>, v=<-86,61,11>, a=<9,-13,-1> |p=<1292,1700,-858>, v=<-72,-94,96>, a=<-4,-5,-4> |p=<304,-640,-455>, v=<53,-12,72>, a=<-11,9,-5> |p=<486,1063,-689>, v=<-52,-66,27>, a=<2,-2,4> |p=<993,-1823,182>, v=<-84,30,-47>, a=<1,16,5> |p=<-1230,-1615,-312>, v=<52,182,96>, a=<6,-8,-10> |p=<-268,1297,728>, v=<20,-105,-40>, a=<0,1,-2> |p=<1476,1697,875>, v=<5,-87,-71>, a=<-15,-5,1> |p=<1476,1193,-1813>, v=<-85,-51,46>, a=<-3,-5,11> |p=<932,-6376,-4019>, v=<-47,24,-82>, a=<1,12,14> |p=<-12763,29,8401>, v=<177,-19,-62>, a=<16,1,-14> |p=<5087,6059,1936>, v=<-139,-65,76>, a=<-2,-9,-9> |p=<-853,-721,-4889>, v=<28,6,40>, a=<0,1,8> |p=<-1288,329,-11219>, v=<58,33,96>, a=<-1,-3,18> |p=<1352,-286,4051>, v=<-61,38,-10>, a=<1,-2,-8> |p=<2477,-271,-4649>, v=<41,-40,32>, a=<-8,3,8> |p=<-1783,-376,-6944>, v=<59,41,155>, a=<0,-2,5> |p=<-8728,2204,-1514>, v=<27,48,-26>, a=<17,-8,5> |p=<2987,-7276,-1829>, v=<-100,54,-31>, a=<0,12,6> |p=<-86,2277,1643>, v=<48,-108,-103>, a=<-4,0,2> |p=<-1640,-726,3722>, v=<45,24,-48>, a=<3,1,-12> |p=<334,-4947,761>, v=<-82,71,-28>, a=<6,15,-1> |p=<2686,1290,572>, v=<-106,16,-41>, a=<-2,-7,1> |p=<1153,3663,152>, v=<-110,35,45>, a=<5,-19,-5> |p=<-3257,-957,-2620>, v=<45,35,-32>, a=<10,1,14> |p=<-4958,4524,-2179>, v=<16,-127,13>, a=<20,-8,8> |p=<-1913,2844,-898>, v=<47,-135,40>, a=<4,0,0> |p=<-3826,-5200,5502>, v=<-27,-24,31>, a=<8,10,-11> |p=<50,-7529,4380>, v=<34,27,-6>, a=<-2,11,-7> |p=<-362,3,273>, v=<20,20,-5>, a=<3,-4,-4> |p=<-927,-577,-887>, v=<82,89,56>, a=<2,-6,6> |p=<-942,-727,1133>, v=<78,-6,-102>, a=<3,14,-2> |p=<-92,-817,-222>, v=<-73,80,17>, a=<15,0,1> |p=<-1062,-87,-642>, v=<68,7,59>, a=<7,0,1> |p=<-532,-1332,-537>, v=<4,27,65>, a=<9,19,-2> |p=<8,888,968>, v=<-17,-19,-58>, a=<3,-13,-7> |p=<-1188,-1222,249>, v=<-13,12,39>, a=<5,3,-4> |p=<-672,-814,1713>, v=<28,45,3>, a=<0,-1,-6> |p=<612,-4354,3273>, v=<87,30,-87>, a=<-9,12,-4> |p=<3048,-2098,-3435>, v=<-27,86,80>, a=<-8,0,5> |p=<2556,3434,1137>, v=<31,-32,2>, a=<-11,-9,-4> |p=<-372,710,-1851>, v=<-47,-31,-61>, a=<5,0,11> |p=<-648,-2698,705>, v=<2,136,20>, a=<2,-2,-4> |p=<564,146,-2007>, v=<-36,-70,108>, a=<1,5,-2> |p=<2040,662,-6411>, v=<-85,-29,129>, a=<0,0,11> |p=<-5642,-1168,-495>, v=<101,-74,-40>, a=<7,8,4> |p=<-3724,-3058,-1279>, v=<-11,-21,-41>, a=<10,9,6> |p=<-1540,-5046,-2875>, v=<56,79,74>, a=<0,7,2> |p=<336,-3506,345>, v=<47,82,17>, a=<-4,3,-2> |p=<5432,3088,2375>, v=<39,-52,-99>, a=<-16,-4,1> |p=<1792,1716,-2749>, v=<-63,55,26>, a=<0,-8,5> |p=<-1274,316,723>, v=<148,76,-40>, a=<-7,-6,1> |p=<924,-104,4223>, v=<-32,4,-49>, a=<0,0,-7> |p=<1484,-832,107>, v=<-168,30,-18>, a=<8,0,1> |p=<-8594,3021,4906>, v=<21,28,4>, a=<14,-7,-9> |p=<10084,-1137,-5786>, v=<-86,35,90>, a=<-13,0,5> |p=<-5030,5628,-2420>, v=<-2,-170,73>, a=<9,0,0> |p=<-2324,-2952,220>, v=<1,124,44>, a=<4,-2,-3> |p=<2857,2757,55>, v=<-3,2,-36>, a=<-5,-5,2> |p=<3319,-2523,2497>, v=<-34,26,26>, a=<-4,3,-6> |p=<5256,903,-1020>, v=<76,11,65>, a=<-12,-2,-2> |p=<8028,5151,-1038>, v=<-1,-33,84>, a=<-12,-6,-3> |p=<3690,-4065,1266>, v=<-47,75,57>, a=<-3,2,-5> |p=<6606,5403,7026>, v=<-17,-40,-66>, a=<-9,-6,-7> |p=<-1638,1383,1338>, v=<11,-86,-51>, a=<14,-2,-6> |p=<896,1026,-622>, v=<-5,-98,-1>, a=<-8,3,6> |p=<763,1425,309>, v=<-78,-134,0>, a=<3,4,-3> |p=<1001,-619,113>, v=<55,72,44>, a=<-17,-4,-7> |p=<1191,109,1991>, v=<-116,-48,-8>, a=<5,3,-4> |p=<3453,-1718,-5230>, v=<136,60,46>, a=<-17,0,9> |p=<-2666,-2646,-4621>, v=<32,47,40>, a=<4,3,8> |p=<1436,-2829,1966>, v=<-51,-16,-45>, a=<-2,15,-5> |p=<696,2161,-2404>, v=<-35,-108,100>, a=<0,0,2> |p=<2486,2401,-1224>, v=<-9,48,20>, a=<-11,-16,4> |p=<3046,261,1116>, v=<-37,71,-139>, a=<-11,-8,8> |p=<-104,2751,2326>, v=<-121,-85,-42>, a=<12,-5,-7> |p=<-1044,-249,496>, v=<73,-19,-45>, a=<-2,3,2> |p=<556,-289,1826>, v=<-28,-59,67>, a=<0,7,-15> |p=<-274,1131,-44>, v=<-18,-46,45>, a=<3,-1,-4> |p=<2266,1141,-504>, v=<-19,-78,26>, a=<-9,2,0> |p=<-891,-129,1722>, v=<-121,92,-73>, a=<15,-8,-1> |p=<243,-2439,3276>, v=<23,70,-158>, a=<-3,4,0> |p=<-72,-339,399>, v=<-17,3,-10>, a=<2,1,-1> |p=<1461,-759,2205>, v=<-57,-109,-30>, a=<-1,13,-7> |p=<-597,-1536,882>, v=<30,-39,-33>, a=<0,10,-1> |p=<2469,-1683,1533>, v=<49,-10,-152>, a=<-15,8,7> |p=<957,3441,1428>, v=<-143,-1,106>, a=<9,-15,-16> |p=<-2487,-927,-5271>, v=<32,-35,194>, a=<8,7,5> |p=<915,585,1701>, v=<-97,-8,-83>, a=<5,-2,0> |p=<-1975,2665,-1727>, v=<138,-30,49>, a=<-4,-9,3> |p=<-2122,-23,-2945>, v=<24,76,74>, a=<7,-7,6> |p=<150,1353,672>, v=<36,-115,-12>, a=<-5,4,-3> |p=<2139,-1299,1437>, v=<-144,-4,-93>, a=<2,9,1> |p=<-955,3036,298>, v=<74,-79,-8>, a=<-2,-11,-1> |p=<2156,-1418,-1640>, v=<-46,84,34>, a=<-9,0,7> |p=<-938,-1418,808>, v=<82,66,25>, a=<-3,2,-8> |p=<-2179,-109,-382>, v=<146,25,-31>, a=<-2,-2,6> |p=<2139,1727,-280>, v=<-63,-74,-46>, a=<-7,-3,7> |p=<-1006,622,-59>, v=<77,-54,-5>, a=<-2,2,1> |p=<235,894,349>, v=<-113,-79,43>, a=<11,3,-7> |p=<2258,452,1624>, v=<-88,37,-32>, a=<-5,-7,-7> |p=<6485,8607,10076>, v=<-46,61,-99>, a=<-6,-14,-8> |p=<15533,4551,638>, v=<-78,-55,-57>, a=<-16,-3,2> |p=<128,6540,4148>, v=<-3,114,-67>, a=<0,-14,-2> |p=<11555,3186,2081>, v=<-116,0,-114>, a=<-9,-4,3> |p=<9371,-3015,-6031>, v=<20,79,54>, a=<-13,0,5> |p=<-12586,339,-7786>, v=<3,-7,59>, a=<16,0,7> |p=<-2056,-7383,-4705>, v=<-67,11,0>, a=<6,9,6> |p=<1025,2796,-13480>, v=<-126,-70,-15>, a=<5,0,18> |p=<-11416,-1962,-766>, v=<-47,12,39>, a=<17,2,-1> |p=<1103,-558,3212>, v=<-88,-24,-83>, a=<3,2,0> |p=<-56,-3584,3008>, v=<78,86,-151>, a=<-6,5,2> |p=<1072,-5108,-1720>, v=<-44,112,71>, a=<0,8,0> |p=<-1256,1936,-1384>, v=<28,-69,57>, a=<2,-1,0> |p=<1996,-992,1472>, v=<-120,-22,-12>, a=<3,5,-4> |p=<3376,1324,908>, v=<-140,-31,-101>, a=<0,-2,5> |p=<3604,412,6920>, v=<-62,-43,-189>, a=<-7,2,-8> |p=<-176,4384,2204>, v=<-17,-21,-80>, a=<2,-13,-1> |p=<-992,-1196,-3616>, v=<42,49,50>, a=<0,0,8> |p=<-353,-1549,-1122>, v=<-72,-82,26>, a=<6,10,1> |p=<727,-3169,-2337>, v=<0,6,-97>, a=<-2,8,13> |p=<-1973,-1387,-3282>, v=<44,-60,92>, a=<2,8,2> |p=<1159,-118,2712>, v=<96,75,-46>, a=<-10,-5,-4> |p=<-974,260,-2553>, v=<-105,-51,37>, a=<10,3,4> |p=<1645,2069,2388>, v=<50,22,-20>, a=<-8,-7,-5> |p=<1726,2420,-3930>, v=<-79,-19,46>, a=<1,-5,7> |p=<1564,4364,1740>, v=<53,-91,-38>, a=<-8,-5,-2> |p=<6496,8583,-2797>, v=<-129,-57,50>, a=<-4,-12,2> |p=<919,-6234,4727>, v=<74,188,9>, a=<-6,0,-9> |p=<2272,-2736,7796>, v=<-1,-3,-67>, a=<-4,5,-10> |p=<-9674,-558,9809>, v=<72,-52,-26>, a=<13,4,-16> |p=<8542,3765,-124>, v=<-55,89,20>, a=<-12,-12,-1> |p=<1909,3138,1790>, v=<-41,74,-21>, a=<-1,-10,-2> |p=<-1419,1399,-3011>, v=<42,-26,-27>, a=<0,-1,7> |p=<1716,-4244,5569>, v=<-53,-178,-32>, a=<0,18,-8> |p=<6270,211,-10931>, v=<-38,78,60>, a=<-9,-5,16> |p=<-5181,-3452,-338>, v=<71,36,62>, a=<5,4,-3> |p=<-6105,-8402,-5915>, v=<31,-1,27>, a=<9,15,9> |p=<-1848,310,-1097>, v=<4,92,17>, a=<3,-6,1> |p=<2803,-1755,-532>, v=<-71,13,2>, a=<-5,6,2> |p=<691,2348,-785>, v=<48,-24,71>, a=<-7,-7,-3> |p=<-233,4779,-994>, v=<-48,-31,0>, a=<5,-16,4> |p=<119,-4021,238>, v=<-41,93,-10>, a=<3,8,0> |p=<-1168,-3647,-3392>, v=<52,76,132>, a=<0,8,2> |p=<-1845,-443,-822>, v=<-24,-30,1>, a=<11,5,4> |p=<2315,1487,4428>, v=<-64,-53,-83>, a=<-5,-2,-13> |p=<3255,-2683,-772>, v=<-132,82,-12>, a=<-3,5,5> |p=<-1405,487,108>, v=<-25,-45,70>, a=<9,2,-7> |p=<-2315,1877,-1142>, v=<73,1,38>, a=<4,-9,2> |p=<-1975,-2143,-3372>, v=<-28,13,13>, a=<12,9,15> |p=<1945,3157,2138>, v=<28,-147,21>, a=<-12,-1,-12> |p=<-3555,977,708>, v=<114,-59,-2>, a=<6,1,-3> |p=<5865,5127,-4422>, v=<-105,-67,118>, a=<-18,-18,10> |p=<-3264,2343,-3273>, v=<79,-72,127>, a=<11,-6,6> |p=<3387,-2301,1992>, v=<-53,129,15>, a=<-14,0,-13> |p=<2295,5276,1762>, v=<-104,-67,-57>, a=<0,-15,-2> |p=<-2072,-774,1036>, v=<37,-22,68>, a=<5,5,-10> |p=<447,865,1300>, v=<-20,-39,-36>, a=<0,0,-2> |p=<-1467,-1852,2323>, v=<90,50,-117>, a=<-2,3,1> |p=<4473,-664,-1241>, v=<-157,-4,45>, a=<-4,3,1> |p=<1580,-1621,-2572>, v=<32,5,48>, a=<-9,6,6> |p=<9680,-3138,-4267>, v=<-41,22,-84>, a=<-14,4,12> |p=<-4107,4648,2023>, v=<32,3,-59>, a=<5,-8,0> |p=<-673,1860,7004>, v=<36,-55,-48>, a=<-1,0,-9> |p=<8337,7453,2516>, v=<-159,-132,84>, a=<-5,-5,-9> |p=<2276,-3123,-1445>, v=<-62,44,37>, a=<-6,12,4> |p=<-1885,-64,1576>, v=<27,33,-12>, a=<7,-3,-7> |p=<-7265,156,268>, v=<89,-23,-25>, a=<6,1,1> |p=<-9137,3036,826>, v=<104,8,-133>, a=<8,-5,6> |p=<-6167,-1770,-4592>, v=<77,86,73>, a=<5,-2,3> |p=<-1685,-2976,2824>, v=<45,27,-22>, a=<0,3,-3> |p=<5821,-870,5740>, v=<3,-13,-29>, a=<-9,2,-7> |p=<331,1596,232>, v=<-11,-100,-135>, a=<0,3,7> |p=<-1230,1100,-8455>, v=<87,-67,165>, a=<-3,2,6> |p=<-1470,5772,3641>, v=<-21,-81,18>, a=<4,-6,-8> |p=<7026,-2852,1913>, v=<-6,106,6>, a=<-13,-1,-4> |p=<-5422,5132,-5575>, v=<-13,-160,42>, a=<11,0,8> |p=<3792,1660,-43>, v=<-175,-121,15>, a=<-9,1,-2> |p=<42,-620,-778>, v=<3,39,24>, a=<0,0,3> |p=<-318,-1370,1697>, v=<11,137,-85>, a=<2,-6,-4> |p=<1842,130,-613>, v=<-69,-11,-19>, a=<-6,0,7> |p=<-963,3070,-2218>, v=<30,-151,144>, a=<5,-7,0> |p=<2847,-2795,1532>, v=<-112,80,-74>, a=<-9,13,-4> |p=<747,-875,197>, v=<12,56,-17>, a=<-7,0,0> |p=<627,-80,1022>, v=<-36,27,-128>, a=<0,-3,7> |p=<2667,655,1427>, v=<-108,-14,-91>, a=<-8,-4,-1> |p=<1002,-215,962>, v=<35,-28,-108>, a=<-12,5,5> |p=<-849,-4500,291>, v=<-67,65,22>, a=<6,5,-2> |p=<6405,4180,5499>, v=<-125,9,-18>, a=<-5,-9,-10> |p=<4576,-4128,1562>, v=<-66,53,-3>, a=<-5,5,-3> |p=<391,4738,-2189>, v=<37,-89,70>, a=<-3,-4,0> |p=<-1004,863,12>, v=<82,-108,15>, a=<-3,5,-1> |p=<1352,1514,-4390>, v=<-10,-49,13>, a=<-2,0,8> |p=<360,-4748,-81>, v=<-26,73,50>, a=<1,5,-3> |p=<-7297,2320,-6157>, v=<-3,-75,22>, a=<15,0,11> |p=<918,-780,229>, v=<68,-55,-8>, a=<-6,5,0> |p=<422,-7135,5871>, v=<-12,86,-62>, a=<0,9,-8> |p=<2921,-2245,1495>, v=<-93,55,-15>, a=<0,1,-2> |p=<1417,-4757,1367>, v=<-79,84,22>, a=<2,4,-4> |p=<2137,-4133,-5545>, v=<-118,-117,40>, a=<3,15,8> |p=<2761,-3685,-2329>, v=<-121,67,-44>, a=<2,3,7> |p=<3145,3851,3831>, v=<-199,-53,-22>, a=<6,-4,-6> |p=<-807,-1909,-8809>, v=<40,-71,10>, a=<-1,8,16> |p=<-3001,-1007,-4300>, v=<-11,2,69>, a=<11,3,9> |p=<2291,3961,-2416>, v=<-19,-30,28>, a=<-6,-11,6> |p=<1571,-3143,-2428>, v=<-14,66,41>, a=<-4,5,5> |p=<683,3001,6056>, v=<73,-90,-200>, a=<-8,-3,-4> |p=<-205,-759,517>, v=<108,44,50>, a=<-8,-1,-6> |p=<-642,1863,3622>, v=<31,-58,23>, a=<0,-2,-15> |p=<-1562,1449,-4405>, v=<83,8,-12>, a=<-1,-6,17> |p=<853,-1242,3668>, v=<14,-67,-51>, a=<-4,10,-9> |p=<-757,46,-6061>, v=<0,-15,156>, a=<3,1,9> |p=<-3287,-1403,-564>, v=<38,0,-35>, a=<9,5,5> |p=<-849,1840,3001>, v=<124,-33,-106>, a=<-7,-4,-2> |p=<1566,2806,-1162>, v=<43,-39,15>, a=<-9,-7,3> |p=<5706,3174,-5141>, v=<-77,-67,44>, a=<-14,-6,15> |p=<-1444,-4807,1648>, v=<-55,150,-100>, a=<6,0,3> |p=<-2596,2137,-7664>, v=<-19,-67,92>, a=<6,0,9> |p=<-4324,1577,-5456>, v=<35,0,23>, a=<6,-3,9> |p=<-1428,2121,1568>, v=<-39,82,-48>, a=<5,-9,0> |p=<-4884,-7063,-1168>, v=<36,-27,-12>, a=<7,15,3> |p=<-2612,-2871,2352>, v=<-35,-26,43>, a=<7,7,-7> |p=<2492,7737,4832>, v=<-13,22,-51>, a=<-4,-16,-6> |p=<3228,-2455,880>, v=<-102,-39,-10>, a=<0,7,-1> |p=<620,-4183,0>, v=<29,15,1>, a=<-3,7,0> |p=<1549,1698,2535>, v=<-94,-85,-179>, a=<-2,-5,0> |p=<-1643,1068,-202>, v=<29,-25,-66>, a=<12,-7,11> |p=<-229,697,-1756>, v=<48,-51,30>, a=<-4,0,13> |p=<1724,39,1219>, v=<-129,-49,-85>, a=<1,6,0> |p=<361,2678,211>, v=<21,-76,46>, a=<-6,-15,-8> |p=<291,410,3284>, v=<-19,-19,-166>, a=<0,-1,-9> |p=<-1711,-2642,-1098>, v=<79,109,72>, a=<6,11,1> |p=<-12485,-3505,-8183>, v=<17,14,59>, a=<16,4,8> |p=<2449,-351,-4877>, v=<92,9,-28>, a=<-8,0,8> |p=<-2377,1435,1241>, v=<63,40,-72>, a=<0,-4,2> |p=<397,7496,462>, v=<146,-22,46>, a=<-8,-9,-3> |p=<4672,-180,1621>, v=<-25,-15,-121>, a=<-5,1,4> |p=<-667,2442,1165>, v=<57,-45,-31>, a=<-2,-1,0> |p=<-97,-7210,6523>, v=<-75,53,-55>, a=<4,7,-6> |p=<-5911,-5329,-5941>, v=<0,62,39>, a=<8,4,6> |p=<-5132,4133,1583>, v=<38,-31,-42>, a=<5,-4,0> |p=<-797,-449,1945>, v=<68,51,-76>, a=<-2,-3,-7> |p=<2203,496,-620>, v=<-28,-20,55>, a=<-15,-2,-2> |p=<-512,286,-725>, v=<17,-14,46>, a=<2,-1,0> |p=<-317,2701,2845>, v=<92,-135,-88>, a=<-9,-6,-13> |p=<2488,-839,10>, v=<-95,13,-19>, a=<-9,5,2> |p=<-32,-584,-1805>, v=<1,68,54>, a=<0,-4,8> |p=<-1487,841,25>, v=<106,-59,12>, a=<-1,0,-2> |p=<9711,3803,1142>, v=<-7,36,3>, a=<-15,-8,-2> |p=<3306,-1797,722>, v=<-4,34,-183>, a=<-5,1,9> |p=<2050,-1523,1668>, v=<-33,42,148>, a=<-3,1,-15> |p=<2914,-227,-2544>, v=<-9,8,66>, a=<-7,0,2> |p=<4507,-227,-1977>, v=<-152,22,-25>, a=<-1,-1,7> |p=<5452,448,777>, v=<-75,-87,-43>, a=<-9,5,1> |p=<-1217,-3197,-2922>, v=<18,76,-102>, a=<2,3,15> |p=<-1703,-2738,-6>, v=<-6,-39,0>, a=<5,10,0> |p=<-29,-6410,453>, v=<16,83,-73>, a=<-1,11,4> |p=<1591,313,-5028>, v=<40,16,102>, a=<-7,-2,6> |p=<1753,-4823,2921>, v=<-46,-88,-58>, a=<0,11,-1> |p=<3672,-6932,2617>, v=<79,26,-89>, a=<-9,8,1> |p=<-1534,8477,2883>, v=<-135,30,21>, a=<9,-13,-5> |p=<-3187,5532,7994>, v=<45,-29,23>, a=<2,-6,-12> |p=<5249,-776,-2988>, v=<-21,59,-39>, a=<-6,-2,6> |p=<-774,-339,-7244>, v=<1,106,112>, a=<1,-5,4> |p=<-2104,-17268,1420>, v=<-3,64,118>, a=<3,20,-8> |p=<-1306,4335,-24>, v=<15,22,0>, a=<1,-7,0> |p=<-972,2893,110>, v=<-133,420,13>, a=<7,-27,1> |p=<1906,-490,2091>, v=<271,-62,298>, a=<-18,9,-21> |p=<-1422,-2788,323>, v=<-200,-398,44>, a=<14,27,-3> |p=<1079,-21,-2677>, v=<156,-2,-384>, a=<-9,-1,22> |p=<-513,1027,-2732>, v=<-71,147,-392>, a=<5,-13,29> |p=<472,-76,-2799>, v=<67,-14,-399>, a=<-6,5,28> |p=<-478,1841,2426>, v=<-69,269,351>, a=<5,-20,-26> |p=<2254,1465,-1528>, v=<324,211,-218>, a=<-19,-13,17> |p=<-277,1286,2981>, v=<-39,181,423>, a=<-1,-8,-24> |p=<71,2026,2683>, v=<5,285,383>, a=<-3,-20,-25> |p=<-581,-2942,-73>, v=<-79,-423,-11>, a=<4,33,-4> |p=<65,2932,137>, v=<7,418,19>, a=<-1,-29,-1> |p=<-401,582,-3050>, v=<-59,88,-434>, a=<1,-4,30> |p=<2976,-590,-108>, v=<421,-80,-12>, a=<-26,2,4> |p=<-2303,-645,-1751>, v=<-329,-91,-251>, a=<21,6,14> |p=<1140,-2857,662>, v=<164,-410,91>, a=<-11,27,-10> |p=<-2532,-643,1350>, v=<-363,-84,191>, a=<29,4,-20> |p=<1816,1234,-2316>, v=<261,177,-329>, a=<-18,-12,23> |p=<499,-2878,-236>, v=<71,-410,-38>, a=<-2,25,6> |p=<2553,-1482,-988>, v=<361,-214,-139>, a=<-24,14,9> |p=<-2086,-2102,-211>, v=<-300,-301,-31>, a=<12,23,-2> |p=<-256,-1962,-2187>, v=<-38,-280,-313>, a=<1,19,20> |p=<-1353,-1829,1849>, v=<-197,-264,260>, a=<15,19,-18> |p=<2427,-1169,1408>, v=<345,-170,206>, a=<-30,5,-17> |p=<-681,372,-3521>, v=<-98,58,-512>, a=<12,-3,39> |p=<-525,-322,-2723>, v=<-71,-46,-387>, a=<9,-2,33> |p=<-1485,2370,-939>, v=<-212,340,-138>, a=<19,-18,11> |p=<2629,23,1333>, v=<375,2,191>, a=<-24,-1,-13> |p=<-962,2687,-565>, v=<-140,383,-78>, a=<8,-20,5> |p=<990,3391,-1021>, v=<144,480,-152>, a=<-9,-32,8> |p=<-1608,2476,39>, v=<-229,351,3>, a=<17,-24,0> |p=<2455,44,-1459>, v=<350,3,-209>, a=<-26,0,19> |p=<3240,154,-210>, v=<457,20,-33>, a=<-31,1,6> |p=<-2171,-88,-1778>, v=<-309,-8,-254>, a=<19,0,15> |p=<-2277,-926,-1445>, v=<-325,-131,-207>, a=<24,5,11> |p=<-589,-1148,2928>, v=<-80,-170,418>, a=<9,12,-29> |p=<-2241,-1063,1406>, v=<-316,-152,197>, a=<24,16,-19> |p=<2092,-955,950>, v=<298,-136,132>, a=<-24,8,-7> |p=<-466,-2201,-1279>, v=<-62,-310,-180>, a=<-1,23,12> |p=<-468,-2983,-1861>, v=<-66,-425,-260>, a=<8,28,23> |p=<-1070,-2706,-272>, v=<-149,-388,-38>, a=<8,27,0> |p=<-2009,-1830,1787>, v=<-291,-264,248>, a=<20,22,-17> |p=<2822,-85,659>, v=<403,-14,89>, a=<-33,0,-10> |p=<-2363,-1805,-611>, v=<-337,-257,-89>, a=<24,16,12> |p=<-2598,2035,-674>, v=<-373,287,-95>, a=<28,-22,8> |p=<1173,2573,243>, v=<164,367,40>, a=<-14,-23,1> |p=<-836,3312,206>, v=<-118,475,29>, a=<8,-34,-2> |p=<1688,-381,2533>, v=<236,-57,357>, a=<-15,3,-25> |p=<143,1759,-2463>, v=<22,249,-355>, a=<0,-14,27> |p=<-2683,2007,980>, v=<-389,283,140>, a=<25,-23,-12> |p=<-670,-1250,-2411>, v=<-97,-178,-347>, a=<6,15,24> |p=<-1136,2357,985>, v=<-164,334,139>, a=<16,-27,-11> |p=<2096,-1737,638>, v=<298,-251,86>, a=<-20,22,-6> |p=<-2631,-271,1623>, v=<-375,-37,230>, a=<29,1,-18> |p=<2424,1243,1437>, v=<348,177,200>, a=<-26,-10,-19> |p=<2060,1385,938>, v=<294,197,134>, a=<-25,-14,-15> |p=<1331,2651,-818>, v=<193,381,-116>, a=<-13,-30,9> |p=<776,1916,1714>, v=<112,274,249>, a=<-5,-18,-17> |p=<-811,427,-2299>, v=<-117,63,-328>, a=<6,0,27> |p=<1354,2492,-186>, v=<191,355,-27>, a=<-16,-24,2> |p=<474,3023,-673>, v=<69,434,-92>, a=<-4,-25,10> |p=<1520,-2352,670>, v=<215,-334,94>, a=<-16,19,-7> |p=<-1149,-2556,-1447>, v=<-166,-360,-206>, a=<11,23,13> |p=<-37,2330,1867>, v=<-5,328,265>, a=<-2,-22,-14> |p=<-2861,-590,507>, v=<-413,-82,70>, a=<27,1,-2> |p=<3202,-250,647>, v=<462,-35,92>, a=<-24,2,-6> |p=<-2286,-833,-1219>, v=<-326,-122,-173>, a=<22,4,15> |p=<-2215,-1793,861>, v=<-321,-252,125>, a=<18,22,-4> |p=<-156,1321,2884>, v=<-21,191,413>, a=<1,-11,-30> |p=<-804,2418,-838>, v=<-114,340,-125>, a=<8,-26,6> |p=<-1121,-1781,-1869>, v=<-157,-256,-265>, a=<12,19,17> |p=<-1529,565,-2482>, v=<-217,86,-354>, a=<15,-5,29> |p=<87,1773,2467>, v=<17,253,356>, a=<0,-12,-24> |p=<-1370,2134,2591>, v=<-195,304,367>, a=<14,-20,-25> |p=<-14,2076,1747>, v=<-4,294,249>, a=<4,-12,-17> |p=<1935,-1618,1382>, v=<281,-226,197>, a=<-18,19,-13> |p=<-2297,1551,77>, v=<-331,223,10>, a=<16,-13,-2> |p=<-1952,-1430,82>, v=<-276,-199,12>, a=<14,13,0> |p=<-1987,-1518,-1457>, v=<-280,-216,-208>, a=<14,15,17> |p=<-1359,-1392,2060>, v=<-196,-199,295>, a=<12,15,-26> |p=<691,-2517,1578>, v=<98,-359,224>, a=<-9,26,-15> |p=<2671,965,580>, v=<381,131,81>, a=<-31,-14,-7> |p=<-243,614,2906>, v=<-31,84,421>, a=<3,-6,-30> |p=<-1052,646,3333>, v=<-149,95,476>, a=<12,-3,-37> |p=<510,1846,2487>, v=<72,264,351>, a=<-9,-20,-24> |p=<-1990,-1380,1739>, v=<-282,-193,248>, a=<18,9,-15> |p=<133,-2661,-1829>, v=<18,-382,-264>, a=<1,28,18> |p=<815,2490,1020>, v=<122,351,144>, a=<-8,-20,-4> |p=<2465,-1704,-1056>, v=<348,-243,-150>, a=<-24,16,12> |p=<-711,-1825,2020>, v=<-107,-263,293>, a=<3,18,-20> |p=<2090,1861,-455>, v=<295,266,-65>, a=<-16,-18,8> |p=<-76,2995,-1382>, v=<-11,422,-196>, a=<2,-32,12> |p=<2104,-1799,1488>, v=<298,-260,207>, a=<-24,19,-13> |p=<63,2542,2053>, v=<10,365,295>, a=<0,-26,-15> |p=<1575,1481,-1420>, v=<224,211,-200>, a=<-11,-18,14> |p=<-2166,-345,-1387>, v=<-306,-49,-201>, a=<17,-1,10> |p=<-945,2623,29>, v=<-132,371,3>, a=<12,-23,-1> |p=<2590,878,-717>, v=<370,129,-102>, a=<-22,-15,9> |p=<2515,-1076,-679>, v=<357,-154,-101>, a=<-23,6,6> |p=<-1338,-2273,-1604>, v=<-186,-328,-231>, a=<14,22,18> |p=<-353,-2665,-1229>, v=<-46,-379,-172>, a=<3,24,12> |p=<-83,2448,-822>, v=<-13,353,-116>, a=<4,-23,8> |p=<-523,2472,1345>, v=<-73,355,192>, a=<8,-26,-15> |p=<-2443,1609,-1552>, v=<-349,231,-216>, a=<27,-17,22> |p=<1999,-1105,2090>, v=<285,-162,296>, a=<-17,10,-20> |p=<1954,2345,1492>, v=<277,339,213>, a=<-19,-23,-14> |p=<2221,-1016,1120>, v=<316,-141,158>, a=<-24,12,-10> |p=<-3168,-1304,44>, v=<-455,-186,10>, a=<27,16,1> |p=<1622,-980,-2335>, v=<231,-145,-337>, a=<-15,13,21> |p=<2185,209,2262>, v=<311,34,326>, a=<-27,2,-22> |p=<-2551,-307,1547>, v=<-364,-42,223>, a=<22,2,-16> |p=<-908,-1546,2694>, v=<-129,-219,384>, a=<11,12,-29> |p=<3364,248,363>, v=<481,35,47>, a=<-30,-4,3> |p=<-417,2230,1781>, v=<-60,320,254>, a=<5,-24,-15> |p=<-1902,-30,-1618>, v=<-265,-1,-228>, a=<20,0,13> |p=<-693,3041,-63>, v=<-100,434,-9>, a=<1,-29,-2> |p=<-1400,565,-2175>, v=<-200,80,-310>, a=<15,-6,17> |p=<-1416,-2376,-1590>, v=<-205,-341,-226>, a=<17,23,12> |p=<1484,-2148,1957>, v=<212,-311,279>, a=<-18,22,-16> |p=<573,2306,-702>, v=<84,331,-100>, a=<-8,-20,4> |p=<2271,1826,646>, v=<317,255,92>, a=<-21,-19,-6> |p=<-1405,1090,2686>, v=<-200,154,380>, a=<16,-7,-25> |p=<1115,-2148,-2264>, v=<161,-308,-323>, a=<-15,18,22> |p=<1491,2294,-1052>, v=<215,330,-149>, a=<-14,-22,8> |p=<2596,1010,885>, v=<374,145,124>, a=<-24,-8,-10> |p=<-1795,1860,-1144>, v=<-257,267,-164>, a=<24,-20,9> |p=<1277,687,-2336>, v=<184,94,-333>, a=<-7,-6,28> |p=<-347,1880,2125>, v=<-49,269,301>, a=<0,-18,-22> |p=<-18,-2622,-1537>, v=<-2,-370,-219>, a=<-2,29,19> |p=<-1855,-2054,1009>, v=<-264,-297,140>, a=<21,17,-14> |p=<-326,-2183,2149>, v=<-40,-311,306>, a=<0,18,-17> |p=<-980,-864,-2259>, v=<-141,-118,-318>, a=<14,10,17> |p=<-1809,905,-2722>, v=<-258,133,-391>, a=<17,-12,26> |p=<592,1196,-2413>, v=<88,171,-351>, a=<-1,-7,26> |p=<2073,1542,2188>, v=<300,220,318>, a=<-19,-15,-18> |p=<-557,-2458,1007>, v=<-79,-350,142>, a=<11,22,-12> |p=<-2392,2150,1346>, v=<-342,309,192>, a=<24,-23,-12> |p=<994,-2356,833>, v=<142,-338,119>, a=<-9,31,-3> |p=<299,2668,-290>, v=<46,382,-41>, a=<-5,-25,2> |p=<1626,-692,-2134>, v=<238,-101,-303>, a=<-14,6,19> |p=<1605,-1643,-682>, v=<228,-238,-98>, a=<-16,19,6> |p=<2925,-496,-312>, v=<419,-74,-44>, a=<-28,3,5> |p=<1803,-1874,1905>, v=<259,-265,271>, a=<-11,18,-19> |p=<-2236,415,-1699>, v=<-319,57,-246>, a=<22,-6,16> |p=<1843,-488,1798>, v=<259,-69,257>, a=<-26,5,-20> |""".stripMargin val input2 = """p=<-2754,1655,331>, v=<-392,240,47>, a=<26,-16,-8> |p=<-834,251,-2722>, v=<-116,33,-386>, a=<3,-5,21> |p=<1021,-1266,3203>, v=<146,-185,456>, a=<-8,12,-36> |p=<-3008,-317,1005>, v=<-426,-45,145>, a=<27,1,-11> |p=<-2940,246,-187>, v=<-420,35,-22>, a=<34,-1,-1> |p=<1801,-1599,-1446>, v=<256,-221,-208>, a=<-15,12,14> |p=<-682,-3221,-349>, v=<-93,-456,-50>, a=<10,31,6> |p=<1654,207,-2009>, v=<238,33,-287>, a=<-20,-10,26> |p=<361,131,3200>, v=<51,15,455>, a=<-4,-1,-32> |p=<-633,-781,-2968>, v=<-91,-114,-422>, a=<5,6,29> |p=<-2215,-1455,1996>, v=<-315,-209,290>, a=<21,17,-15> |p=<-1296,-1166,2232>, v=<-185,-166,322>, a=<10,8,-22> |p=<-506,1002,-2804>, v=<-67,140,-401>, a=<7,-10,31> |p=<886,713,3210>, v=<125,97,458>, a=<-11,-11,-31> |p=<473,1814,2234>, v=<67,258,320>, a=<-6,-21,-19> |p=<-1602,1619,2001>, v=<-225,230,285>, a=<21,-16,-20> |p=<-742,-2555,288>, v=<-107,-365,42>, a=<7,26,-2> |p=<-3147,-1191,643>, v=<-445,-169,93>, a=<36,11,-8> |p=<1263,214,2752>, v=<180,30,395>, a=<-9,-2,-29> |p=<-2143,2199,1241>, v=<-310,308,175>, a=<23,-24,-8> |p=<-2553,928,-1224>, v=<-364,125,-172>, a=<25,-7,9> |p=<-2136,-2245,-1378>, v=<-307,-323,-195>, a=<24,23,13> |p=<889,-1593,2244>, v=<129,-222,323>, a=<-8,17,-23> |p=<-1520,-1646,1398>, v=<-223,-235,199>, a=<21,13,-11> |p=<2628,1000,-86>, v=<374,139,-16>, a=<-27,-16,1> |p=<-2376,-283,-2193>, v=<-336,-38,-314>, a=<29,7,24> |p=<1742,2026,408>, v=<247,292,55>, a=<-17,-23,1> |p=<-2191,-1544,-527>, v=<-312,-215,-75>, a=<20,15,7> |p=<-1704,-1827,1891>, v=<-241,-263,273>, a=<19,22,-18> |p=<-1270,-49,3352>, v=<-181,-13,478>, a=<12,2,-32> |p=<-2569,901,331>, v=<-369,129,47>, a=<26,-4,-4> |p=<1141,2256,1587>, v=<163,320,220>, a=<-13,-22,-18> |p=<1137,-2605,-1860>, v=<159,-373,-265>, a=<-10,24,14> |p=<-34,-1139,-2680>, v=<-3,-162,-383>, a=<0,10,26> |p=<2205,-1859,-418>, v=<318,-263,-57>, a=<-23,19,9> |p=<2263,-885,731>, v=<323,-127,101>, a=<-19,10,-7> |p=<747,-1743,-2548>, v=<107,-251,-360>, a=<-8,19,28> |p=<-2858,-1478,-787>, v=<-404,-214,-111>, a=<31,16,10> |p=<-2627,342,956>, v=<-375,45,136>, a=<26,-6,-12> |p=<-2234,2105,357>, v=<-319,303,51>, a=<19,-20,-4> |p=<1027,-2032,1325>, v=<153,-292,186>, a=<-7,20,-9> |p=<1283,-1286,2609>, v=<185,-183,373>, a=<-10,7,-23> |p=<1360,1947,2379>, v=<197,277,339>, a=<-17,-15,-23> |p=<-860,-679,2987>, v=<-122,-97,427>, a=<3,9,-24> |p=<-1647,2787,-244>, v=<-232,401,-37>, a=<17,-30,1> |p=<837,3170,1198>, v=<119,454,170>, a=<-4,-24,-11> |p=<1266,-1460,2161>, v=<179,-200,308>, a=<-14,10,-21> |p=<1648,1562,-2437>, v=<235,226,-350>, a=<-14,-12,24> |p=<-570,2209,-1513>, v=<-85,316,-215>, a=<1,-21,20> |p=<330,-2321,-199>, v=<47,-329,-28>, a=<-3,24,4> |p=<-2067,1180,1813>, v=<-299,169,263>, a=<20,-8,-15> |p=<-78,-2126,2288>, v=<-5,-307,321>, a=<-2,21,-25> |p=<-1626,281,1926>, v=<-232,40,277>, a=<23,3,-20> |p=<-235,3009,-77>, v=<-32,428,-16>, a=<1,-26,1> |p=<-345,3015,279>, v=<-52,430,42>, a=<0,-21,-1> |p=<2896,-2028,-978>, v=<416,-288,-138>, a=<-32,20,9> |p=<-3125,-612,759>, v=<-449,-87,108>, a=<31,5,-12> |p=<2888,2,384>, v=<414,0,57>, a=<-32,1,-6> |p=<-731,1698,2115>, v=<-106,244,305>, a=<7,-13,-21> |p=<2036,-736,-1453>, v=<294,-107,-208>, a=<-20,6,11> |p=<1652,-2222,234>, v=<236,-319,33>, a=<-18,15,-3> |p=<-515,-3243,235>, v=<-72,-462,30>, a=<3,33,1> |p=<7,-2446,2313>, v=<-3,-346,330>, a=<4,28,-21> |p=<1566,2106,1297>, v=<223,298,187>, a=<-13,-21,-15> |p=<2773,-241,-1939>, v=<393,-34,-277>, a=<-23,3,19> |p=<-1981,-951,1585>, v=<-286,-137,221>, a=<20,8,-18> |p=<-14,2752,627>, v=<-2,392,88>, a=<2,-21,-6> |p=<-2752,-498,2256>, v=<-393,-70,317>, a=<27,1,-23> |p=<-2795,-853,-603>, v=<-406,-121,-86>, a=<25,5,2> |p=<631,-2038,-1425>, v=<90,-293,-206>, a=<-4,20,12> |p=<125,2224,1993>, v=<18,316,291>, a=<4,-21,-25> |p=<-2231,489,-1563>, v=<-322,70,-224>, a=<23,-3,15> |p=<-2139,746,-1996>, v=<-302,109,-279>, a=<21,-5,18> |p=<992,-1201,-2833>, v=<145,-172,-408>, a=<-8,15,24> |p=<-1702,-2598,-45>, v=<-247,-371,-5>, a=<17,28,-2> |p=<-2590,-960,482>, v=<-369,-137,68>, a=<28,7,2> |p=<3216,-233,416>, v=<461,-31,61>, a=<-34,6,-4> |p=<-1121,692,2728>, v=<-162,101,391>, a=<13,-8,-27> |p=<-2671,-146,2193>, v=<-383,-24,313>, a=<22,-3,-22> |p=<763,-241,-3416>, v=<107,-32,-482>, a=<-9,-2,33> |p=<-671,-3065,126>, v=<-94,-437,16>, a=<13,31,-4> |p=<564,-2454,1713>, v=<75,-350,244>, a=<-5,24,-17> |p=<-1735,-2340,-460>, v=<-247,-334,-62>, a=<14,23,4> |p=<6,-2515,1136>, v=<0,-359,163>, a=<0,26,-10> |p=<2952,-18,724>, v=<424,1,103>, a=<-33,2,-9> |p=<-1425,729,2352>, v=<-206,107,337>, a=<17,-7,-23> |p=<-2551,-193,-2026>, v=<-365,-31,-289>, a=<25,3,17> |p=<1329,-2258,-1434>, v=<189,-322,-206>, a=<-18,18,14> |p=<1211,2337,-829>, v=<173,332,-120>, a=<-15,-20,8> |p=<-1528,-2029,2196>, v=<-218,-290,315>, a=<18,18,-19> |p=<2764,2067,855>, v=<391,290,119>, a=<-23,-16,-7> |p=<50,-2547,1000>, v=<8,-363,140>, a=<-1,27,-10> |p=<-1843,-740,-2538>, v=<-258,-105,-364>, a=<20,8,24> |p=<2901,-143,-287>, v=<416,-19,-40>, a=<-32,-3,3> |p=<-745,3115,-349>, v=<-111,448,-51>, a=<7,-34,-3> |p=<1591,264,-2030>, v=<222,37,-288>, a=<-16,-6,19> |p=<166,-48,3636>, v=<23,-10,516>, a=<-1,2,-30> |p=<319,1678,-2277>, v=<46,237,-320>, a=<0,-18,23> |p=<-2171,614,-1695>, v=<-310,87,-242>, a=<21,-4,11> |p=<-1126,665,-2761>, v=<-157,93,-392>, a=<14,-6,29> |p=<1741,2247,1663>, v=<246,324,234>, a=<-17,-16,-20> |p=<1650,-1865,-1148>, v=<236,-268,-164>, a=<-17,14,11> |p=<319,-1899,-1553>, v=<45,-274,-219>, a=<0,18,12> |p=<-319,321,-3639>, v=<-42,45,-518>, a=<5,0,31> |p=<-863,-2811,20>, v=<-123,-397,4>, a=<9,31,-2> |p=<2645,-31,542>, v=<373,-5,73>, a=<-23,1,-4> |p=<-228,-1990,2353>, v=<-35,-287,336>, a=<5,22,-21> |p=<3382,828,-998>, v=<482,123,-143>, a=<-35,-9,7> |p=<-681,-2015,-1438>, v=<-89,-285,-208>, a=<6,19,12> |p=<-2127,-1613,-1494>, v=<-308,-234,-212>, a=<19,16,11> |p=<65,2762,-1780>, v=<9,395,-254>, a=<2,-26,17> |p=<-798,-2143,754>, v=<-112,-311,104>, a=<12,25,-10> |p=<1936,1826,927>, v=<277,263,131>, a=<-15,-20,-10> |p=<-720,-1926,-1387>, v=<-103,-275,-198>, a=<8,16,11> |p=<-2584,-1286,524>, v=<-371,-180,74>, a=<28,15,-9> |p=<286,-3580,426>, v=<39,-510,60>, a=<0,34,-7> |p=<-1940,-1873,-414>, v=<-277,-269,-56>, a=<19,14,6> |p=<2631,-809,-1547>, v=<376,-116,-229>, a=<-30,10,16> |p=<673,2160,-1825>, v=<102,308,-257>, a=<-4,-23,17> |p=<2169,-2413,-1194>, v=<307,-344,-170>, a=<-20,25,16> |p=<603,-3052,-393>, v=<89,-434,-53>, a=<-11,33,1> |p=<-1690,1909,1134>, v=<-241,272,169>, a=<15,-18,-15> |p=<-623,1217,1954>, v=<-93,172,275>, a=<10,-16,-15> |p=<-1697,-316,2170>, v=<-242,-45,310>, a=<20,-3,-19> |p=<-1516,2344,1308>, v=<-216,333,185>, a=<18,-20,-17> |p=<1853,-1625,701>, v=<261,-229,105>, a=<-20,19,-4> |p=<1542,-522,-2138>, v=<220,-70,-305>, a=<-20,8,20> |p=<-1835,-1148,-887>, v=<-257,-165,-126>, a=<22,13,5> |p=<3238,-2064,302>, v=<460,-292,47>, a=<-32,20,0> |p=<1003,-2638,-162>, v=<146,-372,-23>, a=<-10,26,5> |p=<-2709,1375,804>, v=<-385,196,120>, a=<24,-9,-9> |p=<-184,555,2572>, v=<-30,79,367>, a=<1,0,-29> |p=<-754,2751,-299>, v=<-110,393,-47>, a=<9,-28,2> |p=<2362,713,-1616>, v=<332,104,-227>, a=<-23,-7,15> |p=<254,732,-2598>, v=<38,104,-368>, a=<-8,-7,19> |p=<-2364,-799,1470>, v=<-344,-112,211>, a=<23,7,-16> |p=<2519,1937,-284>, v=<360,274,-40>, a=<-32,-22,3> |p=<2368,828,-1323>, v=<333,118,-182>, a=<-27,-5,12> |p=<-1443,-1799,2182>, v=<-204,-257,310>, a=<18,22,-23> |p=<-2230,320,1535>, v=<-319,47,219>, a=<21,-1,-15> |p=<-2176,1006,1711>, v=<-314,138,241>, a=<15,-10,-17> |p=<-2359,-1764,735>, v=<-341,-252,107>, a=<20,19,-6> |p=<-2255,2133,478>, v=<-318,303,67>, a=<21,-23,-4> |p=<1838,2021,-2030>, v=<262,293,-291>, a=<-22,-22,24> |p=<676,2730,-1581>, v=<98,391,-222>, a=<-7,-25,18> |p=<1654,1705,1873>, v=<233,240,270>, a=<-20,-22,-18> |p=<2899,-1228,-768>, v=<414,-171,-110>, a=<-29,10,12> |p=<-1106,-2603,-1038>, v=<-160,-376,-152>, a=<13,33,10> |p=<-2486,-1591,1417>, v=<-352,-223,202>, a=<23,14,-15> |p=<-224,-2723,405>, v=<-31,-392,57>, a=<-4,30,-2> |p=<-990,-385,2834>, v=<-141,-51,401>, a=<11,1,-30> |p=<2393,-1847,-12>, v=<343,-271,-1>, a=<-24,18,0> |p=<897,-1971,2676>, v=<126,-282,379>, a=<-11,19,-26> |p=<-1382,828,2465>, v=<-197,118,354>, a=<12,-11,-24> |p=<2715,-636,-95>, v=<383,-92,-10>, a=<-23,5,2> |p=<-1672,1496,1384>, v=<-238,215,196>, a=<13,-12,-8> |p=<-695,2864,430>, v=<-96,408,66>, a=<13,-28,-9> |p=<-890,2879,152>, v=<-128,419,18>, a=<11,-25,-1> |p=<1150,854,2388>, v=<160,127,344>, a=<-10,-10,-23> |p=<-1328,304,2387>, v=<-189,44,346>, a=<19,0,-20> |p=<1911,1030,2606>, v=<274,147,372>, a=<-21,-5,-22> |p=<-153,1935,1425>, v=<-17,277,204>, a=<-6,-18,-15> |p=<-563,-39,-3152>, v=<-85,-5,-449>, a=<4,0,31> |p=<1376,-434,2342>, v=<194,-58,337>, a=<-11,7,-24> |p=<1328,-3274,1577>, v=<188,-464,224>, a=<-13,32,-11> |p=<-1483,2780,842>, v=<-211,394,122>, a=<14,-27,-4> |p=<-2579,-50,157>, v=<-368,-5,18>, a=<22,0,-2> |p=<-2233,-1101,1703>, v=<-326,-156,244>, a=<23,11,-19> |p=<1576,-2527,660>, v=<225,-364,94>, a=<-14,29,-6> |p=<-920,-2797,-447>, v=<-128,-399,-63>, a=<7,22,4> |p=<-2430,2192,873>, v=<-347,313,128>, a=<25,-21,-11> |p=<616,2820,-591>, v=<84,402,-86>, a=<-5,-28,5> |p=<-544,-1235,2995>, v=<-78,-179,428>, a=<6,12,-29> |p=<-2103,152,1778>, v=<-297,15,262>, a=<21,2,-18> |p=<1499,276,3011>, v=<213,37,435>, a=<-14,-7,-31> |p=<-1913,2443,611>, v=<-270,345,87>, a=<15,-24,-4> |p=<-398,2956,72>, v=<-56,417,10>, a=<1,-31,5> |p=<-1863,1996,-1348>, v=<-266,285,-195>, a=<18,-15,14> |p=<-2302,-248,1303>, v=<-325,-38,181>, a=<17,1,-17> |p=<-591,-341,2548>, v=<-89,-52,364>, a=<4,5,-27> |p=<906,-1426,-2591>, v=<129,-206,-368>, a=<-7,14,19> |p=<-1733,-1479,1564>, v=<-251,-213,222>, a=<18,9,-13> |p=<2526,1103,78>, v=<357,157,11>, a=<-24,-9,-2> |p=<745,1626,2823>, v=<111,228,409>, a=<-6,-17,-23> |p=<-818,43,-2240>, v=<-118,11,-320>, a=<13,1,25> |p=<1837,993,1492>, v=<260,148,213>, a=<-17,-10,-16> |p=<-1099,1353,-2333>, v=<-162,193,-333>, a=<8,-9,22> |p=<467,2292,2372>, v=<66,332,340>, a=<-10,-18,-20> |p=<2035,1594,-773>, v=<290,227,-112>, a=<-18,-8,9> |p=<1663,-1377,1996>, v=<237,-196,283>, a=<-20,14,-16> |p=<-1151,1892,1053>, v=<-163,270,143>, a=<8,-21,-9> |p=<-1985,-1355,-1070>, v=<-283,-192,-151>, a=<22,10,9> |p=<880,-1024,-2847>, v=<121,-146,-401>, a=<-6,10,37> |p=<-2506,-941,-1276>, v=<-359,-141,-182>, a=<25,14,14> |p=<448,-3321,-1237>, v=<65,-469,-174>, a=<-4,31,10> |p=<1082,-384,2456>, v=<154,-55,343>, a=<-4,1,-21> |p=<583,-1175,2602>, v=<80,-167,370>, a=<-5,8,-26> |p=<-2143,1051,-2228>, v=<-306,150,-321>, a=<16,-11,26> |p=<-1351,1113,2530>, v=<-195,156,360>, a=<16,-11,-23> |p=<1289,2415,1068>, v=<186,345,157>, a=<-13,-31,-9> |p=<1829,-441,-2369>, v=<261,-59,-331>, a=<-20,4,25> |p=<-1181,2801,-1204>, v=<-168,406,-169>, a=<11,-25,15> |p=<1789,111,2716>, v=<253,16,391>, a=<-12,-1,-28> |p=<1188,-2396,-1168>, v=<173,-343,-166>, a=<-18,21,11> |p=<-624,-2348,1872>, v=<-87,-331,263>, a=<6,23,-17> |p=<974,2046,1600>, v=<141,293,228>, a=<-10,-20,-20> |p=<1087,-3,2753>, v=<157,4,393>, a=<-10,1,-31> |p=<-1696,2565,1439>, v=<-242,365,200>, a=<15,-21,-14> |p=<-2139,1264,1625>, v=<-308,186,239>, a=<21,-16,-17> |p=<-808,-2806,706>, v=<-116,-402,100>, a=<10,31,-7> |p=<-3344,-671,-1309>, v=<-477,-89,-186>, a=<31,4,12> |p=<-3120,-1016,-1164>, v=<-445,-145,-169>, a=<33,9,11> |p=<-392,1935,-1765>, v=<-54,277,-256>, a=<7,-20,20> |p=<-2772,50,-724>, v=<-398,7,-103>, a=<22,-2,1> |p=<-1135,909,-2293>, v=<-162,123,-325>, a=<11,-2,17> |p=<-2854,-66,-601>, v=<-402,-8,-82>, a=<29,-3,6> |p=<1651,760,1457>, v=<233,111,209>, a=<-16,-9,-14> |p=<-1771,-1151,-2641>, v=<-254,-160,-378>, a=<17,14,27> |p=<-1065,-2133,-2022>, v=<-152,-309,-293>, a=<12,24,14> |p=<1476,2335,-246>, v=<211,333,-32>, a=<-7,-22,0> |p=<-1903,461,2772>, v=<-268,58,396>, a=<21,-2,-25> |p=<765,-2802,769>, v=<112,-398,106>, a=<-3,33,-5> |p=<-3176,954,-234>, v=<-450,133,-36>, a=<29,-9,3> |p=<2177,-558,-2053>, v=<316,-78,-293>, a=<-21,5,19> |p=<394,1915,-2164>, v=<59,277,-313>, a=<-5,-20,21> |p=<1111,2949,1071>, v=<155,421,153>, a=<-10,-29,-12> |p=<-1787,102,2329>, v=<-254,13,332>, a=<14,-3,-20> |p=<-1253,-2502,-882>, v=<-176,-356,-124>, a=<15,24,7> |p=<1524,2539,-1037>, v=<216,362,-148>, a=<-15,-21,5> |p=<1881,745,2344>, v=<266,106,334>, a=<-14,-5,-24> |p=<-824,2492,1274>, v=<-117,355,187>, a=<2,-27,-11> |p=<-2672,-391,-718>, v=<-377,-60,-103>, a=<26,2,7> |p=<1706,-2502,613>, v=<248,-357,87>, a=<-19,23,-9> |p=<2838,442,349>, v=<400,63,52>, a=<-33,-4,-3> |p=<271,1719,-2620>, v=<42,245,-371>, a=<-5,-23,22> |p=<-1158,-1793,1596>, v=<-165,-258,225>, a=<6,10,-14> |p=<2491,-195,-2133>, v=<353,-23,-304>, a=<-22,-4,21> |p=<-119,2896,-1592>, v=<-14,413,-227>, a=<-2,-25,14> |p=<886,-685,2791>, v=<130,-97,398>, a=<-8,6,-26> |p=<1066,-2652,1270>, v=<152,-374,179>, a=<-10,28,-19> |p=<2080,1437,-1544>, v=<290,206,-216>, a=<-23,-15,15> |p=<1863,410,2408>, v=<270,56,345>, a=<-18,-4,-18> |p=<-524,3071,96>, v=<-74,436,11>, a=<7,-33,-4> |p=<580,-948,-2576>, v=<88,-133,-367>, a=<-12,11,22> |p=<-1103,1711,1858>, v=<-154,246,264>, a=<11,-15,-16> |p=<607,-2998,-745>, v=<79,-428,-101>, a=<-11,33,7> |p=<-1900,-1037,-1936>, v=<-269,-150,-275>, a=<16,12,15> |p=<-1155,-491,-2983>, v=<-164,-71,-431>, a=<11,-2,30> |p=<-2544,887,-742>, v=<-363,124,-109>, a=<23,-6,9> |p=<-731,2162,-1216>, v=<-102,311,-170>, a=<7,-19,16> |p=<-2202,-1939,1089>, v=<-320,-277,157>, a=<25,20,-10> |p=<-28,1561,2087>, v=<2,223,300>, a=<0,-16,-20> |p=<-1911,-1149,-1625>, v=<-271,-165,-230>, a=<15,10,12> |p=<-2869,-1090,310>, v=<-414,-155,49>, a=<26,15,-1> |p=<-695,-2254,-1859>, v=<-100,-321,-266>, a=<11,26,13> |p=<-2840,-674,1527>, v=<-405,-95,220>, a=<28,0,-17> |p=<-647,2949,1149>, v=<-91,421,164>, a=<8,-32,-11> |p=<2811,-1286,624>, v=<400,-179,89>, a=<-29,12,-3> |p=<1281,-380,-2752>, v=<182,-55,-391>, a=<-16,8,24> |p=<-2162,-1503,-1690>, v=<-306,-212,-240>, a=<21,15,14> |p=<2629,761,206>, v=<373,108,34>, a=<-27,-7,-7> |p=<-2021,620,2109>, v=<-288,90,301>, a=<20,-12,-22> |p=<-368,-2701,-164>, v=<-52,-380,-20>, a=<6,21,2> |p=<421,-3240,-681>, v=<60,-463,-96>, a=<-5,30,6> |p=<1919,-2148,-570>, v=<273,-304,-84>, a=<-24,24,5> |p=<1869,91,2715>, v=<264,13,389>, a=<-17,-5,-28> |p=<653,2752,1283>, v=<91,393,186>, a=<-3,-26,-15> |p=<-1085,-2377,-504>, v=<-155,-343,-71>, a=<10,23,4> |p=<2790,-724,-1756>, v=<400,-103,-250>, a=<-27,7,20> |p=<2362,670,1049>, v=<341,95,149>, a=<-22,-6,-10> |p=<-3223,261,-688>, v=<-459,42,-99>, a=<29,3,6> |p=<-968,2692,726>, v=<-135,386,100>, a=<9,-27,-6> |p=<763,-873,3032>, v=<108,-128,433>, a=<-7,11,-30> |p=<-397,-2950,-1235>, v=<-54,-417,-179>, a=<-1,30,13> |p=<2644,506,2319>, v=<370,68,328>, a=<-25,-5,-21> |p=<226,1558,2032>, v=<28,223,290>, a=<-2,-18,-18> |p=<-96,-2863,420>, v=<-8,-411,59>, a=<2,29,-1> |p=<2753,-521,644>, v=<389,-74,94>, a=<-25,4,-6> |p=<-2535,604,1696>, v=<-363,84,240>, a=<23,-5,-16> |p=<-1475,-1868,-1676>, v=<-211,-271,-235>, a=<13,20,20> |p=<2257,-411,1855>, v=<326,-61,264>, a=<-19,-2,-19> |p=<2632,1836,822>, v=<376,266,120>, a=<-30,-16,-8> |p=<-1695,1905,-1631>, v=<-243,272,-238>, a=<14,-27,18> |p=<-1726,1459,-2018>, v=<-246,211,-289>, a=<22,-17,23> |p=<2307,2175,489>, v=<328,312,67>, a=<-23,-20,-6> |p=<-1861,2174,-527>, v=<-269,313,-75>, a=<18,-24,5> |p=<-208,1185,2569>, v=<-28,169,371>, a=<-1,-10,-25> |p=<-1923,-300,2216>, v=<-271,-48,315>, a=<19,8,-22> |p=<-428,3024,-1181>, v=<-61,432,-171>, a=<3,-34,14> |p=<549,-2670,-461>, v=<73,-387,-65>, a=<-5,26,3> |p=<-1556,326,-2238>, v=<-221,43,-316>, a=<10,-3,27> |p=<-598,-3422,-454>, v=<-86,-488,-64>, a=<1,35,4> |p=<2143,-443,1333>, v=<302,-66,193>, a=<-20,8,-11> |p=<286,231,2772>, v=<40,35,396>, a=<-7,-1,-30> |p=<362,-2668,9>, v=<51,-379,1>, a=<-1,27,0> |p=<1015,-2626,-85>, v=<142,-376,-11>, a=<-13,33,-2> |p=<-709,904,2451>, v=<-103,130,350>, a=<5,-8,-27> |p=<2081,408,-1170>, v=<298,58,-166>, a=<-15,-7,11> |p=<-482,-2973,-1081>, v=<-69,-420,-151>, a=<2,31,9> |p=<-818,-74,-2792>, v=<-118,-10,-402>, a=<14,-3,32> |p=<2999,-87,-960>, v=<427,-14,-136>, a=<-31,3,6> |p=<2885,-1265,-374>, v=<409,-181,-53>, a=<-29,12,3> |p=<-1572,2938,16>, v=<-221,415,0>, a=<12,-30,0> |p=<-2424,-669,-1204>, v=<-342,-92,-175>, a=<21,8,17> |p=<-1215,1266,-2099>, v=<-173,176,-300>, a=<14,-7,21> |p=<-202,-3331,202>, v=<-33,-475,25>, a=<-1,36,1> |p=<935,2601,-482>, v=<133,370,-68>, a=<-12,-26,4> |p=<-1796,-2630,-1179>, v=<-260,-374,-168>, a=<20,24,10> |p=<-1532,-596,-1900>, v=<-220,-82,-274>, a=<18,5,23> |p=<-1577,-720,-2161>, v=<-228,-100,-303>, a=<17,8,25> |p=<-1215,1584,1974>, v=<-178,226,278>, a=<17,-15,-22> |p=<-3480,-170,1515>, v=<-499,-19,213>, a=<38,-1,-14> |p=<-2436,-111,-929>, v=<-353,-14,-128>, a=<25,0,14> |p=<2047,1023,-2117>, v=<292,149,-304>, a=<-21,-10,21> |p=<1510,-3054,336>, v=<224,-436,55>, a=<-12,35,-2> |p=<-2860,74,1242>, v=<-408,10,177>, a=<29,-2,-11> |p=<423,2218,-2064>, v=<56,316,-290>, a=<-1,-23,19> |p=<-1523,391,2820>, v=<-216,54,401>, a=<16,-3,-25> |p=<2150,822,-2210>, v=<305,114,-314>, a=<-21,-10,22> |p=<980,-2578,716>, v=<140,-368,106>, a=<-13,25,-13> |p=<-2221,-1430,671>, v=<-319,-202,91>, a=<29,20,-6> |p=<71,585,-2438>, v=<13,84,-348>, a=<0,1,24> |p=<-2243,-2418,-28>, v=<-320,-339,-10>, a=<22,23,0> |p=<-1990,1907,1046>, v=<-283,274,147>, a=<14,-22,-10> |p=<646,-563,-2987>, v=<96,-80,-426>, a=<-6,11,28> |p=<1124,-2386,-2399>, v=<166,-340,-342>, a=<-12,28,23> |p=<1269,-527,-2292>, v=<184,-75,-331>, a=<-12,2,24> |p=<-1031,2489,-962>, v=<-147,354,-138>, a=<13,-21,14> |p=<723,-2658,-127>, v=<105,-380,-14>, a=<-6,27,2> |p=<2,1922,2219>, v=<0,278,321>, a=<3,-18,-23> |p=<-2842,1751,-150>, v=<-408,256,-21>, a=<26,-17,-4> |p=<45,-2950,-602>, v=<9,-419,-87>, a=<3,29,6> |p=<-1231,-1203,-2120>, v=<-176,-172,-302>, a=<8,13,18> |p=<1637,-356,-1921>, v=<234,-56,-273>, a=<-14,1,18> |p=<-1712,-1611,-1495>, v=<-246,-229,-213>, a=<16,22,14> |p=<3521,152,-943>, v=<503,23,-134>, a=<-35,6,7> |p=<-2104,-2243,-337>, v=<-302,-320,-51>, a=<19,23,3> |p=<2358,-595,-1456>, v=<336,-91,-213>, a=<-22,8,14> |p=<-525,-1627,2776>, v=<-69,-232,399>, a=<0,14,-32> |p=<1648,963,-1620>, v=<238,134,-231>, a=<-12,-6,15> |p=<-2751,363,-551>, v=<-391,54,-79>, a=<24,-3,9> |p=<300,1792,2155>, v=<47,251,307>, a=<-6,-17,-16> |p=<1106,-214,-2291>, v=<156,-35,-325>, a=<-3,0,23> |p=<-1964,-795,-2331>, v=<-286,-111,-333>, a=<19,15,18> |p=<137,-3166,-572>, v=<21,-452,-82>, a=<0,30,3> |p=<-2691,705,-999>, v=<-388,98,-139>, a=<26,-9,10> |p=<1203,343,-3272>, v=<174,54,-469>, a=<-12,2,32> |p=<3115,-432,-66>, v=<447,-61,-3>, a=<-30,4,0> |p=<2562,-1744,862>, v=<367,-252,123>, a=<-23,17,-5> |p=<1380,-1281,1622>, v=<196,-177,230>, a=<-17,9,-14> |p=<-1200,-844,-2301>, v=<-173,-120,-328>, a=<15,15,20> |p=<-792,-1599,2552>, v=<-111,-231,367>, a=<7,17,-25> |p=<307,2585,-1745>, v=<46,361,-252>, a=<-2,-32,17> |p=<-199,-1278,-2273>, v=<-26,-186,-327>, a=<1,17,22> |p=<1870,-2159,-899>, v=<264,-314,-123>, a=<-18,22,6> |p=<434,1298,2381>, v=<63,185,337>, a=<-4,-11,-23> |p=<-2150,-2011,1077>, v=<-311,-289,157>, a=<15,22,-10> |p=<2355,-966,31>, v=<334,-136,2>, a=<-21,13,1> |p=<880,2467,1228>, v=<131,350,176>, a=<-10,-18,-9> |p=<2696,301,951>, v=<383,47,138>, a=<-29,-3,-10> |p=<50,1466,2481>, v=<4,210,354>, a=<0,-13,-21> |p=<-46,1414,2588>, v=<-3,203,369>, a=<2,-15,-22> |p=<-1343,790,2128>, v=<-191,114,306>, a=<17,-8,-19> |p=<-1893,-320,1958>, v=<-271,-46,278>, a=<18,1,-19> |p=<3013,80,1731>, v=<433,10,244>, a=<-30,0,-12> |p=<-1561,-2177,-1020>, v=<-227,-314,-145>, a=<16,26,16> |p=<-1230,2247,-501>, v=<-169,320,-71>, a=<14,-22,4> |p=<527,-2245,1744>, v=<67,-319,248>, a=<-6,21,-17> |p=<-1513,-166,-2981>, v=<-211,-28,-425>, a=<15,0,29> |p=<440,-823,2548>, v=<63,-116,364>, a=<-4,10,-24> |p=<-1545,-2022,350>, v=<-217,-285,51>, a=<19,18,-6> |p=<-1920,-2099,1374>, v=<-271,-304,197>, a=<18,21,-12> |p=<-1984,2245,966>, v=<-283,325,138>, a=<22,-22,-5> |p=<1286,1145,1885>, v=<186,163,271>, a=<-7,-11,-18> |p=<-2077,-1678,1117>, v=<-294,-243,156>, a=<24,17,-9> |p=<-65,3081,988>, v=<-9,440,141>, a=<-1,-33,-13> |p=<1372,-2516,92>, v=<198,-361,17>, a=<-13,23,0> |p=<574,-2894,-2168>, v=<82,-413,-309>, a=<-1,28,22> |p=<2843,-746,1072>, v=<408,-108,156>, a=<-26,5,-8> |p=<-2673,2015,-608>, v=<-380,287,-87>, a=<29,-14,5> |p=<-1103,-1722,-1992>, v=<-157,-247,-289>, a=<14,19,18> |p=<-619,528,-2863>, v=<-88,75,-410>, a=<5,-7,28> |p=<-1977,2190,1193>, v=<-282,311,167>, a=<17,-19,-13> |p=<860,-3029,253>, v=<123,-433,41>, a=<-8,33,-2> |p=<-1719,1295,-1775>, v=<-245,183,-250>, a=<13,-13,19> |p=<-2978,1898,-292>, v=<-428,271,-47>, a=<30,-18,2> |p=<565,1062,-2232>, v=<80,152,-315>, a=<-4,-10,28> |p=<-1305,1305,-2694>, v=<-183,186,-382>, a=<14,-14,26> |p=<-2484,-273,-1989>, v=<-359,-35,-283>, a=<23,4,18> |p=<1136,-1048,-2857>, v=<166,-150,-410>, a=<-9,9,30> |p=<-442,2206,2090>, v=<-64,315,301>, a=<4,-22,-14> |p=<-23,2898,224>, v=<-3,412,30>, a=<0,-26,1> |p=<2138,959,-1982>, v=<306,140,-283>, a=<-19,-9,17> |p=<-1618,1775,-1360>, v=<-231,253,-191>, a=<22,-18,12> |p=<692,1924,-2492>, v=<99,278,-361>, a=<-6,-17,28> |p=<-1023,2364,-1752>, v=<-142,340,-247>, a=<10,-19,19> |p=<-1750,-2698,1145>, v=<-246,-382,167>, a=<17,25,-11> |p=<3258,1100,-180>, v=<470,158,-26>, a=<-32,-13,0> |p=<-1915,-679,-2235>, v=<-273,-97,-323>, a=<21,9,24> |p=<-1104,-2081,-786>, v=<-155,-297,-113>, a=<11,22,10> |p=<-2858,-640,-706>, v=<-406,-90,-100>, a=<29,5,4> |p=<712,1716,-1986>, v=<102,248,-284>, a=<-7,-17,19> |p=<832,2700,-390>, v=<120,385,-55>, a=<-5,-26,3> |p=<1587,-619,2627>, v=<223,-84,375>, a=<-17,4,-28> |p=<2298,470,2118>, v=<325,62,302>, a=<-16,-8,-19> |p=<-2057,-1407,-2233>, v=<-288,-204,-317>, a=<25,14,26> |p=<-112,-62,2758>, v=<-13,-5,397>, a=<1,-2,-23> |p=<-211,-2054,2162>, v=<-32,-291,309>, a=<6,20,-24> |p=<2083,836,1594>, v=<299,118,228>, a=<-18,-8,-17> |p=<-530,2090,1973>, v=<-76,302,278>, a=<4,-26,-24> |p=<-1080,1942,-1900>, v=<-158,279,-272>, a=<6,-19,19> |p=<-2074,1278,1789>, v=<-301,186,250>, a=<14,-11,-18> |p=<-520,2504,414>, v=<-74,354,60>, a=<-2,-25,-7> |p=<-1176,-2282,-1591>, v=<-170,-326,-228>, a=<16,15,15> |p=<102,2968,990>, v=<12,427,146>, a=<-7,-32,-10> |p=<-2709,1659,-316>, v=<-389,241,-39>, a=<31,-9,1> |p=<-2290,1919,773>, v=<-329,275,105>, a=<22,-16,-12> |p=<615,482,3245>, v=<85,69,463>, a=<-10,0,-27> |p=<1234,2456,-1243>, v=<178,346,-177>, a=<-9,-21,9> |p=<1114,1679,1730>, v=<164,240,248>, a=<-12,-15,-17> |p=<-1422,1522,-1711>, v=<-208,209,-244>, a=<9,-15,21> |p=<2007,-1374,485>, v=<285,-201,69>, a=<-22,17,-4> |p=<-12,2520,544>, v=<-1,362,74>, a=<0,-26,-10> |p=<-474,-1923,2315>, v=<-67,-270,334>, a=<2,18,-21> |p=<1517,-2248,-418>, v=<216,-314,-59>, a=<-14,22,3> |p=<1118,2532,-1334>, v=<159,361,-189>, a=<-12,-25,13> |p=<-1489,-1372,-2353>, v=<-219,-200,-337>, a=<15,18,21> |p=<1056,25,-2775>, v=<149,1,-398>, a=<-17,0,27> |p=<-2726,1082,-1224>, v=<-389,153,-169>, a=<27,-7,12> |p=<751,608,-2592>, v=<102,88,-374>, a=<-6,-7,24> |p=<1945,2317,-136>, v=<276,331,-18>, a=<-23,-24,4> |p=<-3253,69,-228>, v=<-462,11,-36>, a=<36,0,-1> |p=<1255,-2938,-313>, v=<183,-419,-45>, a=<-8,26,7> |p=<-2646,2011,-797>, v=<-380,287,-109>, a=<25,-21,2> |p=<50,-1406,-2557>, v=<5,-198,-362>, a=<6,15,24> |p=<348,-1005,2940>, v=<51,-140,420>, a=<-2,7,-29> |p=<-672,2846,-1419>, v=<-97,402,-207>, a=<6,-28,11> |p=<2859,1440,-24>, v=<408,201,-9>, a=<-27,-21,2> |p=<2157,-1843,429>, v=<313,-263,61>, a=<-22,19,-4> |p=<45,-1064,2940>, v=<6,-158,419>, a=<1,12,-29> |p=<1730,987,-1830>, v=<247,143,-264>, a=<-19,-7,17> |p=<-1122,-1149,2253>, v=<-165,-161,322>, a=<12,11,-25> |p=<2676,-601,-785>, v=<380,-86,-115>, a=<-30,5,8> |p=<2435,-555,-1288>, v=<348,-80,-183>, a=<-24,6,12> |p=<1305,-81,2894>, v=<185,-10,413>, a=<-13,-4,-30> |p=<954,-2008,1396>, v=<140,-292,199>, a=<-9,25,-10> |p=<-133,2590,984>, v=<-19,374,140>, a=<0,-23,-10> |p=<1389,-2086,-2054>, v=<194,-296,-293>, a=<-16,18,19> |p=<-296,-2831,566>, v=<-37,-404,82>, a=<-2,24,1> |p=<-2569,-802,-1287>, v=<-369,-113,-183>, a=<28,10,10> |p=<-1886,1812,-2154>, v=<-266,255,-307>, a=<15,-17,26> |p=<-1719,-1231,1420>, v=<-244,-174,204>, a=<20,14,-18> |p=<-2888,-1394,1274>, v=<-412,-202,183>, a=<28,13,-14> |p=<1984,1660,1284>, v=<287,237,179>, a=<-19,-18,-16> |p=<-41,200,2573>, v=<-4,31,370>, a=<-1,-2,-25> |p=<-3016,34,-1363>, v=<-429,1,-190>, a=<31,-5,13> |p=<-1286,-763,2011>, v=<-183,-107,287>, a=<11,1,-21> |p=<-1848,1908,-618>, v=<-265,274,-87>, a=<19,-22,11> |p=<-688,2384,-207>, v=<-98,336,-29>, a=<7,-22,0> |p=<281,847,-2885>, v=<40,121,-412>, a=<-1,-11,25> |p=<192,-2453,-1601>, v=<31,-355,-222>, a=<-1,24,17> |p=<491,2203,2548>, v=<68,315,367>, a=<-5,-21,-28> |p=<-2321,-624,-555>, v=<-336,-90,-81>, a=<23,6,-1> |p=<-432,-3152,-213>, v=<-63,-450,-31>, a=<-2,31,1> |p=<-1867,1915,-782>, v=<-266,270,-110>, a=<22,-19,7> |p=<-892,-2127,-2359>, v=<-122,-311,-337>, a=<5,25,26> |p=<-941,2518,-1279>, v=<-140,360,-182>, a=<10,-25,11> |p=<1469,340,-3429>, v=<209,48,-490>, a=<-13,0,38> |p=<673,3163,673>, v=<101,451,95>, a=<-8,-34,-1> |p=<800,1337,2614>, v=<114,193,371>, a=<-2,-15,-24> |p=<1261,1722,-2285>, v=<179,249,-326>, a=<-14,-19,19> |p=<1473,-2386,-1740>, v=<210,-340,-248>, a=<-13,21,17> |p=<1905,2345,936>, v=<269,330,128>, a=<-21,-27,-8> |p=<-9,-2986,506>, v=<2,-426,74>, a=<0,29,-4> |p=<1104,2001,1666>, v=<158,286,238>, a=<-11,-20,-14> |p=<-497,-2214,2033>, v=<-66,-314,293>, a=<5,22,-13> |p=<209,-2513,-1928>, v=<29,-361,-273>, a=<-3,23,23> |p=<3148,-137,-45>, v=<452,-16,-6>, a=<-34,1,1> |p=<-738,-382,3098>, v=<-105,-51,440>, a=<8,2,-30> |p=<1401,2701,793>, v=<200,387,112>, a=<-11,-26,-11> |p=<-2116,-937,-1839>, v=<-303,-136,-266>, a=<19,9,20> |p=<686,-763,-3088>, v=<104,-117,-443>, a=<-6,10,27> |p=<-1078,-2695,1808>, v=<-150,-381,252>, a=<7,28,-22> |p=<-1664,-680,2702>, v=<-238,-102,384>, a=<19,8,-26> |p=<-2971,-700,1101>, v=<-431,-98,157>, a=<25,6,-11> |p=<-403,-2013,-1424>, v=<-57,-286,-197>, a=<-1,18,14> |p=<-248,-2160,-1597>, v=<-35,-308,-228>, a=<3,22,15> |p=<-1239,983,-1956>, v=<-175,136,-272>, a=<12,-11,20> |p=<1358,2352,2015>, v=<192,333,283>, a=<-8,-18,-14> |p=<-513,-2703,-1005>, v=<-72,-384,-140>, a=<3,26,14> |p=<1677,2614,-393>, v=<239,372,-55>, a=<-15,-26,2> |p=<568,-2323,1735>, v=<77,-333,241>, a=<-4,20,-10> |p=<2487,1279,-308>, v=<353,188,-42>, a=<-24,-12,9> |p=<1009,316,2729>, v=<136,46,389>, a=<-7,-7,-26> |p=<2442,-775,2407>, v=<345,-111,344>, a=<-25,7,-21> |p=<-936,2174,2023>, v=<-134,305,289>, a=<12,-18,-18> |p=<-731,-714,-2746>, v=<-104,-100,-390>, a=<0,5,30> |p=<422,-3337,-414>, v=<63,-477,-61>, a=<-4,31,4> |p=<1873,1735,-1252>, v=<270,244,-174>, a=<-22,-15,15> |p=<-2135,-1673,-1094>, v=<-306,-239,-155>, a=<21,18,13> |p=<-327,-2234,1998>, v=<-44,-322,283>, a=<1,22,-22> |p=<1599,722,1794>, v=<228,102,260>, a=<-16,-7,-17> |p=<749,-3446,-111>, v=<114,-490,-13>, a=<-9,35,1>""".stripMargin val input = input1 + input2 }
parwen68/advent-of-code-2017
shared/src/test/scala/se/parwen/adoc/day17/SolverSpec.scala
<reponame>parwen68/advent-of-code-2017 package se.parwen.adoc.day17 import org.scalatest._ class SolverSpec extends FlatSpec with Matchers { "The Solver move 3 from pos 0 in buffer [0]" should "be 0" in { val buffer = List(0) Solver.move(0, 3, buffer.size) should be (0) } "The Solver move 3 from pos 1 in buffer [0, 1]" should "be 0" in { val buffer = List(0, 1) Solver.move(1, 3, buffer.size) should be (0) } "The Solver move 3 from pos 1 in buffer [0, 2, 1]" should "be 1" in { val buffer = List(0, 2, 1) Solver.move(1, 3, buffer.size) should be (1) } "The Solver move 3 from pos 1 in buffer [0, 2, 3, 1]" should "be 0" in { val buffer = List(0, 2, 3, 1) Solver.move(1, 3, buffer.size) should be (0) } "The Solver insert 3 at 1 in buffer [0, 1, 2, 3]" should "be [0, 3, 1, 2, 3]" in { val buffer = List(0, 1, 2, 3) Solver.insert(1, 3, buffer) should be (List(0,3,1,2,3)) } "The Solver insert 2 at 0 in buffer [0, 1, 2, 3]" should "be [2, 0, 1, 2, 3]" in { val buffer = List(0, 1, 2, 3) Solver.insert(0, 2, buffer) should be (List(2,0,1,2,3)) } "The Solver insert 4 at 4 in buffer [0, 1, 2, 3]" should "be [0, 1, 2, 3, 4]" in { val buffer = List(0, 1, 2, 3) Solver.insert(4, 4, buffer) should be (List(0,1,2,3,4)) } "The Solver solve (3, 1)" should "be 0,(1)" in { Solver.solve(3, 1) should be ((List(0,1), 1)) } "The Solver solve (3, 2)" should "be 0,(2),1" in { Solver.solve(3, 2) should be ((List(0,2,1), 1)) } "The Solver solve (3, 3)" should "be 0, 2, (3), 1" in { Solver.solve(3, 3) should be ((List(0, 2, 3, 1), 2)) } "The Solver solve (3, 4)" should "be 0 2 (4) 3 1" in { Solver.solve(3, 4) should be ((List(0, 2, 4, 3, 1), 2)) } "The Solver solve (3, 5)" should "be 0 (5) 2 4 3 1" in { Solver.solve(3, 5) should be ((List(0, 5, 2, 4, 3, 1), 1)) } "The Solver solveStep1 (3, 3)" should "be 1" in { Solver.solveStep1(3, 3) should be (1) } "The Solver solveStep1 (3, 4)" should "be 3" in { Solver.solveStep1(3, 4) should be (3) } "The Solver solveStep1 (3, 5)" should "be 2" in { Solver.solveStep1(3, 5) should be (2) } "The Solver solveStep1 (3, 2017)" should "be 638" in { Solver.solveStep1(3, 2017) should be (638) } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day19/Solver.scala
package se.parwen.adoc.day19 object Solver { sealed trait Direction trait HDirection extends Direction trait VDirection extends Direction case object Up extends VDirection case object Down extends VDirection case object Left extends HDirection case object Right extends HDirection case class Path(arr: Array[Array[Char]]) { def apply(x: Int, y: Int): Char = arr(y)(x) def start: (Int, Int) = (arr(0).indexOf('|'),0) } def parse(input: String): Path = { val lines = input.split('\n') val maxLineLength = lines.map(_.length).max Path(lines.map(s => s.padTo(maxLineLength, ' ').toCharArray)) } def solve(input: String): (String, Int) = { val path = parse(input) def contLeft(x: Int,y: Int) = path(x-1,y) != ' ' def contRight(x: Int,y: Int) = path(x+1,y) != ' ' def contUp(x: Int,y: Int) = path(x,y-1) != ' ' def contDown(x: Int,y: Int) = path(x,y+1) != ' ' def loop(x: Int, y: Int, d: Direction, acc: List[Char] = List(), cnt: Int = 0) : (String, Int) = { (path(x,y), d) match { case (' ', _) => (acc.filter(c => c.isLetter).mkString, cnt) case ('+', d : VDirection) if contLeft(x,y) => loop(x-1,y,Left, acc, cnt+1) case ('+', d : VDirection) if contRight(x,y) => loop(x+1,y,Right, acc, cnt+1) case ('+', d : HDirection) if contUp(x,y) => loop(x,y-1,Up, acc, cnt+1) case ('+', d : HDirection) if contDown(x,y) => loop(x,y+1,Down, acc, cnt+1) case (c ,Down) => loop(x, y + 1, Down, acc :+ c, cnt+1) case (c, Up) => loop(x, y - 1, Up, acc :+ c, cnt+1) case (c, Left) => loop(x - 1, y, Left, acc :+ c, cnt+1) case (c, Right) => loop(x + 1, y, Right, acc :+ c, cnt+1) } } val (x,y) = path.start loop(x,y,Down) } def solveStep1(input: String): String = { solve(input)._1 } def solveStep2(input: String): Int = { solve(input)._2 } } trait Solver19 { def solve19(): Unit = { println("Day 19:") val result1 = Solver.solveStep1(Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.input) println(s"step 2 result is $result2") } } object Main extends Solver19 { def main(args: Array[String]): Unit = { solve19() } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day6/Solver.scala
<filename>shared/src/main/scala/se/parwen/adoc/day6/Solver.scala package se.parwen.adoc.day6 object Solver { def stream(value: Int, length: Int, count: Int = 0) : Stream[Int] = { if (count == length) Stream.empty else Math.ceil(value.asInstanceOf[Double] / length).asInstanceOf[Int] #:: stream(value-1, length, count + 1) } def solveStep1(input: List[Int]): Int = { def loop(acc: List[List[Int]], list: List[Int]) : Int = { val (max, idx) = (list.max, list.indexOf(list.max)) val dist = stream(list(idx), list.length).toList val shifted = dist.takeRight(idx + 1) ++ dist.dropRight(idx + 1) val nextList = list.updated(idx, 0).zip(shifted).map {case (a,b) => a + b} if (acc contains nextList) acc.length else loop(nextList :: acc, nextList) } loop(List(input), input) } def solveStep2(input: List[Int]): Int = { def loop(acc: List[List[Int]], list: List[Int]) : Int = { val (max, idx) = (list.max, list.indexOf(list.max)) val dist = stream(list(idx), list.length).toList val shifted = dist.takeRight(idx + 1) ++ dist.dropRight(idx + 1) val nextList = list.updated(idx, 0).zip(shifted).map {case (a,b) => a + b} if (acc contains nextList) { val firstIdx = acc.indexOf(nextList) firstIdx + 1 } else loop(nextList :: acc, nextList) } loop(List(input), input) } } trait Solver6 { def solve6() { println("Day 6:") val result1 = Solver.solveStep1(List(0,5,10,0,11,14,13,4,11,8,8,7,1,4,12,11)) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(List(0,5,10,0,11,14,13,4,11,8,8,7,1,4,12,11)) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day17/Input.scala
package se.parwen.adoc.day17 object Input { }
parwen68/advent-of-code-2017
build.sbt
enablePlugins(ScalaJSPlugin) name := "advent-of-code-2017" version := "1.0" scalaVersion in ThisBuild := "2.12.4" lazy val root = project.in(file(".")). aggregate(adocJS, adocJVM). settings( publish := {}, publishLocal := {} ) lazy val adoc = crossProject.in(file(".")). settings( name := "advent-of-code", version := "1.0-SNAPSHOT", libraryDependencies += { "org.scalatest" %% "scalatest" % "3.0.4" % "test" } ). jvmSettings( // mainClass in Compile := Some("se.parwen.adoc.day13.Main") ). jsSettings( //scalaJSUseMainModuleInitializer := true ) lazy val adocJVM = adoc.jvm lazy val adocJS = adoc.js
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day3/Solver.scala
package se.parwen.adoc.day3 object Solver { val directions: Stream[String] = "R" #:: "U" #:: "L" #:: "D" #:: directions val multipliers: Stream[Int] = Stream.from(1).flatMap(i => Stream(i, i)) def moves: Stream[Char] = multipliers.zip(directions).flatMap { case (multiplier, direction) => direction * multiplier } case class Pos(x:Int, y:Int) { def left: Pos = copy(x = x - 1) def up: Pos = copy(y = y + 1) def right: Pos = copy(x = x + 1) def down: Pos = copy(y = y - 1) } def nextPos(pos: Pos, c: Char): Pos = c match { case 'L' => pos.left case 'R' => pos.right case 'U' => pos.up case 'D' => pos.down } def solveStep1(target: Int): Int = { import java.lang.Math.abs val endPos = (moves take target - 1).toList.foldLeft(Pos(0, 0)){case (pos, c) => nextPos(pos, c) } abs(endPos.x) + abs(endPos.y) } def solveStep2(target: Int): Int = { def sum(pos: Pos, m: Map[Pos, Int]): Int = { List(pos.left, pos.right, pos.up, pos.down, pos.left.up, pos.right.up, pos.left.down, pos.right.down) .map(m.getOrElse(_, 0)).sum } def loop(map: Map[Pos, Int], p: Pos, v: Int, m: Stream[Char]) : Int = m match { case c #:: tail if v < target => val np = nextPos(p, c) val s = sum(np, map) loop(map ++ Map{np -> s}, np, s, tail) case _ => v } loop(Map{Pos(0,0) -> 1}, Pos(0,0), 1, moves) } } trait Solver3 { def solve3(): Unit = { println("Day 3:") val result1 = Solver.solveStep1(289326) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(289326) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day18/Input.scala
package se.parwen.adoc.day18 object Input { val input = """set i 31 |set a 1 |mul p 17 |jgz p p |mul a 2 |add i -1 |jgz i -2 |add a -1 |set i 127 |set p 735 |mul p 8505 |mod p a |mul p 129749 |add p 12345 |mod p a |set b p |mod b 10000 |snd b |add i -1 |jgz i -9 |jgz a 3 |rcv b |jgz b -1 |set f 0 |set i 126 |rcv a |rcv b |set p a |mul p -1 |add p b |jgz p 4 |snd a |set a b |jgz 1 3 |snd b |set f 1 |add i -1 |jgz i -11 |snd a |jgz f -16 |jgz a -19""".stripMargin }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day15/Solver.scala
<filename>shared/src/main/scala/se/parwen/adoc/day15/Solver.scala package se.parwen.adoc.day15 object Solver { def generator(start: Long, factor: Long) : () => Long = { var prev = start () => { val next = prev * factor % 2147483647 prev = next next } } def doMatch(first: Long, second: Long): Boolean = (first & 0xffff) == (second & 0xffff) def solveStep1(aStart: Int, bStart: Int): Int = { val genA = generator(aStart, 16807) val genB = generator(bStart, 48271) def loop(cnt: Long, matched: Int = 0) : Int= { if (cnt == 0) matched else loop(cnt - 1, matched + (if (doMatch(genA(), genB())) 1 else 0)) } loop(40000000L) } def multGenerator(gen: () => Long, multiplier: Long) : () => Long = { () => { def loop(next: Long): Long = { if(next % multiplier == 0) next else loop(gen()) } loop(gen()) } } def solveStep2(aStart: Int, bStart: Int): Int = { val genA = generator(aStart, 16807) val genB = generator(bStart, 48271) (0L until 5000000).toStream.count(_ => doMatch(multGenerator(genA, 4)(), multGenerator(genB, 8)())) } } trait Solver15 { def solve15(): Unit = { println("Day 15:") val result1 = Solver.solveStep1(Input.input('A'), Input.input('B')) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.input('A'), Input.input('B')) println(s"step 2 result is $result2") } } object Main extends Solver15 { def main(args: Array[String]): Unit = { solve15() } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day4/Solver.scala
<gh_stars>0 package se.parwen.adoc.day4 object Solver { def isSame(a: Array[String]): Boolean = { val b = a.foldLeft(Map[String,Int]())((m,v) => m.updated(v, m.getOrElse(v,0) + 1)) b.values.max == 1 } def isAnagram(a: Array[String]): Boolean = { for (w1 <- a) { for (w2 <- a) { if (w1 != w2 && w1.sorted == w2.sorted) { return false } } } true } def solveStep1(input: String): Int = { def isValid(str: String) = { isSame(str.split("\\s+")) } input.split('\n').filter(s => !s.isEmpty).map(pp => (pp, isValid(pp))).count(p => p._2) } def solveStep2(input: String): Int = { def isValid(str: String) = { val a = str.split("\\s+") isSame(a) && isAnagram(a) } input.split('\n').filter(s => !s.isEmpty).map(pp => (pp, isValid(pp))).count(p => p._2) } } trait Solver4 { def solve4(): Unit = { println("Day 4:") val result1 = Solver.solveStep1(Input.input) println(s"step 1 result is $result1") val result2 = Solver.solveStep2(Input.input) println(s"step 2 result is $result2") } }
parwen68/advent-of-code-2017
shared/src/main/scala/se/parwen/adoc/day2/Adv2.scala
package se.parwen.adoc.day2 object Adv2 { val inputStr = """1224 926 1380 688 845 109 118 88 1275 1306 91 796 102 1361 27 995 |1928 2097 138 1824 198 117 1532 2000 1478 539 1982 125 1856 139 475 1338 |848 202 1116 791 1114 236 183 186 150 1016 1258 84 952 1202 988 866 |946 155 210 980 896 875 925 613 209 746 147 170 577 942 475 850 |1500 322 43 95 74 210 1817 1631 1762 128 181 716 171 1740 145 1123 |3074 827 117 2509 161 206 2739 253 2884 248 3307 2760 2239 1676 1137 3055 |183 85 143 197 243 72 291 279 99 189 30 101 211 209 77 198 |175 149 259 372 140 250 168 142 146 284 273 74 162 112 78 29 |169 578 97 589 473 317 123 102 445 217 144 398 510 464 247 109 |3291 216 185 1214 167 495 1859 194 1030 3456 2021 1622 3511 222 3534 1580 |2066 2418 2324 93 1073 82 102 538 1552 962 91 836 1628 2154 2144 1378 |149 963 1242 849 726 1158 164 1134 658 161 1148 336 826 1303 811 178 |3421 1404 2360 2643 3186 3352 1112 171 168 177 146 1945 319 185 2927 2289 |543 462 111 459 107 353 2006 116 2528 56 2436 1539 1770 125 2697 2432 |1356 208 5013 4231 193 169 3152 2543 4430 4070 4031 145 4433 4187 4394 1754 |5278 113 4427 569 5167 175 192 3903 155 1051 4121 5140 2328 203 5653 3233""".stripMargin def main(args: Array[String]): Unit = { def div(arr: Array[Int]): Int ={ for (elem1 <- arr) { for (elem2 <- arr) { if (elem1 != elem2 && elem1 % elem2 == 0) { println(s"${elem1} ${elem2} ${elem1/elem2}") return elem1 / elem2 } } } throw new RuntimeException() } println(inputStr.split('\n').map(s => s.split("\\s+").map(_.toInt)).map(a => div(a)).sum) }}
0xmycf/fabric-mod-scala-template
src/main/scala/com/username/modid/language_adapter/CustomLanguageAdapter.scala
<gh_stars>0 package com.username.modid.language_adapter import net.fabricmc.loader.api.{LanguageAdapter, ModContainer} class CustomLanguageAdapter extends LanguageAdapter { override def create[T](mod: ModContainer, value: String, aClass: Class[T]): T = Class.forName(value + "$").getField("MODULE$").get(null).asInstanceOf[T] }
0xmycf/fabric-mod-scala-template
src/main/scala/com/username/modid/blocks/ModIdBlocks.scala
package com.username.modid.blocks import com.username.modid.MainFile import net.minecraft.block.{AbstractBlock, Block, Blocks} import net.minecraft.item.{BlockItem, Item, ItemGroup} import net.minecraft.util.Identifier import net.minecraft.util.registry.Registry import scala.collection.mutable object ModIdBlocks { private val BlockItemsRegistry = mutable.LinkedHashMap[String, Item]() //linkedMapOf<String, Item>() private val BlockRegistry = mutable.LinkedHashMap[String, Block]() /** * Register blocks here. * [net.minecraft.item.BlockItem]'s gets added automatically (but can't be referenced atm). * If you wish to change the settings of the BlockItem implement your own methods for it. */ val COOL_BLOCK: Block = addBlock("coolblock", new Block(AbstractBlock.Settings.copy(Blocks.STONE))) private def addBlock[B <: Block](name: String, block: B): B = { val correctedName = name.replace(" ", "").toLowerCase.trim BlockRegistry.put(correctedName, block) BlockItemsRegistry.put(correctedName + "_item", new BlockItem(block, new Item.Settings().maxCount(64).group(ItemGroup.MISC))) block } def registerBlocks(): Unit = { this.BlockRegistry.foreach { it => Registry.register(Registry.BLOCK, new Identifier(MainFile.MOD_ID, it._1), it._2) } def registerBlockItems(): Unit = { this.BlockItemsRegistry.foreach { it => Registry.register(Registry.ITEM, new Identifier(MainFile.MOD_ID, it._1), it._2) } } registerBlockItems() } }
0xmycf/fabric-mod-scala-template
src/main/scala/com/username/modid/MainFile.scala
<reponame>0xmycf/fabric-mod-scala-template<filename>src/main/scala/com/username/modid/MainFile.scala package com.username.modid import com.username.modid.blocks.ModIdBlocks import com.username.modid.items.ModIdItems import net.fabricmc.api.ModInitializer /** * Main File * VM options for mixins: * -Dmixin.debug.export=true (exports mixins into run/mixin.out/) * -Dmixin.debug=true (turns on all debugging features) */ object MainFile extends ModInitializer { given MOD_ID: String = "modid" override def onInitialize(): Unit = { ModIdBlocks.registerBlocks() ModIdItems.registerItems() } }
0xmycf/fabric-mod-scala-template
src/main/scala/com/username/modid/items/ModIdItems.scala
<reponame>0xmycf/fabric-mod-scala-template package com.username.modid.items import com.username.modid.MainFile import net.minecraft.item.{Item, ItemGroup} import net.minecraft.util.Identifier import net.minecraft.util.registry.Registry object ModIdItems { private val ItemRegistry = collection.mutable.LinkedHashMap[String, Item]() /** * Register [net.minecraft.item.Item]'s in here. */ val COOL_ITEM: Item = addItem("coolitem", new Item(new Item.Settings().maxCount(64).group(ItemGroup.MISC))) private def addItem[I <: Item](name: String, item: I): I = { val correctedName = name.replace(" ", "").toLowerCase.trim ItemRegistry.put(correctedName, item) item } def registerItems(): Unit = { this.ItemRegistry.foreach { it => Registry.register(Registry.ITEM, new Identifier(MainFile.MOD_ID, it._1), it._2) } } }
0xmycf/fabric-mod-scala-template
src/main/scala/com/username/modid/MainFileClient.scala
package com.username.modid import net.fabricmc.api.{ClientModInitializer, EnvType, Environment} @Environment(EnvType.CLIENT) object MainFileClient extends ClientModInitializer { override def onInitializeClient(): Unit = { } }
jerneyio/data-weave-native
native-cli/src/test/scala/org/mule/weave/dwnative/cli/DataWeaveCLITest.scala
package org.mule.weave.dwnative.cli import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.PrintStream import org.scalatest.FreeSpec import org.scalatest.Matchers import scala.io.Source class DataWeaveCLITest extends FreeSpec with Matchers { "should work with output application/json" in { val out = System.out try { val stream = new ByteArrayOutputStream() System.setOut(new PrintStream(stream, true)) new DataWeaveCLIRunner().run(Array("output application/json --- (1 to 3)[0]")) val source = Source.fromBytes(stream.toByteArray, "UTF-8") val result = source.mkString result.trim shouldBe "1" } finally { System.setOut(out) println("Finish OK 3") } } "should work with simple script and not output" in { val defaultOut = System.out try { val stream = new ByteArrayOutputStream() System.setOut(new PrintStream(stream, true)) new DataWeaveCLIRunner().run(Array("(1 to 3)[0]")) val source = Source.fromBytes(stream.toByteArray, "UTF-8") val result = source.mkString result.trim shouldBe "1" } finally { System.setOut(defaultOut) } } "should work ok when sending payload from stdin" in { val out = System.out val in = System.in try { val input = """[ | 1, | 2, | 3 |] """.stripMargin.trim val stream = new ByteArrayOutputStream() System.setOut(new PrintStream(stream, true)) System.setIn(new ByteArrayInputStream(input.getBytes("UTF-8"))) new DataWeaveCLIRunner().run(Array("payload[0]")) val source = Source.fromBytes(stream.toByteArray, "UTF-8") val result = source.mkString.trim source.close() result.trim shouldBe "1" } finally { System.setOut(out) System.setIn(in) println("Finish OK 2") } } }
jerneyio/data-weave-native
native-common/src/main/scala/org/mule/weave/dwnative/NativeRuntime.scala
<filename>native-common/src/main/scala/org/mule/weave/dwnative/NativeRuntime.scala package org.mule.weave.dwnative import java.io.File import java.io.OutputStream import java.io.PrintWriter import java.io.StringWriter import org.mule.weave.v2.interpreted.module.WeaveDataFormat import org.mule.weave.v2.model.ServiceManager import org.mule.weave.v2.model.service.StdOutputLoggingService import org.mule.weave.v2.model.values.BinaryValue import org.mule.weave.v2.module.reader.AutoPersistedOutputStream import org.mule.weave.v2.module.reader.DefaultAutoPersistedOutputStream import org.mule.weave.v2.module.reader.SourceProvider import org.mule.weave.v2.parser.ast.variables.NameIdentifier import org.mule.weave.v2.parser.exception.LocatableException import org.mule.weave.v2.parser.phase.CompilationException import org.mule.weave.v2.parser.phase.ModuleLoaderManager import org.mule.weave.v2.runtime.DataWeaveScriptingEngine import org.mule.weave.v2.runtime.DynamicModuleComponentFactory import org.mule.weave.v2.runtime.ExecuteResult import org.mule.weave.v2.runtime.InputType import org.mule.weave.v2.runtime.ScriptingBindings import org.mule.weave.v2.sdk.ClassLoaderWeaveResourceResolver class NativeRuntime(libDir: File, path: Array[File]) { private val pathBasedResourceResolver = PathBasedResourceResolver(path ++ Option(libDir.listFiles()).getOrElse(new Array[File](0))) private val weaveScriptingEngine = DataWeaveScriptingEngine(DynamicModuleComponentFactory(ClassLoaderWeaveResourceResolver(), () => pathBasedResourceResolver, systemFirst = true)) def getResourceContent(ni: NameIdentifier): Option[String] = { pathBasedResourceResolver.resolve(ni).map(_.content()) } def run(script: String, inputs: ScriptingBindings): WeaveExecutionResult = { run(script, inputs, new DefaultAutoPersistedOutputStream()) } def run(script: String, inputs: ScriptingBindings, out: OutputStream, defaultOutputMimeType: String = "application/json"): WeaveExecutionResult = { try { val dataWeaveScript = weaveScriptingEngine.compile(script, NameIdentifier.ANONYMOUS_NAME, inputs.entries().map((wi) => new InputType(wi, None)).toArray) val serviceManager = ServiceManager(StdOutputLoggingService) val result = dataWeaveScript.write(inputs, serviceManager, dataWeaveScript.declaredOutput().getOrElse(defaultOutputMimeType), Some(out)) WeaveSuccessResult(out, result.getCharset().name()) } catch { case cr: CompilationException => { WeaveFailureResult(cr.getMessage()) } case le: LocatableException => { WeaveFailureResult(le.getMessage() + " at:\n" + le.location.locationString) } case le: Exception => { val writer = new StringWriter() le.printStackTrace() le.printStackTrace(new PrintWriter(writer)) WeaveFailureResult("Internal error : " + le.getClass.getName + " : " + le.getMessage + "\n" + writer.toString) } } } def eval(script: String, inputs: ScriptingBindings): ExecuteResult = { val dataWeaveScript = weaveScriptingEngine.compile(script, NameIdentifier.ANONYMOUS_NAME, inputs.entries().map((wi) => new InputType(wi, None)).toArray) val serviceManager = ServiceManager(StdOutputLoggingService) dataWeaveScript.exec(inputs, serviceManager) } } case class WeaveInput(name: String, content: SourceProvider) sealed trait WeaveExecutionResult { def result(): String def success(): Boolean } case class WeaveSuccessResult(outputStream: OutputStream, charset: String) extends WeaveExecutionResult { override def success(): Boolean = true override def result(): String = { outputStream match { case ap: AutoPersistedOutputStream => { new String(BinaryValue.getBytesFromSeekableStream(ap.toInputStream, true), charset) } } } } case class WeaveFailureResult(message: String) extends WeaveExecutionResult { override def success(): Boolean = false override def result(): String = message } class CustomWeaveDataFormat(moduleManager: ModuleLoaderManager) extends WeaveDataFormat { override def createModuleLoader(): ModuleLoaderManager = moduleManager } case class WeaveRunnerConfig(path: Array[String], debug: Boolean, scriptToRun: Option[String], main: Option[String], inputs: Map[String, SourceProvider], outputPath: Option[String])
jerneyio/data-weave-native
dependency-manager/src/main/scala/org/weave/deps/DependencyAnnotationProcessor.scala
package org.weave.deps import java.io.File import java.nio.file.Files import coursier.MavenRepository import coursier._ import coursier.cache.ArtifactError import coursier.cache.Cache import coursier.core.Authentication import coursier.util.Gather import coursier.util.Task import org.mule.weave.v2.parser.MessageCollector import org.mule.weave.v2.parser.ast.AstNode import org.mule.weave.v2.parser.ast.LiteralValueAstNode import org.mule.weave.v2.parser.ast.annotation.AnnotationNode import org.mule.weave.v2.parser.ast.variables.NameIdentifier import org.mule.weave.v2.parser.phase.AnnotationProcessor import org.mule.weave.v2.scope.AstNavigator import org.mule.weave.v2.scope.ScopesNavigator import scala.concurrent.ExecutionContext.Implicits.global class DependencyAnnotationProcessor(targetDirectory: File) extends AnnotationProcessor { /** * Run the annotation processing logic on the scope navigation phase */ override def run(annotatedNode: AstNode, astNavigator: AstNavigator, scopeNavigator: ScopesNavigator, messageCollector: MessageCollector, annotation: AnnotationNode): Unit = { val homeUser = new File(System.getProperty("user.home")) val repositories = Seq( MavenRepository(new File(homeUser, ".m2/repository").getAbsolutePath), MavenRepository("http://repository.mulesoft.org/nexus/content/repositories/snapshots/", changing = Some(true)), MavenRepository( "https://maven.anypoint.mulesoft.com/api/v1/organizations/142ebe1a-6e25-4670-9220-0cdce791f1b8/maven", authentication = Some(Authentication("machaval", "3lg0rd0FC"))), MavenRepository("https://repo1.maven.org/maven2")) val parts = annotation.args.get.args.head.value.asInstanceOf[LiteralValueAstNode].literalValue.split(':') println("Trying to Downloading: " + parts) val start = Resolution(Seq(Dependency(Module(Organization(parts(0)), ModuleName(parts(1))), parts(2)))) val fetch = ResolutionProcess.fetch(repositories, Cache.default.fetch) val resolution = start.process.run(fetch).unsafeRun() val localArtifacts: Either[ArtifactError, File] = Gather[Task] .gather(resolution.artifacts().map(Cache.default.file(_).run)) .unsafeRun() .head localArtifacts match { case Left(ae) => { println(ae.message) } case Right(file) => { Files.move(file.toPath, targetDirectory.toPath) } } } } object DependencyAnnotationProcessor { val ANNOTATION_NAME = NameIdentifier("dw::deps::Deps::Dependency") }
jerneyio/data-weave-native
native-common/src/main/scala/org/mule/weave/dwnative/DataWeaveUtils.scala
package org.mule.weave.dwnative import java.io.File import org.mule.weave.v2.env.StaticServiceProvider import org.mule.weave.v2.env.WeaveRuntime import org.mule.weave.v2.model.ServiceRegistration import org.mule.weave.v2.module.DataFormat import org.mule.weave.v2.module.csv.CSVDataFormat import org.mule.weave.v2.module.json.JsonDataFormat import org.mule.weave.v2.module.multipart.MultiPartDataFormat import org.mule.weave.v2.module.native.NativeValueProvider import org.mule.weave.v2.module.octetstream.OctetStreamDataFormat import org.mule.weave.v2.module.properties.PropertiesDataFormat import org.mule.weave.v2.module.textplain.TextPlainDataFormat import org.mule.weave.v2.module.xml.XmlDataFormat import org.mule.weave.v2.parser.phase.ModuleLoaderManager import org.mule.weave.v2.runtime.core.SystemNativeValueProvider import org.mule.weave.v2.runtime.core.functions.ReadFunctionProtocolHandler import org.mule.weave.v2.runtime.core.functions.UrlProtocolHandler object DataWeaveUtils { def getDWHome(): File = { val homeUser = new File(System.getProperty("user.home")) val weavehome = System.getenv("DW_HOME") if (weavehome != null) { val home = new File(weavehome) if (!home.exists()) { println(AnsiColor.red(s"[error] Weave Home Directory `${weavehome}` declared on environment variable `WEAVE_HOME` does not exists.")) } home } else { if (WeaveProperties.verbose) { println("[debug] Env not working trying home directory") } val defaultDWHomeDir = new File(homeUser, ".dw") if (defaultDWHomeDir.exists()) { defaultDWHomeDir } else { println(AnsiColor.yellow(s"[warning] Unable to detect Weave Home directory so local directory is going to be used. Please either define the env variable WEAVE_HOME or copy the weave distro into `${defaultDWHomeDir.getAbsolutePath}`.")) new File("..") } } } def getLibPathHome(): File = { val weavehome = System.getenv("DW_LIB_PATH") if (weavehome != null) { val home = new File(weavehome) if (!home.exists()) { println(AnsiColor.red(s"[error] Weave Library Home Directory `${weavehome}` declared on environment variable `DW_LIB_PATH` does not exists.")) } home } else { new File(getDWHome(), "libs") } } def setupServices(moduleLoaderManager: ModuleLoaderManager): Unit = { val services: Map[Class[_], Seq[_]] = Map( classOf[NativeValueProvider] -> Seq(new SystemNativeValueProvider()), //Native Functions classOf[DataFormat[_, _]] -> Seq( new CSVDataFormat, new JsonDataFormat, new XmlDataFormat, new CustomWeaveDataFormat(moduleLoaderManager), new TextPlainDataFormat, new OctetStreamDataFormat, new PropertiesDataFormat, new MultiPartDataFormat), classOf[ServiceRegistration[_]] -> Seq(), classOf[ReadFunctionProtocolHandler] -> Seq(new UrlProtocolHandler()) ) //Configure static provider WeaveRuntime.setServiceProvider(new StaticServiceProvider(services)) } } object WeaveProperties { var verbose: Boolean = false }
jerneyio/data-weave-native
native-common/src/main/scala/org/mule/weave/dwnative/PathBasedResourceResolver.scala
package org.mule.weave.dwnative import java.io.File import java.util.zip.ZipFile import org.mule.weave.v2.parser.ast.variables.NameIdentifier import org.mule.weave.v2.sdk.WeaveResource import org.mule.weave.v2.sdk.WeaveResourceResolver import org.mule.weave.v2.utils.WeaveConstants import org.mule.weave.v2.utils.WeaveFile import scala.collection.mutable import scala.io.Source class PathBasedResourceResolver(paths: Seq[File]) extends WeaveResourceResolver { def loadResources(): Map[NameIdentifier, Seq[WeaveResource]] = { val result = mutable.ArrayBuffer[(NameIdentifier, WeaveResource)]() paths .foreach(f = (pathEntryFile) => { if (pathEntryFile.isFile) { val zipFile = new ZipFile(pathEntryFile) val entries = zipFile.entries while (entries.hasMoreElements) { val entry = entries.nextElement val path = entry.getName if (!entry.isDirectory && path.endsWith(WeaveFile.fileExtension)) { val identifier = NameIdentifier.fromPath(path) val stream = zipFile.getInputStream(entry) val source = Source.fromInputStream(stream, WeaveConstants.default_encoding) try { result.+=((identifier, WeaveResource(path, source.mkString))) } finally { source.close() } } } } else if (pathEntryFile.isDirectory) { //Load file from directory val rootPath = pathEntryFile.getAbsolutePath recursiveListFiles( pathEntryFile, (f) => { val relativeName = f.getAbsolutePath.substring(rootPath.length + 1) val source = Source.fromFile(f, WeaveConstants.default_encoding) try { val resource = WeaveResource.apply(f.getAbsolutePath, source.mkString) result.+=((NameIdentifier.fromPath(relativeName), resource)) } finally { source.close() } }) } }) val identifierToResources = result.groupBy(_._1).mapValues(_.map(_._2)) identifierToResources } def recursiveListFiles[T](f: File, callback: (File) => Unit): Unit = { val files = f.listFiles if (files != null) { files.foreach((f) => if (f.isFile && f.getName.endsWith(WeaveFile.fileExtension)) { callback(f) } else if (f.isDirectory) { recursiveListFiles(f, callback) }) } } lazy val entries: Map[NameIdentifier, Seq[WeaveResource]] = loadResources() override def resolve(name: NameIdentifier): Option[WeaveResource] = { entries.get(name).flatMap(_.headOption) } override def resolveAll(name: NameIdentifier): Seq[WeaveResource] = { entries.getOrElse(name, Seq()) } } object PathBasedResourceResolver { def apply(libDir: File): PathBasedResourceResolver = { if (libDir.exists()) { val files = libDir.listFiles() if (files != null) { new PathBasedResourceResolver(files) } else { new PathBasedResourceResolver(Seq()) } } else { new PathBasedResourceResolver(Seq()) } } def apply(paths: Seq[File]): PathBasedResourceResolver = new PathBasedResourceResolver(paths) }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part12.scala
package parts import common.printer.printHeader /** * Created by michal on 1/1/15. * The Neophyte's Guide to Scala Part 12: Type Classes */ object part12 extends App { //The problem { printHeader("The problem") { object Statistics { def median(xs: Vector[Double]): Double = xs(xs.size / 2) def quartiles(xs: Vector[Double]): (Double, Double, Double) = (xs(xs.size / 4), median(xs), xs(xs.size / 4 * 3)) def iqr(xs: Vector[Double]): Double = quartiles(xs) match { case (lowerQuartile, _, upperQuartile) => upperQuartile - lowerQuartile } def mean(xs: Vector[Double]): Double = { xs.reduce(_ + _) / xs.size } } } { object Statistics { def median(xs: Vector[Number]): Number = ??? def quartiles(xs: Vector[Number]): (Number, Number, Number) = ??? def iqr(xs: Vector[Number]): Number = ??? def mean(xs: Vector[Number]): Number = ??? } } //Adapter pattern { object Statistics { trait NumberLike[A] { def get: A def plus(y: NumberLike[A]): NumberLike[A] def minus(y: NumberLike[A]): NumberLike[A] def divide(y: Int): NumberLike[A] } case class NumberLikeDouble(x: Double) extends NumberLike[Double] { def get: Double = x def minus(y: NumberLike[Double]) = NumberLikeDouble(x - y.get) def plus(y: NumberLike[Double]) = NumberLikeDouble(x + y.get) def divide(y: Int) = NumberLikeDouble(x / y) } type Quartile[A] = (NumberLike[A], NumberLike[A], NumberLike[A]) def median[A](xs: Vector[NumberLike[A]]): NumberLike[A] = xs(xs.size / 2) def quartiles[A](xs: Vector[NumberLike[A]]): Quartile[A] = (xs(xs.size / 4), median(xs), xs(xs.size / 4 * 3)) def iqr[A](xs: Vector[NumberLike[A]]): NumberLike[A] = quartiles(xs) match { case (lowerQuartile, _, upperQuartile) => upperQuartile.minus(lowerQuartile) } def mean[A](xs: Vector[NumberLike[A]]): NumberLike[A] = xs.reduce(_.plus(_)).divide(xs.size) } } } //Type classes to the rescue! { printHeader("Type classes to the rescue!") //Creating a type class { object Math { trait NumberLike[T] { def plus(x: T, y: T): T def divide(x: T, y: Int): T def minus(x: T, y: T): T } } } //Providing default members { object Math { import annotation.implicitNotFound @implicitNotFound("No member of type class NumberLike in scope for ${T}") trait NumberLike[T] { def plus(x: T, y: T): T def divide(x: T, y: Int): T def minus(x: T, y: T): T } object NumberLike { implicit object NumberLikeDouble extends NumberLike[Double] { def plus(x: Double, y: Double): Double = x + y def divide(x: Double, y: Int): Double = x / y def minus(x: Double, y: Double): Double = x - y } implicit object NumberLikeInt extends NumberLike[Int] { def plus(x: Int, y: Int): Int = x + y def divide(x: Int, y: Int): Int = x / y def minus(x: Int, y: Int): Int = x - y } } } //Coding against type classes { printHeader("Coding against type classes") object Statistics { import Math.NumberLike def mean[T](xs: Vector[T])(implicit ev: NumberLike[T]): T = ev.divide(xs.reduce(ev.plus(_, _)), xs.size) } val numbers = Vector[Double](13, 23.0, 42, 45, 61, 73, 96, 100, 199, 420, 900, 3839) println(Statistics.mean(numbers)) //compilation error => No member of type class NumberLike in scope for String // val snumbers = Vector[String]("13", "23.0", "42", "45", "61", "73", "96", "100", "199", "420", "900", "3839") // println(Statistics.mean(snumbers)) } //Context bounds { printHeader("Context bounds") object Statistics { import Math.NumberLike def mean[T](xs: Vector[T])(implicit ev: NumberLike[T]): T = ev.divide(xs.reduce(ev.plus(_, _)), xs.size) //context bound def median[T : NumberLike](xs: Vector[T]): T = xs(xs.size / 2) def quartiles[T: NumberLike](xs: Vector[T]): (T, T, T) = (xs(xs.size / 4), median(xs), xs(xs.size / 4 * 3)) def iqr[T: NumberLike](xs: Vector[T]): T = quartiles(xs) match { case (lowerQuartile, _, upperQuartile) => implicitly[NumberLike[T]].minus(upperQuartile, lowerQuartile) } } //Custom type class members { printHeader("Custom type class members") object JodaImplicits { import Math.NumberLike import org.joda.time.Duration implicit object NumberLikeDuration extends NumberLike[Duration] { def plus(x: Duration, y: Duration): Duration = x.plus(y) def divide(x: Duration, y: Int): Duration = Duration.millis(x.getMillis / y) def minus(x: Duration, y: Duration): Duration = x.minus(y) } } import Statistics._ import JodaImplicits._ import org.joda.time.Duration._ val durations = Vector(standardSeconds(20), standardSeconds(57), standardMinutes(2), standardMinutes(17), standardMinutes(30), standardMinutes(58), standardHours(2), standardHours(5), standardHours(8), standardHours(17), standardDays(1), standardDays(4)) println(mean(durations).getStandardHours) } } } } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part10.scala
<gh_stars>0 package parts import common.printer.printHeader /** * Created by michal on 12/30/14. * The Neophyte's Guide to Scala Part 10: Staying DRY With Higher-order Functions */ object part10 extends App { // On higher-order functions // 1. One or more of its parameters is a function, and it returns some value. // 2. It returns a function, but none of its parameters is a function. // 3. Both of the above: One or more of its parameters is a function, and it returns a function. // And out of nowhere, a function was born { printHeader("And out of nowhere, a function was born") case class Email( subject: String, text: String, sender: String, recipient: String) type EmailFilter = Email => Boolean def newMailsForUser(mails: Seq[Email], f: EmailFilter) = mails.filter(f) val sentByOneOf: Set[String] => EmailFilter = senders => email => senders.contains(email.sender) val notSentByAnyOf: Set[String] => EmailFilter = senders => email => !senders.contains(email.sender) val minimumSize: Int => EmailFilter = n => email => email.text.size >= n val maximumSize: Int => EmailFilter = n => email => email.text.size <= n val emailFilter: EmailFilter = notSentByAnyOf(Set("<EMAIL>")) val mails = Email( subject = "It's me again, your stalker friend!", text = "Hello my friend! How are you?", sender = "<EMAIL>", recipient = "<EMAIL>") :: Nil val r = newMailsForUser(mails, emailFilter) // returns an empty list println(s"emails: $r") //Reusing existing functions { printHeader("Reusing existing functions") type SizeChecker = Int => Boolean val sizeConstraint: SizeChecker => EmailFilter = f => email => f(email.text.size) val minimumSize: Int => EmailFilter = n => sizeConstraint(_ >= n) val maximumSize: Int => EmailFilter = n => sizeConstraint(_ <= n) } //Function composition { printHeader("Function composition") def complement[A](predicate: A => Boolean) = (a: A) => !predicate(a) // val notSentByAnyOf = sentByOneOf andThen(g => complement(g)) val notSentByAnyOf = sentByOneOf andThen(complement(_)) //Composing predicates { printHeader("Composing predicates") def any[A](predicates: (A => Boolean)*): A => Boolean = a => predicates.exists(pred => pred(a)) def none[A](predicates: (A => Boolean)*) = complement(any(predicates: _*)) def every[A](predicates: (A => Boolean)*) = none(predicates.view.map(complement(_)): _*) val filter: EmailFilter = every( notSentByAnyOf(Set("<EMAIL>")), minimumSize(100), maximumSize(10000) ) } //Composing a transformation pipeline { printHeader("Composing a transformation pipeline") val addMissingSubject = (email: Email) => if (email.subject.isEmpty) email.copy(subject = "No subject") else email val checkSpelling = (email: Email) => email.copy(text = email.text.replaceAll("your", "you're")) val removeInappropriateLanguage = (email: Email) => email.copy(text = email.text.replaceAll("dynamic typing", "**CENSORED**")) val addAdvertismentToFooter = (email: Email) => email.copy(text = email.text + "\nThis mail sent via Super Awesome Free Mail") val pipeline = Function.chain(Seq( addMissingSubject, checkSpelling, removeInappropriateLanguage, addAdvertismentToFooter)) } } //Higher-order functions and partial functions { printHeader("Higher-order functions and partial functions") //Chaining partial functions printHeader("Chaining partial functions") // val handler = fooHandler orElse barHandler orElse bazHandler } } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part2.scala
package parts import common.printer.printHeader /** * Created by michal on 12/7/14. * The Neophyte's Guide to Scala Part 2: Extracting Sequences */ object part2 extends App { { printHeader("Pattern matches some number of elements") val xs = 3 :: 6 :: 12 :: Nil val r = xs match { case List(a, b) => a * b case List(a, b, c) => a + b + c case _ => 0 } println(r) } { printHeader("Pattern matches lists the exact length of which you don’t care") val xs = 3 :: 6 :: 12 :: 24 :: Nil val r = xs match { case List(a, b, _*) => a * b case _ => 0 } println(r) } //def unapplySeq(object: S): Option[Seq[T]] { printHeader("Example: Extracting given names") object GivenNames { def unapplySeq(name: String): Option[Seq[String]] = { val names = name.trim.split(" ") if (names.forall(_.isEmpty)) None else Some(names) } } def greetWithFirstName(name: String) = name match { case GivenNames(firstName, _*) => "Good morning, " + firstName + "!" case _ => "Welcome! Please make sure to fill in your name!" } println(greetWithFirstName("")) println(greetWithFirstName("Bob")) println(greetWithFirstName("<NAME>")) println(greetWithFirstName("<NAME>")) } //def unapplySeq(object: S): Option[(T1, .., Tn-1, Seq[T])] { printHeader("Combining fixed and variable parameter extraction") object Names { def unapplySeq(name: String): Option[(String, String, Seq[String])] = { val names = name.trim.split(" ") if (names.size < 2) None else Some((names.last, names.head, names.drop(1).dropRight(1).toSeq)) } } def greet(fullName: String) = fullName match { case Names(lastName, firstName, _*) => "Good morning, " + firstName + " " + lastName + "!" case _ => "Welcome! Please make sure to fill in your name!" } println(greet("")) println(greet("Bob")) println(greet("Bob LastName")) println(greet("<NAME> LastName")) println(greet("<NAME>ir LastName")) } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part3.scala
<reponame>mkunikowski/the-neophytes-guide-to-scala<filename>src/main/scala/parts/part3.scala package parts import common.printer.printHeader /** * Created by michal on 12/13/14. * The Neophyte's Guide to Scala Part 3: Patterns Everywhere */ object part3 extends App { //Pattern matching expressions { printHeader("Pattern matching expressions") case class Player(name: String, score: Int) def message(player: Player) = player match { case Player(_, score) if score > 100000 => "Get a job, dude!" case Player(name, _) => "Hey " + name + ", nice to see you again!" } def printMessage(player: Player) = println(message(player)) printMessage(Player("Gringo", 10)) } { printHeader("Patterns in value definitions") case class Player(name: String, score: Int) def doSomethingWithTheName(name: String) = println(s"Player name: $name") def currentPlayer(): Player = Player("Daniel", 3500) val player = currentPlayer() doSomethingWithTheName(player.name) val Player(pname, _) = currentPlayer() doSomethingWithTheName(pname) def scores: List[Int] = List() // val best :: rest = scores // println("The score of our champion is " + best) //error pattern doesn't match -> empty list def gameResult(): (String, Int) = ("Daniel", 3500) val result = gameResult() println(result._1 + ": " + result._2) //more readable val (name, score) = gameResult() println(name + ": " + score) } { printHeader("Patterns in for comprehensions") def gameResults(): Seq[(String, Int)] = ("Daniel", 3500) :: ("Melissa", 13000) :: ("John", 7000) :: Nil def hallOfFame = for { result <- gameResults() (name, score) = result if (score > 5000) } yield name println(s"hallOfFame: $hallOfFame") def hallOfFame2 = for { (name, score) <- gameResults() if (score > 5000) } yield name println(s"hallOfFame2: $hallOfFame2") val lists = List(1, 2, 3) :: List.empty :: List(5, 3) :: Nil val listSizes = for { list @ head :: _ <- lists } yield list.size println(s"list sizes without empty list: $listSizes") } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part5.scala
<reponame>mkunikowski/the-neophytes-guide-to-scala package parts import common.printer._ /** * Created by michal on 12/21/14. * The Neophyte's Guide to Scala Part 5: The Option Type */ object part5 extends App { case class User( id: Int, firstName: String, lastName: String, age: Int, gender: Option[String]) object UserRepository { private val users = Map(1 -> User(1, "John", "Doe", 32, Some("male")), 2 -> User(2, "Johanna", "Doe", 30, None)) def findById(id: Int): Option[User] = users.get(id) def findAll = users.values } { printHeader("Creating an option") val greetingSome: Option[String] = Some("Hello world") val greetingNone: Option[String] = None val absentGreeting: Option[String] = Option(null) // absentGreeting will be None val presentGreeting: Option[String] = Option("Hello!") // presentGreeting will be Some("Hello!") println(s"greetingSome: $greetingSome") println(s"greetingNone: $greetingNone") println(s"absentGreeting: $absentGreeting") println(s"presentGreeting: $presentGreeting") } { printHeader("Working with optional values") val user1 = UserRepository.findById(1) //bad access - stay away if (user1.isDefined) { println(user1.get.firstName) } // will print "John" printHeader("Providing a default value") val user = User(2, "Johanna", "Doe", 30, None) println("Gender: " + user.gender.getOrElse("not specified")) // will print "not specified" } { printHeader("Pattern matching") val user1 = User(2, "Johanna", "Doe", 30, None) user1.gender match { case Some(gender) => println("Gender: " + gender) case None => println("Gender: not specified") } val user2 = User(2, "Johanna", "Doe", 30, None) val gender = user2.gender match { case Some(gender) => gender case None => "not specified" } println("Gender: " + gender) } { printHeader("Options can be viewed as collections") { printHeader("Performing a side-effect if a value is present") val user4 = UserRepository.findById(2).foreach(user => println(user.firstName)) // prints "Johanna" println(user4) } { printHeader("Mapping an option") val age = UserRepository.findById(1).map(_.age) // age is Some(32) println(s"age: $age") } { printHeader("flatMap and options") val gender = UserRepository.findById(1).map(_.gender) // gender is an Option[Option[String]] println(s"gender: $gender") val gender1 = UserRepository.findById(1).flatMap(_.gender) // gender is Some("male") val gender2 = UserRepository.findById(2).flatMap(_.gender) // gender is None val gender3 = UserRepository.findById(3).flatMap(_.gender) // gender is None println(s"gender1: $gender1") println(s"gender2: $gender2") println(s"gender3: $gender3") val names: List[List[String]] = List(List("John", "Johanna", "Daniel"), List(), List("Doe", "Westheide")) val namesUpperCaseMap = names.map(_.map(_.toUpperCase)) // results in List(List("JOHN", "JOHANNA", "DANIEL"), List(), List("DOE", "WESTHEIDE")) val namesUpperCaseFlatMap = names.flatMap(_.map(_.toUpperCase)) // results in List("JOHN", "JOHANNA", "DANIEL", "DOE", "WESTHEIDE") println(s"namesUpperCaseMap: $namesUpperCaseMap") println(s"namesUpperCaseFlaMap: $namesUpperCaseFlatMap") val namesOpt: List[Option[String]] = List(Some("Johanna"), None, Some("Daniel")) val namesOptUpperCaseMap = namesOpt.map(_.map(_.toUpperCase)) // List(Some("JOHANNA"), None, Some("DANIEL")) val namesOptUpperCaseFlatMap = namesOpt.flatMap(xs => xs.map(_.toUpperCase)) // List("JOHANNA", "DANIEL") println(s"namesOptUpperCaseMap: $namesOptUpperCaseMap") println(s"namesOptUpperCaseFlaMap: $namesOptUpperCaseFlatMap") } } { printHeader("Filtering an option") val filter1 = UserRepository.findById(1).filter(_.age > 30) // None, because age is <= 30 val filter2 = UserRepository.findById(2).filter(_.age > 30) // Some(user), because age is > 30 val filter3 = UserRepository.findById(3).filter(_.age > 30) // None, because user is already None println(filter1) println(filter2) println(filter3) } { printHeader("For comprehensions") val genders = for { user <- UserRepository.findById(1) gender <- user.gender } yield gender // results in Some("male") println(genders) val allGenders = for { user <- UserRepository.findAll gender <- user.gender } yield gender println(allGenders) } { printHeader("Usage in the left side of a generator") val genders = for { User(_, _, _, _, Some(gender)) <- UserRepository.findAll } yield gender println(genders) } { printHeader("Chaining options") case class Resource(content: String) val resourceFromConfigDir: Option[Resource] = None val resourceFromClasspath: Option[Resource] = Some(Resource("I was found on the classpath")) val resource = resourceFromConfigDir orElse resourceFromClasspath println(resource) } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part11.scala
package parts import common.printer.printHeader /** * Created by michal on 12/30/14. * The Neophyte's Guide to Scala Part 11: Currying and Partially Applied Functions */ object part11 extends App { //Partially applied functions { printHeader("Partially applied functions") case class Email( subject: String, text: String, sender: String, recipient: String) type EmailFilter = Email => Boolean type IntPairPred = (Int, Int) => Boolean def sizeConstraint(pred: IntPairPred, n: Int, email: Email) = pred(email.text.size, n) val gt: IntPairPred = _ > _ val ge: IntPairPred = _ >= _ val lt: IntPairPred = _ < _ val le: IntPairPred = _ <= _ val eq: IntPairPred = _ == _ val minimumSize: (Int, Email) => Boolean = sizeConstraint(ge, _: Int, _: Email) val maximumSize: (Int, Email) => Boolean = sizeConstraint(le, _: Int, _: Email) val constr20: (IntPairPred, Email) => Boolean = sizeConstraint(_: IntPairPred, 20, _: Email) val constr30: (IntPairPred, Email) => Boolean = sizeConstraint(_: IntPairPred, 30, _: Email) //From methods to function objects { printHeader("From methods to function objects") val sizeConstraintFn: (IntPairPred, Int, Email) => Boolean = sizeConstraint _ } //Producing those EmailFilters { printHeader("Producing those EmailFilters") { val min20: EmailFilter = minimumSize(20, _: Email) val max20: EmailFilter = maximumSize(20, _: Email) } { val min20: EmailFilter = constr20(ge, _: Email) val max20: EmailFilter = constr20(le, _: Email) } } //Spicing up your functions { printHeader("Spicing up your functions") def sizeConstraint(pred: IntPairPred)(n: Int)(email: Email): Boolean = pred(email.text.size, n) val sizeConstraintFn: IntPairPred => Int => Email => Boolean = sizeConstraint _ val minSize: Int => Email => Boolean = sizeConstraint(ge) val maxSize: Int => Email => Boolean = sizeConstraint(le) { val min20: Email => Boolean = minSize(20) val max20: Email => Boolean = maxSize(20) } { val min20: Email => Boolean = sizeConstraintFn(ge)(20) val max20: Email => Boolean = sizeConstraintFn(le)(20) } } //Currying existing functions { printHeader("Currying existing functions") val sum: (Int, Int) => Int = _ + _ val sumCurried: Int => Int => Int = sum.curried } //Injecting your dependencies the functional way { printHeader("Injecting your dependencies the functional way") case class User(name: String) trait EmailRepository { def getMails(user: User, unread: Boolean): Seq[Email] } trait FilterRepository { def getEmailFilter(user: User): EmailFilter } trait MailboxService { def getNewMails(emailRepo: EmailRepository)(filterRepo: FilterRepository)(user: User) = emailRepo.getMails(user, true).filter(filterRepo.getEmailFilter(user)) val newMails: User => Seq[Email] } object MockEmailRepository extends EmailRepository { def getMails(user: User, unread: Boolean): Seq[Email] = Nil } object MockFilterRepository extends FilterRepository { def getEmailFilter(user: User): EmailFilter = _ => true } object MailboxServiceWithMockDeps extends MailboxService { val newMails: (User) => Seq[Email] = getNewMails(MockEmailRepository)(MockFilterRepository) _ } MailboxServiceWithMockDeps.newMails(User("daniel")) } } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part1.scala
<reponame>mkunikowski/the-neophytes-guide-to-scala package parts import common.printer.printHeader /** * Created by michal on 12/7/14. * The Neophyte's Guide to Scala Part 1: Extractors */ object part1 extends App { { printHeader("Extracting list values") case class User(firstName: String, lastName: String, score: Int) def advance(xs: List[User]) = xs match { case User(_, _, score1) :: User(_, _, score2) :: _ => score1 - score2 case _ => 0 } val harry = new User("Harry", "Potter", 30) val rubeus = new User("Rubeus", "Hagrid", 10) println("Harry Rubeus score diff: " + advance(List(harry, rubeus))) } //Extracting single value //def unapply(object: S): Some[(T1)] { printHeader("Extracting single value") trait User { def name: String } class FreeUser(val name: String) extends User class PremiumUser(val name: String) extends User object FreeUser { def unapply(user: FreeUser): Option[String] = Some(user.name) } object PremiumUser { def unapply(user: PremiumUser): Option[String] = Some(user.name) } println(FreeUser.unapply(new FreeUser("Daniel"))) val user: User = new PremiumUser("Daniel") val result = user match { case FreeUser(name) => "Hello " + name case PremiumUser(name) => "Welcome back, dear " + name } println(result) } //Extracting several values //def unapply(object: S): Option[(T1, ..., Tn)] { printHeader("Extracting several values") trait User { def name: String def score: Int } class FreeUser(val name: String, val score: Int, val upgradeProbability: Double) extends User class PremiumUser(val name: String, val score: Int) extends User object FreeUser { def unapply(user: FreeUser): Option[(String, Int, Double)] = Some((user.name, user.score, user.upgradeProbability)) } object PremiumUser { def unapply(user: PremiumUser): Option[(String, Int)] = Some((user.name, user.score)) } val user: User = new FreeUser("Daniel", 3000, 0.7d) val r = user match { case FreeUser(name, _, p) => if (p > 0.75) name + ", what can we do for you today?" else "Hello " + name case PremiumUser(name, _) => "Welcome back, dear " + name } println("" + r) } //A Boolean extractor //def unapply(object: S): Boolean { printHeader("A Boolean extractor") trait User { def name: String def score: Int override def toString = s"User(name: $name, score: $score)" } class FreeUser(val name: String, val score: Int, val upgradeProbability: Double) extends User class PremiumUser(val name: String, val score: Int) extends User object FreeUser { def unapply(user: FreeUser): Option[(String, Int, Double)] = Some((user.name, user.score, user.upgradeProbability)) } object PremiumUser { def unapply(user: PremiumUser): Option[(String, Int)] = Some((user.name, user.score)) } object premiumCandidate { def unapply(user: FreeUser): Boolean = user.upgradeProbability > 0.75 } def initiateSpamProgram(user: User) = println(s"initial spam program to user: $user") def sendRegularNewsletter(user: User) = println(s"initial spam program to user: $user") val user: User = new FreeUser("Daniel", 2500, 0.8d) user match { case freeUser @ premiumCandidate() => initiateSpamProgram(freeUser) case _ => sendRegularNewsletter(user) } } //Infix operation patterns { printHeader("Infix operation patterns") val xs = 58 #:: 43 #:: 93 #:: Stream.empty val r = xs match { case first #:: second #:: _ => first - second case _ => -1 } println(r) } // A closer look at the Stream extractor // Here is the complete extractor, taken from the sources of Scala 2.9.2: // object #:: { // def unapply[A](xs: Stream[A]): Option[(A, Stream[A])] = // if (xs.isEmpty) None // else Some((xs.head, xs.tail)) // } { printHeader("A closer look at the Stream extractor") val xs = 58 #:: 43 #:: 93 #:: Stream.empty val r = xs match { case #::(first, #::(second, _)) => first - second case _ => -1 } println(r) } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part13.scala
package parts import common.printer.printHeader /** * Created by michal on 1/2/15. * The Neophyte's Guide to Scala Part 13: Path-dependent Types */ object part13 extends App { //The problem { printHeader("The problem") object Franchise { case class Character(name: String) } class Franchise(name: String) { import Franchise.Character def createFanFiction(lovestruck: Character, objectOfDesire: Character): (Character, Character) = (lovestruck, objectOfDesire) } val starTrek = new Franchise("Star Trek") val starWars = new Franchise("Star Wars") val quark = Franchise.Character("Quark") val jadzia = Franchise.Character("<NAME>") val luke = Franchise.Character("Luke Skywalker") val yoda = Franchise.Character("Yoda") //Unfortunately, at the moment we are unable to prevent bad things from happening: starTrek.createFanFiction(lovestruck = jadzia, objectOfDesire = luke) { object Franchise { case class Character(name: String, franchise: Franchise) } class Franchise(name: String) { import Franchise.Character def createFanFiction( lovestruck: Character, objectOfDesire: Character): (Character, Character) = { require(lovestruck.franchise == objectOfDesire.franchise) (lovestruck, objectOfDesire) } } } } //Safer fiction with path-dependent types { printHeader("Safer fiction with path-dependent types") { class A { class B var b: Option[B] = None } val a1 = new A val a2 = new A val b1 = new a1.B val b2 = new a2.B a1.b = Some(b1) // a2.b = Some(b1) // does not compile } class Franchise(name: String) { case class Character(name: String) def createFanFictionWith(lovestruck: Character, objectOfDesire: Character): (Character, Character) = (lovestruck, objectOfDesire) } val starTrek = new Franchise("Star Trek") val starWars = new Franchise("Star Wars") val quark = starTrek.Character("Quark") val jadzia = starTrek.Character("<NAME>") val luke = starWars.Character("Luke Skywalker") val yoda = starWars.Character("Yoda") starTrek.createFanFictionWith(lovestruck = quark, objectOfDesire = jadzia) starWars.createFanFictionWith(lovestruck = luke, objectOfDesire = yoda) // starTrek.createFanFictionWith(lovestruck = jadzia, objectOfDesire = luke) // compilation error found : starWars.Character, required: starTrek.Character def createFanFiction(f: Franchise)(lovestruck: f.Character, objectOfDesire: f.Character) = (lovestruck, objectOfDesire) } //Abstract type members { printHeader("Abstract type members") object AwesomeDB { abstract class Key(name: String) { type Value } } import AwesomeDB.Key class AwesomeDB { import collection.mutable.Map val data = Map.empty[Key, Any] def get(key: Key): Option[key.Value] = data.get(key).asInstanceOf[Option[key.Value]] def set(key: Key)(value: key.Value): Unit = data.update(key, value) } trait IntValued extends Key { type Value = Int } trait StringValued extends Key { type Value = String } object Keys { val foo = new Key("foo") with IntValued val bar = new Key("bar") with StringValued } val dataStore = new AwesomeDB dataStore.set(Keys.foo)(23) val i: Option[Int] = dataStore.get(Keys.foo) // dataStore.set(Keys.foo)("23") // does not compile } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part7.scala
package parts import common.printer._ /** * Created by michal on 12/26/14. * The Neophyte's Guide to Scala Part 7: The Either Type */ object part7 extends App { //Creating an Either { printHeader("Creating an Either") import scala.io.Source import java.net.URL def getContent(url: URL): Either[String, Source] = if (url.getHost.contains("google")) Left("Requested URL is blocked for the good of the people!") else Right(Source.fromURL(url)) { printHeader("Working with Either values") getContent(new URL("http://google.com")) match { case Left(msg) => println(msg) case Right(source) => source.getLines.foreach(println) } } //Projections { printHeader("Projections") // You cannot, at least not directly, use an Either instance like a collection, // the way you are familiar with from Option and Try. // This is because Either is designed to be unbiased. { printHeader("Mapping") val content: Either[String, Iterator[String]] = getContent(new URL("http://danielwestheide.com")).right.map(_.getLines()) // content is a Right containing the lines from the Source returned by getContent val moreContent: Either[String, Iterator[String]] = getContent(new URL("http://google.com")).right.map(_.getLines) // moreContent is a Left, as already returned by getContent } { val content: Either[Iterator[String], Source] = getContent(new URL("http://danielwestheide.com")).left.map(Iterator(_)) // content is the Right containing a Source, as already returned by getContent val moreContent: Either[Iterator[String], Source] = getContent(new URL("http://google.com")).left.map(Iterator(_)) // moreContent is a Left containing the msg returned by getContent in an Iterator } //Flat mapping { printHeader("Flat mapping") val part5 = new URL("http://t.co/UR1aalX4") val part6 = new URL("http://t.co/6wlKwTmu") val content: Either[String, Either[String, Int]] = getContent(part5).right.map(a => getContent(part6).right.map(b => (a.getLines().size + b.getLines().size) / 2)) { val content: Either[String, Int] = getContent(part5).right.flatMap(a => getContent(part6).right.map(b => (a.getLines().size + b.getLines().size) / 2)) } } //For comprehensions { printHeader("For comprehensions") def averageLineCount(url1: URL, url2: URL): Either[String, Int] = for { source1 <- getContent(url1).right source2 <- getContent(url2).right } yield (source1.getLines().size + source2.getLines().size) / 2 { //error => won't comile // def averageLineCountWontCompile(url1: URL, url2: URL): Either[String, Int] = // for { // source1 <- getContent(url1).right // source2 <- getContent(url2).right // lines1 = source1.getLines().size // lines2 = source2.getLines().size // } yield (lines1 + lines2) / 2 // the same as // def averageLineCountDesugaredWontCompile(url1: URL, url2: URL): Either[String, Int] = // getContent(url1).right.flatMap { source1 => // getContent(url2).right.map { source2 => // val lines1 = source1.getLines().size // val lines2 = source2.getLines().size // (lines1, lines2) // }.map { case (x, y) => x + y / 2 } // } // The problem is that by including a value definition in our for comprehension, a new call to map is // introduced automatically – on the result of the previous call to map, which has returned an Either, // not a RightProjection. As you know, Either doesn’t define a map method, making the compiler a little bit grumpy. //fix { def averageLineCount(url1: URL, url2: URL): Either[String, Int] = for { source1 <- getContent(url1).right source2 <- getContent(url2).right lines1 <- Right(source1.getLines().size).right lines2 <- Right(source2.getLines().size).right } yield (lines1 + lines2) / 2 } } } } //Folding { printHeader("Folding") val content: Iterator[String] = getContent(new URL("http://danielwestheide.com")).fold(Iterator(_), _.getLines()) val moreContent: Iterator[String] = getContent(new URL("http://google.com")).fold(Iterator(_), _.getLines()) } } //When to use Either //Error handling { printHeader("Error handling") import scala.util.control.Exception.catching import java.net.URL //catch only certain type of exception def handling[Ex <: Throwable, T](exType: Class[Ex])(block: => T): Either[Ex, T] = catching(exType).either(block).asInstanceOf[Either[Ex, T]] import java.net.MalformedURLException def parseURL(url: String): Either[MalformedURLException, URL] = handling(classOf[MalformedURLException])(new URL(url)) //better do it with Try case class Customer(age: Int) class Cigarettes case class UnderAgeFailure(age: Int, required: Int) def buyCigarettes(customer: Customer): Either[UnderAgeFailure, Cigarettes] = if (customer.age < 16) Left(UnderAgeFailure(customer.age, 16)) else Right(new Cigarettes) // You should avoid using Either for wrapping unexpected exceptions. Try does that better, // without all the flaws you have to deal with when working with Either. } //Processing collections { printHeader("Processing collections") import java.net.URL type Citizen = String case class BlackListedResource(url: URL, visitors: Set[Citizen]) val blacklist = List( BlackListedResource(new URL("https://google.com"), Set("<NAME>", "<NAME>")), BlackListedResource(new URL("http://yahoo.com"), Set.empty), BlackListedResource(new URL("https://maps.google.com"), Set("<NAME>")), BlackListedResource(new URL("http://plus.google.com"), Set.empty) ) println(s"blacklist: $blacklist") val checkedBlacklist: List[Either[URL, Set[Citizen]]] = blacklist.map(resource => if (resource.visitors.isEmpty) Left(resource.url) else Right(resource.visitors)) println(s"checkedBlacklist $checkedBlacklist") val suspiciousResources = checkedBlacklist.flatMap(_.left.toOption) val problemCitizens = checkedBlacklist.flatMap(_.right.toOption).flatten.toSet println(s"suspiciousResources $suspiciousResources") println(s"problemCitizens $problemCitizens") } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part6.scala
package parts import common.printer._ /** * Created by michal on 12/22/14. * The Neophyte's Guide to Scala Part 6: Error Handling With Try */ object part6 extends App { //Throwing and catching exceptions { printHeader("Throwing and catching exceptions") case class Customer(age: Int) class Cigarettes case class UnderAgeException(message: String) extends Exception(message) def buyCigarettes(customer: Customer): Cigarettes = if (customer.age < 16) throw UnderAgeException(s"Customer must be older than 16 but was ${customer.age}") else new Cigarettes val youngCustomer = Customer(15) try { buyCigarettes(youngCustomer) "Yo, here are your cancer sticks! Happy smoking'!" } catch { case UnderAgeException(msg) => msg } } //Error handling, the functional way { //The semantics of Try printHeader("The semantics of Try") import scala.util.Try import java.net.URL def parseURL(url: String): Try[URL] = Try(new URL(url)) { //Working with Try values printHeader("Working with Try values") val url = parseURL("http://danielwestheide.com") getOrElse new URL("http://duckduckgo.com") println(url) } { //Chaining operations printHeader("Chaining operations") { //Mapping and flat mapping printHeader("Mapping and flat mapping") val r1 = parseURL("http://danielwestheide.com").map(_.getProtocol) // results in Success("http") println(r1) val r2 = parseURL("garbage").map(_.getProtocol) // results in Failure(java.net.MalformedURLException: no protocol: garbage) println(r2) import java.io.InputStream def inputStreamForURL(url: String): Try[Try[Try[InputStream]]] = parseURL(url).map { u => Try(u.openConnection()).map(conn => Try(conn.getInputStream)) } //using flat map to get Try[InputStream] def inputStreamForURLWithFlatMap(url: String): Try[InputStream] = parseURL(url).flatMap { u => Try(u.openConnection()).flatMap(conn => Try(conn.getInputStream)) } } { //Filter and foreach printHeader("Filter and foreach") def parseHttpURL(url: String) = parseURL(url).filter(_.getProtocol == "http") val r1 = parseHttpURL("http://apache.openmirror.de") // results in a Success[URL] val r2 = parseHttpURL("ftp://mirror.netcologne.de/apache.org") // results in a Failure[URL] println(r1) println(r2) parseHttpURL("http://danielwestheide.com").foreach(println) } { //For comprehensions printHeader("For comprehensions") import scala.io.Source def getURLContent(url: String): Try[Iterator[String]] = for { url <- parseURL(url) connection <- Try(url.openConnection()) is <- Try(connection.getInputStream) source = Source.fromInputStream(is) } yield source.getLines() val r = getURLContent("http://danielwestheide.com") println(r) { //Pattern Matching printHeader("Pattern Matching") import scala.util.Success import scala.util.Failure getURLContent("http://danielwestheide.com/foobar") match { case Success(lines) => lines.foreach(println) case Failure(ex) => println(s"Problem rendering URL content: ${ex.getMessage}") } } { //Recovering from a Failure printHeader("Recovering from a Failure") import java.net.MalformedURLException import java.io.FileNotFoundException val content = getURLContent("garbage") recover { case e: FileNotFoundException => Iterator("Requested page does not exist") case e: MalformedURLException => Iterator("Please make sure to enter a valid URL") case _ => Iterator("An unexpected error has occurred. We are so sorry!") } println(content) } } } } }
mkunikowski/the-neophytes-guide-to-scala
build.sbt
name := """the-neophytes-guide-to-scala""" version := "1.0" scalaVersion := "2.11.4" // Change this to another test framework if you prefer libraryDependencies += "org.scalatest" %% "scalatest" % "2.1.6" % "test" //Joda time libraryDependencies += "joda-time" % "joda-time" % "2.1" libraryDependencies += "org.joda" % "joda-convert" % "1.3" // Uncomment to use Akka //libraryDependencies += "com.typesafe.akka" % "akka-actor_2.11" % "2.3.3"
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part8.scala
<filename>src/main/scala/parts/part8.scala package parts import common.printer.printHeader /** * Created by michal on 12/27/14. * The Neophyte's Guide to Scala Part 8: Welcome to the Future */ object part8 extends App { //Why sequential code can be bad { printHeader("Why sequential code can be bad") import scala.util.Try // Some type aliases, just for getting more meaningful method signatures: type CoffeeBeans = String type GroundCoffee = String case class Water(temperature: Int) type Milk = String type FrothedMilk = String type Espresso = String type Cappuccino = String // dummy implementations of the individual steps: def grind(beans: CoffeeBeans): GroundCoffee = s"ground coffee of $beans" def heatWater(water: Water): Water = water.copy(temperature = 85) def frothMilk(milk: Milk): FrothedMilk = s"frothed $milk" def brew(coffee: GroundCoffee, heatedWater: Water): Espresso = "espresso" def combine(espresso: Espresso, frothedMilk: FrothedMilk): Cappuccino = "cappuccino" // some exceptions for things that might go wrong in the individual steps // (we'll need some of them later, use the others when experimenting // with the code): case class GrindingException(msg: String) extends Exception(msg) case class FrothingException(msg: String) extends Exception(msg) case class WaterBoilingException(msg: String) extends Exception(msg) case class BrewingException(msg: String) extends Exception(msg) // going through these steps sequentially: def prepareCappuccino(): Try[Cappuccino] = for { ground <- Try(grind("arabica beans")) water <- Try(heatWater(Water(25))) espresso <- Try(brew(ground, water)) foam <- Try(frothMilk("milk")) } yield combine(espresso, foam) //Working with Futures { printHeader("Working with Futures") import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global import scala.util.Random def grind(beans: CoffeeBeans): Future[GroundCoffee] = Future { println("start grinding...") Thread.sleep(Random.nextInt(2000)) if (beans == "baked beans") throw GrindingException("are you joking?") println("finished grinding...") s"ground coffee of $beans" } def heatWater(water: Water): Future[Water] = Future { println("heating the water now") Thread.sleep(Random.nextInt(2000)) println("hot, it's hot!") water.copy(temperature = 85) } def frothMilk(milk: Milk): Future[FrothedMilk] = Future { println("milk frothing system engaged!") Thread.sleep(Random.nextInt(2000)) println("shutting down milk frothing system") s"frothed $milk" } def brew(coffee: GroundCoffee, heatedWater: Water): Future[Espresso] = Future { println("happy brewing :)") Thread.sleep(Random.nextInt(2000)) println("it's brewed!") "espresso" } // definition of future // object Future { // def apply[T](body: => T)(implicit execctx: ExecutionContext): Future[T] // } //Callbacks { printHeader("Callbacks") grind("arabica beans").onSuccess { case ground => println("okay, got my ground coffee") } import scala.util.{Success, Failure} grind("baked beans").onComplete { case Success(ground) => println(s"got my $ground") case Failure(ex) => println("This grinder needs a replacement, seriously!") } } //Composing futures { printHeader("Composing futures") //Mapping the future { printHeader("Mapping the future") val temperatureOkay: Future[Boolean] = heatWater(Water(25)).map { water => println("we're in the future!") (80 to 85).contains(water.temperature) } } //Keeping the future flat def temperatureOkay(water: Water): Future[Boolean] = Future { (80 to 85).contains(water.temperature) } { printHeader("Keeping the future flat") //Use flatMap instead of map in order to get a Future[Boolean] instead of a Future[Future[Boolean]]: val nestedFuture: Future[Future[Boolean]] = heatWater(Water(25)).map { water => temperatureOkay(water) } val flatFuture: Future[Boolean] = heatWater(Water(25)).flatMap { water => temperatureOkay(water) } } //For comprehensions { printHeader("For comprehensions") val acceptable: Future[Boolean] = for { heatedWater <- heatWater(Water(25)) okay <- temperatureOkay(heatedWater) } yield okay } // If you have multiple computations that can be computed in parallel, you need to take care that // you already create the corresponding Future instances outside of the for comprehension. def prepareCappuccinoSequentially(): Future[Cappuccino] = { for { ground <- grind("arabica beans") water <- heatWater(Water(20)) foam <- frothMilk("milk") espresso <- brew(ground, water) } yield combine(espresso, foam) } // Hence, make sure to instantiate all your independent futures before the for comprehension: def prepareCappuccino(): Future[Cappuccino] = { val groundCoffee = grind("arabica beans") val heatedWater = heatWater(Water(20)) val frothedMilk = frothMilk("milk") for { ground <- groundCoffee water <- heatedWater foam <- frothedMilk espresso <- brew(ground, water) } yield combine(espresso, foam) } } } } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part4.scala
package parts import common.printer.printHeader /** * Created by michal on 12/13/14. * The Neophyte's Guide to Scala Part 4: Pattern Matching Anonymous Functions */ object part4 extends App { { printHeader("Pattern Matching Anonymous Functions") val songTitles = List("The White Hare", "Childe the Hunter", "Take no Rogues") val songTitlesLowerCase = songTitles.map(_.toLowerCase) println(s"Song titles lowercase: $songTitlesLowerCase") val wordFrequencies = ("habitual", 6) :: ("and", 56) :: ("consuetudinary", 2) :: ("additionally", 27) :: ("homely", 5) :: ("society", 13) :: Nil def wordsWithoutOutliers(wordFrequencies: Seq[(String, Int)]): Seq[String] = wordFrequencies.filter(wf => wf._2 > 3 && wf._2 < 25).map(_._1) val wwo = wordsWithoutOutliers(wordFrequencies) // List("habitual", "homely", "society") println(s"wordsWithoutOutliers: $wwo") def wordsWithoutOutliersWithPatternMatching(wordFrequencies: Seq[(String, Int)]): Seq[String] = wordFrequencies.filter { case (_, f) => f > 3 && f < 25 } map { case (w, _) => w } val wwopm = wordsWithoutOutliersWithPatternMatching(wordFrequencies) // List("habitual", "homely", "society") println(s"wordsWithoutOutliersWithPatternMatching: $wwopm") val predicate: (String, Int) => Boolean = { case (_, f) => f > 3 && f < 25 } val transformFn: (String, Int) => String = { case (w, _) => w } } { printHeader("Partial functions") //def collect[B](pf: PartialFunction[A, B]) val wordFrequencies = ("habitual", 6) :: ("and", 56) :: ("consuetudinary", 2) :: ("additionally", 27) :: ("homely", 5) :: ("society", 13) :: Nil val pf: PartialFunction[(String, Int), String] = { case (word, freq) if freq > 3 && freq < 25 => word } val pf2 = new PartialFunction[(String, Int), String] { def apply(wordFrequency: (String, Int)) = wordFrequency match { case (word, freq) if freq > 3 && freq < 25 => word } def isDefinedAt(wordFrequency: (String, Int)) = wordFrequency match { case (word, freq) if freq > 3 && freq < 25 => true case _ => false } } //pf == pf2 assert(wordFrequencies.collect(pf) == wordFrequencies.collect(pf2)) // wordFrequencies.map(pf) // will throw a MatchError val r = wordFrequencies.collect(pf) // List("habitual", "homely", "society") println(s"wordFrequencies.collect(pf): $r") def wordsWithoutOutliers(wordFrequencies: Seq[(String, Int)]): Seq[String] = wordFrequencies.collect { case (word, freq) if freq > 3 && freq < 25 => word } val r2 = wordsWithoutOutliers(wordFrequencies) println(s"wordsWithoutOutliers(wordFrequencies): $r2") } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/common/printer.scala
package common /** * Created by michal on 12/7/14. */ package object printer { def printHeader(header: String) = { val size = 80 val seperator = "-" val strHeader = "\n" + seperator * size + "\n" + header + "\n" + seperator * size + "\n" print(strHeader) } }
mkunikowski/the-neophytes-guide-to-scala
src/main/scala/parts/part9.scala
package parts import common.printer.printHeader import scala.concurrent.Future /** * Created by michal on 12/29/14. * The Neophyte's Guide to Scala Part 9: Promises and Futures in Practice */ object part9 extends App { //Promises { printHeader("Promises") import concurrent.Future import concurrent.ExecutionContext.Implicits.global val f: Future[String] = Future { "Hello world!" } // REPL output: // f: scala.concurrent.Future[String] = scala.concurrent.impl.Promise$DefaultPromise@793e6657 //Promising a rosy future { printHeader("Promising a rosy future") import concurrent.Promise case class TaxCut(reduction: Int) // either give the type as a type parameter to the factory method: val taxcut = Promise[TaxCut]() // or give the compiler a hint by specifying the type of your val: val taxcut2: Promise[TaxCut] = Promise() val taxcutF: Future[TaxCut] = taxcut.future //Completing a Promise { printHeader("Completing a Promise") //Delivering on your Promise { printHeader("Delivering on your Promise") taxcut.success(TaxCut(20)) object Government { def redeemCampaignPledge(): Future[TaxCut] = { val p = Promise[TaxCut]() Future { println("Starting the new legislative period.") Thread.sleep(2000) p.success(TaxCut(20)) println("We reduced the taxes! You must reelect us!!!!1111") } p.future } } import scala.util.{Success, Failure} val taxCutF: Future[TaxCut] = Government.redeemCampaignPledge() println("Now that they're elected, let's see if they remember their promises...") taxCutF.onComplete { case Success(TaxCut(reduction)) => println(s"A miracle! They really cut our taxes by $reduction percentage points!") case Failure(ex) => println(s"They broke their promises! Again! Because of a ${ex.getMessage}") } } //Breaking Promises like a sir { printHeader("Breaking Promises like a sir") case class LameExcuse(msg: String) extends Exception(msg) object Government { def redeemCampaignPledge(): Future[TaxCut] = { val p = Promise[TaxCut]() Future { println("Starting the new legislative period.") Thread.sleep(2000) p.failure(LameExcuse("global economy crisis")) println("We didn't fulfill our promises, but surely they'll understand.") } p.future } } } } } } //Future-based programming in practice { printHeader("Future-based programming in practice") //Blocking IO { printHeader("Blocking IO") // get back a Future[ResultSet] or something similar: // Future { // queryDB(query) //blocking code place in feature // } // So far, we always used the implicitly available global ExecutionContext to execute such future blocks. // It’s probably a good idea to create a dedicated ExecutionContext that you will have in scope in your database layer. // // You can create an ExecutionContext from a Java ExecutorService, // which means you will be able to tune the thread pool for executing your database calls asynchronously // independently from the rest of your application: import java.util.concurrent.Executors import concurrent.ExecutionContext val executorService = Executors.newFixedThreadPool(4) val executionContext = ExecutionContext.fromExecutorService(executorService) } //Long-running computations { printHeader("Long-running computations") // Depending on the nature of your application, it will occasionally have to call long-running tasks that don’t // involve any IO at all, which means they are CPU-bound. These, too, should not be executed by a web server thread. // Hence, you should turn them into Futures, too: // Future { // longRunningComputation(data, moreData) // } // Again, if you have long-running computations, having them run in a separate ExecutionContext for CPU-bound // tasks is a good idea. How to tune your various thread pools is highly dependent on your individual application // and beyond the scope of this article. } } }
akr4/diff-zip
src/main/scala/diff.scala
/* * Copyright 2012 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.physalis.diff_zip.diff import net.physalis.diff_zip.zip._ import java.io.File case class DiffResult( existsOnlyIn1: List[String], existsOnlyIn2: List[String], differentFiles: List[String] ) case class FileDiffResult( zip1: File, zip2: File, diffResult: DiffResult ) object Diff { def diff(zip1: File, zip2: File, detectDirectory: Boolean): FileDiffResult = { Zip.using(zip1) { e1 => Zip.using(zip2) { e2 => val r = diff(e1.toList, e2.toList, detectDirectory) FileDiffResult(zip1, zip2, r) } } } def diff(zip1: List[ZipEntry], zip2: List[ZipEntry], detectDirectory: Boolean): DiffResult = { def map(zip: List[ZipEntry]) = zip.filter { detectDirectory || !_.isDirectory }.map { e => (e.name, e) }.toMap val e1 = map(zip1) val e2 = map(zip2) val existsOnlyIn1 = diffKeys(e1, e2).toList.sorted val existsOnlyIn2 = diffKeys(e2, e1).toList.sorted val differentFiles = intersectKeys(e1, e2). filter { x => !(e1(x).digest sameElements e2(x).digest) }.toList.sorted DiffResult(existsOnlyIn1, existsOnlyIn2, differentFiles) } private def diffKeys[A](m1: Map[A, _], m2: Map[A, _]): Set[A] = m1.keys.toSet.diff(m2.keys.toSet) private def intersectKeys[A](m1: Map[A, _], m2: Map[A, _]): Set[A] = m1.keys.toSet.intersect(m2.keys.toSet) }
akr4/diff-zip
project/build.scala
<gh_stars>1-10 /* * Copyright 2012 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import sbt._ import sbt.Keys._ object MyBuild extends Build { val groupName = "diff-zip" def id(name: String) = "%s-%s" format(groupName, name) override val settings = super.settings :+ (shellPrompt := { s => Project.extract(s).currentProject.id + "> " }) val defaultSettings = Defaults.defaultSettings ++ Seq( version := "0.1", organization := "net.physalis", crossScalaVersions := Seq("2.9.0", "2.9.0-1", "2.9.1"), scalaVersion := "2.9.1", scalacOptions ++= Seq("-unchecked", "-deprecation") ) object Dependency { val basic = { Seq( "org.clapper" %% "argot" % "0.3.8" ) } val io = { val version = "0.3.0" Seq( "com.github.scala-incubator.io" %% "scala-io-core" % version, "com.github.scala-incubator.io" %% "scala-io-file" % version ) } val logging = Seq( "ch.qos.logback" % "logback-classic" % "0.9.25", "org.codehaus.groovy" % "groovy" % "1.8.0", "org.slf4j" % "slf4j-api" % "1.6.4", "org.clapper" %% "grizzled-slf4j" % "0.6.8" ) val test = Seq( "org.scalatest" %% "scalatest" % "1.6.1", "org.scalamock" %% "scalamock-scalatest-support" % "latest.integration" ).map { _ % "test" } val default = basic ++ io ++ logging ++ test } lazy val main = Project(groupName, file("."), settings = defaultSettings ++ Seq( libraryDependencies := Dependency.default, initialCommands := """ |import scalax.io._ |import scalax.file._ |import org.scala_tools.time.Imports._ """.stripMargin ) ++ com.github.retronym.SbtOneJar.oneJarSettings ) }
akr4/diff-zip
src/test/scala/diff-test.scala
<gh_stars>1-10 /* * Copyright 2012 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.physalis.diff_zip import zip._ import diff._ import org.scalatest.FunSuite case class TestingZipEntry( name: String, digest: Array[Byte], isDirectory: Boolean ) extends ZipEntry class DiffSuite extends FunSuite { val a = TestingZipEntry("a", Array(1), false) val b = TestingZipEntry("b", Array(2), false) val c = TestingZipEntry("c", Array(3), false) val SAME = DiffResult(List.empty, List.empty, List.empty) test("same") { val result = Diff.diff( List(a, b), List(a, b), false ) assert(result === SAME) } test("found in the other") { val result = Diff.diff( List(a, b), List(a, c), false ) assert(result === DiffResult( List("b"), List("c"), List.empty )) } test("diff") { val a2 = TestingZipEntry("a", Array(2), false) val result = Diff.diff( List(a), List(a2), false ) assert(result === DiffResult( List.empty, List.empty, List("a") )) } test("ignore directory") { val d1 = TestingZipEntry("d1", Array(1), true) val result = Diff.diff(List(d1), List.empty, false) assert(result === SAME) } test("detect directory") { val d1 = TestingZipEntry("d1", Array(1), true) val result = Diff.diff(List(d1), List.empty, true) assert(result === DiffResult(List("d1"), List.empty, List.empty)) } }
akr4/diff-zip
src/main/scala/zip.scala
<reponame>akr4/diff-zip /* * Copyright 2012 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.physalis.diff_zip.zip import scalax.io._ import resource._ import java.io.File import java.util.zip.ZipInputStream import java.util.zip.{ ZipEntry => JZE } object Zip { def using[A](file: File)(f: ZipEntries => A) = { managed(new ZipInputStream(new java.io.FileInputStream(file))).acquireAndGet { s => f(new ZipEntries(s)) } } } trait ZipEntry { val name: String val digest: Array[Byte] val isDirectory: Boolean } private case class ZipEntryImpl( private val underlying: JZE, digest: Array[Byte] ) extends ZipEntry { lazy val name = underlying.getName lazy val isDirectory = underlying.isDirectory } class ZipEntries private[zip](stream: ZipInputStream) extends collection.Traversable[ZipEntry] { import java.security.MessageDigest def foreach[U](f: ZipEntry => U) { var e = stream.getNextEntry; while(e != null) { val d = makeDigest(MessageDigest.getInstance("MD5"), stream) f(ZipEntryImpl(e, d)) e = stream.getNextEntry } @annotation.tailrec def makeDigest(d: MessageDigest, stream: ZipInputStream): Array[Byte] = { val buf = new Array[Byte](4096) val length = stream.read(buf) if (length > 0) { d.update(buf, 0, length) makeDigest(d, stream) } else { d.digest } } } }
akr4/diff-zip
src/main/scala/main.scala
<filename>src/main/scala/main.scala /* * Copyright 2012 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.physalis.diff_zip import zip._ import diff._ import java.io.File object Main { private def print(diff: FileDiffResult) { println("Files exist only in " + diff.zip1) println("===========================================") diff.diffResult.existsOnlyIn1.foreach(println) println("") println("Files exist only in " + diff.zip2) println("===========================================") diff.diffResult.existsOnlyIn2.foreach(println) println("") println("Files exist in both but not same") println("===========================================") diff.diffResult.differentFiles.foreach(println) } def main(args: Array[String]) { Args(args) match { case Right(Args(zip1, zip2, detectDirectory)) => print(Diff.diff(zip1, zip2, detectDirectory)) case Left(e) => println(e.message) } } } case class ArgsException(message: String) extends Exception case class Args(zip1: File, zip2: File, detectDirectory: Boolean) object Args { import org.clapper.argot._ import ArgotConverters._ def apply(args: Array[String]): Either[ArgsException, Args] = { val parser = new ArgotParser("diff-zip") implicit def toFile(s: String, opt: CommandLineArgument[File]) = { val f = new File(s) if (!f.exists) parser.usage(s + " not found.") f } val zip1 = parser.parameter[File]("ZIP1", "zip file 1", false) val zip2 = parser.parameter[File]("ZIP2", "zip file 2", false) val detectDirectory = parser.flag[Boolean](List("d", "detect-dir"), "Detect directory change") try { parser.parse(args) Right(Args(zip1.value.get, zip2.value.get, detectDirectory.value.getOrElse(false))) } catch { case e: ArgotUsageException => Left(ArgsException(e.message)) } } }
Panos-Bletsos/spark-tpcds-benchmark
build.sbt
name := "spark-tpcds-benchmark" version := "0.1" scalaVersion := "2.11.12" libraryDependencies ++= Seq( "com.typesafe" % "config" % "1.3.2", "com.databricks" %% "spark-sql-perf" % "0.5.0-SNAPSHOT", "org.apache.spark" %% "spark-core" % "2.2.0" % "provided", "org.apache.spark" %% "spark-sql" % "2.2.0" % "provided" ) lazy val app = (project in file("app")) .settings(mainClass in assembly := Some("bletsos.panos.App"))
Panos-Bletsos/spark-tpcds-benchmark
src/main/scala/bletsos/panos/App.scala
package bletsos.panos import com.databricks.spark.sql.perf.tpcds.{TPCDS, TPCDSTables} import com.typesafe.config.{Config, ConfigFactory} import org.apache.spark.sql.SparkSession object App { def main(args: Array[String]): Unit = { val conf: Config = ConfigFactory.load val spark: SparkSession = SparkSession .builder() .master(conf.getString("spark.master")) .appName("spark-tpcds-benchmark") .enableHiveSupport() .getOrCreate() // root directory of location to create data in val rootDir = conf.getString("dataGen.rootDir") // name of database to create. val databaseName = conf.getString("databaseName") // valid spark format like parquet "parquet". val format = conf.getString("dataGen.format") val tables = new TPCDSTables( spark.sqlContext, dsdgenDir = conf.getString("dataGen.dsdgenDir"), // location of dsdgen scaleFactor = conf.getString("dataGen.scaleFactor"), useDoubleForDecimal = false, // true to replace DecimalType with DoubleType useStringForDate = false) // true to replace DateType with StringType tables.genData( location = rootDir, format = format, overwrite = true, // overwrite the data that is already there partitionTables = true, // create the partitioned fact tables clusterByPartitionColumns = true, // shuffle to get partitions coalesced into single files. filterOutNullPartitionValues = false, // true to filter out the partition with NULL key value tableFilter = "", // "" means generate all tables numPartitions = 100) // how many dsdgen partitions to run - number of input tasks. spark.sql(s"create database if not exists $databaseName") tables.createExternalTables( rootDir, format, databaseName, overwrite = true, discoverPartitions = true) tables.analyzeTables(databaseName, analyzeColumns = true) val tpcds = new TPCDS (sqlContext = spark.sqlContext) val resultLocation = conf.getString("resultLocation") // place to write results val iterations = conf.getInt("iterations") // how many iterations of queries to run. val queries = tpcds.tpcds2_4Queries // queries to run. val timeout = 24 * 60 * 60 // timeout, in seconds. spark.sql(s"use $databaseName") val experiment = tpcds.runExperiment( queries, iterations = iterations, resultLocation = resultLocation, forkThread = conf.getBoolean("forkThread")) experiment.waitForFinish(timeout) } }
Amab/topias
src/main/scala/editor/CustomFontMetrics.scala
package editor import java.awt.font.FontRenderContext import java.awt.{Canvas, Font, FontMetrics, RenderingHints} import com.intellij.ide.ui.AntialiasingType import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.{EditorImpl, FontInfo} import com.intellij.util.ui.UIUtil import javax.swing.plaf.FontUIResource class CustomFontMetrics(val editor: Editor, val familyName: String, val size: Int) { lazy val font: FontUIResource = UIUtil.getFontWithFallback(familyName, Font.PLAIN, size) lazy val context: FontRenderContext = getCurrentContext(editor) lazy val metrics: FontMetrics = FontInfo.getFontMetrics(font, context) lazy val lineHeight: Int = Math.ceil(font.createGlyphVector(context, "Ap").getVisualBounds.getHeight).toInt def getFont: Font = metrics.getFont def getSymbolWidth: Int = { val metrics = new Canvas().getFontMetrics(font) metrics.charWidth('A') } def isActual(editor: Editor, familyName: String, size: Int): Boolean = { val font = metrics.getFont if (familyName != font.getFamily || size != font.getSize) return false val currentContext = getCurrentContext(editor) currentContext.equals(metrics.getFontRenderContext) } private def getCurrentContext(editor: Editor): FontRenderContext = { val editorContext = FontInfo.getFontRenderContext(editor.getContentComponent) new FontRenderContext(editorContext.getTransform, AntialiasingType.getKeyForCurrentScope(false), editor match { case impl: EditorImpl => impl.myFractionalMetricsHintValue case _ => RenderingHints.VALUE_FRACTIONALMETRICS_OFF }) } }
mijicd/declarative-concurrency
example/src/main/scala/lambdaconf/Transfer.scala
<reponame>mijicd/declarative-concurrency package lambdaconf import zio._ import zio.clock._ import zio.console._ import zio.duration._ import zio.stm._ /** * Problem: * - Alice has 1000$ on her account, while Bob has 0. * - Bob asks Alice to loan him 10000$. * - Alice receives 100$ every 10 milliseconds until the transfer completes. */ object Transfer extends App { type Account = TRef[Long] object Account { def make(initial: Long): UIO[Account] = TRef.makeCommit(initial) } def transfer(from: Account, to: Account, amount: Long): UIO[Any] = STM.atomically { for { currBalance <- from.get _ <- STM.check(currBalance >= amount) _ <- from.update(_ - amount) _ <- to.update(_ + amount) } yield () } def credit(account: Account, amount: Long): UIO[Any] = account.update(_ + amount).commit def run(args: List[String]): URIO[ZEnv, ExitCode] = { val program = for { alice <- Account.make(1000L) bob <- Account.make(0L) _ <- transfer(alice, bob, 10000L).race(credit(alice, 100L).repeat(Schedule.fixed(10.millis))) balanceAlice <- alice.get.commit balanceBob <- bob.get.commit _ <- putStrLn(s"Alice has $balanceAlice usd") _ <- putStrLn(s"Bob has $balanceBob usd") } yield () program.exitCode } }
mijicd/declarative-concurrency
example/src/main/scala/lambdaconf/Philosophers.scala
<filename>example/src/main/scala/lambdaconf/Philosophers.scala package lambdaconf import zio._ import zio.console._ import zio.stm._ object Philosophers extends App { case object Fork type Fork = Fork.type final case class Seat(left: TRef[Option[Fork]], right: TRef[Option[Fork]]) final case class Table(seats: Chunk[Seat]) extends AnyVal def takeForks(left: TRef[Option[Fork]], right: TRef[Option[Fork]]): USTM[(Fork, Fork)] = (left.get <*> right.get).flatMap { case (Some(l), Some(r)) => left.set(None) *> right.set(None).as((l, r)) case _ => STM.retry } def putForks(left: TRef[Option[Fork]], right: TRef[Option[Fork]])(forks: (Fork, Fork)): USTM[Unit] = (left.get <*> right.get).flatMap { case (None, None) => left.set(Some(forks._1)) *> right.set(Some(forks._2)) case _ => STM.retry } def setupTable(size: Int): UIO[Table] = { val makeFork = TRef.make[Option[Fork]](Some(Fork)) STM.atomically { for { forks0 <- STM.foreach(0 to size)(_ => makeFork) forks = forks0 ++ List(forks0(0)) seats = (forks zip forks.drop(1)).map { case (l, r) => Seat(l, r) } } yield Table(Chunk.fromIterable(seats)) } } def eat(philosopher: Int, roundtable: Table): URIO[Console, Unit] = { val placement = roundtable.seats(philosopher) val left = placement.left val right = placement.right for { forks <- takeForks(left, right).commit _ <- putStrLn(s"Philosopher $philosopher eating...") _ <- putForks(left, right)(forks).commit _ <- putStrLn(s"Philosopher $philosopher is done eating") } yield () } def run(args: List[String]): ZIO[ZEnv, Nothing, ExitCode] = { val count = 10 def eaters(table: Table): Iterable[URIO[Console, Unit]] = (1 to count).map(index => eat(index, table)) for { table <- setupTable(count) fiber <- ZIO.forkAll(eaters(table)) _ <- fiber.join _ <- putStrLn("All philosophers have eaten!") } yield ExitCode.success } }
mijicd/declarative-concurrency
example/src/main/scala/lambdaconf/PQueue.scala
package lambdaconf import zio._ import zio.console._ import zio.stm._ object PQueue extends App { final class PriorityQueue[A](minPriority: TRef[Int], map: TMap[Int, TQueue[A]]) { def offer(a: A, priority: Int): USTM[Unit] = for { queueM <- map.get(priority) queue <- queueM.fold(TQueue.unbounded[A])(STM.succeed(_)) _ <- queue.offer(a) _ <- map.put(priority, queue) _ <- minPriority.update(curr => if (curr > priority) priority else curr) } yield () def take: USTM[A] = { def increaseMin(curr: Int): USTM[Unit] = for { priorities <- map.delete(curr) *> map.keys newMin = priorities.minOption.getOrElse(Int.MaxValue) _ <- minPriority.set(newMin) } yield () for { curr <- minPriority.get queueM <- map.get(curr) queue <- queueM.fold(STM.retry: USTM[TQueue[A]])(STM.succeed(_)) a <- queue.take <* STM.whenM(queue.isEmpty)(increaseMin(curr)) } yield a } } object PriorityQueue { def make[A]: USTM[PriorityQueue[A]] = for { ref <- TRef.make(Int.MaxValue) map <- TMap.empty[Int, TQueue[A]] } yield new PriorityQueue(ref, map) } def run(args: List[String]): URIO[ZEnv, ExitCode] = { val program = for { _ <- putStrLn("Enter any key to exit...") pq <- PriorityQueue.make[String].commit _ <- makeOffers(pq, 3) _ <- makeOffers(pq, 0) _ <- pq.take.commit.flatMap(putStrLn(_)).forever.fork _ <- getStrLn } yield () program.exitCode } private def makeOffers(pq: PriorityQueue[String], priority: Int): UIO[Unit] = ZIO.foreach_(0 to 10)(i => pq.offer(s"Offer: $i with priority $priority", priority).commit) }
mijicd/declarative-concurrency
example/build.sbt
import Dependencies._ inThisBuild( List( scalaVersion := "2.13.1", organization := "com.github.mijicd" ) ) lazy val root = project .in(file(".")) .settings( libraryDependencies += "dev.zio" %% "zio" % "1.0.0-RC21-1" )
emartech/rdb-connector-common
src/test/scala/com/emarsys/rdb/connector/common/models/ConnectorSearchSpec.scala
<gh_stars>0 package com.emarsys.rdb.connector.common.models import akka.NotUsed import akka.stream.scaladsl.Source import com.emarsys.rdb.connector.common.ConnectorResponse import com.emarsys.rdb.connector.common.models.DataManipulation.Criteria import com.emarsys.rdb.connector.common.models.DataManipulation.FieldValueWrapper._ import com.emarsys.rdb.connector.common.models.SimpleSelect._ import com.emarsys.rdb.connector.common.models.TableSchemaDescriptors.{FieldModel, TableModel} import org.mockito.Mockito.{reset, spy, verify} import org.scalatest.mockito.MockitoSugar import org.scalatest.{BeforeAndAfterEach, Matchers, WordSpecLike} import scala.concurrent.duration._ import scala.concurrent.{Await, ExecutionContext, Future} class ConnectorSearchSpec extends WordSpecLike with Matchers with MockitoSugar with BeforeAndAfterEach { implicit val executionCtx: ExecutionContext = ExecutionContext.global val tableName = "tableName" val viewName = "viewName" val defaultTimeout = 3.seconds val sqlTimeout = 3.seconds class TestConnector extends Connector { override implicit val executionContext: ExecutionContext = executionCtx override def close() = ??? override def listTables() = Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true)))) override def listFields(table: String) = Future.successful(Right(Seq(FieldModel("a", ""), FieldModel("b", "")))) override def isOptimized(table: String, fields: Seq[String]) = Future.successful(Right(true)) override def simpleSelect(select: SimpleSelect, timeout: FiniteDuration): ConnectorResponse[Source[Seq[String], NotUsed]] = Future.successful(Right(Source(List(Seq("head"))))) } val myConnector = spy(new TestConnector()) override def beforeEach() = { reset(myConnector) } "#search" should { "return ok - string value" in { val criteria: Criteria = Map("a" -> StringValue("1")) Await.result(myConnector.search(tableName, criteria, Some(1), sqlTimeout), defaultTimeout) shouldBe a[Right[_, _]] verify(myConnector).simpleSelect( SimpleSelect( AllField, TableName(tableName), Some(And(Seq(EqualToValue(FieldName("a"), Value("1"))))), Some(1) ), sqlTimeout ) } "return ok - int value" in { val criteria: Criteria = Map("a" -> IntValue(1)) Await.result(myConnector.search(tableName, criteria, Some(1), sqlTimeout), defaultTimeout) shouldBe a[Right[_, _]] verify(myConnector).simpleSelect( SimpleSelect( AllField, TableName(tableName), Some(And(Seq(EqualToValue(FieldName("a"), Value("1"))))), Some(1) ), sqlTimeout ) } "return ok - bigdecimal value" in { val criteria: Criteria = Map("a" -> BigDecimalValue(1)) Await.result(myConnector.search(tableName, criteria, Some(1), sqlTimeout), defaultTimeout) shouldBe a[Right[_, _]] verify(myConnector).simpleSelect( SimpleSelect( AllField, TableName(tableName), Some(And(Seq(EqualToValue(FieldName("a"), Value("1"))))), Some(1) ), sqlTimeout ) } "return ok - boolean value" in { val criteria: Criteria = Map("a" -> BooleanValue(true)) Await.result(myConnector.search(tableName, criteria, Some(1), sqlTimeout), defaultTimeout) shouldBe a[Right[_, _]] verify(myConnector).simpleSelect( SimpleSelect( AllField, TableName(tableName), Some(And(Seq(EqualToValue(FieldName("a"), Value("true"))))), Some(1) ), sqlTimeout ) } "return ok - null value" in { val criteria: Criteria = Map("a" -> NullValue) Await.result(myConnector.search(tableName, criteria, Some(1), sqlTimeout), defaultTimeout) shouldBe a[Right[_, _]] verify(myConnector).simpleSelect( SimpleSelect( AllField, TableName(tableName), Some(And(Seq(IsNull(FieldName("a"))))), Some(1) ), sqlTimeout ) } } }
emartech/rdb-connector-common
src/test/scala/com/emarsys/rdb/connector/common/defaults/FieldValueConverterSpec.scala
package com.emarsys.rdb.connector.common.defaults import com.emarsys.rdb.connector.common.defaults.FieldValueConverter._ import com.emarsys.rdb.connector.common.models.DataManipulation.FieldValueWrapper._ import com.emarsys.rdb.connector.common.models.SimpleSelect._ import org.scalatest.{Matchers, WordSpecLike} class FieldValueConverterSpec extends WordSpecLike with Matchers { "FieldValueConverter" when { "StringValue" in { import DefaultFieldValueConverters.stringValueConverter StringValue("hello").toSimpleSelectValue shouldEqual Some(Value("hello")) } "IntValue" in { import DefaultFieldValueConverters.intValueConverter IntValue(777).toSimpleSelectValue shouldEqual Some(Value("777")) } "BigDecimalValue" in { import DefaultFieldValueConverters.bigDecimalValueConverter BigDecimalValue(777).toSimpleSelectValue shouldEqual Some(Value("777")) } "BooleanValue - true" in { import DefaultFieldValueConverters.booleanValueConverter BooleanValue(true).toSimpleSelectValue shouldEqual Some(Value("true")) } "BooleanValue - false" in { import DefaultFieldValueConverters.booleanValueConverter BooleanValue(false).toSimpleSelectValue shouldEqual Some(Value("false")) } "NullValue" in { import DefaultFieldValueConverters.nullValueConverter NullValue.toSimpleSelectValue shouldEqual None } } }
emartech/rdb-connector-common
build.sbt
name := "rdb-connector-common" version := "0.1-SNAPSHOT" scalaVersion := "2.12.3" libraryDependencies ++= { val scalaTestV = "3.0.1" Seq( "com.typesafe.akka" %% "akka-stream" % "2.5.6", "com.typesafe.akka" %% "akka-stream-testkit" % "2.5.6" % Test, "org.scalatest" %% "scalatest" % scalaTestV % Test, "org.mockito" % "mockito-core" % "2.18.3" % Test, "com.typesafe.akka" %% "akka-http-spray-json" % "10.0.7" % Test ) }
emartech/rdb-connector-common
src/test/scala/com/emarsys/rdb/connector/common/models/ValidateGroupLimitableQuerySpec.scala
package com.emarsys.rdb.connector.common.models import com.emarsys.rdb.connector.common.models.SimpleSelect._ import org.scalatest.{Matchers, WordSpecLike} class ValidateGroupLimitableQuerySpec extends WordSpecLike with Matchers { import ValidateGroupLimitableQuery.GroupLimitValidationResult._ "ValidateGroupLimitableQuery" should { "empty where cause => Simple" in { val select = SimpleSelect(AllField, TableName("table")) ValidateGroupLimitableQuery.groupLimitableQueryValidation(select) shouldBe Simple } "non OR where cause => Simple" in { val select = SimpleSelect(AllField, TableName("table"), Some(And(Seq(NotNull(FieldName("a")), NotNull(FieldName("b")))))) ValidateGroupLimitableQuery.groupLimitableQueryValidation(select) shouldBe Simple } "badly optimized OR where cause => Simple" in { val select = SimpleSelect(AllField, TableName("table"), Some(Or(Seq(NotNull(FieldName("a")))))) ValidateGroupLimitableQuery.groupLimitableQueryValidation(select) shouldBe Simple } "all OR has the same fields => Groupable" in { val select = SimpleSelect(AllField, TableName("table"), Some(Or(Seq( And(Seq(EqualToValue(FieldName("a"), Value("x")), EqualToValue(FieldName("b"), Value("y")))), And(Seq(EqualToValue(FieldName("b"), Value("z")), EqualToValue(FieldName("a"), Value("w")))) )))) ValidateGroupLimitableQuery.groupLimitableQueryValidation(select) shouldBe Groupable(Seq("b", "a")) } "OR has no inner And => Groupable" in { val select = SimpleSelect(AllField, TableName("table"), Some(Or(Seq( EqualToValue(FieldName("a"), Value("x")), EqualToValue(FieldName("a"), Value("y")) )))) ValidateGroupLimitableQuery.groupLimitableQueryValidation(select) shouldBe Groupable(Seq("a")) } "not all OR has the same fields => NotGroupable" in { val select = SimpleSelect(AllField, TableName("table"), Some(Or(Seq( And(Seq(EqualToValue(FieldName("a"), Value("x")), EqualToValue(FieldName("b"), Value("y")))), And(Seq(EqualToValue(FieldName("b"), Value("z")), EqualToValue(FieldName("c"), Value("w")))) )))) ValidateGroupLimitableQuery.groupLimitableQueryValidation(select) shouldBe NotGroupable val select2 = SimpleSelect(AllField, TableName("table"), Some(Or(Seq( And(Seq(EqualToValue(FieldName("a"), Value("x")), EqualToValue(FieldName("b"), Value("y")))), And(Seq(EqualToValue(FieldName("b"), Value("z")), EqualToValue(FieldName("c"), Value("w")))), And(Seq(EqualToValue(FieldName("a"), Value("x")), EqualToValue(FieldName("c"), Value("w")))) )))) ValidateGroupLimitableQuery.groupLimitableQueryValidation(select2) shouldBe NotGroupable } "OR has non EqualToValue same fields => NotGroupable" in { val select = SimpleSelect(AllField, TableName("table"), Some(Or(Seq( And(Seq(EqualToValue(FieldName("a"), Value("x")), NotNull(FieldName("b")))), And(Seq(EqualToValue(FieldName("a"), Value("z")), NotNull(FieldName("b")))) )))) ValidateGroupLimitableQuery.groupLimitableQueryValidation(select) shouldBe NotGroupable } } }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/models/ValidateDataManipulation.scala
package com.emarsys.rdb.connector.common.models import com.emarsys.rdb.connector.common.models.DataManipulation.{Criteria, Record, UpdateDefinition} import com.emarsys.rdb.connector.common.models.Errors.ErrorWithMessage import com.emarsys.rdb.connector.common.models.ValidateDataManipulation.ValidationResult import scala.concurrent.{ExecutionContext, Future} trait ValidateDataManipulation { private type DeferredValidation = () => Future[ValidationResult] val maxRows: Int def validateUpdateDefinition(tableName: String, updateData: Seq[UpdateDefinition], connector: Connector)(implicit executionContext: ExecutionContext): Future[ValidationResult] = { runValidations(Seq( () => validateUpdateFormat(updateData), () => validateTableIsNotAView(tableName, connector), () => validateUpdateFields(tableName, updateData, connector) )) } def validateInsertData(tableName: String, dataToInsert: Seq[Record], connector: Connector)(implicit executionContext: ExecutionContext): Future[ValidationResult] = { runValidations(Seq( () => validateFormat(dataToInsert), () => validateTableIsNotAView(tableName, connector), () => validateFieldExistence(tableName, dataToInsert.head.keySet, connector) )) map { case ValidationResult.EmptyData => ValidationResult.Valid case failedValidationResult => failedValidationResult } } def validateDeleteCriteria(tableName: String, criteria: Seq[Criteria], connector: Connector)(implicit executionContext: ExecutionContext): Future[ValidationResult] = { runValidations(Seq( () => validateFormat(criteria), () => validateTableIsNotAView(tableName, connector), () => validateFieldExistence(tableName, criteria.head.keySet, connector), () => validateIndices(tableName, criteria.head.keySet, connector) )) } def validateSearchCriteria(tableName: String, criteria: Criteria, connector: Connector)(implicit executionContext: ExecutionContext): Future[ValidationResult] = { runValidations(Seq( () => validateEmtpyCriteria(criteria), () => validateFieldExistence(tableName, criteria.keySet, connector), () => validateIndices(tableName, criteria.keySet, connector) )) } private def validateEmtpyCriteria(data: Criteria) = Future.successful[ValidationResult] { if (data.isEmpty) { ValidationResult.EmptyData } else { ValidationResult.Valid } } private def runValidations(validations: Seq[DeferredValidation])(implicit executionContext: ExecutionContext): Future[ValidationResult] = { if (validations.isEmpty) { Future.successful(ValidationResult.Valid) } else { val validation = validations.head.apply() validation flatMap { case ValidationResult.Valid => runValidations(validations.tail) case failedValidationResult => Future.successful(failedValidationResult) } } } private def validateFieldExistence(tableName: String, updateData: Seq[UpdateDefinition], connector: Connector)(implicit executionContext: ExecutionContext) : Future[ValidationResult] = { if(updateData.isEmpty){ Future.successful(ValidationResult.EmptyData) } else { val keyFields = updateData.head.search.keySet ++ updateData.head.update.keySet validateFieldExistence(tableName, keyFields, connector) } } private def validateFieldExistence(tableName: String, keyFields: Set[String], connector: Connector)(implicit executionContext: ExecutionContext): Future[ValidationResult] = { connector.listFields(tableName).map { case Right(columns) => val nonExistingFields = keyFields.map(_.toLowerCase).diff(columns.map(_.name.toLowerCase).toSet) if (nonExistingFields.isEmpty) { ValidationResult.Valid } else { ValidationResult.NonExistingFields(keyFields.filter(kf => nonExistingFields.contains(kf.toLowerCase))) } case Left(ErrorWithMessage(msg)) => ValidationResult.ValidationFailed(msg) case _ => ValidationResult.NonExistingTable } } private def validateTableIsNotAView(tableName: String, connector: Connector)(implicit executionContext: ExecutionContext): Future[ValidationResult] = { connector.listTables().map { case Right(tableModels) => val tableNameIsAView = tableModels.exists { tableModel => tableModel.name == tableName && tableModel.isView } if (tableNameIsAView) ValidationResult.InvalidOperationOnView else ValidationResult.Valid case Left(ErrorWithMessage(msg)) => ValidationResult.ValidationFailed(msg) case Left(ex) => ValidationResult.ValidationFailed(s"Something went wrong: $ex") } } private def validateUpdateFields(tableName: String, updateData: Seq[UpdateDefinition], connector: Connector)(implicit executionContext: ExecutionContext) : Future[ValidationResult] = { validateFieldExistence(tableName, updateData, connector) flatMap { case ValidationResult.Valid => validateIndices(tableName, updateData.head.search.keySet, connector) case failedValidationResult => Future.successful(failedValidationResult) } } private def validateIndices(tableName: String, keyFields: Set[String], connector: Connector)(implicit executionContext: ExecutionContext): Future[ValidationResult] = { connector.isOptimized(tableName, keyFields.toList).map { case Right(true) => ValidationResult.Valid case Right(false) => ValidationResult.NoIndexOnFields case Left(ErrorWithMessage(msg)) => ValidationResult.ValidationFailed(msg) case Left(ex) => ValidationResult.ValidationFailed(s"Something went wrong: $ex") } } private def validateFormat(data: Seq[Record]) = Future.successful[ValidationResult] { if (data.size > maxRows) { ValidationResult.TooManyRows } else if (data.isEmpty) { ValidationResult.EmptyData } else if (!areAllKeysTheSame(data)) { ValidationResult.DifferentFields } else { ValidationResult.Valid } } private def areAllKeysTheSame(dataToInsert: Seq[Record]): Boolean = { val firstRecordsKeySet = dataToInsert.head.keySet dataToInsert.forall(_.keySet == firstRecordsKeySet) } private def validateUpdateFormat(updateData: Seq[UpdateDefinition]) = Future.successful { if (updateData.size > maxRows) { ValidationResult.TooManyRows } else if (updateData.isEmpty) { ValidationResult.EmptyData } else if (hasEmptyCriteria(updateData)) { ValidationResult.EmptyCriteria } else if (hasEmptyData(updateData)) { ValidationResult.EmptyData } else if (!areAllCriteriaFieldsTheSame(updateData)) { ValidationResult.DifferentFields } else if (!areAllUpdateFieldsTheSame(updateData)) { ValidationResult.DifferentFields } else { ValidationResult.Valid } } private def areAllCriteriaFieldsTheSame(data: Seq[UpdateDefinition]) = { val firstRecordCriteriaKeySet = data.head.search.keySet data.forall(_.search.keySet == firstRecordCriteriaKeySet) } private def areAllUpdateFieldsTheSame(data: Seq[UpdateDefinition]) = { val firstRecordUpdateKeySet = data.head.update.keySet data.forall(_.update.keySet == firstRecordUpdateKeySet) } private def hasEmptyCriteria(updateData: Seq[UpdateDefinition]) = updateData.exists(_.search.isEmpty) private def hasEmptyData(updateData: Seq[UpdateDefinition]) = updateData.exists(_.update.isEmpty) } object ValidateDataManipulation extends ValidateDataManipulation { val maxRows = 1000 sealed trait ValidationResult object ValidationResult { case object Valid extends ValidationResult case object DifferentFields extends ValidationResult case object EmptyData extends ValidationResult case object TooManyRows extends ValidationResult case object NonExistingTable extends ValidationResult case class NonExistingFields(fields: Set[String]) extends ValidationResult case object NoIndexOnFields extends ValidationResult case object EmptyCriteria extends ValidationResult case object InvalidOperationOnView extends ValidationResult case class ValidationFailed(message: String) extends ValidationResult } }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/defaults/FieldValueConverter.scala
package com.emarsys.rdb.connector.common.defaults import com.emarsys.rdb.connector.common.models.DataManipulation.FieldValueWrapper import com.emarsys.rdb.connector.common.models.SimpleSelect.Value trait FieldValueConverter[T <: FieldValueWrapper] { def convert(fieldValueWrapper: T): Option[Value] } trait FieldValueConverters { implicit val stringValueConverter: FieldValueConverter[FieldValueWrapper.StringValue] implicit val intValueConverter: FieldValueConverter[FieldValueWrapper.IntValue] implicit val bigDecimalValueConverter: FieldValueConverter[FieldValueWrapper.BigDecimalValue] implicit val booleanValueConverter: FieldValueConverter[FieldValueWrapper.BooleanValue] implicit val nullValueConverter: FieldValueConverter[FieldValueWrapper.NullValue.type] implicit def fieldValueConverter: FieldValueConverter[FieldValueWrapper] = { case value: FieldValueWrapper.StringValue => stringValueConverter.convert(value) case value: FieldValueWrapper.IntValue => intValueConverter.convert(value) case value: FieldValueWrapper.BigDecimalValue => bigDecimalValueConverter.convert(value) case value: FieldValueWrapper.BooleanValue => booleanValueConverter.convert(value) case value: FieldValueWrapper.NullValue.type => nullValueConverter.convert(value) } } trait DefaultFieldValueConverters extends FieldValueConverters { implicit val stringValueConverter: FieldValueConverter[FieldValueWrapper.StringValue] = (fieldValueWrapper: FieldValueWrapper.StringValue) => Some(Value(fieldValueWrapper.string)) implicit val intValueConverter: FieldValueConverter[FieldValueWrapper.IntValue] = (fieldValueWrapper: FieldValueWrapper.IntValue) => Some(Value(fieldValueWrapper.int.toString)) implicit val bigDecimalValueConverter: FieldValueConverter[FieldValueWrapper.BigDecimalValue] = (fieldValueWrapper: FieldValueWrapper.BigDecimalValue) => Some(Value(fieldValueWrapper.number.toString())) implicit val booleanValueConverter: FieldValueConverter[FieldValueWrapper.BooleanValue] = (fieldValueWrapper: FieldValueWrapper.BooleanValue) => Some(Value(fieldValueWrapper.boolean.toString)) implicit val nullValueConverter: FieldValueConverter[FieldValueWrapper.NullValue.type] = (_: FieldValueWrapper.NullValue.type) => None } object DefaultFieldValueConverters extends DefaultFieldValueConverters object FieldValueConverter { implicit class FieldValueConverterSyntax[T <: FieldValueWrapper](fieldValue: T) { def toSimpleSelectValue(implicit converter: FieldValueConverter[T]): Option[Value] = converter.convert(fieldValue) } }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/defaults/GroupWithLimitStage.scala
package com.emarsys.rdb.connector.common.defaults import akka.NotUsed import akka.stream.scaladsl.{Flow, Source} object GroupWithLimitStage { def apply[K](references: Seq[String], groupLimit: Int): Flow[Seq[String], Seq[String], NotUsed] = { val upperRefs = references.map(_.toUpperCase) def groupKey(xs: Seq[(String, String)]) = xs.filter(x => upperRefs.contains(x._1.toUpperCase)).map(_._2) Flow[Seq[String]] .prefixAndTail(1) .flatMapConcat { case (head, tail) => head.headOption.fold(Source.empty[Seq[(String, String)]]){ header => tail.map(row => header zip row) } } .groupBy(1024, groupKey) .take(groupLimit) .mergeSubstreams .statefulMapConcat(flattenBackToCsvStyle) } private def flattenBackToCsvStyle: () => Seq[(String, String)] => List[Seq[String]] = { () => var wasHeader = false (l: Seq[(String, String)]) => { if (wasHeader) { List(l.map(_._2)) } else { wasHeader = true List(l.map(_._1), l.map(_._2)) } } } }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/models/Errors.scala
package com.emarsys.rdb.connector.common.models import com.emarsys.rdb.connector.common.models.ValidateDataManipulation.ValidationResult object Errors { sealed abstract class ConnectorError(message: String = "") extends Exception(message) case class ConnectionError(error: Throwable) extends ConnectorError(error.getMessage) case class ConnectionConfigError(message: String) extends ConnectorError(message) case class ErrorWithMessage(message: String) extends ConnectorError(message) case class TableNotFound(table: String) extends ConnectorError(s"Table not found: $table") case class SqlSyntaxError(message: String) extends ConnectorError(message) case class AccessDeniedError(message: String) extends ConnectorError(message) case class ConnectionTimeout(message: String) extends ConnectorError(message) case class QueryTimeout(message: String) extends ConnectorError(message) case class FailedValidation(validationResult: ValidationResult) extends ConnectorError case class NotImplementedOperation(message: String) extends ConnectorError case class SimpleSelectIsNotGroupableFormat(message: String) extends ConnectorError case class TooManyQueries(message: String) extends ConnectorError }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/models/SimpleSelect.scala
<reponame>emartech/rdb-connector-common package com.emarsys.rdb.connector.common.models import com.emarsys.rdb.connector.common.models.SimpleSelect.{Fields, TableName, WhereCondition} case class SimpleSelect(fields: Fields, table: TableName, where: Option[WhereCondition] = None, limit: Option[Int] = None, distinct: Option[Boolean] = None) object SimpleSelect { sealed trait Fields sealed trait WhereCondition case class TableName(t: String) case class FieldName(f: String) case class Value(v: String) case object AllField extends Fields case class SpecificFields(fields: Seq[FieldName]) extends Fields case class And(conditions: Seq[WhereCondition]) extends WhereCondition case class Or(conditions: Seq[WhereCondition]) extends WhereCondition case class EqualToValue(field: FieldName, value: Value) extends WhereCondition case class NotNull(field: FieldName) extends WhereCondition case class IsNull(field: FieldName) extends WhereCondition }
emartech/rdb-connector-common
src/test/scala/com/emarsys/rdb/connector/common/ConnectionConfigSpec.scala
<reponame>emartech/rdb-connector-common package com.emarsys.rdb.connector.common import com.emarsys.rdb.connector.common.models.{CommonConnectionReadableData, ConnectionConfig} import org.scalatest.{Matchers, WordSpecLike} import spray.json._ class ConnectionConfigSpec extends WordSpecLike with Matchers { "ConnectionConfig" should { "have a good toString" in { val conf = new ConnectionConfig { override def toCommonFormat: CommonConnectionReadableData = CommonConnectionReadableData("a", "b", "c", "d") } val fields = conf.toString.parseJson.asJsObject.fields fields.size shouldBe 4 fields.keySet shouldBe Set("type", "location", "dataset", "user") } } }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/models/ValidateGroupLimitableQuery.scala
package com.emarsys.rdb.connector.common.models import com.emarsys.rdb.connector.common.models.SimpleSelect.{And, EqualToValue, Or, WhereCondition} import com.emarsys.rdb.connector.common.models.ValidateGroupLimitableQuery.GroupLimitValidationResult trait ValidateGroupLimitableQuery { import ValidateGroupLimitableQuery.GroupLimitValidationResult._ def groupLimitableQueryValidation(simpleSelect: SimpleSelect): GroupLimitValidationResult = { def validateOr(list: Seq[WhereCondition]): GroupLimitValidationResult = { val flatted = list.flatMap { case And(l) => l case x => Seq(x) } val filtered = flatted.collect { case x: EqualToValue => x } if (filtered.size != flatted.size) { NotGroupable } else { val grouped: Map[String, Seq[EqualToValue]] = filtered.groupBy(_.field.f) val sizes = grouped.map(_._2.size) sizes.headOption.fold[GroupLimitValidationResult](NotGroupable) { head => if (sizes.forall(_ == head) && head == list.size) { Groupable(grouped.keys.toSeq) } else { NotGroupable } } } } simpleSelect.where.fold[GroupLimitValidationResult](Simple) { case Or(list) if list.size < 2 => Simple case Or(list) => validateOr(list) case _ => Simple } } } object ValidateGroupLimitableQuery extends ValidateGroupLimitableQuery { sealed trait GroupLimitValidationResult object GroupLimitValidationResult { case object Simple extends GroupLimitValidationResult case class Groupable(references: Seq[String]) extends GroupLimitValidationResult case object NotGroupable extends GroupLimitValidationResult } }
emartech/rdb-connector-common
src/test/scala/com/emarsys/rdb/connector/common/models/ValidateDataManipulatorSpec.scala
package com.emarsys.rdb.connector.common.models import com.emarsys.rdb.connector.common.models.DataManipulation.FieldValueWrapper.StringValue import com.emarsys.rdb.connector.common.models.DataManipulation.{FieldValueWrapper, UpdateDefinition} import com.emarsys.rdb.connector.common.models.Errors.TableNotFound import com.emarsys.rdb.connector.common.models.TableSchemaDescriptors.{FieldModel, TableModel} import com.emarsys.rdb.connector.common.models.ValidateDataManipulation.ValidationResult import org.scalatest.mockito.MockitoSugar import org.scalatest.{Matchers, WordSpecLike} import scala.concurrent.{Await, ExecutionContext, Future} import concurrent.duration._ import org.mockito.Mockito._ import org.mockito.ArgumentMatchers._ class ValidateDataManipulatorSpec extends WordSpecLike with Matchers with MockitoSugar{ implicit val executionContext: ExecutionContext = ExecutionContext.global val defaultTimeout = 3.seconds val tableName = "tableName" val viewName = "viewName" class ValidatorScope { val connector = mock[Connector] } "#validateUpdateData" should { "return valid if everything is ok" in new ValidatorScope { when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", ""), FieldModel("b", ""))))) when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.isOptimized(any[String], any[Seq[String]])).thenReturn(Future.successful(Right(true))) val updateData = Seq(UpdateDefinition(Map("a" -> StringValue("1")), Map("b" -> StringValue("2")))) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.Valid } "return empty if nothing specified to update" in new ValidatorScope { val updateData = Seq[UpdateDefinition]() val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.EmptyData } "return error if number of rows exceeds 1000" in new ValidatorScope { val updateData = (1 to 1001).map(_ => UpdateDefinition(Map[String, FieldValueWrapper](), Map[String, FieldValueWrapper]())) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.TooManyRows } "return error for empty search" in new ValidatorScope { val updateData = Seq(UpdateDefinition(Map[String, FieldValueWrapper](), Map("a" -> StringValue("1")))) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.EmptyCriteria } "return error for empty data" in new ValidatorScope { val updateData = Seq(UpdateDefinition(Map("a" -> StringValue("1")), Map[String, FieldValueWrapper]())) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.EmptyData } "return error if not all criteria contains the same fields" in new ValidatorScope { val updateData = Seq(UpdateDefinition(Map("a" -> StringValue("1"), "b" -> StringValue("2")), Map("c" -> StringValue("3"))), UpdateDefinition(Map("a" -> StringValue("1"), "x" -> StringValue("100")), Map("c" -> StringValue("3")))) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.DifferentFields } "return error if not all update record contains the same fields" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) val updateData = Seq(UpdateDefinition(Map("a" -> StringValue("1"), "b" -> StringValue("2")), Map("a" -> StringValue("1"), "b" -> StringValue("3"))), UpdateDefinition(Map("a" -> StringValue("1"), "x" -> StringValue("100")), Map("c" -> StringValue("3")))) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.DifferentFields } "return error if not all criteria fields present in the database table" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("exists",""), FieldModel("existsToo", ""))))) val updateData = Seq(UpdateDefinition(Map("notExists" -> StringValue("b"), "exists" -> StringValue("2"), "notExistsEither" -> StringValue("whatever")), Map("exists" -> StringValue("value")))) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.NonExistingFields(Set("notExists", "notExistsEither")) } "return error if not all update data fields present in the database table" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("exists",""), FieldModel("existsToo", ""))))) val updateData = Seq(UpdateDefinition(Map("exists" -> StringValue("a")), Map("exists" -> StringValue("value"), "notExists" -> StringValue("notValueHaha")))) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.NonExistingFields(Set("notExists")) } "validate with insensitive column names" in new ValidatorScope { when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", ""), FieldModel("b", ""))))) when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.isOptimized(any[String], any[Seq[String]])).thenReturn(Future.successful(Right(true))) val updateData = Seq(UpdateDefinition(Map("A" -> StringValue("1")), Map("B" -> StringValue("2")))) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.Valid } "return error if criteria fields has no indices" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("not_index",""), FieldModel("a", ""))))) when(connector.isOptimized(tableName, Seq("not_index"))).thenReturn(Future.successful(Right(false))) val updateData = Seq(UpdateDefinition(Map("not_index" -> StringValue("a")), Map("a" -> StringValue("1")))) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(tableName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.NoIndexOnFields } "return error if we want an operation on a view" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) val updateData = Seq(UpdateDefinition(Map("not_index" -> StringValue("a")), Map("a" -> StringValue("1")))) val validationResult = Await.result(ValidateDataManipulation.validateUpdateDefinition(viewName, updateData, connector), defaultTimeout) validationResult shouldBe ValidationResult.InvalidOperationOnView } } "#validateInsertData" should { "return valid if number of rows is below or exactly 1000" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", "text"), FieldModel("b", "text"))))) val data = (1 to 1000).map(_ => Map("a" -> StringValue("1"))) val validationResult = Await.result(ValidateDataManipulation.validateInsertData(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.Valid } "return error if number of rows exceeds 1000" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", "text"), FieldModel("b", "text"))))) val data = (1 to 1001).map(_ => Map("a" -> StringValue("1"))) val validationResult = Await.result(ValidateDataManipulation.validateInsertData(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.TooManyRows } "return valid if all records contains the same fields" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", "text"), FieldModel("b", "text"))))) val data = Seq(Map("a" -> StringValue("b"), "a" -> StringValue("c"))) val validationResult = Await.result(ValidateDataManipulation.validateInsertData(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.Valid } "return valid if all records contains the same fields but in different order" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", "text"), FieldModel("b", "text"))))) val data = Seq(Map("a" -> StringValue("1"), "b" -> StringValue("2")), Map("b" -> StringValue("3"), "a" -> StringValue("4"))) val validationResult = Await.result(ValidateDataManipulation.validateInsertData(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.Valid } "return valid for empty array" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", "text"), FieldModel("b", "text"))))) val validationResult = Await.result(ValidateDataManipulation.validateInsertData(tableName, Seq(), connector), defaultTimeout) validationResult shouldBe ValidationResult.Valid } "return error if not all records contains the same fields" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", "text"), FieldModel("b", "text"))))) val data: Seq[Map[String, StringValue]] = Seq(Map("a" -> StringValue("b")), Map()) val validationResult = Await.result(ValidateDataManipulation.validateInsertData(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.DifferentFields } "return error if not all fields present in the database table" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("exists", "text"), FieldModel("exists2", "text"))))) val data: Seq[Map[String, StringValue]] = Seq(Map("notExists" -> StringValue("b"), "exists" -> StringValue("2"), "notExistsEither" -> StringValue("whatever"))) val validationResult = Await.result(ValidateDataManipulation.validateInsertData(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.NonExistingFields(Set("notExists", "notExistsEither")) } "return error if table not exists" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Left(TableNotFound(tableName)))) val data = Seq(Map("a" -> StringValue("b")), Map("a" -> StringValue("c"))) val validationResult = Await.result(ValidateDataManipulation.validateInsertData(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.NonExistingTable } "return error if we want an operation on a view" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(viewName)).thenReturn(Future.successful(Left(TableNotFound(tableName)))) val data = Seq(Map("a" -> StringValue("b")), Map("a" -> StringValue("c"))) val validationResult = Await.result(ValidateDataManipulation.validateInsertData(viewName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.InvalidOperationOnView } } "#validateDeleteCriteria" should { "return valid if everything is ok" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", "text"), FieldModel("b", "text"))))) when(connector.isOptimized(tableName, Seq("a", "b"))).thenReturn(Future.successful(Right(true))) val criterion = (1 to 1000).map(_ => Map("a" -> StringValue("1"), "b" -> StringValue("2"))) val validationResult = Await.result(ValidateDataManipulation.validateDeleteCriteria(tableName, criterion, connector), defaultTimeout) validationResult shouldBe ValidationResult.Valid } "return error if number of rows exceeds 1000" in new ValidatorScope { val criterion = (1 to 1001).map(_ => Map("a" -> StringValue("1"))) val validationResult = Await.result(ValidateDataManipulation.validateDeleteCriteria(tableName, criterion, connector), defaultTimeout) validationResult shouldBe ValidationResult.TooManyRows } "return error for empty array" in new ValidatorScope { val validationResult = Await.result(ValidateDataManipulation.validateDeleteCriteria(tableName, Seq(), connector), defaultTimeout) validationResult shouldBe ValidationResult.EmptyData } "return error if not all records contains the same fields" in new ValidatorScope { val data: Seq[Map[String, StringValue]] = Seq(Map("a" -> StringValue("b")), Map()) val validationResult = Await.result(ValidateDataManipulation.validateDeleteCriteria(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.DifferentFields } "return error if not all fields present in the database table" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("exists", "text"), FieldModel("existsToo", "text"))))) val data: Seq[Map[String, StringValue]] = Seq(Map("notExists" -> StringValue("b"), "exists" -> StringValue("2"), "notExistsEither" -> StringValue("whatever"))) val validationResult = Await.result(ValidateDataManipulation.validateDeleteCriteria(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.NonExistingFields(Set("notExists", "notExistsEither")) } "return error if table not exists" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Left(TableNotFound(tableName)))) val data = Seq(Map("a" -> StringValue("b")), Map("a" -> StringValue("c"))) val validationResult = Await.result(ValidateDataManipulation.validateDeleteCriteria(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.NonExistingTable } "return error if we want an operation on a view" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) val data = Seq(Map("a" -> StringValue("b")), Map("a" -> StringValue("c"))) val validationResult = Await.result(ValidateDataManipulation.validateDeleteCriteria(viewName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.InvalidOperationOnView } "return error if criteria fields has not indices" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("not_index", ""))))) when(connector.isOptimized(tableName, Seq("not_index"))).thenReturn(Future.successful(Right(false))) val data = Seq(Map("not_index" -> StringValue("b")), Map("not_index" -> StringValue("c"))) val validationResult = Await.result(ValidateDataManipulation.validateDeleteCriteria(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.NoIndexOnFields } } "#validateSearchCriteria" should { "return valid if everything is ok" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", "text"), FieldModel("b", "text"))))) when(connector.isOptimized(tableName, Seq("a", "b"))).thenReturn(Future.successful(Right(true))) val criterion = Map("a" -> StringValue("1"), "b" -> StringValue("2")) val validationResult = Await.result(ValidateDataManipulation.validateSearchCriteria(tableName, criterion, connector), defaultTimeout) validationResult shouldBe ValidationResult.Valid } "return valid if everything is ok with view" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(viewName)).thenReturn(Future.successful(Right(Seq(FieldModel("a", "text"), FieldModel("b", "text"))))) when(connector.isOptimized(viewName, Seq("a", "b"))).thenReturn(Future.successful(Right(true))) val criterion = Map("a" -> StringValue("1"), "b" -> StringValue("2")) val validationResult = Await.result(ValidateDataManipulation.validateSearchCriteria(viewName, criterion, connector), defaultTimeout) validationResult shouldBe ValidationResult.Valid } "return error for empty search" in new ValidatorScope { val validationResult = Await.result(ValidateDataManipulation.validateSearchCriteria(tableName, Map(), connector), defaultTimeout) validationResult shouldBe ValidationResult.EmptyData } "return error if not all fields present in the database table" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("exists", "text"), FieldModel("existsToo", "text"))))) val data: Map[String, StringValue] = Map("notExists" -> StringValue("b"), "exists" -> StringValue("2"), "notExistsEither" -> StringValue("whatever")) val validationResult = Await.result(ValidateDataManipulation.validateSearchCriteria(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.NonExistingFields(Set("notExists", "notExistsEither")) } "return error if table not exists" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Left(TableNotFound(tableName)))) val data = Map("a" -> StringValue("b")) val validationResult = Await.result(ValidateDataManipulation.validateSearchCriteria(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.NonExistingTable } "return error if criteria fields has not indices" in new ValidatorScope { when(connector.listTables()).thenReturn(Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true))))) when(connector.listFields(tableName)).thenReturn(Future.successful(Right(Seq(FieldModel("not_index", ""))))) when(connector.isOptimized(tableName, Seq("not_index"))).thenReturn(Future.successful(Right(false))) val data = Map("not_index" -> StringValue("b")) val validationResult = Await.result(ValidateDataManipulation.validateSearchCriteria(tableName, data, connector), defaultTimeout) validationResult shouldBe ValidationResult.NoIndexOnFields } } }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/models/package.scala
package com.emarsys.rdb.connector.common package object models { case class CommonConnectionReadableData(`type`: String, location: String, dataset: String, user: String) trait ConnectionConfig { def replica[C <: this.type]: Option[C] = None def toCommonFormat: CommonConnectionReadableData final override def toString: String = { val CommonConnectionReadableData(t, location, dataset, user) = toCommonFormat s"""{"type":"$t","location":"$location","dataset":"$dataset","user":"$user"}""" } } case class MetaData(nameQuoter: String, valueQuoter: String, escape: String) }
emartech/rdb-connector-common
src/test/scala/com/emarsys/rdb/connector/common/models/ConnectorSpec.scala
package com.emarsys.rdb.connector.common.models import akka.NotUsed import akka.stream.scaladsl.Source import com.emarsys.rdb.connector.common import com.emarsys.rdb.connector.common.ConnectorResponse import com.emarsys.rdb.connector.common.models.DataManipulation.FieldValueWrapper.StringValue import com.emarsys.rdb.connector.common.models.DataManipulation.{Criteria, Record, UpdateDefinition} import com.emarsys.rdb.connector.common.models.Errors.{FailedValidation, SimpleSelectIsNotGroupableFormat} import com.emarsys.rdb.connector.common.models.SimpleSelect.{AllField, TableName} import com.emarsys.rdb.connector.common.models.TableSchemaDescriptors.{FieldModel, TableModel} import com.emarsys.rdb.connector.common.models.ValidateDataManipulation.ValidationResult.InvalidOperationOnView import org.scalatest.{Matchers, WordSpecLike} import scala.concurrent.duration._ import scala.concurrent.{Await, ExecutionContext, Future} class ConnectorSpec extends WordSpecLike with Matchers { implicit val executionCtx: ExecutionContext = ExecutionContext.global val tableName = "tableName" val viewName = "viewName" val defaultTimeout = 3.seconds val myConnector = new Connector { override implicit val executionContext: ExecutionContext = executionCtx override def close() = ??? override def listTables() = Future.successful(Right(Seq(TableModel(tableName, false), TableModel(viewName, true)))) override def listFields(table: String) = Future.successful(Right(Seq(FieldModel("a", ""), FieldModel("b", "")))) override def isOptimized(table: String, fields: Seq[String]) = Future.successful(Right(true)) override protected def rawUpdate(tableName: String, definitions: Seq[DataManipulation.UpdateDefinition]): ConnectorResponse[Int] = Future.successful(Right(4)) override protected def rawInsertData(tableName: String, data: Seq[Record]): ConnectorResponse[Int] = Future.successful(Right(4)) override protected def rawReplaceData(tableName: String, data: Seq[Record]): ConnectorResponse[Int] = Future.successful(Right(4)) override protected def rawUpsert(tableName: String, data: Seq[Record]): ConnectorResponse[Int] = Future.successful(Right(4)) override protected def rawDelete(tableName: String, criteria: Seq[Criteria]): ConnectorResponse[Int] = Future.successful(Right(4)) } "#update" should { "return ok" in { val definitions = Seq(UpdateDefinition(Map("a" -> StringValue("1")), Map("b" -> StringValue("2")))) Await.result(myConnector.update(tableName, definitions), defaultTimeout) shouldBe Right(4) } "return validation error" in { val definitions = Seq(UpdateDefinition(Map("a" -> StringValue("1")), Map("b" -> StringValue("2")))) Await.result(myConnector.update(viewName, definitions), defaultTimeout) shouldBe Left(FailedValidation(InvalidOperationOnView)) } } "#insert" should { "return ok" in { val records = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(myConnector.insertIgnore(tableName, records), defaultTimeout) shouldBe Right(4) } "return validation error" in { val records = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(myConnector.insertIgnore(viewName, records), defaultTimeout) shouldBe Left(FailedValidation(InvalidOperationOnView)) } } "#replace" should { "return ok" in { val records = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(myConnector.replaceData(tableName, records), defaultTimeout) shouldBe Right(4) } "return validation error" in { val records = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(myConnector.replaceData(viewName, records), defaultTimeout) shouldBe Left(FailedValidation(InvalidOperationOnView)) } } "#upsert" should { "return ok" in { val records = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(myConnector.upsert(tableName, records), defaultTimeout) shouldBe Right(4) } "return validation error" in { val records = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(myConnector.upsert(viewName, records), defaultTimeout) shouldBe Left(FailedValidation(InvalidOperationOnView)) } } "#delete" should { "return ok" in { val criteria = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(myConnector.delete(tableName, criteria), defaultTimeout) shouldBe Right(4) } "return validation error" in { val criteria = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(myConnector.delete(viewName, criteria), defaultTimeout) shouldBe Left(FailedValidation(InvalidOperationOnView)) } } "#isErrorRetryable" should { "return false for any input" in { myConnector.isErrorRetryable(new Exception()) shouldBe false } } "#selectWithGroupLimit" should { val select = SimpleSelect(AllField, TableName("table")) "use simpleSelect if validator choose Simple" in { var calledWith: Seq[SimpleSelect] = Seq.empty val validator = new ValidateGroupLimitableQuery { override def groupLimitableQueryValidation(simpleSelect: SimpleSelect): ValidateGroupLimitableQuery.GroupLimitValidationResult = ValidateGroupLimitableQuery.GroupLimitValidationResult.Simple } val connector = new Connector { override implicit val executionContext: ExecutionContext = executionCtx override val groupLimitValidator = validator override def simpleSelect(select: SimpleSelect, timeout: FiniteDuration): ConnectorResponse[Source[Seq[String], NotUsed]] = { calledWith +:= select common.notImplementedOperation("simpleSelect") } override def close(): Future[Unit] = ??? } connector.selectWithGroupLimit(select, 5, 10.minutes) calledWith.size shouldBe 1 calledWith.head.limit shouldBe Some(5) } "use runSelectWithGroupLimit if validator choose Groupable" in { var calledWith: Seq[SimpleSelect] = Seq.empty val validator = new ValidateGroupLimitableQuery { override def groupLimitableQueryValidation(simpleSelect: SimpleSelect): ValidateGroupLimitableQuery.GroupLimitValidationResult = ValidateGroupLimitableQuery.GroupLimitValidationResult.Groupable(Seq.empty) } val connector = new Connector { override implicit val executionContext: ExecutionContext = executionCtx override val groupLimitValidator = validator override def runSelectWithGroupLimit(select: SimpleSelect, groupLimit: Int, references: Seq[String], timeout: FiniteDuration): ConnectorResponse[Source[Seq[String], NotUsed]] = { calledWith +:= select common.notImplementedOperation("simpleSelect") } override def close(): Future[Unit] = ??? } connector.selectWithGroupLimit(select, 5, 10.minutes) calledWith.size shouldBe 1 calledWith.head.limit shouldBe None } "drop error if validator choose NotGroupable" in { val validator = new ValidateGroupLimitableQuery { override def groupLimitableQueryValidation(simpleSelect: SimpleSelect): ValidateGroupLimitableQuery.GroupLimitValidationResult = ValidateGroupLimitableQuery.GroupLimitValidationResult.NotGroupable } val connector = new Connector { override implicit val executionContext: ExecutionContext = executionCtx override val groupLimitValidator = validator override def close(): Future[Unit] = ??? } Await.result(connector.selectWithGroupLimit(select, 5, 10.minutes), 1.second) shouldBe Left(SimpleSelectIsNotGroupableFormat("SimpleSelect(AllField,TableName(table),None,None,None)")) } } }
emartech/rdb-connector-common
src/test/scala/com/emarsys/rdb/connector/common/models/ConnectorNotImplementedOperationSpec.scala
<reponame>emartech/rdb-connector-common<gh_stars>0 package com.emarsys.rdb.connector.common.models import com.emarsys.rdb.connector.common.models.DataManipulation.FieldValueWrapper.StringValue import com.emarsys.rdb.connector.common.models.DataManipulation.UpdateDefinition import com.emarsys.rdb.connector.common.models.Errors.NotImplementedOperation import com.emarsys.rdb.connector.common.models.SimpleSelect.{AllField, TableName} import org.scalatest.{Matchers, WordSpecLike} import scala.concurrent.duration._ import scala.concurrent.{Await, ExecutionContext} class ConnectorNotImplementedOperationSpec extends WordSpecLike with Matchers { implicit val executionCtx: ExecutionContext = ExecutionContext.global val tableName = "tableName" val sql = "SQL" val defaultTimeout = 3.seconds val sqlTimeout = 3.seconds class ConnectorTestScope extends Connector { override implicit val executionContext: ExecutionContext = executionCtx override def close() = ??? } "default response NotImplementedOperation" should { "#testConnection" in new ConnectorTestScope { Await.result(testConnection(), defaultTimeout) shouldEqual Left(NotImplementedOperation("testConnection not implemented")) } "#listTables" in new ConnectorTestScope { Await.result(listTables(), defaultTimeout) shouldEqual Left(NotImplementedOperation("listTables not implemented")) } "#listTablesWithFields" in new ConnectorTestScope { Await.result(listTablesWithFields(), defaultTimeout) shouldEqual Left(NotImplementedOperation("listTablesWithFields not implemented")) } "#listFields" in new ConnectorTestScope { Await.result(listFields(tableName), defaultTimeout) shouldEqual Left(NotImplementedOperation("listFields not implemented")) } "#isOptimized" in new ConnectorTestScope { Await.result(isOptimized(tableName, Seq()), defaultTimeout) shouldEqual Left(NotImplementedOperation("isOptimized not implemented")) } "#simpleSelect" in new ConnectorTestScope { Await.result(simpleSelect(SimpleSelect(AllField, TableName(tableName)), sqlTimeout), defaultTimeout) shouldEqual Left(NotImplementedOperation("simpleSelect not implemented")) } "#rawSelect" in new ConnectorTestScope { Await.result(rawSelect(sql, None, sqlTimeout), defaultTimeout) shouldEqual Left(NotImplementedOperation("rawSelect not implemented")) } "#validateRawSelect" in new ConnectorTestScope { Await.result(validateRawSelect(sql), defaultTimeout) shouldEqual Left(NotImplementedOperation("validateRawSelect not implemented")) } "#analyzeRawSelect" in new ConnectorTestScope { Await.result(analyzeRawSelect(sql), defaultTimeout) shouldEqual Left(NotImplementedOperation("analyzeRawSelect not implemented")) } "#projectedRawSelect" in new ConnectorTestScope { Await.result(projectedRawSelect(sql, Seq(), None, sqlTimeout), defaultTimeout) shouldEqual Left(NotImplementedOperation("projectedRawSelect not implemented")) } "#validateProjectedRawSelect" in new ConnectorTestScope { Await.result(validateProjectedRawSelect(sql, Seq()), defaultTimeout) shouldEqual Left(NotImplementedOperation("validateProjectedRawSelect not implemented")) } "#rawQuery" in new ConnectorTestScope { Await.result(rawQuery(sql, sqlTimeout), defaultTimeout) shouldEqual Left(NotImplementedOperation("rawQuery not implemented")) } "#rawUpdate" in new ConnectorTestScope { val definitions = Seq(UpdateDefinition(Map("a" -> StringValue("1")), Map("b" -> StringValue("2")))) Await.result(rawUpdate(tableName, definitions), defaultTimeout) shouldBe Left(NotImplementedOperation("rawUpdate not implemented")) } "#rawInsertData" in new ConnectorTestScope { val records = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(rawInsertData(tableName, records), defaultTimeout) shouldBe Left(NotImplementedOperation("rawInsertData not implemented")) } "#rawReplaceData" in new ConnectorTestScope { val records = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(rawReplaceData(tableName, records), defaultTimeout) shouldBe Left(NotImplementedOperation("rawReplaceData not implemented")) } "#rawUpsert" in new ConnectorTestScope { val records = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(rawUpsert(tableName, records), defaultTimeout) shouldBe Left(NotImplementedOperation("rawUpsert not implemented")) } "#rawDelete" in new ConnectorTestScope { val criteria = Seq(Map("a" -> StringValue("1")), Map("a" -> StringValue("2"))) Await.result(rawDelete(tableName, criteria), defaultTimeout) shouldBe Left(NotImplementedOperation("rawDelete not implemented")) } } }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/package.scala
package com.emarsys.rdb.connector import com.emarsys.rdb.connector.common.models.Errors.{ConnectorError, NotImplementedOperation} import scala.concurrent.Future package object common { type ConnectorResponse[T] = Future[Either[ConnectorError,T]] def notImplementedOperation[T](message: String): ConnectorResponse[T] = Future.successful(Left(NotImplementedOperation(message))) }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/defaults/SqlWriter.scala
<reponame>emartech/rdb-connector-common package com.emarsys.rdb.connector.common.defaults import scala.language.implicitConversions import com.emarsys.rdb.connector.common.models.SimpleSelect import com.emarsys.rdb.connector.common.models.SimpleSelect._ import scala.annotation.implicitNotFound @implicitNotFound(msg = "Cannot find implicit SqlWriter type class for ${T}") trait SqlWriter[T] { def write(obj: T): String } object SqlWriter { implicit class WritableSqlElement[T](any: T) { def toSql(implicit writer: SqlWriter[T]): String = writer.write(any) } implicit def func2LazyWriter[T](f: T => String): SqlWriter[T] = lazyWriter((obj: T) => f(obj)) def lazyWriter[T](writer: => SqlWriter[T]): SqlWriter[T] = new SqlWriter[T] { private lazy val delegate = writer def write(x: T): String = delegate.write(x) } def createTableNameWriter(symbol: String, escape: String): SqlWriter[TableName] = (tableName: TableName) => createEscapeQuoter(symbol, escape, tableName.t) def createFieldNameWriter(symbol: String, escape: String): SqlWriter[FieldName] = (fieldName: FieldName) => createEscapeQuoter(symbol, escape, fieldName.f) def createValueWriter(symbol: String, escape: String): SqlWriter[Value] = (value: Value) => createEscapeQuoter(symbol, escape, value.v) def createAllFieldWriter(symbol: String): SqlWriter[AllField.type] = (_: AllField.type) => symbol def createSpecificFieldsWriter(symbol: String)(implicit w: SqlWriter[FieldName]): SqlWriter[SpecificFields] = (x: SpecificFields) => x.fields.map(_.toSql).mkString(symbol) def createIsNullWriter(isNullFormat: String)(implicit w: SqlWriter[FieldName]): SqlWriter[IsNull] = (x: IsNull) => isNullFormat.format(x.field.toSql) def createNotNullWriter(notNullFormat: String)(implicit w: SqlWriter[FieldName]): SqlWriter[NotNull] = (x: NotNull) => notNullFormat.format(x.field.toSql) def createEqualToValueWriter(symbol: String)(implicit w1: SqlWriter[FieldName], w2: SqlWriter[Value]): SqlWriter[EqualToValue] = (x: EqualToValue) => s"${x.field.toSql}$symbol${x.value.toSql}" def createEscapeQuoter(symbol: String, escape: String, name: String): String = { s"$symbol${escaping(symbol,escape,name)}$symbol" } def conditionWriter(symbol: String, conditions: Seq[WhereCondition])(implicit w: SqlWriter[WhereCondition]): String = { if (conditions.size == 1) { conditions.head.toSql } else { s"(${conditions.map(_.toSql).mkString(symbol)})" } } private def escaping(symbol: String, escape: String, text: String): String = { if (text == null) { null } else { val escapedText = if(escape == "") text else text.replace(escape, escape * 2) val symbolEscapedText = if(escape == "" || symbol == "") escapedText else escapedText.replace(symbol, s"$escape$symbol") symbolEscapedText } } } trait DefaultSqlWriters { import SqlWriter._ implicit lazy val tableNameWriter: SqlWriter[TableName] = createTableNameWriter("\"", "\\") implicit lazy val fieldNameWriter: SqlWriter[FieldName] = createFieldNameWriter("\"", "\\") implicit lazy val valueWriter: SqlWriter[Value] = createValueWriter("'", "\\") implicit lazy val allFieldWriter: SqlWriter[AllField.type] = createAllFieldWriter("*") implicit lazy val specificFieldsWriter: SqlWriter[SpecificFields] = createSpecificFieldsWriter(",") implicit lazy val isNullWriter: SqlWriter[IsNull] = createIsNullWriter("%s IS NULL") implicit lazy val notNullWriter: SqlWriter[NotNull] = createNotNullWriter("%s IS NOT NULL") implicit lazy val equalToValueWriter: SqlWriter[EqualToValue] = createEqualToValueWriter("=") implicit lazy val orWriter: SqlWriter[Or] = (x: Or) => conditionWriter(" OR ", x.conditions) implicit lazy val andWriter: SqlWriter[And] = (x: And) => conditionWriter(" AND ", x.conditions) implicit lazy val whereConditionWriter: SqlWriter[WhereCondition] = { case x: EqualToValue => x.toSql case x: IsNull => x.toSql case x: NotNull => x.toSql case x: Or => x.toSql case x: And => x.toSql } implicit lazy val fieldsWriter: SqlWriter[Fields] = { case x: AllField.type => x.toSql case x: SpecificFields => x.toSql } implicit lazy val simpleSelectWriter: SqlWriter[SimpleSelect] = (ss: SimpleSelect) => { val distinct = if(ss.distinct.getOrElse(false)) "DISTINCT " else "" val head = s"SELECT $distinct${ss.fields.toSql} FROM ${ss.table.toSql}" val where = ss.where.map(_.toSql).map(" WHERE " + _).getOrElse("") val limit = ss.limit.map(" LIMIT " + _).getOrElse("") s"$head$where$limit" } } object DefaultSqlWriters extends DefaultSqlWriters
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/models/TableSchemaDescriptors.scala
<filename>src/main/scala/com/emarsys/rdb/connector/common/models/TableSchemaDescriptors.scala package com.emarsys.rdb.connector.common.models object TableSchemaDescriptors { case class TableModel(name: String, isView: Boolean) case class FieldModel(name: String, columnType: String) case class FullTableModel(name: String, isView: Boolean, fields: Seq[FieldModel]) }
emartech/rdb-connector-common
src/test/scala/com/emarsys/rdb/connector/common/defaults/DefaultSqlWriterSpec.scala
<filename>src/test/scala/com/emarsys/rdb/connector/common/defaults/DefaultSqlWriterSpec.scala<gh_stars>0 package com.emarsys.rdb.connector.common.defaults import com.emarsys.rdb.connector.common.models.SimpleSelect._ import org.scalatest.{Matchers, WordSpecLike} import SqlWriter._ import com.emarsys.rdb.connector.common.models.SimpleSelect class DefaultSqlWriterSpec extends WordSpecLike with Matchers { "DefaultSqlWriter" when { "TableName" should { "use default writer" in { import DefaultSqlWriters._ TableName("TABLE1").toSql shouldEqual """"TABLE1"""" } "use default writer - escape" in { import DefaultSqlWriters._ TableName("""TA\BLE"1""").toSql shouldEqual """"TA\\BLE\"1"""" } "use custom writer" in { val customWriters = new DefaultSqlWriters { override implicit lazy val tableNameWriter: SqlWriter[TableName] = SqlWriter.createTableNameWriter("#", "\\") } import customWriters._ TableName("TABLE1").toSql shouldEqual "#TABLE1#" } } "FieldName" should { "use default writer" in { import DefaultSqlWriters._ FieldName("FIELD1").toSql shouldEqual """"FIELD1"""" } "use default writer - escape" in { import DefaultSqlWriters._ FieldName("""F"IEL\D1""").toSql shouldEqual """"F\"IEL\\D1"""" } "use custom writer" in { val customWriters = new DefaultSqlWriters { override implicit lazy val fieldNameWriter: SqlWriter[FieldName] = SqlWriter.createFieldNameWriter("#", "\\") } import customWriters._ FieldName("FIELD1").toSql shouldEqual "#FIELD1#" } } "Value" should { "use default writer" in { import DefaultSqlWriters._ Value("VALUE1").toSql shouldEqual "'VALUE1'" } "use default writer - escape" in { import DefaultSqlWriters._ Value("""VA'L'UE\1""").toSql shouldEqual """'VA\'L\'UE\\1'""" } "use custom writer" in { val customWriters = new DefaultSqlWriters { override implicit lazy val valueWriter: SqlWriter[Value] = SqlWriter.createValueWriter("#", "\\") } import customWriters._ Value("VALUE1").toSql shouldEqual "#VALUE1#" } } "AllFields" should { "use default writer" in { import DefaultSqlWriters._ AllField.toSql shouldEqual "*" } "use custom writer" in { val customWriters = new DefaultSqlWriters { override implicit lazy val allFieldWriter: SqlWriter[SimpleSelect.AllField.type] = SqlWriter.createAllFieldWriter("#") } import customWriters._ AllField.toSql shouldEqual "#" } } "SpecificFields" should { "use default writer - one field" in { import DefaultSqlWriters._ SpecificFields(Seq(FieldName("FIELD1"))).toSql shouldEqual """"FIELD1"""" } "use default writer - many fields" in { import DefaultSqlWriters._ SpecificFields(Seq(FieldName("FIELD1"), FieldName("FIELD2"), FieldName("FIELD3"))).toSql shouldEqual """"FIELD1","FIELD2","FIELD3"""" } "use custom writer - many fields" in { val customWriters = new DefaultSqlWriters { override implicit lazy val specificFieldsWriter: SqlWriter[SpecificFields] = SqlWriter.createSpecificFieldsWriter("#") } import customWriters._ SpecificFields(Seq(FieldName("FIELD1"), FieldName("FIELD2"), FieldName("FIELD3"))).toSql shouldEqual """"FIELD1"#"FIELD2"#"FIELD3"""" } } "IsNull" should { "use default writer" in { import DefaultSqlWriters._ IsNull(FieldName("FIELD1")).toSql shouldEqual """"FIELD1" IS NULL""" } "use custom writer" in { val customWriters = new DefaultSqlWriters { override implicit lazy val isNullWriter: SqlWriter[IsNull] = SqlWriter.createIsNullWriter("<<IS %s NULL>>") } import customWriters._ IsNull(FieldName("FIELD1")).toSql shouldEqual """<<IS "FIELD1" NULL>>""" } } "IsNotNull" should { "use default writer" in { import DefaultSqlWriters._ NotNull(FieldName("FIELD1")).toSql shouldEqual """"FIELD1" IS NOT NULL""" } "use custom writer" in { val customWriters = new DefaultSqlWriters { override implicit lazy val notNullWriter: SqlWriter[NotNull] = SqlWriter.createNotNullWriter("<<IS NOT %s NULL>>") } import customWriters._ NotNull(FieldName("FIELD1")).toSql shouldEqual """<<IS NOT "FIELD1" NULL>>""" } } "EqualToValue" should { "use default writer" in { import DefaultSqlWriters._ EqualToValue(FieldName("FIELD1"), Value("VALUE1")).toSql shouldEqual """"FIELD1"='VALUE1'""" } "use custom writer" in { val customWriters = new DefaultSqlWriters { override implicit lazy val equalToValueWriter: SqlWriter[EqualToValue] = SqlWriter.createEqualToValueWriter(" IS ") } import customWriters._ EqualToValue(FieldName("FIELD1"), Value("VALUE1")).toSql shouldEqual """"FIELD1" IS 'VALUE1'""" } } "Or" should { "use default writer - one condition" in { import DefaultSqlWriters._ Or(Seq(EqualToValue(FieldName("FIELD1"), Value("VALUE1")))).toSql shouldEqual """"FIELD1"='VALUE1'""" } "use default writer - many condition" in { import DefaultSqlWriters._ Or(Seq(IsNull(FieldName("FIELD1")), EqualToValue(FieldName("FIELD2"), Value("VALUE2")))).toSql shouldEqual """("FIELD1" IS NULL OR "FIELD2"='VALUE2')""" } "use default writer - inner or" in { import DefaultSqlWriters._ Or(Seq(IsNull(FieldName("FIELD1")), Or(Seq(IsNull(FieldName("FIELD2")), EqualToValue(FieldName("FIELD3"), Value("VALUE3")))))).toSql shouldEqual """("FIELD1" IS NULL OR ("FIELD2" IS NULL OR "FIELD3"='VALUE3'))""" } "use custom writer - inner or" in { val customWriters = new DefaultSqlWriters { override implicit lazy val orWriter: SqlWriter[Or] = (x: Or) => conditionWriter(" || ", x.conditions) } import customWriters._ Or(Seq(IsNull(FieldName("FIELD1")), Or(Seq(IsNull(FieldName("FIELD2")), EqualToValue(FieldName("FIELD3"), Value("VALUE3")))))).toSql shouldEqual """("FIELD1" IS NULL || ("FIELD2" IS NULL || "FIELD3"='VALUE3'))""" } } "And" should { "use default writer - one condition" in { import DefaultSqlWriters._ And(Seq(EqualToValue(FieldName("FIELD1"), Value("VALUE1")))).toSql shouldEqual """"FIELD1"='VALUE1'""" } "use default writer - many condition" in { import DefaultSqlWriters._ And(Seq(IsNull(FieldName("FIELD1")), EqualToValue(FieldName("FIELD2"), Value("VALUE2")))).toSql shouldEqual """("FIELD1" IS NULL AND "FIELD2"='VALUE2')""" } "use default writer - inner or" in { import DefaultSqlWriters._ And(Seq(IsNull(FieldName("FIELD1")), And(Seq(IsNull(FieldName("FIELD2")), EqualToValue(FieldName("FIELD3"), Value("VALUE3")))))).toSql shouldEqual """("FIELD1" IS NULL AND ("FIELD2" IS NULL AND "FIELD3"='VALUE3'))""" } "use custom writer - inner or" in { val customWriters = new DefaultSqlWriters { override implicit lazy val andWriter: SqlWriter[And] = (x: And) => conditionWriter(" && ", x.conditions) } import customWriters._ And(Seq(IsNull(FieldName("FIELD1")), And(Seq(IsNull(FieldName("FIELD2")), EqualToValue(FieldName("FIELD3"), Value("VALUE3")))))).toSql shouldEqual """("FIELD1" IS NULL && ("FIELD2" IS NULL && "FIELD3"='VALUE3'))""" } } "WhereCondition" should { "combinate all element - use default writers" in { import DefaultSqlWriters._ val where = And(Seq( IsNull(FieldName("FIELD1")), Or(Seq( IsNull(FieldName("FIELD2")), EqualToValue(FieldName("FIELD3"), Value("VALUE3")), NotNull(FieldName("FIELD4")) )), Or(Seq( IsNull(FieldName("FIELD5")) )) )) where.toSql shouldEqual """("FIELD1" IS NULL AND ("FIELD2" IS NULL OR "FIELD3"='VALUE3' OR "FIELD4" IS NOT NULL) AND "FIELD5" IS NULL)""" } "combinate all element - use custom writers" in { val customWriters = new DefaultSqlWriters { override implicit lazy val fieldNameWriter: SqlWriter[FieldName] = SqlWriter.createFieldNameWriter("#", "\\") override implicit lazy val valueWriter: SqlWriter[Value] = SqlWriter.createValueWriter("`", "\\") override implicit lazy val notNullWriter: SqlWriter[NotNull] = SqlWriter.createNotNullWriter("<<IS NOT %s NULL>>") override implicit lazy val equalToValueWriter: SqlWriter[EqualToValue] = SqlWriter.createEqualToValueWriter(" == ") override implicit lazy val isNullWriter: SqlWriter[IsNull] = SqlWriter.createIsNullWriter("NULL(%s)") override implicit lazy val orWriter: SqlWriter[Or] = (x: Or) => conditionWriter(" || ", x.conditions) override implicit lazy val andWriter: SqlWriter[And] = (x: And) => conditionWriter(" && ", x.conditions) } import customWriters._ val where = And(Seq( IsNull(FieldName("FIELD1")), Or(Seq( IsNull(FieldName("FIELD2")), EqualToValue(FieldName("FIELD3"), Value("VALUE3")), NotNull(FieldName("FIELD4")) )), Or(Seq( IsNull(FieldName("FIELD5")) )) )) where.toSql shouldEqual """(NULL(#FIELD1#) && (NULL(#FIELD2#) || #FIELD3# == `VALUE3` || <<IS NOT #FIELD4# NULL>>) && NULL(#FIELD5#))""" } } "SimpleSelect" should { "use default writer - minimal" in { import DefaultSqlWriters._ val select = SimpleSelect( fields = AllField, table = TableName("TABLE1") ) select.toSql shouldEqual """SELECT * FROM "TABLE1"""" } "use default writer - disabled distinct" in { import DefaultSqlWriters._ val select = SimpleSelect( fields = AllField, table = TableName("TABLE1"), distinct = Some(false) ) select.toSql shouldEqual """SELECT * FROM "TABLE1"""" } "use default writer - distinct" in { import DefaultSqlWriters._ val select = SimpleSelect( fields = AllField, table = TableName("TABLE1"), distinct = Some(true) ) select.toSql shouldEqual """SELECT DISTINCT * FROM "TABLE1"""" } "use default writer - specific fields" in { import DefaultSqlWriters._ val select = SimpleSelect( fields = SpecificFields(Seq(FieldName("FIELD1"), FieldName("FIELD2"), FieldName("FIELD3"))), table = TableName("TABLE1") ) select.toSql shouldEqual """SELECT "FIELD1","FIELD2","FIELD3" FROM "TABLE1"""" } "use default writer - where" in { import DefaultSqlWriters._ val select = SimpleSelect( fields = AllField, table = TableName("TABLE1"), where = Some(And(Seq(IsNull(FieldName("FIELD1")), And(Seq(IsNull(FieldName("FIELD2")), EqualToValue(FieldName("FIELD3"), Value("VALUE3"))))))) ) select.toSql shouldEqual """SELECT * FROM "TABLE1" WHERE ("FIELD1" IS NULL AND ("FIELD2" IS NULL AND "FIELD3"='VALUE3'))""" } "use default writer - limit" in { import DefaultSqlWriters._ val select = SimpleSelect( fields = AllField, table = TableName("TABLE1"), limit = Some(100) ) select.toSql shouldEqual """SELECT * FROM "TABLE1" LIMIT 100""" } "use default writer - where and limit" in { import DefaultSqlWriters._ val select = SimpleSelect( fields = AllField, table = TableName("TABLE1"), where = Some(And(Seq(IsNull(FieldName("FIELD1")), And(Seq(IsNull(FieldName("FIELD2")), EqualToValue(FieldName("FIELD3"), Value("VALUE3"))))))), limit = Some(100) ) select.toSql shouldEqual """SELECT * FROM "TABLE1" WHERE ("FIELD1" IS NULL AND ("FIELD2" IS NULL AND "FIELD3"='VALUE3')) LIMIT 100""" } "use default writer - full" in { import DefaultSqlWriters._ val select = SimpleSelect( fields = SpecificFields(Seq(FieldName("FIELD1"), FieldName("FIELD2"), FieldName("FIELD3"))), table = TableName("TABLE1"), where = Some(And(Seq(IsNull(FieldName("FIELD1")), And(Seq(IsNull(FieldName("FIELD2")), EqualToValue(FieldName("FIELD3"), Value("VALUE3"))))))), limit = Some(100), distinct = Some(true) ) select.toSql shouldEqual """SELECT DISTINCT "FIELD1","FIELD2","FIELD3" FROM "TABLE1" WHERE ("FIELD1" IS NULL AND ("FIELD2" IS NULL AND "FIELD3"='VALUE3')) LIMIT 100""" } } } }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/models/Connector.scala
package com.emarsys.rdb.connector.common.models import akka.NotUsed import akka.stream.scaladsl.Source import com.emarsys.rdb.connector.common.defaults.{DefaultFieldValueConverters, FieldValueConverters, GroupWithLimitStage} import com.emarsys.rdb.connector.common.models.DataManipulation.{Criteria, Record, UpdateDefinition} import com.emarsys.rdb.connector.common.models.Errors.{FailedValidation, SimpleSelectIsNotGroupableFormat} import com.emarsys.rdb.connector.common.models.SimpleSelect._ import com.emarsys.rdb.connector.common.models.TableSchemaDescriptors._ import com.emarsys.rdb.connector.common.models.ValidateDataManipulation.ValidationResult import com.emarsys.rdb.connector.common.{ConnectorResponse, notImplementedOperation} import scala.concurrent.duration.FiniteDuration import scala.concurrent.{ExecutionContext, Future} trait Connector { implicit val executionContext: ExecutionContext protected val fieldValueConverters: FieldValueConverters = DefaultFieldValueConverters protected val groupLimitValidator: ValidateGroupLimitableQuery = ValidateGroupLimitableQuery val isErrorRetryable: PartialFunction[Throwable, Boolean] = { case _ => false } def close(): Future[Unit] def innerMetrics(): String = { "{}" } def testConnection(): ConnectorResponse[Unit] = notImplementedOperation(generateNotImplementedMessage("testConnection")) def listTables(): ConnectorResponse[Seq[TableModel]] = notImplementedOperation(generateNotImplementedMessage("listTables")) def listTablesWithFields(): ConnectorResponse[Seq[FullTableModel]] = notImplementedOperation(generateNotImplementedMessage("listTablesWithFields")) def listFields(table: String): ConnectorResponse[Seq[FieldModel]] = notImplementedOperation(generateNotImplementedMessage("listFields")) def isOptimized(table: String, fields: Seq[String]): ConnectorResponse[Boolean] = notImplementedOperation(generateNotImplementedMessage("isOptimized")) def simpleSelect(select: SimpleSelect, timeout: FiniteDuration): ConnectorResponse[Source[Seq[String], NotUsed]] = notImplementedOperation(generateNotImplementedMessage("simpleSelect")) def rawSelect(rawSql: String, limit: Option[Int], timeout: FiniteDuration): ConnectorResponse[Source[Seq[String], NotUsed]] = notImplementedOperation(generateNotImplementedMessage("rawSelect")) def validateRawSelect(rawSql: String): ConnectorResponse[Unit] = notImplementedOperation(generateNotImplementedMessage("validateRawSelect")) def analyzeRawSelect(rawSql: String): ConnectorResponse[Source[Seq[String], NotUsed]] = notImplementedOperation(generateNotImplementedMessage("analyzeRawSelect")) def projectedRawSelect(rawSql: String, fields: Seq[String], limit: Option[Int], timeout: FiniteDuration, allowNullFieldValue: Boolean = false): ConnectorResponse[Source[Seq[String], NotUsed]] = notImplementedOperation(generateNotImplementedMessage("projectedRawSelect")) def validateProjectedRawSelect(rawSql: String, fields: Seq[String]): ConnectorResponse[Unit] = notImplementedOperation(generateNotImplementedMessage("validateProjectedRawSelect")) def rawQuery(rawSql: String, timeout: FiniteDuration): ConnectorResponse[Int] = notImplementedOperation(generateNotImplementedMessage("rawQuery")) final def selectWithGroupLimit(select: SimpleSelect, groupLimit: Int, timeout: FiniteDuration): ConnectorResponse[Source[Seq[String], NotUsed]] = { import ValidateGroupLimitableQuery.GroupLimitValidationResult._ groupLimitValidator.groupLimitableQueryValidation(select) match { case Simple => simpleSelect(select.copy(limit = Option(groupLimit)), timeout) case Groupable(references) => runSelectWithGroupLimit(select, groupLimit, references, timeout) case NotGroupable => Future.successful(Left(SimpleSelectIsNotGroupableFormat(select.toString))) } } protected def runSelectWithGroupLimit(select: SimpleSelect, groupLimit: Int, references: Seq[String], timeout: FiniteDuration): ConnectorResponse[Source[Seq[String], NotUsed]] = { simpleSelect(select, timeout).map(_.map(_.via(GroupWithLimitStage(references, groupLimit)))) } protected def rawUpdate(tableName: String, definitions: Seq[UpdateDefinition]): ConnectorResponse[Int] = notImplementedOperation(generateNotImplementedMessage("rawUpdate")) protected def rawInsertData(tableName: String, definitions: Seq[Record]): ConnectorResponse[Int] = notImplementedOperation(generateNotImplementedMessage("rawInsertData")) protected def rawReplaceData(tableName: String, definitions: Seq[Record]): ConnectorResponse[Int] = notImplementedOperation(generateNotImplementedMessage("rawReplaceData")) protected def rawUpsert(tableName: String, definitions: Seq[Record]): ConnectorResponse[Int] = notImplementedOperation(generateNotImplementedMessage("rawUpsert")) protected def rawDelete(tableName: String, criteria: Seq[Criteria]): ConnectorResponse[Int] = notImplementedOperation(generateNotImplementedMessage("rawDelete")) protected def rawSearch(tableName: String, criteria: Criteria, limit: Option[Int], timeout: FiniteDuration): ConnectorResponse[Source[Seq[String], NotUsed]] = { val query = SimpleSelect( fields = AllField, table = TableName(tableName), where = Some(createWhereCondition(criteria)), limit = limit ) simpleSelect(query, timeout) } private def createWhereCondition(criteria: Criteria): WhereCondition = { import com.emarsys.rdb.connector.common.defaults.FieldValueConverter._ import fieldValueConverters._ And( criteria .mapValues(_.toSimpleSelectValue) .map { case (field, Some(value)) => EqualToValue(FieldName(field), value) case (field, None) => IsNull(FieldName(field)) }.toSeq ) } final def update(tableName: String, definitions: Seq[UpdateDefinition]): ConnectorResponse[Int] = { validateAndExecute(ValidateDataManipulation.validateUpdateDefinition, tableName, rawUpdate, definitions) } final def insertIgnore(tableName: String, records: Seq[Record]): ConnectorResponse[Int] = { validateAndExecute(ValidateDataManipulation.validateInsertData, tableName, rawInsertData, records) } final def replaceData(tableName: String, records: Seq[Record]): ConnectorResponse[Int] = { validateAndExecute(ValidateDataManipulation.validateInsertData, tableName, rawReplaceData, records) } final def upsert(tableName: String, definitions: Seq[Record]): ConnectorResponse[Int] = { validateAndExecute(ValidateDataManipulation.validateInsertData, tableName, rawUpsert, definitions) } final def delete(tableName: String, criteria: Seq[Criteria]): ConnectorResponse[Int] = { validateAndExecute(ValidateDataManipulation.validateDeleteCriteria, tableName, rawDelete, criteria) } final def search(tableName: String, criteria: Criteria, limit: Option[Int], timeout: FiniteDuration): ConnectorResponse[Source[Seq[String], NotUsed]] = { ValidateDataManipulation.validateSearchCriteria(tableName, criteria, this).flatMap { case ValidationResult.Valid => rawSearch(tableName, criteria, limit, timeout) case failedValidationResult => Future.successful(Left(FailedValidation(failedValidationResult))) } } private def validateAndExecute[T]( validationFn: (String, Seq[T], Connector) => Future[ValidationResult], tableName: String, executionFn: (String, Seq[T]) => ConnectorResponse[Int], data: Seq[T]) = { validationFn(tableName, data, this).flatMap { case ValidationResult.Valid => executionFn(tableName, data) case failedValidationResult => Future.successful(Left(FailedValidation(failedValidationResult))) } } private def generateNotImplementedMessage(operation: String): String = { s"$operation not implemented" } } trait ConnectorCompanion { def meta(): MetaData }
emartech/rdb-connector-common
src/main/scala/com/emarsys/rdb/connector/common/models/DataManipulation.scala
<gh_stars>0 package com.emarsys.rdb.connector.common.models object DataManipulation { type Record = Map[String, FieldValueWrapper] type Criteria = Record case class UpdateDefinition(search: Criteria, update: Record) case class StringedUpdateDefinition(search: Map[String, String], update: Map[String, String]) sealed trait FieldValueWrapper object FieldValueWrapper { case class StringValue(string: String) extends FieldValueWrapper case class IntValue(int: Int) extends FieldValueWrapper case class BigDecimalValue(number: BigDecimal) extends FieldValueWrapper case class BooleanValue(boolean: Boolean) extends FieldValueWrapper case object NullValue extends FieldValueWrapper } }
lindemer/pmp
src/test/scala/PmpTester.scala
<filename>src/test/scala/PmpTester.scala<gh_stars>0 /* * Copyright (c) 2021 <NAME> <<EMAIL>> * * SPDX-License-Identifier: Apache-2.0 */ package pmp import org.scalatest.FunSuite import spinal.core._ import spinal.core.sim._ import config.PmpConfig import scala.sys.process._ import scala.util.Random class PmpTester extends FunSuite { var compiled: SimCompiled[PmpController] = null val count = 16 var vec0 = Array.fill(count){Random.nextInt(1000000000)} var vec1 = Array.fill(count){Random.nextInt(1000000000)} var vec2 = (0 until count).map(idx => 0x00ffbfff >> (16 - idx)) test("compile") { compiled = PmpConfig().compile(new PmpController(count = count)) } test("lock") { compiled.doSim(seed = 2) { dut => dut.clockDomain.forkStimulus(10) // Write the pmpaddr# registers. for (idx <- 0 until count) { dut.io.write.valid #= true dut.io.config #= false dut.io.index #= idx dut.io.write.payload #= vec0(idx) dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } // Write the pmpcfg# registers. for (idx <- Range(0, count, 4)) { dut.io.write.valid #= true dut.io.config #= true dut.io.index #= idx dut.io.write.payload #= BigInt("07880789", 16) dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } // Overwrite the pmpcfg# registers. for (idx <- Range(0, count, 4)) { dut.io.write.valid #= true dut.io.config #= true dut.io.index #= idx dut.io.write.payload #= BigInt("03030303", 16) dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } // Check all but the last pmpcfg# registers. if (count > 4) { for (idx <- Range(0, count - 4, 4)) { dut.io.write.valid #= false dut.io.config #= true dut.io.index #= idx dut.clockDomain.waitSampling(1) assert(dut.io.read.toBigInt == BigInt("87888789", 16), "dut.io.readData missmatch") } } // Check the last pmpcfg#. Only the last pmp#cfg should be unlocked. dut.io.write.valid #= false dut.io.config #= true dut.io.index #= count - 1 dut.clockDomain.waitSampling(1) assert(dut.io.read.toBigInt == BigInt("03888789", 16), "dut.io.readData missmatch") // Write the pmpaddr# registers. for (idx <- 0 until count) { dut.io.write.valid #= true dut.io.config #= false dut.io.index #= idx dut.io.write.payload #= vec1(idx) dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } // Check all but the last pmpaddr# registers. for (idx <- 0 until count - 1) { dut.io.write.valid #= false dut.io.config #= false dut.io.index #= idx dut.clockDomain.waitSampling(1) assert(dut.io.read.toBigInt == BigInt(vec0(idx)), "dut.io.readData missmatch") } // Check the last pmpaddr#. Only this one should be overwritten. dut.io.write.valid #= false dut.io.config #= false dut.io.index #= count - 1 dut.clockDomain.waitSampling(1) assert(dut.io.read.toBigInt == BigInt(vec1(count - 1)), "dut.io.readData missmatch") } } test("tor") { compiled.doSim(seed = 2) { dut => dut.clockDomain.forkStimulus(10) // Write the pmpaddr# registers. for (idx <- 0 until count) { dut.io.write.valid #= true dut.io.config #= false dut.io.index #= idx dut.io.write.payload #= 4 << idx dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } // Write the pmpcfg# registers. for (idx <- Range(0, count, 4)) { dut.io.write.valid #= true dut.io.config #= true dut.io.index #= idx dut.io.write.payload #= BigInt("08080808", 16) dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } dut.clockDomain.waitSampling(1) assert(dut.boundLo.getBigInt(0) == BigInt(0), "dut.boundLo(idx) missmatch") assert(dut.boundHi.getBigInt(0) == BigInt(1), "dut.boundHi(idx) missmatch") // Check all but the first pmpaddr# registers. for (idx <- 1 until count) { assert(dut.boundLo.getBigInt(idx) == BigInt(1 << (idx - 1)), "dut.boundLo(idx) missmatch") assert(dut.boundHi.getBigInt(idx) == BigInt(1 << idx), "dut.boundHi(idx) missmatch") } } } test("na4") { compiled.doSim(seed = 2) { dut => dut.clockDomain.forkStimulus(10) // Write the pmpaddr# registers. for (idx <- 0 until count) { dut.io.write.valid #= true dut.io.config #= false dut.io.index #= idx dut.io.write.payload #= 4 << idx dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } // Write the pmpcfg# registers. for (idx <- Range(0, count, 4)) { dut.io.write.valid #= true dut.io.config #= true dut.io.index #= idx dut.io.write.payload #= BigInt("10101010", 16) dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } dut.clockDomain.waitSampling(1) // Check all pmpaddr# registers. for (idx <- 0 until count) { assert(dut.boundLo.getBigInt(idx) == BigInt(1 << idx), "dut.boundLo(idx) missmatch") assert(dut.boundHi.getBigInt(idx) == BigInt((1 << idx) + 1), "dut.boundHi(idx) missmatch") } } } test("napot") { compiled.doSim(seed = 2) { dut => dut.clockDomain.forkStimulus(10) // Write the pmpaddr# registers. for (idx <- 0 until count) { dut.io.write.valid #= true dut.io.config #= false dut.io.index #= idx dut.io.write.payload #= vec2(idx) dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } // Write the pmpcfg# registers. for (idx <- Range(0, count, 4)) { dut.io.write.valid #= true dut.io.config #= true dut.io.index #= idx dut.io.write.payload #= BigInt("18181818", 16) dut.clockDomain.waitSampling(1) while (!dut.io.write.ready.toBoolean) { dut.clockDomain.waitSampling(1) } } dut.clockDomain.waitSampling(1) // Check all pmpaddr# registers. for (idx <- 1 until count) { val mask = vec2(idx) & ~(vec2(idx) + 1) val boundLo = (vec2(idx) ^ mask) val boundHi = boundLo + ((mask + 1) << 3) assert(dut.boundLo.getBigInt(idx) == BigInt(boundLo), "dut.boundLo(idx) missmatch") assert(dut.boundHi.getBigInt(idx) == BigInt(boundHi), "dut.boundHi(idx) missmatch") } } } }
lindemer/pmp
src/main/scala/PmpMain.scala
package pmp import spinal.core._ object PmpMain { def main(args: Array[String]) { SpinalConfig(targetDirectory = "rtl").generateVhdl(new PmpController(count = 16)) } }
lindemer/pmp
src/main/scala/Pmp.scala
/* * Copyright (c) 2021 <NAME> <<EMAIL>> * * SPDX-License-Identifier: Apache-2.0 */ package pmp import spinal.core.sim._ import spinal.core._ import spinal.lib._ /* Each 32-bit pmpcfg# register contains four 8-bit configuration sections. * These section numbers contain flags which apply to regions defined by the * corresponding pmpaddr# register. * * 3 2 1 * 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | pmp3cfg | pmp2cfg | pmp1cfg | pmp0cfg | pmpcfg0 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | pmp7cfg | pmp6cfg | pmp5cfg | pmp4cfg | pmpcfg2 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * 7 6 5 4 3 2 1 0 * +-------+-------+-------+-------+-------+-------+-------+-------+ * | L | 0 | A | X | W | R | pmp#cfg * +-------+-------+-------+-------+-------+-------+-------+-------+ * * L: locks configuration until system reset (including M-mode) * 0: hardwired to zero * A: 0 = OFF (null region / disabled) * 1 = TOR (top of range) * 2 = NA4 (naturally aligned four-byte region) * 3 = NAPOT (naturally aligned power-of-two region, > 7 bytes) * X: execute * W: write * R: read * * TOR: Each 32-bit pmpaddr# register defines the upper bound of the pmp region * right-shifted by two bits. The lower bound of the region is the previous * pmpaddr# register. In the case of pmpaddr0, the lower bound is address 0x0. * * 3 2 1 * 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | address[33:2] | pmpaddr# * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * NAPOT: Each 32-bit pmpaddr# register defines the region address and the size * of the pmp region. The number of concurrent 1s begging at the LSB indicates * the size of the region as a power of two (e.g. 0x...0 = 8-byte, 0x...1 = * 16-byte, 0x...11 = 32-byte, etc.). * * 3 2 1 * 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | address[33:2] |0|1|1|1|1| pmpaddr# * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * NA4: This is essentially an edge case of NAPOT where the entire pmpaddr# * register defines a 4-byte wide region. */ trait Pmp { def OFF = 0 def TOR = 1 def NA4 = 2 def NAPOT = 3 def xlen = 32 def rBit = 0 def wBit = 1 def xBit = 2 def aBits = 4 downto 3 def lBit = 7 } class PmpSetter() extends Component with Pmp { val io = new Bundle { val a = in Bits(2 bits) val addr = in UInt(xlen bits) val prevHi = in UInt(30 bits) val boundLo, boundHi = out UInt(30 bits) } val shifted = io.addr(31 downto 2) io.boundLo := shifted io.boundHi := shifted switch (io.a) { is (TOR) { io.boundLo := io.prevHi } is (NA4) { io.boundHi := shifted + 1 } is (NAPOT) { val mask = io.addr & ~(io.addr + 1) val boundLo = (io.addr ^ mask)(29 downto 0) io.boundLo := boundLo io.boundHi := boundLo + ((mask + 1) |<< 3)(29 downto 0) } } } class PmpController(count : Int) extends Component with Pmp { assert(count % 4 == 0) assert(count <= 16) val pmpaddr = Mem(UInt(xlen bits), count) val pmpcfg = Reg(Bits(8 * count bits)) init(0) val boundLo, boundHi = Mem(UInt(30 bits), count) simPublic() val io = new Bundle { val config = in Bool val index = in UInt(log2Up(count) bits) val read = out Bits(xlen bits) val write = slave Stream(Bits(xlen bits)) } val cfgSel = io.index(log2Up(count) - 1 downto 2) val pmpcfgs = pmpcfg.subdivideIn(xlen bits) val pmpcfgN = pmpcfgs(cfgSel) val pmpNcfg = pmpcfgN.subdivideIn(8 bits) val csr = new Area { when (io.config) { when (io.write.valid) { switch(cfgSel) { for (i <- 0 until (count / 4)) { is(i) { for (j <- Range(0, xlen, 8)) { val bitRange = j + xlen * i + lBit downto j + xlen * i val overwrite = io.write.payload.subdivideIn(8 bits)(j / 8) val locked = pmpcfgs(i).subdivideIn(8 bits)(j / 8)(lBit) when (~locked) { pmpcfg(bitRange).assignFromBits(overwrite) if (j != 0 || i != 0) { when (overwrite(lBit) & overwrite(aBits) === TOR) { pmpcfg(j + xlen * i - 1) := True } } } } } } } } io.read.assignFromBits(pmpcfgN) } otherwise { when (io.write.valid) { val lock = pmpNcfg(io.index(1 downto 0))(lBit) pmpaddr.write( io.index, io.write.payload.asUInt, io.write.valid & ~io.config & ~lock ) } io.read := pmpaddr.readAsync(io.index).asBits } } val pipeline = new Area { val setter = new PmpSetter() val enable = RegInit(False) val counter = Reg(UInt(log2Up(count) bits)) val setNext = RegInit(False) when (io.config) { when (io.write.valid & ~enable) { enable := True io.write.ready := False counter := io.index(log2Up(count) - 1 downto 2) @@ U"2'00" }.elsewhen (enable) { counter := counter + 1 when (counter(1 downto 0) === 3) { enable := False io.write.ready := True } otherwise { io.write.ready := False } } otherwise { io.write.ready := True } } otherwise { when (io.write.valid & ~enable) { enable := True counter := io.index io.write.ready := False when (io.index =/= (count - 1)) { setNext := True } otherwise { setNext := False } }.elsewhen (setNext) { io.write.ready := False counter := counter + 1 setNext := False } otherwise { enable := False io.write.ready := True } } val sel = counter(log2Up(count) - 1 downto 2) setter.io.a := pmpcfgs(sel).subdivideIn(8 bits)(counter(1 downto 0))(aBits) when (counter === 0) { setter.io.prevHi := 0 } otherwise { setter.io.prevHi := boundHi(counter - 1) } setter.io.addr := pmpaddr(counter) when (enable) { boundLo(counter) := setter.io.boundLo boundHi(counter) := setter.io.boundHi } } }