text:
package server6

/*
  To use the DHCPv6 server code you have to call NewServer with two arguments:
  - an address to listen on, and
  - a handler function, that will be called every time a valid DHCPv6 packet is
    received.

  The address to listen on is used to know IP address, port and optionally the
  scope to create and UDP socket to listen on for DHCPv6 traffic.

  The handler is a function that takes as input a packet connection, that can be
  used to reply to the client; a peer address, that identifies the client sending
  the request, and the DHCPv6 packet itself. Just implement your custom logic in
  the handler.

  Optionally, NewServer can receive options that will modify the server object.
  Some options already exist, for example WithConn. If this option is passed with
  a valid connection, the listening address argument is ignored.

  Example program:

package main

import (
	"log"
	"net"

	"github.com/insomniacslk/dhcp/dhcpv6"
	"github.com/insomniacslk/dhcp/dhcpv6/server6"
)

func handler(conn net.PacketConn, peer net.Addr, m dhcpv6.DHCPv6) {
	// this function will just print the received DHCPv6 message, without replying
	log.Print(m.Summary())
}

func main() {
	laddr := net.UDPAddr{
		IP:   net.ParseIP("::1"),
		Port: 547,
	}
	server, err := server6.NewServer(&laddr, handler)
	if err != nil {
		log.Fatal(err)
	}

	// This never returns. If you want to do other stuff, dump it into a
	// goroutine.
	server.Serve()
}

*/

import (
	"log"
	"net"
	"os"

	"github.com/insomniacslk/dhcp/dhcpv6"
	"golang.org/x/net/ipv6"
)

// Handler is a type that defines the handler function to be called every time a
// valid DHCPv6 message is received
type Handler func(conn net.PacketConn, peer net.Addr, m dhcpv6.DHCPv6)

// Server represents a DHCPv6 server object
type Server struct {
	conn    net.PacketConn
	handler Handler
	logger  Logger
}

// Serve starts the DHCPv6 server. The listener will run in background, and can
// be interrupted with `Server.Close`.
func (s *Server) Serve() error {
	s.logger.Printf("Server listening on %s", s.conn.LocalAddr())
	s.logger.Printf("Ready to handle requests")

	defer s.Close()
	for {
		rbuf := make([]byte, 4096) // FIXME this is bad
		n, peer, err := s.conn.ReadFrom(rbuf)
		if err != nil {
			s.logger.Printf("Error reading from packet conn: %v", err)
			return err
		}
		s.logger.Printf("Handling request from %v", peer)

		d, err := dhcpv6.FromBytes(rbuf[:n])
		if err != nil {
			s.logger.Printf("Error parsing DHCPv6 request: %v", err)
			continue
		}

		go s.handler(s.conn, peer, d)
	}
}

// Close sends a termination request to the server, and closes the UDP listener
func (s *Server) Close() error {
	return s.conn.Close()
}

// A ServerOpt configures a Server.
type ServerOpt func(s *Server)

// WithConn configures a server with the given connection.
func WithConn(conn net.PacketConn) ServerOpt {
	return func(s *Server) {
		s.conn = conn
	}
}

// NewServer initializes and returns a new Server object, listening on `addr`.
// * If `addr` is a multicast group, the group will be additionally joined
// * If `addr` is the wildcard address on the DHCPv6 server port (`[::]:547), the
//   multicast groups All_DHCP_Relay_Agents_and_Servers(`[ff02::1:2]`) and
//   All_DHCP_Servers(`[ff05::1:3]:547`) will be joined.
// * If `addr` is nil, IPv6 unspec on the DHCP server port is used and the above
//   behaviour applies
// If `WithConn` is used with a non-nil address, `addr` and `ifname` have
// no effect. In such case, joining the multicast group is the caller's
// responsibility.
func NewServer(ifname string, addr *net.UDPAddr, handler Handler, opt ...ServerOpt) (*Server, error) {
	s := &Server{
		handler: handler,
		logger:  EmptyLogger{},
	}

	for _, o := range opt {
		o(s)
	}
	if s.conn != nil {
		return s, nil
	}

	if addr == nil {
		addr = &net.UDPAddr{
			IP:   net.IPv6unspecified,
			Port: dhcpv6.DefaultServerPort,
		}
	}

	var (
		err   error
		iface *net.Interface
	)
	if ifname == "" {
		iface = nil
	} else {
		iface, err = net.InterfaceByName(ifname)
		if err != nil {
			return nil, err
		}
	}
	// no connection provided by the user, create a new one
	s.conn, err = NewIPv6UDPConn(ifname, addr)
	if err != nil {
		return nil, err
	}

	p := ipv6.NewPacketConn(s.conn)
	if addr.IP.IsMulticast() {
		if err := p.JoinGroup(iface, addr); err != nil {
			return nil, err
		}
	} else if (addr.IP == nil || addr.IP.IsUnspecified()) && addr.Port == dhcpv6.DefaultServerPort {
		// For wildcard addresses on the correct port, listen on both multicast
		// addresses defined in the RFC as a "default" behaviour
		for _, g := range []net.IP{dhcpv6.AllDHCPRelayAgentsAndServers, dhcpv6.AllDHCPServers} {
			group := net.UDPAddr{
				IP:   g,
				Port: dhcpv6.DefaultServerPort,
			}
			if err := p.JoinGroup(iface, &group); err != nil {
				return nil, err
			}

		}
	}

	return s, nil
}

// WithSummaryLogger logs one-line DHCPv6 message summaries when sent & received.
func WithSummaryLogger() ServerOpt {
	return func(s *Server) {
		s.logger = ShortSummaryLogger{
			Printfer: log.New(os.Stderr, "[dhcpv6] ", log.LstdFlags),
		}
	}
}

// WithDebugLogger logs multi-line full DHCPv6 messages when sent & received.
func WithDebugLogger() ServerOpt {
	return func(s *Server) {
		s.logger = DebugLogger{
			Printfer: log.New(os.Stderr, "[dhcpv6] ", log.LstdFlags),
		}
	}
}

// WithLogger set the logger (see interface Logger).
func WithLogger(newLogger Logger) ServerOpt {
	return func(s *Server) {
		s.logger = newLogger
	}
}


text:
import * as bodyParser from "body-parser";
import * as compression from "compression";
import * as cors from "cors";
import * as express from "express";
import * as http from "http";
import * as path from "path";
import * as WebSocketServer from "ws";

import { Cdn } from "@rsi/cdn";
import { IRsiLoggerInstance, RsiLogger } from "@rsi/core";

// create server and listen on provided port (on all network interfaces).
export class WebServer {
  public app: express.Express;
  public ws: WebSocketServer.Server;

  private server: any;
  private port: number | string | boolean;
  private logger: IRsiLoggerInstance;

  constructor(port?: number, private _BASEURI: string = "/") {

    this.logger = RsiLogger.getInstance().getLogger("general");
    this.app = express();

    const whitelist = ["127.0.0.1", "localhost"];
    const corsOpts: cors.CorsOptions = {
      exposedHeaders: "Location",
      origin: "*"
    };

    this.app.use(cors(corsOpts));
    this.app.use(bodyParser.json());
    this.app.use(bodyParser.urlencoded({ extended: false }));
    this.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
      this.logger.info("Query:", req.method, req.url);
      next();
    });
    this.app.use(compression());

    // serve static content for cdn
    this.app.use(this._BASEURI + "cdn/:resource/:filename?", Cdn.getInstance().requestHandler());

    // Get port from environment and store in Express.
    this.port = this.normalizePort(process.env.PORT || port || "3000");
    this.app.set("port", this.port);

    this.server = http.createServer(this.app);

    this.ws = new WebSocketServer.Server({ server: this.server });
  }

  public init() {
    this.server.listen(this.port);
    this.server.on("listening", this.onListening);
  }
  /**
   * Normalize a port into a number, string, or false.
   */
  public normalizePort(val: any): number | string | boolean {
    const port = parseInt(val, 10);

    if (isNaN(port)) {
      // named pipe
      return val;
    }

    if (port >= 0) {
      // port number
      return port;
    }

    return false;
  }

  /**
   * Event listener for HTTP server "listening" event.
   */
  public onListening = () => {
    const addr = this.server.address();
    const bind = typeof addr === "string"
    ? "pipe " + addr
    : "port " + addr.port;
    this.logger.log("log", "Listening on " + bind);
  }

  /**
   * Shutdown the server
   */
  public close = () => {
    this.ws.close(() => {
      // console.log("Closed WS");
    });
    this.server.close();
    this.app = null;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package net.javacrumbs.jsonunit.core.internal;

import net.javacrumbs.jsonunit.core.Configuration;
import net.javacrumbs.jsonunit.core.Option;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import static java.util.Collections.emptyList;
import static java.util.Map.Entry.comparingByKey;

/**
 * Internal utility class to parse JSON values.
 */
public class JsonUtils {
    private static final Converter converter = Converter.createDefaultConverter();

    /**
     * Converts object to JSON.
     *
     * @param source
     * @param label  label to be logged in case of error.
     * @return
     */
    public static Node convertToJson(Object source, String label) {
        return convertToJson(source, label, false);
    }

    /**
     * Converts object to JSON.
     *
     * @param source
     * @param label  label to be logged in case of error.
     * @param lenient lenient parser used for expected values. Allows unquoted keys.
     * @return
     */
    public static Node convertToJson(Object source, String label, boolean lenient) {
        if (source instanceof JsonSource) {
            return converter.convertToNode(((JsonSource) source).getJson(), label, lenient);
        } else {
            return converter.convertToNode(source, label, lenient);
        }
    }

    /**
     * Converts value to Json node. It can be Map, String, null, or primitive. Should not be parsed, just converted.
     * @param source
     * @return
     */
    public static Node valueToNode(Object source) {
        if (source instanceof Node) {
            return (Node) source;
        } else {
            return converter.valueToNode(source);
        }
    }

    /**
     * Returns node with given path.
     *
     * @param root
     * @param path
     * @return
     */
    public static Node getNode(Object root, String path) {
        return getNode(root, Path.create(path));
    }

    /**
      * Returns node with given path.
      *
      * @param root
      * @param path
      * @return
      */
     public static Node getNode(Object root, Path path) {
         return path.getNode(convertToJson(root, "actual"));
     }

    /**
     * Returns true if the node exists.
     */
    @Deprecated
    public static boolean nodeExists(Object json, String path) {
        return !getNode(json, path).isMissingNode();
    }

    public static boolean nodeAbsent(Object json, String path, Configuration configuration) {
        return nodeAbsent(json, Path.create(path), configuration);
    }

    public static boolean nodeAbsent(Object json, Path path, Configuration configuration) {
        return nodeAbsent(json, path, configuration.getOptions().contains(Option.TREATING_NULL_AS_ABSENT));
    }

    public static Object jsonSource(Object json, String pathPrefix) {
        return jsonSource(json, pathPrefix, emptyList());
    }

    public static Object jsonSource(Object json, String pathPrefix, List<String> matchingPaths) {
        return new DefaultJsonSource(json, pathPrefix, matchingPaths);
    }

    public static String getPathPrefix(Object json) {
        if (json instanceof JsonSource) {
            return ((JsonSource) json).getPathPrefix();
        } else {
            return "";
        }
    }

    /**
     * Returns true if the is absent.
     */
    static boolean nodeAbsent(Object json, Path path, boolean treatNullAsAbsent) {
        Node node = getNode(json, path);
        if (node.isNull()) {
            return treatNullAsAbsent;
        } else {
            return node.isMissingNode();
        }
    }

    /**
     * Add quotes around the object iff it's not a JSON object.
     *
     * @param source
     * @return
     */
    static String quoteIfNeeded(String source) {
        String trimmed = source.trim();

        if (isObject(trimmed) || isArray(trimmed) || isString(trimmed)
            || isBoolean(trimmed) || isNull(trimmed)
            || isNumber(trimmed)) {
            return source;
        } else {
            return "\"" + source + "\"";
        }
    }

    /**
     * Add quotes around the object iff it's not a JSON object.
     *
     * @param source
     * @return
     */
    static Object quoteIfNeeded(Object source) {
        if (source instanceof String) {
            return quoteIfNeeded((String) source);
        } else {
            return source;
        }
    }

    /**
     * Wraps deserialized object - supports null, String, numbers, maps, lists, ...
     */
    public static Node wrapDeserializedObject(Object source) {
        return GenericNodeBuilder.wrapDeserializedObject(source);
    }

    public static Object missingNode() {
        return Node.MISSING_NODE;
    }

    private static boolean isNull(String trimmed) {
        return trimmed.equals("null");
    }

    private static boolean isBoolean(String trimmed) {
        return trimmed.equals("true") || trimmed.equals("false");
    }

    private static boolean isString(String trimmed) {
        return trimmed.startsWith("\"");
    }

    private static boolean isArray(String trimmed) {
        return trimmed.startsWith("[");
    }

    private static boolean isObject(String trimmed) {
        return trimmed.startsWith("{");
    }

    private static boolean isNumber(String source) {
        try {
            Double.parseDouble(source);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

    static String prettyPrint(Map<String, Object> map) {
        StringBuilder builder = new StringBuilder();
        builder.append("{");
        Iterator<Entry<String, Object>> entries = map.entrySet().stream().sorted(comparingByKey()).iterator();
        while (entries.hasNext()) {
            Entry<String, Object> entry = entries.next();
            builder.append('"').append(entry.getKey()).append('"').append(":");
            appendQuoteString(entry.getValue(), builder);
            if (entries.hasNext()) {
                builder.append(",");
            }
        }
        builder.append("}");
        return builder.toString();
    }

    private static void appendQuoteString(Object value, StringBuilder builder) {
        if (value instanceof String) {
            builder.append("\"").append(value).append("\"");
        } else {
            builder.append(value);
        }
    }

    private static class DefaultJsonSource implements JsonSource {
        private final Object json;
        private final String pathPrefix;
        private final List<String> matchingPaths;

        public DefaultJsonSource(Object json, String pathPrefix, List<String> matchingPaths) {
            this.json = json;
            this.pathPrefix = pathPrefix;
            this.matchingPaths = matchingPaths;
        }

        @Override
        public Object getJson() {
            return json;
        }

        @Override
        public String getPathPrefix() {
            return pathPrefix;
        }

        @Override
        public List<String> getMatchingPaths() {
            return matchingPaths;
        }
    }
}


text:
WORK_DEFAULT=/tmp
XQTSURL_DEFAULT=http://zorbatest.lambda.nu:8080/~spungi/XQTS_090512.zip

die() {
  echo
  echo 'Arguments: [--workdir <workdir>] [--builddir <builddir>] [--xqtsurl <xqtsurl>] <zorba_repository>'
  echo '<zorba_repository> is the top-level SVN working copy'
  echo "<workdir> is a temp directory to download and unzip XQTS (default: $WORK_DEFAULT)"
  echo '<builddir> is the directory Zorba has been built in'
  echo '           (default: <zorba_repository>/build)'
  echo '<xqtsurl> is the URL where the XQTS archived version can be found'
  echo "          (default: $XQTSURL_DEFAULT)"
  echo '          (you can use for instance http://dev.w3.org/2006/xquery-test-suite/PublicPagesStagingArea/XQTS_1_0_3.zip)'
  exit 1
}

WORK=$WORK_DEFAULT
XQTSURL=$XQTSURL_DEFAULT
while [ $# -gt 1 ]
do
  # --workdir to specify a working directory to download/unzip XQTS
  test "$1" = "--workdir" && { WORK="$2"; shift; shift; }

  # --builddir to specify Zorba build directory (default: srcdir/build)
  test "$1" = "--builddir" && { BUILD="$2"; shift; shift; }

  # xqtsurl to specify the URL where XQTS can be found
  test "$1" = "--xqtsurl" && { XQTSURL="$2"; shift; shift; }
done

SRC="$1"
if [ -z "$BUILD" ]; then
  BUILD="$SRC/build"
fi

if test ! -d "$SRC/test/rbkt"; then
  echo "Invalid zorba repository $SRC"
  die
  exit 1
fi

if test ! -d "$BUILD"; then
  echo "Invalid build directory $BUILD"
  echo "Be sure to finish building Zorba before running this script"
  die
  exit 1
fi

zipname=`basename $XQTSURL`
ZIP="$WORK/$zipname"
echo Downloading test suite to zip $ZIP ...
wget -c -O $ZIP $XQTSURL

orig_pwd=`pwd`

# Canonicalize SRC and BUILD
SRC=$(cd "$SRC" && pwd)
echo Repository is at $SRC
BUILD=$(cd "$BUILD" && pwd)
echo Build dir is at $BUILD

echo Unzipping test suite...
unzip_dir=`mktemp -d "$WORK/$zipfile.XXXXXX"`
cd "$unzip_dir"
unzip $ZIP &>/dev/null

echo Cleaning up previous data...
rm -rf "$SRC/test/rbkt/Queries/w3c_testsuite" "$SRC/test/rbkt/ExpQueryResults/w3c_testsuite" "$SRC/test/rbkt/Scripts/w3c/w3c_reportingresults"

mkdir -p "$SRC/test/rbkt/Queries/w3c_testsuite/TestSources"
mkdir -p "$SRC/test/rbkt/Queries/w3c_testsuite/cat"

echo Importing $zipfile ...
q=`mktemp "$WORK/xq.XXXXXX"`
cat >"$q" <<"EOF"
declare default element namespace "http://www.w3.org/2005/02/query-test-XQTSCatalog";
string-join (
  for $sch in //schema
  return concat ($sch/@uri, "=", $sch/@FileName), "
")
EOF
echo 'Processing URI of catalog (schemas)...'
"$BUILD/bin/zorba" --context-item XQTSCatalog.xml --omit-xml-declaration -o "$SRC/test/rbkt/Queries/w3c_testsuite/TestSources/uri.txt" --as-files --query "$q"

cat >"$q" <<"EOF"
declare default element namespace "http://www.w3.org/2005/02/query-test-XQTSCatalog";
string-join (distinct-values (
  for $mod in //sources/module
  for $tmod in //test-case/module [text () = $mod/@ID]
  let $tc := $tmod/..
  return concat ($tc/@FilePath, $tc/@name, ":", $tmod/@namespace, "=", $mod/@FileName)), "
")
EOF
echo 'Processing URI of catalog (modules)...'
"$BUILD/bin/zorba" --context-item XQTSCatalog.xml --omit-xml-declaration -o "$SRC/test/rbkt/Queries/w3c_testsuite/TestSources/module.txt" --as-files --query "$q"

cat >"$q" <<"EOF"
declare default element namespace "http://www.w3.org/2005/02/query-test-XQTSCatalog";
for $t in //collection
return concat ($t/@ID, "=", string-join( for $x in $t/input-document return fn:concat( "$RBKT_SRC_DIR/Queries/w3c_testsuite/TestSources/", $x, ".xml"), ";" ), "
")
EOF
echo 'Processing URI of catalog (collections)...'
"$BUILD/bin/zorba" --context-item XQTSCatalog.xml --omit-xml-declaration -o "$SRC/test/rbkt/Queries/w3c_testsuite/TestSources/collection.txt" --as-files --query "$q"

cat >"$q" <<"EOF"
declare default element namespace "http://www.w3.org/2005/02/query-test-XQTSCatalog";
string-join ((
for $sch in //schema return concat ("%uri ", $sch/@uri, " ", $sch/@FileName),
for $src in //source return concat ("%src ", $src/@ID, " ", $src/@FileName),
for $tc in //test-case
let $out := $tc//output-file
let $cmp := $tc/output-file[1]/@compare (: assuming that all output-files have to be compared using the same comparison method :)
let $ctx := $tc/contextItem
let $dc  := $tc/defaultCollection
(: assuming only one input-query and x is variable name :)
let $inq := $tc/input-query/@name
return string-join ((
$tc/@name, $tc/@FilePath, $tc/query/@name,
if ($tc/input-file) then string-join (for $i in $tc/input-file return concat (data ($i/@variable), "=", $i/text ()), ";") else "noinlist",
if ($tc/input-URI) then
    string-join (
      for $i in $tc/input-URI
      let $fulluri := /test-suite/sources/source[@ID = $i/text()]
      return
        if ($fulluri) then
          concat (data ($i/@variable), "=$RBKT_SRC_DIR/Queries/w3c_testsuite/", data($fulluri/@FileName))
        else
          concat (data ($i/@variable), "=", $i/text ()), ";")
else "nourilist",
if ($inq) then $inq else "noquery",
if ($cmp) then $cmp else "nocomparison",
if ($ctx) then $ctx else "nocontext",
if ($dc) then $dc else "nodefaultcollection",
if ($out) then string-join($out/text(), ";") else "",
string-join ($tc/expected-error/text(), ";")
), " ")),
"
")
EOF

echo 'Processing catalog...'
"$BUILD/bin/zorba" --context-item XQTSCatalog.xml --omit-xml-declaration --as-files --query "$q" | tee "$WORK/xq-res.txt" | perl -e '
use strict;
use File::Copy;

my $repo=shift;
my %sources;
my $test_src_path = "\$RBKT_SRC_DIR/Queries/w3c_testsuite";
my $test_uris = "$test_src_path/TestSources/uri.txt\n";
open (URIS, ">> $test_uris" );
while (<>) {
chomp;
if (m/^%uri /) {
  my ( $info, $uri, $file) = split (/ /);
  print URIS " $uri=$file\n";
  next;
}
if (m/^%src /) {
  my ($info, $id, $path) = split (/ /);
  $sources {$id} = $path;
  next;
}

my ($name, $path, $query, $inlist, $urilist, $inpq, $cmp, $ctx, $dc, $out, $errlist) = split (/ /);
my @inbnd = split (/;/, $inlist);
my @uribnd = split (/;/, $urilist);
my @errs = split (/;/, $errlist);
my @outfiles = split (/;/, $out);
my $inpath = "Queries/XQuery/$path";
my $inxqueryxpath = "Queries/XQueryX/$path";
my $dstqpath="$repo/test/rbkt/Queries/w3c_testsuite/XQuery/$path";
my $dstxqueryxqpath="$repo/test/rbkt/Queries/w3c_testsuite/XQueryX/$path";
my $inpqpath="$repo/test/rbkt/Queries/w3c_testsuite/InputQueries";
my $dstrespath = "$repo/test/rbkt/ExpQueryResults/w3c_testsuite/$path";
my $fullout = "$dstrespath/$name.xml.res";
my $specfile = "$dstqpath/$name.spec";
my $xqueryxspecfile = "$dstxqueryxqpath/$name.spec";
`mkdir -p $dstqpath`; `mkdir -p $dstxqueryxqpath`; `mkdir -p $dstrespath`; `mkdir -p $inpqpath`;

sub change_doc {
  my ($filename, $varname) = @_;
  open (FILE, $filename);
  open (OUT, ">$filename.new");
  while (<FILE>) {
    s/declare variable \$$varname external/declare variable \$$varname as document-node() external/;
    print OUT;
  }
  close FILE;
  close OUT;
  move ("$filename.new", $filename);
}

copy ("$inpath/$query.xq", "$dstqpath/$name.xq");
copy ("$inxqueryxpath/$query.xqx", "$dstxqueryxqpath/$name.xqx");

if (@outfiles) {

  if (@outfiles >= 1) {
    open (SPEC, ">>$specfile");
    open (SPECX, ">>$xqueryxspecfile");
    print SPEC "Result: ";
    print SPECX "Result: ";
  }

  foreach (@outfiles) {
    my $txtfile = "$_";
    $txtfile =~ 's/[.]txt$/.xml.res/';
    if (@outfiles == 1) {
      $txtfile =~ 's/[.]xml$/.xml.res/';
    } else {
      # avoid possible conflict with alternate .txt result
      $txtfile =~ 's/[.]xml$/-X.xml.res/';
    }
    copy ("ExpectedTestResults/$path/$_", "$dstrespath/$txtfile");
    if (@outfiles >= 1) {
      print SPEC " \$RBKT_SRC_DIR/ExpQueryResults/w3c_testsuite/$path/$txtfile";
      print SPECX "\$RBKT_SRC_DIR/ExpQueryResults/w3c_testsuite/$path/$txtfile";
    }
  }

  if (@outfiles >= 1) {
    print SPEC "\n";
    print SPECX "\n";
    close (SPEC);
    close (SPECX);
  }
}

if ( $inlist ne "noinlist" || $urilist ne "nourilist" || $ctx ne "nocontext" ) {
  open (SPEC, ">>$specfile");
  open (SPECX, ">>$xqueryxspecfile");

  print SPEC "Args:\n";
  print SPECX "Args:\n";

  # enable Dtd loader for tests using Dtd
  if ( $name=~/^fn-id-dtd-/ ||
       $name=~/^fn-idref-dtd-/ ||
       $name=~/^functx-functx-id-from-element-1/
     )
  {
    print SPEC  "--enable-dtd \n";
    print SPECX "--enable-dtd \n";
  }

  if ( $inlist ne "noinlist" ) {
    foreach (@inbnd) {
      my ($var, $srcid) = split /=/;
      print SPEC "-x \n$var=$test_src_path/" . $sources {$srcid} . "\n";
      print SPECX "-x \n$var=$test_src_path/" . $sources {$srcid} . "\n";
      # Rather ugly query post-processing; see bug 2788838
      if (grep $_ eq "XPST0005", @errs) {
        change_doc("$dstqpath/$name.xq", $var);
      }
    }
  }

  if ( $urilist ne "nourilist" ) {
    foreach (@uribnd) {
      my ($var, $srcid) = split /=/;
      print SPEC "-x \n$var:=" . $srcid ."\n";
      print SPECX "-x \n$var:=" . $srcid ."\n";
    }
  }

  if ( $ctx ne "nocontext" ) {
    print SPEC "-x \n.=$test_src_path/" . $sources {$ctx} ."\n";
    print SPECX "-x \n.=$test_src_path/" . $sources {$ctx} ."\n";
  }
  #print SPEC "\n";
  #print SPECX "\n";
  close (SPEC);
  close (SPECX);
}

if ( $cmp ne "nocomparison" ) {
   open (SPEC, ">>$specfile");
   open (SPECX, ">>$xqueryxspecfile");
   print SPEC "Comparison: " . $cmp . "\n";
   print SPECX "Comparison: " . $cmp . "\n";
}

if ( $inpq ne "noquery" ) {
   open (SPEC, ">>$specfile");
   open (SPECX, ">>$xqueryxspecfile");
   print SPEC "InputQuery: \$RBKT_SRC_DIR/Queries/w3c_testsuite/InputQueries/" . $inpq . ".ixq" . "\n";
   print SPECX "InputQuery: \$RBKT_SRC_DIR/Queries/w3c_testsuite/InputQueries/" . $inpq . ".ixq" . "\n";
   copy ( "$inpath/$inpq.xq", "$inpqpath/$inpq.ixq" );
   copy ( "$inxqueryxpath/$inpq.xq", "$inpqpath/$inpq.ixqx" );
}

if ( $dc ne "nodefaultcollection" ) {
   open (SPEC, ">>$specfile");
   open (SPECX, ">>$xqueryxspecfile");
   print SPEC "DefaultCollection: " . $dc . "\n";
   print SPECX "DefaultCollection: " . $dc . "\n";
}

if (@errs) {
  open (SPEC, ">>$specfile");
  open (SPECX, ">>$xqueryxspecfile");
  foreach (@errs) {
    my ($qname) = /^\*$/ ? "*" : "http://www.w3.org/2005/xqt-errors:$_\n";
    print SPEC "Error: $qname\n";
    print SPECX "Error: $qname\n";
  }
  close (SPEC);
  close (SPECX);
}

}
close (URIS);' "$SRC"
rm -f "$q"

echo "Importing test sources..."
mv XQTSCatalog.xml "$SRC/test/rbkt/Queries/w3c_testsuite/"
# Need the modules which have .xq suffix; rename them to .xqi files because we do not want to test them (ctest would find those also)
find "TestSources" -name '*.xq' -exec mv "{}" "$SRC/test/rbkt/Queries/w3c_testsuite/{}i" \;
find "TestSources" -type f -exec mv "{}" "$SRC/test/rbkt/Queries/w3c_testsuite/{}" \;
mv "XQTSCatalog.xsd" "$SRC/test/rbkt/Queries/w3c_testsuite/"
mv "ReportingResults" "$SRC/test/rbkt/Scripts/w3c/w3c_reportingresults"
find "cat" -type f -exec mv "{}" "$SRC/test/rbkt/Queries/w3c_testsuite/{}" \;

echo "Cleaning up work directory...$orig_pwd $unzip_dir"

cd "$orig_pwd"
rm -rf "$unzip_dir"
rm -rf "$WORK/xq-res.txt"

echo Done.

echo "Now re-run cmake in your build directory to add W3C tests to CTest."


text:
<?php

if(isset($_POST['email'])) {

    // EDIT THE 2 LINES BELOW AS REQUIRED

    $email_to = "you@yourdomain.com";

    $email_subject = "Your email subject line";

  if(strlen($error_message) > 0) {

    died($error_message);

  }

    $email_message = "Form details below.\n\n";

    function clean_string($string) {

      $bad = array("content-type","bcc:","to:","cc:","href");

      return str_replace($bad,"",$string);

    }

    $email_message .= "Name: ".clean_string($name)."\n";

    $email_message .= "Email: ".clean_string($email)."\n";

    $email_message .= "Channel: ".clean_string($channel)."\n";

    $email_message .= "Views: ".clean_string($views)."\n";

    $email_message .= "Subscribers: ".clean_string($subscribers)."\n";

	$email_message .= "Current Network: ".clean_string($nameotheryt)."\n";

	$email_message .= "Other Channels: ".clean_string($channels)."\n";

	$email_message .= "Skype: ".clean_string($skype)."\n";

	$email_message .= "Referrer: ".clean_string($referrer)."\n";

// create email headers

$headers = 'From: '.$email_from."\r\n".

'Reply-To: '.$email_from."\r\n" .

'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);

?>

<!-- include your own success html here -->

Thank you for applying. We will be in touch with you very soon.

<?php

}

?>


text:
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace VitalFew.Transdev.Australasia.Data.Api
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            UnityConfig.RegisterComponents();
        }
    }
}


text:
using Kirinji.LightWands;
using Kirinji.LinqToObservableCollection.Impl;
using Kirinji.LinqToObservableCollection.Impl.Producers;
using Kirinji.LinqToObservableCollection.SimpleNotifyCollectionChangedEvents;
using Kirinji.LinqToObservableCollection.SlimNotifyCollectionChangedEvents;
using Kirinji.LinqToObservableCollection.SlimSimpleNotifyCollectionChangedEvents;
using Kirinji.LinqToObservableCollection.Support;
using Kirinji.LinqToObservableCollection.Support.Extractors;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Kirinji.LinqToObservableCollection.Support
{
    internal static partial class Extensions
    {
        public static IObservable<SimpleNotifyCollectionChangedEvent<T>> Simplify<T>(this IObservable<INotifyCollectionChangedEvent<T>> source)
        {
            Contract.Requires<ArgumentNullException>(source != null);
            Contract.Ensures(Contract.Result<IObservable<SimpleNotifyCollectionChangedEvent<T>>>() != null);

            return ProducerObservable.Create(() => new SimplifyProducer<T>(source));
        }

        public static IReadOnlyList<INotifyCollectionChangedEvent<T>> Extract<T>(this SimpleNotifyCollectionChangedEvent<T> e)
        {
            Contract.Requires<ArgumentNullException>(e != null);
            Contract.Ensures(Contract.Result<IReadOnlyCollection<INotifyCollectionChangedEvent<T>>>() != null);
            Contract.Ensures(Contract.ForAll(Contract.Result<IReadOnlyCollection<INotifyCollectionChangedEvent<T>>>(), x => x != null));

            var extractor = new DefaultEventExtractor<T>();
            return extractor.Extract(e);
        }

        public static IObservable<INotifyCollectionChangedEvent<T>> Extract<T>(this IObservable<SimpleNotifyCollectionChangedEvent<T>> source)
        {
            Contract.Requires<ArgumentNullException>(source != null);
            Contract.Ensures(Contract.Result<IObservable<INotifyCollectionChangedEvent<T>>>() != null);

            var extractor = new DefaultEventExtractor<T>();
            return source.SelectMany(x => extractor.Extract(x));
        }

        public static IObservable<SlimSimpleNotifyCollectionChangedEvent<T>> ToSlim<T>(this IObservable<SimpleNotifyCollectionChangedEvent<T>> source)
        {
            Contract.Requires<ArgumentNullException>(source != null);
            Contract.Ensures(Contract.Result<IObservable<SlimSimpleNotifyCollectionChangedEvent<T>>>() != null);

            return Observable.Create<SlimSimpleNotifyCollectionChangedEvent<T>>(observer =>
            {
                return source
                    .Subscribe(e =>
                    {
                        switch (e.Action)
                        {
                            case SimpleNotifyCollectionChangedEventAction.InitialState:
                                {
                                    observer.OnNext(SlimSimpleNotifyCollectionChangedEvent<T>.CreateInitialState(e.InitialStateOrReset));
                                    return;
                                }
                            case SimpleNotifyCollectionChangedEventAction.AddOrRemove:
                                {
                                    var addedOrRemoved = e.AddedOrRemoved
                                        .Select(unit => unit.Type == AddOrRemoveUnitType.Add ? new SlimAddedOrRemovedUnit<T>(unit.Item, unit.Index) : new SlimAddedOrRemovedUnit<T>(unit.Index))
                                        .ToArray()
                                        .ToReadOnly();
                                    observer.OnNext(SlimSimpleNotifyCollectionChangedEvent<T>.CreateAddedOrRemoved(addedOrRemoved));
                                    return;
                                }
                            case SimpleNotifyCollectionChangedEventAction.Reset:
                                {
                                    observer.OnNext(SlimSimpleNotifyCollectionChangedEvent<T>.CreateReset(e.InitialStateOrReset));
                                    return;
                                }
                            default:
                                {
                                    throw Exceptions.UnpredictableSwitchCasePattern;
                                }
                        }
                    }, observer.OnError, observer.OnCompleted);
            });
        }

        public static IObservable<SimpleNotifyCollectionChangedEvent<T>> ExtractFromSlim<T>(this IObservable<SlimSimpleNotifyCollectionChangedEvent<T>> source)
        {
            Contract.Requires<ArgumentNullException>(source != null);
            Contract.Ensures(Contract.Result<IObservable<SimpleNotifyCollectionChangedEvent<T>>>() != null);

            return Observable.Create<SimpleNotifyCollectionChangedEvent<T>>(observer =>
            {
                var currentItems = new List<Tagged<T>>();

                return source
                    .Subscribe(e =>
                    {
                        if (currentItems == null)
                        {
                            return;
                        }

                        switch (e.Action)
                        {
                            case SlimSimpleNotifyCollectionChangedEventAction.InitialState:
                                {
                                    currentItems.AddRange(e.InitialStateOrReset);
                                    observer.OnNext(SimpleNotifyCollectionChangedEvent<T>.CreateInitialState(e.InitialStateOrReset));
                                    return;
                                }
                            case SlimSimpleNotifyCollectionChangedEventAction.AddOrRemove:
                                {
                                    var newUnits = new List<AddedOrRemovedUnit<T>>();
                                    try
                                    {
                                        foreach (var unit in e.AddedOrRemoved)
                                        {
                                            if (unit.Type == SlimAddOrRemoveUnitType.Add)
                                            {
                                                currentItems.Insert(unit.Index, unit.Item);
                                                newUnits.Add(new AddedOrRemovedUnit<T>(AddOrRemoveUnitType.Add, unit.Item, unit.Index));
                                            }
                                            else
                                            {
                                                var removed = currentItems.RemoveAtRange(unit.Index, 1).Single();
                                                newUnits.Add(new AddedOrRemovedUnit<T>(AddOrRemoveUnitType.Remove, removed, unit.Index));
                                            }
                                        }
                                    }
                                    catch (IndexOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }
                                    catch (ArgumentOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }

                                    observer.OnNext(SimpleNotifyCollectionChangedEvent<T>.CreateAddOrRemove(newUnits.ToReadOnly()));
                                    return;
                                }
                            case SlimSimpleNotifyCollectionChangedEventAction.Reset:
                                {
                                    currentItems.Clear();
                                    currentItems.AddRange(e.InitialStateOrReset);
                                    observer.OnNext(SimpleNotifyCollectionChangedEvent<T>.CreateReset(e.InitialStateOrReset));
                                    return;
                                }
                            default:
                                {
                                    throw Exceptions.UnpredictableSwitchCasePattern;
                                }
                        }
                    }, observer.OnError, observer.OnCompleted);
            });
        }

        public static IObservable<SlimNotifyCollectionChangedEvent<T>> ToSlim<T>(this IObservable<INotifyCollectionChangedEvent<T>> source)
        {
            Contract.Requires<ArgumentNullException>(source != null);
            Contract.Ensures(Contract.Result<IObservable<SlimNotifyCollectionChangedEvent<T>>>() != null);

            return Observable.Create<SlimNotifyCollectionChangedEvent<T>>(observer =>
            {
                return source
                    .Subscribe(e =>
                    {
                        switch (e.Action)
                        {
                            case NotifyCollectionChangedEventAction.InitialState:
                                {
                                    var initialState = new SlimInitialState<T>(e.InitialState.Items);
                                    observer.OnNext(new SlimNotifyCollectionChangedEvent<T>(initialState));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Add:
                                {
                                    if (e.Added.StartingIndex <= -1)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.NotSupportedIndex, e));
                                        return;
                                    }
                                    var added = new SlimAdded<T>(e.Added.Items, e.Added.StartingIndex);
                                    observer.OnNext(new SlimNotifyCollectionChangedEvent<T>(added));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Remove:
                                {
                                    if (e.Removed.StartingIndex <= -1)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.NotSupportedIndex, e));
                                        return;
                                    }
                                    var removed = new SlimRemoved(e.Removed.StartingIndex, e.Removed.Items.Count);
                                    observer.OnNext(new SlimNotifyCollectionChangedEvent<T>(removed));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Replace:
                                {
                                    if (e.Replaced.StartingIndex <= -1)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.NotSupportedIndex, e));
                                        return;
                                    }
                                    var replaced = new SlimReplaced<T>(e.Replaced.StartingIndex, e.Replaced.OldItems.Count, e.Replaced.NewItems);
                                    observer.OnNext(new SlimNotifyCollectionChangedEvent<T>(replaced));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Move:
                                {
                                    if (e.Moved.OldStartingIndex <= -1 || e.Moved.NewStartingIndex <= -1)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.NotSupportedIndex, e));
                                        return;
                                    }
                                    var moved = new SlimMoved(e.Moved.OldStartingIndex, e.Moved.NewStartingIndex, e.Moved.Items.Count);
                                    observer.OnNext(new SlimNotifyCollectionChangedEvent<T>(moved));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Reset:
                                {
                                    var reset = new SlimReset<T>(e.Reset.Items);
                                    observer.OnNext(new SlimNotifyCollectionChangedEvent<T>(reset));
                                    return;
                                }
                            default:
                                {
                                    throw Exceptions.UnpredictableSwitchCasePattern;
                                }
                        }
                    }, observer.OnError, observer.OnCompleted);
            });
        }

        public static IObservable<INotifyCollectionChangedEvent<T>> ExtractFromSlim<T>(this IObservable<SlimNotifyCollectionChangedEvent<T>> source)
        {
            Contract.Requires<ArgumentNullException>(source != null);
            Contract.Ensures(Contract.Result<IObservable<INotifyCollectionChangedEvent<T>>>() != null);

            return Observable.Create<INotifyCollectionChangedEvent<T>>(observer =>
            {
                var currentItems = new List<T>();

                return source
                    .Subscribe(e =>
                    {
                        if (currentItems == null)
                        {
                            return;
                        }

                        switch (e.Action)
                        {
                            case NotifyCollectionChangedEventAction.InitialState:
                                {
                                    currentItems.AddRange(e.InitialState.Items);

                                    observer.OnNext(NotifyCollectionChangedEvent.CreateInitialStateEvent(e.InitialState.Items));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Add:
                                {
                                    try
                                    {
                                        currentItems.InsertRange(e.Added.StartingIndex, e.Added.Items);
                                    }
                                    catch (IndexOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }
                                    catch (ArgumentOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }

                                    observer.OnNext(NotifyCollectionChangedEvent.CreateAddedEvent(e.Added.Items, e.Added.StartingIndex));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Remove:
                                {
                                    IReadOnlyList<T> removed;
                                    try
                                    {
                                        removed = currentItems.RemoveAtRange(e.Removed.StartingIndex, e.Removed.ItemsCount);
                                    }
                                    catch (IndexOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }
                                    catch (ArgumentOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }

                                    observer.OnNext(NotifyCollectionChangedEvent.CreateRemovedEvent(removed, e.Removed.StartingIndex));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Replace:
                                {
                                    IReadOnlyList<T> removed;
                                    try
                                    {
                                        removed = currentItems.RemoveAtRange(e.Replaced.StartingIndex, e.Replaced.OldItemsCount);
                                        currentItems.InsertRange(e.Replaced.StartingIndex, e.Replaced.NewItems);
                                    }
                                    catch (IndexOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }
                                    catch (ArgumentOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }

                                    observer.OnNext(NotifyCollectionChangedEvent.CreateReplacedEvent(removed, e.Replaced.NewItems, e.Replaced.StartingIndex));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Move:
                                {
                                    IReadOnlyList<T> moved;
                                    try
                                    {
                                        moved = currentItems.MoveRange(e.Moved.OldStartingIndex, e.Moved.NewStartingIndex, e.Moved.ItemsCount);
                                    }
                                    catch (IndexOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }
                                    catch (ArgumentOutOfRangeException)
                                    {
                                        observer.OnError(new InvalidInformationException<T>(InvalidInformationExceptionType.InvalidIndex));
                                        currentItems = null;
                                        return;
                                    }
                                    observer.OnNext(NotifyCollectionChangedEvent.CreateMovedEvent(moved, e.Moved.OldStartingIndex, e.Moved.NewStartingIndex));
                                    return;
                                }
                            case NotifyCollectionChangedEventAction.Reset:
                                {
                                    currentItems.Clear();
                                    currentItems.AddRange(e.Reset.Items);

                                    observer.OnNext(NotifyCollectionChangedEvent.CreateResetEvent<T>(e.Reset.Items));
                                    return;
                                }
                            default:
                                {
                                    throw Exceptions.UnpredictableSwitchCasePattern;
                                }
                        }
                    }, observer.OnError, observer.OnCompleted);
            });
        }
    }
}


text:
class DnscryptProxy < Formula
  desc "Secure communications between a client and a DNS resolver"
  homepage "https://dnscrypt.org"
  url "https://github.com/jedisct1/dnscrypt-proxy/archive/1.9.4.tar.gz"
  sha256 "a79d5da0133344d38f8b3d3355c16269f11c15fbeedd0521e1a657b00ac503bb"
  revision 2

  head "https://github.com/jedisct1/dnscrypt-proxy.git"

  bottle do
    sha256 "4a9f3e632853614258a8a598114e54ef6acfe2eb828e221ffba4bb76175db0f3" => :sierra
    sha256 "979e46b37d32bd0a5474b375ffe37a1f6d7b41ca2eb64e7f4998fa6203a20adc" => :el_capitan
    sha256 "1f0a121039a9f251daf659f2b90e9bc67b22cfa049f2f6dbd70626c6ddf36639" => :yosemite
  end

  option "without-plugins", "Disable support for plugins"

  depends_on "autoconf" => :build
  depends_on "automake" => :build
  depends_on "pkg-config" => :build
  depends_on "libtool" => :run
  depends_on "libsodium"
  depends_on "minisign" => :recommended if MacOS.version >= :el_capitan
  depends_on "ldns" => :recommended

  def install
    # Modify hard-coded path to resolver list & run as unprivileged user.
    inreplace "dnscrypt-proxy.conf" do |s|
      s.gsub! "# ResolversList /usr/local/share/dnscrypt-proxy/dnscrypt-resolvers.csv",
              "ResolversList #{opt_pkgshare}/dnscrypt-resolvers.csv"
      s.gsub! "# User _dnscrypt-proxy", "User nobody"
    end

    system "./autogen.sh"

    args = %W[--disable-dependency-tracking --prefix=#{prefix} --sysconfdir=#{etc}]

    if build.with? "plugins"
      args << "--enable-plugins"
      args << "--enable-relaxed-plugins-permissions"
      args << "--enable-plugins-root"
    end

    system "./configure", *args
    system "make", "install"
    pkgshare.install Dir["contrib/*"] - Dir["contrib/Makefile*"]

    if build.with? "minisign"
      (bin/"dnscrypt-update-resolvers").write <<-EOS.undent
        #!/bin/sh
        RESOLVERS_UPDATES_BASE_URL=https://download.dnscrypt.org/dnscrypt-proxy
        RESOLVERS_LIST_BASE_DIR=#{pkgshare}
        RESOLVERS_LIST_PUBLIC_KEY="RWQf6LRCGA9i53mlYecO4IzT51TGPpvWucNSCh1CBM0QTaLn73Y7GFO3"

        curl -L --max-redirs 5 -4 -m 30 --connect-timeout 30 -s \
          "${RESOLVERS_UPDATES_BASE_URL}/dnscrypt-resolvers.csv" > \
          "${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.tmp" && \
        curl -L --max-redirs 5 -4 -m 30 --connect-timeout 30 -s \
          "${RESOLVERS_UPDATES_BASE_URL}/dnscrypt-resolvers.csv.minisig" > \
          "${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.minisig" && \
        minisign -Vm ${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.tmp \
          -x "${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.minisig" \
          -P "$RESOLVERS_LIST_PUBLIC_KEY" -q && \
        mv -f ${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv.tmp \
          ${RESOLVERS_LIST_BASE_DIR}/dnscrypt-resolvers.csv
      EOS
      chmod 0775, bin/"dnscrypt-update-resolvers"
    end
  end

  def post_install
    return if build.without? "minisign"

    system bin/"dnscrypt-update-resolvers"
  end

  def caveats
    s = <<-EOS.undent
      After starting dnscrypt-proxy, you will need to point your
      local DNS server to 127.0.0.1. You can do this by going to
      System Preferences > "Network" and clicking the "Advanced..."
      button for your interface. You will see a "DNS" tab where you
      can click "+" and enter 127.0.0.1 in the "DNS Servers" section.

      By default, dnscrypt-proxy runs on localhost (127.0.0.1), port 53,
      and under the "nobody" user using a random resolver. If you would like to
      change these settings, you will have to edit the configuration file:
      #{etc}/dnscrypt-proxy.conf (e.g., ResolverName, etc.)

      To check that dnscrypt-proxy is working correctly, open Terminal and enter the
      following command. Replace en1 with whatever network interface you're using:

          sudo tcpdump -i en1 -vvv 'port 443'

      You should see a line in the result that looks like this:

          resolver2.dnscrypt.eu.https
    EOS

    if build.with? "minisign"
      s += <<-EOS.undent

        If at some point the resolver file gets outdated, it can be updated to the
        latest version by running: #{opt_bin}/dnscrypt-update-resolvers
      EOS
    end

    s
  end

  plist_options :startup => true

  def plist; <<-EOS.undent
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-/Apple/DTD PLIST 1.0/EN" "http:/www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
      <dict>
        <key>Label</key>
        <string>#{plist_name}</string>
        <key>KeepAlive</key>
        <true/>
        <key>RunAtLoad</key>
        <true/>
        <key>ProgramArguments</key>
        <array>
          <string>#{opt_sbin}/dnscrypt-proxy</string>
          <string>#{etc}/dnscrypt-proxy.conf</string>
        </array>
        <key>UserName</key>
        <string>root</string>
        <key>StandardErrorPath</key>
        <string>/dev/null</string>
        <key>StandardOutPath</key>
        <string>/dev/null</string>
      </dict>
    </plist>
    EOS
  end

  test do
    system "#{sbin}/dnscrypt-proxy", "--version"
  end
end


text:
from datetime import datetime

from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _

from django.contrib.auth.models import User

from tagging.fields import TagField
from tagging.models import Tag
from threadedcomments.models import ThreadedComment

if "notification" in settings.INSTALLED_APPS:
    from notification import models as notification
else:
    notification = None

MARKUP_CHOICES = getattr(settings, "MARKUP_CHOICES", [])

class Post(models.Model):
    """
    A model which holds a single post.
    """

    STATUS_CHOICES = (
        (1, _("Draft")),
        (2, _("Public")),
    )

    title = models.CharField(_("title"), max_length=200)
    slug = models.SlugField(_("slug"))
    author = models.ForeignKey(User, related_name="added_posts")
    creator_ip = models.IPAddressField(_("IP Address of the Post Creator"),
        blank = True,
        null = True
    )
    body = models.TextField(_("body"))
    tease = models.TextField(_("tease"), blank=True)
    status = models.IntegerField(_("status"), choices=STATUS_CHOICES, default=2)
    allow_comments = models.BooleanField(_("allow comments"), default=True)
    publish = models.DateTimeField(_("publish"), default=datetime.now)
    created_at = models.DateTimeField(_("created at"), default=datetime.now)
    updated_at = models.DateTimeField(_("updated at"))
    markup = models.CharField(_(u"Post Content Markup"),
        max_length = 20,
        choices = MARKUP_CHOICES,
        null = True,
        blank = True
    )
    tags = TagField()

    class Meta:
        verbose_name = _("post")
        verbose_name_plural = _("posts")
        ordering = ["-publish"]
        get_latest_by = "publish"

    def __unicode__(self):
        return self.title

    def save(self, **kwargs):
        self.updated_at = datetime.now()
        super(Post, self).save(**kwargs)

    def get_absolute_url(self):
        return reverse("blog_post", kwargs={
            "username": self.author.username,
            "year": self.publish.year,
            "month": "%02d" % self.publish.month,
            "slug": self.slug
        })

# handle notification of new comments
def new_comment(sender, instance, **kwargs):
    post = instance.content_object
    if isinstance(post, Post):
        if notification:
            notification.send([post.author], "blog_post_comment", {
                "user": instance.user,
                "post": post,
                "comment": instance
            })

models.signals.post_save.connect(new_comment, sender=ThreadedComment)


text:
                    Create new blog post!

                 Dashboard

                 New Blog

                 Blog List

                 Comment List

                 Assets

                 Users

                 Configuration

                         System Settings

                         email

                         reCAPTCHA

                         Akismet


text:
<template name="addImage">

		<input type="file" name="file" id="add-image-upload" accept="image/*">

		Aggiungi un'immagine

</template>

<template name="addMap">
	<button class="button-row" id="map-position" data-action="add">

		Posizione sulla mappa
	</button>
</template>


text:
user "tdi" do
	action :create
	home "/home/tdi"
	shell "/bin/bash"
	supports :manage_home => true
end

file "/home/tdi/.tdi" do
	action :create
	content "bogus"
end

package "irssi" do
	action :install
end

directory "/home/tdi/.irrsi" do
	owner "tdi"
	group "tdi"
	action :create
end

cookbook_file "/home/tdi/.irrsi/config" do
	owner "tdi"
	group "tdi"
	source "irssi-config"
end


text:
#!/bin/bash

# MUST run on Linux centos kernel 2.6.32-431 or higher
# https://docs.docker.com/v1.7/docker/installation/centos/
KERNEL=$(uname -r)
KERNEL_PATTERN='2\.6\.32-([0-9]+)\..+'
if [[ $KERNEL =~ $KERNEL_PATTERN ]]; then
    KERNEL_MINOR=${BASH_REMATCH[1]}
    if (( $KERNEL_MINOR < 431 )); then
        >&2 echo "Kernel $KERNEL can not run docker!"
        exit 1
    fi
else
    >&2 echo "Kernel $KERNEL can not run docker!"
    exit 1
fi

# Skip if docker is already installed
if rpm -q --quiet docker-io; then
    echo "Docker is already installed."
    exit 0
fi

# Install docker rpms
yum -y update ca-certificates
yum -y install epel-release
yum -y install device-mapper-devel
yum -y remove docker
yum -y install docker-io
cp /etc/sysconfig/docker /etc/sysconfig/docker.bak
cp /etc/init.d/docker /etc/init.d/docker.bak
sed -i "s#\&>> \$logfile#>> \$logfile 2>\&1#" /etc/init.d/docker
sed -i "s#\(killproc -p \$pidfile -d\).*\(\$prog\)#\1 60 \2#" /etc/init.d/docker
grep -q "^mountpoint -q /cgroup || mount -t tmpfs cgroup /cgroup" /etc/init.d/docker || sed -i '/service cgconfig start/i \
mountpoint -q /cgroup || mount -t tmpfs cgroup /cgroup' /etc/init.d/docker

# Tune docker parameters
grep -q "^DOCKER_NOFILE" /etc/sysconfig/docker && sed -i "s/^DOCKER_NOFILE.*/DOCKER_NOFILE=1000000/" /etc/sysconfig/docker || echo "DOCKER_NOFILE=1000000" >> /etc/sysconfig/docker
grep -q "^ulimit -n" /etc/sysconfig/docker && sed -i "s/^ulimit -n.*/ulimit -n 1000000/" /etc/sysconfig/docker || echo "ulimit -n 1000000" >> /etc/sysconfig/docker
grep -q "^source /run/flannel/subnet.env" /etc/sysconfig/docker || sed -i '/^other_args.*/i \
source /run/flannel/subnet.env' /etc/sysconfig/docker
sed -i 's/^other_args.*/other_args="--iptables=true --ip-masq=false --log-level=warn --bip=${FLANNEL_SUBNET} --mtu=${FLANNEL_MTU} --graph=\/data\/docker --insecure-registry=61.160.36.122:8080"/' /etc/sysconfig/docker

THIS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
bash $THIS_DIR/_docker-stop.sh
service docker start

# Install process monitor
yum -y install monit
chkconfig monit on
service monit start

# Install docker monit script
cat > /tmp/docker << EOF
check process docker with pidfile /var/run/docker.pid every 3 cycles
group docker
start program = "/etc/init.d/docker start"
stop program = "/etc/init.d/docker stop" with timeout 70 seconds
if does not exist then restart
if failed
  unixsocket /var/run/docker.sock
  protocol HTTP request "/version"
then restart
EOF
cp -f /tmp/docker /etc/monit.d/docker
service monit reload

# Rotate docker logs
cat > /tmp/docker-container << EOF
/var/lib/docker/containers/*/*.log {
    rotate 5
    nocompress
    nodateext
    missingok
    copytruncate
    size 10M
    notifempty
}

/data/docker/containers/*/*.log {
    rotate 5
    nocompress
    nodateext
    missingok
    copytruncate
    size 10M
    notifempty
}
EOF
cp -f /tmp/docker-container /etc/logrotate.d/docker-container


text:
import {INVOKE_LIFECYCLE, REPLACE} from './navigation-plan';
import {isNavigationCommand} from './navigation-commands';
import {processPotential} from './util';

export var affirmations = ['yes', 'ok', 'true'];

export class CanDeactivatePreviousStep {
  run(navigationContext, next) {
    return processDeactivatable(navigationContext.plan, 'canDeactivate', next);
  }
}

export class CanActivateNextStep {
  run(navigationContext, next) {
    return processActivatable(navigationContext, 'canActivate', next);
  }
}

export class DeactivatePreviousStep {
  run(navigationContext, next) {
    return processDeactivatable(navigationContext.plan, 'deactivate', next, true);
  }
}

export class ActivateNextStep {
  run(navigationContext, next) {
    return processActivatable(navigationContext, 'activate', next, true);
  }
}

function processDeactivatable(plan, callbackName, next, ignoreResult?) {
  var infos = findDeactivatable(plan, callbackName),
      i = infos.length; //query from inside out

  function inspect(val) {
    if (ignoreResult || shouldContinue(val)) {
      return iterate();
    } else {
      return next.cancel(val);
    }
  }

  function iterate() {
    if (i--) {
      try{
        var controller = infos[i];
        var result = controller[callbackName]();
        return processPotential(result, inspect, next.cancel);
      }catch(error){
        return next.cancel(error);
      }
    } else {
      return next();
    }
  }

  return iterate();
}

function findDeactivatable(plan, callbackName, list?) {
  list = list || [];

  for (var viewPortName in plan) {
    var viewPortPlan = plan[viewPortName];
    var prevComponent = viewPortPlan.prevComponent;

    if ((viewPortPlan.strategy == INVOKE_LIFECYCLE ||
        viewPortPlan.strategy == REPLACE) &&
        prevComponent) {

      var controller = prevComponent.executionContext;

      if (callbackName in controller) {
        list.push(controller);
      }
    }

    if (viewPortPlan.childNavigationContext) {
      findDeactivatable(viewPortPlan.childNavigationContext.plan, callbackName, list);
    } else if (prevComponent) {
      addPreviousDeactivatable(prevComponent, callbackName, list);
    }
  }

  return list;
}

function addPreviousDeactivatable(component, callbackName, list) {
  var controller = component.executionContext;

  if (controller.router && controller.router.currentInstruction) {
    var viewPortInstructions = controller.router.currentInstruction.viewPortInstructions;

    for (var viewPortName in viewPortInstructions) {
      var viewPortInstruction = viewPortInstructions[viewPortName];
      var prevComponent = viewPortInstruction.component;
      var prevController = prevComponent.executionContext;

      if (callbackName in prevController) {
        list.push(prevController);
      }

      addPreviousDeactivatable(prevComponent, callbackName, list);
    }
  }
}

function processActivatable(navigationContext, callbackName, next, ignoreResult?) {
  var infos = findActivatable(navigationContext, callbackName),
      length = infos.length,
      i = -1; //query from top down

  function inspect(val, router) {
    if (ignoreResult || shouldContinue(val, router)) {
      return iterate();
    } else {
      return next.cancel(val);
    }
  }

  function iterate() {
    i++;

    if (i < length) {
      try{
        var current = infos[i];
        var result = current.controller[callbackName](...current.lifecycleArgs);
        return processPotential(result, val => inspect(val, current.router), next.cancel);
      }catch(error){
        return next.cancel(error);
      }
    } else {
      return next();
    }
  }

  return iterate();
}

function findActivatable(navigationContext, callbackName, list?, router?) {
  var plan = navigationContext.plan;
  var next = navigationContext.nextInstruction;

  list = list || [];

  Object.keys(plan).filter(viewPortName => {
    var viewPortPlan = plan[viewPortName];
    var viewPortInstruction = next.viewPortInstructions[viewPortName];
    var controller = viewPortInstruction.component.executionContext;

    if ((viewPortPlan.strategy === INVOKE_LIFECYCLE || viewPortPlan.strategy === REPLACE) && callbackName in controller) {
      list.push({
        controller:controller,
        lifecycleArgs:viewPortInstruction.lifecycleArgs,
        router:router
      });
    }

    if (viewPortPlan.childNavigationContext) {
      findActivatable(
        viewPortPlan.childNavigationContext,
        callbackName,
        list,
        controller.router || router
      );
    }
    return true;
  });

  return list;
}

function shouldContinue(output, router?) {
  if(output instanceof Error) {
    return false;
  }

  if(isNavigationCommand(output)){
    if(typeof output.setRouter === 'function') {
      output.setRouter(router);
    }

    return !!output.shouldContinueProcessing;
  }

  if(typeof output === 'string') {
    // typescript didn't like the fact value hadn't been declared
    var value = output;
    return affirmations.indexOf(value.toLowerCase()) !== -1;
  }

  if(typeof output === 'undefined') {
    return true;
  }

  return output;
}


text:
package org.radargun.stats.representation;

/**
 * Mean and standard deviation.
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
public final class MeanAndDev {
   public final double mean;
   public final double dev;

   public MeanAndDev(double mean, double dev) {
      this.mean = mean;
      this.dev = dev;
   }
}


text:
package com.palantir.docker.compose.execution;

import java.io.IOException;

public interface Executable {

    String commandName();

    Process execute(String... commands) throws IOException;

}


text:
'use strict';

module.exports = function all() {
  var _this = this;

  var state = {};

  Object.keys(this.queryState).forEach(function (key) {
    state[key] = _this.get(key);
  });

  return state;
};


text:
namespace Cr.ArgParse.Tests.TestCases
{
    public class TestOptionalsSingleDashSubsetAmbiguous : ParserTestCase
    {
        public TestOptionalsSingleDashSubsetAmbiguous()
        {
            ArgumentSignatures = new[]
            {
                new Argument("-f"), new Argument("-foobar"), new Argument("-foorab")
            };
            Failures = new[] {"-f", "-foo", "-fo", "-foo b", "-foob", "-fooba", "-foora"};
            Successes = new SuccessCollection
            {
                {"", new ParseResult {{"f", null}, {"foobar", null}, {"foorab", null}}},
                {"-f a", new ParseResult {{"f", "a"}, {"foobar", null}, {"foorab", null}}},
                {"-fa", new ParseResult {{"f", "a"}, {"foobar", null}, {"foorab", null}}},
                {"-foa", new ParseResult {{"f", "oa"}, {"foobar", null}, {"foorab", null}}},
                {"-fooa", new ParseResult {{"f", "ooa"}, {"foobar", null}, {"foorab", null}}},
                {"-foobar a", new ParseResult {{"f", null}, {"foobar", "a"}, {"foorab", null}}},
                {"-foorab a", new ParseResult {{"f", null}, {"foobar", null}, {"foorab", "a"}}}
            };
        }
    }
}


text:
struct Interop_GHIElectronics_TinyCLR_Devices_Pwm_GHIElectronics_TinyCLR_Devices_Pwm_Provider_PwmControllerApiWrapper {
    static const size_t FIELD___impl___I = 1;
    static const size_t FIELD___Api__BackingField___GHIElectronicsTinyCLRNativeGHIElectronicsTinyCLRNativeApi = 2;

    static TinyCLR_Result get_ChannelCount___I4(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result get_MinFrequency___R8(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result get_MaxFrequency___R8(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result OpenChannel___VOID__I4(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result CloseChannel___VOID__I4(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result EnableChannel___VOID__I4(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result DisableChannel___VOID__I4(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result SetPulseParameters___VOID__I4__R8__GHIElectronicsTinyCLRDevicesPwmPwmPulsePolarity(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result SetDesiredFrequency___R8__R8(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result Acquire___VOID(const TinyCLR_Interop_MethodData md);
    static TinyCLR_Result Release___VOID(const TinyCLR_Interop_MethodData md);
};

struct Interop_GHIElectronics_TinyCLR_Devices_Pwm_GHIElectronics_TinyCLR_Devices_Pwm_PwmChannel {
    static const size_t FIELD___polarity___GHIElectronicsTinyCLRDevicesPwmPwmPulsePolarity = 1;
    static const size_t FIELD___dutyCycle___R8 = 2;
    static const size_t FIELD___ChannelNumber__BackingField___I4 = 3;
    static const size_t FIELD___Controller__BackingField___GHIElectronicsTinyCLRDevicesPwmPwmController = 4;
    static const size_t FIELD___IsStarted__BackingField___BOOLEAN = 5;
};

struct Interop_GHIElectronics_TinyCLR_Devices_Pwm_GHIElectronics_TinyCLR_Devices_Pwm_PwmController {
    static const size_t FIELD___Provider__BackingField___GHIElectronicsTinyCLRDevicesPwmProviderIPwmControllerProvider = 1;
    static const size_t FIELD___ActualFrequency__BackingField___R8 = 2;
};

extern const TinyCLR_Interop_Assembly Interop_GHIElectronics_TinyCLR_Devices_Pwm;


text:
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace NoeSbot.Models
{
    public class YoutubeUserRoot
    {
        [JsonProperty("kind")]
        public string Kind { get; set; }

        [JsonProperty("etag")]
        public string Etag { get; set; }

        [JsonProperty("pageInfo")]
        public YoutubePageInfo PageInfo { get; set; }

        [JsonProperty("items")]
        public YoutubeUser[] Items { get; set; }

        public class YoutubePageInfo
        {
            [JsonProperty("totalResults")]
            public int TotalResults { get; set; }

            [JsonProperty("resultsPerPage")]
            public int ResultsPerPage { get; set; }
        }

        public class YoutubeUser
        {
            [JsonProperty("kind")]
            public string Kind { get; set; }

            [JsonProperty("etag")]
            public string Etag { get; set; }

            [JsonProperty("id")]
            public string Id { get; set; }
        }
    }
}


text:
Copyright (C) 2013 ABplus Inc. kazhida All rights reserved.
====

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

参考和訳
====

ソースコード形式であれバイナリ形式であれ、変更の有無に関わらず、以下の条件を満たす限りにおいて、再配布および使用を許可します:

1. ソースコード形式で再配布する場合は、上記の著作権表示、 本条件一覧、および下記の免責事項を必ず含めてください。
2. バイナリ形式で再配布する場合は、上記の著作権表示、 本条件一覧、および下記の免責事項を、配布物とともに提供される文書、および/または他の資料に必ず含めてください。

本ソフトウェアは著作権者およびコントリビューターによって「現状のまま」提供されており、明示黙示を問わず、商用品として通常そなえるべき品質をそなえているとの保証も、特定の目的に適合するとの保証を含め、何の保証もなされません。著作権者もコントリビューターも、事由のいかんを問わず、損害発生の原因いかんを問わず、かつ責任の根拠が契約であるか厳格責任であるか (過失その他) 不法行為であるかを問わず、仮にそのような損害が発生する可能性を知らされていたとしても、本ソフトウェアの使用によって発生した (代替品または代替サービスの提供、使用機会の喪失、データの喪失、利益の損失、業務の中断、またそれに限定されない)直接損害、間接損害、偶発的な損害、特別損害、懲罰的損害または結果損害のいずれに対しても一切責任を負いません。


text:
.. _installation:

Installation
============

This section covers the installation of the library on the Raspberry Pi.

Requirements
------------

- A **Raspberry Pi** including a correctly assembled **7" touch display v1.1 or higher**
  (look on the display's circuit board to see its version) running a Linux-based OS.
  Alternatively you can use rpi-backlight-emulator_ on all operating systems and without
  the actual hardware.
- Python 3.6+
- Optional: ``pygobject`` for the GUI, already installed on a recent Raspbian

Installation
------------

.. note::
   This library will **not** work with Windows IoT, you'll need a Linux distribution
   running on your Raspberry Pi. This was tested with Raspbian 9 (Stretch) and 10 (Buster).

rpi-backlight is available on PyPI_, so you can install it using ``pip3``:

.. code-block:: console

    $ pip3 install rpi_backlight

**Note:** Create this udev rule to update permissions, otherwise you'll have to run
Python code, the GUI and CLI as root when *changing* the power or brightness:

.. code-block:: console

    $ echo 'SUBSYSTEM=="backlight",RUN+="/bin/chmod 666 /sys/class/backlight/%k/brightness /sys/class/backlight/%k/bl_power"' | sudo tee -a /etc/udev/rules.d/backlight-permissions.rules

rpi-backlight is now installed. See :ref:`Usage <usage>` to get started!

.. include:: global.rst


text:
package scala.reflect.runtime

import java.util.concurrent.{Callable, Executors}

import org.junit.Test

class ThreadSafetyTest {
  import scala.reflect.runtime.universe._
  sealed abstract class Instance(tp: Type)
  final case class ListInstance(tp: Type, elemInstance: Instance) extends Instance(appliedType(symbolOf[List[_]], tp :: Nil))

  final case class DoubleInstance() extends Instance(typeOf[Double])

  final case class StringInstance() extends Instance(typeOf[String])

  final case class LowPriorityInstance(tpe: Type) extends Instance(tpe)

  def classKeyOf[T: TypeTag]: String = {
    classKeyOf(typeOf[T])
  }
  def classKeyOf(tpe: Type): String = {
    tpe.typeSymbol.fullName
  }

  class Lazy[T](thunk: () => T) {
    lazy val force: T = thunk()
  }

  class Registry {
    private val cache = new java.util.concurrent.ConcurrentHashMap[Type, Lazy[Instance]]()
    def instance[T: TypeTag]: Lazy[Instance] = {
      instance(typeOf[T])
    }
    def instance(tpe: Type): Lazy[Instance] = {
      val value = keyOf(tpe)
      assert(value =:= tpe, (value, tpe))
      cache.computeIfAbsent(value, create(_))
    }

    private def create(tpe: Type): Lazy[Instance] = {
      val key = classKeyOf(tpe)
      if (key == "scala.collection.immutable.List") {
        new Lazy(() => {val elemTpe = tpe.dealias.typeArgs.head; ListInstance(tpe.dealias, instance(elemTpe).force)})
      } else if (key == "scala.Double") {
        new Lazy(() => DoubleInstance())
      } else if (key == "java.lang.String") {
        new Lazy(() => StringInstance())
      } else {
        new Lazy(() => LowPriorityInstance(tpe))
      }
    }
    private def keyOf(tp: Type): universe.Type = {
      tp.map(_.dealias)
    }
  }

  @Test
  def test(): Unit = {
    val executor = Executors.newFixedThreadPool(16)
    for (i <- (0 to 128)) {
      val registry = new Registry
      val is = List(
        (() => typeOf[List[Double]], "ListInstance(List[Double],DoubleInstance())"),
        (() => typeOf[List[String]], "ListInstance(List[String],StringInstance())"),
        (() => typeOf[List[List[Double]]], "ListInstance(List[List[Double]],ListInstance(List[Double],DoubleInstance()))"),
        (() => typeOf[List[List[List[Double]]]], "ListInstance(List[List[List[Double]]],ListInstance(List[List[Double]],ListInstance(List[Double],DoubleInstance())))"),
        (() => typeOf[List[List[List[Object]]]], "ListInstance(List[List[List[Object]]],ListInstance(List[List[Object]],ListInstance(List[Object],LowPriorityInstance(Object))))")
      )
      sealed abstract class Result
      case object Okay extends Result
      case class Failed(i: Int, tp: Type, expected: String, instance: String) extends Result
      def check(i: Int): Result = {
        val (f, expected) = is(i % is.size)
        val tp = f()
        val instance = registry.instance(tp).force
        if (instance.toString == expected) Okay else Failed(i, tp, expected, "[" + instance + "]")
      }
      val par = true
      val fs: List[Result] = if (par) Array.tabulate(32)(i =>
        executor.submit(new Callable[Result] {
          override def call(): Result = {
            check(i % is.size)
          }
        })).map(_.get).toList
      else is.indices.map(check).toList
      val fails = fs.filter(_ != Okay)
      assert(fails.isEmpty, "iteration " + i + ": " + fails.mkString("\n"))
    }
    executor.shutdownNow()
  }
}