text:
package com.seanox.devwex;

import java.io.File;
import java.util.StringTokenizer;

import org.junit.Assert;
import org.junit.Test;

import com.seanox.test.HttpUtils;
import com.seanox.test.HttpUtils.HeaderField;
import com.seanox.test.Pattern;

/**
 * Test cases for {@link com.seanox.devwex.Worker}.
 *
 * @author  Seanox Software Solutions
 * @version 5.5.0 20220909
 */
public class WorkerTest_Get extends AbstractStageRequestTest {

    /**
     * Test case for acceptance.
     * Directories are responded with status 200 and without Content-Length.
     * @throws Exception
     */
    @Test
    public void testAcceptance_01()
            throws Exception {

        final String request = "Get / HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
    }

    /**
     * Test case for acceptance.
     * Directories without a slash at the end, are responded with status 302 and
     * a redirect.
     * @throws Exception
     */
    @Test
    public void testAcceptance_02()
            throws Exception {

        final String request = "Get /test_a HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_302));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_LOCATION("http://vHa:18180/test_a/")));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH_DIFFUSE));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE_DIFFUSE));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED_DIFFUSE));

        final String accessLog = AbstractStage.getAccessStreamCapture().fetch(ACCESS_LOG_RESPONSE_UUID(response));
        Assert.assertTrue(accessLog, accessLog.matches(Pattern.ACCESS_LOG_STATUS_302));
    }

    /**
     * Test case for acceptance.
     * Directories these not exists, are responded with status 404.
     * @throws Exception
     */
    @Test
    public void testAcceptance_03()
            throws Exception {

        final String request = "Get /test_ax HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_404));
    }

    /**
     * Test case for acceptance.
     * Files are responded with status 200, Content-Length, Content-Type and
     * LastModified.
     * @throws Exception
     */
    @Test
    public void testAcceptance_04()
            throws Exception {

        final String request = "Get /method_file.txt HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE));
    }

    /**
     * Test case for acceptance.
     * Files with a slash at the end, are responded with status 302 and a
     * redirect.
     * @throws Exception
     */
    @Test
    public void testAcceptance_05()
            throws Exception {

        final String request = "Get /method_file.txt/ HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_302));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_LOCATION("http://vHa:18180/method_file.txt")));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH_DIFFUSE));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE_DIFFUSE));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED_DIFFUSE));

        final String accessLog = AbstractStage.getAccessStreamCapture().fetch(ACCESS_LOG_RESPONSE_UUID(response));
        Assert.assertTrue(accessLog, accessLog.matches(Pattern.ACCESS_LOG_STATUS_302));
    }

    /**
     * Test case for acceptance.
     * Requests with a correct If-Modified-Since are responded with status 304.
     * @throws Exception
     */
    @Test
    public void testAcceptance_06()
            throws Exception {

        String request;
        String response;

        request = "Get /documents/commons/lastmodified.jsx HTTP/1.0\r\n"
                + "File: ./stage/documents_vh_A/method_file.txt\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        String lastModified = response.replaceAll(Pattern.HTTP_RESPONSE, "$2");

        request = "Get /method_file.txt HTTP/1.0\r\n"
                + "If-Modified-Since: " + lastModified + "\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_304));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_LOCATION_DIFFUSE));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH_DIFFUSE));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE_DIFFUSE));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED_DIFFUSE));

        final String accessLog = AbstractStage.getAccessStreamCapture().fetch(ACCESS_LOG_RESPONSE_UUID(response));
        Assert.assertTrue(accessLog, accessLog.matches(Pattern.ACCESS_LOG_STATUS_304));
    }

    /**
     * Test case for acceptance.
     * Requests with an incorrect If-Modified-Since are responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_07()
            throws Exception {

        final String request = "Get /method_file.txt HTTP/1.0\r\n"
                + "If-Modified-Since: Mon, 19 Jan 2004 16:58:55 GMT\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE));
    }

    /**
     * Test case for acceptance.
     * Requests with a correct If-Modified-Since (incl. length) are responded
     * with status 304.
     * @throws Exception
     */
    @Test
    public void testAcceptance_08()
            throws Exception {

        String request;
        String response;

        request = "Get /documents/commons/lastmodified.jsx HTTP/1.0\r\n"
                + "File: ./stage/documents_vh_A/method_file.txt\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        String lastModified = response.replaceAll(Pattern.HTTP_RESPONSE, "$2");

        request = "Get /method_file.txt HTTP/1.0\r\n"
                + "If-Modified-Since: " + lastModified + "; xxx; length=15\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_304));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH_DIFFUSE));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE_DIFFUSE));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED_DIFFUSE));

        final String accessLog = AbstractStage.getAccessStreamCapture().fetch(ACCESS_LOG_RESPONSE_UUID(response));
        Assert.assertTrue(accessLog, accessLog.matches(Pattern.ACCESS_LOG_STATUS_304));
    }

    /**
     * Test case for acceptance.
     * Requests with a If-Modified-Since (correct date, invalid length) are
     * responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_09()
            throws Exception {

        final String request = "Get /method_file.txt HTTP/1.0\r\n"
                + "If-Modified-Since: Mon, 19 Jan 2004 16:58:56 GMT; xxx; length=21\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE));
    }

    /**
     * Test case for acceptance.
     * Requests with another If-Modified-Since are responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_10()
            throws Exception {

        final String request = "Get /method_file.txt HTTP/1.0\r\n"
                + "If-Modified-Since: Mon, 19 Jan 2004 16:58:57 GMT; xxx; length=20\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE));
    }

    /**
     * Test case for acceptance.
     * Requested directories with a default page are responded with status 200
     * and the details of the default page.
     * @throws Exception
     */
    @Test
    public void testAcceptance_11()
            throws Exception {

        final String request = "Get /test_a/ HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE));
    }

    /**
     * Test case for acceptance.
     * The If-Modified-Since is ignored for directories.
     * The request are responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_12()
            throws Exception {

        final String request = "Get /test_d/ HTTP/1.0\r\n"
                + "If-Modified-Since: Mon, 11 Jan 2004 19:11:58 GMT\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE_TEXT_HTML));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED_DIFFUSE));
    }

    /**
     * Test case for acceptance.
     * The If-Modified-Since is ignored for directories.
     * The request are responded with status 403, because the access is
     * forbidden.
     * @throws Exception
     */
    @Test
    public void testAcceptance_13()
            throws Exception {

        final String request = "Get /forbidden HTTP/1.0\r\n"
                + "If-Modified-Since: Mon, 11 Jan 2004 19:11:58 GMT\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_403));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED_DIFFUSE));
    }

    /**
     * Test case for acceptance.
     * The If-Modified-Since is ignored for absolutes paths.
     * The request are responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_14()
            throws Exception {

        final String request = "Get /absolute HTTP/1.0\r\n"
                + "If-Modified-Since: Mon, 11 Jan 2004 19:11:58 GMT\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE));
    }

    /**
     * Test case for acceptance.
     * The If-Modified-Since is ignored for absolutes paths.
     * The request are responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_15()
            throws Exception {

        final String request = "Get /absolutexxx HTTP/1.0\r\n"
                + "If-Modified-Since: Mon, 11 Jan 2004 19:11:58 GMT\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE));
    }

    /**
     * Test case for acceptance.
     * The If-Modified-Since is ignored for the CGI.
     * The request are responded with status 405, because the CGI does not
     * exist.
     * @throws Exception
     */
    @Test
    public void testAcceptance_16()
            throws Exception {

        final String request = "Get /method.jsx HTTP/1.0\r\n"
                + "If-Modified-Since: Mon, 11 Jan 2004 19:11:58 GMT\r\n"
                + "Host: vHe\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_405));
        Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_LAST_MODIFIED_DIFFUSE));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_TYPE));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
    }

    /**
     * Test case for acceptance.
     * The request are responded with status 200 by the CGI self, if the HEAD
     * method allowed.
     * @throws Exception
     */
    @Test
    public void testAcceptance_17()
            throws Exception {

        final String request = "Get /method.jsx HTTP/1.0\r\n"
                + "Host: vHb\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        final String body = response.replaceAll(Pattern.HTTP_RESPONSE, "$2");
        Assert.assertEquals("hallo", body);
    }

    /**
     * Test case for acceptance.
     * The decoding (MIME/UTF8) from the URL must work.
     * The request is responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_18()
            throws Exception {

        final String request = "Get /decoding_ma\u00DF1bc.html HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(3)));
    }

    /**
     * Test case for acceptance.
     * The decoding (MIME/UTF8) from the URL must work.
     * The request is responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_19()
            throws Exception {

        final String request = "Get /decoding_ma\u00DF1bc.html HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(3)));
    }

    /**
     * Test case for acceptance.
     * The decoding (MIME/UTF8) from the URL must work.
     * The request is responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_20()
            throws Exception {

        final String request = "Get /decoding_ma%DF1bc.html HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(3)));
    }

    /**
     * Test case for acceptance.
     * The decoding (MIME/UTF8) from the URL must work.
     * The request is responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_21()
            throws Exception {

        final String request = "Get /decoding_ma%c3%9f1bc.html HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(3)));
    }

    /**
     * Test case for acceptance.
     * The decoding (MIME/UTF8) from the URL must work.
     * The request is responded with status 200.
     * @throws Exception
     */
    @Test
    public void testAcceptance_22()
            throws Exception {

        final String request = "Get /decoding_ma\u00DF123.html HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(3)));
        final String body = response.replaceAll(Pattern.HTTP_RESPONSE, "$2");
        Assert.assertEquals("-0-", body);
    }

    /**
     * Test case for acceptance.
     * The decoding (MIME/UTF8) from the URL must work.
     * The request is responded with status 200 and the correct content.
     * @throws Exception
     */
    @Test
    public void testAcceptance_23()
            throws Exception {

        final String request = "Get /decoding_ma%DF123.html HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(3)));
        final String body = response.replaceAll(Pattern.HTTP_RESPONSE, "$2");
        Assert.assertEquals("-0-", body);
    }

    /**
     * Test case for acceptance.
     * The decoding (MIME/UTF8) from the URL must work.
     * The request is responded with status 200 and the correct content.
     * @throws Exception
     */
    @Test
    public void testAcceptance_24()
            throws Exception {

        final String request = "Get /decoding_ma\u00DF%c3%9f%DF123.html HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(3)));
        final String body = response.replaceAll(Pattern.HTTP_RESPONSE, "$2");
        Assert.assertEquals("-2-", body);
    }

    /**
     * Test case for acceptance.
     * The decoding (MIME/UTF8) from the URL must work.
     * The request is responded with status 200 and the correct content.
     * @throws Exception
     */
    @Test
    public void testAcceptance_25()
            throws Exception {

        final String request = "Get /decoding_ma%DF\u00DF%c3%9f123.html HTTP/1.0\r\n"
                + "Host: vHa\r\n"
                + "\r\n";
        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
        Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(3)));
        final String body = response.replaceAll(Pattern.HTTP_RESPONSE, "$2");
        Assert.assertEquals("-2-", body);
    }

    private void assertAcceptance_26(int count, String path, String start, String end)
            throws Exception {

        if (start != null
                && start.contains("-")
                && end == null)
            end = "";
        if (end != null
                && end.contains("-")
                && start == null)
            start = "";

        String request = "GET " + path + " HTTP/1.0\r\n"
                + "Host: vHa\r\n";
        if (start != null || end != null) {
            request += "Range: bYteS = " + (start != null ? start : "");
            if (start != null && end != null)
                request += count % 2 == 0 ? "-" : " - ";
            request += end != null ? end : "";
            request += "\r\n";
        }

        if (start != null && start.contains(";"))
            end = null;

        final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request + "\r\n");

        long code;
        long size;

        long fileSize     = new File(AbstractStage.getRootStage(), "documents_vh_A/" + path).length();
        long responseSize = fileSize;
        long startPos     = 0;
        long endPos       = fileSize -1;
        long fileEnd      = fileSize -1;

        if (path.contains("nix")) {

            code = 404;
            Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_404));
            Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
            Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_RANGE_DIFFUSE));

        } else if (path.equals("/")) {

            code = 200;
            Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
            Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH));
            Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_RANGE_DIFFUSE));

        } else {

            code = 206;

            String range = "";
            if (start != null)
                range += " " + start;
            if (start != null && end != null)
                range += "-";
            if (end != null)
                range += " " + end;
            range = range.replaceAll(";.*$", "").trim();

            if (range.matches("^(\\d+)*\\s*-\\s*(\\d+)*$")) {
                StringTokenizer tokenizer = new StringTokenizer(range, "-");
                startPos = Long.parseLong(tokenizer.nextToken().trim());
                if (tokenizer.hasMoreTokens()) {
                    endPos = Long.parseLong(tokenizer.nextToken().trim());
                } else if (range.startsWith("-")) {
                    if (startPos > 0) {
                        endPos   = fileSize -1;
                        startPos = Math.max(0, fileSize -startPos);
                    } else endPos = -1;
                }
                endPos = Math.min(endPos, fileSize -1);
                if (startPos >= fileSize) {
                    code = 416;
                } else if (startPos < fileSize
                        && startPos <= endPos) {
                    endPos++;
                } else {
                    startPos = 0;
                    endPos   = fileSize;
                    code     = 200;
                }

                responseSize = Math.min(fileSize, Math.max(0, endPos -startPos));
            }

            if (start != null)
                start = start.replaceAll("\\s*;.*$", "");
            if (end != null)
                end = end.replaceAll("\\s*;.*$", "");

            if (start == null
                    || end == null)
                code = 200;
            if (start != null
                    && start.trim().isEmpty()
                    && endPos == 0)
                code = 200;
            if (startPos > endPos)
                code = 200;
            if (startPos >= fileSize
                    && fileSize > 0
                    && start != null
                    && end != null)
                code = 416;
            if (start != null
                    && !start.matches("^\\d+$")
                    && !start.trim().isEmpty())
                code = 200;
            if (end != null
                    && !end.matches("^\\d+$")
                    && !end.trim().isEmpty())
                code = 200;

            if (code != 206)
                responseSize = fileSize;

            if (code == 206) {
                Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_206));
                Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(responseSize)));
                Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_RANGE(startPos, endPos -1, fileSize)));
                size = endPos -startPos;
            } else if (code == 416) {
                Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_416));
                Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_RANGE_DIFFUSE));
                size = Long.parseLong(HttpUtils.getResponseHeaderValue(response, HttpUtils.HeaderField.CONTENT_LENGTH));
                Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(size)));
            } else {
                Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS_200));
                Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_CONTENT_LENGTH(fileSize)));
                Assert.assertFalse(response.matches(Pattern.HTTP_RESPONSE_CONTENT_RANGE_DIFFUSE));
                size = fileSize;
            }

            if (code == 200
                    || code == 206) {

                if (code == 206) {

                    String pattern = null;
                    if (startPos == 0 && endPos -1 == fileEnd) {
                        pattern = "(?s)^>0001\\].*\\[1024\\] 1234567890 ABCDEFGHIJKLMNOPQRSTUVWXY<$";
                    } else if (startPos == 0 && endPos -1 == 0) {
                        pattern = "(?s)^>$";
                    } else if (startPos == 0 && endPos -1 == 1) {
                        pattern = "(?s)^>0$";
                    } else if (startPos == 0 && endPos -1 == 127) {
                        pattern = "(?s)^>0001\\].*\\[0003\\] 1234567890 ABCDEFGHIJKLMNOPQR$";
                    } else if (startPos == 1 && endPos -1 == 1) {
                        pattern = "(?s)^0$";
                    } else if (startPos == 1 && endPos -1 == 127) {
                        pattern = "(?s)^0001\\].*\\[0003\\] 1234567890 ABCDEFGHIJKLMNOPQR$";
                    } else if (startPos == 1 && endPos -1 == fileEnd) {
                        pattern = "(?s)^0001\\].*\\[1024\\] 1234567890 ABCDEFGHIJKLMNOPQRSTUVWXY<$";
                    } else if (startPos == 127 && endPos -1 == 256) {
                        pattern = "(?s)^RSTUVWXYZ[\r\n]+\\[0004\\].*\\[0006\\] 1234567890 ABCDEFGHI$";
                    } else if (startPos == 256 && endPos -1 == fileEnd) {
                        pattern = "(?s)^IJKLMNOPQRSTUVWXYZ[\r\n]+\\[0007\\].*\\[1024\\] 1234567890 ABCDEFGHIJKLMNOPQRSTUVWXY<$";
                    } else if (startPos == fileSize -1 && endPos -1 == fileEnd) {
                        pattern = "(?s)^<$";
                    } else if (startPos == fileSize -256 && endPos -1 == fileEnd) {
                        pattern = "(?s)^ABCDEFGHIJKLMNOPQRSTUVWXYZ[\r\n]+\\[1020\\].*\\[1024\\] 1234567890 ABCDEFGHIJKLMNOPQRSTUVWXY<$";
                    } else Assert.fail("Missing test case");

                    String body = response.replaceAll(Pattern.HTTP_RESPONSE, "$2");
                    Assert.assertTrue(body.matches(pattern));
                }

                String accessLog = AbstractStage.getAccessStreamCapture().fetch(ACCESS_LOG_RESPONSE_UUID(response));
                Assert.assertTrue(accessLog, accessLog.matches(Pattern.ACCESS_LOG_STATUS(String.valueOf(code), request, (int)size)));
            }
        }

        final String accessLog = AbstractStage.getAccessStreamCapture().fetch(ACCESS_LOG_RESPONSE_UUID(response));
        Assert.assertTrue(accessLog, accessLog.matches(Pattern.ACCESS_LOG_STATUS(String.valueOf(code), request)));
    }

    /**
     * Test case for acceptance.
     * The correct response for GET request with a Range header is checked.
     * @throws Exception
     */
    @Test
    public void testAcceptance_26()
            throws Exception {

        for (final String path : new String[] {"/partial_content.txt", "/partial_content_empty.txt",
                "/partial_content-nix.txt", "/"}) {

            int count = 0;

            this.assertAcceptance_26(++count, path, "0",      "0");
            this.assertAcceptance_26(++count, path, "0",      "1");
            this.assertAcceptance_26(++count, path, "0",      "127");
            this.assertAcceptance_26(++count, path, "0",      "65535");
            this.assertAcceptance_26(++count, path, "1",      "0");
            this.assertAcceptance_26(++count, path, "1",      "1");
            this.assertAcceptance_26(++count, path, "1",      "127");
            this.assertAcceptance_26(++count, path, "1",      "65535");
            this.assertAcceptance_26(++count, path, "127",    "256");
            this.assertAcceptance_26(++count, path, "256",    "127");

            this.assertAcceptance_26(++count, path, "127",    "0");
            this.assertAcceptance_26(++count, path, "127",    "1");
            this.assertAcceptance_26(++count, path, "65535",  "0");
            this.assertAcceptance_26(++count, path, "65535",  "1");
            this.assertAcceptance_26(++count, path, "256",    "65535");
            this.assertAcceptance_26(++count, path, "65535",  "256");
            this.assertAcceptance_26(++count, path, "-256",   "127");
            this.assertAcceptance_26(++count, path, "-127",   "256");
            this.assertAcceptance_26(++count, path, "256",    "-127");
            this.assertAcceptance_26(++count, path, "127",    "-256");

            this.assertAcceptance_26(++count, path, "0",      "A");
            this.assertAcceptance_26(++count, path, "1",      "A");
            this.assertAcceptance_26(++count, path, "256",    "B");
            this.assertAcceptance_26(++count, path, "65535",  "C");
            this.assertAcceptance_26(++count, path, "-0",     "A");
            this.assertAcceptance_26(++count, path, "-1",     "A");
            this.assertAcceptance_26(++count, path, "-256",   "B");
            this.assertAcceptance_26(++count, path, "-65535", "C");
            this.assertAcceptance_26(++count, path, "A",      "0");
            this.assertAcceptance_26(++count, path, "A",      "1");

            this.assertAcceptance_26(++count, path, "B",      "256");
            this.assertAcceptance_26(++count, path, "C",      "65535");
            this.assertAcceptance_26(++count, path, "A",      "-0");
            this.assertAcceptance_26(++count, path, "A",      "-1");
            this.assertAcceptance_26(++count, path, "B",      "-256");
            this.assertAcceptance_26(++count, path, "C",      "-65535");
            this.assertAcceptance_26(++count, path, "0",      "");
            this.assertAcceptance_26(++count, path, "256",    "");
            this.assertAcceptance_26(++count, path, "65535",  "");
            this.assertAcceptance_26(++count, path, "-0",     "");

            this.assertAcceptance_26(++count, path, "-1",     "");
            this.assertAcceptance_26(++count, path, "-256",   "");
            this.assertAcceptance_26(++count, path, "-65535", "");
            this.assertAcceptance_26(++count, path, null,     "0");
            this.assertAcceptance_26(++count, path, null,     "256");
            this.assertAcceptance_26(++count, path, null,     "65535");
            this.assertAcceptance_26(++count, path, null,     "A");
            this.assertAcceptance_26(++count, path, null,     null);
            this.assertAcceptance_26(++count, path, "",       "0");
            this.assertAcceptance_26(++count, path, "",       "256");

            this.assertAcceptance_26(++count, path, "",       "65535");
            this.assertAcceptance_26(++count, path, "",       "-0");
            this.assertAcceptance_26(++count, path, "",       "-1");
            this.assertAcceptance_26(++count, path, "",       "-256");
            this.assertAcceptance_26(++count, path, "",       "-65535");
            this.assertAcceptance_26(++count, path, "0",      " ");
            this.assertAcceptance_26(++count, path, "1",      " ");
            this.assertAcceptance_26(++count, path, "256",    " ");
            this.assertAcceptance_26(++count, path, "65535",  " ");
            this.assertAcceptance_26(++count, path, "-0",     " ");

            this.assertAcceptance_26(++count, path, null,     "-0");
            this.assertAcceptance_26(++count, path, null,     "-1");
            this.assertAcceptance_26(++count, path, null,     "-256");
            this.assertAcceptance_26(++count, path, null,     "-65535");
            this.assertAcceptance_26(++count, path, "0",      null);
            this.assertAcceptance_26(++count, path, "1",      null);
            this.assertAcceptance_26(++count, path, "256",    null);
            this.assertAcceptance_26(++count, path, "65535",  null);
            this.assertAcceptance_26(++count, path, "-0",     null);
            this.assertAcceptance_26(++count, path, null,     "65535");

            this.assertAcceptance_26(++count, path, null,     "256");
            this.assertAcceptance_26(++count, path, null,     "127");
            this.assertAcceptance_26(++count, path, "-1",     " ");
            this.assertAcceptance_26(++count, path, "-256",   " ");
            this.assertAcceptance_26(++count, path, "-65535", " ");
            this.assertAcceptance_26(++count, path, " ",      "0");
            this.assertAcceptance_26(++count, path, " ",      "1");
            this.assertAcceptance_26(++count, path, " ",      "256");
            this.assertAcceptance_26(++count, path, " ",      "65535");
            this.assertAcceptance_26(++count, path, " ",      "-0");

            this.assertAcceptance_26(++count, path, " ",      "-1");
            this.assertAcceptance_26(++count, path, " ",      "-256");
            this.assertAcceptance_26(++count, path, " ",      "-65535");
            this.assertAcceptance_26(++count, path, "0",      "-");
            this.assertAcceptance_26(++count, path, "1",      "-");
            this.assertAcceptance_26(++count, path, "256",    "-");
            this.assertAcceptance_26(++count, path, "65535",  "-");
            this.assertAcceptance_26(++count, path, "-0",     "-");
            this.assertAcceptance_26(++count, path, "-1",     "-");
            this.assertAcceptance_26(++count, path, "-256",   "-");

            this.assertAcceptance_26(++count, path, "-65535", "-");
            this.assertAcceptance_26(++count, path, "-",      "0");
            this.assertAcceptance_26(++count, path, "-",      "256");
            this.assertAcceptance_26(++count, path, "-",      "65535");
            this.assertAcceptance_26(++count, path, "-",      "-0");
            this.assertAcceptance_26(++count, path, "-",      "-1");
            this.assertAcceptance_26(++count, path, "-",      "-256");
            this.assertAcceptance_26(++count, path, "-",      "-65535");
            this.assertAcceptance_26(++count, path, "0",      ";");
            this.assertAcceptance_26(++count, path, "1",      ";");

            this.assertAcceptance_26(++count, path, "256",    ";");
            this.assertAcceptance_26(++count, path, "65535",  ";");
            this.assertAcceptance_26(++count, path, "0;",     null);
            this.assertAcceptance_26(++count, path, "1;",     null);
            this.assertAcceptance_26(++count, path, "256;",   null);
            this.assertAcceptance_26(++count, path, "65535;", null);
            this.assertAcceptance_26(++count, path, "-0",     ";");
            this.assertAcceptance_26(++count, path, "-1",     ";");
            this.assertAcceptance_26(++count, path, "-256",   ";");
            this.assertAcceptance_26(++count, path, "-65535", ";");

            this.assertAcceptance_26(++count, path, ";",      "0");
            this.assertAcceptance_26(++count, path, ";",      "1");
            this.assertAcceptance_26(++count, path, ";",      "256");
            this.assertAcceptance_26(++count, path, ";",      "65535");
            this.assertAcceptance_26(++count, path, ";",      "-0");
            this.assertAcceptance_26(++count, path, ";",      "-1");
            this.assertAcceptance_26(++count, path, ";",      "-256");
            this.assertAcceptance_26(++count, path, ";",      "-65535");
            this.assertAcceptance_26(++count, path, "1",      "");
            this.assertAcceptance_26(++count, path, "",       "1");
        }
    }

    /**
     * Test case for acceptance.
     * The correct response for GET request with a Range,
     * If-Modified-Since and If-UnModified-Since header is checked.
     * @throws Exception
     */
    @Test
    public void testAcceptance_27()
            throws Exception {

        for (final String path : new String[] {"/partial_content.txt", "/partial_content_empty.txt",
                "/partial_content-nix.txt", "/"}) {

            String requestLastModified = "HEAD " + path + " HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "\r\n";
            String responseLastModified = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", requestLastModified);
            String lastModified = HttpUtils.getResponseHeaderValue(responseLastModified, HeaderField.LAST_MODIFIED);

            if (path.equals("/")) {
                requestLastModified = "Get /documents/commons/lastmodified.jsx HTTP/1.0\r\n"
                        + "File: ./stage/documents_vh_A\r\n"
                        + "Host: vHa\r\n"
                        + "\r\n";
                responseLastModified = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", requestLastModified);
                lastModified = responseLastModified.replaceAll(Pattern.HTTP_RESPONSE, "$2");
            }

            for (String request : new String[] {
                    "GET " + path + "?304 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "Range: bytes=2-10\r\n"
                    + "If-Modified-Since: " + lastModified + "\r\n\r\n",

                    "GET " + path + "?304 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "Range: bytes=2-10\r\n"
                    + "If-Modified-Since: " + lastModified + "\r\n\r\n",

                    "GET " + path + "?206 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "Range: bytes=2-10\r\n"
                    + "If-Modified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n\r\n",

                    "GET " + path + "?412 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "Range: bytes=2-10\r\n"
                    + "If-UnModified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n\r\n",

                    "GET " + path + "?206 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "Range: bytes=2-10\r\n"
                    + "If-UnModified-Since: " + lastModified + "\r\n\r\n",

                    "GET " + path + "?304 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "Range: bytes=2-10\r\n"
                    + "If-UnModified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n"
                    + "If-Modified-Since: " + lastModified + "\r\n\r\n",

                    "GET " + path + "?206 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "Range: bytes=2-10\r\n"
                    + "If-UnModified-Since: " + lastModified + "\r\n"
                    + "If-Modified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n\r\n",

                    "GET " + path + "?304 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "Range: bytes=2-10\r\n"
                    + "If-UnModified-Since: " + lastModified + "\r\n"
                    + "If-Modified-Since: " + lastModified + "\r\n\r\n",

                    "GET " + path + "?412 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "Range: bytes=2-10\r\n"
                    + "If-UnModified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n"
                    + "If-Modified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n\r\n",

                    "GET " + path + "?200 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "If-Modified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n\r\n",

                    "GET " + path + "?304 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "If-Modified-Since: " + lastModified + "\r\n\r\n",

                    "GET " + path + "?412 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "If-UnModified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n\r\n",

                    "GET " + path + "?200 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "If-UnModified-Since: " + lastModified + "\r\n\r\n",

                    "GET " + path + "?304 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "If-UnModified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n"
                    + "If-Modified-Since: " + lastModified + "\r\n\r\n",

                    "GET " + path + "?200 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "If-UnModified-Since: " + lastModified + "\r\n"
                    + "If-Modified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n\r\n",

                    "GET " + path + "?304 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "If-UnModified-Since: " + lastModified + "\r\n"
                    + "If-Modified-Since: " + lastModified + "\r\n\r\n",

                    "GET " + path + "?412 HTTP/1.0\r\n"
                    + "Host: vHa\r\n"
                    + "If-UnModified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n"
                    + "If-Modified-Since: Thu, 07 Oct 1980 10:20:30 GMT\r\n\r\n"}) {

                String code = request.replaceAll("(?s)^.*?\\?(\\d+) .*$", "$1");

                if (path.equals("/partial_content_empty.txt")) {
                    request = request.replaceAll("(?s)(\r\nRange: bytes=)2-10(\r\n)", "$10-0$2");
                    if (code.equals("206"))
                        code = "200";
                }

                if (path.equals("/partial_content-nix.txt")) {
                    request = request.replaceAll("(?s)(\r\nRange: bytes=)2-10(\r\n)", "$2");
                    code = "404";
                }

                if (path.equals("/")) {
                    request = request.replaceAll("(?s)(\r\nRange: bytes=)2-10(\r\n)", "$2");
                    code = "200";
                }

                final String response = AbstractStageRequestTest.sendRequest("127.0.0.1:18180", request);
                Assert.assertTrue(response.matches(Pattern.HTTP_RESPONSE_STATUS(code)));
            }
        }
    }
}


text:
{
  this.opts = {
    method: "GET"
  };
  this.response = resolvable();
  this._headers = {};
  this._caseless = caseless(this._headers);

  let failSet = () => {
    throw new Error("Cannot set read-only property.");
  };

  Object.defineProperty(this, "json", {
    get: () => this.response.then(resp => resp.clone().json()),
    set: failSet
  });
  Object.defineProperty(this, "text", {
    get: () => this.response.then(resp => resp.clone().text()),
    set: failSet
  });
  Object.defineProperty(this, "arrayBuffer", {
    get: () => this.response.then(resp => resp.clone().arrayBuffer()),
    set: failSet
  });
  Object.defineProperty(this, "blob", {
    get: () => this.response.then(resp => resp.clone().blob()),
    set: failSet
  });
  Object.defineProperty(this, "formData", {
    get: () => this.response.then(resp => resp.clone().formData()),
    set: failSet
  });

  this._args(...args);

  setTimeout(() => {
    this._request();
  }, 0);
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe InstrumentKey do
end


text:
<?php

namespace Sabre\DAV\Auth\Backend;

use Sabre\DAV;
use Sabre\HTTP;

require_once 'Sabre/HTTP/ResponseMock.php';

class AbstractBasicTest extends \PHPUnit_Framework_TestCase {

    /**
     * @expectedException Sabre\DAV\Exception\NotAuthenticated
     */
    public function testAuthenticateNoHeaders() {

        $response = new HTTP\ResponseMock();
        $server = new DAV\Server();
        $server->httpResponse = $response;

        $backend = new AbstractBasicMock();
        $backend->authenticate($server,'myRealm');

    }

    /**
     * @expectedException Sabre\DAV\Exception\NotAuthenticated
     */
    public function testAuthenticateUnknownUser() {

        $response = new HTTP\ResponseMock();
        $tree = new DAV\ObjectTree(new DAV\SimpleCollection('bla'));
        $server = new DAV\Server($tree);
        $server->httpResponse = $response;

        $request = new HTTP\Request(array(
            'PHP_AUTH_USER' => 'username',
            'PHP_AUTH_PW' => 'wrongpassword',
        ));
        $server->httpRequest = $request;

        $backend = new AbstractBasicMock();
        $backend->authenticate($server,'myRealm');

    }

    public function testAuthenticate() {

        $response = new HTTP\ResponseMock();
        $tree = new DAV\ObjectTree(new DAV\SimpleCollection('bla'));
        $server = new DAV\Server($tree);
        $server->httpResponse = $response;

        $request = new HTTP\Request(array(
            'PHP_AUTH_USER' => 'username',
            'PHP_AUTH_PW' => 'password',
        ));
        $server->httpRequest = $request;

        $backend = new AbstractBasicMock();
        $this->assertTrue($backend->authenticate($server,'myRealm'));

        $result = $backend->getCurrentUser();

        $this->assertEquals('username', $result);

    }

}

class AbstractBasicMock extends AbstractBasic {

    /**
     * Validates a username and password
     *
     * This method should return true or false depending on if login
     * succeeded.
     *
     * @param string $username
     * @param string $password
     * @return bool
     */
    function validateUserPass($username, $password) {

        return ($username == 'username' && $password == 'password');

    }

}


text:
require([
  'app/app-init',
  'search/search-init',
  'detail/detail-init',
  'application'
],
function () {
  'use strict';
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pami.DotNet.ReferenceArchitecture.Soporte.DI.AtributosComponentes
{
    /// <summary>
    /// Este atributo se ultiliza para representar query objects
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class QueryAttribute : ComponenteAttribute
    {
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>example-java8</artifactId>
  <version>1.0-SNAPSHOT</version>

  <dependencies>

    <dependency>
      <groupId>org.avaje.ebeanorm</groupId>
      <artifactId>avaje-ebeanorm</artifactId>
      <version>4.2.1-SNAPSHOT</version>
    </dependency>

    <!--
    Optional but Ebean will read these annotations
    like @size to determine column lengths etc
    -->
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>1.0.0.GA</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.7</version>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.2</version>
    </dependency>

    <dependency>
      <groupId>org.avaje</groupId>
      <artifactId>avaje-agentloader</artifactId>
      <version>1.1.1</version>
    </dependency>

    <dependency>
      <groupId>org.avaje.ebeanorm</groupId>
      <artifactId>avaje-ebeanorm-agent</artifactId>
      <version>4.1.10</version>
    </dependency>

    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>1.4.178</version>
    </dependency>

    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-integration</artifactId>
      <version>1.3</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.avaje.ebeanorm</groupId>
        <artifactId>avaje-ebeanorm-mavenenhancer</artifactId>
        <version>4.1.10</version>
        <executions>
          <execution>
            <id>main</id>
            <phase>process-classes</phase>
            <configuration>
              <classSource>target/classes</classSource>
              <packages>org.example.domain.**</packages>
              <transformArgs>debug=1</transformArgs>
            </configuration>
            <goals>
              <goal>enhance</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

    </plugins>

  </build>

</project>


text:
package com.beyondjservlet.gateway.servlet;

import com.beyondj.gateway.IMetricsPublishingAndCollectionService;
import com.codahale.metrics.Metric;
import com.lenox.beyondj.metrics.MetricsResponse;
import com.lenox.platform.MetricsMessage;
import com.lenox.platform.MetricsMessageCollection;
import com.lenox.platform.MetricsProviderInfo;
import com.thoughtworks.xstream.XStream;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spring.remoting.CamelProxyFactoryBean;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class MetricsServlet extends HttpServlet {

    private XStream xstream = new XStream();
    private IMetricsPublishingAndCollectionService metricsServiceRegistrar;
    private IMetricsPublishingAndCollectionService metricsServiceFetcher;
    private IMetricsPublishingAndCollectionService metricsServiceProvider;

    @Override
    public void init() throws ServletException {
        super.init();
    }

    protected void findService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws IOException {

        String contextPath = httpServletRequest.getParameter("__c");   //specify context
        String allServices = httpServletRequest.getParameter("__a");  //get all services

        try {
            if (StringUtils.isNotBlank(allServices) && StringUtils.isNotBlank(contextPath)) {
                listMetrics(httpServletRequest, httpServletResponse, contextPath);
            } else {
                listMetrics(httpServletRequest, httpServletResponse, null);
            }
        } catch (Exception e) {
            LOG.error("Error", e);
            throw new IOException(e);
        }
    }

    private void validateMetricsServiceRegistrarProxy() {
        if (metricsServiceRegistrar != null) {
            return;
        }
        try {
            metricsServiceRegistrar = getMetricsServiceProxy("direct-vm://registerMetricsProvider");
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    private void validateMetricsServiceFetcherProxy() {
        if (metricsServiceFetcher != null) {
            return;
        }
        try {
            metricsServiceFetcher = getMetricsServiceProxy("direct-vm://fetchMetrics");
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    private void validateMetricsServiceProviderProxy() {
        if (metricsServiceProvider != null) {
            return;
        }
        try {
            metricsServiceProvider = getMetricsServiceProxy("direct-vm://provideMetrics");
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    private void listMetrics(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             String contextPath) throws IOException {

        validateMetricsServiceFetcherProxy();

        //TODO: filter by contextPath where required

        String metricsStr = metricsServiceFetcher.fetchAllMetrics2();

        String accept = httpServletRequest.getHeader(ACCEPT);

        if (org.apache.commons.lang.StringUtils.isNotBlank(accept) && accept.equalsIgnoreCase(JSON)) {
            httpServletResponse.setContentType(JSON);
            httpServletResponse.getWriter().write(metricsStr);
        } else {
            httpServletResponse.setContentType(XML);
            MetricsResponse metricsResponse = new MetricsResponse();
            metricsStr = StringEscapeUtils.escapeXml10(metricsStr);
            metricsResponse.setPayload(metricsStr);
            httpServletResponse.getWriter().write(xstream.toXML(metricsResponse));
        }
    }

    private void registerMetricsProvider(HttpServletRequest req) throws ServletException, IOException {
        validateMetricsServiceRegistrarProxy();
        String providerInfo = req.getParameter(PROVIDER_INFO);
        String providedMetrics = req.getParameter(PROVIDED_METRICS);
        try {
            MetricsProviderInfo info = (MetricsProviderInfo) xstream.fromXML(providerInfo);
            MetricsMessage metricsMessage = (com.lenox.platform.MetricsMessage) xstream.fromXML(providedMetrics);
            metricsServiceRegistrar.registerMetricsProvider(info, metricsMessage);
        } catch (Exception e) {
            LOG.error("Error unmarshalling " + providerInfo, e);
        }
    }

    private void provide(HttpServletRequest req) throws ServletException, IOException {

        validateMetricsServiceProviderProxy();
        String providerInfo = req.getParameter(PROVIDER_INFO);
        String metricsData = req.getParameter(METRICS_DATA);

        try {
            MetricsProviderInfo info = (MetricsProviderInfo) xstream.fromXML(providerInfo);
            MetricsMessageCollection messageCollection = (MetricsMessageCollection) xstream.fromXML(metricsData);
            metricsServiceProvider.provide(info, messageCollection);
        } catch (Exception e) {
            LOG.error("Error unmarshalling " + providerInfo + "\n" + metricsData, e);
        }
    }

    private IMetricsPublishingAndCollectionService getMetricsServiceProxy(String targetUrl) throws Exception {
        CamelProxyFactoryBean factory = new CamelProxyFactoryBean();
        factory.setServiceInterface(IMetricsPublishingAndCollectionService.class);
        factory.setServiceUrl(targetUrl);
        factory.setCamelContext(new DefaultCamelContext());
        factory.afterPropertiesSet();
        return (IMetricsPublishingAndCollectionService) factory.getObject();
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter(OPERATION);
        if (REGISTER.equalsIgnoreCase(operation)) {
            doRegisterPost(req, resp);
        } else {
            findService(req, resp);
        }
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doRegisterPost(req, resp);
    }

    private void doRegisterPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter(OPERATION);
        if (REGISTER.equalsIgnoreCase(operation)) {
            registerMetricsProvider(req);
        } else if (PROVISION.equalsIgnoreCase(operation)) {
            provide(req);
        } else {
            LOG.error("Unknown operation found: " + operation);
        }
    }

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = req.getParameter(OPERATION);
        if (REGISTER.equalsIgnoreCase(operation) || PROVISION.equalsIgnoreCase(operation)) {
            doRegisterPost(req, resp);
        } else {
            findService(req, resp);
        }
    }

    private static final Logger LOG = LoggerFactory.getLogger(MetricsServlet.class);

    public static final String XML = "application/xml";
    public static final String JSON = "application/json";
    public static final String PROVIDER_INFO = "providerInfo";
    public static final String ACCEPT = "Accept";
    public static final String OPERATION = "operation";
    public static final String REGISTER = "register";
    public static final String PROVISION = "provision";
    public static final String METRICS_DATA = "metricsData";
    public static final String PROVIDED_METRICS = "providedMetrics";
}


text:
package com.phloc.commons.compare;

import java.util.Comparator;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * This is another *lol* class: a {@link Comparator} for {@link Comparable}
 * objects.
 *
 * @author Philip Helger
 */
public class ComparatorComparable <DATATYPE extends Comparable <? super DATATYPE>> extends
                                                                                AbstractComparator <DATATYPE>
{
  /**
   * Comparator with default sort order and no nested comparator.
   */
  public ComparatorComparable ()
  {
    super ();
  }

  /**
   * Constructor with sort order.
   *
   * @param eSortOrder
   *        The sort order to use. May not be null.
   */
  public ComparatorComparable (@Nonnull final ESortOrder eSortOrder)
  {
    super (eSortOrder);
  }

  /**
   * Comparator with default sort order and a nested comparator.
   *
   * @param aNestedComparator
   *        The nested comparator to be invoked, when the main comparison
   *        resulted in 0.
   */
  public ComparatorComparable (@Nullable final Comparator <? super DATATYPE> aNestedComparator)
  {
    super (aNestedComparator);
  }

  /**
   * Comparator with sort order and a nested comparator.
   *
   * @param eSortOrder
   *        The sort order to use. May not be null.
   * @param aNestedComparator
   *        The nested comparator to be invoked, when the main comparison
   *        resulted in 0.
   */
  public ComparatorComparable (@Nonnull final ESortOrder eSortOrder,
                               @Nullable final Comparator <? super DATATYPE> aNestedComparator)
  {
    super (eSortOrder, aNestedComparator);
  }

  @Override
  protected final int mainCompare (@Nonnull final DATATYPE aElement1, @Nonnull final DATATYPE aElement2)
  {
    return aElement1.compareTo (aElement2);
  }
}


text:
package org.apache.lucene.util;

/**
 * Thrown by lucene on detecting that Thread.interrupt() had
 * been called.  Unlike Java's InterruptedException, this
 * exception is not checked..
 */

public final class ThreadInterruptedException extends RuntimeException {
  public ThreadInterruptedException(InterruptedException ie) {
    super(ie);
  }
}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_TypeLoadException4088653924.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.DllNotFoundException
struct  DllNotFoundException_t3753030609  : public TypeLoadException_t4088653924
{
public:

public:
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
<md-dialog aria-label="Edit Cue">
  <md-dialog-content>

        <select ng-model="cue.cueCode" as-string>
          <option value="" disabled selected>Choose cue event</option>
          <option ng-selected="($index + 1) === cue.cueCode" ng-repeat="type in cueTypes" value="{{$index + 1}}">{{type}}</option>
        </select>

        <paco-help tip="app-triggers" ng-if="cue.cueCode === 4 || cue.cueCode === 5 || cue.cueCode === 18">
          Help: App Triggers
        </paco-help>

      <md-input-container ng-if="cue.cueCode === 3 || cue.cueCode === 4 || cue.cueCode === 5 || cue.cueCode === 18">
        Source of Paco Action
        <input type="text" ng-model="cue.cueSource">
      </md-input-container>

  </md-dialog-content>

    <md-button ng-click="hide()" class="md-primary">
      Done
    </md-button>

</md-dialog>


text:
local hotkey = require "hs.hotkey"
local alert = require "hs.alert"
local blueutil = "/usr/local/bin/blueutil"

BluetoothControl = {}

function BluetoothControl.status()
  output = io.popen(blueutil, "r")
  result = output:read()
  return result:find("Power: 1") and "on" or "off"
end

function BluetoothControl.toggle()
  if BluetoothControl.status() == "on" then
    alert.show("Bluetooth: Off")
    os.execute(blueutil.." power 0")
  else
    alert.show("Bluetooth: On")
    os.execute(blueutil.." power 1")
  end
end

return BluetoothControl


text:
package blue.lapis.pore.impl.event.block;

import static com.google.common.base.Preconditions.checkNotNull;

import blue.lapis.pore.impl.block.PoreBlock;

import org.apache.commons.lang3.NotImplementedException;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.spongepowered.api.event.block.BlockEvent;

public class PoreEntityBlockFormEvent extends EntityBlockFormEvent {

    private final BlockEvent handle;

    public PoreEntityBlockFormEvent(BlockEvent handle) {
        super(null, null, null);
        this.handle = checkNotNull(handle, "handle");
    }

    public BlockEvent getHandle() {
        return handle;
    }

    @Override
    public Block getBlock() {
        return PoreBlock.of(getHandle().getLocation());
    }

    @Override
    public Entity getEntity() {
        throw new NotImplementedException("TODO"); // TODO
    }

    @Override
    public BlockState getNewState() {
        throw new NotImplementedException("TODO"); // TODO
    }

    @Override
    public boolean isCancelled() {
        throw new NotImplementedException("TODO"); // TODO
    }

    @Override
    public void setCancelled(boolean cancel) {
        throw new NotImplementedException("TODO"); // TODO
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:myapp="http://schemas.android.com/apk/res/com.motolky"
  		android:layout_width="fill_parent"
  		android:layout_height="fill_parent"
  		android:orientation="vertical">
	<ListView xmlns:android="http://schemas.android.com/apk/res/android"
	 		android:layout_width="fill_parent"
			android:layout_height="fill_parent"
			android:layout_weight="1"
			android:id="@+id/android:list"/>
	<RelativeLayout android:layout_height="wrap_content"
			android:layout_width="fill_parent"
		        android:layout_marginTop="15dip"
		        android:layout_marginBottom="15dip">
		<ToggleButton android:id="@+id/micButton"
		        android:layout_width="40dip"
		        android:layout_height="40dip"
		        android:textOn="" android:textOff=""
		        android:layout_margin="5dip"
		        android:checked="true"
				android:layout_centerVertical="true"
		        android:background="@drawable/mic_selector"
		        android:onClick="micToggleClick"
		        />
		<ToggleButton android:id="@+id/speakerButton"
		        android:layout_width="40dip"
		        android:layout_height="40dip"
		        android:textOn="" android:textOff=""
				android:layout_toRightOf="@id/micButton"
		        android:layout_marginRight="10dip"
		        android:checked="true"
				android:layout_centerVertical="true"
		        android:background="@drawable/speaker_selector"
		        android:onClick="speakerToggleClick"/>
		<SeekBar android:id="@+id/volumeSeekbar"
				android:layout_width="fill_parent"
				android:layout_height="wrap_content"
				android:layout_toRightOf="@id/speakerButton"
				android:layout_centerVertical="true"
				android:layout_marginRight="10dip"
				android:progress="10"
				android:max="20"/>
	</RelativeLayout>
</LinearLayout>


text: export SCALA_HOME=/usr/local/Cellar/scala/2.10.3/libexec/


text:
class ArrayUtil
{
	public:
		static int highestProduct(int *values, const int ARRAY_SIZE);

};

#endif // ARRAYUTIL_H


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia 20(3-4): 814 (1971)

#### Original name
Phylloporus rubriceps Corner

### Remarks
null


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"

    tools:context=".DownloadActivity" >

    <include layout="@layout/navigationbar"
             android:id="@+id/nav_bar"
             android:layout_gravity="top"/>

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF"
        android:textSize="28dp"
        android:background="#FF0000"
        android:text="下载主题包" android:layout_gravity="center"/>

</FrameLayout>


text:
generator-puppet
================

A yo generator for puppet modules.  Considering that we are relatively new to puppet, this generator does not yet
have any advanced functionality and only lays down a very basic scaffold.


text:
                       Tambah Press Release

Kelola Event

Tambah Press Release

                                <form role="form" enctype="multipart/form-data" action="<?php echo site_url('KelolaNews/tambah_news_check/');?>" method="POST">

                                            <?php if($this->session->flashdata('msg_gagal')!=''){?>

                                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                                                    <?php echo $this->session->flashdata('msg_gagal');?>

                                            <?php }?>

                                            Judul Press Release   :
                                            <input type="text" required name="judul_news" class="form-control" id="exampleInputEmail1" value="<?php
                                                    if (isset($dataNews['judul_news']))
                                                    {
                                                        echo htmlspecialchars($dataNews['judul_news']);
                                                    }
                                            ?>">

                                            Penulis Press Release:
                                            <input type="text" required name="posted_by" class="form-control" id="exampleInputEmail1" value="<?php
                                                if (isset($dataNews['posted_by']))
                                                {
                                                    echo htmlspecialchars($dataNews['posted_by']);
                                                }
                                            ?>">

												 Deskripsi Press Release :

												<textarea required id="editor_wow" name="deskripsi_news" rows="10" cols="80">
													<?php
                                                        if (isset($dataNews['isi_news']))
                                                        {
                                                            echo htmlspecialchars($dataNews['isi_news']);
                                                        }
                                                    ?>
												</textarea>

                                            Unggah File Gambar :

                                                <input class="form" type="file" name="filefoto" required >

File diizinkan: jpg, jpeg, dan png (Max 2Mb)

                                    <input type="hidden" name="id_event" value="<?php echo $id_event; ?>">

                                        <button type="submit" name="submit" value="1" class="btn btn-primary"> Simpan</button>

                                </form>


text:
'use strict';

/**
 * Module dependencies
 */

// Node.js core.
const path = require('path');

// Public node modules.
const _ = require('lodash');
const async = require('async');

// Strapi utilities.
const dictionary = require('strapi-utils').dictionary;

/**
 * Async module loader to create a
 * dictionary of the external hooks
 */

module.exports = strapi => {
  return {

    /**
     * Initialize the hook
     */

    initialize: cb => {
      async.auto({

        // Load external hooks from the `node_modules` directory.
        externalHooks: cb => {
          dictionary.optional({
            dirname: path.resolve(strapi.config.appPath, 'node_modules'),
            filter: /^(package\.json)$/,
            excludeDirs: /^((?!(strapi-)).)*$/,
            depth: 2
          }, cb);
        }
      },

      // Callback.
      (err, hooks) => {
        // Just in case there is an error.
        if (err) {
          return cb(err);
        }

        // Order hooks to consider specific use cases
        // (ex: Knex needs to be load before Bookshelf)
        const externalHooks = _.pickBy(hooks.externalHooks, hook => {
          return _.get(_.get(hook, 'package.json'), 'strapi.isHook');
        });

        // Array of hook names
        const externalHooksKeys = _.keys(externalHooks);

        // Sort array to load hook in order
        _.forEach(externalHooksKeys, () => {
          _.forEach(externalHooksKeys, (value, index) => {
            const nextTo = _.first(_.get(externalHooks[value]['package.json'], 'strapi.nextTo'));

            if (nextTo) {
              const nextToIndex = _.indexOf(externalHooksKeys, nextTo);

              if (index < nextToIndex) {
                externalHooksKeys.unshift(externalHooksKeys[nextToIndex]);
                externalHooksKeys.splice(nextToIndex + 1, 1);
              }
            }
          });
        });

        // Transform array to object and replace integer key with hook name
        const externalHooksOrdered = _.mapKeys(_.toPlainObject(externalHooksKeys), value => value);

        // Add the loaded hooks into the hook dictionary exposed at `strapi.hooks`.
        _.set(strapi, 'externalHooks', _.reduce(externalHooksOrdered, (memo, module, identity) => {
          const hookName = identity.replace(/^strapi-/, '');

          memo[hookName] = identity;

          return memo;
        }, {}));

        cb();
      });
    }
  };
};


text:
require 'travis/logs/config'

module Travis
  def self.config
    Logs.config
  end

  module Logs
    def self.config
      @config ||= Config.load
    end

    def self.database_connection=(connection)
      @database_connection = connection
    end

    def self.database_connection
      @database_connection
    end
  end
end


text:
package uk.nhs.hdn.dts.client.out;

import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.jetbrains.annotations.NotNull;
import uk.nhs.hdn.common.commandLine.AbstractConsoleEntryPoint;
import uk.nhs.hdn.common.commandLine.ShouldHaveExitedException;
import uk.nhs.hdn.common.serialisers.CouldNotSerialiseException;
import uk.nhs.hdn.dts.domain.*;
import uk.nhs.hdn.dts.domain.identifiers.DtsIdentifier;
import uk.nhs.hdn.dts.domain.identifiers.LocalIdentifier;
import uk.nhs.hdn.dts.domain.identifiers.WorkflowIdentifier;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import static java.lang.System.getProperty;
import static java.lang.System.out;
import static uk.nhs.hdn.dts.client.out.ControlFileWriter.copyDataFileAndCreateEmptyControlFile;
import static uk.nhs.hdn.dts.domain.ContentEncoding.Compressed;
import static uk.nhs.hdn.dts.domain.DtsName.UnknownDtsName;
import static uk.nhs.hdn.dts.domain.SmtpAddress.UnknownSmtpAddress;
import static uk.nhs.hdn.dts.domain.Subject.UnknownSubject;
import static uk.nhs.hdn.dts.domain.TransactionSequenceIdentifier.One;
import static uk.nhs.hdn.dts.domain.identifiers.DtsIdentifier.UnknownDtsIdentifier;
import static uk.nhs.hdn.dts.domain.identifiers.LocalIdentifier.UnknownLocalIdentifier;
import static uk.nhs.hdn.dts.domain.identifiers.WorkflowIdentifier.UnknownWorkflowIdentifier;

public final class HdnDtsOutConsoleEntryPoint extends AbstractConsoleEntryPoint
{
	private static final String WorkflowIdentifierOption = "workflow-identifier";
	private static final String SubjectOption = "subject";
	private static final String LocalIdentifierOption = "local-identifier";
	private static final String DtsIdentifierOption = "dts-identifier";
	private static final String ContentEncodingOption = "content-encoding";
	private static final String FromSmtpOption = "from-smtp";
	private static final String ToSmtpOption = "to-smtp";
	private static final String FromDtsNameOption = "from-dts-name";
	private static final String ToDtsNameOption = "to-dts-name";
	private static final String InOption = "in";
	private static final String OutOption = "out";
	private static final String SiteIdentifierOption = "site-identifier";
	private static final String SequenceIdentifierOption = "sequence-identifier";

	@Override
	protected boolean options(@NotNull final OptionParser options)
	{
		options.accepts(WorkflowIdentifierOption).withRequiredArg().ofType(WorkflowIdentifier.class).defaultsTo(UnknownWorkflowIdentifier).describedAs("workflow identifier");
		options.accepts(SubjectOption).withRequiredArg().ofType(Subject.class).defaultsTo(UnknownSubject).describedAs("subject of data");
		options.accepts(LocalIdentifierOption).withRequiredArg().ofType(LocalIdentifier.class).defaultsTo(UnknownLocalIdentifier).describedAs("local identifier");
		options.accepts(DtsIdentifierOption).withRequiredArg().ofType(DtsIdentifier.class).defaultsTo(UnknownDtsIdentifier).describedAs("DTS identifier");
		options.accepts(ContentEncodingOption).withRequiredArg().ofType(ContentEncoding.class).defaultsTo(Compressed).describedAs("compress or encrypt");
		options.accepts(FromSmtpOption).withRequiredArg().ofType(SmtpAddress.class).defaultsTo(UnknownSmtpAddress).describedAs("from SMTP address");
		options.accepts(ToSmtpOption).requiredIf(FromSmtpOption).withRequiredArg().ofType(SmtpAddress.class).defaultsTo(UnknownSmtpAddress).describedAs("to SMTP address");
		options.accepts(FromDtsNameOption).withRequiredArg().ofType(DtsName.class).defaultsTo(UnknownDtsName).describedAs("from DTS name");
		options.accepts(ToDtsNameOption).requiredIf(FromDtsNameOption).withRequiredArg().ofType(DtsName.class).defaultsTo(UnknownDtsName).describedAs("to DTS name");
		options.accepts(OutOption).withRequiredArg().ofType(File.class).describedAs("a folder to create the control file in");
		options.accepts(InOption).requiredIf(OutOption).withRequiredArg().ofType(File.class).defaultsTo(new File(getProperty("user.dir"))).describedAs("path to a file containing data");
		options.accepts(SiteIdentifierOption).requiredIf(OutOption, InOption).withRequiredArg().ofType(String.class).describedAs("SiteId including APP");
		options.accepts(SequenceIdentifierOption).requiredIf(OutOption, InOption, SequenceIdentifierOption).withRequiredArg().ofType(TransactionSequenceIdentifier.class).defaultsTo(One).describedAs("transaction sequence identifier (zero padded)");
		return true;
	}

	@SuppressWarnings({"UseOfSystemOutOrSystemErr", "OverlyCoupledMethod", "OverlyLongMethod"})
	@Override
	protected void execute(@NotNull final OptionSet optionSet) throws CouldNotSerialiseException, IOException
	{
		final WorkflowIdentifier workflowIdentifier = required(optionSet, WorkflowIdentifierOption);
		if (workflowIdentifier.isUnknown())
		{
			exitWithErrorAndHelp(WorkflowIdentifierOption, workflowIdentifier, "must be supplied");
			return;
		}
		final Subject subject = defaulted(optionSet, SubjectOption);
		final LocalIdentifier localIdentifier = defaulted(optionSet, LocalIdentifierOption);
		final DtsIdentifier dtsIdentifier = defaulted(optionSet, DtsIdentifierOption);
		final ContentEncoding contentEncoding = defaulted(optionSet, ContentEncodingOption);
		final SmtpAddress fromSmtpAddress = defaulted(optionSet, FromSmtpOption);
		final SmtpAddress toSmtpAddress = defaulted(optionSet, ToSmtpOption);
		final DtsName fromDtsName = defaulted(optionSet, FromDtsNameOption);
		final DtsName toDtsName = defaulted(optionSet, ToDtsNameOption);

		final AddressPair<SmtpAddress> smtpAddresses;
		final AddressPair<DtsName> dtsNames;
		try
		{
			smtpAddresses = new AddressPair<>(fromSmtpAddress, toSmtpAddress);
			dtsNames = new AddressPair<>(fromDtsName, toDtsName);
		}
		catch (IllegalArgumentException ignored)
		{
			exitWithErrorAndHelp("Please provide from and to for a set of SMTP addresses and / or DTS names");
			throw new ShouldHaveExitedException();
		}

		if (smtpAddresses.isUnknown() && dtsNames.isUnknown())
		{
			exitWithErrorAndHelp("Please provide from and to for either or SMTP addresses and DTS names");
			throw new ShouldHaveExitedException();
		}

		final OutputStream outputStream;
		if (optionSet.has(OutOption))
		{
			final File outFolder = writableDirectory(optionSet, OutOption);
			final File inDataFile = readableFile(optionSet, InOption);
			final String siteIdentifierIncludingApp = required(optionSet, SiteIdentifierOption);
			final TransactionSequenceIdentifier sequenceIdentifier = required(optionSet, SequenceIdentifierOption);

			outputStream = copyDataFileAndCreateEmptyControlFile(outFolder, inDataFile, siteIdentifierIncludingApp, sequenceIdentifier);
		}
		else
		{
			outputStream = out;
		}

		new ControlFileWriter(outputStream).writeControlFile(workflowIdentifier, subject, localIdentifier, dtsIdentifier, contentEncoding, smtpAddresses, dtsNames);
	}

	public static void main(@NotNull final String... commandLineArguments)
	{
		execute(HdnDtsOutConsoleEntryPoint.class, commandLineArguments);
	}
}


text:
package org.apache.flex.compiler.internal.tree.as.metadata;

import java.util.Collection;
import java.util.EnumSet;

import org.apache.flex.compiler.asdoc.IASDocComment;
import org.apache.flex.compiler.common.ASModifier;
import org.apache.flex.compiler.common.IMetaInfo;
import org.apache.flex.compiler.constants.IMetaAttributeConstants;
import org.apache.flex.compiler.internal.scopes.ASScope;
import org.apache.flex.compiler.internal.semantics.PostProcessStep;
import org.apache.flex.compiler.internal.tree.as.BaseDefinitionNode;
import org.apache.flex.compiler.internal.tree.as.IdentifierNode;
import org.apache.flex.compiler.problems.ICompilerProblem;
import org.apache.flex.compiler.tree.as.IASNode;
import org.apache.flex.compiler.tree.as.IDefinitionNode;
import org.apache.flex.compiler.tree.as.IDocumentableDefinitionNode;
import org.apache.flex.compiler.tree.as.IExpressionNode;
import org.apache.flex.compiler.tree.as.INamespaceNode;
import org.apache.flex.compiler.tree.metadata.IMetaTagsNode;

/**
 * For metatags that decorate a definition, such as Events, Effects and Styles,
 * we treat them internally as IDefinitions. This is the common baseclass for
 * all of them
 */
public abstract class BaseDefinitionMetaTagNode extends MetaTagNode implements IDefinitionNode, IDocumentableDefinitionNode
{
    /**
     * The name of the node
     */
    protected IdentifierNode nameNode;

    /**
     * Node that represents the comment range
     */
    private IASDocComment asDocComment;

    public BaseDefinitionMetaTagNode(MetaTagNode other)
    {
        super(other);
    }

    public BaseDefinitionMetaTagNode(String name)
    {
        super(name);
    }

    public void setName(IdentifierNode name)
    {
        if (name != null)
        {
            nameNode = name;
            nameNode.setParent(this);
        }
        addToMap(IMetaAttributeConstants.NAME_EVENT_NAME, getName());
    }

    @Override
    public String getName()
    {
        if (nameNode != null)
            return nameNode.getName();
        return "";
    }

    @Override
    public IExpressionNode getNameExpressionNode()
    {
        return nameNode;
    }

    public IdentifierNode getNameNode()
    {
        return nameNode;
    }

    @Override
    public int getNameEnd()
    {
        if (nameNode != null)
            return nameNode.getEnd();
        return -1;
    }

    @Override
    public int getNameStart()
    {
        if (nameNode != null)
            return nameNode.getStart();
        return -1;
    }

    @Override
    public int getNameAbsoluteStart()
    {
        if (nameNode != null)
            return nameNode.getAbsoluteStart();
        return -1;
    }

    @Override
    public int getNameAbsoluteEnd()
    {
        if (nameNode != null)
            return nameNode.getAbsoluteEnd();
        return -1;
    }

    @Override
    protected void analyze(EnumSet<PostProcessStep> set, ASScope scope, Collection<ICompilerProblem> problems)
    {
    }

    @Override
    public String getShortName()
    {
        return getName();
    }

    @Override
    public String getQualifiedName()
    {
        String parentQualifiedName = getParentQualifiedName();
        if (parentQualifiedName != null && parentQualifiedName.length() > 0)
            return parentQualifiedName + "." + getShortName();
        if (getPackageName() != null && getPackageName().length() > 0)
            return getPackageName() + "." + getShortName();

        return getShortName();
    }

    /**
     * Returns true if our definition matches the passed in definition
     *
     * @param node the {@link BaseDefinitionNode} to compare against
     * @return true if we are a match
     */
    public boolean matches(BaseDefinitionMetaTagNode node)
    {
        if (node == null)
            return false;

        if (node.getClass() != getClass())
            return false;

        if (node == this)
            return true;

        if (node.getQualifiedName().compareTo(getQualifiedName()) != 0)
            return false;

        String packageName = node.getPackageName();
        String packageName2 = getPackageName();
        if (packageName == null && packageName2 != null)
            return false;

        if (packageName != null && packageName2 != null && packageName.compareTo(packageName2) != 0)
            return false;

        if (node.getContainingFilePath().compareTo(getContainingFilePath()) != 0)
                return false;
        return true;
    }

    public String getParentQualifiedName()
    {
        IASNode parent = getParent();
        if (parent instanceof MetaTagsNode)
        {
            IASNode decNode = ((MetaTagsNode)parent).getDecoratedDefinition();
            if (decNode != null)
                return ((IDefinitionNode)decNode).getQualifiedName();
        }
        return null;
    }

    @Override
    public boolean hasModifier(ASModifier modifier)
    {
        return false;
    }

    @Override
    public boolean hasNamespace(String namespace)
    {
        return false;
    }

    @Override
    public boolean isImplicit()
    {
        return false;
    }

    @Override
    public IMetaTagsNode getMetaTags()
    {
        return null;
    }

    @Override
    public IMetaInfo[] getMetaInfos()
    {
        return new IMetaInfo[0];
    }

    @Override
    public String getNamespace()
    {
        return null;
    }

    public INamespaceNode resolveNamespace()
    {
        return null;
    }

    public void setASDocComment(IASDocComment ref)
    {
        asDocComment = ref;
    }

    /**
     * Determines if this node has an explicit comment
     */
    @Override
    public boolean hasExplicitComment()
    {
        return asDocComment != null;
    }

    /**
     * Returns the raw {@link IASDocComment} without any processing
     *
     * @return an {@link IASDocComment} or null
     */
    public IASDocComment getASDocComment()
    {
        return asDocComment;
    }
}


text:
package rx.parse2;

import android.app.Activity;

import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;

import java.util.Collection;
import java.util.Date;

import io.reactivex.Completable;
import io.reactivex.Single;
import io.reactivex.annotations.CheckReturnValue;
import io.reactivex.annotations.NonNull;
import rx.bolts2.RxTask;

public class ParseFacebookObservable {

    @NonNull
    public static Completable link(@NonNull final ParseUser user, @NonNull final Activity activity) {
        return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, activity));
    }

    @NonNull
    public static Completable link(@NonNull final ParseUser user, @NonNull final Activity activity, int activityCode) {
        return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, activity, activityCode));
    }

    @NonNull
    public static Completable link(@NonNull final ParseUser user, @NonNull final Collection<String> permissions, @NonNull final Activity activity) {
        return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, permissions, activity));
    }

    @NonNull
    public static Completable link(@NonNull final ParseUser user, @NonNull final Collection<String> permissions, @NonNull final Activity activity, int activityCode) {
        return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, permissions, activity, activityCode));
    }

    @NonNull
    public static Completable link(@NonNull final ParseUser user, @NonNull final String facebookId, @NonNull final String accessToken, @NonNull final Date expirationDate) {
        return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, facebookId, accessToken, expirationDate));
    }

    @CheckReturnValue
    @NonNull
    public static Single<ParseUser> logIn(@NonNull final Collection<String> permissions, Activity activity, int activityCode) {
        return RxTask.single(() -> ParseFacebookUtils.logInInBackground(permissions, activity, activityCode));
    }

    @CheckReturnValue
    @NonNull
    public static Single<ParseUser> logIn(@NonNull final Collection<String> permissions, @NonNull final Activity activity) {
        // package class com.parse.FacebookAuthenticationProvider.DEFAULT_AUTH_ACTIVITY_CODE
        // private com.facebook.android.Facebook.DEFAULT_AUTH_ACTIVITY_CODE = 32665
        return logIn(permissions, activity, 32665);
    }

    @CheckReturnValue
    @NonNull
    public static Single<ParseUser> logIn(@NonNull final String facebookId, @NonNull final String accessToken, @NonNull final Date expirationDate) {
        return RxTask.single(() -> ParseFacebookUtils.logInInBackground(facebookId, accessToken, expirationDate));
    }

    @NonNull
    public static Completable saveLatestSessionData(@NonNull final ParseUser user) {
        return RxTask.completable(() -> ParseFacebookUtils.saveLatestSessionDataInBackground(user));
    }

    @NonNull
    public static Completable unlink(@NonNull final ParseUser user) {
        return RxTask.completable(() -> ParseFacebookUtils.unlinkInBackground(user));
    }

}


text:
package controllers.Post

import controllers.{Secured}
import models.Post.ModelComment
import org.joda.time.DateTime
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.MongoController
import reactivemongo.api.collections.default.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import scala.concurrent.ExecutionContext.Implicits.global
import play.api.Logger

import scala.concurrent.Future

/**
 * Created by marvin on 15-5-29.
 *
 */
class Comment extends Controller with MongoController with Secured {
  def collection = db.collection[BSONCollection]("comments")

  def makeComment(id:String) = Action.async { implicit request =>
      ModelComment.form.bindFromRequest.fold(
        errors => Future.successful(Ok("Error")),
        comment =>
          collection.insert(comment.copy(postId = Some(BSONObjectID(id)),creationDate = Some(new DateTime()), updateDate = Some(new DateTime()))).map(_ =>
            Redirect(controllers.Post.routes.Post.getAllPost()))
      )
  }

  def deleteCommentById(id:String) = Action.async{implicit request =>
    Logger.info("deleteCommentById")
    collection.remove(BSONDocument("_id" -> BSONObjectID(id))).map{
      case lastError => Redirect(controllers.Post.routes.Post.getAllPost())
    }
  }

  /*def getCommentByPostId(postId:String) = Action.async{
    implicit request =>
      val comments = collection.find(BSONDocument("postId" -> BSONObjectID(postId))).cursor[models.Post.Comment]
      comments.collect[List]().map { commentList =>
        val contentList: List[String] = commentList.map {
          comment => comment.content
        }
        Logger.info(contentList.toString())
        Ok(views.html.Post.comments.render(contentList))
      }
  }*/

}


text:
using PAC
using Base.Test

seed = 100
srand(seed)

include("testutils.jl")
include("spouse_pomdp.jl") # creates a pomdp named spse_problem

policy = safePolicy
curr_state = "happy"

obs_freq = Dict(observations, zeros(size(observations)))
state_freq = Dict(states, zeros(size(states)))
total_reward = 0.0

# simulate for a million trials
N =1_000_000
obs = Nothing()
for i=1:N
  old_state = curr_state
  action = policy(obs, actions)
  curr_state = spse_problem.transition(curr_state, action)
  total_reward += spse_problem.reward(old_state, action, curr_state)
  obs = spse_problem.emission(old_state, action, curr_state)

  # collect frequencies
  obs_freq[obs] += 1
  state_freq[curr_state] += 1
end

print("Total Reward: ")
println(total_reward)
println("Simulation Frequencies")
print("Observations: ")
println(obs_freq)
print("States: ")
println(state_freq)

# safe policy values
safe_obs_freq = ["calm"=>258116.0,"smiling"=>643698.0,"yelling"=>98186.0]
safe_state_freq = ["angry"=>195917.0,"happy"=>804083.0]

if seed == 100
  errortol = 1e-9*N
else
  errortol = 1e-2*N
end

testDict(obs_freq, safe_obs_freq, errortol)
testDict(state_freq, safe_state_freq, errortol)


text:
package main

import (
	"github.com/spf13/cobra"

	"fmt"

	genprotopb "github.com/googleapis/gapic-showcase/server/genproto"

	"github.com/golang/protobuf/jsonpb"

	"google.golang.org/api/iterator"

	"os"
)

var ListUsersInput genprotopb.ListUsersRequest

var ListUsersFromFile string

func init() {
	IdentityServiceCmd.AddCommand(ListUsersCmd)

	ListUsersCmd.Flags().Int32Var(&ListUsersInput.PageSize, "page_size", 10, "Default is 10. The maximum number of users to return. Server may...")

	ListUsersCmd.Flags().StringVar(&ListUsersInput.PageToken, "page_token", "", "The value of...")

	ListUsersCmd.Flags().StringVar(&ListUsersFromFile, "from_file", "", "Absolute path to JSON file containing request payload")

}

var ListUsersCmd = &cobra.Command{
	Use:   "list-users",
	Short: "Lists all users.",
	Long:  "Lists all users.",
	PreRun: func(cmd *cobra.Command, args []string) {

		if ListUsersFromFile == "" {

		}

	},
	RunE: func(cmd *cobra.Command, args []string) (err error) {

		in := os.Stdin
		if ListUsersFromFile != "" {
			in, err = os.Open(ListUsersFromFile)
			if err != nil {
				return err
			}
			defer in.Close()

			err = jsonpb.Unmarshal(in, &ListUsersInput)
			if err != nil {
				return err
			}

		}

		if Verbose {
			printVerboseInput("Identity", "ListUsers", &ListUsersInput)
		}
		iter := IdentityClient.ListUsers(ctx, &ListUsersInput)

		// populate iterator with a page
		_, err = iter.Next()
		if err != nil && err != iterator.Done {
			return err
		}

		if Verbose {
			fmt.Print("Output: ")
		}
		printMessage(iter.Response)

		return err
	},
}


text:
package constants

import (
	"bytes"
	"text/template"

	"github.com/cihangir/gene/generators/common"
	"github.com/cihangir/gene/utils"
	"github.com/cihangir/schema"
)

// Generate generates the constants for given schema/model
func Generate(s *schema.Schema) ([]byte, error) {
	temp := template.New("constants.tmpl").Funcs(common.TemplateFuncs)
	if _, err := temp.Parse(ConstantsTemplate); err != nil {
		return nil, err
	}

	data := struct {
		Schema *schema.Schema
	}{
		Schema: s,
	}

	var buf bytes.Buffer

	if err := temp.ExecuteTemplate(&buf, "constants.tmpl", data); err != nil {
		return nil, err
	}

	return utils.Clear(buf)
}

// ConstantsTemplate holds the template for the constant generation
var ConstantsTemplate = `
{{$title := .Schema.Title}}
{{range $key, $value := .Schema.Properties}}
    {{if len $value.Enum}}
        // {{DepunctWithInitialUpper $title}}{{DepunctWithInitialUpper $key}} holds the predefined enums
        var {{DepunctWithInitialUpper $title}}{{DepunctWithInitialUpper $key}}  = struct {
        {{range $defKey, $val := $value.Enum}}
            {{DepunctWithInitialUpper $val}} string
        {{end}}
        }{
        {{range $defKey, $val := $value.Enum}}
            {{DepunctWithInitialUpper $val}}: "{{$val}}",
        {{end}}
        }
    {{end}}
{{end}}
`


text:
package com.urcraft.wurm.sickle.common.json;

import java.io.IOException;

@SuppressWarnings("serial") // use default serial UID
class JsonNumber extends JsonValue {

  private final String string;

  JsonNumber(String string) {
    if (string == null) {
      throw new NullPointerException("string is null");
    }
    this.string = string;
  }

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

  @Override
  void write(JsonWriter writer) throws IOException {
    writer.writeNumber(string);
  }

  @Override
  public boolean isNumber() {
    return true;
  }

  @Override
  public int asInt() {
    return Integer.parseInt(string, 10);
  }

  @Override
  public long asLong() {
    return Long.parseLong(string, 10);
  }

  @Override
  public float asFloat() {
    return Float.parseFloat(string);
  }

  @Override
  public double asDouble() {
    return Double.parseDouble(string);
  }

  @Override
  public int hashCode() {
    return string.hashCode();
  }

  @Override
  public boolean equals(Object object) {
    if (this == object) {
      return true;
    }
    if (object == null) {
      return false;
    }
    if (getClass() != object.getClass()) {
      return false;
    }
    JsonNumber other = (JsonNumber)object;
    return string.equals(other.string);
  }

}