text:
package ch.ethz.acl.intrinsics

import java.io.{File, FileOutputStream, PrintStream}

import ch.ethz.acl.intrinsics.MicroArchType._
import ch.ethz.acl.passera.unsigned.{UByte, UInt, ULong, UShort}

import scala.language.postfixOps
import scala.xml.{Node, XML}
import scala.lms.common.{ArrayOpsExp, BooleanOpsExp, PrimitiveOpsExp, SeqOpsExp}

protected class IntrinsicsGenerator extends IntrinsicsBase with ArrayOpsExp with SeqOpsExp with PrimitiveOpsExp with BooleanOpsExp {
  implicit def uIntTyp    : Typ[UInt] = manifestTyp
  implicit def uByteTyp   : Typ[UByte] = manifestTyp
  implicit def uShortTyp  : Typ[UShort] = manifestTyp
  implicit def uLongTyp   : Typ[ULong] = manifestTyp
  implicit def anyTyp     : Typ[Any] = manifestTyp

  val rootPath = new File(".").getAbsolutePath
  val srcPath = rootPath + "/src/main/scala/ch/ethz/acl/intrinsics/"
  val resourcePath = rootPath + "/src/main/resources/"
  val xmlFile = resourcePath + "data-3.3.16.xml"
  val nrIntrinsicsPerFile = 175
  var intrinsicsNames = scala.collection.mutable.Set[String]()

  case class Parameter (varName: String, pType: String)

  case class Intrinsic (node: Node,
                        name: String,
                        tech: String,
                        CPUID: List[String],
                        returnType: String,
                        intrinsicType: List[IntrinsicsType.IntrinsicsType],
                        category: List[IntrinsicsCategory.IntrinsicsCategory],
                        performance: Map[MicroArchType, Performance],
                        nonOffsetParams: List[Parameter],
                        offsetParams: List[Parameter],
                        description: String,
                        operation: List[String],
                        header: String
                       ) {

    def getAllTypeStrings = returnType :: offsetParams.map(_.pType)
    def toXML = node.toString()
    def allParams = nonOffsetParams ::: offsetParams

    def mirroringPrefix = {
      if (extractArrayParams.nonEmpty) {
        "iDef@"
      } else {
        ""
      }
    }

    def getDefName = {
      var defName = name.toUpperCase()

      while (defName.charAt(0) == '_') {
        defName = defName.substring(1)
      }

      assert(!defName.equals(name), "Method and class have the same name")
      defName
    }

    def getParamsAsStrings = {
      allParams.map(p => {
        p.varName + ": " + p.pType
      }).mkString(", ")
    }

    def getLMSParams = {
      allParams.map(p => {
        p.varName + ": Exp[" + (if (offsetParams.contains(p)) "U" else remap(p.pType)) + "]"
      }).mkString(", ")
    }

    def getParams = {
      allParams.map(p => p.varName).mkString(", ")
    }

    def getReturnType = {
      val standardRetType = remap(returnType)
      if (standardRetType == "A[T]") "VoidPointer" else standardRetType
    }

    def extractArrayParams = {
      nonOffsetParams.filter(isArrayParam)
    }

    def prettyDescription = {
      Utils.wrap(description, 78)
    }

    def hasVoidPointers = {
      nonOffsetParams.exists(p => remap(p.pType) == "A[T]")
    }

    def hasArrayTypes = {
      extractArrayParams.nonEmpty || getReturnType.startsWith("A[")
    }

    def typeParams = {
      if (hasArrayTypes) {
        if (hasVoidPointers) "[A[_], T:Typ, U:Integral]" else "[A[_], U:Integral]"
      } else {
        ""
      }
    }

    def abstractContainer = {
      if (hasArrayTypes) {
        "(implicit val cont: Container[A])"
      } else {
        ""
      }
    }

    def abstractNonValContainer = {
      if (hasArrayTypes) {
        "(implicit cont: Container[A])"
      } else {
        ""
      }
    }

    def genMirror(varName: String) = {
      if (extractArrayParams.nonEmpty) {
        s"iDef.cont.applyTransformer($varName, f)"
      } else {
        s"f($varName)"
      }
    }

    def optionallyAddImplContMirror = {
      if (hasArrayTypes) {
        if (hasVoidPointers) "(iDef.voidType, iDef.integralType, iDef.cont)" else "(iDef.integralType, iDef.cont)"
      } else {
        ""
      }
    }

    def addImplCont() = {
      if (hasArrayTypes) {
        if (hasVoidPointers) "(typ[T], implicitly[Integral[U]], cont)" else "(implicitly[Integral[U]], cont)"
      } else {
        ""
      }
    }

    def addSuperClass() = {
      if (hasVoidPointers)
        s"VoidPointerIntrinsicsDef[T, U, $getReturnType]"
      else if (extractArrayParams.nonEmpty)
        s"PointerIntrinsicsDef[U, $getReturnType]"
      else
        s"IntrinsicsDef[$getReturnType]"
    }
  }

  def isArrayParam(p: Parameter) = {
    val tpe = typeMappings(p.pType)
    tpe.typeArguments.nonEmpty
  }

  def santizeParamName(s: String) = s match {
    case "RoundKey" => "roundKey"
    case "type" => "tpe"
    case "val" => "value"
    case _ => s
  }

  def manifestSimple[T](tp: Typ[T]): String = {
    val name = tp match {
      case _ if tp <:< typ[Unit]    => "Unit"
      case _ if tp <:< typ[Double]  => "Double"
      case _ if tp <:< typ[Float]   => "Float"
      case _ if tp <:< typ[Char]    => "Char"
      case _ if tp <:< typ[Boolean] => "Boolean"
      case _ if tp <:< typ[Long]    => "Long"
      case _ if tp <:< typ[Int]     => "Int"
      case _ if tp <:< typ[Short]   => "Short"
      case _ if tp <:< typ[Byte]    => "Byte"
      case _ if tp.runtimeClass.getSimpleName == "Object" => "Any"
      case _ => tp.runtimeClass.getSimpleName
    }
    tp.typeArguments.isEmpty match {
      case true => name
      case _ =>
        val simpleType = manifestSimple(tp.typeArguments.head)
        "A[" + (if (simpleType == "Any") "T" else simpleType) + "]"
    }
  }

  def remap(tpe: String) = {
    val m = typeMappings(tpe)
    manifestSimple(m)
  }

  val typeMappings = Map (

    /* ============= Enums ============= */

    "_MM_BROADCAST32_ENUM"     -> typ[Int],
    "_MM_BROADCAST64_ENUM"     -> typ[Int],
    "_MM_DOWNCONV_EPI32_ENUM"  -> typ[Int],
    "_MM_DOWNCONV_EPI64_ENUM"  -> typ[Int],
    "_MM_DOWNCONV_PD_ENUM"     -> typ[Int],
    "_MM_DOWNCONV_PS_ENUM"     -> typ[Int],
    "_MM_EXP_ADJ_ENUM"         -> typ[Int],
    "_MM_MANTISSA_NORM_ENUM"   -> typ[Int],
    "_MM_MANTISSA_SIGN_ENUM"   -> typ[Int],
    "_MM_PERM_ENUM"            -> typ[Int],
    "_MM_SWIZZLE_ENUM"         -> typ[Int],
    "_MM_UPCONV_EPI32_ENUM"    -> typ[Int],
    "_MM_UPCONV_EPI64_ENUM"    -> typ[Int],
    "_MM_UPCONV_PD_ENUM"       -> typ[Int],
    "_MM_UPCONV_PS_ENUM"       -> typ[Int],
    "const _MM_UPCONV_PS_ENUM" -> typ[Int],
    "const _MM_CMPINT_ENUM"    -> typ[Int],

    /* ============= Intrinsics ============= */

    "__m64"           -> typ[__m64],
    "__m64*"          -> typ[Array[__m64]],
    "__m64 const*"    -> typ[Array[__m64]],

    "__m128"          -> typ[__m128],
    "__m128 *"        -> typ[Array[__m128]],
    "__m128 const *"  -> typ[Array[__m128]],

    "__m128d"         -> typ[__m128d],
    "__m128d *"       -> typ[Array[__m128d]],
    "__m128d const *" -> typ[Array[__m128d]],

    "__m128i"         -> typ[__m128i],
    "_m128i *"        -> typ[Array[__m128i]],
    "__m128i*"        -> typ[Array[__m128i]],
    "__m128i *"       -> typ[Array[__m128i]],
    "const __m128i*"  -> typ[Array[__m128i]],
    "__m128i const*"  -> typ[Array[__m128i]],

    "__m256"          -> typ[__m256],
    "__m256 *"        -> typ[Array[__m256]],

    "__m256d"         -> typ[__m256d],
    "__m256d *"       -> typ[Array[__m256d]],

    "__m256i"         -> typ[__m256i],
    "__m256i *"       -> typ[Array[__m256i]],
    "__m256i const *" -> typ[Array[__m256i]],
    "__m256i const*"  -> typ[Array[__m256i]],

    "__m512"          -> typ[__m512],
    "_m512"          -> typ[__m512],
    "__m512 *"        -> typ[Array[__m512]],
    "__m512d"         -> typ[__m512d],
    "__m512d *"       -> typ[Array[__m512d]],
    "__m512i"         -> typ[__m512i],
    "_m512i"         -> typ[__m512i],

    "__mmask8"        -> typ[Int],
    "__mmask16"       -> typ[Int],
    "_mmask16"       -> typ[Int],
    "__mmask16 *"     -> typ[Array[Int]],
    "__mmask32"       -> typ[Int],
    "__mmask64"       -> typ[Long],

    /* ============= Char / Byte ============= */

    "unsigned char"      -> typ[UByte],

    "char"               -> typ[Byte],
    "__int8"             -> typ[Byte],
    "char const*"        -> typ[Array[Byte]],
    "char*"              -> typ[Array[Byte]],

    /* =============== Short ================ */

    "unsigned short"     -> typ[UShort],
    "unsigned short*"    -> typ[Array[UShort]],
    "unsigned short *"   -> typ[Array[UShort]],

    "short"              -> typ[Short],
    "__int16"            -> typ[Short],

    /* =============== Integer ================ */

    "unsigned"           -> typ[UInt],
    "unsigned int"       -> typ[UInt],
    "unsigned __int32"   -> typ[UInt],
    "const unsigned int" -> typ[UInt],
    "unsigned int*"      -> typ[Array[UInt]],
    "unsigned int *"     -> typ[Array[UInt]],
    "unsigned __int32*"  -> typ[Array[UInt]],

    "int"                -> typ[Int],
    "size_t"             -> typ[Int],
    "__int32"            -> typ[Int],
    "const int"          -> typ[Int],
    "int*"               -> typ[Array[Int]],
    "__int32*"           -> typ[Array[Int]],
    "int const*"         -> typ[Array[Int]],

    /* ================ Long ================== */

    "unsigned long"      -> typ[ULong],
    "unsigned __int64"   -> typ[ULong],
    "unsigned __int64*"  -> typ[Array[ULong]],
    "unsigned __int64 *" -> typ[Array[ULong]],

    "__int64"            -> typ[Long],
    "long long"          -> typ[Long],
    "__int64*"           -> typ[Array[Long]],
    "__int64 const*"     -> typ[Array[Long]],

    /* ================ Float ================== */

    "float"              -> typ[Float],
    "float*"             -> typ[Array[Float]],
    "float *"            -> typ[Array[Float]],
    "float const *"      -> typ[Array[Float]],
    "float const*"       -> typ[Array[Float]],
    "const float*"       -> typ[Array[Float]],

    /* ================ Double ================= */

    "double"             -> typ[Double],
    "double*"            -> typ[Array[Double]],
    "double *"           -> typ[Array[Double]],
    "double const*"      -> typ[Array[Double]],
    "double const *"     -> typ[Array[Double]],
    "const double*"      -> typ[Array[Double]],

    /* ================ Void ================= */

    "void"               -> typ[Unit],
    "void*"              -> typ[Array[Any]],
    "void *"             -> typ[Array[Any]],
    "void const*"        -> typ[Array[Any]],
    "void const *"       -> typ[Array[Any]],
    "const void *"       -> typ[Array[Any]],
    "const void **"      -> typ[DoubleVoidPointer]
  )

  def indent(s: String, ind: String) = {
    s.trim.lines.map(l => ind + l).mkString("\n")
  }

  def generateISA(isa: String, intrinsics: List[Intrinsic], out: PrintStream, statsOutput: PrintStream, parent: String = "") = {
    if (parent == "") statsOutput.println(s"$isa statistics:\n\n")

    out.println(getPreamble)
    out.println("trait " + isa + " extends IntrinsicsBase {")

    var numberOfPointerArguments = 0
    var pointerArgumentsNames: List[String] = List()

    // Generate code for LMS case classes
    intrinsics foreach { in => {
      if (in.extractArrayParams.size > 1) {
        statsOutput.println(s"Intrinsic ${in.name} has ${in.extractArrayParams.size} pointer arguments")
      }
      if (in.getReturnType == "A[T]") {
        statsOutput.println(s"Intrinsic ${in.name} has void return type")
      }

      val perfs = in.performance.keys.map({ arch =>
        val perf = in.performance(arch)
        arch.toString + " -> Performance(" + perf.latency + ", " + perf.throughput + ")"
      }).mkString(", \n")
      val performanceMap = in.performance.size match {
        case 0 => "Map.empty[MicroArchType, Performance]"
        case _ => "Map (\n" + indent(perfs, "      ") + "\n    )"
      }

      out.println("  /**")
      out.println(indent(in.prettyDescription, "   * "))
      out.println(indent(in.getParamsAsStrings, "   * "))
      out.println("   */")

      out.println(
        s"""  case class ${in.getDefName}${in.typeParams}(${in.getLMSParams})${in.abstractContainer} extends ${in.addSuperClass()} {
            |    val category = List(${ in.category.map(c => "IntrinsicsCategory." + c.toString).mkString(", ") })
            |    val intrinsicType = List(${ in.intrinsicType.map(c => "IntrinsicsType." + c.toString).mkString(", ") })
            |    val performance = $performanceMap
            |    val header = "${in.header}"
            |  }
      """.stripMargin)

      out.println()

    }}

    // Generate code for LMS methods
    intrinsics foreach { in =>
      in.getReturnType match {
        case _ if in.getReturnType == "VoidPointer" || in.getReturnType.startsWith("A[") =>
          out.println(
            s"""  def ${in.name}${in.typeParams}(${in.getLMSParams})${in.abstractNonValContainer}: Exp[${in.getReturnType}] = {
                |    reflectMutable(${in.getDefName}(${in.getParams})${in.addImplCont()})
                |  }
            """.stripMargin)
        case _ if in.category.contains(IntrinsicsCategory.Load) =>
          out.println(
            s"""  def ${in.name}${in.typeParams}(${in.getLMSParams})(implicit cont: Container[A]): Exp[${in.getReturnType}] = {
                |    cont.read(${in.extractArrayParams.map(_.varName).mkString(", ")})(${in.getDefName}(${in.getParams})${in.addImplCont()})
                |  }
            """.stripMargin)
        case _ if in.extractArrayParams.nonEmpty =>
          numberOfPointerArguments = numberOfPointerArguments + 1
          pointerArgumentsNames = pointerArgumentsNames ::: List(in.name)

          val arrays = in.extractArrayParams
          out.println(
            s"""  def ${in.name}${in.typeParams}(${in.getLMSParams})(implicit cont: Container[A]): Exp[${in.getReturnType}] = {
                |    cont.write(${arrays.map(_.varName).mkString(", ")})(${in.getDefName}(${in.getParams})${in.addImplCont()})
                |  }
            """.stripMargin)
        case "Unit" =>
          out.println(
            s"""  def ${in.name}${in.typeParams}(${in.getLMSParams}): Exp[${in.getReturnType}] = {
                |    reflectEffect(${in.getDefName}(${in.getParams}))
                |  }
            """.stripMargin)
        case _ =>
          out.println(
            s"""  def ${in.name}${in.typeParams}(${in.getLMSParams}): Exp[${in.getReturnType}] = {
                |    ${in.getDefName}(${in.getParams})
                |  }
            """.stripMargin)
      }
    }

    if (parent == "") statsOutput.println(s"Number of $isa intrinsics: ${intrinsics.size}")
    statsOutput.println(s"Number of intrinsics with pointer arguments: $numberOfPointerArguments")
    pointerArgumentsNames foreach statsOutput.println

    // Generate code for mirroring
    out.println("  override def mirror[A:Typ](e: Def[A], f: Transformer)(implicit pos: SourceContext): Exp[A] = (e match {")
    intrinsics foreach { in =>
      out.println(
        s"""    case ${in.mirroringPrefix}${in.getDefName} (${in.getParams}) =>
            |      ${in.name}(${in.allParams.map(p => in.genMirror(p.varName)).mkString(", ")})${in.optionallyAddImplContMirror}""".stripMargin)
    }
    out.println()
    intrinsics foreach { in =>
      out.println(
        s"""    case Reflect(${in.mirroringPrefix}${in.getDefName} (${in.getParams}), u, es) =>
            |      reflectMirrored(Reflect(${in.getDefName} (${in.allParams.map(p => in.genMirror(p.varName)).mkString(", ")})${in.optionallyAddImplContMirror}, mapOver(f,u), f(es)))(mtype(typ[A]), pos)""".stripMargin)
    }

    out.println("    case _ => super.mirror(e, f)")
    out.println("  }).asInstanceOf[Exp[A]] // why??")
    out.println("}")
    out.println()

    // Generate trait for code generation
    out.println(
      s"""trait CGen$isa extends CGenIntrinsics {
          |
          |  val IR: ${if (parent == "") isa else parent}
          |  import IR._
          |
         |  override def emitNode(sym: Sym[Any], rhs: Def[Any]) = rhs match {
       """.stripMargin)

    def paramPlusOffset(parameter: Parameter): String = {
      if (!isArrayParam(parameter)) {
        return "${quote(" + parameter.varName + ")}"
      }

      val cast = s"(${parameter.pType}) "
      val basis = "${quote(" + parameter.varName + ")"
      val offset = " + (if(" + parameter.varName + "Offset == Const(0)) \"\" else \" + \" + quote(" + parameter.varName + "Offset))}"
      cast + s"($basis $offset)"
    }

    intrinsics foreach { in =>
      out.println(s"    case iDef@${in.getDefName}(${in.getParams}) =>")
      out.println("      headers += iDef.header")
      if (in.getReturnType == "Unit")
        out.println("      stream.println(%s)".format(s"""s\"${in.name}(${in.nonOffsetParams.map(paramPlusOffset).mkString(", ")});\""""))
      else
        out.println("      emitValDef(sym, %s)".format(s"""s\"${in.name}(${in.nonOffsetParams.map(paramPlusOffset).mkString(", ")})\""""))

    }

    out.println("    case _ => super.emitNode(sym, rhs)")
    out.println("  }")
    out.println("}")
  }

  def getAttribute(node: Node, attr: String) = {
    val value = node.attribute(attr) match {
      case Some(x) => x.toString()
      case None =>
        println(node)
        throw new RuntimeException(s"Can not find attr $attr")
    }
    if (value.trim().equals("")) {
      println(node)
      throw new RuntimeException(s"attr $attr is empty")
    } else {
      value
    }
  }

  def parseIntrinsics(nodes: List[Node]) = {

    nodes map { node =>
      val name = getAttribute(node, "name")
      val techRaw = getAttribute(node, "tech")
      val returnType = name match {
        case "_MM_TRANSPOSE4_PS" => "void"
        case _ => getAttribute(node, "rettype")
      }
      val CPUID           = (node \ "CPUID").map(_.text).toList
      val intrinsicType   = (node \ "type").map(t => strToIntrisicsType(t.text)).toList
      val category        = (node \ "category").map(c => strToIntrinsicsCategory(c.text)).toList
      val descriptionList = (node \ "description").map(_.text).toList
      val operation       = (node \ "operation").map(_.text).toList
      val headerList      = (node \ "header").map(_.text).toList

      val primitiveParams = (node \ "parameter").toList flatMap { param =>
        val pType   = getAttribute(param, "type")
        pType match {
          case "void" => None
          case _ =>
            val varName = santizeParamName(getAttribute(param, "varname"))
            Some(Parameter(varName, pType))
        }
      } distinct
      val arrayParams = primitiveParams.filter(isArrayParam).map(p => Parameter(p.varName + "Offset", "int"))

      val performance = (node \ "perfdata").toList.flatMap({ perf =>
        val arch = strToMicroArchType(getAttribute(perf, "arch"))
        val lat = perf.attribute("lat") match {
          case Some(latNode) => latNode.text.trim match {
            case "" => None
            case "Varies" => None
            case txt => Some(java.lang.Double.parseDouble(txt))
          }
          case None => None
        }

        val tpt = perf.attribute("tpt") match {
          case Some(tptNode) => tptNode.text.trim match {
            case "" => None
            case "Varies" => None
            case txt => Some(java.lang.Double.parseDouble(txt))
          }
          case None => None
        }
        (lat, tpt) match {
          case (None, None) => None
          case _ => Some(arch -> Performance(lat, tpt))
        }
      }).toMap

      // Cleanup
      val tech = techRaw.replace(".", "").replace("-", "").replace("/", "_")
      val description = descriptionList.headOption.getOrElse("No description available for this intrinsic")
      val header = headerList.head

      Intrinsic (node, name, tech, CPUID, returnType, intrinsicType, category,
        performance, primitiveParams, arrayParams, description, operation, header
      )
    }

  }

  def createISA(name: String, allIntrinsics: List[Intrinsic]) = {
    val intrinsics = allIntrinsics
      .filter(in => in.tech.equals(name) && !intrinsicsNames.contains(in.name))
      .groupBy(_.name)
      .mapValues(_.head)
      .values
      .toList
    intrinsicsNames ++= intrinsics.map(in => in.name)
    if (intrinsics.size < nrIntrinsicsPerFile) {
      val path = srcPath + name + ".scala"
      val output = new PrintStream(new FileOutputStream(path))
      val statsOutputFile = new File(rootPath + "/stats/" + name + ".txt")
      statsOutputFile.createNewFile()
      val statsOutput = new PrintStream(new FileOutputStream(statsOutputFile), false)
      generateISA(name, intrinsics, output, statsOutput)
    } else {
      createComplexISA(name, intrinsics)
    }
  }

  def createComplexISA(name: String, intrinsics: List[Intrinsic]) = {
    val statsOutputFile = new File(rootPath + "/stats/" + name + ".txt")
    statsOutputFile.createNewFile()
    val statsOutput = new PrintStream(new FileOutputStream(statsOutputFile), false)
    statsOutput.println(s"$name statistics:\n\n")
    statsOutput.println(s"Number of $name intrinsics: ${intrinsics.size}")

    val subFiles = intrinsics.grouped(nrIntrinsicsPerFile).toList.zipWithIndex
    subFiles foreach {case (subIntrinsics, index) =>
      val newName = name + "0" + index
      val path = srcPath + newName + ".scala"
      val output = new PrintStream(new FileOutputStream(path))
      generateISA(newName, subIntrinsics, output, statsOutput, name)
    }
    val path = srcPath + name + ".scala"
    val out = new PrintStream(new FileOutputStream(path))
    out.println(getLogo)
    out.println("package ch.ethz.acl.intrinsics")
    out.println()
    out.print(s"trait $name extends IntrinsicsBase")
    subFiles foreach {case (_, index) => out.print(" with " + name + "0" + index)}
    val shouldAdd512KNC = (name == "AVX512" || name == "KNC") && new java.io.File(srcPath + "AVX512_KNC.scala").exists
    if (shouldAdd512KNC) {
      out.print(" with AVX512_KNC")
    }
    out.println("\n")

    out.print(s"trait CGen$name extends CGenIntrinsics")
    subFiles foreach {case (_, index) => out.print(" with CGen" + name + "0" + index)}
    if (shouldAdd512KNC) {
      out.print(" with CGenAVX512_KNC")
    }
    out.println(" {")
    out.println(s"  val IR: $name")
    out.println("}\n")
  }

  def generate (): Unit = {
    val xml: Node = XML.loadFile(xmlFile)
    val nodes = (xml \\ "intrinsic").toList

    val intrinsics = parseIntrinsics(nodes)
        createISA("MMX", intrinsics)

        createISA("SSE", intrinsics)
        createISA("SSE2", intrinsics)
        createISA("SSE3", intrinsics)
        createISA("SSSE3", intrinsics)
        createISA("SSE41", intrinsics)
        createISA("SSE42", intrinsics)

        createISA("AVX", intrinsics)
        createISA("AVX2", intrinsics)

        createISA("AVX512_KNC", intrinsics)
        createISA("AVX512", intrinsics)
        createISA("FMA", intrinsics)
        createISA("KNC", intrinsics)
        createISA("SVML", intrinsics)

        createISA("Other", intrinsics)
  }

  def strToMicroArchType(s: String): MicroArchType = s match {
    case "Haswell"      => Haswell
    case "Ivy Bridge"   => IvyBridge
    case "Nehalem"      => Nehalem
    case "Sandy Bridge" => SandyBridge
    case "Westmere"     => Westmere
  }

  def strToIntrisicsType(s: String): IntrinsicsType.IntrinsicsType = s match {
    case "Floating Point" => IntrinsicsType.FloatingPoint
    case "Integer" => IntrinsicsType.Integer
    case "Mask" => IntrinsicsType.Mask
  }

  def strToIntrinsicsCategory(s: String): IntrinsicsCategory.IntrinsicsCategory = {
    import IntrinsicsCategory._
    s match {
      case "Application-Targeted" => ApplicationTargeted
      case "Arithmetic" => Arithmetic
      case "Bit Manipulation" => BitManipulation
      case "Cast" => Cast
      case "Compare" => Compare
      case "Convert" => Convert
      case "Cryptography" => Cryptography
      case "Elementary Math Functions" => ElementaryMathFunctions
      case "General Support" => GeneralSupport
      case "Load" => Load
      case "Logical" => Logical
      case "Mask" => Mask
      case "Miscellaneous" => Miscellaneous
      case "Move" => Move
      case "OS-Targeted" => OSTargeted
      case "Probability/Statistics" => ProbabilityStatistics
      case "Random" => Random
      case "Set" => IntrinsicsSet
      case "Shift" => Shift
      case "Special Math Functions" => SpecialMathFunctions
      case "Store" => Store
      case "String Compare" => StringCompare
      case "Swizzle" => Swizzle
      case "Trigonometry" => Trigonometry
      case _ => throw new RuntimeException("Intrinsics category unknown")
    }
  }

  def getPreamble = {
    getLogo + """
      |package ch.ethz.acl.intrinsics
      |
      |import ch.ethz.acl.intrinsics.MicroArchType._
      |import ch.ethz.acl.passera.unsigned.{UByte, UInt, ULong, UShort}
      |
      |import scala.reflect.SourceContext
      |import scala.language.higherKinds
      |
    """.stripMargin
  }

  def getLogo = {
    """/**
      |  *  Intel Intrinsics for Lightweight Modular Staging Framework
      |  *  https://github.com/ivtoskov/lms-intrinsics
      |  *  Department of Computer Science, ETH Zurich, Switzerland
      |  *      __                         _         __         _               _
      |  *     / /____ ___   _____        (_)____   / /_ _____ (_)____   _____ (_)_____ _____
      |  *    / // __ `__ \ / ___/______ / // __ \ / __// ___// // __ \ / ___// // ___// ___/
      |  *   / // / / / / /(__  )/_____// // / / // /_ / /   / // / / /(__  )/ // /__ (__  )
      |  *  /_//_/ /_/ /_//____/       /_//_/ /_/ \__//_/   /_//_/ /_//____//_/ \___//____/
      |  *
      |  *  Copyright (C) 2017 Ivaylo Toskov (itoskov@ethz.ch)
      |  *                     Alen Stojanov (astojanov@inf.ethz.ch)
      |  *
      |  *  Licensed under the Apache License, Version 2.0 (the "License");
      |  *  you may not use this file except in compliance with the License.
      |  *  You may obtain a copy of the License at
      |  *
      |  *  http://www.apache.org/licenses/LICENSE-2.0
      |  *
      |  *  Unless required by applicable law or agreed to in writing, software
      |  *  distributed under the License is distributed on an "AS IS" BASIS,
      |  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      |  *  See the License for the specific language governing permissions and
      |  *  limitations under the License.
      |  */
    """.stripMargin
  }

}


text:
<?php namespace Exchange\EWSType; use Exchange\EWSType;
/**
 * Contains EWSType_ContainsExpressionType.
 */

/**
 * Represents a search expression that determines whether a given property
 * contains the supplied constant string value.
 *
 * @package php-ews\Types
 */
class EWSType_ContainsExpressionType extends EWSType
{
    /**
     * Identifies a constant value in a restriction.
     *
     * @since Exchange 2007
     *
     * @var EWSType_ConstantValueType
     */
    public $Constant;

    /**
     * Determines whether the search ignores cases and spaces.
     *
     * @since Exchange 2007
     *
     * @var EWSType_ContainmentComparisonType
     */
    public $ContainmentComparison;

    /**
     * Identifies the boundaries of a search.
     *
     * @since Exchange 2007
     *
     * @var EWSType_ContainmentModeType
     */
    public $ContainmentMode;

    /**
     * Identifies MAPI properties.
     *
     * @since Exchange 2007
     *
     * @var EWSType_PathToExtendedFieldType
     */
    public $ExtendedFieldURI;

    /**
     * Identifies frequently referenced properties by URI.
     *
     * @since Exchange 2007
     *
     * @var EWSType_PathToUnindexedFieldType
     */
    public $FieldURI;

    /**
     * Identifies individual members of a dictionary.
     *
     * @since Exchange 2007
     *
     * @var EWSType_PathToIndexedFieldType
     */
    public $IndexedFieldURI;
}

redpajama_set_name: RedPajamaGithub


text:
package com.svbio.workflow.base;

import akka.dispatch.ExecutionContexts;
import dagger.Module;
import dagger.Provides;
import scala.concurrent.ExecutionContext;
import scala.concurrent.ExecutionContextExecutor;

import javax.inject.Singleton;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Dagger module that provides an {@link ExecutionContextExecutor}.
 */
@Module
public final class ExecutionContextModule {
    @Override
    public String toString() {
        return String.format("Dagger module '%s'", getClass().getSimpleName());
    }

    @Provides
    @Singleton
    static ExecutionContextExecutor provideShortLivedExecutor(LifecycleManager lifecycleManager) {
        final ExecutorService executorService = Executors.newCachedThreadPool();
        lifecycleManager.addLifecyclePhaseListener(
            new LifecyclePhaseListener(ScheduledExecutorService.class.getSimpleName(), LifecyclePhase.STARTED) {
                @Override
                protected void onStop() {
                    executorService.shutdownNow();
                }
            }
        );
        return ExecutionContexts.fromExecutorService(executorService);
    }

    @Provides
    static Executor getExecutor(ExecutionContextExecutor executionContextExecutor) {
        return executionContextExecutor;
    }

    @Provides
    static ExecutionContext getExecutionContext(ExecutionContextExecutor executionContextExecutor) {
        return executionContextExecutor;
    }
}


text:
//AUTOGENERATED, DO NOTMODIFY.
//Do not edit this file directly.

#pragma warning disable 1591
// ReSharper disable CheckNamespace
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace RethinkDb.Driver.Model {

    [JsonConverter(typeof(StringEnumConverter))]
    public enum Conflict {
        error,
        replace,
        update,
    }

}


text:
<?php

class WPB2D_Config
{
    const MAX_HISTORY_ITEMS = 20;

    private
        $db,
        $options
        ;

    public function __construct()
    {
        $this->db = WPB2D_Factory::db();
    }

    public static function get_backup_dir()
    {
        return str_replace('/', DIRECTORY_SEPARATOR, WP_CONTENT_DIR . '/backups');
    }

    public function set_option($name, $value)
    {
        //Short circut if not changed
        if ($this->get_option($name) === $value) {
            return $this;
        }

        $exists = $this->db->get_var(
            $this->db->prepare("SELECT * FROM {$this->db->prefix}wpb2d_options WHERE name = %s", $name)
        );

        if (is_null($exists)) {
            $this->db->insert($this->db->prefix . "wpb2d_options", array(
                'name' => $name,
                'value' => $value,
            ));
        } else {
            $this->db->update(
                $this->db->prefix . 'wpb2d_options',
                array('value' => $value),
                array('name' => $name)
            );
        }

        $this->options[$name] = $value;

        return $this;
    }

    public function get_option($name, $no_cache = false)
    {
        if (!isset($this->options[$name]) || $no_cache) {
            $this->options[$name] = $this->db->get_var(
                $this->db->prepare("SELECT value FROM {$this->db->prefix}wpb2d_options WHERE name = %s", $name)
            );
        }

        return $this->options[$name];
    }

    public static function set_time_limit()
    {
        @set_time_limit(0);
    }

    public static function set_memory_limit()
    {
        @ini_set('memory_limit', WP_MAX_MEMORY_LIMIT);
    }

    public function is_scheduled()
    {
        return wp_get_schedule('execute_instant_drobox_backup') !== false;
    }

    public function set_schedule($day, $time, $frequency)
    {
        $blog_time = strtotime(date('Y-m-d H', strtotime(current_time('mysql'))) . ':00:00');

        //Grab the date in the blogs timezone
        $date = date('Y-m-d', $blog_time);

        //Check if we need to schedule the backup in the future
        $time_arr = explode(':', $time);
        $current_day = date('D', $blog_time);
        if ($day && ($current_day != $day)) {
            $date = date('Y-m-d', strtotime("next $day"));
        } elseif ((int) $time_arr[0] <= (int) date('H', $blog_time)) {
            if ($day) {
                $date = date('Y-m-d', strtotime("+7 days", $blog_time));
            } else {
                $date = date('Y-m-d', strtotime("+1 day", $blog_time));
            }
        }

        $timestamp = wp_next_scheduled('execute_periodic_drobox_backup');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'execute_periodic_drobox_backup');
        }

        //This will be in the blogs timezone
        $scheduled_time = strtotime($date . ' ' . $time);

        //Convert the selected time to that of the server
        $server_time = strtotime(date('Y-m-d H') . ':00:00') + ($scheduled_time - $blog_time);

        wp_schedule_event($server_time, $frequency, 'execute_periodic_drobox_backup');

        return $this;
    }

    public function get_schedule()
    {
        $time = wp_next_scheduled('execute_periodic_drobox_backup');
        $frequency = wp_get_schedule('execute_periodic_drobox_backup');
        $schedule = null;

        if ($time && $frequency) {
            //Convert the time to the blogs timezone
            $blog_time = strtotime(date('Y-m-d H', strtotime(current_time('mysql'))) . ':00:00');
            $blog_time += $time - strtotime(date('Y-m-d H') . ':00:00');
            $schedule = array($blog_time, $frequency);
        }

        return $schedule;
    }

    public function clear_history()
    {
        $this->set_option('history', null);
    }

    public function get_history()
    {
        $history = $this->get_option('history');
        if (!$history){
            return array();
        }

        return explode(',', $history);
    }

    public function get_dropbox_path($source, $file, $root = false)
    {
        $dropbox_location = null;
        if ($this->get_option('store_in_subfolder')){
            $dropbox_location = $this->get_option('dropbox_location');
        }

        if ($root){
            return $dropbox_location;
        }

        $source = rtrim($source, DIRECTORY_SEPARATOR);

        return ltrim(dirname(str_replace($source, $dropbox_location, $file)), DIRECTORY_SEPARATOR);
    }

    public function log_finished_time()
    {
        $history = $this->get_history();
        $history[] = time();

        if (count($history) > self::MAX_HISTORY_ITEMS) {
            array_shift($history);
        }

        $this->set_option('history', implode(',', $history));

        return $this;
    }

    public function complete()
    {
        wp_clear_scheduled_hook('monitor_dropbox_backup_hook');
        wp_clear_scheduled_hook('run_dropbox_backup_hook');
        wp_clear_scheduled_hook('execute_instant_drobox_backup');

        $processed = new WPB2D_Processed_Files();
        $processed->truncate();

        $processed = new WPB2D_Processed_DBTables();
        $processed->truncate();

        $this->set_option('in_progress', false);
        $this->set_option('is_running', false);
        $this->set_option('last_backup_time', time());

        return $this;
    }

    public function die_if_stopped()
    {
        $in_progress = $this->db->get_var("SELECT value FROM {$this->db->prefix}wpb2d_options WHERE name = 'in_progress'");
        if (!$in_progress) {
            $msg = __('Backup stopped by user.', 'wpbtd');
            WPB2D_Factory::get('logger')->log($msg);
            die($msg);
        }
    }
}


text:
import {NgModule} from '@angular/core';
import {Route, RouterModule} from '@angular/router';
import {DEFAULT_ACTIONBAR} from '@common/components/actionbars/routing';
import {BREADCRUMBS} from '../../../index.messages';

import {CLUSTER_ROUTE} from '../routing';

import {ClusterRoleBindingDetailComponent} from './detail/component';
import {ClusterRoleBindingListComponent} from './list/component';

const CLUSTERROLEBINDING_LIST_ROUTE: Route = {
  path: '',
  component: ClusterRoleBindingListComponent,
  data: {
    breadcrumb: BREADCRUMBS.ClusterRoleBindings,
    parent: CLUSTER_ROUTE,
  },
};

const CLUSTERROLEBINDING_DETAIL_ROUTE: Route = {
  path: ':resourceName',
  component: ClusterRoleBindingDetailComponent,
  data: {
    breadcrumb: '{{ resourceName }}',
    parent: CLUSTERROLEBINDING_LIST_ROUTE,
  },
};

@NgModule({
  imports: [RouterModule.forChild([CLUSTERROLEBINDING_LIST_ROUTE, CLUSTERROLEBINDING_DETAIL_ROUTE, DEFAULT_ACTIONBAR])],
  exports: [RouterModule],
})
export class ClusterRoleBindingRoutingModule {}


text:
import { defineMessages } from 'react-intl'

export default defineMessages({
  bookmarkFilter: 'ブックマークフィルタ',
})


text:
package org.gwtbootstrap3.demo.client.application.css.validation;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;

import org.gwtbootstrap3.client.ui.Form;
import org.gwtbootstrap3.client.ui.PanelBody;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.form.error.BasicEditorError;
import org.gwtbootstrap3.extras.toggleswitch.client.ui.ToggleSwitch;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.ViewImpl;

/**
 * @author Steven Jardine
 */
public class FormsWithValidationView extends ViewImpl implements FormsWithValidationPresenter.MyView {

    interface Binder extends UiBinder<Widget, FormsWithValidationView> {
    }

    interface CredentialDriver extends SimpleBeanEditorDriver<Credentials, CredentialsEditor> {
    }

    private static final CredentialDriver DRIVER = GWT.create(CredentialDriver.class);

    @Ignore
    @UiField
    protected TextBox allowBlankTextBox;

    @Ignore
    @UiField
    protected PanelBody body;

    @Ignore
    @UiField
    protected Form form;

    @Ignore
    @UiField
    protected DivElement result;

    @Ignore
    @UiField
    protected ToggleSwitch submitOnEnterToggle;

    @Ignore
    @UiField
    protected ToggleSwitch validateOnBlurToggle;

    @Ignore
    @UiField
    protected TextBox yesNoTextBox;

    @Inject
    FormsWithValidationView(final Binder uiBinder, CredentialsEditor editor) {
        initWidget(uiBinder.createAndBindUi(this));
        body.add(editor);
        DRIVER.initialize(editor);
        form.setSubmitOnEnter(true);
        submitOnEnterToggle.addValueChangeHandler(new ValueChangeHandler<Boolean>() {

            @Override
            public void onValueChange(ValueChangeEvent<Boolean> event) {
                boolean on = event.getValue();
                form.setSubmitOnEnter(on);
            }
        });
        validateOnBlurToggle.addValueChangeHandler(new ValueChangeHandler<Boolean>() {

            @Override
            public void onValueChange(ValueChangeEvent<Boolean> event) {
                boolean on = event.getValue();
                allowBlankTextBox.setValidateOnBlur(on);
                yesNoTextBox.setValidateOnBlur(on);
            }
        });

        yesNoTextBox.addValidator(new org.gwtbootstrap3.client.ui.form.validator.Validator<String>() {

            @Override
            public int getPriority() {
                return Priority.MEDIUM;
            }

            @Override
            public List<EditorError> validate(Editor<String> editor, String value) {
                List<EditorError> result = new ArrayList<EditorError>();
                String valueStr = value == null ? "" : value;
                if (!("Yes".equalsIgnoreCase(valueStr) || "No".equalsIgnoreCase(valueStr))) {
                    result.add(new BasicEditorError(yesNoTextBox, value, "Must be \"Yes\" or \"No\""));
                }
                return result;
            }
        });
    }

    /** {@inheritDoc} */
    @Override
    protected void onAttach() {
        super.onAttach();
        DRIVER.edit(new Credentials());
    }

    @UiHandler("formResetButton")
    public void onFormResetClick(ClickEvent event) {
        form.reset();
    }

    @UiHandler("formValidateButton")
    public void onFormValidateClick(ClickEvent event) {
        form.validate();
    }

    @UiHandler("loginButton")
    public void onLoginClick(ClickEvent event) {
        Credentials creds = DRIVER.flush();

        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<Credentials>> violations = validator.validate(creds, Default.class);
        if (violations.size() > 0) {
            DRIVER.setConstraintViolations(new ArrayList<ConstraintViolation<?>>(violations));
        }

        if (!DRIVER.hasErrors()) {
            result.setInnerText(creds.toString());
        }
    }

    @UiHandler("resetButton")
    public void onResetClick(ClickEvent event) {
        DRIVER.edit(new Credentials());
        result.removeAllChildren();
    }

}


text:
import codecs
import os

import abstractRenderer
import books

#
#   Renderer for Accordance - accordancebible.com
#

IN = 1
OUT = 2
JUSTOUT = 3

class Renderer(abstractRenderer.AbstractRenderer):

    def __init__(self, inputDir, outputDir, outputName, config):
        self.identity = 'renderer for accordance bible software'
        self.outputDescription = os.path.join(outputDir, outputName + '.accordance.txt')
        abstractRenderer.AbstractRenderer.__init__(self, inputDir, outputDir, outputName, config)
        # Unset
        self.f = None  # output file stream
        # IO
        self.outputFilename = os.path.join(outputDir, outputName + '.accordance.txt')
        self.inputDir = inputDir
        # Flags
        self.cb = ''    # Current Book
        self.cc = '001'    # Current Chapter
        self.cv = '001'    # Currrent Verse
        self.infootnote = False
        self.verseHadContent = True
        self.ndStatus = OUT
        self.beforeFirstVerse = True
        self.needsParagraph = True
        self.inEmphasis = False

    def render(self):
        self.f = open(self.outputFilename, 'w', encoding='macroman') # 'utf_8_sig macroman
        self.loadUSFM(self.inputDir)
        self.run()
        self.f.close()

    #   SUPPORT

    def escape(self, s):
        if self.ndStatus == IN: return s.strip()
        if self.ndStatus == JUSTOUT: self.ndStatus = OUT ; return ' ' + s if s[0].isalnum() else s
        return '' if self.infootnote else s

    def write(self, s):
        if not self.beforeFirstVerse:
            self.f.write(s)

    #   TOKENS

    def render_id(self, token):
        self.cb = books.bookKeyForIdValue(token.value)
    def render_c(self, token):
        self.cc = token.value.zfill(3)
    def render_v(self, token):
        self.cv = token.value.zfill(3)
        if not self.verseHadContent: self.write(' ~')
        self.verseHadContent = False
        if self.cv.isdigit():
            if self.beforeFirstVerse:
                # No \n on first line
                self.beforeFirstVerse = False
            else:
                self.f.write('\n')
            self.f.write(books.accordanceNameForBookKey(self.cb) + ' ' + str(int(self.cc)) + ':' + str(int(self.cv.split('-')[0])) + ' ') # str(int(self.cb))
        else:
            # This shouldn't happen in release, but will happen in development
            # eg \v 23a
            self.logger.warning('Ignoring ' + books.accordanceNameForBookKey(self.cb) + ' ' + str(int(self.cc)) + ':' + self.cv)
        if self.needsParagraph:
            self.needsParagraph = False
            self.write(' ¶ ')
    def render_text(self, token):
        self.verseHadContent = True
        if self.inEmphasis:
            self.write('')
        self.write(self.escape(token.value + ' '))
        if self.inEmphasis:
            self.write('')
    def render_f_s(self, token):     self.write('[')
    def render_f_e(self, token):     self.write(']')
    def render_p(self, token):       self.needsParagraph = True
    def render_pi(self, token):      self.needsParagraph = True
    def render_m(self, token):       self.needsParagraph = True
    def render_nb(self, token):      self.needsParagraph = True
    def render_nd_s(self,token):     self.ndStatus = IN; self.write('<c>')
    def render_nd_e(self,token):     self.ndStatus = JUSTOUT; self.write('</c>')
    def render_q1(self, token):      self.write('
\t')
    def render_q2(self, token):      self.write('
\t\t')
    def render_q3(self, token):      self.write('
\t\t\t')
    def render_b(self, token):       self.write('
')
    def render_qs_s(self, token):    self.inEmphasis = True
    def render_qs_e(self, token):    self.inEmphasis = False
    def render_em_s(self, token):    self.inEmphasis = True
    def render_em_e(self, token):    self.inEmphasis = False

    def render_d(self, token):
        """ Accordance """
        # Accordance requries Psalms to have :0 verse
        if books.accordanceNameForBookKey(self.cb) == 'Psa':
            self.f.write(                         '\n' +
                                                  books.accordanceNameForBookKey(self.cb) +
                                                    ' ' +
                                                  str(int(self.cc)) +
                                            ':0 ¶ ' +
                                                  token.value +
                                                ' ')

    # Ignored
    def render_h(self, token):      pass
    def render_mt(self, token):     pass
    def render_mt2(self, token):    pass
    def render_ms(self, token):     pass
    def render_ms2(self, token):    pass
    def render_s(self, token):      pass
    def render_s2(self, token):     pass
    def render_wj_s(self, token):   pass
    def render_wj_e(self, token):   pass


text:
package com.spotify.folsom.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.nio.ByteBuffer;
import java.util.List;

public class MemcacheEncoder extends MessageToMessageEncoder<Request<?>> {

  public static final int MAX_KEY_LEN = 250;
  public static final int MAX_MULTIGET_SIZE = 255;
  public static final int MAX_ASCII_REQUEST = 100 + MAX_MULTIGET_SIZE * (MAX_KEY_LEN + 1);

  public static final int MAX_BINARY_REQUEST = MAX_MULTIGET_SIZE * (MAX_KEY_LEN + 32);
  public static final int MAX_REQUEST = Math.max(MAX_ASCII_REQUEST, MAX_BINARY_REQUEST);

  // Big enough to encode the largest possible request
  private final ByteBuffer workingBuffer = ByteBuffer.allocate(MAX_REQUEST);

  @Override
  public void encode(final ChannelHandlerContext ctx, final Request<?> request,
                     final List<Object> out)
      throws Exception {
    workingBuffer.clear();
    final ByteBuf message = request.writeRequest(ctx.alloc(), workingBuffer);
    out.add(message);
  }

}


text:
<?php
/**
 * Define the app routes in this file. This is done via the Router::register()
 * method, or methods matching the four major HTTP methods (get, post, put and
 * delete). See below for a full description of the routing in groundwork.
 */

// The app home
$router->register('', 'HomeResource');

// A demo route showing how a route can be registered with an anonymous
// function - safe to delete.
$router->register('demo/:id?/:field?', function($request, $response) {
    $response->send(200, $request->routeParams());
});

// A demo showing how a route can be registered with a HTTP method based
// shortcut - safe to delete.
$router->get('users', function($request, $response) {
    $response->send(200);
});
$router->post('users', function($request, $response) {
    $response->send(200);
});

/**
 * The first param of the route registration methods is the route as a string.
 * Some valid route formats are as follows:
 *
 * '' to /$basedir/
 * 'articles' maps to /$basedir/articles
 * 'articles/:id' maps to /$basedir/articles/x
 * 'articles/:id? maps to /$basedir/articles/x (where x is optional)
 * 'articles/:id/:field to /$basedir/articles/x/y
 *
 * Where $basedir is the web root, defined in app/config.php.
 *
 * The second param can be a string or an anonymous function. Its job is to
 * dictate what happens when a route is encountered.
 *
 * As a string, it should equal the name of a class extending from
 * \Groundwork\Classes\Resource that exists in app/Resources, in the
 * \Resources namespace. This second param is not case sensitive, although
 * the class name itself should have a leading uppercase, as should the file
 * name itself.
 *
 * In this mode, the router will map directly to Resource::output(), which
 * factors in the HTTP request method to determine what method to execute on
 * the child Resource class.
 *
 * Here's an example:
 *
 * $router->register('articles/:id', 'articles');
 *
 * This will map the route /$basedir/articles/x to the resource class Articles,
 * with the HTTP request method determining which method of Articles is
 * accessed to generate the output, e.g. http_GET() for GET, http_POST() for
 * POST, and so on. For a working example, see the Home resource that is
 * included with the framework (app/Resources/Home.php). This is a bare
 * minimal Resource child class to respond to GET/POST/PUT/DELETE requests.
 *
 * As an anonymous function/closure, the second param becomes the sole source
 * of logic for the route, regardless of the HTTP request method. This means
 * defining an anonymous function is probably only best for quick and simple
 * responses.
 *
 * When defining your anonymous function, you are given a few params -
 * $request (an instance of \Groundwork\Classes\Request) and $response (an
 * instance of \Groundwork\Classes\Response), in that order. In other words,
 * you have the same functionality as you would have when writing a full
 * Resource class to handle requests and responses.
 *
 * Here is an example of an anonymous function route:
 *
 * $router->get('articles/:id?', function($request, $response) {
 *      $response->send(200, $request->routeParams());
 * });
 *
 * Navigating to /$basedir/articles/1 with that route should output {"id":"1"}
 * to the browser/console.
 */


text:
namespace Sharp6800.Debugger.MemoryMaps
{
    public enum MapEventType
    {
        Add,
        Remove,
        Update,
        Clear
    }
}


text:
// PieceStructuresGen.cpp

// Declares the cPieceStructuresGen class representing the PieceStructures finisher generator

#include "Globals.h"
#include "PieceStructuresGen.h"
#include "PrefabStructure.h"
#include "PieceGeneratorBFSTree.h"
#include "IniFile.h"
#include "../Stopwatch.h"

class cPieceStructuresGen::cGen:
	public cGridStructGen
{
	typedef cGridStructGen Super;

public:
	cGen(int a_Seed, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen, int a_SeaLevel, const AString & a_Name):
		Super(a_Seed),
		m_BiomeGen(a_BiomeGen),
		m_HeightGen(a_HeightGen),
		m_SeaLevel(a_SeaLevel),
		m_Name(a_Name),
		m_MaxDepth(5)
	{
	}

	/** Loads the piecepool from a file.
	Returns true on success, logs warning and returns false on failure. */
	bool LoadFromFile(const AString & a_FileName)
	{
		// Load the piecepool from the file, log any warnings:
		if (!m_PiecePool.LoadFromFile(a_FileName, true))
		{
			return false;
		}
		if (NoCaseCompare(m_PiecePool.GetIntendedUse(), "PieceStructures") != 0)
		{
			LOGWARNING("PieceStructures generator: File %s is intended for use in \"%s\", rather than piece structures. Loading the file, but the generator may behave unexpectedly.",
				a_FileName.c_str(), m_PiecePool.GetIntendedUse().c_str()
			);
		}
		m_PiecePool.AssignGens(m_Seed, m_BiomeGen, m_HeightGen, m_SeaLevel);

		// Apply generator params from the piecepool (in the metadata) into the generator:
		auto & generatorParams = m_PiecePool.GetAllMetadata();
		SetGeneratorParams(generatorParams);
		m_MaxDepth = GetStringMapInteger<int>(generatorParams, "MaxDepth", m_MaxDepth);

		return true;
	}

	// cGridStructGen overrides:
	virtual cStructurePtr CreateStructure(int a_GridX, int a_GridZ, int a_OriginX, int a_OriginZ) override
	{
		cStopwatch sw(Printf("CreateStructure for %s at <%d, %d>", m_Name.c_str(), a_GridX, a_GridZ));
		cPlacedPieces outPieces;
		cPieceGeneratorBFSTree pg(m_PiecePool, m_Seed);
		pg.PlacePieces(a_OriginX, a_OriginZ, m_MaxDepth, outPieces);
		return std::make_shared<cPrefabStructure>(a_GridX, a_GridZ, a_OriginX, a_OriginZ, std::move(outPieces), m_HeightGen);
	}

protected:

	/** The type used for storing a connection from one piece to another, while building the piece tree. */
	struct cConnection
	{
		cPiece * m_Piece;                  // The piece being connected
		cPiece::cConnector m_Connector;    // The piece's connector being used (relative non-rotated coords)
		int m_NumCCWRotations;             // Number of rotations necessary to match the two connectors
		int m_Weight;                      // Relative chance that this connection will be chosen

		cConnection(cPiece & a_Piece, cPiece::cConnector & a_Connector, int a_NumCCWRotations, int a_Weight);
	};
	typedef std::vector<cConnection> cConnections;

	/** The type used for storing a pool of connectors that will be attempted to expand by another piece. */
	struct cFreeConnector
	{
		cPlacedPiece * m_Piece;
		cPiece::cConnector m_Connector;

		cFreeConnector(cPlacedPiece * a_Piece, const cPiece::cConnector & a_Connector);
	};
	typedef std::vector<cFreeConnector> cFreeConnectors;

	/** The underlying biome generator that defines whether the structure is created or not */
	cBiomeGenPtr m_BiomeGen;

	/** The underlying height generator, used to position the prefabs crossing chunk borders if they are set to FitGround. */
	cTerrainHeightGenPtr m_HeightGen;

	/** The world's sea level, if available. Used for some cVerticalStrategy descendants. */
	int m_SeaLevel;

	/** The name that is used for reporting. */
	AString m_Name;

	/** All available prefabs. */
	cPrefabPiecePool m_PiecePool;

	/** Maximum depth of the generated piece tree. */
	int m_MaxDepth;
};

////////////////////////////////////////////////////////////////////////////////
// cPieceStructuresGen:

cPieceStructuresGen::cPieceStructuresGen(int a_Seed):
	m_Seed(a_Seed)
{
}

bool cPieceStructuresGen::Initialize(const AString & a_Prefabs, int a_SeaLevel, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen)
{
	// Load each piecepool:
	auto structures = StringSplitAndTrim(a_Prefabs, "|");
	for (const auto & s: structures)
	{
		auto fileName = Printf("Prefabs%cPieceStructures%c%s.cubeset", cFile::PathSeparator, cFile::PathSeparator, s.c_str());
		if (!cFile::IsFile(fileName))
		{
			fileName.append(".gz");
			if (!cFile::IsFile(fileName))
			{
				LOGWARNING("Cannot load PieceStructures cubeset file %s", fileName.c_str());
				continue;
			}
		}
		auto gen = std::make_shared<cGen>(m_Seed, a_BiomeGen, a_HeightGen, a_SeaLevel, s);
		if (gen->LoadFromFile(fileName))
		{
			m_Gens.push_back(gen);
		}
	}

	// Report a warning if no generators available:
	if (m_Gens.empty())
	{
		LOGWARNING("The PieceStructures generator was asked to generate \"%s\", but none of the prefabs are valid.", a_Prefabs.c_str());
		return false;
	}
	return true;
}

void cPieceStructuresGen::GenFinish(cChunkDesc & a_Chunk)
{
	for (auto & gen: m_Gens)
	{
		gen->GenFinish(a_Chunk);
	}
}


text:
class CreateTrucks < ActiveRecord::Migration[5.0]
  def change
    create_table :trucks do |t|
      t.string :name
      t.integer :trips_per_day
      t.integer :max_weight
      t.integer :max_volume
      t.references :user, foreign_key: true

      t.timestamps
    end

    rename_column :trucks, :user_id, :driver_id
  end
end


text:
/*************************************************************************/
/*  vector3.cpp                                                          */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "vector3.h"

#include "core/math/basis.h"

void Vector3::rotate(const Vector3 &p_axis, const real_t p_phi) {
	*this = Basis(p_axis, p_phi).xform(*this);
}

Vector3 Vector3::rotated(const Vector3 &p_axis, const real_t p_phi) const {
	Vector3 r = *this;
	r.rotate(p_axis, p_phi);
	return r;
}

void Vector3::set_axis(const int p_axis, const real_t p_value) {
	ERR_FAIL_INDEX(p_axis, 3);
	coord[p_axis] = p_value;
}

real_t Vector3::get_axis(const int p_axis) const {
	ERR_FAIL_INDEX_V(p_axis, 3, 0);
	return operator[](p_axis);
}

Vector3 Vector3::clamp(const Vector3 &p_min, const Vector3 &p_max) const {
	return Vector3(
			CLAMP(x, p_min.x, p_max.x),
			CLAMP(y, p_min.y, p_max.y),
			CLAMP(z, p_min.z, p_max.z));
}

void Vector3::snap(const Vector3 p_step) {
	x = Math::snapped(x, p_step.x);
	y = Math::snapped(y, p_step.y);
	z = Math::snapped(z, p_step.z);
}

Vector3 Vector3::snapped(const Vector3 p_step) const {
	Vector3 v = *this;
	v.snap(p_step);
	return v;
}

Vector3 Vector3::limit_length(const real_t p_len) const {
	const real_t l = length();
	Vector3 v = *this;
	if (l > 0 && p_len < l) {
		v /= l;
		v *= p_len;
	}

	return v;
}

Vector3 Vector3::cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, const real_t p_weight) const {
	Vector3 p0 = p_pre_a;
	Vector3 p1 = *this;
	Vector3 p2 = p_b;
	Vector3 p3 = p_post_b;

	real_t t = p_weight;
	real_t t2 = t * t;
	real_t t3 = t2 * t;

	Vector3 out;
	out = 0.5 *
			((p1 * 2.0) +
					(-p0 + p2) * t +
					(2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 +
					(-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3);
	return out;
}

Vector3 Vector3::move_toward(const Vector3 &p_to, const real_t p_delta) const {
	Vector3 v = *this;
	Vector3 vd = p_to - v;
	real_t len = vd.length();
	return len <= p_delta || len < CMP_EPSILON ? p_to : v + vd / len * p_delta;
}

Basis Vector3::outer(const Vector3 &p_with) const {
	Vector3 row0(x * p_with.x, x * p_with.y, x * p_with.z);
	Vector3 row1(y * p_with.x, y * p_with.y, y * p_with.z);
	Vector3 row2(z * p_with.x, z * p_with.y, z * p_with.z);

	return Basis(row0, row1, row2);
}

bool Vector3::is_equal_approx(const Vector3 &p_v) const {
	return Math::is_equal_approx(x, p_v.x) && Math::is_equal_approx(y, p_v.y) && Math::is_equal_approx(z, p_v.z);
}

Vector3::operator String() const {
	return "(" + String::num_real(x, false) + ", " + String::num_real(y, false) + ", " + String::num_real(z, false) + ")";
}


text:
var assert = require("assert");

function FiberPool(targetFiberCount) {
  assert.ok(this instanceof FiberPool);
  assert.strictEqual(typeof targetFiberCount, "number");

  var fiberStack = [];

  function makeNewFiber(Fiber) {
    // Just in case someone tampers with Fiber.yield, don't let that interfere
    // with our processing of the callback queue.
    var originalYield = Fiber.yield;

    var fiber = new Fiber(function () {
      while (true) {
        // Call Fiber.yield() to await further instructions.
        var entry = originalYield.call(Fiber);

        // Ensure this Fiber is no longer in the pool once it begins to
        // execute an entry.
        assert.strictEqual(fiberStack.indexOf(fiber), -1);

        if (entry.dynamics) {
          // Restore the dynamic environment of this fiber as if
          // entry.callback had been wrapped by Meteor.bindEnvironment.
          Object.keys(entry.dynamics).forEach(function (key) {
            fiber[key] = entry.dynamics[key];
          });
        }

        try {
          var result = entry.callback.apply(
            entry.context || null,
            entry.args || []
          );

          setImmediate(entry.resolve.bind(entry, result));

        } catch (error) {
          entry.reject(error);
        }

        // Remove all own properties of the fiber before returning it to
        // the pool.
        Object.keys(fiber).forEach(function (key) {
          delete fiber[key];
        });

        if (fiberStack.length < targetFiberCount) {
          fiberStack.push(fiber);
        } else {
          // If the pool has already reached the target maximum number of
          // Fibers, don't bother recycling this Fiber.
          break;
        }
      }
    });

    // Run the new Fiber up to the first yield point, so that it will be
    // ready to receive entries.
    fiber.run();

    return fiber;
  }

  // Run the entry.callback function in a Fiber either taken from the pool
  // or created anew if the pool is empty. This method returns a Promise
  // for the eventual result of the entry.callback function.
  this.run = function (entry, Promise) {
    assert.strictEqual(typeof entry, "object");
    assert.strictEqual(typeof entry.callback, "function");

    if (typeof Promise.Fiber !== "function") {
      return new Promise(function (resolve) {
        resolve(entry.callback.apply(
          entry.context || null,
          entry.args
        ));
      });
    }

    var fiber = fiberStack.pop() || makeNewFiber(Promise.Fiber);

    var promise = new Promise(function (resolve, reject) {
      entry.resolve = resolve;
      entry.reject = reject;
    });

    fiber.run(entry);

    return promise;
  };

  // Limit the maximum number of idle Fibers that may be kept in the
  // pool. Note that the run method will never refuse to create a new
  // Fiber if the pool is empty; it's just that excess Fibers might be
  // thrown away upon completion, if the pool is full.
  this.setTargetFiberCount = function (limit) {
    assert.strictEqual(typeof limit, "number");

    targetFiberCount = Math.max(limit, 0);

    if (targetFiberCount < fiberStack.length) {
      // If the requested target count is less than the current length of
      // the stack, truncate the stack and terminate any surplus Fibers.
      fiberStack.splice(targetFiberCount).forEach(function (fiber) {
        fiber.reset();
      });
    }

    return this;
  };
}

// Call pool.drain() to terminate all Fibers waiting in the pool and
// signal to any outstanding Fibers that they should exit upon completion,
// instead of reinserting themselves into the pool.
FiberPool.prototype.drain = function () {
  return this.setTargetFiberCount(0);
};

exports.makePool = function (targetFiberCount) {
  return new FiberPool(targetFiberCount || 20);
};


text:
package arn

import "github.com/aerogo/nano"

// Purchase represents an item purchase by a user.
type Purchase struct {
	UserID   UserID `json:"userId"`
	ItemID   ID     `json:"itemId"`
	Quantity int    `json:"quantity"`
	Price    int    `json:"price"`
	Currency string `json:"currency"`
	Date     string `json:"date"`

	hasID
}

// Item returns the item the user bought.
func (purchase *Purchase) Item() *ShopItem {
	item, _ := GetShopItem(purchase.ItemID)
	return item
}

// User returns the user who made the purchase.
func (purchase *Purchase) User() *User {
	user, _ := GetUser(purchase.UserID)
	return user
}

// NewPurchase creates a new Purchase object with a generated ID.
func NewPurchase(userID UserID, itemID string, quantity int, price int, currency string) *Purchase {
	return &Purchase{
		hasID: hasID{
			ID: GenerateID("Purchase"),
		},
		UserID:   userID,
		ItemID:   itemID,
		Quantity: quantity,
		Price:    price,
		Currency: currency,
		Date:     DateTimeUTC(),
	}
}

// StreamPurchases returns a stream of all purchases.
func StreamPurchases() <-chan *Purchase {
	channel := make(chan *Purchase, nano.ChannelBufferSize)

	go func() {
		for obj := range DB.All("Purchase") {
			channel <- obj.(*Purchase)
		}

		close(channel)
	}()

	return channel
}

// AllPurchases returns a slice of all anime.
func AllPurchases() ([]*Purchase, error) {
	all := make([]*Purchase, 0, DB.Collection("Purchase").Count())

	for obj := range StreamPurchases() {
		all = append(all, obj)
	}

	return all, nil
}

// FilterPurchases filters all purchases by a custom function.
func FilterPurchases(filter func(*Purchase) bool) ([]*Purchase, error) {
	var filtered []*Purchase

	for obj := range StreamPurchases() {
		if filter(obj) {
			filtered = append(filtered, obj)
		}
	}

	return filtered, nil
}


text:
using namespace llvm;
using namespace llvm::xray;
using llvm::yaml::Input;

namespace {
using XRayRecordStorage =
    std::aligned_storage<sizeof(XRayRecord), alignof(XRayRecord)>::type;

// Populates the FileHeader reference by reading the first 32 bytes of the file.
Error readBinaryFormatHeader(StringRef Data, XRayFileHeader &FileHeader) {
  // FIXME: Maybe deduce whether the data is little or big-endian using some
  // magic bytes in the beginning of the file?

  // First 32 bytes of the file will always be the header. We assume a certain
  // format here:
  //
  //   (2)   uint16 : version
  //   (2)   uint16 : type
  //   (4)   uint32 : bitfield
  //   (8)   uint64 : cycle frequency
  //   (16)  -      : padding

  DataExtractor HeaderExtractor(Data, true, 8);
  uint32_t OffsetPtr = 0;
  FileHeader.Version = HeaderExtractor.getU16(&OffsetPtr);
  FileHeader.Type = HeaderExtractor.getU16(&OffsetPtr);
  uint32_t Bitfield = HeaderExtractor.getU32(&OffsetPtr);
  FileHeader.ConstantTSC = Bitfield & 1uL;
  FileHeader.NonstopTSC = Bitfield & 1uL << 1;
  FileHeader.CycleFrequency = HeaderExtractor.getU64(&OffsetPtr);
  std::memcpy(&FileHeader.FreeFormData, Data.bytes_begin() + OffsetPtr, 16);
  if (FileHeader.Version != 1 && FileHeader.Version != 2 &&
      FileHeader.Version != 3)
    return make_error<StringError>(
        Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
        std::make_error_code(std::errc::invalid_argument));
  return Error::success();
}

Error loadNaiveFormatLog(StringRef Data, XRayFileHeader &FileHeader,
                         std::vector<XRayRecord> &Records) {
  if (Data.size() < 32)
    return make_error<StringError>(
        "Not enough bytes for an XRay log.",
        std::make_error_code(std::errc::invalid_argument));

  if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
    return make_error<StringError>(
        "Invalid-sized XRay data.",
        std::make_error_code(std::errc::invalid_argument));

  if (auto E = readBinaryFormatHeader(Data, FileHeader))
    return E;

  // Each record after the header will be 32 bytes, in the following format:
  //
  //   (2)   uint16 : record type
  //   (1)   uint8  : cpu id
  //   (1)   uint8  : type
  //   (4)   sint32 : function id
  //   (8)   uint64 : tsc
  //   (4)   uint32 : thread id
  //   (4)   uint32 : process id
  //   (8)   -      : padding
  for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) {
    DataExtractor RecordExtractor(S, true, 8);
    uint32_t OffsetPtr = 0;
    switch (auto RecordType = RecordExtractor.getU16(&OffsetPtr)) {
    case 0: { // Normal records.
      Records.emplace_back();
      auto &Record = Records.back();
      Record.RecordType = RecordType;
      Record.CPU = RecordExtractor.getU8(&OffsetPtr);
      auto Type = RecordExtractor.getU8(&OffsetPtr);
      switch (Type) {
      case 0:
        Record.Type = RecordTypes::ENTER;
        break;
      case 1:
        Record.Type = RecordTypes::EXIT;
        break;
      case 2:
        Record.Type = RecordTypes::TAIL_EXIT;
        break;
      case 3:
        Record.Type = RecordTypes::ENTER_ARG;
        break;
      default:
        return make_error<StringError>(
            Twine("Unknown record type '") + Twine(int{Type}) + "'",
            std::make_error_code(std::errc::executable_format_error));
      }
      Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
      Record.TSC = RecordExtractor.getU64(&OffsetPtr);
      Record.TId = RecordExtractor.getU32(&OffsetPtr);
      Record.PId = RecordExtractor.getU32(&OffsetPtr);
      break;
    }
    case 1: { // Arg payload record.
      auto &Record = Records.back();
      // Advance two bytes to avoid padding.
      OffsetPtr += 2;
      int32_t FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
      auto TId = RecordExtractor.getU32(&OffsetPtr);
      auto PId = RecordExtractor.getU32(&OffsetPtr);

      // Make a check for versions above 3 for the Pid field
      if (Record.FuncId != FuncId || Record.TId != TId ||
          (FileHeader.Version >= 3 ? Record.PId != PId : false))
        return make_error<StringError>(
            Twine("Corrupted log, found arg payload following non-matching "
                  "function + thread record. Record for function ") +
                Twine(Record.FuncId) + " != " + Twine(FuncId) + "; offset: " +
                Twine(S.data() - Data.data()),
            std::make_error_code(std::errc::executable_format_error));

      auto Arg = RecordExtractor.getU64(&OffsetPtr);
      Record.CallArgs.push_back(Arg);
      break;
    }
    default:
      return make_error<StringError>(
          Twine("Unknown record type == ") + Twine(RecordType),
          std::make_error_code(std::errc::executable_format_error));
    }
  }
  return Error::success();
}

/// When reading from a Flight Data Recorder mode log, metadata records are
/// sparse compared to packed function records, so we must maintain state as we
/// read through the sequence of entries. This allows the reader to denormalize
/// the CPUId and Thread Id onto each Function Record and transform delta
/// encoded TSC values into absolute encodings on each record.
struct FDRState {
  uint16_t CPUId;
  uint16_t ThreadId;
  int32_t ProcessId;
  uint64_t BaseTSC;

  /// Encode some of the state transitions for the FDR log reader as explicit
  /// checks. These are expectations for the next Record in the stream.
  enum class Token {
    NEW_BUFFER_RECORD_OR_EOF,
    WALLCLOCK_RECORD,
    NEW_CPU_ID_RECORD,
    FUNCTION_SEQUENCE,
    SCAN_TO_END_OF_THREAD_BUF,
    CUSTOM_EVENT_DATA,
    CALL_ARGUMENT,
    BUFFER_EXTENTS,
    PID_RECORD,
  };
  Token Expects;

  // Each threads buffer may have trailing garbage to scan over, so we track our
  // progress.
  uint64_t CurrentBufferSize;
  uint64_t CurrentBufferConsumed;
};

const char *fdrStateToTwine(const FDRState::Token &state) {
  switch (state) {
  case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
    return "NEW_BUFFER_RECORD_OR_EOF";
  case FDRState::Token::WALLCLOCK_RECORD:
    return "WALLCLOCK_RECORD";
  case FDRState::Token::NEW_CPU_ID_RECORD:
    return "NEW_CPU_ID_RECORD";
  case FDRState::Token::FUNCTION_SEQUENCE:
    return "FUNCTION_SEQUENCE";
  case FDRState::Token::SCAN_TO_END_OF_THREAD_BUF:
    return "SCAN_TO_END_OF_THREAD_BUF";
  case FDRState::Token::CUSTOM_EVENT_DATA:
    return "CUSTOM_EVENT_DATA";
  case FDRState::Token::CALL_ARGUMENT:
    return "CALL_ARGUMENT";
  case FDRState::Token::BUFFER_EXTENTS:
    return "BUFFER_EXTENTS";
  case FDRState::Token::PID_RECORD:
    return "PID_RECORD";
  }
  return "UNKNOWN";
}

/// State transition when a NewBufferRecord is encountered.
Error processFDRNewBufferRecord(FDRState &State, uint8_t RecordFirstByte,
                                DataExtractor &RecordExtractor) {

  if (State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
    return make_error<StringError>(
        Twine("Malformed log. Read New Buffer record kind out of sequence; "
              "expected: ") +
            fdrStateToTwine(State.Expects),
        std::make_error_code(std::errc::executable_format_error));
  uint32_t OffsetPtr = 1; // 1 byte into record.
  State.ThreadId = RecordExtractor.getU16(&OffsetPtr);
  State.Expects = FDRState::Token::WALLCLOCK_RECORD;
  return Error::success();
}

/// State transition when an EndOfBufferRecord is encountered.
Error processFDREndOfBufferRecord(FDRState &State, uint8_t RecordFirstByte,
                                  DataExtractor &RecordExtractor) {
  if (State.Expects == FDRState::Token::NEW_BUFFER_RECORD_OR_EOF)
    return make_error<StringError>(
        Twine("Malformed log. Received EOB message without current buffer; "
              "expected: ") +
            fdrStateToTwine(State.Expects),
        std::make_error_code(std::errc::executable_format_error));
  State.Expects = FDRState::Token::SCAN_TO_END_OF_THREAD_BUF;
  return Error::success();
}

/// State transition when a NewCPUIdRecord is encountered.
Error processFDRNewCPUIdRecord(FDRState &State, uint8_t RecordFirstByte,
                               DataExtractor &RecordExtractor) {
  if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE &&
      State.Expects != FDRState::Token::NEW_CPU_ID_RECORD)
    return make_error<StringError>(
        Twine("Malformed log. Read NewCPUId record kind out of sequence; "
              "expected: ") +
            fdrStateToTwine(State.Expects),
        std::make_error_code(std::errc::executable_format_error));
  uint32_t OffsetPtr = 1; // Read starting after the first byte.
  State.CPUId = RecordExtractor.getU16(&OffsetPtr);
  State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
  State.Expects = FDRState::Token::FUNCTION_SEQUENCE;
  return Error::success();
}

/// State transition when a TSCWrapRecord (overflow detection) is encountered.
Error processFDRTSCWrapRecord(FDRState &State, uint8_t RecordFirstByte,
                              DataExtractor &RecordExtractor) {
  if (State.Expects != FDRState::Token::FUNCTION_SEQUENCE)
    return make_error<StringError>(
        Twine("Malformed log. Read TSCWrap record kind out of sequence; "
              "expecting: ") +
            fdrStateToTwine(State.Expects),
        std::make_error_code(std::errc::executable_format_error));
  uint32_t OffsetPtr = 1; // Read starting after the first byte.
  State.BaseTSC = RecordExtractor.getU64(&OffsetPtr);
  return Error::success();
}

/// State transition when a WallTimeMarkerRecord is encountered.
Error processFDRWallTimeRecord(FDRState &State, uint8_t RecordFirstByte,
                               DataExtractor &RecordExtractor) {
  if (State.Expects != FDRState::Token::WALLCLOCK_RECORD)
    return make_error<StringError>(
        Twine("Malformed log. Read Wallclock record kind out of sequence; "
              "expecting: ") +
            fdrStateToTwine(State.Expects),
        std::make_error_code(std::errc::executable_format_error));

  // TODO: Someday, reconcile the TSC ticks to wall clock time for presentation
  // purposes. For now, we're ignoring these records.
  State.Expects = FDRState::Token::NEW_CPU_ID_RECORD;
  return Error::success();
}

/// State transition when a PidRecord is encountered.
Error processFDRPidRecord(FDRState &State, uint8_t RecordFirstByte,
                          DataExtractor &RecordExtractor) {

  if (State.Expects != FDRState::Token::PID_RECORD)
    return make_error<StringError>(
        Twine("Malformed log. Read Pid record kind out of sequence; "
              "expected: ") +
            fdrStateToTwine(State.Expects),
        std::make_error_code(std::errc::executable_format_error));

  uint32_t OffsetPtr = 1; // Read starting after the first byte.
  State.ProcessId = RecordExtractor.getU32(&OffsetPtr);
  State.Expects = FDRState::Token::NEW_CPU_ID_RECORD;
  return Error::success();
}

/// State transition when a CustomEventMarker is encountered.
Error processCustomEventMarker(FDRState &State, uint8_t RecordFirstByte,
                               DataExtractor &RecordExtractor,
                               size_t &RecordSize) {
  // We can encounter a CustomEventMarker anywhere in the log, so we can handle
  // it regardless of the expectation. However, we do set the expectation to
  // read a set number of fixed bytes, as described in the metadata.
  uint32_t OffsetPtr = 1; // Read after the first byte.
  uint32_t DataSize = RecordExtractor.getU32(&OffsetPtr);
  uint64_t TSC = RecordExtractor.getU64(&OffsetPtr);

  // FIXME: Actually represent the record through the API. For now we only
  // skip through the data.
  (void)TSC;
  RecordSize = 16 + DataSize;
  return Error::success();
}

/// State transition when an BufferExtents record is encountered.
Error processBufferExtents(FDRState &State, uint8_t RecordFirstByte,
                           DataExtractor &RecordExtractor) {
  if (State.Expects != FDRState::Token::BUFFER_EXTENTS)
    return make_error<StringError>(
        Twine("Malformed log. Buffer Extents unexpected; expected: ") +
            fdrStateToTwine(State.Expects),
        std::make_error_code(std::errc::executable_format_error));
  uint32_t OffsetPtr = 1; // Read after the first byte.
  State.CurrentBufferSize = RecordExtractor.getU64(&OffsetPtr);
  State.Expects = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF;
  return Error::success();
}

/// State transition when a CallArgumentRecord is encountered.
Error processFDRCallArgumentRecord(FDRState &State, uint8_t RecordFirstByte,
                                   DataExtractor &RecordExtractor,
                                   std::vector<XRayRecord> &Records) {
  uint32_t OffsetPtr = 1; // Read starting after the first byte.
  auto &Enter = Records.back();

  if (Enter.Type != RecordTypes::ENTER)
    return make_error<StringError>(
        "CallArgument needs to be right after a function entry",
        std::make_error_code(std::errc::executable_format_error));
  Enter.Type = RecordTypes::ENTER_ARG;
  Enter.CallArgs.emplace_back(RecordExtractor.getU64(&OffsetPtr));
  return Error::success();
}

/// Advances the state machine for reading the FDR record type by reading one
/// Metadata Record and updating the State appropriately based on the kind of
/// record encountered. The RecordKind is encoded in the first byte of the
/// Record, which the caller should pass in because they have already read it
/// to determine that this is a metadata record as opposed to a function record.
///
/// Beginning with Version 2 of the FDR log, we do not depend on the size of the
/// buffer, but rather use the extents to determine how far to read in the log
/// for this particular buffer.
///
/// In Version 3, FDR log now includes a pid metadata record after
/// WallTimeMarker
Error processFDRMetadataRecord(FDRState &State, uint8_t RecordFirstByte,
                               DataExtractor &RecordExtractor,
                               size_t &RecordSize,
                               std::vector<XRayRecord> &Records,
                               uint16_t Version) {
  // The remaining 7 bits are the RecordKind enum.
  uint8_t RecordKind = RecordFirstByte >> 1;
  switch (RecordKind) {
  case 0: // NewBuffer
    if (auto E =
            processFDRNewBufferRecord(State, RecordFirstByte, RecordExtractor))
      return E;
    break;
  case 1: // EndOfBuffer
    if (Version >= 2)
      return make_error<StringError>(
          "Since Version 2 of FDR logging, we no longer support EOB records.",
          std::make_error_code(std::errc::executable_format_error));
    if (auto E = processFDREndOfBufferRecord(State, RecordFirstByte,
                                             RecordExtractor))
      return E;
    break;
  case 2: // NewCPUId
    if (auto E =
            processFDRNewCPUIdRecord(State, RecordFirstByte, RecordExtractor))
      return E;
    break;
  case 3: // TSCWrap
    if (auto E =
            processFDRTSCWrapRecord(State, RecordFirstByte, RecordExtractor))
      return E;
    break;
  case 4: // WallTimeMarker
    if (auto E =
            processFDRWallTimeRecord(State, RecordFirstByte, RecordExtractor))
      return E;
    // In Version 3 and and above, a PidRecord is expected after WallTimeRecord
    if (Version >= 3)
      State.Expects = FDRState::Token::PID_RECORD;
    break;
  case 5: // CustomEventMarker
    if (auto E = processCustomEventMarker(State, RecordFirstByte,
                                          RecordExtractor, RecordSize))
      return E;
    break;
  case 6: // CallArgument
    if (auto E = processFDRCallArgumentRecord(State, RecordFirstByte,
                                              RecordExtractor, Records))
      return E;
    break;
  case 7: // BufferExtents
    if (auto E = processBufferExtents(State, RecordFirstByte, RecordExtractor))
      return E;
    break;
  case 9: // Pid
    if (auto E = processFDRPidRecord(State, RecordFirstByte, RecordExtractor))
      return E;
    break;
  default:
    // Widen the record type to uint16_t to prevent conversion to char.
    return make_error<StringError>(
        Twine("Illegal metadata record type: ")
            .concat(Twine(static_cast<unsigned>(RecordKind))),
        std::make_error_code(std::errc::executable_format_error));
  }
  return Error::success();
}

/// Reads a function record from an FDR format log, appending a new XRayRecord
/// to the vector being populated and updating the State with a new value
/// reference value to interpret TSC deltas.
///
/// The XRayRecord constructed includes information from the function record
/// processed here as well as Thread ID and CPU ID formerly extracted into
/// State.
Error processFDRFunctionRecord(FDRState &State, uint8_t RecordFirstByte,
                               DataExtractor &RecordExtractor,
                               std::vector<XRayRecord> &Records) {
  switch (State.Expects) {
  case FDRState::Token::NEW_BUFFER_RECORD_OR_EOF:
    return make_error<StringError>(
        "Malformed log. Received Function Record before new buffer setup.",
        std::make_error_code(std::errc::executable_format_error));
  case FDRState::Token::WALLCLOCK_RECORD:
    return make_error<StringError>(
        "Malformed log. Received Function Record when expecting wallclock.",
        std::make_error_code(std::errc::executable_format_error));
  case FDRState::Token::PID_RECORD:
    return make_error<StringError>(
        "Malformed log. Received Function Record when expecting pid.",
        std::make_error_code(std::errc::executable_format_error));
  case FDRState::Token::NEW_CPU_ID_RECORD:
    return make_error<StringError>(
        "Malformed log. Received Function Record before first CPU record.",
        std::make_error_code(std::errc::executable_format_error));
  default:
    Records.emplace_back();
    auto &Record = Records.back();
    Record.RecordType = 0; // Record is type NORMAL.
    // Strip off record type bit and use the next three bits.
    uint8_t RecordType = (RecordFirstByte >> 1) & 0x07;
    switch (RecordType) {
    case static_cast<uint8_t>(RecordTypes::ENTER):
      Record.Type = RecordTypes::ENTER;
      break;
    case static_cast<uint8_t>(RecordTypes::EXIT):
      Record.Type = RecordTypes::EXIT;
      break;
    case static_cast<uint8_t>(RecordTypes::TAIL_EXIT):
      Record.Type = RecordTypes::TAIL_EXIT;
      break;
    default:
      // Cast to an unsigned integer to not interpret the record type as a char.
      return make_error<StringError>(
          Twine("Illegal function record type: ")
              .concat(Twine(static_cast<unsigned>(RecordType))),
          std::make_error_code(std::errc::executable_format_error));
    }
    Record.CPU = State.CPUId;
    Record.TId = State.ThreadId;
    Record.PId = State.ProcessId;
    // Back up to read first 32 bits, including the 4 we pulled RecordType
    // and RecordKind out of. The remaining 28 are FunctionId.
    uint32_t OffsetPtr = 0;
    // Despite function Id being a signed int on XRayRecord,
    // when it is written to an FDR format, the top bits are truncated,
    // so it is effectively an unsigned value. When we shift off the
    // top four bits, we want the shift to be logical, so we read as
    // uint32_t.
    uint32_t FuncIdBitField = RecordExtractor.getU32(&OffsetPtr);
    Record.FuncId = FuncIdBitField >> 4;
    // FunctionRecords have a 32 bit delta from the previous absolute TSC
    // or TSC delta. If this would overflow, we should read a TSCWrap record
    // with an absolute TSC reading.
    uint64_t NewTSC = State.BaseTSC + RecordExtractor.getU32(&OffsetPtr);
    State.BaseTSC = NewTSC;
    Record.TSC = NewTSC;
  }
  return Error::success();
}

/// Reads a log in FDR mode for version 1 of this binary format. FDR mode is
/// defined as part of the compiler-rt project in xray_fdr_logging.h, and such
/// a log consists of the familiar 32 bit XRayHeader, followed by sequences of
/// of interspersed 16 byte Metadata Records and 8 byte Function Records.
///
/// The following is an attempt to document the grammar of the format, which is
/// parsed by this function for little-endian machines. Since the format makes
/// use of BitFields, when we support big-endian architectures, we will need to
/// adjust not only the endianness parameter to llvm's RecordExtractor, but also
/// the bit twiddling logic, which is consistent with the little-endian
/// convention that BitFields within a struct will first be packed into the
/// least significant bits the address they belong to.
///
/// We expect a format complying with the grammar in the following pseudo-EBNF
/// in Version 1 of the FDR log.
///
/// FDRLog: XRayFileHeader ThreadBuffer*
/// XRayFileHeader: 32 bytes to identify the log as FDR with machine metadata.
///     Includes BufferSize
/// ThreadBuffer: NewBuffer WallClockTime NewCPUId FunctionSequence EOB
/// BufSize: 8 byte unsigned integer indicating how large the buffer is.
/// NewBuffer: 16 byte metadata record with Thread Id.
/// WallClockTime: 16 byte metadata record with human readable time.
/// Pid: 16 byte metadata record with Pid
/// NewCPUId: 16 byte metadata record with CPUId and a 64 bit TSC reading.
/// EOB: 16 byte record in a thread buffer plus mem garbage to fill BufSize.
/// FunctionSequence: NewCPUId | TSCWrap | FunctionRecord
/// TSCWrap: 16 byte metadata record with a full 64 bit TSC reading.
/// FunctionRecord: 8 byte record with FunctionId, entry/exit, and TSC delta.
///
/// In Version 2, we make the following changes:
///
/// ThreadBuffer: BufferExtents NewBuffer WallClockTime NewCPUId
///               FunctionSequence
/// BufferExtents: 16 byte metdata record describing how many usable bytes are
///                in the buffer. This is measured from the start of the buffer
///                and must always be at least 48 (bytes).
///
/// In Version 3, we make the following changes:
///
/// ThreadBuffer: BufferExtents NewBuffer WallClockTime Pid NewCPUId
///               FunctionSequence
/// EOB: *deprecated*
Error loadFDRLog(StringRef Data, XRayFileHeader &FileHeader,
                 std::vector<XRayRecord> &Records) {
  if (Data.size() < 32)
    return make_error<StringError>(
        "Not enough bytes for an XRay log.",
        std::make_error_code(std::errc::invalid_argument));

  // For an FDR log, there are records sized 16 and 8 bytes.
  // There actually may be no records if no non-trivial functions are
  // instrumented.
  if (Data.size() % 8 != 0)
    return make_error<StringError>(
        "Invalid-sized XRay data.",
        std::make_error_code(std::errc::invalid_argument));

  if (auto E = readBinaryFormatHeader(Data, FileHeader))
    return E;

  uint64_t BufferSize = 0;
  {
    StringRef ExtraDataRef(FileHeader.FreeFormData, 16);
    DataExtractor ExtraDataExtractor(ExtraDataRef, true, 8);
    uint32_t ExtraDataOffset = 0;
    BufferSize = ExtraDataExtractor.getU64(&ExtraDataOffset);
  }

  FDRState::Token InitialExpectation;
  switch (FileHeader.Version) {
  case 1:
    InitialExpectation = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF;
    break;
  case 2:
  case 3:
    InitialExpectation = FDRState::Token::BUFFER_EXTENTS;
    break;
  default:
    return make_error<StringError>(
        Twine("Unsupported version '") + Twine(FileHeader.Version) + "'",
        std::make_error_code(std::errc::executable_format_error));
  }
  FDRState State{0, 0, 0, 0, InitialExpectation, BufferSize, 0};

  // RecordSize will tell the loop how far to seek ahead based on the record
  // type that we have just read.
  size_t RecordSize = 0;
  for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(RecordSize)) {
    DataExtractor RecordExtractor(S, true, 8);
    uint32_t OffsetPtr = 0;
    if (State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF) {
      RecordSize = State.CurrentBufferSize - State.CurrentBufferConsumed;
      if (S.size() < RecordSize) {
        return make_error<StringError>(
            Twine("Incomplete thread buffer. Expected at least ") +
                Twine(RecordSize) + " bytes but found " + Twine(S.size()),
            make_error_code(std::errc::invalid_argument));
      }
      State.CurrentBufferConsumed = 0;
      State.Expects = FDRState::Token::NEW_BUFFER_RECORD_OR_EOF;
      continue;
    }
    uint8_t BitField = RecordExtractor.getU8(&OffsetPtr);
    bool isMetadataRecord = BitField & 0x01uL;
    bool isBufferExtents =
        (BitField >> 1) == 7; // BufferExtents record kind == 7
    if (isMetadataRecord) {
      RecordSize = 16;
      if (auto E =
              processFDRMetadataRecord(State, BitField, RecordExtractor,
                                       RecordSize, Records, FileHeader.Version))
        return E;
    } else { // Process Function Record
      RecordSize = 8;
      if (auto E = processFDRFunctionRecord(State, BitField, RecordExtractor,
                                            Records))
        return E;
    }

    // The BufferExtents record is technically not part of the buffer, so we
    // don't count the size of that record against the buffer's actual size.
    if (!isBufferExtents)
      State.CurrentBufferConsumed += RecordSize;
    assert(State.CurrentBufferConsumed <= State.CurrentBufferSize);
    if ((FileHeader.Version == 2 || FileHeader.Version == 3) &&
        State.CurrentBufferSize == State.CurrentBufferConsumed) {
      // In Version 2 of the log, we don't need to scan to the end of the thread
      // buffer if we've already consumed all the bytes we need to.
      State.Expects = FDRState::Token::BUFFER_EXTENTS;
      State.CurrentBufferSize = BufferSize;
      State.CurrentBufferConsumed = 0;
    }
  }

  // Having iterated over everything we've been given, we've either consumed
  // everything and ended up in the end state, or were told to skip the rest.
  bool Finished = State.Expects == FDRState::Token::SCAN_TO_END_OF_THREAD_BUF &&
                  State.CurrentBufferSize == State.CurrentBufferConsumed;
  if ((State.Expects != FDRState::Token::NEW_BUFFER_RECORD_OR_EOF &&
       State.Expects != FDRState::Token::BUFFER_EXTENTS) &&
      !Finished)
    return make_error<StringError>(
        Twine("Encountered EOF with unexpected state expectation ") +
            fdrStateToTwine(State.Expects) +
            ". Remaining expected bytes in thread buffer total " +
            Twine(State.CurrentBufferSize - State.CurrentBufferConsumed),
        std::make_error_code(std::errc::executable_format_error));

  return Error::success();
}

Error loadYAMLLog(StringRef Data, XRayFileHeader &FileHeader,
                  std::vector<XRayRecord> &Records) {
  YAMLXRayTrace Trace;
  Input In(Data);
  In >> Trace;
  if (In.error())
    return make_error<StringError>("Failed loading YAML Data.", In.error());

  FileHeader.Version = Trace.Header.Version;
  FileHeader.Type = Trace.Header.Type;
  FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
  FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
  FileHeader.CycleFrequency = Trace.Header.CycleFrequency;

  if (FileHeader.Version != 1)
    return make_error<StringError>(
        Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
        std::make_error_code(std::errc::invalid_argument));

  Records.clear();
  std::transform(Trace.Records.begin(), Trace.Records.end(),
                 std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
                   return XRayRecord{R.RecordType, R.CPU, R.Type, R.FuncId,
                                     R.TSC,        R.TId, R.PId,  R.CallArgs};
                 });
  return Error::success();
}
} // namespace

Expected<Trace> llvm::xray::loadTraceFile(StringRef Filename, bool Sort) {
  int Fd;
  if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
    return make_error<StringError>(
        Twine("Cannot read log from '") + Filename + "'", EC);
  }

  uint64_t FileSize;
  if (auto EC = sys::fs::file_size(Filename, FileSize)) {
    return make_error<StringError>(
        Twine("Cannot read log from '") + Filename + "'", EC);
  }
  if (FileSize < 4) {
    return make_error<StringError>(
        Twine("File '") + Filename + "' too small for XRay.",
        std::make_error_code(std::errc::executable_format_error));
  }

  // Map the opened file into memory and use a StringRef to access it later.
  std::error_code EC;
  sys::fs::mapped_file_region MappedFile(
      Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
  if (EC) {
    return make_error<StringError>(
        Twine("Cannot read log from '") + Filename + "'", EC);
  }
  auto Data = StringRef(MappedFile.data(), MappedFile.size());

  // Attempt to detect the file type using file magic. We have a slight bias
  // towards the binary format, and we do this by making sure that the first 4
  // bytes of the binary file is some combination of the following byte
  // patterns: (observe the code loading them assumes they're little endian)
  //
  //   0x01 0x00 0x00 0x00 - version 1, "naive" format
  //   0x01 0x00 0x01 0x00 - version 1, "flight data recorder" format
  //   0x02 0x00 0x01 0x00 - version 2, "flight data recorder" format
  //
  // YAML files don't typically have those first four bytes as valid text so we
  // try loading assuming YAML if we don't find these bytes.
  //
  // Only if we can't load either the binary or the YAML format will we yield an
  // error.
  StringRef Magic(MappedFile.data(), 4);
  DataExtractor HeaderExtractor(Magic, true, 8);
  uint32_t OffsetPtr = 0;
  uint16_t Version = HeaderExtractor.getU16(&OffsetPtr);
  uint16_t Type = HeaderExtractor.getU16(&OffsetPtr);

  enum BinaryFormatType { NAIVE_FORMAT = 0, FLIGHT_DATA_RECORDER_FORMAT = 1 };

  Trace T;
  switch (Type) {
  case NAIVE_FORMAT:
    if (Version == 1 || Version == 2 || Version == 3) {
      if (auto E = loadNaiveFormatLog(Data, T.FileHeader, T.Records))
        return std::move(E);
    } else {
      return make_error<StringError>(
          Twine("Unsupported version for Basic/Naive Mode logging: ") +
              Twine(Version),
          std::make_error_code(std::errc::executable_format_error));
    }
    break;
  case FLIGHT_DATA_RECORDER_FORMAT:
    if (Version == 1 || Version == 2 || Version == 3) {
      if (auto E = loadFDRLog(Data, T.FileHeader, T.Records))
        return std::move(E);
    } else {
      return make_error<StringError>(
          Twine("Unsupported version for FDR Mode logging: ") + Twine(Version),
          std::make_error_code(std::errc::executable_format_error));
    }
    break;
  default:
    if (auto E = loadYAMLLog(Data, T.FileHeader, T.Records))
      return std::move(E);
  }

  if (Sort)
    std::stable_sort(T.Records.begin(), T.Records.end(),
              [&](const XRayRecord &L, const XRayRecord &R) {
                return L.TSC < R.TSC;
              });

  return std::move(T);
}


text:
package somossuinos.aptcomplex.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import somossuinos.aptcomplex.domain.ReferenceMonth;
import somossuinos.aptcomplex.domain.statement.MonthlyStatement;

/**
 * Created by ceballos on 02/09/15.
 */
public interface StatementRepository extends JpaRepository<MonthlyStatement, Long> {

    @Query("from MonthlyStatement ms " +
            "left outer join fetch ms.statementGroups sg " +
            "left outer join fetch sg.apartmentsStatement aps " +
            "join fetch aps.apartment a " +
            "where ms.referenceMonth = :month " +
            "and sg.type = 'INCOMES' ")
    MonthlyStatement findWithApartmentsByReferenceMonth(
            @Param("month") final ReferenceMonth month
    );

}


text:
<?php
/**
 * The template for displaying posts in the Quote post format
 *
 * @package WordPress
 * @subpackage Twenty_Thirteen
 * @since Twenty Thirteen 1.0
 */
?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

		<?php
			/* translators: %s: Name of current post */
			the_content( sprintf(
				esc_html__( 'Continue reading %s', 'twentythirteen' ),
				the_title( '', ' →', false )
			) );

			wp_link_pages( array( 'before' => '
' . __( 'Pages:', 'twentythirteen' ) . '', 'after' => '
', 'link_before' => '', 'link_after' => '' ) );
		?>

		<?php twentythirteen_entry_meta(); ?>

		<?php if ( comments_open() && ! is_single() ) : ?>

			<?php comments_popup_link( '' . __( 'Leave a comment', 'twentythirteen' ) . '', __( 'One comment so far', 'twentythirteen' ), __( 'View all % comments', 'twentythirteen' ) ); ?>

		<?php endif; // comments_open() ?>
		<?php edit_post_link( __( 'Edit', 'twentythirteen' ), '', '' ); ?>