text:
#include "TestingJS.h"

#include "chronotext/Context.h"

using namespace std;
using namespace ci;
using namespace chr;

using namespace jsp;

void TestingJS::performRun(bool force)
{
    if (force || false)
    {
        dumpObject(globalHandle());
    }

    if (force || false)
    {
        executeScript(InputSource::getAsset("helpers.js"));
        executeScript(InputSource::getAsset("test.js"));

        call(globalHandle(), "start");
        LOGI << writeDetailed(get<OBJECT>(globalHandle(), "foo")) << endl;

        executeScript("print(1, 'אריאל מלכא', {x: 5, y: null})");
        executeScript("error tester", __FILE__, __LINE__);
    }

    // ---

    if (force || true)
    {
        JSP_TEST(force || true, testParsing1)
        JSP_TEST(force || true, testParsing2)
        JSP_TEST(force || true, testStringify)
        JSP_TEST(force || true, testToSource)
    }

    if (force || false)
    {
        testThreadSafety();
    }

    if (force || false)
    {
        testEvaluationScope();
        testFunctionScope();
    }

    if (force || false)
    {
        testCustomScriptExecution();
    }

    if (force || false)
    {
        testShapes1();
        testShapes2();
        testAtoms();
        testReservedSlots();
        testJSID();
    }

    if (force || true)
    {
        JSP_TEST(force || true, testGetter1)
        JSP_TEST(force || true, testSetter1)
        JSP_TEST(force || true, testGetterSetter1)
    }

    if (force || true)
    {
        JSP_TEST(force || true, testCustomConstruction1)
        JSP_TEST(force || true, testCustomConstruction2)
        JSP_TEST(force || true, testNewObject)
    }

    if (force || true)
    {
        JSP_TEST(force || true, testReadOnlyProperty1)
        JSP_TEST(force || true, testReadOnlyProperty2)

        JSP_TEST(force || true, testPermanentProperty1)
        JSP_TEST(force || true, testPermanentProperty2)

        JSP_TEST(force || true, testObjectReset1)
        JSP_TEST(force || true, testObjectReset2)
    }

    if (force || true)
    {
        JSP_TEST(force || true, testGetProperty1)
        JSP_TEST(force || true, testGetElement1)

        JSP_TEST(force || true, testGetProperties1)
        JSP_TEST(force || true, testGetProperties2)
        JSP_TEST(force || true, testGetElements1)
        JSP_TEST(force || true, testToValue1)
        JSP_TEST(force || true, testToValue2)
        JSP_TEST(force || true, testSetElements1)
        JSP_TEST(force || true, testSetElements2)
    }

    if (force || true)
    {
        JSP_TEST(force || true, testBulkArrayOperations1)
        JSP_TEST(force || true, testBulkArrayOperations2)

        JSP_TEST(force || true, testBulkArrayOperations3)
        JSP_TEST(force || true, testBulkArrayOperations4)
    }

    if (force || true)
    {
        JSP_TEST(force || true, testArrayElementCount)
    }
}

#pragma mark ---------------------------------------- ARRAYS ----------------------------------------

/*
 * DEMONSTRATED:
 *
 * - HOW TO OBTAIN THE "TRUE" ELEMENT-COUNT OF A JS-ARRAY
 * - HOW TO WORK WITH ForOfIterator
 */
void TestingJS::testArrayElementCount()
{
    RootedObject array(cx, newArray());

    set(array, 0, -255);
    set(array, 1, true);
    set(array, 2, nullptr);
    set(array, 3, "foo");

    deleteElement(array, 1);

    /*
     * Array.length IS NOT REFLECTING THE "TRUE" ELEMENT-COUNT
     */
    JSP_CHECK(getLength(array) == 4);

    // ---

    uint32_t elementCount = 0;

    RootedValue iterable(cx, ObjectOrNullValue(array));
    ForOfIterator it(cx);

    if (it.init(iterable))
    {
        bool done = false;
        RootedValue value(cx);

        while (it.next(&value, &done) && !done)
        {
            if (!value.isUndefined())
            {
                elementCount++;
            }
        }
    }

    JSP_CHECK(elementCount == 3);
}

#pragma mark ---------------------------------------- GETTING / SETTING PROPERTIES AND ELEMENTS ----------------------------------------

/*
 * TESTING THE BEHAVIOR OF JS_GetProperty FOR NON-DEFINED PROPERTIES:
 *
 * - IT "RETURNS" A VALUE OF TYPE "UNDEFINED"
 * - IT'S POSSIBLE TO CHECK THE TYPE OF THE RETURNED VALUE
 */
void TestingJS::testGetProperty1()
{
    RootedObject object(cx, newPlainObject());
    RootedValue result(cx);

    if (JS_GetProperty(cx, object, "notDefined", &result))
    {
        JSP_CHECK(result.isUndefined());

        JSP_CHECK(!result.isNull());
        JSP_CHECK(!result.isObject());
        JSP_CHECK(!result.isNumber());
        JSP_CHECK(!result.isInt32());
        JSP_CHECK(!result.isString());
    }
    else
    {
        JSP_CHECK(false);
    }
}

/*
 * TESTING THE BEHAVIOR OF JS_GetElement FOR NON-DEFINED ELEMENTS: SIMILAR TO JS_GetProperty
 */
void TestingJS::testGetElement1()
{
    RootedObject array(cx, newArray());
    RootedValue result(cx);

    if (JS_GetElement(cx, array, 999, &result))
    {
        JSP_CHECK(result.isUndefined());

        JSP_CHECK(!result.isNull());
        JSP_CHECK(!result.isObject());
        JSP_CHECK(!result.isNumber());
        JSP_CHECK(!result.isInt32());
        JSP_CHECK(!result.isString());
    }
    else
    {
        JSP_CHECK(false);
    }
}

// ---

void TestingJS::testGetProperties1()
{
    RootedObject object(cx, evaluateObject("({x: 25.5, area: 33.33, balance: -255, count: 0xff123456, alive: true, parent: null, child: {}, name: 'foo', xxx: undefined})"));

    JSP_CHECK(get<FLOAT32>(object, "x") == 25.5f);
    JSP_CHECK(get<FLOAT64>(object, "area") == 33.33);
    JSP_CHECK(get<INT32>(object, "balance") == -255);
    JSP_CHECK(get<UINT32>(object, "count") == 0xff123456);
    JSP_CHECK(get<BOOLEAN>(object, "alive") == true);
    JSP_CHECK(get<OBJECT>(object, "parent") == nullptr);
    JSP_CHECK(get<OBJECT>(object, "child")->getClass() == &JSObject::class_);
    JSP_CHECK(get<STRING>(object, "name") == "foo");

    /*
     * DEFAULT VALUES
     */
    JSP_CHECK(get<FLOAT32>(object, "notDefined") == 0);
    JSP_CHECK(get<FLOAT64>(object, "notDefined") == 0);
    JSP_CHECK(get<INT32>(object, "notDefined") == 0);
    JSP_CHECK(get<UINT32>(object, "notDefined") == 0);
    JSP_CHECK(get<BOOLEAN>(object, "notDefined") == false);
    JSP_CHECK(get<OBJECT>(object, "notDefined") == nullptr);
    JSP_CHECK(get<STRING>(object, "notDefined") == "");

    JSP_CHECK(get<INT32>(object, "xxx", -333) == -333); // CUSTOM DEFAULT VALUE
}

void TestingJS::testGetProperties2()
{
    RootedObject object(cx, evaluateObject("({bah: {}, whatever: 'bar', doh: 'baz'})"));

    RootedObject o(cx, get<OBJECT>(object, "bah"));
    testProperties(object, {"bah", "whatever", "doh"}, o, "bar", "baz");
}

void TestingJS::testProperties(HandleObject object, const vector<string> &properties, HandleObject o, const string &s1, const char *s2)
{
    JSP_CHECK(get<OBJECT>(object, properties[0].data()) == o);
    JSP_CHECK(get<OBJECT>(object, "notDefined") != o);

    JSP_CHECK(get<STRING>(object, properties[1].data()) == s1);
    JSP_CHECK(get<STRING>(object, "notDefined") != s1);

    JSP_CHECK(get<STRING>(object, properties[2].data()) == s2);
    JSP_CHECK(get<STRING>(object, "notDefined") != s2);
}

// ---

void TestingJS::testGetElements1()
{
    RootedObject array(cx, evaluateObject("([25.5, 33.33, -255, 0xff123456, true, null, {}, 'foo', , {}, 'bar', 'baz'])"));
    int index = 0;

    JSP_CHECK(get<FLOAT32>(array, index++) == 25.5f);
    JSP_CHECK(get<FLOAT64>(array, index++) == 33.33);
    JSP_CHECK(get<INT32>(array, index++) == -255);
    JSP_CHECK(get<UINT32>(array, index++) == 0xff123456);
    JSP_CHECK(get<BOOLEAN>(array, index++) == true);
    JSP_CHECK(get<OBJECT>(array, index++) == nullptr);
    JSP_CHECK(get<OBJECT>(array, index++)->getClass() == &JSObject::class_);
    JSP_CHECK(get<STRING>(array, index++) == "foo");

    /*
     * DEFAULT VALUES
     */
    JSP_CHECK(get<FLOAT32>(array, 999) == 0);
    JSP_CHECK(get<FLOAT64>(array, 999) == 0);
    JSP_CHECK(get<INT32>(array, 999) == 0);
    JSP_CHECK(get<UINT32>(array, 999) == 0);
    JSP_CHECK(get<BOOLEAN>(array, 999) == false);
    JSP_CHECK(get<OBJECT>(array, 999) == nullptr);
    JSP_CHECK(get<STRING>(array, 999) == "");

    JSP_CHECK(get<INT32>(array, index++, -333) == -333); // CUSTOM DEFAULT VALUE

    // ---

    RootedObject o(cx, get<OBJECT>(array, index));
    JSP_CHECK(get<OBJECT>(array, index++) == o);
    JSP_CHECK(get<OBJECT>(array, 999) != o);

    string s1 = "bar";
    JSP_CHECK(get<STRING>(array, index++) == s1);
    JSP_CHECK(get<STRING>(array, 999) != s1);

    const char *s2 = "baz";
    JSP_CHECK(get<STRING>(array, index++) == s2);
    JSP_CHECK(get<STRING>(array, 999) != s2);
}

// ---

void TestingJS::testToValue1()
{
    RootedObject array(cx, newArray());
    int index = 0;

    /*
     * TODO: toValue(void) COULD PRODUCE AN UNDEFINED VALUE
     */

    RootedValue f(cx, toValue(25.5f));
    JS_SetElement(cx, array, index++, f);

    RootedValue d(cx, toValue(33.33));
    JS_SetElement(cx, array, index++, d);

    RootedValue i(cx, toValue(-255));
    JS_SetElement(cx, array, index++, i);

    RootedValue ui(cx, toValue(0xff123456));
    JS_SetElement(cx, array, index++, ui);

    RootedValue b(cx, toValue(true));
    JS_SetElement(cx, array, index++, b);

    RootedValue n(cx, toValue(nullptr));
    JS_SetElement(cx, array, index++, n);

    RootedValue o(cx, toValue(newPlainObject()));
    JS_SetElement(cx, array, index++, o);

    RootedValue s(cx, toValue("foo"));
    JS_SetElement(cx, array, index++, s);

    JSP_CHECK(toSource(array) == "[25.5, 33.33, -255, 4279383126, true, null, {}, \"foo\"]");
}

void TestingJS::testToValue2()
{
    RootedObject array(cx, newArray());

    RootedObject o(cx, newPlainObject());
    setValues1(array, {0, 1, 2}, o, "bar", "baz");

    JSP_CHECK(toSource(array) == "[{}, \"bar\", \"baz\"]");
}

void TestingJS::setValues1(HandleObject array, const vector<int> &indices, HandleObject o, const string &s1, const char *s2)
{
    RootedValue rooted(cx);
    int index = 0;

    rooted = toValue(o);
    JS_SetElement(cx, array, indices[index++], rooted);

    rooted = toValue(s1);
    JS_SetElement(cx, array, indices[index++], rooted);

    rooted = toValue(s2);
    JS_SetElement(cx, array, indices[index++], rooted);
}

// ---

void TestingJS::testSetElements1()
{
    RootedObject array(cx, newArray());
    int index = 0;

    /*
     * TODO: set(array, index, void) COULD SET AN UNDEFINED VALUE
     */

    set(array, index++, 25.5f);
    set(array, index++, 33.33);
    set(array, index++, -255);
    set(array, index++, 0xff123456);
    set(array, index++, true);
    set(array, index++, nullptr);
    set(array, index++, newPlainObject());
    set(array, index++, "foo");

    JSP_CHECK(toSource(array) == "[25.5, 33.33, -255, 4279383126, true, null, {}, \"foo\"]");
}

void TestingJS::testSetElements2()
{
    RootedObject array(cx, newArray());

    RootedObject o(cx, newPlainObject());
    setValues2(array, {0, 1, 2}, o, "bar", "baz");

    JSP_CHECK(toSource(array) == "[{}, \"bar\", \"baz\"]");
}

void TestingJS::setValues2(HandleObject array, const vector<int> &indices, HandleObject o, const string &s1, const char *s2)
{
    RootedValue rooted(cx);
    int index = 0;

    set(array, indices[index++], o);
    set(array, indices[index++], s1);
    set(array, indices[index++], s2);
}

// ---

void TestingJS::testBulkArrayOperations1()
{
    {
        RootedObject array(cx, evaluateObject("([1.33, , 3.33])"));

        auto elements = getElements<FLOAT64>(array);
        JSP_CHECK(write(elements) == "[1.33, 0, 3.33]");
    }

    {
        RootedObject array(cx, evaluateObject("([-4096, , 8192])"));

        auto elements = getElements<INT32>(array, 555); // USING A CUSTOM DEFAULT-VALUE
        JSP_CHECK(write(elements) == "[-4096, 555, 8192]");
    }

    {
        RootedObject array(cx, evaluateObject("([0xff123456, , 8192])"));

        auto elements = getElements<UINT32>(array);
        JSP_CHECK(write(elements) == "[4279383126, 0, 8192]");
    }

    {
        RootedObject array(cx, evaluateObject("([true, , false])"));

        auto elements = getElements<BOOLEAN>(array);
        JSP_CHECK(write(elements) == "[1, 0, 0]");
    }

    {
        /*
         * USAGE OF Proto::getElements<OBJECT>(HandleObject sourceArray) IS DISCOURAGED:
         * - NOT GC-SAFE IN TERM OF OUTPUT-VALUES
         *
         * RECOMMENDED ALTERNATIVE:
         * - Proto::getElements(HandleObject sourceArray, AutoValueVector &elements)
         */

        RootedObject array(cx, evaluateObject("([{}, , []])"));
        auto elements = getElements<OBJECT>(array);

        setLength(array, 0);
        appendElements(array, elements);
        JSP_CHECK(toSource(array) == "[{}, null, []]");
    }

    {
        RootedObject array(cx, evaluateObject("(['one', , 'three'])"));

        auto elements = getElements<STRING>(array, "INVALID"); // USING A CUSTOM DEFAULT-VALUE
        JSP_CHECK(write(elements) == "[one, INVALID, three]");
    }

    // ---

    {
        RootedObject array(cx, newArray());
        JSP_CHECK(getElements<UINT32>(array).empty());
    }

    JSP_CHECK(getElements<UINT32>(NullPtr()).empty());
}

void TestingJS::testBulkArrayOperations2()
{
    {
        RootedObject array(cx, newArray());

        JSP_CHECK(appendElements(array, vector<FLOAT32> {1.5f, 2.5f, 3.5f}) == 3);
        JSP_CHECK(toSource(array) == "[1.5, 2.5, 3.5]");
    }

    {
        RootedObject array(cx, newArray());

        JSP_CHECK(appendElements(array, vector<FLOAT64> {1.33, 2.33, 3.33}) == 3);
        JSP_CHECK(toSource(array) == "[1.33, 2.33, 3.33]");
    }

    {
        RootedObject array(cx, newArray());

        JSP_CHECK(appendElements(array, vector<INT32> {-4096, 256, 8192}) == 3);
        JSP_CHECK(toSource(array) == "[-4096, 256, 8192]");
    }

    {
        RootedObject array(cx, newArray());

        JSP_CHECK(appendElements(array, vector<UINT32> {0xff123456, 256, 8192}) == 3);
        JSP_CHECK(toSource(array) == "[4279383126, 256, 8192]");
    }

    {
        RootedObject array(cx, newArray());

        JSP_CHECK(appendElements(array, vector<BOOLEAN> {true, false, false}) == 3);
        JSP_CHECK(toSource(array) == "[true, false, false]");
    }

    {
        /*
         * USAGE OF Proto::appendElements<OBJECT>(HandleObject targetArray, const vector<OBJECT> &elements) IS DISCOURAGED:
         * - NOT GC-SAFE IN TERM OF INPUT-VALUES
         *
         * RECOMMENDED ALTERNATIVE:
         * - Proto::appendElements(HandleObject targetArray, const HandleValueArray &elements)
         */

        RootedObject array(cx, newArray());

        JSP_CHECK(appendElements(array, vector<OBJECT> {newPlainObject(), nullptr, newArray()}) == 3);
        JSP_CHECK(toSource(array) == "[{}, null, []]");
    }

    {
        RootedObject array(cx, newArray());

        JSP_CHECK(appendElements(array, vector<STRING> {"one", "two", "three"}) == 3);
        JSP_CHECK(toSource(array) == "[\"one\", \"two\", \"three\"]");
    }

    // ---

    {
        RootedObject array(cx, newArray());
        JSP_CHECK(!appendElements(array, vector<INT32> {}));
    }

    JSP_CHECK(!appendElements(NullPtr(), vector<INT32> {1, 2, 3}));

    // ---

    {
        RootedObject array(cx, evaluateObject("([1, 2, 3])"));

        JSP_CHECK(appendElements(array, vector<INT32> {4, 5}) == 2);
        JSP_CHECK(toSource(array) == "[1, 2, 3, 4, 5]");
    }
}

// ---

/*
 * CHECKING JAVASCRIPT'S POLICY WITH ARRAYS IN REGARD TO "HOLES" AND UNDEFINED-VALUES
 *
 * NOTE: "(void 0)" IS WHAT Array.toSource() WRITES FOR UNDEFINED-VALUES
 */
void TestingJS::testBulkArrayOperations3()
{
    AutoValueVector contents(cx);

    contents.append(UndefinedValue());
    contents.append(NumberValue(123));
    contents.append(UndefinedValue());

    RootedObject array(cx, newArray(contents));
    JSP_CHECK(toSource(array) == "[(void 0), 123, (void 0)]"); // WE COULD HAVE EXPECTED [, 123, ,]

    // ---

    executeScript("var array1 = []; array1.length = 3; array1[1] = 123;");
    JSP_CHECK(toSource(get<OBJECT>(globalHandle(), "array1")) == "[, 123, ,]"); // AS EXPECTED

    executeScript("var array2 = []; for (var i = 0; i < array1.length; i++) array2[i] = array1[i];"); // NO WARNINGS
    JSP_CHECK(toSource(get<OBJECT>(globalHandle(), "array2")) == "[(void 0), 123, (void 0)]"); // WE COULD HAVE EXPECTED [, 123, ,]

    //

    executeScript("array1.push(33.33); array1.push(array1[0])"); // PRODUCES A WARNING: ReferenceError: reference to undefined property array1[0]
    JSP_CHECK(toSource(get<OBJECT>(globalHandle(), "array1")) == "[, 123, , 33.33, (void 0)]");
}

/*
 * APPLYING THE PRINCIPLES VERIFIED IN testBulkArrayOperations3()
 */
void TestingJS::testBulkArrayOperations4()
{
    RootedObject array1(cx, evaluateObject("([1, 33.33, {}, , [], null, 'foo'])")); // THE 4th ELEMENT IS A "HOLE"

    AutoValueVector elements1(cx);
    JSP_CHECK(getElements(array1, elements1) == 7);

    RootedObject array2(cx, newArray());
    JSP_CHECK(appendElements(array2, elements1) == 7);

    JSP_CHECK(toSource(array2) == "[1, 33.33, {}, (void 0), [], null, \"foo\"]"); // UNLIKE array1: THE 4th ELEMENT IS AN UNDEFINED-VALUE

    // ---

    RootedObject array3(cx, newArray());
    setLength(array3, 1); // array3 CONTAINS A "HOLE"

    AutoValueVector elements3(cx);
    JSP_CHECK(getElements(array3, elements3) == 1);

    RootedObject array4(cx, evaluateObject("([1, 2])"));
    JSP_CHECK(appendElements(array4, elements3) == 1);

    JSP_CHECK(toSource(array4) == "[1, 2, (void 0)]"); // THE ELEMENT APPENDED IS AN UNDEFINED-VALUE

    // ---

    RootedValue value(cx, NumberValue(99));
    JSP_CHECK(getElement(array3, 0, &value) && value.isUndefined()); // ACCESSING A "HOLE" PRODUCES AN UNDEFINED-VALUE

    append<FLOAT64>(array3, 55.55);
    appendElement(array3, value);

    JSP_CHECK(toSource(array3) == "[, 55.55, (void 0)]");
}

#pragma mark ---------------------------------------- READ-ONLY AND PERMANENT PROPERTIES ----------------------------------------

/*
 * OPEN QUESTION: HOW TO DEFINE A PROPERTY WHICH WOULD BE READ-ONLY AND PERMANENT ONLY FROM THE JS SIDE?
 *
 * 1) THE SOLUTION PROBABLY LIES AT THE "SHAPE" LEVEL...

 * 2) USING JS_SetAllNonReservedSlotsToUndefined() PROVIDES SOME INSIGHTS:
 *    - SEE testObjectReset1() AND testObjectReset2()
 *
 * 3) NOTE THAT JS_ClearNonGlobalObject() IS NOT RECOMMENDED:
 *   - SEE https://bugzilla.mozilla.org/show_bug.cgi?id=1043281
 *
 * 4) INSIGHTFUL:
 *    - http://perfectionkills.com/understanding-delete
 *      - E.G.
 *        - "var foo = 33" WILL CREATE A NON-DELETABLE PROPERTY
 *        - BUT "bar = 55" WON'T!
 *    - http://www.2ality.com/2013/08/protecting-objects.html
 */

/*
 * FINDINGS:
 *
 * 1) ONCE-DEFINED: READ-ONLY PROPERTIES CAN'T BE SET, EVEN VIA C++
 *
 * 2) FAILURE IS NOT DETECTED:
 *    - PROBABLY BECAUSE IT IS ONLY A "WARNING" (I.E. UNLESS IN "STRICT" MODE)
 *    - UNLIKE WITH PROPERTY DELETION: THERE IS NO JS_DefineProperty2
 */
void TestingJS::testReadOnlyProperty1()
{
    RootedValue value1(cx, NumberValue(55));
    JS_DefineProperty(cx, globalHandle(), "readonly1", value1, JSPROP_ENUMERATE | JSPROP_READONLY);

    RootedValue value2(cx, toValue("foo"));

    if (JS_SetProperty(cx, globalHandle(), "readonly1", value2))
    {
        RootedValue value3(cx);

        if (JS_GetProperty(cx, globalHandle(), "readonly1", &value3) && value3.isNumber())
        {
            JSP_CHECK(true, "FAILURE TO SET PROPERTY readonly1 IS NOT DETECTED");
        }
    }

    LOGI << "UNABLE TO SET (READ-ONLY) PROPERTY NOR TO DETECT FAILURE VIA C++" << endl;
}

/*
 * FINDINGS:
 *
 * 1) READ-ONLY PROPERTIES CAN BE DELETED VIA JS
 *    - UNLESS DEFINED AS PERMANENT
 */
void TestingJS::testReadOnlyProperty2()
{
    RootedValue value(cx, NumberValue(999));
    JS_DefineProperty(cx, globalHandle(), "readonly2", value, JSPROP_ENUMERATE | JSPROP_READONLY);

    executeScript("delete this.readonly2");

    if (hasOwnProperty(globalHandle(), "readonly2"))
    {
        JSP_CHECK(true, "PROPERTY readonly2 IS DELETABLE");
    }

    LOGI << "ABLE TO DELETE (READ-ONLY | NON-PERMANENT) PROPERTY VIA JS" << endl;
}

/*
 * FINDINGS:
 *
 * 1) PERMANENT PROPERTIES CAN'T BE DELETED, EVEN VIA C++
 *
 * 2) JS_DeleteProperty2 (I.E. JS_DeleteProperty) MUST BE USED
 *    - OTHERWISE: IT'S NOT POSSIBLE TO DETECT FAILURE
 */
void TestingJS::testPermanentProperty1()
{
    RootedValue value(cx, NumberValue(123));
    JS_DefineProperty(cx, globalHandle(), "permanent1", value, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

    bool success = false;

    if (!JS_DeleteProperty2(cx, globalHandle(), "permanent1", &success) && success)
    {
        JSP_CHECK(true, "PROPERTY permanent1 IS NOT DELETABLE");
    }

    LOGI << "UNABLE TO DELETE (PERMANENT) PROPERTY VIA C++" << endl;
}

/*
 * FINDINGS:
 *
 * 1) PERMANENT PROPERTIES CAN'T BE REDEFINED, EVEN VIA C++
 */
void TestingJS::testPermanentProperty2()
{
    RootedValue value(cx, NumberValue(123));
    JS_DefineProperty(cx, globalHandle(), "permanent2", value, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

    JS_DefineProperty(cx, globalHandle(), "permanent2", UndefinedHandleValue, JSPROP_ENUMERATE);

    bool success = false;

    if (!JS_DeleteProperty2(cx, globalHandle(), "permanent2", &success) && success)
    {
        JSP_CHECK(true, "PROPERTY permanent2 IS NOT DELETABLE");
    }

    LOGI << "UNABLE TO SET REDEFINE (PERMANENT) PROPERTY VIA C++" << endl;
}

// ---

void TestingJS::testObjectReset1()
{
    RootedObject object(cx);

    object = evaluateObject("({'foo': 456, bar: [1, {baz: 'xxx'}, 3]})");
    define(object, "permanent", 123, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

    /*
     * WILL SET (AMONG OTHERS) THE permanent (READ-ONLY) PROPERTY TO UNDEFINED
     */
    JS_SetAllNonReservedSlotsToUndefined(cx, object);
    JSP_CHECK(toSource(object) == "({foo:(void 0), bar:(void 0), permanent:(void 0)})");

    /*
     * HOWEVER: THE permanent PROPERTY STILL CAN'T BE DELETED
     */
    JSP_CHECK(!deleteProperty(object, "permanent"));

}

void TestingJS::testObjectReset2()
{
    if (false)
    {
        /*
         * WARNING: THIS WILL WIPE-OUT MUCH MORE THAN EXPECTED, E.G.
         *
         * CONSTRUCTORS LIKE: Object, Date, ETC.
         * OBJECTS LIKE: JSON, ETC.
         * FUNCTIONS LIKE: escape(), decodeURI(), ETC.
         */
        JS_SetAllNonReservedSlotsToUndefined(cx, globalHandle());

        /*
         * AND OF COURSE MUCH OF THE STUFF DEFINED WITHIN Manager::init(), AS FOLLOWS:
         */

        try
        {
            executeScript("print(123)"); // TypeError: print is not a function
        }
        catch (exception &e)
        {}

        try
        {
            executeScript("var barker = new Barker('xxx');"); // TypeError: Barker is not a constructor
        }
        catch (exception &e)
        {}
    }
}

#pragma mark ---------------------------------------- CUSTOM CONSTRUCTION ----------------------------------------

const JSClass TestingJS::CustomClass1 =
{
    "CustomObject1",
    0,
    JS_PropertyStub,       // add
    JS_DeletePropertyStub, // delete
    JS_PropertyStub,       // get
    JS_StrictPropertyStub, // set
    JS_EnumerateStub,
    JS_ResolveStub,
    JS_ConvertStub,
};

const JSClass TestingJS::CustomClass2 =
{
    "CustomObject2",
    0,
    JS_PropertyStub,        // add
    JS_DeletePropertyStub,  // delete
    JS_PropertyStub,        // get
    JS_StrictPropertyStub,  // set
    JS_EnumerateStub,
    JS_ResolveStub,
    JS_ConvertStub,
    nullptr,
    nullptr,
    nullptr,
    CustomConstructor       // construct
};

bool TestingJS::CustomConstructor(JSContext *cx, unsigned argc, Value *vp)
{
    auto args = CallArgsFromVp(argc, vp);

    if (!args.isConstructing() || !args.calleev().isObject())
    {
        JS_ReportError(cx, "CONSTRUCTION FAILED");
        return false;
    }

    /*
     * CALLEE ANALYSIS: IS IT A FUNCTION OR AN OBJECT?
     */

    JSObject &callee = args.callee();
    const JSClass *classp;

    if (callee.is<JSFunction>())
    {
        if (!callee.as<JSFunction>().isNative())
        {
            JS_ReportError(cx, "CONSTRUCTION FAILED");
            return false;
        }

        /*
         * CALLED VIA JS
         */
        classp = &CustomClass1; // IMPOSSIBLE TO INFER JSClass
    }
    else
    {
        if (!callee.getClass()->construct)
        {
            JS_ReportError(cx, "CONSTRUCTION FAILED");
            return false;
        }

        /*
         * CALLED VIA C++
         */
        classp = js::Jsvalify(callee.getClass()); // I.E. CustomClass2
    }

    LOGI << "CONSTRUCTING " << classp->name << " WITH " << args.length() << " ARGUMENTS" << endl;

    JSObject *obj = JS_NewObjectForConstructor(cx, classp, args);

    if (!obj)
    {
        JS_ReportError(cx, "CONSTRUCTION FAILED");
        return false;
    }

    args.rval().setObject(*obj);
    return true;
}

/*
 * INSTANTIATION WITH ARGUMENTS, VIA JSNative CONSTRUCTOR
 */
void TestingJS::testCustomConstruction1()
{
    RootedObject prototype(cx, JS_InitClass(cx, globalHandle(), NullPtr(), &CustomClass1, CustomConstructor, 0, nullptr, nullptr, nullptr, nullptr));
    dumpObject(prototype);

    try
    {
        /*
         * REQUIRED FOR JS-SIDE INSTANTIATION:
         * CustomConstructor PASSED AS JSNative CONSTRUCTOR-ARGUMENT TO JS_InitClass()
         */
        evaluateObject("new CustomObject1(1, 'foo')");
    }
    catch (exception &e)
    {
        JSP_CHECK(false);
    }

    // ---

    AutoValueVector args(cx);
    args.append(toValue(255));
    args.append(toValue(nullptr));
    args.append(toValue("hello"));

    RootedValue value(cx);

    if (JS_GetProperty(cx, globalHandle(), "CustomObject1", &value))
    {
        if (value.isObject())
        {
            RootedObject constructor(cx, &value.toObject());
            JSP_CHECK(JS_New(cx, constructor, args));
        }
    }
}

/*
 * INSTANTIATION WITH ARGUMENTS, VIA construct HOOK
 */
void TestingJS::testCustomConstruction2()
{
    RootedObject prototype(cx, JS_InitClass(cx, globalHandle(), NullPtr(), &CustomClass2, nullptr, 0, nullptr, nullptr, nullptr, nullptr));
    dumpObject(prototype);

    /*
     * JUST TO ILLUSTRATE THE POSSIBILITY OF USING AutoValueArray...
     *
     * BETTER ALTERNATIVES:
     * - FOR MULTIPLE ARGUMENTS: AutoValueVector OR AutoWrappedValueVector
     * - FOR SINGLE ARGUMENTS: RootedValue
     */
    AutoValueArray<1> args(cx);
    args[0].setNumber(33.0);

    /*
     * REQUIRED IF JS_InitClass() WAS NOT CALLED WITH JSNative CONSTRUCTOR-ARGUMENT:
     * CustomConstructor DEFINED AS construct HOOK IN JSClass DECLARATION
     */
    JSP_CHECK(JS_New(cx, prototype, args));

    // ---

    RootedValue value(cx);

    if (JS_GetProperty(cx, globalHandle(), "CustomObject2", &value))
    {
        if (value.isObject())
        {
            RootedObject constructor(cx, &value.toObject());
            JSP_CHECK(JS_New(cx, constructor, args));
        }
    }
}

// ---

void TestingJS::testNewObject()
{
    /*
     * PASSING A SINGLE RootedValue IS VALID:
     * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS::HandleValueArray
     */

    RootedValue arg1(cx, toValue(16.67));
    JSP_CHECK(toSource(newObject("Number", arg1)) == "(new Number(16.67))");

    RootedValue arg2(cx, toValue("2014-09-27T21:14:32.695Z"));
    JSP_CHECK(toSource(newObject("Date", arg2)) == "(new Date(1411852472695))");

    // ---

    /*
     * PASSING NO ARGUMENTS IS OKAY TOO
     */

    JSObject *barker = newObject("Barker");
    JSP_CHECK(Barker::bark(barker));

    // ---

    /*
     * SILENTLY FAILS
     */
    JSP_CHECK(!newObject("xxx"));

    /*
     * JS COMPLAINS THAT "function print() ... is not a constructor"
     */
    JSP_CHECK(!newObject("print"));

    // ---

    /*
     * INSTANTIATING PURE JS CUSTOM OBJECT...
     */

    executeScript("\
                  var Person = function(name) { this.name = name; };\
                  Person.prototype.sayHello = function() { return 'my name is ' + this.name; };\
                  ");

    RootedValue arg(cx, toValue("Luka"));
    RootedObject person(cx, newObject("Person", arg));

    RootedValue result(cx, call(person, "sayHello"));
    JSP_CHECK(compare(result, "my name is Luka"));
}

#pragma mark ---------------------------------------- CUSTOM GETTERS / SETTERS ----------------------------------------

/*
 * REFERENCES:
 *
 * - https://github.com/arielm/Spidermonkey/blob/chr_31/js/src/jsapi-tests/testDefineGetterSetterNonEnumerable.cpp
 */

static bool getter1(JSContext *cx, unsigned argc, Value *vp)
{
    auto args = CallArgsFromVp(argc, vp);

    LOGI << "getter1 CALLED" << endl;

    args.rval().setInt32(33);
    return true;
}

void TestingJS::testGetter1()
{
    RootedObject function(cx, JS_GetFunctionObject(JS_NewFunction(cx, getter1, 0, 0, NullPtr(), "get")));

    JS_DefineProperty(cx, globalHandle(), "oneR",
                      JS::UndefinedHandleValue, JSPROP_GETTER | JSPROP_PERMANENT,
                      JS_DATA_TO_FUNC_PTR(JSPropertyOp, (JSObject*)function));

    // ---

    executeScript("var test = oneR; print(test)");
}

// ---

static bool setter1(JSContext *cx, unsigned argc, Value *vp)
{
    auto args = CallArgsFromVp(argc, vp);

    if (args.hasDefined(0))
    {
        LOGI << "setter1 CALLED WITH: " << JSP::toString(args[0]) << endl;

        args.rval().setUndefined();
        return true;
    }

    return false;
}

void TestingJS::testSetter1()
{
    RootedObject function(cx, JS_GetFunctionObject(JS_NewFunction(cx, setter1, 0, 0, NullPtr(), "set")));

    JS_DefineProperty(cx, globalHandle(), "oneW",
                      JS::UndefinedHandleValue, JSPROP_SETTER | JSPROP_PERMANENT,
                      nullptr,
                      JS_DATA_TO_FUNC_PTR(JSStrictPropertyOp, (JSObject*)function));

    // ---

    executeScript("oneW = 255");
}

// ---

static int getterSetterValue1 = 199;

static bool getterSetter1(JSContext *cx, unsigned argc, Value *vp)
{
    auto args = CallArgsFromVp(argc, vp);

    if (args.hasDefined(0))
    {
        LOGI << "getterSetter1: setter CALLED WITH: " << JSP::toString(args[0]) << endl;

        if (args[0].isInt32())
        {
            getterSetterValue1 = args[0].toInt32();

            args.rval().setUndefined();
            return true;
        }
    }
    else
    {
        LOGI << "getterSetter1: getter CALLED" << endl;

        args.rval().setInt32(getterSetterValue1);
        return true;
    }

    return false;
}

void TestingJS::testGetterSetter1()
{
    RootedObject getterFunction(cx, JS_GetFunctionObject(JS_NewFunction(cx, getterSetter1, 0, 0, NullPtr(), "get")));
    RootedObject setterFunction(cx, JS_GetFunctionObject(JS_NewFunction(cx, getterSetter1, 0, 0, NullPtr(), "set")));

    JS_DefineProperty(cx, globalHandle(), "oneRW",
                      JS::UndefinedHandleValue, JSPROP_GETTER | JSPROP_SETTER | JSPROP_PERMANENT,
                      JS_DATA_TO_FUNC_PTR(JSPropertyOp, (JSObject*)getterFunction),
                      JS_DATA_TO_FUNC_PTR(JSStrictPropertyOp, (JSObject*)setterFunction));

    // ---

    executeScript("var test = ++oneRW; print(test);");
}

#pragma mark ---------------------------------------- SHAPES ----------------------------------------

/*
 * MUST READ:
 * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/Property_cache
 *
 * MORE:
 * https://github.com/ricardoquesada/Spidermonkey/blob/master/js/src/vm/Shape.h#L37-100
 * https://github.com/ricardoquesada/Spidermonkey/blob/master/js/src/vm/Shape.h#L469-514
 */

void TestingJS::testShapes1()
{
    JSObject *object = evaluateObject("({one: 1, two: 'deux', trois: [1, 2, 3]})");

    RootedObject obj(cx, object);
    AutoIdVector idv(cx);

    if (GetPropertyNames(cx, obj, JSITER_OWNONLY, &idv))
    {
        RootedId id(cx);
        RootedObject obj2(cx); // MOST OF THE TIME EQUAL TO obj (UNLESS SOME "PROXYING" IS TAKING PLACE)
        js::RootedShape shape(cx);

        for (size_t i = 0; i < idv.length(); ++i)
        {
            id = idv[i];

            if (JSObject::lookupGeneric(cx, obj, id, &obj2, &shape))
            {
                JS_ASSERT(obj2->isNative()); // WILL IT WORK FOR "NEW OBJECT PROTOTYPES" DEFINED ON THE JS SIDE? (TODO: CHECK)

                if (shape->hasSlot())
                {
                    RootedValue vp(cx);
                    vp.set(obj2->nativeGetSlot(shape->slot())); // PROBABLY THE BRIDGE TO ("NATURALLY" NON-ACCESSIBLE) "RESERVED SLOTS" FROM THE JS SIDE

                    LOGI << JSP::write(id) << ": " << write(vp) << endl;
                }
            }
        }
    }

    LOGI << endl;
}

void TestingJS::testShapes2()
{
    JSObject *object1 = evaluateObject("({one: 1, two: 'deux', trois: [1, 2, 3]})");
    dumpObject(object1);
    LOGI << "-----" << endl;

    JSObject *object2 = evaluateObject("({one: 250, two: 'dos', trois: [0]})");
    dumpObject(object2);
    LOGI << "-----" << endl;
}

#pragma mark ---------------------------------------- ATOMS ----------------------------------------

/*
 * INVESTIGATING ATOMS:
 * - ATOMS ARE UNIQUE AND IMMUTABLE JS STRINGS STORED INTERNALLY BY SPIDERMONKEY
 *   - EFFICIENT "MAPPING" CAPABILITIES (LOOKUP, STORAGE, ETC.) ARE PROVIDED BY THE SYSTEM
 * - EACH JS OBJECT PROPERTY-NAME IS ASSOCIATED WITH AN ATOM (I.E. THE "SLOT" OF THE PROPERTY HAVE AN "ATOM JSID")
 * - THE CONCEPT OF "SYMBOL" IN ECMA 6 SEEMS RELATED TO ATOMS:
 *   https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
 *
 *
 * WISDOM ACQUIRED WHILE WORKING ON ToSourceTraverser.cpp:
 * - THE "IDENTIFIER MECHANISM" CAN BE USED TO DIFFERENTIATE BETWEEN ATOMS LIKE property1 AND property-two
 *   - THE LATTER IS NOT "COMPILABLE" (UNLESS QUOTED), AND THEREFORE IS NOT CONSIDERED AS AN "IDENTIFIER"
 *   - SEE "bool IsIdentifier(JSLinearString *str)" IN "frontend/BytecodeCompiler.h"
 */

void TestingJS::testAtoms()
{
    createObject1();
    createObject2();

    string property1 = "property2";
    JSAtom *atom1 = Atomize(cx, property1.data(), property1.size());

    string property2 = "property-two";
    JSAtom *atom2 = Atomize(cx, property2.data(), property2.size());

    /*
     * DEMONSTRATING THAT AN ATOM IS A JS STRING
     */
    dumpAtom(atom1);
    dumpAtom(atom2);

    // ---

    jsid id1 = js::AtomToId(atom1);
    jsid id2 = js::AtomToId(atom2);

    /*
     * DEMONSTRATING THAT A JSID CAN BE AN ATOM
     */
    LOGI << JSP::write(id1) << endl;
    LOGI << JSP::write(id2) << endl;
}

#pragma mark ---------------------------------------- RESERVED SLOTS ----------------------------------------

JSClass TestClass1
{
    "TestClass1",
    JSCLASS_HAS_RESERVED_SLOTS(1),
    JS_PropertyStub,
    JS_DeletePropertyStub,
    JS_PropertyStub,
    JS_StrictPropertyStub,
    JS_EnumerateStub,
    JS_ResolveStub,
    JS_ConvertStub
};

/*
 * INVESTIGATING RESERVED SLOTS:
 * - https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_GetReservedSlot
 * - http://mxr.mozilla.org/mozilla-central/ident?i=JSCLASS_HAS_RESERVED_SLOTS
 *
 *
 * FINDINGS: RESERVED SLOTS HAVE NO JSID
 *
 * PROS: PROBABLY THE FASTEST WAY TO ACCESS A JS OBJECT'S VAUE
 * CONS: NOT "NATURALLY" ACCESSIBLE FROM JS - UPDATE: SEE JSObjet::nativeGetSlot() USED IN testShapes1()
 *
 * FOLLOW-UP:
 * - THERE MIGHT BE A BETTER ALTERNATIVE TO PREDEFINED-SLOTS:
 *   - SIMPLY USING NATIVE GETTERS/SETTERS, E.G. AS FOLLOWS:
 *     - https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_Cookbook#Defining_a_property_with_a_getter_and_setter
 *     - https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_Cookbook#Defining_a_constant_property
 *   - BASICALLY:
 *     - OUR NATIVE "HANDLER" COULD STORE PROPERTIES IN ANY POSSIBLE WAY
 *     - WE'RE NOT BOUND TO RESERVED-SLOTS ANYMORE
 *     - HOWEVER:
 *       - IF WE STORE THE VALUE AS NATIVE PRIMITIVES IN C++ MEMORY
 *         - WE MUST BE SURE TO RELEASE THE MEMORY WHEN OUR JS OBJECT IS GARBAGE-COLLECTED
 */

void TestingJS::testReservedSlots()
{
    RootedObject object(cx, JS_NewObject(cx, &TestClass1, NullPtr(), NullPtr()));

    JS_SetReservedSlot(object, 0, DoubleValue(33.33));

    RootedValue value2(cx, NumberValue(999));
    JS_SetProperty(cx, object, "property2", value2);

    /*
     * DEMONSTRATES THAT THE RESERVED SLOT HAVE NO JSID
     */
    dumpObject(object);

    /*
     * DEMONSTRATES THAT THE RESERVED SLOT IS NOT (AUTOMATICALLY) ACCESSIBLE VIA JS
     */
    LOGI << toSource(object) << endl;
}

#pragma mark ---------------------------------------- JSID ----------------------------------------

/*
 * INVESTIGATING JSID:
 * - https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_reference/jsid
 *
 *
 * FINDINGS:
 * - EACH PROPERTY IN A JS-OBJECT IS ASSOCIATED WITH A "SLOT"
 *   - EACH SLOT CAN BE ASSOCIATED WITH A JSID
 * - A JSID CAN BE OF THE FOLLOWING TYPES:
 *   - STRING (OR ATOM) (USED FOR THE STRING-PROPERTIES OF AN OBJECT)
 *   - INT (USED FOR THE NUMERIC-PROPERTIES OF AN OBJECT, E.G. ARRAY INDICES)
 *   - OBJECT
 *   - VOID
 *
 * THIS TEST DEMONSTRATES THAT SPIDERMONKEY IS CACHING PROPERTY-NAMES SO THAT
 * A PROPERTY WITH THE SAME NAME IN TWO DIFFERENT JS OBJECT REFERS TO THE SAME JSID
 */

void TestingJS::testJSID()
{
    /*
     * DEMONSTRATES THAT PROPERTY-NAMES ARE CACHED:
     * A PROPERTY WITH THE SAME NAME IN TWO DIFFERENT JS OBJECTS WILL REFER TO THE SAME "ATOM JSID"
     */
    dumpIds(createObject1());
    dumpIds(createObject2());

    // ---

    RootedId id1(cx);
    if (!IndexToId(cx, 1, &id1)) throw;

    RootedId id2(cx);
    if (!IndexToId(cx, 2, &id2)) throw;

    /*
     * DEMONSTRATES HOW AN "INT JSID" IS GENERATED, USING THE FORMULA DEFINED IN "public/Id.h"
     * ((i << 1) | JSID_TYPE_INT);
     */
    LOGI << JSP::write(id1) << endl; // PRINTS: jsid 0x3 = 1
    LOGI << JSP::write(id2) << endl; // PRINTS: jsid 0x5 = 2
}

#pragma mark ---------------------------------------- MISC ----------------------------------------

void TestingJS::dumpIds(JSObject *object)
{
    AutoIdVector idv(cx);

    if (GetPropertyNames(cx, object, JSITER_OWNONLY, &idv))
    {
        for (size_t i = 0; i < idv.length(); ++i)
        {
            LOGI << JSP::write(idv[i]) << endl;
        }
    }
}

JSObject* TestingJS::createObject1()
{
    RootedObject object(cx, newPlainObject());

    RootedValue value1(cx, NumberValue(33.33));
    JS_SetProperty(cx, object, "property1", value1);

    RootedValue value2(cx, NumberValue(66.67));
    JS_SetProperty(cx, object, "property-two", value2);

    return object;
}

JSObject* TestingJS::createObject2()
{
    return evaluateObject("({'property-two': 456, property1: 123})");
}

JSObject* TestingJS::createArray()
{
    return evaluateObject("(['e0', 'e1', 'e2'])");
}

#pragma mark ---------------------------------------- THREAD SAFETY ----------------------------------------

class TestTask : public Task
{
    TestingJS *target;

public:
    TestTask(TestingJS *target) : target(target) {}

    void run()
    {
        sleep(1000);

        /*
         * SUPPOSED TO CAUSE AN ASSERTION-FAILURE WHEN SPIDERMONKEY IS BUILT WITH "JS_THREADSAFE"
         *
         * TODO:
         * - FIND-OUT WHY IT CRASHES ON SPIDERMONKEY 31
         *   I.E. INSTEAD OF ALWAYS CAUSING AN ASSERTION-FAILURE
         *   E.G. RELATED TO CurrentThreadCanAccessRuntime(cx->runtime())
         */

        target->testAtoms(); // FORBIDDEN: A JS-CONTEXT MUST BE ACCESSED FROM THE THREAD THAT CREATED IT
    }
};

void TestingJS::testThreadSafety()
{
    taskManager().addTask(make_shared<TestTask>(this));
}

#pragma mark ---------------------------------------- MISC ----------------------------------------

/*
 * CONCLUSIONS:
 *
 * SCOPE:
 * JS::Evaluate (USED BY Proto::evaluateObject) WILL FAIL IF NO obj PARAMETER IS PROVIDED
 * I.E. WE SHOULD CONTINUE USING THE GLOBAL-OBJECT BY DEFAULT
 *
 * FOLLOW-UP:
 * - MORE INFO TO DIGEST (TODO): https://github.com/ricardoquesada/Spidermonkey/blob/master/js/src/jsapi.h#L3671-3703
 */

void TestingJS::testEvaluationScope()
{
    JSObject *newObject = evaluateObject("({x: 250.33, foo: [1, 2, 3], bar: 'baz'})");
    dumpObject(newObject);
}

/*
 * CONCLUSIONS:
 *
 * SCOPE:
 * SEE COMMENTS REGARDING HOW JS_CallFunctionValue (USED BY Proto::call)
 * WILL BEHAVE DEPENDING ON THE obj PARAMETER
 */

void TestingJS::testFunctionScope()
{
    /*
     * GLOBAL SCOPE
     */
    executeScript("var someAmbiguousThing = 2, someGlobalThing = 0");

    string source = "({\
    someAmbiguousThing: 3,\
    function1: function(parameter) { return parameter * someGlobalThing; },\
    function2: function(parameter) { return parameter * this.someAmbiguousThing; }\
    })";

    RootedObject containerObject(cx, evaluateObject(source));
    dumpObject(containerObject);

    // ---

    AutoValueArray<1> args(cx);
    args[0].setNumber(33.0);

    RootedValue function1(cx);
    RootedValue function2(cx);

    if (getProperty(containerObject, "function1", &function1))
    {
        /*
         * IF containerObject, OR NullPtr(), OR NOTHING (I.E. THE GLOBAL-OBJECT) IS PROVIDED:
         * someGlobalThing WILL BE PROPERLY RESOLVED
         */
        JS::RootedValue result1(cx, call(NullPtr(), function1, args));
        LOGI << "RESULT 1: " << write(result1) << endl; // RESULT: 0
    }

    if (getProperty(containerObject, "function2", &function2))
    {
        /*
         * IF containerObject IS PROVIDED:
         * this.someAmbiguousThing WILL RESOLVE TO THE "LOCAL VALUE"
         */
        RootedValue result2A(cx, call(containerObject, function2, args));
        LOGI << "RESULT 2A: " << write(result2A) << endl; // RESULT: 99

        /*
         * IF nullptr OR NOTHING (I.E. THE GLOBAL-OBJECT) IS PROVIDED:
         * this.someAmbiguousThing WILL RESOLVE TO THE "GLOBAL VALUE"
         */
        RootedValue result2B(cx, call(NullPtr(), function2, args));
        LOGI << "RESULT 2B: " << write(result2B) << endl; // RESULT: 66
    }
}

void TestingJS::testCustomScriptExecution()
{
    auto inputSource = InputSource::getFileInDocuments("temp.js");
    string source = utils::readText<string>(inputSource);
    string filePathHint = inputSource->getFilePathHint();

    OwningCompileOptions options(cx);
    options.setNoScriptRval(true); // TODO: SHOULD BE FORCED, INSIDE Proto::exec
    options.setVersion(JSVersion::JSVERSION_ECMA_5);
    options.setUTF8(false);
    options.setFileAndLine(cx, filePathHint.data(), 1);

    exec(source, options);
}

// ---

void TestingJS::testParsing1()
{
    string source = utils::readText<string>(InputSource::getAsset("config.json"));

    initComplexJSON(source);
    string js = evaluateString("JSON.stringify(JSON.parse(complexJSON), null, 2)");

    JSObject *parsed = parse(source);
    string cpp = stringify(parsed);

    JSP_CHECK(js == cpp);
}

/*
 * "JSON.parse() does not allow trailing commas"
 *
 * REFERENCE: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
 */
void TestingJS::testParsing2()
{
    try
    {
        executeScript("JSON.parse('[1, 2, 3,]')");
        JSP_CHECK(false); // UNREACHABLE DUE TO SyntaxError
    }
    catch (exception &e)
    {}

    // ---

    JSObject *parsed = parse("[1, 2, 3,]");
    JSP_CHECK(!parsed); // NULL RESULT DUE TO SyntaxError
}

void TestingJS::initComplexJSON(const string &source)
{
    RootedValue value(cx, toValue(source));
    setProperty(globalHandle(), "complexJSON", value);
}

//

/*
 * WORKS BECAUSE THERE ARE NO "CYCLIC VALUES" IN OBJECT
 * OTHERWISE: RETURNS EMPTY-STRING AND REPORTS JS-EXCEPTION ("TypeError: cyclic object value")
 */
void TestingJS::testStringify()
{
    initComplexJSObject();

    /*
     * USING stringify VIA JS
     */
    string js = evaluateString("JSON.stringify(complexObject, null, 2)");

    /*
     * USING stringify VIA C++
     */
    string cpp = stringify(get<OBJECT>(globalHandle(), "complexObject"));

    JSP_CHECK(js == cpp);
}

/*
 * WORKS BECAUSE OBJECT IS NOT "HUGE"
 * OTHERWISE: RETURNS EMPTY-STRING AND REPORTS JS-EXCEPTION ("InternalError: allocation size overflow")
 */
void TestingJS::testToSource()
{
    initComplexJSObject();

    /*
     * USING toSource() VIA JS
     */
    string js = evaluateString("complexObject.toSource()");

    /*
     * USING toSource() VIA C++
     */
    string cpp = toSource(get<OBJECT>(globalHandle(), "complexObject"));

    JSP_CHECK(js == cpp);
}

void TestingJS::initComplexJSObject()
{
    if (!hasOwnProperty(globalHandle(), "complexObject"))
    {
        executeScript(InputSource::getAsset("handlebars.js"));
        JSObject *complexObject = get<OBJECT>(globalHandle(), "Handlebars");

        set(globalHandle(), "complexObject", complexObject);
    }
}


text:
/**
 * Maven plugins (others than {@link org.apache.sis.util.resources.ResourceCompilerMojo}) used
 * for building Apache SIS. See the Maven-generated module description for more information.
 *
 * @author  Martin Desruisseaux (IRD, Geomatys)
 * @version 0.8
 * @since   0.3
 * @module
 */
package org.apache.sis.internal.maven;

redpajama_set_name: RedPajamaGithub


text:
package Mod.Block;

import cpw.mods.fml.common.network.FMLNetworkHandler;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import Mod.Lib.Refrence;
import Mod.Main.Main;
import Mod.TileEntity.TileEntityElectricFurnace;

public class ModBlockElectricFurnace extends BlockContainer{

	protected ModBlockElectricFurnace(int par1) {
		super(par1, Material.iron);
	}

	Icon IconSide;
	Icon IconFront;

	public static final int META_ISACTIVE = 0x00000008;
	public static final int MASK_DIR = 0x00000007;
	public static final int META_DIR_NORTH = 0x00000001;
	public static final int META_DIR_SOUTH = 0x00000002;
	public static final int META_DIR_EAST = 0x00000003;
	public static final int META_DIR_WEST = 0x00000000;

	@Override
	public TileEntity createNewTileEntity(World world) {
		return new TileEntityElectricFurnace();
	}
    public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9)
    {
        if (par1World.isRemote)
        {

            return true;
        }
        else
        {

        	FMLNetworkHandler.openGui(par5EntityPlayer, Main.instance, 0, par1World, par2, par3, par4);
            return true;
        }
    }

    @Override
    public void breakBlock(World World, int x, int y, int z, int id, int meta)
    {
    	TileEntity tile = World.getBlockTileEntity(x, y, z);

    	if(tile != null && tile instanceof IInventory){
    		IInventory inv = (IInventory)tile;

    		for(int i = 0; i < inv.getSizeInventory(); i++){
    			ItemStack stack = inv.getStackInSlotOnClosing(i);

    			if(stack != null){
    				float spawnX = x + World.rand.nextFloat();
    				float spawnY = y + World.rand.nextFloat();
    				float spawnZ = z + World.rand.nextFloat();

    				EntityItem droppedItem = new EntityItem(World, spawnX, spawnY, spawnZ, stack);

    				float mult = 0.05F;

    				droppedItem.motionX = (-0.5 + World.rand.nextFloat()) * mult;
    				droppedItem.motionY = (4 + World.rand.nextFloat()) * mult;
    				droppedItem.motionZ = (-0.5 + World.rand.nextFloat()) * mult;

    				World.spawnEntityInWorld(droppedItem);

    			}

    		}
    	}

		super.breakBlock(World, x, y, z, id, meta);
    }

	private static int getSideFromFacing(int facing)
	{
		switch(facing)
		{
		case META_DIR_WEST:
			return 4;

		case META_DIR_EAST:
			return 5;

		case META_DIR_NORTH:
			return 2;

		case META_DIR_SOUTH:
			return 3;

		default:
			return 4;
		}
	}

	   public void registerIcons(IconRegister par1IconRegister)
	    {

	        this.IconSide = par1IconRegister.registerIcon(Refrence.Mod_Id + ":" + "ElFurnaceSide");
	        this.IconFront = par1IconRegister.registerIcon(Refrence.Mod_Id + ":" + "ElFurnaceFront");

	    }

		@Override
		public Icon getIcon(int side, int metadata)
		{
			boolean isActive = ((metadata >> 3) == 1);
			int facing = (metadata & MASK_DIR);

			return (side == getSideFromFacing(facing) ? (IconFront) : (side == 1 ? this.IconSide : side == 0 ? IconSide : this.IconSide));
		}

		@Override
		public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack itemStack)
		{
			int metadata = 0;
			int facing = META_DIR_WEST;

			int dir = MathHelper.floor_double((double)(entity.rotationYaw * 4f / 360f) + 0.5) & 3;
			if(dir == 0)
				facing = META_DIR_NORTH;
			if(dir == 1)
				facing = META_DIR_EAST;
			if(dir == 2)
				facing = META_DIR_SOUTH;
			if(dir == 3)
				facing = META_DIR_WEST;

			metadata |= facing;
			world.setBlockMetadataWithNotify(x, y, z, metadata, 2);
		}

}


text:
package com.evolveum.midpoint.prism;

import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;

import javax.xml.namespace.QName;

/**
 * @author semancik
 *
 */
public class PrismConstants {

	public static final String EXTENSION_LOCAL_NAME = "extension";
	public static final String NAME_LOCAL_NAME = "name";

	public static final String ATTRIBUTE_ID_LOCAL_NAME = "id";
	public static final String ATTRIBUTE_OID_LOCAL_NAME = "oid";
	public static final String ATTRIBUTE_VERSION_LOCAL_NAME = "version";
	public static final String ATTRIBUTE_REF_TYPE_LOCAL_NAME = "type";
	public static final String ATTRIBUTE_RELATION_LOCAL_NAME = "relation";

	public static final String ELEMENT_DESCRIPTION_LOCAL_NAME = "description";
	public static final String ELEMENT_FILTER_LOCAL_NAME = "filter";

	public static final String NS_PREFIX = "http://prism.evolveum.com/xml/ns/public/";
	public static final String NS_ANNOTATION = NS_PREFIX + "annotation-3";
	public static final String PREFIX_NS_ANNOTATION = "a";
	public static final String NS_TYPES = NS_PREFIX + "types-3";
	public static final String PREFIX_NS_TYPES = "t";
	public static final String NS_QUERY = NS_PREFIX + "query-3";
	public static final String PREFIX_NS_QUERY = "q";

	public static final String NS_MATCHING_RULE = NS_PREFIX + "matching-rule-3";
	public static final String PREFIX_NS_MATCHING = "mr";

	public static final String NS_PREFIX_CRYPTO = NS_PREFIX + "crypto/";
	public static final String NS_PREFIX_CRYPTO_ALGORITHM = NS_PREFIX_CRYPTO + "algorithm/";
	public static final String NS_CRYPTO_ALGORITHM_PBKD = NS_PREFIX_CRYPTO_ALGORITHM + "pbkd-3";

	// Annotations

	public static final QName A_PROPERTY_CONTAINER = new QName(NS_ANNOTATION, "container");
	public static final QName A_OBJECT = new QName(NS_ANNOTATION, "object");

	public static final QName A_DEFAULT_NAMESPACE = new QName(NS_ANNOTATION, "defaultNamespace");
	public static final QName A_IGNORED_NAMESPACE = new QName(NS_ANNOTATION, "ignoredNamespace");

	public static final QName A_TYPE = new QName(NS_ANNOTATION, "type");
	public static final QName A_DISPLAY_NAME = new QName(NS_ANNOTATION, "displayName");
	public static final QName A_DISPLAY_ORDER = new QName(NS_ANNOTATION, "displayOrder");
	public static final QName A_HELP = new QName(NS_ANNOTATION, "help");
	public static final QName A_ACCESS = new QName(NS_ANNOTATION, "access");
	public static final String A_ACCESS_CREATE = "create";
	public static final String A_ACCESS_UPDATE = "update";
	public static final String A_ACCESS_READ = "read";
	public static final QName A_INDEXED = new QName(NS_ANNOTATION, "indexed");
	public static final QName A_IGNORE = new QName(NS_ANNOTATION, "ignore");
	public static final QName A_OPERATIONAL = new QName(NS_ANNOTATION, "operational");
	public static final QName A_EXTENSION = new QName(NS_ANNOTATION, "extension");
	public static final QName A_EXTENSION_REF = new QName(NS_ANNOTATION, "ref");
	public static final QName A_OBJECT_REFERENCE = new QName(NS_ANNOTATION, "objectReference");
	public static final QName A_OBJECT_REFERENCE_TARGET_TYPE = new QName(NS_ANNOTATION, "objectReferenceTargetType");
	public static final QName A_COMPOSITE = new QName(NS_ANNOTATION, "composite");
	public static final QName A_DEPRECATED = new QName(NS_ANNOTATION, "deprecated");
	public static final QName A_LABEL = new QName(NS_ANNOTATION, "label");
	public static final QName A_MATCHING_RULE = new QName(NS_ANNOTATION, "matchingRule");
	public static final QName A_EMPHASIZED = new QName(NS_ANNOTATION, "emphasized");
	public static final QName A_VALUE_ENUMERATION_REF = new QName(NS_ANNOTATION, "valueEnumerationRef");
	public static final QName A_HETEROGENEOUS_LIST_ITEM = new QName(NS_ANNOTATION, "heterogeneousListItem");

	public static final QName SCHEMA_DOCUMENTATION = new QName(W3C_XML_SCHEMA_NS_URI, "documentation");
	public static final QName SCHEMA_APP_INFO = new QName(W3C_XML_SCHEMA_NS_URI, "appinfo");

	public static final QName A_MAX_OCCURS = new QName(NS_ANNOTATION, "maxOccurs");
	public static final String MULTIPLICITY_UNBONUNDED = "unbounded";

	public static final QName A_NAMESPACE = new QName(NS_ANNOTATION, "namespace");
	public static final String A_NAMESPACE_PREFIX = "prefix";
	public static final String A_NAMESPACE_URL = "url";

	//Query constants
	public static final QName Q_OID = new QName(NS_QUERY, "oid");
	public static final QName Q_TYPE = new QName(NS_QUERY, "type");
	public static final QName Q_RELATION = new QName(NS_QUERY, "relation");
	public static final QName Q_VALUE = new QName(NS_QUERY, "value");
	public static final QName Q_ORDER_BY = new QName(NS_QUERY, "orderBy");
	public static final QName Q_ANY = new QName(NS_QUERY, "any");

	// Path constants
	public static final String T_PARENT_LOCAL_PART = "parent";
	public static final QName T_PARENT = new QName(NS_TYPES, T_PARENT_LOCAL_PART);
	public static final QName T_OBJECT_REFERENCE = new QName(NS_TYPES, "objectReference");
	public static final String T_ID_LOCAL_PART = "id";
	public static final QName T_ID = new QName(NS_TYPES, T_ID_LOCAL_PART);

	// Misc

	public static final Class DEFAULT_VALUE_CLASS = String.class;

	public static final QName POLYSTRING_TYPE_QNAME = new QName(NS_TYPES, "PolyStringType");
	public static final QName POLYSTRING_ELEMENT_ORIG_QNAME = new QName(NS_TYPES, "orig");
	public static final QName POLYSTRING_ELEMENT_NORM_QNAME = new QName(NS_TYPES, "norm");

    // a bit of hack: by this local name we know if a object is a reference (c:ObjectReferenceType)
    public static final String REFERENCE_TYPE_NAME = "ObjectReferenceType";

    public static final boolean EQUALS_DEFAULT_IGNORE_METADATA = true;
    public static final boolean EQUALS_DEFAULT_IS_LITERAL = false;

    public static final String EXPRESSION_LOCAL_PART = "expression";
}


text:
//-----------------------------------------------------------------------
// <copyright file="InvalidBlockchainFilesException.cs">
// Copyright © Ladislau Molnar. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace BitcoinBlockchain.Parser
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Runtime.Serialization;

    /// <summary>
    /// The exception that is thrown when the list of Bitcoin blockchain files is found to be invalid.
    /// The blockchain folder must contain files named with the pattern "blkxxxxx.dat",
    /// starting from "blk00000.dat" and with no gaps in the numeric section.
    /// Note that this exception is referring only to the file names and not to the files content.
    /// </summary>
    [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "blk and dat refer to file names and extensions")]
    [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "blk and dat refer to file names and extensions.")]
    [Serializable]
    public class InvalidBlockchainFilesException : Exception
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="InvalidBlockchainFilesException"/> class.
        /// </summary>
        public InvalidBlockchainFilesException()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="InvalidBlockchainFilesException"/> class.
        /// </summary>
        /// <param name="message">
        /// The message that describes the error.
        /// </param>
        public InvalidBlockchainFilesException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="InvalidBlockchainFilesException"/> class.
        /// </summary>
        /// <param name="message">
        /// The message that describes the error.
        /// </param>
        /// <param name="innerException">
        /// The exception that is the cause of the current exception,
        /// or a null reference if no inner exception is specified.
        /// </param>
        public InvalidBlockchainFilesException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="InvalidBlockchainFilesException"/> class with serialized data.
        /// </summary>
        /// <param name="info">
        /// The System.Runtime.Serialization.SerializationInfo that holds the serialized data
        /// about this instance of the <see cref="InvalidBlockchainFilesException"/> class.
        /// </param>
        /// <param name="context">
        /// The System.Runtime.Serialization.StreamingContext that contains contextual information about the
        /// source or destination.
        /// </param>
        protected InvalidBlockchainFilesException(
           SerializationInfo info,
           StreamingContext context)
            : base(info, context)
        {
        }
    }
}


text:
require 'formula'

class Lesstif < Formula
  desc "Open source implementation of OSF/Motif"
  homepage 'http://lesstif.sourceforge.net'
  url 'https://downloads.sourceforge.net/project/lesstif/lesstif/0.95.2/lesstif-0.95.2.tar.bz2'
  sha1 'b894e544d529a235a6a665d48ca94a465f44a4e5'

  bottle do
    revision 1
    sha1 "50b1cecbfce9a66ae8253b6efe1ecef4c58678fc" => :yosemite
    sha1 "f6439fb1fda16afd5ae5447f071170b08a9484c3" => :mavericks
    sha1 "dff63d044e87b2137cf8f961f9c46186b7af18d1" => :mountain_lion
  end

  depends_on :x11
  depends_on "freetype"

  def install
    # LessTif does naughty, naughty, things by assuming we want autoconf macros
    # to live in wherever `aclocal --print-ac-dir` says they should.
    # Shame on you LessTif! *wags finger*
    inreplace 'configure', "`aclocal --print-ac-dir`", "#{share}/aclocal"

    # 'sed' fails if LANG=en_US.UTF-8 as is often the case on Macs.
    # The configure script finds our superenv sed wrapper, sets SED,
    # but then doesn't use that variable.
    ENV['LANG'] = 'C'

    system "./configure", "--prefix=#{prefix}",
                          "--disable-debug",
                          "--enable-production",
                          "--disable-dependency-tracking",
                          "--enable-shared",
                          "--enable-static"

    system "make"

    # LessTif won't install in parallel 'cause several parts of the Makefile will
    # try to make the same directory and `mkdir` will fail.
    ENV.deparallelize
    system "make install"
  end
end


text:
'use strict';

describe('Controllers Tests ', function () {

    beforeEach(module('jhipsterApp'));

    var $scope, $httpBackend, q, Auth;

    // define the mock Auth service
    beforeEach(function() {
        Auth = {
            changePassword: function() {}
        };
    });

    beforeEach(inject(function ($rootScope, $controller, $q, $injector) {
        $scope = $rootScope.$new();
        q = $q;
        $httpBackend = $injector.get('$httpBackend');
        $controller('PasswordController', {$scope: $scope, Auth: Auth});
    }));

    describe('PasswordController', function () {
        it('should show error if passwords do not match', function () {
            //GIVEN
            $scope.password = 'password1';
            $scope.confirmPassword = 'password2';
            //WHEN
            $scope.changePassword();
            //THEN
            expect($scope.doNotMatch).toBe('ERROR');
        });
        it('should call Service and set OK on Success', function () {
            //GIVEN
            var pass = 'myPassword';
            $scope.password = pass;
            $scope.confirmPassword = pass;

            spyOn(Auth, 'changePassword').and.returnValue(new function(){
                var deferred = q.defer();
                $scope.error = null;
                $scope.success = 'OK';
                return deferred.promise;
            });

            //WHEN
            $scope.changePassword();

            //THEN
            expect($scope.error).toBeNull();
            expect($scope.success).toBe('OK');
        });
    });
});


text:
package com.bgstation0.android.sample.fragmenttransaction_;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {

    // ƒƒ"ƒoƒtƒB[ƒ‹ƒh
    static final String TAG = "Fragment2";	// TAG'ð"Fragment2"'ŏ‰Šú‰».

    // ƒrƒ…[¶¬Žž
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        // ƒƒO'ðŽc'·.
        Log.d(TAG, "Fragment2.onCreateView");	// "Fragment2.onCreateView"'ƃƒO'ÉŽc'·.

        // Šù'è'̏ˆ—.
        super.onCreateView(inflater, container, savedInstanceState);

        // Fragment2'ÌEditText'ðŽæ"¾.
        View view = inflater.inflate(R.layout.fragment2_main, null);	// inflater.inflate'ÅR.layout.fragment2_main'©'çƒrƒ…['ðì¬.
        return view;	// view'ð•Ô'·.

    }

}


text:
from touchdown.core import argument, errors, resource, serializers
from touchdown.core.action import Action
from touchdown.core.plan import Plan

from . import IniFile

class Variable(resource.Resource):

    resource_name = "variable"

    name = argument.String()
    retain_default = argument.Boolean(default=False)
    config = argument.Resource(IniFile)

class Describe(Plan):

    resource = Variable
    name = "describe"

    def get_actions(self):
        try:
            val, user_set = self.runner.get_service(self.resource, "get").execute()
        except KeyError:
            val = None
            user_set = False
        self.object = {"Value": val, "UserSet": user_set}
        return []

class ApplyAction(Action):
    @property
    def description(self):
        yield "Generate and store setting {!r}".format(self.resource.name)

    def run(self):
        default = serializers.maybe(self.resource.default).render(
            self.runner, self.resource
        )
        self.runner.get_service(self.resource, "set").execute(default)

class Apply(Plan):

    resource = Variable
    name = "apply"
    apply_action = ApplyAction

    def get_actions(self):
        try:
            val, user_set = self.runner.get_service(self.resource, "get").execute()
        except KeyError:
            user_set = False
        if not user_set and self.resource.retain_default:
            yield self.apply_action(self)

class Set(Plan):

    resource = Variable
    name = "set"

    def from_string(self, value):
        return value

    def to_lines(self, value):
        return [value]

    def execute(self, value):
        conf = self.runner.get_service(self.resource.config, "describe")
        if "." not in self.resource.name:
            raise errors.Error("You didn't specify a section")
        conf.set(self.resource.name, "\n".join(self.to_lines(value)))

class Get(Plan):

    resource = Variable
    name = "get"

    def to_string(self, value):
        return str(value)

    def from_lines(self, value):
        assert len(value) == 1
        return value[0]

    def get_default_value(self):
        return serializers.maybe(self.resource.default).render(
            self.runner, self.resource
        )

    def execute(self):
        conf = self.runner.get_service(self.resource.config, "describe")
        if "." not in self.resource.name:
            raise errors.Error("You didn't specify a section")
        try:
            value = conf.get(self.resource.name)
        except KeyError:
            value = None

        if not value:
            return self.get_default_value(), False

        return self.from_lines(value.splitlines()), True

class Refresh(Plan):

    resource = Variable
    name = "refresh"

    def execute(self):
        setter = self.runner.get_service(self.resource, "set")
        setter.execute(
            serializers.maybe(self.resource.default).render(self.runner, self.resource)
        )

class VariableAsString(serializers.Serializer):
    def __init__(self, resource):
        self.resource = resource

    def render(self, runner, object):
        return runner.get_service(self.resource, "get").execute()[0]

    def dependencies(self, object):
        return frozenset((self.resource,))


text:
Task.create(description: 'First Task', completed: false, due_date: "2014-12-19")
Task.create(description: 'Second Task', completed: true)
Task.create(description: 'Third Task', completed: false)
Task.create(description: 'Fourth Task', completed: true, due_date: "2014-12-19")
Task.create(description: 'Fifth Task', completed: false, due_date: "2014-12-19")


text:
function k = sdlfmvKernCompute(kern, t, t2, covIC)

% SDLFMVKERNCOMPUTE Compute the SDLFMV kernel given the parameters and X.
%
%	Description:
%
%	K = SDLFMVKERNCOMPUTE(KERN, T1, T2, COVIC) computes the kernel
%	parameters for the swicthing dynamical latent force model kernel
%	corresponding to the velocities given inputs associated with rows
%	and columns.
%	 Returns:
%	  K - the kernel matrix computed at the given points.
%	 Arguments:
%	  KERN - the kernel structure for which the matrix is computed.
%	  T1 - the input matrix associated with the rows of the kernel.
%	  T2 - the input matrix associated with the columns of the kernel.
%	  COVIC - covariance for the initial conditions
%
%	K = SDLFMVKERNCOMPUTE(KERN, T, COVIC) computes the kernel matrix for
%	the switching dynamical latent force kernel corresponding to the
%	velocities given a design matrix of inputs.
%	 Returns:
%	  K - the kernel matrix computed at the given points.
%	 Arguments:
%	  KERN - the kernel structure for which the matrix is computed.
%	  T - input data matrix in the form of a design matrix.
%	  COVIC - covariance for the initial conditions
%
%
%	See also
%	SDLFMKERNPARAMINIT, KERNCOMPUTE, KERNCREATE, SDLFMKERNDIAGCOMPUTE

%	Copyright (c) 2010 Mauricio A. Alvarez

if nargin < 4
  covIC = t2;
  t2 = t;
end

if size(t, 2) > 1 || size(t2, 2) > 1
  error('Input can only have one column');
end

k = sdlfmXsdlfmKernCompute(kern, kern, t, t2, covIC, 'VelVel');

if nargin < 3;
  k = k + k';
  k = k*0.5;
end

k = real(k); % introduced MA 2008


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>Index (myorm 1.0-SNAPSHOT API)</title>
<meta name="date" content="2017-05-29">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

B C D E F G H I M N P R S T U V

B

BasicEntityManager - Class in fr.epsi.orm.myorm.persistence

Created by fteychene on 14/05/17.

C

changeValuesByReflection() - Static method in class fr.epsi.orm.myorm.lib.sample.Samples

Column - Annotation Type in fr.epsi.orm.myorm.annotation

Created by fteychene on 14/05/17.

create(DataSource, Set<Class<?>>) - Static method in class fr.epsi.orm.myorm.persistence.BasicEntityManager

Create a BasicEntityManager and check the persistents classes

createDatasourceAndExecuteQuery() - Static method in class fr.epsi.orm.myorm.lib.sample.Samples

D

delete(T) - Method in class fr.epsi.orm.myorm.persistence.BasicEntityManager

delete(T) - Method in interface fr.epsi.orm.myorm.persistence.EntityManager

Delete an entity from the database

E

Entity - Annotation Type in fr.epsi.orm.myorm.annotation

Created by fteychene on 14/05/17.

EntityManager - Interface in fr.epsi.orm.myorm.persistence

Created by fteychene on 14/05/17.

entityToParams(Object, Predicate<Field>...) - Static method in class fr.epsi.orm.myorm.persistence.MappingHelper

equals(Object) - Method in class fr.epsi.orm.myorm.lib.sample.User

execute() - Method in class fr.epsi.orm.myorm.lib.NamedPreparedStatement

executeQuery() - Method in class fr.epsi.orm.myorm.lib.NamedPreparedStatement

executeUpdate() - Method in class fr.epsi.orm.myorm.lib.NamedPreparedStatement

F

find(Class<T>, Object) - Method in class fr.epsi.orm.myorm.persistence.BasicEntityManager

find(Class<T>, Object) - Method in interface fr.epsi.orm.myorm.persistence.EntityManager

Find a entity in the database with its id

findAll(Class<T>) - Method in class fr.epsi.orm.myorm.persistence.BasicEntityManager

findAll(Class<T>) - Method in interface fr.epsi.orm.myorm.persistence.EntityManager

Return all the databases rows as entity for an entity class

fr.epsi.orm.myorm.annotation - package fr.epsi.orm.myorm.annotation

fr.epsi.orm.myorm.lib - package fr.epsi.orm.myorm.lib

fr.epsi.orm.myorm.lib.sample - package fr.epsi.orm.myorm.lib.sample

fr.epsi.orm.myorm.persistence - package fr.epsi.orm.myorm.persistence

G

generateDeleteSql(Class<?>) - Static method in class fr.epsi.orm.myorm.persistence.SqlGenerator

GenerationType - Enum in fr.epsi.orm.myorm.annotation

Created by fteychene on 14/05/17.

getAnnotationForClass(Class<?>, Class<T>) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

getAnnotationForField(Field, Class<T>) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

getBirthDate() - Method in class fr.epsi.orm.myorm.lib.sample.User

getByDirectAccessValue(Field, Object) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

getColumnNameForField(Field) - Static method in class fr.epsi.orm.myorm.persistence.SqlGenerator

getConnectionCount() - Method in class fr.epsi.orm.myorm.lib.sample.User

getEmail() - Method in class fr.epsi.orm.myorm.lib.sample.User

getFieldByName(Class<?>, String) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

getFieldDeclaringAnnotation(Class<?>, Class<T>) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

getFields(Class<?>, Predicate<Field>...) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

getFieldsDeclaringAnnotation(Class<?>, Class<T>) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

getFieldsWithoutTransient(Class<?>) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

getFirstName() - Method in class fr.epsi.orm.myorm.lib.sample.User

getFromResultSetByType(Class<?>, ResultSet, String) - Static method in class fr.epsi.orm.myorm.persistence.MappingHelper

getGeneratedKeys() - Method in class fr.epsi.orm.myorm.lib.NamedPreparedStatement

getId() - Method in class fr.epsi.orm.myorm.lib.sample.User

getLastName() - Method in class fr.epsi.orm.myorm.lib.sample.User

getTableForEntity(Class<?>) - Static method in class fr.epsi.orm.myorm.persistence.SqlGenerator

getValue(Field, Object) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

H

hashCode() - Method in class fr.epsi.orm.myorm.lib.sample.User

I

Id - Annotation Type in fr.epsi.orm.myorm.annotation

Created by fteychene on 14/05/17.

instanciate(Class<? extends T>) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

isFieldIdGenerated(Field) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

M

main(String[]) - Static method in class fr.epsi.orm.myorm.lib.sample.Samples

mapFromResultSet(Class<? extends T>, ResultSet) - Static method in class fr.epsi.orm.myorm.persistence.MappingHelper

MappingHelper - Class in fr.epsi.orm.myorm.persistence

Created by fteychene on 14/05/17.

MappingHelper() - Constructor for class fr.epsi.orm.myorm.persistence.MappingHelper

mapToInstance(ResultSet, Class<T>) - Static method in class fr.epsi.orm.myorm.persistence.MappingHelper

N

NamedPreparedStatement - Class in fr.epsi.orm.myorm.lib

Created by fteychene on 16/05/17.

P

parseQuery(String) - Static method in class fr.epsi.orm.myorm.lib.NamedPreparedStatement

prepare(Connection, String, int) - Static method in class fr.epsi.orm.myorm.lib.NamedPreparedStatement

prepare(Connection, String) - Static method in class fr.epsi.orm.myorm.lib.NamedPreparedStatement

R

readAnnotationAtRuntime() - Static method in class fr.epsi.orm.myorm.lib.sample.Samples

ReflectionUtil - Class in fr.epsi.orm.myorm.lib

Created by fteychene on 14/05/17.

ReflectionUtil() - Constructor for class fr.epsi.orm.myorm.lib.ReflectionUtil

S

Samples - Class in fr.epsi.orm.myorm.lib.sample

Created by fteychene on 14/05/17.

Samples() - Constructor for class fr.epsi.orm.myorm.lib.sample.Samples

save(T) - Method in class fr.epsi.orm.myorm.persistence.BasicEntityManager

save(T) - Method in interface fr.epsi.orm.myorm.persistence.EntityManager

Save an entity in the database

setBirthDate(LocalDate) - Method in class fr.epsi.orm.myorm.lib.sample.User

setConnectionCount(Integer) - Method in class fr.epsi.orm.myorm.lib.sample.User

setEmail(String) - Method in class fr.epsi.orm.myorm.lib.sample.User

setFirstName(String) - Method in class fr.epsi.orm.myorm.lib.sample.User

setId(Long) - Method in class fr.epsi.orm.myorm.lib.sample.User

setLastName(String) - Method in class fr.epsi.orm.myorm.lib.sample.User

setParameter(String, Object) - Method in class fr.epsi.orm.myorm.lib.NamedPreparedStatement

setParameters(Map<String, Object>) - Method in class fr.epsi.orm.myorm.lib.NamedPreparedStatement

setValue(Field, Object, Object) - Static method in class fr.epsi.orm.myorm.lib.ReflectionUtil

SqlGenerator - Class in fr.epsi.orm.myorm.persistence

Created by fteychene on 14/05/17.

SqlGenerator() - Constructor for class fr.epsi.orm.myorm.persistence.SqlGenerator

T

toString() - Method in class fr.epsi.orm.myorm.lib.sample.User

Transient - Annotation Type in fr.epsi.orm.myorm.annotation

Created by fteychene on 16/05/17.

U

User - Class in fr.epsi.orm.myorm.lib.sample

Created by fteychene on 14/05/17.

User() - Constructor for class fr.epsi.orm.myorm.lib.sample.User

V

valueOf(String) - Static method in enum fr.epsi.orm.myorm.annotation.GenerationType

Returns the enum constant of this type with the specified name.

values() - Static method in enum fr.epsi.orm.myorm.annotation.GenerationType

Returns an array containing the constants of this enum type, in
the order they are declared.

B C D E F G H I M N P R S T U V

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2017. All rights reserved.


text:
package fr.univnantes.termsuite.framework;

import java.util.ArrayList;
import java.util.List;

public abstract class AggregateEngine extends Engine {

	public abstract void configure();

	private List<EngineDescription> childEngineDescriptions = new ArrayList<>();

	protected EngineDescription pipe(String engineName, Class<? extends Engine> engineClass, Object... parameters) {
		EngineDescription childDesc = new EngineDescription(engineName, engineClass, parameters);
		pipelineService.registerEngineName(childDesc.getEngineName());
		childEngineDescriptions.add(childDesc);
		return childDesc;
	}

	protected EngineDescription pipe(Class<? extends Engine> engineClass, Object... parameters) {
		return pipe(engineClass.getSimpleName(), engineClass, parameters);
	}

	public List<EngineDescription> getEngineDescriptions() {
		return childEngineDescriptions;
	}
}


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>

    <parent>
        <groupId>com.mobilebits</groupId>
        <artifactId>complicode-java</artifactId>
        <version>1.01</version>
    </parent>

    <artifactId>complicode-samples</artifactId>
    <version>1.01</version>

    <dependencies>
        <dependency>
            <groupId>com.mobilebits</groupId>
            <artifactId>complicode</artifactId>
            <version>1.01</version>
        </dependency>
    </dependencies>
</project>


text:
#ifndef _MACHINE_PROC_H_
#define	_MACHINE_PROC_H_

#include <machine/globals.h>

/*
 * Machine-dependent part of the proc structure for i386.
 */
struct mdproc {
	struct trapframe *md_regs;	/* registers on current frame */
};

#endif /* !_MACHINE_PROC_H_ */


text:
package com.Da_Technomancer.crossroads.API.effects.mechArm;

import java.util.Random;
import java.util.UUID;

import com.Da_Technomancer.crossroads.Main;
import com.Da_Technomancer.crossroads.entity.EntityArmRidable;
import com.Da_Technomancer.crossroads.tileentities.technomancy.MechanicalArmTileEntity;
import com.mojang.authlib.GameProfile;

import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.common.util.FakePlayerFactory;

public class MechArmUseEffect implements IMechArmEffect{

	private static final Random ID_GEN = new Random();

	@Override
	public boolean onTriggered(World world, BlockPos pos, double posX, double posY, double posZ, EnumFacing side, EntityArmRidable ent, MechanicalArmTileEntity te){
		if(!ent.getPassengers().isEmpty() && ent.getPassengers().get(0) instanceof EntityItem){
			EntityItem itemEnt = (EntityItem) ent.getPassengers().get(0);
			ItemStack heldStack = itemEnt.getItem();
			int oldSize = heldStack.getCount();
			boolean itemBlock = heldStack.getItem() instanceof ItemBlock;
			FakePlayer user = FakePlayerFactory.get((WorldServer) world, new GameProfile(new UUID(ID_GEN.nextLong(), ID_GEN.nextLong()), Main.MODID + "-arm_use_effect-" + world.provider.getDimension()));
			user.setHeldItem(EnumHand.MAIN_HAND, heldStack);
			user.setPositionAndRotation(posX, posY, posZ, side.getHorizontalAngle(), 0);
			user.eyeHeight = 0;
			Vec3d posVec = new Vec3d(posX, posY, posZ);
			EnumActionResult result = EnumActionResult.PASS;
			if(heldStack.getItem() instanceof ItemBlock){
				//Blocks can be placed in midair by this device.
				boolean offsetPos = !world.getBlockState(pos.offset(side)).getBlock().isReplaceable(world, pos.offset(side));
				result = heldStack.onItemUse(user, world, offsetPos ? pos.offset(side) : pos, EnumHand.MAIN_HAND, side.getOpposite(), side == EnumFacing.WEST ? 1 : 0, side == EnumFacing.DOWN ? 1 : 0, side == EnumFacing.NORTH ? 1 : 0);
			}else{
				RayTraceResult trace = world.rayTraceBlocks(posVec, posVec.add(new Vec3d(side.getDirectionVec())), false, false, true);
				if(trace != null && trace.typeOfHit == RayTraceResult.Type.BLOCK){
					Vec3d hitVec = trace.hitVec.subtract(new Vec3d(trace.getBlockPos()));
					result = heldStack.onItemUse(user, world, trace.getBlockPos(), EnumHand.MAIN_HAND, trace.sideHit, (float) hitVec.x, (float) hitVec.y, (float) hitVec.z);
				}
			}
			if(result == EnumActionResult.PASS){
				ActionResult<ItemStack> actionResult = heldStack.useItemRightClick(world, user, EnumHand.MAIN_HAND);
				result = actionResult.getType();
				itemEnt.setItem(actionResult.getResult());
			}

			return result == EnumActionResult.SUCCESS && (!itemBlock || itemEnt.getItem().getCount() != oldSize);
		}
		return false;
	}
}


text:
local T = luatool:FetchWithType(current_time, level(HPLevelType.kHeight, 2), param("T-K"), current_forecast_type)
local RH = luatool:FetchWithType(current_time, level(HPLevelType.kHeight, 2), param("RH-0TO1"), current_forecast_type)
local RHscale = 100

if not RH then
  RH = luatool:FetchWithType(current_time, level(HPLevelType.kHeight, 2), param("RH-PRCNT"), current_forecast_type)
  RHscale = 1
end

if not RH or not T then
  return
end

local res = {}

for i=1, #T do
  res[i] = 1 / (1 + math.exp(22 - 2.7 * (T[i] - 273.15) - 0.2 * RH[i] * RHscale))
end

result:SetParam(param("PRECPHASE-0TO1"))
result:SetValues(res)
luatool:WriteToFile(result)


text:
import signal
import socket
import threading

try:
    from time import monotonic
except ImportError:
    from time import time as monotonic
import time

import pytest

from .socketpair_helper import socketpair
from urllib3.util.wait import (
    wait_for_read,
    wait_for_write,
    wait_for_socket,
    select_wait_for_socket,
    poll_wait_for_socket,
    _have_working_poll,
)

@pytest.fixture
def spair():
    a, b = socketpair()
    yield a, b
    a.close()
    b.close()

variants = [wait_for_socket, select_wait_for_socket]
if _have_working_poll():
    variants.append(poll_wait_for_socket)

@pytest.mark.parametrize("wfs", variants)
def test_wait_for_socket(wfs, spair):
    a, b = spair

    with pytest.raises(RuntimeError):
        wfs(a, read=False, write=False)

    assert not wfs(a, read=True, timeout=0)
    assert wfs(a, write=True, timeout=0)

    b.send(b"x")
    assert wfs(a, read=True, timeout=0)
    assert wfs(a, read=True, timeout=10)
    assert wfs(a, read=True, timeout=None)

    # Fill up the socket with data
    a.setblocking(False)
    try:
        while True:
            a.send(b"x" * 999999)
    except (OSError, socket.error):
        pass

    # Now it's not writable anymore
    assert not wfs(a, write=True, timeout=0)

    # But if we ask for read-or-write, that succeeds
    assert wfs(a, read=True, write=True, timeout=0)

    # Unless we read from it
    assert a.recv(1) == b"x"
    assert not wfs(a, read=True, write=True, timeout=0)

    # But if the remote peer closes the socket, then it becomes readable
    b.close()
    assert wfs(a, read=True, timeout=0)

    # Waiting for a socket that's actually been closed is just a bug, and
    # raises some kind of helpful exception (exact details depend on the
    # platform).
    with pytest.raises(Exception):
        wfs(b, read=True)

def test_wait_for_read_write(spair):
    a, b = spair

    assert not wait_for_read(a, 0)
    assert wait_for_write(a, 0)

    b.send(b"x")

    assert wait_for_read(a, 0)
    assert wait_for_write(a, 0)

    # Fill up the socket with data
    a.setblocking(False)
    try:
        while True:
            a.send(b"x" * 999999)
    except (OSError, socket.error):
        pass

    # Now it's not writable anymore
    assert not wait_for_write(a, 0)

@pytest.mark.skipif(not hasattr(signal, "setitimer"), reason="need setitimer() support")
@pytest.mark.parametrize("wfs", variants)
def test_eintr(wfs, spair):
    a, b = spair
    interrupt_count = [0]

    def handler(sig, frame):
        assert sig == signal.SIGALRM
        interrupt_count[0] += 1

    old_handler = signal.signal(signal.SIGALRM, handler)
    try:
        assert not wfs(a, read=True, timeout=0)
        start = monotonic()
        try:
            # Start delivering SIGALRM 10 times per second
            signal.setitimer(signal.ITIMER_REAL, 0.1, 0.1)
            # Sleep for 1 second (we hope!)
            wfs(a, read=True, timeout=1)
        finally:
            # Stop delivering SIGALRM
            signal.setitimer(signal.ITIMER_REAL, 0)
        end = monotonic()
        dur = end - start
        assert 0.9 < dur < 3
    finally:
        signal.signal(signal.SIGALRM, old_handler)

    assert interrupt_count[0] > 0

@pytest.mark.skipif(not hasattr(signal, "setitimer"), reason="need setitimer() support")
@pytest.mark.parametrize("wfs", variants)
def test_eintr_zero_timeout(wfs, spair):
    a, b = spair
    interrupt_count = [0]

    def handler(sig, frame):
        assert sig == signal.SIGALRM
        interrupt_count[0] += 1

    old_handler = signal.signal(signal.SIGALRM, handler)
    try:
        assert not wfs(a, read=True, timeout=0)
        try:
            # Start delivering SIGALRM 1000 times per second,
            # to trigger race conditions such as
            # https://github.com/urllib3/urllib3/issues/1396.
            signal.setitimer(signal.ITIMER_REAL, 0.001, 0.001)
            # Hammer the system call for a while to trigger the
            # race.
            for i in range(100000):
                wfs(a, read=True, timeout=0)
        finally:
            # Stop delivering SIGALRM
            signal.setitimer(signal.ITIMER_REAL, 0)
    finally:
        signal.signal(signal.SIGALRM, old_handler)

    assert interrupt_count[0] > 0

@pytest.mark.skipif(not hasattr(signal, "setitimer"), reason="need setitimer() support")
@pytest.mark.parametrize("wfs", variants)
def test_eintr_infinite_timeout(wfs, spair):
    a, b = spair
    interrupt_count = [0]

    def handler(sig, frame):
        assert sig == signal.SIGALRM
        interrupt_count[0] += 1

    def make_a_readable_after_one_second():
        time.sleep(1)
        b.send(b"x")

    old_handler = signal.signal(signal.SIGALRM, handler)
    try:
        assert not wfs(a, read=True, timeout=0)
        start = monotonic()
        try:
            # Start delivering SIGALRM 10 times per second
            signal.setitimer(signal.ITIMER_REAL, 0.1, 0.1)
            # Sleep for 1 second (we hope!)
            thread = threading.Thread(target=make_a_readable_after_one_second)
            thread.start()
            wfs(a, read=True)
        finally:
            # Stop delivering SIGALRM
            signal.setitimer(signal.ITIMER_REAL, 0)
            thread.join()
        end = monotonic()
        dur = end - start
        assert 0.9 < dur < 3
    finally:
        signal.signal(signal.SIGALRM, old_handler)

    assert interrupt_count[0] > 0


text:
#ifndef _CLASS_WORLDPARSEROBJ
#define _CLASS_WORLDPARSEROBJ

#include <Eigen/Dense>

#include <string>
#include <vector>

struct WorldParserObj
{
public:
	 WorldParserObj();
	~WorldParserObj();

	void CreateWorld(const std::string& /*filename*/);

private:
	void CreateObstacle (const std::string& /*line*/);

private:
	typedef std::vector<Eigen::Vector3d,Eigen::aligned_allocator<Eigen::Vector3d> > T_Vector3;

private:
	T_Vector3 points_;
	T_Vector3 normals_;
};

#endif //_CLASS_WORLDPARSEROBJ


text:
<?php

Yii::import('application.models._base.BaseDeviceGroup');

class DeviceGroup extends BaseDeviceGroup
{
    /**
     * @return DeviceGroup
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public static function label($n = 1)
    {
        return Yii::t('app', 'DeviceGroup|DeviceGroups', $n);
    }

}


text:
'use strict';

import { NgModule } from '@angular/core';

import CommonModule from './../common/common.module';

import { RoutingModuleWithProviders, routingProviders } from './routes/index';
import components from './components/index';
import directives from './directives/index';
import pipes from './pipes/index';
import services from './services/index';

export default class AboutModule {
    static get annotations() {
        return [
            new NgModule({
                imports: [
                    CommonModule,
                    RoutingModuleWithProviders
                ],
                declarations: [
                    ...components,
                    ...directives,
                    ...pipes
                ],
                providers: [
                    ...services,
                    ...routingProviders
                ]
            })
        ];
    }
};


text:
""" doc string"""

from time import sleep
from Connectors.CalConnector import CalConnector
from apiclient.errors import HttpError

class Command(object):
    """ doc string """
    def __init__(self):
        connector = CalConnector()
        credentials = connector.get_credentials()
        self.service = connector.setup(credentials)

    def delete_event(self, cal_id, event_id):
        """ Wraps either a delete or import request in an "exponential backoff,"
            I think... """
        # The Google Calendar API can take 5 requests per second, apparently. I don't know
        # how you're really supposed to implement "exponential backoff" but I think I need
        # this 'wait' value number - the seconds to wait between requests - to be greater
        # than zero - so it's divided by ten a little later...
        wait = 2.25
        while True:
            try:
                sleep(wait / 10) # waits 0.225 seconds
                # then calls the function
                self.service.events().delete(calendarId=cal_id, eventId=event_id).execute()
            except HttpError as err:
                if err.resp.status in [403, 500, 503]:
                    wait = wait * wait # If e.g. Rate Limit Exceeded, squares the wait time
                else: raise
            else: break

    def delete_events(self, cal_id, query=None):
        """ Deletes work events from all three personal calendars. """
        matching_events = []
        page_token = None
        while True:
            events_result = self.service.events().list(
                calendarId=cal_id, pageToken=page_token,
                singleEvents=True, orderBy='startTime',
                showHiddenInvitations=True, q=query
            ).execute()
            matching_events.extend(events_result.get('items'))
            page_token = events_result.get('nextPageToken')
            if not page_token:
                break
        for item in matching_events:
            try:
                wait = 2.25
                while True:
                    try:
                        sleep(wait / 10) # waits 0.225 seconds
                        # then calls the function
                        self.service.events().delete(calendarId=cal_id, eventId=item.get('id', '')).execute()
                    except HttpError as err:
                        if err.resp.status in [403, 500, 503]:
                            wait = wait * wait # If e.g. Rate Limit Exceeded, squares the wait time
                        else: raise
                    else: break
            except HttpError as err:
                if err.resp.status in [410]:
                    continue
                else:
                    raise
        return

    def import_event(self, cal_id, event):
        """ doc string """
        event.pop('id', None)
        event.pop('recurringEventId', None)
        wait = 2.25
        while True:
            try:
                sleep(wait / 10) # waits 0.225 seconds
                # then calls the function
                self.service.events().import_(calendarId=cal_id, body=event).execute()
            except HttpError as err:
                if err.resp.status in [403, 500, 503]:
                    wait = wait * wait # If e.g. Rate Limit Exceeded, squares the wait time
                else: raise
            else: break


text:
from google.cloud import artifactregistry_v1beta2

async def sample_get_project_settings():
    # Create a client
    client = artifactregistry_v1beta2.ArtifactRegistryAsyncClient()

    # Initialize request argument(s)
    request = artifactregistry_v1beta2.GetProjectSettingsRequest(
        name="name_value",
    )

    # Make the request
    response = await client.get_project_settings(request=request)

    # Handle the response
    print(response)

# [END artifactregistry_v1beta2_generated_ArtifactRegistry_GetProjectSettings_async]


text:
<meta charset="utf-8">
<title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.title }}</title>
{% if page.excerpt %}<meta name="description" content="{{ page.excerpt | strip_html }}">{% endif %}
{% if page.tags %}<meta name="keywords" content="{{ page.tags | join: ', ' }}">{% endif %}
{% if page.author %}
  {% assign author = site.data.authors[page.author] %}{% else %}{% assign author = site.owner %}
{% endif %}

{% include open-graph.html %}

{% if site.owner.google.verify %}<!-- Webmaster Tools verfication -->
<meta name="google-site-verification" content="{{ site.owner.google.verify }}">{% endif %}
{% if site.owner.bing-verify %}<meta name="msvalidate.01" content="{{ site.owner.bing-verify }}">{% endif %}

{% capture canonical %}{{ site.url }}{% if site.permalink contains '.html' %}{{ page.url }}{% else %}{{ page.url | remove:'index.html' | strip_slash }}{% endif %}{% endcapture %}
<link rel="canonical" href="{{ canonical }}">
<link href="{{ site.url }}/feed.xml" type="application/atom+xml" rel="alternate" title="{{ site.title }} Feed">
{% if site.owner.google.plus %}<link rel="author" href="https://plus.google.com/+{{ site.owner.google.plus }}?rel=author">{% endif %}

<!-- https://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- For all browsers -->
<link rel="stylesheet" href="{{ site.url }}/assets/css/main.css?v={{ site.version }}">
<!-- Webfonts -->
<script src="//use.edgefonts.net/source-sans-pro:n2,i2,n3,i3,n4,i4,n6,i6,n7,i7,n9,i9;source-code-pro:n4,n7;volkhov.js"></script>

<meta http-equiv="cleartype" content="on">

<!-- HTML5 Shiv and Media Query Support -->
<!--[if lt IE 9]>
  <script src="{{ site.url }}/assets/js/vendor/html5shiv.min.js"></script>
  <script src="{{ site.url }}/assets/js/vendor/respond.min.js"></script>
<![endif]-->

<!-- Modernizr -->
<script src="{{ site.url }}/assets/js/vendor/modernizr-2.7.1.custom.min.js"></script>

<!-- Icons -->
<link rel="apple-touch-icon" sizes="57x57" href="{{ site.url }}/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="{{ site.url }}/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="{{ site.url }}/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="{{ site.url }}/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="{{ site.url }}/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="{{ site.url }}/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="{{ site.url }}/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="{{ site.url }}/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="{{ site.url }}/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="{{ site.url }}/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="{{ site.url }}/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="{{ site.url }}/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="{{ site.url }}/favicon-16x16.png">
<link rel="manifest" href="{{ site.url }}/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">

<!-- no cache -->
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />