text:
package sp.domain.logic

import java.time._
import sp.domain._
import play.api.libs.json._
import play.api.libs.json.Reads.verifying

object JsonLogic extends JsonImplicit

trait JsonImplicit extends JsonDerived {

  def writeJson[T](x: T)(implicit fjs: JSWrites[T]) = {
    Json.stringify(Json.toJson(x))
  }

  // testing not using derive macros to limit the compiled size
  // due macro expansion. Especially in scala js.

  import play.api.libs.json.Reads._ // Custom validation helpers
  import play.api.libs.functional.syntax._

  def extrObj[T](json: JsValue, t: String, reader: Reads[T]) = {
    val conv = (JsPath \ "isa").read[String](verifying[String](_ == t)).reads(json)
    conv.flatMap(t => reader.reads(json))
  }

  // StateEvaluator and Updater

  implicit lazy val readASSIGN: Reads[ASSIGN] = new Reads[ASSIGN] {
    def reads(json: JsValue): JsResult[ASSIGN] = {
      val rr = (JsPath \ "id").read[ID].map(id => ASSIGN(id))
      extrObj(json, "ASSIGN", rr)
    }
  }
  implicit lazy val writeASSIGN: Writes[ASSIGN] = new Writes[ASSIGN] {
    override def writes(o: ASSIGN): SPValue =  Json.obj(
      "isa"->"ASSIGN",
      "id" -> o.id
    )
  }
  implicit lazy val readDECR: Reads[DECR] = new Reads[DECR] {
    def reads(json: JsValue): JsResult[DECR] = {
      val rr = (JsPath \ "n").read[Int].map(x => DECR(x))
      extrObj(json, "DECR", rr)
    }
  }
  implicit lazy val writeDECR: Writes[DECR] = new Writes[DECR] {
    override def writes(o: DECR): SPValue = Json.obj(
      "isa"->"DECR",
      "n" -> o.n
    )
  }
  implicit lazy val readINCR: Reads[INCR] = new Reads[INCR] {
    def reads(json: JsValue): JsResult[INCR] = {
      val rr = (JsPath \ "n").read[Int].map(x => INCR(x))
      extrObj(json, "INCR", rr)
    }
  }
  implicit lazy val writeINCR: Writes[INCR] = new Writes[INCR] {
    override def writes(o: INCR): SPValue = Json.obj(
      "isa"->"INCR",
      "n" -> o.n
    )
  }
  implicit lazy val readValueHolder: Reads[ValueHolder] = new Reads[ValueHolder] {
    def reads(json: JsValue): JsResult[ValueHolder] = {
      val rr = (JsPath \ "v").read[SPValue].map(x => ValueHolder(x))
      extrObj(json, "ValueHolder", rr)
    }
  }
  implicit lazy val writeValueHolder: Writes[ValueHolder] = new Writes[ValueHolder] {
    override def writes(o: ValueHolder): SPValue = Json.obj(
      "isa"->"ValueHolder",
      "v" -> o.v
    )
  }
  implicit lazy val readSVIDEval: Reads[SVIDEval] = new Reads[SVIDEval] {
    def reads(json: JsValue): JsResult[SVIDEval] = {
      val rr = (JsPath \ "id").read[ID].map(id => SVIDEval(id))
      extrObj(json, "SVIDEval", rr)
    }
  }
  implicit lazy val writeSVIDEval: Writes[SVIDEval] = new Writes[SVIDEval] {
    override def writes(o: SVIDEval): SPValue = Json.obj(
      "isa"->"SVIDEval",
      "id" -> o.id
    )
  }
  implicit lazy val readStateUpd: Reads[StateUpdater] = new JSReads[StateUpdater] {
    override def reads(json: SPValue): JsResult[StateUpdater] = {
      json.validate[ValueHolder] orElse
        json.validate[INCR] orElse
        json.validate[DECR] orElse
        json.validate[ASSIGN]
    }
  }
  implicit lazy val writeStateUpd: Writes[StateUpdater] = new Writes[StateUpdater] {
    override def writes(o: StateUpdater): SPValue = {
      o match {
        case x: ValueHolder => Json.toJson(x)(writeValueHolder)
        case x: INCR => Json.toJson(x)(writeINCR)
        case x: DECR => Json.toJson(x)(writeDECR)
        case x: ASSIGN => Json.toJson(x)(writeASSIGN)
      }
    }
  }

  implicit lazy val readStateEval: Reads[StateEvaluator] = new JSReads[StateEvaluator] {
    override def reads(json: SPValue): JsResult[StateEvaluator] = {
      json.validate[ValueHolder] orElse
        json.validate[SVIDEval]
    }
  }
  implicit lazy val writeStateEval: Writes[StateEvaluator] = new Writes[StateEvaluator] {
    override def writes(o: StateEvaluator): SPValue = {
      o match {
        case x: ValueHolder => Json.toJson(x)(writeValueHolder)
        case x: SVIDEval => Json.toJson(x)(writeSVIDEval)
      }
    }
  }

  // Propositions and conditions

  def rr[T](make: (StateEvaluator, StateEvaluator) => T) = {
    val left = (JsPath \ "left").read[StateEvaluator]
    val right = (JsPath \ "right").read[StateEvaluator]
    left.flatMap(l => right.map(r => make(l, r)))
  }
  def ww(isa: String, left: StateEvaluator, right: StateEvaluator) = {
    Json.obj(
      "isa"->isa,
      "left"->left,
      "right"->right
    )
  }

  implicit lazy val readEQ: Reads[EQ] = new Reads[EQ] {
    def reads(json: JsValue): JsResult[EQ] = {
      extrObj(json, "EQ", rr(EQ.apply))
    }
  }
  implicit lazy val writeEQ: Writes[EQ] = new Writes[EQ] {
    override def writes(o: EQ): SPValue = {
      ww("EQ", o.left, o.right)
    }
  }
  implicit lazy val readNEQ: Reads[NEQ] = new Reads[NEQ] {
    def reads(json: JsValue): JsResult[NEQ] = {
      extrObj(json, "NEQ", rr(NEQ.apply))
    }
  }
  implicit lazy val writeNEQ: Writes[NEQ] = new Writes[NEQ] {
    override def writes(o: NEQ): SPValue = {
      ww("NEQ", o.left, o.right)
    }
  }
  implicit lazy val readGREQ: Reads[GREQ] = new Reads[GREQ] {
    def reads(json: JsValue): JsResult[GREQ] = {
      extrObj(json, "GREQ", rr(GREQ.apply))
    }
  }
  implicit lazy val writeGREQ: Writes[GREQ] = new Writes[GREQ] {
    override def writes(o: GREQ): SPValue = {
      ww("GREQ", o.left, o.right)
    }
  }
  implicit lazy val readLEEQ: Reads[LEEQ] = new Reads[LEEQ] {
    def reads(json: JsValue): JsResult[LEEQ] = {
      extrObj(json, "LEEQ", rr(LEEQ.apply))
    }
  }
  implicit lazy val writeLEEQ: Writes[LEEQ] = new Writes[LEEQ] {
    override def writes(o: LEEQ): SPValue = {
      ww("LEEQ", o.left, o.right)
    }
  }
  implicit lazy val readGR: Reads[GR] = new Reads[GR] {
    def reads(json: JsValue): JsResult[GR] = {
      extrObj(json, "GR", rr(GR.apply))
    }
  }
  implicit lazy val writeGR: Writes[GR] = new Writes[GR] {
    override def writes(o: GR): SPValue = {
      ww("GR", o.left, o.right)
    }
  }
  implicit lazy val readLE: Reads[LE] = new Reads[LE] {
    def reads(json: JsValue): JsResult[LE] = {
      extrObj(json, "LE", rr(LE.apply))
    }
  }
  implicit lazy val writeLE: Writes[LE] = new Writes[LE] {
    override def writes(o: LE): SPValue = {
      ww("LE", o.left, o.right)
    }
  }
  implicit lazy val readPropEval: Reads[PropositionEvaluator] = new JSReads[PropositionEvaluator] {
    override def reads(json: SPValue): JsResult[PropositionEvaluator] = {
        json.validate[EQ] orElse
        json.validate[NEQ] orElse
        json.validate[GREQ] orElse
        json.validate[LEEQ] orElse
        json.validate[GR] orElse
        json.validate[LE]
    }
  }
  implicit lazy val writePropEval: Writes[PropositionEvaluator] = new Writes[PropositionEvaluator] {
    override def writes(o: PropositionEvaluator): SPValue = {
      o match {
        case x: EQ => Json.toJson(x)(writeEQ)
        case x: NEQ => Json.toJson(x)(writeNEQ)
        case x: GREQ => Json.toJson(x)(writeGREQ)
        case x: LEEQ => Json.toJson(x)(writeLEEQ)
        case x: GR => Json.toJson(x)(writeGR)
        case x: LE => Json.toJson(x)(writeLE)
      }
    }
  }

  def extrObj2[T](json: JsValue, t: String, reader: Reads[T]) = {
    val conv = (JsPath \ "isa").read[String](verifying[String](_ == t)).reads(json)
    conv.flatMap(t => reader.reads(json))
  }

  implicit lazy val propW: Writes[Proposition] =  WriteProp
  implicit lazy val readAND: Reads[AND] = new Reads[AND] {
    def reads(json: JsValue): JsResult[AND] = {
      val t = (JsPath \ "isa").read[String](verifying[String](_ == "AND")).reads(json)
      val res =  (JsPath \ "props").lazyRead(implicitly[Reads[List[Proposition]]]).reads(json)
      t.flatMap(x => res.map(xs => AND(xs)))
    }
  }
  implicit lazy val writeAND: Writes[AND] = new Writes[AND] {
    override def writes(o: AND): SPValue = Json.obj(
      "isa"->"AND",
      "props"->o.props
    )
  }
  implicit lazy val readOR: Reads[OR] = new Reads[OR] {
    def reads(json: JsValue): JsResult[OR] = {
      val t = (JsPath \ "isa").read[String](verifying[String](_ == "OR")).reads(json)
      val res =  (JsPath \ "props").lazyRead(implicitly[Reads[List[Proposition]]]).reads(json)
      t.flatMap(x => res.map(xs => OR(xs)))
    }
  }
  implicit lazy val writeOR: Writes[OR] = new Writes[OR] {
    override def writes(o: OR): SPValue = Json.obj(
      "isa"->"OR",
      "props"->o.props
    )
  }

  implicit lazy val readNOT: Reads[NOT] = new Reads[NOT] {
    def reads(json: JsValue): JsResult[NOT] = {
      val t = (JsPath \ "isa").read[String](verifying[String](_ == "NOT")).reads(json)
      val res =  (JsPath \ "p").lazyRead(implicitly[Reads[Proposition]]).reads(json)
      t.flatMap(x => res.map(xs => NOT(xs)))
    }
  }
  implicit lazy val writeNOT: Writes[NOT] = new Writes[NOT] {
    override def writes(o: NOT): SPValue = Json.obj(
      "isa"->"NOT",
      "p"->o.p
    )
  }

  def parseMe(x: SPValue): JsResult[Proposition] = {
    val res = x.asOpt[String].flatMap{ p =>
      Proposition.parseStr(p)
    }
    res match {
      case Some(ok) => JsSuccess[Proposition](ok)
      case None => JsError("Could not convert proposition from a string ")
    }
  }

  implicit lazy val readProp: Reads[Proposition] = new JSReads[Proposition] {
    override def reads(json: SPValue): JsResult[Proposition] = {
      json.validate[PropositionEvaluator] orElse
        json.validate[AND] orElse
        json.validate[OR] orElse
        json.validate[NOT] orElse
        (JsPath \ "isa").read[String](verifying[String](_ == "AlwaysTrue")).reads(json).map(x => AlwaysTrue) orElse
        (JsPath \ "isa").read[String](verifying[String](_ == "AlwaysFalse")).reads(json).map(x => AlwaysFalse) orElse
        parseMe(json)
    }
  }
  implicit object WriteProp extends Writes[Proposition]  {
    override def writes(o: Proposition): SPValue = {
      o match {
        case x: PropositionEvaluator => Json.toJson(x)(writePropEval)
        case x: AND => Json.toJson(x)(writeAND)
        case x: OR => Json.toJson(x)(writeOR)
        case x: NOT => Json.toJson(x)(writeNOT)
        case AlwaysTrue => Json.obj("isa"-> "AlwaysTrue")
        case AlwaysFalse => Json.obj("isa"-> "AlwaysFalse")
      }
    }
  }

  implicit lazy val actionsRead: JSReads[Action] = (
      (JsPath \ "id").read[ID] and
        (JsPath \ "value").read[StateUpdater]
    )(Action.apply _)

  implicit lazy val actionsWrites: JSWrites[Action] = (
    (JsPath \ "id").write[ID] and
      (JsPath \ "value").write[StateUpdater]
    )(unlift(Action.unapply))

  implicit lazy val condsRead: JSReads[Condition] = (
    (JsPath \ "guard").read[Proposition] and
    (JsPath \ "action").readWithDefault[List[Action]](List()) and
    (JsPath \ "attributes").readWithDefault[SPAttributes](SPAttributes.empty)
  )(Condition.apply _)
  implicit lazy val condsWrites: JSWrites[Condition] = (
    (JsPath \ "guard").write[Proposition] and
      (JsPath \ "action").write[List[Action]]and
      (JsPath \ "attributes").write[SPAttributes]
    )(unlift(Condition.unapply))

  // SOPs

  implicit lazy val sopW: Writes[SOP] =  WriteSOP
  def createTheSOP[T](json: JsValue, t: String, make: (List[SOP], ID) => T) = {
    val isa = (JsPath \ "isa").read[String](verifying[String](_ == t)).reads(json)
    val res =  (JsPath \ "sop").lazyRead(implicitly[Reads[List[SOP]]]).reads(json)
    val id =  (JsPath \ "nodeID").read[ID].reads(json).getOrElse(ID.newID)
    isa.flatMap(x => res.map(xs => make(xs, id)))
  }
  def wwSOP(isa: String, sop: List[SOP], nodeID: ID) = {
    Json.obj(
      "isa"->isa,
      "sop"->sop,
      "nodeID"->nodeID
    )
  }

  implicit lazy val readParallel: Reads[Parallel] = new Reads[Parallel] {
    def reads(json: JsValue): JsResult[Parallel] = {
      createTheSOP(json, "Parallel", Parallel.apply)
    }
  }
  implicit lazy val writeParallel: Writes[Parallel] = new Writes[Parallel] {
    override def writes(o: Parallel): SPValue = {
      wwSOP("Parallel", o.sop, o.nodeID)
    }
  }
  implicit lazy val readAlternative: Reads[Alternative] = new Reads[Alternative] {
    def reads(json: JsValue): JsResult[Alternative] = {
      createTheSOP(json, "Alternative", Alternative.apply)
    }
  }
  implicit lazy val writeAlternative: Writes[Alternative] = new Writes[Alternative] {
    override def writes(o: Alternative): SPValue = {
      wwSOP("Alternative", o.sop, o.nodeID)
    }
  }
  implicit lazy val readArbitrary: Reads[Arbitrary] = new Reads[Arbitrary] {
    def reads(json: JsValue): JsResult[Arbitrary] = {
      createTheSOP(json, "Arbitrary", Arbitrary.apply)
    }
  }
  implicit lazy val writeArbitrary: Writes[Arbitrary] = new Writes[Arbitrary] {
    override def writes(o: Arbitrary): SPValue = {
      wwSOP("Arbitrary", o.sop, o.nodeID)
    }
  }
  implicit lazy val readSequence: Reads[Sequence] = new Reads[Sequence] {
    def reads(json: JsValue): JsResult[Sequence] = {
      createTheSOP(json, "Sequence", Sequence.apply)
    }
  }
  implicit lazy val writeSequence: Writes[Sequence] = new Writes[Sequence] {
    override def writes(o: Sequence): SPValue = {
      wwSOP("Sequence", o.sop, o.nodeID)
    }
  }
  implicit lazy val readSometimeSequence: Reads[SometimeSequence] = new Reads[SometimeSequence] {
    def reads(json: JsValue): JsResult[SometimeSequence] = {
      createTheSOP(json, "SometimeSequence", SometimeSequence.apply)
    }
  }
  implicit lazy val writeSometimeSequence: Writes[SometimeSequence] = new Writes[SometimeSequence] {
    override def writes(o: SometimeSequence): SPValue = {
      wwSOP("SometimeSequence", o.sop, o.nodeID)
    }
  }
  implicit lazy val readOther: Reads[Other] = new Reads[Other] {
    def reads(json: JsValue): JsResult[Other] = {
      createTheSOP(json, "Other", Other.apply)
    }
  }
  implicit lazy val writeOther: Writes[Other] = new Writes[Other] {
    override def writes(o: Other): SPValue = {
      wwSOP("Other", o.sop, o.nodeID)
    }
  }
  implicit lazy val readOperationNode: Reads[OperationNode] = new Reads[OperationNode] {
    def reads(json: JsValue): JsResult[OperationNode] = {
      val isa = (JsPath \ "isa").read[String](verifying[String](_ == "OperationNode")).reads(json)
      val res =  (JsPath \ "sop").lazyRead(implicitly[Reads[List[SOP]]]).reads(json).getOrElse(List[SOP]())
      val id =  (JsPath \ "nodeID").read[ID].reads(json).getOrElse(ID.newID)
      val op =  (JsPath \ "operation").read[ID].reads(json)
      val conds =  (JsPath \ "conditions").read[List[Condition]].reads(json).getOrElse(List())
      isa.flatMap(x => op.map(o => OperationNode(o, conds, res, id)))
    }
  }
  implicit lazy val writeOperationNode: Writes[OperationNode] = new Writes[OperationNode] {
    override def writes(o: OperationNode): SPValue = Json.obj(
      "isa"->"OperationNode",
      "operation" -> o.operation,
      "conditions"-> o.conditions,
      "sop"-> o.sop,
      "nodeID"->o.nodeID
    )
  }

  implicit lazy val readSOP: Reads[SOP] = new JSReads[SOP] {
    override def reads(json: SPValue): JsResult[SOP] = {
        json.validate[Parallel] orElse
        json.validate[Alternative] orElse
        json.validate[Arbitrary] orElse
        json.validate[Sequence] orElse
        json.validate[SometimeSequence] orElse
        json.validate[Other] orElse
        json.validate[OperationNode] orElse
        (JsPath \ "isa").read[String](verifying[String](_ == "EmptySOP")).reads(json).map(x => EmptySOP)
    }
  }
  implicit object WriteSOP extends Writes[SOP]  {
    override def writes(o: SOP): SPValue = {
      o match {
        case x: Parallel => Json.toJson(x)(writeParallel)
        case x: Alternative => Json.toJson(x)(writeAlternative)
        case x: Arbitrary => Json.toJson(x)(writeArbitrary)
        case x: Sequence => Json.toJson(x)(writeSequence)
        case x: SometimeSequence => Json.toJson(x)(writeSometimeSequence)
        case x: Other => Json.toJson(x)(writeOther)
        case x: OperationNode => Json.toJson(x)(writeOperationNode)
        case EmptySOP => Json.obj("isa"-> "EmptySOP")
      }
    }
  }

  // IDAble
  implicit lazy val structRead: JSReads[StructNode] = (
    (JsPath \ "item").read[ID] and
      (JsPath \ "parent").readNullableWithDefault[ID](None) and
      (JsPath \ "nodeID").read[ID] and
      (JsPath \ "attributes").readWithDefault[SPAttributes](SPAttributes.empty)
  )(StructNode.apply _)

  implicit lazy val structwrites: JSWrites[StructNode] = (
    (JsPath \ "item").write[ID] and
      (JsPath \ "parent").writeNullable[ID] and
      (JsPath \ "nodeID").write[ID] and
      (JsPath \ "attributes").write[SPAttributes](SPAttributes.empty)
    )(unlift(StructNode.unapply))
  //

  implicit lazy val stateReads: JSReads[Map[ID, SPValue]] = new JSReads[Map[ID, SPValue]] {
    override def reads(json: JsValue): JsResult[Map[ID, SPValue]] = {
      json.validate[Map[String, SPValue]].map(xs => xs.collect{case (k, v) if ID.isID(k) => ID.makeID(k).get -> v})
    }
  }
  implicit lazy val stateWrites: JSWrites[Map[ID, SPValue]] = new OWrites[Map[ID, SPValue]] {
    override def writes(xs: Map[ID, SPValue]): JsObject = {
      val toFixedMap = xs.map{case (k, v) => k.toString -> v}
      JsObject(toFixedMap)
    }
  }

  def extrIDable(isa: String, json: SPValue) = {
    val conv = (JsPath \ "isa").read[String](verifying[String](_ == isa)).reads(json)
    val name = (JsPath \ "name").read[String].reads(json)
    val id = (JsPath \ "id").read[ID].reads(json).getOrElse(ID.newID)
    val attr = (JsPath \ "attributes").read[SPAttributes].reads(json).getOrElse(SPAttributes.empty)
    conv.flatMap(i => name.map(n => (n, id, attr)))
  }

  def wwIDAble(isa: String, extra: SPAttributes, x: IDAble): JsObject = {
    val first = Json.obj(
      "isa"-> isa,
      "name"-> x.name)
    val last = Json.obj(
      "attributes"-> x.attributes,
      "id"-> x.id
    )

    first ++ extra ++ last
  }

  implicit lazy val readOperation: Reads[Operation] = new Reads[Operation] {
    def reads(json: JsValue): JsResult[Operation] = {
      val idable = extrIDable("Operation", json)
      val cond = (JsPath \ "conditions").read[List[Condition]].reads(json).getOrElse(List())
      idable.map{case (n, id, attr) => Operation(n, cond, attr, id)}
    }
  }
  implicit lazy val writeOperation: Writes[Operation] = new Writes[Operation] {
    override def writes(o: Operation): SPValue = {
      wwIDAble("Operation", SPAttributes("conditions"->o.conditions), o)
    }
  }
  implicit lazy val readThing: Reads[Thing] = new Reads[Thing] {
    def reads(json: JsValue): JsResult[Thing] = {
      val idable = extrIDable("Thing", json)
      idable.map{case (n, id, attr) => Thing(n, attr, id)}
    }
  }
  implicit lazy val writeThing: Writes[Thing] = new Writes[Thing] {
    override def writes(o: Thing): SPValue = {
      wwIDAble("Thing", SPAttributes.empty, o)
    }
  }
  implicit lazy val readSOPSpec: Reads[SOPSpec] = new Reads[SOPSpec] {
    def reads(json: JsValue): JsResult[SOPSpec] = {
      val idable = extrIDable("SOPSpec", json)
      val sop = (JsPath \ "sop").read[List[SOP]].reads(json).getOrElse(List())
      idable.map{case (n, id, attr) => SOPSpec(n, sop, attr, id)}
    }
  }
  implicit lazy val writeSOPSpec: Writes[SOPSpec] = new Writes[SOPSpec] {
    override def writes(o: SOPSpec): SPValue = {
      wwIDAble("SOPSpec", SPAttributes("sop"->o.sop), o)
    }
  }
  implicit lazy val readSPSpec: Reads[SPSpec] = new Reads[SPSpec] {
    def reads(json: JsValue): JsResult[SPSpec] = {
      val idable = extrIDable("SPSpec", json)
      idable.map{case (n, id, attr) => SPSpec(n, attr, id)}
    }
  }
  implicit lazy val writeSPSpec: Writes[SPSpec] = new Writes[SPSpec] {
    override def writes(o: SPSpec): SPValue = {
      wwIDAble("SPSpec", SPAttributes.empty, o)
    }
  }
  implicit lazy val readSPResult: Reads[SPResult] = new Reads[SPResult] {
    def reads(json: JsValue): JsResult[SPResult] = {
      val idable = extrIDable("SPResult", json)
      idable.map{case (n, id, attr) => SPResult(n, attr, id)}
    }
  }
  implicit lazy val writeSPResult: Writes[SPResult] = new Writes[SPResult] {
    override def writes(o: SPResult): SPValue = {
      wwIDAble("SPResult", SPAttributes.empty, o)
    }
  }
  implicit lazy val readSPState: Reads[SPState] = new Reads[SPState] {
    def reads(json: JsValue): JsResult[SPState] = {
      val idable = extrIDable("SPState", json)
      val state = (JsPath \ "state").read[Map[ID, SPValue]].reads(json).getOrElse(Map())
      idable.map{case (n, id, attr) => SPState(n, state, attr, id)}
    }
  }
  implicit lazy val writeSPState: Writes[SPState] = new Writes[SPState] {
    override def writes(o: SPState): SPValue = {
      wwIDAble("SPState", SPAttributes("state"->o.state), o)
    }
  }
  implicit lazy val readStruct: Reads[Struct] = new Reads[Struct] {
    def reads(json: JsValue): JsResult[Struct] = {
      val idable = extrIDable("Struct", json)
      val items = (JsPath \ "items").read[List[StructNode]].reads(json).getOrElse(List())
      idable.map{case (n, id, attr) => Struct(n, items.toSet, attr, id)}
    }
  }
  implicit lazy val writeStruct: Writes[Struct] = new Writes[Struct] {
    override def writes(o: Struct): SPValue = {
      wwIDAble("Struct", SPAttributes("items"->o.items), o)
    }
  }

  implicit lazy val readIDAble: Reads[IDAble] = new JSReads[IDAble] {
    override def reads(json: SPValue): JsResult[IDAble] = {
        json.validate[Operation] orElse
        json.validate[Thing] orElse
        json.validate[SOPSpec] orElse
        json.validate[SPSpec] orElse
        json.validate[SPResult] orElse
        json.validate[SPState] orElse
        json.validate[Struct]
    }
  }
  implicit object WriteIDAble extends Writes[IDAble]  {
    override def writes(o: IDAble): SPValue = {
      o match {
        case x: Operation=> Json.toJson(x)(writeOperation)
        case x: Thing=> Json.toJson(x)(writeThing)
        case x: SOPSpec=> Json.toJson(x)(writeSOPSpec)
        case x: SPSpec=> Json.toJson(x)(writeSPSpec)
        case x: SPResult=> Json.toJson(x)(writeSPResult)
        case x: SPState=> Json.toJson(x)(writeSPState)
        case x: Struct=> Json.toJson(x)(writeStruct)
      }
    }
  }

  // Extra formats

  lazy val dateF = format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
  implicit lazy val javatimeF = new Format[ZonedDateTime] {
    override def reads(json: JsValue): JsResult[ZonedDateTime] = {
      json.validate[String].map(ZonedDateTime.parse(_, dateF))
    }

    override def writes(o: ZonedDateTime): JsValue = {
      Json.toJson(o.format(dateF))
    }

  }

  implicit lazy val ididReads: JSReads[Map[ID, ID]] = new JSReads[Map[ID, ID]] {
    override def reads(json: JsValue): JsResult[Map[ID, ID]] = {
      json.validate[Map[String, String]].map(xs => xs.collect{case (k, v) if ID.isID(k) && ID.isID(v) => ID.makeID(k).get -> ID.makeID(v).get})
    }
  }
  implicit lazy val ididWrites: JSWrites[Map[ID, ID]] = new OWrites[Map[ID, ID]] {
    override def writes(xs: Map[ID, ID]): JsObject = {
      val toFixedMap = xs.map{case (k, v) => k.toString -> SPValue(v)}
      JsObject(toFixedMap)
    }
  }

}

trait JsonDerived{
  //def spFormat[A]: OFormat[A] =  derived.oformat[A]()
  val jsonISA = (__ \ "isa").format[String]

  import play.api.libs.json.{OFormat, OWrites, Reads}
  import shapeless.Lazy
  import julienrf.json.derived._

  val derive: Json.type = Json

  def deriveCaseObject[A](implicit derivedReads: Lazy[DerivedReads[A]], derivedOWrites: Lazy[DerivedOWrites[A]]): OFormat[A] =
    OFormat(derivedReads.value.reads(TypeTagReads.nested, NameAdapter.identity), derivedOWrites.value.owrites(TypeTagOWrites.nested, NameAdapter.identity))

  def deriveFormatSimple[A](implicit derivedReads: Lazy[DerivedReads[A]], derivedOWrites: Lazy[DerivedOWrites[A]]): OFormat[A] =
    OFormat(derivedReads.value.reads(TypeTagReads.nested, NameAdapter.identity), derivedOWrites.value.owrites(TypeTagOWrites.nested, NameAdapter.identity))

  def deriveFormatISA[A](implicit derivedReads: Lazy[DerivedReads[A]], derivedOWrites: Lazy[DerivedOWrites[A]]): OFormat[A] =
    OFormat(derivedReads.value.reads(TypeTagReads.flat(jsonISA), NameAdapter.identity), derivedOWrites.value.owrites(TypeTagOWrites.flat(jsonISA), NameAdapter.identity))

 def deriveReadISA[A](implicit derivedReads: Lazy[DerivedReads[A]]): Reads[A] =
    derivedReads.value.reads(TypeTagReads.flat(jsonISA), NameAdapter.identity)

 def deriveWriteISA[A](implicit derivedOWrites: Lazy[DerivedOWrites[A]]): OWrites[A] =
     derivedOWrites.value.owrites(TypeTagOWrites.flat(jsonISA), NameAdapter.identity)

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: viet
 * Date: 24/06/15
 * Time: 14:21
 */
namespace Blog\Controller;

use Blog\Service\PostServiceInterface;
use Zend\Form\FormInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class DeleteController extends AbstractActionController
{
    protected $postService;

    public function __construct(PostServiceInterface $postService)
    {
        $this->postService = $postService;
    }
    public function deleteAction() {
        try {
            $post = $this->postService->findPost($this->params('id'));
        } catch (\InvalidArgumentException $e) {
            return $this->redirect()->toRoute('post');
        }

        $request = $this->getRequest();

        if ($request->isPost()) {
            $del = $request->getPost('delete_confirmation', 'no');

            if ($del === 'yes') {
                $this->postService->deletePost($post);
            }

            return $this->redirect()->toRoute('post');
        }

        return new ViewModel(array(
            'post' => $post
        ));
    }
}

redpajama_set_name: RedPajamaGithub


text:
describe("bug #4196: HTTP basic auth credential retention", function () {
    let mainPage
    beforeEach(function (client, done) {
        mainPage = client
            .url("localhost:3230")
            .page.main()

        client.waitForElementVisible(".download-url-input:not([disabled])", 5000)
            .pause(80)
            .clearValue(".download-url-input")
            .setValue(".download-url-input", "http://localhost:3230/test-specs/bugs/4196.yaml")
            .click("button.download-url-button")
            .pause(1000)

        done()
    })
    afterEach(function (client, done) {
        done()
    })
    it("should display the most recent auth data across modal close/opens", function (client) {
        client.waitForElementVisible(".opblock-tag-section", 10000)
            .click("button.btn.authorize") // Open modal
            .waitForElementVisible("section>input", 5000)
            .setValue("section>input", "aaa") // Set user
            .waitForElementVisible(`section>input[type="password"]`, 5000)
            .setValue(`section>input[type="password"]`, "aaa") // Set password
            .click(".auth-btn-wrapper button:nth-child(1)") // Click Authorize
            .assert.containsText("div.wrapper:nth-child(4)>code", "aaa")
            .click(".auth-btn-wrapper button:nth-child(2)") // Close modal
            .pause(50)
            .click("button.btn.authorize") // Open modal
            .pause(50)
            .click(".auth-btn-wrapper button:nth-child(1)") // Logout
            .waitForElementVisible("section>input", 5000)
            .setValue("section>input", "bbb") // Set user
            .waitForElementVisible(`section>input[type="password"]`, 5000)
            .setValue(`section>input[type="password"]`, "bbb") // Set password
            .click(".auth-btn-wrapper button:nth-child(1)") // Click Authorize
            .pause(5000)
            .assert.containsText("div.wrapper:nth-child(4)>code", "bbb")

        client.end()
    })
})


text:
from django.conf import settings

# TODO: this setting is deprecated, add a deprecation notice
PROPRIETARY_BACKEND_NAME = getattr(settings, 'PROPRIETARY_BACKEND_NAME', "Django")

REST_AUTH_BACKEND_NAME = getattr(settings, 'REST_AUTH_BACKEND_NAME', PROPRIETARY_BACKEND_NAME)
REST_AUTH_URL_NAMESPACE = getattr(settings, 'REST_AUTH_URL_NAMESPACE', 'rest_framework_social_oauth2')


text:
require 'sanatio/built-in/support/compare'

module Sanatio
  module BuiltIn
    class LessThan < Compare
      def initialize(value)
        super(value, :<)
      end

      def reason(_)
        :greater_than_or_equal_to
      end
    end
  end
end


text:
package wikokit.base.wikt.sql.test;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import junit.framework.TestCase;

import wikokit.base.wikt.sql.*;

import wikokit.base.wikipedia.language.LanguageType;
import wikokit.base.wikipedia.sql.Connect;

public class TLangTest extends TestCase {

	public Context context = null;
	Connect ruwikt_conn;

	protected void setUp() throws Exception {
		super.setUp();
		ruwikt_conn = new Connect(context, LanguageType.ru);
		ruwikt_conn.openDatabase();
	}

	protected void tearDown() throws Exception {
		super.tearDown();
		ruwikt_conn.close();
	}

	public void testGetID() {
		System.out.println("getID");

		// once upon a time: create Wiktionary parsed db
        // skip for SQLite: TLang.recreateTable(ruwikt_conn);

		SQLiteDatabase db = ruwikt_conn.getDB();

        // once upon a time: use Wiktionary parsed db
        TLang.createFastMaps(db);

        // and every usual day
        int os_id = TLang.getIDFast(LanguageType.os);

        TLang tlang = TLang.get(db, LanguageType.os);
        assertNotNull(tlang);
        assertEquals(tlang.getID(), os_id);
	}
	/*
	public void testGetIDFast() {
		fail("Not yet implemented");
	}

	public void testGetTLangFast() {
		fail("Not yet implemented");
	}

	public void testGet() {
		fail("Not yet implemented");
	}

	public void testGetAllLanguages() {
		fail("Not yet implemented");
	}

	public void testGetAllTLang() {
		fail("Not yet implemented");
	}*/

	public void testParseLangCode() {

		System.out.println("parseLangCode");
        String str;
        TLang[] langs;

        str = "";
        langs = TLang.parseLangCode(str);
        assertTrue(langs != null);
        assertTrue(langs.length == 0);

        str = " not_valid language-code";
        langs = TLang.parseLangCode(str);
        assertTrue(langs != null);
        assertTrue(langs.length == 0);

        str = " en only-one-valid-code";
        langs = TLang.parseLangCode(str);
        assertTrue(langs != null);
        assertTrue(langs.length == 1);

        str = " en lt ru os fr it's enough";
        langs = TLang.parseLangCode(str);
        assertTrue(langs != null);
        assertTrue(langs.length == 5);
	}

	public void testIsEquals() {
		 System.out.println("isEquals");
	        String str_lang2;
	        TLang tlang1[];
	        boolean res;

	        // isEquals(TLang tlang1[], String str_lang2)

	        tlang1 = new TLang[0];
	        // source_lang[0] = TLang.get(LanguageType.en);

	        // 0 == 0
	        str_lang2 = "";
	        res = TLang.isEquals(tlang1, str_lang2);
	        assertTrue(res); // empty codes are equal

	        // 0 == 0
	        str_lang2 = "non-language_code";
	        res = TLang.isEquals(tlang1, str_lang2);
	        assertTrue(res);

	        // "en" != 0
	        str_lang2 = "non-language_code and one language code en";
	        res = TLang.isEquals(tlang1, str_lang2);
	        assertFalse(res);

	        // "en" != "de"
	        str_lang2 = "en";
	        tlang1 = new TLang[1];
	        tlang1[0] = TLang.get(LanguageType.de);
	        res = TLang.isEquals(tlang1, str_lang2);
	        assertFalse(res);

	        // "os fr" == "fr os"
	        str_lang2 = "os fr";
	        tlang1 = new TLang[2];
	        tlang1[0] = TLang.get(LanguageType.fr);
	        tlang1[1] = TLang.get(LanguageType.os);
	        res = TLang.isEquals(tlang1, str_lang2);
	        assertTrue(res);
	}

	/*public void testCreateFastMaps() {
		fail("Not yet implemented");
	}*/

}


text:
<?php

namespace Mtt\BlogBundle\Entity\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Mtt\BlogBundle\Entity\SystemParameters;

/**
 * SystemParametersRepository
 *
 * @method SystemParameters|null findOneByOptionKey($key)
 */
class SystemParametersRepository extends ServiceEntityRepository
{
    /**
     * @param ManagerRegistry $registry
     */
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, SystemParameters::class);
    }
}


text:
<nb-card>
  <nb-card-body class="example-last-child-no-b-margin">
    <nb-alert status="basic">Basic. You have been successfully authenticated!</nb-alert>
    <nb-alert status="primary">Primary. You have been successfully authenticated!</nb-alert>
    <nb-alert status="success">Success. You have been successfully authenticated!</nb-alert>
    <nb-alert status="info">Info. You have been successfully authenticated!</nb-alert>
    <nb-alert status="danger">Danger. You have been successfully authenticated!</nb-alert>
    <nb-alert status="warning">Warning. You have been successfully authenticated!</nb-alert>
    <div class="control-status-example">
      <nb-alert status="control">Control. You have been successfully authenticated!</nb-alert>
    </div>
  </nb-card-body>
</nb-card>


text:
export abstract class BulkQuery {
  pluginOptions: IShopifyPluginOptions

  constructor(pluginOptions: IShopifyPluginOptions) {
    this.pluginOptions = pluginOptions
  }

  abstract query(date?: Date): string

  protected bulkOperationQuery(query: string): string {
    return `
      mutation INITIATE_BULK_OPERATION {
        bulkOperationRunQuery(
        query: """
          ${query}
        """
      ) {
        bulkOperation {
          id
          status
        }
        userErrors {
          field
          message
        }
      }
    }
    `
  }
}


text:
#ifndef ossimTieGptSet_HEADER
#define ossimTieGptSet_HEADER

#include <iostream>
#include <vector>
#include <ossim/base/ossimXmlNode.h>
#include <ossim/base/ossimTieGpt.h>
#include <ossim/base/ossimFilename.h>
#include <ossim/matrix/newmat.h>

class ossimDpt;

/**
 * storage class for a set of geographic tie points, between master and slave images
 * + GML (OGC) serialization
 *
 * NOTES
 * master points are stored on the ground
 * ground SRS is EPSG:4326 only (WGS84) + height in meters above ellispoid
 *
 * slave points are stored as image positions
 *
 * general ground/image accuracy values are stored
 *
 * TODO :
 */
class OSSIMDLLEXPORT ossimTieGptSet
{
public:

   inline ossimTieGptSet() {}

   inline ossimTieGptSet(const ossimTieGptSet& aSet)
      :
      theTies(aSet.getTiePoints()),
      theMasterPath(aSet.getMasterPath()),
      theSlavePath(aSet.getSlavePath()),
      theImageCov(aSet.getImageCov()),
      theGroundCov(aSet.getGroundCov())
   {}

   inline ~ossimTieGptSet() {}

   const ossimTieGptSet& operator=(const ossimTieGptSet&);

   // accessors
   inline void  setTiePoints(const std::vector<ossimRefPtr<ossimTieGpt> >& aTieSet) { theTies = aTieSet; }
   inline const std::vector<ossimRefPtr<ossimTieGpt> >& getTiePoints()const         { return theTies; }
   inline       std::vector<ossimRefPtr<ossimTieGpt> >& refTiePoints()              { return theTies; }

   inline void  setMasterPath(const ossimString& aPath) { theMasterPath = aPath; }
   inline const ossimString& getMasterPath()const       { return theMasterPath; }

   inline void  setSlavePath(const ossimString& aPath) { theSlavePath = aPath; }
   inline const ossimString& getSlavePath()const       { return theSlavePath; }

   inline void  setImageCov(const NEWMAT::SymmetricMatrix& aCovMat) { theImageCov = aCovMat; }
   inline const NEWMAT::SymmetricMatrix& getImageCov()const       { return theImageCov; }
   inline       NEWMAT::SymmetricMatrix& refImageCov()            { return theImageCov; }

   inline void  setGroundCov(const NEWMAT::SymmetricMatrix& aCovMat) { theGroundCov = aCovMat; }
   inline const NEWMAT::SymmetricMatrix& getGroundCov()const       { return theGroundCov; }
   inline       NEWMAT::SymmetricMatrix& refGroundCov()            { return theGroundCov; }

   void getSlaveMasterPoints(std::vector<ossimDpt>& imv, std::vector<ossimGpt>& gdv)const;

   inline unsigned int size()const { return (unsigned int)theTies.size(); }

   /**
    * operations
    */
   void addTiePoint(ossimRefPtr<ossimTieGpt> aTiePt);
   void clearTiePoints();

   void getGroundBoundaries(ossimGpt& gBoundInf, ossimGpt& gBoundSup)const;

   /**
    * text output : header + tab separated tie points
    */
   std::ostream& printTab(std::ostream& os) const;

   /**
    * GML features (XML) serialization
    */
   ossimRefPtr<ossimXmlNode> exportAsGmlNode(ossimString aGmlVersion="2.1.2")const;
   bool importFromGmlNode(ossimRefPtr<ossimXmlNode> aGmlNode, ossimString aGmlVersion="2.1.2");

  /**
   * Public data members
   */
   static const char* TIEPTSET_TAG;

protected:
   /**
    * Protected data members
    */
   std::vector<ossimRefPtr<ossimTieGpt> > theTies;      //store by reference so derived classes can be used
   ossimString                       theMasterPath; //!full or relative path to master dataset
   ossimString                       theSlavePath; //!full or relative path to slave dataset
   NEWMAT::SymmetricMatrix           theImageCov;  //! image error covariance matrix
   NEWMAT::SymmetricMatrix           theGroundCov; //! ground error covariance matrix

   /**
    * Protected methods
    */
   ossimString symMatrixToText(const NEWMAT::SymmetricMatrix& sym,
                               const ossimString& el_sep=" ",
                               const ossimString& row_sep=";")const;

   NEWMAT::SymmetricMatrix textToSymMatrix(const ossimString& text,
                               unsigned int dim,
                               const ossimString& seps=" ;\t\r\n")const; //list of possible elements or row separators

};

#endif /* #ifndef ossimTieGptSet_HEADER */


text:
"""
$description Internet portal in Estonia, Latvia, and Lithuania providing daily news, ranging from gardening to politics.
$url delfi.lt
$url delfi.ee
$url delfi.lv
$type vod
"""

import itertools
import logging
import re
from urllib.parse import urlparse

from streamlink.plugin import Plugin, PluginError, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream.hls import HLSStream
from streamlink.utils.parse import parse_qsd
from streamlink.utils.url import update_scheme

log = logging.getLogger(__name__)

@pluginmatcher(re.compile(
    r"https?://(?:[\w-]+\.)?delfi\.(?P<tld>lt|lv|ee)"
))
class Delfi(Plugin):
    _api = {
        "lt": "https://g2.dcdn.lt/vfe/data.php",
        "lv": "https://g.delphi.lv/vfe/data.php",
        "ee": "https://g4.nh.ee/vfe/data.php",
    }

    def _get_streams_api(self, video_id):
        log.debug(f"Found video ID: {video_id}")

        tld = self.match.group("tld")
        try:
            data = self.session.http.get(
                self._api.get(tld, "lt"),
                params=dict(video_id=video_id),
                schema=validate.Schema(
                    validate.parse_json(),
                    {
                        "success": True,
                        "data": {
                            "versions": {
                                str: validate.all(
                                    [{
                                        "type": str,
                                        "src": str,
                                    }],
                                    validate.filter(lambda item: item["type"] == "application/x-mpegurl")
                                )
                            }
                        }
                    },
                    validate.get(("data", "versions"))
                )
            )
        except PluginError:
            log.error("Failed to get streams from API")
            return

        for stream in itertools.chain(*data.values()):
            src = update_scheme("https://", stream["src"], force=False)
            yield from HLSStream.parse_variant_playlist(self.session, src).items()

    def _get_streams_delfi(self, src):
        try:
            data = self.session.http.get(src, schema=validate.Schema(
                validate.parse_html(),
                validate.xml_xpath_string(".//script[contains(text(),'embedJs.setAttribute(')][1]/text()"),
                validate.any(None, validate.all(
                    str,
                    validate.transform(re.compile(r"embedJs\.setAttribute\('src',\s*'(.+?)'").search),
                    validate.any(None, validate.all(
                        validate.get(1),
                        validate.transform(lambda url: parse_qsd(urlparse(url).fragment)),
                        {"stream": str},
                        validate.get("stream"),
                        validate.parse_json(),
                        {"versions": [{
                            "hls": str
                        }]},
                        validate.get("versions")
                    ))
                ))
            ))
        except PluginError:
            log.error("Failed to get streams from iframe")
            return

        for stream in data:
            src = update_scheme("https://", stream["hls"], force=False)
            yield from HLSStream.parse_variant_playlist(self.session, src).items()

    def _get_streams(self):
        root = self.session.http.get(self.url, schema=validate.Schema(
            validate.parse_html()
        ))

        video_id = root.xpath("string(.//div[@data-provider='dvideo'][@data-id][1]/@data-id)")
        if video_id:
            return self._get_streams_api(str(video_id))

        yt_id = root.xpath("string(.//script[contains(@src,'/yt.js')][@data-video]/@data-video)")
        if yt_id:
            return self.session.streams(f"https://www.youtube.com/watch?v={yt_id}")

        yt_iframe = root.xpath("string(.//iframe[starts-with(@src,'https://www.youtube.com/')][1]/@src)")
        if yt_iframe:
            return self.session.streams(str(yt_iframe))

        delfi = root.xpath("string(.//iframe[@name='delfi-stream'][@src][1]/@src)")
        if delfi:
            return self._get_streams_delfi(str(delfi))

__plugin__ = Delfi


text:
from django.db.models import Count
from django.shortcuts import render
from django.views import View
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from rest_framework import filters
from rest_framework import viewsets

from .serializers import CardSerializer, CardThinSerializer
from .models import Card, Dish

class IndexView(View):
    template_name = 'index.html'
    items_per_page = 3

    def get(self, request):
        cards = Card.objects.filter(dishes__gt=0).annotate(dishes_count=Count('dishes'))

        page = request.GET.get('page')
        sort_by = request.GET.get('sort_by')
        if sort_by:
            cards = cards.order_by(sort_by)

        paginator = Paginator(cards, self.items_per_page)

        try:
            cards = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            cards = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            cards = paginator.page(paginator.num_pages)
        return render(request, self.template_name, {'cards': cards})

class IndexAsynchronousView(View):
    template_name = 'asynchronous.html'

    def get(self, request):
        return render(request, self.template_name)

class DetailsView(View):
    template_name = 'details.html'

    def get(self, request, card_pk):
        card = Card.objects.get(id=card_pk)
        dishes = Dish.objects.filter(card=card)
        return render(request, self.template_name, {'card': card, 'dishes': dishes})

class CardViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Card.objects.filter(dishes__gt=0).annotate(dishes_count=Count('dishes'))
    serializer_class = CardSerializer
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('name', 'dishes_count')

    def get_serializer_class(self):
        if self.action == 'list':
            return CardThinSerializer
        if self.action == 'retrieve':
            return CardSerializer
        return CardSerializer


text:
package nodes.nlp

import org.apache.spark.SparkContext
import org.scalatest.FunSuite
import pipelines.LocalSparkContext

class StringUtilsSuite extends FunSuite with LocalSparkContext {
  val stringToManip = Array("  The quick BROWN fo.X ", " ! !.,)JumpeD. ovER the LAZy DOG.. ! ")
  test("trim") {
    sc = new SparkContext("local", "test")
    val out = Trim.apply(sc.parallelize(stringToManip, 1)).collect().toSeq
    assert(out === Seq("The quick BROWN fo.X", "! !.,)JumpeD. ovER the LAZy DOG.. !"))
  }

  test("lower case") {
    sc = new SparkContext("local", "test")
    val out = LowerCase().apply(sc.parallelize(stringToManip, 1)).collect().toSeq
    assert(out === Seq("  the quick brown fo.x ", " ! !.,)jumped. over the lazy dog.. ! "))
  }

  test("tokenizer") {
    sc = new SparkContext("local", "test")
    val out = Tokenizer().apply(sc.parallelize(stringToManip, 1)).collect().toSeq
    assert(out === Seq(Seq("", "The", "quick", "BROWN", "fo", "X"), Seq("", "JumpeD", "ovER", "the", "LAZy", "DOG")))
  }
}


text:
<?php
if (!defined('XHPROF_LIB_ROOT')) {
  define('XHPROF_LIB_ROOT', dirname(dirname(__FILE__)) . '/xhprof_lib');
}
require_once("../config.php");
require_once XHPROF_LIB_ROOT . '/display/xhprof.php';
require(XHPROF_LIB_ROOT . "/utils/common.php");

if (FALSE !== $controlIPs && !in_array($_SERVER['REMOTE_ADDR'], $controlIPs)) {
  die("You do not have permission to view this page.");
}

unset($controlIPs);

// param name, its type, and default value
$params = array(
  'run' => array(XHPROF_STRING_PARAM, ''),
  'wts' => array(XHPROF_STRING_PARAM, ''),
  'symbol' => array(XHPROF_STRING_PARAM, ''),
  'sort' => array(XHPROF_STRING_PARAM, 'wt'), // wall time
  'run1' => array(XHPROF_STRING_PARAM, ''),
  'run2' => array(XHPROF_STRING_PARAM, ''),
  'source' => array(XHPROF_STRING_PARAM, 'xhprof'),
  'all' => array(XHPROF_UINT_PARAM, 0),
);

// pull values of these params, and create named globals for each param
xhprof_param_init($params);

/* reset params to be a array of variable names to values
   by the end of this page, param should only contain values that need
   to be preserved for the next page. unset all unwanted keys in $params.
 */
foreach ($params as $k => $v) {
  $params[$k] = $$k;

  // unset key from params that are using default values. So URLs aren't
  // ridiculously long.
  if ($params[$k] == $v[1]) {
    unset($params[$k]);
  }
}

$vbar = ' class="vbar"';
$vwbar = ' class="vwbar"';
$vwlbar = ' class="vwlbar"';
$vbbar = ' class="vbbar"';
$vrbar = ' class="vrbar"';
$vgbar = ' class="vgbar"';

$xhprof_runs_impl = new XHProfRuns_Default();

$domainFilter = getFilter('domain_filter');
$serverFilter = getFilter('server_filter');

$domainsRS = $xhprof_runs_impl->getDistinct(array('column' => 'server name'));
$domainFilterOptions = array("None");
while ($row = XHProfRuns_Default::getNextAssoc($domainsRS)) {
  $domainFilterOptions[] = $row['server name'];
}

$serverRS = $xhprof_runs_impl->getDistinct(array('column' => 'server_id'));
$serverFilterOptions = array("None");
while ($row = XHProfRuns_Default::getNextAssoc($serverRS)) {
  $serverFilterOptions[] = $row['server_id'];
}

$criteria = array();
if (!is_null($domainFilter)) {
  $criteria['server name'] = $domainFilter;
}
if (!is_null($serverFilter)) {
  $criteria['server_id'] = $serverFilter;
}
$_xh_header = "";
if (isset($_GET['run1']) || isset($_GET['run'])) {
  require("themes/templates/header.tpl.php");
  displayXHProfReport($xhprof_runs_impl, $params, $source, $run, $wts,
    $symbol, $sort, $run1, $run2);
}
elseif (isset($_GET['geturl'])) {
  $last = (isset($_GET['last'])) ? $_GET['last'] : 100;
  $last = (int) $last;
  $criteria['url'] = $_GET['geturl'];
  $criteria['limit'] = $last;
  $criteria['order by'] = 'timestamp';
  $rs = $xhprof_runs_impl->getUrlStats($criteria);
  list($header, $body) = showChart($rs, TRUE);
  $_xh_header .= $header;

  require("themes/templates/header.tpl.php");
  $rs = $xhprof_runs_impl->getRuns($criteria);
  require("themes/templates/emptyBody.tpl.php");

  $url = htmlentities($_GET['geturl'], ENT_QUOTES, "UTF-8");
  displayRuns($rs, "Runs with URL: $url");
}
elseif (isset($_GET['getcurl'])) {
  $last = (isset($_GET['last'])) ? $_GET['last'] : 100;
  $last = (int) $last;
  $criteria['c_url'] = $_GET['getcurl'];
  $criteria['limit'] = $last;
  $criteria['order by'] = 'timestamp';

  $rs = $xhprof_runs_impl->getUrlStats($criteria);
  list($header, $body) = showChart($rs, TRUE);
  $_xh_header .= $header;
  require("themes/templates/header.tpl.php");

  $url = htmlentities($_GET['getcurl'], ENT_QUOTES, "UTF-8");
  $rs = $xhprof_runs_impl->getRuns($criteria);
  require("themes/templates/emptyBody.tpl.php");
  displayRuns($rs, "Runs with Simplified URL: $url");
}
elseif (isset($_GET['getruns'])) {
  require("themes/templates/header.tpl.php");
  $days = (int) $_GET['days'];

  switch ($_GET['getruns']) {
    case "cpu":
      $load = "cpu";
      break;
    case "wt":
      $load = "wt";
      break;
    case "pmu":
      $load = "pmu";
      break;
  }

  $criteria['order by'] = $load;
  $criteria['limit'] = "500";
  $criteria['where'] = "DATE_SUB(CURDATE(), INTERVAL $days DAY) <= `timestamp`";
  $rs = $xhprof_runs_impl->getRuns($criteria);
  displayRuns($rs, "Worst runs by $load");
}
elseif (isset($_GET['hit'])) {
  require("themes/templates/header.tpl.php");
  $last = (isset($_GET['hit'])) ? $_GET['hit'] : 25;
  $last = (int) $last;
  $days = (isset($_GET['days'])) ? $_GET['days'] : 1;
  $days = (int) $days;
  if (isset($_GET['type']) && ($_GET['type'] === 'url' OR $_GET['type'] = 'curl')) {
    $type = $_GET['type'];
  }
  else {
    $type = 'url';
  }

  $criteria['limit'] = $last;
  $criteria['days'] = $days;
  $criteria['type'] = $type;
  $resultSet = $xhprof_runs_impl->getHardHit($criteria);

  echo "
Hardest Hit
\n";
  echo "

URL	Hits	Total Wall Time	Avg Wall Time

";
  echo "
\n";
  while ($row = XHProfRuns_Default::getNextAssoc($resultSet)) {
    $url = urlencode($row['url']);
    $html['url'] = htmlentities($row['url'], ENT_QUOTES, 'UTF-8');
    echo "\t
{$html['url']}	{$row['count']}	" . number_format($row['total_wall']) . " ms	" . number_format($row['avg_wall']) . " ms
\n";
  }
  echo "
\n";
  echo "
\n";
  echo <<<CODESE

CODESE;
}
else {
  require("themes/templates/header.tpl.php");
  $last = (isset($_GET['last'])) ? $_GET['last'] : 25;
  $last = (int) $last;
  $criteria['order by'] = "timestamp";
  $criteria['limit'] = $last;
  $rs = $xhprof_runs_impl->getRuns($criteria);
  displayRuns($rs, "Last $last Runs");
}

require("themes/templates/footer.tpl.php");


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="title" content="##PROJECTFNAME##" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
    <title>##PROJECTFNAME##</title>
    <link rel="shortcut icon" href="/favicon.ico" />
    <link rel="stylesheet" type="text/css" media="screen" href="/css/main.css" />

Ooops, something went wrong.


text:
<?php

namespace TT\platformBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class matchCompetType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('numeroEquie', null, array('label' => 'label.equipe'))
            ->add('score')
            ->add('journee')
            ->add('anne')
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'TT\platformBundle\Entity\matchCompet'
        ));
    }
}


text:
package org.gradle.api.artifacts.component;

import org.gradle.api.artifacts.ModuleIdentifier;
import org.gradle.internal.scan.UsedByScanPlugin;

/**
 * An identifier for a component instance which is available as a module version.
 *
 * @since 1.10
 */
@UsedByScanPlugin
public interface ModuleComponentIdentifier extends ComponentIdentifier {
    /**
     * The module group of the component.
     *
     * @return Component group
     * @since 1.10
     */
    String getGroup();

    /**
     * The module name of the component.
     *
     * @return Component module
     * @since 1.10
     */
    String getModule();

    /**
     * The module version of the component.
     *
     * @return Component version
     * @since 1.10
     */
    String getVersion();

    /**
     * The module identifier of the component. Returns the same information
     * as {@link #getGroup()} and {@link #getModule()}.
     *
     * @return the module identifier
     *
     * @since 4.9
     */
    ModuleIdentifier getModuleIdentifier();
}


text:
package org.apache.beam.sdk.extensions.protobuf;

import static org.apache.beam.sdk.extensions.protobuf.ProtoSchemaTranslator.SCHEMA_OPTION_META_NUMBER;
import static org.apache.beam.sdk.extensions.protobuf.ProtoSchemaTranslator.SCHEMA_OPTION_META_TYPE_NAME;
import static org.apache.beam.sdk.extensions.protobuf.ProtoSchemaTranslator.getFieldNumber;

import com.google.protobuf.BoolValue;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.Duration;
import com.google.protobuf.FloatValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Int64Value;
import com.google.protobuf.StringValue;
import com.google.protobuf.Timestamp;
import com.google.protobuf.UInt32Value;
import com.google.protobuf.UInt64Value;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.beam.sdk.extensions.protobuf.Proto2SchemaMessages.OptionalNested;
import org.apache.beam.sdk.extensions.protobuf.Proto2SchemaMessages.OptionalPrimitive;
import org.apache.beam.sdk.extensions.protobuf.Proto2SchemaMessages.RequiredNested;
import org.apache.beam.sdk.extensions.protobuf.Proto2SchemaMessages.RequiredPrimitive;
import org.apache.beam.sdk.extensions.protobuf.Proto3SchemaMessages.MapPrimitive;
import org.apache.beam.sdk.extensions.protobuf.Proto3SchemaMessages.Nested;
import org.apache.beam.sdk.extensions.protobuf.Proto3SchemaMessages.OneOf;
import org.apache.beam.sdk.extensions.protobuf.Proto3SchemaMessages.OuterOneOf;
import org.apache.beam.sdk.extensions.protobuf.Proto3SchemaMessages.Primitive;
import org.apache.beam.sdk.extensions.protobuf.Proto3SchemaMessages.RepeatPrimitive;
import org.apache.beam.sdk.extensions.protobuf.Proto3SchemaMessages.WktMessage;
import org.apache.beam.sdk.extensions.protobuf.ProtoSchemaLogicalTypes.Fixed32;
import org.apache.beam.sdk.extensions.protobuf.ProtoSchemaLogicalTypes.Fixed64;
import org.apache.beam.sdk.extensions.protobuf.ProtoSchemaLogicalTypes.SFixed32;
import org.apache.beam.sdk.extensions.protobuf.ProtoSchemaLogicalTypes.SFixed64;
import org.apache.beam.sdk.extensions.protobuf.ProtoSchemaLogicalTypes.SInt32;
import org.apache.beam.sdk.extensions.protobuf.ProtoSchemaLogicalTypes.SInt64;
import org.apache.beam.sdk.extensions.protobuf.ProtoSchemaLogicalTypes.UInt32;
import org.apache.beam.sdk.extensions.protobuf.ProtoSchemaLogicalTypes.UInt64;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.Field;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.schemas.logicaltypes.NanosDuration;
import org.apache.beam.sdk.schemas.logicaltypes.NanosInstant;
import org.apache.beam.sdk.schemas.logicaltypes.OneOfType;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;

class TestProtoSchemas {

  static Field withFieldNumber(String name, FieldType fieldType, int fieldNumber) {
    return Field.of(name, fieldType)
        .withOptions(
            Schema.Options.builder()
                .setOption(SCHEMA_OPTION_META_NUMBER, FieldType.INT32, fieldNumber));
  }

  static Schema.Options withTypeName(String typeName) {
    return Schema.Options.builder()
        .setOption(SCHEMA_OPTION_META_TYPE_NAME, FieldType.STRING, typeName)
        .build();
  }

  // The schema we expect from the Primitive proto.
  static final Schema PRIMITIVE_SCHEMA =
      Schema.builder()
          .addField(withFieldNumber("primitive_double", FieldType.DOUBLE, 1))
          .addField(withFieldNumber("primitive_float", FieldType.FLOAT, 2))
          .addField(withFieldNumber("primitive_int32", FieldType.INT32, 3))
          .addField(withFieldNumber("primitive_int64", FieldType.INT64, 4))
          .addField(withFieldNumber("primitive_uint32", FieldType.logicalType(new UInt32()), 5))
          .addField(withFieldNumber("primitive_uint64", FieldType.logicalType(new UInt64()), 6))
          .addField(withFieldNumber("primitive_sint32", FieldType.logicalType(new SInt32()), 7))
          .addField(withFieldNumber("primitive_sint64", FieldType.logicalType(new SInt64()), 8))
          .addField(withFieldNumber("primitive_fixed32", FieldType.logicalType(new Fixed32()), 9))
          .addField(withFieldNumber("primitive_fixed64", FieldType.logicalType(new Fixed64()), 10))
          .addField(
              withFieldNumber("primitive_sfixed32", FieldType.logicalType(new SFixed32()), 11))
          .addField(
              withFieldNumber("primitive_sfixed64", FieldType.logicalType(new SFixed64()), 12))
          .addField(withFieldNumber("primitive_bool", FieldType.BOOLEAN, 13))
          .addField(withFieldNumber("primitive_string", FieldType.STRING, 14))
          .addField(withFieldNumber("primitive_bytes", FieldType.BYTES, 15))
          .setOptions(
              Schema.Options.builder()
                  .setOption(
                      SCHEMA_OPTION_META_TYPE_NAME,
                      FieldType.STRING,
                      "proto3_schema_messages.Primitive"))
          .build();

  static final Schema OPTIONAL_PRIMITIVE_SCHEMA =
      Schema.builder()
          .addField(withFieldNumber("primitive_int32", FieldType.INT32, 1))
          .addField(withFieldNumber("primitive_bool", FieldType.BOOLEAN, 2))
          .addField(withFieldNumber("primitive_string", FieldType.STRING, 3))
          .addField(withFieldNumber("primitive_bytes", FieldType.BYTES, 4))
          .setOptions(
              Schema.Options.builder()
                  .setOption(
                      SCHEMA_OPTION_META_TYPE_NAME,
                      FieldType.STRING,
                      "proto2_schema_messages.OptionalPrimitive"))
          .build();

  static final Schema REQUIRED_PRIMITIVE_SCHEMA =
      Schema.builder()
          .addField(withFieldNumber("primitive_int32", FieldType.INT32, 1))
          .addField(withFieldNumber("primitive_bool", FieldType.BOOLEAN, 2))
          .addField(withFieldNumber("primitive_string", FieldType.STRING, 3))
          .addField(withFieldNumber("primitive_bytes", FieldType.BYTES, 4))
          .setOptions(
              Schema.Options.builder()
                  .setOption(
                      SCHEMA_OPTION_META_TYPE_NAME,
                      FieldType.STRING,
                      "proto2_schema_messages.RequiredPrimitive"))
          .build();

  // A sample instance of the  row.
  private static final byte[] BYTE_ARRAY = new byte[] {1, 2, 3, 4};
  static final Row PRIMITIVE_ROW =
      Row.withSchema(PRIMITIVE_SCHEMA)
          .addValues(
              1.1, 2.2F, 32, 64L, 33, 65L, 123, 124L, 30, 62L, 31, 63L, true, "horsey", BYTE_ARRAY)
          .build();

  // A sample instance of the proto.
  static final Primitive PRIMITIVE_PROTO =
      Primitive.newBuilder()
          .setPrimitiveDouble(1.1)
          .setPrimitiveFloat(2.2F)
          .setPrimitiveInt32(32)
          .setPrimitiveInt64(64)
          .setPrimitiveUint32(33)
          .setPrimitiveUint64(65)
          .setPrimitiveSint32(123)
          .setPrimitiveSint64(124)
          .setPrimitiveFixed32(30)
          .setPrimitiveFixed64(62)
          .setPrimitiveSfixed32(31)
          .setPrimitiveSfixed64(63)
          .setPrimitiveBool(true)
          .setPrimitiveString("horsey")
          .setPrimitiveBytes(ByteString.copyFrom(BYTE_ARRAY))
          .build();

  // A sample instance of the  row.
  static final Row OPTIONAL_PRIMITIVE_ROW =
      Row.withSchema(OPTIONAL_PRIMITIVE_SCHEMA).addValues(32, true, "horsey", BYTE_ARRAY).build();

  // A sample instance of the proto.
  static final OptionalPrimitive OPTIONAL_PRIMITIVE_PROTO =
      OptionalPrimitive.newBuilder()
          .setPrimitiveInt32(32)
          .setPrimitiveBool(true)
          .setPrimitiveString("horsey")
          .setPrimitiveBytes(ByteString.copyFrom(BYTE_ARRAY))
          .build();

  // A sample instance of the  row.
  static final Row REQUIRED_PRIMITIVE_ROW =
      Row.withSchema(REQUIRED_PRIMITIVE_SCHEMA).addValues(32, true, "horsey", BYTE_ARRAY).build();

  // A sample instance of the proto.
  static final RequiredPrimitive REQUIRED_PRIMITIVE_PROTO =
      RequiredPrimitive.newBuilder()
          .setPrimitiveInt32(32)
          .setPrimitiveBool(true)
          .setPrimitiveString("horsey")
          .setPrimitiveBytes(ByteString.copyFrom(BYTE_ARRAY))
          .build();

  // The schema for the RepeatedPrimitive proto.
  static final Schema REPEATED_SCHEMA =
      Schema.builder()
          .addField(withFieldNumber("repeated_double", FieldType.array(FieldType.DOUBLE), 1))
          .addField(withFieldNumber("repeated_float", FieldType.array(FieldType.FLOAT), 2))
          .addField(withFieldNumber("repeated_int32", FieldType.array(FieldType.INT32), 3))
          .addField(withFieldNumber("repeated_int64", FieldType.array(FieldType.INT64), 4))
          .addField(
              withFieldNumber(
                  "repeated_uint32", FieldType.array(FieldType.logicalType(new UInt32())), 5))
          .addField(
              withFieldNumber(
                  "repeated_uint64", FieldType.array(FieldType.logicalType(new UInt64())), 6))
          .addField(
              withFieldNumber(
                  "repeated_sint32", FieldType.array(FieldType.logicalType(new SInt32())), 7))
          .addField(
              withFieldNumber(
                  "repeated_sint64", FieldType.array(FieldType.logicalType(new SInt64())), 8))
          .addField(
              withFieldNumber(
                  "repeated_fixed32", FieldType.array(FieldType.logicalType(new Fixed32())), 9))
          .addField(
              withFieldNumber(
                  "repeated_fixed64", FieldType.array(FieldType.logicalType(new Fixed64())), 10))
          .addField(
              withFieldNumber(
                  "repeated_sfixed32", FieldType.array(FieldType.logicalType(new SFixed32())), 11))
          .addField(
              withFieldNumber(
                  "repeated_sfixed64", FieldType.array(FieldType.logicalType(new SFixed64())), 12))
          .addField(withFieldNumber("repeated_bool", FieldType.array(FieldType.BOOLEAN), 13))
          .addField(withFieldNumber("repeated_string", FieldType.array(FieldType.STRING), 14))
          .addField(withFieldNumber("repeated_bytes", FieldType.array(FieldType.BYTES), 15))
          .setOptions(withTypeName("proto3_schema_messages.RepeatPrimitive"))
          .build();

  // A sample instance of the row.
  static final Row REPEATED_ROW =
      Row.withSchema(REPEATED_SCHEMA)
          .addArray(1.1, 1.1)
          .addArray(2.2F, 2.2F)
          .addArray(32, 32)
          .addArray(64L, 64L)
          .addArray(33, 33)
          .addArray(65L, 65L)
          .addArray(123, 123)
          .addArray(124L, 124L)
          .addArray(30, 30)
          .addArray(62L, 62L)
          .addArray(31, 31)
          .addArray(63L, 63L)
          .addArray(true, true)
          .addArray("horsey", "horsey")
          .addArray(BYTE_ARRAY, BYTE_ARRAY)
          .build();

  // A sample instance of the proto.
  static final RepeatPrimitive REPEATED_PROTO =
      RepeatPrimitive.newBuilder()
          .addAllRepeatedDouble(ImmutableList.of(1.1, 1.1))
          .addAllRepeatedFloat(ImmutableList.of(2.2F, 2.2F))
          .addAllRepeatedInt32(ImmutableList.of(32, 32))
          .addAllRepeatedInt64(ImmutableList.of(64L, 64L))
          .addAllRepeatedUint32(ImmutableList.of(33, 33))
          .addAllRepeatedUint64(ImmutableList.of(65L, 65L))
          .addAllRepeatedSint32(ImmutableList.of(123, 123))
          .addAllRepeatedSint64(ImmutableList.of(124L, 124L))
          .addAllRepeatedFixed32(ImmutableList.of(30, 30))
          .addAllRepeatedFixed64(ImmutableList.of(62L, 62L))
          .addAllRepeatedSfixed32(ImmutableList.of(31, 31))
          .addAllRepeatedSfixed64(ImmutableList.of(63L, 63L))
          .addAllRepeatedBool(ImmutableList.of(true, true))
          .addAllRepeatedString(ImmutableList.of("horsey", "horsey"))
          .addAllRepeatedBytes(
              ImmutableList.of(ByteString.copyFrom(BYTE_ARRAY), ByteString.copyFrom(BYTE_ARRAY)))
          .build();

  static final Row NULL_REPEATED_ROW =
      Row.withSchema(REPEATED_SCHEMA)
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .addArray()
          .build();

  // A sample instance of the proto.
  static final RepeatPrimitive NULL_REPEATED_PROTO = RepeatPrimitive.newBuilder().build();

  // The schema for the MapPrimitive proto.
  static final Schema MAP_PRIMITIVE_SCHEMA =
      Schema.builder()
          .addField(
              withFieldNumber(
                  "string_string_map", FieldType.map(FieldType.STRING, FieldType.STRING), 1))
          .addField(
              withFieldNumber(
                  "string_int_map", FieldType.map(FieldType.STRING, FieldType.INT32), 2))
          .addField(
              withFieldNumber(
                  "int_string_map", FieldType.map(FieldType.INT32, FieldType.STRING), 3))
          .addField(
              withFieldNumber(
                  "string_bytes_map", FieldType.map(FieldType.STRING, FieldType.BYTES), 4))
          .setOptions(withTypeName("proto3_schema_messages.MapPrimitive"))
          .build();

  // A sample instance of the row.
  static final Row MAP_PRIMITIVE_ROW =
      Row.withSchema(MAP_PRIMITIVE_SCHEMA)
          .addValue(ImmutableMap.of("k1", "v1", "k2", "v2"))
          .addValue(ImmutableMap.of("k1", 1, "k2", 2))
          .addValue(ImmutableMap.of(1, "v1", 2, "v2"))
          .addValue(ImmutableMap.of("k1", BYTE_ARRAY, "k2", BYTE_ARRAY))
          .build();

  // A sample instance of the proto.
  static final MapPrimitive MAP_PRIMITIVE_PROTO =
      MapPrimitive.newBuilder()
          .putAllStringStringMap(ImmutableMap.of("k1", "v1", "k2", "v2"))
          .putAllStringIntMap(ImmutableMap.of("k1", 1, "k2", 2))
          .putAllIntStringMap(ImmutableMap.of(1, "v1", 2, "v2"))
          .putAllStringBytesMap(
              ImmutableMap.of(
                  "k1", ByteString.copyFrom(BYTE_ARRAY), "k2", ByteString.copyFrom(BYTE_ARRAY)))
          .build();

  // A sample instance of the row.
  static final Row NULL_MAP_PRIMITIVE_ROW =
      Row.withSchema(MAP_PRIMITIVE_SCHEMA)
          .addValue(ImmutableMap.of())
          .addValue(ImmutableMap.of())
          .addValue(ImmutableMap.of())
          .addValue(ImmutableMap.of())
          .build();

  // A sample instance of the proto.
  static final MapPrimitive NULL_MAP_PRIMITIVE_PROTO = MapPrimitive.newBuilder().build();

  // The schema for the Nested proto.
  static final Schema NESTED_SCHEMA =
      Schema.builder()
          .addField(
              withFieldNumber("nested", FieldType.row(PRIMITIVE_SCHEMA).withNullable(true), 1))
          .addField(
              withFieldNumber("nested_list", FieldType.array(FieldType.row(PRIMITIVE_SCHEMA)), 2))
          .addField(
              withFieldNumber(
                  "nested_map",
                  FieldType.map(FieldType.STRING, FieldType.row(PRIMITIVE_SCHEMA)),
                  3))
          .setOptions(withTypeName("proto3_schema_messages.Nested"))
          .build();

  // A sample instance of the row.
  static final Row NESTED_ROW =
      Row.withSchema(NESTED_SCHEMA)
          .addValue(PRIMITIVE_ROW)
          .addArray(ImmutableList.of(PRIMITIVE_ROW, PRIMITIVE_ROW))
          .addValue(ImmutableMap.of("k1", PRIMITIVE_ROW, "k2", PRIMITIVE_ROW))
          .build();

  // A sample instance of the proto.
  static final Nested NESTED_PROTO =
      Nested.newBuilder()
          .setNested(PRIMITIVE_PROTO)
          .addAllNestedList(ImmutableList.of(PRIMITIVE_PROTO, PRIMITIVE_PROTO))
          .putAllNestedMap(ImmutableMap.of("k1", PRIMITIVE_PROTO, "k2", PRIMITIVE_PROTO))
          .build();

  // The schema for the OneOf proto.
  private static final List<Field> ONEOF_FIELDS =
      ImmutableList.of(
          withFieldNumber("oneof_int32", FieldType.INT32, 2),
          withFieldNumber("oneof_bool", FieldType.BOOLEAN, 3),
          withFieldNumber("oneof_string", FieldType.STRING, 4),
          withFieldNumber("oneof_primitive", FieldType.row(PRIMITIVE_SCHEMA), 5));
  private static final Map<String, Integer> ONE_OF_ENUM_MAP =
      ONEOF_FIELDS.stream().collect(Collectors.toMap(Field::getName, f -> getFieldNumber(f)));
  static final OneOfType ONE_OF_TYPE = OneOfType.create(ONEOF_FIELDS, ONE_OF_ENUM_MAP);
  static final Schema ONEOF_SCHEMA =
      Schema.builder()
          .addField("special_oneof", FieldType.logicalType(ONE_OF_TYPE))
          .addField(withFieldNumber("place1", FieldType.STRING, 1))
          .addField(withFieldNumber("place2", FieldType.INT32, 6))
          .setOptions(withTypeName("proto3_schema_messages.OneOf"))
          .build();

  // Sample row instances for each OneOf case.
  static final Row ONEOF_ROW_INT32 =
      Row.withSchema(ONEOF_SCHEMA)
          .addValues(ONE_OF_TYPE.createValue("oneof_int32", 1), "foo", 0)
          .build();
  static final Row ONEOF_ROW_BOOL =
      Row.withSchema(ONEOF_SCHEMA)
          .addValues(ONE_OF_TYPE.createValue("oneof_bool", true), "foo", 0)
          .build();
  static final Row ONEOF_ROW_STRING =
      Row.withSchema(ONEOF_SCHEMA)
          .addValues(ONE_OF_TYPE.createValue("oneof_string", "foo"), "foo", 0)
          .build();
  static final Row ONEOF_ROW_PRIMITIVE =
      Row.withSchema(ONEOF_SCHEMA)
          .addValues(ONE_OF_TYPE.createValue("oneof_primitive", PRIMITIVE_ROW), "foo", 0)
          .build();

  // Sample proto instances for each oneof case.
  static final OneOf ONEOF_PROTO_INT32 =
      OneOf.newBuilder().setOneofInt32(1).setPlace1("foo").setPlace2(0).build();
  static final OneOf ONEOF_PROTO_BOOL =
      OneOf.newBuilder().setOneofBool(true).setPlace1("foo").setPlace2(0).build();
  static final OneOf ONEOF_PROTO_STRING =
      OneOf.newBuilder().setOneofString("foo").setPlace1("foo").setPlace2(0).build();
  static final OneOf ONEOF_PROTO_PRIMITIVE =
      OneOf.newBuilder().setOneofPrimitive(PRIMITIVE_PROTO).setPlace1("foo").setPlace2(0).build();

  // The schema for the OuterOneOf proto.
  private static final List<Field> OUTER_ONEOF_FIELDS =
      ImmutableList.of(
          withFieldNumber("oneof_oneof", FieldType.row(ONEOF_SCHEMA), 1),
          withFieldNumber("oneof_int32", FieldType.INT32, 2));
  private static final Map<String, Integer> OUTER_ONE_OF_ENUM_MAP =
      OUTER_ONEOF_FIELDS.stream().collect(Collectors.toMap(Field::getName, f -> getFieldNumber(f)));
  static final OneOfType OUTER_ONEOF_TYPE =
      OneOfType.create(OUTER_ONEOF_FIELDS, OUTER_ONE_OF_ENUM_MAP);
  static final Schema OUTER_ONEOF_SCHEMA =
      Schema.builder()
          .addField("outer_oneof", FieldType.logicalType(OUTER_ONEOF_TYPE))
          .setOptions(withTypeName("proto3_schema_messages.OuterOneOf"))
          .build();

  // A sample instance of the Row.
  static final Row OUTER_ONEOF_ROW =
      Row.withSchema(OUTER_ONEOF_SCHEMA)
          .addValues(OUTER_ONEOF_TYPE.createValue("oneof_oneof", ONEOF_ROW_PRIMITIVE))
          .build();

  // A sample instance of the proto.
  static final OuterOneOf OUTER_ONEOF_PROTO =
      OuterOneOf.newBuilder().setOneofOneof(ONEOF_PROTO_PRIMITIVE).build();

  static final Schema WKT_MESSAGE_SCHEMA =
      Schema.builder()
          .addField(withFieldNumber("double", FieldType.DOUBLE, 1).withNullable(true))
          .addField(withFieldNumber("float", FieldType.FLOAT, 2).withNullable(true))
          .addField(withFieldNumber("int32", FieldType.INT32, 3).withNullable(true))
          .addField(withFieldNumber("int64", FieldType.INT64, 4).withNullable(true))
          .addField(
              withFieldNumber("uint32", FieldType.logicalType(new UInt32()), 5).withNullable(true))
          .addField(
              withFieldNumber("uint64", FieldType.logicalType(new UInt64()), 6).withNullable(true))
          .addField(withFieldNumber("bool", FieldType.BOOLEAN, 13).withNullable(true))
          .addField(withFieldNumber("string", FieldType.STRING, 14).withNullable(true))
          .addField(withFieldNumber("bytes", FieldType.BYTES, 15).withNullable(true))
          .addField(
              withFieldNumber("timestamp", FieldType.logicalType(new NanosInstant()), 16)
                  .withNullable(true))
          .addField(
              withFieldNumber("duration", FieldType.logicalType(new NanosDuration()), 17)
                  .withNullable(true))
          .setOptions(withTypeName("proto3_schema_messages.WktMessage"))
          .build();
  // A sample instance of the  row.
  static final Instant JAVA_NOW = Instant.now();
  static final Timestamp PROTO_NOW =
      Timestamp.newBuilder()
          .setSeconds(JAVA_NOW.getEpochSecond())
          .setNanos(JAVA_NOW.getNano())
          .build();
  static final java.time.Duration JAVA_DURATION =
      java.time.Duration.ofSeconds(JAVA_NOW.getEpochSecond(), JAVA_NOW.getNano());
  static final Duration PROTO_DURATION =
      Duration.newBuilder()
          .setSeconds(JAVA_NOW.getEpochSecond())
          .setNanos(JAVA_NOW.getNano())
          .build();
  static final Row WKT_MESSAGE_ROW =
      Row.withSchema(WKT_MESSAGE_SCHEMA)
          .addValues(
              1.1, 2.2F, 32, 64L, 33, 65L, true, "horsey", BYTE_ARRAY, JAVA_NOW, JAVA_DURATION)
          .build();

  // A sample instance of the proto.
  static final WktMessage WKT_MESSAGE_PROTO =
      WktMessage.newBuilder()
          .setDouble(DoubleValue.of(1.1))
          .setFloat(FloatValue.of(2.2F))
          .setInt32(Int32Value.of(32))
          .setInt64(Int64Value.of(64))
          .setUint32(UInt32Value.of(33))
          .setUint64(UInt64Value.of(65))
          .setBool(BoolValue.of(true))
          .setString(StringValue.of("horsey"))
          .setBytes(BytesValue.of(ByteString.copyFrom(BYTE_ARRAY)))
          .setTimestamp(PROTO_NOW)
          .setDuration(PROTO_DURATION)
          .build();

  // The schema for the OptionalNested proto.
  static final Schema OPTIONAL_NESTED_SCHEMA =
      Schema.builder()
          .addField(
              withFieldNumber("nested", FieldType.row(OPTIONAL_PRIMITIVE_SCHEMA), 1)
                  .withNullable(true))
          .setOptions(withTypeName("proto2_schema_messages.OptionalNested"))
          .build();

  // A sample instance of the proto.
  static final OptionalNested OPTIONAL_NESTED =
      OptionalNested.newBuilder().setNested(OPTIONAL_PRIMITIVE_PROTO).build();

  // The schema for the Required Nested proto.
  static final Schema REQUIRED_NESTED_SCHEMA =
      Schema.builder()
          .addField(
              withFieldNumber("nested", FieldType.row(REQUIRED_PRIMITIVE_SCHEMA), 1)
                  .withNullable(false))
          .setOptions(withTypeName("proto2_schema_messages.RequiredNested"))
          .build();

  // A sample instance of the proto.
  static final RequiredNested REQUIRED_NESTED =
      RequiredNested.newBuilder().setNested(REQUIRED_PRIMITIVE_PROTO).build();
}


text:
import unittest

import numpy

import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition

class TestMax(unittest.TestCase):

    def setUp(self):
        self.x = numpy.random.uniform(-1, 1, (3, 2, 4)).astype(numpy.float32)
        self.gy = numpy.array(2, dtype=numpy.float32)

    def check_forward(self, x_data, axis=None, keepdims=False):
        x = chainer.Variable(x_data)
        y = functions.max(x, axis=axis, keepdims=keepdims)
        self.assertEqual(y.data.dtype, numpy.float32)
        y_expect = self.x.max(axis=axis, keepdims=keepdims)
        self.assertEqual(y.data.shape, y_expect.shape)
        testing.assert_allclose(y_expect, y.data)

    def test_forward_cpu(self):
        self.check_forward(self.x)

    def test_forward_axis_cpu(self):
        for i in range(self.x.ndim):
            self.check_forward(self.x, axis=i)

    def test_forward_negative_axis_cpu(self):
        self.check_forward(self.x, axis=-1)

    def test_forward_multi_axis_cpu(self):
        self.check_forward(self.x, axis=(0, 1))

    def test_forward_multi_axis_invert_cpu(self):
        self.check_forward(self.x, axis=(1, 0))

    def test_forward_negative_multi_axis_cpu(self):
        self.check_forward(self.x, axis=(0, -1))

    def test_forward_negative_multi_axis_invert_cpu(self):
        self.check_forward(self.x, axis=(-2, 0))

    @attr.gpu
    def test_forward_gpu(self):
        self.check_forward(cuda.to_gpu(self.x))

    @attr.gpu
    def test_forward_axis_gpu(self):
        for i in range(self.x.ndim):
            self.check_forward(cuda.to_gpu(self.x), axis=i)

    @attr.gpu
    def test_forward_negative_axis_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=-1)

    @attr.gpu
    def test_forward_multi_axis_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(0, 1))

    @attr.gpu
    def test_forward_multi_axis_invert_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(1, 0))

    @attr.gpu
    def test_forward_negative_multi_axis_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(0, -1))

    @attr.gpu
    def test_forward_negative_multi_axis_invert_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(-2, 0))

    def check_backward(self, x_data, y_grad, axis=None, keepdims=False):
        gradient_check.check_backward(
            functions.Max(axis, keepdims),
            x_data, y_grad, dtype='d', eps=1e-5, rtol=1e-3, atol=1e-3)

    @condition.retry(3)
    def test_backward_cpu(self):
        self.check_backward(self.x, self.gy)

    @condition.retry(3)
    def test_backward_axis_cpu(self):
        for i in range(self.x.ndim):
            gy = numpy.ones_like(self.x.max(axis=i)) * self.gy
            self.check_backward(self.x, gy, axis=i)

    @condition.retry(3)
    def test_backward_negative_axis_cpu(self):
        gy = numpy.ones_like(self.x.max(axis=-1)) * self.gy
        self.check_backward(self.x, gy, axis=-1)

    @condition.retry(3)
    def test_backward_multi_axis_cpu(self):
        gy = numpy.ones_like(self.x.max(axis=(0, 1))) * self.gy
        self.check_backward(self.x, gy, axis=(0, 1))

    @condition.retry(3)
    def test_backward_multi_axis_invert_cpu(self):
        gy = numpy.ones_like(self.x.max(axis=(1, 0))) * self.gy
        self.check_backward(self.x, gy, axis=(1, 0))

    @condition.retry(3)
    def test_backward_negative_multi_axis_cpu(self):
        gy = numpy.ones_like(self.x.max(axis=(0, -1))) * self.gy
        self.check_backward(self.x, gy, axis=(0, -1))

    @condition.retry(3)
    def test_backward_negative_multi_axis_invert_cpu(self):
        gy = numpy.ones_like(self.x.max(axis=(-2, 0))) * self.gy
        self.check_backward(self.x, gy, axis=(-2, 0))

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))

    @attr.gpu
    @condition.retry(3)
    def test_backward_axis_gpu(self):
        for i in range(self.x.ndim):
            gy = numpy.ones_like(self.x.sum(axis=i)) * self.gy
            self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=i)

    @attr.gpu
    @condition.retry(3)
    def test_backward_negative_axis_gpu(self):
        for i in range(self.x.ndim):
            gy = numpy.ones_like(self.x.sum(axis=-1)) * self.gy
            self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=-1)

    @attr.gpu
    @condition.retry(3)
    def test_backward_multi_axis_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(0, 1))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(0, 1))

    @attr.gpu
    @condition.retry(3)
    def test_backward_multi_axis_invert_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(1, 0))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(1, 0))

    @attr.gpu
    @condition.retry(3)
    def test_backward_negative_multi_axis_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(0, -1))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(0, -1))

    @attr.gpu
    @condition.retry(3)
    def test_backward_negative_multi_axis_invert_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(-2, 0))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(-2, 0))

    def test_invalid_axis_type(self):
        with self.assertRaises(TypeError):
            functions.Max([0])

    def test_invalid_axis_type_in_tuple(self):
        with self.assertRaises(TypeError):
            functions.Max((1, 'x'))

    def test_duplicate_axis(self):
        with self.assertRaises(ValueError):
            functions.Max((0, 0))

    def test_pos_neg_duplicate_axis(self):
        with self.assertRaises(ValueError):
            self.x.max(axis=(1, -2))

class TestMin(unittest.TestCase):

    def setUp(self):
        self.x = numpy.random.uniform(-1, 1, (3, 2, 4)).astype(numpy.float32)
        self.gy = numpy.array(2, dtype=numpy.float32)

    def check_forward(self, x_data, axis=None, keepdims=False):
        x = chainer.Variable(x_data)
        y = functions.min(x, axis=axis, keepdims=keepdims)
        self.assertEqual(y.data.dtype, numpy.float32)
        y_expect = self.x.min(axis=axis, keepdims=keepdims)
        self.assertEqual(y.data.shape, y_expect.shape)
        testing.assert_allclose(y_expect, y.data)

    def test_forward_cpu(self):
        self.check_forward(self.x)

    def test_forward_axis_cpu(self):
        for i in range(self.x.ndim):
            self.check_forward(self.x, axis=i)

    def test_forward_negative_axis_cpu(self):
        self.check_forward(self.x, axis=-1)

    def test_forward_multi_axis_cpu(self):
        self.check_forward(self.x, axis=(0, 1))

    def test_forward_multi_axis_invert_cpu(self):
        self.check_forward(self.x, axis=(1, 0))

    def test_forward_negative_multi_axis_cpu(self):
        self.check_forward(self.x, axis=(0, -1))

    def test_forward_negative_multi_axis_invert_cpu(self):
        self.check_forward(self.x, axis=(-2, 0))

    @attr.gpu
    def test_forward_gpu(self):
        self.check_forward(cuda.to_gpu(self.x))

    @attr.gpu
    def test_forward_axis_gpu(self):
        for i in range(self.x.ndim):
            self.check_forward(cuda.to_gpu(self.x), axis=i)

    @attr.gpu
    def test_forward_negative_axis_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=-1)

    @attr.gpu
    def test_forward_multi_axis_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(0, 1))

    @attr.gpu
    def test_forward_multi_axis_invert_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(1, 0))

    @attr.gpu
    def test_forward_negative_multi_axis_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(0, -1))

    @attr.gpu
    def test_forward_negative_multi_axis_invert_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(-2, 0))

    def check_backward(self, x_data, y_grad, axis=None, keepdims=False):
        gradient_check.check_backward(
            functions.Min(axis=axis, keepdims=keepdims),
            x_data, y_grad, eps=1e-4, rtol=1e-3, atol=1e-3)

    @condition.retry(3)
    def test_backward_cpu(self):
        self.check_backward(self.x, self.gy)

    @condition.retry(3)
    def test_backward_axis_cpu(self):
        for i in range(self.x.ndim):
            gy = numpy.ones_like(self.x.min(axis=i)) * self.gy
            self.check_backward(self.x, gy, axis=i)

    @condition.retry(3)
    def test_backward_negative_axis_cpu(self):
        gy = numpy.ones_like(self.x.min(axis=-1)) * self.gy
        self.check_backward(self.x, gy, axis=-1)

    @condition.retry(3)
    def test_backward_multi_axis_cpu(self):
        gy = numpy.ones_like(self.x.min(axis=(0, 1))) * self.gy
        self.check_backward(self.x, gy, axis=(0, 1))

    @condition.retry(3)
    def test_backward_multi_axis_invert_cpu(self):
        gy = numpy.ones_like(self.x.min(axis=(1, 0))) * self.gy
        self.check_backward(self.x, gy, axis=(1, 0))

    @condition.retry(3)
    def test_backward_negative_multi_axis_cpu(self):
        gy = numpy.ones_like(self.x.min(axis=(0, -1))) * self.gy
        self.check_backward(self.x, gy, axis=(0, -1))

    @condition.retry(3)
    def test_backward_negative_multi_axis_invert_cpu(self):
        gy = numpy.ones_like(self.x.min(axis=(-2, 0))) * self.gy
        self.check_backward(self.x, gy, axis=(-2, 0))

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))

    @attr.gpu
    @condition.retry(3)
    def test_backward_axis_gpu(self):
        for i in range(self.x.ndim):
            gy = numpy.ones_like(self.x.sum(axis=i)) * self.gy
            self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=i)

    @attr.gpu
    @condition.retry(3)
    def test_backward_negative_axis_gpu(self):
        for i in range(self.x.ndim):
            gy = numpy.ones_like(self.x.sum(axis=-1)) * self.gy
            self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=-1)

    @attr.gpu
    @condition.retry(3)
    def test_backward_multi_axis_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(0, 1))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(0, 1))

    @attr.gpu
    @condition.retry(3)
    def test_backward_multi_axis_invert_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(1, 0))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(1, 0))

    @attr.gpu
    @condition.retry(3)
    def test_backward_negative_multi_axis_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(0, -1))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(0, -1))

    @attr.gpu
    @condition.retry(3)
    def test_backward_negative_multi_axis_invert_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(-2, 0))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(-2, 0))

    def test_invalid_axis_type(self):
        with self.assertRaises(TypeError):
            functions.Min([0])

    def test_invalid_axis_type_in_tuple(self):
        with self.assertRaises(TypeError):
            functions.Min((1, 'x'))

    def test_duplicate_axis(self):
        with self.assertRaises(ValueError):
            functions.Min((0, 0))

    def test_pos_neg_duplicate_axis(self):
        with self.assertRaises(ValueError):
            self.x.min(axis=(1, -2))

@testing.parameterize(*testing.product_dict(
    [
        {'function_name': 'argmax', 'function_class': functions.ArgMax},
        {'function_name': 'argmin', 'function_class': functions.ArgMin},
    ],
    [
        {'axis': None},
        {'axis': 0},
        {'axis': 1},
        {'axis': 2},
        {'axis': -1},
        {'axis': -2},
        {'axis': -3},
    ],
    [
        {'dtype': numpy.float16},
        {'dtype': numpy.float32},
        {'dtype': numpy.float64},
    ]
))
class TestArgMinMax(unittest.TestCase):

    def setUp(self):
        self.function = getattr(functions, self.function_name)
        self.expect = getattr(numpy, self.function_name)

        self.x = numpy.random.uniform(-1, 1, (3, 2, 4)).astype(self.dtype)

    def check_forward(self, x_data):
        x = chainer.Variable(x_data)
        y = self.function(x, axis=self.axis)
        self.assertEqual(y.data.dtype, numpy.int32)
        y_expect = self.expect(self.x, axis=self.axis)
        self.assertEqual(y.data.shape, y_expect.shape)
        testing.assert_allclose(y_expect, y.data)

    def test_forward_cpu(self):
        self.check_forward(self.x)

    @attr.gpu
    def test_forward_gpu(self):
        self.check_forward(cuda.to_gpu(self.x))

    def check_backward(self, x_data):
        x = chainer.Variable(x_data)
        y = self.function(x, axis=self.axis)
        y.backward()
        self.assertIsNone(x.grad)

    @condition.retry(3)
    def test_backward_cpu(self):
        self.check_backward(self.x)

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.check_backward(cuda.to_gpu(self.x))

    def test_invalid_axis_type(self):
        with self.assertRaises(TypeError):
            self.function_class([0])

    def test_invalid_axis_type_in_tuple(self):
        with self.assertRaises(TypeError):
            self.function_class((1, 'x'))

testing.run_module(__name__, __file__)


text:
package org.ethereum.net.client;

import org.ethereum.manager.WorldManager;
import org.ethereum.net.server.ChannelManager;
import org.ethereum.net.server.EthereumChannelInitializer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultMessageSizeEstimator;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import static org.ethereum.config.SystemProperties.CONFIG;

/**
 * This class creates the connection to an remote address using the Netty framework
 *
 * @see http://netty.io
 */
@Component
@Scope("prototype")
public class PeerClient {

    private static final Logger logger = LoggerFactory.getLogger("net");

//    private boolean peerDiscoveryMode = false;

    @Autowired
    private ApplicationContext ctx;

    @Autowired
    WorldManager worldManager;

    @Autowired
    public ChannelManager channelManager;

    public void connect(String host, int port, String remoteId) {
        connect(host, port, remoteId, false);
    }

    public void connect(String host, int port, String remoteId, boolean discoveryMode) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        worldManager.getListener().trace("Connecting to: " + host + ":" + port);

        EthereumChannelInitializer ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, remoteId);
        ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);

            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONFIG.peerConnectionTimeout());
            b.remoteAddress(host, port);

            b.handler(ethereumChannelInitializer);

            // Start the client.
            ChannelFuture f = b.connect().sync();

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();

            channelManager.notifyDisconnect(ethereumChannelInitializer.getChannel());
            logger.debug("Connection is closed");
        } catch (Exception e) {
            logger.error("Exception: {}", e.toString());
//            logger.trace("Exception details:", e);
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}


text:
{{define "db/dbImport"}}
{{template "Tpl/header" .}}
{{template "Tpl/headerSecond" .}}
{{template "Tpl/sidebar" .}}

{{set . "navigation" "导入"}}
{{set . "active" "dbImport"}}

  {{template "Tpl/dbNavigationOne" .}}
  {{template "Tpl/dbNavigationTwo" .}}

        导入

        <form class="am-form am-form-horizontal am-container" enctype="multipart/form-data" >

                 .JS file exported with TinMongo:

                JS File:
                <button type="button" class="am-btn am-btn-default am-btn-sm">
                     选择要上传的文件</button>
                  <input id="js-file"  type="file" multiple>

            Confirm

                    <button type="button" class="am-close" >×</button>

                    <button type="button"  class="am-close">×</button>

              <button type="button" class="am-btn am-btn-default am-btn-block" id="js_import_btn" >导入</button>

        </form>

        <form class="am-form am-form-horizontal am-container" enctype="multipart/form-data" >

             .JSON file exported with mongoexport:

            Import to collection name:

              <input type="text" id="import_collection">

              JSON File:
              <button type="button" class="am-btn am-btn-default am-btn-sm">
                   选择要上传的文件</button>
                <input id="json-file"  type="file" multiple>

            Confirm

                    <button type="button" class="am-close" >×</button>

                    <button type="button"  class="am-close">×</button>

              <button type="button" class="am-btn am-btn-default am-btn-block" id="json_import_btn" >导入</button>

              <input type="text" value="{{.DBName}}" id="dbName">

        </form>

{{template "Tpl/footer" .}}

{{end}}


text: This is my first rnn model in tensorflow


text:
package ca.com.androidbinnersproject.adapters;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.ArrayList;

public class ViewPagerAdapter extends FragmentPagerAdapter {

	private final ArrayList<Fragment> fragList = new ArrayList<>();
	private final ArrayList<String> titleList = new ArrayList<>();

	public ViewPagerAdapter(FragmentManager fragmentManager) {
		super(fragmentManager);
	}

	@Override
	public Fragment getItem(int position) {
		return fragList.get(position);
	}

	@Override
	public CharSequence getPageTitle(int position) {
		return titleList.get(position);
	}

	@Override
	public int getCount() {
		return fragList.size();
	}

	public void AddFragment(Fragment frag, String title) {
		fragList.add(frag);
		titleList.add(title);
	}
}


text:
var gulp = require("gulp");
var bower = require("gulp-bower");
var elixir = require("laravel-elixir");

gulp.task('bower', function() {
    return bower();
});

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Less
 | file for our application, as well as publishing vendor resources.
 |
 */

var paths = {
    'jquery': 'vendor/jquery-legacy/dist',
    'bootstrap': 'vendor/bootstrap-sass/assets',
    'bootswatch': 'vendor/bootswatch',
    'fontawesome': 'vendor/font-awesome',
    'metisMenu': 'vendor/metisMenu/dist',
    'colorbox': 'vendor/jquery-colorbox',
    'dataTables': 'vendor/datatables/media',
    'dataTablesBootstrap3Plugin': 'vendor/datatables-bootstrap3-plugin/media'
};

elixir.config.sourcemaps = false;

elixir(function (mix) {

    // Run bower install
    mix.task('bower');

    // Copy fonts straight to public
    mix.copy(paths.bootstrap + '/fonts/bootstrap/**', 'public/fonts');
    mix.copy(paths.fontawesome + '/fonts/**', 'public/fonts');

    // Copy images straight to public
    mix.copy(paths.colorbox + '/example3/images/**', 'public/img');

     // Compile SASS and output to default resource directory
    mix.sass('app.scss', 'resources/css', {
        includePaths: [
            'resources/' + paths.bootstrap + '/stylesheets/',
            'resources/' + paths.bootswatch + '/',
            'resources/' + paths.fontawesome + '/scss/'
        ]
    });

    // Merge CSSs
    mix.styles([
        paths.colorbox + '/example3/colorbox.css',
        paths.dataTablesBootstrap3Plugin + '/css/datatables-bootstrap3.css',
        paths.metisMenu + '/metisMenu.css',
        'css/app.css' // app.css is generated by sass and has some overrides
    ], 'public/css/all.css', 'resources/');

    // Merge scripts
    mix.scripts([
        paths.jquery + '/jquery.js',
        paths.bootstrap + '/javascripts/bootstrap.js',
        paths.dataTables + '/js/jquery.dataTables.js',
        paths.dataTablesBootstrap3Plugin + '/js/datatables-bootstrap3.js',
        paths.colorbox + '/jquery.colorbox.js',
        paths.metisMenu + '/metisMenu.js'
    ], 'public/js/all.js', 'resources/');

    // Cache-bust all.css and all.js
    mix.version([
        'public/css/all.css',
        'public/js/all.js'
    ]);
});


text:
qc::conn_if_modified_since
==========================

part of [Docs](../index.md)

Usage
-----
`qc::conn_if_modified_since `

Description
-----------
Return the value of the current If-Modified-Since header, if one exists, or "" otherwise.

----------------------------------
*[Qcode Software Limited] [qcode]*

[qcode]: http://www.qcode.co.uk "Qcode Software"