text:
package scalan.compilation

import java.awt.Desktop
import java.io.{PrintWriter, File}

import scalan.{Scalan, Base}
import scalan.util.{ProcessUtil, FileUtil, StringUtil, ScalaNameUtil}
import scala.collection.immutable.StringOps

// TODO implement this outside of the cake

/** Implementation of Graphviz's dot file generator. */
trait GraphVizExport extends Base { self: Scalan =>

  case class GraphFile(file: File, fileType: String) {
    def open() = {
      Desktop.getDesktop.open(file)
    }
  }

  // TODO it would be better to have nodeColor(elem: Elem[_], optDef: Option[Def[_]]) to
  // avoid looking up definition, but this leads to ClassFormatError (likely Scala bug)
  protected def nodeColor(td: TypeDesc, d: Def[_])(implicit config: GraphVizConfig): String = d match {
    case _ => nodeColor(td)
  }

  protected def nodeColor(td: TypeDesc): String = td match {
    case _: ConcreteElem[_, _] => "green"
    case _: FuncElem[_, _] => "magenta"
    case _: CompanionElem[_] => "lightgray"
    case _ => "gray"
  }

  // ensures nice line wrapping
  final protected def nodeLabel(parts: String*)(implicit config: GraphVizConfig) = {
    config.nodeLabel(parts)
  }

  private def emitNode0(x: Sym, d: Option[Def[_]], acc: GraphData)(implicit stream: PrintWriter, config: GraphVizConfig) = {
    stream.println(StringUtil.quote(x) + " [")
    val acc1 = acc.addNode(x, d)
    val xElem = x.elem
    val label = acc1.typeString(xElem)
    val xAndD = d match {
      case Some(rhs) =>
        val lhsStr = s"$x: $label ="
        val rhsStr = formatDef(rhs)
        val rhsElem = rhs.resultType
        if (rhsElem != xElem) {
          List(lhsStr, s"$rhsStr:", acc1.typeString(rhsElem))
        } else {
          List(lhsStr, rhsStr)
        }
      case None =>
        List(s"$x: $label")
    }
    val metadata = if (config.emitMetadata) formatMetadata(x) else Nil
    val allParts = xAndD ++ metadata
    stream.println(nodeLabel(allParts: _*))

    val (shape, color) = d match {
      case Some(rhs) =>
        ("box", nodeColor(xElem, rhs))
      case None =>
        ("oval", nodeColor(xElem))
    }
    // use full type name for the tooltip
    stream.println(s"shape=$shape, color=$color, tooltip=${StringUtil.quote(x.varNameWithType)}, style=filled, fillcolor=white")
    stream.println("]")
    acc1
  }

  private def emitNode(sym: Sym, rhs: Def[_], acc: GraphData)(implicit stream: PrintWriter, config: GraphVizConfig) = {
    val acc1 = rhs match {
      case g: AstGraph =>
        g.boundVars.foldLeft(acc)((acc2, x) => emitNode0(x, None, acc2))
      case _ =>
        acc
    }
    emitNode0(sym, Some(rhs), acc1)
  }

  protected def formatMetadata(s: Sym): List[String] = Nil

  protected def formatDef(d: Def[_])(implicit config: GraphVizConfig): String = d match {
    case Const(x) =>
      val formattedX = formatConst(x)
      s"Const($formattedX)"
    case l: Lambda[_, _] =>
      val y = l.y
      val bodyStr = y match {
        case Def(b) =>
          val rhs = formatDef(b)
          if (config.showLambdaReturnSym)
            s"$y = $rhs"
          else
            rhs
        case _ => y.toString
      }
      s"${l.x} => $bodyStr"
    case Apply(f, arg, _) => s"$f($arg)"
    case Tup(a, b) => s"($a, $b)"
    case First(pair) => s"$pair._1"
    case Second(pair) => s"$pair._2"
    case ApplyBinOp(op, lhs, rhs) => s"$lhs ${op.opName} $rhs"
    case ApplyUnOp(op, arg) => op match {
      case NumericToInt(_) => s"$arg.toInt"
      case ToString() => s"$arg.toString"
      case HashCode() => s"$arg.hashCode"
      case _ => s"${op.opName} $arg"
    }
    case _ => d.toString
  }

  protected def formatConst(x: Any): String = x match {
    case str: String =>
      val tripleQuote = "\"\"\""
      new StringOps(str).lines.toSeq match {
        case Seq() =>
          "\"\""
        case Seq(line) =>
          if (line.contains("\""))
            tripleQuote + line + tripleQuote
          else
            StringUtil.quote(line)
        case lines =>
          (tripleQuote +: lines :+ tripleQuote).mkString("\n")
      }
    case c: Char => s"'$c'"
    case f: Float => s"${f}f"
    case l: Long => s"${l}l"
    case arr: Array[_] => s"Array(${arr.toSeq.map(formatConst).mkString(", ")})"
    case seq: Seq[_] =>
      s"${seq.stringPrefix}(${seq.map(formatConst).mkString(", ")})"
    case null => "null"
    case _ => x.toString
  }

  private def emitDepEdges(sym: Sym, rhs: Def[_])(implicit stream: PrintWriter, config: GraphVizConfig) = {
    val (deps, lambdaVars) = rhs match {
      case l: Lambda[_, _] => lambdaDeps(l)
      case _ => (rhs.deps.toList, Nil)
    }
    emitEdges(lambdaVars, sym, "[style=dashed, color=lightgray, weight=0]")
    emitEdges(deps, sym, "[style=solid]")
  }

  private def emitEdges(list: Seq[Any], target: Any, params: String)(implicit stream: PrintWriter) =
    list.foreach(emitEdge(_, target, params))

  private def emitEdge(source: Any, target: Any, params: String)(implicit stream: PrintWriter): Unit =
    stream.println(s"${StringUtil.quote(source)} -> ${StringUtil.quote(target)} $params")

  // can be overridden if desired
  def defaultGraphVizConfig: GraphVizConfig =
    GraphVizConfig.default

  def emitDepGraph(d: Def[_], directory: File, fileName: String)(implicit config: GraphVizConfig): Option[GraphFile] =
    emitDepGraph(d.deps, directory, fileName)(config)
  def emitDepGraph(start: Sym, directory: File, fileName: String)(implicit config: GraphVizConfig): Option[GraphFile] =
    emitDepGraph(List(start), directory, fileName)(config)
  def emitDepGraph(ss: Seq[Sym], directory: File, fileName: String)(implicit config: GraphVizConfig): Option[GraphFile] =
    emitDepGraph(new PGraph(ss.toList), directory, fileName)(config)
  def emitExceptionGraph(e: Throwable, directory: File, fileName: String)(implicit config: GraphVizConfig): Option[GraphFile] =
    emitDepGraph(Left(e), directory, fileName)
  def emitDepGraph(graph: AstGraph, directory: File, fileName: String)(implicit config: GraphVizConfig): Option[GraphFile] =
    emitDepGraph(Right(graph), directory, fileName)
  def emitDepGraph(exceptionOrGraph: Either[Throwable, AstGraph], directory: File, fileName: String)(implicit config: GraphVizConfig): Option[GraphFile] =
    emitGraphFile(directory, fileName)(emitDepGraph(exceptionOrGraph, fileName)(_, config))

  def emitDot(dotText: String, directory: File, fileName: String)(implicit config: GraphVizConfig): Option[GraphFile] =
    emitGraphFile(directory, fileName)(_.println(dotText))

  private def emitGraphFile(directory: File, fileName: String)(f: PrintWriter => Unit)(implicit config: GraphVizConfig): Option[GraphFile] = {
    if (config.emitGraphs) {
      val dotFileName = s"$fileName.dot"
      val file = new File(directory, dotFileName)
      FileUtil.withFile(file)(f)

      val dotFile = new File(directory, dotFileName)
      val dotGraphFile = GraphFile(dotFile, "dot")

      Some(config.format match {
        case "dot" =>
          dotGraphFile
        case format =>
          val convertedFileName = FileUtil.replaceOrAppendExtension(dotFileName, format)
          try {
            ProcessUtil.launch(Seq("dot", s"-T$format", "-o", convertedFileName, dotFileName), directory)
            GraphFile(new File(directory, convertedFileName), format)
          } catch {
            case e: Exception =>
              logWarn(s"Failed to convert ${dotFile.getAbsolutePath} to $format: ${e.getMessage}")
              dotGraphFile
          }
      })
    } else None
  }

  implicit class SeqExpExtensionsForEmitGraph(symbols: Seq[Sym]) {
    // Not default argument to allow use from the debugger
    def show(): Unit = show(defaultGraphVizConfig)
    def show(config: GraphVizConfig): Unit = showGraphs(symbols: _*)(config)
  }

  def showGraphs(roots: Sym*)(implicit config: GraphVizConfig): Unit =
    showGraphs(new PGraph(roots.toList))

  def showGraphs(graph: AstGraph)(implicit config: GraphVizConfig): Unit = {
    val prefix = graph.roots.mkString("_")
    val file = File.createTempFile(s"graph_${prefix}_", ".dot")
    // unfortunately can end up deleting the file before the process reads it
    // file.deleteOnExit()
    val directory = file.getAbsoluteFile.getParentFile
    val fileName = FileUtil.stripExtension(file.getName)
    emitDepGraph(graph, directory, fileName)(config).foreach(_.open())
  }

  private def lambdaDeps(l: Lambda[_, _]): (List[Sym], List[Sym]) = l.y match {
    case Def(l1: Lambda[_, _]) =>
      val (ds, vs) = lambdaDeps(l1)
      (ds, l.x :: vs)
    case _ => (l.y.node.deps.toList, List(l.x))
  }

  protected def clusterColor(g: AstGraph) = g match {
    case _: ProgramGraph => None
    case _: Lambda[_, _] => Some("#FFCCFF")
    case _: ThunkDef[_] => Some("#FFCCCC")
    case _ => Some("lightgray")
  }

  protected def clusterSchedule(g: AstGraph) = g match {
    case lam: Lambda[_, _] => lam.schedule.filter(_ != lam.y)
    case _ => g.schedule
  }

  protected def shouldEmitCluster(g: AstGraph) = g match {
    case lam: Lambda[_, _] => !lam.isIdentity
    case _ => true
  }

  // This function accumulates all emitted nodes so that dependency edges are placed outside any clusters.
  // Otherwise dot will incorrectly show nodes inside clusters they don't belong to.
  private def emitCluster(g: AstGraph, acc: GraphData)(implicit stream: PrintWriter, config: GraphVizConfig): GraphData = {
    val schedule = clusterSchedule(g)

    schedule.foldLeft(acc) { case (acc1, s) =>
      val d = s.node
      d match {
        case g: AstGraph if shouldEmitCluster(g) =>
          if (config.subgraphClusters) {
            stream.println(s"subgraph cluster_$s {")
            clusterColor(g).foreach { color =>
              stream.println(s"style=dashed; color=${StringUtil.quote(color)}")
            }
          }
          val acc2 = emitNode(s, d, acc1)
          // for lambdas, do we want lambdaDeps instead?
          val sources = g.boundVars
          if (config.subgraphClusters && sources.nonEmpty) {
            stream.println(s"{rank=source; ${sources.mkString("; ")}}")
          }
          val acc3 = emitCluster(g, acc2)
          if (config.subgraphClusters) {
            stream.println(s"{rank=sink; $s}")
            stream.println("}")
          }
          acc3
        case _ =>
          emitNode(s, d, acc1)
      }
    }
  }

  private def emitExceptionCluster(e: Throwable, depth: Int, acc: GraphData)(implicit stream: PrintWriter, config: GraphVizConfig): GraphData = {
    // edges appear before their end nodes but it shouldn't be a problem
    val nodeName = exceptionNodeName(depth)

    val acc1 = e.getCause match {
      case null => acc
      case cause =>
        val causeDepth = depth + 1
        emitEdge(exceptionNodeName(causeDepth), nodeName, "[style=dashed, color=red]")
        emitExceptionCluster(cause, causeDepth, acc)
    }

    val acc2 = e match {
      case e: StagingException if e.syms.nonEmpty =>
        val syms1 = e.syms
        val depGraph = new PGraph(syms1.toList)
        emitEdges(syms1, nodeName, "[color=red]")
        emitCluster(depGraph, acc1)
      case _ =>
        acc1
    }
    emitExceptionNode(e, depth)
    acc2
  }

  private def exceptionNodeName(depth: Int) = "e" + depth

  private def emitExceptionNode(e: Throwable, depth: Int)(implicit stream: PrintWriter, config: GraphVizConfig) = {
    stream.println(StringUtil.quote(exceptionNodeName(depth)) + " [")
    // complete stacks are huge; we'd like to put them into tooltip, but \l doesn't work there and xdot doesn't show
    // the tooltip anyway
    val firstUsefulStackTraceLine = e.getStackTrace.find { ste =>
      val methodName = ScalaNameUtil.cleanScalaName(ste.getMethodName)
      // skip ???, !!!, throwInvocationException and other methods which just build and throw exceptions
      !(methodName.endsWith("???") || methodName.endsWith("!!!") || methodName.startsWith("throw"))
    }.map(ste => ScalaNameUtil.cleanScalaName(ste.toString)).toList
    stream.println(config.nodeLabel(new StringOps(e.toString).lines.toList ++ firstUsefulStackTraceLine))
    stream.println(s"shape=note,color=red,style=filled,fillcolor=white")
    stream.println("]")
  }

  private sealed trait Label {
    def label: String
  }
  private case class NoAlias(label: String) extends Label
  private case class Alias(label: String, rhs: String, td: TypeDesc) extends Label

  private case class GraphData(nodes: Map[Sym, Option[Def[_]]], labels: Map[TypeDesc, Label], aliases: List[Alias], aliasCounter: Int)(implicit config: GraphVizConfig) {
    def addNode(s: Sym, d: Option[Def[_]]): GraphData = {
      val withType = config.maxTypeNameLength match {
        case Some(maxLength) =>
          val elems = d.map(_.resultType).toSet + s.elem
          elems.foldLeft(this)(_.registerType(_, maxLength))
        case None =>
          this
      }
      val nodes1 = withType.nodes + (s -> d)
      withType.copy(nodes = nodes1)
    }

    def typeString(td: TypeDesc) = {
      def f(td1: TypeDesc, recurse: Boolean): String =
        labels.get(td1) match {
          case Some(l) =>
            l.label
          case None =>
            if (recurse) {
              td1.getName(f(_, false))
            } else {
              // TODO this should never happen, but does with TypeWrappers
              // !!!(s"$td1 is used in $td.getName, but isn't registered in $labels")
              td1.name
            }
        }

      f(td, true)
    }

    private def registerType(td: TypeDesc, maxLength: Int): GraphData = {
      if (labels.contains(td))
        this
      else {
        val withTypeArgs = partsIterator(td).foldLeft(this)(_.registerType(_, maxLength))
        withTypeArgs.registerType0(td, maxLength)
      }
    }

    private def registerType0(td: TypeDesc, maxLength: Int): GraphData = {
      val labelString0 = typeString(td)

      val (label, newAliases, newAliasCounter) =
        if (labelString0.length > maxLength) {
          val alias = Alias(s"T$aliasCounter", labelString0, td)
          (alias, alias :: aliases, aliasCounter + 1)
        } else
          (NoAlias(labelString0), aliases, aliasCounter)

      val newLabels = labels + (td -> label)
      copy(labels = newLabels, aliases = newAliases, aliasCounter = newAliasCounter)
    }

    def finishGraph(implicit stream: PrintWriter) = {
      nodes.foreach {
        case (sym, Some(rhs)) =>
          emitDepEdges(sym, rhs)
        case _ =>
      }

      def emitAliasEdge(node: Any, td: TypeDesc): Unit =
        labels.get(td) match {
          case Some(Alias(label1, _, _)) =>
            // dotted doesn't work in xdot
            emitEdge(node, label1, """[style=dashed, color=turquoise]""")
          case _ =>
        }

      if (aliasCounter > 0) {
        stream.println(s"subgraph cluster_aliases {")
        stream.println("""label="Type Aliases"""")
        val orderedAliases = aliases.reverse
        orderedAliases.foreach {
          case Alias(label, rhs, td) =>
            stream.println(s"""$label [label="type $label = $rhs", shape=box, style=rounded, color=${nodeColor(td)}, fillcolor=white]""")
            // Below code doesn't show the dependencies correctly
//            if (config.typeAliasEdges) {
//              partsIterator(td).foreach(emitAliasEdge(label, _))
//            }
        }
        if (aliases.length > 1) {
          stream.println(orderedAliases.map(_.label).mkString(" -> ") + " [style=invis]")
        }
        stream.println("}")
        if (config.typeAliasEdges) {
          nodes.keysIterator.foreach {
            s => emitAliasEdge(s, s.elem)
          }
        }
      }
    }
  }
  private object GraphData {
    def empty(implicit config: GraphVizConfig) = GraphData(Map.empty, Map.empty, Nil, 0)
  }

  protected def partsIterator(td: TypeDesc) = td match {
    case e: Elem[_] =>
      e.typeArgsDescs
    case _: Cont[_] =>
      Iterator.empty
  }

  private def emitDepGraph(exceptionOrGraph: Either[Throwable, AstGraph], name: String)(implicit stream: PrintWriter, config: GraphVizConfig): Unit = {
    stream.println(s"""digraph "$name" {""")

    stream.println("concentrate=true")
    stream.println(s"node [style=filled, fillcolor=orangered]")
    stream.println(config.orientationString)

    val finalData = exceptionOrGraph match {
      case Left(e) => emitExceptionCluster(e, 0, GraphData.empty)
      case Right(graph) => emitCluster(graph, GraphData.empty)
    }

    finalData.finishGraph(stream)
    stream.println("}")
    stream.close()
  }
}

sealed trait Orientation
case object Portrait extends Orientation
case object Landscape extends Orientation

object Orientation {
}

sealed trait ControlFlowStyle
case object ControlFlowWithBoxes extends ControlFlowStyle
case object ControlFlowWithArrows extends ControlFlowStyle

// outside the cake to be usable from ItTestsUtil
case class GraphVizConfig(emitGraphs: Boolean,
                          format: String,
                          orientation: Orientation,
                          maxLabelLineLength: Int,
                          subgraphClusters: Boolean,
                          maxTypeNameLength: Option[Int],
                          typeAliasEdges: Boolean,
                          emitMetadata: Boolean,
                          showLambdaReturnSym: Boolean
                         ) {

  // ensures nice line wrapping
  def nodeLabel(parts: Seq[String]): String = {
    def escape(s: String) = s.replace("""\""", """\\""").replace("\"", """\"""")
    val lineBreak = """\l"""

    var lineLength = 0
    val sb = new StringBuilder()
    var isFirst = true
    parts.foreach { part =>
      val lines = new StringOps(part).lines.toSeq
      if (isFirst) {
        isFirst = false
      } else {
        lines match {
          case Seq() =>
            // do nothing
          case Seq(line) =>
            val lineLengthIfNoNewLine = lineLength + 1 + line.length
            lineLength = if (lineLengthIfNoNewLine <= maxLabelLineLength) {
              sb.append(" ")
              lineLengthIfNoNewLine
            } else {
              sb.append(lineBreak)
              line.length
            }
          case _ =>
            sb.append(lineBreak)
            lineLength = lines.last.length
        }
      }
      sb.append(lines.map(escape).mkString(lineBreak))
    }
    val label0 = sb.result()
    // left-justify the last line if there are multiple lines
    val label = if (label0.contains(lineBreak) && !label0.endsWith(lineBreak))
      label0 + lineBreak
    else
      label0
    s"label=${StringUtil.quote(label)}"
  }

  def orientationString = if (orientation == Landscape) "rankdir=LR" else ""
}

object GraphVizConfig {
  // not made implicit because it would be too easy to use
  // it accidentally instead of passing up
  // For some reason, return type has to be given explicitly
  val default: GraphVizConfig = GraphVizConfig(
    emitGraphs = true,
    format = "dot",
    orientation = Portrait,
    maxLabelLineLength = 50,
    subgraphClusters = true,
    maxTypeNameLength = None,
    typeAliasEdges = false,
    emitMetadata = false,
    showLambdaReturnSym = false
  )

  val none: GraphVizConfig = default.copy(emitGraphs = false)
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  This is the JRebel configuration file. It maps the running application to your IDE workspace, enabling JRebel reloading for this project.
  Refer to https://manuals.zeroturnaround.com/jrebel/standalone/config.html for more information.
-->
<application generated-by="intellij" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://update.zeroturnaround.com/jrebel/rebel-2_1.xsd">

	<classpath>
		<dir name="D:/kang/IdeaProjects/java-learn/spring-samples/multi-module-spring-platform-webapp-sample/webapp/out/production/classes">
		</dir>
	</classpath>

</application>

redpajama_set_name: RedPajamaGithub


text:
package pkg

func tpfn[T chan int]() {
	var ch T
	for range ch {
		defer println() //@ diag(`defers in this range loop`)
	}
}


text:
package top.itmp.rtbox;

import android.os.Build;
import android.os.StatFs;
import android.os.SystemClock;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import top.itmp.rtbox.command.BinCommand;
import top.itmp.rtbox.command.Command;
import top.itmp.rtbox.command.SimpleCommand;
import top.itmp.rtbox.utils.FS;
import top.itmp.rtbox.utils.Log;

/**
 * Created by hz on 2016/5/2.
 */
public class RtBox {
    public static final String TAG = "rtbox";
    public static final String VERSION = "rtbox" + " v" + BuildConfig.VERSION_NAME + '.' + BuildConfig.VERSION_CODE;
    public static final int REBOOT_SOFT = 1;
    public static final int REBOOT_REBOOT = 2;
    public static final int REBOOT_SHUTDOWN = 3;
    public static final int REBOOT_RECOVERY = 4;
    public static final int REBOOT_BOOTLOADER = 5;
    public static final int REBOOT_DOWNLOAD = 6;
    public static boolean Debug = BuildConfig.DEBUG;
    public static int DefaultCommandTimeout = 10000;
    private Shell shell;

    /**
     * Get a RtBox
     *
     * @param shell to exec commands on
     */
    public RtBox(Shell shell) {
        super();
        this.shell = shell;
    }

    /**
     * General methord to check if user has su binary and accepts root access!
     *
     * @return true if root worked
     */
    public static boolean isRootAccessGranted() {
        boolean rootAccess = false;
        try {
            Shell rootShell = Shell.startRootShell();
            rootAccess = rootShell.isRootAccessGranted();
            rootShell.close();
        } catch (IOException e) {
            Log.w(TAG, "Root Access Not Granted!!", e);
        }

        return rootAccess;
    }

    /**
     * get pids of process name
     *
     * @param processName process name
     * @return " " if pids is empty.
     * @throws IOException
     * @throws TimeoutException
     */
    public ArrayList<String> getPids(String processName) throws IOException, TimeoutException {
        PsCommand psCommand = new PsCommand(processName);
        shell.add(psCommand).waitForFinish();

        return psCommand.getPids();
    }

    /**
     * This method can be used to kill a running process
     *

     * (commands: ps, kill)
     *
     * @param processName name of process to kill
     * @return true if process was found and killed successfully
     * @throws IOException
     * @throws TimeoutException
     */
    public boolean killAll(String processName) throws TimeoutException,
            IOException {
        Log.d(RtBox.TAG, "Killing process " + processName);

        PsCommand psCommand = new PsCommand(processName);
        shell.add(psCommand).waitForFinish();

        // kill processes
        if (!psCommand.getPids().isEmpty()) {
            // example: kill -9 1234 1222 5343
            SimpleCommand killCommand = new SimpleCommand("kill -9 "
                    + psCommand.getPidsString());
            shell.add(killCommand).waitForFinish();

            if (killCommand.getExitCode() == 0) {
                return true;
            } else {
                return false;
            }
        } else {
            Log.d(RtBox.TAG, "No pid found! Nothing was killed!");
            return false;
        }
    }

    /**
     * Kill a running executable
     *

     * See README for more information how to use your own executables!
     *
     * @param binName
     * @return
     * @throws TimeoutException
     * @throws IOException
     */
    public boolean killAllBinCommand(String binName) throws TimeoutException, IOException {
        return killAll(BinCommand.BIN_PREFIX + binName + BinCommand.BIN_SUFFIX);
    }

    /**
     * This method can be used to to check if a process is running
     *
     * @param processName name of process to check
     * @return true if process was found
     * @throws IOException
     * @throws TimeoutException (Could not determine if the process is running)
     */
    public boolean isProcessRunning(String processName) throws TimeoutException, IOException {
        PsCommand psCommand = new PsCommand(processName);
        shell.add(psCommand).waitForFinish();

        // if pids are available process is running!
        if (!psCommand.getPids().isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Checks if binary is running
     *
     * @param binName
     * @return
     * @throws TimeoutException
     * @throws IOException
     */
    public boolean isBinaryRunning(String binName) throws TimeoutException, IOException {
        return isProcessRunning(BinCommand.BIN_PREFIX + binName
                + BinCommand.BIN_SUFFIX);
    }

    /**
     * @param file String that represent the file, including the full path to the file and its name.
     * @return File permissions as String, for example: 777, returns null on error
     * @throws IOException
     * @throws TimeoutException
     */
    public String getFilePermissions(String file) throws TimeoutException, IOException {
        Log.d(RtBox.TAG, "Checking permissions for " + file);

        String permissions = null;

        if (fileExists(file)) {
            Log.d(RtBox.TAG, file + " was found.");

            LsCommand lsCommand = new LsCommand(file);
            shell.add(lsCommand).waitForFinish();

            permissions = lsCommand.getPermissions();
        }

        return permissions;
    }

    /**
     * Sets permission of file
     *
     * @param file        absolute path to file
     * @param permissions String like 777
     * @return true if command worked
     * @throws TimeoutException
     * @throws IOException
     */
    public boolean setFilePermissions(String file, String permissions)
            throws TimeoutException, IOException {
        Log.d(RtBox.TAG, "Set permissions of " + file + " to " + permissions);

        SimpleCommand chmodCommand = new SimpleCommand("chmod " + permissions + " " + file);
        shell.add(chmodCommand).waitForFinish();

        if (chmodCommand.getExitCode() == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * This will return a String that represent the symlink for a specified file.
     *
     * @param file The path to the file to get the Symlink for. (must have absolute path)
     * @return A String that represent the symlink for a specified file or null if no symlink
     * exists.
     * @throws IOException
     * @throws TimeoutException
     */
    public String getSymlink(String file) throws TimeoutException,
            IOException {
        Log.d(RtBox.TAG, "Find symlink for " + file);

        String symlink = null;

        LsCommand lsCommand = new LsCommand(file);
        shell.add(lsCommand).waitForFinish();

        symlink = lsCommand.getSymlink();

        return symlink;
    }

    /**
     * Copys a file to a destination. Because cp is not available on all android devices, we use dd
     * or cat.
     *
     * @param source      example: /data/data/org.adaway/files/hosts
     * @param destination example: /system/etc/hosts
     * @param remountAsRw remounts the destination as read/write before writing to it
     *                    tries to copy file attributes from source to destination, if only cat is available
     *                    only permissions are preserved
     * @return true if it was successfully copied
     * @throws IOException
     * @throws TimeoutException
     */
    public boolean copyFile(String source, String destination, boolean remountAsRw,
                            boolean preservePermissions) throws IOException, TimeoutException {

        /*
         * dd can only copy files, but we can not check if the source is a file without invoking
         * shell commands, because from Java we probably have no read access, thus we only check if
         * they are ending with trailing slashes
         */
        if (source.endsWith("/") || destination.endsWith("/")) {
            throw new FileNotFoundException("dd can only copy files!");
        }

        // remount destination as read/write before copying to it
        if (remountAsRw) {
            if (!remount(destination, "RW")) {
                Log.d(RtBox.TAG,
                        "Remounting failed! There is probably no need to remount this partition!");
            }
        }

        // get permissions of source before overwriting
        String permissions = null;
        if (preservePermissions) {
            permissions = getFilePermissions(source);
        }

        boolean commandSuccess = false;

        SimpleCommand ddCommand = new SimpleCommand("dd if=" + source + " of="
                + destination);
        shell.add(ddCommand).waitForFinish();

        if (ddCommand.getExitCode() == 0) {
            commandSuccess = true;
        } else {
            // try cat if dd fails
            SimpleCommand catCommand = new SimpleCommand("cat " + source + " > "
                    + destination);
            shell.add(catCommand).waitForFinish();

            if (catCommand.getExitCode() == 0) {
                commandSuccess = true;
            }
        }

        // set back permissions from source to destination
        if (preservePermissions) {
            setFilePermissions(destination, permissions);
        }

        // remount destination back to read only
        if (remountAsRw) {
            if (!remount(destination, "RO")) {
                Log.d(RtBox.TAG,
                        "Remounting failed! There is probably no need to remount this partition!");
            }
        }

        return commandSuccess;
    }

    /**
     * Shutdown or reboot device. Possible actions are REBOOT_SOFT, REBOOT_REBOOT,
     * REBOOT_SHUTDOWN, REBOOT_RECOVERY, REBOOT_BOOTLOADER,
     * REBOOT_DOWNLOAD: Not all devices have this option. You can try this, but risk is yours
     *
     * @param action
     * @throws IOException
     * @throws TimeoutException
     */
    public void reboot(int action) throws TimeoutException, IOException {
        if (action == REBOOT_SOFT) {
            killAll("system_server");
            // or: killAll("zygote");
        } else {
            String command;
            switch (action) {
                case REBOOT_REBOOT:
                    command = "reboot";
                    break;
                case REBOOT_SHUTDOWN:
                    command = "reboot -p";
                    break;
                case REBOOT_RECOVERY:
                    command = "reboot recovery";
                    break;
                case REBOOT_BOOTLOADER:
                    command = "reboot bootloader";
                    break;
                case REBOOT_DOWNLOAD:
                    command = "reboot download";
                    break;
                default:
                    command = "reboot";
                    break;
            }

            SimpleCommand rebootCommand = new SimpleCommand(command);
            shell.add(rebootCommand).waitForFinish();

            if (rebootCommand.getExitCode() == -1) {
                Log.e(RtBox.TAG, "Reboot failed!");
            }
        }
    }

    /**
     * Use this to check whether or not a file exists on the filesystem.
     *
     * @param file String that represent the file, including the full path to the file and its name.
     * @return a boolean that will indicate whether or not the file exists.
     * @throws IOException
     * @throws TimeoutException
     */
    public boolean fileExists(String file) throws TimeoutException, IOException {
        FileExistsCommand fileExistsCommand = new FileExistsCommand(file);
        shell.add(fileExistsCommand).waitForFinish();

        if (fileExistsCommand.isFileExists()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Execute user defined Java code while having temporary permissions on a file
     *
     * @param file
     * @param withPermissions
     * @throws TimeoutException
     * @throws IOException
     */
    public void withPermission(String file, String permission, WithPermissions withPermissions)
            throws TimeoutException, IOException {
        String oldPermissions = getFilePermissions(file);

        // set permissions (If set to 666, then Dalvik VM can also write to that file!)
        setFilePermissions(file, permission);

        // execute user defined code
        withPermissions.whileHavingPermissions();

        // set back to old permissions
        setFilePermissions(file, oldPermissions);
    }

    /**
     * Execute user defined Java code while having temporary write permissions on a file using chmod
     * 666
     *
     * @param file
     * @param withWritePermissions
     * @throws TimeoutException
     * @throws IOException
     */
    public void withWritePermissions(String file, WithPermissions withWritePermissions)
            throws TimeoutException, IOException {
        withPermission(file, "666", withWritePermissions);
    }

    /**
     * Sets system clock using /dev/alarm
     *
     * @param millis
     * @throws TimeoutException
     * @throws IOException
     */
    public void setSystemClock(final long millis) throws TimeoutException, IOException {
        withWritePermissions("/dev/alarm", new WithPermissions() {

            @Override
            void whileHavingPermissions() {
                SystemClock.setCurrentTimeMillis(millis);
            }
        });
    }

    /**
     * Adjust system clock by offset using /dev/alarm
     *
     * @param offset
     * @throws TimeoutException
     * @throws IOException
     */
    public void adjustSystemClock(final long offset) throws TimeoutException, IOException {
        withWritePermissions("/dev/alarm", new WithPermissions() {

            @Override
            void whileHavingPermissions() {
                SystemClock.setCurrentTimeMillis(System.currentTimeMillis() + offset);
            }
        });
    }

    /**
     * This will take a path, which can contain the file name as well, and attempt to remount the
     * underlying partition.
     *

     * For example, passing in the following string:
     * "/system/bin/some/directory/that/really/would/never/exist" will result in /system ultimately
     * being remounted. However, keep in mind that the longer the path you supply, the more work
     * this has to do, and the slower it will run.
     *
     * @param file      file path
     * @param mountType mount type: pass in RO (Read only) or RW (Read Write)
     * @return a boolean which indicates whether or not the partition has been
     * remounted as specified.
     */
    public boolean remount(String file, String mountType) {
        // Recieved a request, get an instance of Remounter
        FS fs = new FS(shell);
        // send the request
        return (fs.remount(file, mountType));
    }

    /**
     * This will tell you how the specified mount is mounted. rw, ro, etc...
     *
     * @param path The mount you want to check
     * @return String What the mount is mounted as.
     * @throws Exception if we cannot determine how the mount is mounted.
     */
    public String getMountedAs(String path) throws Exception {
        ArrayList<FS.Mount> mounts = FS.getMounts();
        if (mounts != null) {
            for (FS.Mount mount : mounts) {
                if (path.contains(mount.getMountPoint().getAbsolutePath())) {
                    Log.d(RtBox.TAG, (String) mount.getFlags().toArray()[0]);
                    return (String) mount.getFlags().toArray()[0];
                }
            }

            throw new Exception();
        } else {
            throw new Exception();
        }
    }

    /**
     * Check if there is enough space on partition where target is located
     *
     * @param size   size of file to put on partition
     * @param target path where to put the file
     * @return true if it will fit on partition of target, false if it will not fit.
     */
    @SuppressWarnings("deprecation")
    public boolean hasEnoughSpaceOnPartition(String target, long size) {
        try {
            // new File(target).getFreeSpace() (API 9) is not working on data partition

            // get directory without file
            String directory = new File(target).getParent().toString();

            StatFs stat = new StatFs(directory);

            long blockSize;
            long availableBlocks;

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
                blockSize = stat.getBlockSizeLong();
                availableBlocks = stat.getAvailableBlocksLong();
            } else {
                blockSize = stat.getBlockSize();
                availableBlocks = stat.getAvailableBlocks();
            }
            long availableSpace = availableBlocks * blockSize;

            Log.i(RtBox.TAG, "Checking for enough space: Target: " + target
                    + ", directory: " + directory + " size: " + size + ", availableSpace: "
                    + availableSpace);

            if (size < availableSpace) {
                return true;
            } else {
                Log.e(RtBox.TAG, "Not enough space on partition!");
                return false;
            }
        } catch (Exception e) {
            // if new StatFs(directory) fails catch IllegalArgumentException and just return true as
            // workaround
            Log.e(RtBox.TAG, "Problem while getting available space on partition!", e);
            return true;
        }
    }

    /**
     * TODO: Not tested!
     *
     * @param toggle
     * @throws IOException
     * @throws TimeoutException
     */
    public void toggleAdbDaemon(boolean toggle) throws TimeoutException, IOException {
        SimpleCommand disableAdb = new SimpleCommand("setprop persist.service.adb.enable 0",
                "stop adbd");
        SimpleCommand enableAdb = new SimpleCommand("setprop persist.service.adb.enable 1",
                "stop adbd", "sleep 1", "start adbd");

        if (toggle) {
            shell.add(enableAdb).waitForFinish();
        } else {
            shell.add(disableAdb).waitForFinish();
        }
    }

    public static enum LogLevel {
        VERBOSE,
        ERROR,
        DEBUG,
        WARN
    }

    /**
     * This command class gets all pids to a given process name
     */
    private class PsCommand extends Command {
        private String processName;
        private ArrayList<String> pids;
        private String psRegex;
        private Pattern psPattern;

        public PsCommand(String processName) {
            super("ps");
            this.processName = processName;
            pids = new ArrayList<>();

            /**
             * regex to get pid out of ps line, example:
             *
             *

             *  root    24736    1   12140  584   ffffffff 40010d14 S /data/data/org.adaway/files/blank_webserver
             * ^\\S \\s ([0-9]+)                          .*                                      processName    $
             *

             */
            psRegex = "^\\S+\\s+([0-9]+).*" + Pattern.quote(processName) + "$";
            psPattern = Pattern.compile(psRegex);
        }

        public ArrayList<String> getPids() {
            return pids;
        }

        public String getPidsString() {
            StringBuilder sb = new StringBuilder();
            for (String s : pids) {
                sb.append(s);
                sb.append(" ");
            }

            return sb.toString();
        }

        @Override
        public void output(int id, String line) {
            // general check if line contains processName
            if (line.contains(processName)) {
                Matcher psMatcher = psPattern.matcher(line);

                // try to match line exactly
                try {
                    if (psMatcher.find()) {
                        String pid = psMatcher.group(1);
                        // add to pids list
                        pids.add(pid);
                        Log.d(RtBox.TAG, "Found pid: " + pid);
                    } else {
                        Log.d(RtBox.TAG, "Matching in ps command failed!");
                    }
                } catch (Exception e) {
                    Log.e(RtBox.TAG, "Error with regex!", e);
                }
            }
        }

        @Override
        public void afterExecution(int id, int exitCode) {
        }

    }

    /**
     * Ls command to get permissions or symlinks
     */
    private class LsCommand extends Command {
        private String fileName;
        private String permissionRegex;
        private Pattern permissionPattern;
        private String symlinkRegex;
        private Pattern symlinkPattern;

        private String symlink;
        private String permissions;

        public LsCommand(String file) {
            super("ls -l " + file);

            // get only filename:
            this.fileName = (new File(file)).getName();
            Log.d(RtBox.TAG, "fileName: " + fileName);

            /**
             * regex to get pid out of ps line, example:
             *
             *

             * with busybox:
             *     lrwxrwxrwx     1 root root            15 Aug 13 12:14 dev/stdin -> /proc/self/fd/0
             *
             * with toolbox:
             *     lrwxrwxrwx root root            15 Aug 13 12:14 stdin -> /proc/self/fd/0
             *
             * Regex:
             * ^.*?(\\S{10})                     .*                                                  $
             *

             */
            permissionRegex = "^.*?(\\S{10}).*$";
            permissionPattern = Pattern.compile(permissionRegex);

            /**
             * regex to get symlink
             *
             *

             *     ->           /proc/self/fd/0
             * ^.*?\\-\\> \\s+  (.*)           $
             *

             */
            symlinkRegex = "^.*?\\-\\>\\s+(.*)$";
            symlinkPattern = Pattern.compile(symlinkRegex);
        }

        public String getSymlink() {
            return symlink;
        }

        public String getPermissions() {
            return permissions;
        }

        /**
         * Converts permission string from ls command to numerical value. Example: -rwxrwxrwx gets
         * to 777
         *
         * @param permissions
         * @return
         */
        private String convertPermissions(String permissions) {
            int owner = getGroupPermission(permissions.substring(1, 4));
            int group = getGroupPermission(permissions.substring(4, 7));
            int world = getGroupPermission(permissions.substring(7, 10));

            return "" + owner + group + world;
        }

        /**
         * Calculates permission for one group
         *
         * @param permission
         * @return value of permission string
         */
        private int getGroupPermission(String permission) {
            int value = 0;

            if (permission.charAt(0) == 'r') {
                value += 4;
            }
            if (permission.charAt(1) == 'w') {
                value += 2;
            }
            if (permission.charAt(2) == 'x') {
                value += 1;
            }

            return value;
        }

        @Override
        public void output(int id, String line) {
            // general check if line contains file
            if (line.contains(fileName)) {

                // try to match line exactly
                try {
                    Matcher permissionMatcher = permissionPattern.matcher(line);
                    if (permissionMatcher.find()) {
                        permissions = convertPermissions(permissionMatcher.group(1));

                        Log.d(RtBox.TAG, "Found permissions: " + permissions);
                    } else {
                        Log.d(RtBox.TAG, "Permissions were not found in ls command!");
                    }

                    // try to parse for symlink
                    Matcher symlinkMatcher = symlinkPattern.matcher(line);
                    if (symlinkMatcher.find()) {
                        /*
                         * TODO: If symlink points to a file in the same directory the path is not
                         * absolute!!!
                         */
                        symlink = symlinkMatcher.group(1);
                        Log.d(RtBox.TAG, "Symlink found: " + symlink);
                    } else {
                        Log.d(RtBox.TAG, "No symlink found!");
                    }
                } catch (Exception e) {
                    Log.e(RtBox.TAG, "Error with regex!", e);
                }
            }
        }

        @Override
        public void afterExecution(int id, int exitCode) {
        }

    }

    /**
     * This command checks if a file exists
     */
    private class FileExistsCommand extends Command {
        private String file;
        private boolean fileExists = false;

        public FileExistsCommand(String file) {
            super("ls " + file);
            this.file = file;
        }

        public boolean isFileExists() {
            return fileExists;
        }

        @Override
        public void output(int id, String line) {
            if (line.trim().equals(file)) {
                fileExists = true;
            }
        }

        @Override
        public void afterExecution(int id, int exitCode) {
        }

    }

    public abstract class WithPermissions {
        abstract void whileHavingPermissions();
    }
}


text:
"""Command for deleting instances managed by managed instance group."""

from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import instance_groups_utils
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.command_lib.compute import flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.instance_groups import flags as instance_groups_flags

class DeleteInstances(base_classes.BaseAsyncMutator):
  """Delete instances managed by managed instance group."""

  @staticmethod
  def Args(parser):
    parser.add_argument('--instances',
                        type=arg_parsers.ArgList(min_length=1),
                        metavar='INSTANCE',
                        required=True,
                        help='Names of instances to delete.')
    instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG.AddArgument(
        parser)

  @property
  def method(self):
    return 'DeleteInstances'

  @property
  def service(self):
    return self.compute.instanceGroupManagers

  @property
  def resource_type(self):
    return 'instanceGroupManagers'

  def CreateRequests(self, args):
    resource_arg = instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG
    default_scope = compute_scope.ScopeEnum.ZONE
    scope_lister = flags.GetDefaultScopeLister(
        self.compute_client, self.project)
    igm_ref = resource_arg.ResolveAsResource(
        args, self.resources, default_scope=default_scope,
        scope_lister=scope_lister)
    instances = instance_groups_utils.CreateInstanceReferences(
        self.resources, self.compute_client, igm_ref, args.instances)

    if igm_ref.Collection() == 'compute.instanceGroupManagers':
      service = self.compute.instanceGroupManagers
      request = (
          self.messages.
          ComputeInstanceGroupManagersDeleteInstancesRequest(
              instanceGroupManager=igm_ref.Name(),
              instanceGroupManagersDeleteInstancesRequest=(
                  self.messages.InstanceGroupManagersDeleteInstancesRequest(
                      instances=instances,
                  )
              ),
              project=self.project,
              zone=igm_ref.zone,
          ))
    else:
      service = self.compute.regionInstanceGroupManagers
      request = (
          self.messages.
          ComputeRegionInstanceGroupManagersDeleteInstancesRequest(
              instanceGroupManager=igm_ref.Name(),
              regionInstanceGroupManagersDeleteInstancesRequest=(
                  self.messages.
                  RegionInstanceGroupManagersDeleteInstancesRequest(
                      instances=instances,
                  )
              ),
              project=self.project,
              region=igm_ref.region,
          ))

    return [(service, self.method, request)]

DeleteInstances.detailed_help = {
    'brief': 'Delete instances managed by managed instance group.',
    'DESCRIPTION': """
        *{command}* is used to deletes one or more instances from a managed
instance group. Once the instances are deleted, the size of the group is
automatically reduced to reflect the changes.

If you would like to keep the underlying virtual machines but still remove them
from the managed instance group, use the abandon-instances command instead.
""",
}


text:
package com.pg85.otg.forge.gui;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;

import org.apache.logging.log4j.LogManager;

import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.JsonOps;
import com.pg85.otg.OTG;
import com.pg85.otg.config.dimensions.DimensionConfig;
import com.pg85.otg.config.dimensions.DimensionConfig.OTGOverWorld;
import com.pg85.otg.constants.Constants;
import com.pg85.otg.forge.biome.OTGBiomeProvider;
import com.pg85.otg.forge.dimensions.OTGDimensionType;
import com.pg85.otg.forge.gen.OTGNoiseChunkGenerator;
import com.pg85.otg.forge.gui.screens.CreateOTGDimensionsScreen;
import net.minecraft.client.gui.screen.BiomeGeneratorTypeScreens;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.DynamicRegistries;
import net.minecraft.util.registry.MutableRegistry;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.SimpleRegistry;
import net.minecraft.world.Dimension;
import net.minecraft.world.DimensionType;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.provider.OverworldBiomeProvider;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.DebugChunkGenerator;
import net.minecraft.world.gen.DimensionSettings;
import net.minecraft.world.gen.FlatChunkGenerator;
import net.minecraft.world.gen.FlatGenerationSettings;
import net.minecraft.world.gen.NoiseChunkGenerator;
import net.minecraft.world.gen.settings.DimensionGeneratorSettings;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.world.ForgeWorldType;
import net.minecraftforge.registries.ForgeRegistries;

@OnlyIn(Dist.CLIENT)
public class OTGGui
{
	public static DimensionConfig currentSelection;

	// Define a new world type for the world creation screen
	public static final BiomeGeneratorTypeScreens OTG_WORLD_TYPE = new BiomeGeneratorTypeScreens(Constants.MOD_ID_SHORT)
	{
		protected ChunkGenerator generator(Registry<Biome> biomes, Registry<DimensionSettings> dimensionSettings, long seed)
		{
			// Called when selecting the OTG world type in the world creation gui.
			currentSelection = DimensionConfig.createDefaultConfig();
			if(!OTG.getEngine().getPresetLoader().getAllPresets().isEmpty())
			{
				currentSelection.Overworld = new OTGOverWorld(OTG.getEngine().getPresetLoader().getDefaultPresetFolderName(), seed, null, null);
				return new OTGNoiseChunkGenerator(new OTGBiomeProvider(OTG.getEngine().getPresetLoader().getDefaultPresetFolderName(), seed, false, false, biomes), seed, () -> dimensionSettings.getOrThrow(DimensionSettings.OVERWORLD));
			} else {
				// If no presets are installed, return the default chunkgenerator / biomeprovider
				return new NoiseChunkGenerator(new OverworldBiomeProvider(seed, false, false, biomes), seed, () ->
				{
					return dimensionSettings.getOrThrow(DimensionSettings.OVERWORLD);
				});
			}
		}
	};

	public static void init()
	{
		// Register the otg worldtype for the world creation screen
		BiomeGeneratorTypeScreens.PRESETS.add(OTG_WORLD_TYPE);

		// Register world type customisation button / screens
		@SuppressWarnings("unchecked")
		Map<Optional<BiomeGeneratorTypeScreens>, BiomeGeneratorTypeScreens.IFactory> otgWorldOptionsScreen =
			ImmutableMap.of(
				Optional.of(OTG_WORLD_TYPE),
				(createWorldScreen, dimensionGeneratorSettings) ->
				{
					if(!OTG.getEngine().getPresetLoader().getAllPresets().isEmpty())
					{
						return new CreateOTGDimensionsScreen(
							createWorldScreen,
							// Define apply function, generates updated
							// settings when leaving customisation menu.
							(dimGenSettings) ->
							{
								DynamicRegistries.Impl dynamicRegistries = createWorldScreen.worldGenSettingsComponent.registryHolder();
								MutableRegistry<DimensionType> dimensionTypesRegistry = dynamicRegistries.registryOrThrow(Registry.DIMENSION_TYPE_REGISTRY);
								Registry<Biome> biomesRegistry = dynamicRegistries.registryOrThrow(Registry.BIOME_REGISTRY);
								Registry<DimensionSettings> dimensionSettingsRegistry = dynamicRegistries.registryOrThrow(Registry.NOISE_GENERATOR_SETTINGS_REGISTRY);

								long seed = dimensionGeneratorSettings.seed();
								boolean generateFeatures = dimensionGeneratorSettings.generateFeatures();
								boolean generateBonusChest = dimensionGeneratorSettings.generateBonusChest();

								// If there is a dimensionconfig for the generatorsettings, use that. Otherwise find a preset by name.
								DimensionConfig dimConfig = dimGenSettings.dimensionConfig;
								currentSelection = dimConfig;
								SimpleRegistry<Dimension> dimensions = dimensionGeneratorSettings.dimensions();
								if(dimConfig.isModpackConfig())
								{
									// Non-otg overworld, generatorsettings contains non-otg world type.
									ForgeWorldType def = dimConfig.Overworld.NonOTGWorldType == null ? null : ForgeRegistries.WORLD_TYPES.getValue(new ResourceLocation(dimConfig.Overworld.NonOTGWorldType));
									if(def != null)
									{
										DimensionGeneratorSettings existingDimSetting = def.createSettings(dynamicRegistries, seed, generateFeatures, generateBonusChest, dimConfig.Overworld.NonOTGGeneratorSettings);
										dimensions = existingDimSetting.dimensions();
									} else {
										SimpleRegistry<Dimension> simpleregistry = DimensionType.defaultDimensions(dimensionTypesRegistry, biomesRegistry, dimensionSettingsRegistry, seed);
										DimensionGeneratorSettings existingDimSetting = null;
										switch(dimConfig.Overworld.NonOTGWorldType == null ? "" : dimConfig.Overworld.NonOTGWorldType)
										{
											case "flat":
												JsonObject jsonobject = dimConfig.Overworld.NonOTGGeneratorSettings != null && !dimConfig.Overworld.NonOTGGeneratorSettings.isEmpty() ? JSONUtils.parse(dimConfig.Overworld.NonOTGGeneratorSettings) : new JsonObject();
												Dynamic<JsonElement> dynamic = new Dynamic<>(JsonOps.INSTANCE, jsonobject);
												existingDimSetting = new DimensionGeneratorSettings(seed, generateFeatures, generateBonusChest, DimensionGeneratorSettings.withOverworld(dimensionTypesRegistry, simpleregistry, new FlatChunkGenerator(FlatGenerationSettings.CODEC.parse(dynamic).resultOrPartial(LogManager.getLogger()::error).orElseGet(() -> {
												return FlatGenerationSettings.getDefault(biomesRegistry);
												}))));
												break;
											case "debug_all_block_states":
												existingDimSetting = new DimensionGeneratorSettings(seed, generateFeatures, generateBonusChest, DimensionGeneratorSettings.withOverworld(dimensionTypesRegistry, simpleregistry, new DebugChunkGenerator(biomesRegistry)));
												break;
											case "amplified":
												existingDimSetting = new DimensionGeneratorSettings(seed, generateFeatures, generateBonusChest, DimensionGeneratorSettings.withOverworld(dimensionTypesRegistry, simpleregistry, new NoiseChunkGenerator(new OverworldBiomeProvider(seed, false, false, biomesRegistry), seed, () -> {
													return dimensionSettingsRegistry.getOrThrow(DimensionSettings.AMPLIFIED);
												})));
												break;
											case "largebiomes":
												existingDimSetting = new DimensionGeneratorSettings(seed, generateFeatures, generateBonusChest, DimensionGeneratorSettings.withOverworld(dimensionTypesRegistry, simpleregistry, new NoiseChunkGenerator(new OverworldBiomeProvider(seed, false, true, biomesRegistry), seed, () -> {
													return dimensionSettingsRegistry.getOrThrow(DimensionSettings.OVERWORLD);
												})));
												break;
											default:
												existingDimSetting = new DimensionGeneratorSettings(seed, generateFeatures, generateBonusChest, DimensionGeneratorSettings.withOverworld(dimensionTypesRegistry, simpleregistry, DimensionGeneratorSettings.makeDefaultOverworld(biomesRegistry, dimensionSettingsRegistry, seed)));
												break;
										}
										dimensions = existingDimSetting.dimensions();
									}
								}
								else if(dimGenSettings.dimGenSettings != null)
								{
									// Add non-otg overworld configured via customize menu.
									Entry<RegistryKey<Dimension>, Dimension> registryEntry = ((Entry<RegistryKey<Dimension>, Dimension>)dimGenSettings.dimGenSettings.dimensions().entrySet().toArray()[0]);
									if (registryEntry.getKey() == Dimension.OVERWORLD)
									{
										dimensions.register(registryEntry.getKey(), registryEntry.getValue(), dimensions.lifecycle(registryEntry.getValue()));
									}
								}

								createWorldScreen.worldGenSettingsComponent.updateSettings(
									OTGDimensionType.createOTGDimensionGeneratorSettings(
										dimConfig.isModpackConfig() ? Constants.MODPACK_CONFIG_NAME : null,
										dimConfig,
										dimensionTypesRegistry,
										biomesRegistry,
										dimensionSettingsRegistry,
										seed,
										generateFeatures,
										generateBonusChest,
										dimensions
									)
								);
							}
						);
					} else {
						// If no preset are installed, do nothing (exits to main menu)
						return null;
					}
				}
			)
		;

		BiomeGeneratorTypeScreens.EDITORS = ImmutableMap.<Optional<BiomeGeneratorTypeScreens>, BiomeGeneratorTypeScreens.IFactory>builder()
			.putAll(BiomeGeneratorTypeScreens.EDITORS)
			.putAll(otgWorldOptionsScreen)
			.build()
		;
	}
}


text:
@interface ViewController ()<TTMGameDelegate> {
    IBOutlet BoardView* _boardView;
    IBOutlet UILabel* _statusLabel;
    IBOutlet UIStepper* _sideStepper;
    TTMManualPlayer *_userPlayer;
    TTMPlayer *_aiPlayer;
    TTMGame *_game;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _userPlayer = [[TTMManualPlayer alloc] init];
    _aiPlayer = [[TTMMinMaxPlayer alloc] init];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(boardViewTappedWithGestureRecognizer:)];
    [_boardView addGestureRecognizer:tap];
    [self startNewGame];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)startNewGame {
    _statusLabel.text = @"New game is started...";
    TTMBoard *board = [[TTMBoard alloc] initWithSide:(int)_sideStepper.value];
    [_boardView drawBoard:[board copy]];

    _game = [[TTMGame alloc] initWithBoard:board];
    _game.delegate = self;
    [_game addPlayerToGame: _aiPlayer];
    [_game addPlayerToGame: _userPlayer];
    [_game startGame];

}

-(IBAction)newGameTouched:(id)sender {
    [self startNewGame];
}
-(IBAction)sizeValueChanged:(id)sender {
    [self startNewGame];
}

-(void)boardViewTappedWithGestureRecognizer:(UITapGestureRecognizer *)gestureRecognizer {
    if(gestureRecognizer.state == UIGestureRecognizerStateRecognized)
    {
        CGPoint point = [gestureRecognizer locationInView:gestureRecognizer.view];
        BoardView *boardView = (BoardView*)gestureRecognizer.view;
        [_userPlayer takeManualTurn: [boardView boardCoordinatesFromCGPoint:point] inGame:_game];
    }
}

-(void)game:(TTMGame *)game player:(TTMPlayer*) player mark:(TTMMark) mark tookTurnWithCoords:(TTMCoords) coords {
    [_boardView drawBoard:[game copyBoard]];

    _statusLabel.text = [NSString stringWithFormat:@"It's player's '%@' turn now.", NSStringWithTTMMark(TTMMarkOppositeToMark(mark))];
}

-(void)game:(TTMGame *)game player:(TTMPlayer*) player mark:(TTMMark) mark wonWithStartingCoords:(TTMCoords) coords endingCoords:(TTMCoords) coords {
    [_boardView drawBoard:[game copyBoard]];
    NSString *txt = [NSString stringWithFormat:@"Player '%@' won :)", NSStringWithTTMMark(mark)];
    if (mark==TTMMarkNULL) {
        txt = @"Its draw :(";
    }
    _statusLabel.text = [NSString stringWithFormat:@"%@ To start a new game press a button", txt];
}

@end


text:
@implementation ATTableViewCellButtonView

#pragma mark - initializers

- (id)initWithUtilityButtons:(NSArray *)utilityButtons parentCell:(ATSwipableTableViewCell *)parentCell utilityButtonSelector:(SEL)utilityButtonSelector {
    self = [super init];

    if (self) {
        self.utilityButtons = utilityButtons;
        self.utilityButtonWidth = [self calculateUtilityButtonWidth];
        self.parentCell = parentCell;
        self.utilityButtonSelector = utilityButtonSelector;
        self.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    }

    return self;
}

- (CGFloat)calculateUtilityButtonWidth {
    CGFloat buttonWidth = kUtilityButtonWidthDefault;
    if (buttonWidth * _utilityButtons.count > kUtilityButtonsWidthMax) {
        CGFloat buffer = (buttonWidth * _utilityButtons.count) - kUtilityButtonsWidthMax;
        buttonWidth -= (buffer / _utilityButtons.count);
    }
    return buttonWidth;
}

- (CGFloat)utilityButtonsWidth {
    return (_utilityButtons.count * _utilityButtonWidth);
}

- (void)populateUtilityButtons {
    NSUInteger utilityButtonsCounter = 0;
    for (UIButton *utilityButton in _utilityButtons) {
        CGFloat utilityButtonXCord = 0;
        if (utilityButtonsCounter >= 1) utilityButtonXCord = _utilityButtonWidth * utilityButtonsCounter;
        [utilityButton setFrame:CGRectMake(utilityButtonXCord, 0, _utilityButtonWidth, CGRectGetHeight(self.bounds))];
        utilityButton.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [utilityButton setTag:utilityButtonsCounter];
        [utilityButton addTarget:_parentCell action:_utilityButtonSelector forControlEvents:UIControlEventTouchDown];
        [self addSubview: utilityButton];
        utilityButtonsCounter++;
    }
}

@end


text:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// Node packages.
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
// Project packages.
const media_manager_1 = require("@bldr/media-manager");
const log = __importStar(require("@bldr/log"));
/**
 * Rename a media asset after the `id` in the meta data file.
 *
 * @param filePath - The media asset file path.
 */
function renameFromIdOneFile(filePath) {
    let result;
    try {
        result = media_manager_1.readYamlMetaData(filePath);
    }
    catch (error) {
        log.error(filePath);
        log.error(error);
        return;
    }
    if (result.ref != null) {
        let ref = result.ref;
        const oldPath = filePath;
        // .mp4
        const extension = path_1.default.extname(oldPath);
        const oldBaseName = path_1.default.basename(oldPath, extension);
        let newPath = null;
        // Gregorianik_HB_Alleluia-Ostermesse -> Alleluia-Ostermesse
        ref = ref.replace(/.*_[A-Z]{2,}_/, '');
        log.info(ref);
        if (ref !== oldBaseName) {
            newPath = path_1.default.join(path_1.default.dirname(oldPath), `${ref}${extension}`);
        }
        else {
            return;
        }
        media_manager_1.moveAsset(oldPath, newPath);
    }
}
/**
 * Rename a media asset or all child asset of the parent working directory
 * after the `id` in the meta data file.
 *
 * @param files - An array of input files, comes from the commanders'
 *   variadic parameter `[files...]`.
 */
function action(files) {
    return __awaiter(this, void 0, void 0, function* () {
        yield media_manager_1.walk({
            asset(relPath) {
                if (fs_1.default.existsSync(`${relPath}.yml`)) {
                    renameFromIdOneFile(relPath);
                }
            }
        }, {
            path: files
        });
    });
}
module.exports = action;


text:
> Borderless fullscreen is a wonderful thing.

A little tool for making games run in borderless fullscreen instead of windowed mode.
Apps are displayed with a user-set filter to reduce needless clutter.
Fullscreenizing apps is fully reversible to their initial settings, and multiple monitors are supported.
A hotkey can be used instead of the UI.
Configuration options are saved, and the hotkey can automatically enable upon startup.

## Binaries
See [here](https://github.com/KasumiL5x/Fullscreenizer/releases) for the available binaries.

## Status
This project was created around 2014/2015 and is not maintained.


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Leviathan.Testing.TestParsedObject2>
  <AField1>30/12/2006 11:00:01</AField1>
  <AField2>
    <Leviathan.Testing.TestParsedObject3>
      <AField1>1</AField1>
      <AField2>Test1</AField2>
      <AProperty1>2</AProperty1>
      <AProperty2>Test2</AProperty2>
    </Leviathan.Testing.TestParsedObject3>
  </AField2>
  <AField3>Leviathan.Testing.TestParsedObject</AField3>
</Leviathan.Testing.TestParsedObject2>


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.firefox;

import static java.util.Collections.singletonMap;
import static org.openqa.selenium.remote.CapabilityType.PROXY;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.html5.LocalStorage;
import org.openqa.selenium.html5.SessionStorage;
import org.openqa.selenium.html5.WebStorage;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.CommandInfo;
import org.openqa.selenium.remote.FileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.html5.RemoteWebStorage;
import org.openqa.selenium.remote.http.HttpMethod;
import org.openqa.selenium.remote.service.DriverCommandExecutor;
import org.openqa.selenium.remote.service.DriverService;

import java.nio.file.Path;
import java.util.Objects;
import java.util.Set;

/**
 * An implementation of the {#link WebDriver} interface that drives Firefox.
 *

 * The best way to construct a {@code FirefoxDriver} with various options is to make use of the
 * {@link FirefoxOptions}, like so:
 *
 *

 *FirefoxOptions options = new FirefoxOptions()
 *    .setProfile(new FirefoxProfile());
 *WebDriver driver = new FirefoxDriver(options);
 *

 */
public class FirefoxDriver extends RemoteWebDriver implements WebStorage, HasExtensions {

  public static final class SystemProperty {

    /**
     * System property that defines the location of the Firefox executable file.
     */
    public static final String BROWSER_BINARY = "webdriver.firefox.bin";

    /**
     * System property that defines the location of the file where Firefox log should be stored.
     */
    public static final String BROWSER_LOGFILE = "webdriver.firefox.logfile";

    /**
     * System property that defines the additional library path (Linux only).
     */
    public static final String BROWSER_LIBRARY_PATH = "webdriver.firefox.library.path";

    /**
     * System property that defines the profile that should be used as a template.
     * When the driver starts, it will make a copy of the profile it is using,
     * rather than using that profile directly.
     */
    public static final String BROWSER_PROFILE = "webdriver.firefox.profile";

    /**
     * System property that defines the location of the webdriver.xpi browser extension to install
     * in the browser. If not set, the prebuilt extension bundled with this class will be used.
     */
    public static final String DRIVER_XPI_PROPERTY = "webdriver.firefox.driver";

    /**
     * Boolean system property that instructs FirefoxDriver to use Marionette backend,
     * overrides any capabilities specified by the user
     */
    public static final String DRIVER_USE_MARIONETTE = "webdriver.firefox.marionette";
  }

  public static final String BINARY = "firefox_binary";
  public static final String PROFILE = "firefox_profile";
  public static final String MARIONETTE = "marionette";

  private static class ExtraCommands {
    static String INSTALL_EXTENSION = "installExtension";
    static String UNINSTALL_EXTENSION = "uninstallExtension";
  }

  private static final ImmutableMap<String, CommandInfo> EXTRA_COMMANDS = ImmutableMap.of(
      ExtraCommands.INSTALL_EXTENSION,
      new CommandInfo("/session/:sessionId/moz/addon/install", HttpMethod.POST),
      ExtraCommands.UNINSTALL_EXTENSION,
      new CommandInfo("/session/:sessionId/moz/addon/uninstall", HttpMethod.POST)
  );

  private static class FirefoxDriverCommandExecutor extends DriverCommandExecutor {
    public FirefoxDriverCommandExecutor(DriverService service) {
      super(service, EXTRA_COMMANDS);
    }
  }

  protected FirefoxBinary binary;
  private RemoteWebStorage webStorage;

  public FirefoxDriver() {
    this(new FirefoxOptions());
  }

  /**
   * @deprecated Use {@link #FirefoxDriver(FirefoxOptions)}.
   */
  @Deprecated
  public FirefoxDriver(Capabilities desiredCapabilities) {
    this(new FirefoxOptions(Objects.requireNonNull(desiredCapabilities, "No capabilities seen")));
  }

  /**
   * @deprecated Use {@link #FirefoxDriver(GeckoDriverService, FirefoxOptions)}.
   */
  @Deprecated
  public FirefoxDriver(GeckoDriverService service, Capabilities desiredCapabilities) {
    this(
        Objects.requireNonNull(service, "No geckodriver service provided"),
        new FirefoxOptions(desiredCapabilities));
  }

  public FirefoxDriver(FirefoxOptions options) {
    super(toExecutor(options), dropCapabilities(options));
    webStorage = new RemoteWebStorage(getExecuteMethod());
  }

  public FirefoxDriver(GeckoDriverService service) {
    super(new FirefoxDriverCommandExecutor(service), new FirefoxOptions());
    webStorage = new RemoteWebStorage(getExecuteMethod());
  }

  public FirefoxDriver(XpiDriverService service) {
    super(new FirefoxDriverCommandExecutor(service), new FirefoxOptions());
    webStorage = new RemoteWebStorage(getExecuteMethod());
  }

  public FirefoxDriver(GeckoDriverService service, FirefoxOptions options) {
    super(new FirefoxDriverCommandExecutor(service), dropCapabilities(options));
    webStorage = new RemoteWebStorage(getExecuteMethod());
  }

  public FirefoxDriver(XpiDriverService service, FirefoxOptions options) {
    super(new FirefoxDriverCommandExecutor(service), dropCapabilities(options));
    webStorage = new RemoteWebStorage(getExecuteMethod());
  }

  private static CommandExecutor toExecutor(FirefoxOptions options) {
    Objects.requireNonNull(options, "No options to construct executor from");
    DriverService.Builder<?, ?> builder;

    if (! Boolean.parseBoolean(System.getProperty(SystemProperty.DRIVER_USE_MARIONETTE, "true"))
        || options.isLegacy()) {
      FirefoxProfile profile = options.getProfile();
      if (profile == null) {
        profile = new FirefoxProfile();
        options.setCapability(FirefoxDriver.PROFILE, profile);
      }
      builder = XpiDriverService.builder()
          .withBinary(options.getBinary())
          .withProfile(profile);
    } else {
      builder = new GeckoDriverService.Builder()
          .usingFirefoxBinary(options.getBinary());
    }

    return new FirefoxDriverCommandExecutor(builder.build());
  }

  @Override
  public void setFileDetector(FileDetector detector) {
    throw new WebDriverException(
        "Setting the file detector only works on remote webdriver instances obtained " +
        "via RemoteWebDriver");
  }

  @Override
  public LocalStorage getLocalStorage() {
    return webStorage.getLocalStorage();
  }

  @Override
  public SessionStorage getSessionStorage() {
    return webStorage.getSessionStorage();
  }

  private static boolean isLegacy(Capabilities desiredCapabilities) {
    Boolean forceMarionette = forceMarionetteFromSystemProperty();
    if (forceMarionette != null) {
      return !forceMarionette;
    }
    Object marionette = desiredCapabilities.getCapability(MARIONETTE);
    return marionette instanceof Boolean && ! (Boolean) marionette;
  }

  @Override
  public String installExtension(Path path) {
    return (String) execute(ExtraCommands.INSTALL_EXTENSION,
                            ImmutableMap.of("path", path.toAbsolutePath().toString(),
                                            "temporary", false)).getValue();
  }

  @Override
  public void uninstallExtension(String extensionId) {
    execute(ExtraCommands.UNINSTALL_EXTENSION, singletonMap("id", extensionId));
  }

  private static Boolean forceMarionetteFromSystemProperty() {
    String useMarionette = System.getProperty(SystemProperty.DRIVER_USE_MARIONETTE);
    if (useMarionette == null) {
      return null;
    }
    return Boolean.valueOf(useMarionette);
  }

  /**
   * Drops capabilities that we shouldn't send over the wire.
   *
   * Used for capabilities which aren't BeanToJson-convertable, and are only used by the local
   * launcher.
   */
  private static Capabilities dropCapabilities(Capabilities capabilities) {
    if (capabilities == null) {
      return new ImmutableCapabilities();
    }

    MutableCapabilities caps;

    if (isLegacy(capabilities)) {
      final Set<String> toRemove = Sets.newHashSet(BINARY, PROFILE);
      caps = new MutableCapabilities(
          Maps.filterKeys(capabilities.asMap(), key -> !toRemove.contains(key)));
    } else {
      caps = new MutableCapabilities(capabilities);
    }

    // Ensure that the proxy is in a state fit to be sent to the extension
    Proxy proxy = Proxy.extractFrom(capabilities);
    if (proxy != null) {
      caps.setCapability(PROXY, proxy);
    }

    return caps;
  }
}


text:
package helpers

import (
	"context"
	"fmt"
	"os"

	chunk "github.com/ipfs/go-ipfs/importer/chunk"
	dag "github.com/ipfs/go-ipfs/merkledag"
	pi "github.com/ipfs/go-ipfs/thirdparty/posinfo"
	ft "github.com/ipfs/go-ipfs/unixfs"

	node "gx/ipfs/QmU7bFWQ793qmvNy7outdCaMfSDNk8uqhx4VNrxYj5fj5g/go-ipld-node"
)

// BlockSizeLimit specifies the maximum size an imported block can have.
var BlockSizeLimit = 1048576 // 1 MB

// rough estimates on expected sizes
var roughDataBlockSize = chunk.DefaultBlockSize
var roughLinkBlockSize = 1 << 13 // 8KB
var roughLinkSize = 34 + 8 + 5   // sha256 multihash + size + no name + protobuf framing

// DefaultLinksPerBlock governs how the importer decides how many links there
// will be per block. This calculation is based on expected distributions of:
//  * the expected distribution of block sizes
//  * the expected distribution of link sizes
//  * desired access speed
// For now, we use:
//
//   var roughLinkBlockSize = 1 << 13 // 8KB
//   var roughLinkSize = 288          // sha256 + framing + name
//   var DefaultLinksPerBlock = (roughLinkBlockSize / roughLinkSize)
//
// See calc_test.go
var DefaultLinksPerBlock = (roughLinkBlockSize / roughLinkSize)

// ErrSizeLimitExceeded signals that a block is larger than BlockSizeLimit.
var ErrSizeLimitExceeded = fmt.Errorf("object size limit exceeded")

// UnixfsNode is a struct created to aid in the generation
// of unixfs DAG trees
type UnixfsNode struct {
	raw     bool
	rawnode *dag.RawNode
	node    *dag.ProtoNode
	ufmt    *ft.FSNode
	posInfo *pi.PosInfo
}

// NewUnixfsNode creates a new Unixfs node to represent a file
func NewUnixfsNode() *UnixfsNode {
	return &UnixfsNode{
		node: new(dag.ProtoNode),
		ufmt: &ft.FSNode{Type: ft.TFile},
	}
}

// NewUnixfsBlock creates a new Unixfs node to represent a raw data block
func NewUnixfsBlock() *UnixfsNode {
	return &UnixfsNode{
		node: new(dag.ProtoNode),
		ufmt: &ft.FSNode{Type: ft.TRaw},
	}
}

// NewUnixfsNodeFromDag reconstructs a Unixfs node from a given dag node
func NewUnixfsNodeFromDag(nd *dag.ProtoNode) (*UnixfsNode, error) {
	mb, err := ft.FSNodeFromBytes(nd.Data())
	if err != nil {
		return nil, err
	}

	return &UnixfsNode{
		node: nd,
		ufmt: mb,
	}, nil
}

func (n *UnixfsNode) NumChildren() int {
	return n.ufmt.NumChildren()
}

func (n *UnixfsNode) Set(other *UnixfsNode) {
	n.node = other.node
	n.raw = other.raw
	n.rawnode = other.rawnode
	if other.ufmt != nil {
		n.ufmt.Data = other.ufmt.Data
	}
}

func (n *UnixfsNode) GetChild(ctx context.Context, i int, ds dag.DAGService) (*UnixfsNode, error) {
	nd, err := n.node.Links()[i].GetNode(ctx, ds)
	if err != nil {
		return nil, err
	}

	pbn, ok := nd.(*dag.ProtoNode)
	if !ok {
		return nil, dag.ErrNotProtobuf
	}

	return NewUnixfsNodeFromDag(pbn)
}

// addChild will add the given UnixfsNode as a child of the receiver.
// the passed in DagBuilderHelper is used to store the child node an
// pin it locally so it doesnt get lost
func (n *UnixfsNode) AddChild(child *UnixfsNode, db *DagBuilderHelper) error {
	n.ufmt.AddBlockSize(child.FileSize())

	childnode, err := child.GetDagNode()
	if err != nil {
		return err
	}

	// Add a link to this node without storing a reference to the memory
	// This way, we avoid nodes building up and consuming all of our RAM
	err = n.node.AddNodeLinkClean("", childnode)
	if err != nil {
		return err
	}

	_, err = db.batch.Add(childnode)
	if err != nil {
		return err
	}

	return nil
}

// Removes the child node at the given index
func (n *UnixfsNode) RemoveChild(index int, dbh *DagBuilderHelper) {
	n.ufmt.RemoveBlockSize(index)
	n.node.SetLinks(append(n.node.Links()[:index], n.node.Links()[index+1:]...))
}

func (n *UnixfsNode) SetData(data []byte) {
	n.ufmt.Data = data
}

func (n *UnixfsNode) FileSize() uint64 {
	if n.raw {
		return uint64(len(n.rawnode.RawData()))
	}
	return n.ufmt.FileSize()
}

func (n *UnixfsNode) SetPosInfo(offset uint64, fullPath string, stat os.FileInfo) {
	n.posInfo = &pi.PosInfo{offset, fullPath, stat}
}

// getDagNode fills out the proper formatting for the unixfs node
// inside of a DAG node and returns the dag node
func (n *UnixfsNode) GetDagNode() (node.Node, error) {
	nd, err := n.getBaseDagNode()
	if err != nil {
		return nil, err
	}

	if n.posInfo != nil {
		return &pi.FilestoreNode{
			Node:    nd,
			PosInfo: n.posInfo,
		}, nil
	}

	return nd, nil
}

func (n *UnixfsNode) getBaseDagNode() (node.Node, error) {
	if n.raw {
		return n.rawnode, nil
	}

	data, err := n.ufmt.GetBytes()
	if err != nil {
		return nil, err
	}
	n.node.SetData(data)
	return n.node, nil
}


text:
#ifndef _ROLE_H
#define _ROLE_H

#include "WDModule.h"
#include "Registry.h"
#include "Tracer.h"

class Session;
class Context;

class RolesModule: public WDModule {
public:
	RolesModule(const char *name) :
		WDModule(name) {
	}
	virtual bool Init(const ROAnything config);
	virtual bool ResetFinis(const ROAnything);
	virtual bool Finis();
};

/*!abstraction of authentication level and manager of the sites possible navigation paths for this level
A role represents the authentication level a session has.
A request is always checked against the necessary authentication level a session must have.
If it fails, reauthentication is required before processing the request.
It manages the possible navigation paths a user can have according to his authentication levels.
The default algorithm in GetNewPageName uses a Map defined in the role's configuration.
This configuration defines mappings from a transition token to a new page name, optionally defining a preprocess action */
class Role: public HierarchConfNamed {
public:
	/*! @copydoc RegisterableObject::RegisterableObject(const char *) */
	Role(const char *name) :
		HierarchConfNamed(name) {
	}
    /*! use Map from config to determine new page name, implements a state machine
	 subclasses use hook DoGetNewPageName if they implement the state machine
	 other than from the Role's configuration
	 \param c the context that might be used for additional decision
	 \param transition direction to go in state machine (2nd index to map)
	 \param pagename page we come from (1st index to map) and page we go to if true
	 \return true if pagename is set, false if transition couldn't find a page */
	virtual bool GetNewPageName(Context & c, String & transition, String & pagename) const;
	/*! get the action page map config from the role's configuration file
	 \param entry token-specific config from map or Null if not defined
	 \param transition direction to go in state machine (2nd index to map)
	 \param pagename page we come from (1st index to map) and page we go to if true
	 \return true if corresponding token-config was found */
	bool GetNextActionConfig(ROAnything & entry, String & transition, String & pagename) const;
	/*! check if the given transition is a StayOnSamePage-token
	 These tokens can be specified on a per Role basis using the slot StayOnSamePageTokens
	 \param transition token to check
	 \return true if the given token was defined as StayOnSamePage token */
	bool IsStayOnSamePageToken(String & transition) const;
	//!copies information from query or query["fields"] into the tmp store; if they are not already defined there; this takes place before processing the request
	virtual void PrepareTmpStore(Context & c); // copies state contained in the query to the TmpStore
	//!copies information from the tmp store into the query according to a StateFull list defined in the role's configuration
	virtual void CollectLinkState(Anything & a, Context & c); // copies state contained in the TmpStore to the URLState
	// manage 'role store' in session after creation or relogin
	virtual bool Init(Context & c);
	//!clean up role store in Session s, hook for subclasses as a replacement for destructor
	virtual void Finis(Session & s, Role *newrole);
	//!hook to synchronize the rolestore with the required content to process the query at hand; default implementation does nothing
	virtual bool Synchronize(Context & c) const;
	//! test if this role is valid and if the query is well formed for the role
	bool Verify(Context & c, String & transition, String & pagename) const;
	/*! return the session timeout value for this role
	 This is retrieved from the roles configuration slot "SessionTimeout", if not configured the default is 60 seconds. Configuration hierarchy is used
	 \return session timeout value for this role */
	virtual long GetTimeout() const;
	RegCacheDef(Role);

	//! Like Role, but when FindRole(role_name) fails, try FileRole(dflt)
	static Role *FindRoleWithDefault(const char *role_name, Context &ctx, const char *dflt = "Role");

	/*! Default implementation of DefaultRole mechanism, renders content of /DefaultRole slot */
	static String GetDefaultRoleName(Context &ctx);

	String GetRequestRoleName(Context &ctx, String const &transition) const {
		return DoGetRequestRoleName(ctx, transition);
	}
    /*! Get a number of the given Role's hierarchy depth, based on the configured hierarchy
	 * @param pRole Role to get the level for
	 * @return number which tells how many hierarchy levels we are away from the top level Role, or -1 if given Role is not valid
	 */
	static long GetRoleLevel(const Role *pRole);

	static const char* gpcCategory;
	static const char* gpcConfigPath;

protected:
	/*! @copydoc IFAObject::Clone(Allocator *) */
	IFAObject *Clone(Allocator *a) const {
		return new (a) Role(fName);
	}
	/*! security API hooks for subclasses
	 Checks role levels by name. Default implementation uses the role hierarchy to find mismatches.
	 \param name the name of the role we want to test for its level
	 \return returns false if this doesn't have privileges of role with name */
	virtual bool CheckLevel(const String &name) const;

	//! Subclass hook to verify Role
	/*!	Default implementation does nothing and returns true
	 * @param c Context that might be used for decision
	 * @param transition Current direction to go
	 * @param pagename Page we come from
	 * @return true always */
	virtual bool DoVerify(Context &c, String &transition, String &pagename) const;

	/*! check if the transition/action is valid for this role, regardless of the rest
	 default implementation allows "Logout" for all roles
	 \param transition paramater from query["action"] (called action for historical reasons) */
	virtual bool TransitionAlwaysOK(const String &transition) const;

	virtual String DoGetRequestRoleName(Context &ctx, String const &transition) const;
};

#define RegisterRole(name) RegisterObject(name, Role)

#endif


text:
import createDebug from 'debug'
import {parse as parseUrl} from 'url'

const debug = createDebug('clebert:error')

const handleError = (ctx, error, {
  createErrorMessage = ({message}) => ({error: message}),
  errorPageUrl = '/oops',
  shouldRedirectToErrorPage = ({originalUrl}) => {
    const {pathname} = parseUrl(originalUrl)

    return ![/^\/api\//, /^\/assets\//, /^\/oops\/?$/].some(re => re.test(pathname))
  }
} = {}) => {
  try {
    if (errorPageUrl && shouldRedirectToErrorPage(ctx)) {
      ctx.status = 302

      debug(ctx.format(`${ctx.status} redirect to ${errorPageUrl}`))

      ctx.redirect(errorPageUrl)
    } else {
      debug(ctx.format(`respond with status code ${ctx.status}`))

      ctx.body = createErrorMessage(ctx, error)
    }
  } catch (error) {
    debug(ctx.format('error handling failed'))

    ctx.status = 500

    ctx.body = ctx.message
  }
}

export default options => async (ctx, next) => {
  try {
    await next()

    const {status} = ctx

    if (status >= 400) {
      debug(ctx.format(`handle status code ${status}`))

      handleError(ctx, null, options)
    }
  } catch (error) {
    debug(ctx.format(`handle ${(error ? error.stack : '') || 'unknown error'}`))

    ctx.status = error.status || 500

    handleError(ctx, error, options)
  }
}


text:
// Type definitions for netconf 2.0
// Project: https://github.com/darylturner/node-netconf
// Definitions by: Leodinas Hao <https://github.com/leodinas-hao>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

export class Client {
  /**
   * Creates a new Client object by passing in the connection parameters. Both password and private key authentication methods are supported
   */
  constructor(params: {
    host: string,
    username: string,
    port?: number | undefined,
    password?: string | undefined,
    pkey?: string | undefined,
  })

  /**
   * Opens a session
   */
  open(callback: ((err: any) => void)): void;

  /**
   * Sends requests. Requests are sent using the .rpc() method
   */
  rpc(request: any, callback: ((err: any, reply: any) => void)): void;

  /**
   * Closes the session
   */
  close(callback?: (err: any) => void): void;

  /**
   * Collects some useful information from several RPC calls and presents the results back
   */
  facts(callback: ((err: any, facts: { hostname: string, version: string, module: string, uptime: string, serial: string }) => void)): void;

  /**
   * Loads configuration data into candidate-config using NETCONF. Default options are equivalent to "load merge" and would expect configuration data in JunOS curly-brace format
   */
  load(args: string | { config: any, action?: 'merge' | 'replace' | 'override' | 'update' | 'set' | undefined, format?: 'text' | 'xml' | undefined }, callback: (err: any, reply: any) => void): void;

  /**
   * Commits candidate configuration to device
   */
  commit(callback: ((err: any, reply: any) => void)): void;

  /**
   * Shows difference between running and candidate-config. Equivalent to "show | compare".
   */
  compare(callback: ((err: any, diff: any) => void)): void;

  /**
   * Discards candidate configuration on device
   */
  rollback(callback: ((err: any, reply: any) => void)): void;
}


text:
package mx.infotec.dads.sekc.admin.kernel.rest.util;

import org.springframework.http.HttpStatus;

/**
 *
 * @author wisog
 */
public class ResponseWrapper {

    private HttpStatus responseCode;

    private String errorMessage = "";

    private Object responseObject;

    public void setResponseCode(HttpStatus responseCode) {
        this.responseCode = responseCode;
    }

    public HttpStatus getResponseCode() {
        return responseCode;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setResponseObject(Object responseObject) {
        this.responseObject = responseObject;
    }

    public Object getResponseObject() {
        return responseObject;
    }

    @Override
    public String toString() {
        return "{ \"error_message\":\"" + errorMessage + "\", \"data\":" + responseObject + '}';
    }
}


text:
Package.describe({
  name: 'tap:i18n-db',
  summary: 'Internationalization for Meteor Collections',
  version: '0.4.0',
  git: 'https://github.com/TAPevents/tap-i18n-db'
});

Package.on_use(function (api) {
  api.versionsFrom('METEOR@0.9.1');

  api.use(["coffeescript", "underscore", "meteor", "jquery", "reactive-dict"], ['server', 'client']);

  api.use("autopublish", ['server', 'client'], {weak: true})

  api.use('tap:i18n@1.0.3', ['client', 'server']);
  api.imply('tap:i18n', ['client', 'server']);

  api.use('yogiben:admin@1.1.0', {weak: true});

  api.add_files('globals.js', ['client', 'server']);
  api.add_files('tap_i18n_db-common.coffee', ['client', 'server']);
  api.add_files('tap_i18n_db-server.coffee', 'server');
  api.add_files('tap_i18n_db-client.coffee', 'client');
});