text:
package qrhl

import java.io.PrintWriter
import java.nio.file.attribute.FileTime
import java.nio.file.{Files, NoSuchFileException, Path, Paths}
import java.util
import org.log4s
import isabellex.{IsabelleX, RichTerm}
import qrhl.logic._
import qrhl.toplevel.{Command, Parser, ParserContext, Toplevel}
import de.unruh.isabelle.control
import control.IsabelleMLException
import qrhl.State.logger

import scala.collection.mutable
import hashedcomputation.{Hash, HashTag, Hashable, HashedValue, RawHash}
import org.apache.commons.codec.binary.Hex
import IsabelleX.{ContextX, globalIsabelle => GIsabelle}
import GIsabelle.Ops
import de.unruh.isabelle.mlvalue.MLValue
import de.unruh.isabelle.pure.Typ
import hashedcomputation.filesystem.FingerprintedDirectorySnapshot
import scalaz.Scalaz.ToIdOps

// Implicits
import de.unruh.isabelle.mlvalue.Implicits._
import de.unruh.isabelle.pure.Implicits._
import qrhl.isabellex.MLValueConverters.Implicits._
import scala.concurrent.ExecutionContext.Implicits._
import GIsabelle.isabelleControl
import hashedcomputation.Implicits._
import qrhl.isabellex.Implicits._

trait Tactic extends HashedValue {
  def apply(state: State, goal : Subgoal)(implicit output: PrintWriter) : List[Subgoal]
}

class UserException private (private val msg:String, private var _position:String=null, private var _log:String=null) extends RuntimeException(msg) {
  /** Sets the position if no position set yet. Does nothing if `position == null`. */
  def setPosition(position:String): Unit =
    if (_position==null)
      _position = position

  /** Sets the log if no log set yet. Does nothing if `log == null`. */
  def setLog(log:String): Unit =
    if (_log==null)
      _log = log

  def position : String = _position
  def log : String = _log
  def positionMessage : String =
    if (position != null && position != "<terminal>")
      s"$position: $msg"
    else
      msg
}
object UserException {
  private val logger = log4s.getLogger

  def apply(msg: String) = new UserException(msg)
  def apply(e: IsabelleMLException, position: String = null, log: String = null): UserException = {
//    logger.debug(s"Failing operation: operation ${e.operation} with input ${e.input}")
    val e2 = UserException("(in Isabelle) "+IsabelleX.symbols.symbolsToUnicode(e.getMessage))
    e2.setPosition(position)
    e2.setLog(log)
    e2
  }
}

/** A path together with a last-modification time and content hash. */
class FileTimeStamp(val file:Path) {
  import FileTimeStamp.logger

  private var time = FileTimeStamp.getLastModifiedTime(file)
  private val hash = Utils.hashFile(file)
  /** Returns whether the file (content) has changed since the FileTimeStamp was created.
   * Uses the last modification time as a shortcut – the assumption is that
   * the content will be unmodified if the time is */
  def changed : Boolean =
    if (time==FileTimeStamp.getLastModifiedTime(file))
      false
    else {
      val newHash = Utils.hashFile(file)
      if (util.Arrays.equals(hash,newHash)) {
        time = FileTimeStamp.getLastModifiedTime(file)
        false
      } else {
        logger.debug(s"File change detected: ${Hex.encodeHexString(hash)} -> ${Hex.encodeHexString(newHash)}")
        true
      }
    }

  override def toString: String = s"$file@$time@${Hex.encodeHexString(hash).substring(0,8)}"
}
object FileTimeStamp {
  private val logger = log4s.getLogger
  def getLastModifiedTime(file:Path): FileTime = try
    Files.getLastModifiedTime(file)
  catch {
    case _ : NoSuchFileException => FileTime.fromMillis(-1)
  }
}

class CheatMode private (
                    private val cheatAtAll : Boolean, // whether any cheating should happen at all
                    private val cheatInProof : Boolean, // cheating till the end of the current proof
                    private val cheatInFile : Boolean, // cheating till the end of current file
                    private val inInclude : Boolean // in included file
                    ) extends HashedValue {
//  assert(includeLevel >= 0)
//  def endInclude = new CheatMode(cheatAtAll=cheatAtAll, cheatInProof=cheatInProof, cheatInFile=false, includeLevel=includeLevel-1)
  def endProof = new CheatMode(cheatAtAll=cheatAtAll, cheatInProof=false, cheatInFile=cheatInFile, inInclude=inInclude)
  def cheating: Boolean = cheatAtAll && (cheatInFile || cheatInProof || inInclude)
  def startCheatInProof = new CheatMode(cheatAtAll=cheatAtAll, cheatInProof=true, cheatInFile=cheatInFile, inInclude=inInclude)
  def startCheatInFile = new CheatMode(cheatAtAll=cheatAtAll, cheatInProof=cheatInProof, cheatInFile=true, inInclude=inInclude)
  def startInclude = new CheatMode(cheatAtAll=cheatAtAll, cheatInProof=cheatInProof, cheatInFile=cheatInFile, inInclude=true)
  def stopCheatInFile(inProof:Boolean) = new CheatMode(cheatAtAll=cheatAtAll,
    cheatInProof=cheatInProof || (inProof && cheatInFile),
    cheatInFile=false, inInclude=inInclude)

  override def hash: Hash[CheatMode.this.type] =
    HashTag()(Hashable.hash(cheatAtAll), Hashable.hash(cheatInFile), Hashable.hash(cheatInProof), Hashable.hash(inInclude))
}

object CheatMode {
  def make(cheatAtAll:Boolean): CheatMode = new CheatMode(cheatAtAll=cheatAtAll,false,false,false)
}

class State private (val environment: Environment,
                     val goal: Goal,
                     val currentLemma: Option[(String,RichTerm)],
                     private val _isabelle: Option[IsabelleX.ContextX],
                     private val _isabelleTheory: List[Path],
//                     val dependencies: List[FileTimeStamp],
                     /** Absolute path */
                     val currentDirectory: Path,
                     val cheatMode : CheatMode,
                     val includedFiles : Set[Path],
                     val lastOutput : String,
                     _hash : Hash[State])
    extends HashedValue {
  def applyIsabelleToplevelCommand(command: String): State = {
    if (currentLemma.isDefined)
      throw UserException(s"""Isabelle commands are only possible outside a proof. Maybe you intended to use "isa ${command}."?""")
    val newContext = Ops.applyToplevelCommand(isabelle.context, IsabelleX.symbols.unicodeToSymbols(command)).retrieveNow
    copy(isabelle = Some(new ContextX(isabelle.isabelle, newContext)),
      hash = HashTag()(hash, Hashable.hash(command)))
  }

  def focusOrUnfocus(selector: Option[SubgoalSelector], focusVariant: String): State = {
    if (cheatMode.cheating)
      copy(goal=Goal.empty, hash=HashTag()(hash))
    else if (currentLemma.isEmpty)
      throw UserException("No pending proof")
    else
      copy(goal = goal.focusOrUnfocus(selector, focusVariant),
        hash = HashTag()(hash, Hashable.hash(focusVariant)))
  }

  val hash: Hash[this.type] = _hash.asInstanceOf[Hash[this.type]]

//  private def HashTag()(hash)(implicit file: sourcecode.File, line: sourcecode.Line) : Hash[State] =
//    RawHash.hashString(s"State: $file:$line:${hash.hex}:empty")

//  private def HashTag()(hash,hashes: Hash[Any]*)(implicit file: sourcecode.File, line: sourcecode.Line): Hash[State] =
//    RawHash.hashString(s"State: $file:$line:${hash.hex}:${hashes.map(_.hex).mkString("")}")

//  private def HashTag()(hash,arguments: HashedValue*)(implicit file: sourcecode.File, line: sourcecode.Line): Hash[State] =
//    HashTag()(hash,arguments.map(_.hash) : _*)(file, line)

  def include(file: Path)(implicit output: PrintWriter, fs: FingerprintedDirectorySnapshot): State = {
    output.println("Including file "+file)
    val fullpath = currentDirectory.resolve(file)
//    val relpath = fs.relativize(fullpath)

    logger.debug(s"Including $fullpath")
    if (includedFiles.contains(fullpath)) {
      println(s"Already included $fullpath. Skipping.")
      this
    } else {
      val fileContent = fs.getFile(fullpath).getOrElse { throw UserException(s"File $file not found (relative to $currentDirectory)") }
      val state1 = this.copy(includedFiles = includedFiles + fullpath, cheatMode=cheatMode.startInclude,
        hash = HashTag()(this.hash, fileContent.hash))
      val state2 = Toplevel.computeStateFromFileContent(state1, fullpath, fileContent, fs, allowMultilineCommands = true)
//      val toplevel = Toplevel.makeToplevelFromState(state1, fs)
//      toplevel.run(fileContent, fullpath)
//      val state2 = toplevel.state
      val state3 = state2.copy(
        cheatMode = cheatMode, // restore original cheatMode
        currentDirectory = currentDirectory,  // restore original currentDirectory
        hash = HashTag()(state2.hash))
      state3
    }
  }

  private def setCheatMode(cheatMode: CheatMode): State = copy(cheatMode = cheatMode, hash = HashTag()(hash, Hashable.hash(cheatMode)))
  def cheatInFile: State = setCheatMode(cheatMode.startCheatInFile)
  def cheatInProof: State = setCheatMode(cheatMode.startCheatInProof)
  def stopCheating: State = setCheatMode(cheatMode.stopCheatInFile(currentLemma.isDefined))

  def isabelle: IsabelleX.ContextX = _isabelle match {
    case Some(isa) => isa
    case None => throw UserException(Parser.noIsabelleError)
  }
  def hasIsabelle: Boolean = _isabelle.isDefined

  def qed: State = {
    assert(currentLemma.isDefined)
    assert(goal.isProved)

    val (name,prop) = currentLemma.get
    val isa = if (name!="") _isabelle.map(_.addAssumption(name,prop.isabelleTerm)) else _isabelle
    // TODO: Base this on the state from the beginning of the proof, then the proof interna definitely won't affect the hash
    copy(isabelle=isa, currentLemma=None, cheatMode=cheatMode.endProof,
      hash = HashTag()(hash)
    )
  }

  private def containsDuplicates[A](seq: Seq[A]): Boolean = {
    val seen = new mutable.HashSet[A]()
    for (e <- seq) {
      if (seen.contains(e)) return true
      seen += e
    }
    false
  }

  def declareProgram(name: String, oracles: List[String], program: Block): State = {
    if (containsDuplicates(oracles))
      throw UserException("Oracles "+oracles.mkString(",")+" must not contain duplicates")

    for (x <- program.variablesDirect)
      if (!environment.variableExistsForProg(x))
        throw UserException(s"Undeclared variable $x in program")

    if (_isabelle.isEmpty) throw UserException("Missing isabelle command.")
    if (this.environment.variableExists(name))
      throw UserException(s"Name $name already used for a variable or program.")

    val decl = ConcreteProgramDecl(environment,name,oracles,program)
    val env1 = environment.declareProgram(decl)
    val isa = decl.declareInIsabelle(_isabelle.get)

//    val isa1 = _isabelle.get.declareVariable(name, if (oracles.isEmpty) Isabelle.programT else Isabelle.oracle_programT)

//    val isa2 = decl.getSimplifierRules.foldLeft(isa1) { (isa,rule) => isa.addAssumption("", rule.isabelleTerm, simplifier = true) }

    logger.debug(s"Program variables: ${env1.programs(name).variablesRecursive}")

    copy(environment = env1, isabelle=Some(isa),
      hash = HashTag()(hash, decl.hash))
  }

  def declareAdversary(name: String, free: Seq[Variable], inner: Seq[Variable], written: Seq[Variable], covered: Seq[Variable], overwritten: Seq[Variable], numOracles : Int): State = {
//    val isa1 = _isabelle.get.declareVariable(name,
//      if (numOracles==0) Isabelle.programT else Isabelle.oracle_programT)
    val decl = AbstractProgramDecl(name, free=free.toList,inner=inner.toList,written=written.toList,covered=covered.toList,overwritten=overwritten.toList, numOracles=numOracles)
    val isa = decl.declareInIsabelle(_isabelle.get)
//    val isa2 = decl.getSimplifierRules.foldLeft(isa1) { (isa,rule) => isa.addAssumption("", rule.isabelleTerm, simplifier = true) }
    val env1 = environment.declareProgram(decl)

    logger.debug(s"Program variables: ${env1.programs(name).variablesRecursive}")

    copy(environment = env1, isabelle=Some(isa),
      hash = HashTag()(hash, decl.hash))
  }

  def applyTactic(tactic:Tactic)(implicit output: PrintWriter) : State =
    if (cheatMode.cheating)
      copy(goal=Goal.empty, hash=HashTag()(hash))
    else if (goal.isProved)
      throw UserException("No pending proof")
    else {
      val newGoal = goal.applyTactic(this, tactic)
      copy(goal = newGoal,
        hash=HashTag()(hash, newGoal.hash))
    }

  private def copy(environment:Environment=environment,
                   goal:Goal=goal,
                   isabelle:Option[IsabelleX.ContextX]=_isabelle.map(_.force),
//                   dependencies:List[FileTimeStamp]=dependencies,
                   currentLemma:Option[(String,RichTerm)]=currentLemma,
                   currentDirectory:Path=currentDirectory,
                   cheatMode:CheatMode=cheatMode,
                   isabelleTheory:List[Path]=_isabelleTheory,
                   includedFiles:Set[Path]=includedFiles,
                   lastOutput:String=lastOutput,
                   hash: Hash[State]) : State =
    new State(environment=environment, goal=goal, _isabelle=isabelle, cheatMode=cheatMode,
      currentLemma=currentLemma, currentDirectory=currentDirectory,
      includedFiles=includedFiles, _isabelleTheory=isabelleTheory, lastOutput = lastOutput,
      _hash = hash)

  def changeDirectory(dir:Path): State = {
    assert(dir!=null)
    assert(dir.isAbsolute)
    if (dir==currentDirectory) return this
    if (!Files.isDirectory(dir)) throw UserException(s"Non-existent directory: $dir")
//    if (hasIsabelle) throw UserException("Cannot change directory after loading Isabelle")
    copy(currentDirectory=dir, hash = HashTag()(hash,Hashable.hash(dir)))
  }

  def setLastOutput(output: String): State =
    copy(lastOutput = output, hash = HashTag()(hash,Hashable.hash(output)))

  def openGoal(name:String, goal:Subgoal) : State = this.currentLemma match {
    case None =>
      goal.checkVariablesDeclared(environment)
      copy(goal=Goal(goal), currentLemma=Some((name,goal.toTerm(_isabelle.get))),
        hash = HashTag()(hash,Hashable.hash(name), goal.hash))
    case _ => throw UserException("There is still a pending proof.")
  }

  override def toString: String = if (cheatMode.cheating)
    "In cheat mode."
  else goal.longDescription

  lazy val parserContext: ParserContext = ParserContext(isabelle=_isabelle, environment=environment)

  def parseCommand(str:String): Command = {
    implicit val parserContext: ParserContext = this.parserContext
    Parser.parseAll(Parser.command,str) match {
      case Parser.Success(cmd2,_) => cmd2
      case res @ Parser.NoSuccess(msg, _) =>
        throw UserException(msg)
    }
  }

  def parseExpression(typ:Typ, str:String): RichTerm = {
    implicit val parserContext: ParserContext = this.parserContext
    Parser.parseAll(Parser.expression(typ),str) match {
      case Parser.Success(cmd2,_) => cmd2
      case res @ Parser.NoSuccess(msg, _) =>
        throw UserException(msg)
    }
  }

  def parseBlock(str:String): Block = {
    implicit val parserContext: ParserContext = this.parserContext
    Parser.parseAll(Parser.block,str) match {
      case Parser.Success(cmd2,_) => cmd2
      case res @ Parser.NoSuccess(msg, _) =>
        throw UserException(msg)
    }
  }

  def loadIsabelle(theory:Seq[String], session : Option[String])(implicit fs: FingerprintedDirectorySnapshot) : State = {
    assert(currentDirectory.isAbsolute)
    val theoryPath = theory.toList map { thy => currentDirectory.resolve(thy+".thy") }

    // In order to get snapshot exceptions before running Isabelle (saves time)
    for (t <- theoryPath) fs.getFile(t)

    if (_isabelle.isDefined)
      if (theoryPath != _isabelleTheory)
        throw UserException(s"Isabelle loaded twice with different theories: ${if (_isabelleTheory.isEmpty) "none" else _isabelleTheory.mkString(", ")} vs. ${if (theoryPath.isEmpty) "none" else theoryPath.mkString(", ")}")
      else
        return this

    // If currentDirectory (from where we initialize via "isabelle" command) contains ROOT or ROOTS, use it as additional session directory
    val sessionDirectory =
      currentDirectory.toAbsolutePath.normalize
        .into { d =>
          if (fs.getFile(d.resolve("ROOT")).isDefined || fs.getFile(d.resolve("ROOTS")).isDefined)
            Some(d) else None }

    val isabelle = IsabelleX.globalIsabelleWith(sessionDir = sessionDirectory, session = session)
    logger.debug(s"Paths of theories to load: $theoryPath")
    val (ctxt,deps) = isabelle.getQRHLContextWithFiles(theoryPath : _*)
    logger.debug(s"Dependencies of theory ${theory.mkString(", ")}: ${deps.mkString(", ")}")

    for (f <- deps) assert(f.isAbsolute)

//    val relDeps = deps.map(currentFS.relativize)

    // This ensures that even when one .get fails (and updates the Toplevel.rootDirectory), the others are
    // tried to (so all updates happen in one go).
    for (d <- deps) try { fs.getFile(d) } catch { case _ : Throwable => }

    val deps2 = for (file <- deps) yield {
//      val relfile = currentFS.relativize(file)
      val content = fs.getFile(file)
      logger.debug(s"$file -> $content")
      (file, content)
    }

    val newState = copy(isabelle = Some(ctxt), isabelleTheory=theoryPath,
      hash = HashTag()(hash,Hashable.hash(theory.toList), Hashable.hash(deps2)))
    // We declare a quantum variable aux :: infinite by default (for use in equal-tac, for example)
    newState.declareVariable("aux", GIsabelle.infiniteT, quantum = true)
  }

//  def filesChanged : List[Path] = {
//    dependencies.filter(_.changed).map(_.file)
//  }

  private def declare_quantum_variable(isabelle: IsabelleX.ContextX, name: String, typ: Typ) : IsabelleX.ContextX = {
    val ctxt = Ops.declare_quantum_variable(MLValue((name, typ, isabelle.context))).retrieveNow
    new ContextX(isabelle.isabelle, ctxt)
//    isabelle.map(id => isabelle.isabelle.invoke(State.declare_quantum_variable, (name,typ,id)))
  }

  private def declare_classical_variable(isabelle: IsabelleX.ContextX, name: String, typ: Typ) : IsabelleX.ContextX = {
    val ctxt = Ops.declare_classical_variable(MLValue((name, typ, isabelle.context))).retrieveNow
    new ContextX(isabelle.isabelle, ctxt)
//    isabelle.map(id => isabelle.isabelle.invoke(State.declare_classical_variable, (name,typ,id)))
  }

  def declareVariable(name: String, typ: Typ, quantum: Boolean = false): State = {
    val newEnv = environment.declareVariable(name, typ, quantum = quantum)
      .declareAmbientVariable("var_"+name, typ)
      .declareAmbientVariable("var_"+Variable.index1(name), typ)
      .declareAmbientVariable("var_"+Variable.index2(name), typ)
    if (_isabelle.isEmpty) throw UserException("Missing isabelle command.")
    val isa = _isabelle.get
    val newIsa =
      if (quantum)
        declare_quantum_variable(isa, name, typ)
      else
        declare_classical_variable(isa, name, typ)

    copy(environment = newEnv, isabelle = Some(newIsa),
      hash = HashTag()(hash, RawHash.hashString(name), Hashable.hash(typ), Hashable.hash(quantum)))
  }

  def declareAmbientVariable(name: String, typ: Typ): State = {
    val newEnv = environment.declareAmbientVariable(name, typ)
    if (_isabelle.isEmpty) throw UserException("Missing isabelle command.")
    val isa = _isabelle.get.declareVariable(name, typ)
    copy(environment = newEnv, isabelle = Some(isa),
      hash = HashTag()(hash, RawHash.hashString(name), Hashable.hash(typ)))
  }
}

object State {
  def empty(cheating:Boolean) = new State(environment=Environment.empty, goal=Goal.empty,
    _isabelle=None, _isabelleTheory=null,
//    dependencies=Nil,
    currentLemma=None, currentDirectory=Paths.get("").toAbsolutePath,
    cheatMode=CheatMode.make(cheating), includedFiles=Set.empty,
    lastOutput = "Ready.",
    _hash = HashTag()(Hashable.hash(cheating)))
//  private[State] val defaultIsabelleTheory = "QRHL"

  private val logger = log4s.getLogger
}


text:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace OrchardCore.Demo
{
    public class NonBlockingMiddleware
    {
        private readonly RequestDelegate _next;

        public NonBlockingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            // If the tenant pipeline is re-executed on error, the header is already set.
            httpContext.Response.Headers["Orchard"] = "2.0";
            await _next.Invoke(httpContext);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require_self
 *= require handyCSS.css

 *= require ux-libraries/bootstrap/bootstrap
 *= require ux-libraries/archon
 *= require ux-libraries/responsive
 *= require ux-libraries/prettify
 *= require ux-libraries/custom
 *= require ux-libraries/font-awesome
 */


text: search_result['4036']=["topic_00000000000009B1_events--.html","SubscriptionsDto Events",""];


text:
package main

import (
	"fmt"
	"log"
	"log/syslog"
	"os"
	"os/signal"
	"sort"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
	"github.com/aws/aws-sdk-go/aws/ec2metadata"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/hanwen/go-fuse/fuse"
	"github.com/hanwen/go-fuse/fuse/nodefs"
	"github.com/hanwen/go-fuse/fuse/pathfs"
	"github.com/hanwen/go-fuse/unionfs"
	"github.com/jessevdk/go-flags"
	"github.com/jszwedko/ec2-metadatafs/internal/logging"
	"github.com/jszwedko/ec2-metadatafs/metadatafs"
	"github.com/jszwedko/ec2-metadatafs/tagsfs"
	"github.com/sevlyar/go-daemon"
)

const (
	verbose     = 1
	moreVerbose = 2
)

var (
	// VersionString is the git tag this binary is associated with
	VersionString string

	facilityMap = map[string]syslog.Priority{
		"KERN":     syslog.LOG_KERN,
		"USER":     syslog.LOG_USER,
		"MAIL":     syslog.LOG_MAIL,
		"DAEMON":   syslog.LOG_DAEMON,
		"AUTH":     syslog.LOG_AUTH,
		"SYSLOG":   syslog.LOG_SYSLOG,
		"LPR":      syslog.LOG_LPR,
		"NEWS":     syslog.LOG_NEWS,
		"UUCP":     syslog.LOG_UUCP,
		"CRON":     syslog.LOG_CRON,
		"AUTHPRIV": syslog.LOG_AUTHPRIV,
		"FTP":      syslog.LOG_FTP,

		"LOCAL0": syslog.LOG_LOCAL0,
		"LOCAL1": syslog.LOG_LOCAL1,
		"LOCAL2": syslog.LOG_LOCAL2,
		"LOCAL3": syslog.LOG_LOCAL3,
		"LOCAL4": syslog.LOG_LOCAL4,
		"LOCAL5": syslog.LOG_LOCAL5,
		"LOCAL6": syslog.LOG_LOCAL6,
		"LOCAL7": syslog.LOG_LOCAL7,
	}
)

func sortedValidFacilities() []string {
	facilities := FacilityNamesSlice(make([]string, 0, len(facilityMap)))
	for k := range facilityMap {
		facilities = append(facilities, k)
	}
	sort.Sort(facilities)
	return facilities
}

// FacilityNamesSlice supports sorting of facility names
type FacilityNamesSlice []string

func (f FacilityNamesSlice) Len() int {
	return len(f)
}

func (f FacilityNamesSlice) Less(i, j int) bool {
	return facilityMap[f[i]] < facilityMap[f[j]]
}

func (f FacilityNamesSlice) Swap(i, j int) {
	f[i], f[j] = f[j], f[i]
}

// Options holds the command line arguments and flags
// Intended for use with go-flags
type Options struct {
	Verbose       []bool `short:"v" long:"verbose"     description:"Print verbose logs, can be specified multiple times (up to 2)"`
	Foreground    bool   `short:"f" long:"foreground"  description:"Run in foreground"`
	Version       bool   `short:"V" long:"version"     description:"Display version info"`
	EndpointAlias string `          long:"endpoint"    description:"Deprecated alias for --instance-metadata-service-endpoint"`

	MetadataServiceEndpoint string        `short:"e" long:"instance-metadata-service-endpoint"  description:"Instance Metadata Service HTTP endpoint" default:"http://169.254.169.254/latest/"`
	MetadataServiceVersion  string        `short:"m" long:"instance-metadata-service-version"   description:"Instance Metadata Service version" default:"v1" choice:"v1" choice:"v2"`
	MetadataServiceTokenTTL time.Duration `short:"T" long:"instance-metadata-service-token-ttl" description:"Instance Metadata Service token TTL (only valid for Instance Metadata Service version v2)" default:"6h"`

	CacheSec     int          `short:"c" long:"cachesec"    description:"Number of seconds to cache files attributes and directory listings. 0 to disable, -1 for indefinite." default:"0"`
	Tags         bool         `short:"t" long:"tags"        description:"Mount EC2 instance tags at <mount point>/tags"`
	MountOptions mountOptions `short:"o" long:"options"     description:"Mount options, see below for description"`

	DisableSyslog  bool   `short:"n" long:"no-syslog"        description:"Disable syslog when daemonized"`
	SyslogFacility string `short:"F" long:"syslog-facility"  description:"Syslog facility to use when daemonized (see below for options)" default:"USER"`

	AWSCredentials awsCredentials `group:"AWS Credentials (only used when mounting tags)"`

	Args struct {
		Mountpoint string `positional-arg-name:"mountpoint"   description:"Directory to mount the filesystem at"`
	} `positional-args:"yes"`
}

type awsCredentials struct {
	AWSAccessKeyID     string `long:"aws-access-key-id"     description:"AWS Access Key ID (adds to credential chain, see below)"`
	AWSSecretAccessKey string `long:"aws-secret-access-key" description:"AWS Secret Access key (adds to credential chain, see below)"`
	AWSSessionToken    string `long:"aws-session-token"     description:"AWS session token (adds to credential chain, see below)"`
}

func (a *awsCredentials) credentialChain() *credentials.Credentials {
	return credentials.NewChainCredentials([]credentials.Provider{
		&credentials.StaticProvider{
			Value: credentials.Value{
				AccessKeyID:     a.AWSAccessKeyID,
				SecretAccessKey: a.AWSSecretAccessKey,
				SessionToken:    a.AWSSessionToken,
			},
		},
		&credentials.EnvProvider{},
		&credentials.SharedCredentialsProvider{},
		&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
	})
}

// mountOptions implements flags.Marshaller and flags.Unmarshaller interface to
// read `mount` style options from the user
type mountOptions struct {
	opts []string
}

func (o *mountOptions) String() string {
	return strings.Join(o.opts, ",")
}

func (o *mountOptions) MarshalFlag() (string, error) {
	return o.String(), nil
}

func (o *mountOptions) UnmarshalFlag(s string) error {
	if o.opts == nil {
		o.opts = []string{}
	}

	o.opts = append(o.opts, strings.Split(s, ",")...)

	return nil
}

// ExtractOption deletes the option specified and returns whether the option
// was found and its value (if it has one)
// E.g. endpoint=http://example.com or allow_other
func (o *mountOptions) ExtractOption(s string) (ok bool, value string) {
	if o.opts == nil {
		o.opts = []string{}
	}

	index := -1
	for i, opt := range o.opts {
		parts := strings.SplitN(opt, "=", 2)

		if parts[0] != s {
			continue
		}

		index = i
		if len(parts) == 2 {
			value = parts[1]
		}
		break
	}

	if index != -1 {
		o.opts = append(o.opts[:index], o.opts[index+1:]...)
	}

	return index != -1, value
}

// mountTags mounts another endpoint onto the FUSE FS at tags/ exposing the EC2
// instance tags as files
func mountTags(nfs *pathfs.PathNodeFs, options *Options, logger *logging.Logger) {
	svc := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(options.MetadataServiceEndpoint)})
	instanceID, err := svc.GetMetadata("instance-id")
	if err != nil {
		logger.Fatalf("failed to query instance id to initialize tags mount: %v\n", err)
	}
	region, err := svc.Region()
	if err != nil {
		logger.Fatalf("failed to query instance region to initialize tags mount: %v\n", err)
	}

	sess := session.New(&aws.Config{
		Region:      aws.String(region),
		Credentials: options.AWSCredentials.credentialChain(),
	})

	status := nfs.Mount(
		"tags",
		pathfs.NewPathNodeFs(tagsfs.New(ec2.New(sess), instanceID, logger), nil).Root(), nil)
	if status != fuse.OK {
		logger.Fatalf("tags mount fail: %v\n", status)
	}
}

func prepareServer(options *Options, logger *logging.Logger) *fuse.Server {
	var fs pathfs.FileSystem

	logger.Debugf("mounting at %s directed at %s with options: %+v", options.Args.Mountpoint, options.MetadataServiceEndpoint, options.MountOptions.opts)
	var client metadatafs.MetadataClient
	switch options.MetadataServiceVersion {
	case "v1":
		client = metadatafs.NewIMDSv1Client(options.MetadataServiceEndpoint, logger)
	case "v2":
		client = metadatafs.NewIMDSv2Client(options.MetadataServiceEndpoint, options.MetadataServiceTokenTTL, logger)
	default:
		fmt.Printf("unknown --instance-medatata-service-version %s", options.MetadataServiceVersion)
		os.Exit(1)
	}
	fs = metadatafs.New(client, logger)
	switch {
	case options.CacheSec == 0:
		logger.Debugf("caching disabled")
	case options.CacheSec <= 0:
		logger.Debugf("indefinite caching enabled")
		fs = unionfs.NewCachingFileSystem(fs, time.Duration(-1)*time.Second)
	default:
		logger.Debugf("caching enabled (%d seconds)", options.CacheSec)
		fs = unionfs.NewCachingFileSystem(fs, time.Duration(options.CacheSec)*time.Second)
	}

	nfs := pathfs.NewPathNodeFs(fs, nil)
	server, err := fuse.NewServer(
		nodefs.NewFileSystemConnector(nfs.Root(), nil).RawFS(),
		options.Args.Mountpoint,
		&fuse.MountOptions{Options: options.MountOptions.opts})
	if err != nil {
		logger.Fatalf("mount fail: %v\n", err)
	}

	server.SetDebug(len(options.Verbose) >= moreVerbose)

	if options.Tags {
		go func() {
			server.WaitMount()
			logger.Debugf("mounting tags")
			mountTags(nfs, options, logger)
			logger.Debugf("tags mounted")
		}()
	}

	// Unmount when the process exits
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-ch
		err := server.Unmount()
		if err != nil {
			logger.Warningf("could not unmount: %s", err)
		}
		os.Exit(1)
	}()

	return server
}

// signal the parent of our process that we started successfully so it can exit
func sigalParent(logger *logging.Logger) {
	pid, err := strconv.Atoi(os.Getenv("EC2_METADATAFS_NOTIFY"))
	if err != nil {
		logger.Warningf("unable to decode parent pid for notification: %s", err)
		return
	}

	p, err := os.FindProcess(pid)
	if err != nil {
		logger.Warningf("unable to find parent pid for notification: %s", err)
		return
	}

	err = p.Signal(syscall.SIGUSR1)
	if err != nil {
		logger.Warningf("unable to find notify parent: %s", err)
	}
}

func waitForSignal(logger *logging.Logger) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGUSR1)

	select {
	case <-c:
		logger.Infof("child process successfully mounted")
	case <-time.After(time.Second * 5):
		logger.Fatalf("timeout waiting for child process to mount, try running in the foreground")
	}
}

func main() {
	options := &Options{}

	logger := logging.NewLogger()
	defer logger.Close()

	// go-fuse logging uses the stdlib logger
	debugWriter := logger.Writer(logging.DebugLevel)
	defer debugWriter.Close()
	log.SetOutput(debugWriter)
	log.SetFlags(0)

	parser := flags.NewParser(options, flags.HelpFlag|flags.PassDoubleDash)
	parser.LongDescription = `
ec2metadatafs mounts a FUSE filesystem which exposes the EC2 instance metadata
(and optionally the tags) of the host as files and directories rooted at the
given location.`

	_, err := parser.Parse()
	if err, ok := err.(*flags.Error); err != nil && (!ok || err.Type != flags.ErrHelp) {
		logger.Fatalf("error parsing command line options: %s", err)
	}

	if options.Version {
		fmt.Printf("%s\n", VersionString)
		os.Exit(0)
	}

	if parser.FindOptionByLongName("help").IsSet() {
		parser.WriteHelp(os.Stdout)
		fmt.Printf(`
Mount options:
  -o debug                                        Enable debug logging, same as -v
  -o fuse_debug                                   Enable fuse_debug logging (implies debug), same as -vv
  -o endpoint=ENDPOINT                            Deprecated alias for -o instance_metadata_service_endpoint=
  -o instance_metadata_service_endpoint=ENDPOINT  Instance metadata service HTTP endpoint, same as --instance-metadata-service-endpoint=
  -o instance_metadata_service_version=VERSION    Instance Metadata Service version, v1 or v2, same as --instance-metadata-service-version=
  -o instance_metadata_service_token_ttl=TTL      Instance Metadata Service token TTL, only valid with service_version=v2, same as --instance-metadata-service-token-ttl=
  -o tags                                          Mount the instance tags at <mount point>/tags, same as --tags
  -o aws_access_key_id=ID                         AWS API access key (see below), same as --aws-access-key-id=
  -o aws_secret_access_key=KEY                    AWS API secret key (see below), same as --aws-secret-access-key=
  -o aws_session_token=KEY                        AWS API session token (see below), same as --aws-session-token=
  -o cachesec=SEC                                 Number of seconds to cache files attributes and directory listings, same as --cachesec
  -o syslog_facility=                             Syslog facility to send messages upon when daemonized (see below)
  -o no_syslog                                    Disable logging to syslog when daemonized
  -o FUSEOPTION=OPTIONVALUE                       FUSE mount option, please see the OPTIONS section of your FUSE manual for valid options

AWS credential chain:
  AWS credentials only required when mounting the instance tags (--tags or -o tags).

  Checks for credentials in the following places, in order:

  - Provided AWS credentials via flags or mount options
  - $AWS_ACCESS_KEY_ID, $AWS_SECRET_ACCESS_KEY, and $AWS_SESSION_TOKEN environment variables
  - Shared credentials file -- respects $AWS_DEFAULT_PROFILE and $AWS_SHARED_CREDENTIALS_FILE
  - IAM role associated with the instance

  Note that the AWS session token is only needed for temporary credentials from AWS security token service.

Instance Metadata Service (IMDS) Version:

AWS has two modes for interacting with the metadata API:

* v1: request/response method (traditional)
* v2: session-oriented method (more secure)

If you are unsure, choose v2. The default is currently v1 for backwards compatibliity.

See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html for additional details.

Caching:

Caching of the following is supported and controlled via the cachesec parameter:

* File attributes
* Directory attributes
* Directory listings

When accessed this metadata will be cached for the number of seconds specified
by cachesec. Use 0, the default, to disable caching and -1 to cache
indefinitely (good if you never expect instance metadata to change). This cache
is kept in memory and lost when the process is restarted.

Valid syslog facilities:
  %s

Version:
  %s

Author:
  Jesse Szwedko

Project Homepage:
  http://github.com/jszwedko/ec2-metadatafs

Report bugs to:
  http://github.com/jszwedko/ec2-metadatafs/issues
`, strings.Join(sortedValidFacilities(), ", "), VersionString)
		os.Exit(0)
	}

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	if options.Args.Mountpoint == "" {
		fmt.Println("error parsing command line options: the required argument `mountpoint` was not provided")
		os.Exit(1)
	}

	// fallback to alias if set and the main option is not
	if parser.FindOptionByLongName("instance-metadata-service-endpoint").IsSetDefault() && parser.FindOptionByLongName("endpoint").IsSet() {
		options.MetadataServiceEndpoint = options.EndpointAlias
	}

	if ok, value := options.MountOptions.ExtractOption("endpoint"); ok {
		options.MetadataServiceEndpoint = value
	}

	// overrides -o endpoint=
	if ok, value := options.MountOptions.ExtractOption("instance_metadata_service_endpoint"); ok {
		options.MetadataServiceEndpoint = value
	}

	if ok, value := options.MountOptions.ExtractOption("aws_access_key_id"); ok {
		options.AWSCredentials.AWSAccessKeyID = value
	}

	if ok, value := options.MountOptions.ExtractOption("aws_secret_access_key"); ok {
		options.AWSCredentials.AWSSecretAccessKey = value
	}

	if ok, value := options.MountOptions.ExtractOption("aws_session_token"); ok {
		options.AWSCredentials.AWSSessionToken = value
	}

	if ok, value := options.MountOptions.ExtractOption("cachesec"); ok {
		options.CacheSec, err = strconv.Atoi(value)
		if err != nil {
			fmt.Printf("error parsing cachesec as integer: %s\n", err)
			os.Exit(1)
		}
	}

	if ok, _ := options.MountOptions.ExtractOption("tags"); ok {
		options.Tags = true
	}

	if ok, _ := options.MountOptions.ExtractOption("no_syslog"); ok {
		options.DisableSyslog = true
	}

	if ok, value := options.MountOptions.ExtractOption("syslog_facility"); ok {
		options.SyslogFacility = value
	}

	if ok, _ := options.MountOptions.ExtractOption("debug"); ok {
		options.Verbose = []bool{true}
	}

	if ok, _ := options.MountOptions.ExtractOption("fuse_debug"); ok {
		options.Verbose = []bool{true, true}
	}

	syslogFacility, ok := facilityMap[options.SyslogFacility]
	if !ok {
		logger.Fatalf("unrecognized syslog facility: %s", options.SyslogFacility)
	}

	if len(options.Verbose) >= verbose {
		logger.MinLevel = logging.DebugLevel
	}

	if options.Foreground {
		prepareServer(options, logger).Serve()
		return
	}

	// daemonize
	if !options.DisableSyslog {
		logger.EnableSyslog(syslogFacility)
	}

	context := &daemon.Context{Env: append(os.Environ(), fmt.Sprintf("EC2_METADATAFS_NOTIFY=%d", os.Getpid()))}

	child, err := context.Reborn()
	if err != nil {
		logger.Fatalf("fork fail: %s", err)
	}

	if child == nil {
		defer context.Release()

		server := prepareServer(options, logger)
		go func() {
			server.WaitMount()
			sigalParent(logger)
		}()
		server.Serve()
	} else {
		logger.Infof("forked child with PID %d", child.Pid)
		waitForSignal(logger)
	}
}


text:
/*
HEADER STUFF HERE
*/

window.FREE = (function(my) {
  'use strict';

  my.Battery = Battery;

  function Battery(name) {
    this.name = name;

    this.tests = {};
    this.currentTest = null;

    this.start = new Date();
    this.end = null;

    this.completed = false;
  }

  Battery.prototype.complete = complete;
  function complete() {
    if (this.currentTest) {
      this.endTest();
    }

    this.completed = true;
    this.end = new Date();
  }

  Battery.prototype.beginTest = beginTest;
  function beginTest(testName) {
    if (this.tests[testName] != null) {
      throw new Error('Test of name ' + testName + ' has already been used');
    }

    var test = new Test(testName);
    this.tests[testName] = test;
    this.currentTest = test;

    return test;
  }

  Battery.prototype.endTest = endTest;
  function endTest() {
    this.markCurrentTest();
    this.currentTest.complete();
    this.currentTest = null;
  }

  Battery.prototype.markCurrentTest = markCurrentTest;
  function markCurrentTest() {
    this.currentTest.addMark();
  }

  function Test(name) {
    this.name = name;

    this.start = new Date();
    this.lastMarkTime = this.start;

    this.marks = [];

    this.completed = false;
  }

  Test.prototype.addMark = addMark;
  function addMark() {
    var mark = new Mark(this.lastMarkTime);
    this.lastMarkTime = mark.time;
    this.marks.push(mark);
  }

  Test.prototype.complete = completeTest;
  function completeTest() {
    this.completed = true;
  }

  function Mark(time) {
    this.time = new Date();
    this.delta = (+(this.time)) - (+(time));
  }

  return my;
})(window.FREE || {});


text:
#ifndef QMULTIMEDIA_H
#define QMULTIMEDIA_H

#include <QtCore/qpair.h>
#include <QtCore/qmetatype.h>
#include <QtCore/qstring.h>

#include <QtMultimedia/qtmultimediadefs.h>

QT_BEGIN_NAMESPACE

namespace QMultimedia
{
    enum SupportEstimate
    {
        NotSupported,
        MaybeSupported,
        ProbablySupported,
        PreferredService
    };

    enum EncodingQuality
    {
        VeryLowQuality,
        LowQuality,
        NormalQuality,
        HighQuality,
        VeryHighQuality
    };

    enum EncodingMode
    {
        ConstantQualityEncoding,
        ConstantBitRateEncoding,
        AverageBitRateEncoding,
        TwoPassEncoding
    };

    enum AvailabilityStatus
    {
        Available,
        ServiceMissing,
        Busy,
        ResourceError
    };

}

QT_END_NAMESPACE

Q_DECLARE_METATYPE(QMultimedia::AvailabilityStatus)
Q_DECLARE_METATYPE(QMultimedia::SupportEstimate)
Q_DECLARE_METATYPE(QMultimedia::EncodingMode)
Q_DECLARE_METATYPE(QMultimedia::EncodingQuality)

#endif


text:
const config = require('./gocardless.json')
const GoCardless = require('../lib/index.js')
GoCardless.client(config.token, config.version, true)
console.log(`Running tests in sandbox mode (${GoCardless.client()._url})`)


text:
<?php
require 'vendor/autoload.php';

use ChromeDevTools\Chrome;

$chrome = new Chrome();

$chrome->Page->enable();
$chrome->Network->enable();

$chrome->Page->navigate(['url' => 'http://www.nytimes.com/']);
$chrome->waitEvent("Page.frameStoppedLoading", 10);
#Wait last objects to load
sleep(5);

$cookies = $chrome->Network->getCookies();
foreach ($cookies['result']['cookies'] as $cookie) {
    echo ("Cookie:");
    echo ("\tDomain:". $cookie["domain"]);
    echo ("\tKey:". $cookie["name"]);
    echo ("\tValue:". $cookie["value"]);
    echo ("\n");
}


text:
package com.inferno43.findme;

/**
 * Created by ${ mohanakrishnan.m} on 1/27/17.
 */

public interface BasePresenter {

    void start();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns	= "http://www.w3.org/ns/widgets"
    xmlns:gap	= "http://phonegap.com/ns/1.0"
    id		    = "com.phonegap.hydra"
		version 	= "__VERSION__">
  <name>Hydra</name>
  <description>
    Hydrate your PhoneGap app with assets from the cloud.
  </description>
  <author email="fil@adobe.com">
    Fil Maj
  </author>
	<icon src="img/icon-big.png" width="196" height="245" />
	<icon src="img/icon-small.png" width="77" height="96" />
  </widget>


text:
using System;
using System.Xml.Linq;

namespace Trigon.UI
{
    /// <summary>
    /// User interface markup language context.
    /// </summary>
    public sealed class MarkupContext
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MarkupContext" /> class.
        /// </summary>
        internal MarkupContext() { }

        /// <summary>
        /// Gets the target object.
        /// </summary>
        /// <value>The target object.</value>
        public object Target { get; internal set; }

        /// <summary>
        /// Gets the markup element.
        /// </summary>
        /// <value>The markup element.</value>
        public XElement Element { get; internal set; }

        /// <summary>
        /// Gets the property name.
        /// </summary>
        /// <value>The property name.</value>
        public string PropertyName { get; internal set; }

        /// <summary>
        /// Gets the property owner type.
        /// </summary>
        /// <value>The property owner type.</value>
        public Type PropertyOwner { get; internal set; }

        /// <summary>
        /// Parses a reference markup (i.g. prefix:Type.Property.Property).
        /// </summary>
        /// <param name="markup">The markup.</param>
        /// <returns>The parsed type and optional property path, or null if the markup could not be parsed.</returns>
        public Tuple<Type, string[]> Parse(string markup) => MarkupParser.Parse(markup, this.Element);
    }
}


text:
namespace device {

// Cast implementation of BluetoothTestBase.
class BluetoothTestCast : public BluetoothTestBase {
 public:
  BluetoothTestCast();

  BluetoothTestCast(const BluetoothTestCast&) = delete;
  BluetoothTestCast& operator=(const BluetoothTestCast&) = delete;

  ~BluetoothTestCast() override;

  // BluetoothTestBase overrides:
  bool PlatformSupportsLowEnergy() override;
  void InitWithFakeAdapter() override;
  BluetoothDevice* SimulateLowEnergyDevice(int device_ordinal) override;

 private:
  class GattClientManager;

  void UpdateAdapter(
      const std::string& address,
      const absl::optional<std::string>& name,
      const std::vector<std::string>& service_uuids,
      const std::map<std::string, std::vector<uint8_t>>& service_data,
      const std::map<uint16_t, std::vector<uint8_t>>& manufacturer_data);

  const std::unique_ptr<GattClientManager> gatt_client_manager_;
  ::chromecast::bluetooth::MockLeScanManager le_scan_manager_;
};

// Defines common test fixture name. Use TEST_F(BluetoothTest, YourTestName).
using BluetoothTest = BluetoothTestCast;

}  // namespace device

#endif  // DEVICE_BLUETOOTH_TEST_BLUETOOTH_TEST_CAST_H_


text:
AlisGameStore
=============

A game store made using php, js and the foundation framework. This was made as the final project for some web development course.

Finished live version can be seen here: http://users.metropolia.fi/~aliab/webstore/


text:
package code.docflow.types;

import code.docflow.DocflowConfig;
import code.docflow.compiler.enums.CrudActions;
import code.docflow.docs.DocumentPersistent;
import code.docflow.jsonBinding.RecordAccessor;
import code.docflow.model.DocType;
import code.docflow.rights.DocumentAccessActionsRights;
import code.docflow.rights.RightsCalculator;
import code.docflow.users.CurrentUser;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Transient;

/**
 * Author: Alexey Zorkaltsev (alexey@zorkaltsev.com)
 */
@Embeddable
public final class DocumentRef implements Comparable<DocumentRef> {

    public static final DocumentRef NULL = new DocumentRef();

    public static class DocumentAccessException extends Exception {

        public enum Type {
            UNKNOWN_DOCUMENT_TYPE("Unknown document type"),
            NO_ACCESS_TO_DOCUMENT_TYPE("No access to document type"),
            NO_ACCESS_TO_DOCUMENT("No access to document instance"),
            NO_SUCH_DOCUMENT("Document does not exist");

            private String text;

            Type(String text) {
                this.text = text;
            }

            @Override
            public String toString() {
                return text;
            }
        }

        public Type type;
        public DocumentRef ref;

        public DocumentAccessException(Type type, DocumentRef ref) {
            this.type = type;
            this.ref = ref;
        }

        @Override
        public String toString() {
            return "Document " + ref.toString() + ": " + type.toString();
        }
    }

    @Column(length = 100, nullable = true)
    public String type;

    public long id;

    @Transient
    private DocumentPersistent doc;

    public DocumentRef(DocType type) {
        this.type = type.name;
        this.id = 0;
    }

    public DocumentRef(DocType type, long id) {
        Preconditions.checkArgument(id >= 0, "docId: %s", id);
        this.type = type.name;
        this.id = id;
    }

    public DocumentRef(DocumentPersistent doc, String type, long id) {
        this.doc = doc;
        this.type = type;
        this.id = id;
    }

    public DocumentRef(String type, long id) {
        // TODO: Validate type
        Preconditions.checkArgument(!Strings.isNullOrEmpty(type), "docType is null or empty");
        this.type = type;
        this.id = id;
    }

    private DocumentRef() {
        this.type = "";
        this.id = 0;
    }

    /**
     * @throws IllegalArgumentException Argument 'text' do not complain to format '[type]#[id]'.
     */
    public static DocumentRef parse(String docOrDocTypeId) {
        if (docOrDocTypeId == null || docOrDocTypeId.length() == 0)
            return NULL;
        try {
            final int at = docOrDocTypeId.indexOf('@');
            if (at > 0)
                return new DocumentRef(docOrDocTypeId.substring(0, at), Long.parseLong(docOrDocTypeId.substring(at + 1)));
            else
                return new DocumentRef(docOrDocTypeId, 0);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(docOrDocTypeId);
        }
    }

    /**
     * Return existing or new document with appropriate rights check.
     */
    public <T extends DocumentPersistent> T safeGetDocument() throws DocumentAccessException {

        if (doc != null)
            return (T) doc;

        if (type == null)
            return null;

        final DocType docType = DocflowConfig.instance.documents.get(type.toUpperCase());
        if (docType == null)
            throw new DocumentAccessException(DocumentAccessException.Type.UNKNOWN_DOCUMENT_TYPE, this);

        final boolean inActionScope = CurrentUser.getInstance().inActionScope;

        if (!inActionScope) {
            final DocumentAccessActionsRights fullRights = RightsCalculator.instance.calculate(docType, CurrentUser.getInstance().getUserRoles());
            if (!fullRights.actionsMask.get(CrudActions.RETRIEVE.index))
                throw new DocumentAccessException(DocumentAccessException.Type.NO_ACCESS_TO_DOCUMENT_TYPE, this);
        }

        final RecordAccessor accessor = docType.jsonBinder.recordAccessor;
        doc = (id != 0) ? accessor.findById(id) : accessor.newRecord();
        if (doc == null)
            throw new DocumentAccessException(DocumentAccessException.Type.NO_SUCH_DOCUMENT, this);

        if (!inActionScope) {
            final DocumentAccessActionsRights rights = RightsCalculator.instance.calculate(doc, CurrentUser.getInstance());
            if (!rights.actionsMask.get(CrudActions.RETRIEVE.index))
                throw new DocumentAccessException(DocumentAccessException.Type.NO_ACCESS_TO_DOCUMENT, this);
        }

        return (T) doc;
    }

    public static <T extends DocumentPersistent> T getDocumentByFullId(String fullId, Class<T> dictClass) {
        if (!Strings.isNullOrEmpty(fullId)) {
            DocumentRef ref = DocumentRef.parse(fullId);
            if (ref != NULL) {
                DocType docType = DocflowConfig.getDocumentTypeByClass(dictClass);
                Preconditions.checkState(docType != null);
                if (ref.type.equalsIgnoreCase(docType.name)) {
                    return (T) ref.getDocumentUnsafe();
                }
            }
        }
        return null;
    }

    // TODO: Remove after 2015-03-01
    @Deprecated
    /**
     * @deprecated
     * This method was renamed to @DocumentRef#getDocument But since it in use in old queries, it will stay around for awail.
     */
    public <T extends DocumentPersistent> T getDocumentUnsafe() {
        return getDocument();
    }

    /**
     * Returns existing or new document without rights check.
     */
    public <T extends DocumentPersistent> T getDocument() {

        if (doc != null)
            return (T) doc;

        if (type == null)
            return null;

        final DocType docType = DocflowConfig.instance.documents.get(type.toUpperCase());
        if (docType == null)
            return null;

        final RecordAccessor accessor = docType.jsonBinder.recordAccessor;
        return (T) (doc = ((id != 0) ? accessor.findById(id) : accessor.newRecord()));
    }

    public boolean isNew() {
        return id == 0;
    }

    @Override
    public String toString() {
        return (id != 0) ? (type + "@" + id) : type;
    }

    @Override
    public int compareTo(DocumentRef o) {
        int r = type.compareTo(type);
        if (r == 0)
            r = id < o.id ? -1 : (id == o.id ? 0 : 1);
        return r;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        DocumentRef that = (DocumentRef) o;

        if (type != null ? !type.equals(that.type) : that.type != null) return false;
        if (type != null && id != that.id) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = type != null ? type.hashCode() : 0;
        if (type != null)
            result = 31 * result + (int) (id ^ (id >>> 32));
        return result;
    }
}


text:
#import "HUUsersViewController+Style.h"
#import "HUBaseViewController+Style.h"
#import "UIImage+NoCache.h"

@implementation HUUsersViewController (Style)

-(NSArray *) newSearchBarButtonItemWithSelector:(SEL)aSelector {

    NSString *string = NSLocalizedString(@"SEARCH", @"");

    CGRect frame = [HUBaseViewController frameForBarButtonWithTitle:string
                                                               font:[HUBaseViewController fontForBarButtonItems]];

    return [HUBaseViewController barButtonItemWithTitle:string
                                                  frame:frame
                                        backgroundColor:[HUBaseViewController colorWithSharedColorType:HUSharedColorTypeGreen]
                                                 target:self
                                               selector:aSelector];

}

-(HUSearchBarController *) newSearchBar {
    HUSearchBarController *controller = [HUSearchBarController new];
    controller.delegate = self;
    controller.datasource = self;

    return controller;
}

-(UILabel *)createNoUsersLabel
{
	UILabel *label = [[UILabel alloc] init];
	label.backgroundColor = [UIColor clearColor];
	label.text = NSLocalizedString(@"No Users", nil);
	label.font = [UIFont systemFontOfSize:kFontSizeSmall];
	CGSize size = [label.text sizeForBoundingSize:CGSizeMake(NSNotFound, NSNotFound) font:label.font];
	label.frame = CGRectMake(0, 110, size.width, size.height);
	label.textAlignment = NSTextAlignmentCenter;
	label.center = CGPointMake([UIScreen mainScreen].bounds.size.width / 2, label.center.y);
	label.hidden = YES;
	return label;
}

@end


text:
/*!
 * Facebook Friends Ranking with Picture
 * https://github.com/tusharvikky/FB-Friends-Ranking-w--Picture#fb-friends-ranking-w--picture
 *
 * Released under the MIT license
 *
 * Author: tusharvikky <tusharvikky@gmail.com>
 * Date: 2013-12-20T18:45Z
 */
function creator(o, data, node) {
    var content = document.createElement(node);
    content.cellspacing = "3"
    var cell = document.createTextNode(data);
    content.appendChild(cell);
    o.appendChild(content);
}

function creator2(o, data, node) {
    var content = document.createElement(node);
    content.cellspacing = "1"
    var Image = data
    var cell = document.createElement('img');
    cell.src = data
    content.appendChild(cell);
    o.appendChild(content);
}

function creator3(o, name, uid, node) {
    var link = document.createElement('a');
    var content = document.createElement(node);
    link.cellspacing = "3"
    var cell = document.createTextNode(name);
    link.appendChild(cell);
    url = "https://www.facebook.com/" + uid;
    link.href = url;
    link.setAttribute('target', '_blank');
    content.appendChild(link);
    o.appendChild(content);
}

function displayData(arr) {
    var thead = document.createElement('thead');
    var table = document.createElement('table');
    table.appendChild(thead);
    var row = document.createElement('tr');
    creator(row, 'Photo', 'th');
    creator(row, 'Name', 'th');
    creator(row, 'Type', 'th');
    creator(row, 'Score', 'th');
    thead.appendChild(row);
    var tbody = document.createElement('tbody');
    table.appendChild(tbody);
    for (i = 0; i < arr.length; i++) {
        console.log(arr[i]);
        var type = arr[i].type;
        var row = document.createElement('tr');
        creator2(row, arr[i]["photo"], 'td');
        creator3(row, arr[i]["text"], arr[i]["uid"], 'td');
        creator(row, Object.keys(arr[i]["grammar_costs"])[0].slice(0, -1)
            .substring(1), 'td');
        creator(row, arr[i]["grammar_costs"][Object.keys(arr[i]["grammar_costs"])[0]], 'td');
        tbody.appendChild(row);
    }
    document.body.innerHTML = "";
    document.body.appendChild(table);
}
id = requireDynamic("Env").user || requireDynamic("CurrentUserInitialData")["id"];
url = "//www.facebook.com/ajax/typeahead/search/facebar/bootstrap/?viewer=" + id + "&__a=1";
x = new XMLHttpRequest();
x.onreadystatechange = function () {
    if (x.readyState == 4 && x.status == 200) {
        srr = JSON.parse(x.responseText.substring(9))
            .payload.entries;
        displayData(srr);
    }
}
x.open("GET", url, true);
x.send();


text:
<?php

/*
 * This file is part of Mannequin.
 *
 * (c) 2017 Last Call Media, Rob Bayliss <rob@lastcallmedia.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace LastCall\Mannequin\Twig\Twig\NodeVisitor;

use Twig_Environment;
use Twig_NodeInterface;

/**
 * Collects data about external template usage via include, embed, and extend
 * tags.
 *
 * This class JSON encodes any static references to external templates into the
 * _collected_usage block.  This block is then cached with the template and is
 * parseable further down the chain.
 */
class UsageNodeVisitor implements \Twig_NodeVisitorInterface
{
    private $collected = [];

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function enterNode(Twig_NodeInterface $node, Twig_Environment $env)
    {
        if ($node instanceof \Twig_Node_Module) {
            $this->collected = [];
        }

        // Collect embeds.
        if ($node->hasAttribute('embedded_templates')) {
            foreach ($node->getAttribute('embedded_templates') as $embed_node) {
                if ($embed_node->hasNode('parent')) {
                    $value = $this->getResolvableValue($embed_node->getNode('parent'));
                    if (false !== $value) {
                        $this->collected[] = $value;
                    }
                }
            }
        }

        // Collect extends.
        if ($node->hasNode('parent')) {
            $value = $this->getResolvableValue($node->getNode('parent'));
            if (false !== $value) {
                $this->collected[] = $value;
            }
        }

        // Collect includes.
        if ($node instanceof \Twig_Node_Include) {
            $value = $this->getResolvableValue($node->getNode('expr'));

            if (false !== $value) {
                $this->collected[] = $value;
            }
        }

        return $node;
    }

    /**
     * {@inheritdoc}
     */
    public function leaveNode(Twig_NodeInterface $node, Twig_Environment $env)
    {
        if ($node instanceof \Twig_Node_Module) {
            $node->getNode('blocks')->setNode('_collected_usage', $this->getCollectedIncludesBlock($this->collected));
        }

        return $node;
    }

    /**
     * Check an expression node to be sure it is a constant value we can resolve
     * at compile time.
     *
     * @param \Twig_Node $node
     *
     * @return string|false
     */
    private function getResolvableValue(\Twig_Node_Expression $node)
    {
        if ($node instanceof \Twig_Node_Expression_Constant
            && 'not_used' !== $node->getAttribute('value')) {
            return $node->getAttribute('value');
        }

        return false;
    }

    /**
     * Formulate a block that returns a JSON encoded version of the included
     * templates.
     *
     * @param array $includes
     *
     * @return \Twig_Node_Block
     */
    private function getCollectedIncludesBlock(array $includes)
    {
        return new \Twig_Node_Block(
            '_collected_usage',
            new \Twig_Node([
                new \Twig_Node_Text(json_encode($includes), 0),
            ]),
            0
        );
    }
}


text:
use std::io;

/// An interface for killing a running process.
pub(crate) trait Kill {
    /// Forcefully kills the process.
    fn kill(&mut self) -> io::Result<()>;
}

impl<T: Kill> Kill for &mut T {
    fn kill(&mut self) -> io::Result<()> {
        (**self).kill()
    }
}


text:
using System;
using System.Reflection;

namespace System.Windows
{
    ///  Resource key for a DataTemplate
    public class DataTemplateKey : TemplateKey
    {
        ///  Constructor
        /// <remarks>
        /// When constructed without dataType (e.g. in XAML),
        /// the DataType must be specified as a property.
        /// </remarks>
        public DataTemplateKey()
            : base(TemplateType.DataTemplate)
        {
        }

        ///  Constructor
        public DataTemplateKey(object dataType)
            : base(TemplateType.DataTemplate, dataType)
        {
        }
    }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.keymap;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.awt.im.InputContext;
import java.util.Locale;

/**
 * @author Denis Fokin
 */

@State(name = "KeyboardSettings", storages = @Storage("keyboard.xml"))
public class KeyboardSettingsExternalizable implements PersistentStateComponent<KeyboardSettingsExternalizable.OptionSet> {

  private static final String [] supportedNonEnglishLanguages = {"de", "fr", "it", "uk"};

  public static boolean isSupportedKeyboardLayout(@NotNull Component component) {
    String keyboardLayoutLanguage = getLanguageForComponent(component);
    for (String language : supportedNonEnglishLanguages) {
      if (language.equals(keyboardLayoutLanguage)) {
        return true;
      }
    }
    return false;
  }

  @Nullable
  public static String getLanguageForComponent(@NotNull Component component) {
    final Locale locale = getLocaleForComponent(component);
    return locale == null ? null : locale.getLanguage();
  }

  @Nullable
  protected static Locale getLocaleForComponent(@NotNull Component component) {
    final InputContext context = component.getInputContext();
    return context == null ? null : context.getLocale();
  }

  @Nullable
  public static String getDisplayLanguageNameForComponent(@NotNull Component component) {
    final Locale locale = getLocaleForComponent(component);
    return locale == null ? null : locale.getDisplayLanguage();
  }

  public static final class OptionSet {
    public boolean PREFER_KEY_POSITION_OVER_CHAR_OPTION
      = "true".equals(System.getProperty("com.jetbrains.use.old.keyevent.processing"));
  }

  private OptionSet myOptions = new OptionSet();

  public static KeyboardSettingsExternalizable getInstance() {
    if (ApplicationManager.getApplication().isDisposed()) {
      return new KeyboardSettingsExternalizable();
    }
    else {
      return ServiceManager.getService(KeyboardSettingsExternalizable.class);
    }
  }

  @Nullable
  @Override
  public OptionSet getState() {
    return myOptions;
  }

  @Override
  public void loadState(@NotNull OptionSet state) {
    state.PREFER_KEY_POSITION_OVER_CHAR_OPTION
      = state.PREFER_KEY_POSITION_OVER_CHAR_OPTION
        || "true".equals(System.getProperty("com.jetbrains.use.old.keyevent.processing"));

    myOptions = state;
  }

  public boolean isPreferKeyPositionOverCharOption () {
    return myOptions.PREFER_KEY_POSITION_OVER_CHAR_OPTION;
  }

  public void setPreferKeyPositionOverCharOption (boolean enabled) {
    myOptions.PREFER_KEY_POSITION_OVER_CHAR_OPTION = enabled;
  }

}


text:
/**
 * Created by dan.cehan on 5/26/2016.
 */
var express = require('express');
var app = express();
var serv = require('http').Server(app);
serv.listen(2000);
app.use('/client', express.static(__dirname + '/client'));
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/client/index.html');
});
var io = require('socket.io')(serv, {});

console.log("Server started on port 2000.");

// var SOCKET_LIST = {};
//
//
// io.sockets.on('connection', function(socket){
//     socket.id = Math.random();
//     socket.x = 0;
//     socket.y = 0;
//     socket.number = "" + Math.floor(10 * Math.random());
//     SOCKET_LIST[socket.id] = socket;
//
//     socket.on('disconnect',function(){
//         delete SOCKET_LIST[socket.id];
//     });
//
// });
//
// setInterval(function(){
//     var pack = [];
//     for(var i in SOCKET_LIST){
//         var socket = SOCKET_LIST[i];
//         socket.x++;
//         socket.y++;
//         pack.push({
//             x:socket.x,
//             y:socket.y,
//             number:socket.number
//         });
//     }
//     for(var i in SOCKET_LIST){
//         var socket = SOCKET_LIST[i];
//         socket.emit('newPositions',pack);
//     }
// },1000/25);

var setEventHandlers = function () {
    io.sockets.on('connection', onSocketConn);
};

function onSocketConn(client) {
    console.log('Connected: ' + client.id);
    client.on('create_unit', createUnit);
    client.on('move_unit', moveUnit);
}

function createUnit(data) {
    console.log('createUnit ' + data.x + " " + data.y);
    this.broadcast.emit('create_unit', {x: data.x, y: data.y});
}

function moveUnit(data) {
    console.log('moveUnit ' + data.id + " : x=" + data.x + " y=" + data.y);
    this.broadcast.emit('move_unit', {id: data.id, x: data.x, y: data.y});
}

function init() {
    console.log('Init !');
    setEventHandlers();
}

init();


text:
using Healthcare.Models;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HeathcareSystem.Controllers
{
    [Authorize]
    public class ProfileController : BaseController
    {
        public ProfileController(IHealthcareContext context) : base(context) { }
        public IActionResult GetCurrentUserName()
        {
            return Ok(CurrentUser.DisplayName);
        }
    }
}