text:
#ifdef _WIN32
#   include <windows.h>
#endif

#include <sql.h>
#include <sqlext.h>

#include <vector>
#include <string>
#include <algorithm>

#ifndef _MSC_VER
#   define BOOST_TEST_DYN_LINK
#endif

#include <boost/test/unit_test.hpp>

#include "ignite/ignite.h"
#include "ignite/ignition.h"
#include "ignite/impl/binary/binary_utils.h"

#include "test_type.h"
#include "test_utils.h"

using namespace ignite;
using namespace ignite::cache;
using namespace ignite::cache::query;
using namespace ignite::common;

using namespace boost::unit_test;

using ignite::impl::binary::BinaryUtils;

/**
 * Test setup fixture.
 */
struct QueriesTestSuiteFixture
{
    /**
     * Establish connection to node.
     *
     * @param connectStr Connection string.
     */
    void Connect(const std::string& connectStr)
    {
        // Allocate an environment handle
        SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);

        BOOST_REQUIRE(env != NULL);

        // We want ODBC 3 support
        SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, reinterpret_cast<void*>(SQL_OV_ODBC3), 0);

        // Allocate a connection handle
        SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);

        BOOST_REQUIRE(dbc != NULL);

        // Connect string
        std::vector<SQLCHAR> connectStr0;

        connectStr0.reserve(connectStr.size() + 1);
        std::copy(connectStr.begin(), connectStr.end(), std::back_inserter(connectStr0));

        SQLCHAR outstr[ODBC_BUFFER_SIZE];
        SQLSMALLINT outstrlen;

        // Connecting to ODBC server.
        SQLRETURN ret = SQLDriverConnect(dbc, NULL, &connectStr0[0], static_cast<SQLSMALLINT>(connectStr0.size()),
            outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_COMPLETE);

        if (!SQL_SUCCEEDED(ret))
        {
            Ignition::Stop(grid.GetName(), true);

            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_DBC, dbc));
        }

        // Allocate a statement handle
        SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);

        BOOST_REQUIRE(stmt != NULL);
    }

    void Disconnect()
    {
        // Releasing statement handle.
        SQLFreeHandle(SQL_HANDLE_STMT, stmt);

        // Disconneting from the server.
        SQLDisconnect(dbc);

        // Releasing allocated handles.
        SQLFreeHandle(SQL_HANDLE_DBC, dbc);
        SQLFreeHandle(SQL_HANDLE_ENV, env);
    }

    static Ignite StartNode(const char* name, const char* config)
    {
        IgniteConfiguration cfg;

        cfg.jvmOpts.push_back("-Xdebug");
        cfg.jvmOpts.push_back("-Xnoagent");
        cfg.jvmOpts.push_back("-Djava.compiler=NONE");
        cfg.jvmOpts.push_back("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005");
        cfg.jvmOpts.push_back("-XX:+HeapDumpOnOutOfMemoryError");
        cfg.jvmOpts.push_back("-Duser.timezone=GMT");

#ifdef IGNITE_TESTS_32
        cfg.jvmInitMem = 256;
        cfg.jvmMaxMem = 768;
#else
        cfg.jvmInitMem = 1024;
        cfg.jvmMaxMem = 4096;
#endif

        char* cfgPath = getenv("IGNITE_NATIVE_TEST_ODBC_CONFIG_PATH");

        BOOST_REQUIRE(cfgPath != 0);

        cfg.springCfgPath.assign(cfgPath).append("/").append(config);

        IgniteError err;

        return Ignition::Start(cfg, name);
    }

    static Ignite StartAdditionalNode(const char* name)
    {
        return StartNode(name, "queries-test-noodbc.xml");
    }

    /**
     * Constructor.
     */
    QueriesTestSuiteFixture() : testCache(0), env(NULL), dbc(NULL), stmt(NULL)
    {
        grid = StartNode("NodeMain", "queries-test.xml");

        testCache = grid.GetCache<int64_t, TestType>("cache");
    }

    /**
     * Destructor.
     */
    ~QueriesTestSuiteFixture()
    {
        Disconnect();

        Ignition::StopAll(true);
    }

    template<typename T>
    void CheckTwoRowsInt(SQLSMALLINT type)
    {
        Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache");

        SQLRETURN ret;

        TestType in1(1, 2, 3, 4, "5", 6.0f, 7.0, true, Guid(8, 9), BinaryUtils::MakeDateGmt(1987, 6, 5),
            BinaryUtils::MakeTimestampGmt(1998, 12, 27, 1, 2, 3, 456));

        TestType in2(8, 7, 6, 5, "4", 3.0f, 2.0, false, Guid(1, 0), BinaryUtils::MakeDateGmt(1976, 1, 12),
            BinaryUtils::MakeTimestampGmt(1978, 8, 21, 23, 13, 45, 456));

        testCache.Put(1, in1);
        testCache.Put(2, in2);

        const size_t columnsCnt = 11;

        T columns[columnsCnt] = { 0 };

        // Binding columns.
        for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
        {
            ret = SQLBindCol(stmt, i + 1, type, &columns[i], sizeof(columns[i]), 0);

            if (!SQL_SUCCEEDED(ret))
                BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
        }

        char request[] = "SELECT i8Field, i16Field, i32Field, i64Field, strField, "
            "floatField, doubleField, boolField, guidField, dateField, timestampField FROM TestType";

        ret = SQLExecDirect(stmt, reinterpret_cast<SQLCHAR*>(request), SQL_NTS);
        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

        ret = SQLFetch(stmt);

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

        BOOST_CHECK_EQUAL(columns[0], 1);
        BOOST_CHECK_EQUAL(columns[1], 2);
        BOOST_CHECK_EQUAL(columns[2], 3);
        BOOST_CHECK_EQUAL(columns[3], 4);
        BOOST_CHECK_EQUAL(columns[4], 5);
        BOOST_CHECK_EQUAL(columns[5], 6);
        BOOST_CHECK_EQUAL(columns[6], 7);
        BOOST_CHECK_EQUAL(columns[7], 1);
        BOOST_CHECK_EQUAL(columns[8], 0);
        BOOST_CHECK_EQUAL(columns[9], 0);
        BOOST_CHECK_EQUAL(columns[10], 0);

        SQLLEN columnLens[columnsCnt] = { 0 };

        // Binding columns.
        for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
        {
            ret = SQLBindCol(stmt, i + 1, type, &columns[i], sizeof(columns[i]), &columnLens[i]);

            if (!SQL_SUCCEEDED(ret))
                BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
        }

        ret = SQLFetch(stmt);
        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

        BOOST_CHECK_EQUAL(columns[0], 8);
        BOOST_CHECK_EQUAL(columns[1], 7);
        BOOST_CHECK_EQUAL(columns[2], 6);
        BOOST_CHECK_EQUAL(columns[3], 5);
        BOOST_CHECK_EQUAL(columns[4], 4);
        BOOST_CHECK_EQUAL(columns[5], 3);
        BOOST_CHECK_EQUAL(columns[6], 2);
        BOOST_CHECK_EQUAL(columns[7], 0);
        BOOST_CHECK_EQUAL(columns[8], 0);
        BOOST_CHECK_EQUAL(columns[9], 0);
        BOOST_CHECK_EQUAL(columns[10], 0);

        BOOST_CHECK_EQUAL(columnLens[0], static_cast<SQLLEN>(sizeof(T)));
        BOOST_CHECK_EQUAL(columnLens[1], static_cast<SQLLEN>(sizeof(T)));
        BOOST_CHECK_EQUAL(columnLens[2], static_cast<SQLLEN>(sizeof(T)));
        BOOST_CHECK_EQUAL(columnLens[3], static_cast<SQLLEN>(sizeof(T)));
        BOOST_CHECK_EQUAL(columnLens[4], static_cast<SQLLEN>(sizeof(T)));
        BOOST_CHECK_EQUAL(columnLens[5], static_cast<SQLLEN>(sizeof(T)));
        BOOST_CHECK_EQUAL(columnLens[6], static_cast<SQLLEN>(sizeof(T)));
        BOOST_CHECK_EQUAL(columnLens[7], static_cast<SQLLEN>(sizeof(T)));
        BOOST_CHECK_EQUAL(columnLens[8], SQL_NO_TOTAL);
        BOOST_CHECK_EQUAL(columnLens[9], SQL_NO_TOTAL);
        BOOST_CHECK_EQUAL(columnLens[10], SQL_NO_TOTAL);

        ret = SQLFetch(stmt);
        BOOST_CHECK(ret == SQL_NO_DATA);
    }

    int CountRows(SQLHSTMT stmt)
    {
        int res = 0;

        SQLRETURN ret = SQL_SUCCESS;

        while (ret == SQL_SUCCESS)
        {
            ret = SQLFetch(stmt);

            if (ret == SQL_NO_DATA)
                break;

            if (!SQL_SUCCEEDED(ret))
                BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

            ++res;
        }

        return res;
    }

    /** Node started during the test. */
    Ignite grid;

    /** Test cache instance. */
    Cache<int64_t, TestType> testCache;

    /** ODBC Environment. */
    SQLHENV env;

    /** ODBC Connect. */
    SQLHDBC dbc;

    /** ODBC Statement. */
    SQLHSTMT stmt;
};

BOOST_FIXTURE_TEST_SUITE(QueriesTestSuite, QueriesTestSuiteFixture)

BOOST_AUTO_TEST_CASE(TestLegacyConnection)
{
    Connect("DRIVER={Apache Ignite};SERVER=127.0.0.1;PORT=11110;CACHE=cache");
}

BOOST_AUTO_TEST_CASE(TestConnectionProtocolVersion_1_6_0)
{
    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache;PROTOCOL_VERSION=1.6.0");
}

BOOST_AUTO_TEST_CASE(TestConnectionProtocolVersion_1_8_0)
{
    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache;PROTOCOL_VERSION=1.8.0");
}

BOOST_AUTO_TEST_CASE(TestTwoRowsInt8)
{
    CheckTwoRowsInt<signed char>(SQL_C_STINYINT);
}

BOOST_AUTO_TEST_CASE(TestTwoRowsUint8)
{
    CheckTwoRowsInt<unsigned char>(SQL_C_UTINYINT);
}

BOOST_AUTO_TEST_CASE(TestTwoRowsInt16)
{
    CheckTwoRowsInt<signed short>(SQL_C_SSHORT);
}

BOOST_AUTO_TEST_CASE(TestTwoRowsUint16)
{
    CheckTwoRowsInt<unsigned short>(SQL_C_USHORT);
}

BOOST_AUTO_TEST_CASE(TestTwoRowsInt32)
{
    CheckTwoRowsInt<signed long>(SQL_C_SLONG);
}

BOOST_AUTO_TEST_CASE(TestTwoRowsUint32)
{
    CheckTwoRowsInt<unsigned long>(SQL_C_ULONG);
}

BOOST_AUTO_TEST_CASE(TestTwoRowsInt64)
{
    CheckTwoRowsInt<int64_t>(SQL_C_SBIGINT);
}

BOOST_AUTO_TEST_CASE(TestTwoRowsUint64)
{
    CheckTwoRowsInt<uint64_t>(SQL_C_UBIGINT);
}

BOOST_AUTO_TEST_CASE(TestTwoRowsString)
{
    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache");

    SQLRETURN ret;

    TestType in1(1, 2, 3, 4, "5", 6.0f, 7.0, true, Guid(8, 9), BinaryUtils::MakeDateGmt(1987, 6, 5),
        BinaryUtils::MakeTimestampGmt(1998, 12, 27, 1, 2, 3, 456));

    TestType in2(8, 7, 6, 5, "4", 3.0f, 2.0, false, Guid(1, 0), BinaryUtils::MakeDateGmt(1976, 1, 12),
        BinaryUtils::MakeTimestampGmt(1978, 8, 21, 23, 13, 45, 999999999));

    testCache.Put(1, in1);
    testCache.Put(2, in2);

    const size_t columnsCnt = 11;

    SQLCHAR columns[columnsCnt][ODBC_BUFFER_SIZE] = { 0 };

    // Binding columns.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
    {
        ret = SQLBindCol(stmt, i + 1, SQL_C_CHAR, &columns[i], ODBC_BUFFER_SIZE, 0);

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
    }

    SQLCHAR request[] = "SELECT i8Field, i16Field, i32Field, i64Field, strField, "
        "floatField, doubleField, boolField, guidField, dateField, timestampField FROM TestType";

    ret = SQLExecDirect(stmt, request, SQL_NTS);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLFetch(stmt);

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[0])), "1");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[1])), "2");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[2])), "3");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[3])), "4");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[4])), "5");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[5])), "6");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[6])), "7");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[7])), "1");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[8])), "00000000-0000-0008-0000-000000000009");
    // Such format is used because Date returned as Timestamp.
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[9])), "1987-06-05 00:00:00");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[10])), "1998-12-27 01:02:03");

    SQLLEN columnLens[columnsCnt] = { 0 };

    // Binding columns.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
    {
        ret = SQLBindCol(stmt, i + 1, SQL_C_CHAR, &columns[i], ODBC_BUFFER_SIZE, &columnLens[i]);

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
    }

    ret = SQLFetch(stmt);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[0])), "8");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[1])), "7");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[2])), "6");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[3])), "5");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[4])), "4");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[5])), "3");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[6])), "2");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[7])), "0");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[8])), "00000000-0000-0001-0000-000000000000");
    // Such format is used because Date returned as Timestamp.
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[9])), "1976-01-12 00:00:00");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[10])), "1978-08-21 23:13:45");

    BOOST_CHECK_EQUAL(columnLens[0], 1);
    BOOST_CHECK_EQUAL(columnLens[1], 1);
    BOOST_CHECK_EQUAL(columnLens[2], 1);
    BOOST_CHECK_EQUAL(columnLens[3], 1);
    BOOST_CHECK_EQUAL(columnLens[4], 1);
    BOOST_CHECK_EQUAL(columnLens[5], 1);
    BOOST_CHECK_EQUAL(columnLens[6], 1);
    BOOST_CHECK_EQUAL(columnLens[7], 1);
    BOOST_CHECK_EQUAL(columnLens[8], 36);
    BOOST_CHECK_EQUAL(columnLens[9], 19);
    BOOST_CHECK_EQUAL(columnLens[10], 19);

    ret = SQLFetch(stmt);
    BOOST_CHECK(ret == SQL_NO_DATA);
}

BOOST_AUTO_TEST_CASE(TestOneRowString)
{
    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache");

    SQLRETURN ret;

    TestType in(1, 2, 3, 4, "5", 6.0f, 7.0, true, Guid(8, 9), BinaryUtils::MakeDateGmt(1987, 6, 5),
        BinaryUtils::MakeTimestampGmt(1998, 12, 27, 1, 2, 3, 456));

    testCache.Put(1, in);

    const size_t columnsCnt = 11;

    SQLCHAR columns[columnsCnt][ODBC_BUFFER_SIZE] = { 0 };

    SQLLEN columnLens[columnsCnt] = { 0 };

    // Binding columns.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
    {
        ret = SQLBindCol(stmt, i + 1, SQL_C_CHAR, &columns[i], ODBC_BUFFER_SIZE, &columnLens[i]);

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
    }

    SQLCHAR request[] = "SELECT i8Field, i16Field, i32Field, i64Field, strField, "
        "floatField, doubleField, boolField, guidField, dateField, timestampField FROM TestType";

    ret = SQLExecDirect(stmt, request, SQL_NTS);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLFetch(stmt);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[0])), "1");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[1])), "2");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[2])), "3");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[3])), "4");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[4])), "5");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[5])), "6");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[6])), "7");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[7])), "1");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[8])), "00000000-0000-0008-0000-000000000009");
    // Such format is used because Date returned as Timestamp.
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[9])), "1987-06-05 00:00:00");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[10])), "1998-12-27 01:02:03");

    BOOST_CHECK_EQUAL(columnLens[0], 1);
    BOOST_CHECK_EQUAL(columnLens[1], 1);
    BOOST_CHECK_EQUAL(columnLens[2], 1);
    BOOST_CHECK_EQUAL(columnLens[3], 1);
    BOOST_CHECK_EQUAL(columnLens[4], 1);
    BOOST_CHECK_EQUAL(columnLens[5], 1);
    BOOST_CHECK_EQUAL(columnLens[6], 1);
    BOOST_CHECK_EQUAL(columnLens[7], 1);
    BOOST_CHECK_EQUAL(columnLens[8], 36);
    BOOST_CHECK_EQUAL(columnLens[9], 19);
    BOOST_CHECK_EQUAL(columnLens[10], 19);

    ret = SQLFetch(stmt);
    BOOST_CHECK(ret == SQL_NO_DATA);
}

BOOST_AUTO_TEST_CASE(TestOneRowStringLen)
{
    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache");

    SQLRETURN ret;

    TestType in(1, 2, 3, 4, "5", 6.0f, 7.0, true, Guid(8, 9), BinaryUtils::MakeDateGmt(1987, 6, 5),
        BinaryUtils::MakeTimestampGmt(1998, 12, 27, 1, 2, 3, 456));

    testCache.Put(1, in);

    const size_t columnsCnt = 11;

    SQLLEN columnLens[columnsCnt] = { 0 };

    // Binding columns.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
    {
        ret = SQLBindCol(stmt, i + 1, SQL_C_CHAR, 0, 0, &columnLens[i]);

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
    }

    SQLCHAR request[] = "SELECT i8Field, i16Field, i32Field, i64Field, strField, "
        "floatField, doubleField, boolField, guidField, dateField, timestampField FROM TestType";

    ret = SQLExecDirect(stmt, request, SQL_NTS);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLFetch(stmt);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    BOOST_CHECK_EQUAL(columnLens[0], 1);
    BOOST_CHECK_EQUAL(columnLens[1], 1);
    BOOST_CHECK_EQUAL(columnLens[2], 1);
    BOOST_CHECK_EQUAL(columnLens[3], 1);
    BOOST_CHECK_EQUAL(columnLens[4], 1);
    BOOST_CHECK_EQUAL(columnLens[5], 1);
    BOOST_CHECK_EQUAL(columnLens[6], 1);
    BOOST_CHECK_EQUAL(columnLens[7], 1);
    BOOST_CHECK_EQUAL(columnLens[8], 36);
    BOOST_CHECK_EQUAL(columnLens[9], 19);
    BOOST_CHECK_EQUAL(columnLens[10], 19);

    ret = SQLFetch(stmt);
    BOOST_CHECK(ret == SQL_NO_DATA);
}

BOOST_AUTO_TEST_CASE(TestDataAtExecution)
{
    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache");

    SQLRETURN ret;

    TestType in1(1, 2, 3, 4, "5", 6.0f, 7.0, true, Guid(8, 9), BinaryUtils::MakeDateGmt(1987, 6, 5),
        BinaryUtils::MakeTimestampGmt(1998, 12, 27, 1, 2, 3, 456));

    TestType in2(8, 7, 6, 5, "4", 3.0f, 2.0, false, Guid(1, 0), BinaryUtils::MakeDateGmt(1976, 1, 12),
        BinaryUtils::MakeTimestampGmt(1978, 8, 21, 23, 13, 45, 999999999));

    testCache.Put(1, in1);
    testCache.Put(2, in2);

    const size_t columnsCnt = 11;

    SQLLEN columnLens[columnsCnt] = { 0 };
    SQLCHAR columns[columnsCnt][ODBC_BUFFER_SIZE] = { 0 };

    // Binding columns.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
    {
        ret = SQLBindCol(stmt, i + 1, SQL_C_CHAR, &columns[i], ODBC_BUFFER_SIZE, &columnLens[i]);

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
    }

    SQLCHAR request[] = "SELECT i8Field, i16Field, i32Field, i64Field, strField, "
        "floatField, doubleField, boolField, guidField, dateField, timestampField FROM TestType "
        "WHERE i32Field = ? AND strField = ?";

    ret = SQLPrepare(stmt, request, SQL_NTS);

    SQLLEN ind1 = 1;
    SQLLEN ind2 = 2;

    SQLLEN len1 = SQL_DATA_AT_EXEC;
    SQLLEN len2 = SQL_LEN_DATA_AT_EXEC(static_cast<SQLLEN>(in1.strField.size()));

    ret = SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 100, 100, &ind1, sizeof(ind1), &len1);

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 100, 100, &ind2, sizeof(ind2), &len2);

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLExecute(stmt);

    BOOST_REQUIRE_EQUAL(ret, SQL_NEED_DATA);

    void* oind;

    ret = SQLParamData(stmt, &oind);

    BOOST_REQUIRE_EQUAL(ret, SQL_NEED_DATA);

    if (oind == &ind1)
        ret = SQLPutData(stmt, &in1.i32Field, 0);
    else if (oind == &ind2)
        ret = SQLPutData(stmt, (SQLPOINTER)in1.strField.c_str(), (SQLLEN)in1.strField.size());
    else
        BOOST_FAIL("Unknown indicator value");

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLParamData(stmt, &oind);

    BOOST_REQUIRE_EQUAL(ret, SQL_NEED_DATA);

    if (oind == &ind1)
        ret = SQLPutData(stmt, &in1.i32Field, 0);
    else if (oind == &ind2)
        ret = SQLPutData(stmt, (SQLPOINTER)in1.strField.c_str(), (SQLLEN)in1.strField.size());
    else
        BOOST_FAIL("Unknown indicator value");

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLParamData(stmt, &oind);

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLFetch(stmt);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[0])), "1");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[1])), "2");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[2])), "3");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[3])), "4");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[4])), "5");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[5])), "6");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[6])), "7");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[7])), "1");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[8])), "00000000-0000-0008-0000-000000000009");
    // Such format is used because Date returned as Timestamp.
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[9])), "1987-06-05 00:00:00");
    BOOST_CHECK_EQUAL(std::string(reinterpret_cast<char*>(columns[10])), "1998-12-27 01:02:03");

    BOOST_CHECK_EQUAL(columnLens[0], 1);
    BOOST_CHECK_EQUAL(columnLens[1], 1);
    BOOST_CHECK_EQUAL(columnLens[2], 1);
    BOOST_CHECK_EQUAL(columnLens[3], 1);
    BOOST_CHECK_EQUAL(columnLens[4], 1);
    BOOST_CHECK_EQUAL(columnLens[5], 1);
    BOOST_CHECK_EQUAL(columnLens[6], 1);
    BOOST_CHECK_EQUAL(columnLens[7], 1);
    BOOST_CHECK_EQUAL(columnLens[8], 36);
    BOOST_CHECK_EQUAL(columnLens[9], 19);
    BOOST_CHECK_EQUAL(columnLens[10], 19);

    ret = SQLFetch(stmt);
    BOOST_CHECK(ret == SQL_NO_DATA);
}

BOOST_AUTO_TEST_CASE(TestNullFields)
{
    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache");

    SQLRETURN ret;

    TestType in(1, 2, 3, 4, "5", 6.0f, 7.0, true, Guid(8, 9), BinaryUtils::MakeDateGmt(1987, 6, 5),
        BinaryUtils::MakeTimestampGmt(1998, 12, 27, 1, 2, 3, 456));

    TestType inNull;

    inNull.allNulls = true;

    testCache.Put(1, in);
    testCache.Put(2, inNull);
    testCache.Put(3, in);

    const size_t columnsCnt = 10;

    SQLLEN columnLens[columnsCnt] = { 0 };

    int8_t i8Column;
    int16_t i16Column;
    int32_t i32Column;
    int64_t i64Column;
    char strColumn[ODBC_BUFFER_SIZE];
    float floatColumn;
    double doubleColumn;
    bool boolColumn;
    SQL_DATE_STRUCT dateColumn;
    SQL_TIMESTAMP_STRUCT timestampColumn;

    // Binding columns.
    ret = SQLBindCol(stmt, 1, SQL_C_STINYINT, &i8Column, 0, &columnLens[0]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindCol(stmt, 2, SQL_C_SSHORT, &i16Column, 0, &columnLens[1]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindCol(stmt, 3, SQL_C_SLONG, &i32Column, 0, &columnLens[2]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindCol(stmt, 4, SQL_C_SBIGINT, &i64Column, 0, &columnLens[3]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindCol(stmt, 5, SQL_C_CHAR, &strColumn, ODBC_BUFFER_SIZE, &columnLens[4]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindCol(stmt, 6, SQL_C_FLOAT, &floatColumn, 0, &columnLens[5]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindCol(stmt, 7, SQL_C_DOUBLE, &doubleColumn, 0, &columnLens[6]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindCol(stmt, 8, SQL_C_BIT, &boolColumn, 0, &columnLens[7]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindCol(stmt, 9, SQL_C_DATE, &dateColumn, 0, &columnLens[8]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    ret = SQLBindCol(stmt, 10, SQL_C_TIMESTAMP, &timestampColumn, 0, &columnLens[9]);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    SQLCHAR request[] = "SELECT i8Field, i16Field, i32Field, i64Field, strField, "
        "floatField, doubleField, boolField, dateField, timestampField FROM TestType ORDER BY _key";

    ret = SQLExecDirect(stmt, request, SQL_NTS);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    // Fetching the first non-null row.
    ret = SQLFetch(stmt);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    // Checking that columns are not null.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
        BOOST_CHECK_NE(columnLens[i], SQL_NULL_DATA);

    // Fetching null row.
    ret = SQLFetch(stmt);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    // Checking that columns are null.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
        BOOST_CHECK_EQUAL(columnLens[i], SQL_NULL_DATA);

    // Fetching the last non-null row.
    ret = SQLFetch(stmt);
    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    // Checking that columns are not null.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
        BOOST_CHECK_NE(columnLens[i], SQL_NULL_DATA);

    ret = SQLFetch(stmt);
    BOOST_CHECK(ret == SQL_NO_DATA);
}

BOOST_AUTO_TEST_CASE(TestDistributedJoins)
{
    // Starting additional node.
    Ignite node1 = StartAdditionalNode("Node1");
    Ignite node2 = StartAdditionalNode("Node2");

    const int entriesNum = 1000;

    // Filling cache with data.
    for (int i = 0; i < entriesNum; ++i)
    {
        TestType entry;

        entry.i32Field = i;
        entry.i64Field = entriesNum - i - 1;

        testCache.Put(i, entry);
    }

    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache");

    SQLRETURN ret;

    const size_t columnsCnt = 2;

    SQLBIGINT columns[columnsCnt] = { 0 };

    // Binding colums.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
    {
        ret = SQLBindCol(stmt, i + 1, SQL_C_SLONG, &columns[i], 0, 0);

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
    }

    SQLCHAR request[] =
        "SELECT T0.i32Field, T1.i64Field FROM TestType AS T0 "
        "INNER JOIN TestType AS T1 "
        "ON (T0.i32Field = T1.i64Field)";

    ret = SQLExecDirect(stmt, request, SQL_NTS);

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    int rowsNum = CountRows(stmt);

    BOOST_CHECK_GT(rowsNum, 0);
    BOOST_CHECK_LT(rowsNum, entriesNum);

    Disconnect();

    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache;DISTRIBUTED_JOINS=true;");

    // Binding colums.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
    {
        ret = SQLBindCol(stmt, i + 1, SQL_C_SLONG, &columns[i], 0, 0);

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
    }

    ret = SQLExecDirect(stmt, request, SQL_NTS);

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    rowsNum = CountRows(stmt);

    BOOST_CHECK_EQUAL(rowsNum, entriesNum);
}

BOOST_AUTO_TEST_CASE(TestDistributedJoinsWithOldVersion)
{
    // Starting additional node.
    Ignite node1 = StartAdditionalNode("Node1");
    Ignite node2 = StartAdditionalNode("Node2");

    const int entriesNum = 1000;

    // Filling cache with data.
    for (int i = 0; i < entriesNum; ++i)
    {
        TestType entry;

        entry.i32Field = i;
        entry.i64Field = entriesNum - i - 1;

        testCache.Put(i, entry);
    }

    Connect("DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache;DISTRIBUTED_JOINS=true;PROTOCOL_VERSION=1.6.0");

    SQLRETURN ret;

    const size_t columnsCnt = 2;

    SQLBIGINT columns[columnsCnt] = { 0 };

    // Binding colums.
    for (SQLSMALLINT i = 0; i < columnsCnt; ++i)
    {
        ret = SQLBindCol(stmt, i + 1, SQL_C_SLONG, &columns[i], 0, 0);

        if (!SQL_SUCCEEDED(ret))
            BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
    }

    SQLCHAR request[] =
        "SELECT T0.i32Field, T1.i64Field FROM TestType AS T0 "
        "INNER JOIN TestType AS T1 "
        "ON (T0.i32Field = T1.i64Field)";

    ret = SQLExecDirect(stmt, request, SQL_NTS);

    if (!SQL_SUCCEEDED(ret))
        BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));

    int rowsNum = CountRows(stmt);

    BOOST_CHECK_GT(rowsNum, 0);
    BOOST_CHECK_LT(rowsNum, entriesNum);
}

BOOST_AUTO_TEST_SUITE_END()


text:
package sprinklerConfig;

# Dark Sky API Key and location
$apiKey = "ENTER YOUR API KEY HERE";
$weatherLatitude = "ENTER YOUR LATITUDE HERE";
$weatherLongitude = "ENTER YOUR LONGITUDE HERE";

# number of zones and minutes to run per zone (up to 4x to avoid run off)
# these should match
$numberZones = 8;
@minutesToRunPerZone = (10,10,10,10,10,5,5,5);

# wait time between turning off a zone to turing on the next
$secondsDelayBetweenZones = 1;

# base URL for the OS Pi app
$baseUrl = "http://10.1.1.180/";

# Temperature above which sprinklers run at night to cool off
$coolDownThreshold = 88;

1;

redpajama_set_name: RedPajamaGithub


text:
using System.IO;
using NMocha;

namespace NMock2.Matchers {
    /// <summary>
    /// Matcher for indexer getters. Checks that the arguments passed to the indexer match.
    /// </summary>
    public class IndexGetterArgumentsMatcher : ArgumentsMatcher {
        /// <summary>
        /// Initializes a new instance of the <see cref="IndexGetterArgumentsMatcher"/> class.
        /// </summary>
        /// <param name="valueMatchers">The value matchers. This is an ordered list of matchers, each matching a single method argument.</param>
        public IndexGetterArgumentsMatcher(params Matcher[] valueMatchers) : base(valueMatchers) {
        }

        /// <summary>
        /// Describes this object.
        /// </summary>
        /// <param name="description"></param>
        public override void DescribeOn(IDescription description) {
            description.AppendText("[");
            WriteListOfMatchers(MatcherCount(), description);
            description.AppendText("]");
        }
    }
}


text:
from app import app, auth
from app.core.auth.models import User
from app.core.api.templates import APITemplate
from app.modules.ticketing.models import Ticket, TicketResponse
from .models import Monitor, MonitorResponse, Device, Region, State
from flask import Blueprint, g, jsonify, abort, url_for, request
from sqlalchemy import inspect
import datetime

template = APITemplate()
module = Blueprint('monitoring', __name__)

@module.route('/<int:id>', methods=['GET'])
@auth.login_required
def get(id):
    template.model = Monitor
    return template.get(id)

@module.route('/', methods=['GET'])
@module.route('/list', methods=['GET'])
@auth.login_required
def get_list():
    template.model = Monitor
    return template.get_list()

app.register_blueprint(module, url_prefix='/monitoring')


text: .. include:: CHANGES


text:
<?php

namespace Etu\Module\CumulBundle\Controller;

use Doctrine\ORM\EntityManager;
use Etu\Core\CoreBundle\Framework\Definition\Controller;
use Etu\Core\UserBundle\Entity\Course;
use Etu\Core\UserBundle\Entity\User;
use Etu\Core\UserBundle\Schedule\Helper\ScheduleBuilder;
use Etu\Module\CumulBundle\Schedule\ScheduleComparator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
// Import annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class MainController extends Controller
{
    /**
     * @Route("/cumul", name="cumul_index")
     * @Template()
     */
    public function indexAction()
    {
        $this->denyAccessUnlessGranted('ROLE_CUMUL');

        /** @var $em EntityManager */
        $em = $this->getDoctrine()->getManager();

        /*
         * Parse the request, find users, remove invalid logins and find courses
         */
        $logins = (isset($_GET['q']) && !empty($_GET['q'])) ? explode(':', $_GET['q']) : [];

        if (empty($logins)) {
            return $this->redirect($this->generateUrl('cumul_index').'?q='.$this->getUser()->getLogin());
        }

        $qb = $em->createQueryBuilder();

        /** @var User[] $users */
        $users = $qb->select('u')
            ->from('EtuUserBundle:User', 'u')
            ->where($qb->expr()->in('u.login', $logins))
            ->getQuery()
            ->getResult();

        if (count($logins) != count($users)) {
            $found = [];

            foreach ($users as $user) {
                $found[] = $user->getLogin();
            }

            $this->get('session')->getFlashBag()->set('message', [
                'type' => 'error',
                'message' => $this->get('translator')->transChoice(
                        'cumul.main.errors.invalid_logins',
                        count(array_diff($logins, $found)),
                        ['%items%' => implode('", "', array_diff($logins, $found))]
                    ),
            ]);

            return $this->redirect($this->generateUrl('cumul_index').'?q='.implode(':', $found));
        }

        $usersIds = [];

        foreach ($users as $user) {
            $usersIds[] = $user->getId();
        }

        /** @var $courses Course[] */
        $courses = $em->createQueryBuilder()
            ->select('c, u')
            ->from('EtuUserBundle:Course', 'c')
            ->leftJoin('c.user', 'u')
            ->where($qb->expr()->in('u.id', $usersIds))
            ->getQuery()
            ->getResult();

        /*
         * Generate add URLs
         */
        $qb = $em->createQueryBuilder();

        $branchsUsers = $qb->select('u.login, u.branch, u.niveau')
            ->from('EtuUserBundle:User', 'u')
            ->where($qb->expr()->in('u.branch', array_values(User::$branches)))
            ->orderBy('u.branch', 'ASC')
            ->addOrderBy('u.niveau', 'ASC')
            ->getQuery()
            ->getScalarResult();

        $addBranchs = [];

        foreach ($branchsUsers as $branchsUser) {
            $branch = $branchsUser['branch'];

            if (empty($branch)) {
                continue;
            }

            if (!isset($addBranchs[$branch]['all'])) {
                $addBranchs[$branch]['all'] = $logins;
            }

            if (!isset($addBranchs[$branch][$branchsUser['niveau']])) {
                $addBranchs[$branch][$branchsUser['niveau']] = $logins;
            }

            $addBranchs[$branch]['all'][] = $branchsUser['login'];
            $addBranchs[$branch][$branchsUser['niveau']][] = $branchsUser['login'];
        }

        /*
         * Generate remove URLs
         */
        // Logins
        $removeUrlsLogins = [];

        foreach ($logins as $login) {
            $others = $logins;
            unset($others[array_search($login, $logins)]);
            $removeUrlsLogins[$login] = $others;
        }

        // Branchs
        $branchs = [];
        $removeUrlsBranchs = [];

        foreach ($users as $user) {
            $branchs[$user->getBranch()][] = $user->getLogin();
        }

        foreach ($branchs as $branch => $l) {
            if (empty($branch)) {
                $branch = $this->get('translator')->trans('cumul.main.index.other');
            }

            $others = $branchs;
            unset($others[$branch]);

            $removeUrlsBranchs[$branch] = [];

            foreach ($others as $branchLogins) {
                foreach ($branchLogins as $branchLogin) {
                    $removeUrlsBranchs[$branch][] = $branchLogin;
                }
            }
        }

        unset($users);

        /*
         * Compare schedules
         */
        /** @var $builders ScheduleBuilder[] */
        $builders = [];

        /** @var $users User[] */
        $users = [];

        foreach ($courses as $course) {
            if (!isset($builders[$course->getUser()->getLogin()])) {
                $builders[$course->getUser()->getLogin()] = new ScheduleBuilder();
            }

            $builders[$course->getUser()->getLogin()]->addCourse($course);
            $users[$course->getUser()->getLogin()] = $course->getUser();
        }

        foreach ($logins as $login) {
            if (!isset($users[$login])) {
                $builders[$login] = new ScheduleBuilder();
                $users[$login] = $em->getRepository('EtuUserBundle:User')->findOneByLogin($login);
            }
        }

        $comparator = new ScheduleComparator($builders);

        return [
            'comparating' => true,
            'courses' => $courses,
            'comparison' => $comparator->compare(),
            'users' => $users,
            'countUsers' => count($users),
            'colSize' => round(14 / count($users), 2),
            'logins' => json_encode($logins),
            'addBranchs' => $addBranchs,
            'removeUrlsLogins' => $removeUrlsLogins,
            'removeUrlsBranchs' => $removeUrlsBranchs,
        ];
    }

    /**
     * @Route("/import/{type}", name="cumul_import")
     * @Template()
     *
     * @param mixed $type
     */
    public function importAction(Request $request, $type)
    {
        $this->denyAccessUnlessGranted('ROLE_CUMUL');

        $post = $request->request;
        $files = $request->files;

        $logins = [];

        /** @var EntityManager $em */
        $em = $this->getDoctrine()->getManager();

        if ($type == 'file') {
            /*
             * File import
             */

            // Data
            $data = file_get_contents($files->get('import-file')->getPathname());

            // Data type
            $dataType = $post->get('import-data-type');

            if (!in_array($dataType, ['fullName', 'login', 'studentId'])) {
                $dataType = 'fullName';
            }

            // Separator
            $separator = "\n";

            if ($post->get('separator-textarea') != 'new-line' && mb_strlen($post->get('separator-char')) >= 1) {
                $separator = $post->get('separator-char');
            }

            $dataItems = array_map('trim', explode($separator, $data));
        } else {
            /*
             * Textarea import
             */

            // Data
            $data = $post->get('import-textarea');

            // Data type
            $dataType = $post->get('import-data-type');

            if (!in_array($dataType, ['fullName', 'login', 'studentId'])) {
                $dataType = 'fullName';
            }

            // Separator
            $separator = "\n";

            if ($post->get('separator-textarea') != 'new-line' && mb_strlen($post->get('separator-char')) >= 1) {
                $separator = $post->get('separator-char');
            }

            $dataItems = array_map('trim', explode($separator, $data));
        }

        $qb = $em->createQueryBuilder();

        /** @var User[] $users */
        $users = $qb->select('u')
            ->from('EtuUserBundle:User', 'u')
            ->where($qb->expr()->in('u.'.$dataType, $dataItems))
            ->getQuery()
            ->getResult();

        if (count($dataItems) > count($users)) {
            $dbItems = [];

            foreach ($users as $user) {
                if ($dataType == 'fullName') {
                    $dbItems[] = $user->getFullName();
                } elseif ($dataType == 'studentId') {
                    $dbItems[] = $user->getStudentId();
                } else {
                    $dbItems[] = $user->getLogin();
                }
            }

            $errorType = 'cumul.main.errors.invalid_logins';

            if ($dataType == 'fullName') {
                $errorType = 'cumul.main.errors.invalid_names';
            } elseif ($dataType == 'studentId') {
                $errorType = 'cumul.main.errors.invalid_ids';
            }

            $this->get('session')->getFlashBag()->set('message', [
                'type' => 'error',
                'message' => $this->get('translator')->transChoice(
                        $errorType,
                        count(array_diff($dataItems, $dbItems)),
                        ['%items%' => implode('", "', array_diff($dataItems, $dbItems))]
                    ),
            ]);
        }

        foreach ($users as $user) {
            $logins[] = $user->getLogin();
        }

        return $this->redirect($this->generateUrl('cumul_index').'?q='.implode(':', $logins));
    }
}


text:
using FluentAssertions;
using NUnit.Framework;

namespace Nest.Tests.Unit.QueryParsers.Queries
{
	[TestFixture]
	public class NestedQueryTests : ParseQueryTestsBase
	{
		[Test]
		public void Nested_Deserializes()
		{
			var q = this.SerializeThenDeserialize(
				f=>f.Nested,
				f=>f.Nested(nq=>nq
					.Path(p=>p.NestedFollowers)
					.Query(qq=>Query1)
					.Score(NestedScore.Max)
					)
				);
			q.Score.Should().Be(NestedScore.Max);
			q.Path.Should().Be("nestedFollowers");
			AssertIsTermQuery(q.Query, Query1);
		}

	}
}


text:
function rfs = rfscaleg(rf, pulseduration)
% RFSCALEG Converts a normalized RF waveform to Gauss
%   RF_G = RFSCALEG(RF, PW)
% Inputs:
%   RF - scaled to sum to the desired flip angle in radians
%   PW - Pulse duration in ms
% Outputs:
%   RF_G - rf pulse scaled to Gauss
%
% Peder Larson 10/6/04

GAMMA = 4257; % Hz/G

rfs = rf*length(rf)/(2*pi*GAMMA*pulseduration*1e-3);


text:
<?php

include 'model.php';
include 'controller.php';

$this->route()->addRule(
	'/news', array(
			'controller' => 'Controller_News',
			'package' => 'news',
			'action' => 'showAll',
		)
	);

$this->route()->addRule(
	'/news/:name{string}', array(
			'controller' => 'Controller_News',
			'package' => 'news',
			'action' => 'showOne',
		)
	);

include 'admin/model.php';
include 'admin/controller.php';

$this->route()->addRule(
	'/admin/news', array(
			'controller' => 'Controller_News_Admin',
			'package' => 'news',
			'action' => 'show',
		)
	);

$this->route()->addRule(
	'/admin/news/add', array(
			'controller' => 'Controller_News_Admin',
			'package' => 'news',
			'action' => 'add',
		)
	);


text:
"""This module provides mock 'specs' for third party modules that can be used
when needing to mock those third party modules"""

# pywsman
PYWSMAN_SPEC = (
    'Client',
    'ClientOptions',
    'EndPointReference',
    'FLAG_ENUMERATION_OPTIMIZATION',
    'Filter',
    'XmlDoc',
    'wsman_transport_set_verify_host',
    'wsman_transport_set_verify_peer',
)

# scciclient
SCCICLIENT_SPEC = (
    'irmc',
)

SCCICLIENT_IRMC_SCCI_SPEC = (
    'POWER_OFF',
    'POWER_ON',
    'POWER_RESET',
    'SCCIClientError',
    'get_client',
    'get_report',
    'get_sensor_data',
)


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Azure.ServiceBus.Management
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    public class AuthorizationRules : List<AuthorizationRule>, IEquatable<AuthorizationRules>
    {
        private bool RequiresEncryption => this.Count > 0;

        internal XElement Serialize()
        {
            var rules = new XElement(
                XName.Get("AuthorizationRules", ManagementClientConstants.ServiceBusNamespace),
                this.Select(rule => rule.Serialize()));

            return rules;
        }

        internal static AuthorizationRules ParseFromXElement(XElement xElement)
        {
            var rules = new AuthorizationRules();
            var xRules = xElement.Elements(XName.Get("AuthorizationRule", ManagementClientConstants.ServiceBusNamespace));
            rules.AddRange(xRules.Select(rule => AuthorizationRule.ParseFromXElement(rule)));
            return rules;
        }

        public override int GetHashCode()
        {
            int hash = 7;
            unchecked
            {
                foreach (var rule in this)
                {
                    hash = (hash * 7) + rule.GetHashCode();
                }
            }

            return hash;
        }

        public override bool Equals(object obj)
        {
            var other = obj as AuthorizationRules;
            return this.Equals(other);
        }

        public bool Equals(AuthorizationRules other)
        {
            if (ReferenceEquals(other, null) || this.Count != other.Count)
            {
                return false;
            }

            var cnt = new Dictionary<string, AuthorizationRule>();
            foreach (AuthorizationRule rule in this)
            {
                cnt[rule.KeyName] = rule;
            }

            foreach (AuthorizationRule otherRule in other)
            {
                if (!cnt.TryGetValue(otherRule.KeyName, out var rule) || !rule.Equals(otherRule))
                {
                    return false;
                }
            }

            return true;
        }

        public static bool operator ==(AuthorizationRules o1, AuthorizationRules o2)
        {
            if (ReferenceEquals(o1, o2))
            {
                return true;
            }

            if (ReferenceEquals(o1, null) || ReferenceEquals(o2, null))
            {
                return false;
            }

            return o1.Equals(o2);
        }

        public static bool operator !=(AuthorizationRules o1, AuthorizationRules o2)
        {
            return !(o1 == o2);
        }
    }
}


text:
<title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

API Documentation

Service/DeveloperGarden/Request/ConferenceCall/RemoveConferenceTemplateParticipantRequest.php

Global

                      Classes

\Zend_Service_DeveloperGarden_Request_ConferenceCall_RemoveConferenceTemplateParticipantRequest

Zend Framework

LICENSE

This source file is subject to the new BSD license that is bundled
with this package in the file LICENSE.txt.
It is also available through the world-wide-web at this URL:
http://framework.zend.com/license/new-bsd
If you did not receive a copy of the license and are unable to
obtain it through the world-wide-web, please send an email
to license@zend.com so we can send you a copy immediately.

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service

subpackage

DeveloperGarden

version

$Id: RemoveConferenceTemplateParticipantRequest.php 23775 2011-03-01 17:25:24Z ralph $

\Zend_Service_DeveloperGarden_Request_ConferenceCall_RemoveConferenceTemplateParticipantRequest
jump to top

Extends from

\Zend_Service_DeveloperGarden_Request_RequestAbstract

author

Marco Kaiser

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service

subpackage

DeveloperGarden

Properties

string
                 $participantId= 'null'

the participant id

Default valuenullDetails

Type

string

string
                 $templateId= 'null'

the template id

Default valuenullDetails

Type

string

Methods

__construct(
          integer $environment, string $templateId, string $participantId
          )

        :
          \Zend_Service_DeveloperGarden_Request_RequestAbstract

constructor

Parameters

Name
Type
Description

$environment
integer

$templateId
string

$participantId
string

Returns

Type
Description

\Zend_Service_DeveloperGarden_Request_RequestAbstract

getEnvironment(

          )

        :
          integer

the current configured environment value

Inherited from:
                    \Zend_Service_DeveloperGarden_Request_RequestAbstract::getEnvironment()

Returns

Type
Description

integer

setEnvironment(
          integer $environment
          )

        :
          \Zend_Service_DeveloperGarden_Request_RequestAbstract

sets a new moduleId

Inherited from:
                    \Zend_Service_DeveloperGarden_Request_RequestAbstract::setEnvironment()

Parameters

Name
Type
Description

$environment
integer

Returns

Type
Description

\Zend_Service_DeveloperGarden_Request_RequestAbstract

setParticipantId(
          string $participantId
          )

        :
          \Zend_Service_DeveloperGarden_Request_ConferenceCall_RemoveConferenceTemplateParticipantRequest

set the participant id

Parameters

Name
Type
Description

$participantId
string

Returns

Type
Description

\Zend_Service_DeveloperGarden_Request_ConferenceCall_RemoveConferenceTemplateParticipantRequest

setTemplateId(
          string $templateId
          )

        :
          \Zend_Service_DeveloperGarden_Request_ConferenceCall_RemoveConferenceTemplateParticipantRequest

set the template id

Parameters

Name
Type
Description

$templateId
string

Returns

Type
Description

\Zend_Service_DeveloperGarden_Request_ConferenceCall_RemoveConferenceTemplateParticipantRequest

Documentation was generated by DocBlox 0.13.3.


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="grouch">
        <note>
            Automatically created based on framefiles: bitch (37.8)
        </note>
        <roleset id="grouch.01" name="complain" vncls="37.8">
            <roles>
                <role descr="complainer" n="0">
                    <vnrole vncls="37.8" vntheta="agent"/>
                </role>
                <role descr="cause, complain of or about" n="1">
                    <vnrole vncls="37.8" vntheta="topic"/>
                </role>
                <role descr="hearer, complain to" n="2">
                    <vnrole vncls="37.8" vntheta="recipient"/>
                </role>
            </roles>
            <example name="no ARG2" src="web usage" type="">
                <text>The AMA clubs grouched about the film and the bad press it gave family oriented bike riders.</text>
                <note/>
                <arg f="" n="0">The AMA clubs</arg>
                <rel f="">grouched</rel>
                <arg f="" n="1">about the filk and the bad press it gave family oriented bike riders</arg>
            </example>
            <example name="All args" src="web usage" type="">
                <text>He grouched to Jon, "wanna buy a schooner?" </text>
                <note/>
                <arg f="" n="0">He</arg>
                <rel f="">grouched</rel>
                <arg f="" n="2">to Jon</arg>
                <arg f="" n="1">wanna buy a schooner?</arg>

            </example>
            <note>Edited by hwangd</note>
        </roleset>
    </predicate>
</frameset>


text:
\section{Durchführung}

  Bei der Durchführung des Versuches wird für die $\gamma$-Strahlung das
  $^{137}\symup{Cs}$ Nuklid und für die
  $\beta$-Strahlung $^{99}\symup{Tc}$ als Strahlungsquelle verwendet.
  Als Absorper werden Zink (Zn) und Blei (Pb) für den ersten Strahler und
  Aluminium (Al) für den zweiten verwendet.

  Die durchgehende Strahlung wird mit einem Geiger-Müller-Zählrohr gemessen. Da
  diese Messungen durch den so genannten "Nulleffekt" (kosmische Strahlung)
  verfälscht werden könnten, wird das Zählrohr mit Blei ummantelt und zu beginn
  die Strahlung ohne Strahler für 1000 Sekunden gemessen.
  Anschließend wird das jeweilige Metall zwischen Strahler und Zählrohr gespannt,
  und die ganze Konstruktion mit Blei ummantelt (siehe Abb. 4).
  %Bild
  \begin{figure}[H]
  \centering
    \includegraphics[width=0.7\textwidth]{Rohdaten/aufbau.png}
    \caption{Versuchsaufbau für die $\gamma$-Strahlung [1].}
    \label{fig:aufbau}
  \end{figure}
  Pro Metall werden Zehn Messungen für verschiedene Dicken durchgeführt werden.
  Dabei werden die Messzeit mit höherer Dicke und schwererem Metall erhöht.
  Dies geht soweit, dass bei einer Dicke von 5 cm bei Blei eine Messzeit von
  1000 Sekunden verwendet wird.


text:
layout: page
title: Carl Riley's 68th Birthday
date: 2016-05-24
author: Stephen Pennington
tags: weekly links, java
status: published
summary: In eget felis orci. Sed hendrerit erat urna, cursus.
banner: images/banner/office-01.jpg
booking:
  startDate: 06/18/2018
  endDate: 06/19/2018
  ctyhocn: BNAWHHX
  groupCode: CR6B
published: true
---
Vestibulum eu efficitur eros. Nunc libero ante, mollis nec risus quis, viverra pulvinar augue. Pellentesque quam ipsum, condimentum eleifend orci sit amet, fringilla bibendum tortor. Vivamus varius massa vitae orci finibus finibus. Ut consequat vulputate nunc, ac porttitor tellus dapibus in. Aliquam quam leo, accumsan ut euismod molestie, sodales eget nulla. Proin id scelerisque neque. Suspendisse purus nibh, tempus eu convallis id, pellentesque non nisl. In ex est, faucibus ac risus sit amet, venenatis ornare libero. Proin finibus iaculis finibus. Fusce rhoncus felis odio, id aliquam velit luctus at.

* Duis quis nunc vitae ex ornare fringilla nec a lectus
* Sed ullamcorper nulla a arcu efficitur, eu lobortis enim porttitor
* Duis sed eros a ex placerat pulvinar.

In placerat auctor ante vel laoreet. Nam pellentesque lacinia nibh, non pulvinar leo faucibus at. Cras ex neque, blandit eget mauris a, ullamcorper auctor arcu. Duis enim magna, sodales sed mauris quis, efficitur elementum elit. Donec eget felis quis nunc rhoncus aliquam. Cras eget tincidunt nisl. Phasellus nulla sapien, imperdiet et faucibus vitae, iaculis quis neque. Nam sollicitudin nibh ut turpis pretium, vel convallis odio lacinia. Suspendisse eu orci eu ligula condimentum eleifend eget vitae quam.
Quisque eget sollicitudin erat. Donec eros nisi, fringilla nec neque sit amet, feugiat sagittis orci. Morbi et turpis tempor, laoreet lectus eu, pharetra velit. Sed interdum tellus arcu, eget fermentum nisl tristique in. Nulla laoreet sapien nec est viverra rutrum. In non justo feugiat dolor scelerisque commodo. Vivamus mattis urna vehicula hendrerit tempus. Nunc fermentum lorem ut auctor luctus. Donec tempor sem sit amet sapien pellentesque, vitae feugiat nunc aliquam. Maecenas et convallis arcu, ac tempus libero. Aenean sodales enim vitae venenatis tempor. Sed eu tincidunt leo.


text:
<?php
namespace ReduxCore\ReduxFramework;
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
    if ( ! class_exists( 'ReduxCore\\ReduxFramework\\Redux_Customizer_Control' ) ) {
        class Redux_Customizer_Control extends \WP_Customize_Control {

            public function render() {
                $this->redux_id = str_replace( 'customize-control-', '', 'customize-control-' . str_replace( '[', '-', str_replace( ']', '', $this->id ) ) );
                $class          = 'customize-control redux-group-tab redux-field customize-control-' . $this->type;
                $opt_name       = explode( '[', $this->id );
                $opt_name       = $opt_name[0];
                ?>
                <li id="<?php echo esc_attr( $this->redux_id ); ?>" class="<?php echo esc_attr( $class ); ?>">
                    <?php if ( $this->type != "repeater" ): ?>
                        <input type="hidden"
                            data-id="<?php echo esc_attr( $this->id ); ?>"
                            data-key="<?php echo str_replace( $opt_name . '-', '', $this->redux_id ); ?>"
                            class="redux-customizer-input"
                            id="customizer_control_id_<?php echo esc_attr( $this->redux_id ); ?>" <?php echo esc_url( $this->link() ) ?>
                            value=""/>
                    <?php endif; ?>
                    <?php $this->render_content(); ?>

                <?php

            }

            public function render_content() {
                do_action( 'redux/advanced_customizer/control/render/' . $this->redux_id, $this );
            }

            public function label() {
                // The label has already been sanitized in the Fields class, no need to re-sanitize it.
                echo $this->label;
            }

            public function description() {
                if ( ! empty( $this->description ) ) {
                    // The description has already been sanitized in the Fields class, no need to re-sanitize it.
                    echo '' . $this->description . '';
                }
            }

            public function title() {
                echo '';
                $this->label();
                $this->description();
                echo '';
            }
        }
    }


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_dom_InputPortData_h
#define mozilla_dom_InputPortData_h

#include "mozilla/dom/InputPortBinding.h"
#include "nsIInputPortService.h"

class nsString;

namespace mozilla {
namespace dom {

enum class InputPortType : uint32_t
{
  Av,
  Displayport,
  Hdmi,
  EndGuard_
};

class InputPortData final : public nsIInputPortData
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIINPUTPORTDATA

  InputPortData();

  const nsString& GetId() const;

  const InputPortType GetType() const;

private:
  ~InputPortData();

  nsString mId;
  nsString mType;
  bool mIsConnected;
};

} // namespace dom
} // namespace mozilla

#endif // mozilla_dom_InputPortData_h


text:
package net.netheos.pcsapi.credentials;

/**
 * Contains the application information.
 */
public interface AppInfo
{

    /**
     * Get the storage provider name
     *
     * @return The provider name
     */
    String getProviderName();

    /**
     * Get the application name
     *
     * @return the application name
     */
    String getAppName();

}


text:
{% extends "accounts/base.html" %}
{% load djblets_deco i18n %}

{% block title %}{% trans "Password Reset Complete" %}{% endblock %}

{% block auth_content %}

{% trans "Password Reset Complete" %}

{%  url 'login' as login_url %}
{%  blocktrans %}
 Your password has been set. You may go ahead and
 log in now.
{%  endblocktrans %}

{% endblock auth_content %}


text:
<playercorefactory>
    <players>
        <player name="BDPlayLister" type="ExternalPlayer" audio="false" video="true">
            <filename>C:\Utils\BDPlayLister\bdplaylister.bat</filename>
            <args>"{0}"</args>
            <hidexbmc>false</hidexbmc>
            <hideconsole>true</hideconsole>
            <playcountminimumtime>600</playcountminimumtime>-->
        </player>
    </players>
    <rules action="prepend">
        <rule protocols="daap|rtv|rtmp|http|https|rtmpe|mms|rtp" player="DVDPlayer" />
        <rule filename=".*intro.mp4" player="DVDPlayer" />
        <rule filename=".*index.bdmv" player="BDPlayLister" />
    </rules>
</playercorefactory>


text:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StockportContentApi.Config;
using StockportContentApi.Repositories;
using StockportContentApi.Model;
using System.Collections.Generic;
using System.Linq;
using StockportContentApi.ContentfulModels;
using AutoMapper;
using StockportContentApi.ManagementModels;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;

namespace StockportContentApi.Controllers
{
    public class EventController : Controller
    {
        private readonly ResponseHandler _handler;
        private readonly Func<string, ContentfulConfig> _createConfig;
        private readonly Func<ContentfulConfig, EventRepository> _eventRepository;
        private readonly Func<ContentfulConfig, EventCategoryRepository> _eventCategoryRepository;
        private readonly Func<ContentfulConfig, ManagementRepository> _managementRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<EventController> _logger;

        public EventController(ResponseHandler handler,
            Func<string, ContentfulConfig> createConfig,
            Func<ContentfulConfig, EventRepository> eventRepository,
            Func<ContentfulConfig, EventCategoryRepository> eventCategoryRepository,
            Func<ContentfulConfig, ManagementRepository> managementRepository,
            IMapper mapper,
            ILogger<EventController> logger)
        {
            _handler = handler;
            _createConfig = createConfig;
            _eventRepository = eventRepository;
            _managementRepository = managementRepository;
            _eventCategoryRepository = eventCategoryRepository;
            _mapper = mapper;
            _logger = logger;
        }

        [HttpGet]
        [Route("{businessId}/event-categories")]
        [Route("v1/{businessId}/event-categories")]
        public async Task<IActionResult> GetEventCategories(string businessId)
        {
            return await _handler.Get(() =>
            {
                var eventRepository = _eventCategoryRepository(_createConfig(businessId));
                return eventRepository.GetEventCategories();
            });
        }

        [HttpGet]
        [Route("{businessId}/eventhomepage")]
        [Route("v1/{businessId}/eventhomepage")]
        public async Task<IActionResult> Homepage(string businessId)
        {
            var categoryRepository = _eventCategoryRepository(_createConfig(businessId));
            var categoriesresponse = await categoryRepository.GetEventCategories();
            var categories = categoriesresponse.Get<List<EventCategory>>();

            var repository = _eventRepository(_createConfig(businessId));
            var response = await repository.GetEventHomepage();
            var homepage = response.Get<EventHomepage>();

            homepage.Categories = categories;
            return Ok(homepage);
        }

        [HttpGet]
        [Route("{businessId}/events/{slug}")]
        [Route("v1/{businessId}/events/{slug}")]
        public async Task<IActionResult> Detail(string slug, string businessId, [FromQuery] DateTime? date)
        {
            return await _handler.Get(() =>
            {
                var repository = _eventRepository(_createConfig(businessId));
                return repository.GetEvent(slug, date);
            });
        }

        [ApiExplorerSettings(IgnoreApi = true)]
        [HttpPut]
        [Route("{businessId}/events/{slug}")]
        [Route("v1/{businessId}/events/{slug}")]
        public async Task<IActionResult> UpdateEvent([FromBody] Event eventDetail, string businessId)
        {
            var repository = _eventRepository(_createConfig(businessId));
            var existingEvent = await repository.GetContentfulEvent(eventDetail.Slug);

            var existingCategories = await repository.GetContentfulEventCategories();
            var referencedCategories = existingCategories.Items.Where(c => eventDetail.EventCategories.Any(ed => c.Name == ed.Name)).ToList();

            var managementEvent = ConvertToManagementEvent(eventDetail, referencedCategories, existingEvent);

            return await _handler.Get(async () =>
            {
                var managementRepository = _managementRepository(_createConfig(businessId));
                var version = await managementRepository.GetVersion(existingEvent.Sys.Id);
                existingEvent.Sys.Version = version;
                var result = await managementRepository.CreateOrUpdate(managementEvent, existingEvent.Sys);
                return result;
            });
        }

        [HttpGet]
        [Route("{businessId}/events")]
        [Route("{businessId}/events/latest/{limit}")]
        [Route("v1/{businessId}/events")]
        [Route("v1/{businessId}/events/latest/{limit}")]
        public async Task<IActionResult> Index(
            string businessId,
            int limit = 0,
            [FromQuery] DateTime? dateFrom = null,
            [FromQuery] DateTime? dateTo = null,
            [FromQuery] string category = null,
            [FromQuery] bool? featured = null,
            [FromQuery] string tag = null,
            [FromQuery] string price = null, [FromQuery] double latitude = 0, [FromQuery] double longitude = 0)
        {
            return await _handler.Get(() =>
            {
                var repository = _eventRepository(_createConfig(businessId));
                return repository.Get(dateFrom, dateTo, category, limit, featured, tag, price, latitude, longitude);
            });
        }

        [HttpGet]
        [Route("{businessId}/events/by-category")]
        [Route("v1/{businessId}/events/by-category")]
        public async Task<IActionResult> GetEventsByCatrgoryOrTag(string businessId, [FromQuery] string category = "", bool onlyNextOccurrence = true)
        {
            var repository = _eventRepository(_createConfig(businessId));

            if (string.IsNullOrEmpty(category)) return new NotFoundObjectResult("No category was supplied");

            try
            {
                // TODO: Change this to a service call
                var eventsByCategory = await repository.GetEventsByCategory(category, onlyNextOccurrence);
                var eventsByTag = await repository.GetEventsByTag(category, onlyNextOccurrence);

                if (eventsByCategory.Count == 0 && eventsByTag.Count == 0) return new NotFoundObjectResult($"No events found for category {category}");

                var events = eventsByCategory.Count > 0 ? eventsByCategory : eventsByTag;

                return new OkObjectResult(events);
            }
            catch (Exception ex)
            {
                _logger.LogError(new EventId(0), ex, $"There was an error with getting events by category / tag for category {category}");
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }

        [ApiExplorerSettings(IgnoreApi = true)]
        [HttpDelete]
        [Route("{businessId}/events/{slug}")]
        [Route("v1/{businessId}/events/{slug}")]
        public async Task<IActionResult> DeleteEvent(string slug, string businessId)
        {
            var repository = _eventRepository(_createConfig(businessId));
            var existingEvent = await repository.GetContentfulEvent(slug);

            return await _handler.Get(async () =>
            {
                var managementRepository = _managementRepository(_createConfig(businessId));
                var version = await managementRepository.GetVersion(existingEvent.Sys.Id);
                existingEvent.Sys.Version = version;
                return await managementRepository.Delete(existingEvent.Sys);
            });
        }

        private ManagementEvent ConvertToManagementEvent(Event eventDetail, List<ContentfulEventCategory> categories, ContentfulEvent existingEvent)
        {
            var contentfulEvent = _mapper.Map<ContentfulEvent>(eventDetail);
            contentfulEvent.EventCategories = categories;
            contentfulEvent.Image = existingEvent.Image;
            contentfulEvent.Group = existingEvent.Group;
            contentfulEvent.Documents = existingEvent.Documents;
            var managementEvent = new ManagementEvent();
            _mapper.Map(contentfulEvent, managementEvent);
            return managementEvent;
        }
    }
}


text:
"""Preprocesses COCO minival data for Object Detection evaluation using mean Average Precision.

The 2014 validation images & annotations can be downloaded from:
http://cocodataset.org/#download
The minival image ID whitelist, a subset of the 2014 validation set, can be
found here:
https://github.com/tensorflow/models/blob/master/research/object_detection/data/mscoco_minival_ids.txt.

This script takes in the original images folder, instances JSON file and
image ID whitelist and produces the following in the specified output folder:
A subfolder for whitelisted images (images/), and a file (ground_truth.pbtxt)
containing an instance of tflite::evaluation::ObjectDetectionGroundTruth.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import ast
import collections
import os
import shutil
import sys
from tensorflow.lite.tools.evaluation.proto import evaluation_stages_pb2

def _get_ground_truth_detections(instances_file,
                                 whitelist_file=None,
                                 num_images=None):
  """Processes the annotations JSON file and returns ground truth data corresponding to whitelisted image IDs.

  Args:
    instances_file: COCO instances JSON file, usually named as
      instances_val20xx.json.
    whitelist_file: File containing COCO minival image IDs to whitelist for
      evaluation, one per line.
    num_images: Number of whitelisted images to pre-process. First num_images
      are chosen based on sorted list of filenames. If None, all whitelisted
      files are preprocessed.

  Returns:
    A dict mapping image id (int) to a per-image dict that contains:
      'filename', 'image' & 'height' mapped to filename & image dimensions
      respectively
      AND
      'detections' to a list of detection dicts, with each mapping:
        'category_id' to COCO category id (starting with 1) &
        'bbox' to a list of dimension-normalized [top, left, bottom, right]
        bounding-box values.
  """
  # Read JSON data into a dict.
  with open(instances_file, 'r') as annotation_dump:
    data_dict = ast.literal_eval(annotation_dump.readline())

  image_data = collections.OrderedDict()
  all_file_names = []

  # Read whitelist.
  if whitelist_file is not None:
    with open(whitelist_file, 'r') as whitelist:
      image_id_whitelist = set([int(x) for x in whitelist.readlines()])
  else:
    image_id_whitelist = [image['id'] for image in data_dict['images']]

  # Get image names and dimensions.
  for image_dict in data_dict['images']:
    image_id = image_dict['id']
    if image_id not in image_id_whitelist:
      continue
    image_data_dict = {}
    image_data_dict['id'] = image_dict['id']
    image_data_dict['file_name'] = image_dict['file_name']
    all_file_names.append(image_data_dict['file_name'])
    image_data_dict['height'] = image_dict['height']
    image_data_dict['width'] = image_dict['width']
    image_data_dict['detections'] = []
    image_data[image_id] = image_data_dict

  if num_images:
    all_file_names.sort()
    all_file_names = all_file_names[:num_images]
  all_file_names = set(all_file_names)

  # Get detected object annotations per image.
  for annotation_dict in data_dict['annotations']:
    image_id = annotation_dict['image_id']
    if image_id not in image_id_whitelist:
      continue
    if image_id not in image_data:
      continue
    image_data_dict = image_data[image_id]
    if image_data_dict['file_name'] not in all_file_names:
      del image_data[image_id]
      continue

    bbox = annotation_dict['bbox']
    # bbox format is [x, y, width, height]
    # Refer: http://cocodataset.org/#format-data
    top = bbox[1]
    left = bbox[0]
    bottom = top + bbox[3]
    right = left + bbox[2]
    if (top > image_data_dict['height'] or left > image_data_dict['width'] or
        bottom > image_data_dict['height'] or right > image_data_dict['width']):
      continue
    object_d = {}
    object_d['bbox'] = [
        top / image_data_dict['height'], left / image_data_dict['width'],
        bottom / image_data_dict['height'], right / image_data_dict['width']
    ]
    object_d['category_id'] = annotation_dict['category_id']
    image_data_dict['detections'].append(object_d)

  return image_data

def _dump_data(ground_truth_detections, images_folder_path, output_folder_path):
  """Dumps images & data from ground-truth objects into output_folder_path.

  The following are created in output_folder_path:
    images/: sub-folder for whitelisted validation images.
    ground_truth.pb: A binary proto file containing all ground-truth
    object-sets.

  Args:
    ground_truth_detections: A dict mapping image id to ground truth data.
      Output of _get_ground_truth_detections.
    images_folder_path: Validation images folder
    output_folder_path: folder to output files to.
  """
  # Ensure output folders exist.
  if not os.path.exists(output_folder_path):
    os.makedirs(output_folder_path)
  output_images_folder = os.path.join(output_folder_path, 'images')
  if not os.path.exists(output_images_folder):
    os.makedirs(output_images_folder)
  output_proto_file = os.path.join(output_folder_path, 'ground_truth.pb')

  ground_truth_data = evaluation_stages_pb2.ObjectDetectionGroundTruth()
  for image_dict in ground_truth_detections.values():
    # Create an ObjectsSet proto for this file's ground truth.
    detection_result = ground_truth_data.detection_results.add()
    detection_result.image_id = image_dict['id']
    detection_result.image_name = image_dict['file_name']
    for detection_dict in image_dict['detections']:
      object_instance = detection_result.objects.add()
      object_instance.bounding_box.normalized_top = detection_dict['bbox'][0]
      object_instance.bounding_box.normalized_left = detection_dict['bbox'][1]
      object_instance.bounding_box.normalized_bottom = detection_dict['bbox'][2]
      object_instance.bounding_box.normalized_right = detection_dict['bbox'][3]
      object_instance.class_id = detection_dict['category_id']
    # Copy image.
    shutil.copy2(
        os.path.join(images_folder_path, image_dict['file_name']),
        output_images_folder)

  # Dump proto.
  with open(output_proto_file, 'wb') as proto_file:
    proto_file.write(ground_truth_data.SerializeToString())

def _parse_args():
  """Creates a parser that parse the command line arguments.

  Returns:
    A namespace parsed from command line arguments.
  """
  parser = argparse.ArgumentParser(
      description='preprocess_coco_minival: Preprocess COCO minival dataset')
  parser.add_argument(
      '--images_folder',
      type=str,
      help='Full path of the validation images folder.',
      required=True)
  parser.add_argument(
      '--instances_file',
      type=str,
      help='Full path of the input JSON file, like instances_val20xx.json.',
      required=True)
  parser.add_argument(
      '--whitelist_file',
      type=str,
      help='File with COCO image ids to preprocess, one on each line.',
      required=False)
  parser.add_argument(
      '--num_images',
      type=int,
      help='Number of whitelisted images to preprocess into the output folder.',
      required=False)
  parser.add_argument(
      '--output_folder',
      type=str,
      help='Full path to output images & text proto files into.',
      required=True)
  return parser.parse_known_args(args=sys.argv[1:])[0]

if __name__ == '__main__':
  args = _parse_args()
  ground_truths = _get_ground_truth_detections(args.instances_file,
                                               args.whitelist_file,
                                               args.num_images)
  _dump_data(ground_truths, args.images_folder, args.output_folder)


text:
<?php

namespace Frigg\FlightBundle\Controller\API;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Routing\ClassResourceInterface;
use FOS\Rest\Util\Codes;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Frigg\FlightBundle\Entity\Airline;
use Frigg\FlightBundle\Form\AirlineType;

class AirlineController extends FOSRestController implements ClassResourceInterface
{
    /**
     * @ApiDoc(
     *  section="Airlines",
     *  resource=true,
     *  description="Returns a collection of all airlines",
     *  statusCodes={
     *      200="Returned when successful"
     *  }
     * )
     *
     * @Rest\View()
     */
    public function cgetAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        return $em->getRepository('FriggFlightBundle:Airline')->findAll();
    }

    /**
     * @ApiDoc(
     *  section="Airlines",
     *  resource=true,
     *  description="Returns a single airline object",
     *  statusCodes={
     *      200="Returned when successful",
     *      404="Returned when airline does not exist"
     *  },
     *  requirements={
     *      {"name"="airlineId", "dataType"="integer", "requirement"="\d+", "description"="Unique airline identifier"},
     *  }
     * )
     *
     * @Rest\View()
     */
    public function getAction($airlineId)
    {
        $airlineService = $this->container->get('frigg.airline.flight');
        $airlineService->setParentById($airlineId);
        return $airlineService->getParent();
    }

    /**
     * @ApiDoc(
     *  section="Airlines",
     *  tags="TO-DO",
     *  description="Generates and returns graph data"
     * )
     *
     * @Rest\View()
     */
    public function cgetGraphAction(Request $request, $airlineId)
    {
        return null;
    }

    /**
     * @ApiDoc(
     *  section="Airlines",
     *  resource=true,
     *  description="Creates an airline and returns the view",
     *  statusCodes={
     *      201="Returned when airline was successfully created",
     *      200="Returned when request did not validate and the form is returned",
     *      403="Returned when the request was not authorized"
     *  }
     * )
     *
     * @return View|array
     */
    public function cpostAction(Request $request)
    {
        if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedHttpException('Access denied. Only administrators may add data to the API.');
        }

        // Create Airline form instance based
        $airlineEntity = new Airline();
        $form = $this->createForm(new AirlineType(), $airlineEntity);

        // Validate against request data
        $form->bind($request);
        if ($form->isValid()) {
            // Save new airline entity
            $em = $this->getDoctrine()->getManager();
            $em->persist($airlineEntity);
            $em->flush();

            // Return view of new airline entity (HTTP 201)
            return $this->redirectView(
                $this->generateUrl(
                    'get_airline',
                    array(
                        'airlineId' => $airlineEntity->getId()
                    )
                ),
                Codes::HTTP_CREATED
            );
        }

        // Else return form to client
        return array(
            'form' => $form,
        );
    }

    /**
     * @ApiDoc(
     *  section="Airlines",
     *  resource=true,
     *  description="Quickcreates an airline",
     *  statusCodes={
     *      204="Returned when the flight has been successfully created",
     *      200="Returned when request did not validate and the form is returned",
     *      404={
     *          "Returned when airline does not exist",
     *          "Or when flight does not exist"
     *      }
     *  },
     *  requirements={
     *      {"name"="airlineId", "dataType"="integer", "requirement"="\d+", "description"="Unique airline identifier"},
     *  }
     * )
     *
     * @return View|array
     */
    public function putAction(Request $request, $airlineId)
    {
        if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedHttpException('Access denied. Only administrators may add data to the API.');
        }

        // Load service
        $airlineService = $this->container->get('frigg.airline.flight');

        // Create a form instance of given airline
        $airlineService->setParentById($airlineId);
        $airlineEntity = $airlineService->getParent();
        $form = $this->createForm(new AirlineType(), $airlineEntity);

        // Validate request data with form
        $form->bind($request);
        if ($form->isValid()) {
            // Create new airline
            $em = $this->getDoctrine()->getManager();
            $em->persist($airlineEntity);
            $em->flush();

            // Return empty view (HTTP 204)
            return $this->view(null, Codes::HTTP_NO_CONTENT);
        }

        // Else return view to client
        return array(
            'form' => $form,
        );
    }

    /**
     * @ApiDoc(
     *  section="Airlines",
     *  resource=true,
     *  description="Delete an airline",
     *  statusCodes={
     *      204="Returned when airline was successfully deleted",
     *      403="Returned when the request was not authorized",
     *      404="Returned when airline does not exist"
     *  },
     *  requirements={
     *      {"name"="airlineId", "dataType"="integer", "requirement"="\d+", "description"="Unique airline identifier"}
     *  }
     * )
     *
     * @return View|array
     */
    public function deleteAction($airlineId)
    {
        if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedHttpException('Access denied. Only administrators may delete data from the API');
        }

        // Load service
        $airlineService = $this->container->get('frigg.airline.flight');

        // Fetch given airline (or throw 404 exception here)
        $airlineService->setParentById($airlineId);
        $airlineEntity = $airlineService->getParent();

        // Delete airline entity
        $em = $this->getDoctrine()->getManager();
        $em->remove($airlineEntity);
        $em->flush();

        // Return empty view (HTTP 204)
        return $this->view(null, Codes::HTTP_NO_CONTENT);
    }
}


text:
package forplay.java;

import java.awt.image.BufferedImage;

import forplay.core.AssetLoadException;
import forplay.core.Image;
import forplay.core.Canvas;
import forplay.core.CanvasImage;
import forplay.core.ResourceCallback;

class JavaImage implements CanvasImage {

  BufferedImage img;
  private JavaCanvas canvas;
  private Exception exception;

  JavaImage(BufferedImage img) {
    this.img = img;
  }

  public JavaImage(AssetLoadException assetLoadException) {
    this.exception = assetLoadException;
  }

  @Override
  public Canvas canvas() {
    if (canvas == null) {
      canvas = new JavaCanvas(img.createGraphics(), width(), height());
    }
    return canvas;
  }

  @Override
  public void replaceWith(Image img) {
    assert img instanceof JavaImage;
    this.img = ((JavaImage) img).img;
  }

  @Override
  public void addCallback(ResourceCallback<Image> callback) {
    if (img == null) {
      callback.error(exception != null ? exception : new RuntimeException());
    } else {
      callback.done(this);
    }
  }

  @Override
  public int width() {
    return img.getWidth();
  }

  @Override
  public int height() {
    return img.getHeight();
  }

  @Override
  public boolean isReady() {
    return (img != null && exception == null);
  }
}


text:
package org.concordion.cubano.driver.web;

import java.util.List;

import org.concordion.cubano.driver.BrowserBasedTest;
import org.concordion.cubano.driver.web.pagefactory.PageObjectAwareHtmlElementDecorator;
import org.concordion.ext.ScreenshotTaker;
import org.concordion.ext.storyboard.CardResult;
import org.concordion.slf4j.ext.ReportLogger;
import org.concordion.slf4j.ext.ReportLoggerFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.TargetLocator;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import ru.yandex.qatools.htmlelements.loader.decorator.HtmlElementLocatorFactory;

/**
 * Provides core functionality for pages objects using the page object factory pattern.
 *
 * @param <T> Class of the PageObject extending this class, so that we can implement fluent style methods
 * @author Andrew Sumner
 */
public abstract class BasePageObject<T extends BasePageObject<T>> {
    private final ReportLogger logger = ReportLoggerFactory.getReportLogger(this.getClass().getName());
    private BrowserBasedTest test;
    private PageHelper pageHelper;

    /**
     * Creates a new page object.
     *
     * @param test                 Calling class
     * @param timeoutWaitInSeconds Maximum time to wait for page to finish loading
     * @param params               An optional set of parameters to pass to the waitUntilPageIsLoaded method
     */
    protected BasePageObject(BrowserBasedTest test, int timeoutWaitInSeconds, Object... params) {
        this.test = test;
        this.pageHelper = new PageHelper(this, BasePageObject.class);

        getLogger().step("Page Object: {}", getSimpleName());

        refreshPageElements();
        waitUntilPageIsLoaded(timeoutWaitInSeconds, params);
    }

    /**
     * Updates all fields in this class (and descendant classes) with new pointers to the elements on the webpage we're pointing at.
     *

     * This is useful in the event that an Ajax request has reloaded large portions of your page and to avoid StaleElementExcpetions it is easier just to
     * refresh all fields that work out which ones need updating.
     */
    public void refreshPageElements() {
        PageFactory.initElements(new PageObjectAwareHtmlElementDecorator(new HtmlElementLocatorFactory(getBrowser().getDriver()), this), this);
    }

    /**
     * Has two purposes:
     *
     *
     *

     *
Check that an element on the page that uniquely identifies this page is present

     *
Ensure that the page is fully loaded (eg Ajax requests have completed) so don't have to implement waits when accessing elements on the page

     *

     *
     * All PageObjects must implement this method.
     *
     * @param timeoutWaitInSeconds Number of seconds to wait for the page to load before timing out
     * @param params               List of parameters passed to the constructor, if any
     */
    protected abstract void waitUntilPageIsLoaded(int timeoutWaitInSeconds, Object... params);

    /**
     * @return The name of the current page object.
     */
    public String getSimpleName() {
        return this.getClass().getSimpleName();
    }

    /**
     * Provide a reference to the logger implemented for the current page object.
     *
     * @return Logger
     */
    public ReportLogger getLogger() {
        return logger;
    }

    /**
     * Provide a reference to the calling class that implements the TestDriveable interface.
     *
     * @return Reference to class implementing the TestDriveable interface
     */
    public BrowserBasedTest getTest() {
        return test;
    }

    /**
     * Opens a browser if not already open and return a reference to it.
     *
     * @return A reference to the current browser
     */
    public Browser getBrowser() {
        return test.getBrowser();
    }

    /**
     * Perform a visual comparison of the window with a baseline image.
     *
     * @return A self reference
     */
    @SuppressWarnings("unchecked")
    public T checkWindow() {
        pageHelper.checkWindow(getSimpleName());
        return (T) this;
    }

    /**
     * Perform a visual comparison of the window with a baseline image.
     *
     * @param region Element on page to compare
     * @return A self reference
     */
    @SuppressWarnings("unchecked")
    public T checkRegion(WebElement region) {
        pageHelper.checkRegion(region, getSimpleName());
        return (T) this;
    }

    /**
     * IE will often show a security certificate warning page when accessing a website, if present select continue to website.
     *
     * @param browser Browser
     */
    protected static void ignoreSecurityCertificateWarning(Browser browser) {
        // For some reason unable to access elements on this page, javascript workaround is required
        if (browser.getDriver().getTitle().equals("Certificate Error: Navigation Blocked")) {
            browser.getDriver().navigate().to("javascript:document.getElementById('overridelink').click()");
        }
    }

    /**
     * Check to see if the element is on the page or not.
     *
     * @param element WebElement to search for
     * @return found or not
     */
    protected boolean isElementPresent(WebElement element) {
        return pageHelper.isElementPresent(element);
    }

    /**
     * Check to see if the element is on the page or not.
     *
     * @param driver Reference to WebDriver
     * @param by     How to find the element
     * @return Is the element on the page
     */
    protected static boolean isElementPresent(WebDriver driver, By by) {
        return PageHelper.isElementPresent(driver, by);
    }

    /**
     * Notify listener that it should take a screenshot of the current page.
     *
     *
A default description is constructed assuming that a click is about to be performed on an element
     * in the format: {@literal Clicking '<element text>'}

     *
     * @param element Element to highlight, or null if not applicable
     * @return A self reference
     */
    @SuppressWarnings("unchecked")
    protected T capturePage(WebElement element) {
        pageHelper.capturePage(element);
        return (T) this;
    }

    /**
     * Notify listener that it should take a screenshot of the current page.
     *
     * @param description Description to include with screenshot
     * @return A self reference
     */
    @SuppressWarnings("unchecked")
    public T capturePage(String description) {
        pageHelper.capturePage((WebElement) null, description);
        return (T) this;
    }

    /**
     * Notify listener that it should take a screenshot of the current page.
     *
     * @param element     Element to highlight, or null if not applicable
     * @param description Description to include with screenshot
     * @return A self reference
     */
    @SuppressWarnings("unchecked")
    public T capturePage(WebElement element, String description) {
        pageHelper.capturePage(element, description);
        return (T) this;
    }

    /**
     * Notify listener that it should take a screenshot of the current page.
     *
     * @param screenshotTaker Custom screenshot taker
     * @param description     Description to include with screenshot
     * @return A self reference
     */
    @SuppressWarnings("unchecked")
    public T capturePage(ScreenshotTaker screenshotTaker, String description) {
        pageHelper.capturePage(screenshotTaker, description);
        return (T) this;
    }

    /**
     * Notify listener that it should take a screenshot of the current page.
     *
     * @param element     Element to highlight, or null if not applicable
     * @param description Description to include with screenshot
     * @param result      Status
     * @return A self reference
     */
    @SuppressWarnings("unchecked")
    public T capturePage(WebElement element, String description, CardResult result) {
        pageHelper.capturePage(element, description, result);
        return (T) this;
    }

    /**
     * Notify listener that it should take a screenshot of the current page and then click the supplied element
     * and return a new instance of the expected page.
     *
     *
A default description is constructed in the format: {@literal Clicking '<element text>'}

     *
     * @param
          The type of the desired page object
     * @param element      Element to click
     * @param expectedPage Class of page that should be returned
     * @return new PageObject of type expectedPage
     */
    public  P capturePageAndClick(WebElement element, Class
 expectedPage, Object... params) {
        return pageHelper.capturePageAndClick(element, expectedPage, params);
    }

    /**
     * Notify listener that it should take a screenshot of the current page and then click the supplied element
     * and return a new instance of the expected page.
     *
     * @param
 The type of the desired page object
     * @param element Element to click
     * @param description Description of the action being taken
     * @param expectedPage Class of page that should be returned
     * @param params Optional list of parameters that can be passed in to the constructor
     * @return new PageObject of type expectedPage
     */
    public  P capturePageAndClick(WebElement element, String description, Class
 expectedPage, Object... params) {
        return pageHelper.capturePageAndClick(element, description, expectedPage, params);
    }

    /**
     * Notify listener that it should take a screenshot of the current page and then click the supplied element
     * and return a new instance of the expected page.
     *
     * @param
 The type of the desired page object
     * @param element Element to click
     * @param timeoutSeconds Timeout in Seconds
     * @param description Description of the action being taken
     * @param expectedPage Class of page that should be returned
     * @param params Optional list of parameters that can be passed in to the constructor
     * @return new PageObject of type expectedPage
     */
    public  P capturePageAndClick(WebElement element, int timeoutSeconds, String description, Class
 expectedPage, Object... params) {
        return pageHelper.capturePageAndClick(element, timeoutSeconds, description, expectedPage, params);
    }

    /**
     * Helper method for creating new page objects from an expected class
     *

     * Requires that the expectedPage extends from PageObject and has a public constructor with a single
     * parameter of TestDriveable.
     *
     * @param
 The type of the desired page object
     * @param expectedPage Page that should be returned
     * @param params Optional list of parameters that can be passed in to the constructor
     * @return New instance of supplied page object
     */
    public  P newInstance(Class
 expectedPage, Object... params) {
        return pageHelper.newInstance(expectedPage, params);
    }

    /**
     * Wait for the element to be clickable.
     *
     * @param webElement The element to check is clickable.
     * @param timeOutInSeconds Timeout in Seconds.
     *
     */
    public void waitForElementToClickable(WebElement webElement, int timeOutInSeconds) {
        pageHelper.waitForElementToClickable(webElement, timeOutInSeconds);
    }

    /**
     * Find the first visible element in a list.
     *
     * @param webElements list of elements to search through
     * @return A visible WebElement or null if no visible elements in list
     */
    protected WebElement getFirstVisibleElement(List<WebElement> webElements) {
        return pageHelper.getFirstVisibleElement(webElements);
    }

    /**
     * Override this method to implement any code that needs to be run prior to taking a screen shot,
     * eg fixing floating headers.
     */
    public void prepareForScreenshot() {

    }

    //CHECKSTYLE:OFF - Not handling TimeoutException

    /**
     * A convenience method for executing ExpectedConditions.
     *
     * Ignore {@link WebDriverException}. When a DOM operation is happening on the page it may
     * temporarily cause the element to be inaccessible. Ignore these hierarchy of Exceptions.
     *
     * @param condition The expected condition
     * @param timeOutInSeconds how long to wait for the expected condition to evaluate to true
     * @throws org.openqa.selenium.TimeoutException If the timeout expires
     */
    //CHECKSTYLE:ON
    protected void waitUntil(ExpectedCondition<?> condition, int timeOutInSeconds) {
        WebDriverWait wait = new WebDriverWait(getBrowser().getDriver(), timeOutInSeconds);
        wait.ignoring(WebDriverException.class);
        wait.until(condition);
    }

    /**
     * Similar to WebDriver's switchTo().{@link TargetLocator#defaultContent()} but will always select the main document when a page contains iframes.
     */
    public void switchToMainDocument() {
        pageHelper.switchToMainDocument();
    }

    /**
     * Get the current frame's name or id property.
     *
     * @return Empty string if main document selected otherwise will return name property if set, id property if set, else 'UNKNOWN FRAME'
     * for selected iframe.
     */
    public String getCurrentFrameNameOrId() {
        return pageHelper.getCurrentFrameNameOrId();
    }
}


text:
Simple tool to download all the past year papers from the subjects you are registered to.

###Features
- Automagically fetches all your past year papers based on the subjects you are subscribed to.
- Organizes all the past year papers into relevant folders based on subject.

### To Run
- Compile From Source
  1. Install Ruby
    - Windows
      - http://rubyinstaller.org/ ( Nokogiri does not support Ruby 2.2.0 at time or writing so get 2.0.0   instead)
    - Linux/MacOSX
      - Anyway you wish, but i recommend RVM https://rvm.io/rvm/install
  2. run ` bundle install `
  3. run ` ruby pastyear.rb `

[](Example)
[](Example)


text:
use proxy_wasm::traits::{Context, HttpContext};
use proxy_wasm::types::*;

proxy_wasm::main! {{
    proxy_wasm::set_http_context(|_, _| -> Box<dyn HttpContext> { Box::new(TestStream) });
}}

struct TestStream;

impl Context for TestStream {}

impl HttpContext for TestStream {
    fn on_http_request_headers(&mut self, _: usize, _: bool) -> Action {
        self.reset_http_request();
        Action::Continue
    }

    fn on_http_response_headers(&mut self, _: usize, _: bool) -> Action {
        self.reset_http_response();
        Action::Continue
    }
}


text:
package scato
package clazz

import scala.language.implicitConversions

trait ApplicativeSyntax {
  implicit def applicativeOpsA[A](a: A): ApplicativeSyntax.OpsA[A] = new ApplicativeSyntax.OpsA(a)
}

object ApplicativeSyntax {
  class OpsA[A](a: A) {
    def pure[F[_]](implicit F: Applicative[F]): F[A] = F.pure(a)
  }
}


text:
class CreateChannels < ActiveRecord::Migration[5.0]
  def change
    create_table :channels do |t|
      t.string :name
      t.text :description
      t.belongs_to :report

      t.timestamps
    end
  end
end