text:
package org.bson.json;

import org.bson.BsonBinary;
import org.bson.BsonDbPointer;
import org.bson.BsonInvalidOperationException;
import org.bson.BsonRegularExpression;
import org.bson.BsonTimestamp;
import org.bson.types.Decimal128;
import org.bson.types.ObjectId;
import org.junit.Before;
import org.junit.Test;

import java.io.StringWriter;
import java.util.Date;
import java.util.List;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;

@SuppressWarnings("unchecked")
public class JsonWriterTest {
    private StringWriter stringWriter;
    private JsonWriter writer;

    @Before
    public void before() {
        stringWriter = new StringWriter();
        writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().build());
    }

    private static class TestData<T> {
        private final T value;
        private final String expected;

        TestData(final T value, final String expected) {
            this.value = value;
            this.expected = expected;
        }
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowExceptionForBooleanWhenWritingBeforeStartingDocument() {
        writer.writeBoolean("b1", true);
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowExceptionForNameWhenWritingBeforeStartingDocument() {
        writer.writeName("name");
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowExceptionForStringWhenStateIsValue() {
        writer.writeStartDocument();
        writer.writeString("SomeString");
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowExceptionWhenEndingAnArrayWhenStateIsValue() {
        writer.writeStartDocument();
        writer.writeEndArray();
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowExceptionWhenWritingASecondName() {
        writer.writeStartDocument();
        writer.writeName("f1");
        writer.writeName("i2");
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowExceptionWhenEndingADocumentBeforeValueIsWritten() {
        writer.writeStartDocument();
        writer.writeName("f1");
        writer.writeEndDocument();
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnExceptionWhenTryingToWriteASecondValue() {
        writer.writeDouble(100);
        writer.writeString("i2");
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnExceptionWhenTryingToWriteJavaScript() {
        writer.writeDouble(100);
        writer.writeJavaScript("var i");
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnExceptionWhenWritingANameInAnArray() {
        writer.writeStartDocument();
        writer.writeStartArray("f2");
        writer.writeName("i3");
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnExceptionWhenEndingDocumentInTheMiddleOfWritingAnArray() {
        writer.writeStartDocument();
        writer.writeStartArray("f2");
        writer.writeEndDocument();
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnExceptionWhenEndingAnArrayInASubDocument() {
        writer.writeStartDocument();
        writer.writeStartArray("f2");
        writer.writeStartDocument();
        writer.writeEndArray();
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnExceptionWhenWritingANameInAnArrayEvenWhenSubDocumentExistsInArray() {
        writer.writeStartDocument();
        writer.writeStartArray("f2");
        writer.writeStartDocument();
        writer.writeEndDocument();
        writer.writeName("i3");
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnExceptionWhenAttemptingToEndAnArrayThatWasNotStarted() {
        writer.writeStartDocument();
        writer.writeStartArray("f2");
        writer.writeEndArray();
        writer.writeEndArray();
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnErrorIfTryingToWriteNameIntoAJavascriptScope() {
        writer.writeStartDocument();
        writer.writeJavaScriptWithScope("js1", "var i = 1");

        writer.writeName("b1");
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnErrorIfTryingToWriteValueIntoAJavascriptScope() {
        writer.writeStartDocument();
        writer.writeJavaScriptWithScope("js1", "var i = 1");

        writer.writeBinaryData(new BsonBinary(new byte[]{0, 0, 1, 0}));
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnErrorIfTryingToWriteArrayIntoAJavascriptScope() {
        writer.writeStartDocument();
        writer.writeJavaScriptWithScope("js1", "var i = 1");

        writer.writeStartArray();
    }

    @Test(expected = BsonInvalidOperationException.class)
    public void shouldThrowAnErrorIfTryingToWriteEndDocumentIntoAJavascriptScope() {
        writer.writeStartDocument();
        writer.writeJavaScriptWithScope("js1", "var i = 1");

        writer.writeEndDocument();
    }

    @Test
    public void testEmptyDocument() {
        writer.writeStartDocument();
        writer.writeEndDocument();
        String expected = "{}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testSingleElementDocument() {
        writer.writeStartDocument();
        writer.writeName("s");
        writer.writeString("str");
        writer.writeEndDocument();
        String expected = "{\"s\": \"str\"}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testTwoElementDocument() {
        writer.writeStartDocument();
        writer.writeName("s");
        writer.writeString("str");
        writer.writeName("d");
        writer.writeString("str2");
        writer.writeEndDocument();
        String expected = "{\"s\": \"str\", \"d\": \"str2\"}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testNestedDocument() {
        writer.writeStartDocument();
        writer.writeName("doc");
        writer.writeStartDocument();
        writer.writeName("doc");
        writer.writeStartDocument();
        writer.writeName("s");
        writer.writeString("str");
        writer.writeEndDocument();
        writer.writeEndDocument();
        writer.writeEndDocument();
        String expected = "{\"doc\": {\"doc\": {\"s\": \"str\"}}}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testSingleString() {
        writer.writeStartDocument();
        writer.writeString("abc", "xyz");
        writer.writeEndDocument();
        String expected = "{\"abc\": \"xyz\"}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testBoolean() {
        writer.writeStartDocument();
        writer.writeBoolean("abc", true);
        writer.writeEndDocument();
        String expected = "{\"abc\": true}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testDouble() {
        List<TestData<Double>> tests = asList(new TestData<Double>(0.0, "0.0"), new TestData<Double>(0.0005, "5.0E-4"),
                new TestData<Double>(0.5, "0.5"), new TestData<Double>(1.0, "1.0"),
                new TestData<Double>(1.5, "1.5"), new TestData<Double>(1.5E+40, "1.5E40"),
                new TestData<Double>(1.5E-40, "1.5E-40"),
                new TestData<Double>(1234567890.1234568E+123, "1.2345678901234568E132"),
                new TestData<Double>(Double.MAX_VALUE, "1.7976931348623157E308"),
                new TestData<Double>(Double.MIN_VALUE, "4.9E-324"),

                new TestData<Double>(-0.0005, "-5.0E-4"),
                new TestData<Double>(-0.5, "-0.5"),
                new TestData<Double>(-1.0, "-1.0"),
                new TestData<Double>(-1.5, "-1.5"),
                new TestData<Double>(-1.5E+40, "-1.5E40"),
                new TestData<Double>(-1.5E-40, "-1.5E-40"),
                new TestData<Double>(-1234567890.1234568E+123, "-1.2345678901234568E132"),

                new TestData<Double>(Double.NaN, "NaN"),
                new TestData<Double>(Double.NEGATIVE_INFINITY, "-Infinity"),
                new TestData<Double>(Double.POSITIVE_INFINITY, "Infinity"));
        for (final TestData<Double> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build());
            writer.writeStartDocument();
            writer.writeDouble("d", cur.value);
            writer.writeEndDocument();
            String expected = "{\"d\": {\"$numberDouble\": \"" + cur.expected + "\"}}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testInt64Shell() {
        List<TestData<Long>> tests = asList(new TestData<Long>(Long.MIN_VALUE, "NumberLong(\"-9223372036854775808\")"),
                new TestData<Long>(Integer.MIN_VALUE - 1L, "NumberLong(\"-2147483649\")"),
                new TestData<Long>(Integer.MIN_VALUE + 0L, "NumberLong(-2147483648)"),
                new TestData<Long>(0L, "NumberLong(0)"),
                new TestData<Long>(Integer.MAX_VALUE + 0L, "NumberLong(2147483647)"),
                new TestData<Long>(Integer.MAX_VALUE + 1L, "NumberLong(\"2147483648\")"),
                new TestData<Long>(Long.MAX_VALUE, "NumberLong(\"9223372036854775807\")"));
        for (final TestData<Long> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
            writer.writeStartDocument();
            writer.writeInt64("l", cur.value);
            writer.writeEndDocument();
            String expected = "{\"l\": " + cur.expected + "}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testInt64Relaxed() {
        List<TestData<Long>> tests = asList(new TestData<Long>(Long.MIN_VALUE, "-9223372036854775808"),
                new TestData<Long>(Integer.MIN_VALUE - 1L, "-2147483649"),
                new TestData<Long>(Integer.MIN_VALUE - 0L, "-2147483648"),
                new TestData<Long>(0L, "0"),
                new TestData<Long>(Integer.MAX_VALUE + 0L, "2147483647"),
                new TestData<Long>(Integer.MAX_VALUE + 1L, "2147483648"),
                new TestData<Long>(Long.MAX_VALUE, "9223372036854775807"));

        for (final TestData<Long> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());
            writer.writeStartDocument();
            writer.writeInt64("l", cur.value);
            writer.writeEndDocument();
            String expected = "{\"l\": " + cur.expected + "}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testDecimal128SShell() {
        List<TestData<Decimal128>> tests = asList(
                new TestData<Decimal128>(Decimal128.parse("1.0"), "1.0"),
                new TestData<Decimal128>(Decimal128.POSITIVE_INFINITY, Decimal128.POSITIVE_INFINITY.toString()));

        for (final TestData<Decimal128> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
            writer.writeStartDocument();
            writer.writeDecimal128("d", cur.value);
            writer.writeEndDocument();
            String expected = "{\"d\": NumberDecimal(\"" + cur.expected + "\")}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testDecimal128Relaxed() {
        List<TestData<Decimal128>> tests = asList(
                new TestData<Decimal128>(Decimal128.parse("1.0"), "1.0"),
                new TestData<Decimal128>(Decimal128.POSITIVE_INFINITY, Decimal128.POSITIVE_INFINITY.toString()));

        for (final TestData<Decimal128> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());
            writer.writeStartDocument();
            writer.writeDecimal128("d", cur.value);
            writer.writeEndDocument();
            String expected = "{\"d\": {\"$numberDecimal\": \"" + cur.expected + "\"}}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testArray() {
        writer.writeStartDocument();
        writer.writeStartArray("array");
        writer.writeInt32(1);
        writer.writeInt32(2);
        writer.writeInt32(3);
        writer.writeEndArray();
        writer.writeEndDocument();
        String expected = "{\"array\": [1, 2, 3]}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testBinaryRelaxed() {
        List<TestData<BsonBinary>> tests = asList(new TestData<BsonBinary>(new BsonBinary(new byte[0]),
                        "{\"$binary\": {\"base64\": \"\", "
                                + "\"subType\": \"00\"}}"),
                new TestData<BsonBinary>(new BsonBinary(new byte[]{1}),
                        "{\"$binary\": {\"base64\": \"AQ==\", "
                                + "\"subType\": \"00\"}}"),
                new TestData<BsonBinary>(new BsonBinary(new byte[]{1, 2}),
                        "{\"$binary\": {\"base64\": \"AQI=\", "
                                + "\"subType\": \"00\"}}"),
                new TestData<BsonBinary>(new BsonBinary(new byte[]{1, 2, 3}),
                        "{\"$binary\": {\"base64\": \"AQID\", "
                                + "\"subType\": \"00\"}}"),
                new TestData<BsonBinary>(new BsonBinary((byte) 0x80, new byte[]{1, 2, 3}),
                        "{\"$binary\": {\"base64\": \"AQID\", "
                                + "\"subType\": \"80\"}}"));
        for (final TestData<BsonBinary> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());
            writer.writeStartDocument();
            writer.writeBinaryData("binary", cur.value);
            writer.writeEndDocument();
            String expected = "{\"binary\": " + cur.expected + "}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testBinaryShell() {
        List<TestData<BsonBinary>> tests = asList(new TestData<BsonBinary>(new BsonBinary(new byte[0]), "new BinData(0, \"\")"),
                new TestData<BsonBinary>(new BsonBinary(new byte[]{1}), "new BinData(0, \"AQ==\")"),
                new TestData<BsonBinary>(new BsonBinary(new byte[]{1, 2}), "new BinData(0, \"AQI=\")"),
                new TestData<BsonBinary>(new BsonBinary(new byte[]{1, 2, 3}), "new BinData(0, \"AQID\")"),
                new TestData<BsonBinary>(new BsonBinary((byte) 0x80, new byte[]{1, 2, 3}),
                        "new BinData(128, \"AQID\")"));
        for (final TestData<BsonBinary> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
            writer.writeStartDocument();
            writer.writeBinaryData("binary", cur.value);
            writer.writeEndDocument();
            String expected = "{\"binary\": " + cur.expected + "}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testDateTimeRelaxed() {
        List<TestData<Date>> tests = asList(new TestData<Date>(new Date(0), "{\"$date\": \"1970-01-01T00:00:00Z\"}"),
                new TestData<Date>(new Date(Long.MAX_VALUE), "{\"$date\": {\"$numberLong\": \"9223372036854775807\"}}"),
                new TestData<Date>(new Date(Long.MIN_VALUE), "{\"$date\": {\"$numberLong\": \"-9223372036854775808\"}}"));
        for (final TestData<Date> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());
            writer.writeStartDocument();
            writer.writeDateTime("date", cur.value.getTime());
            writer.writeEndDocument();
            String expected = "{\"date\": " + cur.expected + "}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testDateTimeShell() {
        List<TestData<Date>> tests = asList(new TestData<Date>(new Date(0), "ISODate(\"1970-01-01T00:00:00.000Z\")"),
                new TestData<Date>(new Date(1), "ISODate(\"1970-01-01T00:00:00.001Z\")"),
                new TestData<Date>(new Date(-1), "ISODate(\"1969-12-31T23:59:59.999Z\")"),
                new TestData<Date>(new Date(Long.MAX_VALUE), "new Date(9223372036854775807)"),
                new TestData<Date>(new Date(Long.MIN_VALUE), "new Date(-9223372036854775808)"));
        for (final TestData<Date> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
            writer.writeStartDocument();
            writer.writeDateTime("date", cur.value.getTime());
            writer.writeEndDocument();
            String expected = "{\"date\": " + cur.expected + "}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testJavaScript() {
        writer.writeStartDocument();
        writer.writeJavaScript("f", "function f() { return 1; }");
        writer.writeEndDocument();
        String expected = "{\"f\": {\"$code\": \"function f() { return 1; }\"}}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testJavaScriptWithScope() {
        writer.writeStartDocument();
        writer.writeJavaScriptWithScope("f", "function f() { return n; }");
        writer.writeStartDocument();
        writer.writeInt32("n", 1);
        writer.writeEndDocument();
        writer.writeEndDocument();
        String expected =
                "{\"f\": {\"$code\": \"function f() { return n; }\", " + "\"$scope\": {\"n\": 1}}}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testMaxKeyStrict() {
        writer.writeStartDocument();
        writer.writeMaxKey("maxkey");
        writer.writeEndDocument();
        String expected = "{\"maxkey\": {\"$maxKey\": 1}}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testMinKeyStrict() {
        writer.writeStartDocument();
        writer.writeMinKey("minkey");
        writer.writeEndDocument();
        String expected = "{\"minkey\": {\"$minKey\": 1}}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testMaxKeyShell() {
        writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
        writer.writeStartDocument();
        writer.writeMaxKey("maxkey");
        writer.writeEndDocument();
        String expected = "{\"maxkey\": MaxKey}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testMinKeyShell() {
        writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
        writer.writeStartDocument();
        writer.writeMinKey("minkey");
        writer.writeEndDocument();
        String expected = "{\"minkey\": MinKey}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testNull() {
        writer.writeStartDocument();
        writer.writeNull("null");
        writer.writeEndDocument();
        String expected = "{\"null\": null}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testObjectIdShell() {
        writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
        ObjectId objectId = new ObjectId("4d0ce088e447ad08b4721a37");

        writer.writeStartDocument();
        writer.writeObjectId("_id", objectId);
        writer.writeEndDocument();

        String expected = "{\"_id\": ObjectId(\"4d0ce088e447ad08b4721a37\")}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testObjectIdStrict() {
        ObjectId objectId = new ObjectId("4d0ce088e447ad08b4721a37");

        writer.writeStartDocument();
        writer.writeObjectId("_id", objectId);
        writer.writeEndDocument();

        String expected = "{\"_id\": {\"$oid\": \"4d0ce088e447ad08b4721a37\"}}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testRegularExpressionShell() {
        List<TestData<BsonRegularExpression>> tests;
        tests = asList(new TestData<BsonRegularExpression>(new BsonRegularExpression(""), "/(?:)/"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a"), "/a/"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a/b"), "/a\\/b/"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a\\b"), "/a\\b/"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "i"), "/a/i"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "m"), "/a/m"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "x"), "/a/x"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "s"), "/a/s"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "imxs"), "/a/imsx"));
        for (final TestData<BsonRegularExpression> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
            writer.writeStartDocument();
            writer.writeRegularExpression("regex", cur.value);
            writer.writeEndDocument();
            String expected = "{\"regex\": " + cur.expected + "}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testRegularExpressionRelaxed() {
        List<TestData<BsonRegularExpression>> tests;
        tests = asList(new TestData<BsonRegularExpression>(new BsonRegularExpression(""),
                        "{\"$regularExpression\": {\"pattern\": \"\", \"options\": \"\"}}"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a"),
                        "{\"$regularExpression\": {\"pattern\": \"a\", \"options\": \"\"}}"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a/b"),
                        "{\"$regularExpression\": {\"pattern\": \"a/b\", \"options\": \"\"}}"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a\\b"),
                        "{\"$regularExpression\": {\"pattern\": \"a\\\\b\", \"options\": \"\"}}"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "i"),
                        "{\"$regularExpression\": {\"pattern\": \"a\", \"options\": \"i\"}}"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "m"),
                        "{\"$regularExpression\": {\"pattern\": \"a\", \"options\": \"m\"}}"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "x"),
                        "{\"$regularExpression\": {\"pattern\": \"a\", \"options\": \"x\"}}"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "s"),
                        "{\"$regularExpression\": {\"pattern\": \"a\", \"options\": \"s\"}}"),
                new TestData<BsonRegularExpression>(new BsonRegularExpression("a", "imxs"),
                        "{\"$regularExpression\": {\"pattern\": \"a\", \"options\": \"imsx\"}}"));
        for (final TestData<BsonRegularExpression> cur : tests) {
            stringWriter = new StringWriter();
            writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());
            writer.writeStartDocument();
            writer.writeRegularExpression("regex", cur.value);
            writer.writeEndDocument();
            String expected = "{\"regex\": " + cur.expected + "}";
            assertEquals(expected, stringWriter.toString());
        }
    }

    @Test
    public void testSymbol() {
        writer.writeStartDocument();
        writer.writeSymbol("symbol", "name");
        writer.writeEndDocument();
        String expected = "{\"symbol\": {\"$symbol\": \"name\"}}";
        assertEquals(expected, stringWriter.toString());
    }

    //
    @Test
    public void testTimestampStrict() {
        writer.writeStartDocument();
        writer.writeTimestamp("timestamp", new BsonTimestamp(1000, 1));
        writer.writeEndDocument();
        String expected = "{\"timestamp\": {\"$timestamp\": {\"t\": 1000, \"i\": 1}}}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testTimestampShell() {
        writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
        writer.writeStartDocument();
        writer.writeTimestamp("timestamp", new BsonTimestamp(1000, 1));
        writer.writeEndDocument();
        String expected = "{\"timestamp\": Timestamp(1000, 1)}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testUndefinedRelaxed() {
        writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());
        writer.writeStartDocument();
        writer.writeUndefined("undefined");
        writer.writeEndDocument();
        String expected = "{\"undefined\": {\"$undefined\": true}}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testUndefinedShell() {
        writer = new JsonWriter(stringWriter, JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build());
        writer.writeStartDocument();
        writer.writeUndefined("undefined");
        writer.writeEndDocument();
        String expected = "{\"undefined\": undefined}";
        assertEquals(expected, stringWriter.toString());
    }

    @Test
    public void testDBPointer() {
        writer.writeStartDocument();
        writer.writeDBPointer("dbPointer", new BsonDbPointer("my.test", new ObjectId("4d0ce088e447ad08b4721a37")));
        writer.writeEndDocument();
        String expected = "{\"dbPointer\": {\"$ref\": \"my.test\", \"$id\": {\"$oid\": \"4d0ce088e447ad08b4721a37\"}}}";
        assertEquals(expected, stringWriter.toString());
    }
}


text:
This repo will teach you the basics of Javascript programming language and Jquery library.

Javascript
------------------

JavaScript is a lightweight, interpreted programming language. It is designed for creating network-centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and cross-platform.

Jquery
------------------

jQuery is a fast and concise JavaScript library created by John Resig in 2006. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for Rapid Web Development.

JQuery is a library of Java scripts that simplifies event handling, animations etc. It is very powerful and easy to use.

JavaScript vs JQuery
------------------

JavaScript is a language. jQuery is a library built with JavaScript to help JavaScript programmers who are doing common web tasks.

Both JavaScript and Jquery are javascripts. The only difference is that jQuery has been optimized to perform many common scripting functions in fewer lines of codes.

Coding challenges - Try it yourself online
------------------

Check out the below code challenges made with [Code School](https://www.codeschool.com/)

https://www.javascript.com/

http://try.jquery.com/

Exercises
------------------
Find more lessons and exercise files in the exercises folder

redpajama_set_name: RedPajamaGithub


text:
package info.tregmine.listeners;

import info.tregmine.Tregmine;
import info.tregmine.api.*;
import info.tregmine.api.lore.Created;
import info.tregmine.api.util.ScoreboardClearTask;
import info.tregmine.commands.MentorCommand;
import info.tregmine.database.*;
import info.tregmine.events.PlayerMoveBlockEvent;
import info.tregmine.quadtree.Point;
import info.tregmine.zones.Lot;
import info.tregmine.zones.ZoneWorld;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Skull;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scoreboard.*;

import java.util.*;

public class TregminePlayerListener implements Listener {
    private Tregmine plugin;
    private Map<Item, GenericPlayer> droppedItems;

    public TregminePlayerListener(Tregmine instance) {
        this.plugin = instance;

        droppedItems = new HashMap<>();
    }

    private void activateGuardians() {
        // Identify all guardians and categorize them based on their current
        // state
        Collection<? extends Player> players = plugin.getServer().getOnlinePlayers();
        Set<GenericPlayer> guardians = new HashSet<GenericPlayer>();
        List<GenericPlayer> activeGuardians = new ArrayList<GenericPlayer>();
        List<GenericPlayer> inactiveGuardians = new ArrayList<GenericPlayer>();
        List<GenericPlayer> queuedGuardians = new ArrayList<GenericPlayer>();
        for (Player srvPlayer : players) {
            GenericPlayer guardian = plugin.getPlayer(srvPlayer.getName());
            if (guardian == null || guardian.getRank() != Rank.GUARDIAN) {
                continue;
            }

            GenericPlayer.GuardianState state = guardian.getGuardianState();
            if (state == null) {
                state = GenericPlayer.GuardianState.QUEUED;
            }

            switch (state) {
                case ACTIVE:
                    activeGuardians.add(guardian);
                    break;
                case INACTIVE:
                    inactiveGuardians.add(guardian);
                    break;
                case QUEUED:
                    queuedGuardians.add(guardian);
                    break;
            }

            guardian.setGuardianState(GenericPlayer.GuardianState.QUEUED);
            guardians.add(guardian);
        }

        Collections.sort(activeGuardians, new RankComparator());
        Collections.sort(inactiveGuardians, new RankComparator(true));
        Collections.sort(queuedGuardians, new RankComparator());

        int idealCount = (int) Math.ceil(Math.sqrt(players.size()) / 2);
        // There are not enough guardians active, we need to activate a few more
        if (activeGuardians.size() <= idealCount) {
            // Make a pool of every "willing" guardian currently online
            List<GenericPlayer> activationList = new ArrayList<GenericPlayer>();
            activationList.addAll(activeGuardians);
            activationList.addAll(queuedGuardians);

            // If the pool isn't large enough to satisfy demand, we add the
            // guardians
            // that have made themselves inactive as well.
            if (activationList.size() < idealCount) {
                int diff = idealCount - activationList.size();
                // If there aren't enough of these to satisfy demand, we add all
                // of them
                if (diff >= inactiveGuardians.size()) {
                    activationList.addAll(inactiveGuardians);
                }
                // Otherwise we just add the lowest ranked of the inactive
                else {
                    activationList.addAll(inactiveGuardians.subList(0, diff));
                }
            }

            // If there are more than necessarry guardians online, only activate
            // the most highly ranked.
            Set<GenericPlayer> activationSet;
            if (activationList.size() > idealCount) {
                Collections.sort(activationList, new RankComparator());
                activationSet = new HashSet<>(activationList.subList(0, idealCount));
            } else {
                activationSet = new HashSet<>(activationList);
            }

            // Perform activation
            StringBuffer globalMessage = new StringBuffer();
            String delim = "";
            for (GenericPlayer guardian : activationSet) {
                guardian.setGuardianState(GenericPlayer.GuardianState.ACTIVE);
                globalMessage.append(delim);
                globalMessage.append(guardian.getName());
                delim = ", ";
            }

            Set<GenericPlayer> oldActiveGuardians = new HashSet<GenericPlayer>(activeGuardians);
            if (!activationSet.containsAll(oldActiveGuardians) || activationSet.size() != oldActiveGuardians.size()) {

                plugin.getServer().broadcastMessage(ChatColor.BLUE + "Active guardians are: " + globalMessage
                        + ". Please contact any of them if you need help.");

                // Notify previously active guardian of their state change
                for (GenericPlayer guardian : activeGuardians) {
                    if (!activationSet.contains(guardian)) {
                        guardian.sendMessage(ChatColor.BLUE
                                + "You are no longer on active duty, and should not respond to help requests, unless asked by an admin or active guardian.");
                    }
                }

                // Notify previously inactive guardians of their state change
                for (GenericPlayer guardian : inactiveGuardians) {
                    if (activationSet.contains(guardian)) {
                        guardian.sendMessage(ChatColor.BLUE
                                + "You have been restored to active duty and should respond to help requests.");
                    }
                }

                // Notify previously queued guardians of their state change
                for (GenericPlayer guardian : queuedGuardians) {
                    if (activationSet.contains(guardian)) {
                        guardian.sendMessage(
                                ChatColor.BLUE + "You are now on active duty and should respond to help requests.");
                    }
                }
            }
        }
    }

    @EventHandler
    public void onDeath(PlayerDeathEvent event) {
        GenericPlayer player = plugin.getPlayer(event.getEntity());
        player.setLastPos(player.getLocation());
    }

    @EventHandler
    public void onEntityDamage(EntityDamageEvent event) {
        Entity e = event.getEntity();
        if (e instanceof Player) {
            if (event.getCause() == DamageCause.HOT_FLOOR) {
                event.setCancelled(true);
            }
        } else {
            return;
        }
    }

    @EventHandler
    public void onPlayerBlockMove(PlayerMoveBlockEvent event) {
        GenericPlayer player = event.getPlayer();

        // To add player.hasBadge for a flight badge when made
        if (player.getRank().canFly() && player.isFlying() && player.isSprinting()) {
            player.setFlySpeed(0.4f); // To be balanced
        } else {
            player.setFlySpeed(0.1f); // 0.1 is default
        }
    }

    @EventHandler
    public void onPlayerClick(PlayerInteractEvent event) {
        if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getHand() != EquipmentSlot.HAND) {
            return;
        }
        Player player = event.getPlayer();
        BlockState block = event.getClickedBlock().getState();
        if (block instanceof Skull) {
            Skull skull = (Skull) block;
            if (!skull.getSkullType().equals(SkullType.PLAYER)) {
                return;
            }
            OfflinePlayer owner = skull.getOwningPlayer();
            GenericPlayer skullowner = plugin.getPlayerOffline(owner);
            if (skullowner != null) {
                ChatColor C = skullowner.getNameColor();
                player.sendMessage(ChatColor.AQUA + "This is " + C + owner + "'s " + ChatColor.AQUA + "head!");
            } else {
                player.sendMessage(ChatColor.AQUA + "This is " + ChatColor.WHITE + owner + ChatColor.AQUA + "'s head!");

            }
        }
    }

    @EventHandler
    public void onPlayerDropItem(PlayerDropItemEvent event) {
        GenericPlayer player = this.plugin.getPlayer(event.getPlayer());

        if (player.getGameMode() == GameMode.CREATIVE) {
            event.setCancelled(true);
            return;
        }

        if (!player.getRank().arePickupsLogged()) {
            return;
        }

        if (!player.getRank().canPickup()) {
            event.setCancelled(true);
            return;
        }

        Item item = event.getItemDrop();
        droppedItems.put(item, player);
    }

    @EventHandler
    public void onPlayerFlight(PlayerToggleFlightEvent event) {
        GenericPlayer player = plugin.getPlayer(event.getPlayer());
        if (player.getRank().canModifyZones()) {
            return;
        }

        if (!player.getRank().canFly()) {
            event.setCancelled(true);
        }

        if (player.hasFlag(GenericPlayer.Flags.HARDWARNED) || player.hasFlag(GenericPlayer.Flags.SOFTWARNED)) {

            event.setCancelled(true);
        }

        Location loc = player.getLocation();

        ZoneWorld world = plugin.getWorld(loc.getWorld());
        Lot lot = world.findLot(new Point(loc.getBlockX(), loc.getBlockZ()));
        if (lot == null) {
            return;
        }

        if (!lot.hasFlag(Lot.Flags.FLIGHT_ALLOWED)) {
            event.setCancelled(true);
        }

    }

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
            Player player = event.getPlayer();
            Block block = event.getClickedBlock();
            Location loc = block.getLocation();

            if (player.getInventory().getItemInMainHand().getType() == Material.BOOK) {

                player.sendMessage(ChatColor.DARK_AQUA + "Type: " + ChatColor.AQUA + block.getType().toString() + " ("
                        + ChatColor.BLUE + block.getType().toString() + ChatColor.DARK_AQUA + ")");
                player.sendMessage(ChatColor.DARK_AQUA + "Data: " + ChatColor.AQUA + (int) block.getData());
                player.sendMessage(ChatColor.RED + "X" + ChatColor.WHITE + ", " + ChatColor.GREEN + "Y"
                        + ChatColor.WHITE + ", " + ChatColor.BLUE + "Z" + ChatColor.WHITE + ": " + ChatColor.RED
                        + loc.getBlockX() + ChatColor.WHITE + ", " + ChatColor.GREEN + loc.getBlockY() + ChatColor.WHITE
                        + ", " + ChatColor.BLUE + loc.getBlockZ());

                try {
                    player.sendMessage(ChatColor.DARK_AQUA + "Biome: " + ChatColor.AQUA + block.getBiome().toString());
                } catch (Exception e) {
                    player.sendMessage(ChatColor.DARK_AQUA + "Biome: " + ChatColor.AQUA + "NULL");
                }

                Tregmine.LOGGER.info("POS: " + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ());
            }
        }
    }

    @EventHandler
    public void onPlayerItemHeld(InventoryCloseEvent event) {
        Player player = (Player) event.getPlayer();
        if (player.getGameMode() == GameMode.CREATIVE) {
            for (ItemStack item : player.getInventory().getContents()) {
                if (item != null) {
                    if (item.hasItemMeta()) {
                        ItemMeta meta = item.getItemMeta();
                        List<String> oldlore = meta.getLore();
                        String line2 = "";
                        if (oldlore != null) {
                            line2 = oldlore.get(1).replace("Â", "");
                        }
                        List<String> lore = new ArrayList<String>();
                        lore.add(Created.CREATIVE.toColorString());
                        GenericPlayer p = this.plugin.getPlayer(player);
                        if (line2.contains("by: ") && !line2.contains(p.getChatNameNoHover())) {
                            lore.add(line2 + ", " + p.getChatNameNoHover());
                        } else {
                            lore.add(ChatColor.WHITE + "by: " + p.getChatNameNoHover());
                        }
                        lore.add(ChatColor.WHITE + "Value: " + ChatColor.MAGIC + "0000" + ChatColor.RESET
                                + ChatColor.WHITE + " Treg");
                        meta.setLore(lore);
                        item.setItemMeta(meta);
                    }
                }
            }
        }

        GenericPlayer p = plugin.getPlayer(player);
        if (p == null) {
            Tregmine.LOGGER.info(player.getName() + " was not found in player map.");
            return;
        }

        if (p.getCurrentInventory() != null) {
            p.saveInventory(p.getCurrentInventory());
        }
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        event.setJoinMessage(null);
        GenericPlayer player = plugin.getPlayer(event.getPlayer());
        if (player == null) {
            event.getPlayer().kickPlayer("error loading profile!");
            return;
        }

        Rank rank = player.getRank();

        // Handle invisibility, if set
        List<GenericPlayer> players = plugin.getOnlinePlayers();
        if (player.hasFlag(GenericPlayer.Flags.INVISIBLE)) {
            player.sendMessage(ChatColor.YELLOW + "You are now invisible!");

            // Hide the new player from all existing players
            for (GenericPlayer current : players) {
                if (!current.getRank().canVanish()) {
                    current.hidePlayer(player);
                } else {
                    current.showPlayer(player);
                }
            }
        } else {
            for (GenericPlayer current : players) {
                current.showPlayer(player);
            }
        }

        World cWorld = player.getWorld();
        String[] worldNamePortions = cWorld.getName().split("_");

        if (worldNamePortions[0].equalsIgnoreCase("world")) {
            player.loadInventory("survival", false);
        } else {
            player.loadInventory(worldNamePortions[0], false);
        }

        // Hide currently invisible players from the player that just signed on
        for (GenericPlayer current : players) {
            if (current.hasFlag(GenericPlayer.Flags.INVISIBLE)) {
                player.hidePlayer(current);
            } else {
                player.showPlayer(current);
            }

            if (player.getRank().canVanish()) {
                player.showPlayer(current);
            }
        }

        // Set applicable game mode
        if (rank == Rank.BUILDER) {
            player.setGameMode(GameMode.CREATIVE);
        } else if (!rank.canUseCreative()) {
            player.setGameMode(GameMode.SURVIVAL);
        }

        // Try to find a mentor for new players
        if (rank == Rank.UNVERIFIED) {

            return;
        }

        // Check if the player is allowed to fly
        if (player.hasFlag(GenericPlayer.Flags.HARDWARNED) || player.hasFlag(GenericPlayer.Flags.SOFTWARNED)) {
            player.sendMessage("You are warned and are not allowed to fly.");
            player.setAllowFlight(false);
        } else if (rank.canFly()) {
            if (player.hasFlag(GenericPlayer.Flags.FLY_ENABLED) || player.getGameMode() == GameMode.SPECTATOR) {
                player.sendMessage("Flying: Allowed and Enabled! Toggle flying with /fly");
                player.setAllowFlight(true);
            } else {
                player.sendMessage("Flying: Allowed but Disabled! Toggle flying with /fly");
                player.setAllowFlight(false);
            }
        } else {
            player.sendMessage("You are NOT allowed to fly");
            player.setAllowFlight(false);
        }

        try (IContext ctx = plugin.createContext()) {
            if (player.getPlayTime() > 10 * 3600 && rank == Rank.SETTLER) {
                player.setRank(Rank.RESIDENT);
                rank = Rank.RESIDENT;

                IPlayerDAO playerDAO = ctx.getPlayerDAO();
                playerDAO.updatePlayer(player);
                playerDAO.updatePlayerInfo(player);

                player.sendMessage(
                        ChatColor.DARK_GREEN + "Congratulations! " + "You are now a resident on Tregmine!");
            }

            // Load motd
            IMotdDAO motdDAO = ctx.getMotdDAO();
            String message = motdDAO.getMotd();
            if (message != null) {
                String[] lines = message.split("\n");
                for (String line : lines) {
                    player.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + line);
                }
            }
        } catch (DAOException e) {
            throw new RuntimeException(e);
        }

        // Show a score board
        if (player.isOnline()) {
            ScoreboardManager manager = Bukkit.getScoreboardManager();
            Scoreboard board = manager.getNewScoreboard();

            Objective objective = board.registerNewObjective("1", "2");
            objective.setDisplaySlot(DisplaySlot.SIDEBAR);
            objective.setDisplayName("" + ChatColor.AQUA + "" + ChatColor.BOLD + "Welcome to Tregmine!");

            // Update staff statistics
            plugin.updateStatistics();

            // Get a fake offline player
            String desc = ChatColor.BLUE + "Online guardians: ";
            Score score = objective.getScore(desc);

            score.setScore(plugin.getOnlineGuardians());

            String juniors = ChatColor.RED + "Online juniors: ";
            Score junior = objective.getScore(juniors);
            junior.setScore(plugin.getOnlineJuniors());

            String seniors = ChatColor.DARK_RED + "Online seniors: ";
            Score senior = objective.getScore(seniors);
            senior.setScore(plugin.getOnlineSeniors());
            try {
                player.setScoreboard(board);

                ScoreboardClearTask.start(plugin, player);
            } catch (IllegalStateException e) {
                // ignore
            }
        }

        // Recalculate guardians
        activateGuardians();

        if (rank == Rank.TOURIST || rank == Rank.UNVERIFIED) {
            // Try to find a mentor for tourists that rejoin
            MentorCommand.findMentor(plugin, player);
        } else if (player.canMentor()) {
            Queue<GenericPlayer> students = plugin.getStudentQueue();
            if (students.size() > 0) {
                player.sendMessage(
                        ChatColor.YELLOW + "Mentors are needed! " + "Type /mentor to offer your services!");
            }
        }

        if (rank == Rank.DONATOR && !player.hasBadge(Badge.PHILANTROPIST)) {
            player.awardBadgeLevel(Badge.PHILANTROPIST, "For being a Tregmine donator!");
        }
    }

    @EventHandler
    public void onPlayerKick(PlayerKickEvent event) {
        event.setLeaveMessage(null);
    }

    @EventHandler
    public void onPlayerLogin(PlayerLoginEvent event) {

        GenericPlayer player;

        try {
            player = plugin.addPlayer(event.getPlayer(), event.getAddress());
            if (player == null) {
                event.disallow(Result.KICK_OTHER, ChatColor.RED + "Something went wrong");
                return;
            }
        } catch (PlayerBannedException e) {
            event.disallow(Result.KICK_BANNED, e.getMessage());
            return;
        }

        if (player.getRank() == Rank.UNVERIFIED) {
            player.setChatState(GenericPlayer.ChatState.SETUP);
        }

        if (player.getLocation().getWorld().getName().matches("world_the_end")) {
            player.teleportWithHorse(this.plugin.getServer().getWorld("world").getSpawnLocation());
        }
        if (plugin.getLockdown() && !event.getPlayer().isOp()) {

            if (!player.getIsStaff()) {
                event.disallow(Result.KICK_OTHER, ChatColor.GOLD + "Tregmine " + ChatColor.RED
                        + "is on lockdown, only staff can join. Check the forums for more info.");
                return;
            }

        }

        if (player.getKeyword() != null) {
            String url = plugin.getConfig().getString("general.url").replace("http://", "").replace("https://", "")
                    + ":" + Bukkit.getPort();
            String urlnoport = plugin.getConfig().getString("general.url").replace("http://", "").replace("https://",
                    "");

            String keyword = player.getKeyword() + url.toLowerCase();
            Tregmine.LOGGER.warning("host: " + event.getHostname());
            Tregmine.LOGGER.warning("keyword:" + keyword);

            if (keyword.equals(event.getHostname().toLowerCase()) || keyword.matches(urlnoport)) {
                Tregmine.LOGGER.warning(player.getName() + " keyword :: success");
            } else {
                Tregmine.LOGGER.warning(player.getName() + " keyword :: faild");
                event.disallow(Result.KICK_BANNED, ChatColor.RED
                        + "Wrong keyword!\nIf you have forgotten your keyword, contact a senior admin via Discord.\nhttp://tinyurl.com/TregmineDiscord");
            }
        } else {
            Tregmine.LOGGER.warning(player.getName() + " keyword :: notset");
        }

        if (player.getRank() == Rank.GUARDIAN) {
            player.setGuardianState(GenericPlayer.GuardianState.ACTIVE);
        }
    }

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event) {
        GenericPlayer player = this.plugin.getPlayer(event.getPlayer());
        if (player.getFrozen()) {
            event.setCancelled(true);
        }
        if (player.isAfk()) {
            player.setAfk(false);
        }
    }

    @EventHandler
    public void onPlayerPickupItem(PlayerPickupItemEvent event) {
        GenericPlayer player = this.plugin.getPlayer(event.getPlayer());

        if (player.getGameMode() == GameMode.CREATIVE) {
            event.setCancelled(true);
            return;
        }

        if (!player.getRank().arePickupsLogged()) {
            return;
        }

        if (!player.getRank().canPickup()) {
            event.setCancelled(true);
            return;
        }

        try (IContext ctx = plugin.createContext()) {
            Item item = event.getItem();
            GenericPlayer droppedBy = droppedItems.get(item);

            if (droppedBy != null && droppedBy.getId() != player.getId()) {
                ItemStack stack = item.getItemStack();

                ILogDAO logDAO = ctx.getLogDAO();
                logDAO.insertGiveLog(droppedBy, player, stack);

                player.sendMessage(new TextComponent(ChatColor.YELLOW + "You got " + stack.getAmount() + " "
                        + stack.getType() + " from " + droppedBy.getName() + "."));

                if (droppedBy.isOnline()) {
                    droppedBy.sendMessage(new TextComponent(ChatColor.YELLOW + "You gave " + stack.getAmount()
                            + " " + stack.getType() + " to " + player.getName() + "."));
                }
            }
            droppedItems.remove(item);
        } catch (DAOException e) {
            throw new RuntimeException(e);
        }
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        GenericPlayer player = plugin.getPlayer(event.getPlayer());
        if (player == null) {
            Tregmine.LOGGER.info(event.getPlayer().getName() + " was not found " + "in players map when quitting.");
            return;
        }

        if (player.isCombatLogged()) {
            player.setHealth(0);
            Tregmine.LOGGER.info(event.getPlayer().getName() + " just combat logged... What a fool!");
        }

        player.saveInventory(player.getCurrentInventory());
        event.setQuitMessage(null);

        if (!player.isOp() && player.getQuitCause() != QuitCause.AFK) {
            if (player.getQuitMessage() != null) {
                plugin.broadcast(player.getChatName(),
                        new TextComponent(" quit: " + ChatColor.YELLOW + player.getQuitMessage()));
            } else {
                Random rand = new Random();
                int msgIndex = rand.nextInt(plugin.getQuitMessages().size());
                plugin.broadcast(new TextComponent(ChatColor.GRAY + "Quit: "), player.getChatName(),
                        new TextComponent(ChatColor.GRAY + " " + plugin.getQuitMessages().get(msgIndex)));
            }
        }

        // Look if there are any students being mentored by the exiting player
        if (player.getStudent() != null) {
            GenericPlayer student = player.getStudent();

            try (IContext ctx = plugin.createContext()) {
                IMentorLogDAO mentorLogDAO = ctx.getMentorLogDAO();
                int mentorLogId = mentorLogDAO.getMentorLogId(student, player);
                mentorLogDAO.updateMentorLogEvent(mentorLogId, IMentorLogDAO.MentoringEvent.CANCELLED);
            } catch (DAOException e) {
                throw new RuntimeException(e);
            }

            student.setMentor(null);
            player.setStudent(null);

            student.sendMessage(ChatColor.RED + "Your mentor left. We'll try "
                    + "to find a new one for you as quickly as possible.");

            MentorCommand.findMentor(plugin, student);
        } else if (player.getMentor() != null) {
            GenericPlayer mentor = player.getMentor();

            try (IContext ctx = plugin.createContext()) {
                IMentorLogDAO mentorLogDAO = ctx.getMentorLogDAO();
                int mentorLogId = mentorLogDAO.getMentorLogId(player, mentor);
                mentorLogDAO.updateMentorLogEvent(mentorLogId, IMentorLogDAO.MentoringEvent.CANCELLED);
            } catch (DAOException e) {
                throw new RuntimeException(e);
            }

            mentor.setStudent(null);
            player.setMentor(null);

            mentor.sendMessage(ChatColor.RED + "Your student left. :(");
        }

        plugin.removePlayer(player);
        Tregmine.LOGGER.info("Unloaded settings for " + player.getName() + ".");

        activateGuardians();
    }

    @EventHandler
    public void onPlayerRespawnSave(PlayerRespawnEvent event) {
        GenericPlayer p = plugin.getPlayer(event.getPlayer());
        p.saveInventory(p.getCurrentInventory());
    }

    @EventHandler
    public void onPreCommand(PlayerCommandPreprocessEvent event) {
        // Tregmine.LOGGER.info("COMMAND: " + event.getPlayer().getName() + "::"
        // + event.getMessage());
    }

    private static class RankComparator implements Comparator<GenericPlayer> {
        private int order;

        public RankComparator() {
            this.order = 1;
        }

        public RankComparator(boolean reverseOrder) {
            this.order = reverseOrder ? -1 : 1;
        }

        @Override
        public int compare(GenericPlayer a, GenericPlayer b) {
            return order * (a.getGuardianRank() - b.getGuardianRank());
        }
    }
}


text:
Rails.application.routes.draw do

  match '/404' => 'errors#status_404', :as => :status_404

  namespace :admin do
    resources :events
  end

  mount Alchemy::Engine => "/alchemy"

end


text:
	@class Motor6DBindersClient
]=]

local require = require(script.Parent.loader).load(script)

local BinderProvider = require("BinderProvider")
local Binder = require("Binder")

return BinderProvider.new(script.Name, function(self, serviceBag)
	self:Add(Binder.new("Motor6DStack", require("Motor6DStackClient"), serviceBag))
end)


text:
package org.apache.camel.component.restlet;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.rest.RestBindingMode;
import org.junit.Test;

/**
 * @version
 */
public class RestRestletBindingModeAutoWithJsonTest extends RestletTestSupport {

    @Test
    public void testBindingMode() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:input");
        mock.expectedMessageCount(1);
        mock.message(0).body().isInstanceOf(UserPojo.class);

        String body = "{\"id\": 123, \"name\": \"Donald Duck\"}";
        template.sendBody("http://localhost:" + portNum + "/users/new", body);

        assertMockEndpointsSatisfied();

        UserPojo user = mock.getReceivedExchanges().get(0).getIn().getBody(UserPojo.class);
        assertNotNull(user);
        assertEquals(123, user.getId());
        assertEquals("Donald Duck", user.getName());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                restConfiguration().component("restlet").host("localhost").port(portNum).bindingMode(RestBindingMode.auto);

                // use the rest DSL to define the rest services
                rest("/users/")
                    .post("new").consumes("application/json").type(UserPojo.class)
                        .to("mock:input");
            }
        };
    }
}


text:
<!--///////////////////////////////////////////////////////////////////////
//                                                                       //
//   iReader! (c) 2010 Samabox. All rights reserved.                     //
//                                                                       //
////////////////////////////////////////////////////////////////////////-->

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<script src="assets/scripts/utils.js" type="text/javascript"></script>
	<script src="assets/scripts/settings.js" type="text/javascript"></script>
	<script src="assets/scripts/main.js" type="text/javascript"></script>
</head>
<body onload="init()">

</body>
</html>


text:
LOCAL_DEVELOPMENT = true

module ActiveFile
  if LOCAL_DEVELOPMENT
    require 'active_file/adapter'
    require 'active_file/base'
  else
    require "active_support/dependencies/autoload"
    extend ActiveSupport::Autoload
    autoload :Base
    autoload :Adapter
  end
end


text:
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_CPU_IR_EMISSION_UTILS_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_CPU_IR_EMISSION_UTILS_H_

#include "llvm/IR/Value.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"

namespace xla {
namespace cpu {

bool PotentiallyImplementedAsEigenConvolution(
    const HloInstruction& convolution);

// Dynamic loop bounds are specified as an array of dimension index
// [start, limit) pairs of ir values (one for each partitioned outer dimension).
//
// EX: Let 'shape' = [8, 16, 32], with the loop bounds of the two-most major
//     dimensions dynamic. Then 'dynamic_loop_bounds' will contain the
//     following ir values for the two most-major dimensions:
//       [dim0_index_start_ir_value, dim0_index_limit_ir_value]
//       [dim1_index_start_ir_value, dim1_index_limit_ir_value]
//
// See IrFunction and ParallelLoopEmitter for details.
using DynamicLoopBounds = std::vector<std::pair<llvm::Value*, llvm::Value*>>;

}  // namespace cpu
}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_SERVICE_CPU_IR_EMISSION_UTILS_H_


text:
@implementation NSManagedObject (Query)

+(Query *)where:(NSDictionary *)attributes {
    Query *query = [[Query alloc] initWithPredicates:@[]];
    [query setEntityDescription:[[self class] description]];
    return [query where:attributes];
}

+(Query *)queryFor:(NSDictionary *)attributes {
    return [self where:attributes];
}
@end


text:
<?php

declare(strict_types=1);

namespace Tests\SitemapPlugin\Application;

use PSS\SymfonyMockerContainer\DependencyInjection\MockerContainer;
use Sylius\Bundle\CoreBundle\Application\Kernel as SyliusKernel;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
use Sylius\Calendar\SyliusCalendarBundle;

final class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    private const CONFIG_EXTS = '.{php,xml,yaml,yml}';

    public function getCacheDir(): string
    {
        return $this->getProjectDir() . '/var/cache/' . $this->environment;
    }

    public function getLogDir(): string
    {
        return $this->getProjectDir() . '/var/log';
    }

    public function registerBundles(): iterable
    {
        foreach ($this->getConfigurationDirectories() as $confDir) {
            $bundlesFile = $confDir . '/bundles.php';
            if (false === is_file($bundlesFile)) {
                continue;
            }
            yield from $this->registerBundlesFromFile($bundlesFile);

            if(class_exists(SyliusCalendarBundle::class)) {
                yield new SyliusCalendarBundle();
            }
        }
    }

    protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void
    {
        foreach ($this->getConfigurationDirectories() as $confDir) {
            $bundlesFile = $confDir . '/bundles.php';
            if (false === is_file($bundlesFile)) {
                continue;
            }
            $container->addResource(new FileResource($bundlesFile));
        }

        $container->setParameter('container.dumper.inline_class_loader', true);

        foreach ($this->getConfigurationDirectories() as $confDir) {
            $this->loadContainerConfiguration($loader, $confDir);
        }
    }

    protected function configureRoutes(RouteCollectionBuilder $routes): void
    {
        foreach ($this->getConfigurationDirectories() as $confDir) {
            $this->loadRoutesConfiguration($routes, $confDir);
        }
    }

    protected function getContainerBaseClass(): string
    {
        if ($this->isTestEnvironment() && class_exists(MockerContainer::class)) {
            return MockerContainer::class;
        }

        return parent::getContainerBaseClass();
    }

    private function isTestEnvironment(): bool
    {
        return 0 === strpos($this->getEnvironment(), 'test');
    }

    private function loadContainerConfiguration(LoaderInterface $loader, string $confDir): void
    {
        $loader->load($confDir . '/{packages}/*' . self::CONFIG_EXTS, 'glob');
        $loader->load($confDir . '/{packages}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, 'glob');
        $loader->load($confDir . '/{services}' . self::CONFIG_EXTS, 'glob');
        $loader->load($confDir . '/{services}_' . $this->environment . self::CONFIG_EXTS, 'glob');
    }

    private function loadRoutesConfiguration(RouteCollectionBuilder $routes, string $confDir): void
    {
        $routes->import($confDir . '/{routes}/*' . self::CONFIG_EXTS, '/', 'glob');
        $routes->import($confDir . '/{routes}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, '/', 'glob');
        $routes->import($confDir . '/{routes}' . self::CONFIG_EXTS, '/', 'glob');
    }

    /**
     * @return BundleInterface[]
     */
    private function registerBundlesFromFile(string $bundlesFile): iterable
    {
        $contents = require $bundlesFile;
        foreach ($contents as $class => $envs) {
            if (isset($envs['all']) || isset($envs[$this->environment])) {
                yield new $class();
            }
        }
    }

    /**
     * @return string[]
     */
    private function getConfigurationDirectories(): iterable
    {
        yield $this->getProjectDir() . '/config';
        $syliusConfigDir = $this->getProjectDir() . '/config/sylius/' . SyliusKernel::MAJOR_VERSION . '.' . SyliusKernel::MINOR_VERSION;
        if (is_dir($syliusConfigDir)) {
            yield $syliusConfigDir;
        }
        $symfonyConfigDir = $this->getProjectDir() . '/config/symfony/' . BaseKernel::MAJOR_VERSION . '.' . BaseKernel::MINOR_VERSION;
        if (is_dir($symfonyConfigDir)) {
            yield $symfonyConfigDir;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>ExcelManager (ExcelUtils)</title>
<meta name="date" content="2015-10-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

net.sf.excelutils.webwork

类 ExcelManager

java.lang.Object

net.sf.excelutils.webwork.ExcelManager

public class ExcelManager
extends java.lang.Object

从以下版本开始:

2005-10-10

版本:

$Revision: 126 $ $Date: 2006-09-17 16:32:41 +0800 (星期日, 17 九月 2006) $

作者:

jokeway

字段概要

字段

限定符和类型
字段和说明

protected ExcelLoader
excelLoader

构造器概要

构造器

构造器和说明

ExcelManager()

方法概要

方法

限定符和类型
方法和说明

java.lang.Object
buildContextObject(com.opensymphony.xwork.util.OgnlValueStack stack)

java.io.InputStream
getExcel(javax.servlet.ServletContext context,
        java.lang.String location)

protected ExcelLoader
getExcelLoader(javax.servlet.ServletContext context)

static ExcelManager
getInstance()

从类继承的方法 java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

字段详细资料

excelLoader

protected ExcelLoader excelLoader

构造器详细资料

ExcelManager

public ExcelManager()

方法详细资料

getInstance

public static final ExcelManager getInstance()

buildContextObject

public java.lang.Object buildContextObject(com.opensymphony.xwork.util.OgnlValueStack stack)

getExcelLoader

protected ExcelLoader getExcelLoader(javax.servlet.ServletContext context)

getExcel

public java.io.InputStream getExcel(javax.servlet.ServletContext context,
                           java.lang.String location)

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

Copyright (C) 2003-2006 The ExcelUtils Project.


text:
package org.wso2.carbon.cassandra.mgt.datasource.hector;

public class HectorDataSource {

    private HectorDataSourceConfiguration config;

    public HectorDataSource(HectorDataSourceConfiguration config) {
        this.config = config;
    }

}


text:
package org.radargun.reporting.html;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.radargun.config.Cluster;
import org.radargun.reporting.Timeline;
import org.radargun.reporting.html.HtmlReporter;
import org.radargun.reporting.html.TimelineDocument;
import org.radargun.utils.TimeService;
import org.testng.annotations.Test;

/**
 * Writes a basic {@link TimelineDocument} with few charts.
 *
 * @author Radim Vansa <rvansa@redhat.com>
 */
public class TimelineChartsTest {

   @Test
   public void test() {
      long now = TimeService.currentTimeMillis();
      Timeline t0 = new Timeline(0);
      Timeline t1 = new Timeline(1);
      t0.addValue(Timeline.Category.sysCategory("Category A"), new Timeline.Value(now + 1000, 10));
      t0.addValue(Timeline.Category.sysCategory("Category A"), new Timeline.Value(now + 2000, 5));
      t0.addValue(Timeline.Category.sysCategory("Category A"), new Timeline.Value(now + 3000, 8));
      t0.addValue(Timeline.Category.sysCategory("Category A"), new Timeline.Value(now + 4000, 12));

      t1.addValue(Timeline.Category.sysCategory("Category A"), new Timeline.Value(now + 1000, 13));
      t1.addValue(Timeline.Category.sysCategory("Category A"), new Timeline.Value(now + 2000, 15));
      t1.addValue(Timeline.Category.sysCategory("Category A"), new Timeline.Value(now + 4000, 5));

      t0.addEvent("Category B", new Timeline.TextEvent(now + 800, "Started"));
      t0.addEvent("Category B", new Timeline.IntervalEvent(now + 1500, "Stage one", 1000));
      t0.addEvent("Category B", new Timeline.IntervalEvent(now + 2600, "Stage two", 1500));

      t1.addEvent("Category B", new Timeline.TextEvent(now + 900, "Started"));
      t1.addEvent("Category B", new Timeline.IntervalEvent(now + 1400, "Stage one", 1100));
      t1.addEvent("Category B", new Timeline.IntervalEvent(now + 2700, "Stage two", 1600));

      t0.addValue(Timeline.Category.sysCategory("Category C"), new Timeline.Value(now + 1000, 600));
      t0.addValue(Timeline.Category.sysCategory("Category C"), new Timeline.Value(now + 2500, 800));
      t0.addValue(Timeline.Category.sysCategory("Category C"), new Timeline.Value(now + 3100, 2000));
      t0.addValue(Timeline.Category.sysCategory("Category C"), new Timeline.Value(now + 4000, 1200));

      t1.addValue(Timeline.Category.sysCategory("Category C"), new Timeline.Value(now + 1200, 513));
      t1.addValue(Timeline.Category.sysCategory("Category C"), new Timeline.Value(now + 2100, 912));
      t1.addValue(Timeline.Category.sysCategory("Category C"), new Timeline.Value(now + 3800, 485));

      Cluster cluster = new Cluster();
      cluster.addGroup("default", 2);
      TimelineDocument timelineDocument = new TimelineDocument(new TimelineDocument.Configuration(), "test", "testconfig", "Test Config", Arrays.asList(t0, t1), Timeline.Category.Type.SYSMONITOR, cluster);

      timelineDocument.createReportDirectory();
      timelineDocument.createTestCharts();

      Map root = new HashMap();
      root.put("timelineDocument", timelineDocument);

      HtmlReporter.processTemplate(root, timelineDocument.getDirectory(), timelineDocument.getFileName(), "timelineReport.ftl");
   }
}


text:
namespace blink {

void V8TestInterfaceEventInit::toImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, TestInterfaceEventInit& impl, ExceptionState& exceptionState)
{
    if (isUndefinedOrNull(v8Value))
        return;
    if (!v8Value->IsObject()) {
        exceptionState.throwTypeError("cannot convert to dictionary.");
        return;
    }

    V8EventInitDictionary::toImpl(isolate, v8Value, impl, exceptionState);
    if (exceptionState.hadException())
        return;

    v8::Local<v8::Object> v8Object = v8Value->ToObject(isolate);
    v8::TryCatch block;
    v8::Local<v8::Value> stringMemberValue = v8Object->Get(v8String(isolate, "stringMember"));
    if (block.HasCaught()) {
        exceptionState.rethrowV8Exception(block.Exception());
        return;
    }
    if (stringMemberValue.IsEmpty() || stringMemberValue->IsUndefined()) {
        // Do nothing.
    } else {
        TOSTRING_VOID(V8StringResource<>, stringMember, stringMemberValue);
        impl.setStringMember(stringMember);
    }

}

v8::Local<v8::Value> toV8(const TestInterfaceEventInit& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate)
{
    v8::Local<v8::Object> v8Object = v8::Object::New(isolate);
    toV8EventInitDictionary(impl, v8Object, creationContext, isolate);
    toV8TestInterfaceEventInit(impl, v8Object, creationContext, isolate);
    return v8Object;
}

void toV8TestInterfaceEventInit(const TestInterfaceEventInit& impl, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate* isolate)
{
    if (impl.hasStringMember()) {
        dictionary->Set(v8String(isolate, "stringMember"), v8String(isolate, impl.stringMember()));
    }

}

TestInterfaceEventInit NativeValueTraits<TestInterfaceEventInit>::nativeValue(const v8::Local<v8::Value>& value, v8::Isolate* isolate, ExceptionState& exceptionState)
{
    TestInterfaceEventInit impl;
    V8TestInterfaceEventInit::toImpl(isolate, value, impl, exceptionState);
    return impl;
}

} // namespace blink


text:
define(function (require) {
    'use strict';

    var modal = require('../plugin/modal');
    var $ = require('jquery');

    var tmplModal = document.querySelector('#modal-example');
    var nodeModal = tmplModal.content.firstElementChild.cloneNode(true);

    var modalExample = modal(nodeModal);

    modalExample.on('open', function (e) {
        if (Math.round(Math.random())) {
            e.preventDefault();
            alert('Prevent you open the modal!!');
        }
    }).on('opened', function (e) {
        alert('Modal opened!!');
    }).on('close', function (e) {
        if (Math.round(Math.random())) {
            e.preventDefault();
            alert('Prevent you close the modal!!');
        }
    }).on('closed', function (e) {
        alert('Modal closed!!');
    });

    $('#btn-open').on('click', function (e) {
        e.preventDefault();
        modalExample.open();
    });

    $('#btn-destroy').on('click', function (e) {
        e.preventDefault();
        modalExample.destroy();
    });
});


text:
layout: default
title: Pyramid Blogtool
slug: getting-started
lead: "An overview of the new diazo theme for the meetshaus blogging deployment"
base_url: "../"
---

Meetshaus Blogtool

            This is the new default meetshaus blog theme

Blog listing Demo

Next we will define a custom blog listing to rebuild the already
        usable plone addon version of this blog


text:
Comments can be associated with runs using the `comment` command.

We use the `simple` sample project.

    >>> project = Project(sample("projects", "simple"))

## Specify comment for a run

We can specify a comment when running an operation.

    >>> simple_run, _ = project.run_capture("simple", comment="This is a simple op.")

The comment is included in the run `comments` attribute.

    >>> pprint(simple_run.get("comments"))
    [{'body': 'This is a simple op.',
      'host': '...',
      'time': ...,
      'user': '...'}]

Time is recorded as an epochs timestamp.

    >>> type(simple_run.get("comments")[0]["time"]).__name__
    'int'

## Comments in runs list

The `-c, --comments` option is used to inlude comments in the runs
list.

    >>> run("guild -H '%s' runs -c" % project.guild_home)
    [1:...]  simple (samples/projects/simple)  ...  completed  x=1.0
      ...@... ...-...-... ...:...:...
    <BLANKLINE>
        This is a simple op.
    <exit 0>

## Comments in runs info

The `-c, --comments` option is used to include comments in the runs
into output.

    >>> run("guild -H '%s' runs info --comments" % project.guild_home)
    id: ...
    operation: simple
    ...
    comments:
      -
        body: This is a simple op.
        host: ...
        time: ...-...-... ...:...:...
        user:...
    <exit 0>

## Filtering comments

Runs can be selected using comment filters.

    >>> project.list_runs(comments=["a simple op"])
    [<guild.run.Run '...'>]

    >>> project.list_runs(comments=["not a simple op"])
    []

    >>> project.list_runs(comments=["not simple", "simple"])
    [<guild.run.Run '...'>]

    >>> run("guild -H '%s' runs -Fc 'a simple op'" % project.guild_home)
    [1:...]  simple (samples/projects/simple)  ...  completed  x=1.0
    <exit 0>

    >>> run("guild -H '%s' runs -Fc 'not a simple op'" % project.guild_home)
    <exit 0>

    >>> run("guild -H '%s' cat --output -Fc 'simple op'" % project.guild_home)
    x: 1.0
    y: 2.0
    <exit 0>

    >>> run("guild -H '%s' cat --output -Fc 'complicated'" % project.guild_home)
    guild: no matching runs
    <exit 1>

## Batch and trial comments

Batch comments are specified using the `-bc` option, which is
available for the project API via the `batch_comment` keyword arg.

    >>> project.run("simple",
    ...     flags={"x": [2.0, 3.0]},
    ...     comment="a trial comment",
    ...     batch_comment="my cool batch",
    ...     keep_batch=True)
    INFO: [guild] Running trial ...: simple (x=2.0)
    x: 2.0
    y: 3.0
    INFO: [guild] Running trial ...: simple (x=3.0)
    x: 3.0
    y: 4.0

Show comments for the lasts three runs (two trials and one batch).

    >>> run("guild -H '%s' comment -l 1:3" % project.guild_home)
    ???  simple (samples/projects/simple)   ...  completed  x=3.0
    [1] ...
    <BLANKLINE>
      a trial comment
    <BLANKLINE>
    ...  simple (samples/projects/simple)   ...  completed  x=2.0
    [1] ...
    <BLANKLINE>
      a trial comment
    <BLANKLINE>
    ...  simple+ (samples/projects/simple)  ...  completed
    [1] ...
    <BLANKLINE>
      my cool batch
    <exit 0>

## Add comments

Add a comment using the `comment` command with the `-a` option.

    >>> run("guild -H '%s' comment -a 'a second comment' -y" % project.guild_home)
    Added comment to 1 run(s)
    <exit 0>

    >>> run("guild -H '%s' comment --list" % project.guild_home)
    ???  simple (samples/projects/simple)  ...  completed  x=3.0
    [1] ...
    <BLANKLINE>
      a trial comment
    <BLANKLINE>
    [2] ...
    <BLANKLINE>
      a second comment
    <exit 0>

Delete a comment using the `-d` option with the applicable comment index.

    >>> run("guild -H '%s' comment 1 -d 1 -y" % project.guild_home)
    Deleted comment for 1 run(s)
    <exit 0>

    >>> run("guild -H '%s' comment --list" % project.guild_home)
    ???  simple (samples/projects/simple)  ...  completed  x=3.0
    [1] ...
    <BLANKLINE>
      a second comment
    <exit 0>

Clear comments using the `-c` option.

    >>> run("guild -H '%s' comment -c -y" % project.guild_home)
    Deleted all comments for 1 run(s)
    <exit 0>

    >>> run("guild -H '%s' comment --list" % project.guild_home)
    ???  simple (samples/projects/simple)  ...  completed  x=3.0
      <no comments>
    <exit 0>

When adding a comment, `-u` is used to set the user.

    >>> run("guild -H '%s' comment --add 'comment with user' -u harold -y" % project.guild_home)
    Added comment to 1 run(s)
    <exit 0>

A user can include a host in the form `USER@HOST`.

    >>> run("guild -H '%s' comment --add 'comment with user' -u maude@place -y" % project.guild_home)
    Added comment to 1 run(s)
    <exit 0>

    >>> run("guild -H '%s' runs --comments -n1" % project.guild_home)
    [1:...]  simple (samples/projects/simple)   ...  completed  x=3.0
      harold@... ...-...-... ...:...:...
    <BLANKLINE>
        comment with user
    <BLANKLINE>
      maude@place ...-...-... ...:...:...
    <BLANKLINE>
        comment with user
    <BLANKLINE>
    <exit 0>

## Comments run attribute

Comments are saved in the `comments` run attr as YAML formatted plain text.

    >>> run("guild -H '%s' cat -p .guild/attrs/comments" % project.guild_home)
    - body: comment with user
      host: ...
      time: ...
      user: harold
    - body: comment with user
      host: place
      time: ...
      user: maude
    <exit 0>

## Misc

When a batch comment is provided for a non-batch operation, Guild
shows a warning message.

    >>> run("guild -H '%s' run --batch-comment xxx simple -y"
    ...     % project.guild_home, cwd=project.cwd)
    WARNING: operation is not a batch - ignoring batch comment
    x: 1.0
    y: 2.0
    <exit 0>


text:
#ifndef AMBROLIB_STM32F4_WATCHDOG_H
#define AMBROLIB_STM32F4_WATCHDOG_H

#include <stdint.h>

#include <aprinter/meta/ServiceUtils.h>
#include <aprinter/base/Preprocessor.h>
#include <aprinter/base/Object.h>
#include <aprinter/base/DebugObject.h>
#include <aprinter/base/Hints.h>

namespace APrinter {

template <typename Arg>
class Stm32f4Watchdog {
    APRINTER_USE_TYPES1(Arg, (Context, ParentObject, Params))

    static uint32_t const PrescalerValue =
        Params::Divider == 4 ? IWDG_PRESCALER_4 :
        Params::Divider == 8 ? IWDG_PRESCALER_8 :
        Params::Divider == 16 ? IWDG_PRESCALER_16 :
        Params::Divider == 32 ? IWDG_PRESCALER_32 :
        Params::Divider == 64 ? IWDG_PRESCALER_64 :
        Params::Divider == 128 ? IWDG_PRESCALER_128 :
        Params::Divider == 256 ? IWDG_PRESCALER_256 :
        UINT32_MAX;
    static_assert(PrescalerValue != UINT32_MAX, "Invalid watchdog Divider value");
    static_assert(Params::Reload <= 0xFFF, "Invalid watchdog Reload value");

public:
    struct Object;

private:
    using TheDebugObject = DebugObject<Context, Object>;

public:
    static constexpr double WatchdogTime = Params::Reload / ((double)LSI_VALUE / Params::Divider);

    static void init (Context c)
    {
        auto *o = Object::self(c);
        TheDebugObject::init(c);

        o->iwdg_handle.Instance = IWDG;
        o->iwdg_handle.Init.Prescaler = PrescalerValue;
        o->iwdg_handle.Init.Reload = Params::Reload;

        HAL_IWDG_Init(&o->iwdg_handle);
    }

    static void deinit (Context c)
    {
        TheDebugObject::deinit(c);
    }

    template <typename ThisContext>
    static void reset (ThisContext c)
    {
        auto *o = Object::self(c);
        TheDebugObject::access(c);

        HAL_IWDG_Refresh(&o->iwdg_handle);
    }

    APRINTER_NO_RETURN
    static void emergency_abort ()
    {
        while (true);
    }

public:
    struct Object : public ObjBase<Stm32f4Watchdog, ParentObject, MakeTypeList<TheDebugObject>> {
        IWDG_HandleTypeDef iwdg_handle;
    };
};

APRINTER_ALIAS_STRUCT_EXT(Stm32f4WatchdogService, (
    APRINTER_AS_VALUE(int, Divider),
    APRINTER_AS_VALUE(uint16_t, Reload)
), (
    APRINTER_ALIAS_STRUCT_EXT(Watchdog, (
        APRINTER_AS_TYPE(Context),
        APRINTER_AS_TYPE(ParentObject),
        APRINTER_AS_VALUE(bool, DebugMode)
    ), (
        using Params = Stm32f4WatchdogService;
        APRINTER_DEF_INSTANCE(Watchdog, Stm32f4Watchdog)
    ))
))

}

#endif


text:
using namespace qglviewer;

enum ColorType
  {
    _FixedColor = 0,
    _LutColor,
    _NormalColor,
    _PositionColor,
    _OcclusionColor,
    _VRLutColor
  };

class MeshGenerator
{
 public :
  MeshGenerator();
  ~MeshGenerator();

  QList<char *> plyStrings;

  QString start(VolumeFileManager*,
		int, int, int,
		Vec, Vec,
		QString,
		Vec, int,
		QList<Vec>,
		QList<Vec>,
		QList<CropObject>,
		QList<PathObject>,
		uchar*,
		int, int, int, int,
		QVector<uchar>,
		QVector<uchar>,
		bool);

 private :
  QTextEdit *m_meshLog;
  QProgressBar *m_meshProgress;

  VolumeFileManager *m_vfm;
  int m_voxelType;
  int m_nX, m_nY, m_nZ;
  int m_depth, m_width, m_height;
  Vec m_dataMin, m_dataMax, m_dataSize;
  int m_samplingLevel;

  bool m_blendPresent;
  bool m_tearPresent;
  bool m_cropPresent;
  bool m_pathBlendPresent;
  bool m_pathCropPresent;
  QList<CropObject> m_crops;
  QList<PathObject> m_paths;

  int m_pruneX, m_pruneY, m_pruneZ;
  float m_pruneLod;
  QVector<uchar> m_pruneData;

  bool m_useTagColors;
  QVector<uchar> m_tagColors;

  float m_scaleModel;

  bool m_batchMode;

  void generateMesh(int, int,
		    QString,
		    int, int,
		    QGradientStops,
		    int, int,
		    bool,
		    Vec,
		    QList<Vec>,
		    QList<Vec>,
		    QList<CropObject>,
		    QList<PathObject>,
		    bool, bool, uchar*,
		    int, bool);

  void saveMeshToPLY(QString, int, int, int, bool);
  void saveMeshToSTL(QString, int, int, int, bool);

  bool getValues(int&, float&,
		 int&, int&, int&, int&,
		 bool&, bool&, bool&,
		 QGradientStops&,
		 bool, int&, bool&);

  QColor getLutColor(uchar*,
		     int*,
		     int, int, int, int,
		     uchar,
		     QVector3D,
		     QVector3D,
		     uchar*,
		     QVector3D,
		     bool);

  QGradientStops resampleGradientStops(QGradientStops);

  void smoothData(uchar*, int, int, int, int);

  void applyTear(int, int, int,
		 uchar*, uchar*, bool);

  bool checkPathCrop(Vec);
  bool checkPathBlend(Vec, ushort, uchar*);
  bool checkCrop(Vec);
  bool checkBlend(Vec, ushort, uchar*);
  void applyOpacity(int, uchar*, uchar*, uchar*,
		    uchar*, uchar*, uchar*);

  void smoothMesh(QList<Vec>&,
		  QList<Vec>&,
		  QList<Vec>&,
		  int);

};

#endif MESHGENERATOR_H


text:
class StartsWithPrimitive2 {

  String foo(String str) {
    return 'L' + str + '<caret>;';
  }
}