monocle.macros.GenLens Scala Examples
The following examples show how to use monocle.macros.GenLens.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: User.scala From crm-seed with Apache License 2.0 | 5 votes |
package com.dataengi.crm.identities.models import com.dataengi.crm.identities.models.UserStates.UserState import com.mohiva.play.silhouette.api.{Identity, LoginInfo} import monocle.macros.GenLens import monocle.{Lens, PLens} case class User(loginInfo: LoginInfo, company: Company, role: Role, state: UserState = UserStates.Activated, id: Option[Long] = None) extends Identity object UserStates extends Enumeration { type UserState = Value val Activated = Value(0) val Deactivated = Value(1) } object Users { val role: Lens[User, Role] = GenLens[User](_.role) val roleName: Lens[Role, String] = GenLens[Role](_.name) val rolePermissions: Lens[Role, Seq[Permission]] = GenLens[Role](_.permissions) val userRoleName: PLens[User, User, String, String] = role composeLens roleName val userPermissions: PLens[User, User, Seq[Permission], Seq[Permission]] = role composeLens rolePermissions }
Example 2
Source File: WsOrderBookState.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.ws.state import akka.actor.typed.ActorRef import cats.syntax.option._ import com.wavesplatform.dex.api.ws.entities.{WsLastTrade, WsOrderBookSettings} import com.wavesplatform.dex.api.ws.protocol import com.wavesplatform.dex.api.ws.protocol.WsOrderBookChanges import com.wavesplatform.dex.api.ws.state.WsAddressState.getNextUpdateId import com.wavesplatform.dex.domain.asset.AssetPair import com.wavesplatform.dex.domain.model.Denormalization.{denormalizeAmountAndFee, denormalizePrice} import com.wavesplatform.dex.domain.model.{Amount, Price} import com.wavesplatform.dex.model.{LastTrade, LevelAmounts} import monocle.macros.GenLens import scala.collection.immutable.TreeMap case class WsOrderBookState(wsConnections: Map[ActorRef[WsOrderBookChanges], Long], changedAsks: Set[Price], changedBids: Set[Price], lastTrade: Option[LastTrade], changedTickSize: Option[Double]) { val genLens: GenLens[WsOrderBookState] = GenLens[WsOrderBookState] def addSubscription(x: ActorRef[WsOrderBookChanges]): WsOrderBookState = copy(wsConnections = wsConnections.updated(x, 0L)) def withoutSubscription(x: ActorRef[WsOrderBookChanges]): WsOrderBookState = if (wsConnections.size == 1) WsOrderBookState(Map.empty, Set.empty, Set.empty, None, None) else copy(wsConnections = wsConnections - x) def hasSubscriptions: Boolean = wsConnections.nonEmpty def hasChanges: Boolean = changedAsks.nonEmpty || changedBids.nonEmpty || lastTrade.nonEmpty || changedTickSize.nonEmpty def denormalized(amountDecimals: Int, priceDecimals: Int, xs: TreeMap[Price, Amount]): TreeMap[Double, Double] = xs.map { case (price, amount) => denormalizePrice(price, amountDecimals, priceDecimals).toDouble -> denormalizeAmountAndFee(amount, amountDecimals).toDouble } def lastTrade(amountDecimals: Int, priceDecimals: Int, x: LastTrade): WsLastTrade = WsLastTrade( price = denormalizePrice(x.price, amountDecimals, priceDecimals).toDouble, amount = denormalizeAmountAndFee(x.amount, amountDecimals).toDouble, side = x.side ) def flushed(assetPair: AssetPair, amountDecimals: Int, priceDecimals: Int, asks: TreeMap[Price, Amount], bids: TreeMap[Price, Amount], timestamp: Long): WsOrderBookState = copy( wsConnections = if (hasChanges) { val changes = protocol.WsOrderBookChanges( assetPair = assetPair, asks = denormalized(amountDecimals, priceDecimals, take(asks, changedAsks)), bids = denormalized(amountDecimals, priceDecimals, take(bids, changedBids)), lastTrade = lastTrade.map(lastTrade(amountDecimals, priceDecimals, _)), updateId = 0L, // Will be changed below timestamp = timestamp, settings = if (changedTickSize.isDefined) WsOrderBookSettings(None, changedTickSize).some else None ) wsConnections.map { case (conn, updateId) => val newUpdateId = getNextUpdateId(updateId) conn ! changes.copy(updateId = newUpdateId) conn -> newUpdateId } } else wsConnections, changedAsks = Set.empty, changedBids = Set.empty, lastTrade = None, changedTickSize = None ) def take(xs: TreeMap[Price, Amount], levels: Set[Price]): TreeMap[Price, Amount] = { // 1. Levels will be always smaller, than xs // 2. A level could gone from xs val r = TreeMap.newBuilder[Price, Amount](xs.ordering) levels.foreach { level => r += level -> xs.getOrElse(level, 0L) } r.result() } def accumulateChanges(lc: LevelAmounts, lt: Option[LastTrade], ts: Option[Double]): WsOrderBookState = if (hasSubscriptions) { ( genLens(_.changedAsks).modify(_ ++ lc.asks.keySet) andThen genLens(_.changedBids).modify(_ ++ lc.bids.keySet) andThen genLens(_.lastTrade).modify { if (lt.isEmpty) _ else lt } andThen genLens(_.changedTickSize).modify { if (ts.isEmpty) _ else ts } )(this) } else this }
Example 3
Source File: DistinctTest.scala From nyaya with GNU Lesser General Public License v2.1 | 5 votes |
package nyaya.gen import monocle.macros.GenLens import scalaz.std.list._ import scalaz.std.set._ import utest._ object DistinctTest extends TestSuite { case class Age(value: Int) case class Person(name: String, age: Age, set: Set[Age]) case class Stuff(list: List[Age], ppl: List[Person]) val pl = new GenLens[Person] val personName = pl(_.name) val personAge = pl(_.age) val personSet = pl(_.set) val sl = new GenLens[Stuff] val stuffList = sl(_.list) val stuffPpl = sl(_.ppl) val dAge = Distinct.fint.xmap(Age)(_.value).addh(Age(0)).distinct val dPersonAges = dAge.at(personAge) + dAge.lift[Set].at(personSet).addh(Age(500)) val dStuffAges = dPersonAges.lift[List].at(stuffPpl) + dAge.lift[List].at(stuffList) val dPplNames = Distinct.str.at(personName).lift[List] val dStuff = dPplNames.at(stuffPpl) * dStuffAges implicit def autoAge(i: Int) = Age(i) val p1 = Person("A", 10, Set(10, 20, 30)) val p2 = Person("B", 10, Set(50, 20)) val p3 = Person("B", 500, Set(5, 500)) val as = List[Age](10, 100, 0, 200, 30) val s = Stuff(as, List(p1, p2, p3)) def ages(s: Stuff): List[Age] = s.list ::: s.ppl.flatMap(p => p.age :: p.set.toList) def names(s: Stuff): List[String] = s.ppl.map(_.name) val t = dStuff.run(s) val List(sa, ta) = List(s, t) map ages val r = ta.toSet override def tests = Tests { "names" - assert(names(t).sorted == List("A", "B", "C")) "ages" - { "Same number of ages" - assert(sa.size == ta.size) "All ages distinct" - assert(r.size == ta.size) "Original ages preserved" - (sa.toSet[Age] - 0 - 500).foreach(o => assert(r contains o)) "No blacklisted ages" - assert(!r.contains(0), !r.contains(500)) } } }
Example 4
Source File: Opts.scala From hammock with MIT License | 5 votes |
package hammock package hi import cats.{Eq, Show} import cats.implicits._ import alleycats.Empty import monocle.{Lens, Optional} import monocle.macros.GenLens case class Opts(auth: Option[Auth], headers: Map[String, String], cookies: Option[List[Cookie]]) object Opts { val auth: Lens[Opts, Option[Auth]] = GenLens[Opts](_.auth) val authOpt: Optional[Opts, Auth] = Optional[Opts, Auth] { _.auth } { auth => { case opts @ Opts(Some(_), _, _) => opts.copy(auth = Some(auth)) case opts => opts } } val headers: Lens[Opts, Map[String, String]] = GenLens[Opts](_.headers) val cookies: Lens[Opts, Option[List[Cookie]]] = GenLens[Opts](_.cookies) val cookiesOpt: Optional[Opts, List[Cookie]] = Optional[Opts, List[Cookie]] { _.cookies } { cookies => { case opts @ Opts(_, _, Some(_)) => opts.copy(cookies = Some(cookies)) case opts => opts } } implicit val optsEmpty = new Empty[Opts] { def empty = Opts(None, Map(), None) } implicit val optsEq = new Eq[Opts] { def eqv(a: Opts, b: Opts): Boolean = a.auth === b.auth && a.headers === b.headers && a.cookies === b.cookies } implicit val optsShow: Show[Opts] = Show.fromToString val empty = optsEmpty.empty }
Example 5
Source File: package.scala From franklin with Apache License 2.0 | 5 votes |
package com.azavea.franklin.extensions import cats.Functor import cats.implicits._ import com.azavea.stac4s.extensions.label.{LabelItemExtension, LabelLinkExtension} import com.azavea.stac4s.extensions.layer.LayerItemExtension import com.azavea.stac4s.{StacItem, StacLink} import monocle.macros.GenLens package object validation { def getItemValidator(extensions: List[String]): StacItem => StacItem = { makeValidator(extensions map { s => ExtensionName.fromString(s) match { case Label => ItemValidator[LabelItemExtension].validate _ case Layer => ItemValidator[LayerItemExtension].validate _ case Unchecked(_) => (x: StacItem) => x } }) } def getLinkValidator(extensions: List[String]): StacLink => StacLink = { makeValidator(extensions map { s => ExtensionName.fromString(s) match { case Label => LinkValidator[LabelLinkExtension].validate _ case Layer => (x: StacLink) => x case Unchecked(_) => (x: StacLink) => x } }) } private def makeValidator[A](funcs: List[A => A]): A => A = funcs.toNel map { _.reduce((f1: A => A, f2: A => A) => f1 compose f2) } getOrElse { x => x } val linksLens = GenLens[StacItem](_.links) def validateItemAndLinks(item: StacItem): StacItem = { val itemValidator = getItemValidator(item.stacExtensions) val linkValidator = getLinkValidator(item.stacExtensions) (linksLens.modify(Functor[List].lift(linkValidator)) compose itemValidator)(item) } }
Example 6
Source File: OptimizedSvgApi.scala From reftree with GNU General Public License v3.0 | 5 votes |
package reftree.svg.api import monocle.Optional import monocle.macros.GenLens import reftree.geometry.{Color, Path, Point, Polyline} import reftree.util.Optics.{RichLens, RichOptional} case class SvgWrapper[Svg]( api: BaseSvgApi[Svg], svg: Svg, classes: Set[String], children: Option[List[SvgWrapper[Svg]]], translation: Option[Point], opacity: Option[Double], fillColor: Option[Option[Color]], strokeColor: Option[Option[Color]], strokeWidth: Option[Double], polygonPoints: Option[Polyline], pathPath: Option[Path], textPosition: Option[Point] ) { def unwrap: Svg = { api.immediateChildren.setOption(children.map(_.map(_.unwrap))) _ andThen api.translation.setOption(translation) andThen api.opacity.setOption(opacity) andThen api.fillColor.setOption(fillColor) andThen api.strokeColor.setOption(strokeColor) andThen api.strokeWidth.setOption(strokeWidth) andThen api.polygonPoints.setOption(polygonPoints) andThen api.pathPath.setOption(pathPath) andThen api.textPosition.setOption(textPosition) apply svg } } object SvgWrapper { def wrap[Svg](api: BaseSvgApi[Svg])(svg: Svg): SvgWrapper[Svg] = SvgWrapper( api, svg, api.elementClasses.get(svg), api.immediateChildren.getOption(svg).map(_.map(wrap(api))), api.translation.getOption(svg), api.opacity.getOption(svg), api.fillColor.getOption(svg), api.strokeColor.getOption(svg), api.strokeWidth.getOption(svg), api.polygonPoints.getOption(svg), api.pathPath.getOption(svg), api.textPosition.getOption(svg) ) } case class OptimizedSvgApi[Svg](api: BaseSvgApi[Svg]) extends BaseSvgApi[SvgWrapper[Svg]] { private val underlying = GenLens[SvgWrapper[Svg]](_.svg) val elementName = underlying composeGetter api.elementName val elementId = underlying composeGetter api.elementId val elementClasses = GenLens[SvgWrapper[Svg]](_.classes).asGetter lazy val translation: Optional[SvgWrapper[Svg], Point] = GenLens[SvgWrapper[Svg]](_.translation).asFlatOptional val immediateChildren: Optional[SvgWrapper[Svg], List[SvgWrapper[Svg]]] = GenLens[SvgWrapper[Svg]](_.children).asFlatOptional val shapeRendering = underlying composeOptional api.shapeRendering val textRendering = underlying composeOptional api.textRendering val viewBox = underlying composeOptional api.viewBox val opacity: Optional[SvgWrapper[Svg], Double] = GenLens[SvgWrapper[Svg]](_.opacity).asFlatOptional val fillColor: Optional[SvgWrapper[Svg], Option[Color]] = GenLens[SvgWrapper[Svg]](_.fillColor).asFlatOptional val strokeColor: Optional[SvgWrapper[Svg], Option[Color]] = GenLens[SvgWrapper[Svg]](_.strokeColor).asFlatOptional val strokeWidth: Optional[SvgWrapper[Svg], Double] = GenLens[SvgWrapper[Svg]](_.strokeWidth).asFlatOptional val polygonPoints: Optional[SvgWrapper[Svg], Polyline] = GenLens[SvgWrapper[Svg]](_.polygonPoints).asFlatOptional val pathPath: Optional[SvgWrapper[Svg], Path] = GenLens[SvgWrapper[Svg]](_.pathPath).asFlatOptional val textPosition: Optional[SvgWrapper[Svg], Point] = GenLens[SvgWrapper[Svg]](_.textPosition).asFlatOptional val anchorTitle = underlying composeOptional api.anchorTitle }
Example 7
Source File: Downsample.scala From osmesa with Apache License 2.0 | 5 votes |
package osmesa.bm import geotrellis.vector._ import org.apache.spark.rdd.RDD import vectorpipe.osm._ import monocle.macros.GenLens import com.vividsolutions.jts.algorithm.Centroid object Downsample { val tags = GenLens[vectorpipe.osm.ElementMeta](_.tags) def transmute(rdd: RDD[OSMFeature]) = { rdd.map({ f => val geom = { val _geom = Centroid.getCentroid(f.geom.jtsGeom) Point(_geom.x, _geom.y) } val data = tags.set(f.data.tags + ("multiplicity" -> 1.toString))(f.data) new OSMFeature(geom, data) }) } private def getAddress(f: OSMFeature, zoom: Int): (Double, Double) = { f.geom match { case p: Point => val u: Double = (p.x + 180.0)/360.0 val v: Double = (p.y + 90.0)/180.0 val x: Long = java.lang.Double.doubleToRawLongBits(u) >> (48-zoom) val y: Long = java.lang.Double.doubleToRawLongBits(v) >> (48-zoom) (x, y) case _ => throw new Exception } } def apply(rdd: RDD[OSMFeature], zoom: Int) = { rdd .map({ f => (getAddress(f, zoom), f) }) .reduceByKey({ case (f1: OSMFeature, f2: OSMFeature) => val mult1 = f1.data.tags.getOrElse("multiplicity", throw new Exception).toInt val mult2 = f2.data.tags.getOrElse("multiplicity", throw new Exception).toInt val geom = f1.geom val data = tags.set(f1.data.tags + ("multiplicity" -> (mult1+mult2).toString))(f1.data) new OSMFeature(geom, data) }) .values } }
Example 8
Source File: Options.scala From sansible with MIT License | 5 votes |
package ansible.std import ansible.CommonOptions._ import ansible.Playbook.{Options => POpts} import ansible.Task.{Options => TOpts} import ansible.{CommonOptions, Playbook, Task} import monocle.macros.GenLens trait Options { implicit object PlaybookCommonOpts extends CommonOptions[POpts] { override def tags(o: POpts) = o.tags override def become(o: POpts) = o.become override def setBecome(o: POpts, b: Become) = o.copy(become = Some(b)) override def setTags(o: POpts, ts: Set[Tag]) = o.copy(tags = Some(ts)) override def setRemoteUser(o: POpts, u: String) = o.copy(remoteUser = Some(u)) override def remoteUser(o: POpts) = o.remoteUser override def setEnv(o: POpts, e: Map[String, String]) = o.copy(env = Some(e)) override def serial(o: POpts) = o.serial override def setSerial(o: POpts, s: Serial) = o.copy(serial = Some(s)) override def env(o: POpts) = o.env } implicit object PlaybookOptics extends Optics[Playbook, POpts] { override def ev = PlaybookCommonOpts override def optionsLens = GenLens[Playbook](_.options) } implicit object TaskCommonOpts extends CommonOptions[TOpts] { override def tags(o: TOpts) = o.tags override def become(o: TOpts) = o.become override def setBecome(o: TOpts, b: Become) = o.copy(become = Some(b)) override def setTags(o: TOpts, ts: Set[Tag]) = o.copy(tags = Some(ts)) override def setRemoteUser(o: TOpts, u: String) = o.copy(remoteUser = Some(u)) override def remoteUser(o: TOpts) = o.remoteUser override def setEnv(o: TOpts, e: Map[String, String]) = o.copy(env = Some(e)) override def serial(o: TOpts) = o.serial override def setSerial(o: TOpts, s: Serial) = o.copy(serial = Some(s)) override def env(o: TOpts) = o.env } implicit object TaskOptics extends Optics[Task, TOpts] { override def ev = TaskCommonOpts override def optionsLens = GenLens[Task](_.options) } }
Example 9
Source File: AliasWithLensSpec.scala From Vegas with MIT License | 5 votes |
package vegas.macros import monocle.Lens import monocle.macros.GenLens import org.scalatest.{FlatSpec, Matchers} import scala.annotation.StaticAnnotation class AliasWithLensSpec extends FlatSpec with Matchers { class ignore_me extends StaticAnnotation case class Ex(a: Int) val _a = GenLens[Ex](_.a) @aliased trait Test { @alias_with_lens("fnA1", _a) private def fnA(a: Lens[Ex, Int])(b: Int, c: String) = (a, b, c) @ignore_me private def fnB(a: Lens[Ex, Int])(b: Int, c: String) = (a, b, c) @alias_with_lens("fnC1", _a) @ignore_me private def fnC(a: Lens[Ex, Int])(b: Int, c: String) = (a, b, c) } "alias_with_lens" should "alias the annotated method and partially apply it using the given lens" in { val t = new Test { } t.fnA1(1, "2") should equal((_a, 1, "2")) } it should "ignore other annotations" in { val t = new Test { } t.fnC1(1, "2") should equal((_a, 1, "2")) } }
Example 10
Source File: OpticsExamples.scala From scala-tutorials with MIT License | 5 votes |
package com.baeldung.scala.monocle import monocle.{Iso, Lens, Prism, Optional} import monocle.macros.GenLens import monocle.macros.Lenses object OpticsExamples { trait Discount case class NoDiscount() extends Discount case class PercentageOff(value: Double) extends Discount case class FixPriceOff(value: Double) extends Discount case class User(name: String, cart: Cart) case class Cart(id: String, item: Item, quantity: Int) case class Item( sku: String, price: Double, leftInStock: Int, discount: Discount ) def updateStockWithoutLenses(user: User): User = { user.copy( cart = user.cart.copy( item = user.cart.item.copy(leftInStock = user.cart.item.leftInStock - 1) ) ) } def updateStockWithLenses(user: User): User = { val cart: Lens[User, Cart] = GenLens[User](_.cart) val item: Lens[Cart, Item] = GenLens[Cart](_.item) val leftInStock: Lens[Item, Int] = GenLens[Item](_.leftInStock) (cart composeLens item composeLens leftInStock).modify(_ - 1)(user) } def updateDiscountedItemsPrice(cart: Cart, newDiscount: Double): Cart = { val discountLens: Lens[Item, Discount] = GenLens[Item](_.discount) val onlyPctDiscount = Prism.partial[Discount, Double] { case PercentageOff(p) => p }(PercentageOff) val newItem = (discountLens composePrism onlyPctDiscount set newDiscount)(cart.item) cart.copy(item = newItem) } def getDiscountValue(discount: Discount): Option[Double] = { val maybeDiscountValue = Optional[Discount, Double] { case pctOff: PercentageOff => Some(pctOff.value) case fixOff: FixPriceOff => Some(fixOff.value) case _ => None } { discountValue => discount => discount match { case pctOff: PercentageOff => pctOff.copy(value = discountValue) case fixOff: FixPriceOff => fixOff.copy(value = discountValue) case _ => discount } } maybeDiscountValue.getOption(discount) } case class PriceEUR(value: Double) case class PriceGBP(value: Double) val tranformCurrency = Iso[PriceEUR, PriceGBP] { eur => PriceGBP(eur.value * 0.9) } { gbp => PriceEUR(gbp.value / 0.9) } }