code
stringlengths
5
1M
repo_name
stringlengths
5
109
path
stringlengths
6
208
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1M
package fp_in_scala.chapter_04 /** * Created by jankeesvanandel on 14/11/15. */ sealed trait Validation[+E, +A] { def map[B](f: A => B): Validation[E, B] = this match { case l: Errors[E] => l case Success(a) => Success(f(a)) } def map2[EE >: E, B, C](b: => Validation[EE, B])(f: (A, B) => C): Validation[EE, C] = this match { case l1: Errors[E] => b match { case l2: Errors[E] => Errors(l1.get ++ l2.get) case _ => l1 } case Success(a) => b.map(f(a, _)) } } case class Errors[+E](get: Seq[E]) extends Validation[E, Nothing] case class Success[+A](get: A) extends Validation[Nothing, A] object Validation { def sequence[E, A](es: List[Validation[E, A]]): Validation[E, List[A]] = { traverse(es)(e => e) } def traverse[E, A, B](as: List[A])(f: A => Validation[E, B]): Validation[E, List[B]] = { as.foldRight[Validation[E, List[B]]](Success(Nil))((a, b) => f(a).map2(b)(_ :: _)) } }
jankeesvanandel/fp-in-scala
src/main/scala/fp_in_scala/chapter_04/Validation.scala
Scala
apache-2.0
946
package eveapi.data.crest import java.time._ case class FleetUrl[L](href: L) extends GetLink[L, Fleet[L]] with PutLink[L, FleetUpdate] case class FleetUpdate(isFreeMove: Option[Boolean] = None, motd: Option[String] = None) // TODO write circe/argonaut codecs for this one sealed abstract class InviteMember[L] extends Serializable with Product { def role: String def wingID: Option[Long] def squadID: Option[Long] def character: GetLinkI[L, Character[L]] } object InviteMember { case class FleetCommander[L](character: GetLinkI[L, Character[L]]) extends InviteMember[L] { def role = "fleetCommander" val wingID = None val squadID = None } case class WingCommander[L](character: GetLinkI[L, Character[L]], wingId: Long) extends InviteMember[L] { def role = "wingCommander" val wingID = Some(wingId) val squadID = None } case class SquadCommander[L](character: GetLinkI[L, Character[L]], wingId: Long, squadId: Long) extends InviteMember[L] { def role = "squadCommander" val wingID = Some(wingId) val squadID = Some(squadId) } case class SquadMember[L](character: GetLinkI[L, Character[L]], wingId: Long, squadId: Long) extends InviteMember[L] { def role = "squadMember" val wingID = Some(wingId) val squadID = Some(squadId) } case class RandomInvite[L](character: GetLinkI[L, Character[L]]) extends InviteMember[L] { def role = "squadMember" val wingID = None val squadID = None } } case class Fleet[L]( isFreeMove: Boolean, isRegistered: Boolean, isVoiceEnabled: Boolean, motd: String, wings: GetLinkI[L, Paginated[Wing[L]]], members: GetPostLink[L, Paginated[Member[L]], InviteMember[L]] ) /** * Choose one of: squadMember, squadCommander, wingCommander, fleetCommander */ case class MoveMember[L]( role: String = "squadMember", newWingId: Option[Long], squadID: Option[Long]) case class Member[L]( boosterID: Short, character: StandardIdentifier[L, Character], joinTime: Instant, roleID: Short, ship: StandardIdentifier[L, Ship], solarSystem: StandardIdentifier[L, SolarSystem], squadID: Long, station: Option[StandardIdentifier[L, Station]], takesFleetWarp: Boolean, wingID: Long, href: L ) extends PutLink[L, MoveMember[L]] with DeleteLink[L] case class Wing[L]( id: Long, name: String, squadsList: List[Squad[L]], squads: PostLinkI[L, Empty], href: L ) extends PutLink[L, Name] with DeleteLink[L] case class Name(name: String) case class Squad[L]( id: Long, name: String, href: L ) extends PutLink[L, Name] with DeleteLink[L] case class Ship[L]()
scala-eveapi/eveapi
data/src/main/scala/eveapi/data/crest/fleet.scala
Scala
mit
2,648
package org.jetbrains.plugins.scala package format import org.jetbrains.plugins.scala.base.SimpleTestCase import org.jetbrains.plugins.scala.lang.psi.api.expr.ScExpression import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory.createExpressionFromText import org.junit.Assert._ /** * Pavel Fatin */ class InterpolatedStringFormatterTest extends SimpleTestCase { def testEmpty() { assertEquals("", format()) } def testText() { assertEquals("foo", format(Text("foo"))) } def testEscapeChar() { val text = Text("\\n") assertEquals("\\\\n", format(text)) assertEquals(quoted("\\n", multiline = true), formatFull(text)) } def testSlash() { assertEquals("\\\\\\\\", format(Text("\\\\"))) } def testDollar() { assertEquals("$$", format(Text("$"))) assertEquals(quoted("$"), formatFull(Text("$"))) val parts = Seq(Text("$ "), Injection(exp("amount"), None)) assertEquals("$$ $amount", format(parts: _*)) assertEquals(quoted("$$ $amount", prefix = "s"), formatFull(parts: _*)) } def testPlainExpression() { val injection = Injection(exp("foo"), None) assertEquals("$foo", format(injection)) assertEquals(quoted("$foo", prefix = "s"), formatFull(injection)) } def testExpressionWithDispensableFormat() { val injection = Injection(exp("foo"), Some(Specifier(null, "%d"))) assertEquals(quoted("$foo", prefix = "s"), formatFull(injection)) } def testExpressionWithMadatoryFormat() { val injection = Injection(exp("foo"), Some(Specifier(null, "%2d"))) assertEquals(quoted("$foo%2d", prefix = "f"), formatFull(injection)) } def testPlainLiteral() { assertEquals(quoted("123"), formatFull(Injection(exp("123"), None))) } def testLiteralWithDispensableFormat() { val injection = Injection(exp("123"), Some(Specifier(null, "%d"))) assertEquals(quoted("123"), formatFull(injection)) } def testLiteralWithMadatoryFormat() { val injection = Injection(exp("123"), Some(Specifier(null, "%2d"))) assertEquals(quoted("${123}%2d", prefix = "f"), formatFull(injection)) } def testPlainComplexExpression() { val injection = Injection(exp("foo.bar"), None) assertEquals(quoted("${foo.bar}", prefix = "s"), formatFull(injection)) } def testComplexExpressionWithDispensableFormat() { val injection = Injection(exp("foo.bar"), Some(Specifier(null, "%d"))) assertEquals(quoted("${foo.bar}", prefix = "s"), formatFull(injection)) } def testComplexExpressionWithMadatoryFormat() { val injection = Injection(exp("foo.bar"), Some(Specifier(null, "%2d"))) assertEquals(quoted("${foo.bar}%2d", prefix = "f"), formatFull(injection)) } def testPlainBlockExpression() { val injection = Injection(exp("{foo.bar}"), None) assertEquals(quoted("${foo.bar}", prefix = "s"), formatFull(injection)) } def testBlockExpressionWithDispensableFormat() { val injection = Injection(exp("{foo.bar}"), Some(Specifier(null, "%d"))) assertEquals(quoted("${foo.bar}", prefix = "s"), formatFull(injection)) } def testBlockExpressionWithMadatoryFormat() { val injection = Injection(exp("{foo.bar}"), Some(Specifier(null, "%2d"))) assertEquals(quoted("${foo.bar}%2d", prefix = "f"), formatFull(injection)) } def testMixedParts() { val parts = Seq(Text("foo "), Injection(exp("exp"), None), Text(" bar")) assertEquals(quoted("foo $exp bar", prefix = "s"), formatFull(parts: _*)) } def testLiterals() { val stringLiteral = exp(quoted("foo")) assertEquals(quoted("foo"), formatFull(Injection(stringLiteral, None))) val longLiteralInjection = Injection(exp("123L"), None) assertEquals(quoted("123"), formatFull(longLiteralInjection)) val booleanLiteralInjection = Injection(exp("true"), None) assertEquals(quoted("true"), formatFull(booleanLiteralInjection)) } def testOther() { assertEquals("", format(UnboundExpression(exp("foo")))) } private def format(parts: StringPart*): String = { InterpolatedStringFormatter.formatContent(parts) } //with prefix and quotes private def formatFull(parts: StringPart*): String = { InterpolatedStringFormatter.format(parts) } private def quoted(s: String, multiline: Boolean = false, prefix: String = "") = { val quote = if (multiline) "\\"\\"\\"" else "\\"" s"$prefix$quote$s$quote" } private def exp(s: String): ScExpression = { createExpressionFromText(s)(fixture.getProject) } }
jastice/intellij-scala
scala/scala-impl/test/org/jetbrains/plugins/scala/format/InterpolatedStringFormatterTest.scala
Scala
apache-2.0
4,481
package chandu0101.scalajs.facades.examples.pages.components.leaflet import chandu0101.scalajs.facades.examples.pages.common.CodeExample import chandu0101.scalajs.facades.leaflet._ import japgolly.scalajs.react.ReactComponentB import japgolly.scalajs.react.vdom.all._ import scala.scalajs.js.Dynamic.{global => g, literal => json} /** * Created by chandrasekharkode on 3/3/15. */ object LMarkersDemo { val code = """ | div( id := "map", width := "600px", height := "285px") | | val RANDOM_LOCATIONS = Map( | "Tenali" -> LLatLng(16.2428, 80.6400), | "Vijayawada" -> LLatLng(16.5083, 80.6417), | "Machilipatnam" -> LLatLng(16.1700, 81.1300), | "Amaravati" -> LLatLng(16.5728, 80.3575), | "Guntur" -> LLatLng(16.3008, 80.4428) | ) | | // define map | val map = LMap("map").setView(MY_LOCATION, 8.0) | map.addLayer(getTileLayer) | LIconDefault.imagePath = "images/" // set images path | RANDOM_LOCATIONS.map { | case (place,latlng) => LMarker(latlng).bindPopup(place).addTo(map) | } | """.stripMargin val component = ReactComponentB[Unit]("LMarkersDemo") .render(P => { div( h3("Multiple Markers"), CodeExample(code)( div(key := "map", id := "map", width := "600px", height := "285px") ) ) }) .componentDidMount(scope => { // define map val map = LMap("map").setView(MY_LOCATION, 9.0) map.addLayer(getTileLayer) LIconDefault.imagePath = "images" // set images path RANDOM_LOCATIONS.map { case (place,latlng) => LMarker(latlng).bindPopup(place).addTo(map) } }) .buildU def apply() = component() }
chandu0101/scalajs-facades
examples/src/main/scala/chandu0101/scalajs/facades/examples/pages/components/leaflet/LMarkersDemo.scala
Scala
mit
1,763
package spgui.widgets import java.time._ import java.text.SimpleDateFormat import java.util.UUID import japgolly.scalajs.react._ import japgolly.scalajs.react.vdom.html_<^._ import japgolly.scalajs.react.ReactDOM import spgui.SPWidget import spgui.widgets.css.{WidgetStyles => Styles} import spgui.communication._ import sp.domain._ import sp.domain.Logic._ import org.singlespaced.d3js.d3 import org.singlespaced.d3js.Ops._ import scala.concurrent.duration._ import scala.scalajs.js import scala.util.{Success, Try} import scala.util.Random.nextInt import org.scalajs.dom import org.scalajs.dom.raw import org.scalajs.dom.{svg => *} import org.singlespaced.d3js.d3 import org.singlespaced.d3js.Ops._ import spgui.circuit.SPGUICircuit import scalacss.ScalaCssReact._ import scalacss.DevDefaults._ import scala.collection.mutable.ListBuffer import sp.erica.{API_PatientEvent => api} import sp.erica.{API_Patient => apiPatient} object PlaceWidget { private class Backend($: BackendScope[String, Map[String, apiPatient.Patient]]) { var patientObs = Option.empty[rx.Obs] def setPatientObs(): Unit = { patientObs = Some(spgui.widgets.akuten.PatientModel.getPatientObserver( patients => $.setState(patients).runNow() )) } val wsObs = BackendCommunication.getWebSocketStatusObserver( mess => { if (mess) send(api.GetState) }, "patient-cards-widget-topic") def send(mess: api.Event) { val json = ToAndFrom.make(SPHeader(from = "PatientCardsWidget", to = "WidgetService"), mess) BackendCommunication.publish(json, "widget-event") } def render(team: String, p: Map[String, apiPatient.Patient]) = { <.div(Styles.helveticaZ) } def onUnmount() = { println("Unmounting") patientObs.foreach(_.kill()) wsObs.kill() Callback.empty } } def extractTeam(attributes: Map[String, SPValue]) = { attributes.get("team").flatMap(x => x.asOpt[String]).getOrElse("medicin") } private val component = ScalaComponent.builder[String]("TeamStatusWidget") .initialState(Map("-1" -> EricaLogic.dummyPatient)) .renderBackend[Backend] .componentDidMount(ctx => Callback(ctx.backend.setPatientObs())) .componentDidUpdate(ctx => Callback(addTheD3(ctx.getDOMNode, ctx.currentState, ctx.currentProps))) .componentWillUnmount(_.backend.onUnmount()) .build /** * Checks if the patient belongs to this team. */ def belongsToThisTeam(patient: apiPatient.Patient, filter: String): Boolean = { filter.isEmpty || patient.team.team.contains(filter) } def getPlace(patient: apiPatient.Patient): String = { if (patient.examination.isOnExam) "Examination" else if (patient.location.roomNr == "ivr" || patient.location.roomNr == "iv") "InnerWaitingRoom" else if (patient.location.roomNr != "") "RoomOnSquare" else "Other" } private def addTheD3(element: raw.Element, initialPlaceMap: Map[String, apiPatient.Patient], filter: String): Unit = { d3.select(element).selectAll("*").remove() val width = element.clientWidth // Kroppens bredd val height = (86/419.0)*width // Kroppens höjd val barHeight = (35.4/419.0)*width // Grafernas höjd val smallRec = (15/419.0)*width // Höjd samt bredd, små rektanglar val sizeNumbers = s"${(23/419.0)*width}px" // Storlek på siffror inuti graferna val sizeText = s"${(13/419.0)*width}px" // Storlek på text intill små rektanglar val fontSize = s"${(22/419.0)*width}" def distance(d: Double): Double = { // Placerar siffran på rätt avstånd från sidan av grafen. if(d > 99) {(50/419.0)*width} else if(d > 9) {(35/419.0)*width} else {(20/419.0)*width} } def removeZero(d: Double): String ={ // Ifall det är noll patienter i en kategori så skriver den inte ut nollan. if(d.equals(0)) {""} else {d.toString()} } // ------- Färger --------- val colorBarOne = "#4d5256" val colorBarTwo = "#1b998b" val colorBarThree = "#9df2e9" val colorBarFour = "#f5fffe" val colorNumbersLight = "#FFFFFF" val colorNumbersDark = "#000000" // ------------------------- // TODO: Never use vars if not needed in scala. Use map and foldLeft if you need to aggregate var teamMap: Map[String, apiPatient.Patient] = (initialPlaceMap - "-1").filter(p => belongsToThisTeam(p._2, filter)) var roomOnSquareCount = 0 var innerWaitingRoomCount = 0 var examinationCount = 0 var otherCount = 0 teamMap.foreach{ p => getPlace(p._2) match { case "RoomOnSquare" => roomOnSquareCount += 1 case "InnerWaitingRoom" => innerWaitingRoomCount += 1 case "Examination" => examinationCount += 1 case "Other" => otherCount += 1 } } var placeMap: Map[String, Double] = Map( "RoomOnSquare" -> roomOnSquareCount, "InnerWaitingRoom" -> innerWaitingRoomCount, "Examination" -> examinationCount, "Other" -> otherCount ) var length: Map[String, Double] = Map( "RoomOnSquare" -> 0, "InnerWaitingRoom" -> 0, "Examination" -> 0, "Other" -> 0 ) placeMap.foreach{ p => val sum = placeMap("RoomOnSquare") + placeMap("InnerWaitingRoom") + placeMap("Examination") + placeMap("Other") if (sum == 0) { length += p._1 -> 0 } else { length += p._1 -> (p._2/(sum))*width } } val svg = d3.select(element).append("svg") .attr("width", width) .attr("height", height) val g = svg.append("g") // ----------- Graf ett ------------- g.append("rect") .attr("x", 0) .attr("y", (50/419.0)*width) .attr("width", length("RoomOnSquare")) .attr("height", barHeight) .attr("fill", colorBarOne) svg.append("text") .attr("x", length("RoomOnSquare") - distance(placeMap("RoomOnSquare"))) .attr("y", (75/419.0)*width) .attr("font-size", fontSize) .text(s"${removeZero(placeMap("RoomOnSquare"))}") .attr("fill", colorNumbersLight) // ----------- Graf två ------------- g.append("rect") .attr("x", length("RoomOnSquare")) .attr("y", (50/419.0)*width) .attr("width", length("InnerWaitingRoom")) .attr("height", barHeight) .attr("fill", colorBarTwo) svg.append("text") .attr("x", length("RoomOnSquare") + length("InnerWaitingRoom") - distance(placeMap("InnerWaitingRoom"))) .attr("y", (75/419.0)*width) .attr("font-size", fontSize) .text(s"${removeZero(placeMap("InnerWaitingRoom"))}") .attr("fill", colorNumbersLight) // ----------- Graf tre ------------- g.append("rect") .attr("x", length("InnerWaitingRoom") + length("RoomOnSquare")) .attr("y", (50/419.0)*width) .attr("width", length("Examination")) .attr("height", barHeight) .attr("fill", colorBarThree) svg.append("text") .attr("x", length("RoomOnSquare") + length("InnerWaitingRoom") + length("Examination") - distance(placeMap("Examination"))) .attr("y", (75/419.0)*width) .attr("font-size", fontSize) .text(s"${removeZero(placeMap("Examination"))}") .attr("fill", colorNumbersDark) // ----------- Graf fyra ------------- g.append("rect") .attr("x", length("Examination") + length("InnerWaitingRoom") + length("RoomOnSquare")) .attr("y", (50/419.0)*width) .attr("width", length("Other")) .attr("height", barHeight) .attr("fill", colorBarFour) svg.append("text") .attr("x", length("RoomOnSquare") + length("InnerWaitingRoom") + length("Examination") + length("Other") - distance(placeMap("Other"))) .attr("y", (75/419.0)*width) .attr("font-size", fontSize) .text(s"${removeZero(placeMap("Other"))}") .attr("fill", colorNumbersDark) // ------------------------------------ // -------- Små Rektanglar ------------ // --------- Rektangel ett ----------- g.append("rect") .attr("x", 0) .attr("y", (30/419.0)*width) .attr("width", smallRec) .attr("height", smallRec) .attr("fill", colorBarOne) svg.append("text") .attr("x", (20/419.0)*width) .attr("y", (42.5/419.0)*width) .attr("font-size", sizeText) .text("Rum på torg") // --------- Rektangel två ----------- g.append("rect") .attr("x", ((0 + 120)/419.0)*width) .attr("y", (30/419.0)*width) .attr("width", smallRec) .attr("height", smallRec) .attr("fill", colorBarTwo) svg.append("text") .attr("x", ((20 + 120)/419.0)*width) .attr("y", (42.5/419.0)*width) .attr("font-size", sizeText) .text("Inre väntrum") // --------- Rektangel tre ----------- g.append("rect") .attr("x", ((0 + 240)/419.0)*width) .attr("y", (30/419.0)*width) .attr("width", smallRec) .attr("height", smallRec) .attr("fill", colorBarThree) svg.append("text") .attr("x", ((20 + 240)/419.0)*width) .attr("y", (42.5/419.0)*width) .attr("font-size", sizeText) .text("Undersökning") // --------- Rektangel fyra ----------- g.append("rect") .attr("x", ((0 + 360)/419.0)*width) .attr("y", (30/419.0)*width) .attr("width", smallRec) .attr("height", smallRec) .attr("fill", colorBarFour) svg.append("text") .attr("x", ((20 + 360)/419.0)*width) .attr("y", (42.5/419.0)*width) .attr("font-size", sizeText) .text("Annat") // ------------------------------------ // ----------- PLATS -------------- svg.append("text") .attr("x", 0) .attr("y", (20/419.0)*width) .attr("font-size", s"${(15/419.0)*width}pt") .text("PLATS") .attr("fill", "#95989a") ^.`class` := "timeline-finished-bg" // --------------------------------- } def apply() = spgui.SPWidget(spwb => { val currentTeam = extractTeam(spwb.frontEndState.attributes) component(currentTeam) }) }
kristoferB/SP
sperica/frontend/src/main/scala/spgui/widgets/PlaceWidget.scala
Scala
mit
10,265
package org.opencompare.io.bestbuy import org.opencompare.hac.agglomeration.{CompleteLinkage, AgglomerationMethod} import org.opencompare.api.java.Product import org.opencompare.api.java.clustering.HierarchicalClusterer import scala.collection.JavaConversions._ /** * Created by gbecan on 4/10/15. */ class ProductClusterer { // var productMap : Map[String, Product] = Map.empty // private def calculateProductSimilarityByIntersection(currentProduct: Product, toCompareProduct: Product): Int = { // val intersection: Set[String] = getFeatureNamesWithoutEmptyValuesOfAProduct(currentProduct) // intersection.intersect(getFeatureNamesWithoutEmptyValuesOfAProduct(toCompareProduct)).size // } // // private def getFeatureNamesWithoutEmptyValuesOfAProduct(product: Product): Set[String] = { // val setOfFeaturesWithContent: Set[String] = mutable.Set.empty[String] // import scala.collection.JavaConversions._ // for (cell <- product.getCells) if (cell.getContent ne "N/A") setOfFeaturesWithContent.add(cell.getFeature.getName) // setOfFeaturesWithContent // } // def productDissimilarityMetric(p1Name : String, p2Name : String) : Double = { // // val p1 = productMap(p1Name) // val p2 = productMap(p2Name) def productDissimilarityMetric(p1 : Product, p2 : Product) : Double = { val featuresP1 = getFeatureNamesWithoutEmptyValues(p1) val featuresP2 = getFeatureNamesWithoutEmptyValues(p2) val intersection = featuresP1.intersect(featuresP2) val allFeaturesP1 = p1.getCells.map(_.getFeature.getName).toSet val allFeaturesP2 = p2.getCells.map(_.getFeature.getName).toSet val allFeatures = allFeaturesP1 union allFeaturesP2 (allFeatures.size - intersection.size.toDouble) / allFeatures.size } def getFeatureNamesWithoutEmptyValues(product : Product) : Set[String] = { product.getCells.filter(_.getContent != "N/A").map(_.getFeature.getName).toSet } def computeClustersOfProducts( products : List[Product], threshold : Option[Double], maxClusterSize : Option[Int], mergingCondition : Option[(List[Product], List[Product]) => Boolean], agglomerationMethod : AgglomerationMethod = new CompleteLinkage) : List[List[Product]] = { // productMap = products.map(p => (p.getName -> p)).toMap // val clusterer = new HierarchicalClusterer[String](productDissimilarityMetric, threshold, maxClusterSize) // val nameClusters = clusterer.cluster(products.map(_.getName)) // val clusters = nameClusters.map(c => c.map(name => productMap(name))) val clusterer = new HierarchicalClusterer[Product](productDissimilarityMetric, threshold, maxClusterSize, mergingCondition, agglomerationMethod) clusterer.cluster(products) } }
OpenCompare/OpenCompare
org.opencompare/io-best-buy/src/main/scala/org/opencompare/io/bestbuy/ProductClusterer.scala
Scala
apache-2.0
2,877
/* * Licensed to Intel Corporation under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Intel Corporation licenses this file to You 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 com.intel.analytics.bigdl.utils object Util { def kthLargest(arr: Array[Long], l: Int, r: Int, k: Int): Long = { if (k == 0) return Long.MaxValue val pos = randomPartition(arr, l, r) if (pos-l == k-1) return arr(pos) if (pos-l > k-1) return kthLargest(arr, l, pos-1, k) kthLargest(arr, pos + 1, r, k - pos + l - 1) } def swap(arr: Array[Long], i: Int, j: Int): Unit = { val temp = arr(i) arr(i) = arr(j) arr(j) = temp } private def partition(arr: Array[Long], l: Int, r: Int): Int = { val x = arr(r) var i = l for (j <- l to (r - 1)) { if (arr(j) > x) { swap(arr, i, j); i += 1 } } swap(arr, i, r); i } private def randomPartition(arr: Array[Long], l: Int, r: Int): Int = { val n = r - l + 1; val pivot = ((Math.random()) % n).toInt; swap(arr, l + pivot, r); partition(arr, l, r); } }
SeaOfOcean/BigDL
dl/src/main/scala/com/intel/analytics/bigdl/utils/Util.scala
Scala
apache-2.0
1,709
/* * Copyright 2017 HM Revenue & Customs * * 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 uk.gov.hmrc.ct.accounts.frs102.boxes import uk.gov.hmrc.ct.accounts.frs102.retriever.Frs102AccountsBoxRetriever import uk.gov.hmrc.ct.box._ case class AC209B(value: Option[Int]) extends CtBoxIdentifier(name = "Intangible assets - Other - Cost - Revaluations") with CtOptionalInteger with Input with ValidatableBox[Frs102AccountsBoxRetriever] with Validators { override def validate(boxRetriever: Frs102AccountsBoxRetriever): Set[CtValidation] = { collectErrors( validateMoney(value) ) } }
pncampbell/ct-calculations
src/main/scala/uk/gov/hmrc/ct/accounts/frs102/boxes/AC209B.scala
Scala
apache-2.0
1,131
package api.hue import api.hue.dao.attribute.{Attribute, TransitionTime} import api.hue.endpoint.{Groups, Lights} import com.google.inject.Inject import com.github.nscala_time.time.Imports._ import play.api.libs.json.JsValue import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future /** * Convenience methods for setting a group or light to various pre-defined states * @author ddexter */ class State @Inject() (groupsEndpoint: Groups, lightsEndpoint: Lights) { def sunrise(groupName: String, endTime: DateTime): Future[JsValue] = timedRun(groupName, endTime, ColorConstants.MAX_BRIGHT) def sunset(groupName: String, endTime: DateTime): Future[JsValue] = timedRun(groupName, endTime, ColorConstants.SUNSET) def off(groupName: String): Future[JsValue] = simpleRun(groupName, ColorConstants.OFF) def on(groupName: String): Future[JsValue] = simpleRun(groupName, ColorConstants.ON) def maxBright(groupName: String): Future[JsValue] = simpleRun(groupName, ColorConstants.MAX_BRIGHT) def wakeUp(groupName: String): Future[JsValue] = simpleRun(groupName, ColorConstants.MAX_DIM) private def simpleRun(groupName: String, attributes: Seq[Attribute]): Future[JsValue] = { groupsEndpoint.getGroupId(groupName).flatMap(maybeGroupId => { val groupId = maybeGroupId match { case Some(id) => id case _ => throw new IllegalArgumentException("Group name not found") } groupsEndpoint.put(groupId, attributes:_*) }) } /** * Slowly fade into provided attributes * @param groupName The name of the group to apply fade */ private def timedRun(groupName: String, endTime: DateTime, attributes: Seq[Attribute]): Future[JsValue] = { groupsEndpoint.getGroupId(groupName).flatMap(maybeGroupId => { val groupId = maybeGroupId match { case Some(id) => id case _ => throw new IllegalArgumentException("Group name not found") } val now = DateTime.now val transitionDuration = if (now > endTime) 1.second.toDuration.toScalaDuration else if (now.to(endTime).toDuration.toScalaDuration > TransitionTime.MAX_TRANSITION_TIME) TransitionTime.MAX_TRANSITION_TIME else now.to(endTime).toDuration.toScalaDuration val transitionTime = TransitionTime(transitionDuration) groupsEndpoint.put(groupId, attributes :+ transitionTime:_*) }) } }
ddexter/HomeBackend
src/main/scala/api/hue/State.scala
Scala
apache-2.0
2,424
/** * Copyright (c) 2002-2012 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.cypher.internal.symbols import org.neo4j.cypher.{CypherException, CypherTypeException} trait CypherType { def isAssignableFrom(other: CypherType): Boolean = this.getClass.isAssignableFrom(other.getClass) def iteratedType: CypherType = throw new RuntimeException("wut") def mergeWith(other: CypherType): CypherType = { if (this.isAssignableFrom(other)) other else if (other.isAssignableFrom(this)) this else throw new CypherTypeException("Failed merging " + this + " with " + other) } def parentType: CypherType val isCollection: Boolean = false } object CypherType { def fromJava(obj: Any): CypherType = { if (obj.isInstanceOf[String] || obj.isInstanceOf[Char]) return StringType() if (obj.isInstanceOf[Number]) return NumberType() if (obj.isInstanceOf[Boolean]) return BooleanType() if (obj.isInstanceOf[Seq[_]] || obj.isInstanceOf[Array[_]]) return AnyCollectionType() AnyType() } } /* TypeSafe is everything that needs to check it's types */ trait TypeSafe { /* Checks if internal type dependencies are met. Throws an exception if it fails */ def assertTypes(symbols: SymbolTable) // Same as assert types, but doesn't throw if it fails def checkTypes(symbols: SymbolTable): Boolean = try { assertTypes(symbols) true } catch { case _: CypherException => false } def symbolDependenciesMet(symbols: SymbolTable): Boolean = symbolTableDependencies.forall(name => check(symbols, name)) def symbolTableDependencies: Set[String] private def check(symbols: SymbolTable, name: String): Boolean = symbols.identifiers.contains(name) } /* Typed is the trait all classes that have a return type, or have dependencies on an expressions' type. */ trait Typed { /* Checks if internal type dependencies are met, checks if the expected type is valid, and returns the actual type of the expression. Will throw an exception if the check fails */ def evaluateType(expectedType: CypherType, symbols: SymbolTable): CypherType /* Checks if internal type dependencies are met and returns the actual type of the expression */ def getType(symbols: SymbolTable): CypherType = evaluateType(AnyType(), symbols) }
dksaputra/community
cypher/src/main/scala/org/neo4j/cypher/internal/symbols/CypherType.scala
Scala
gpl-3.0
3,050
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.spark.deploy.history.yarn import org.apache.spark.{Logging, SparkContext, SparkFirehoseListener} import org.apache.spark.scheduler.SparkListenerEvent /** * Spark listener which queues up all received events to the [[YarnHistoryService]] passed * as a constructor. There's no attempt to filter event types at this point. * * @param sc context * @param service service to forward events to */ private[spark] class YarnEventListener(sc: SparkContext, service: YarnHistoryService) extends SparkFirehoseListener with Logging { /** * queue the event with the service, timestamped to the current time. * * @param event event to queue */ override def onEvent(event: SparkListenerEvent): Unit = { service.process(event) } }
steveloughran/spark-timeline-integration
yarn-timeline-history/src/main/scala/org/apache/spark/deploy/history/yarn/YarnEventListener.scala
Scala
apache-2.0
1,570
package skinny import org.scalatest.FlatSpec class DBSettingsSpec extends FlatSpec with DBSettingsInitializer { behavior of "DBSettings" it should "have #initialize" in { val originalValue = System.getProperty(SkinnyEnv.EnvKey) try { System.setProperty(SkinnyEnv.EnvKey, "test") initialize(false) initialize(true) destroy() } finally { if (originalValue != null) { System.setProperty(SkinnyEnv.EnvKey, originalValue) } } } }
seratch/skinny-framework
orm/src/test/scala/skinny/DBSettingsSpec.scala
Scala
mit
496
package com.arcusys.learn.liferay.services import com.arcusys.learn.liferay.LiferayClasses.LAssetEntry import com.liferay.portal.kernel.dao.orm.{DynamicQuery, RestrictionsFactoryUtil} import com.liferay.portal.util.PortalUtil import com.liferay.portlet.asset.model.AssetEntry import com.liferay.portlet.asset.service.{AssetCategoryLocalServiceUtil, AssetEntryLocalServiceUtil} import scala.collection.JavaConverters._ object AssetEntryLocalServiceHelper { def dynamicQuery(query: DynamicQuery): Seq[AssetEntry] = AssetEntryLocalServiceUtil.dynamicQuery(query).asScala.map(_.asInstanceOf[AssetEntry]) def dynamicQuery(): DynamicQuery = AssetEntryLocalServiceUtil.dynamicQuery() def getAssetEntry(entryId: Long): AssetEntry = AssetEntryLocalServiceUtil.getEntry(entryId) def getAssetEntry(className: String, classPK: Long): LAssetEntry = AssetEntryLocalServiceUtil.getEntry(className, classPK) def fetchAssetEntry(className: String, classPK: Long): Option[AssetEntry] = Option(AssetEntryLocalServiceUtil.fetchEntry(className, classPK)) def fetchAssetEntry(entryId: Long): Option[AssetEntry] = Option(AssetEntryLocalServiceUtil.fetchEntry(entryId)) def fetchAssetEntries(className: String, classPK: Seq[Long]): Seq[AssetEntry] = { val classNameId = PortalUtil.getClassNameId(className) classPK match { case Nil => Seq() case seq => val ids = seq.asJavaCollection val query = AssetEntryLocalServiceUtil.dynamicQuery() .add(RestrictionsFactoryUtil.eq("classNameId", classNameId)) .add(RestrictionsFactoryUtil.in("classPK", ids)) AssetEntryLocalServiceUtil.dynamicQuery(query).asScala .map(_.asInstanceOf[AssetEntry]) } } def getAssetEntriesByCategory(categoryId: Long, classNameId: Long): Seq[AssetEntry] = { AssetEntryLocalServiceUtil.getAssetCategoryAssetEntries(categoryId).asScala .filter(_.getClassNameId == classNameId) } def deleteAssetEntry(entryId: Long): AssetEntry = AssetEntryLocalServiceUtil.deleteAssetEntry(entryId) def createAssetEntry(entryId: Long) = AssetEntryLocalServiceUtil.createAssetEntry(entryId) def updateAssetEntry(assetEntry: AssetEntry): AssetEntry = { if(assetEntry.isNew) AssetEntryLocalServiceUtil.addAssetEntry(assetEntry) else AssetEntryLocalServiceUtil.updateAssetEntry(assetEntry) } def setAssetCategories(entryId: Long, categoryIds: Array[Long]): Unit = { if (!categoryIds.isEmpty) categoryIds.foreach(categoryId => AssetCategoryLocalServiceUtil.setAssetEntryAssetCategories(entryId, categoryIds)) else AssetCategoryLocalServiceUtil.clearAssetEntryAssetCategories(entryId) } def addAssetCategories(entryId: Long, categoryIds: Array[Long]): Unit = categoryIds.foreach(categoryId => AssetCategoryLocalServiceUtil.addAssetEntryAssetCategories(entryId, categoryIds)) def removeAssetCategories(entryId: Long, categoryIds: Array[Long]): Unit = categoryIds.foreach(categoryId => AssetCategoryLocalServiceUtil.deleteAssetEntryAssetCategories(entryId, categoryIds)) }
igor-borisov/valamis
learn-liferay620-services/src/main/scala/com/arcusys/learn/liferay/services/AssetEntryLocalServiceHelper.scala
Scala
gpl-3.0
3,075
package stagerwr import squid.utils._ import Embedding.Predef._ import Embedding.Quasicodes._ import squid.lib.{transparent,transparencyPropagating} import Math.{pow,sqrt} // FIXME: accessors and ctor not set @transparent... //case class Position(@transparent x: Double, @transparent y: Double) //case class Position(@transparencyPropagating x: Double, @transparencyPropagating y: Double) //case class Planet(@transparencyPropagating pos: Position, @transparencyPropagating mass: Double) // Note: @transparencyPropagating so that even when // TODO have a @pure/@transparentType/@transparent annotation to add on the Position CLASS itself, for a similar effect class Position(private val _x: Double, private val _y: Double) { @transparencyPropagating def x = _x; @transparencyPropagating def y = _y; } object Position { def apply(_x: Double, _y: Double) = new Position(_x,_y) } class Planet(private val _pos: Position, private val _mass: Double) { @transparencyPropagating def pos = _pos; @transparencyPropagating def mass = _mass; } object Planet { def apply(pos: Position, mass: Double) = new Planet(pos,mass) } /* Created by lptk on 18/06/17. */ object Power extends App { def gravityForce(p0: Planet, p1: Planet) = p0.mass * p1.mass / Math.pow(distance(p0.pos,p1.pos), 2) def distance(x0: Position, x1: Position) = Math.sqrt(pow(x0.x - x1.x, 2) + pow(x0.y - x1.y, 2)) }
epfldata/squid
example/src/main/scala/experimentation/stagerwr/Power.scala
Scala
apache-2.0
1,411
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.spark.ml.param.shared import java.io.PrintWriter import scala.reflect.ClassTag import scala.xml.Utility /** * Code generator for shared params (sharedParams.scala). Run under the Spark folder with * {{{ * build/sbt "mllib/runMain org.apache.spark.ml.param.shared.SharedParamsCodeGen" * }}} */ private[shared] object SharedParamsCodeGen { def main(args: Array[String]): Unit = { val params = Seq( ParamDesc[Double]("regParam", "regularization parameter (>= 0)", isValid = "ParamValidators.gtEq(0)"), ParamDesc[Int]("maxIter", "maximum number of iterations (>= 0)", isValid = "ParamValidators.gtEq(0)"), ParamDesc[String]("featuresCol", "features column name", Some("\\"features\\"")), ParamDesc[String]("labelCol", "label column name", Some("\\"label\\"")), ParamDesc[String]("predictionCol", "prediction column name", Some("\\"prediction\\"")), ParamDesc[String]("rawPredictionCol", "raw prediction (a.k.a. confidence) column name", Some("\\"rawPrediction\\"")), ParamDesc[String]("probabilityCol", "Column name for predicted class conditional" + " probabilities. Note: Not all models output well-calibrated probability estimates!" + " These probabilities should be treated as confidences, not precise probabilities", Some("\\"probability\\"")), ParamDesc[String]("varianceCol", "Column name for the biased sample variance of prediction"), ParamDesc[Double]("threshold", "threshold in binary classification prediction, in range [0, 1]", isValid = "ParamValidators.inRange(0, 1)", finalMethods = false, finalFields = false), ParamDesc[Array[Double]]("thresholds", "Thresholds in multi-class classification" + " to adjust the probability of predicting each class." + " Array must have length equal to the number of classes, with values > 0" + " excepting that at most one value may be 0." + " The class with largest value p/t is predicted, where p is the original probability" + " of that class and t is the class's threshold", isValid = "(t: Array[Double]) => t.forall(_ >= 0) && t.count(_ == 0) <= 1", finalMethods = false), ParamDesc[String]("inputCol", "input column name"), ParamDesc[Array[String]]("inputCols", "input column names"), ParamDesc[String]("outputCol", "output column name", Some("uid + \\"__output\\"")), ParamDesc[Array[String]]("outputCols", "output column names"), ParamDesc[Int]("checkpointInterval", "set checkpoint interval (>= 1) or " + "disable checkpoint (-1). E.g. 10 means that the cache will get checkpointed " + "every 10 iterations. Note: this setting will be ignored if the checkpoint directory " + "is not set in the SparkContext", isValid = "(interval: Int) => interval == -1 || interval >= 1"), ParamDesc[Boolean]("fitIntercept", "whether to fit an intercept term", Some("true")), ParamDesc[String]("handleInvalid", "how to handle invalid entries. Options are skip (which " + "will filter out rows with bad values), or error (which will throw an error). More " + "options may be added later", isValid = "ParamValidators.inArray(Array(\\"skip\\", \\"error\\"))", finalFields = false), ParamDesc[Boolean]("standardization", "whether to standardize the training features" + " before fitting the model", Some("true")), ParamDesc[Long]("seed", "random seed", Some("this.getClass.getName.hashCode.toLong")), ParamDesc[Double]("elasticNetParam", "the ElasticNet mixing parameter, in range [0, 1]." + " For alpha = 0, the penalty is an L2 penalty. For alpha = 1, it is an L1 penalty", isValid = "ParamValidators.inRange(0, 1)"), ParamDesc[Double]("tol", "the convergence tolerance for iterative algorithms (>= 0)", isValid = "ParamValidators.gtEq(0)"), ParamDesc[Double]("stepSize", "Step size to be used for each iteration of optimization (>" + " 0)", isValid = "ParamValidators.gt(0)", finalFields = false), ParamDesc[String]("weightCol", "weight column name. If this is not set or empty, we treat " + "all instance weights as 1.0"), ParamDesc[String]("solver", "the solver algorithm for optimization", finalFields = false), ParamDesc[Int]("aggregationDepth", "suggested depth for treeAggregate (>= 2)", Some("2"), isValid = "ParamValidators.gtEq(2)", isExpertParam = true), ParamDesc[Boolean]("collectSubModels", "whether to collect a list of sub-models trained " + "during tuning. If set to false, then only the single best sub-model will be available " + "after fitting. If set to true, then all sub-models will be available. Warning: For " + "large models, collecting all sub-models can cause OOMs on the Spark driver", Some("false"), isExpertParam = true), ParamDesc[String]("loss", "the loss function to be optimized", finalFields = false) ) val code = genSharedParams(params) val file = "src/main/scala/org/apache/spark/ml/param/shared/sharedParams.scala" val writer = new PrintWriter(file) writer.write(code) writer.close() } /** Description of a param. */ private case class ParamDesc[T: ClassTag]( name: String, doc: String, defaultValueStr: Option[String] = None, isValid: String = "", finalMethods: Boolean = true, finalFields: Boolean = true, isExpertParam: Boolean = false) { require(name.matches("[a-z][a-zA-Z0-9]*"), s"Param name $name is invalid.") require(doc.nonEmpty) // TODO: more rigorous on doc def paramTypeName: String = { val c = implicitly[ClassTag[T]].runtimeClass c match { case _ if c == classOf[Int] => "IntParam" case _ if c == classOf[Long] => "LongParam" case _ if c == classOf[Float] => "FloatParam" case _ if c == classOf[Double] => "DoubleParam" case _ if c == classOf[Boolean] => "BooleanParam" case _ if c.isArray && c.getComponentType == classOf[String] => s"StringArrayParam" case _ if c.isArray && c.getComponentType == classOf[Double] => s"DoubleArrayParam" case _ => s"Param[${getTypeString(c)}]" } } def valueTypeName: String = { val c = implicitly[ClassTag[T]].runtimeClass getTypeString(c) } private def getTypeString(c: Class[_]): String = { c match { case _ if c == classOf[Int] => "Int" case _ if c == classOf[Long] => "Long" case _ if c == classOf[Float] => "Float" case _ if c == classOf[Double] => "Double" case _ if c == classOf[Boolean] => "Boolean" case _ if c == classOf[String] => "String" case _ if c.isArray => s"Array[${getTypeString(c.getComponentType)}]" } } } /** Generates the HasParam trait code for the input param. */ private def genHasParamTrait(param: ParamDesc[_]): String = { val name = param.name val Name = name(0).toUpper +: name.substring(1) val Param = param.paramTypeName val T = param.valueTypeName val doc = param.doc val defaultValue = param.defaultValueStr val defaultValueDoc = defaultValue.map { v => s" (default: $v)" }.getOrElse("") val setDefault = defaultValue.map { v => s""" | setDefault($name, $v) |""".stripMargin }.getOrElse("") val isValid = if (param.isValid != "") { ", " + param.isValid } else { "" } val groupStr = if (param.isExpertParam) { Array("expertParam", "expertGetParam") } else { Array("param", "getParam") } val methodStr = if (param.finalMethods) { "final def" } else { "def" } val fieldStr = if (param.finalFields) { "final val" } else { "val" } val htmlCompliantDoc = Utility.escape(doc) s""" |/** | * Trait for shared param $name$defaultValueDoc. This trait may be changed or | * removed between minor versions. | */ |@DeveloperApi |trait Has$Name extends Params { | | /** | * Param for $htmlCompliantDoc. | * @group ${groupStr(0)} | */ | $fieldStr $name: $Param = new $Param(this, "$name", "$doc"$isValid) |$setDefault | /** @group ${groupStr(1)} */ | $methodStr get$Name: $T = $$($name) |} |""".stripMargin } /** Generates Scala source code for the input params with header. */ private def genSharedParams(params: Seq[ParamDesc[_]]): String = { val header = """/* | * Licensed to the Apache Software Foundation (ASF) under one or more | * contributor license agreements. See the NOTICE file distributed with | * this work for additional information regarding copyright ownership. | * The ASF licenses this file to You 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 org.apache.spark.ml.param.shared | |import org.apache.spark.annotation.DeveloperApi |import org.apache.spark.ml.param._ | |// DO NOT MODIFY THIS FILE! It was generated by SharedParamsCodeGen. | |// scalastyle:off |""".stripMargin val footer = "// scalastyle:on\\n" val traits = params.map(genHasParamTrait).mkString header + traits + footer } }
esi-mineset/spark
mllib/src/main/scala/org/apache/spark/ml/param/shared/SharedParamsCodeGen.scala
Scala
apache-2.0
10,826
/* * Copyright 2014 Michael Krolikowski * * 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 com.github.mkroli.shurl import scala.concurrent.duration.DurationInt import scala.language.postfixOps import akka.actor.ActorSystem import akka.util.Timeout trait AkkaComponent { val actorSystem = ActorSystem() implicit val timeout = Timeout(250 milliseconds) }
mkroli/shurl
src/main/scala/com/github/mkroli/shurl/AkkaComponent.scala
Scala
apache-2.0
881
import sbt.Keys._ import sbt._ object RootBuild extends Build { val liftVersion = SettingKey[String]("liftVersion", "Full version number of the Lift Web Framework") val liftEdition = SettingKey[String]("liftEdition", "Lift Edition (short version number to append to artifact name)") lazy val project = Project( id = "type-prog", base = file("."), settings = Project.defaultSettings ++ Defaults.itSettings ++ Seq( liftEdition <<= liftVersion { _.substring(0,3) } ) ).configs( IntegrationTest ) }
joescii/type-prog-impress
project/Build.scala
Scala
apache-2.0
543
/* * foundweekends project * * 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 giter8 import java.io.File object Home { val home = Option(System.getProperty("G8_HOME")) .map(new File(_)) .getOrElse( new File(System.getProperty("user.home"), ".g8") ) }
foundweekends/giter8
cli-git/src/main/scala/Home.scala
Scala
apache-2.0
790
package ml.sparkling.graph /** * API of Sparkling Graph library. * Created by Roman Bartusiak ([email protected] http://riomus.github.io). */ package object api
sparkling-graph/sparkling-graph
api/src/main/scala/ml/sparkling/graph/api/package.scala
Scala
bsd-2-clause
174
package co.spendabit.webapp.forms.v3.controls import org.apache.commons.fileupload.FileItem import scala.xml.NodeSeq class FileUpload extends FileBasedInput[FileItem] { def validate(fileItem: Option[FileItem]): Either[String, FileItem] = { fileItem match { case Some(fi) => Right(fi) case None => Left("Please choose a file to upload.") } } override def html(value: Option[FileItem]): NodeSeq = <input type="file" /> } object FileUpload { def apply() = new FileUpload }
spendabit/webapp-tools
src/co/spendabit/webapp/forms/v3/controls/FileUpload.scala
Scala
unlicense
508
/* * Copyright 2009-2014 LinkedIn, Inc * * 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 com.linkedin.norbert package network package partitioned package loadbalancer import com.linkedin.norbert.cluster.{InvalidClusterException, Node} import com.linkedin.norbert.network.common.Endpoint import org.specs2.mutable.SpecificationWithJUnit import org.specs2.specification.Scope /** * Test cases for <code>DefaultClusteredLoadBalancer</code>. Since the class is implemented based on the * <code>DefaultPartitionedLoadBalancer</code>, this test case just checks the additional functionality. */ class DefaultClusteredLoadBalancerFactorySpec extends SpecificationWithJUnit { trait DefaultClusteredLoadBalancerSetup extends Scope { case class EId(id: Int) implicit def eId2ByteArray(eId: EId): Array[Byte] = BigInt(eId.id).toByteArray class EIdDefaultLoadBalancerFactory(numPartitions: Int, clusterId: Node => Int, serveRequestsIfPartitionMissing: Boolean) extends DefaultClusteredLoadBalancerFactory[EId](numPartitions, clusterId, serveRequestsIfPartitionMissing) { protected def calculateHash(id: EId) = HashFunctions.fnv(id) def getNumPartitions(endpoints: Set[Endpoint]) = numPartitions } class TestEndpoint(val node: Node, var csr: Boolean) extends Endpoint { def canServeRequests = csr def setCsr(ncsr: Boolean) { csr = ncsr } } def toEndpoints(nodes: Set[Node]): Set[Endpoint] = nodes.map(n => new TestEndpoint(n, true)) def markUnavailable(endpoints: Set[Endpoint], id: Int) { endpoints.foreach { endpoint => if (endpoint.node.id == id) { endpoint.asInstanceOf[TestEndpoint].setCsr(false) } } } /** * Sample clusterId implementation. This test case assumes that the node id has replica information. The most * digits before least three digits are cluster id. Thus, it computes cluster id from node id by dividing 1000. * * @param node a node. * @return cluster id. */ def clusterId(node: Node): Int = node.id / 1000 val loadBalancerFactory = new EIdDefaultLoadBalancerFactory(20, clusterId, false) /** * Multi-replica example. The least three digits is used for node id in each replica. The most digits before least * three digits for cluster id. For example, 11010 means 10 node in cluster 11. This example closely related with the * clusterId method that extract cluster number from node information. */ val nodes = Set( Node(1001, "localhost:31313", true, Set(0, 1, 2, 3)), Node(1002, "localhost:31313", true, Set(4, 5, 6, 7)), Node(1003, "localhost:31313", true, Set(8, 9, 10, 11)), Node(1004, "localhost:31313", true, Set(12, 13, 14, 15)), Node(1005, "localhost:31313", true, Set(16, 17, 18, 19)), Node(2001, "localhost:31313", true, Set(0, 2, 4, 6)), Node(2002, "localhost:31313", true, Set(8, 10, 12, 14)), Node(2003, "localhost:31313", true, Set(16, 18, 1, 3)), Node(2004, "localhost:31313", true, Set(5, 7, 9, 11)), Node(2005, "localhost:31313", true, Set(13, 15, 17, 19)), Node(3001, "localhost:31313", true, Set(0, 3, 6, 9)), Node(3002, "localhost:31313", true, Set(12, 15, 18, 1)), Node(3003, "localhost:31313", true, Set(4, 7, 10, 13)), Node(3004, "localhost:31313", true, Set(16, 19, 2, 5)), Node(3005, "localhost:31313", true, Set(8, 11, 14, 17)), Node(4001, "localhost:31313", true, Set(0, 4, 8, 12)), Node(4002, "localhost:31313", true, Set(16, 1, 5, 9)), Node(4003, "localhost:31313", true, Set(13, 17, 2, 6)), Node(4004, "localhost:31313", true, Set(10, 14, 18, 3)), Node(4005, "localhost:31313", true, Set(7, 11, 15, 19)), Node(5001, "localhost:31313", true, Set(0, 5, 10, 15)), Node(5002, "localhost:31313", true, Set(1, 6, 11, 16)), Node(5003, "localhost:31313", true, Set(2, 7, 12, 17)), Node(5004, "localhost:31313", true, Set(3, 8, 13, 18)), Node(5005, "localhost:31313", true, Set(4, 9, 14, 19)), Node(10001, "localhost:31313", true, Set(0, 6, 12, 18)), Node(10002, "localhost:31313", true, Set(5, 11, 17, 4)), Node(10003, "localhost:31313", true, Set(10, 16, 3, 9)), Node(10004, "localhost:31313", true, Set(15, 2, 8, 14)), Node(10005, "localhost:31313", true, Set(1, 7, 13, 19)) ) } /** * Test case for plain fan-out controls. This test case checks whether the number of clusters is same as the limits * of clusters. */ "DefaultClusteredLoadBalancer" should { " returns nodes within only N clusters from nodesForPartitionsIdsInNReplicas" in new DefaultClusteredLoadBalancerSetup { // Prepares load balancer. val lb = loadBalancerFactory.newLoadBalancer(toEndpoints(nodes)) // Prepares id sets. val set = (for (id <- 1001 to 2000) yield (id)).foldLeft(Set.empty[EId]) { (set, id) => set.+(EId(id)) } // Checks whether return node lists are properly bounded in given number of clusters. for (n <- 0 to 6) { // Selecting nodes from N clusters. val nodesInClusters = lb.nodesForPartitionedIdsInNReplicas(set, n, None, None) // Creating a mapping cluster to nodes. val selectedClusterSet = nodesInClusters.keySet.foldLeft(Set.empty[Int]) { (set, node) => set.+(clusterId(node)) } // Checks whether we have total n different clusters. (selectedClusterSet.size) must be_==(if (n == 0) (6) else (n)) } } /** * Test case for all partition is missing. The implementation should pick up a node even though all nodes are not * available. Under multi-replica with rerouting strategy. It is better to return the node rather than throw * exception. This test case calls nodesForPartitionsIdsInNReplicas under the condition that all partition zero is * missing. However, it should return the set of nodes. */ "nodesForPartitionsIdsInNReplicas not throw NoNodeAvailable if partition is missing." in new DefaultClusteredLoadBalancerSetup { // TestNode set wraps Node. val endpoints = toEndpoints(nodes) // Mark all node unavailable for partition zero. markUnavailable(endpoints, 1001) markUnavailable(endpoints, 2001) markUnavailable(endpoints, 3001) markUnavailable(endpoints, 4001) markUnavailable(endpoints, 5001) markUnavailable(endpoints, 10001) // Prepares load balancer. val lb = loadBalancerFactory.newLoadBalancer(endpoints) // Prepares id sets. val set = (for (id <- 2001 to 2100) yield (id)).foldLeft(Set.empty[EId]) { (set, id) => set.+(EId(id)) } for (n <- 0 to 6) { // Returns nodes even though some partition is not available. lb.nodesForPartitionedIdsInNReplicas(set, n, None, None) must_!= throwA[NoNodesAvailableException] } } /** * Test case for sending one cluster by specifying the cluster id. */ " returns nodes within only one clusters from nodesForPartitionsIdsInNReplicas" in new DefaultClusteredLoadBalancerSetup { // Prepares load balancer. val lb = loadBalancerFactory.newLoadBalancer(toEndpoints(nodes)) // Prepares id sets. val set = (for (id <- 2001 to 3000) yield (id)).foldLeft(Set.empty[EId]) { (set, id) => set.+(EId(id)) } // Prepares all cluster id set val clusterSet: Set[Int] = { (for (node <- nodes) yield clusterId(node)).foldLeft(Set[Int]()) { case (set, key) => set + key } } // Checks whether we return nodes from specified cluster. for (id <- clusterSet) { // Selecting nodes from the cluster specified as id. val nodesInClusters = lb.nodesForPartitionedIdsInOneCluster(set, id, None, None) // Creating a mapping cluster to nodes. val selectedClusterSet = nodesInClusters.keySet.foldLeft(Set.empty[Int]) { (set, node) => set.+(clusterId(node)) } // Checks whether we have total one cluster (selectedClusterSet.size) must be_==(1) // Checks whether the cluster id is same as given id (selectedClusterSet) must be_==(Set(id)) } } /** * Test case for sending one cluster with invalid cluster id. */ "nodesForPartitionsIdsInOneCluster should throw NoClusterException if there is no matching cluster id" in new DefaultClusteredLoadBalancerSetup { // Prepares load balancer. val lb = loadBalancerFactory.newLoadBalancer(toEndpoints(nodes)) // Prepares id sets. val set = (for (id <- 2001 to 3000) yield (id)).foldLeft(Set.empty[EId]) { (set, id) => set.+(EId(id)) } val invalidClusterId = -1 lb.nodesForPartitionedIdsInOneCluster(set, invalidClusterId, None, None) must throwA[InvalidClusterException] } } }
linkedin/norbert
network/src/test/scala/com/linkedin/norbert/network/partitioned/loadbalancer/DefaultClusteredLoadBalancerFactorySpec.scala
Scala
apache-2.0
9,544
package uk.co.sprily package btf.webjs import scala.concurrent.duration.FiniteDuration import scala.scalajs.js import scala.scalajs.js.Date import scala.scalajs.js.typedarray.ArrayBuffer import monifu.reactive._ import monifu.reactive.channels._ import org.scalajs.dom import upickle._ sealed trait WSState case object WSOpen extends WSState case object WSClosing extends WSState case object WSClosed extends WSState trait WSModule { def connect(url: String, heartbeat: FiniteDuration): WS } trait WS { type Error = String def status: Observable[WSState] def data[T:Reader]: Observable[Either[Error,T]] def errors: Observable[dom.ErrorEvent] def disconnect(): Unit } object WSModule extends WSModule { import monifu.concurrent.Implicits.globalScheduler val logger = Logging.ajaxLogger( "uk.co.sprily.btf.webjs.WS", js.Dynamic.global.jsRoutes.uk.co.sprily.btf.web.controllers.Logging.log().absoluteURL().asInstanceOf[String]) private[WSModule] case class IntervalHandler(value: Int) extends AnyVal /** * TODO: implement back-pressure, so that we receive the latest * data when ready. This requires an update to the WS controller * server-side. Currently PublishChannel is unbuffered. */ protected[WSModule] class WSImpl( url: String, heartbeat: FiniteDuration, statusChannel: PublishChannel[WSState], dataChannel: PublishChannel[String], errorsChannel: PublishChannel[dom.ErrorEvent]) extends WS { private[this] var raw: Option[dom.WebSocket] = None private[this] var active = true private[this] var lastHB = Date.now() reconnect() // initial connection // Re-connect whenever the websocket disconnects status.filter(_ == WSClosed).foreach(_ => reconnect()) status.filter(_ == WSOpen).foreach(_ => logger.info(s"Connected to $url")) // Set-up heartbeat dataChannel.filter(_ == "heartbeat").foreach(_ => lastHB = Date.now()) private[this] val intervalH = IntervalHandler(dom.window.setInterval(checkHeartbeat _, heartbeat.toMillis)) override def status = statusChannel override def errors = errorsChannel override def data[T:Reader] = { dataChannel.filter(_ != "heartbeat").map { s => try { Right(upickle.read[T](s)) } catch { case e: Exception => Left(e.toString) }} } override def disconnect(): Unit = { logger.info(s"Closing websocket: $this") active = false dom.window.clearInterval(intervalH.value) raw.foreach(_.close()) } private[this] def reconnect(): Unit = { if (active) { logger.info(s"Opening connection to $url") raw = Some { val ws = new dom.WebSocket(url) ws.onopen = (e: dom.Event) => statusChannel.pushNext(WSOpen) ws.onclose = (e: dom.CloseEvent) => statusChannel.pushNext(WSClosed) ws.onmessage = (e: dom.MessageEvent) => dataChannel.pushNext(e.data.asInstanceOf[String]) ws.onerror = (e: dom.ErrorEvent) => errorsChannel.pushNext(e) ws } } } private[this] def checkHeartbeat(): Unit = { logger.debug(s"Checking heartbeat") if (lastHB + heartbeat.toMillis < Date.now()) { heartbeatFailed() } } private[this] def heartbeatFailed(): Unit = { logger.warning(s"Heartbeat failed") raw match { case Some(ws) if ws.readyState == dom.WebSocket.OPEN => logger.warning(s"Closing connection due to heartbeat failing") statusChannel.pushNext(WSClosing) ws.close() case Some(_) => logger.debug(s"Not closing connection due to heartbeat failure as it is not open") case None => logger.error(s"Unexpected state: no raw websocket available") reconnect() } } } override def connect(url: String, heartbeat: FiniteDuration): WS = { val statusChannel = PublishChannel[WSState]() val dataChannel = PublishChannel[String]() val errorsChannel = PublishChannel[dom.ErrorEvent]() new WSImpl(url, heartbeat, statusChannel, dataChannel, errorsChannel) } }
sprily/brush-training
web-js/src/main/scala/WS.scala
Scala
gpl-3.0
4,179
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.ignite.spark.impl import org.apache.ignite.cache.query.Query import org.apache.ignite.configuration.CacheConfiguration import org.apache.ignite.spark.IgniteContext import org.apache.spark.{TaskContext, Partition} import scala.reflect.ClassTag class IgniteSqlRDD[R: ClassTag, T, K, V]( ic: IgniteContext, cacheName: String, cacheCfg: CacheConfiguration[K, V], qry: Query[T], conv: (T) ⇒ R, keepBinary: Boolean ) extends IgniteAbstractRDD[R, K, V](ic, cacheName, cacheCfg, keepBinary) { override def compute(split: Partition, context: TaskContext): Iterator[R] = { val cur = ensureCache().query(qry) TaskContext.get().addTaskCompletionListener((_) ⇒ cur.close()) new IgniteQueryIterator[T, R](cur.iterator(), conv) } override protected def getPartitions: Array[Partition] = { Array(new IgnitePartition(0)) } }
WilliamDo/ignite
modules/spark/src/main/scala/org/apache/ignite/spark/impl/IgniteSqlRDD.scala
Scala
apache-2.0
1,713
package com.twitter.concurrent import org.scalatest.FunSuite import org.scalatest.concurrent.Eventually import org.scalatest.junit.JUnitRunner import org.junit.runner.RunWith import com.twitter.util.{Promise, Await} import com.twitter.conversions.time._ @RunWith(classOf[JUnitRunner]) class LocalSchedulerTest extends FunSuite { private val scheduler = new LocalScheduler def submit(f: => Unit) = scheduler.submit(new Runnable { def run() = f }) val N = 100 test("run the first submitter immediately") { var ok = false submit { ok = true } assert(ok) } test("run subsequent submits serially") { var n = 0 submit { assert(n === 0) submit { assert(n === 1) submit { assert(n === 2) n += 1 } n += 1 } n += 1 } assert(n === 3) } test("handle many submits") { var ran = Nil: List[Int] submit { for (which <- 0 until N) submit { ran match { case Nil if which == 0 => // ok case hd :: _ => assert(hd === which - 1) case _ => fail("ran wrong") } ran ::= which } } assert(ran === (0 until N).reverse) } } @RunWith(classOf[JUnitRunner]) class ThreadPoolSchedulerTest extends FunSuite with Eventually { test("works") { val p = new Promise[Unit] val scheduler = new ThreadPoolScheduler("test") scheduler.submit(new Runnable { def run() { p.setDone() } }) eventually { p.isDone } scheduler.shutdown() } }
mosesn/util
util-core/src/test/scala/com/twitter/concurrent/SchedulerTest.scala
Scala
apache-2.0
1,599
package org.jetbrains.plugins.scala package lang package psi package impl package expr import _root_.org.jetbrains.plugins.scala.lang.resolve.ScalaResolveResult import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi._ import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.IncorrectOperationException import org.jetbrains.plugins.scala.extensions._ import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes import org.jetbrains.plugins.scala.lang.psi.api.expr._ import org.jetbrains.plugins.scala.lang.psi.api.toplevel.templates.ScExtendsBlock import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScObject, ScTemplateDefinition, ScTypeDefinition} import org.jetbrains.plugins.scala.lang.psi.api.{ScalaElementVisitor, ScalaFile} import org.jetbrains.plugins.scala.lang.psi.types.result.{Failure, TypingContext} import org.jetbrains.plugins.scala.lang.psi.types.{ScType, ScTypeExt} import _root_.scala.collection.mutable.ArrayBuffer /** * @author Alexander Podkhalyuzin * Date: 14.03.2008 */ class ScSuperReferenceImpl(node: ASTNode) extends ScalaPsiElementImpl(node) with ScSuperReference { override def toString = "SuperReference" def isHardCoded: Boolean = { val id = findChildByType[PsiElement](ScalaTokenTypes.tIDENTIFIER) if (id == null) false else { ScalaPsiUtil.fileContext(id) match { case file: ScalaFile if file.isCompiled => val next = id.getNode.getTreeNext if (next == null) false else next.getPsi match { case comment: PsiComment => val commentText = comment.getText val path = commentText.substring(2, commentText.length - 2) val classes = ScalaPsiManager.instance(getProject).getCachedClasses(getResolveScope, path) if (classes.length == 1) { drvTemplate.exists(td => !ScalaPsiUtil.cachedDeepIsInheritor(td, classes(0))) } else { val clazz: Option[PsiClass] = classes.find(!_.isInstanceOf[ScObject]) clazz match { case Some(psiClass) => drvTemplate.exists(td => !ScalaPsiUtil.cachedDeepIsInheritor(td, psiClass)) case _ => false } } case _ => false } case _ => false } } } def drvTemplate: Option[ScTemplateDefinition] = reference match { case Some(q) => q.bind() match { case Some(ScalaResolveResult(td : ScTypeDefinition, _)) => Some(td) case _ => None } case None => ScalaPsiUtil.drvTemplate(this) } def staticSuper: Option[ScType] = { val id = findChildByType[PsiElement](ScalaTokenTypes.tIDENTIFIER) if (id == null) None else findSuper(id) } override def getReference = { val id = findChildByType[PsiElement](ScalaTokenTypes.tIDENTIFIER) if (id == null) null else new PsiReference { def getElement = ScSuperReferenceImpl.this def getRangeInElement = new TextRange(0, id.getTextLength).shiftRight(id.getStartOffsetInParent) def getCanonicalText = resolve match { case c : PsiClass => c.qualifiedName case _ => null } def isSoft: Boolean = false def handleElementRename(newElementName: String) = doRename(newElementName) def bindToElement(e : PsiElement) = e match { case c : PsiClass => doRename(c.name) case _ => throw new IncorrectOperationException("cannot bind to anything but class") } private def doRename(newName : String) = { val parent = id.getNode.getTreeParent parent.replaceChild(id.getNode, ScalaPsiElementFactory.createIdentifier(newName, getManager)) ScSuperReferenceImpl.this } def isReferenceTo(element: PsiElement) = element match { case c : PsiClass => c.name == id.getText && resolve == c case _ => false } def resolve = { def resolveNoHack: PsiClass = { findSuper(id) match { case Some(t) => t.extractClass() match { case Some(c) => c case None => null } case _ => null } } ScalaPsiUtil.fileContext(id) match { case file: ScalaFile if file.isCompiled => val next = id.getNode.getTreeNext if (next == null) resolveNoHack else next.getPsi match { case comment: PsiComment => val commentText = comment.getText val path = commentText.substring(2, commentText.length - 2) val classes = ScalaPsiManager.instance(getProject).getCachedClasses(getResolveScope, path) if (classes.length == 1) classes(0) else classes.find(!_.isInstanceOf[ScObject]).getOrElse(resolveNoHack) case _ => resolveNoHack } case _ => resolveNoHack } } def getVariants: Array[Object] = superTypes match { case None => Array[Object]() case Some(supers) => val buff = new ArrayBuffer[Object] supers.foreach { t => t.extractClass() match { case Some(c) => buff += c case None => }} buff.toArray } } } def findSuper(id : PsiElement) : Option[ScType] = superTypes match { case None => None case Some(types) => val name = id.getText for (t <- types) { t.extractClass() match { case Some(c) if name == c.name => return Some(t) case _ => } } None } private def superTypes: Option[Seq[ScType]] = reference match { case Some(q) => q.resolve() match { case clazz: PsiClass => Some(clazz.getSuperTypes.map(_.toScType(getProject, getResolveScope))) case _ => None } case None => PsiTreeUtil.getContextOfType(this, false, classOf[ScExtendsBlock]) match { case null => None case eb: ScExtendsBlock => Some(eb.superTypes) } } protected override def innerType(ctx: TypingContext) = Failure("Cannot infer type of `super' expression", Some(this)) override def accept(visitor: ScalaElementVisitor) { visitor.visitSuperReference(this) } override def accept(visitor: PsiElementVisitor) { visitor match { case visitor: ScalaElementVisitor => visitor.visitSuperReference(this) case _ => super.accept(visitor) } } }
whorbowicz/intellij-scala
src/org/jetbrains/plugins/scala/lang/psi/impl/expr/ScSuperReferenceImpl.scala
Scala
apache-2.0
6,469
package com.realizationtime.btdogg.tcphashes import akka.actor.{Actor, ActorLogging, ActorRef, ActorSystem, Props} import akka.stream.{Materializer, OverflowStrategy} import akka.stream.scaladsl.{Flow, Sink, Source, Tcp} import com.realizationtime.btdogg.BtDoggConfiguration.TcpHashSourceConfig import com.realizationtime.btdogg.commons.TKey import com.realizationtime.btdogg.hashessource.HashesSource.Artificial import com.realizationtime.btdogg.tcphashes.TcpHashesSource.{ProcessingDone, RegisterPublisher, TcpHashesMediator} import scala.concurrent.Future class TcpHashesSource(implicit val system: ActorSystem, val materializer: Materializer) { val tcpHashesMediatorActor: ActorRef = system.actorOf(Props(classOf[TcpHashesMediator], materializer)) def registerPublisherToTcpActor(publisher: ActorRef): Unit = tcpHashesMediatorActor ! RegisterPublisher(publisher) val hashesFromTcp: Source[Artificial, ActorRef] = Source.actorRef[Artificial](TcpHashSourceConfig.bufferForAllConnections, OverflowStrategy.fail) .alsoTo( Flow[Artificial] .map((a: Artificial) => ProcessingDone(a.key)) .to(Sink.foreach(tcpHashesMediatorActor ! _)) ) .named("hashes from tcp") } object TcpHashesSource { private class TcpHashesMediator(implicit materializer: Materializer) extends Actor with ActorLogging { import context._ override def receive: Receive = { case RegisterPublisher(publisher) => become(normalOperation(publisher, startServer())) case StopServer => stop(self) } private var hashesBeingProcessed: Map[TKey, List[ActorRef]] = Map().withDefaultValue(List()) private def normalOperation(publisher: ActorRef, serverBinding: Future[Tcp.ServerBinding]): Receive = { case RequestProcessing(key) => publisher ! Artificial(key) hashesBeingProcessed += key -> (sender() :: hashesBeingProcessed(key)) case processingDone: ProcessingDone => handleProcessingDone(processingDone) case StopServer => serverBinding.flatMap(binding => { log.info("unbinding TCP server") binding.unbind() }).foreach(_ => self ! StopServer) become(shuttingDown(publisher)) } def shuttingDown(publisher: ActorRef): Receive = { case processingDone: ProcessingDone => handleProcessingDone(processingDone) case StopServer => publisher ! akka.actor.Status.Success("success") stop(self) } private def handleProcessingDone(processingDone: ProcessingDone): Unit = { hashesBeingProcessed(processingDone.key) .foreach(requester => requester ! processingDone) hashesBeingProcessed -= processingDone.key } private def startServer()(implicit system: ActorSystem, materializer: Materializer): Future[Tcp.ServerBinding] = TcpHashesServer.runServer(self) } sealed trait TcpHashesMediatorProtocol private final case class RegisterPublisher(publisher: ActorRef) extends TcpHashesMediatorProtocol final case class RequestProcessing(key: TKey) extends TcpHashesMediatorProtocol case object StopServer extends TcpHashesMediatorProtocol sealed trait ProcessingResponse final case class ProcessingDone(key: TKey) extends TcpHashesMediatorProtocol with ProcessingResponse final case class ProcessingAborted(key: TKey) extends ProcessingResponse }
bwrega/btdogg
src/main/scala/com/realizationtime/btdogg/tcphashes/TcpHashesSource.scala
Scala
mit
3,365
/* * Copyright 2016-2017 original author or authors * * 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 tap.analysis.languagetool import javax.inject.Singleton import org.languagetool.language.BritishEnglish /** * Created by [email protected] on 21/10/17. */ @Singleton class Languages { val brittishEnglish = new BritishEnglish }
uts-cic/tap
src/main/scala/tap/analysis/languagetool/Languages.scala
Scala
apache-2.0
867
package com.acrussell.lambda sealed abstract class Expression case class Identifier(identifier: String) extends Expression case class Abstraction(identifier: Identifier, expression: Expression) extends Expression case class Application(e1: Expression, e2: Expression) extends Expression
euclio/scala-lambda
src/main/scala/IntermediateRepresentation.scala
Scala
mit
289
package org.automanlang.core.logging.tables import java.util.UUID import org.automanlang.core.info.QuestionType._ import scala.slick.driver.H2Driver.simple._ object DBQuestion { val questionTypeMapper = MappedColumnType.base[QuestionType, Int]( { case CheckboxQuestion => 0 case CheckboxDistributionQuestion => 1 case EstimationQuestion => 2 case FreeTextQuestion => 3 case FreeTextDistributionQuestion => 4 case RadioButtonQuestion => 5 case RadioButtonDistributionQuestion => 6 case MultiEstimationQuestion => 7 case Survey => 8 }, { case 0 => CheckboxQuestion case 1 => CheckboxDistributionQuestion case 2 => EstimationQuestion case 3 => FreeTextQuestion case 4 => FreeTextDistributionQuestion case 5 => RadioButtonQuestion case 6 => RadioButtonDistributionQuestion case 7 => MultiEstimationQuestion case 8 => Survey } ) } class DBQuestion(tag: Tag) extends Table[(UUID, String, QuestionType, String, String)](tag, "DBQUESTION") { implicit val questionTypeMapper = DBQuestion.questionTypeMapper def id = column[UUID]("QUESTION_ID", O.PrimaryKey) def memo_hash = column[String]("MEMO_HASH") def question_type = column[QuestionType]("QUESTION_TYPE") def text = column[String]("TEXT") def title = column[String]("TITLE") override def * = (id, memo_hash, question_type, text, title) }
dbarowy/AutoMan
libautoman/src/main/scala/org/automanlang/core/logging/tables/DBQuestion.scala
Scala
gpl-2.0
1,436
/* * Copyright 2015 Nicolas Rinaudo * * 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 kantan.csv package generic import org.scalatest.funsuite.AnyFunSuite class RegressionTests extends AnyFunSuite { test("Implicit resolution should not be impacted by the presence of default arguments (#65)") { case class Foobar(i: Int) // Wart Remover false positive on statements that are not actually fields. @SuppressWarnings(Array("org.wartremover.warts.PublicInference")) object Test { import kantan.csv.ops._ List(Foobar(3)).asCsv(rfc) "1".asCsvReader[Foobar](rfc) } // Necessary to prevent scalac from complaining about Test being unused. I really need to turn off "unused code" // detection in tests... Test } }
nrinaudo/scala-csv
generic/shared/src/test/scala/kantan/csv/generic/RegressionTests.scala
Scala
mit
1,287
package webapp import derive.key case class DealWrapperDAO(@key("status") status: String, @key("deal") deal: DealDAO) case class DealDAO(@key("uid") uid: String, @key("left") left: Int, @key("right") right: Int) case class DishDAO(@key("name") title: String, @key("image") image: String, @key("keywords") keywords: String, @key("score") score: Int)
pikkle/FoodMatch
client/src/main/scala/webapp/DAO.scala
Scala
apache-2.0
394
package au.com.agiledigital.rest.controllers.transport import java.net.InetAddress import java.security.cert.X509Certificate import play.api.libs.typedmap.TypedMap import play.api.mvc.request.{ RemoteConnection, RequestTarget } import play.api.mvc.{ Headers, RequestHeader } /** * Empty request header implementation. */ class EmptyRequestHeader extends RequestHeader { override def connection: RemoteConnection = new RemoteConnection { override def remoteAddress: InetAddress = InetAddress.getByName("") override def secure: Boolean = false override def clientCertificateChain: Option[Seq[X509Certificate]] = None } override def method: String = "" override def target: RequestTarget = RequestTarget("", "", Map.empty) override def version: String = "" override def headers: Headers = Headers() override def attrs: TypedMap = TypedMap.empty }
agiledigital/play-rest-support
core/src/main/scala/au/com/agiledigital/rest/controllers/transport/EmptyRequestHeader.scala
Scala
apache-2.0
883
/* * La Trobe University - Distributed Deep Learning System * Copyright 2016 Matthias Langer ([email protected]) * * 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 edu.latrobe.blaze.batchpools import edu.latrobe._ import edu.latrobe.blaze._ import edu.latrobe.io.graph._ import scala.Seq import scala.collection._ import scala.util.hashing._ /** * Encapsulates the concept of repeating that was previously coded in the * baseclass. */ final class Repeat(override val builder: RepeatBuilder, override val seed: InstanceSeed, override val source: BatchPool) extends DependentBatchPool[RepeatBuilder] { val noRepetitions : Int = builder.noRepetitions override val outputHints : BuildHints = { val noSamples = noRepetitions * inputHints.layout.noSamples inputHints.derive( inputHints.platform, inputHints.layout.derive(noSamples), inputHints.referencePlatform, inputHints.referenceLayout.derive(noSamples) ) } override def draw() : BatchPoolDrawContext = { // Pull one batch from source. val ctx = source.draw() if (ctx.isEmpty) { return ctx } val inp = ctx.batch // Fill up array. val srcN = ArrayEx.fill( noRepetitions - 1, inp ) // Concatenate batches. val out = inp.concat(srcN) // Concat forces copy. Hence, decoupling from source is safe. ctx.close() DependentBatchPoolDrawContext(out) } } final class RepeatBuilder extends DependentBatchPoolBuilder[RepeatBuilder] { override def repr : RepeatBuilder = this private var _noRepetitions : Int = 10 def noRepetitions : Int = _noRepetitions def noRepetitions_=(value: Int) : Unit = { require(value > 0) _noRepetitions = value } def setNoRepetitions(value: Int) : RepeatBuilder = { noRepetitions_=(value) this } override protected def doToString() : List[Any] = _noRepetitions :: super.doToString() override def hashCode() : Int = MurmurHash3.mix(super.hashCode(), _noRepetitions.hashCode()) override def canEqual(that: Any) : Boolean = that.isInstanceOf[RepeatBuilder] override protected def doEquals(other: Equatable) : Boolean = super.doEquals(other) && (other match { case other: RepeatBuilder => _noRepetitions == other._noRepetitions case _ => false }) override protected def doCopy() : RepeatBuilder = RepeatBuilder() override def copyTo(other: InstanceBuilder): Unit = { super.copyTo(other) other match { case other: RepeatBuilder => // TODO: Fix this: source.copyTo(other.source) other._noRepetitions = _noRepetitions case _ => } } override protected def doBuild(source: BatchPool, seed: InstanceSeed) : Repeat = new Repeat(this, seed, source) // --------------------------------------------------------------------------- // Conversion related // --------------------------------------------------------------------------- override protected def doToGraphEx(hints: Option[BuildHints], inputs: Seq[Vertex], nodeSink: mutable.Buffer[Node], edgeSink: mutable.Buffer[Edge]) : (Option[BuildHints], Seq[Vertex]) = { // Create self-vertex. val vertex = Vertex.derive(toString("\\n", "")) nodeSink += vertex // Add the vertex and edges with all inputs. for (input <- inputs) { val edge = Edge(input, vertex, LineStyle.Solid) for (hints <- hints) { edge.label = hints.toEdgeLabel } edgeSink += edge } // Compute output hints. val outHints = hints.map(hints => hints.derive( hints.platform, hints.layout.derive( hints.layout.noSamples * _noRepetitions ), hints.referencePlatform, hints.referenceLayout.derive( hints.referenceLayout.noSamples * _noRepetitions ) )) (outHints, Seq(vertex)) } } object RepeatBuilder { final def apply() : RepeatBuilder = new RepeatBuilder final def apply(source: BatchPoolBuilder) : RepeatBuilder = apply().setSource(source) final def apply(source: BatchPoolBuilder, noRepetitions: Int) : RepeatBuilder = apply(source).setNoRepetitions(noRepetitions) }
bashimao/ltudl
blaze/src/main/scala/edu/latrobe/blaze/batchpools/Repeat.scala
Scala
apache-2.0
4,859
/* Copyright 2009-2016 EPFL, Lausanne */ package leon package utils import scala.annotation.implicitNotFound @implicitNotFound("No implicit debug section found in scope. You need define an implicit DebugSection to use debug/ifDebug") sealed abstract class DebugSection(val name: String, val mask: Int) case object DebugSectionSolver extends DebugSection("solver", 1 << 0) case object DebugSectionSynthesis extends DebugSection("synthesis", 1 << 1) case object DebugSectionTimers extends DebugSection("timers", 1 << 2) case object DebugSectionOptions extends DebugSection("options", 1 << 3) case object DebugSectionVerification extends DebugSection("verification", 1 << 4) case object DebugSectionTermination extends DebugSection("termination", 1 << 5) case object DebugSectionTrees extends DebugSection("trees", 1 << 6) case object DebugSectionPositions extends DebugSection("positions", 1 << 7) case object DebugSectionDataGen extends DebugSection("datagen", 1 << 8) case object DebugSectionEvaluation extends DebugSection("eval", 1 << 9) case object DebugSectionRepair extends DebugSection("repair", 1 << 10) case object DebugSectionLeon extends DebugSection("leon", 1 << 11) case object DebugSectionXLang extends DebugSection("xlang", 1 << 12) case object DebugSectionTypes extends DebugSection("types", 1 << 13) case object DebugSectionIsabelle extends DebugSection("isabelle", 1 << 14) case object DebugSectionReport extends DebugSection("report", 1 << 15) case object DebugSectionGenC extends DebugSection("genc", 1 << 16) object DebugSections { val all = Set[DebugSection]( DebugSectionSolver, DebugSectionSynthesis, DebugSectionTimers, DebugSectionOptions, DebugSectionVerification, DebugSectionTermination, DebugSectionTrees, DebugSectionPositions, DebugSectionDataGen, DebugSectionEvaluation, DebugSectionRepair, DebugSectionLeon, DebugSectionXLang, DebugSectionTypes, DebugSectionIsabelle, DebugSectionReport, DebugSectionGenC ) }
regb/leon
src/main/scala/leon/utils/DebugSections.scala
Scala
gpl-3.0
2,193
/** * Original work: SecureSocial (https://github.com/jaliss/securesocial) * Copyright 2013 Jorge Aliss (jaliss at gmail dot com) - twitter: @jaliss * * Derivative work: Silhouette (https://github.com/mohiva/play-silhouette) * Modifications Copyright 2015 Mohiva Organisation (license at mohiva dot com) * * 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 com.mohiva.play.silhouette.impl.providers import java.net.URLEncoder._ import com.mohiva.play.silhouette.api._ import com.mohiva.play.silhouette.api.exceptions._ import com.mohiva.play.silhouette.api.util.ExtractableRequest import com.mohiva.play.silhouette.impl.exceptions.{ AccessDeniedException, UnexpectedResponseException } import com.mohiva.play.silhouette.impl.providers.OAuth2Provider._ import com.mohiva.play.silhouette.{ impl, _ } import play.api.libs.json._ import play.api.libs.functional.syntax._ import play.api.libs.ws.WSResponse import play.api.mvc._ import scala.concurrent.{ ExecutionContext, Future } import scala.util.{ Failure, Success, Try } /** * The Oauth2 info. * * @param accessToken The access token. * @param tokenType The token type. * @param expiresIn The number of seconds before the token expires. * @param refreshToken The refresh token. * @param params Additional params transported in conjunction with the token. */ case class OAuth2Info( accessToken: String, tokenType: Option[String] = None, expiresIn: Option[Int] = None, refreshToken: Option[String] = None, params: Option[Map[String, String]] = None) extends AuthInfo /** * The Oauth2 info companion object. */ object OAuth2Info { /** * Converts the JSON into a [[impl.providers.OAuth2Info]] object. */ implicit val infoReads = ( (__ \\ AccessToken).read[String] and (__ \\ TokenType).readNullable[String] and (__ \\ ExpiresIn).readNullable[Int] and (__ \\ RefreshToken).readNullable[String] )((accessToken: String, tokenType: Option[String], expiresIn: Option[Int], refreshToken: Option[String]) => new OAuth2Info(accessToken, tokenType, expiresIn, refreshToken) ) } /** * Base implementation for all OAuth2 providers. */ trait OAuth2Provider extends SocialProvider with Logger { /** * The type of the auth info. */ type A = OAuth2Info /** * The settings type. */ type Settings = OAuth2Settings /** * The state provider implementation. */ protected val stateProvider: OAuth2StateProvider /** * A list with headers to send to the API. */ protected val headers: Seq[(String, String)] = Seq() /** * Starts the authentication process. * * @param request The current request. * @tparam B The type of the request body. * @return Either a Result or the auth info from the provider. */ def authenticate[B]()(implicit request: ExtractableRequest[B]): Future[Either[Result, OAuth2Info]] = { request.extractString(Error).map { case e @ AccessDenied => new AccessDeniedException(AuthorizationError.format(id, e)) case e => new UnexpectedResponseException(AuthorizationError.format(id, e)) } match { case Some(throwable) => Future.failed(throwable) case None => request.extractString(Code) match { // We're being redirected back from the authorization server with the access code case Some(code) => stateProvider.validate.flatMap { state => getAccessToken(code).map(oauth2Info => Right(oauth2Info)) } // There's no code in the request, this is the first step in the OAuth flow case None => stateProvider.build.map { state => val serializedState = state.serialize val stateParam = if (serializedState.isEmpty) List() else List(State -> serializedState) val params = settings.scope.foldLeft(List( (ClientID, settings.clientID), (RedirectURI, resolveCallbackURL(settings.redirectURL)), (ResponseType, Code)) ++ stateParam ++ settings.authorizationParams.toList) { case (p, s) => (Scope, s) :: p } val encodedParams = params.map { p => encode(p._1, "UTF-8") + "=" + encode(p._2, "UTF-8") } val url = settings.authorizationURL.getOrElse { throw new ConfigurationException(AuthorizationURLUndefined.format(id)) } + encodedParams.mkString("?", "&", "") val redirect = stateProvider.publish(Results.Redirect(url), state) logger.debug("[Silhouette][%s] Use authorization URL: %s".format(id, settings.authorizationURL)) logger.debug("[Silhouette][%s] Redirecting to: %s".format(id, url)) Left(redirect) } } } } /** * Gets the access token. * * @param code The access code. * @param request The current request. * @return The info containing the access token. */ protected def getAccessToken(code: String)(implicit request: RequestHeader): Future[OAuth2Info] = { httpLayer.url(settings.accessTokenURL).withHeaders(headers: _*).post(Map( ClientID -> Seq(settings.clientID), ClientSecret -> Seq(settings.clientSecret), GrantType -> Seq(AuthorizationCode), Code -> Seq(code), RedirectURI -> Seq(resolveCallbackURL(settings.redirectURL))) ++ settings.accessTokenParams.mapValues(Seq(_))).flatMap { response => logger.debug("[Silhouette][%s] Access token response: [%s]".format(id, response.body)) Future.from(buildInfo(response)) } } /** * Builds the OAuth2 info from response. * * @param response The response from the provider. * @return The OAuth2 info on success, otherwise a failure. */ protected def buildInfo(response: WSResponse): Try[OAuth2Info] = { response.json.validate[OAuth2Info].asEither.fold( error => Failure(new UnexpectedResponseException(InvalidInfoFormat.format(id, error))), info => Success(info) ) } } /** * The OAuth2Provider companion object. */ object OAuth2Provider { /** * The error messages. */ val AuthorizationURLUndefined = "[Silhouette][%s] Authorization URL is undefined" val AuthorizationError = "[Silhouette][%s] Authorization server returned error: %s" val InvalidInfoFormat = "[Silhouette][%s] Cannot build OAuth2Info because of invalid response format: %s" /** * The OAuth2 constants. */ val ClientID = "client_id" val ClientSecret = "client_secret" val RedirectURI = "redirect_uri" val Scope = "scope" val ResponseType = "response_type" val State = "state" val GrantType = "grant_type" val AuthorizationCode = "authorization_code" val AccessToken = "access_token" val Error = "error" val Code = "code" val TokenType = "token_type" val ExpiresIn = "expires_in" val Expires = "expires" val RefreshToken = "refresh_token" val AccessDenied = "access_denied" } /** * The OAuth2 state. * * This is to prevent the client for CSRF attacks as described in the OAuth2 RFC. * @see https://tools.ietf.org/html/rfc6749#section-10.12 */ trait OAuth2State { /** * Checks if the state is expired. This is an absolute timeout since the creation of * the state. * * @return True if the state is expired, false otherwise. */ def isExpired: Boolean /** * Returns a serialized value of the state. * * @return A serialized value of the state. */ def serialize: String } /** * Provides state for authentication providers. */ trait OAuth2StateProvider { /** * The type of the state implementation. */ type State <: OAuth2State /** * Builds the state. * * @param request The current request. * @param ec The execution context to handle the asynchronous operations. * @tparam B The type of the request body. * @return The build state. */ def build[B](implicit request: ExtractableRequest[B], ec: ExecutionContext): Future[State] /** * Validates the provider and the client state. * * @param request The current request. * @param ec The execution context to handle the asynchronous operations. * @tparam B The type of the request body. * @return The state on success, otherwise an failure. */ def validate[B](implicit request: ExtractableRequest[B], ec: ExecutionContext): Future[State] /** * Publishes the state to the client. * * @param result The result to send to the client. * @param state The state to publish. * @param request The current request. * @tparam B The type of the request body. * @return The result to send to the client. */ def publish[B](result: Result, state: State)(implicit request: ExtractableRequest[B]): Result } /** * The OAuth2 settings. * * @param authorizationURL The authorization URL provided by the OAuth provider. * @param accessTokenURL The access token URL provided by the OAuth provider. * @param redirectURL The redirect URL to the application after a successful authentication on the OAuth provider. * The URL can be a relative path which will be resolved against the current request's host. * @param clientID The client ID provided by the OAuth provider. * @param clientSecret The client secret provided by the OAuth provider. * @param scope The OAuth2 scope parameter provided by the OAuth provider. * @param authorizationParams Additional params to add to the authorization request. * @param accessTokenParams Additional params to add to the access token request. * @param customProperties A map of custom properties for the different providers. */ case class OAuth2Settings( authorizationURL: Option[String] = None, accessTokenURL: String, redirectURL: String, clientID: String, clientSecret: String, scope: Option[String] = None, authorizationParams: Map[String, String] = Map.empty, accessTokenParams: Map[String, String] = Map.empty, customProperties: Map[String, String] = Map.empty)
cemcatik/play-silhouette
silhouette/app/com/mohiva/play/silhouette/impl/providers/OAuth2Provider.scala
Scala
apache-2.0
10,354
package com.github.vooolll.serialization import com.typesafe.scalalogging.LazyLogging import com.github.vooolll.domain.oauth.FacebookError.FacebookErrorType import com.github.vooolll.domain.oauth._ import io.circe._ import io.circe.Decoder._ import FacebookError._ object FacebookErrorCodeDecoders extends LazyLogging { implicit val decodeErrorType: Decoder[FacebookErrorType] = decodeInt map { case InvalidApiKey.code => InvalidApiKey case Session.code => Session case Unknown.code => Unknown case ServiceDown.code => ServiceDown case TooManyCalls.code => TooManyCalls case UserTooManyCalls.code => FacebookError.UserTooManyCalls case PermissionDenied.code => PermissionDenied case AccessTokenHasExpired.code => AccessTokenHasExpired case ApplicationLimitReached.code => ApplicationLimitReached case Blocked.code => Blocked case DuplicatePost.code => DuplicatePost case ErrorPostingLink.code => ErrorPostingLink case value if value >= 200 && value <= 299 => PermissionNotGrantedOrRemoved case InvalidVerificationCodeFormat.code => InvalidVerificationCodeFormat case SpecifiedObjectNotFound.code => SpecifiedObjectNotFound case e => logger.warn("Unknown code : " + e) FacebookError.Facebook4SUnsupportedError } }
vooolll/facebook4s
src/main/scala/com/github/vooolll/serialization/FacebookErrorCodeDecoders.scala
Scala
apache-2.0
1,529
/* * Copyright 2021 HM Revenue & Customs * * 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 uk.gov.hmrc.ct.computations import uk.gov.hmrc.ct.box.{CtBoxIdentifier, CtOptionalInteger, Linked} case class CP108(value: Option[Int]) extends CtBoxIdentifier(name = "Unpaid director's bonuses") with CtOptionalInteger object CP108 extends Linked[CP53, CP108] { override def apply(source: CP53): CP108 = CP108(source.value) }
hmrc/ct-calculations
src/main/scala/uk/gov/hmrc/ct/computations/CP108.scala
Scala
apache-2.0
945
object Main extends App { val source = scala.io.Source.fromFile(args(0)) val lines = source.getLines.filter(_.length > 0) for (l <- lines) println(BigInt(l).bitCount % 3) }
nikai3d/ce-challenges
moderate/predict_the_number.scala
Scala
bsd-3-clause
184
/* * Copyright 2001-2013 Artima, Inc. * * 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 org.scalatest import matchers.{BeMatcher, MatchResult, BePropertyMatcher, BePropertyMatchResult} import SharedHelpers._ import FailureMessages.decorateToStringValue import Matchers._ import exceptions.TestFailedException class ShouldBeShorthandForAllSpec extends Spec with EmptyMocks with BookPropertyMatchers { def errorMessage(index: Int, message: String, lineNumber: Int, left: Any): String = "'all' inspection failed, because: \\n" + " at index " + index + ", " + message + " (ShouldBeShorthandForAllSpec.scala:" + lineNumber + ") \\n" + "in " + decorateToStringValue(left) object `The shouldBe syntax` { def `should work with theSameInstanceAs` { val string = "Hi" val obj: AnyRef = string val otherString = new String("Hi") all(List(string, obj)) shouldBe theSameInstanceAs (string) all(List(string, obj)) shouldBe theSameInstanceAs (obj) val list = List(otherString, string) val caught1 = intercept[TestFailedException] { all(list) shouldBe theSameInstanceAs (otherString) } assert(caught1.message === (Some(errorMessage(1, "\\"Hi\\" was not the same instance as \\"Hi\\"", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with any` { all(List(8, 8, 8)) shouldBe 8 val list1 = List(1, 2) val caught1 = intercept[TestFailedException] { all(list1) shouldBe 1 } assert(caught1.message === (Some(errorMessage(1, "2 was not equal to 1", thisLineNumber - 2, list1)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val s = null all(List[String](s)) shouldBe null val list2 = List(null, "hi") val caught2 = intercept[TestFailedException] { all(list2) shouldBe null } assert(caught2.message === (Some(errorMessage(1, "\\"hi\\" was not null", thisLineNumber - 2, list2)))) assert(caught2.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) all(List(8, 9, 10)) shouldBe > (7) val list3 = List(7, 8, 9) val caught3 = intercept[TestFailedException] { all(list3) shouldBe > (7) } assert(caught3.message === Some(errorMessage(0, "7 was not greater than 7", thisLineNumber - 2, list3))) assert(caught3.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) all(List(4, 5, 6)) shouldBe < (7) val list4 = List(5, 6, 7) val caught4 = intercept[TestFailedException] { all(list4) shouldBe < (7) } assert(caught4.message === Some(errorMessage(2, "7 was not less than 7", thisLineNumber - 2, list4))) assert(caught4.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) all(List(7, 8, 9)) shouldBe >= (7) val list5 = List(6, 7, 8) val caught5 = intercept[TestFailedException] { all(list5) shouldBe >= (7) } assert(caught5.message === Some(errorMessage(0, "6 was not greater than or equal to 7", thisLineNumber - 2, list5))) assert(caught5.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) all(List(1, 2, 3)) shouldBe <= (7) val list6 = List(1, 2, 8) val caught6 = intercept[TestFailedException] { all(list6) shouldBe <= (7) } assert(caught6.message === Some(errorMessage(2, "8 was not less than or equal to 7", thisLineNumber - 2, list6))) assert(caught6.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) all(List(true, true, true)) shouldBe true val list7 = List(true, false, true) val caught7 = intercept[TestFailedException] { all(list7) shouldBe true } assert(caught7.message === Some(errorMessage(1, "false was not true", thisLineNumber - 2, list7))) assert(caught7.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should give a special "was not" instead of "was not equal to" error message if the right hand side is Boolean` { all(List(true, true, true)) shouldBe true val list1 = List(false, true) val caught1 = intercept[TestFailedException] { all(list1) shouldBe false } assert(caught1.message === (Some(errorMessage(1, "true was not false", thisLineNumber - 2, list1)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with BeMatcher` { class OddMatcher extends BeMatcher[Int] { def apply(left: Int): MatchResult = { MatchResult( left % 2 == 1, left.toString + " was even", left.toString + " was odd" ) } } val odd = new OddMatcher val even = not (odd) all(List(1, 3, 5)) shouldBe odd all(List(2, 4, 6)) shouldBe even val list1 = List(1, 2, 3) val caught1 = intercept[TestFailedException] { all(list1) shouldBe (odd) } assert(caught1.message === Some(errorMessage(1, "2 was even", thisLineNumber - 2, list1))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val list2 = List(6, 7, 8) val caught2 = intercept[TestFailedException] { all(list2) shouldBe (even) } assert(caught2.message === Some(errorMessage(1, "7 was odd", thisLineNumber - 2, list2))) assert(caught2.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with symbol` { emptyMock shouldBe 'empty isEmptyMock shouldBe 'empty all(List(emptyMock, isEmptyMock)) shouldBe 'empty val list1 = List(noPredicateMock) val ex1 = intercept[TestFailedException] { all(list1) shouldBe 'empty } assert(ex1.message === Some(errorMessage(0, "NoPredicateMock has neither an empty nor an isEmpty method", thisLineNumber - 2, list1))) assert(ex1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(ex1.failedCodeLineNumber === Some(thisLineNumber - 4)) val list2 = List(noPredicateMock) val ex2 = intercept[TestFailedException] { all(list2) shouldBe 'full } assert(ex2.message === Some(errorMessage(0, "NoPredicateMock has neither a full nor an isFull method", thisLineNumber - 2, list2))) assert(ex2.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(ex2.failedCodeLineNumber === Some(thisLineNumber - 4)) all(List(emptyMock, isEmptyMock)) shouldBe a ('empty) val list3 = List(noPredicateMock) val ex3 = intercept[TestFailedException] { all(list3) shouldBe a ('empty) } assert(ex3.message === Some(errorMessage(0, "NoPredicateMock has neither an empty nor an isEmpty method", thisLineNumber - 2, list3))) assert(ex3.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(ex3.failedCodeLineNumber === Some(thisLineNumber - 4)) all(List(emptyMock)) shouldBe an ('empty) val list4 = List(noPredicateMock) val ex4 = intercept[TestFailedException] { all(list4) shouldBe an ('empty) } assert(ex4.message === Some(errorMessage(0, "NoPredicateMock has neither an empty nor an isEmpty method", thisLineNumber - 2, list4))) assert(ex4.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(ex4.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with BePropertyMatcher` { case class MyFile( val name: String, val file: Boolean, val isDirectory: Boolean ) class FileBePropertyMatcher extends BePropertyMatcher[MyFile] { def apply(file: MyFile) = { new BePropertyMatchResult(file.file, "file") } } class DirectoryBePropertyMatcher extends BePropertyMatcher[MyFile] { def apply(file: MyFile) = { new BePropertyMatchResult(file.isDirectory, "directory") } } def file = new FileBePropertyMatcher def directory = new DirectoryBePropertyMatcher val myFile = new MyFile("temp.txt", true, false) val book = new Book("A Tale of Two Cities", "Dickens", 1859, 45, true) val badBook = new Book("A Tale of Two Cities", "Dickens", 1859, 45, false) all(List(book)) shouldBe goodRead val list1 = List(badBook) val caught1 = intercept[TestFailedException] { all(list1) shouldBe goodRead } assert(caught1.message === Some(errorMessage(0, "Book(A Tale of Two Cities,Dickens,1859,45,false) was not goodRead", thisLineNumber - 2, list1))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) all(List(book)) shouldBe a (goodRead) val list2 = List(badBook) val caught2 = intercept[TestFailedException] { all(list2) shouldBe a (goodRead) } assert(caught2.message === Some(errorMessage(0, "Book(A Tale of Two Cities,Dickens,1859,45,false) was not a goodRead", thisLineNumber - 2, list2))) assert(caught2.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) all(List(book)) shouldBe an (goodRead) val list3 = List(badBook) val caught3 = intercept[TestFailedException] { all(list3) shouldBe an (goodRead) } assert(caught3.message === Some(errorMessage(0, "Book(A Tale of Two Cities,Dickens,1859,45,false) was not an goodRead", thisLineNumber - 2, list3))) assert(caught3.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should with +-` { val sevenDotOh = 7.0 val minusSevenDotOh = -7.0 val sevenDotOhFloat = 7.0f val minusSevenDotOhFloat = -7.0f val sevenLong = 7L val minusSevenLong = -7L val sevenInt = 7 val minusSevenInt = -7 val sevenShort: Short = 7 val minusSevenShort: Short = -7 val sevenByte: Byte = 7 val minusSevenByte: Byte = -7 all(List(sevenDotOh)) shouldBe (7.1 +- 0.2) all(List(sevenDotOh)) shouldBe (6.9 +- 0.2) all(List(sevenDotOh)) shouldBe (7.0 +- 0.2) all(List(sevenDotOh)) shouldBe (7.2 +- 0.2) all(List(sevenDotOh)) shouldBe (6.8 +- 0.2) all(List(minusSevenDotOh)) shouldBe (-7.1 +- 0.2) all(List(minusSevenDotOh)) shouldBe (-6.9 +- 0.2) all(List(minusSevenDotOh)) shouldBe (-7.0 +- 0.2) all(List(minusSevenDotOh)) shouldBe (-7.2 +- 0.2) all(List(minusSevenDotOh)) shouldBe (-6.8 +- 0.2) // Double +- Float all(List(sevenDotOh)) shouldBe (7.1 +- 0.2f) all(List(sevenDotOh)) shouldBe (6.9 +- 0.2f) all(List(sevenDotOh)) shouldBe (7.0 +- 0.2f) all(List(sevenDotOh)) shouldBe (7.2 +- 0.2f) all(List(sevenDotOh)) shouldBe (6.8 +- 0.2f) all(List(minusSevenDotOh)) shouldBe (-7.1 +- 0.2f) all(List(minusSevenDotOh)) shouldBe (-6.9 +- 0.2f) all(List(minusSevenDotOh)) shouldBe (-7.0 +- 0.2f) all(List(minusSevenDotOh)) shouldBe (-7.2 +- 0.2f) all(List(minusSevenDotOh)) shouldBe (-6.8 +- 0.2f) // Double +- Long all(List(sevenDotOh)) shouldBe (7.1 +- 2L) all(List(sevenDotOh)) shouldBe (6.9 +- 2L) all(List(sevenDotOh)) shouldBe (7.0 +- 2L) all(List(sevenDotOh)) shouldBe (7.2 +- 2L) all(List(sevenDotOh)) shouldBe (6.8 +- 2L) all(List(minusSevenDotOh)) shouldBe (-7.1 +- 2L) all(List(minusSevenDotOh)) shouldBe (-6.9 +- 2L) all(List(minusSevenDotOh)) shouldBe (-7.0 +- 2L) all(List(minusSevenDotOh)) shouldBe (-7.2 +- 2L) all(List(minusSevenDotOh)) shouldBe (-6.8 +- 2L) // Double +- Int all(List(sevenDotOh)) shouldBe (7.1 +- 2) all(List(sevenDotOh)) shouldBe (6.9 +- 2) all(List(sevenDotOh)) shouldBe (7.0 +- 2) all(List(sevenDotOh)) shouldBe (7.2 +- 2) all(List(sevenDotOh)) shouldBe (6.8 +- 2) all(List(minusSevenDotOh)) shouldBe (-7.1 +- 2) all(List(minusSevenDotOh)) shouldBe (-6.9 +- 2) all(List(minusSevenDotOh)) shouldBe (-7.0 +- 2) all(List(minusSevenDotOh)) shouldBe (-7.2 +- 2) all(List(minusSevenDotOh)) shouldBe (-6.8 +- 2) // Double +- Short all(List(sevenDotOh)) shouldBe (7.1 +- 2.toShort) all(List(sevenDotOh)) shouldBe (6.9 +- 2.toShort) all(List(sevenDotOh)) shouldBe (7.0 +- 2.toShort) all(List(sevenDotOh)) shouldBe (7.2 +- 2.toShort) all(List(sevenDotOh)) shouldBe (6.8 +- 2.toShort) all(List(minusSevenDotOh)) shouldBe (-7.1 +- 2.toShort) all(List(minusSevenDotOh)) shouldBe (-6.9 +- 2.toShort) all(List(minusSevenDotOh)) shouldBe (-7.0 +- 2.toShort) all(List(minusSevenDotOh)) shouldBe (-7.2 +- 2.toShort) all(List(minusSevenDotOh)) shouldBe (-6.8 +- 2.toShort) // Double +- Byte all(List(sevenDotOh)) shouldBe (7.1 +- 2.toByte) all(List(sevenDotOh)) shouldBe (6.9 +- 2.toByte) all(List(sevenDotOh)) shouldBe (7.0 +- 2.toByte) all(List(sevenDotOh)) shouldBe (7.2 +- 2.toByte) all(List(sevenDotOh)) shouldBe (6.8 +- 2.toByte) all(List(minusSevenDotOh)) shouldBe (-7.1 +- 2.toByte) all(List(minusSevenDotOh)) shouldBe (-6.9 +- 2.toByte) all(List(minusSevenDotOh)) shouldBe (-7.0 +- 2.toByte) all(List(minusSevenDotOh)) shouldBe (-7.2 +- 2.toByte) all(List(minusSevenDotOh)) shouldBe (-6.8 +- 2.toByte) // Float +- Float all(List(sevenDotOhFloat)) shouldBe (7.1f +- 0.2f) all(List(sevenDotOhFloat)) shouldBe (6.9f +- 0.2f) all(List(sevenDotOhFloat)) shouldBe (7.0f +- 0.2f) all(List(sevenDotOhFloat)) shouldBe (7.2f +- 0.2f) all(List(sevenDotOhFloat)) shouldBe (6.8f +- 0.2f) all(List(minusSevenDotOhFloat)) shouldBe (-7.1f +- 0.2f) all(List(minusSevenDotOhFloat)) shouldBe (-6.9f +- 0.2f) all(List(minusSevenDotOhFloat)) shouldBe (-7.0f +- 0.2f) all(List(minusSevenDotOhFloat)) shouldBe (-7.2f +- 0.2f) all(List(minusSevenDotOhFloat)) shouldBe (-6.8f +- 0.2f) // Float +- Long all(List(sevenDotOhFloat)) shouldBe (7.1f +- 2L) all(List(sevenDotOhFloat)) shouldBe (6.9f +- 2L) all(List(sevenDotOhFloat)) shouldBe (7.0f +- 2L) all(List(sevenDotOhFloat)) shouldBe (7.2f +- 2L) all(List(sevenDotOhFloat)) shouldBe (6.8f +- 2L) all(List(minusSevenDotOhFloat)) shouldBe (-7.1f +- 2L) all(List(minusSevenDotOhFloat)) shouldBe (-6.9f +- 2L) all(List(minusSevenDotOhFloat)) shouldBe (-7.0f +- 2L) all(List(minusSevenDotOhFloat)) shouldBe (-7.2f +- 2L) all(List(minusSevenDotOhFloat)) shouldBe (-6.8f +- 2L) // Float +- Int all(List(sevenDotOhFloat)) shouldBe (7.1f +- 2) all(List(sevenDotOhFloat)) shouldBe (6.9f +- 2) all(List(sevenDotOhFloat)) shouldBe (7.0f +- 2) all(List(sevenDotOhFloat)) shouldBe (7.2f +- 2) all(List(sevenDotOhFloat)) shouldBe (6.8f +- 2) all(List(minusSevenDotOhFloat)) shouldBe (-7.1f +- 2) all(List(minusSevenDotOhFloat)) shouldBe (-6.9f +- 2) all(List(minusSevenDotOhFloat)) shouldBe (-7.0f +- 2) all(List(minusSevenDotOhFloat)) shouldBe (-7.2f +- 2) all(List(minusSevenDotOhFloat)) shouldBe (-6.8f +- 2) // Float +- Short all(List(sevenDotOhFloat)) shouldBe (7.1f +- 2.toShort) all(List(sevenDotOhFloat)) shouldBe (6.9f +- 2.toShort) all(List(sevenDotOhFloat)) shouldBe (7.0f +- 2.toShort) all(List(sevenDotOhFloat)) shouldBe (7.2f +- 2.toShort) all(List(sevenDotOhFloat)) shouldBe (6.8f +- 2.toShort) all(List(minusSevenDotOhFloat)) shouldBe (-7.1f +- 2.toShort) all(List(minusSevenDotOhFloat)) shouldBe (-6.9f +- 2.toShort) all(List(minusSevenDotOhFloat)) shouldBe (-7.0f +- 2.toShort) all(List(minusSevenDotOhFloat)) shouldBe (-7.2f +- 2.toShort) all(List(minusSevenDotOhFloat)) shouldBe (-6.8f +- 2.toShort) // Float +- Byte all(List(sevenDotOhFloat)) shouldBe (7.1f +- 2.toByte) all(List(sevenDotOhFloat)) shouldBe (6.9f +- 2.toByte) all(List(sevenDotOhFloat)) shouldBe (7.0f +- 2.toByte) all(List(sevenDotOhFloat)) shouldBe (7.2f +- 2.toByte) all(List(sevenDotOhFloat)) shouldBe (6.8f +- 2.toByte) all(List(minusSevenDotOhFloat)) shouldBe (-7.1f +- 2.toByte) all(List(minusSevenDotOhFloat)) shouldBe (-6.9f +- 2.toByte) all(List(minusSevenDotOhFloat)) shouldBe (-7.0f +- 2.toByte) all(List(minusSevenDotOhFloat)) shouldBe (-7.2f +- 2.toByte) all(List(minusSevenDotOhFloat)) shouldBe (-6.8f +- 2.toByte) // Long +- Long all(List(sevenLong)) shouldBe (9L +- 2L) all(List(sevenLong)) shouldBe (8L +- 2L) all(List(sevenLong)) shouldBe (7L +- 2L) all(List(sevenLong)) shouldBe (6L +- 2L) all(List(sevenLong)) shouldBe (5L +- 2L) all(List(minusSevenLong)) shouldBe (-9L +- 2L) all(List(minusSevenLong)) shouldBe (-8L +- 2L) all(List(minusSevenLong)) shouldBe (-7L +- 2L) all(List(minusSevenLong)) shouldBe (-6L +- 2L) all(List(minusSevenLong)) shouldBe (-5L +- 2L) // Long +- Int all(List(sevenLong)) shouldBe (9L +- 2) all(List(sevenLong)) shouldBe (8L +- 2) all(List(sevenLong)) shouldBe (7L +- 2) all(List(sevenLong)) shouldBe (6L +- 2) all(List(sevenLong)) shouldBe (5L +- 2) all(List(minusSevenLong)) shouldBe (-9L +- 2) all(List(minusSevenLong)) shouldBe (-8L +- 2) all(List(minusSevenLong)) shouldBe (-7L +- 2) all(List(minusSevenLong)) shouldBe (-6L +- 2) all(List(minusSevenLong)) shouldBe (-5L +- 2) // Long +- Short all(List(sevenLong)) shouldBe (9L +- 2.toShort) all(List(sevenLong)) shouldBe (8L +- 2.toShort) all(List(sevenLong)) shouldBe (7L +- 2.toShort) all(List(sevenLong)) shouldBe (6L +- 2.toShort) all(List(sevenLong)) shouldBe (5L +- 2.toShort) all(List(minusSevenLong)) shouldBe (-9L +- 2.toShort) all(List(minusSevenLong)) shouldBe (-8L +- 2.toShort) all(List(minusSevenLong)) shouldBe (-7L +- 2.toShort) all(List(minusSevenLong)) shouldBe (-6L +- 2.toShort) all(List(minusSevenLong)) shouldBe (-5L +- 2.toShort) // Long +- Byte all(List(sevenLong)) shouldBe (9L +- 2.toByte) all(List(sevenLong)) shouldBe (8L +- 2.toByte) all(List(sevenLong)) shouldBe (7L +- 2.toByte) all(List(sevenLong)) shouldBe (6L +- 2.toByte) all(List(sevenLong)) shouldBe (5L +- 2.toByte) all(List(minusSevenLong)) shouldBe (-9L +- 2.toByte) all(List(minusSevenLong)) shouldBe (-8L +- 2.toByte) all(List(minusSevenLong)) shouldBe (-7L +- 2.toByte) all(List(minusSevenLong)) shouldBe (-6L +- 2.toByte) all(List(minusSevenLong)) shouldBe (-5L +- 2.toByte) // Int +- Int all(List(sevenInt)) shouldBe (9 +- 2) all(List(sevenInt)) shouldBe (8 +- 2) all(List(sevenInt)) shouldBe (7 +- 2) all(List(sevenInt)) shouldBe (6 +- 2) all(List(sevenInt)) shouldBe (5 +- 2) all(List(minusSevenInt)) shouldBe (-9 +- 2) all(List(minusSevenInt)) shouldBe (-8 +- 2) all(List(minusSevenInt)) shouldBe (-7 +- 2) all(List(minusSevenInt)) shouldBe (-6 +- 2) all(List(minusSevenInt)) shouldBe (-5 +- 2) // Int +- Short all(List(sevenInt)) shouldBe (9 +- 2.toShort) all(List(sevenInt)) shouldBe (8 +- 2.toShort) all(List(sevenInt)) shouldBe (7 +- 2.toShort) all(List(sevenInt)) shouldBe (6 +- 2.toShort) all(List(sevenInt)) shouldBe (5 +- 2.toShort) all(List(minusSevenInt)) shouldBe (-9 +- 2.toShort) all(List(minusSevenInt)) shouldBe (-8 +- 2.toShort) all(List(minusSevenInt)) shouldBe (-7 +- 2.toShort) all(List(minusSevenInt)) shouldBe (-6 +- 2.toShort) all(List(minusSevenInt)) shouldBe (-5 +- 2.toShort) // Int +- Byte all(List(sevenInt)) shouldBe (9 +- 2.toByte) all(List(sevenInt)) shouldBe (8 +- 2.toByte) all(List(sevenInt)) shouldBe (7 +- 2.toByte) all(List(sevenInt)) shouldBe (6 +- 2.toByte) all(List(sevenInt)) shouldBe (5 +- 2.toByte) all(List(minusSevenInt)) shouldBe (-9 +- 2.toByte) all(List(minusSevenInt)) shouldBe (-8 +- 2.toByte) all(List(minusSevenInt)) shouldBe (-7 +- 2.toByte) all(List(minusSevenInt)) shouldBe (-6 +- 2.toByte) all(List(minusSevenInt)) shouldBe (-5 +- 2.toByte) // Short +- Short all(List(sevenShort)) shouldBe (9.toShort +- 2.toShort) all(List(sevenShort)) shouldBe (8.toShort +- 2.toShort) all(List(sevenShort)) shouldBe (7.toShort +- 2.toShort) all(List(sevenShort)) shouldBe (6.toShort +- 2.toShort) all(List(sevenShort)) shouldBe (5.toShort +- 2.toShort) all(List(minusSevenShort)) shouldBe ((-9).toShort +- 2.toShort) all(List(minusSevenShort)) shouldBe ((-8).toShort +- 2.toShort) all(List(minusSevenShort)) shouldBe ((-7).toShort +- 2.toShort) all(List(minusSevenShort)) shouldBe ((-6).toShort +- 2.toShort) all(List(minusSevenShort)) shouldBe ((-5).toShort +- 2.toShort) // Short +- Byte all(List(sevenShort)) shouldBe (9.toShort +- 2.toByte) all(List(sevenShort)) shouldBe (8.toShort +- 2.toByte) all(List(sevenShort)) shouldBe (7.toShort +- 2.toByte) all(List(sevenShort)) shouldBe (6.toShort +- 2.toByte) all(List(sevenShort)) shouldBe (5.toShort +- 2.toByte) all(List(minusSevenShort)) shouldBe ((-9).toShort +- 2.toByte) all(List(minusSevenShort)) shouldBe ((-8).toShort +- 2.toByte) all(List(minusSevenShort)) shouldBe ((-7).toShort +- 2.toByte) all(List(minusSevenShort)) shouldBe ((-6).toShort +- 2.toByte) all(List(minusSevenShort)) shouldBe ((-5).toShort +- 2.toByte) // Byte +- Byte all(List(sevenByte)) shouldBe (9.toByte +- 2.toByte) all(List(sevenByte)) shouldBe (8.toByte +- 2.toByte) all(List(sevenByte)) shouldBe (7.toByte +- 2.toByte) all(List(sevenByte)) shouldBe (6.toByte +- 2.toByte) all(List(sevenByte)) shouldBe (5.toByte +- 2.toByte) all(List(minusSevenByte)) shouldBe ((-9).toByte +- 2.toByte) all(List(minusSevenByte)) shouldBe ((-8).toByte +- 2.toByte) all(List(minusSevenByte)) shouldBe ((-7).toByte +- 2.toByte) all(List(minusSevenByte)) shouldBe ((-6).toByte +- 2.toByte) all(List(minusSevenByte)) shouldBe ((-5).toByte +- 2.toByte) val list1 = List(sevenDotOh) val caught1 = intercept[TestFailedException] { all(list1) shouldBe (17.1 +- 0.2) } assert(caught1.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 0.2", thisLineNumber - 2, list1))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) // Double +- Float val list2 = List(sevenDotOh) val caught2 = intercept[TestFailedException] { all(list2) shouldBe (17.1 +- 0.2f) } assert(caught2.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 0.20000000298023224", thisLineNumber - 2, list2))) assert(caught2.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) // Double +- Long val list3 = List(sevenDotOh) val caught3 = intercept[TestFailedException] { all(list3) shouldBe (17.1 +- 2L) } assert(caught3.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 2.0", thisLineNumber - 2, list3))) assert(caught3.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) // Double +- Int val list4 = List(sevenDotOh) val caught4 = intercept[TestFailedException] { all(list4) shouldBe (17.1 +- 2) } assert(caught4.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 2.0", thisLineNumber - 2, list4))) assert(caught4.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) // Double +- Short val list5 = List(sevenDotOh) val caught5 = intercept[TestFailedException] { all(list5) shouldBe (17.1 +- 2.toShort) } assert(caught5.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 2.0", thisLineNumber - 2, list5))) assert(caught5.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) // Double +- Byte val list6 = List(sevenDotOh) val caught6 = intercept[TestFailedException] { all(list6) shouldBe (17.1 +- 2.toByte) } assert(caught6.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 2.0", thisLineNumber - 2, list6))) assert(caught6.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) // Float +- Float val list7 = List(sevenDotOhFloat) val caught7 = intercept[TestFailedException] { all(list7) shouldBe (17.1f +- 0.2f) } assert(caught7.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 0.2", thisLineNumber - 2, list7))) assert(caught7.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) // Float +- Long val list8 = List(sevenDotOhFloat) val caught8 = intercept[TestFailedException] { all(list8) shouldBe (17.1f +- 2L) } assert(caught8.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 2.0", thisLineNumber - 2, list8))) assert(caught8.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) // Float +- Int val list9 = List(sevenDotOhFloat) val caught9 = intercept[TestFailedException] { all(list9) shouldBe (17.1f +- 2) } assert(caught9.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 2.0", thisLineNumber - 2, list9))) assert(caught9.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) // Float +- Short val list10 = List(sevenDotOhFloat) val caught10 = intercept[TestFailedException] { all(list10) shouldBe (17.1f +- 2.toShort) } assert(caught10.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 2.0", thisLineNumber - 2, list10))) assert(caught10.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) // Float +- Byte val list11 = List(sevenDotOhFloat) val caught11 = intercept[TestFailedException] { all(list11) shouldBe (17.1f +- 2.toByte) } assert(caught11.message === Some(errorMessage(0, "7.0 was not 17.1 plus or minus 2.0", thisLineNumber - 2, list11))) assert(caught11.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) // Long +- Long val list12 = List(sevenLong) val caught12 = intercept[TestFailedException] { all(list12) shouldBe (19L +- 2L) } assert(caught12.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list12))) assert(caught12.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) // Long +- Int val list13 = List(sevenLong) val caught13 = intercept[TestFailedException] { all(list13) shouldBe (19L +- 2) } assert(caught13.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list13))) assert(caught13.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught13.failedCodeLineNumber === Some(thisLineNumber - 4)) // Long +- Short val list14 = List(sevenLong) val caught14 = intercept[TestFailedException] { all(list14) shouldBe (19L +- 2.toShort) } assert(caught14.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list14))) assert(caught14.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught14.failedCodeLineNumber === Some(thisLineNumber - 4)) // Long +- Byte val list15 = List(sevenLong) val caught15 = intercept[TestFailedException] { all(list15) shouldBe (19L +- 2.toByte) } assert(caught15.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list15))) assert(caught15.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught15.failedCodeLineNumber === Some(thisLineNumber - 4)) // Int +- Int val list16 = List(sevenInt) val caught16 = intercept[TestFailedException] { all(list16) shouldBe (19 +- 2) } assert(caught16.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list16))) assert(caught16.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught16.failedCodeLineNumber === Some(thisLineNumber - 4)) // Int +- Short val list17 = List(sevenInt) val caught17 = intercept[TestFailedException] { all(list17) shouldBe (19 +- 2.toShort) } assert(caught17.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list17))) assert(caught17.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught17.failedCodeLineNumber === Some(thisLineNumber - 4)) // Int +- Byte val list18 = List(sevenInt) val caught18 = intercept[TestFailedException] { all(list18) shouldBe (19 +- 2.toByte) } assert(caught18.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list18))) assert(caught18.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught18.failedCodeLineNumber === Some(thisLineNumber - 4)) // Short +- Short val list19 = List(sevenShort) val caught19 = intercept[TestFailedException] { all(list19) shouldBe (19.toShort +- 2.toShort) } assert(caught19.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list19))) assert(caught19.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught19.failedCodeLineNumber === Some(thisLineNumber - 4)) // Short +- Byte val list20 = List(sevenShort) val caught20 = intercept[TestFailedException] { all(list20) shouldBe (19.toShort +- 2.toByte) } assert(caught20.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list20))) assert(caught20.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught20.failedCodeLineNumber === Some(thisLineNumber - 4)) // Byte +- Byte val list21 = List(sevenByte) val caught21 = intercept[TestFailedException] { all(list21) shouldBe (19.toByte +- 2.toByte) } assert(caught21.message === Some(errorMessage(0, "7 was not 19 plus or minus 2", thisLineNumber - 2, list21))) assert(caught21.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught21.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with a [AnyRef]` { val string1 = "Hi" val string2: Any = "Hello" val int = 8 all(List(string1, string2)) shouldBe a [String] all(List(string1, int)) shouldBe a [Any] val list: List[Any] = List(string1, int, string2) val caught1 = intercept[TestFailedException] { all(list) shouldBe a [String] } assert(caught1.message === (Some(errorMessage(1, "8 was not an instance of java.lang.String, but an instance of java.lang.Integer", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with a [java.lang.Integer] but not [Int]` { val int1 = 7 val int2: Any = 8 val str = "Hi" all(List(int1, int2)) shouldBe a [java.lang.Integer] all(List(int1, str)) shouldBe a [Any] val list: List[Any] = List(int1, int2) val caught1 = intercept[TestFailedException] { all(list) shouldBe a [Int] } assert(caught1.message === (Some(errorMessage(0, int1 + " was not an instance of int, but an instance of java.lang.Integer", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with a [java.lang.Long], but not [Long]` { val long1 = 7L val long2: Any = 8L val str = "Hi" all(List(long1, long2)) shouldBe a [java.lang.Long] all(List(long1, str)) shouldBe a [Any] val list: List[Any] = List(long1, long2) val caught1 = intercept[TestFailedException] { all(list) shouldBe a [Long] } assert(caught1.message === (Some(errorMessage(0, long1 + " was not an instance of long, but an instance of java.lang.Long", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with a [java.lang.Short], but not [Short]` { val short1: Short = 7 val short2: Any = 8.toShort val str = "Hi" all(List(short1, short2)) shouldBe a [java.lang.Short] all(List(short1, str)) shouldBe a [Any] val list: List[Any] = List(short1, short2) val caught1 = intercept[TestFailedException] { all(list) shouldBe a [Short] } assert(caught1.message === (Some(errorMessage(0, short1 + " was not an instance of short, but an instance of java.lang.Short", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with a [java.lang.Byte], but not [Byte]` { val byte1: Byte = 7.toByte val byte2: Any = 8.toByte val str = "Hi" all(List(byte1, byte2)) shouldBe a [java.lang.Byte] all(List(byte1, str)) shouldBe a [Any] val list: List[Any] = List(byte1, byte2) val caught1 = intercept[TestFailedException] { all(list) shouldBe a [Byte] } assert(caught1.message === (Some(errorMessage(0, byte1 + " was not an instance of byte, but an instance of java.lang.Byte", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with a [java.lang.Double], but not [Double]` { val double1: Double = 7.77 val double2: Any = 8.88 val str = "Hi" all(List(double1, double2)) shouldBe a [java.lang.Double] all(List(double1, str)) shouldBe a [Any] val list: List[Any] = List(double1, double2) val caught1 = intercept[TestFailedException] { all(list) shouldBe a [Double] } assert(caught1.message === (Some(errorMessage(0, double1 + " was not an instance of double, but an instance of java.lang.Double", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with a [java.lang.Float], but not [Float]` { val float1: Float = 7.77f val float2: Any = 8.88f val str = "Hi" all(List(float1, float2)) shouldBe a [java.lang.Float] all(List(float1, str)) shouldBe a [Any] val list: List[Any] = List(float1, float2) val caught1 = intercept[TestFailedException] { all(list) shouldBe a [Float] } assert(caught1.message === (Some(errorMessage(0, float1 + " was not an instance of float, but an instance of java.lang.Float", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with a [java.lang.Boolean], but not [Boolean]` { val bool1 = false val bool2: Any = true val str = "Hi" all(List(bool1, bool2)) shouldBe a [java.lang.Boolean] all(List(bool1, str)) shouldBe a [Any] val list: List[Any] = List(bool1, bool2) val caught1 = intercept[TestFailedException] { all(list) shouldBe a [Boolean] } assert(caught1.message === (Some(errorMessage(0, bool1 + " was not an instance of boolean, but an instance of java.lang.Boolean", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with a [java.lang.Character], but not [Char]` { val c1 = '7' val c2: Any = '8' val str = "Hi" all(List(c1, c2)) shouldBe a [java.lang.Character] all(List(c1, str)) shouldBe a [Any] val list: List[Any] = List(c1, c2) val caught1 = intercept[TestFailedException] { all(list) shouldBe a [Char] } assert(caught1.message === (Some(errorMessage(0, "'7' was not an instance of char, but an instance of java.lang.Character", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with an [AnyRef]` { val string1 = "Hi" val string2: Any = "Hello" val int = 8 all(List(string1, string2)) shouldBe an [String] all(List(string1, int)) shouldBe an [Any] val list: List[Any] = List(string1, int, string2) val caught1 = intercept[TestFailedException] { all(list) shouldBe an [String] } assert(caught1.message === (Some(errorMessage(1, "8 was not an instance of java.lang.String, but an instance of java.lang.Integer", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with an [java.lang.Intger], but not [Int]` { val int1 = 7 val int2: Any = 8 val str = "Hi" all(List(int1, int2)) shouldBe an [java.lang.Integer] all(List(int1, str)) shouldBe an [Any] val list: List[Any] = List(int1, int2) val caught1 = intercept[TestFailedException] { all(list) shouldBe an [Int] } assert(caught1.message === (Some(errorMessage(0, int1 + " was not an instance of int, but an instance of java.lang.Integer", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with an [java.lang.Long], but not [Long]` { val long1 = 7L val long2: Any = 8L val str = "Hi" all(List(long1, long2)) shouldBe an [java.lang.Long] all(List(long1, str)) shouldBe an [Any] val list: List[Any] = List(long1, long2) val caught1 = intercept[TestFailedException] { all(list) shouldBe an [Long] } assert(caught1.message === (Some(errorMessage(0, long1 + " was not an instance of long, but an instance of java.lang.Long", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with an [java.lang.Short], but not [Short]` { val short1: Short = 7 val short2: Any = 8.toShort val str = "Hi" all(List(short1, short2)) shouldBe an [java.lang.Short] all(List(short1, str)) shouldBe an [Any] val list: List[Any] = List(short1, short2) val caught1 = intercept[TestFailedException] { all(list) shouldBe an [Short] } assert(caught1.message === (Some(errorMessage(0, short1 + " was not an instance of short, but an instance of java.lang.Short", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with an [java.lang.Byte], but not [Byte]` { val byte1: Byte = 7.toByte val byte2: Any = 8.toByte val str = "Hi" all(List(byte1, byte2)) shouldBe an [java.lang.Byte] all(List(byte1, str)) shouldBe an [Any] val list: List[Any] = List(byte1, byte2) val caught1 = intercept[TestFailedException] { all(list) shouldBe an [Byte] } assert(caught1.message === (Some(errorMessage(0, byte1 + " was not an instance of byte, but an instance of java.lang.Byte", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with an [java.lang.Double], but not [Double]` { val double1: Double = 7.77 val double2: Any = 8.88 val str = "Hi" all(List(double1, double2)) shouldBe an [java.lang.Double] all(List(double1, str)) shouldBe an [Any] val list: List[Any] = List(double1, double2) val caught1 = intercept[TestFailedException] { all(list) shouldBe an [Double] } assert(caught1.message === (Some(errorMessage(0, double1 + " was not an instance of double, but an instance of java.lang.Double", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with an [java.lang.Float], but not [Float]` { val float1: Float = 7.77f val float2: Any = 8.88f val str = "Hi" all(List(float1, float2)) shouldBe an [java.lang.Float] all(List(float1, str)) shouldBe an [Any] val list: List[Any] = List(float1, float2, str) val caught1 = intercept[TestFailedException] { all(list) shouldBe an [Float] } assert(caught1.message === (Some(errorMessage(0, float1 + " was not an instance of float, but an instance of java.lang.Float", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with an [java.lang.Boolean], but not [Boolean]` { val bool1 = false val bool2: Any = true val str = "Hi" all(List(bool1, bool2)) shouldBe an [java.lang.Boolean] all(List(bool1, str)) shouldBe an [Any] val list: List[Any] = List(bool1, bool2) val caught1 = intercept[TestFailedException] { all(list) shouldBe an [Boolean] } assert(caught1.message === (Some(errorMessage(0, bool1 + " was not an instance of boolean, but an instance of java.lang.Boolean", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should work with an [java.lang.Character], but not [Char]` { val c1 = '7' val c2: Any = '8' val str = "Hi" all(List(c1, c2)) shouldBe an [java.lang.Character] all(List(c1, str)) shouldBe an [Any] val list: List[Any] = List(c1, c2) val caught1 = intercept[TestFailedException] { all(list) shouldBe an [Char] } assert(caught1.message === (Some(errorMessage(0, "'7' was not an instance of char, but an instance of java.lang.Character", thisLineNumber - 2, list)))) assert(caught1.failedCodeFileName === Some("ShouldBeShorthandForAllSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } } }
cheeseng/scalatest
scalatest-test/src/test/scala/org/scalatest/ShouldBeShorthandForAllSpec.scala
Scala
apache-2.0
46,600
package lila.tv import chess.Color import scala.concurrent.duration._ import scala.concurrent.Promise import lila.common.LightUser import lila.game.Game import lila.hub.SyncActor final private[tv] class ChannelSyncActor( channel: Tv.Channel, onSelect: TvSyncActor.Selected => Unit, proxyGame: Game.ID => Fu[Option[Game]], rematchOf: Game.ID => Option[Game.ID], lightUserSync: LightUser.GetterSync )(implicit ec: scala.concurrent.ExecutionContext) extends SyncActor { import ChannelSyncActor._ // games featured on this channel // first entry is the current game private var history = List.empty[Game.ID] private def oneId = history.headOption // the list of candidates by descending rating order private var manyIds = List.empty[Game.ID] private val candidateIds = new lila.memo.ExpireSetMemo(3 minutes) protected val process: SyncActor.Receive = { case GetGameId(promise) => promise success oneId case GetGameIdAndHistory(promise) => promise success GameIdAndHistory(oneId, history drop 1) case GetGameIds(max, promise) => promise success manyIds.take(max) case GetReplacementGameId(oldId, exclude, promise) => promise success { rematchOf(oldId) ++ manyIds find { !exclude.contains(_) } } case SetGame(game) => onSelect(TvSyncActor.Selected(channel, game)) history = game.id :: history.take(2) case TvSyncActor.Select => candidateIds.keys .map(proxyGame) .sequenceFu .map(_.view.collect { case Some(g) if channel isFresh g => g }.toList) .foreach { candidates => oneId ?? proxyGame foreach { case Some(current) if channel isFresh current => fuccess(wayBetter(current, candidates)) orElse rematch(current) foreach elect case Some(current) => rematch(current) orElse fuccess(bestOf(candidates)) foreach elect case _ => elect(bestOf(candidates)) } manyIds = candidates .sortBy { g => -(~g.averageUsersRating) } .take(50) .map(_.id) } } def addCandidate(game: Game): Unit = candidateIds put game.id private def elect(gameOption: Option[Game]): Unit = gameOption foreach { this ! SetGame(_) } private def wayBetter(game: Game, candidates: List[Game]) = bestOf(candidates) filter { isWayBetter(game, _) } private def isWayBetter(g1: Game, g2: Game) = score(g2.resetTurns) > (score(g1.resetTurns) * 1.17) private def rematch(game: Game): Fu[Option[Game]] = rematchOf(game.id) ?? proxyGame private def bestOf(candidates: List[Game]) = { import cats.implicits._ candidates.maximumByOption(score) } private def score(game: Game): Int = heuristics.foldLeft(0) { case (score, fn) => score + fn(game) } private type Heuristic = Game => Int private val heuristics: List[Heuristic] = List( ratingHeuristic(Color.White), ratingHeuristic(Color.Black), titleHeuristic(Color.White), titleHeuristic(Color.Black) ) private def ratingHeuristic(color: Color): Heuristic = game => game.player(color).stableRating | 1300 private def titleHeuristic(color: Color): Heuristic = game => ~game .player(color) .some .flatMap { p => p.stableRating.exists(2100 <) ?? p.userId } .flatMap(lightUserSync) .flatMap(_.title) .flatMap(Tv.titleScores.get) } object ChannelSyncActor { case class GetGameId(promise: Promise[Option[Game.ID]]) case class GetGameIds(max: Int, promise: Promise[List[Game.ID]]) case class GetReplacementGameId(oldId: Game.ID, exclude: List[Game.ID], promise: Promise[Option[Game.ID]]) private case class SetGame(game: Game) case class GetGameIdAndHistory(promise: Promise[GameIdAndHistory]) case class GameIdAndHistory(gameId: Option[Game.ID], history: List[Game.ID]) }
luanlv/lila
modules/tv/src/main/ChannelSyncActor.scala
Scala
mit
3,929
/** * Licensed to Big Data Genomics (BDG) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The BDG licenses this file * to you 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 org.bdgenomics.utils.minhash import org.apache.spark.mllib.linalg.{ Vector, Vectors } object MinHashSignature { /** * For two signatures, finds the key for the first bucket that both signatures * hash to, if one exists. * * @note This method does not check to ensure that the band size divides * roundly into the size of the signature; we delegate this check * to the function caller. * * @param sig1 First signature to compare. * @param sig2 Second signature to compare. * @param bandSize The size of bands to use. * @return Returns an option containing the first overlapping bucket key, if * one exists. */ private[minhash] def firstBucket(sig1: MinHashSignature, sig2: MinHashSignature, bandSize: Int): Option[MinHashBucketKey] = { // get and zip buckets val keys = sig1.bucket(bandSize).zip(sig2.bucket(bandSize)) // find first bucket where the two are equal, and take the band keys.find(p => p._1.equals(p._2)) .map(p => p._1) } } case class MinHashSignature private[minhash] (hashArray: Array[Int]) { /** * Splits this signature into multiple bands, which can then be used to * drive locality sensitive approximate checking. * * @note This method does not check to ensure that the band size divides * roundly into the size of the signature; we delegate this check * to the function caller. * * @param bandSize The number of signature rows to use per band. * @return Returns this signature sliced into multiple band keys. */ private[minhash] def bucket(bandSize: Int): Iterable[MinHashBucketKey] = { // split into groups val groups = hashArray.grouped(bandSize) // build and return keys var band = -1 groups.map(keys => { band += 1 MinHashBucketKey(band, keys) }).toIterable } /** * Computes the estimated Jaccard similarity of two objects that have MinHash * signatures. * * @note This signature must be the same length as the signature we are * comparing to. We do not perform this check; we delegate this check * to the function caller. * * @param other Another signature to similarity against. * @return Returns the estimated Jaccard similarity of two signatures, which * is defined as the number of elements in the signature that agree * over the total length of the signature. */ def similarity(other: MinHashSignature): Double = { var overlap = 0 // loop over elements - increment overlap count if signatures match hashArray.indices.foreach(i => { if (hashArray(i) == other.hashArray(i)) { overlap += 1 } }) // similarity is the number of matching elements over the signature length overlap.toDouble / hashArray.length.toDouble } /** * Goes from hash array to an MLLib vector. * * @return A dense vector that can be used in MLLib. */ def toVector: Vector = Vectors.dense(hashArray.map(_.toDouble)) }
tdanford/bdg-utils
utils-minhash/src/main/scala/org/bdgenomics/utils/minhash/MinHashSignature.scala
Scala
apache-2.0
3,896
/** Copyright 2014 TappingStone, Inc. * * 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 io.prediction.engines.base import io.prediction.controller.PDataSource import io.prediction.data.view.PBatchView import io.prediction.data.view.ViewPredicates import org.joda.time.DateTime import org.joda.time.Duration import scala.reflect.ClassTag import grizzled.slf4j.Logger import org.apache.spark.rdd.RDD import org.apache.spark.SparkContext import org.apache.spark.SparkContext._ class PEventsDataSource[DP: ClassTag, Q, A]( dsp: AbstractEventsDataSourceParams) extends PDataSource[DP, PTrainingData, Q, A] { @transient lazy val logger = Logger[this.type] override def read(sc: SparkContext): Seq[(DP, PTrainingData, RDD[(Q, A)])] = { val batchView = new PBatchView( appId = dsp.appId, startTime = dsp.startTime, untilTime = dsp.untilTime, sc = sc) if (dsp.slidingEval.isEmpty) { val (uid2ui, users) = extractUsers(batchView, dsp.untilTime) val (iid2ii, items) = extractItems(batchView, dsp.untilTime) val actions = extractActions(batchView, uid2ui, iid2ii, dsp.startTime, dsp.untilTime) val trainingData = new PTrainingData( users = users, items = items, u2iActions = actions) return Seq((null.asInstanceOf[DP], trainingData, sc.parallelize(Seq[(Q, A)]()))) } else { val evalParams = dsp.slidingEval.get val evalDuration = evalParams.evalDuration val firstTrainUntil = evalParams.firstTrainingUntilTime return (0 until evalParams.evalCount).map { idx => { // Use [dsp.startTime, firstTrain + idx * duration) as training val trainUntil = firstTrainUntil.plus(idx * evalDuration.getMillis) val evalStart = trainUntil val evalUntil = evalStart.plus(evalDuration) println(s"Eval $idx " + s"train: [, $trainUntil) eval: [$evalStart, $evalUntil)") val (uid2ui, users) = extractUsers(batchView, Some(trainUntil)) val (iid2ii, items) = extractItems(batchView, Some(trainUntil)) val trainActions = extractActions( batchView, uid2ui, iid2ii, startTimeOpt = dsp.startTime, untilTimeOpt = Some(trainUntil)) val trainingData = new PTrainingData( users = users, items = items, u2iActions = trainActions) // Use [firstTrain + idx * duration, firstTraing + (idx+1) * duration) // as testing val evalActions = extractActions( batchView, uid2ui, iid2ii, startTimeOpt = Some(evalStart), untilTimeOpt = Some(evalUntil)) val (dp, qaSeq) = generateQueryActualSeq( users, items, evalActions, trainUntil, evalStart, evalUntil, sc) (dp, trainingData, qaSeq) }} } } // sub-classes should override this method. def generateQueryActualSeq( users: RDD[(Int, UserTD)], items: RDD[(Int, ItemTD)], actions: RDD[U2IActionTD], trainUntil: DateTime, evalStart: DateTime, evalUntil: DateTime, sc: SparkContext): (DP, RDD[(Q, A)]) = { // first return value is a fake data param to make compiler happy (null.asInstanceOf[DP], sc.parallelize(Seq[(Q, A)]())) } def extractUsers(batchView: PBatchView, untilTimeOpt: Option[DateTime] = None) : (RDD[(String, Int)], RDD[(Int, UserTD)]) = { val attributeNames = dsp.attributeNames val usersMap: RDD[((String, UserTD), Int)] = batchView .aggregateProperties( entityType = attributeNames.user, untilTimeOpt = untilTimeOpt) .map { case (entityId, dataMap) => (entityId, new UserTD(uid = entityId)) } .zipWithUniqueId // theis Long id may exist gaps but no need spark job // TODO: may need to change local EventDataSource to use Long. // Force to Int now so can re-use same userTD, itemTD, and ratingTD .mapValues( _.toInt ) (usersMap.map{ case ((uid, uTD), idx) => (uid, idx) }, usersMap.map{ case ((uid, uTD), idx) => (idx, uTD) }) } def extractItems(batchView: PBatchView, untilTimeOpt: Option[DateTime] = None) : (RDD[(String, Int)], RDD[(Int, ItemTD)]) = { val attributeNames = dsp.attributeNames val itemsMap: RDD[((String, ItemTD), Int)] = batchView .aggregateProperties( entityType = attributeNames.item, untilTimeOpt = untilTimeOpt) .map { case (entityId, dataMap) => val itemTD = try { new ItemTD( iid = entityId, itypes = dataMap.get[List[String]](attributeNames.itypes), starttime = dataMap.getOpt[DateTime](attributeNames.starttime) .map(_.getMillis), endtime = dataMap.getOpt[DateTime](attributeNames.endtime) .map(_.getMillis), inactive = dataMap.getOpt[Boolean](attributeNames.inactive) .getOrElse(false) ) } catch { case exception: Exception => { logger.error(s"${exception}: entityType ${attributeNames.item} " + s"entityID ${entityId}: ${dataMap}." ) throw exception } } (entityId -> itemTD) } .filter { case (id, (itemTD)) => // TODO. Traverse itemTD.itypes to avoid a toSet function. Looking up // dsp.itypes is constant time. dsp.itypes .map{ t => !(itemTD.itypes.toSet.intersect(t).isEmpty) }.getOrElse(true) } .zipWithUniqueId // the Long id may exist gaps but no need spark job // TODO: may need to change local EventDataSource to use Long. // Force to Int now so can re-use same userTD, itemTD, and ratingTD .mapValues( _.toInt ) (itemsMap.map{ case ((iid, iTD), idx) => (iid, idx) }, itemsMap.map{ case ((iid, iTD), idx) => (idx, iTD) }) } def extractActions(batchView: PBatchView, uid2ui: RDD[(String, Int)], iid2ii: RDD[(String, Int)], startTimeOpt: Option[DateTime] = None, untilTimeOpt: Option[DateTime] = None ): RDD[U2IActionTD] = { val attributeNames = dsp.attributeNames batchView .events .filter( e => (true && ViewPredicates.getStartTimePredicate(startTimeOpt)(e) && ViewPredicates.getUntilTimePredicate(untilTimeOpt)(e) && attributeNames.u2iActions.contains(e.event) && dsp.actions.contains(e.event) )) // TODO: can use broadcast variable if uid2ui and iid2ui is small // so no need to join to avoid shuffle .map( e => (e.entityId, e) ) .join(uid2ui) // (entityID, (e, ui)) .map{ case (eid, (e, ui)) => require( (e.targetEntityId != None), s"u2i Event: ${e} cannot have targetEntityId empty.") (e.targetEntityId.get, (e, ui)) } .join(iid2ii) // (targetEntityId, ((e, ui), ii)) .map{ case (teid, ((e, ui), ii)) => try { new U2IActionTD( uindex = ui, iindex = ii, action = e.event, v = e.properties.getOpt[Int](attributeNames.rating), t = e.eventTime.getMillis ) } catch { case exception: Exception => { logger.error(s"${exception}: event ${e}.") throw exception } } } } }
TheDataShed/PredictionIO
engines/src/main/scala/base/PEventsDataSource.scala
Scala
apache-2.0
7,812
package services.elasticsearch.elastic4s import java.nio.charset.Charset import com.sksamuel.elastic4s.http.{JacksonSupport, ResponseHandler} import org.apache.http.HttpEntity import org.elasticsearch.client.{Response, ResponseException} import play.api.libs.json.{JsValue, Json} import scala.io.{Codec, Source} import scala.util.{Failure, Try} /** * This is a custom response handler for musit. It enables us to preserve the origin * response from elasticsearch parsed to JsValue. */ object MusitResponseHandler { def parse[U: Manifest](entity: HttpEntity): MusitESResponse[U] = { val charset = Option(entity.getContentEncoding).map(_.getValue).getOrElse("UTF-8") implicit val codec: Codec = Codec(Charset.forName(charset)) val body = Source.fromInputStream(entity.getContent).mkString MusitESResponse(JacksonSupport.mapper.readValue[U](body), Json.parse(body)) } def default[U: Manifest] = new MusitResponseHandler[U] def failure404[U: Manifest] = new Musit404ResponseHandler[U] } class MusitResponseHandler[U: Manifest] extends ResponseHandler[MusitESResponse[U]] { override def onResponse(response: Response): Try[MusitESResponse[U]] = Try(MusitResponseHandler.parse[U](response.getEntity)) } class Musit404ResponseHandler[U: Manifest] extends MusitResponseHandler[U] { override def onError(e: Exception): Try[MusitESResponse[U]] = e match { case re: ResponseException if re.getResponse.getStatusLine.getStatusCode == 404 => Try(MusitResponseHandler.parse[U](re.getResponse.getEntity)) case _ => Failure(e) } } /** * The parsed response from elastic4s and the raw response pared with play-json. */ case class MusitESResponse[R](response: R, raw: JsValue)
MUSIT-Norway/musit
service_backend/app/services/elasticsearch/elastic4s/MusitResponseHandler.scala
Scala
gpl-2.0
1,731
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.flink.table.plan.cost import org.apache.calcite.plan.RelOptCost /** * This class is based on Apache Calcite's [[org.apache.calcite.plan.volcano.VolcanoCost#Factory]]. */ class FlinkCostFactory extends FlinkCostFactoryBase { override def makeCost( rowCount: Double, cpu: Double, io: Double, network: Double, memory: Double): RelOptCost = { new FlinkCost(rowCount, cpu, io, network, memory) } override def makeCost(dRows: Double, dCpu: Double, dIo: Double): RelOptCost = { new FlinkCost(dRows, dCpu, dIo, 0.0, 0.0) } override def makeHugeCost: RelOptCost = FlinkCost.Huge override def makeInfiniteCost: RelOptCost = FlinkCost.Infinity override def makeTinyCost: RelOptCost = FlinkCost.Tiny override def makeZeroCost: RelOptCost = FlinkCost.Zero }
ueshin/apache-flink
flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/cost/FlinkCostFactory.scala
Scala
apache-2.0
1,638
/* Copyright 2013 Twitter, Inc. 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 com.twitter.summingbird.example import com.twitter.bijection.{ Bufferable, Codec, Injection } import com.twitter.summingbird.batch.BatchID import twitter4j.Status import twitter4j.json.DataObjectFactory /** * Serialization is often the most important (and hairy) * configuration issue for any system that needs to store its data * over the long term. Summingbird controls serialization through the * "Injection" interface. * * By maintaining identical Injections from K and V to Array[Byte], * one can guarantee that data written one day will be readable the * next. This isn't the case with serialization engines like Kryo, * where serialization format depends on unstable parameters, like * the serializer registration order for the given Kryo instance. */ object Serialization { /** * This Injection converts the twitter4j.Status objects that Storm * and Scalding will process into Strings. */ implicit val statusCodec: Injection[Status, String] = Injection.buildCatchInvert[Status, String](DataObjectFactory.getRawJSON(_))( json => DataObjectFactory.createStatus(json) ) /** * We can chain the Status <-> String injection above with the * library-supplied String <-> Array[Byte] injection to generate a * full-on serializer for Status objects of the type * Injection[Status, Array[Byte]]. Our Storm and Scalding sources * can now pull in this injection using Scala's implicit resolution * and properly register the serializer. */ implicit val toBytes = Injection.connect[Status, String, Array[Byte]] /** * Summingbird's implementation of the batch/realtime merge * requires that the Storm-based workflow store (K, BatchID) -> V * pairs, while the Hadoop-based workflow stores K -> (BatchID, V) * pairs. * * The following two injections use Bijection's "Bufferable" object * to generate injections that take (T, BatchID) or (BatchID, T) to * bytes. * * For true production applications, I'd suggest defining a thrift * or protobuf "pair" structure that can safely store these pairs * over the long-term. */ implicit def kInjection[T: Codec]: Injection[(T, BatchID), Array[Byte]] = { implicit val buf = Bufferable.viaInjection[(T, BatchID), (Array[Byte], Array[Byte])] Bufferable.injectionOf[(T, BatchID)] } implicit def vInj[V: Codec]: Injection[(BatchID, V), Array[Byte]] = Injection.connect[(BatchID, V), (V, BatchID), Array[Byte]] }
rangadi/summingbird
summingbird-example/src/main/scala/com/twitter/summingbird/example/Serialization.scala
Scala
apache-2.0
3,049
package jgo.tools.compiler package interm package expr package bfunc import types._ import instr._ import codeseq.CodeBuilder object Make extends BuiltinTypeFunc { def name = "make" private def intCode(e: Expr, desc: String)(pos: Pos): Err[CodeBuilder] = e match { case UntypedIntegralConst(i) => result(PushInt(i, I32)) case HasType(iT: IntegralType) => result(e.evalUnder) case _ => problem("specified %s not of integral type", desc)(pos) //"specified size not of integral type", etc. } def typeInvoke(t: Type, args: List[Expr])(pos: Pos) = t.underlying match { case SliceType(et) => args match { case List() => problem("not enough arguments for slice-make; length unspecified")(pos) case List(len) => for (lenC <- intCode(len, "length")(pos)) yield UnderlyingExpr(lenC |+| MakeSliceLen(et), t) case List(len, cap) => for ((lenC, capC) <- (intCode(len, "length")(pos), intCode(cap, "capacity")(pos))) yield UnderlyingExpr(lenC |+| capC |+| MakeSliceLenCap(et), t) case _ => problem("too many arguments for slice-make")(pos) } case MapType(k, v) => args match { case List() => result(UnderlyingExpr(MakeMap(k, v), t)) case List(size) => for (sizeC <- intCode(size, "size")(pos)) yield UnderlyingExpr(sizeC |+| MakeMapSize(k, v), t) case _ => problem("too many arguments for map-make")(pos) } case AnyChanType(et) => args match { case List() => result(UnderlyingExpr(MakeChan(et), t)) case List(size) => for (sizeC <- intCode(size, "size")(pos)) yield UnderlyingExpr(sizeC |+| MakeChanSize(et), t) case _ => problem("too many arguments for chan-make")(pos) } case _ => problem("cannot make type %s; slice, map, or chan type required", t)(pos) } }
thomasmodeneis/jgo
src/src/main/scala/jgo/tools/compiler/interm/expr/bfunc/Make.scala
Scala
gpl-3.0
1,858
/* * Copyright 2007-2010 WorldWide Conferencing, LLC * * 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 bootstrap.liftweb import _root_.net.liftweb._ import common.{Box, Full, Empty, Failure} import util.{Helpers, Log, NamedPF, Props} import http._ import actor._ import provider._ import sitemap._ import Helpers._ import example._ import widgets.autocomplete._ import comet._ import model._ import lib._ import _root_.net.liftweb.mapper.{DB, ConnectionManager, Schemifier, DefaultConnectionIdentifier, ConnectionIdentifier} import _root_.java.sql.{Connection, DriverManager} import snippet._ /** * A class that's instantiated early and run. It allows the application * to modify lift's environment */ class Boot { def boot { DB.defineConnectionManager(DefaultConnectionIdentifier, DBVendor) LiftRules.addToPackages("net.liftweb.example") LiftRules.localeCalculator = r => definedLocale.openOr(LiftRules.defaultLocaleCalculator(r)) if (!Props.inGAE) { // No DB stuff in GAE Schemifier.schemify(true, Log.infoF _, User, WikiEntry, Person) } WebServices.init() XmlServer.init() LiftRules.statelessDispatchTable.append { case r@Req("stateless" :: _, "", GetRequest) => StatelessHtml.render(r) _ } LiftRules.dispatch.prepend(NamedPF("Login Validation") { case Req("login" :: page, "", _) if !LoginStuff.is && page.head != "validate" => () => Full(RedirectResponse("/login/validate")) }) LiftRules.snippetDispatch.append(NamedPF("Template") (Map("Template" -> Template, "AllJson" -> AllJson))) LiftRules.snippetDispatch.append { case "MyWizard" => MyWizard case "WizardChallenge" => WizardChallenge case "ScreenForm" => PersonScreen } LiftRules.snippetDispatch.append(Map("runtime_stats" -> RuntimeStats)) /* * Show the spinny image when an Ajax call starts */ LiftRules.ajaxStart = Full(() => LiftRules.jsArtifacts.show("ajax-loader").cmd) /* * Make the spinny image go away when it ends */ LiftRules.ajaxEnd = Full(() => LiftRules.jsArtifacts.hide("ajax-loader").cmd) LiftRules.early.append(makeUtf8) LiftSession.onBeginServicing = RequestLogger.beginServicing _ :: LiftSession.onBeginServicing LiftSession.onEndServicing = RequestLogger.endServicing _ :: LiftSession.onEndServicing LiftRules.setSiteMap(SiteMap(MenuInfo.menu: _*)) ThingBuilder.boot() AutoComplete.init() // Dump information about session every 10 minutes SessionMaster.sessionWatchers = SessionInfoDumper :: SessionMaster.sessionWatchers // Dump browser information each time a new connection is made LiftSession.onBeginServicing = BrowserLogger.haveSeenYou _ :: LiftSession.onBeginServicing } private def makeUtf8(req: HTTPRequest): Unit = {req.setCharacterEncoding("UTF-8")} } object RequestLogger { object startTime extends RequestVar(0L) def beginServicing(session: LiftSession, req: Req) { startTime(millis) } def endServicing(session: LiftSession, req: Req, response: Box[LiftResponse]) { val delta = millis - startTime.is Log.info("At " + (timeNow) + " Serviced " + req.uri + " in " + (delta) + "ms " + ( response.map(r => " Headers: " + r.toResponse.headers) openOr "" )) } } object MenuInfo { import Loc._ def menu: List[Menu] = Menu(Loc("home", List("index"), "Home")) :: Menu(Loc("Interactive", List("interactive"), "Interactive Stuff"), Menu(Loc("chat", List("chat"), "Comet Chat", Unless(() => Props.inGAE, "Disabled for GAE"))), Menu(Loc("longtime", List("longtime"), "Updater", Unless(() => Props.inGAE, "Disabled for GAE"))), Menu(Loc("ajax", List("ajax"), "AJAX Samples")), Menu(Loc("ajax form", List("ajax-form"), "AJAX Form")), Menu(Loc("js confirm", List("rhodeisland"), "Modal Dialog")), Menu(Loc("json", List("json"), "JSON Messaging")), Menu(Loc("json_more", List("json_more"), "More JSON")), Menu(Loc("form_ajax", List("form_ajax"), "Ajax and Forms")) ) :: Menu(Loc("Persistence", List("persistence"), "Persistence", Unless(() => Props.inGAE, "Disabled for GAE")), Menu(Loc("xml fun", List("xml_fun"), "XML Fun", Unless(() => Props.inGAE, "Disabled for GAE"))), Menu(Loc("database", List("database"), "Database", Unless(() => Props.inGAE, "Disabled for GAE"))), Menu(Loc("simple", Link(List("simple"), true, "/simple/index"), "Simple Forms", Unless(() => Props.inGAE, "Disabled for GAE"))), Menu(Loc("template", List("template"), "Templates", Unless(() => Props.inGAE, "Disabled for GAE")))) :: Menu(Loc("Templating", List("templating", "index"), "Templating"), Menu(Loc("Surround", List("templating", "surround"), "Surround")), Menu(Loc("Embed", List("templating", "embed"), "Embed")), Menu(Loc("eval-order", List("templating", "eval_order"), "Evalutation Order")), Menu(Loc("select-o-matuc", List("templating", "selectomatic"), "Select <div>s")), Menu(Loc("Simple Wizard", List("simple_wizard"), "Simple Wizard")), Menu(Loc("head", List("templating", "head"), "<head/> tag"))) :: Menu(Loc("ws", List("ws"), "Web Services", Unless(() => Props.inGAE, "Disabled for GAE"))) :: Menu(Loc("lang", List("lang"), "Localization")) :: Menu(Loc("menu_top", List("menu", "index"), "Menus"), Menu(Loc("menu_one", List("menu", "one"), "First Submenu")), Menu(Loc("menu_two", List("menu", "two"), "Second Submenu (has more)"), Menu(Loc("menu_two_one", List("menu", "two_one"), "First (2) Submenu")), Menu(Loc("menu_two_two", List("menu", "two_two"), "Second (2) Submenu")) ), Menu(Loc("menu_three", List("menu", "three"), "Third Submenu")), Menu(Loc("menu_four", List("menu", "four"), "Forth Submenu")) ) :: Menu(WikiStuff) :: Menu(Loc("Misc", List("misc"), "Misc code"), Menu(Loc("guess", List("guess"), "Number Guessing")), Menu(Loc("Wiz", List("wiz"), "Wizard")), Menu(Loc("Wiz2", List("wiz2"), "Wizard Challenge")), Menu(Loc("Simple Screen", List("simple_screen"), "Simple Screen")), Menu(Loc("arc", List("arc"), "Arc Challenge #1")), Menu(Loc("file_upload", List("file_upload"), "File Upload")), Menu(Loc("login", Link(List("login"), true, "/login/index"), <xml:group>Requiring Login<strike>SiteMap</strike> </xml:group>)), Menu(Loc("count", List("count"), "Counting"))) :: Menu(Loc("lift", ExtLink("http://liftweb.net"), <xml:group> <i>Lift</i>project home</xml:group>)) :: Nil } /** * Database connection calculation */ object DBVendor extends ConnectionManager { private var pool: List[Connection] = Nil private var poolSize = 0 private val maxPoolSize = 4 private lazy val chooseDriver = Props.mode match { case Props.RunModes.Production => "org.apache.derby.jdbc.EmbeddedDriver" case _ => "org.h2.Driver" } private lazy val chooseURL = Props.mode match { case Props.RunModes.Production => "jdbc:derby:lift_example;create=true" case _ => "jdbc:h2:mem:lift;DB_CLOSE_DELAY=-1" } private def createOne: Box[Connection] = try { val driverName: String = Props.get("db.driver") openOr chooseDriver val dbUrl: String = Props.get("db.url") openOr chooseURL Class.forName(driverName) val dm = (Props.get("db.user"), Props.get("db.password")) match { case (Full(user), Full(pwd)) => DriverManager.getConnection(dbUrl, user, pwd) case _ => DriverManager.getConnection(dbUrl) } Full(dm) } catch { case e: Exception => e.printStackTrace; Empty } def newConnection(name: ConnectionIdentifier): Box[Connection] = synchronized { pool match { case Nil if poolSize < maxPoolSize => val ret = createOne poolSize = poolSize + 1 ret.foreach(c => pool = c :: pool) ret case Nil => wait(1000L); newConnection(name) case x :: xs => try { x.setAutoCommit(false) Full(x) } catch { case e => try { pool = xs poolSize = poolSize - 1 x.close newConnection(name) } catch { case e => newConnection(name) } } } } def releaseConnection(conn: Connection): Unit = synchronized { pool = conn :: pool notify } } object BrowserLogger { object HaveSeenYou extends SessionVar(false) def haveSeenYou(session: LiftSession, request: Req) { if (!HaveSeenYou.is) { Log.info("Created session " + session.uniqueId + " IP: {" + request.request.remoteAddress + "} UserAgent: {{" + request.userAgent.openOr("N/A") + "}}") HaveSeenYou(true) } } } object SessionInfoDumper extends LiftActor { private var lastTime = millis val tenMinutes: Long = 10 minutes protected def messageHandler = { case SessionWatcherInfo(sessions) => if ((millis - tenMinutes) > lastTime) { lastTime = millis val rt = Runtime.getRuntime rt.gc RuntimeStats.lastUpdate = timeNow RuntimeStats.totalMem = rt.totalMemory RuntimeStats.freeMem = rt.freeMemory RuntimeStats.sessions = sessions.size val dateStr: String = timeNow.toString Log.info("[MEMDEBUG] At " + dateStr + " Number of open sessions: " + sessions.size) Log.info("[MEMDEBUG] Free Memory: " + pretty(rt.freeMemory)) Log.info("[MEMDEBUG] Total Memory: " + pretty(rt.totalMemory)) } } private def pretty(in: Long): String = if (in > 1000L) pretty(in / 1000L) + "," + (in % 1000L) else in.toString }
jeppenejsum/liftweb
examples/example/src/main/scala/bootstrap/liftweb/Boot.scala
Scala
apache-2.0
10,685
package scala.scalajs.runtime import scala.scalajs.js import StackTrace.JSStackTraceElem /** Information about the JavaScript environment Scala.js runs in. * * Holds configuration for the Scala.js internals and should not be used * directly (could be retrieved via [[runtime.environmentInfo]]). * * This facade type serves as a documentation on what aspects of Scala.js can * be influenced through environment options. * * Upon startup, Scala.js checks whether the name <code>__ScalaJSEnv</code> is * defined in its scope (and references an object). If so, it uses it as * environment info. * Missing, non-optional fields (according to this facade type) are initialized * to default values, optional fields are kept as in the original object. * Finally, [[js.Object.freeze]] is called on the object to avoid modification. * * @groupname envInfo Scala.js environment configuration * @groupprio envInfo 1 */ @js.native trait EnvironmentInfo extends js.Object { /** The global JavaScript scope (corresponds to js.Dynamic.global) * * @group envInfo */ def global: js.Dynamic = js.native /** The scope for Scala.js exports (i.e. objects and classes) * * @group envInfo */ def exportsNamespace: js.Dynamic = js.native /** The function that is called by [[java.lang.Runtime.exit]] * * @group envInfo */ def exitFunction: js.UndefOr[js.Function1[Int, Nothing]] = js.native /** Method used to source map JavaScript stack traces * * @group envInfo */ def sourceMapper: js.UndefOr[js.Function1[ // scalastyle:ignore js.Array[JSStackTraceElem], js.Array[JSStackTraceElem]]] = js.native }
CapeSepias/scala-js
library/src/main/scala/scala/scalajs/runtime/EnvironmentInfo.scala
Scala
bsd-3-clause
1,673
package io.fintrospect.parameters import com.twitter.finagle.http.{Message, Request} trait HeaderParameter[T] extends Parameter with Rebindable[Message, T, RequestBinding] { override val where = "header" } object HeaderExtractAndRebind extends ParameterExtractAndBind[Message, String, RequestBinding] { def newBinding(parameter: Parameter, value: String) = new RequestBinding(parameter, { req: Request => { req.headerMap.add(parameter.name, value) req } }) def valuesFrom(parameter: Parameter, message: Message): Option[Seq[String]] = { val headers = message.headerMap.getAll(parameter.name) if (headers.isEmpty) None else Some(headers) } }
daviddenton/fintrospect
core/src/main/scala/io/fintrospect/parameters/HeaderParameter.scala
Scala
apache-2.0
686
package io.iohk.ethereum.rlp import java.nio.ByteBuffer import scala.annotation.{switch, tailrec} import scala.collection.immutable.Queue /** * Recursive Length Prefix (RLP) encoding. * <p> * The purpose of RLP is to encode arbitrarily nested arrays of binary data, and * RLP is the main encoding method used to serialize objects in Ethereum. The * only purpose of RLP is to encode structure; encoding specific atomic data * types (eg. strings, integers, floats) is left up to higher-order protocols; in * Ethereum the standard is that integers are represented in big endian binary * form. If one wishes to use RLP to encode a dictionary, the two suggested * canonical forms are to either use &#91;&#91;k1,v1],[k2,v2]...] with keys in * lexicographic order or to use the higher-level Patricia Tree encoding as * Ethereum does. * <p> * The RLP encoding function takes in an item. An item is defined as follows: * <p> * - A string (ie. byte array) is an item - A list of items is an item * <p> * For example, an empty string is an item, as is the string containing the word * "cat", a list containing any number of strings, as well as more complex data * structures like ["cat",["puppy","cow"],"horse",[[]],"pig",[""],"sheep"]. Note * that in the context of the rest of this article, "string" will be used as a * synonym for "a certain number of bytes of binary data"; no special encodings * are used and no knowledge about the content of the strings is implied. * <p> * See: https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP */ private[rlp] object RLP { /** * Reason for threshold according to Vitalik Buterin: * - 56 bytes maximizes the benefit of both options * - if we went with 60 then we would have only had 4 slots for long strings * so RLP would not have been able to store objects above 4gb * - if we went with 48 then RLP would be fine for 2^128 space, but that's way too much * - so 56 and 2^64 space seems like the right place to put the cutoff * - also, that's where Bitcoin's varint does the cutof */ private val SizeThreshold: Int = 56 /** * Allow for content up to size of 2&#94;64 bytes * */ private val MaxItemLength: Double = Math.pow(256, 8) /** RLP encoding rules are defined as follows: */ /* * For a single byte whose value is in the [0x00, 0x7f] range, that byte is * its own RLP encoding. */ /** * [0x80] * If a string is 0-55 bytes long, the RLP encoding consists of a single * byte with value 0x80 plus the length of the string followed by the * string. The range of the first byte is thus [0x80, 0xb7]. */ private val OffsetShortItem: Int = 0x80 /** * [0xb7] * If a string is more than 55 bytes long, the RLP encoding consists of a * single byte with value 0xb7 plus the length of the length of the string * in binary form, followed by the length of the string, followed by the * string. For example, a length-1024 string would be encoded as * \\xb9\\x04\\x00 followed by the string. The range of the first byte is thus * [0xb8, 0xbf]. */ private val OffsetLongItem: Int = 0xb7 /** * [0xc0] * If the total payload of a list (i.e. the combined length of all its * items) is 0-55 bytes long, the RLP encoding consists of a single byte * with value 0xc0 plus the length of the list followed by the concatenation * of the RLP encodings of the items. The range of the first byte is thus * [0xc0, 0xf7]. */ private val OffsetShortList: Int = 0xc0 /** * [0xf7] * If the total payload of a list is more than 55 bytes long, the RLP * encoding consists of a single byte with value 0xf7 plus the length of the * length of the list in binary form, followed by the length of the list, * followed by the concatenation of the RLP encodings of the items. The * range of the first byte is thus [0xf8, 0xff]. */ private val OffsetLongList = 0xf7 /** * This functions decodes an RLP encoded Array[Byte] without converting it to any specific type. This method should * be faster (as no conversions are done) * * @param data RLP Encoded instance to be decoded * @return A RLPEncodeable * @throws RLPException if there is any error */ private[rlp] def rawDecode(data: Array[Byte]): RLPEncodeable = decodeWithPos(data, 0)._1 /** * This function encodes an RLPEncodeable instance * * @param input RLP Instance to be encoded * @return A byte array with item encoded */ private[rlp] def encode(input: RLPEncodeable): Array[Byte] = { input match { case list: RLPList => val output = list.items.foldLeft(Array[Byte]()) { (acum, item) => acum ++ encode(item) } encodeLength(output.length, OffsetShortList) ++ output case value: RLPValue => val inputAsBytes = value.bytes if (inputAsBytes.length == 1 && (inputAsBytes(0) & 0xff) < 0x80) inputAsBytes else encodeLength(inputAsBytes.length, OffsetShortItem) ++ inputAsBytes } } /** * This function transform a byte into byte array * * @param singleByte to encode * @return encoded bytes */ private[rlp] def byteToByteArray(singleByte: Byte): Array[Byte] = { if ((singleByte & 0xff) == 0) Array.emptyByteArray else Array[Byte](singleByte) } /** * This function converts a short value to a big endian byte array of minimal length * * @param singleShort value to encode * @return encoded bytes */ private[rlp] def shortToBigEndianMinLength(singleShort: Short): Array[Byte] = { if ((singleShort & 0xff) == singleShort) byteToByteArray(singleShort.toByte) else Array[Byte]((singleShort >> 8 & 0xff).toByte, (singleShort >> 0 & 0xff).toByte) } /** * This function converts an int value to a big endian byte array of minimal length * * @param singleInt value to encode * @return encoded bytes */ private[rlp] def intToBigEndianMinLength(singleInt: Int): Array[Byte] = { if (singleInt == (singleInt & 0xff)) byteToByteArray(singleInt.toByte) else if (singleInt == (singleInt & 0xffff)) shortToBigEndianMinLength(singleInt.toShort) else if (singleInt == (singleInt & 0xffffff)) Array[Byte]((singleInt >>> 16).toByte, (singleInt >>> 8).toByte, singleInt.toByte) else Array[Byte]((singleInt >>> 24).toByte, (singleInt >>> 16).toByte, (singleInt >>> 8).toByte, singleInt.toByte) } /** * This function converts from a big endian byte array of minimal length to an int value * * @param bytes encoded bytes * @return Int value * @throws RLPException If the value cannot be converted to a valid int */ private[rlp] def bigEndianMinLengthToInt(bytes: Array[Byte]): Int = { (bytes.length: @switch) match { case 0 => 0: Short case 1 => bytes(0) & 0xff case 2 => ((bytes(0) & 0xff) << 8) + (bytes(1) & 0xff) case 3 => ((bytes(0) & 0xff) << 16) + ((bytes(1) & 0xff) << 8) + (bytes(2) & 0xff) case Integer.BYTES => ((bytes(0) & 0xff) << 24) + ((bytes(1) & 0xff) << 16) + ((bytes(2) & 0xff) << 8) + (bytes(3) & 0xff) case _ => throw RLPException("Bytes don't represent an int") } } /** * Converts a int value into a byte array. * * @param value - int value to convert * @return value with leading byte that are zeroes striped */ private def intToBytesNoLeadZeroes(value: Int): Array[Byte] = ByteBuffer.allocate(Integer.BYTES).putInt(value).array().dropWhile(_ == (0: Byte)) /** * Integer limitation goes up to 2&#94;31-1 so length can never be bigger than MAX_ITEM_LENGTH */ private def encodeLength(length: Int, offset: Int): Array[Byte] = { if (length < SizeThreshold) Array((length + offset).toByte) else if (length < MaxItemLength && length > 0xff) { val binaryLength: Array[Byte] = intToBytesNoLeadZeroes(length) (binaryLength.length + offset + SizeThreshold - 1).toByte +: binaryLength } else if (length < MaxItemLength && length <= 0xff) Array((1 + offset + SizeThreshold - 1).toByte, length.toByte) else throw RLPException("Input too long") } /** * This function calculates, based on RLP definition, the bounds of a single value. * * @param data An Array[Byte] containing the RLP item to be searched * @param pos Initial position to start searching * @return Item Bounds description * @see [[io.iohk.ethereum.rlp.ItemBounds]] */ private[rlp] def getItemBounds(data: Array[Byte], pos: Int): ItemBounds = { if (data.isEmpty) throw RLPException("Empty Data") else { val prefix: Int = data(pos) & 0xff if (prefix == OffsetShortItem) { ItemBounds(start = pos, end = pos, isList = false, isEmpty = true) } else if (prefix < OffsetShortItem) ItemBounds(start = pos, end = pos, isList = false) else if (prefix <= OffsetLongItem) { val length = prefix - OffsetShortItem ItemBounds(start = pos + 1, end = pos + length, isList = false) } else if (prefix < OffsetShortList) { val lengthOfLength = prefix - OffsetLongItem val lengthBytes = data.slice(pos + 1, pos + 1 + lengthOfLength) val length = bigEndianMinLengthToInt(lengthBytes) val beginPos = pos + 1 + lengthOfLength ItemBounds(start = beginPos, end = beginPos + length - 1, isList = false) } else if (prefix <= OffsetLongList) { val length = prefix - OffsetShortList ItemBounds(start = pos + 1, end = pos + length, isList = true) } else { val lengthOfLength = prefix - OffsetLongList val lengthBytes = data.slice(pos + 1, pos + 1 + lengthOfLength) val length = bigEndianMinLengthToInt(lengthBytes) val beginPos = pos + 1 + lengthOfLength ItemBounds(start = beginPos, end = beginPos + length - 1, isList = true) } } } private def decodeWithPos(data: Array[Byte], pos: Int): (RLPEncodeable, Int) = if (data.isEmpty) throw RLPException("data is too short") else { getItemBounds(data, pos) match { case ItemBounds(start, end, false, isEmpty) => RLPValue(if (isEmpty) Array.emptyByteArray else data.slice(start, end + 1)) -> (end + 1) case ItemBounds(start, end, true, _) => RLPList(decodeListRecursive(data, start, end - start + 1, Queue()): _*) -> (end + 1) } } @tailrec private def decodeListRecursive( data: Array[Byte], pos: Int, length: Int, acum: Queue[RLPEncodeable] ): (Queue[RLPEncodeable]) = { if (length == 0) acum else { val (decoded, decodedEnd) = decodeWithPos(data, pos) decodeListRecursive(data, decodedEnd, length - (decodedEnd - pos), acum :+ decoded) } } } private case class ItemBounds(start: Int, end: Int, isList: Boolean, isEmpty: Boolean = false)
input-output-hk/etc-client
src/main/scala/io/iohk/ethereum/rlp/RLP.scala
Scala
mit
10,932
package org.igye.logic.predicates.common import org.igye.logic.Predicate case class eqTo(left: Predicate, right: Predicate) extends Predicate(left, right) { override def copy(orderedChildren: List[Predicate]): eqTo = eqTo(orderedChildren(0), orderedChildren(1)) override def toString: String = s"$left ==> $right" }
Igorocky/logicproc
src/main/scala/org/igye/logic/predicates/common/eqTo.scala
Scala
mit
327
/* * 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 wvlet.airframe.sql.model import wvlet.airframe.sql.analyzer.QuerySignatureConfig trait LogicalPlan extends TreeNode[LogicalPlan] with Product with SQLSig { def modelName: String = { val n = this.getClass.getSimpleName if (n.endsWith("$")) n.substring(0, n.length - 1) else n } def pp: String = { LogicalPlanPrinter.print(this) } /** * All child nodes of this plan node * * @return */ def children: Seq[LogicalPlan] /** * Expressions associated to this LogicalPlan node * * @return */ def expressions: Seq[Expression] = { def collectExpression(x: Any): Seq[Expression] = { x match { case e: Expression => e :: Nil case Some(x) => collectExpression(x) case s: Iterable[_] => s.flatMap(collectExpression _).toSeq case other => Nil } } productIterator.flatMap { x => collectExpression(x) }.toSeq } def mapChildren(f: LogicalPlan => LogicalPlan): LogicalPlan = { var changed = false def recursiveTransform(arg: Any): AnyRef = arg match { case e: Expression => e case l: LogicalPlan => { val newPlan = f(l) if (!newPlan.eq(l)) { changed = true } newPlan } case Some(x) => Some(recursiveTransform(x)) case s: Seq[_] => s.map(recursiveTransform _) case other: AnyRef => other case null => null } val newArgs = productIterator.map(recursiveTransform).toIndexedSeq if (changed) { copyInstance(newArgs) } else { this } } def transform(rule: PartialFunction[LogicalPlan, LogicalPlan]): LogicalPlan = { val newNode: LogicalPlan = rule.applyOrElse(this, identity[LogicalPlan]) if (newNode.eq(this)) { mapChildren(_.transform(rule)) } else { newNode.mapChildren(_.transform(rule)) } } def transformExpressions(rule: PartialFunction[Expression, Expression]): LogicalPlan = { def recursiveTransform(arg: Any): AnyRef = arg match { case e: Expression => e.transformExpression(rule) case l: LogicalPlan => l.transformExpressions(rule) case Some(x) => Some(recursiveTransform(x)) case s: Seq[_] => s.map(recursiveTransform _) case other: AnyRef => other case null => null } val newArgs = productIterator.map(recursiveTransform).toIndexedSeq copyInstance(newArgs) } protected def copyInstance(newArgs: Seq[AnyRef]): this.type = { val primaryConstructor = this.getClass.getDeclaredConstructors()(0) val newObj = primaryConstructor.newInstance(newArgs: _*) newObj.asInstanceOf[this.type] } def collectExpressions: List[Expression] = { def recursiveCollect(arg: Any): List[Expression] = arg match { case e: Expression => e :: e.collectSubExpressions case l: LogicalPlan => l.collectExpressions case Some(x) => recursiveCollect(x) case s: Seq[_] => s.flatMap(recursiveCollect _).toList case other: AnyRef => Nil case null => Nil } productIterator.flatMap(recursiveCollect).toList } def traverseExpressions[U](rule: PartialFunction[Expression, U]): Unit = { def recursiveTraverse(arg: Any): Unit = arg match { case e: Expression => e.traverseExpressions(rule) case l: LogicalPlan => l.traverseExpressions(rule) case Some(x) => recursiveTraverse(x) case s: Seq[_] => s.foreach(recursiveTraverse _) case other: AnyRef => case null => } productIterator.foreach(recursiveTraverse) } // Input attributes (column names) of the relation def inputAttributes: Seq[Attribute] // Output attributes (column names) of the relation def outputAttributes: Seq[Attribute] // True if all input attributes are resolved. lazy val resolved: Boolean = expressions.forall(_.resolved) && resolvedChildren def resolvedChildren: Boolean = children.forall(_.resolved) } trait LeafPlan extends LogicalPlan { override def children: Seq[LogicalPlan] = Nil override def inputAttributes: Seq[Attribute] = Nil } trait UnaryPlan extends LogicalPlan { def child: LogicalPlan override def children: Seq[LogicalPlan] = child :: Nil override def inputAttributes: Seq[Attribute] = child.outputAttributes } trait BinaryPlan extends LogicalPlan { def left: LogicalPlan def right: LogicalPlan override def children: Seq[LogicalPlan] = Seq(left, right) } /** * A trait for LogicalPlan nodes that can generate SQL signatures */ trait SQLSig { def sig(config: QuerySignatureConfig = QuerySignatureConfig()): String } object LogicalPlan { import Expression._ private def isSelectAll(selectItems: Seq[Attribute]): Boolean = { selectItems.exists { case AllColumns(x) => true case _ => false } } // Relational operator trait Relation extends LogicalPlan with SQLSig // A relation that takes a single input relation sealed trait UnaryRelation extends Relation with UnaryPlan { def inputRelation: Relation = child override def child: Relation } case class ParenthesizedRelation(child: Relation) extends UnaryRelation { override def sig(config: QuerySignatureConfig): String = child.sig(config) override def inputAttributes: Seq[Attribute] = child.inputAttributes override def outputAttributes: Seq[Attribute] = child.outputAttributes } case class AliasedRelation(child: Relation, alias: Identifier, columnNames: Option[Seq[String]]) extends UnaryRelation { override def sig(config: QuerySignatureConfig): String = child.sig(config) override def inputAttributes: Seq[Attribute] = child.inputAttributes override def outputAttributes: Seq[Attribute] = child.outputAttributes } case class Values(rows: Seq[Expression]) extends Relation with LeafPlan { override def sig(config: QuerySignatureConfig): String = { s"V[${rows.length}]" } override def outputAttributes: Seq[Attribute] = (0 until rows.size).map(x => UnresolvedAttribute(s"i${x}")) } case class TableRef(name: QName) extends Relation with LeafPlan { override def sig(config: QuerySignatureConfig): String = { if (config.embedTableNames) { name.toString } else { "T" } } override def outputAttributes: Seq[Attribute] = Nil override lazy val resolved: Boolean = false } case class RawSQL(sql: String) extends Relation with LeafPlan { override def sig(config: QuerySignatureConfig): String = "Q" override def outputAttributes: Seq[Attribute] = Nil } // Deduplicate (duplicate elimination) the input releation case class Distinct(child: Relation) extends UnaryRelation { override def sig(config: QuerySignatureConfig): String = s"E(${child.sig(config)})" override def outputAttributes: Seq[Attribute] = child.outputAttributes } case class Sort(child: Relation, orderBy: Seq[SortItem]) extends UnaryRelation { override def sig(config: QuerySignatureConfig): String = s"O[${orderBy.length}](${child.sig(config)})" override def outputAttributes: Seq[Attribute] = child.outputAttributes } case class Limit(child: Relation, limit: LongLiteral) extends UnaryRelation { override def sig(config: QuerySignatureConfig): String = s"L(${child.sig(config)})" override def outputAttributes: Seq[Attribute] = child.outputAttributes } case class Filter(child: Relation, filterExpr: Expression) extends UnaryRelation { override def sig(config: QuerySignatureConfig): String = s"F(${child.sig(config)})" override def outputAttributes: Seq[Attribute] = child.outputAttributes } case object EmptyRelation extends Relation with LeafPlan { // Need to override this method so as not to create duplicate case object instances override def copyInstance(newArgs: Seq[AnyRef]) = this override def sig(config: QuerySignatureConfig) = "" override def outputAttributes: Seq[Attribute] = Nil } // This node can be a pivot node for generating a SELECT statament sealed trait Selection extends UnaryRelation { def selectItems: Seq[Attribute] } case class Project(child: Relation, selectItems: Seq[Attribute]) extends UnaryRelation with Selection { override def sig(config: QuerySignatureConfig): String = { val proj = if (LogicalPlan.isSelectAll(selectItems)) "*" else s"${selectItems.length}" s"P[${proj}](${child.sig(config)})" } // TODO override def outputAttributes: Seq[Attribute] = { selectItems } } case class Aggregate( child: Relation, selectItems: Seq[Attribute], groupingKeys: Seq[GroupingKey], having: Option[Expression] ) extends UnaryRelation with Selection { override def sig(config: QuerySignatureConfig): String = { val proj = if (LogicalPlan.isSelectAll(selectItems)) "*" else s"${selectItems.length}" s"A[${proj},${groupingKeys.length}](${child.sig(config)})" } override def toString = s"Aggregate[${groupingKeys.mkString(",")}](Select[${selectItems.mkString(", ")}(${child})" override def outputAttributes: Seq[Attribute] = selectItems } case class Query(withQuery: With, body: Relation) extends Relation { override def children: Seq[LogicalPlan] = { val b = Seq.newBuilder[LogicalPlan] b ++= withQuery.children b += body b.result() } override def sig(config: QuerySignatureConfig): String = { val wq = for (q <- withQuery.queries) yield { s"${q.query.sig(config)}" } val wq_s = wq.mkString(",") s"W[${wq_s}](${body.sig(config)})" } override def inputAttributes: Seq[Attribute] = body.inputAttributes override def outputAttributes: Seq[Attribute] = body.outputAttributes } case class With(recursive: Boolean, queries: Seq[WithQuery]) extends LogicalPlan { override def sig(config: QuerySignatureConfig) = "" override def children: Seq[LogicalPlan] = queries override def inputAttributes: Seq[Attribute] = ??? override def outputAttributes: Seq[Attribute] = ??? } case class WithQuery(name: Identifier, query: Relation, columnNames: Option[Seq[Identifier]]) extends LogicalPlan with UnaryPlan { override def sig(config: QuerySignatureConfig) = "" override def child: LogicalPlan = query override def inputAttributes: Seq[Attribute] = query.inputAttributes override def outputAttributes: Seq[Attribute] = query.outputAttributes } // Joins case class Join(joinType: JoinType, left: Relation, right: Relation, cond: JoinCriteria) extends Relation { override def modelName: String = joinType.toString override def children: Seq[LogicalPlan] = Seq(left, right) override def sig(config: QuerySignatureConfig): String = { s"${joinType.symbol}(${left.sig(config)},${right.sig(config)})" } override def inputAttributes: Seq[Attribute] = left.outputAttributes ++ right.outputAttributes override def outputAttributes: Seq[Attribute] = inputAttributes } sealed abstract class JoinType(val symbol: String) // Exact match (= equi join) case object InnerJoin extends JoinType("J") // Joins for preserving left table entries case object LeftOuterJoin extends JoinType("LJ") // Joins for preserving right table entries case object RightOuterJoin extends JoinType("RJ") // Joins for preserving both table entries case object FullOuterJoin extends JoinType("FJ") // Cartesian product of two tables case object CrossJoin extends JoinType("CJ") // From clause contains only table names, and // Where clause specifies join criteria case object ImplicitJoin extends JoinType("J") sealed trait SetOperation extends Relation { override def children: Seq[Relation] } case class Intersect(relations: Seq[Relation]) extends SetOperation { override def children: Seq[Relation] = relations override def sig(config: QuerySignatureConfig): String = { s"IX(${relations.map(_.sig(config)).mkString(",")})" } override def inputAttributes: Seq[Attribute] = relations.head.inputAttributes override def outputAttributes: Seq[Attribute] = relations.head.outputAttributes } case class Except(left: Relation, right: Relation) extends SetOperation { override def children: Seq[Relation] = Seq(left, right) override def sig(config: QuerySignatureConfig): String = { s"EX(${left.sig(config)},${right.sig(config)})" } override def inputAttributes: Seq[Attribute] = left.inputAttributes override def outputAttributes: Seq[Attribute] = left.outputAttributes } case class Union(relations: Seq[Relation]) extends SetOperation { override def children: Seq[Relation] = relations override def toString = { s"Union(${relations.mkString(",")})" } override def sig(config: QuerySignatureConfig): String = { val in = relations.map(_.sig(config)).mkString(",") s"U(${in})" } override def inputAttributes: Seq[Attribute] = relations.head.inputAttributes override def outputAttributes: Seq[Attribute] = relations.head.outputAttributes } case class Unnest(columns: Seq[Expression], withOrdinality: Boolean) extends Relation { override def children: Seq[LogicalPlan] = Seq.empty override def inputAttributes: Seq[Attribute] = Seq.empty // TODO override def outputAttributes: Seq[Attribute] = Seq.empty // TODO override def sig(config: QuerySignatureConfig): String = s"Un[${columns.length}]" } case class Lateral(query: Relation) extends UnaryRelation { override def child: Relation = query override def outputAttributes: Seq[Attribute] = query.outputAttributes // TODO override def sig(config: QuerySignatureConfig): String = s"Lt(${query.sig(config)})" } case class LateralView( child: Relation, exprs: Seq[Expression], tableAlias: Identifier, columnAliases: Seq[Identifier] ) extends UnaryRelation { override def outputAttributes: Seq[Attribute] = columnAliases.map(x => UnresolvedAttribute(x.value)) override def sig(config: QuerySignatureConfig): String = s"LV(${child.sig(config)})" } // DDL sealed trait DDL extends LogicalPlan with LeafPlan with SQLSig { override def outputAttributes: Seq[Attribute] = Seq.empty } case class CreateSchema(schema: QName, ifNotExists: Boolean, properties: Option[Seq[SchemaProperty]]) extends DDL { override def sig(config: QuerySignatureConfig) = "CS" } case class DropSchema(schema: QName, ifExists: Boolean, cascade: Boolean) extends DDL { override def sig(config: QuerySignatureConfig) = "DS" } case class RenameSchema(schema: QName, renameTo: Identifier) extends DDL { override def sig(config: QuerySignatureConfig) = "RS" } case class CreateTable(table: QName, ifNotExists: Boolean, tableElems: Seq[TableElement]) extends DDL { override def sig(config: QuerySignatureConfig): String = { s"CT(${TableRef(table).sig(config)})" } } case class CreateTableAs( table: QName, ifNotEotExists: Boolean, columnAliases: Option[Seq[Identifier]], query: Relation ) extends DDL { override def sig(config: QuerySignatureConfig) = s"CT(${TableRef(table).sig(config)},${query.sig(config)})" override def inputAttributes: Seq[Attribute] = query.inputAttributes override def outputAttributes: Seq[Attribute] = Nil } case class DropTable(table: QName, ifExists: Boolean) extends DDL { override def sig(config: QuerySignatureConfig): String = { s"DT(${TableRef(table).sig(config)})" } } trait Update extends LogicalPlan with SQLSig case class InsertInto(table: QName, columnAliases: Option[Seq[Identifier]], query: Relation) extends Update with UnaryRelation { override def child: Relation = query override def sig(config: QuerySignatureConfig): String = { s"I(${TableRef(table).sig(config)},${query.sig(config)})" } override def inputAttributes: Seq[Attribute] = query.inputAttributes override def outputAttributes: Seq[Attribute] = Nil } case class Delete(table: QName, where: Option[Expression]) extends Update with LeafPlan { override def sig(config: QuerySignatureConfig): String = { s"D(${TableRef(table).sig(config)})" } override def inputAttributes: Seq[Attribute] = Nil override def outputAttributes: Seq[Attribute] = Nil } case class RenameTable(table: QName, renameTo: QName) extends DDL { override def sig(config: QuerySignatureConfig): String = { s"RT(${TableRef(table).sig(config)})" } } case class RenameColumn(table: QName, column: Identifier, renameTo: Identifier) extends DDL { override def sig(config: QuerySignatureConfig) = "RC" } case class DropColumn(table: QName, column: Identifier) extends DDL { override def sig(config: QuerySignatureConfig) = "DC" } case class AddColumn(table: QName, column: ColumnDef) extends DDL { override def sig(config: QuerySignatureConfig) = "AC" } case class CreateView(viewName: QName, replace: Boolean, query: Relation) extends DDL { override def sig(config: QuerySignatureConfig) = "CV" } case class DropView(viewName: QName, ifExists: Boolean) extends DDL { override def sig(config: QuerySignatureConfig) = "DV" } }
wvlet/airframe
airframe-sql/src/main/scala/wvlet/airframe/sql/model/LogicalPlan.scala
Scala
apache-2.0
18,249
/* * Copyright (c) 2010 by Alexander Grünewald * * This file is part of gruenewa-grid, a grid computing runtime. * * gruenewa-grid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gruenewa.grid import gruenewa.prelude._ import gruenewa.streams._ import java.net.{ Socket, ServerSocket, SocketTimeoutException } import java.io.{InputStream, OutputStream} import scala.concurrent.ops.spawn object Server { def start(port: Int, handle: Socket => Unit): Closable = { @volatile var run = true val listener = new ServerSocket(port) listener.setSoTimeout(1000) spawn { while (run) { try { val connection = listener.accept() spawn { handle(connection) } } catch { case e: SocketTimeoutException => () } } listener.close() } new { def close() { run = false } } } } class ClassServerHandle(provider: String => Option[InputStream]) extends (Socket => Unit) { import java.io.{ BufferedReader, InputStreamReader } def apply(connection: Socket) { using(new BufferedReader(new InputStreamReader(connection.getInputStream()))) { in => using(connection.getOutputStream()) { out => try { val line = in.readLine if (line == null) { out.write("HTTP/1.0 404 Not found\r\n\r\n".getBytes) } else { val className = parseClassName(line) provider(className) match { case None => { out.write("HTTP/1.0 404 Not found\r\n\r\n".getBytes) } case Some(is) => using(is) { _ => out.write("HTTP/1.0 200 OK\r\n".getBytes) out.write("Content-Type: application/octet-stream\r\n\r\n".getBytes) transfer(is, out) } } } } } } } private def parseClassName(line: String) = { val startPos = line.indexOf("/") val endPos = line.indexOf(" ", startPos) line.substring(startPos + 1, endPos) } } class ComputationHandle extends (Socket => Unit) { import java.net.{ URL, URLClassLoader } import java.util.concurrent.Callable import java.io.{ InputStream => IS, DataInputStream => DIS, DataOutputStream => DOS, ObjectInputStream => OIS, ObjectOutputStream => OOS, ByteArrayInputStream => BIS, ObjectStreamClass } def getClassLoader(host: String, port: Int) = new URLClassLoader(Array(new URL("http://" + host + ":" + port + "/")), Thread.currentThread().getContextClassLoader) def apply(connection: Socket) { using(new OIS(connection.getInputStream())) { ois => using(new OOS(connection.getOutputStream())) { oos => val classLoaderPort = ois.readInt() val classLoaderHost = connection.getInetAddress.getHostName val executable = ois.readObject().asInstanceOf[Array[Byte]] val classloader = getClassLoader(classLoaderHost, classLoaderPort) using(new BIS(executable)) { bis => val task = load[Task[_,_]](bis, classloader) val result = task() oos.writeObject(result) oos.flush() } } } } def load[T](obj: IS, classloader: ClassLoader): T = { val oIn = new OIS(obj) { override def resolveClass(desc: ObjectStreamClass): Class[_] = { val className = desc.getName() val clazz = try { Class.forName(className) } catch { case e: ClassNotFoundException => { classloader.loadClass(className) } } clazz } } using(oIn){ _ => oIn.readObject().asInstanceOf[T] } } }
gruenewa/gruenewa-grid
src/main/scala/gruenewa/grid/Server.scala
Scala
gpl-3.0
4,317
package org.jetbrains.plugins.scala.failed.annotator import org.jetbrains.plugins.scala.PerfCycleTests import org.jetbrains.plugins.scala.annotator.OverridingAnnotatorTestBase import org.junit.experimental.categories.Category /** * Created by mucianm on 22.03.16. */ @Category(Array(classOf[PerfCycleTests])) class OverridingAnnotatorTest extends OverridingAnnotatorTestBase { //#SCL-8577 overriding of inaccessible members with qualified private must show an error def testInaccessiblePrivateMembers(): Unit = { assert( messages( """ |object FOO { |class A { | private[A] def foo = 1 |} | |class B extends A { | override def foo: Int = 2 |}} """.stripMargin ).nonEmpty) } def testSCL8228(): Unit = { assertNothing( messages( """ | trait TraitWithGeneric [T]{ | // If you click on the left on green down arrow, it does not list implementation from SelfTypeWildcard | def method: String | } | | trait SelfType { self: TraitWithGeneric[Unit] => | override def method = "no problem here" | } | | trait SelfTypeWildcard { self: TraitWithGeneric[_] => | // BUG: Triggers "Overrides nothing" inspection | override def method = "inspection problem here for selftype" | } | object ItActuallyCompilesAndWorks extends TraitWithGeneric[Unit] with SelfTypeWildcard | ItActuallyCompilesAndWorks.method // returns "inspection problem here for selftype" """.stripMargin) ) } def testSCL7987(): Unit = { assertNothing( messages( """ |trait Foo { | protected type T | def foo(t: T) |} | |new Foo { | override protected type T = String // will pass if protected modifier is removed | override def foo(t: T) = () |} """.stripMargin ) ) } def testScl9767(): Unit = { assertMatches( messages( """case class Q[B](b: B) | |trait Foo[A] { | def method(value: A): Unit | | def concat[T](that: Foo[T]): Foo[Q[A]] = new Foo[Q[A]] { | override def method(value: Q[A]): Unit = () | } |} """.stripMargin)) { case Nil => } } def testScl6809(): Unit = { assertMatches( messages( """import java.{util => ju} | |abstract class CollectionToArrayBug[E <: AnyRef](collection: ju.Collection[E]) | extends ju.Collection[E] |{ | def toArray[T](a: Array[T]): Array[T] = ??? | override def toArray[T](a: Array[T with AnyRef]): Array[T with AnyRef] = ??? |} """.stripMargin)) { case Nil => } } def testScl11327(): Unit = { assertMatches( messages( """import MyOverride._ | |class MyOverride(string: String) { | | def foo(): String = { | bar(string) | } |} | |object MyOverride extends SomeTrait { | def bar(string: String): String = string + "bar" | | override def baz(string: String): String = string.reverse + "baz" |} | |trait SomeTrait { | def baz(string: String): String |} """.stripMargin)) { case Nil => } } }
loskutov/intellij-scala
test/org/jetbrains/plugins/scala/failed/annotator/OverridingAnnotatorTest.scala
Scala
apache-2.0
3,604
/* * Copyright (c) 2012-2019 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.snowplowanalytics.snowplow.enrich.common package utils // Java import java.net.URI import java.net.URLDecoder import java.net.URLEncoder import java.lang.{Integer => JInteger} import java.math.{BigDecimal => JBigDecimal} import java.lang.{Byte => JByte} import java.util.UUID import java.nio.charset.StandardCharsets.UTF_8 // Scala import scala.collection.JavaConversions._ import scala.util.Try import scala.util.control.NonFatal // Apache HTTP import org.apache.http.client.utils.URLEncodedUtils // Apache Commons Codec import org.apache.commons.codec.binary.Base64 // Scalaz import scalaz._ import Scalaz._ // Scala URI import io.lemonlabs.uri.{Uri, Url} import io.lemonlabs.uri.config.UriConfig import io.lemonlabs.uri.decoding.PercentDecoder import io.lemonlabs.uri.encoding.percentEncode /** * General-purpose utils to help the * ETL process along. */ object ConversionUtils { private val UrlSafeBase64 = new Base64(true) // true means "url safe" /** * Simple case class wrapper around the * components of a URI. */ case class UriComponents( // Required scheme: String, host: String, port: JInteger, // Optional path: Option[String], query: Option[String], fragment: Option[String]) /** * Explodes a URI into its 6 components * pieces. Simple code but we use it * in multiple places * * @param uri The URI to explode into its * constituent pieces * * @return The 6 components in a UriComponents * case class */ def explodeUri(uri: URI): UriComponents = { val port = uri.getPort // TODO: should we be using decodeString below instead? // Trouble is we can't be sure of the querystring's encoding. val query = fixTabsNewlines(uri.getRawQuery) val path = fixTabsNewlines(uri.getRawPath) val fragment = fixTabsNewlines(uri.getRawFragment) UriComponents( scheme = uri.getScheme, host = uri.getHost, port = if (port == -1 && uri.getScheme == "https") { 443 } else if (port == -1) { 80 } else { port }, path = path, query = query, fragment = fragment ) } /** * Quick helper to make sure our Strings are TSV-safe, * i.e. don't include tabs, special characters, newlines * etc. * * @param str The string we want to make safe * @return a safe String */ def makeTsvSafe(str: String): String = fixTabsNewlines(str).orNull /** * Replaces tabs with four spaces and removes * newlines altogether. * * Useful to prepare user-created strings for * fragile storage formats like TSV. * * @param str The String to fix * @return The String with tabs and newlines fixed. */ def fixTabsNewlines(str: String): Option[String] = { val f = for { s <- Option(str) r = s.replaceAll("\\\\t", " ").replaceAll("\\\\p{Cntrl}", "") // Any other control character } yield r if (f == Some("")) None else f } /** * Decodes a URL-safe Base64 string. * * For details on the Base 64 Encoding with URL * and Filename Safe Alphabet see: * * http://tools.ietf.org/html/rfc4648#page-7 * * @param str The encoded string to be * decoded * @param field The name of the field * @return a Scalaz Validation, wrapping either an * an error String or the decoded String */ // TODO: probably better to change the functionality and signature // a little: // // 1. Signature -> : Validation[String, Option[String]] // 2. Functionality: // 1. If passed in null or "", return Success(None) // 2. If passed in a non-empty string but result == "", then return a Failure, because we have failed to decode something meaningful def decodeBase64Url(field: String, str: String): Validation[String, String] = try { val decodedBytes = UrlSafeBase64.decode(str) val result = new String(decodedBytes, UTF_8) // Must specify charset (EMR uses US_ASCII) result.success } catch { case NonFatal(e) => "Field [%s]: exception Base64-decoding [%s] (URL-safe encoding): [%s]".format(field, str, e.getMessage).fail } /** * Encodes a URL-safe Base64 string. * * For details on the Base 64 Encoding with URL * and Filename Safe Alphabet see: * * http://tools.ietf.org/html/rfc4648#page-7 * * @param str The string to be encoded * @return the string encoded in URL-safe Base64 */ def encodeBase64Url(str: String): String = { val bytes = UrlSafeBase64.encode(str.getBytes) new String(bytes, UTF_8).trim // Newline being appended by some Base64 versions } /** * Validates that the given field contains a valid UUID. * * @param field The name of the field being validated * @param str The String hopefully containing a UUID * @return a Scalaz ValidatedString containing either * the original String on Success, or an error * String on Failure. */ val validateUuid: (String, String) => ValidatedString = (field, str) => { def check(s: String)(u: UUID): Boolean = (u != null && s.toLowerCase == u.toString) val uuid = Try(UUID.fromString(str)).toOption.filter(check(str)) uuid match { case Some(_) => str.toLowerCase.success case None => s"Field [$field]: [$str] is not a valid UUID".fail } } /** * @param field The name of the field being validated * @param str The String hopefully parseable as an integer * @return a Scalaz ValidatedString containing either * the original String on Success, or an error * String on Failure. */ val validateInteger: (String, String) => ValidatedString = (field, str) => { try { str.toInt str.success } catch { case _: java.lang.NumberFormatException => s"Field [$field]: [$str] is not a valid integer".fail } } /** * Decodes a String in the specific encoding, * also removing: * * Newlines - because they will break Hive * * Tabs - because they will break non-Hive * targets (e.g. Infobright) * * IMPLDIFF: note that this version, unlike * the Hive serde version, does not call * cleanUri. This is because we cannot assume * that str is a URI which needs 'cleaning'. * * TODO: simplify this when we move to a more * robust output format (e.g. Avro) - as then * no need to remove line breaks, tabs etc * * @param enc The encoding of the String * @param field The name of the field * @param str The String to decode * * @return a Scalaz Validation, wrapping either * an error String or the decoded String */ val decodeString: (String, String, String) => ValidatedString = (enc, field, str) => try { // TODO: switch to style of fixTabsNewlines above // TODO: potentially switch to using fixTabsNewlines too to avoid duplication val s = Option(str).getOrElse("") val d = URLDecoder.decode(s, enc) val r = d.replaceAll("(\\\\r|\\\\n)", "").replaceAll("\\\\t", " ") r.success } catch { case NonFatal(e) => "Field [%s]: Exception URL-decoding [%s] (encoding [%s]): [%s]".format(field, str, enc, e.getMessage).fail } /** * On 17th August 2013, Amazon made an * unannounced change to their CloudFront * log format - they went from always encoding * % characters, to only encoding % characters * which were not previously encoded. For a * full discussion of this see: * * https://forums.aws.amazon.com/thread.jspa?threadID=134017&tstart=0# * * On 14th September 2013, Amazon rolled out a further fix, * from which point onwards all fields, including the * referer and useragent, would have %s double-encoded. * * This causes issues, because the ETL process expects * referers and useragents to be only single-encoded. * * This function turns a double-encoded percent (%) into * a single-encoded one. * * Examples: * 1. "page=Celestial%25Tarot" - no change (only single encoded) * 2. "page=Dreaming%2520Way%2520Tarot" -> "page=Dreaming%20Way%20Tarot" * 3. "loading 30%2525 complete" -> "loading 30%25 complete" * * Limitation of this approach: %2588 is ambiguous. Is it a: * a) A double-escaped caret "ˆ" (%2588 -> %88 -> ^), or: * b) A single-escaped "%88" (%2588 -> %88) * * This code assumes it's a). * * @param str The String which potentially has double-encoded %s * @return the String with %s now single-encoded */ def singleEncodePcts(str: String): String = str.replaceAll("%25([0-9a-fA-F][0-9a-fA-F])", "%$1") // Decode %25XX to %XX /** * Decode double-encoded percents, then percent decode * * @param field The name of the field * @param str The String to decode * * @return a Scalaz Validation, wrapping either * an error String or the decoded String */ def doubleDecode(field: String, str: String): ValidatedString = ConversionUtils.decodeString("UTF-8", field, singleEncodePcts(str)) /** * Encodes a string in the specified encoding * * @param enc The encoding to be used * @param str The string which needs to be URLEncoded * @return a URL encoded string */ def encodeString(enc: String, str: String): String = URLEncoder.encode(str, enc) /** * Parses a string to create a [[URI]]. * Parsing is relaxed, i.e. even if a URL is not correctly percent-encoded or not RFC 3986-compliant, it can be parsed. * * @param uri String containing the URI to parse. * @return [[Validation]] wrapping the result of the parsing: * - [[Success]] with the parsed URI if there was no error or with [[None]] if the input was `null`. * - [[Failure]] with the error message if something went wrong. */ def stringToUri(uri: String): Validation[String, Option[URI]] = Try( Option(uri) // to handle null .map(_.replaceAll(" ", "%20")) .map(URI.create) ) match { case util.Success(parsed) => parsed.success case util.Failure(javaErr) => implicit val c = UriConfig(decoder = PercentDecoder(ignoreInvalidPercentEncoding = true), encoder = percentEncode -- '+') Uri .parseTry(uri) .map(_.toJavaURI) match { case util.Success(javaURI) => Some(javaURI).success case util.Failure(scalaErr) => "Provided URI [%s] could not be parsed, neither by Java parsing (error: [%s]) nor by Scala parsing (error: [%s])." .format(uri, javaErr.getMessage, scalaErr.getMessage) .failure } } /** * Attempt to extract the querystring from a URI as a map * * @param uri URI containing the querystring * @param encoding Encoding of the URI */ def extractQuerystring(uri: URI, encoding: String): Validation[String, Map[String, String]] = Try(URLEncodedUtils.parse(uri, encoding).map(p => (p.getName -> p.getValue))).recoverWith { case NonFatal(_) => Try(Url.parse(uri.toString).query.params).map(l => l.map(t => (t._1, t._2.getOrElse("")))) } match { case util.Success(s) => s.toMap.success case util.Failure(e) => s"Could not parse uri [$uri]. Uri parsing threw exception: [$e].".fail } /** * Extract a Scala Int from * a String, or error. * * @param str The String * which we hope is an * Int * @param field The name of the * field we are trying to * process. To use in our * error message * @return a Scalaz Validation, * being either a * Failure String or * a Success JInt */ val stringToJInteger: (String, String) => Validation[String, JInteger] = (field, str) => if (Option(str).isEmpty) { null.asInstanceOf[JInteger].success } else { try { val jint: JInteger = str.toInt jint.success } catch { case nfe: NumberFormatException => "Field [%s]: cannot convert [%s] to Int".format(field, str).fail } } /** * Convert a String to a String containing a * Redshift-compatible Double. * * Necessary because Redshift does not support all * Java Double syntaxes e.g. "3.4028235E38" * * Note that this code does NOT check that the * value will fit within a Redshift Double - * meaning Redshift may silently round this number * on load. * * @param str The String which we hope contains * a Double * @param field The name of the field we are * validating. To use in our error message * @return a Scalaz Validation, being either * a Failure String or a Success String */ val stringToDoublelike: (String, String) => ValidatedString = (field, str) => try { if (Option(str).isEmpty || str == "null") { // "null" String check is LEGACY to handle a bug in the JavaScript tracker null.asInstanceOf[String].success } else { val jbigdec = new JBigDecimal(str) jbigdec.toPlainString.success // Strip scientific notation } } catch { case nfe: NumberFormatException => "Field [%s]: cannot convert [%s] to Double-like String".format(field, str).fail } /** * Convert a String to a Double * * @param str The String which we hope contains * a Double * @param field The name of the field we are * validating. To use in our error message * @return a Scalaz Validation, being either * a Failure String or a Success Double */ def stringToMaybeDouble(field: String, str: String): Validation[String, Option[Double]] = try { if (Option(str).isEmpty || str == "null") { // "null" String check is LEGACY to handle a bug in the JavaScript tracker None.success } else { val jbigdec = new JBigDecimal(str) jbigdec.doubleValue().some.success } } catch { case nfe: NumberFormatException => "Field [%s]: cannot convert [%s] to Double-like String".format(field, str).fail } /** * Converts a String to a Double with two decimal places. Used to honor schemas with * multipleOf 0.01. * Takes a field name and a string value and return a validated double. */ val stringToTwoDecimals: (String, String) => Validation[String, Double] = (field, str) => try { BigDecimal(str).setScale(2, BigDecimal.RoundingMode.HALF_EVEN).toDouble.success } catch { case nfe: NumberFormatException => "Field [%s]: cannot convert [%s] to Double".format(field, str).fail } /** * Converts a String to a Double. * Takes a field name and a string value and return a validated float. */ val stringToDouble: (String, String) => Validation[String, Double] = (field, str) => try { BigDecimal(str).toDouble.success } catch { case nfe: NumberFormatException => "Field [%s]: cannot convert [%s] to Double".format(field, str).fail } /** * Extract a Java Byte representing * 1 or 0 only from a String, or error. * * @param str The String * which we hope is an * Byte * @param field The name of the * field we are trying to * process. To use in our * error message * @return a Scalaz Validation, * being either a * Failure String or * a Success Byte */ val stringToBooleanlikeJByte: (String, String) => Validation[String, JByte] = (field, str) => str match { case "1" => (1.toByte: JByte).success case "0" => (0.toByte: JByte).success case _ => "Field [%s]: cannot convert [%s] to Boolean-like JByte".format(field, str).fail } /** * Converts a String of value "1" or "0" * to true or false respectively. * * @param str The String to convert * @return True for "1", false for "0", or * an error message for any other * value, all boxed in a Scalaz * Validation */ val stringToBoolean: (String, String) => Validation[String, Boolean] = (field, str) => if (str == "1") { true.success } else if (str == "0") { false.success } else { "Field [%s]: Cannot convert [%s] to boolean, only 1 or 0.".format(field, str).fail } /** * Truncates a String - useful for making sure * Strings can't overflow a database field. * * @param str The String to truncate * @param length The maximum length of the String * to keep * @return the truncated String */ def truncate(str: String, length: Int): String = if (str == null) { null } else { str.take(length) } /** * Helper to convert a Boolean value to a Byte. * Does not require any validation. * * @param bool The Boolean to convert into a Byte * @return 0 if false, 1 if true */ def booleanToJByte(bool: Boolean): JByte = (if (bool) 1 else 0).toByte /** * Helper to convert a Byte value * (1 or 0) into a Boolean. * * @param b The Byte to turn * into a Boolean * @return the Boolean value of b, or * an error message if b is * not 0 or 1 - all boxed in a * Scalaz Validation */ def byteToBoolean(b: Byte): Validation[String, Boolean] = if (b == 0) false.success else if (b == 1) true.success else "Cannot convert byte [%s] to boolean, only 1 or 0.".format(b).fail }
RetentionGrid/snowplow
3-enrich/scala-common-enrich/src/main/scala/com.snowplowanalytics.snowplow.enrich/common/utils/ConversionUtils.scala
Scala
apache-2.0
18,462
package com.verizon.trapezium.api.akkahttp.utils import com.typesafe.config.ConfigFactory /** * Created by chundch on 4/25/17. */ object HttpServicesConstants { lazy val REQUEST_SIZE_LIMIT = 100 * 1024 * 1024 lazy val LIVE_STATUS_MSG = "Live!" lazy val HTTPS_PROTOCAL = "https://" lazy val HTTP_PROTOCOL = "http://" lazy val AUTHORIZATION_URL_KEY = "HTTP_AUTHORIZATION_REQ_URL" val APP_CONFIGURATION = ConfigFactory.load() val HTTP_SERVICES_BINDING_PORT = APP_CONFIGURATION.getInt( "apisvcs.akka.http.port") lazy val UNAUTHORIZED_ERROR_MSG = APP_CONFIGURATION.getString( "apisvcs.unauthorized.request.message") lazy val PAGE_NOT_FOUND_ERROR_MSG = APP_CONFIGURATION.getString( "apisvcs.unauthorized.request.message") lazy val VZ_DATE_HEADER_KEY = "x-vz-date" lazy val VZ_AUTHORIZATION_HEADER_KEY = "Authorization" lazy val FAILED_REQUEST_ERROR_MSG = APP_CONFIGURATION.getString( "apisvcs.failed.request.message") lazy val NO_VALID_AUTHORIZER_ERROR_MSG = APP_CONFIGURATION.getString( "apisvcs.failed.noauthorizer.message") lazy val FEDERATED_AUTHORIZER_CONFIG = "Federated" lazy val WSO2_AUTHORIZATION_DATA_KEY = "X-JWT-Assertion" lazy val WSO2_AUTHORIZATION_PROVIDER = "wso2" lazy val COUCHBASE_AUTHORIZATION_PROVIDER = "couchbase" }
Verizon/trapezium
api-akkahttp/src/main/scala/com/verizon/trapezium/api/akkahttp/utils/HttpServicesConstants.scala
Scala
apache-2.0
1,320
package genericFunctionRDD.impl import genericFunctionRDD.SpatialRDDPartition import org.apache.spark.Logging import com.newbrightidea.util.RTree import scala.collection.mutable.ArrayBuffer import scala.reflect.ClassTag /** * Created by merlin on 2/9/16. */ class RtreePartition [K, V] (protected val tree: RTree[V]) ( override implicit val kTag: ClassTag[K], override implicit val vTag: ClassTag[V] ) extends SpatialRDDPartition[K,V] with Logging{ override def size: Long = tree.size() override def isDefined(k: K): Boolean = tree==null /** * range search and find points inside the box, and each element meet the condition, and return a iterator, * and this iterator can be used for other RDD */ override def topMin(k: Int,f: (K, V) => Double): Iterator[(K, V)] = ??? /** * range search and find points inside the box, and each element meet the condition, and return a iterator, * and this iterator can be used for other RDD */ override def rangefilter(begin: Double, end: Double,f: (K, V) => Double): Iterator[(K, V)] = ??? override def iterator: Iterator[(K, V)] = { val nodes=this.tree.iterators() val buffer=new ArrayBuffer[(K,V)]() for(i <- 0 to nodes.size()) { val n=nodes.get(i) buffer.+=((n.getCorrd.asInstanceOf[K],n.getEntry)) } buffer.toIterator } /** * range search and find points inside the box, and each element meet the condition, and return a iterator, * and this iterator can be used for other RDD */ override def topMax(k: Int,f: (K, V) => Double): Iterator[(K, V)] = ??? /** * * @param UDF * @param DERUDF * @return */ def getSmallest(UDF:String, DERUDF:Array[String]):Float= { this.tree.getSmallest(UDF,DERUDF) } } private[genericFunctionRDD] object RtreePartition { def apply[K: ClassTag, V: ClassTag] (iter: Iterator[(K, V)]) = apply[K, V, V](iter, (id, a) => a, (id, a, b) => b) def apply[K: ClassTag, U: ClassTag, V: ClassTag] (iter: Iterator[(K, V)], z: (K, U) => V, f: (K, V, U) => V) : SpatialRDDPartition[K, V] = { val numDimensions: Int = Util.input_data_dimensions val minNum: Int = Util.localrtree_min_number val maxNum: Int = Util.localrtree_max_number val rt: RTree[V] = new RTree[V](minNum, maxNum, numDimensions, RTree.SeedPicker.QUADRATIC) iter.foreach { case (k,v)=> k match { case coords: Array[Float]=> rt.insert(coords,v) } } new RtreePartition(rt) } }
merlintang/genericFunctionOverSpark
src/main/scala/genericFunctionRDD/impl/RtreePartition.scala
Scala
apache-2.0
2,542
package server import java.io._ import java.net._ /** * Represents a user, as viewed from the server. Users should be unique by username. * A user is only authenticated by socket connection while online, and once offline * the user no longer exists. */ class User(userSocket: Socket, val username: String, inFromClient: BufferedReader, outToClient: DataOutputStream) { Main.users.add(this) private var online = true //private val inFromClient = new BufferedReader(new InputStreamReader(userSocket.getInputStream())) //private val outToClient = new DataOutputStream(userSocket.getOutputStream()) /** * Block on recieving a message (as line) from user. */ def receiveLine(): Option[String] = { var result: Option[String] = None if (online) { try { result = Some(inFromClient.readLine()) } catch { case _: Throwable => { online = false } } } result } /** * This is the principal method for sending a message back to * the user. The standard form of such message is: * < sender:::timestamp:::msg > */ def send(msg: String): Unit = { if (online) { try { outToClient.writeBytes(msg + "\\n") } catch { case _: Throwable => { online = false } } } } //def ping() = {} /** * Find out if the user is currently considered online by the server. */ def isOnline = online /** * Disconnect the user from the server. */ def disconnect() = { Main.users.remove(this) send(Main.constructSystemMessage("You have been disconnected.")) userSocket.close() online = false } } /** * A constructor object for class User. NB! Its apply method returns a user wrapped * in an option, only defined if construction was successful. */ object User { /** * Constructs a User, wrapped in an option, from the given user socket. * A valid user is constructed if and only if a correct connection message * is received. This message is of the form: * < code:::username:::parameters > * and is only valid if the code is correct and the username is not already * taken. */ def apply(userSocket: Socket): Option[User] = { val inFromClient = new BufferedReader(new InputStreamReader(userSocket.getInputStream(), "UTF-8")) val outToClient = new DataOutputStream(userSocket.getOutputStream()) try { val connectionMessage = inFromClient.readLine() val messageComponents = connectionMessage.split(":::").map(_.trim) if (messageComponents.length < 2) { //Invalid message return None } else if (!Main.MESSAGECODES.contains(messageComponents(0))) { //Invalid version outToClient.writeBytes("Invalid message code. The client version might need to be updated.\\n") return None } else { val username = messageComponents(1) if (Main.users.find(_.username == username).isDefined) { outToClient.writeBytes("Username already in use.\\n") return None } else { outToClient.writeBytes(":::001\\n") //Connected successfully. return Some(new User(userSocket, username, inFromClient, outToClient)) } } None } catch { case _: Throwable => { return None } } } }
Berthur/Chat
src/server/User.scala
Scala
gpl-3.0
3,361
package com.github.mdr.mash.ns.collections import com.github.mdr.mash.functions.{ BoundParams, MashFunction, Parameter, ParameterModel } import com.github.mdr.mash.runtime.MashList object ChunkedFunction extends MashFunction("collections.chunked") { object Params { val Size = Parameter( nameOpt = Some("size"), summaryOpt = Some("Number of elements in each chunk")) val Sequence = Parameter( nameOpt = Some("sequence"), summaryOpt = Some("Sequence to split into chunks")) } import Params._ val params = ParameterModel(Size, Sequence) def call(boundParams: BoundParams): MashList = { val n = boundParams.validateInteger(Size) if (n <= 0) boundParams.throwInvalidArgument(Size, "size must be positive") val inSequence = boundParams(Sequence) val sequence = boundParams.validateSequence(Sequence) MashList(sequence.grouped(n).toList.map(xs ⇒ WhereFunction.reassembleSequence(inSequence, xs))) } override def typeInferenceStrategy = SlidingTypeInferenceStrategy override def summaryOpt = Some("Split a sequence up into chunks of a given size") override def descriptionOpt = Some("""Returns a list of chunks (sequences of elements of the given size). Any elements left over will be placed into a final chunk. Examples: <mash> chunked 2 [1, 2, 3, 4, 5] # [[1, 2], [3, 4], [5]] </mash>""") }
mdr/mash
src/main/scala/com/github/mdr/mash/ns/collections/ChunkedFunction.scala
Scala
mit
1,375
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.flink.table.sources.tsextractors import org.apache.flink.api.common.typeinfo.{SqlTimeTypeInfo, TypeInformation} import org.apache.flink.table.api.{Types, ValidationException} import org.apache.flink.table.expressions.{Cast, Expression, PlannerExpression, ResolvedFieldReference} /** * Converts an existing [[Long]], [[java.sql.Timestamp]], or * timestamp formatted [[java.lang.String]] field (e.g., "2018-05-28 12:34:56.000") into * a rowtime attribute. * * @param field The field to convert into a rowtime attribute. */ final class ExistingField(val field: String) extends TimestampExtractor { override def getArgumentFields: Array[String] = Array(field) @throws[ValidationException] override def validateArgumentFields(argumentFieldTypes: Array[TypeInformation[_]]): Unit = { val fieldType = argumentFieldTypes(0) fieldType match { case Types.LONG => // OK case Types.SQL_TIMESTAMP => // OK case Types.STRING => // OK case _: TypeInformation[_] => throw new ValidationException( s"Field '$field' must be of type Long or Timestamp or String but is of type $fieldType.") } } /** * Returns an [[Expression]] that casts a [[Long]], [[java.sql.Timestamp]], or * timestamp formatted [[java.lang.String]] field (e.g., "2018-05-28 12:34:56.000") * into a rowtime attribute. */ override def getExpression(fieldAccesses: Array[ResolvedFieldReference]): PlannerExpression = { val fieldAccess: PlannerExpression = fieldAccesses(0) fieldAccess.resultType match { case Types.LONG => // access LONG field fieldAccess case Types.SQL_TIMESTAMP => // cast timestamp to long Cast(fieldAccess, Types.LONG) case Types.STRING => Cast(Cast(fieldAccess, SqlTimeTypeInfo.TIMESTAMP), Types.LONG) } } override def equals(other: Any): Boolean = other match { case that: ExistingField => field == that.field case _ => false } override def hashCode(): Int = { field.hashCode } }
ueshin/apache-flink
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/sources/tsextractors/ExistingField.scala
Scala
apache-2.0
2,872
/** * Copyright (C) 2011 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.xforms.processor.handlers.xhtml import org.orbeon.oxf.externalcontext.URLRewriter._ import org.orbeon.oxf.util.URLRewriterUtils import org.orbeon.oxf.xforms._ import org.orbeon.oxf.xforms.processor.ScriptBuilder._ import org.orbeon.oxf.xforms.XFormsAssetPaths import org.orbeon.oxf.xforms.processor.handlers.{HandlerContext, XHTMLOutput} import org.orbeon.oxf.xforms.state.XFormsStateManager import org.orbeon.oxf.xforms.xbl.XBLAssetsSupport import org.orbeon.oxf.xml.XMLConstants.XHTML_NAMESPACE_URI import org.orbeon.oxf.xml.XMLReceiverSupport._ import org.orbeon.oxf.xml._ import org.orbeon.xforms.HeadElement import org.xml.sax.Attributes // Handler for `<xh:head>` class XHTMLHeadHandler( uri : String, localname : String, qName : String, localAtts : Attributes, handlerContext : HandlerContext ) extends XFormsBaseHandlerXHTML( uri, localname, qName, localAtts, handlerContext, repeating = false, forwarding = true ) { import XHTMLHeadHandler._ private var formattingPrefix: String = null override def start(): Unit = { implicit val xmlReceiver: XMLReceiver = handlerContext.controller.output handlerContext.controller.combinePf(XHTMLOutput.headPf) // Declare `xmlns:f` formattingPrefix = handlerContext.findFormattingPrefixDeclare // Open head element xmlReceiver.startElement(uri, localname, qName, attributes) val xhtmlPrefix = XMLUtils.prefixFromQName(qName) // Create prefix for combined resources if needed val isMinimal = XFormsGlobalProperties.isMinimalResources val isVersionedResources = URLRewriterUtils.isResourcesVersioned // Include static XForms CSS and JS val externalContext = handlerContext.externalContext if (containingDocument.isServeInlineResources) withElement("style", xhtmlPrefix, XHTML_NAMESPACE_URI, List("type" -> "text/css", "media" -> "all")) { text( """html body form.xforms-initially-hidden, html body .xforms-form .xforms-initially-hidden { display: none }""" ) } val ops = containingDocument.staticOps val (baselineScripts, baselineStyles) = ops.baselineResources val (scripts, styles) = ops.bindingResources // Stylesheets outputCSSResources(xhtmlPrefix, isMinimal, containingDocument.staticState.assets, styles, baselineStyles) // Scripts locally { // Linked JavaScript resources outputJavaScriptResources(xhtmlPrefix, isMinimal, containingDocument.staticState.assets, scripts, baselineScripts) if (! containingDocument.isServeInlineResources) { // Static resources if (containingDocument.staticOps.uniqueJsScripts.nonEmpty) element( localName = "script", prefix = xhtmlPrefix, uri = XHTML_NAMESPACE_URI, atts = ("src" -> (XFormsAssetPaths.FormStaticResourcesPath + containingDocument.staticState.digest + ".js") :: StandaloneScriptBaseAtts) ) // Dynamic resources element( localName = "script", prefix = xhtmlPrefix, uri = XHTML_NAMESPACE_URI, atts = ("src" -> (XFormsAssetPaths.FormDynamicResourcesPath + containingDocument.uuid + ".js") :: StandaloneScriptBaseAtts) ) } else { def writeContent(content: String): Unit = withElement("script", xhtmlPrefix, XHTML_NAMESPACE_URI, List("type" -> "text/javascript")) { text(escapeJavaScriptInsideScript(content)) } // Scripts known statically val uniqueClientScripts = containingDocument.staticOps.uniqueJsScripts if (uniqueClientScripts.nonEmpty) { val sb = new StringBuilder writeScripts(uniqueClientScripts, sb append _) writeContent(sb.toString) } // Scripts known dynamically findConfigurationProperties( containingDocument = containingDocument, versionedResources = isVersionedResources, heartbeatDelay = XFormsStateManager.getHeartbeatDelay(containingDocument, handlerContext.externalContext) ) foreach writeContent findOtherScriptInvocations(containingDocument) foreach writeContent List( buildJavaScriptInitialData( containingDocument = containingDocument, rewriteResource = externalContext.getResponse.rewriteResourceURL(_: String, REWRITE_MODE_ABSOLUTE_PATH_OR_RELATIVE), controlsToInitialize = containingDocument.controls.getCurrentControlTree.rootOpt map (gatherJavaScriptInitializations(_, includeValue = true)) getOrElse Nil ) ) foreach writeContent } } } override def end(): Unit = { val xmlReceiver = handlerContext.controller.output xmlReceiver.endElement(uri, localname, qName) handlerContext.findFormattingPrefixUndeclare(formattingPrefix) } } private object XHTMLHeadHandler { val ScriptBaseAtts = List( "type" -> "text/javascript" ) val StandaloneScriptBaseAtts = List( "type" -> "text/javascript", "class" -> "xforms-standalone-resource", "defer" -> "defer" ) val StyleBaseAtts = List( "type" -> "text/css", "media" -> "all" ) val LinkBaseAtts = List( "rel" -> "stylesheet", "type" -> "text/css", "media" -> "all" ) def valueOptToList(name: String, value: Option[String]): List[(String, String)] = value.toList map (name -> _) def outputJavaScriptResources( xhtmlPrefix : String, minimal : Boolean, assets : XFormsAssets, headElements : List[HeadElement], baselineResources : List[String])(implicit receiver : XMLReceiver ): Unit = { def outputScriptElement(resource: Option[String], cssClass: Option[String], content: Option[String]): Unit = withElement( localName = "script", prefix = xhtmlPrefix, uri = XHTML_NAMESPACE_URI, atts = ScriptBaseAtts ::: valueOptToList("src", resource) ::: valueOptToList("class", cssClass) ) { content foreach text } XBLAssetsSupport.outputResources( outputElement = outputScriptElement, builtin = assets.js, headElements = headElements, xblBaseline = baselineResources, minimal = minimal ) } def outputCSSResources( xhtmlPrefix : String, minimal : Boolean, assets : XFormsAssets, headElements : List[HeadElement], baselineResources : List[String])(implicit receiver : XMLReceiver ): Unit = { def outputLinkOrStyleElement(resource: Option[String], cssClass: Option[String], content: Option[String]): Unit = withElement( localName = resource match { case Some(_) => "link" case None => "style" }, prefix = xhtmlPrefix, uri = XHTML_NAMESPACE_URI, atts = (resource match { case Some(resource) => ("href" -> resource) :: LinkBaseAtts case None => StyleBaseAtts }) ::: valueOptToList("class", cssClass) ) { content foreach text } XBLAssetsSupport.outputResources( outputElement = outputLinkOrStyleElement, builtin = assets.css, headElements = headElements, xblBaseline = baselineResources, minimal = minimal ) } }
orbeon/orbeon-forms
xforms-runtime/shared/src/main/scala/org/orbeon/oxf/xforms/processor/handlers/xhtml/XHTMLHeadHandler.scala
Scala
lgpl-2.1
8,291
package cz.jenda.pidifrky.data.dao import cz.jenda.pidifrky.data.pojo.{Card, Merchant} import cz.jenda.pidifrky.data.{CardsTable, MerchantsTable} /** * @author Jenda Kolena, [email protected] */ sealed trait InsertCommand { def query: String def args: Array[AnyRef] } case class CardInsertCommand(card: Card) extends InsertCommand { import card._ override def query: String = s"insert into ${CardsTable.NAME} values (?, ?, ?, ?, ?, ?, ?, ?, ?)" private val (lat, lon) = location.map(l => (l.getLatitude.toString, l.getLongitude.toString)).getOrElse(("", "")) override def args: Array[AnyRef] = Array(id.toString, number.toString, name, nameRaw, (if (hasImage) 1 else 0).toString, lat, lon, merchantsIds.mkString(","), neighboursIds.map(_.getOrElse(0)).mkString(",")) } case class MerchantInsertCommand(merchant: Merchant) extends InsertCommand { import merchant._ override def query: String = s"insert into ${MerchantsTable.NAME} values (?, ?, ?, ?, ?, ?, ?, ?)" private val (lat, lon) = location.map(l => (l.getLatitude.toString, l.getLongitude.toString)).getOrElse(("", "")) override def args: Array[AnyRef] = Array(id.toString, name, nameRaw, address, lat, lon, (if (merchantLocation.precise) 1 else 0).toString, cardsIds.mkString(",")) } case class CardToMerchantsLinkUpdateCommand(cardId: Int, merchants: Seq[Int]) extends InsertCommand { override def query: String = s"update ${CardsTable.NAME} set ${CardsTable.COL_MERCHANTS_IDS} = ? where id = ?" override def args: Array[AnyRef] = Array(merchants.mkString(","), cardId.toString) } case class MerchantToCardsLinkUpdateCommand(merchantId: Int, cards: Seq[Int]) extends InsertCommand { override def query: String = s"update ${MerchantsTable.NAME} set ${MerchantsTable.COL_CARDS_IDS} = ? where id = ?" override def args: Array[AnyRef] = Array(cards.mkString(","), merchantId.toString) }
jendakol/pidifrky
client/src/main/scala/cz/jenda/pidifrky/data/dao/insertcommands.scala
Scala
apache-2.0
1,901
package fr.acinq.bitcoin import fr.acinq.bitcoin.Crypto._ import scodec.bits.ByteVector import java.io.{ByteArrayInputStream, ByteArrayOutputStream, InputStream, OutputStream} import scala.annotation.tailrec import scala.collection.mutable.ArrayBuffer /** * script execution flags */ object ScriptFlags { val SCRIPT_VERIFY_NONE = 0 // Evaluate P2SH subscripts (softfork safe, BIP16). val SCRIPT_VERIFY_P2SH = 1 << 0 // Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure. // Evaluating a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) by checksig causes script failure. // (softfork safe, but not used or intended as a consensus rule). val SCRIPT_VERIFY_STRICTENC = 1 << 1 // Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP62 rule 1) val SCRIPT_VERIFY_DERSIG = 1 << 2 // Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure // (softfork safe, BIP62 rule 5). val SCRIPT_VERIFY_LOW_S = 1 << 3 // verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7). val SCRIPT_VERIFY_NULLDUMMY = 1 << 4 // Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2). val SCRIPT_VERIFY_SIGPUSHONLY = 1 << 5 // Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct // pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating // any other push causes the script to fail (BIP62 rule 3). // In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4). // (softfork safe) val SCRIPT_VERIFY_MINIMALDATA = 1 << 6 // Discourage use of NOPs reserved for upgrades (NOP1-10) // // Provided so that nodes can avoid accepting or mining transactions // containing executed NOP's whose meaning may change after a soft-fork, // thus rendering the script invalid; with this flag set executing // discouraged NOPs fails the script. This verification flag will never be // a mandatory flag applied to scripts in a block. NOPs that are not // executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected. val SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = 1 << 7 // Require that only a single stack element remains after evaluation. This changes the success criterion from // "At least one stack element must remain, and when interpreted as a boolean, it must be true" to // "Exactly one stack element must remain, and when interpreted as a boolean, it must be true". // (softfork safe, BIP62 rule 6) // Note: CLEANSTACK should never be used without P2SH. val SCRIPT_VERIFY_CLEANSTACK = 1 << 8 // Verify CHECKLOCKTIMEVERIFY // // See BIP65 for details. val SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = 1 << 9 // See BIP112 for details val SCRIPT_VERIFY_CHECKSEQUENCEVERIFY = 1 << 10 // support CHECKSEQUENCEVERIFY opcode // // Support segregated witness // val SCRIPT_VERIFY_WITNESS = 1 << 11 // Making v2-v16 witness program non-standard // val SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM = 1 << 12 // Segwit script only: Require the argument of OP_IF/NOTIF to be exactly 0x01 or empty vector // val SCRIPT_VERIFY_MINIMALIF = 1 << 13 // Signature(s) must be empty vector if an CHECK(MULTI)SIG operation failed // val SCRIPT_VERIFY_NULLFAIL = 1 << 14 // Public keys in segregated witness scripts must be compressed // val SCRIPT_VERIFY_WITNESS_PUBKEYTYPE = 1 << 15 // Making OP_CODESEPARATOR and FindAndDelete fail any non-segwit scripts // val SCRIPT_VERIFY_CONST_SCRIPTCODE = 1 << 16 /** * Mandatory script verification flags that all new blocks must comply with for * them to be valid. (but old blocks may not comply with) Currently just P2SH, * but in the future other flags may be added, such as a soft-fork to enforce * strict DER encoding. * * Failing one of these tests may trigger a DoS ban - see CheckInputs() for * details. */ val MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH /** * Standard script verification flags that standard transactions will comply * with. However scripts violating these flags may still be present in valid * blocks and we must accept those blocks. */ val STANDARD_SCRIPT_VERIFY_FLAGS = MANDATORY_SCRIPT_VERIFY_FLAGS | SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_STRICTENC | SCRIPT_VERIFY_MINIMALDATA | SCRIPT_VERIFY_NULLDUMMY | SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS | SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_MINIMALIF | SCRIPT_VERIFY_NULLFAIL | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY | SCRIPT_VERIFY_CHECKSEQUENCEVERIFY | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE | SCRIPT_VERIFY_CONST_SCRIPTCODE /** For convenience, standard but not mandatory verify flags. */ val STANDARD_NOT_MANDATORY_VERIFY_FLAGS = STANDARD_SCRIPT_VERIFY_FLAGS & ~MANDATORY_SCRIPT_VERIFY_FLAGS } object Script { import Protocol._ import ScriptFlags._ import fr.acinq.bitcoin.ScriptElt._ type Stack = List[ByteVector] private val True = ByteVector.fromByte(1) private val False = ByteVector.empty /** * parse a script from a input stream of binary data * * @param input input stream * @param stack initial command stack * @return an updated command stack */ @tailrec def parse(input: InputStream, stack: collection.immutable.Vector[ScriptElt] = Vector.empty[ScriptElt]): List[ScriptElt] = { val code = input.read() code match { case -1 => stack.toList case 0 => parse(input, stack :+ OP_0) case opCode if opCode > 0 && opCode < 0x4c => parse(input, stack :+ OP_PUSHDATA(bytes(input, opCode), opCode)) case 0x4c => parse(input, stack :+ OP_PUSHDATA(bytes(input, uint8(input)), 0x4c)) case 0x4d => parse(input, stack :+ OP_PUSHDATA(bytes(input, uint16(input)), 0x4d)) case 0x4e => parse(input, stack :+ OP_PUSHDATA(bytes(input, uint32(input)), 0x4e)) case opCode if code2elt.contains(opCode) => parse(input, stack :+ code2elt(opCode)) case opCode => parse(input, stack :+ OP_INVALID(opCode)) // unknown/invalid ops can be parsed but not executed } } def parse(blob: ByteVector): List[ScriptElt] = if (blob.length > 10000) throw new RuntimeException("script is too large") else parse(new ByteArrayInputStream(blob.toArray)) def parse(blob: Array[Byte]): List[ScriptElt] = parse(ByteVector.view(blob)) @tailrec def write(script: Seq[ScriptElt], out: OutputStream): Unit = script match { case Nil => () case OP_PUSHDATA(data, length) :: tail if data.length < 0x4c && data.length == length => out.write(data.length.toInt); out.write(data.toArray); write(tail, out) case OP_PUSHDATA(data, 0x4c) :: tail if data.length < 0xff => writeUInt8(0x4c, out); writeUInt8(data.length.toInt, out); out.write(data.toArray); write(tail, out) case OP_PUSHDATA(data, 0x4d) :: tail if data.length < 0xffff => writeUInt8(0x4d, out); writeUInt16(data.length.toInt, out); out.write(data.toArray); write(tail, out) case OP_PUSHDATA(data, 0x4e) :: tail if data.length < 0xffffffff => writeUInt8(0x4e, out); writeUInt32(data.length, out); out.write(data.toArray); write(tail, out) case op@OP_PUSHDATA(_, _) :: _ => throw new RuntimeException(s"invalid element $op") case head :: tail => out.write(elt2code(head)); write(tail, out) } def write(script: Seq[ScriptElt]): ByteVector = { val out = new ByteArrayOutputStream() write(script, out) ByteVector.view(out.toByteArray) } def isUpgradableNop(op: ScriptElt) = op match { case OP_NOP1 | OP_NOP4 | OP_NOP5 | OP_NOP6 | OP_NOP7 | OP_NOP8 | OP_NOP9 | OP_NOP10 => true case _ => false } def isSimpleValue(op: ScriptElt) = op match { case OP_1NEGATE | OP_0 | OP_1 | OP_2 | OP_3 | OP_4 | OP_5 | OP_6 | OP_7 | OP_8 | OP_9 | OP_10 | OP_11 | OP_12 | OP_13 | OP_14 | OP_15 | OP_16 => true case _ => false } def simpleValue(op: ScriptElt): Byte = { require(isSimpleValue(op)) if (op == OP_0) 0 else (elt2code(op) - 0x50).toByte } def isDisabled(op: ScriptElt) = op match { case OP_CAT | OP_SUBSTR | OP_LEFT | OP_RIGHT | OP_INVERT | OP_AND | OP_OR | OP_XOR | OP_2MUL | OP_2DIV | OP_MUL | OP_DIV | OP_MOD | OP_LSHIFT | OP_RSHIFT => true case _ => false } def cost(op: ScriptElt): Int = op match { case _ if isSimpleValue(op) => 0 case OP_PUSHDATA(_, _) => 0 case OP_RESERVED => 0 case _ => 1 } def encodeNumber(value: Long): ByteVector = { if (value == 0) ByteVector.empty else { val result = ArrayBuffer.empty[Byte] val neg = value < 0 var absvalue = if (neg) -value else value while (absvalue > 0) { result += (absvalue & 0xff).toByte absvalue >>= 8 } // - If the most significant byte is >= 0x80 and the value is positive, push a // new zero-byte to make the significant byte < 0x80 again. // - If the most significant byte is >= 0x80 and the value is negative, push a // new 0x80 byte that will be popped off when converting to an integral. // - If the most significant byte is < 0x80 and the value is negative, add // 0x80 to it, since it will be subtracted and interpreted as a negative when // converting to an integral. if ((result.last & 0x80) != 0) { result += { if (neg) 0x80.toByte else 0 } } else if (neg) { result(result.length - 1) = (result(result.length - 1) | 0x80).toByte } ByteVector.view(result.toArray) } } def decodeNumber(input: ByteVector, checkMinimalEncoding: Boolean, maximumSize: Int = 4): Long = { if (input.isEmpty) 0 else if (input.length > maximumSize) throw new RuntimeException(s"number cannot be encoded on more than $maximumSize bytes") else { if (checkMinimalEncoding) { // Check that the number is encoded with the minimum possible // number of bytes. // // If the most-significant-byte - excluding the sign bit - is zero // then we're not minimal. Note how this test also rejects the // negative-zero encoding, 0x80. if ((input.last & 0x7f) == 0) { // One exception: if there's more than one byte and the most // significant bit of the second-most-significant-byte is set // it would conflict with the sign bit. An example of this case // is +-255, which encode to 0xff00 and 0xff80 respectively. // (big-endian). if (input.size <= 1 || (input(input.size - 2) & 0x80) == 0) { throw new RuntimeException("non-minimally encoded script number") } } } var result = 0L for (i <- input.toSeq.indices) { result |= (input(i) & 0xffL) << (8 * i) } // If the input vector's most significant byte is 0x80, remove it from // the result's msb and return a negative. if ((input.last & 0x80) != 0) -(result & ~(0x80L << (8 * (input.size - 1)))) else result } } def castToBoolean(input: ByteVector): Boolean = input.toSeq.reverse match { case head +: tail if head == 0x80.toByte && tail.forall(_ == 0) => false case something if something.exists(_ != 0) => true case _ => false } def isPushOnly(script: Seq[ScriptElt]): Boolean = !script.exists { case op if isSimpleValue(op) => false case OP_PUSHDATA(_, _) => false case _ => true } def isPayToScript(script: Seq[ScriptElt]): Boolean = script match { case OP_HASH160 :: OP_PUSHDATA(multisigAddress, _) :: OP_EQUAL :: Nil if multisigAddress.length == 20 => true case _ => false } def isPayToScript(script: ByteVector): Boolean = script.length == 23 && script(0) == elt2code(OP_HASH160).toByte && script(1) == 0x14 && script(22) == elt2code(OP_EQUAL).toByte def isNativeWitnessScript(script: Seq[ScriptElt]): Boolean = script match { case (OP_0 | OP_1 | OP_2 | OP_3 | OP_4 | OP_5 | OP_6 | OP_7 | OP_8 | OP_9 | OP_10 | OP_11 | OP_12 | OP_13 | OP_14 | OP_15 | OP_16) :: OP_PUSHDATA(witnessProgram, _) :: Nil if witnessProgram.length >= 2 && witnessProgram.length <= 40 => true case _ => false } def isNativeWitnessScript(script: ByteVector): Boolean = isNativeWitnessScript(parse(script)) def removeSignature(script: List[ScriptElt], signature: ByteVector): List[ScriptElt] = { val toRemove = OP_PUSHDATA(signature) script.filterNot(_ == toRemove) } def removeSignatures(script: List[ScriptElt], sigs: List[ByteVector]): List[ScriptElt] = sigs.foldLeft(script)(removeSignature) def checkLockTime(lockTime: Long, tx: Transaction, inputIndex: Int): Boolean = { // There are two kinds of nLockTime: lock-by-blockheight // and lock-by-blocktime, distinguished by whether // nLockTime < LOCKTIME_THRESHOLD. // // We want to compare apples to apples, so fail the script // unless the type of nLockTime being tested is the same as // the nLockTime in the transaction. if (!( (tx.lockTime < Transaction.LOCKTIME_THRESHOLD && lockTime < Transaction.LOCKTIME_THRESHOLD) || (tx.lockTime >= Transaction.LOCKTIME_THRESHOLD && lockTime >= Transaction.LOCKTIME_THRESHOLD) )) { return false } // Now that we know we're comparing apples-to-apples, the // comparison is a simple numeric one. if (lockTime > tx.lockTime) return false // Finally the nLockTime feature can be disabled and thus // CHECKLOCKTIMEVERIFY bypassed if every txin has been // finalized by setting nSequence to maxint. The // transaction would be allowed into the blockchain, making // the opcode ineffective. // // Testing if this vin is not final is sufficient to // prevent this condition. Alternatively we could test all // inputs, but testing just this input minimizes the data // required to prove correct CHECKLOCKTIMEVERIFY execution. if (tx.txIn(inputIndex).isFinal) return false true } def checkSequence(sequence: Long, tx: Transaction, inputIndex: Int): Boolean = { // Relative lock times are supported by comparing the passed // in operand to the sequence number of the input. val txToSequence = tx.txIn(inputIndex).sequence // Fail if the transaction's version number is not set high // enough to trigger BIP 68 rules. if (tx.version < 2) return false // Sequence numbers with their most significant bit set are not // consensus constrained. Testing that the transaction's sequence // number do not have this bit set prevents using this property // to get around a CHECKSEQUENCEVERIFY check. if ((txToSequence & TxIn.SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0) return false // Mask off any bits that do not have consensus-enforced meaning // before doing the integer comparisons val nLockTimeMask = TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG | TxIn.SEQUENCE_LOCKTIME_MASK val txToSequenceMasked = txToSequence & nLockTimeMask val nSequenceMasked = sequence & nLockTimeMask // There are two kinds of nSequence: lock-by-blockheight // and lock-by-blocktime, distinguished by whether // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG. // // We want to compare apples to apples, so fail the script // unless the type of nSequenceMasked being tested is the same as // the nSequenceMasked in the transaction. if (!( (txToSequenceMasked < TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG) || (txToSequenceMasked >= TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= TxIn.SEQUENCE_LOCKTIME_TYPE_FLAG) )) { return false } // Now that we know we're comparing apples-to-apples, the // comparison is a simple numeric one. if (nSequenceMasked > txToSequenceMasked) return false true } /** * Execution context of a tx script. A script is always executed in the "context" of a transaction that is being * verified. * * @param tx transaction that is being verified * @param inputIndex 0-based index of the tx input that is being processed */ case class Context(tx: Transaction, inputIndex: Int, amount: Satoshi) { require(inputIndex >= 0 && inputIndex < tx.txIn.length, "invalid input index") } object Runner { /** * This class represents the state of the script execution engine * * @param conditions current "position" wrt if/notif/else/endif * @param altstack initial alternate stack * @param opCount initial op count * @param scriptCode initial script (can be modified by OP_CODESEPARATOR for example) */ case class State(conditions: List[Boolean], altstack: Stack, opCount: Int, scriptCode: List[ScriptElt]) type Callback = (List[ScriptElt], Stack, State) => Boolean } /** * Bitcoin script runner * * @param context script execution context * @param scriptFlag script flags * @param callback optional callback */ class Runner(context: Context, scriptFlag: Int = MANDATORY_SCRIPT_VERIFY_FLAGS, callback: Option[Runner.Callback] = None) { import Runner._ def checkSignature(pubKey: ByteVector, sigBytes: ByteVector, scriptCode: ByteVector, signatureVersion: Int): Boolean = { if (sigBytes.isEmpty) false else if (!Crypto.checkSignatureEncoding(sigBytes, scriptFlag)) throw new RuntimeException("invalid signature") else if (!Crypto.checkPubKeyEncoding(pubKey, scriptFlag, signatureVersion)) throw new RuntimeException("invalid public key") else if (!Crypto.isPubKeyValidLax(pubKey)) false // see how this is different from above ? else { val sigHashFlags = sigBytes.last & 0xff // sig hash is the last byte val sigBytes1 = sigBytes.take(sigBytes.length - 1) // drop sig hash if (sigBytes1.isEmpty) false else { val hash = Transaction.hashForSigning(context.tx, context.inputIndex, scriptCode, sigHashFlags, context.amount, signatureVersion) val result = Crypto.verifySignature(hash, Crypto.der2compact(sigBytes1), PublicKey.fromBin(pubKey)) result } } } def checkSignatures(pubKeys: Seq[ByteVector], sigs: Seq[ByteVector], scriptCode: ByteVector, signatureVersion: Int): Boolean = sigs match { case Nil => true case _ if sigs.length > pubKeys.length => false case sig :: _ if !Crypto.checkSignatureEncoding(sig, scriptFlag) => throw new RuntimeException("invalid signature") case sig :: _ => if (checkSignature(pubKeys.head, sig, scriptCode, signatureVersion)) checkSignatures(pubKeys.tail, sigs.tail, scriptCode, signatureVersion) else checkSignatures(pubKeys.tail, sigs, scriptCode, signatureVersion) } def checkMinimalEncoding: Boolean = (scriptFlag & SCRIPT_VERIFY_MINIMALDATA) != 0 def decodeNumber(input: ByteVector, maximumSize: Int = 4): Long = Script.decodeNumber(input, checkMinimalEncoding, maximumSize) /** * execute a serialized script, starting from an empty stack * * @param script serialized script * @return the stack created by the script */ def run(script: ByteVector): Stack = run(parse(script)) /** * execute a script, starting from an empty stack * * @return the stack created by the script */ def run(script: List[ScriptElt]): Stack = run(script, List.empty[ByteVector]) /** * execute a serialized script, starting from an existing stack * * @param script serialized script * @param stack initial stack * @return the stack updated by the script */ def run(script: ByteVector, stack: Stack): Stack = run(parse(script), stack) def run(script: List[ScriptElt], stack: Stack): Stack = run(script, stack, SigVersion.SIGVERSION_BASE) /** * execute a script, starting from an existing stack * * @param script serialized script * @param stack initial stack * @param signatureVersion signature version (0: use pre-segwit tx hash, 1: use segwit tx hash) * @return the stack updated by the script */ def run(script: List[ScriptElt], stack: Stack, signatureVersion: Int): Stack = run(script, stack, State(conditions = List.empty[Boolean], altstack = List.empty[ByteVector], opCount = 0, scriptCode = script), signatureVersion) /** * execute a bitcoin script * * @param script script * @param stack initial stack * @param state initial state * @return the stack updated by the script */ @tailrec final def run(script: List[ScriptElt], stack: Stack, state: State, signatureVersion: Int): Stack = { import state._ callback.map(f => f(script, stack, state)) if ((stack.length + altstack.length) > 1000) throw new RuntimeException(s"stack is too large: stack size = ${stack.length} alt stack size = ${altstack.length}") if (opCount > 201) throw new RuntimeException("operation count is over the limit") script match { // first, things that are always checked even in non-executed IF branches case Nil if conditions.nonEmpty => throw new RuntimeException("IF/ENDIF imbalance") case Nil => stack case op :: _ if isDisabled(op) => throw new RuntimeException(s"$op isdisabled") case OP_CODESEPARATOR :: _ if signatureVersion == SigVersion.SIGVERSION_BASE && (scriptFlag & SCRIPT_VERIFY_CONST_SCRIPTCODE) != 0 => throw new RuntimeException("Using OP_CODESEPARATOR in non-witness script") case OP_VERIF :: _ => throw new RuntimeException("OP_VERIF is always invalid") case OP_VERNOTIF :: _ => throw new RuntimeException("OP_VERNOTIF is always invalid") case OP_PUSHDATA(data, _) :: _ if data.size > MaxScriptElementSize => throw new RuntimeException("Push value size limit exceeded") // check whether we are in a non-executed IF branch case OP_IF :: tail if conditions.contains(false) => run(tail, stack, state.copy(conditions = false :: conditions, opCount = opCount + 1), signatureVersion) case OP_IF :: tail => stack match { case True :: stacktail if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 => run(tail, stacktail, state.copy(conditions = true :: conditions, opCount = opCount + 1), signatureVersion) case False :: stacktail if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 => run(tail, stacktail, state.copy(conditions = false :: conditions, opCount = opCount + 1), signatureVersion) case _ :: stacktail if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 => throw new RuntimeException("OP_IF argument must be minimal") case head :: stacktail if castToBoolean(head) => run(tail, stacktail, state.copy(conditions = true :: conditions, opCount = opCount + 1), signatureVersion) case head :: stacktail => run(tail, stacktail, state.copy(conditions = false :: conditions, opCount = opCount + 1), signatureVersion) } case OP_NOTIF :: tail if conditions.contains(false) => run(tail, stack, state.copy(conditions = true :: conditions, opCount = opCount + 1), signatureVersion) case OP_NOTIF :: tail => stack match { case False :: stacktail if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 => run(tail, stacktail, state.copy(conditions = true :: conditions, opCount = opCount + 1), signatureVersion) case True :: stacktail if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 => run(tail, stacktail, state.copy(conditions = false :: conditions, opCount = opCount + 1), signatureVersion) case _ :: stacktail if signatureVersion == SigVersion.SIGVERSION_WITNESS_V0 && (scriptFlag & SCRIPT_VERIFY_MINIMALIF) != 0 => throw new RuntimeException("OP_NOTIF argument must be minimal") case head :: stacktail if castToBoolean(head) => run(tail, stacktail, state.copy(conditions = false :: conditions, opCount = opCount + 1), signatureVersion) case head :: stacktail => run(tail, stacktail, state.copy(conditions = true :: conditions, opCount = opCount + 1), signatureVersion) } case OP_ELSE :: tail => run(tail, stack, state.copy(conditions = !conditions.head :: conditions.tail, opCount = opCount + 1), signatureVersion) case OP_ENDIF :: tail => run(tail, stack, state.copy(conditions = conditions.tail, opCount = opCount + 1), signatureVersion) case head :: tail if conditions.contains(false) => run(tail, stack, state.copy(opCount = opCount + cost(head)), signatureVersion) // and now, things that are checked only in an executed IF branch case OP_0 :: tail => run(tail, ByteVector.empty :: stack, state, signatureVersion) case op :: tail if isSimpleValue(op) => run(tail, encodeNumber(simpleValue(op)) :: stack, state, signatureVersion) case OP_NOP :: tail => run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion) case op :: tail if isUpgradableNop(op) && ((scriptFlag & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) != 0) => throw new RuntimeException("use of upgradable NOP is discouraged") case op :: tail if isUpgradableNop(op) => run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion) case OP_1ADD :: tail if stack.isEmpty => throw new RuntimeException("cannot run OP_1ADD on am empty stack") case OP_1ADD :: tail => run(tail, encodeNumber(decodeNumber(stack.head) + 1) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_1SUB :: tail if stack.isEmpty => throw new RuntimeException("cannot run OP_1SUB on am empty stack") case OP_1SUB :: tail => run(tail, encodeNumber(decodeNumber(stack.head) - 1) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_ABS :: tail if stack.isEmpty => throw new RuntimeException("cannot run OP_ABS on am empty stack") case OP_ABS :: tail => run(tail, encodeNumber(Math.abs(decodeNumber(stack.head))) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_ADD :: tail => stack match { case a :: b :: stacktail => val x = decodeNumber(a) val y = decodeNumber(b) val result = x + y run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("cannot run OP_ADD on a stack with less than 2 elements") } case OP_BOOLAND :: tail => stack match { case x1 :: x2 :: stacktail => val n1 = decodeNumber(x1) val n2 = decodeNumber(x2) val result = if (n1 != 0 && n2 != 0) 1 else 0 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("cannot run OP_BOOLAND on a stack with less than 2 elements") } case OP_BOOLOR :: tail => stack match { case x1 :: x2 :: stacktail => val n1 = decodeNumber(x1) val n2 = decodeNumber(x2) val result = if (n1 != 0 || n2 != 0) 1 else 0 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("cannot run OP_BOOLOR on a stack with less than 2 elements") } case OP_CHECKLOCKTIMEVERIFY :: tail if (scriptFlag & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY) != 0 => stack match { case head :: _ => // Note that elsewhere numeric opcodes are limited to // operands in the range -2**31+1 to 2**31-1, however it is // legal for opcodes to produce results exceeding that // range. This limitation is implemented by CScriptNum's // default 4-byte limit. // // If we kept to that limit we'd have a year 2038 problem, // even though the nLockTime field in transactions // themselves is uint32 which only becomes meaningless // after the year 2106. // // Thus as a special case we tell CScriptNum to accept up // to 5-byte bignums, which are good until 2**39-1, well // beyond the 2**32-1 limit of the nLockTime field itself. val locktime = decodeNumber(head, maximumSize = 5) if (locktime < 0) throw new RuntimeException("CLTV lock time cannot be negative") if (!checkLockTime(locktime, context.tx, context.inputIndex)) throw new RuntimeException("unsatisfied CLTV lock time") // stack is not popped: we use stack here and not stacktail !! run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("cannot run OP_CHECKLOCKTIMEVERIFY on an empty stack") } case OP_CHECKLOCKTIMEVERIFY :: _ if (scriptFlag & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) != 0 => throw new RuntimeException("use of upgradable NOP is discouraged") case OP_CHECKLOCKTIMEVERIFY :: tail => run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion) case OP_CHECKSEQUENCEVERIFY :: tail if (scriptFlag & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY) != 0 => stack match { case head :: _ => // nSequence, like nLockTime, is a 32-bit unsigned integer // field. See the comment in CHECKLOCKTIMEVERIFY regarding // 5-byte numeric operands. val sequence = decodeNumber(head, maximumSize = 5) // In the rare event that the argument may be < 0 due to // some arithmetic being done first, you can always use // 0 MAX CHECKSEQUENCEVERIFY. if (sequence < 0) throw new RuntimeException("CSV lock time cannot be negative") // To provide for future soft-fork extensibility, if the // operand has the disabled lock-time flag set, // CHECKSEQUENCEVERIFY behaves as a NOP. if ((sequence & TxIn.SEQUENCE_LOCKTIME_DISABLE_FLAG) == 0) { // Actually compare the specified inverse sequence number // with the input. if (!checkSequence(sequence, context.tx, context.inputIndex)) throw new RuntimeException("unsatisfied CSV lock time") } // stack is not popped: we use stack here and not stacktail !! run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("cannot run OP_CHECKSEQUENCEVERIFY on an empty stack") } case OP_CHECKSEQUENCEVERIFY :: _ if (scriptFlag & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) != 0 => throw new RuntimeException("use of upgradable NOP is discouraged") case OP_CHECKSEQUENCEVERIFY :: tail => run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion) case OP_CHECKSIG :: tail => stack match { case pubKey :: sigBytes :: stacktail => // remove signature from script val scriptCode1 = if (signatureVersion == SigVersion.SIGVERSION_BASE) { val scriptCode1 = removeSignature(scriptCode, sigBytes) if (scriptCode1.length != scriptCode.length && (scriptFlag & SCRIPT_VERIFY_CONST_SCRIPTCODE) != 0) throw new RuntimeException("Signature is found in scriptCode") scriptCode1 } else scriptCode val success = checkSignature(pubKey, sigBytes, Script.write(scriptCode1), signatureVersion) if (!success && (scriptFlag & SCRIPT_VERIFY_NULLFAIL) != 0) { require(sigBytes.isEmpty, "Signature must be zero for failed CHECKSIG operation") } run(tail, (if (success) True else False) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_CHECKSIG on a stack with less than 2 elements") } case OP_CHECKSIGVERIFY :: tail => run(OP_CHECKSIG :: OP_VERIFY :: tail, stack, state.copy(opCount = opCount - 1), signatureVersion) case OP_CHECKMULTISIG :: tail => // pop public keys val m = decodeNumber(stack.head).toInt if (m < 0 || m > 20) throw new RuntimeException("OP_CHECKMULTISIG: invalid number of public keys") val nextOpCount = opCount + 1 + m if (nextOpCount > 201) throw new RuntimeException("operation count is over the limit") val stack1 = stack.tail val pubKeys = stack1.take(m) val stack2 = stack1.drop(m) // pop signatures val n = decodeNumber(stack2.head).toInt if (n < 0 || n > m) throw new RuntimeException("OP_CHECKMULTISIG: invalid number of signatures") val stack3 = stack2.tail // check that we have at least n + 1 items on the stack (+1 because of a bug in the reference client) require(stack3.size >= n + 1, "invalid stack operation") val sigs = stack3.take(n) if ((scriptFlag & ScriptFlags.SCRIPT_VERIFY_NULLDUMMY) != 0) require(stack3(n).isEmpty, "multisig dummy is not empty") val stack4 = stack3.drop(n + 1) // Drop the signature in pre-segwit scripts but not segwit scripts val scriptCode1 = if (signatureVersion == SigVersion.SIGVERSION_BASE) { val scriptCode1 = removeSignatures(scriptCode, sigs) if (scriptCode1.length != scriptCode.length && (scriptFlag & SCRIPT_VERIFY_CONST_SCRIPTCODE) != 0) throw new RuntimeException("Signature is found in scriptCode") scriptCode1 } else scriptCode val success = checkSignatures(pubKeys, sigs, Script.write(scriptCode1), signatureVersion) if (!success && (scriptFlag & SCRIPT_VERIFY_NULLFAIL) != 0) { sigs.foreach(sig => require(sig.isEmpty, "Signature must be zero for failed CHECKMULTISIG operation")) } run(tail, (if (success) True else False) :: stack4, state.copy(opCount = nextOpCount), signatureVersion) case OP_CHECKMULTISIGVERIFY :: tail => run(OP_CHECKMULTISIG :: OP_VERIFY :: tail, stack, state.copy(opCount = opCount - 1), signatureVersion) case OP_CODESEPARATOR :: tail => run(tail, stack, state.copy(opCount = opCount + 1, scriptCode = tail), signatureVersion) case OP_DEPTH :: tail => run(tail, encodeNumber(stack.length) :: stack, state.copy(opCount = opCount + 1), signatureVersion) case OP_SIZE :: _ if stack.isEmpty => throw new RuntimeException("Cannot run OP_SIZE on an empty stack") case OP_SIZE :: tail => run(tail, encodeNumber(stack.head.length) :: stack, state.copy(opCount = opCount + 1), signatureVersion) case OP_DROP :: tail => run(tail, stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_2DROP :: tail => run(tail, stack.tail.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_DUP :: tail => run(tail, stack.head :: stack, state.copy(opCount = opCount + 1), signatureVersion) case OP_2DUP :: tail => stack match { case x1 :: x2 :: stacktail => run(tail, x1 :: x2 :: x1 :: x2 :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_2DUP on a stack with less than 2 elements") } case OP_3DUP :: tail => stack match { case x1 :: x2 :: x3 :: stacktail => run(tail, x1 :: x2 :: x3 :: x1 :: x2 :: x3 :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_3DUP on a stack with less than 3 elements") } case OP_EQUAL :: tail => stack match { case a :: b :: stacktail if a != b => run(tail, False :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case a :: b :: stacktail => run(tail, True :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_EQUAL on a stack with less than 2 elements") } case OP_EQUALVERIFY :: tail => stack match { case a :: b :: _ if a != b => throw new RuntimeException("OP_EQUALVERIFY failed: elements are different") case a :: b :: stacktail => run(tail, stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_EQUALVERIFY on a stack with less than 2 elements") } case OP_FROMALTSTACK :: tail => run(tail, altstack.head :: stack, state.copy(altstack = altstack.tail), signatureVersion) case OP_HASH160 :: tail => run(tail, Crypto.hash160(stack.head) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_HASH256 :: tail => run(tail, Crypto.hash256(stack.head) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_IFDUP :: tail => stack match { case Nil => throw new RuntimeException("Cannot perform OP_IFDUP on an empty stack") case head :: _ if castToBoolean(head) => run(tail, head :: stack, state.copy(opCount = opCount + 1), signatureVersion) case _ => run(tail, stack, state.copy(opCount = opCount + 1), signatureVersion) } case OP_LESSTHAN :: tail => stack match { case x1 :: x2 :: stacktail => val result = if (decodeNumber(x2) < decodeNumber(x1)) 1 else 0 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_LESSTHAN on a stack with less than 2 elements") } case OP_LESSTHANOREQUAL :: tail => stack match { case x1 :: x2 :: stacktail => val result = if (decodeNumber(x2) <= decodeNumber(x1)) 1 else 0 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_LESSTHANOREQUAL on a stack with less than 2 elements") } case OP_GREATERTHAN :: tail => stack match { case x1 :: x2 :: stacktail => val result = if (decodeNumber(x2) > decodeNumber(x1)) 1 else 0 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_GREATERTHAN on a stack with less than 2 elements") } case OP_GREATERTHANOREQUAL :: tail => stack match { case x1 :: x2 :: stacktail => val result = if (decodeNumber(x2) >= decodeNumber(x1)) 1 else 0 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_GREATERTHANOREQUAL on a stack with less than 2 elements") } case OP_MAX :: tail => stack match { case x1 :: x2 :: stacktail => val n1 = decodeNumber(x1) val n2 = decodeNumber(x2) val result = if (n1 > n2) n1 else n2 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_MAX on a stack with less than 2 elements") } case OP_MIN :: tail => stack match { case x1 :: x2 :: stacktail => val n1 = decodeNumber(x1) val n2 = decodeNumber(x2) val result = if (n1 < n2) n1 else n2 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_MIN on a stack with less than 2 elements") } case OP_NEGATE :: tail if stack.isEmpty => throw new RuntimeException("cannot run OP_NEGATE on am empty stack") case OP_NEGATE :: tail => run(tail, encodeNumber(-decodeNumber(stack.head)) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_NIP :: tail => stack match { case x1 :: x2 :: stacktail => run(tail, x1 :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_NIP on a stack with less than 2 elements") } case OP_NOT :: tail if stack.isEmpty => throw new RuntimeException("cannot run OP_NOT on am empty stack") case OP_NOT :: tail => run(tail, encodeNumber(if (decodeNumber(stack.head) == 0) 1 else 0) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_0NOTEQUAL :: tail if stack.isEmpty => throw new RuntimeException("cannot run OP_0NOTEQUAL on am empty stack") case OP_0NOTEQUAL :: tail => run(tail, encodeNumber(if (decodeNumber(stack.head) == 0) 0 else 1) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_NUMEQUAL :: tail => stack match { case x1 :: x2 :: stacktail => val result = if (decodeNumber(x1) == decodeNumber(x2)) 1 else 0 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_NUMEQUAL on a stack with less than 2 elements") } case OP_NUMEQUALVERIFY :: tail => stack match { case x1 :: x2 :: stacktail => if (decodeNumber(x1) != decodeNumber(x2)) throw new RuntimeException("OP_NUMEQUALVERIFY failed") run(tail, stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_NUMEQUALVERIFY on a stack with less than 2 elements") } case OP_NUMNOTEQUAL :: tail => stack match { case x1 :: x2 :: stacktail => val result = if (decodeNumber(x1) != decodeNumber(x2)) 1 else 0 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_NUMNOTEQUAL on a stack with less than 2 elements") } case OP_OVER :: tail => stack match { case _ :: x2 :: _ => run(tail, x2 :: stack, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_OVER on a stack with less than 2 elements") } case OP_2OVER :: tail => stack match { case _ :: _ :: x3 :: x4 :: _ => run(tail, x3 :: x4 :: stack, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_2OVER on a stack with less than 4 elements") } case OP_PICK :: tail => stack match { case head :: stacktail => val n = decodeNumber(head).toInt run(tail, stacktail(n) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_PICK on a stack with less than 1 elements") } case OP_PUSHDATA(data, code) :: _ if ((scriptFlag & SCRIPT_VERIFY_MINIMALDATA) != 0) && !OP_PUSHDATA.isMinimal(data, code) => throw new RuntimeException("not minimal push") case OP_PUSHDATA(data, _) :: tail => run(tail, data :: stack, state, signatureVersion) case OP_ROLL :: tail => stack match { case head :: stacktail => val n = decodeNumber(head).toInt run(tail, stacktail(n) :: stacktail.take(n) ::: stacktail.takeRight(stacktail.length - 1 - n), state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_ROLL on a stack with less than 1 elements") } case OP_ROT :: tail => stack match { case x1 :: x2 :: x3 :: stacktail => run(tail, x3 :: x1 :: x2 :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_ROT on a stack with less than 3 elements") } case OP_2ROT :: tail => stack match { case x1 :: x2 :: x3 :: x4 :: x5 :: x6 :: stacktail => run(tail, x5 :: x6 :: x1 :: x2 :: x3 :: x4 :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_2ROT on a stack with less than 6 elements") } case OP_RIPEMD160 :: tail => run(tail, Crypto.ripemd160(stack.head) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_SHA1 :: tail => run(tail, Crypto.sha1(stack.head) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_SHA256 :: tail => run(tail, Crypto.sha256(stack.head) :: stack.tail, state.copy(opCount = opCount + 1), signatureVersion) case OP_SUB :: tail => stack match { case x1 :: x2 :: stacktail => val result = decodeNumber(x2) - decodeNumber(x1) run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("cannot run OP_SUB on a stack of less than 2 elements") } case OP_SWAP :: tail => stack match { case x1 :: x2 :: stacktail => run(tail, x2 :: x1 :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_SWAP on a stack with less than 2 elements") } case OP_2SWAP :: tail => stack match { case x1 :: x2 :: x3 :: x4 :: stacktail => run(tail, x3 :: x4 :: x1 :: x2 :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_2SWAP on a stack with less than 4 elements") } case OP_TOALTSTACK :: tail => run(tail, stack.tail, state.copy(altstack = stack.head :: altstack), signatureVersion) case OP_TUCK :: tail => stack match { case x1 :: x2 :: stacktail => run(tail, x1 :: x2 :: x1 :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_TUCK on a stack with less than 2 elements") } case OP_VERIFY :: tail => stack match { case Nil => throw new RuntimeException("cannot run OP_VERIFY on an empty stack") case head :: _ if !castToBoolean(head) => throw new RuntimeException("OP_VERIFY failed") case _ :: stacktail => run(tail, stacktail, state.copy(opCount = opCount + 1), signatureVersion) } case OP_WITHIN :: tail => stack match { case encMax :: encMin :: encN :: stacktail => val max = decodeNumber(encMax) val min = decodeNumber(encMin) val n = decodeNumber(encN) val result = if (n >= min && n < max) 1 else 0 run(tail, encodeNumber(result) :: stacktail, state.copy(opCount = opCount + 1), signatureVersion) case _ => throw new RuntimeException("Cannot perform OP_WITHIN on a stack with less than 3 elements") } } } def verifyWitnessProgram(witness: ScriptWitness, witnessVersion: Long, program: ByteVector): Unit = { val (stack: Seq[ByteVector], scriptPubKey) = witnessVersion match { case 0 if program.length == 20 => // P2WPKH, program is simply the pubkey hash require(witness.stack.length == 2, "Invalid witness program, should have 2 items") (witness.stack, OP_DUP :: OP_HASH160 :: OP_PUSHDATA(program) :: OP_EQUALVERIFY :: OP_CHECKSIG :: Nil) case 0 if program.length == 32 => // P2WPSH, program is the hash of the script, and witness is the stack + the script val check = Crypto.sha256(witness.stack.last) require(check.bytes == program, "witness program mismatch") (witness.stack.dropRight(1), Script.parse(witness.stack.last)) case 0 => throw new IllegalArgumentException(s"Invalid witness program length: ${program.length}") case _ if (scriptFlag & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) != 0 => throw new IllegalArgumentException(s"Invalid witness version: $witnessVersion") case _ => // Higher version witness scripts return true for future softfork compatibility return } stack.foreach(item => require(item.length <= MaxScriptElementSize, "item is bigger than maximum push size")) val stack1 = run(scriptPubKey, stack.toList.reverse, SigVersion.SIGVERSION_WITNESS_V0) require(stack1.length == 1) require(castToBoolean(stack1.head)) } def verifyScripts(scriptSig: ByteVector, scriptPubKey: ByteVector): Boolean = verifyScripts(scriptSig, scriptPubKey, ScriptWitness.empty) /** * verify a script sig/script pubkey pair: * <ul> * <li>parse and run script sig</li> * <li>parse and run script pubkey using the stack generated by the previous step</li> * <li>check the final stack</li> * <li>extract and run embedded pay2sh scripts if any and check the stack again</li> * </ul> * * @param scriptSig signature script * @param scriptPubKey public key script * @return true if the scripts were successfully verified */ def verifyScripts(scriptSig: ByteVector, scriptPubKey: ByteVector, witness: ScriptWitness): Boolean = { def checkStack(stack: Stack): Boolean = { if (stack.isEmpty) false else if (!Script.castToBoolean(stack.head)) false else if ((scriptFlag & SCRIPT_VERIFY_CLEANSTACK) != 0) { if ((scriptFlag & SCRIPT_VERIFY_P2SH) == 0) throw new RuntimeException("illegal script flag") stack.size == 1 } else true } if ((scriptFlag & SCRIPT_VERIFY_WITNESS) != 0) { // We can't check for correct unexpected witness data if P2SH was off, so require // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be // possible, which is not a softfork. require((scriptFlag & SCRIPT_VERIFY_P2SH) != 0) } val ssig = Script.parse(scriptSig) if (((scriptFlag & SCRIPT_VERIFY_SIGPUSHONLY) != 0) && !Script.isPushOnly(ssig)) throw new RuntimeException("signature script is not PUSH-only") val stack = run(ssig) val spub = Script.parse(scriptPubKey) val stack0 = run(spub, stack) require(stack0.nonEmpty, "Script verification failed, stack should not be empty") require(castToBoolean(stack0.head), "Script verification failed, stack starts with 'false'") var hadWitness = false val stack1 = if ((scriptFlag & SCRIPT_VERIFY_WITNESS) != 0) { spub match { case op :: OP_PUSHDATA(program, code) :: Nil if isSimpleValue(op) && OP_PUSHDATA.isMinimal(program, code) && program.length >= 2 && program.length <= 40 => hadWitness = true val witnessVersion = simpleValue(op) require(ssig.isEmpty, "Malleated segwit script") verifyWitnessProgram(witness, witnessVersion, program) stack0.take(1) case _ => stack0 } } else stack0 val stack2 = if (((scriptFlag & SCRIPT_VERIFY_P2SH) != 0) && Script.isPayToScript(scriptPubKey)) { // scriptSig must be literals-only or validation fails if (!Script.isPushOnly(ssig)) throw new RuntimeException("signature script is not PUSH-only") // pay to script: // script sig is built as sig1 :: ... :: sigN :: serialized_script :: Nil // and script pubkey is HASH160 :: hash :: EQUAL :: Nil // if we got here after running script pubkey, it means that hash == HASH160(serialized script) // and stack would be serialized_script :: sigN :: ... :: sig1 :: Nil // we pop the first element of the stack, deserialize it and run it against the rest of the stack val stackp2sh = run(stack.head, stack.tail) require(stackp2sh.nonEmpty, "Script verification failed, stack should not be empty") require(castToBoolean(stackp2sh.head), "Script verification failed, stack starts with 'false'") if ((scriptFlag & SCRIPT_VERIFY_WITNESS) != 0) { Script.parse(stack.head) match { case op :: OP_PUSHDATA(program, _) :: Nil if isSimpleValue(op) && program.length >= 2 && program.length <= 32 => hadWitness = true val witnessVersion = simpleValue(op) //require(ssig.isEmpty, "Malleated segwit script") verifyWitnessProgram(witness, witnessVersion, program) stackp2sh.take(1) case _ => stackp2sh } } else stackp2sh } else stack1 if ((scriptFlag & SCRIPT_VERIFY_WITNESS) != 0 && !hadWitness) { require(witness.isNull) } checkStack(stack2) } } /** * extract a public key hash from a public key script * * @param script public key script * @return the public key hash wrapped in the script */ def publicKeyHash(script: List[ScriptElt]): ByteVector = script match { case OP_DUP :: OP_HASH160 :: OP_PUSHDATA(data, _) :: OP_EQUALVERIFY :: OP_CHECKSIG :: OP_NOP :: Nil => data // non standard pay to pubkey... case OP_DUP :: OP_HASH160 :: OP_PUSHDATA(data, _) :: OP_EQUALVERIFY :: OP_CHECKSIG :: Nil => data // standard pay to pubkey case OP_HASH160 :: OP_PUSHDATA(data, _) :: OP_EQUAL :: Nil if data.size == 20 => data // standard pay to script } def publicKeyHash(script: ByteVector): ByteVector = publicKeyHash(parse(script)) /** * extract a public key from a signature script * * @param script signature script * @return the public key wrapped in the script */ def publicKey(script: List[ScriptElt]): ByteVector = script match { case OP_PUSHDATA(data1, _) :: OP_PUSHDATA(data2, _) :: Nil if data1.length > 2 && data2.length > 2 => data2 case OP_PUSHDATA(data, _) :: OP_CHECKSIG :: Nil => data } /** * Creates a m-of-n multisig script. * * @param m is the number of required signatures * @param pubkeys are the public keys signatures will be checked against (there should be at least as many public keys * as required signatures) * @return a multisig redeem script */ def createMultiSigMofN(m: Int, pubkeys: Seq[PublicKey]): Seq[ScriptElt] = { require(m > 0 && m <= 16, s"number of required signatures is $m, should be between 1 and 16") require(pubkeys.nonEmpty && pubkeys.size <= 16, s"number of public keys is ${pubkeys.size}, should be between 1 and 16") require(m <= pubkeys.size, "The required number of signatures shouldn't be greater than the number of public keys") val op_m = ScriptElt.code2elt(m + 0x50) // 1 -> OP_1, 2 -> OP_2, ... 16 -> OP_16 val op_n = ScriptElt.code2elt(pubkeys.size + 0x50) op_m :: pubkeys.toList.map(pub => OP_PUSHDATA(pub.value)) ::: op_n :: OP_CHECKMULTISIG :: Nil } /** * @param pubKeyHash public key hash * @return a pay-to-public-key-hash script */ def pay2pkh(pubKeyHash: ByteVector): Seq[ScriptElt] = { require(pubKeyHash.length == 20, "pubkey hash length must be 20 bytes") OP_DUP :: OP_HASH160 :: OP_PUSHDATA(pubKeyHash) :: OP_EQUALVERIFY :: OP_CHECKSIG :: Nil } /** * @param pubKey public key * @return a pay-to-public-key-hash script */ def pay2pkh(pubKey: PublicKey): Seq[ScriptElt] = pay2pkh(pubKey.hash160) def isPay2pkh(script: Seq[ScriptElt]): Boolean = { script match { case OP_DUP :: OP_HASH160 :: OP_PUSHDATA(data, _) :: OP_EQUALVERIFY :: OP_CHECKSIG :: Nil if data.length == 20 => true case _ => false } } /** * @param script bitcoin script * @return a pay-to-script script */ def pay2sh(script: Seq[ScriptElt]): Seq[ScriptElt] = pay2sh(Script.write(script)) /** * @param script bitcoin script * @return a pay-to-script script */ def pay2sh(script: ByteVector): Seq[ScriptElt] = OP_HASH160 :: OP_PUSHDATA(hash160(script)) :: OP_EQUAL :: Nil def isPay2sh(script: Seq[ScriptElt]): Boolean = { script match { case OP_HASH160 :: OP_PUSHDATA(data, _) :: OP_EQUAL :: Nil if data.length == 20 => true case _ => false } } /** * @param script bitcoin script * @return a pay-to-witness-script script */ def pay2wsh(script: Seq[ScriptElt]): Seq[ScriptElt] = pay2wsh(Script.write(script)) /** * @param script bitcoin script * @return a pay-to-witness-script script */ def pay2wsh(script: ByteVector): Seq[ScriptElt] = OP_0 :: OP_PUSHDATA(sha256(script)) :: Nil def isPay2wsh(script: Seq[ScriptElt]): Boolean = { script match { case OP_0 :: OP_PUSHDATA(data, _) :: Nil if data.length == 32 => true case _ => false } } /** * @param pubKeyHash public key hash * @return a pay-to-witness-public-key-hash script */ def pay2wpkh(pubKeyHash: ByteVector): Seq[ScriptElt] = { require(pubKeyHash.length == 20, "pubkey hash length must be 20 bytes") OP_0 :: OP_PUSHDATA(pubKeyHash) :: Nil } /** * @param pubKey public key * @return a pay-to-witness-public-key-hash script */ def pay2wpkh(pubKey: PublicKey): Seq[ScriptElt] = pay2wpkh(pubKey.hash160) def isPay2wpkh(script: Seq[ScriptElt]): Boolean = { script match { case OP_0 :: OP_PUSHDATA(data, _) :: Nil if data.length == 20 => true case _ => false } } /** * @param pubKey public key * @param sig signature matching the public key * @return script witness for the corresponding pay-to-witness-public-key-hash script */ def witnessPay2wpkh(pubKey: PublicKey, sig: ByteVector): ScriptWitness = ScriptWitness(sig :: pubKey.value :: Nil) /** * @param pubKeys are the public keys signatures will be checked against. * @param sigs are the signatures for a subset of the public keys. * @return script witness for the pay-to-witness-script-hash script containing a multisig script. */ def witnessMultiSigMofN(pubKeys: Seq[PublicKey], sigs: Seq[ByteVector]): ScriptWitness = { val redeemScript = Script.write(Script.createMultiSigMofN(sigs.size, pubKeys)) ScriptWitness(ByteVector.empty +: sigs :+ redeemScript) } }
ACINQ/bitcoin-lib
src/main/scala/fr/acinq/bitcoin/Script.scala
Scala
apache-2.0
58,954
package camelinaction import akka.actor.Actor._ import akka.camel._ /** * @author Martin Krasser */ object SectionE4 extends Application { import SampleActors._ val service = CamelServiceManager.startCamelService val httpConsumer2 = actorOf[HttpConsumer2] val httpProducer1 = actorOf[HttpProducer1].start val httpProducer2 = actorOf[HttpProducer2].start service.awaitEndpointActivation(1) { httpConsumer2.start } // Send message to httpProducer and wait for response httpProducer1 !! "Camel rocks" match { case Some(m: Message) => println("response = %s" format m.bodyAs[String]) case Some(f: Failure) => println("failure = %s" format f.cause.getMessage) case None => println("timeout") } // Send message to httpProducer2 without waiting for a response httpProducer2 ! "Camel rocks" // Wait a bit for httpProducer2 to write the response to stdout Thread.sleep(2000) service.stop httpConsumer2.stop httpProducer1.stop httpProducer2.stop }
sprklinginfo/camelinaction2
old_chapters/appendixE/src/main/scala/SectionE4.scala
Scala
apache-2.0
1,011
package fpinscala import fpinscala.datastructures._ object Ch03 { val a = List(1, 2, 3, 4, 5) match { case Cons(x, Cons(2, Cons(4, _))) => x case Nil => 42 case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y case Cons(h, t) => h + List.sum(t) case _ => 101 } def main(args: Array[String]): Unit = { println(a) } }
mebubo/fpinscala
exercises/src/main/scala/fpinscala/Ch03.scala
Scala
mit
349
package org.jetbrains.plugins.scala.lang.rearranger import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.EntryType._ import com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Modifier._ import com.intellij.psi.codeStyle.arrangement.std.{ArrangementSettingsToken, StdArrangementSettingsToken, StdArrangementTokenType, StdArrangementTokens} import org.jetbrains.annotations.NonNls import org.jetbrains.plugins.scala.ScalaBundle import scala.collection.immutable.{HashMap, HashSet, ListSet} import scala.language.higherKinds //noinspection TypeAnnotation,SameParameterValue //TODO: use names from bundle object RearrangerUtils { private def token(@NonNls id: String, name: String, tokenType: StdArrangementTokenType): StdArrangementSettingsToken = StdArrangementSettingsToken.token(id, name, tokenType) private def tokenById(@NonNls id: String, tokenType: StdArrangementTokenType): StdArrangementSettingsToken = StdArrangementSettingsToken.token(id, StringUtil.toLowerCase(id).replace("_", " "), tokenType) val SCALA_GETTERS_AND_SETTERS: ArrangementSettingsToken = token( "SCALA_KEEP_SCALA_GETTERS_SETTERS_TOGETHER", ScalaBundle.message("rearranger.panel.keep.scala.style.getters.and.setters.together"), StdArrangementTokenType.GROUPING ) val JAVA_GETTERS_AND_SETTERS: ArrangementSettingsToken = token( "SCALA_KEEP_JAVA_GETTERS_SETTERS_TOGETHER", ScalaBundle.message("rearranger.panel.keep.java.style.getters.and.setters.together"), StdArrangementTokenType.GROUPING ) val SPLIT_INTO_UNARRANGEABLE_BLOCKS_BY_EXPRESSIONS: ArrangementSettingsToken = token( "SCALA_SPLIT_BY_EXPRESSIONS", ScalaBundle.message("rearranger.panel.split.into.unarrangeable.blocks.by.expressions"), StdArrangementTokenType.GROUPING ) val SPLIT_INTO_UNARRANGEABLE_BLOCKS_BY_IMPLICITS: ArrangementSettingsToken = token( "SCALA_SPLIT_BY_IMPLICITS", ScalaBundle.message("rearranger.panel.split.into.unarrangeable.blocks.by.implicits"), StdArrangementTokenType.GROUPING ) //access modifiers @NonNls val SEALED : ArrangementSettingsToken = token("SCALA_SEALED", "sealed", StdArrangementTokenType.MODIFIER) @NonNls val IMPLICIT: ArrangementSettingsToken = token("SCALA_IMPLICIT", "implicit", StdArrangementTokenType.MODIFIER) @NonNls val CASE : ArrangementSettingsToken = token("SCALA_CASE", "case", StdArrangementTokenType.MODIFIER) @NonNls val OVERRIDE: ArrangementSettingsToken = token("SCALA_OVERRIDE", "override", StdArrangementTokenType.MODIFIER) @NonNls val LAZY : ArrangementSettingsToken = token("SCALA_LAZY", "lazy", StdArrangementTokenType.MODIFIER) @NonNls val TYPE : ArrangementSettingsToken = token("SCALA_TYPE", "type", StdArrangementTokenType.ENTRY_TYPE) @NonNls val FUNCTION : ArrangementSettingsToken = token("SCALA_FUNCTION", "function", StdArrangementTokenType.ENTRY_TYPE) @NonNls val VAL : ArrangementSettingsToken = token("SCALA_VAL", "val", StdArrangementTokenType.ENTRY_TYPE) @NonNls val MACRO : ArrangementSettingsToken = token("SCALA_MACRO", "macro", StdArrangementTokenType.ENTRY_TYPE) @NonNls val OBJECT : ArrangementSettingsToken = token("SCALA_OBJECT", "object", StdArrangementTokenType.ENTRY_TYPE) val UNSEPARABLE_RANGE: ArrangementSettingsToken = tokenById("SCALA_UNSEPARABLE_RANGE", StdArrangementTokenType.ENTRY_TYPE) //maps and sets of tokens val scalaTypesValues = HashSet(TYPE, FUNCTION, CLASS, VAL, VAR, TRAIT, MACRO, CONSTRUCTOR, OBJECT) private val scalaTypesById = scalaTypesValues.map(t => t.getId -> t).toMap private type tokensType = (String, ArrangementSettingsToken) val supportedOrders = HashSet(StdArrangementTokens.Order.BY_NAME, StdArrangementTokens.Order.KEEP) val scalaAccessModifiers = ListSet(PUBLIC, PROTECTED, PRIVATE) private val scalaAccessModifiersByName = scalaAccessModifiers.groupBySingle(_.getRepresentationValue) private val scalaAccessModifiersById = scalaAccessModifiers.groupBySingle(_.getId) private val scalaOtherModifiers = ListSet(SEALED, IMPLICIT, ABSTRACT, CASE, FINAL, OVERRIDE, LAZY) private val scalaOtherModifiersByName = scalaOtherModifiers.groupBySingle(_.getRepresentationValue) private val scalaOtherModifiersById = scalaOtherModifiers.groupBySingle(_.getId) val scalaModifiers = scalaAccessModifiers ++ scalaOtherModifiers val commonModifiers = scalaAccessModifiers + FINAL //TODO: determine if final is common private val scalaModifiersByName = scalaAccessModifiersByName ++ scalaOtherModifiersByName private val scalaTokensById = scalaAccessModifiersById ++ scalaOtherModifiersById ++ scalaTypesById def getModifierByName(modifierName: String): Option[ArrangementSettingsToken] = scalaModifiersByName.get(modifierName) def getTokenById(modifierId: String): Option[ArrangementSettingsToken] = scalaTokensById.get(modifierId) val tokensForType = HashMap( TYPE -> (commonModifiers + OVERRIDE), FUNCTION -> (commonModifiers + OVERRIDE + IMPLICIT), CLASS -> (commonModifiers + ABSTRACT + SEALED), TRAIT -> (commonModifiers + ABSTRACT + SEALED), VAL -> (commonModifiers + OVERRIDE + LAZY + ABSTRACT), VAR -> (commonModifiers + OVERRIDE), MACRO -> (commonModifiers + OVERRIDE), CONSTRUCTOR -> scalaAccessModifiers, OBJECT -> commonModifiers ) private implicit class CollectionExt[A](private val collection: Iterable[A]) extends AnyVal { def groupBySingle[T](f: A => T): Map[T, A] = collection.map(x => f(x) -> x).toMap } }
JetBrains/intellij-scala
scala/scala-impl/src/org/jetbrains/plugins/scala/lang/rearranger/RearrangerUtils.scala
Scala
apache-2.0
5,659
/* * Copyright 2014 Alan Rodas Bonjour * * 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 com.alanrodas.scaland.cli import com.alanrodas.scaland._ import com.alanrodas.scaland.cli.definitions.{ArgumentDefinition, FlagDefinition} import org.scalatest._ import language.postfixOps class BuildersSpec extends FlatSpec with Matchers with BeforeAndAfter { val emptyString = "" val foo = "foo" val bar = "bar" val baz = "baz" val f = "f" val b = "b" val g = "g" val shortSign = "-" val longSign = "--" val shortSignAlt = "/" val longSignAlt = "/" implicit var commandManager = new CommandManager() before { commandManager.setSigns(shortSign, longSign) } after { commandManager = new CommandManager() } /* ********* Values ************ */ "A ValueDefinition as mandatory" should "form nicely if a valid name is given" in { cli.value named foo mandatory } it should "form nicely if a name with spaces is given" in { cli.value named s"$foo $bar $baz" mandatory } it should "throw an IllegalArgumentException if no name is passed" in { an [IllegalArgumentException] should be thrownBy { cli.value named emptyString mandatory } } it should "not contain a default value" in { (cli.value named foo mandatory).default should be (None) } "A ValueDefinition with default value" should "form nicely if a valid name is given" in { cli.value named foo as "something" } it should "form nicely if a name with spaces is given" in { cli.value named s"$foo $bar" as "something" } it should "throw an IllegalArgumentException if no name is passed" in { an [IllegalArgumentException] should be thrownBy { cli.value named emptyString as "something" } } it should "take any value as default value" in { cli.value named s"$foo $bar $baz" as "" cli.value named s"$foo $bar" as 4 cli.value named s"$foo $baz $bar" as Seq(1,2,3,4) cli.value named s"$bar $bar" as Some(("four", 4)) } it should "retrieve the same value as passed when queried" in { (cli.value named s"$foo $bar $baz" as "").default.get should be ("") (cli.value named s"$foo $bar" as 4).default.get should be (4) (cli.value named s"$foo $baz $bar" as Seq(1,2,3,4)).default.get should be (Seq(1,2,3,4)) (cli.value named s"$bar $bar" as Some(("four", 4))).default.get should be (Some(("four", 4))) } /* ********* Flags ************ */ "A FlagDefinition" should "form nicely if a valid name is given" in { cli.flag named bar : FlagDefinition } it should "throw an IllegalArgumentException if no name is passed" in { an [IllegalArgumentException] should be thrownBy { cli.flag named emptyString : FlagDefinition } } it should "throw an IllegalArgumentException if the passed name has spaces" in { an [IllegalArgumentException] should be thrownBy { cli.flag named s"$bar $baz" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named s" $baz" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named s"$foo " : FlagDefinition } } it should "throw an IllegalArgumentException if the name starts with the short or long sign of the CommandManager" in { an [IllegalArgumentException] should be thrownBy { cli.flag named s"$shortSign$foo" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named s"$longSign$foo" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named s"$shortSign$b" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named s"$longSign$f" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named shortSign : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named longSign : FlagDefinition } commandManager.setSigns(shortSignAlt, longSignAlt) an [IllegalArgumentException] should be thrownBy { cli.flag named s"$shortSignAlt$baz" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named s"$longSignAlt$foo" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named s"$shortSignAlt$g" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named s"$longSignAlt$f" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named shortSignAlt : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named longSignAlt : FlagDefinition } } it should "form nicely if the name has short or long sign in the middle or end" in { cli.flag named s"$bar$shortSign$baz" : FlagDefinition cli.flag named s"$foo$longSign$baz" : FlagDefinition cli.flag named s"$baz$shortSign" : FlagDefinition cli.flag named s"$bar$longSign" : FlagDefinition cli.flag named s"$g$shortSign" : FlagDefinition cli.flag named s"$b$longSign" : FlagDefinition cli.flag named shortSignAlt : FlagDefinition cli.flag named longSignAlt : FlagDefinition commandManager.setSigns(shortSignAlt, longSignAlt) cli.flag named s"$bar$shortSignAlt$baz" : FlagDefinition cli.flag named s"$foo$longSignAlt$baz" : FlagDefinition cli.flag named s"$baz$shortSignAlt" : FlagDefinition cli.flag named s"$bar$longSignAlt" : FlagDefinition cli.flag named s"$g$shortSignAlt" : FlagDefinition cli.flag named s"$f$longSignAlt" : FlagDefinition cli.flag named shortSign : FlagDefinition cli.flag named longSign : FlagDefinition } it should "form nicely if a valid name and alias are given" in { cli.flag named foo alias g : FlagDefinition cli.flag named b alias bar : FlagDefinition } it should "throw an IllegalArgumentException if the alias is empty" in { an [IllegalArgumentException] should be thrownBy { cli.flag named baz alias emptyString : FlagDefinition } } it should "throw an IllegalArgumentException if the alias has spaces" in { an [IllegalArgumentException] should be thrownBy { cli.flag named f alias s"$foo $bar" : FlagDefinition } } it should "throw an IllegalArgumentException if the name and alias are both larger than one character" in { an [IllegalArgumentException] should be thrownBy { cli.flag named baz alias bar : FlagDefinition } } it should "throw an IllegalArgumentException if the name and alias are both of one character" in { an [IllegalArgumentException] should be thrownBy { cli.flag named b alias f : FlagDefinition } } it should "throw an IllegalArgumentException if the alias starts with the short or long sign of the CommandManager" in { an [IllegalArgumentException] should be thrownBy { cli.flag named f alias s"$shortSign$baz" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named f alias s"$longSign$baz" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named foo alias s"$shortSign$b" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named bar alias s"$longSign$f" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named foo alias shortSign : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named bar alias longSign : FlagDefinition } commandManager.setSigns(shortSignAlt, longSignAlt) an [IllegalArgumentException] should be thrownBy { cli.flag named f alias s"$shortSignAlt$baz" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named b alias s"$longSignAlt$bar" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named bar alias s"$shortSignAlt$f" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named baz alias s"$longSignAlt$b" : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named foo alias shortSignAlt : FlagDefinition } an [IllegalArgumentException] should be thrownBy { cli.flag named bar alias longSignAlt : FlagDefinition } } it should "form nicely if the alias has short or long sign in the middle or end" in { cli.flag named f alias s"$bar$shortSign$baz" : FlagDefinition cli.flag named g alias s"$bar$longSign$baz" : FlagDefinition cli.flag named g alias s"$bar$shortSign" : FlagDefinition cli.flag named b alias s"$bar$longSign" : FlagDefinition cli.flag named foo alias shortSignAlt : FlagDefinition cli.flag named bar alias longSignAlt : FlagDefinition commandManager.setSigns(shortSignAlt, longSignAlt) cli.flag named g alias s"$bar$shortSignAlt$baz" : FlagDefinition cli.flag named f alias s"$bar$longSignAlt$baz" : FlagDefinition cli.flag named f alias s"$foo$shortSignAlt" : FlagDefinition cli.flag named b alias s"$baz$longSignAlt" : FlagDefinition cli.flag named foo alias shortSign : FlagDefinition } /* ********* Arguments ************ */ "An ArgumentDefinition" should "form nicely if a valid name is given" in { cli.arg named foo taking 1 value : ArgumentDefinition[_] } it should "throw an IllegalArgumentException if no name is passed" in { an [IllegalArgumentException] should be thrownBy { cli.arg named emptyString taking 1 value : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if the passed name has spaces" in { an [IllegalArgumentException] should be thrownBy { cli.arg named s"$foo $baz" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named s" $foo" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named s"$foo " taking 1 value : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if the name starts with the short or long sign of the CommandManager" in { an [IllegalArgumentException] should be thrownBy { cli.arg named s"$shortSign$foo" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named s"$longSign$foo" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named s"$shortSign$b" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named s"$longSign$f" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named shortSign taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named longSign taking 1 value : ArgumentDefinition[_] } commandManager.setSigns(shortSignAlt, longSignAlt) an [IllegalArgumentException] should be thrownBy { cli.arg named s"$shortSignAlt$baz" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named s"$longSignAlt$foo" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named s"$shortSignAlt$g" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named s"$longSignAlt$f" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named shortSignAlt taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named longSignAlt taking 1 value : ArgumentDefinition[_] } } it should "form nicely if the name has short or long sign in the middle or end" in { cli.arg named s"$bar$shortSign$baz" taking 7 values : ArgumentDefinition[_] cli.arg named s"$foo$longSign$baz" taking 1 value : ArgumentDefinition[_] cli.arg named s"$baz$shortSign" taking 1 value : ArgumentDefinition[_] cli.arg named s"$bar$longSign" taking 4 values : ArgumentDefinition[_] cli.arg named s"$g$shortSign" taking 1 value : ArgumentDefinition[_] cli.arg named s"$b$longSign" taking 1 value : ArgumentDefinition[_] cli.arg named shortSignAlt taking 2 values : ArgumentDefinition[_] cli.arg named longSignAlt taking 1 value : ArgumentDefinition[_] commandManager.setSigns(shortSignAlt, longSignAlt) cli.arg named s"$bar$shortSignAlt$baz" taking 1 value : ArgumentDefinition[_] cli.arg named s"$foo$longSignAlt$baz" taking 1 value : ArgumentDefinition[_] cli.arg named s"$baz$shortSignAlt" taking 5 values : ArgumentDefinition[_] cli.arg named s"$bar$longSignAlt" taking 1 value : ArgumentDefinition[_] cli.arg named s"$g$shortSignAlt" taking 2 values : ArgumentDefinition[_] cli.arg named s"$f$longSignAlt" taking 1 value : ArgumentDefinition[_] cli.arg named shortSign taking 2 values : ArgumentDefinition[_] cli.arg named longSign taking 1 value : ArgumentDefinition[_] } it should "form nicely if a valid name and alias are given" in { cli.arg named foo alias g taking 1 value : ArgumentDefinition[_] cli.arg named b alias baz taking 1 value : ArgumentDefinition[_] } it should "throw an IllegalArgumentException if the alias is empty" in { an [IllegalArgumentException] should be thrownBy { cli.arg named baz alias emptyString taking 1 value : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if the alias has spaces" in { an [IllegalArgumentException] should be thrownBy { cli.arg named f alias s"$foo $bar" taking 1 value : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if the name and alias are both larger than one character" in { an [IllegalArgumentException] should be thrownBy { cli.arg named baz alias bar taking 1 value : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if the name and alias are both of one character" in { an [IllegalArgumentException] should be thrownBy { cli.arg named f alias g taking 1 value : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if the alias starts with the short or long sign of the CommandManager" in { an [IllegalArgumentException] should be thrownBy { cli.arg named f alias s"$shortSign$baz" taking 1 values : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named f alias s"$longSign$baz" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named foo alias s"$shortSign$b" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named bar alias s"$longSign$f" taking 5 values : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named foo alias shortSign taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named bar alias longSign taking 1 value : ArgumentDefinition[_] } commandManager.setSigns(shortSignAlt, longSignAlt) an [IllegalArgumentException] should be thrownBy { cli.arg named f alias s"$shortSignAlt$baz" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named b alias s"$longSignAlt$bar" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named bar alias s"$shortSignAlt$f" taking 2 values : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named baz alias s"$longSignAlt$b" taking 1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named foo alias shortSignAlt taking 4 values : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named bar alias longSignAlt taking 1 value : ArgumentDefinition[_] } } it should "form nicely if the alias has short or long sign in the middle or end" in { cli.arg named f alias s"$bar$shortSign$baz" taking 1 value : ArgumentDefinition[_]; cli.arg named g alias s"$bar$longSign$baz" taking 2 values : ArgumentDefinition[_]; cli.arg named g alias s"$bar$shortSign" taking 1 value : ArgumentDefinition[_]; cli.arg named b alias s"$bar$longSign" taking 1 value : ArgumentDefinition[_]; cli.arg named foo alias shortSignAlt taking 4 values : ArgumentDefinition[_]; cli.arg named bar alias longSignAlt taking 1 value : ArgumentDefinition[_]; commandManager.setSigns(shortSignAlt, longSignAlt) cli.arg named g alias s"$bar$shortSignAlt$baz" taking 1 value : ArgumentDefinition[_]; cli.arg named f alias s"$bar$longSignAlt$baz" taking 3 values : ArgumentDefinition[_]; cli.arg named f alias s"$foo$shortSignAlt" taking 1 value : ArgumentDefinition[_]; cli.arg named b alias s"$baz$longSignAlt" taking 2 values : ArgumentDefinition[_]; cli.arg named foo alias shortSign taking 1 value : ArgumentDefinition[_] } it should "throw an IllegalArgumentException if the number of arguments passed is lower than zero" in { an [IllegalArgumentException] should be thrownBy { cli.arg named foo taking -1 values : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named bar taking -5 values : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named foo taking -1 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named bar taking -5 value : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if the number of arguments passed is zero" in { an [IllegalArgumentException] should be thrownBy { cli.arg named baz taking 0 values : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named baz taking 0 value : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if value is called when taking is more than one" in { an [IllegalArgumentException] should be thrownBy { cli.arg named baz taking 2 value : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named baz taking 8 value : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if values is called when taking is one" in { an [IllegalArgumentException] should be thrownBy { cli.arg named baz taking 1 values : ArgumentDefinition[_] } } it should "throw an IllegalArgumentException if the number of default values is greater than taking" in { an [IllegalArgumentException] should be thrownBy { cli.arg named foo taking 3 as (1,2,3,4) : ArgumentDefinition[_] } an [IllegalArgumentException] should be thrownBy { cli.arg named bar taking 1 as ("one", "two") : ArgumentDefinition[_] } } it should "form nicely if a the number of arguments is less or equal than the number taken" in { cli.arg named foo taking 1 as "one" : ArgumentDefinition[_] cli.arg named f taking 3 as ("one", "two", "three") : ArgumentDefinition[_] cli.arg named g taking 5 as (1,2,3,4) : ArgumentDefinition[_] cli.arg named bar taking 3 as (None, Some("Wiiii")) : ArgumentDefinition[_] } it should "return the same value as inputed" in { (cli.arg named baz taking 1 as "one").argumentValues should be (Array("one")) (cli.arg named bar taking 3 as ("one", "two", "three")).argumentValues should be (Array("one", "two", "three")) (cli.arg named f taking 5 as (1,2,3,4)).argumentValues should be (Array(1,2,3,4)) (cli.arg named foo taking 3 as (None, Some("Wiiii"))).argumentValues should be (Array(None, Some("Wiiii"))) } /* ********* Commands ************ */ "A CommandDefinition" should "form nicely if a valid name is given" in { // cli.command named foo receives () does {_=>} cli.root does {_=>} } it should "throw an IllegalArgumentException if no name is passed" in { an [IllegalArgumentException] should be thrownBy { cli.command named emptyString does {_=>} } } it should "throw an IllegalArgumentException if a name with spaces is passed" in { an [IllegalArgumentException] should be thrownBy { cli.command named s"$foo $bar" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named s" $baz" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named s"$foo " does {_=>} } } it should "throw an IllegalArgumentException if the name starts with the short or long sign of the CommandManager" in { an [IllegalArgumentException] should be thrownBy { cli.command named s"$shortSign$foo" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named s"$longSign$foo" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named s"$shortSign$b" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named s"$longSign$f" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named shortSign does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named longSign does {_=>} } commandManager.setSigns(shortSignAlt, longSignAlt) an [IllegalArgumentException] should be thrownBy { cli.command named s"$shortSignAlt$baz" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named s"$longSignAlt$foo" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named s"$shortSignAlt$g" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named s"$longSignAlt$f" does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named shortSignAlt does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named longSignAlt does {_=>} } } it should "form nicely if the name has short or long sign in the middle or end" in { cli.command named s"$bar$shortSign$baz" does {_=>} cli.command named s"$foo$longSign$baz" does {_=>} cli.command named s"$baz$shortSign" does {_=>} cli.command named s"$bar$longSign" does {_=>} cli.command named s"$g$shortSign" does {_=>} cli.command named s"$b$longSign" does {_=>} cli.command named shortSignAlt does {_=>} commandManager.setSigns(shortSignAlt, longSignAlt) cli.command named s"$bar$shortSignAlt$baz" does {_=>} cli.command named s"$foo$longSignAlt$baz" does {_=>} cli.command named s"$baz$shortSignAlt" does {_=>} cli.command named s"$bar$longSignAlt" does {_=>} cli.command named s"$g$shortSignAlt" does {_=>} cli.command named s"$b$longSignAlt" does {_=>} cli.command named shortSign does {_=>} cli.command named longSign does {_=>} } it should "throw an IllegalArgumentException if two values have the same name" in { an [IllegalArgumentException] should be thrownBy { cli.command named foo receives ( cli.value named bar mandatory, cli.value named bar mandatory ) does {_=>} } an [IllegalArgumentException] should be thrownBy { root receives( cli.value named bar mandatory, cli.value named bar as "barbar" ) does { _ =>} } an [IllegalArgumentException] should be thrownBy { cli.command named foo receives ( cli.value named baz as "one", cli.value named baz as "two" ) does {_=>} } } it should "form nicely if mandatory values are in correct order" in { cli.command named foo receives ( cli.value named foo mandatory, cli.value named bar as "bar", cli.value named baz as "baz" ) does {_=>} root receives ( cli.value named foo mandatory, cli.value named bar mandatory, cli.value named baz as "baz" ) does {_=>} } it should "throw an IllegalArgumentException if mandatory values are not in order" in { an [IllegalArgumentException] should be thrownBy { cli.command named foo receives ( cli.value named foo as "foo", cli.value named bar mandatory, cli.value named baz mandatory ) does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named foo receives ( cli.value named foo as "foo", cli.value named bar mandatory, cli.value named baz as "baz" ) does {_=>} } an [IllegalArgumentException] should be thrownBy { root receives ( cli.value named foo mandatory, cli.value named bar as "bar", cli.value named baz mandatory ) does {_=>} } } it should "form nicely if minimum and maximum number of values are positive and maximum is greater than lower" in { cli.command named foo minimumOf 1 does {_=>} root maximumOf 7 does {_=>} cli.command named bar maximumOf 1 does {_=>} cli.command named baz minimumOf 4 maximumOf 10 does {_=>} cli.command named f minimumOf 1 maximumOf 7 does {_=>} } it should "throw an IllegalArgumentException if minimum number of values is lower than zero" in { an [IllegalArgumentException] should be thrownBy { cli.command named foo minimumOf -1 does {_=>} } an [IllegalArgumentException] should be thrownBy { root minimumOf -5 does {_=>} } } it should "throw an IllegalArgumentException if minimum number of values is zero" in { an [IllegalArgumentException] should be thrownBy { cli.command named foo minimumOf 0 does {_=>} } } it should "throw an IllegalArgumentException if maximum number of values is lower than zero" in { an [IllegalArgumentException] should be thrownBy { root maximumOf -1 does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named foo maximumOf -5 does {_=>} } } it should "throw an IllegalArgumentException if maximum number of values is zero" in { an [IllegalArgumentException] should be thrownBy { cli.command named foo maximumOf 0 does {_=>} } } it should "throw an IllegalArgumentException if minimum number of values is larger or equal than maximum" in { an [IllegalArgumentException] should be thrownBy { cli.command named foo minimumOf 2 maximumOf 1 does {_=>} } an [IllegalArgumentException] should be thrownBy { root minimumOf 7 maximumOf 3 does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.command named foo minimumOf 3 maximumOf 3 does {_=>} } } it should "form nicely if a set of valid arguments and flags are passed" in { cli.command named foo accepts ( flag named foo, flag named bar, arg named baz alias f taking 1 value ) does {_=>} cli.root accepts ( flag named g, flag named bar alias b, arg named foo alias f taking 1 value ) does {_=>} cli.command named bar accepts ( flag named foo, arg named bar alias b taking 3 as (1, 2, 3), arg named baz alias g taking 1 value ) does {_=>} cli.command named baz accepts ( flag named f alias foo, arg named bar alias b taking 1 as "one", arg named baz alias g taking 1 value ) does {_=>} } it should "throw an IllegalArgumentException if a flag or argument have same name" in { an [IllegalArgumentException] should be thrownBy { cli.command named foo accepts ( flag named foo, flag named foo, arg named baz alias f taking 1 value ) does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.root accepts ( flag named g, flag named bar alias b, arg named bar alias f taking 1 value ) does {_=>} } an [IllegalArgumentException] should be thrownBy { cli.root accepts( flag named bar alias b, arg named f taking 1 as "one", arg named f alias baz taking 1 value ) does { _ =>} } } it should "throw an IllegalArgumentException if a command with the same name is defined twice" in { an[IllegalArgumentException] should be thrownBy { cli.command named foo does { _ =>} cli.command named foo does { _ =>} } } it should "throw an IllegalArgumentException if the root command is defined twice" in { an[IllegalArgumentException] should be thrownBy { root does { _ =>} root does { _ =>} } } }
alanrodas/scaland
cli/src/test/scala/com/alanrodas/scaland/cli/BuildersSpec.scala
Scala
apache-2.0
29,738
package scutil.lang import scutil.lang.tc._ // TODO 213 PartialFunction will have unapply there, do we still need this? object Extractor { def total[S,T](func:S=>T):Extractor[S,T] = Extractor(s => Some(func(s))) def partial[S,T](func:PartialFunction[S,T]):Extractor[S,T] = Extractor(func.lift) def filtered[T](pred:Predicate[T]):Extractor[T,T] = Extractor(it => if (pred(it)) Some(it) else None) def identity[T]:Extractor[T,T] = Extractor(Some.apply) def trivial[T]:Extractor[T,Any] = Extractor(constant(None)) implicit def ExtractorFunctor[S]:Functor[Extractor[S,_]] = new Functor[Extractor[S,_]] { def map[A,B](it:Extractor[S,A])(func:A=>B):Extractor[S,B] = it map func } //------------------------------------------------------------------------------ //## typeclass instances implicit def ExtractorSemigroup[S,T]:Semigroup[Extractor[S,T]] = Semigroup instance (_ orElse _) } /** representative extractor (as opposed to compiler magic) */ final case class Extractor[S,T](read:S=>Option[T]) { def unapply(s:S):Option[T] = read(s) /** symbolic alias for andThen */ def >=>[U](that:Extractor[T,U]):Extractor[S,U] = this andThen that /** symbolic alias for compose */ def <=<[R](that:Extractor[R,S]):Extractor[R,T] = this compose that def compose[R](that:Extractor[R,S]):Extractor[R,T] = that andThen this def andThen[U](that:Extractor[T,U]):Extractor[S,U] = Extractor(s => this read s flatMap that.read) def orElse(that:Extractor[S,T]):Extractor[S,T] = Extractor(s => (this read s) orElse (that read s)) def map[U](func:T=>U):Extractor[S,U] = Extractor(s => read(s) map func) def contraMap[R](func:R=>S):Extractor[R,T] = Extractor(func andThen read) def filter(pred:T=>Boolean):Extractor[S,T] = Extractor(s => read(s) filter pred) def contraFilter(pred:S=>Boolean):Extractor[S,T] = Extractor(s => if (pred(s)) read(s) else None) def toPFunction:S=>Option[T] = s => read(s) def toPartialFunction:PartialFunction[S,T] = Function unlift read }
ritschwumm/scutil
modules/core/src/main/scala/scutil/lang/Extractor.scala
Scala
bsd-2-clause
2,026
import scala.quoted._ object MacroRuntime { def impl()(using q: Quotes): Expr[Unit] = { import quotes.reflect._ report.error("some error", Position.ofMacroExpansion) '{ println("Implementation in MacroCompileError") } } }
dotty-staging/dotty
sbt-test/source-dependencies/macro-expansion-dependencies-2/changes/MacroRuntimeCompileError.scala
Scala
apache-2.0
249
package chapter08 object CodeReduction { def main(args: Array[String]): Unit = { val nos = List(-11, 10, -2, 5, 25, -32, 55) //filtering the list println(nos.filter((x: Int) => x > 0)) //target typing in the filter println(nos.filter(x => x > 0)) //using _ instead of variable(placeholder syntax) println(nos.filter(_ > 0)) //Type is necessary if the compiler cant infer it from code val f = (_: Int) + (_: Int) println(f(5, 15)) } }
aakashmathai/ScalaTutorial
src/main/scala/chapter08/CodeReduction.scala
Scala
apache-2.0
483
package wow.realm.events import scodec.bits.BitVector import wow.realm.entities.CharacterRef import wow.realm.protocol.payloads.ClientMovement import scala.collection.mutable /** * World events */ sealed trait WorldEvent case class PlayerJoined(character: CharacterRef) extends WorldEvent case class Tick(number: Long, msTime: Long, previousTick: Tick) extends WorldEvent case class DispatchWorldUpdate(events: mutable.MutableList[WorldEvent]) extends WorldEvent case class PlayerMoved(payload: ClientMovement, headerBits: BitVector, payloadBits: BitVector) extends WorldEvent
SKNZ/SpinaciCore
wow/core/src/main/scala/wow/realm/events/WorldEvent.scala
Scala
mit
588
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.spark.sql.hive.orc.abfs import com.cloudera.spark.cloud.abfs.AbfsTestSetup import org.apache.spark.sql.sources.CloudPartitionTest /** * Partitioned queries with ORC data against ABFS. */ class AbfsOrcPartitionSuite extends CloudPartitionTest with AbfsTestSetup { init() def init(): Unit = { if (enabled) { initFS() } } override def dataSourceName(): String = { "orc" } }
hortonworks-spark/cloud-integration
cloud-examples/src/test/scala/org/apache/spark/sql/hive/orc/abfs/AbfsOrcPartitionSuite.scala
Scala
apache-2.0
1,228
package mesosphere.marathon package api import java.util.concurrent.atomic.AtomicInteger import javax.inject.Provider import akka.event.EventStream import mesosphere.AkkaUnitTestLike import mesosphere.marathon.core.group.GroupManagerModule import mesosphere.marathon.state.RootGroup import mesosphere.marathon.storage.repository.GroupRepository import mesosphere.marathon.test.Mockito import scala.concurrent.Future import mesosphere.marathon.core.async.ExecutionContexts import mesosphere.AkkaUnitTestLike class TestGroupManagerFixture( initialRoot: RootGroup = RootGroup.empty, authenticated: Boolean = true, authorized: Boolean = true, authFn: Any => Boolean = _ => true) extends Mockito with AkkaUnitTestLike { val service = mock[MarathonSchedulerService] val groupRepository = mock[GroupRepository] val eventBus = mock[EventStream] val authFixture = new TestAuthFixture() authFixture.authenticated = authenticated authFixture.authorized = authorized authFixture.authFn = authFn implicit val authenticator = authFixture.auth val config = AllConf.withTestConfig("--zk_timeout", "3000") val actorId = new AtomicInteger(0) val schedulerProvider = new Provider[DeploymentService] { override def get() = service } groupRepository.root() returns Future.successful(initialRoot) private[this] val groupManagerModule = new GroupManagerModule( config = config, scheduler = schedulerProvider, groupRepo = groupRepository)(ExecutionContexts.global, eventBus, authenticator) val groupManager = groupManagerModule.groupManager }
janisz/marathon
src/test/scala/mesosphere/marathon/api/TestGroupManagerFixture.scala
Scala
apache-2.0
1,593
package com.catinthedark.yoba.records import scala.math.Ordering.FloatOrdering /** * Created by over on 23.08.15. */ case class Record(time: Int, name: String, country: String) extends Ordered[Record] { val floatOrdering = new FloatOrdering {} override def compare(that: Record): Int = floatOrdering.compare(time, that.time) }
cat-in-the-dark/old48_33_game
src/main/scala/com/catinthedark/yoba/records/Record.scala
Scala
mit
339
package com.lyrx.latex import java.io.File import com.lyrx.text.{Context, GenBase, StringSerializer} /** * Created by alex on 28.12.16. */ trait LaTeXOutputter { val generator:GenBase[String] def assertLaTeX(output: Either[File, String]) = output match { case Left(aFile: File) => println ("Wrote " +aFile) case Right(aMessage: String) => println (aMessage) } def pdf(aFileName: String )(implicit context: Context): Either[File, String] = { new StringSerializer(generator).serialize(aFileName) LTXPDFProcessor()(context.outputIsInput()).process(aFileName).output() } def pdf2(aFileName: String )(implicit context: Context): Either[File, String] = { new StringSerializer(generator).serialize(aFileName) LTXPDFProcessor()(context.outputIsInput()).process(aFileName).process(aFileName). output() } }
lyrx/lyrxgenerator
src/main/scala/com/lyrx/latex/LaTeXOutputter.scala
Scala
gpl-3.0
856
package priv.sp.house import priv.sp._ import priv.sp.CardSpec._ import priv.sp.GameCardEffect._ import priv.sp.update.{SlotUpdate, PlayerUpdate} import priv.util.FuncDecorators object Kinetician extends ChangeTarget { val manipulator = new Creature("kinetician.manipulator", Attack(3), 28, I18n("kinetician.manipulator.description"), effects = effects(Direct -> manipulate), reaction = new ManipulatorReaction) val Kinetician = House("kinetician", List( new Creature("kinetician.magerunner", Attack(4), 10, I18n("kinetician.magerunner.description"), effects = effects(Direct -> mage)), new Creature("kinetician.tricker", Attack(4), 10, I18n("kinetician.tricker.description"), effects = effects(OnTurn -> trick)), Spell("kinetician.force", I18n("kinetician.force.description"), inputSpec = Some(SelectTargetCreature), effects = effects(Direct -> focus)), Spell("kinetician.warp", I18n("kinetician.warp.description"), inputSpec = Some(SelectTargetCreature), effects = effects(Direct -> warp)), new Creature("kinetician.mage", Attack(7), 22, I18n("kinetician.mage.description"), effects = effects(OnTurn -> lone)), Spell("kinetician.call", I18n("kinetician.call.description"), inputSpec = Some(SelectOwner(nonSpecial)), effects = effects(Direct -> fittest)), Spell("kinetician.barrier", I18n("kinetician.barrier.description"), inputSpec = Some(SelectOwnerCreature), effects = effects(Direct -> forceBarrier)), manipulator), data = Targeting(None), eventListener = Some(new CustomListener(new KineticianListener))) Kinetician.initCards(Houses.basicCostFunc) def mage = { env : Env => import env._ player.slots.foldl(Option.empty[SlotUpdate]) { case (acc, s) if s.num == selected => acc case (None, s) => Some(s) case (acc @ Some(s0), s) => if (s.get.attack > s0.get.attack) Some(s) else acc }.foreach { s ⇒ player.slots.move(selected, s.num) } } def trick = { env : Env => import env._ nearestSlotOpposed(selected, player, opposed = false) foreach { n ⇒ player.slots.move(selected, n) } } def lone = { env : Env => val nbEmpty = env.otherPlayer.slots.slots.count(_.value.isEmpty) env.otherPlayer inflict Damage(nbEmpty, env, isAbility = true) env.focus() } def fittest = { env : Env => val slot = env.getOwnerSelectedSlot() val houseIndex = slot.get.card.houseIndex val cards = env.player.value.desc.get.houses(houseIndex).cards.map(_.card) env.player.addDescMod(cards.map { c => HalveCardCost(c)} : _ *) } def forceBarrier = { env : Env => val slot = env.getOwnerSelectedSlot() val slotState = slot.get slot write Some(slotState.copy( life = slotState.life * 2, maxLife = slotState.maxLife * 2, status = slotState.status - CardSpec.runFlag)) } def warp = { env : Env => val slot = env.getTargetSelectedSlot() val slotState = slot.get if (slotState.life > slotState.card.cost) { slot write Some(slotState.copy(life = slotState.card.cost)) } } val focusBonus = AttackAdd(1) def focus = { env : Env => env.player.slots foreach (_.attack add focusBonus) changeTarget(env) env.player addEffect (OnEndTurn -> oneTimePlayerEffect { env : Env => env.player.slots foreach (_.attack removeFirstEq focusBonus) }) } val attack3 = SetAttack(3) def manipulate = { env : Env => env.otherPlayer.slots foreach (_.attack add attack3) env.otherPlayer addEffect (OnEndTurn -> { env : Env => env.player.slots foreach (_.attack removeFirstEq attack3) }) } class ManipulatorReaction extends Reaction { final def afterSubmit(slotIdOption : Option[Int]) = { slotIdOption foreach { slotId => selected.otherPlayer.slots.slots.find(s => s.value.isDefined && s.get.id == slotId) foreach { slot => val slotState = slot.get if (selected.slots.getOpenSlots.size > 0 || slotState.card.cost * 4 >= selected.get.life) { selected inflict Damage(4 * slotState.card.cost, Context(selected.playerId, Some(manipulator), selected.num), isAbility = true) val openSlots = selected.slots.getOpenSlots val targetSlot = openSlots.find(_.num == slot.num) getOrElse openSlots.head selected.otherPlayer.slots.move(slot.num, targetSlot.num, selected.playerId) } } } } } def getTargeting(player : PlayerUpdate) : Targeting = player.pstate.data.asInstanceOf[Targeting] def setTarget(player : PlayerUpdate, target : Option[Int] ) : Unit = player.updateData[Targeting](x ⇒ x.copy(target = target)) class KineticianListener extends ChangeTargetListener { override def init(p: PlayerUpdate) { super.init(p) p.otherPlayer.submitCommand = (FuncDecorators decorate p.otherPlayer.submitCommand) after2 { (command, slotIdOption) => player.slots.foreach { slot => slot.get.reaction match { case manip : ManipulatorReaction => manip afterSubmit slotIdOption case _ => } } } p.submitCommand = (FuncDecorators decorate p.submitCommand) after { command => if (player.pstate.desc.descMods.nonEmpty) { player.removeDescMod(HalveCardCost(command.card)) } } } } } case class HalveCardCost(card : Card) extends DescMod { def apply(house: House, cards: Vector[CardDesc]): Vector[CardDesc] = { if (house.houseIndex == card.houseIndex) cards.map(c ⇒ if (c.card == card) c.copy(cost = c.cost / 2) else c) else cards } }
illim/freespectrogdx
core/src/main/scala/priv/sp/house/Kinetician.scala
Scala
gpl-3.0
5,726
package fpinscala.state2 trait RNG { def nextInt: (Int, RNG) } case class SimpleRNG(seed: Long) extends RNG { def nextInt: (Int, RNG) = { val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL val nextRNG = SimpleRNG(newSeed) val n = (newSeed >>> 16).toInt (n, nextRNG) } } object RNG { type Rand[+A] = RNG => (A, RNG) def nonNegativeInt(rng: RNG): (Int, RNG) = { val (i, nextRNG) = rng.nextInt if (i < 0) { (-(i+1), nextRNG) } else { (i, nextRNG) } } def double(rng: RNG): (Double, RNG) = { val (i, nextRNG) = nonNegativeInt(rng) (i / (Int.MaxValue.toDouble + 1), nextRNG) } def intDouble(rng: RNG): ((Int, Double), RNG) = { val (i, rng1) = rng.nextInt val (d, rng2) = double(rng) ((i, d), rng2) } def doubleInt(rng: RNG): ((Double, Int), RNG) = { val (d, rng1) = double(rng) val (i, rng2) = rng1.nextInt ((d, i), rng2) } def double3(rng: RNG): ((Double, Double, Double), RNG) = { val (d1, rng1) = double(rng) val (d2, rng2) = double(rng1) val (d3, rng3) = double(rng2) ((d1, d2, d3), rng3) } }
mebubo/fpinscala
exercises/src/main/scala/fpinscala/state2/State.scala
Scala
mit
1,132
/* * OpenURP, Open University Resouce Planning * * Copyright (c) 2013-2014, OpenURP Software. * * OpenURP is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenURP is distributed in the hope that it will be useful. * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Beangle. If not, see <http://www.gnu.org/licenses/>. */ package org.openurp.ws.services.teach.attendance.impl import org.beangle.commons.bean.Initializing import org.beangle.commons.cache.{ Cache, CacheManager } import org.beangle.data.jdbc.query.JdbcExecutor import org.openurp.ws.services.teach.attendance.domain.DateFormats._ import org.openurp.ws.services.teach.attendance.model.CourseBean import java.sql.Date /** * 基础数据服务 * * @author chaostone * @version 1.0, 2014/03/22 * @since 0.0.1 */ class BaseDataService extends Initializing { var executor: JdbcExecutor = _ var cacheManager: CacheManager = _ private var semesterCache: Cache[String, Int] = _ private var courseCache: Cache[Number, CourseBean] = _ private var teacherCache: Cache[Number, String] = _ private var adminclassCache: Cache[Number, String] = _ def isHoliday(date: Date): Boolean = { !executor.query("select id from holidays d where d.date_on=?", date).isEmpty } def getSemesterId(date: Date): Option[Int] = { val dateStr = toDateStr(date) var rs = semesterCache.get(dateStr) if (rs.isEmpty) { val ids = executor.query("select rl.id from JXRL_T rl where ? between rl.qssj and rl.jzsj", date) for (ida <- ids; ido <- ida) { val id = ido.asInstanceOf[Number].intValue() semesterCache.put(dateStr, id) rs = Some(id) } } rs } def getTeacherName(id: Number): String = { var rs = teacherCache.get(id) var teacherName = "" if (rs.isEmpty) { val names = executor.query("select a.xm from JCXX_JZG_T a where a.id=?", id) for (name <- names) { teacherName = name.head.toString teacherCache.put(id, teacherName) } } teacherName } def getAdminclassName(id: Number): String = { var adminclassName = "" if (id != null) { var rs = adminclassCache.get(id) if (rs.isEmpty) { val names = executor.query("select a.bjmc from jcxx_bj_t a where a.id=?", id) for (name <- names) { adminclassName = name.head.toString adminclassCache.put(id, adminclassName) } } } adminclassName } def getCourse(id: Number): Option[CourseBean] = { var rs = courseCache.get(id) if (rs.isEmpty) { val names = executor.query("select a.id,a.kcdm,a.kcmc from JCXX_kc_T a where a.id=?", id.longValue()) for (name <- names) { val course = new CourseBean(name(0).asInstanceOf[Number].longValue, name(1).toString, name(2).toString) courseCache.put(id, course) rs = Some(course) } } rs } def init() { semesterCache = cacheManager.getCache("semester") courseCache = cacheManager.getCache("course") teacherCache = cacheManager.getCache("teacher") adminclassCache = cacheManager.getCache("adminclass") } }
openurp/edu-attendance-core
attendance/src/main/scala/org/openurp/ws/services/teach/attendance/impl/BaseDataService.scala
Scala
gpl-3.0
3,538
package objsets /** * The interface used by the grading infrastructure. Do not change signatures * or your submission will fail with a NoSuchMethodError. */ trait TweetSetInterface { def incl(tweet: Tweet): TweetSet def remove(tweet: Tweet): TweetSet def contains(tweet: Tweet): Boolean def foreach(f: Tweet => Unit): Unit def union(that: TweetSet): TweetSet def mostRetweeted: Tweet def descendingByRetweet: TweetList }
rusucosmin/courses
fp/4-object-oriented-sets-rusucosmin/src/main/scala/objsets/TweetSetInterface.scala
Scala
mit
439
import scala.quoted._ import scala.quoted.autolift object Macros { implicit inline def withSource(arg: Any): (String, Any) = ${ impl('arg) } private def impl(arg: Expr[Any])(using qctx: QuoteContext) : Expr[(String, Any)] = { import qctx.tasty._ val source = arg.unseal.underlyingArgument.pos.sourceCode.toString '{Tuple2($source, $arg)} } }
som-snytt/dotty
tests/run-macros/tasty-original-source/Macros_1.scala
Scala
apache-2.0
364
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.spark.sql.execution import java.util.concurrent.atomic.AtomicLong import org.apache.spark.SparkContext import org.apache.spark.sql.SQLContext import org.apache.spark.sql.ui.SparkPlanGraph import org.apache.spark.util.Utils private[sql] object SQLExecution { val EXECUTION_ID_KEY = "spark.sql.execution.id" private val _nextExecutionId = new AtomicLong(0) private def nextExecutionId: Long = _nextExecutionId.getAndIncrement /** * Wrap an action that will execute "queryExecution" to track all Spark jobs in the body so that * we can connect them with an execution. */ def withNewExecutionId[T]( sqlContext: SQLContext, queryExecution: SQLContext#QueryExecution)(body: => T): T = { val sc = sqlContext.sparkContext val oldExecutionId = sc.getLocalProperty(EXECUTION_ID_KEY) if (oldExecutionId == null) { val executionId = SQLExecution.nextExecutionId sc.setLocalProperty(EXECUTION_ID_KEY, executionId.toString) val r = try { val callSite = Utils.getCallSite() sqlContext.listener.onExecutionStart( executionId, callSite.shortForm, callSite.longForm, queryExecution.toString, SparkPlanGraph(queryExecution.executedPlan), System.currentTimeMillis()) try { body } finally { // Ideally, we need to make sure onExecutionEnd happens after onJobStart and onJobEnd. // However, onJobStart and onJobEnd run in the listener thread. Because we cannot add new // SQL event types to SparkListener since it's a public API, we cannot guarantee that. // // SQLListener should handle the case that onExecutionEnd happens before onJobEnd. // // The worst case is onExecutionEnd may happen before onJobStart when the listener thread // is very busy. If so, we cannot track the jobs for the execution. It seems acceptable. sqlContext.listener.onExecutionEnd(executionId, System.currentTimeMillis()) } } finally { sc.setLocalProperty(EXECUTION_ID_KEY, null) } r } else { // Don't support nested `withNewExecutionId`. This is an example of the nested // `withNewExecutionId`: // // class DataFrame { // def foo: T = withNewExecutionId { something.createNewDataFrame().collect() } // } // // Note: `collect` will call withNewExecutionId // In this case, only the "executedPlan" for "collect" will be executed. The "executedPlan" // for the outer DataFrame won't be executed. So it's meaningless to create a new Execution // for the outer DataFrame. Even if we track it, since its "executedPlan" doesn't run, // all accumulator metrics will be 0. It will confuse people if we show them in Web UI. // // A real case is the `DataFrame.count` method. throw new IllegalArgumentException(s"$EXECUTION_ID_KEY is already set") } } /** * Wrap an action with a known executionId. When running a different action in a different * thread from the original one, this method can be used to connect the Spark jobs in this action * with the known executionId, e.g., `BroadcastHashJoin.broadcastFuture`. */ def withExecutionId[T](sc: SparkContext, executionId: String)(body: => T): T = { val oldExecutionId = sc.getLocalProperty(SQLExecution.EXECUTION_ID_KEY) try { sc.setLocalProperty(SQLExecution.EXECUTION_ID_KEY, executionId) body } finally { sc.setLocalProperty(SQLExecution.EXECUTION_ID_KEY, oldExecutionId) } } }
andrewor14/iolap
sql/core/src/main/scala/org/apache/spark/sql/execution/SQLExecution.scala
Scala
apache-2.0
4,443
// Copyright 2017 EPFL DATA Lab (data.epfl.ch) // // 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 squid.utils import squid.lib.{transparencyPropagating, transparent} /** Cheap Lazy implementation for pure computations */ final class Lazy[+A <: AnyRef](vl: () => A, computeWhenShow: Boolean) { private[this] var computedValue: A = null.asInstanceOf[A] private[this] var computing = false def isComputing = computing def computed = computedValue != null @transparent def value = { if (computedValue == null) { val wasComputing = computing computing = true try computedValue = vl() finally computing = wasComputing } computedValue } @transparencyPropagating def `internal pure value` = value // TODO doc def internal_pure_value = value // TODO doc override def toString = s"Lazy(${if (computed || computeWhenShow) value else "..."})" } object Lazy { @transparencyPropagating def apply[A <: AnyRef](vl: => A): Lazy[A] = mk(vl, true) @transparencyPropagating def mk[A <: AnyRef](vl: => A, computeWhenShow: Bool) = new Lazy(() => vl, computeWhenShow) }
epfldata/squid
core/src/main/scala/squid/utils/Lazy.scala
Scala
apache-2.0
1,636
package org.jetbrains.plugins.scala.util object JvmOptions { def addOpens(modulePackageList: String*): Seq[String] = modulePackageList.flatMap { modulePackage => Seq("--add-opens", s"$modulePackage=ALL-UNNAMED") } }
JetBrains/intellij-scala
scala/scala-impl/src/org/jetbrains/plugins/scala/util/JvmOptions.scala
Scala
apache-2.0
234
/** * Created on: Dec 7, 2013 */ package com.iteamsolutions.angular.models.atom /** * The '''Person''' type is the Domain Object Model reification of the * [[http://www.ietf.org/rfc/rfc4287.txt Person]] concept. * * @author svickers * */ trait Person { /// Instance Properties def name : String; def uri : Option[URI]; def email : Option[URI]; }
osxhacker/angular-codegen
src/main/scala/com/iteamsolutions/angular/models/atom/Person.scala
Scala
bsd-2-clause
361
package uk.org.nbn.nbnv.importer.validation import uk.org.nbn.nbnv.importer.records.NbnRecord import uk.org.nbn.nbnv.importer.fidelity.{ResultLevel, Result} import uk.org.nbn.nbnv.importer.utility.StringParsing._ import collection.mutable.ListBuffer //validate the "<D" date type class Nbnv194Validator extends DateFormatValidator { def code = "NBNV-194" def validate(record: NbnRecord) = { val results = new ListBuffer[Result] if (record.startDate.isDefined) { results.append( new Result { def level: ResultLevel.ResultLevel = ResultLevel.ERROR def reference: String = record.key def message: String = "%s: A start date should not be specified for date type '%s'".format(code, record.dateType) }) } else { val validFormats = List("dd/MM/yyyy", "dd-MM-yyyy", "yyyy/MM/dd", "yyyy-MM-dd", "dd MMM yyyy") results.appendAll(validateDate(record,false,true,validFormats)) } results.toList } }
JNCC-dev-team/nbn-importer
importer/src/main/scala/uk/org/nbn/nbnv/importer/validation/Nbnv194Validator.scala
Scala
apache-2.0
1,020
package io.taig.android.monix.syntax import io.taig.android.monix.operation import monix.eval.Task import scala.language.implicitConversions trait task { implicit def monixTaskSyntax[T]( task: Task[T] ): operation.task[T] = new operation.task[T](task) implicit def monixTaskCompanionSyntax( task: Task.type ): operation.task.companion = new operation.task.companion(task) } object task extends task
Taig/Toolbelt
monix/src/main/scala/io/taig/android/monix/syntax/task.scala
Scala
mit
424
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 kafka.integration import java.util.concurrent._ import java.util.concurrent.atomic._ import scala.collection._ import junit.framework.Assert._ import kafka.cluster._ import kafka.server._ import org.scalatest.junit.JUnit3Suite import kafka.consumer._ import kafka.serializer._ import kafka.producer.{KeyedMessage, Producer} import kafka.utils.TestUtils class FetcherTest extends JUnit3Suite with KafkaServerTestHarness { val numNodes = 1 def generateConfigs() = TestUtils.createBrokerConfigs(numNodes, zkConnect).map(KafkaConfig.fromProps) val messages = new mutable.HashMap[Int, Seq[Array[Byte]]] val topic = "topic" val queue = new LinkedBlockingQueue[FetchedDataChunk] var fetcher: ConsumerFetcherManager = null override def setUp() { super.setUp TestUtils.createTopic(zkClient, topic, partitionReplicaAssignment = Map(0 -> Seq(configs.head.brokerId)), servers = servers) val cluster = new Cluster(servers.map(s => new Broker(s.config.brokerId, "localhost", s.boundPort()))) fetcher = new ConsumerFetcherManager("consumer1", new ConsumerConfig(TestUtils.createConsumerProperties("", "", "")), zkClient) fetcher.stopConnections() val topicInfos = configs.map(c => new PartitionTopicInfo(topic, 0, queue, new AtomicLong(0), new AtomicLong(0), new AtomicInteger(0), "")) fetcher.startConnections(topicInfos, cluster) } override def tearDown() { fetcher.stopConnections() super.tearDown } def testFetcher() { val perNode = 2 var count = TestUtils.sendMessages(servers, topic, perNode).size fetch(count) assertQueueEmpty() count = TestUtils.sendMessages(servers, topic, perNode).size fetch(count) assertQueueEmpty() } def assertQueueEmpty(): Unit = assertEquals(0, queue.size) def fetch(expected: Int) { var count = 0 while(true) { val chunk = queue.poll(2L, TimeUnit.SECONDS) assertNotNull("Timed out waiting for data chunk " + (count + 1), chunk) for(message <- chunk.messages) count += 1 if(count == expected) return } } }
tempbottle/kafka
core/src/test/scala/unit/kafka/integration/FetcherTest.scala
Scala
apache-2.0
2,949
package com.mogproject.mogami.core.state import com.mogproject.mogami._ import com.mogproject.mogami.core.PieceConstant._ import com.mogproject.mogami.core.SquareConstant._ import com.mogproject.mogami.core.state.State.PromotionFlag._ import com.mogproject.mogami.util.Implicits._ import com.mogproject.mogami.util.MapUtil import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers class StateSpec extends AnyFlatSpec with Matchers with ScalaCheckDrivenPropertyChecks { val dataForTest = Seq( State.HIRATE, State.empty, State(WHITE, Map( P11 -> WL, P21 -> WN, P22 -> WS, P32 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P82 -> WR, P14 -> WP, P23 -> WP, P34 -> WP, P43 -> WP, P53 -> WP, P63 -> BPB, P73 -> WP, P83 -> WP, P93 -> WP, P16 -> BP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P75 -> BP, P87 -> BP, P97 -> BP, P19 -> BL, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P58 -> BG, P78 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS ++ Map(BP -> 1, BB -> 1, WP -> 1, WR -> 1).mapKeys(Hand.apply)), State(BLACK, Map( P11 -> WPL, P21 -> WPN, P31 -> WPS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WPS, P81 -> WPN, P91 -> WPL, P22 -> WPB, P82 -> WPR, P13 -> WPP, P23 -> WPP, P33 -> WPP, P43 -> WPP, P53 -> WPP, P63 -> WPP, P73 -> WPP, P83 -> WPP, P93 -> WPP, P17 -> BPP, P27 -> BPP, P37 -> BPP, P47 -> BPP, P57 -> BPP, P67 -> BPP, P77 -> BPP, P87 -> BPP, P97 -> BPP, P28 -> BPR, P88 -> BPB, P19 -> BPL, P29 -> BPN, P39 -> BPS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BPS, P89 -> BPN, P99 -> BPL ), State.EMPTY_HANDS), State(BLACK, Map(P51 -> WK), State.EMPTY_HANDS ++ Map(BP -> 18, BL -> 4, BN -> 4, BS -> 4, BG -> 4, BB -> 2, BR -> 2).mapKeys(Hand.apply)), State(WHITE, Map(P59 -> BK), State.EMPTY_HANDS ++ Map(WP -> 18, WL -> 4, WN -> 4, WS -> 4, WG -> 4, WB -> 2, WR -> 2).mapKeys(Hand.apply)) ) val csaForTest = Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n" + "P2 * -HI * * * * * -KA * \n" + "P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n" + "P4 * * * * * * * * * \n" + "P5 * * * * * * * * * \n" + "P6 * * * * * * * * * \n" + "P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n" + "P8 * +KA * * * * * +HI * \n" + "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n" + "P+\n" + "P-\n" + "+", "P1 * * * * * * * * * \n" + "P2 * * * * * * * * * \n" + "P3 * * * * * * * * * \n" + "P4 * * * * * * * * * \n" + "P5 * * * * * * * * * \n" + "P6 * * * * * * * * * \n" + "P7 * * * * * * * * * \n" + "P8 * * * * * * * * * \n" + "P9 * * * * * * * * * \n" + "P+\n" + "P-\n" + "+", "P1-KY-KE-GI-KI-OU * * -KE-KY\n" + "P2 * -HI * * * * -KI-GI * \n" + "P3-FU-FU-FU+UM-FU-FU * -FU * \n" + "P4 * * * * * * -FU * -FU\n" + "P5 * * +FU * * * * * * \n" + "P6 * * * * * * * * +FU\n" + "P7+FU+FU * * +FU+FU+FU+FU * \n" + "P8 * * +GI * +KI * * * * \n" + "P9+KY+KE * * +OU+KI+GI+KE+KY\n" + "P+00KA00FU\n" + "P-00HI00FU\n" + "-", "P1-NY-NK-NG-KI-OU-KI-NG-NK-NY\n" + "P2 * -RY * * * * * -UM * \n" + "P3-TO-TO-TO-TO-TO-TO-TO-TO-TO\n" + "P4 * * * * * * * * * \n" + "P5 * * * * * * * * * \n" + "P6 * * * * * * * * * \n" + "P7+TO+TO+TO+TO+TO+TO+TO+TO+TO\n" + "P8 * +UM * * * * * +RY * \n" + "P9+NY+NK+NG+KI+OU+KI+NG+NK+NY\n" + "P+\n" + "P-\n" + "+", "P1 * * * * -OU * * * * \n" + "P2 * * * * * * * * * \n" + "P3 * * * * * * * * * \n" + "P4 * * * * * * * * * \n" + "P5 * * * * * * * * * \n" + "P6 * * * * * * * * * \n" + "P7 * * * * * * * * * \n" + "P8 * * * * * * * * * \n" + "P9 * * * * * * * * * \n" + "P+00HI00HI00KA00KA00KI00KI00KI00KI00GI00GI00GI00GI00KE00KE00KE00KE" + "00KY00KY00KY00KY00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU" + "00FU00FU00FU00FU00FU00FU\n" + "P-\n" + "+", "P1 * * * * * * * * * \n" + "P2 * * * * * * * * * \n" + "P3 * * * * * * * * * \n" + "P4 * * * * * * * * * \n" + "P5 * * * * * * * * * \n" + "P6 * * * * * * * * * \n" + "P7 * * * * * * * * * \n" + "P8 * * * * * * * * * \n" + "P9 * * * * +OU * * * * \n" + "P+\n" + "P-00HI00HI00KA00KA00KI00KI00KI00KI00GI00GI00GI00GI00KE00KE00KE00KE" + "00KY00KY00KY00KY00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU" + "00FU00FU00FU00FU00FU00FU\n" + "-" ) val kifForTest = Seq( Seq( "後手の持駒:なし", " 9 8 7 6 5 4 3 2 1", "+---------------------------+", "|v香v桂v銀v金v玉v金v銀v桂v香|一", "| ・v飛 ・ ・ ・ ・ ・v角 ・|二", "|v歩v歩v歩v歩v歩v歩v歩v歩v歩|三", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|四", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|五", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|六", "| 歩 歩 歩 歩 歩 歩 歩 歩 歩|七", "| ・ 角 ・ ・ ・ ・ ・ 飛 ・|八", "| 香 桂 銀 金 玉 金 銀 桂 香|九", "+---------------------------+", "先手の持駒:なし" ), Seq( "後手の持駒:なし", " 9 8 7 6 5 4 3 2 1", "+---------------------------+", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|一", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|二", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|三", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|四", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|五", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|六", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|七", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|八", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|九", "+---------------------------+", "先手の持駒:なし" ), Seq( "後手の持駒:飛 歩 ", " 9 8 7 6 5 4 3 2 1", "+---------------------------+", "|v香v桂v銀v金v玉 ・ ・v桂v香|一", "| ・v飛 ・ ・ ・ ・v金v銀 ・|二", "|v歩v歩v歩 馬v歩v歩 ・v歩 ・|三", "| ・ ・ ・ ・ ・ ・v歩 ・v歩|四", "| ・ ・ 歩 ・ ・ ・ ・ ・ ・|五", "| ・ ・ ・ ・ ・ ・ ・ ・ 歩|六", "| 歩 歩 ・ ・ 歩 歩 歩 歩 ・|七", "| ・ ・ 銀 ・ 金 ・ ・ ・ ・|八", "| 香 桂 ・ ・ 玉 金 銀 桂 香|九", "+---------------------------+", "先手の持駒:角 歩 ", "後手番" ), Seq( "後手の持駒:なし", " 9 8 7 6 5 4 3 2 1", "+---------------------------+", "|v杏v圭v全v金v玉v金v全v圭v杏|一", "| ・v龍 ・ ・ ・ ・ ・v馬 ・|二", "|vとvとvとvとvとvとvとvとvと|三", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|四", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|五", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|六", "| と と と と と と と と と|七", "| ・ 馬 ・ ・ ・ ・ ・ 龍 ・|八", "| 杏 圭 全 金 玉 金 全 圭 杏|九", "+---------------------------+", "先手の持駒:なし" ), Seq( "後手の持駒:なし", " 9 8 7 6 5 4 3 2 1", "+---------------------------+", "| ・ ・ ・ ・v玉 ・ ・ ・ ・|一", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|二", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|三", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|四", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|五", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|六", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|七", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|八", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|九", "+---------------------------+", "先手の持駒:飛二 角二 金四 銀四 桂四 香四 歩十八 " ), Seq( "後手の持駒:飛二 角二 金四 銀四 桂四 香四 歩十八 ", " 9 8 7 6 5 4 3 2 1", "+---------------------------+", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|一", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|二", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|三", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|四", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|五", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|六", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|七", "| ・ ・ ・ ・ ・ ・ ・ ・ ・|八", "| ・ ・ ・ ・ 玉 ・ ・ ・ ・|九", "+---------------------------+", "先手の持駒:なし", "後手番" ) ).map(_.mkString("\n")) "State#apply" must "throw an error when the requirements do not meet" in { assertThrows[IllegalArgumentException](State(BLACK, Map.empty, State.EMPTY_HANDS ++ Map(Hand(BP) -> 19))) assertThrows[IllegalArgumentException](State(BLACK, Map.empty, Map(Hand(BP) -> 1))) assertThrows[IllegalArgumentException](State(BLACK, Map(P11 -> BP), State.EMPTY_HANDS)) assertThrows[IllegalArgumentException](State(BLACK, Map(P11 -> WK, P12 -> BP), State.EMPTY_HANDS)) assertThrows[IllegalArgumentException](State(BLACK, Map(P56 -> BP, P55 -> BP), State.EMPTY_HANDS)) // nifu assertThrows[IllegalArgumentException](State(BLACK, Map(P11 -> WP, P12 -> WP, P13 -> WP), State.EMPTY_HANDS)) // nifu assertThrows[IllegalArgumentException](State(BLACK, Map(P11 -> WP, P12 -> WP, P13 -> WP, P14 -> BP, P15 -> BP), State.EMPTY_HANDS)) // nifu } "State#toCsaString" must "describe the state" in { dataForTest(0).toCsaString mustBe csaForTest(0) dataForTest(1).toCsaString mustBe csaForTest(1) dataForTest(2).toCsaString mustBe csaForTest(2) dataForTest(3).toCsaString mustBe csaForTest(3) dataForTest(4).toCsaString mustBe csaForTest(4) dataForTest(5).toCsaString mustBe csaForTest(5) } it must "restore states" in forAll(StateGen.statesWithFullPieces) { st => State.parseCsaString(st.toCsaString) mustBe st } "State#toSfenString" must "describe the state" in { dataForTest(0).toSfenString mustBe "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b -" dataForTest(1).toSfenString mustBe "9/9/9/9/9/9/9/9/9 b -" dataForTest(2).toSfenString mustBe "lnsgk2nl/1r4gs1/ppp+Bpp1p1/6p1p/2P6/8P/PP2PPPP1/2S1G4/LN2KGSNL w BPrp" dataForTest(3).toSfenString mustBe "+l+n+sgkg+s+n+l/1+r5+b1/+p+p+p+p+p+p+p+p+p/9/9/9/+P+P+P+P+P+P+P+P+P/1+B5+R1/+L+N+SGKG+S+N+L b -" dataForTest(4).toSfenString mustBe "4k4/9/9/9/9/9/9/9/9 b 2R2B4G4S4N4L18P" dataForTest(5).toSfenString mustBe "9/9/9/9/9/9/9/9/4K4 w 2r2b4g4s4n4l18p" } it must "restore states" in forAll(StateGen.statesWithFullPieces) { st => State.parseSfenString(st.toSfenString) mustBe st } "State#toUsenString" must "describe the state" in { dataForTest(0).toUsenString mustBe "lnsgkgsnl_1r5b1_ppppppppp_9_9_9_PPPPPPPPP_1B5R1_LNSGKGSNL.b.-" dataForTest(1).toUsenString mustBe "9_9_9_9_9_9_9_9_9.b.-" dataForTest(2).toUsenString mustBe "lnsgk2nl_1r4gs1_pppzBpp1p1_6p1p_2P6_8P_PP2PPPP1_2S1G4_LN2KGSNL.w.BPrp" dataForTest(3).toUsenString mustBe "zlznzsgkgzsznzl_1zr5zb1_zpzpzpzpzpzpzpzpzp_9_9_9_zPzPzPzPzPzPzPzPzP_1zB5zR1_zLzNzSGKGzSzNzL.b.-" dataForTest(4).toUsenString mustBe "4k4_9_9_9_9_9_9_9_9.b.2R2B4G4S4N4L18P" dataForTest(5).toUsenString mustBe "9_9_9_9_9_9_9_9_4K4.w.2r2b4g4s4n4l18p" } it must "restore states" in forAll(StateGen.statesWithFullPieces) { st => State.parseUsenString(st.toUsenString) mustBe st } "State#toKifString" must "describe the state" in { dataForTest(0).toKifString mustBe kifForTest(0) dataForTest(1).toKifString mustBe kifForTest(1) dataForTest(2).toKifString mustBe kifForTest(2) dataForTest(3).toKifString mustBe kifForTest(3) dataForTest(4).toKifString mustBe kifForTest(4) dataForTest(5).toKifString mustBe kifForTest(5) } it must "restore states" in forAll(StateGen.statesWithFullPieces) { st => State.parseKifString(st.toKifString) mustBe st } "State#makeMove" must "make next state" in { State.HIRATE.makeMove(Move(BLACK, Some(P77), P76, PAWN, false, false, None, None, false)) mustBe Some(State(WHITE, Map( P11 -> WL, P21 -> WN, P31 -> WS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P22 -> WB, P82 -> WR, P13 -> WP, P23 -> WP, P33 -> WP, P43 -> WP, P53 -> WP, P63 -> WP, P73 -> WP, P83 -> WP, P93 -> WP, P17 -> BP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P67 -> BP, P76 -> BP, P87 -> BP, P97 -> BP, P28 -> BR, P88 -> BB, P19 -> BL, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS)) State(BLACK, Map( P11 -> WL, P21 -> WN, P31 -> WS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P22 -> WB, P82 -> WR, P14 -> WP, P23 -> WP, P33 -> WP, P43 -> WP, P53 -> WP, P63 -> WP, P73 -> WP, P83 -> WP, P93 -> WP, P13 -> BP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P67 -> BP, P77 -> BP, P87 -> BP, P97 -> BP, P28 -> BR, P88 -> BB, P19 -> BL, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS).makeMove(Move(BLACK, Some(P13), P12, PPAWN, true, false, None, None, false)) mustBe Some(State(WHITE, Map( P11 -> WL, P21 -> WN, P31 -> WS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P22 -> WB, P82 -> WR, P14 -> WP, P23 -> WP, P33 -> WP, P43 -> WP, P53 -> WP, P63 -> WP, P73 -> WP, P83 -> WP, P93 -> WP, P12 -> BPP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P67 -> BP, P77 -> BP, P87 -> BP, P97 -> BP, P28 -> BR, P88 -> BB, P19 -> BL, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS)) State(BLACK, Map( P12 -> WL, P21 -> WN, P31 -> WS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P22 -> WB, P82 -> WR, P14 -> WP, P23 -> WP, P33 -> WP, P43 -> WP, P53 -> WP, P63 -> WP, P73 -> WP, P83 -> WP, P93 -> WP, P13 -> BP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P67 -> BP, P77 -> BP, P87 -> BP, P97 -> BP, P28 -> BR, P88 -> BB, P19 -> BL, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS).makeMove(Move(BLACK, Some(P13), P12, PAWN, false, false, None, Some(LANCE), false)) mustBe Some(State(WHITE, Map( P21 -> WN, P31 -> WS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P22 -> WB, P82 -> WR, P14 -> WP, P23 -> WP, P33 -> WP, P43 -> WP, P53 -> WP, P63 -> WP, P73 -> WP, P83 -> WP, P93 -> WP, P12 -> BP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P67 -> BP, P77 -> BP, P87 -> BP, P97 -> BP, P28 -> BR, P88 -> BB, P19 -> BL, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS.updated(Hand(BL), 1))) State(BLACK, Map( P12 -> WPL, P21 -> WN, P31 -> WS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P22 -> WB, P82 -> WR, P14 -> WP, P23 -> WP, P33 -> WP, P43 -> WP, P53 -> WP, P63 -> WP, P73 -> WP, P83 -> WP, P93 -> WP, P13 -> BP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P67 -> BP, P77 -> BP, P87 -> BP, P97 -> BP, P28 -> BR, P88 -> BB, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS.updated(Hand(BL), 1)).makeMove(Move(BLACK, Some(P13), P12, PAWN, false, false, None, Some(PLANCE), false)) mustBe Some(State(WHITE, Map( P21 -> WN, P31 -> WS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P22 -> WB, P82 -> WR, P14 -> WP, P23 -> WP, P33 -> WP, P43 -> WP, P53 -> WP, P63 -> WP, P73 -> WP, P83 -> WP, P93 -> WP, P12 -> BP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P67 -> BP, P77 -> BP, P87 -> BP, P97 -> BP, P28 -> BR, P88 -> BB, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS.updated(Hand(BL), 2))) State(BLACK, Map( P11 -> WL, P21 -> WN, P31 -> WS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P22 -> WB, P82 -> WR, P14 -> WP, P23 -> WP, P33 -> WP, P43 -> WP, P53 -> WP, P63 -> WP, P73 -> WP, P83 -> WP, P93 -> WP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P67 -> BP, P77 -> BP, P87 -> BP, P97 -> BP, P28 -> BR, P88 -> BB, P19 -> BL, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS.updated(Hand(BP), 1)).makeMove(Move(BLACK, None, P12, PAWN, false, false, None, None, false)) mustBe Some(State(WHITE, Map( P11 -> WL, P21 -> WN, P31 -> WS, P41 -> WG, P51 -> WK, P61 -> WG, P71 -> WS, P81 -> WN, P91 -> WL, P22 -> WB, P82 -> WR, P14 -> WP, P23 -> WP, P33 -> WP, P43 -> WP, P53 -> WP, P63 -> WP, P73 -> WP, P83 -> WP, P93 -> WP, P12 -> BP, P27 -> BP, P37 -> BP, P47 -> BP, P57 -> BP, P67 -> BP, P77 -> BP, P87 -> BP, P97 -> BP, P28 -> BR, P88 -> BB, P19 -> BL, P29 -> BN, P39 -> BS, P49 -> BG, P59 -> BK, P69 -> BG, P79 -> BS, P89 -> BN, P99 -> BL ), State.EMPTY_HANDS)) } "State#getPromotionFlag" must "return flags" in { State.HIRATE.getPromotionFlag(Left(P77), P76) mustBe Some(CannotPromote) // pawn State(BLACK, Map(P12 -> BP), State.EMPTY_HANDS).getPromotionFlag(Left(P12), P11) mustBe Some(MustPromote) State(BLACK, Map(P13 -> BP), State.EMPTY_HANDS).getPromotionFlag(Left(P13), P12) mustBe Some(CanPromote) State(BLACK, Map(P14 -> BP), State.EMPTY_HANDS).getPromotionFlag(Left(P14), P13) mustBe Some(CanPromote) State(BLACK, Map(P15 -> BP), State.EMPTY_HANDS).getPromotionFlag(Left(P15), P14) mustBe Some(CannotPromote) State(BLACK, Map(P19 -> BP), State.EMPTY_HANDS).getPromotionFlag(Left(P19), P18) mustBe Some(CannotPromote) State(BLACK, Map(P12 -> BPP), State.EMPTY_HANDS).getPromotionFlag(Left(P12), P11) mustBe Some(CannotPromote) State(BLACK, Map(P13 -> BPP), State.EMPTY_HANDS).getPromotionFlag(Left(P13), P12) mustBe Some(CannotPromote) State(WHITE, Map(P11 -> WP), State.EMPTY_HANDS).getPromotionFlag(Left(P11), P12) mustBe Some(CannotPromote) State(WHITE, Map(P16 -> WP), State.EMPTY_HANDS).getPromotionFlag(Left(P16), P17) mustBe Some(CanPromote) State(WHITE, Map(P17 -> WP), State.EMPTY_HANDS).getPromotionFlag(Left(P17), P18) mustBe Some(CanPromote) State(WHITE, Map(P18 -> WP), State.EMPTY_HANDS).getPromotionFlag(Left(P18), P19) mustBe Some(MustPromote) State(WHITE, Map(P17 -> WPP), State.EMPTY_HANDS).getPromotionFlag(Left(P17), P18) mustBe Some(CannotPromote) State(WHITE, Map(P18 -> WPP), State.EMPTY_HANDS).getPromotionFlag(Left(P18), P19) mustBe Some(CannotPromote) // lance State(BLACK, Map(P12 -> BL), State.EMPTY_HANDS).getPromotionFlag(Left(P12), P11) mustBe Some(MustPromote) State(BLACK, Map(P13 -> BL), State.EMPTY_HANDS).getPromotionFlag(Left(P13), P12) mustBe Some(CanPromote) State(BLACK, Map(P13 -> BL), State.EMPTY_HANDS).getPromotionFlag(Left(P13), P11) mustBe Some(MustPromote) State(BLACK, Map(P14 -> BL), State.EMPTY_HANDS).getPromotionFlag(Left(P14), P13) mustBe Some(CanPromote) State(BLACK, Map(P15 -> BL), State.EMPTY_HANDS).getPromotionFlag(Left(P15), P14) mustBe Some(CannotPromote) State(BLACK, Map(P19 -> BL), State.EMPTY_HANDS).getPromotionFlag(Left(P19), P18) mustBe Some(CannotPromote) State(BLACK, Map(P12 -> BPL), State.EMPTY_HANDS).getPromotionFlag(Left(P12), P11) mustBe Some(CannotPromote) State(BLACK, Map(P13 -> BPL), State.EMPTY_HANDS).getPromotionFlag(Left(P13), P12) mustBe Some(CannotPromote) State(WHITE, Map(P11 -> WL), State.EMPTY_HANDS).getPromotionFlag(Left(P11), P12) mustBe Some(CannotPromote) State(WHITE, Map(P16 -> WL), State.EMPTY_HANDS).getPromotionFlag(Left(P16), P17) mustBe Some(CanPromote) State(WHITE, Map(P17 -> WL), State.EMPTY_HANDS).getPromotionFlag(Left(P17), P18) mustBe Some(CanPromote) State(WHITE, Map(P18 -> WL), State.EMPTY_HANDS).getPromotionFlag(Left(P18), P19) mustBe Some(MustPromote) State(WHITE, Map(P17 -> WPL), State.EMPTY_HANDS).getPromotionFlag(Left(P17), P18) mustBe Some(CannotPromote) State(WHITE, Map(P18 -> WPL), State.EMPTY_HANDS).getPromotionFlag(Left(P18), P19) mustBe Some(CannotPromote) // knight State(BLACK, Map(P13 -> BN), State.EMPTY_HANDS).getPromotionFlag(Left(P13), P21) mustBe Some(MustPromote) State(BLACK, Map(P14 -> BN), State.EMPTY_HANDS).getPromotionFlag(Left(P14), P22) mustBe Some(MustPromote) State(BLACK, Map(P15 -> BN), State.EMPTY_HANDS).getPromotionFlag(Left(P15), P23) mustBe Some(CanPromote) State(BLACK, Map(P16 -> BN), State.EMPTY_HANDS).getPromotionFlag(Left(P16), P24) mustBe Some(CannotPromote) State(BLACK, Map(P19 -> BN), State.EMPTY_HANDS).getPromotionFlag(Left(P19), P27) mustBe Some(CannotPromote) State(BLACK, Map(P13 -> BPN), State.EMPTY_HANDS).getPromotionFlag(Left(P13), P12) mustBe Some(CannotPromote) State(BLACK, Map(P14 -> BPN), State.EMPTY_HANDS).getPromotionFlag(Left(P14), P13) mustBe Some(CannotPromote) State(WHITE, Map(P11 -> WN), State.EMPTY_HANDS).getPromotionFlag(Left(P11), P23) mustBe Some(CannotPromote) State(WHITE, Map(P14 -> WN), State.EMPTY_HANDS).getPromotionFlag(Left(P14), P26) mustBe Some(CannotPromote) State(WHITE, Map(P15 -> WN), State.EMPTY_HANDS).getPromotionFlag(Left(P15), P27) mustBe Some(CanPromote) State(WHITE, Map(P16 -> WN), State.EMPTY_HANDS).getPromotionFlag(Left(P16), P28) mustBe Some(MustPromote) State(WHITE, Map(P17 -> WN), State.EMPTY_HANDS).getPromotionFlag(Left(P17), P29) mustBe Some(MustPromote) State(WHITE, Map(P17 -> WPN), State.EMPTY_HANDS).getPromotionFlag(Left(P17), P18) mustBe Some(CannotPromote) State(WHITE, Map(P18 -> WPN), State.EMPTY_HANDS).getPromotionFlag(Left(P18), P19) mustBe Some(CannotPromote) // others State(BLACK, Map(P33 -> BS), State.EMPTY_HANDS).getPromotionFlag(Left(P33), P44) mustBe Some(CanPromote) State(BLACK, Map(P44 -> BS), State.EMPTY_HANDS).getPromotionFlag(Left(P44), P33) mustBe Some(CanPromote) State(BLACK, Map(P77 -> BS), State.EMPTY_HANDS).getPromotionFlag(Left(P77), P66) mustBe Some(CannotPromote) State(WHITE, Map(P77 -> WS), State.EMPTY_HANDS).getPromotionFlag(Left(P77), P66) mustBe Some(CanPromote) State(WHITE, Map(P66 -> WS), State.EMPTY_HANDS).getPromotionFlag(Left(P66), P77) mustBe Some(CanPromote) // from hand State(BLACK, Map.empty, State.EMPTY_HANDS.updated(Hand(BP), 1)).getPromotionFlag(Right(Hand(BP)), P55) mustBe Some(CannotPromote) State(WHITE, Map.empty, State.EMPTY_HANDS.updated(Hand(WP), 1)).getPromotionFlag(Right(Hand(WP)), P55) mustBe Some(CannotPromote) } it must "return None when from is invalid" in { State.HIRATE.getPromotionFlag(Left(P55), P54) mustBe None State.HIRATE.getPromotionFlag(Left(P33), P34) mustBe None } "State#getAttackBB" must "return the sum of attack bitboards" in { val s1: State = State.parseCsaString(Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU * -FU-FU-FU-FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7+FU+FU+FU+FU+FU+FU+FU+FU+FU", "P8 * +KA * * -FU * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+", "P-", "+" ).mkString("\n")) s1.getAttackBB(BLACK) mustBe BitBoard(Seq( "---------", "---------", "---------", "---------", "---------", "*********", "*-*---***", "*********", "*-******-" ).mkString) s1.getAttackBB(WHITE) mustBe BitBoard(Seq( "-******-*", "*********", "***---*-*", "****-****", "---------", "---------", "---------", "---------", "----*----" ).mkString) } "State#isChecked" must "return true when the player's king is checked" in { val s1: State = State.parseCsaString(Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU * -FU-FU-FU-FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7+FU+FU+FU+FU+FU+FU+FU+FU+FU", "P8 * +KA * * -FU * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+", "P-", "+" ).mkString("\n")) val s2: State = State.parseCsaString(Seq( "P1 * * * * -KI * * * * ", "P2 * * * +OU * * * * * ", "P3 * * * * * * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+", "P-", "+" ).mkString("\n")) val s3: State = State.parseCsaString(Seq( "P1 * * * * -OU * * * * ", "P2 * * * +KI * * * * * ", "P3 * * * * * * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+", "P-", "-" ).mkString("\n")) val s4: State = State.parseCsaString(Seq( "P1 * * * * * * * -OU * ", "P2 * * * * * * * * * ", "P3 * * * * * * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8+KA * * * * * * * * ", "P9 * * * * * * * * * ", "P+", "P-", "-" ).mkString("\n")) val s5: State = State.parseCsaString(Seq( "P1 * * * * * * * -OU * ", "P2 * * * * * * * * * ", "P3 * * * * * +UM * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8+KA * * * * * * * * ", "P9 * * * * * * * +KY * ", "P+00FU", "P-", "-" ).mkString("\n")) s1.isChecked mustBe true s2.isChecked mustBe true s3.isChecked mustBe true s4.isChecked mustBe true } it must "return false when the king is not on the board" in { val s1: State = State.parseCsaString(Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU-FU-FU-FU-FU-FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7+FU+FU+FU+FU+FU+FU+FU+FU+FU", "P8 * +KA * * * * * +HI * ", "P9+KY+KE+GI+KI * +KI+GI+KE+KY", "P+", "P-", "+" ).mkString("\n")) val s2: State = State.parseCsaString(Seq( "P1-KY-KE-GI-KI * -KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU-FU-FU-FU-FU-FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7+FU+FU+FU+FU+FU+FU+FU+FU+FU", "P8 * +KA * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+", "P-", "-" ).mkString("\n")) val s3: State = State.parseCsaString(Seq( "P1-KY-KE-GI-KI * -KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU-FU-FU-FU-FU-FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7+FU+FU+FU+FU+FU+FU+FU+FU+FU", "P8 * +KA * * * * * +HI * ", "P9+KY+KE+GI+KI * +KI+GI+KE+KY", "P+", "P-", "+" ).mkString("\n")) s1.isChecked mustBe false s2.isChecked mustBe false s3.isChecked mustBe false } "State#getAttacker" must "return attackers" in { val s1: State = State.parseCsaString(Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU-FU-FU-FU-FU-FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7+FU+FU+FU+FU+FU+FU+FU+FU+FU", "P8 * +KA * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+", "P-", "+" ).mkString("\n")) val s2: State = State.parseCsaString(Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU-FU-FU-FU-FU-FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7+FU+FU+FU+FU+FU+FU+FU+FU+FU", "P8 * +KA * * * * * +HI * ", "P9+KY+KE+GI+KI * +KI+GI+KE+KY", "P+", "P-", "+" ).mkString("\n")) val s3: State = State.parseCsaString(Seq( "P1 * * * * * * * -OU * ", "P2 * * * * * * * * * ", "P3 * * * * * * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8+KA * * * * * * * * ", "P9 * * * * * * * * * ", "P+", "P-", "-" ).mkString("\n")) val s4: State = State.parseCsaString(Seq( "P1 * * * * * * * -OU * ", "P2 * * * * * * * * * ", "P3 * * * * * +UM * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8+KA * * * * * * * * ", "P9 * * * * * * * +KY * ", "P+00FU", "P-", "-" ).mkString("\n")) val s5: State = State.parseCsaString(Seq( "P1 * * * * * * * -OU * ", "P2 * * * * * * * -FU * ", "P3 * * * * * -GI * * * ", "P4 * * -HI * * * +OU * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8+KA * * * * * * * * ", "P9 * * * * * * * +KY * ", "P+00FU", "P-", "+" ).mkString("\n")) s1.attackers mustBe Set.empty s2.attackers mustBe Set.empty s3.attackers mustBe Set(P98) s4.attackers mustBe Set(P43, P29) s5.attackers mustBe Set(P43, P74) } "State#guards" must "return guard attributes" in { val s1: State = State.parseCsaString(Seq( "P1 * * * * -KY * * * * ", "P2 * * * * -KY * * * * ", "P3-KA * * * -KY * * * -UM", "P4 * +FU * * * * * * * ", "P5 * * * * * * -GI * * ", "P6 * * * * * * * * * ", "P7 * * * * +OU * +TO-HI * ", "P8 * * * * +FU * * * * ", "P9 * * * * -RY * * * * ", "P+", "P-", "+" ).mkString("\n")) s1.guards mustBe Map( P53 -> BitBoard(Seq( "---------", "----*----", "----*----", "----*----", "----*----", "----*----", "---------", "---------", "---------" ).mkString), P35 -> BitBoard(Seq( "---------", "---------", "--------*", "-------*-", "------*--", "-----*---", "---------", "---------", "---------" ).mkString), P84 -> BitBoard(Seq( "---------", "---------", "*--------", "-*-------", "--*------", "---*-----", "---------", "---------", "---------" ).mkString), P37 -> BitBoard(Seq( "---------", "---------", "---------", "---------", "---------", "---------", "-----***-", "---------", "---------" ).mkString), P58 -> BitBoard(Seq( "---------", "---------", "---------", "---------", "---------", "---------", "---------", "----*----", "----*----" ).mkString)) } "State#legalMoves" must "return set with proper size" in { State.HIRATE.legalMoves(None).size must be(30) State.parseCsaString( """P1+HI * * * * * * * *. |P2 * * +OU * +GI * +GI+GI-OU |P3 * * * * +KA * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * * * * * * * *. |P9 * +KY * +KY * +KY * * *. |P+00HI00KA00KI00GI00KE00KY00FU |P-00KI00KI00KI00KE00KE00KE00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU00FU |+""".stripMargin).legalMoves(None).size must be(593) State.parseSfenString("ln1g4l/1ks1g4/1pp6/pg1P2pp1/2P2R2p/PP1NP1PP1/1KNg4P/1S+r6/L7L b 2B2SN4P").legalMoves(None).size mustBe 3 } "State#isMated" must "return true when the state is mated" in { State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * * * * * * * *. |P9 * * * * * * * * *. |P+ |P- |+""".stripMargin).isMated mustBe true State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * -FU * * * *. |P8 * * * * -KI * * * *. |P9 * * * * +OU * * * *. |P+00HI00KA |P- |+""".stripMargin).isMated mustBe true State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * +FU+FU+FU+KI * * *. |P9 * -HI * * +OU+FU * * *. |P+00FU00FU |P- |+""".stripMargin).isMated mustBe true State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * +FU+FU+FU+KI * * *. |P9 * -HI * * +OU * * * *. |P+00FU00FU |P- |+""".stripMargin).isMated mustBe true State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * -KI * * * *. |P8 * * -KI * * * -KI * *. |P9 * * * * +OU * * * *. |P+ |P- |+""".stripMargin).isMated mustBe true State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * +HI * * * *. |P4 * * * * -KY * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * -KA * * * * * *. |P8 * * +FU * * * -KI * *. |P9 * * * +KE+OU * * * *. |P+00FU |P- |+""".stripMargin).isMated mustBe true State.parseCsaString( """P1 * * * * * -KY * * *. |P2 * * * * * * * * *. |P3 * * * * -KY * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * -KA * * * * * *. |P7 * * * * * * * * *. |P8 * * * +GI+OU * * * *. |P9 * * * +KI * * * * *. |P+00FU |P- |+""".stripMargin).isMated mustBe true State.parseCsaString( """P1 * * * * * * -RY * +OU |P2 * * * * * * * * +TO |P3 * * * * * * * * -HI |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * * * * * * * *. |P9 * * * * * * * * *. |P+00FU |P- |+""".stripMargin).isMated mustBe true State.parseCsaString( """P1 * * * * * * -GI-KE-OU |P2 * * * * * * -KY-KA-KY |P3 * * * * * * -FU+KE-FU |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * * * * * * * *. |P9 * * * * * * * * *. |P+ |P-00HI00KA00KI00GI00KE00KY00FU |-""".stripMargin).isMated mustBe true State.parseCsaString( """P1+NG+HI+KI+GI+HI+KA+NY+GI+KA |P2+FU+FU+FU+FU+FU+FU+FU+FU+FU |P3+OU+KE * * * * * +KE *. |P4+KY+KE * * * * * +KE *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * * * * * * * *. |P9 * * * * * * * * *. |P+00FU |P- |+""".stripMargin).isMated mustBe true } it must "return false when the state is not mated" in { State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * * * * * * * *. |P9 * * * * * * * * *. |P+00FU |P- |+""".stripMargin).isMated mustBe false State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * -KA * * * *. |P8 * * * * -KI * * * *. |P9 * * * * +OU * * * *. |P+00HI00KA |P- |+""".stripMargin).isMated mustBe false State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * +KY+FU+FU+KI * * *. |P9 * -HI * * +OU+FU * * *. |P+00FU00FU |P- |+""".stripMargin).isMated mustBe false State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * +FU+FU+FU * * * *. |P9 * -HI * * +OU * * * *. |P+00FU00FU |P- |+""".stripMargin).isMated mustBe false State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * * * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * -KI * * * *. |P8 * * -KI * * * -KI * *. |P9 * * * * +OU * * * *. |P+00KA |P- |+""".stripMargin).isMated mustBe false State.parseCsaString( """P1 * * * * * * * * *. |P2 * * * * * * * * *. |P3 * * * * +HI * * * *. |P4 * * * * -KY * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * +FU-KA * * -KI * *. |P9 * * * +KE+OU * * * *. |P+00FU |P- |+""".stripMargin).isMated mustBe false State.parseCsaString( """P1 * * * * * -KY * * *. |P2 * * * * * * * * *. |P3 * * * * -KY * * * *. |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * -KA * * * * * *. |P7 * * * * * * * * *. |P8 * * * +GI+OU * * * *. |P9 * * * -KI * * * * *. |P+00FU |P- |+""".stripMargin).isMated mustBe false State.parseCsaString( """P1 * * * * * * -RY * +OU |P2 * * * * * * * * +TO |P3 * * * * * * * * -UM |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * * * * * * * *. |P9 * * * * * * * * *. |P+00FU |P- |+""".stripMargin).isMated mustBe false State.parseCsaString( """P1 * * * * * * -RY * +OU |P2 * * * * * * -RY * *. |P3 * * * * * * * * +KE |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * * * * * * * *. |P9 * * * * * * * * *. |P+00FU |P- |+""".stripMargin).isMated mustBe false State.parseCsaString( """P1 * * * * * * -GI-KE-OU |P2 * * * * * * -KI-KA-KY |P3 * * * * * * -FU+KE-FU |P4 * * * * * * * * *. |P5 * * * * * * * * *. |P6 * * * * * * * * *. |P7 * * * * * * * * *. |P8 * * * * * * * * *. |P9 * * * * * * * * *. |P+ |P-00HI00KA00KI00GI00KE00KY00FU |-""".stripMargin).isMated mustBe false } "State#hasHand" must "return if the in-hand piece exists" in { State.HIRATE.hasHand(Hand(BP)) mustBe false State.empty.updateHandPiece(BP, 1).get.hasHand(Hand(BP)) mustBe true State.empty.updateHandPiece(BP, 2).get.hasHand(Hand(BP)) mustBe true State.empty.updateHandPiece(BP, 18).get.hasHand(Hand(BP)) mustBe true } "State#getNonSuicidalMovesOnBoard" must "return" in { State.parseCsaString(Seq( "P1 * * * * * * * * * ", "P2 * * * * * +HI-KI-OU * ", "P3 * * * * * * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+", "P-", "-" ).mkString("\n")).getNonSuicidalMovesOnBoard mustBe Map( Square(3, 2) -> BitBoard("000.010.000.000.000.000.000.000.000"), Square(2, 2) -> BitBoard("007.001.007.000.000.000.000.000.000") ) State.parseCsaString(Seq( "P1 * * * * * * * * * ", "P2 * * * +HI * +HI-KI-OU * ", "P3 * * * * * * -GI * * ", "P4 * * * * * +KA * * * ", "P5 * * * * * +KA * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+", "P-", "-" ).mkString("\n")).getNonSuicidalMovesOnBoard mustBe Map( Square(3, 2) -> BitBoard("000.010.000.000.000.000.000.000.000"), Square(2, 2) -> BitBoard("007.000.001.000.000.000.000.000.000"), Square(3, 3) -> BitBoard("000.000.000.010.000.000.000.000.000") ) } "State#getEscapeMoves" must "return" in { State.parseCsaString(Seq( "P1 * * * * * * * * * ", "P2 * * * * * * * * * ", "P3 * * * * * * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * +OU+KE-KI * * * * ", "P7 * * +GI-RY * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+", "P-", "+" ).mkString("\n")).getEscapeMoves mustBe Map( Left(P76) -> BitBoard("000.000.000.000.340.200.200.000.000"), Left(P66) -> BitBoard("000.000.000.000.000.000.000.000.000"), Left(P77) -> BitBoard("000.000.000.000.000.000.000.000.000") ) State.parseCsaString(Seq( "P1 * * * * * * * * * ", "P2 * * * * * * * * * ", "P3 * * * * * -OU * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * +KA * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * +KY+KY * * ", "P+", "P-", "-" ).mkString("\n")).getEscapeMoves mustBe Map( Left(P43) -> BitBoard("000.000.020.020.000.000.000.000.000") ) } "State#unusedPtypeCount" must "return numbers of unused pieces" in { State.MATING_BLACK.unusedPtypeCount mustBe State.capacity.keys.map(_ -> 0).toMap ++ Map(KING -> 1) State.MATING_WHITE.unusedPtypeCount mustBe State.capacity.keys.map(_ -> 0).toMap ++ Map(KING -> 1) State.HANDICAP_3_PIECE.unusedPtypeCount mustBe State.capacity.keys.map(_ -> 0).toMap ++ Map(ROOK -> 1, BISHOP -> 1, LANCE -> 1) State.HANDICAP_THREE_PAWNS.unusedPtypeCount mustBe Map(KING -> 0, ROOK -> 1, BISHOP -> 1, GOLD -> 2, SILVER -> 2, KNIGHT -> 2, LANCE -> 2, PAWN -> 6) } "State#isUchifuzumePossible" must "return true if Uchifuzume is possible" in { val states = Seq( Seq( "P1 * * * * * * * -FU-OU", "P2 * * * * * * * * * ", "P3 * * * * * * * * +TO", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-", "+" ), Seq( "P1 * * * * * * +TO * -OU", "P2 * * * * * * * * * ", "P3 * * * * * * * * +TO", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU00FU00FU", "P-", "+" ), Seq( "P1 * * * * * * * * * ", "P2 * * * * * * * * * ", "P3 * * * * * * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * -OU * * ", "P8 * * * * * * * * * ", "P9 * * * * * +KE+OU+KY * ", "P+", "P-00FU", "-" ), Seq( "P1 * * * * * * * * * ", "P2 * * * * * * * * -KA", "P3 * * * * * * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * -OU * * * * * * * ", "P8 * * * * * * * * * ", "P9+OU * * * * * * * * ", "P+", "P-00FU", "-" ), Seq( "P1 * * * * * * * * * ", "P2 * * * * * * * * * ", "P3 * * * * +KA * * * * ", "P4 * * * * -FU * * * * ", "P5 * * * -KE-OU * * * * ", "P6 * * * -KY * * +RY * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-", "+" ), Seq( "P1 * * * * * * * * * ", "P2 * * * * * * * * * ", "P3 * * * * * * * * * ", "P4 * * * * * -KI * * * ", "P5 * * * * +KA * +KA * * ", "P6 * * * * +HI+OU+HI * * ", "P7 * * * * +FU+FU+FU * * ", "P8 * * * * * -TO * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-00FU", "-" ) ).map(s => State.parseCsaString(s.mkString("\n"))) states.map(_.isUchifuzumePossible) mustBe Seq.fill(states.length)(true) } it must "return false if Uchifuzume is impossible" in { val states = Seq( Seq( "P1 * * * * * * * -FU-OU", "P2 * * * * * * * * * ", "P3 * * * * * * * * +TO", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+", "P-", "+" ), Seq( "P1 * * * * * * * -FU-OU", "P2 * * * * * * * * -FU", "P3 * * * * * * * * +TO", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-", "+" ), Seq( "P1 * * * * * * * -KI-OU", "P2 * * * * * * * * * ", "P3 * * * * * * * * +TO", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-", "+" ), Seq( "P1 * * * * * * * -FU-OU", "P2 * * * * * * * -KY * ", "P3 * * * * * * * * +FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-", "+" ), Seq( "P1 * * * * * * * -FU-OU", "P2 * * * * * * * -KY * ", "P3 * * * * * * * +HI * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-", "+" ), Seq( "P1 * * * * * * * -FU-OU", "P2 * * * * * * * * * ", "P3 * * * * * * * * +TO", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-", "-" ), Seq( "P1 * * * * +OU * * * * ", "P2 * * * -TO * -TO * * * ", "P3 * * * * -UM * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-00FU", "-" ), Seq( "P1 * * * * * * * * * ", "P2 * * * * * * * * * ", "P3 * * * * * * * * * ", "P4 * * * * * -KI * * * ", "P5 * * * * +KA * +KA * * ", "P6 * * * * +HI+OU+HI * * ", "P7 * * * * +FU+FU+FU * * ", "P8 * * * * * -FU * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-00FU", "-" ), Seq( "P1 * * * * +OU * * * * ", "P2 * * * -TO * -TO * * * ", "P3 * * * * -UM * * * * ", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7 * * * +RY * +RY * * * ", "P8 * * * * * * * * * ", "P9 * * * * -OU * * * * ", "P+00FU", "P-00FU", "+" ), Seq( "P1 * * * * * * * * * ", "P2 * * * * * * * * * ", "P3 * * * * +KA * * * * ", "P4 * * * * -FU * * * * ", "P5 * * * -KE-OU * * * * ", "P6 * * * -KY * +HI * * * ", "P7 * * * * * * * * * ", "P8 * * * * * * * * * ", "P9 * * * * * * * * * ", "P+00FU", "P-", "+" ) ).map(s => State.parseCsaString(s.mkString("\n"))) states.map(_.isUchifuzumePossible) mustBe Seq.fill(states.length)(false) } "State#createMoveFromNextState" must "create Move" in { val states = Seq( Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU-FU-FU-FU-FU-FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * * * * * * * * ", "P7+FU+FU+FU+FU+FU+FU+FU+FU+FU", "P8 * +KA * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+", "P-", "+" ), Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU-FU-FU-FU-FU-FU", "P4 * * * * * * * * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU * +FU+FU+FU+FU+FU+FU", "P8 * +KA * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+", "P-", "-" ), Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * -HI * * * * * -KA * ", "P3-FU-FU-FU-FU-FU-FU * -FU-FU", "P4 * * * * * * -FU * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU * +FU+FU+FU+FU+FU+FU", "P8 * +KA * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+", "P-", "+" ), Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * -HI * * * * * +KA * ", "P3-FU-FU-FU-FU-FU-FU * -FU-FU", "P4 * * * * * * -FU * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU * +FU+FU+FU+FU+FU+FU", "P8 * * * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+00KA", "P-", "-" ), Seq( "P1-KY-KE-GI-KI-OU-KI-GI-KE-KY", "P2 * * * * * * -HI+KA * ", "P3-FU-FU-FU-FU-FU-FU * -FU-FU", "P4 * * * * * * -FU * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU * +FU+FU+FU+FU+FU+FU", "P8 * * * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+00KA", "P-", "+" ), Seq( "P1-KY-KE-GI-KI-OU-KI+UM-KE-KY", "P2 * * * * * * -HI * * ", "P3-FU-FU-FU-FU-FU-FU * -FU-FU", "P4 * * * * * * -FU * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU * +FU+FU+FU+FU+FU+FU", "P8 * * * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+00KA00GI", "P-", "-" ), Seq( "P1-KY-KE-GI-KI-OU * -KI-KE-KY", "P2 * * * * * * -HI * * ", "P3-FU-FU-FU-FU-FU-FU * -FU-FU", "P4 * * * * * * -FU * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU * +FU+FU+FU+FU+FU+FU", "P8 * * * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+00KA00GI", "P-00KA", "+" ), Seq( "P1-KY-KE-GI-KI-OU * -KI-KE-KY", "P2 * * * * * * -HI * * ", "P3-FU-FU-FU-FU-FU-FU+GI-FU-FU", "P4 * * * * * * -FU * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU * +FU+FU+FU+FU+FU+FU", "P8 * * * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+00KA", "P-00KA", "-" ), Seq( "P1-KY-KE-GI-KI-OU * -KI-KE-KY", "P2 * * * * * * -HI * * ", "P3-FU-FU-FU-FU-FU-FU+GI-FU-FU", "P4 * * * * * * -FU * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU * +FU+FU+FU+FU+FU+FU", "P8 * -KA * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+00KA", "P-", "+" ), Seq( "P1-KY-KE-GI-KI-OU * -KI-KE-KY", "P2 * * * * * * -HI * * ", "P3-FU-FU-FU-FU-FU-FU * -FU-FU", "P4 * * * * * +NG-FU * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU * +FU+FU+FU+FU+FU+FU", "P8 * -KA * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+00KA", "P-", "-" ), Seq( "P1-KY-KE-GI-KI-OU * -KI-KE-KY", "P2 * * * * * * -HI * * ", "P3-FU-FU-FU-FU-FU-FU * -FU-FU", "P4 * * * * * +NG-FU * * ", "P5 * * * * * * * * * ", "P6 * * +FU * * * * * * ", "P7+FU+FU-UM+FU+FU+FU+FU+FU+FU", "P8 * * * * * * * +HI * ", "P9+KY+KE+GI+KI+OU+KI+GI+KE+KY", "P+00KA", "P-", "+" ) ).map(s => State.parseCsaString(s.mkString("\n"))) states(0).createMoveFromNextState(states(1), None) mustBe Some(Move(BLACK, Some(P77), P76, PAWN, false, false, None, None, false)) states(1).createMoveFromNextState(states(2), Some(P76)) mustBe Some(Move(WHITE, Some(P33), P34, PAWN, false, false, None, None, false)) states(2).createMoveFromNextState(states(3), Some(P34)) mustBe Some(Move(BLACK, Some(P88), P22, BISHOP, false, false, None, Some(BISHOP), false)) states(3).createMoveFromNextState(states(4), Some(P22)) mustBe Some(Move(WHITE, Some(P82), P32, ROOK, false, false, None, None, false)) states(4).createMoveFromNextState(states(5), Some(P32)) mustBe Some(Move(BLACK, Some(P22), P31, PBISHOP, true, false, None, Some(SILVER), false)) states(5).createMoveFromNextState(states(6), Some(P31)) mustBe Some(Move(WHITE, Some(P41), P31, GOLD, false, true, None, Some(PBISHOP), false)) states(6).createMoveFromNextState(states(7), Some(P31)) mustBe Some(Move(BLACK, None, P33, SILVER, false, false, None, None, false)) states(7).createMoveFromNextState(states(8), Some(P33)) mustBe Some(Move(WHITE, None, P88, BISHOP, false, false, None, None, false)) states(8).createMoveFromNextState(states(9), Some(P88)) mustBe Some(Move(BLACK, Some(P33), P44, PSILVER, true, false, None, None, false)) states(9).createMoveFromNextState(states(10), Some(P44)) mustBe Some(Move(WHITE, Some(P88), P77, PBISHOP, true, false, None, None, true)) // error cases states(0).createMoveFromNextState(states(3), None) mustBe None } }
mogproject/mog-core-scala
shared/src/test/scala/com/mogproject/mogami/core/state/StateSpec.scala
Scala
apache-2.0
60,166
package com.tbrown.twitterStream import jsonz._ import org.joda.time.DateTime case class User ( location: Option[String], statusesCount: Int, lang: String, id: Long, favouritesCount: Int, description: Option[String], name: String, createdAt: DateTime, followersCount: Int, friendsCount: Int, screenName: String, idStr: String, profileImageUrl: String ) object User extends JsonModule { implicit val UserFormat = productFormat13( "location", "statuses_count", "lang", "id", "favourites_count", "description", "name", "created_at", "followers_count", "friends_count", "screen_name", "id_str", "profile_image_url" )(User.apply)(User.unapply) } case class MediaElements ( mediaUrlHttps: String, url: String ) object MediaElements extends JsonModule { implicit val MediaElementsFormat = productFormat2("media_url_https", "url")(MediaElements.apply)(MediaElements.unapply) } case class ExtendedEntities ( media: List[MediaElements] ) object ExtendedEntities extends JsonModule { implicit val ExtendedEntitiesFormat = productFormat1("media")(ExtendedEntities.apply)(ExtendedEntities.unapply) } case class Tweet( retweeted: Boolean, lang: String, id: Long, extendedEntities: Option[ExtendedEntities], timestamp: String, createdAt: DateTime, favoriteCount: Int, text: String, source: String, retweetCount: Int, idStr: String, user: User ) object Tweet extends JsonModule { implicit val tweetFormat = productFormat12( "retweeted", "lang", "id", "extended_entities", "timestamp_ms", "created_at", "favorite_count", "text", "source", "retweet_count", "id_str", "user")(Tweet.apply)(Tweet.unapply) } object TweetStreams extends Enumeration { val Sample, Filter = Value }
tbrown1979/Tweeper
src/main/scala/models/Tweet.scala
Scala
mit
1,835
/* * Copyright (c) 2013-2014 Telefónica Investigación y Desarrollo S.A.U. * * 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 es.tid.cosmos.infinity.common.util import java.io.IOException import scala.concurrent.{Future, Promise} import scala.concurrent.duration._ import org.scalatest.FlatSpec import org.scalatest.matchers.MustMatchers class TimeBoundTest extends FlatSpec with MustMatchers { "A time bound result" must "succeed when it becomes available within time limits" in { val result = timeBound.awaitResult(Future.successful("Success")) result must be ("Success") } it must "fail with IOException when future does not complete within time limits" in { evaluating { timeBound.awaitResult(Promise().future) } must produce [IOException] } it must "fail with IOException when future fails within time limits" in { evaluating { timeBound.awaitResult(Future.failed(new RuntimeException("oops"))) } must produce [IOException] } "A time bound action" must "be true when action completes within time limits" in { timeBound.awaitAction(Future.successful()) must be (true) } it must "be false when action does not complete within time limits" in { timeBound.awaitAction(Promise().future) must be (false) } it must "be false when action future fails within time limits" in { timeBound.awaitAction(Future.failed(new RuntimeException("oops"))) must be (false) } it must "be false when action evaluation fails" in { timeBound.awaitAction(sys.error("oops")) must be (false) } val timeBound = new TimeBound(1.second) }
telefonicaid/fiware-cosmos-platform
infinity/common/src/test/scala/es/tid/cosmos/infinity/common/util/TimeBoundTest.scala
Scala
apache-2.0
2,118
/* * Copyright 2017 Datamountaineer. * * 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 com.datamountaineer.streamreactor.connect.elastic6 import java.nio.ByteBuffer import com.datamountaineer.streamreactor.connect.json.SimpleJsonConverter import com.fasterxml.jackson.databind.JsonNode import com.landoop.connect.sql.StructSql._ import com.landoop.json.sql.JacksonJson import com.landoop.json.sql.JsonSql._ import com.landoop.sql.Field import com.typesafe.scalalogging.StrictLogging import org.apache.kafka.connect.data.{Schema, Struct} import scala.util.{Failure, Success, Try} private object Transform extends StrictLogging { lazy val simpleJsonConverter = new SimpleJsonConverter() def apply(fields: Seq[Field], ignoredFields: Seq[Field], schema: Schema, value: Any, withStructure: Boolean): JsonNode = { def raiseException(msg: String, t: Throwable) = throw new IllegalArgumentException(msg, t) if (value == null) { if (schema == null || !schema.isOptional) { raiseException("Null value is not allowed.", null) } else null } else { if (schema != null) { schema.`type`() match { case Schema.Type.BYTES => //we expected to be json val array = value match { case a: Array[Byte] => a case b: ByteBuffer => b.array() case other => raiseException("Invalid payload:$other for schema Schema.BYTES.", null) } Try(JacksonJson.mapper.readTree(array)) match { case Failure(e) => raiseException("Invalid json.", e) case Success(json) => Try(json.sql(fields, !withStructure)) match { case Failure(e) => raiseException(s"A KCQL exception occurred. ${e.getMessage}", e) case Success(jn) => jn } } case Schema.Type.STRING => //we expected to be json Try(JacksonJson.asJson(value.asInstanceOf[String])) match { case Failure(e) => raiseException("Invalid json", e) case Success(json) => Try(json.sql(fields, !withStructure)) match { case Success(jn) => jn case Failure(e) => raiseException(s"A KCQL exception occurred.${e.getMessage}", e) } } case Schema.Type.STRUCT => val struct = value.asInstanceOf[Struct] Try(struct.sql(fields, !withStructure)) match { case Success(s) => simpleJsonConverter.fromConnectData(s.schema(), s) case Failure(e) => raiseException(s"A KCQL error occurred.${e.getMessage}", e) } case other => raiseException("Can't transform Schema type:$other.", null) } } else { //we can handle java.util.Map (this is what JsonConverter can spit out) value match { case m: java.util.Map[_, _] => val map = m.asInstanceOf[java.util.Map[String, Any]] val jsonNode: JsonNode = JacksonJson.mapper.valueToTree(map) Try(jsonNode.sql(fields, !withStructure)) match { case Success(j) => j case Failure(e) => raiseException(s"A KCQL exception occurred.${e.getMessage}", e) } case s: String => Try(JacksonJson.asJson(value.asInstanceOf[String])) match { case Failure(e) => raiseException("Invalid json.", e) case Success(json) => Try(json.sql(fields, !withStructure)) match { case Success(jn) => jn case Failure(e) => raiseException(s"A KCQL exception occurred.${e.getMessage}", e) } } case b: Array[Byte] => Try(JacksonJson.mapper.readTree(b)) match { case Failure(e) => raiseException("Invalid json.", e) case Success(json) => Try(json.sql(fields, !withStructure)) match { case Failure(e) => raiseException(s"A KCQL exception occurred. ${e.getMessage}", e) case Success(jn) => jn } } //we take it as String case other => raiseException(s"Value:$other is not handled!", null) } } } } }
datamountaineer/stream-reactor
kafka-connect-elastic6/src/main/scala/com/datamountaineer/streamreactor/connect/elastic6/Transform.scala
Scala
apache-2.0
4,862
/* Copyright 2012 Twitter, Inc. 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 com.twitter.algebird.bijection import com.twitter.algebird.{Group, InvariantSemigroup, Monoid, Ring, Semigroup} import com.twitter.bijection.{AbstractBijection, Bijection, Conversion, ImplicitBijection, Reverse} /** * Bijections on Algebird's abstract algebra datatypes. * * @author Oscar Boykin * @author Sam Ritchie */ class BijectedSemigroup[T, U](implicit val sg: Semigroup[T], bij: ImplicitBijection[T, U]) extends InvariantSemigroup[T, U](bij.bijection.toFunction, bij.bijection.inverse.toFunction) { val bijection: Bijection[U, T] = bij.bijection.inverse } class BijectedMonoid[T, U](implicit val monoid: Monoid[T], bij: ImplicitBijection[T, U]) extends BijectedSemigroup[T, U] with Monoid[U] { override val zero: U = bijection.invert(monoid.zero) } class BijectedGroup[T, U](implicit val group: Group[T], bij: ImplicitBijection[T, U]) extends BijectedMonoid[T, U] with Group[U] { override def negate(u: U): U = bijection.invert(group.negate(bijection(u))) override def minus(l: U, r: U): U = bijection.invert(group.minus(bijection(l), bijection(r))) } class BijectedRing[T, U](implicit val ring: Ring[T], bij: ImplicitBijection[T, U]) extends BijectedGroup[T, U] with Ring[U] { override val one: U = bijection.invert(ring.one) override def times(l: U, r: U): U = bijection.invert(ring.times(bijection(l), bijection(r))) override def product(iter: TraversableOnce[U]): U = bijection.invert(ring.product(iter.map(bijection.toFunction))) } trait AlgebirdBijections { implicit def semigroupBijection[T, U]( implicit bij: ImplicitBijection[T, U]): Bijection[Semigroup[T], Semigroup[U]] = new AbstractBijection[Semigroup[T], Semigroup[U]] { override def apply(sg: Semigroup[T]) = new BijectedSemigroup[T, U]()(sg, bij) override def invert(sg: Semigroup[U]) = new BijectedSemigroup[U, T]()(sg, Reverse(bij.bijection)) } implicit def monoidBijection[T, U](implicit bij: ImplicitBijection[T, U]): Bijection[Monoid[T], Monoid[U]] = new AbstractBijection[Monoid[T], Monoid[U]] { override def apply(mon: Monoid[T]) = new BijectedMonoid[T, U]()(mon, bij) override def invert(mon: Monoid[U]) = new BijectedMonoid[U, T]()(mon, Reverse(bij.bijection)) } implicit def groupBijection[T, U](implicit bij: ImplicitBijection[T, U]): Bijection[Group[T], Group[U]] = new AbstractBijection[Group[T], Group[U]] { override def apply(group: Group[T]) = new BijectedGroup[T, U]()(group, bij) override def invert(group: Group[U]) = new BijectedGroup[U, T]()(group, Reverse(bij.bijection)) } implicit def ringBijection[T, U](implicit bij: ImplicitBijection[T, U]): Bijection[Ring[T], Ring[U]] = new AbstractBijection[Ring[T], Ring[U]] { override def apply(ring: Ring[T]) = new BijectedRing[T, U]()(ring, bij) override def invert(ring: Ring[U]) = new BijectedRing[U, T]()(ring, Reverse(bij.bijection)) } } object AlgebirdBijections extends AlgebirdBijections
nevillelyh/algebird
algebird-bijection/src/main/scala/com/twitter/algebird/bijection/AlgebirdBijections.scala
Scala
apache-2.0
3,615
package org.qirx.cms.elasticsearch.index import play.api.libs.json.JsValue import play.api.libs.json.JsObject import org.qirx.cms.i18n.Messages import scala.language.implicitConversions import org.qirx.cms.metadata.PropertyMetadata object Implicits { import scala.language.implicitConversions implicit def addMapppingsAndTransformer[T <: PropertyMetadata](property: T)( implicit m: Mappings[T], t:Transformer[T]): PropertyMetadata with PropertyMappings with PropertyTransformer = new PropertyMetadata with PropertyMappings with PropertyTransformer { val id = property.id val confidential = property.confidential val generator = property.generator def validate(messages: Messages, value: Option[JsValue]) = property.validate(messages, value) lazy val toJson = property.toJson def mappings(name: String) = m.mappings(name) def transform(name: String, document: JsObject) = t.transform(name, document) } }
EECOLOR/play-cms
elasticsearch/src/main/scala/org/qirx/cms/elasticsearch/index/Implicits.scala
Scala
mit
975
package ml.sparkling.graph.operators.algorithms.random.ctrw.processor import ml.sparkling.graph.operators.algorithms.random.ctrw.factory.MessageFactory import ml.sparkling.graph.operators.algorithms.random.ctrw.struct.{CTRWMessage, CTRWVertex} import org.apache.spark.graphx._ import scala.reflect.ClassTag /** * Created by mth on 4/13/17. */ class CTRWProcessor[VD, ED: ClassTag](graph: Graph[VD, ED], factory: MessageFactory) extends Serializable { lazy val initGraph = prepareRawGraph private def prepareRawGraph = { val nbsIds = graph.ops.collectNeighborIds(EdgeDirection.Either) graph.outerJoinVertices(nbsIds)((id, _, nbs) => CTRWVertex(id, nbs.getOrElse(Array.empty), Array.empty, initialized = false)) } def createInitMessages(sampleSize: Int)(vertex: CTRWVertex) = { val msg = for (i <- 0 until sampleSize) yield factory.create(vertex) CTRWVertex(vertex.id, vertex.neighbours, msg.toArray) } def sendMessage(triplet: EdgeTriplet[CTRWVertex, ED]) = { def messagesTo(dest: VertexId) = { def messages = triplet.otherVertexAttr(dest).messages messages filter (_.nextVertex.exists(_ == dest)) toList } Iterator((triplet.srcId, messagesTo(triplet.srcId))) ++ Iterator((triplet.dstId, messagesTo(triplet.dstId))) } def sendMessageCtx(round: Int)(edgeContext: EdgeContext[CTRWVertex, _, List[CTRWMessage]]) = { val triplet = edgeContext.toEdgeTriplet def messagesTo(dest: VertexId) = { def messages = triplet.otherVertexAttr(dest).messages messages filter (_.nextVertex.exists(_ ==dest)) toList } def send(msg: List[CTRWMessage], f: (List[CTRWMessage]) => Unit) = if (msg.nonEmpty) f(msg) send(messagesTo(edgeContext.srcId), edgeContext.sendToSrc) send(messagesTo(edgeContext.dstId), edgeContext.sendToDst) } def mergeMessages(msg1: List[CTRWMessage], msg2: List[CTRWMessage]) = msg1 ++ msg2 def applyMessages(round: Int)(vertexId: VertexId, data: CTRWVertex, messagesOps: Option[List[CTRWMessage]]) = { val newMessages = messagesOps match { case Some(messages) => messages map (factory.correct(data, _)) case None => List.empty } val keptMessages = data.messages filter (_.nextVertex.isEmpty) CTRWVertex(vertexId, data.neighbours, newMessages.toArray ++ keptMessages) } }
sparkling-graph/sparkling-graph
operators/src/main/scala/ml/sparkling/graph/operators/algorithms/random/ctrw/processor/CTRWProcessor.scala
Scala
bsd-2-clause
2,329
/* * Copyright (c) 2014-2020 by The Monix Project Developers. * See the project homepage at: https://monix.io * * 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 monix.reactive.internal.operators import monix.execution.Ack.{Continue, Stop} import scala.util.control.NonFatal import monix.reactive.Observable.Operator import monix.reactive.observers.Subscriber private[reactive] final class FilterOperator[A](p: A => Boolean) extends Operator[A, A] { def apply(out: Subscriber[A]): Subscriber[A] = new Subscriber[A] { implicit val scheduler = out.scheduler private[this] var isDone = false def onNext(elem: A) = { // Protects calls to user code from within the operator and // stream the error downstream if it happens, but if the // error happens because of calls to `onNext` or other // protocol calls, then the behavior should be undefined. var streamError = true try { if (p(elem)) { streamError = false out.onNext(elem) } else Continue } catch { case NonFatal(ex) if streamError => onError(ex) Stop } } def onError(ex: Throwable): Unit = if (!isDone) { isDone = true out.onError(ex) } def onComplete(): Unit = if (!isDone) { isDone = true out.onComplete() } } }
alexandru/monifu
monix-reactive/shared/src/main/scala/monix/reactive/internal/operators/FilterOperator.scala
Scala
apache-2.0
1,965
package org.jetbrains.plugins.scala.failed.annotator import org.jetbrains.plugins.scala.base.ScalaLightCodeInsightFixtureTestAdapter /** * @author Anton Yalyshev */ class OverloadingBadCodeGreenTest extends ScalaLightCodeInsightFixtureTestAdapter { override protected def shouldPass: Boolean = false def testScl2117A(): Unit = { val text = s"""object Test extends App{ | class A | class B extends A | def foo(x: A, y: B) = print(1) | object foo { | def apply(x: B, y: B) = print(3) | def apply(x: A, y: A) = print(5) | } | | ${CARET}foo(new B, new B) |} """.stripMargin checkHasErrorAroundCaret(text) } def testScl2117B(): Unit = { val text = s"""object Test { | def apply[T](x1: T) = "one arg" // A | def apply[T](x1: T, x2: T) = "two args" // B | def apply[T](elems: T*) = "var-args: " + elems.size // C |} | |object Exec { | ${CARET}Test(1) |} """.stripMargin checkHasErrorAroundCaret(text) } }
JetBrains/intellij-scala
scala/scala-impl/test/org/jetbrains/plugins/scala/failed/annotator/OverloadingBadCodeGreenTest.scala
Scala
apache-2.0
1,188
def forLoop { println("For loop using java-style iteration") println("argument size = " + args.length.toString) for (i <- 0 until args.length) { println(args(8)) } } forLoop
skywind3000/language
scala/for_loop.scala
Scala
mit
200
/** * Digi-Lib - base library for Digi components * * Copyright (c) 2012-2014 Alexey Aksenov [email protected] * * 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 org.digimead.digi.lib.log.api import java.util.Date trait XMessage { val date: Date val tid: Long val level: XLevel val tag: String val tagClass: Class[_] val message: String val throwable: Option[Throwable] val pid: Int } object XMessage { type MessageBuilder = (Date, Long, XLevel, String, Class[_], String, Option[Throwable], Int) => XMessage }
ezh/digi-lib
src/main/scala/org/digimead/digi/lib/log/api/XMessage.scala
Scala
apache-2.0
1,051
package org.bitcoins.core.protocol.ln.currency import org.bitcoins.core.currency.{CurrencyUnit, Satoshis} import org.bitcoins.core.number.{BasicArithmetic, UInt64} import org.bitcoins.core.protocol.NetworkElement import scodec.bits.ByteVector import scala.math.BigDecimal.RoundingMode /** * The common currency unit used in the * LN protocol for updating HTLCs. * * @see [[https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md#adding-an-htlc-update_add_htlc BOLT2]] */ sealed abstract class MilliSatoshis extends NetworkElement with Ordered[MilliSatoshis] with BasicArithmetic[MilliSatoshis] { require(toBigInt >= 0, s"Millisatoshis cannot be negative, got $toBigInt") protected def underlying: BigInt /** * Output example: * {{{ * > MilliSatoshis(10) * 10 msat * }}} */ override def toString: String = { val num = toBigInt val postFix = if (num == 1) "msat" else "msats" s"$num $postFix" } def toBigInt: BigInt = underlying def toLong: Long = toBigInt.bigInteger.longValueExact def toBigDecimal: BigDecimal = BigDecimal(toBigInt) def toLnCurrencyUnit: LnCurrencyUnit = { LnCurrencyUnits.fromMSat(this) } def ==(lnCurrencyUnit: LnCurrencyUnit): Boolean = { toLnCurrencyUnit == lnCurrencyUnit } def !=(lnCurrencyUnit: LnCurrencyUnit): Boolean = { toLnCurrencyUnit != lnCurrencyUnit } def >=(ln: LnCurrencyUnit): Boolean = { toLnCurrencyUnit >= ln } def >(ln: LnCurrencyUnit): Boolean = { toLnCurrencyUnit > ln } def <(ln: LnCurrencyUnit): Boolean = { toLnCurrencyUnit < ln } def <=(ln: LnCurrencyUnit): Boolean = { toLnCurrencyUnit <= ln } def ==(ms: MilliSatoshis): Boolean = { toBigInt == ms.toBigInt } def !=(ms: MilliSatoshis): Boolean = { toBigInt != ms.toBigInt } override def compare(ms: MilliSatoshis): Int = toBigInt compare ms.toBigInt override def +(ms: MilliSatoshis): MilliSatoshis = { MilliSatoshis(toBigInt + ms.toBigInt) } override def -(ms: MilliSatoshis): MilliSatoshis = { MilliSatoshis(toBigInt - ms.toBigInt) } override def *(factor: BigInt): MilliSatoshis = { MilliSatoshis(toBigInt * factor) } override def *(factor: MilliSatoshis): MilliSatoshis = { MilliSatoshis(toBigInt * factor.toBigInt) } def toUInt64: UInt64 = { UInt64(underlying) } def toSatoshis: Satoshis = { toLnCurrencyUnit.toSatoshis } override def bytes: ByteVector = toUInt64.bytes.reverse } object MilliSatoshis { private case class MilliSatoshisImpl(underlying: BigInt) extends MilliSatoshis val zero: MilliSatoshis = MilliSatoshis(0) val one: MilliSatoshis = MilliSatoshis(1) def apply(underlying: BigInt): MilliSatoshis = { MilliSatoshisImpl(underlying) } def fromPico(picoBitcoins: PicoBitcoins): MilliSatoshis = { val pico = picoBitcoins.toPicoBitcoinDecimal // we need to divide by 10 to get to msat val msatDec = pico / LnCurrencyUnits.MSAT_TO_PICO //now we need to round, we are going to round the same way round //outputs when publishing txs to the blockchain //https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md#commitment-transaction-outputs val rounded = msatDec.setScale(0, RoundingMode.DOWN) MilliSatoshis(rounded.toBigIntExact.get) } def apply(lnCurrencyUnit: LnCurrencyUnit): MilliSatoshis = { fromPico(picoBitcoins = lnCurrencyUnit.toPicoBitcoins) } def apply(currencyUnit: CurrencyUnit): MilliSatoshis = { fromSatoshis(currencyUnit.satoshis) } def fromSatoshis(sat: Satoshis): MilliSatoshis = { MilliSatoshis(sat.toBigInt * 1000) } }
bitcoin-s/bitcoin-s-core
core/src/main/scala/org/bitcoins/core/protocol/ln/currency/MilliSatoshis.scala
Scala
mit
3,708
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.scala.dsl import builder.{RouteBuilderSupport, RouteBuilder} import org.apache.camel.Exchange import org.junit.Assert.{assertEquals, assertTrue} import org.junit.Test import org.apache.camel.processor.onexception._ /** * Scala DSL equivalent for org.apache.camel.processor.onexception.OnExceptionHandledTest */ class SOnExceptionHandledTest extends OnExceptionHandledTest with RouteBuilderSupport { override def createRouteBuilder = new RouteBuilder { handle[IllegalArgumentException] { to("log:foo?showAll=true") to("mock:handled") }.handled "direct:start" throwException(new IllegalArgumentException("Forced")) } } /** * Scala DSL equivalent for org.apache.camel.processor.onexception.OnExceptionComplexRouteTest */ class SOnExceptionComplexRouteTest extends OnExceptionComplexRouteTest with RouteBuilderSupport { override def createRouteBuilder = new RouteBuilder { errorHandler(deadLetterChannel("mock:error")) handle[MyTechnicalException] { to("mock:tech.error") }.maximumRedeliveries(2).handled "direct:start" ==> { handle[MyFunctionalException]().maximumRedeliveries(0) to("bean:myServiceBean") to("mock:result") } "direct:start2" ==> { handle[MyFunctionalException] { to("mock:handled") }.maximumRedeliveries(0).handled to("bean:myServiceBean") to("mock:result") } } } /** * Scala DSL equivalent for the org.apache.camel.processor.OnExceptionRetryUntilWithDefaultErrorHandlerTest */ class SOnExceptionRetryUntilWithDefaultErrorHandlerTest extends ScalaTestSupport { var invoked = 0 @Test def testRetryUntil = { val out = template.requestBody("direct:start", "Hello World"); assertEquals("Sorry", out); assertEquals(3, invoked); } def threeTimes(exchange: Exchange) = { invoked += 1; assertEquals("Hello World", exchange.in); assertTrue(exchange.getException.isInstanceOf[MyFunctionalException]); exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER, classOf[Int]) < 3; } val builder = new RouteBuilder { errorHandler(defaultErrorHandler.maximumRedeliveries(1).logStackTrace(false)) handle[MyFunctionalException] { transform("Sorry") }.retryWhile(threeTimes).handled "direct:start" throwException(new MyFunctionalException("Sorry, you cannot do this")) } }
engagepoint/camel
components/camel-scala/src/test/scala/org/apache/camel/scala/dsl/OnExceptionTest.scala
Scala
apache-2.0
3,220