text:
package org.apache.ignite.jdbc.thin;

import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.concurrent.Callable;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.lang.RunnableX;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.junit.Assert;
import org.junit.Test;

import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
import static org.apache.ignite.testframework.GridTestUtils.assertThrows;
import static org.apache.ignite.testframework.GridTestUtils.assertThrowsAnyCause;

/**
 * Result set test.
 */
@SuppressWarnings({"FloatingPointEquality", "ThrowableNotThrown", "AssertWithSideEffects"})
public class JdbcThinResultSetSelfTest extends JdbcThinAbstractSelfTest {
    /** URL. */
    private static final String URL = "jdbc:ignite:thin://127.0.0.1/";

    /** SQL query. */
    private static final String SQL =
        "select id, boolVal, byteVal, shortVal, intVal, longVal, floatVal, " +
            "doubleVal, bigVal, strVal, arrVal, dateVal, timeVal, tsVal, objVal " +
            "from TestObject where id = 1";

    /** Statement. */
    private Statement stmt;

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        CacheConfiguration<?, ?> cache = defaultCacheConfiguration();

        cache.setCacheMode(PARTITIONED);
        cache.setBackups(1);
        cache.setWriteSynchronizationMode(FULL_SYNC);
        cache.setIndexedTypes(
            Integer.class, TestObject.class
        );

        cfg.setCacheConfiguration(cache);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        startGridsMultiThreaded(3);

        IgniteCache<Integer, TestObject> cache = grid(0).cache(DEFAULT_CACHE_NAME);

        assert cache != null;

        TestObject o = createObjectWithData(1);

        cache.put(1, o);
        cache.put(2, new TestObject(2));
    }

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        Connection conn = DriverManager.getConnection(URL);

        conn.setSchema('"' + DEFAULT_CACHE_NAME + '"');

        stmt = conn.createStatement();

        assert stmt != null;
        assert !stmt.isClosed();
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        if (stmt != null) {
            stmt.getConnection().close();

            stmt.close();

            assert stmt.isClosed();
        }
    }

    /**
     * @param id ID.
     * @return Object.
     * @throws MalformedURLException If URL in incorrect.
     */
    @SuppressWarnings("deprecation")
    private TestObject createObjectWithData(int id) throws MalformedURLException {
        TestObject o = new TestObject(id);

        o.boolVal = true;
        o.byteVal = 1;
        o.shortVal = 1;
        o.intVal = 1;
        o.longVal = 1L;
        o.floatVal = 1.0f;
        o.doubleVal = 1.0d;
        o.bigVal = new BigDecimal(1);
        o.strVal = "1";
        o.arrVal = new byte[] {1};
        o.dateVal = new Date(1, 1, 1);
        o.timeVal = new Time(1, 1, 1);
        o.tsVal = new Timestamp(1);
        o.urlVal = new URL("http://abc.com/");

        return o;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testBoolean() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getBoolean("boolVal");
                assert rs.getBoolean(2);
                assert rs.getByte(2) == 1;
                assert rs.getInt(2) == 1;
                assert rs.getShort(2) == 1;
                assert rs.getLong(2) == 1;
                assert rs.getDouble(2) == 1.0;
                assert rs.getFloat(2) == 1.0f;
                assert rs.getBigDecimal(2).equals(new BigDecimal(1));
                assert rs.getString(2).equals("true");

                assert rs.getObject(2, Boolean.class);
                assert rs.getObject(2, Byte.class) == 1;
                assert rs.getObject(2, Short.class) == 1;
                assert rs.getObject(2, Integer.class) == 1;
                assert rs.getObject(2, Long.class) == 1;
                assert rs.getObject(2, Float.class) == 1.f;
                assert rs.getObject(2, Double.class) == 1;
                assert rs.getObject(2, BigDecimal.class).equals(new BigDecimal(1));
                assert rs.getObject(2, String.class).equals("true");
            }

            cnt++;
        }

        assert cnt == 1;

        ResultSet rs0 = stmt.executeQuery("select 1");

        assert rs0.next();
        assert rs0.getBoolean(1);

        rs0 = stmt.executeQuery("select 0");

        assert rs0.next();
        assert !rs0.getBoolean(1);

        rs0 = stmt.executeQuery("select '1'");

        assert rs0.next();
        assert rs0.getBoolean(1);

        rs0 = stmt.executeQuery("select '0'");

        assert rs0.next();
        assert !rs0.getBoolean(1);

        assertThrowsAnyCause(log, new Callable<Void>() {
            @Override public Void call() throws Exception {
                ResultSet rs0 = stmt.executeQuery("select ''");

                assert rs0.next();
                assert rs0.getBoolean(1);

                return null;
            }
        }, SQLException.class, "Cannot convert to boolean: ");

        assertThrowsAnyCause(log, new Callable<Void>() {
            @Override public Void call() throws Exception {
                ResultSet rs0 = stmt.executeQuery("select 'qwe'");

                assert rs0.next();
                assert rs0.getBoolean(1);

                return null;
            }
        }, SQLException.class, "Cannot convert to boolean: qwe");
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testByte() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getByte("byteVal") == 1;

                assert rs.getBoolean(3);
                assert rs.getByte(3) == 1;
                assert rs.getInt(3) == 1;
                assert rs.getShort(3) == 1;
                assert rs.getLong(3) == 1;
                assert rs.getDouble(3) == 1.0;
                assert rs.getFloat(3) == 1.0f;
                assert rs.getBigDecimal(3).equals(new BigDecimal(1));
                assert rs.getString(3).equals("1");

                assert rs.getObject(3, Boolean.class);
                assert rs.getObject(3, Byte.class) == 1;
                assert rs.getObject(3, Short.class) == 1;
                assert rs.getObject(3, Integer.class) == 1;
                assert rs.getObject(3, Long.class) == 1;
                assert rs.getObject(3, Float.class) == 1.f;
                assert rs.getObject(3, Double.class) == 1;
                assert rs.getObject(3, BigDecimal.class).equals(new BigDecimal(1));
                assert rs.getObject(3, String.class).equals("1");
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testShort() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getShort("shortVal") == 1;

                assert rs.getBoolean(4);
                assert rs.getByte(4) == 1;
                assert rs.getShort(4) == 1;
                assert rs.getInt(4) == 1;
                assert rs.getLong(4) == 1;
                assert rs.getDouble(4) == 1.0;
                assert rs.getFloat(4) == 1.0f;
                assert rs.getBigDecimal(4).equals(new BigDecimal(1));
                assert rs.getString(4).equals("1");

                assert rs.getObject(4, Boolean.class);
                assert rs.getObject(4, Byte.class) == 1;
                assert rs.getObject(4, Short.class) == 1;
                assert rs.getObject(4, Integer.class) == 1;
                assert rs.getObject(4, Long.class) == 1;
                assert rs.getObject(4, Float.class) == 1.f;
                assert rs.getObject(4, Double.class) == 1;
                assert rs.getObject(4, BigDecimal.class).equals(new BigDecimal(1));
                assert rs.getObject(4, String.class).equals("1");
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testInteger() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getInt("intVal") == 1;

                assert rs.getBoolean(5);
                assert rs.getByte(5) == 1;
                assert rs.getShort(5) == 1;
                assert rs.getInt(5) == 1;
                assert rs.getLong(5) == 1;
                assert rs.getDouble(5) == 1.0;
                assert rs.getFloat(5) == 1.0f;
                assert rs.getBigDecimal(5).equals(new BigDecimal(1));
                assert rs.getString(5).equals("1");

                assert rs.getObject(5, Boolean.class);
                assert rs.getObject(5, Byte.class) == 1;
                assert rs.getObject(5, Short.class) == 1;
                assert rs.getObject(5, Integer.class) == 1;
                assert rs.getObject(5, Long.class) == 1;
                assert rs.getObject(5, Float.class) == 1.f;
                assert rs.getObject(5, Double.class) == 1;
                assert rs.getObject(5, BigDecimal.class).equals(new BigDecimal(1));
                assert rs.getObject(5, String.class).equals("1");
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testLong() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getLong("longVal") == 1;

                assert rs.getBoolean(6);
                assert rs.getByte(6) == 1;
                assert rs.getShort(6) == 1;
                assert rs.getInt(6) == 1;
                assert rs.getLong(6) == 1;
                assert rs.getDouble(6) == 1.0;
                assert rs.getFloat(6) == 1.0f;
                assert rs.getBigDecimal(6).equals(new BigDecimal(1));
                assert rs.getString(6).equals("1");

                assert rs.getObject(6, Boolean.class);
                assert rs.getObject(6, Byte.class) == 1;
                assert rs.getObject(6, Short.class) == 1;
                assert rs.getObject(6, Integer.class) == 1;
                assert rs.getObject(6, Long.class) == 1;
                assert rs.getObject(6, Float.class) == 1.f;
                assert rs.getObject(6, Double.class) == 1;
                assert rs.getObject(6, BigDecimal.class).equals(new BigDecimal(1));
                assert rs.getObject(6, String.class).equals("1");
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testFloat() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getFloat("floatVal") == 1.0;

                assert rs.getBoolean(7);
                assert rs.getByte(7) == 1;
                assert rs.getShort(7) == 1;
                assert rs.getInt(7) == 1;
                assert rs.getLong(7) == 1;
                assert rs.getDouble(7) == 1.0;
                assert rs.getFloat(7) == 1.0f;
                assert rs.getBigDecimal(7).equals(new BigDecimal(1));
                assert rs.getString(7).equals("1.0");

                assert rs.getObject(7, Boolean.class);
                assert rs.getObject(7, Byte.class) == 1;
                assert rs.getObject(7, Short.class) == 1;
                assert rs.getObject(7, Integer.class) == 1;
                assert rs.getObject(7, Long.class) == 1;
                assert rs.getObject(7, Float.class) == 1.f;
                assert rs.getObject(7, Double.class) == 1;
                assert rs.getObject(7, BigDecimal.class).equals(new BigDecimal(1));
                assert rs.getObject(7, String.class).equals("1.0");
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDouble() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getDouble("doubleVal") == 1.0;

                assert rs.getBoolean(8);
                assert rs.getByte(8) == 1;
                assert rs.getShort(8) == 1;
                assert rs.getInt(8) == 1;
                assert rs.getLong(8) == 1;
                assert rs.getDouble(8) == 1.0;
                assert rs.getFloat(8) == 1.0f;
                assert rs.getBigDecimal(8).equals(new BigDecimal(1));
                assert rs.getString(8).equals("1.0");

                assert rs.getObject(8, Boolean.class);
                assert rs.getObject(8, Byte.class) == 1;
                assert rs.getObject(8, Short.class) == 1;
                assert rs.getObject(8, Integer.class) == 1;
                assert rs.getObject(8, Long.class) == 1;
                assert rs.getObject(8, Float.class) == 1.f;
                assert rs.getObject(8, Double.class) == 1;
                assert rs.getObject(8, BigDecimal.class).equals(new BigDecimal(1));
                assert rs.getObject(8, String.class).equals("1.0");
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testBigDecimal() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getBigDecimal("bigVal").intValue() == 1;

                assert rs.getBoolean(9);
                assert rs.getByte(9) == 1;
                assert rs.getShort(9) == 1;
                assert rs.getInt(9) == 1;
                assert rs.getLong(9) == 1;
                assert rs.getDouble(9) == 1.0;
                assert rs.getFloat(9) == 1.0f;
                assert rs.getBigDecimal(9).equals(new BigDecimal(1));
                assert rs.getString(9).equals("1");

                assert rs.getObject(9, Boolean.class);
                assert rs.getObject(9, Byte.class) == 1;
                assert rs.getObject(9, Short.class) == 1;
                assert rs.getObject(9, Integer.class) == 1;
                assert rs.getObject(9, Long.class) == 1;
                assert rs.getObject(9, Float.class) == 1.f;
                assert rs.getObject(9, Double.class) == 1;
                assert rs.getObject(9, BigDecimal.class).equals(new BigDecimal(1));
                assert rs.getObject(9, String.class).equals("1");
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testBigDecimalScale() throws Exception {
        assert "0.12".equals(convertStringToBigDecimalViaJdbc("0.1234", 2).toString());
        assert "1.001".equals(convertStringToBigDecimalViaJdbc("1.0005", 3).toString());
        assert "1E+3".equals(convertStringToBigDecimalViaJdbc("1205.5", -3).toString());
        assert "1.3E+4".equals(convertStringToBigDecimalViaJdbc("12505.5", -3).toString());
    }

    /**
     * @param strDec String representation of a decimal value.
     * @param scale Scale.
     * @return BigDecimal object.
     * @throws SQLException On error.
     */
    private BigDecimal convertStringToBigDecimalViaJdbc(String strDec, int scale) throws SQLException {
        try (ResultSet rs = stmt.executeQuery("select '" + strDec + "'")) {
            assert rs.next();

            return rs.getBigDecimal(1, scale);
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testString() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert "1".equals(rs.getString("strVal"));

                assert rs.getBoolean(10);
                assert rs.getByte(10) == 1;
                assert rs.getShort(10) == 1;
                assert rs.getInt(10) == 1;
                assert rs.getLong(10) == 1;
                assert rs.getDouble(10) == 1.0;
                assert rs.getFloat(10) == 1.0f;
                assert rs.getBigDecimal(10).equals(new BigDecimal("1"));
                assert rs.getString(10).equals("1");

                assert rs.getObject(10, Boolean.class);
                assert rs.getObject(10, Byte.class) == 1;
                assert rs.getObject(10, Short.class) == 1;
                assert rs.getObject(10, Integer.class) == 1;
                assert rs.getObject(10, Long.class) == 1;
                assert rs.getObject(10, Float.class) == 1.f;
                assert rs.getObject(10, Double.class) == 1;
                assert rs.getObject(10, BigDecimal.class).equals(new BigDecimal(1));
                assert rs.getObject(10, String.class).equals("1");
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testArray() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert Arrays.equals(rs.getBytes("arrVal"), new byte[] {1});
                assert Arrays.equals(rs.getBytes(11), new byte[] {1});
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @SuppressWarnings("deprecation")
    @Test
    public void testDate() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getDate("dateVal").equals(new Date(1, 1, 1));

                assert rs.getDate(12).equals(new Date(1, 1, 1));
                assert rs.getTime(12).equals(new Time(new Date(1, 1, 1).getTime()));
                assert rs.getTimestamp(12).equals(new Timestamp(new Date(1, 1, 1).getTime()));

                assert rs.getObject(12, Date.class).equals(new Date(1, 1, 1));
                assert rs.getObject(12, Time.class).equals(new Time(new Date(1, 1, 1).getTime()));
                assert rs.getObject(12, Timestamp.class).equals(new Timestamp(new Date(1, 1, 1).getTime()));
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @SuppressWarnings("deprecation")
    @Test
    public void testTime() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getTime("timeVal").equals(new Time(1, 1, 1));

                assert rs.getDate(13).equals(new Date(new Time(1, 1, 1).getTime()));
                assert rs.getTime(13).equals(new Time(1, 1, 1));
                assert rs.getTimestamp(13).equals(new Timestamp(new Time(1, 1, 1).getTime()));

                assert rs.getObject(13, Date.class).equals(new Date(new Time(1, 1, 1).getTime()));
                assert rs.getObject(13, Time.class).equals(new Time(1, 1, 1));
                assert rs.getObject(13, Timestamp.class).equals(new Timestamp(new Time(1, 1, 1).getTime()));
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testTimestamp() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        while (rs.next()) {
            if (cnt == 0) {
                assert rs.getTimestamp("tsVal").getTime() == 1;

                assert rs.getDate(14).equals(new Date(new Timestamp(1).getTime()));
                assert rs.getTime(14).equals(new Time(new Timestamp(1).getTime()));
                assert rs.getTimestamp(14).equals(new Timestamp(1));

                assert rs.getObject(14, Date.class).equals(new Date(new Timestamp(1).getTime()));
                assert rs.getObject(14, Time.class).equals(new Time(new Timestamp(1).getTime()));
                assert rs.getObject(14, Timestamp.class).equals(new Timestamp(1));
            }

            cnt++;
        }

        assert cnt == 1;
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testObject() throws Exception {
        ResultSet rs = stmt.executeQuery(SQL);

        int cnt = 0;

        TestObjectField exp = new TestObjectField(100, "AAAA");

        while (rs.next()) {
            if (cnt == 0) {
                Assert.assertEquals("Result by column label mismatch", exp, rs.getObject("objVal"));

                Assert.assertEquals("Result by column index mismatch", exp, rs.getObject(15));

                Assert.assertEquals("Result by column index with general cast mismatch",
                    exp, rs.getObject(15, Object.class));

                Assert.assertEquals("Result by column index with precise cast mismatch",
                    exp, rs.getObject(15, TestObjectField.class));
            }

            cnt++;
        }

        Assert.assertEquals("Result count mismatch", 1, cnt);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testNavigation() throws Exception {
        ResultSet rs = stmt.executeQuery("select id from TestObject where id > 0");

        assert rs.isBeforeFirst();
        assert !rs.isAfterLast();
        assert !rs.isFirst();
        assert !rs.isLast();
        assert rs.getRow() == 0;

        assert rs.next();

        assert !rs.isBeforeFirst();
        assert !rs.isAfterLast();
        assert rs.isFirst();
        assert !rs.isLast();
        assert rs.getRow() == 1;

        assert rs.next();

        assert !rs.isBeforeFirst();
        assert !rs.isAfterLast();
        assert !rs.isFirst();
        assert rs.isLast();
        assert rs.getRow() == 2;

        assert !rs.next();

        assert !rs.isBeforeFirst();
        assert rs.isAfterLast();
        assert !rs.isFirst();
        assert !rs.isLast();
        assert rs.getRow() == 0;

        rs = stmt.executeQuery("select id from TestObject where id < 0");

        assert !rs.isBeforeFirst();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testFindColumn() throws Exception {
        final ResultSet rs = stmt.executeQuery(SQL);

        assert rs != null;
        assert rs.next();

        assert rs.findColumn("id") == 1;

        assertThrows(
            log,
            new Callable<Object>() {
                @Override public Object call() throws Exception {
                    rs.findColumn("wrong");

                    return null;
                }
            },
            SQLException.class,
            "Column not found: wrong"
        );
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testNotSupportedTypes() throws Exception {
        final ResultSet rs = stmt.executeQuery(SQL);

        assert rs.next();

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getArray(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getArray("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getAsciiStream(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getAsciiStream("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getBinaryStream(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getBinaryStream("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getBlob(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getBlob("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getClob(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getClob("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getCharacterStream(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getCharacterStream("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getNCharacterStream(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getNCharacterStream("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getNClob(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getNClob("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getRef(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getRef("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getRowId(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getRowId("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getSQLXML(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getSQLXML("id");
            }
        });
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testUpdateNotSupported() throws Exception {
        final ResultSet rs = stmt.executeQuery(SQL);

        assert rs.next();

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBoolean(1, true);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBoolean("id", true);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateByte(1, (byte)0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateByte("id", (byte)0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateShort(1, (short)0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateShort("id", (short)0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateInt(1, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateInt("id", 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateLong(1, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateLong("id", 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateFloat(1, (float)0.0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateFloat("id", (float)0.0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateDouble(1, 0.0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateDouble("id", 0.0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateString(1, "");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateString("id", "");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateTime(1, new Time(0));
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateTime("id", new Time(0));
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateDate(1, new Date(0));
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateDate("id", new Date(0));
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateTimestamp(1, new Timestamp(0));
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateTimestamp("id", new Timestamp(0));
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBytes(1, new byte[]{});
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBytes("id", new byte[]{});
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateArray(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateArray("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBlob(1, (Blob)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBlob(1, (InputStream)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBlob(1, null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBlob("id", (Blob)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBlob("id", (InputStream)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBlob("id", null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateClob(1, (Clob)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateClob(1, (Reader)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateClob(1, null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateClob("id", (Clob)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateClob("id", (Reader)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateClob("id", null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNClob(1, (NClob)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNClob(1, (Reader)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNClob(1, null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNClob("id", (NClob)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNClob("id", (Reader)null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNClob("id", null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateAsciiStream(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateAsciiStream(1, null, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateAsciiStream(1, null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateAsciiStream("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateAsciiStream("id", null, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateAsciiStream("id", null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateCharacterStream(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateCharacterStream(1, null, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateCharacterStream(1, null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateCharacterStream("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateCharacterStream("id", null, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateCharacterStream("id", null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNCharacterStream(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNCharacterStream(1, null, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNCharacterStream(1, null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNCharacterStream("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNCharacterStream("id", null, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNCharacterStream("id", null, 0L);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateRef(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateRef("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateRowId(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateRowId("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNString(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNString("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateSQLXML(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateSQLXML("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateObject(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateObject(1, null, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateObject("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateObject("id", null, 0);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBigDecimal(1, null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateBigDecimal("id", null);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNull(1);
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateNull("id");
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.cancelRowUpdates();
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.updateRow();
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.deleteRow();
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.insertRow();
            }
        });

        checkNotSupported(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.moveToInsertRow();
            }
        });
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testExceptionOnClosedResultSet() throws Exception {
        final ResultSet rs = stmt.executeQuery(SQL);

        rs.close();

        // Must do nothing on closed result set
        rs.close();

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getBoolean(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getBoolean("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getByte(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getByte("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getShort(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getShort("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getInt(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getInt("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getLong(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getLong("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getFloat(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getFloat("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getDouble(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getDouble("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getString(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getString("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getBytes(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getBytes("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getDate(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getDate(1, new GregorianCalendar());
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getDate("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getDate("id", new GregorianCalendar());
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getTime(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getTime(1, new GregorianCalendar());
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getTime("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getTime("id", new GregorianCalendar());
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getTimestamp(1);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getTimestamp(1, new GregorianCalendar());
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getTimestamp("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getTimestamp("id", new GregorianCalendar());
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getObject("objVal");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getObject("objVal", TestObjectField.class);
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.wasNull();
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getMetaData();
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.next();
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.last();
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.afterLast();
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.beforeFirst();
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.first();
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.findColumn("id");
            }
        });

        checkResultSetClosed(new RunnableX() {
            @Override public void runx() throws Exception {
                rs.getRow();
            }
        });
    }

    /**
     * Test object.
     */
    private static class TestObject implements Serializable {
        /** */
        @QuerySqlField
        private final int id;

        /** */
        @QuerySqlField
        private Boolean boolVal;

        /** */
        @QuerySqlField
        private Byte byteVal;

        /** */
        @QuerySqlField
        private Short shortVal;

        /** */
        @QuerySqlField
        private Integer intVal;

        /** */
        @QuerySqlField
        private Long longVal;

        /** */
        @QuerySqlField
        private Float floatVal;

        /** */
        @QuerySqlField
        private Double doubleVal;

        /** */
        @QuerySqlField
        private BigDecimal bigVal;

        /** */
        @QuerySqlField
        private String strVal;

        /** */
        @QuerySqlField
        private byte[] arrVal;

        /** */
        @QuerySqlField
        private Date dateVal;

        /** */
        @QuerySqlField
        private Time timeVal;

        /** */
        @QuerySqlField
        private Timestamp tsVal;

        /** */
        @QuerySqlField
        private URL urlVal;

        /** */
        @QuerySqlField
        private TestObjectField objVal = new TestObjectField(100, "AAAA");

        /** */
        @QuerySqlField
        private TestObjectField f2 = new TestObjectField(500, "BBBB");

        /** */
        @QuerySqlField
        private TestObjectField f3;

        /**
         * @param id ID.
         */
        private TestObject(int id) {
            this.id = id;
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            return S.toString(TestObject.class, this);
        }

        /** {@inheritDoc} */
        @SuppressWarnings({"BigDecimalEquals", "EqualsHashCodeCalledOnUrl", "RedundantIfStatement"})
        @Override public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            TestObject that = (TestObject)o;

            if (id != that.id) return false;
            if (!Arrays.equals(arrVal, that.arrVal)) return false;
            if (bigVal != null ? !bigVal.equals(that.bigVal) : that.bigVal != null) return false;
            if (boolVal != null ? !boolVal.equals(that.boolVal) : that.boolVal != null) return false;
            if (byteVal != null ? !byteVal.equals(that.byteVal) : that.byteVal != null) return false;
            if (dateVal != null ? !dateVal.equals(that.dateVal) : that.dateVal != null) return false;
            if (doubleVal != null ? !doubleVal.equals(that.doubleVal) : that.doubleVal != null) return false;
            if (objVal != null ? !objVal.equals(that.objVal) : that.objVal != null) return false;
            if (f2 != null ? !f2.equals(that.f2) : that.f2 != null) return false;
            if (f3 != null ? !f3.equals(that.f3) : that.f3 != null) return false;
            if (floatVal != null ? !floatVal.equals(that.floatVal) : that.floatVal != null) return false;
            if (intVal != null ? !intVal.equals(that.intVal) : that.intVal != null) return false;
            if (longVal != null ? !longVal.equals(that.longVal) : that.longVal != null) return false;
            if (shortVal != null ? !shortVal.equals(that.shortVal) : that.shortVal != null) return false;
            if (strVal != null ? !strVal.equals(that.strVal) : that.strVal != null) return false;
            if (timeVal != null ? !timeVal.equals(that.timeVal) : that.timeVal != null) return false;
            if (tsVal != null ? !tsVal.equals(that.tsVal) : that.tsVal != null) return false;
            if (urlVal != null ? !urlVal.equals(that.urlVal) : that.urlVal != null) return false;

            return true;
        }

        /** {@inheritDoc} */
        @SuppressWarnings("EqualsHashCodeCalledOnUrl")
        @Override public int hashCode() {
            int res = id;

            res = 31 * res + (boolVal != null ? boolVal.hashCode() : 0);
            res = 31 * res + (byteVal != null ? byteVal.hashCode() : 0);
            res = 31 * res + (shortVal != null ? shortVal.hashCode() : 0);
            res = 31 * res + (intVal != null ? intVal.hashCode() : 0);
            res = 31 * res + (longVal != null ? longVal.hashCode() : 0);
            res = 31 * res + (floatVal != null ? floatVal.hashCode() : 0);
            res = 31 * res + (doubleVal != null ? doubleVal.hashCode() : 0);
            res = 31 * res + (bigVal != null ? bigVal.hashCode() : 0);
            res = 31 * res + (strVal != null ? strVal.hashCode() : 0);
            res = 31 * res + (arrVal != null ? Arrays.hashCode(arrVal) : 0);
            res = 31 * res + (dateVal != null ? dateVal.hashCode() : 0);
            res = 31 * res + (timeVal != null ? timeVal.hashCode() : 0);
            res = 31 * res + (tsVal != null ? tsVal.hashCode() : 0);
            res = 31 * res + (urlVal != null ? urlVal.hashCode() : 0);
            res = 31 * res + (objVal != null ? objVal.hashCode() : 0);
            res = 31 * res + (f2 != null ? f2.hashCode() : 0);
            res = 31 * res + (f3 != null ? f3.hashCode() : 0);

            return res;
        }
    }

    /**
     * Test object field.
     */
    @SuppressWarnings("PackageVisibleField")
    private static class TestObjectField implements Serializable {
        /** */
        final int a;

        /** */
        final String b;

        /**
         * @param a A.
         * @param b B.
         */
        private TestObjectField(int a, String b) {
            this.a = a;
            this.b = b;
        }

        /** {@inheritDoc} */
        @Override public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            TestObjectField that = (TestObjectField)o;

            return a == that.a && !(b != null ? !b.equals(that.b) : that.b != null);
        }

        /** {@inheritDoc} */
        @Override public int hashCode() {
            int res = a;

            res = 31 * res + (b != null ? b.hashCode() : 0);

            return res;
        }

        /** {@inheritDoc} */
        @Override public String toString() {
            return S.toString(TestObjectField.class, this);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
public class Blort
{
    /**
     * just because this should do nothing
     */
    void voidFunction() {
    }

    /**
     * Current SSA form requires each move-exception block to have
     * a unique predecessor
     */
    void edgeSplitMoveException() {
        try {
            hashCode();
            hashCode();
        } catch (Throwable tr) {
        }
    }

    /**
     * An empty infinite loop for the empty goto optimizer
     */
    void infiniteLoop() {
        while (true) {
        }
    }
}


text:
from setuptools import setup
setup(
    name = "SimpleDaemon",
    version = "1.0.2",
    packages = ['simple_daemon'],
    # metadata
    author = "Roman Shuvalov",
    author_email = "orangato@yandex.ru",
    description = "Simple daemon package. Import Daemon class, subclass it, override run method and you ready.",
    keywords = "simple daemon",
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.eeeya.fantuan.server.mapper.YfRestaurantMapper">
  <resultMap id="BaseResultMap" type="com.eeeya.fantuan.server.domain.YfRestaurant">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="short_name" jdbcType="VARCHAR" property="shortName" />
    <result column="full_name" jdbcType="VARCHAR" property="fullName" />
    <result column="max_table" jdbcType="INTEGER" property="maxTable" />
    <result column="restaurant_phone" jdbcType="VARCHAR" property="restaurantPhone" />
    <result column="restaurant_address" jdbcType="VARCHAR" property="restaurantAddress" />
    <result column="restaurant_longitude" jdbcType="DOUBLE" property="restaurantLongitude" />
    <result column="restaurant_latitude" jdbcType="DOUBLE" property="restaurantLatitude" />
    <result column="dianping_url" jdbcType="VARCHAR" property="dianpingUrl" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    id, short_name, full_name, max_table, restaurant_phone, restaurant_address, restaurant_longitude,
    restaurant_latitude, dianping_url
  </sql>
  <select id="selectByExample" parameterType="com.eeeya.fantuan.server.domain.YfRestaurantExample" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from yf_restaurant
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
    <if test="offset!=-1">
      limit ${offset}, ${rows}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select
    <include refid="Base_Column_List" />
    from yf_restaurant
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from yf_restaurant
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <delete id="deleteByExample" parameterType="com.eeeya.fantuan.server.domain.YfRestaurantExample">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from yf_restaurant
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.eeeya.fantuan.server.domain.YfRestaurant">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into yf_restaurant (short_name, full_name, max_table,
      restaurant_phone, restaurant_address, restaurant_longitude,
      restaurant_latitude, dianping_url)
    values (#{shortName,jdbcType=VARCHAR}, #{fullName,jdbcType=VARCHAR}, #{maxTable,jdbcType=INTEGER},
      #{restaurantPhone,jdbcType=VARCHAR}, #{restaurantAddress,jdbcType=VARCHAR}, #{restaurantLongitude,jdbcType=DOUBLE},
      #{restaurantLatitude,jdbcType=DOUBLE}, #{dianpingUrl,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.eeeya.fantuan.server.domain.YfRestaurant">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into yf_restaurant
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="shortName != null">
        short_name,
      </if>
      <if test="fullName != null">
        full_name,
      </if>
      <if test="maxTable != null">
        max_table,
      </if>
      <if test="restaurantPhone != null">
        restaurant_phone,
      </if>
      <if test="restaurantAddress != null">
        restaurant_address,
      </if>
      <if test="restaurantLongitude != null">
        restaurant_longitude,
      </if>
      <if test="restaurantLatitude != null">
        restaurant_latitude,
      </if>
      <if test="dianpingUrl != null">
        dianping_url,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="shortName != null">
        #{shortName,jdbcType=VARCHAR},
      </if>
      <if test="fullName != null">
        #{fullName,jdbcType=VARCHAR},
      </if>
      <if test="maxTable != null">
        #{maxTable,jdbcType=INTEGER},
      </if>
      <if test="restaurantPhone != null">
        #{restaurantPhone,jdbcType=VARCHAR},
      </if>
      <if test="restaurantAddress != null">
        #{restaurantAddress,jdbcType=VARCHAR},
      </if>
      <if test="restaurantLongitude != null">
        #{restaurantLongitude,jdbcType=DOUBLE},
      </if>
      <if test="restaurantLatitude != null">
        #{restaurantLatitude,jdbcType=DOUBLE},
      </if>
      <if test="dianpingUrl != null">
        #{dianpingUrl,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.eeeya.fantuan.server.domain.YfRestaurantExample" resultType="java.lang.Integer">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select count(*) from yf_restaurant
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update yf_restaurant
    <set>
      <if test="record.id != null">
        id = #{record.id,jdbcType=BIGINT},
      </if>
      <if test="record.shortName != null">
        short_name = #{record.shortName,jdbcType=VARCHAR},
      </if>
      <if test="record.fullName != null">
        full_name = #{record.fullName,jdbcType=VARCHAR},
      </if>
      <if test="record.maxTable != null">
        max_table = #{record.maxTable,jdbcType=INTEGER},
      </if>
      <if test="record.restaurantPhone != null">
        restaurant_phone = #{record.restaurantPhone,jdbcType=VARCHAR},
      </if>
      <if test="record.restaurantAddress != null">
        restaurant_address = #{record.restaurantAddress,jdbcType=VARCHAR},
      </if>
      <if test="record.restaurantLongitude != null">
        restaurant_longitude = #{record.restaurantLongitude,jdbcType=DOUBLE},
      </if>
      <if test="record.restaurantLatitude != null">
        restaurant_latitude = #{record.restaurantLatitude,jdbcType=DOUBLE},
      </if>
      <if test="record.dianpingUrl != null">
        dianping_url = #{record.dianpingUrl,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update yf_restaurant
    set id = #{record.id,jdbcType=BIGINT},
      short_name = #{record.shortName,jdbcType=VARCHAR},
      full_name = #{record.fullName,jdbcType=VARCHAR},
      max_table = #{record.maxTable,jdbcType=INTEGER},
      restaurant_phone = #{record.restaurantPhone,jdbcType=VARCHAR},
      restaurant_address = #{record.restaurantAddress,jdbcType=VARCHAR},
      restaurant_longitude = #{record.restaurantLongitude,jdbcType=DOUBLE},
      restaurant_latitude = #{record.restaurantLatitude,jdbcType=DOUBLE},
      dianping_url = #{record.dianpingUrl,jdbcType=VARCHAR}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.eeeya.fantuan.server.domain.YfRestaurant">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update yf_restaurant
    <set>
      <if test="shortName != null">
        short_name = #{shortName,jdbcType=VARCHAR},
      </if>
      <if test="fullName != null">
        full_name = #{fullName,jdbcType=VARCHAR},
      </if>
      <if test="maxTable != null">
        max_table = #{maxTable,jdbcType=INTEGER},
      </if>
      <if test="restaurantPhone != null">
        restaurant_phone = #{restaurantPhone,jdbcType=VARCHAR},
      </if>
      <if test="restaurantAddress != null">
        restaurant_address = #{restaurantAddress,jdbcType=VARCHAR},
      </if>
      <if test="restaurantLongitude != null">
        restaurant_longitude = #{restaurantLongitude,jdbcType=DOUBLE},
      </if>
      <if test="restaurantLatitude != null">
        restaurant_latitude = #{restaurantLatitude,jdbcType=DOUBLE},
      </if>
      <if test="dianpingUrl != null">
        dianping_url = #{dianpingUrl,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.eeeya.fantuan.server.domain.YfRestaurant">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update yf_restaurant
    set short_name = #{shortName,jdbcType=VARCHAR},
      full_name = #{fullName,jdbcType=VARCHAR},
      max_table = #{maxTable,jdbcType=INTEGER},
      restaurant_phone = #{restaurantPhone,jdbcType=VARCHAR},
      restaurant_address = #{restaurantAddress,jdbcType=VARCHAR},
      restaurant_longitude = #{restaurantLongitude,jdbcType=DOUBLE},
      restaurant_latitude = #{restaurantLatitude,jdbcType=DOUBLE},
      dianping_url = #{dianpingUrl,jdbcType=VARCHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>


text:
$(document).ready(function() {
    var knowledgeId = $('#knowledgeId').val();
    if (knowledgeId) {
        $('#survey_info').addClass('hide');
        $('#survey_edit').removeClass('hide');
        document._TEMPLATE.editable = true;
        $('#items').html('');
        document.__load_survey(_CONTEXT + '/open.survey/load/' + knowledgeId);
    }

    $('#deletebutton').click(function(){
        var knowledgeId = $('#knowledgeId').val();
        bootbox.confirm("Are you sure delete?", function(result) {
            if (result) {
                $.ajax({
                    url: _CONTEXT + '/protect.survey/delete/' + knowledgeId,
                    type: 'DELETE',
                    timeout: 10000  // 単位はミリ秒
                }).done(function(result, textStatus, xhr) {
                    $.notify(result.message, 'success');
                }).fail(function(xhr, textStatus, error) {
                    handleErrorResponse(xhr, textStatus, error);
                });
            }
        });
    });

    $('#btnShowAnswer').click(function(){
        $('#editSurvey').modal('hide');
        $('#modalAnswerSurvey').modal('show');
    });

    // フォームのサブミットは禁止
    $('#surveyForm').submit(function(event) {
        logging('submit. ' + $('#typeId').val());
        // 操作対象のフォーム要素を取得
        var $form = $(this);
        // ページ遷移を禁止して、Ajaxで保存
        event.preventDefault();

        // 送信ボタンを取得
        // (後で使う: 二重送信を防止する。)
        var $button = $form.find('button');

        // ボタンを無効化し、二重送信を防止
        $button.attr('disabled', true);
        // 送信
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            timeout: 10000,  // 単位はミリ秒
        }).done(function(result, textStatus, xhr) {
            // 入力値を初期化
            console.log(result);
            $.notify(result.message, 'info');
            if ($form.attr('action') == (_CONTEXT + '/protect.survey/delete')) {
                // 削除完了時の処理
            }
            $('#deletebutton').removeClass('hide');
        }).fail(function(xhr, textStatus, error) {
            handleErrorResponse(xhr, textStatus, error);
        }).always(function( jqXHR, textStatus ) {
            // ボタンを有効化し、再送信を許可
            $button.attr('disabled', false);
        });
        return false;
    });

    var loadList = function() {
        $.ajax({
            url: _CONTEXT + '/protect.survey/list?q=' + $('#searchId').val(),
            type: 'GET',
            data: '',
            timeout: 10000,  // 単位はミリ秒
        }).done(function(result, textStatus, xhr) {
            if (result.length > 0) {
                var listHtml = '
';
                result.forEach(function(survey) {
                    listHtml += '<button type="button" class="list-group-item list-group-item-action surveyItem">';
                    listHtml += '#' + survey.knowledgeId + '';
                    listHtml += '  ' + survey.title + ' / ' + survey.knowledgeTitle;

                    listHtml += '</button>';
                });
                listHtml += '
'
                $('#surveyList').html(listHtml);

                $('.surveyItem').click(function() {
                    var id = $(this).find('.surveyItemId').text().substring(1);
                    bootbox.confirm({
                        title: 'Confirm copy',
                        message: _MSG_CONFIRM_COPY,
                        buttons: {
                            confirm: {
                                label: ' Yes',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: ' No',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                copySurvey(id).then(function() {
                                    $('#modalCopySurvey').modal('hide');
                                });
                            }
                        }
                    });
                });
            } else {
                $('#surveyList').html(_MSG_SUVEY_NOT_FOUND);
            }
        }).fail(function(xhr, textStatus, error) {
            handleErrorResponse(xhr, textStatus, error);
        });
    };
    var copySurvey = function(id) {
        $('#typeName').val('');
        $('#description').val('');
        $('.deleteItemButton').click();
        return document.__load_survey(_CONTEXT + '/open.survey/load/' + id);
    };

    $('#modalCopySurvey').on('show.bs.modal', function (event) {
        $('#surveyList').html('');
    });
    $('#modalCopySurvey').on('shown.bs.modal', function (event) {
        loadList();
    });
    $('#searchId').keypress(function() {
        var old = $('#searchId').val();
        setTimeout(function(){
            var v = $('#searchId').val();
            if(old != v){
                loadList();
            }
        }, 100);
    });

});


text:
using System.Threading.Tasks;

namespace SparkPost
{
    public interface IMessageEvents
    {
        Task<ListMessageEventsResponse> List();
        Task<ListMessageEventsResponse> List(object query);
    }
}


text:
import fs from 'fs'
import path from 'path'
import { app, BrowserWindow, screen } from 'electron'

const dir = app.getPath('userData')

export default (name, options) => {
  const stateStoreFile = path.join(dir, 'window-state-' + name + '.json')
  const defaultSize = { width: options.width, height: options.height }

  let state = {}
  let win

  const restore = () => {
    try {
      return Object.assign({}, defaultSize, JSON.parse(fs.readFileSync(stateStoreFile)))
    } catch (err) {
      return Object.assign({}, defaultSize)
    }
  }

  const getCurrentState = () => {
    const position = win.getPosition()
    const size = defaultSize.useContentSize ? win.getContentSize() : win.getSize()
    return { x: position[0], y: position[1], width: size[0], height: size[1] }
  }

  const windowWithinBounds = (windowState, bounds) => {
    return windowState.x >= bounds.x &&
      windowState.y >= bounds.y &&
      windowState.x + windowState.width <= bounds.x + bounds.width &&
      windowState.y + windowState.height <= bounds.y + bounds.height
  }

  const resetToDefaults = (windowState) => {
    const bounds = screen.getPrimaryDisplay().bounds
    return Object.assign({}, defaultSize, {
      x: (bounds.width - defaultSize.width) / 2,
      y: (bounds.height - defaultSize.height) / 2
    })
  }

  const ensureVisibleOnSomeDisplay = (windowState) => {
    const visible = screen.getAllDisplays().some((display) => windowWithinBounds(windowState, display.bounds))
    if (!visible) {
      return resetToDefaults(windowState)
    }
    return windowState
  }

  const saveState = () => {
    if (!win.isMinimized() && !win.isMaximized()) {
      Object.assign(state, getCurrentState())
    }
    fs.writeFileSync(stateStoreFile, JSON.stringify(state), 'utf8')
  }

  state = ensureVisibleOnSomeDisplay(restore())

  win = new BrowserWindow(Object.assign({}, options, state))

  win.on('close', saveState)

  return win
}


text: A Java library for converting flat files into XML (and XML into flat files).


text:
<?php namespace Ollieread\Multiauth;

use Illuminate\Auth\AuthManager as OriginalAuthManager;
use Illuminate\Auth\DatabaseUserProvider;
use Illuminate\Auth\EloquentUserProvider;

class AuthManager extends OriginalAuthManager {

	protected $config;
	protected $name;

	public function __construct($app, $name, $config) {
		parent::__construct($app);

		$this->config = $config;
		$this->name = $name;
	}

	protected function createDriver($driver) {
		$guard = parent::createDriver($driver);

		$guard->setCookieJar($this->app['cookie']);
		$guard->setDispatcher($this->app['events']);

		return $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
	}

	protected function callCustomCreator($driver) {
		$custom = parent::callCustomCreator($driver);

		if ($custom instanceof Guard) return $custom;

		return new Guard($custom, $this->app['session.store'], $this->name);
	}

	public function createDatabaseDriver() {
		$provider = $this->createDatabaseProvider();

		return new Guard($provider, $this->app['session.store'], $this->name);
	}

	protected function createDatabaseProvider() {
		$connection = $this->app['db']->connection();
		$table = $this->config['table'];

		return new DatabaseUserProvider($connection, $this->app['hash'], $table);
	}

	public function createEloquentDriver() {
		$provider = $this->createEloquentProvider();

		return new Guard($provider, $this->app['session.store'], $this->name);
	}

	protected function createEloquentProvider() {
		$model = $this->config['model'];

		return new EloquentUserProvider($this->app['hash'], $model);
	}

	public function getDefaultDriver() {
		return $this->config['driver'];
	}

	public function setDefaultDriver($name)
	{
		$this->config['driver'] = $name;
	}

}


text:
import pika
import sys
import getopt
from hub_pair import HubPair

class HubMaster(object):

    def __init__(self, controls_exchange, exchange_list):
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
        self.channel = self.connection.channel()
        self.channel.exchange_declare(exchange=controls_exchange, type='topic')
        self.result = self.channel.queue_declare(exclusive=True)
        self.queue_name = self.result.method.queue
        self.my_exchange=controls_exchange
        self.channel.queue_bind(exchange=controls_exchange, queue=self.queue_name, routing_key="control.#")
        self.channel.basic_consume(self.handleRequest, self.queue_name, no_ack=True)
        self.hub_pairs=self.loadHubs(exchange_list)
        self.startHubs()

    #load hubs and
    def loadHubs(self, exchange_list):
        hub_pairs={}

        for e in exchange_list:
          hub_pair=HubPair(e)
          hub_pairs[e]=hub_pair
        return hub_pairs

    def startHubs(self):
        for key in self.hub_pairs:
          self.hub_pairs[key].waitRequest()

    def waitRequest(self):
        print ' [*] Hub waiting for messages. To exit press CTRL+C... Exchange is '+self.my_exchange
        self.channel.start_consuming()

    def handleRequest(self, ch, method, props, body):
        start = method.routing_key.find(".")
        end = method.routing_key.find(".",start+1)
        print ' [*] hub_master Received message: '+body
        command=method.routing_key[start+1:end ]

        start = method.routing_key.find(".")
        start = method.routing_key.find(".",start+1)
        end = method.routing_key.find(".",start+1)
        argument=method.routing_key[start+1:end ]

        #TODO: Handle commands + arguments

    def stopExchange(self, exchange):
        pass

    def restartExchange(self, exchange):
        pass

    def getExchangeStats(self, exchange):
        pass

def main(argv):

   try:
      opts, args = getopt.getopt(argv,"e:",["exchanges="])
   except getopt.GetoptError:
      print 'hub_master.py -e<EXC_ID1>:<EXC_ID2>:...:<EXC_IDX> '
      sys.exit(2)
   for opt, arg in opts:
      print arg
      if opt == '-h':
         print 'hub_master.py -e<EXC_ID1>:<EXC_ID2>:...:<EXC_IDX> '
         sys.exit(1)
      elif opt in ("-e", "--exchanges="):
         exchange_list = arg

   hub_master = HubMaster("MasterControl", exchange_list.split(':'))
   hub_master.waitRequest()

if __name__ == "__main__":
   try:
      opts, args = getopt.getopt(sys.argv,"e:",["exchanges="])
      print args
   except getopt.GetoptError:
      pass
   main(sys.argv[1:])


text:
var _ = require('underscore');

var jobs = [];
var jobFailCount = {};

module.exports.push = function(jobId, jobType, jobData, callback) {
  var data = {
    jobId: jobId,
    jobType: jobType,
    jobData: jobData
  };
  jobs.push(data);
  process.nextTick(function() {
    callback();
  });
};

module.exports.each = function(count, eachFn, callback) {
  jobs = _.shuffle(jobs);
  for (var i = 0; i < count && jobs.length > 0; i++) {
    var job = jobs.shift();
    eachFn(job.jobId, job.jobType, job.jobData);
  }
  process.nextTick(function() {
    callback();
  });
};

module.exports.requeue = function(jobId, jobType, jobData, callback) {
  var data = {
    jobId: jobId,
    jobType: jobType,
    jobData: jobData
  };
  process.nextTick(function() {
    jobs.unshift(data);
    callback();
  });
};

module.exports.empty = function(callback) {
  jobs = [];
  process.nextTick(function() {
    callback();
  });
};


text:
package de.spacerun.mainmenu;

import java.util.ArrayList;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.VerticalSplitTransition;

import de.spacerun.control.SensorParser;
import de.spacerun.main.Data;
import de.spacerun.main.Spacerun;

@SuppressWarnings({"rawtypes", "unchecked"}) //prevent eclipse from displaying a warning because Data is a generic type
public class MainMenuState extends BasicGameState {
  private SimpleFont menuFont, headerFont;
  private int width, index, headerSpace, menuSpace;
  private int headerWidth;
  private int[] menuWidth;
  private String[] menuText;
  private int stateID;
  private Image image;

  private ArrayList<Data> status;
  private SensorParser spOne, spTwo;
  private String[] connectionStatus;

  public MainMenuState(int ID, ArrayList<Data> status) {
  	this.stateID = ID;
  	this.status = status;
  }

  @Override
  public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
  	index = 0;
    menuText = new String[] {"Spiel starten", "Multiplayer", "Highscores", "Steuerung", "Exit"};
    connectionStatus = new String[] {"Player 1: connected", "Player 1: disconnected",
        "Player 2: connected", "Player 2: disconnected"};

    width = gc.getWidth();
    headerSpace = gc.getHeight()/(menuText.length + 1);
    menuSpace = (gc.getHeight() - (2 * headerSpace))/((menuText.length + 1) * 2);

    menuFont = new SimpleFont("data/space age.ttf", menuSpace/2);
    headerFont = new SimpleFont("data/space age.ttf", headerSpace);

    headerWidth = headerFont.get().getWidth("Spacerun")/2;
    menuWidth = new int[menuText.length];
    for(int i = 0; i < menuText.length; i++){
      menuWidth[i] = menuFont.get().getWidth(menuText[i])/2;
    }

    image = new Image("data/Universe.png");

    spOne = (SensorParser)status.get(2).getData();
    spTwo = (SensorParser)status.get(3).getData();
  }

  @Override
  public void render(GameContainer gc, StateBasedGame sbg, Graphics g) {
    float start = 2 * headerSpace;

    image.draw(0,0,gc.getWidth(),gc.getHeight());
    headerFont.get().drawString(width/2 - headerWidth, 0, "Spacerun");

    for(int i = 0; i < menuText.length; i++){
    	if(i == index){
    	  menuFont.get().drawString(width/2 - menuWidth[i], start, menuText[i], Color.red);
    	}else{
    	  menuFont.get().drawString(width/2 - menuWidth[i], start, menuText[i]);
    	}

    	start += menuSpace * 2;
    }

    // player connection status rendering
    if((boolean)status.get(1).getData()){
      float tmpHeight = menuFont.get().getHeight(connectionStatus[0]);

      if(spOne.getConnected()){
        menuFont.get().drawString(0, gc.getHeight() - (2 * tmpHeight), connectionStatus[0]);
      }else{
        menuFont.get().drawString(0, gc.getHeight() - (2 * tmpHeight), connectionStatus[1], Color.red);
      }

      if(spTwo.getConnected()){
        menuFont.get().drawString(0, gc.getHeight() - tmpHeight, connectionStatus[2]);
      }else{
        menuFont.get().drawString(0, gc.getHeight() - tmpHeight, connectionStatus[3], Color.red);
      }
    }
  }

  @Override
  public void update (GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
  	Input input = gc.getInput();

    if(input.isKeyPressed(Input.KEY_UP)){
  	  if(index > 0){
        index--;
  	  }
    }else if(input.isKeyPressed(Input.KEY_DOWN)){
      if(index < (menuText.length -1)){
        index++;
      }
    }else if(input.isKeyPressed(Input.KEY_ENTER)){
  	  if(menuText[index] == "Spiel starten"){ //make sure player is connected
  		  if( (spOne.getConnected() && ((boolean)status.get(1).getData())) ||
  		      !(boolean)status.get(1).getData() ){
  		    sbg.getState(Spacerun.GAMESTATE).init(gc, sbg);
  		    sbg.enterState(Spacerun.GAMESTATE, null, new VerticalSplitTransition());
        }
    	}else if(menuText[index] == "Multiplayer"){ //make sure player is connected
    	  if( (spOne.getConnected() && spTwo.getConnected() && ((boolean)status.get(1).getData())) ||
    	      !(boolean)status.get(1).getData()){
    	    status.get(0).setData(true);
  		    sbg.getState(Spacerun.GAMESTATE).init(gc, sbg);
  		    sbg.enterState(Spacerun.GAMESTATE, null, new VerticalSplitTransition());
        }
  	  }else if(menuText[index] == "Highscores"){
  	    sbg.getState(Spacerun.HIGHSCORESTATE).init(gc, sbg);
    	  sbg.enterState(Spacerun.HIGHSCORESTATE, null, new VerticalSplitTransition());
      }else if(menuText[index] == "Steuerung"){
        sbg.getState(Spacerun.CONTROLSTATE).init(gc, sbg);
        sbg.enterState(Spacerun.CONTROLSTATE, null, new VerticalSplitTransition());
  		}else if(menuText[index] == "Exit"){
    	  gc.exit();
  	  }
    }
    if(input.isKeyPressed(Input.KEY_ESCAPE)){
  	  gc.exit();
    }
  }

  @Override
  public int getID() {
	  return stateID;
	}
}


text:
package com.jambit.feuermoni.config.jersey;

import javax.ws.rs.ApplicationPath;

import org.glassfish.jersey.message.DeflateEncoder;
import org.glassfish.jersey.message.GZipEncoder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.server.filter.EncodingFilter;
import org.springframework.stereotype.Component;

@Component
@ApplicationPath("api/v1")
public class JerseyApplication extends ResourceConfig {

    public JerseyApplication() {
        packages("com.jambit.feuermoni.resource");

        property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);

        register(ValidationConfigContextResolver.class);
        EncodingFilter.enableFor(this, GZipEncoder.class, DeflateEncoder.class);
    }
}


text:
https://medium.com/@patdhlk/how-to-install-go-1-9-1-on-ubuntu-16-04-ee64c073cd79

$ sudo snap install go --classic

$ go version
go version go1.11.2 linux/amd64

$ which go
/snap/bin/go

  $ snap find go
  $ snap list
  $ sudo snap remove go
  $ sudo snap install go

### install go1.9.7

https://golang.org/doc/install?download=go1.9.7.linux-amd64.tar.gz

  $ sudo tar -C /usr/local -xzf go1.9.7.linux-amd64.tar.gz

* test
create $HOME/go/src/hello/hello.go
  $ go run $HOME/go/src/hello/hello.go

* build
  $ cd $HOME/go/src/hello
  $ go build
  $ ./hello

* install
  $ go install
  $ ~/go/bin/hello

### install Igo - go kernel for Jupyter
* Interactive Go programming with Jupyter
https://github.com/yunabe/lgo

~/go/src/github.com/yunabe/lgo/examples
~/go/notebooks

### Learn go
* https://gobyexample.com/
* https://www.tutorialspoint.com/go/go_logical_operators.htm
* https://github.com/a8m/go-lang-cheat-sheet

$ go get github.com/mmcgrana/gobyexample    # git url without prefix=https:// and suffix=.git

### go commands

* list src repo
  $ cd $HOME/go/src
  $ go list ./...


text:
(() => {
	let lastPlayedPdjChannel = null;
	document.body.addEventListener('playpause:promodj', function () {
		const CP = window.CORE.CurrentPlayer;
		if (CP) {
			switch (CP.status) {
				case 'play':
					CP.perform("pause");
					break;
				case 'pause':
					CP.perform("play");
					break;
			}
		}

		const R = window.Radio;
		if (R) {
			if (R.played) {
				R.Playa.PlayerStop();
				R.Unfire();

				lastPlayedPdjChannel = $$("span.played"); // pdj has assigned jquery name to "$$"
				lastPlayedPdjChannel.removeClass("played");

				R.played = false;
			}
			else {
				R.Playa.PlayerPlay();
				lastPlayedPdjChannel.addClass("played");
				R.played = true;
			}
		}
	});
})();


text:
from . import log
from . import client as hc_client
from . import monitor as hc_monitor
from . import server as hc_server

client = hc_client
monitor = hc_monitor
server = hc_server

def setup():
    log.setup()


text:
/*	Veronica Lesnar
	HW 03 */

#include "Main.h"

int main() {
	typedef int myType;

	int numEntries = 10;

	List<myType> list(numEntries);
	List<myType> anotherList(0);
	List<double> doubleList(numEntries);
	List<char> charList(numEntries);

	for (int i = 0; i < (numEntries); i++)
	{
		list.data[i] = static_cast<myType>(i);
		doubleList.data[i] = i + 0.5;
		charList.data[i] = i + 97;
	}

	list.Print();
	cout << "The size of this list is: " << list.GetSize() << endl;

	list.Push(11);
	list.Push(12);
	list.Push(13);

	list.Print();
	cout << "The size of this list is: " << list.GetSize() << endl;

	list.Pop();
	list.Pop();
	list.Pop();
	list.Pop();
	list.Pop();
	list.Pop();

	list.Print();
	cout << "The size of this list is: " << list.GetSize() << endl;

	anotherList.Print();

	charList.Print();
	charList.Pop();
	charList.Pop();
	charList.Print();

	doubleList.Print();
	doubleList.Pop();
	doubleList.Pop();
	doubleList.Print();

	getchar();
	return 0;
}


text:
package org.apache.asterix.common.replication;

public interface IReplicationStrategy {

    /**
     * @param datasetId
     * @return True, if the dataset should be replicated. Otherwise false.
     */
    boolean isMatch(int datasetId);
}


text:
namespace libgui
{

class Size
{
public:
  Size();
  Size(double width, double height);

  double width;
  double height;
};

}


text:
#ifndef DMBNETWORK_H
#define DMBNETWORK_H

#include "dmbdefines.h"
#include <sys/epoll.h>
#include "core/dmblist.h"

#define DMB_NW_NONE  0 //none, accept
#define DMB_NW_READ  1 //read
#define DMB_NW_WRITE 2 //write

typedef int dmbSOCKET;
typedef int dmbPIPE;

typedef struct epoll_event dmbNetworkEvent;

typedef struct dmbEpollData {
    dmbINT epfd;
    dmbUINT eventSize;
    dmbNetworkEvent events[];
} dmbEpollData;

typedef struct dmbConnReq {
    dmbBYTE *data;
    dmbUINT len;
    dmbCode (*merge) (struct dmbConnReq*, dmbBYTE*, dmbUINT);
    void (*release) (struct dmbConnReq*);
} dmbConnReq;

typedef struct dmbConnect {
    dmbINT cliFd;
    dmbBYTE *readBuf;
    dmbBOOL canRead;
    dmbBOOL canWrite;
    dmbBOOL isblocked;
    dmbUINT readIndex;
    dmbUINT readBufSize;
    dmbUINT readLength;
    dmbUINT requestIndex;
    dmbConnReq request;
    dmbBYTE *writeBuf;
    dmbUINT writeIndex;
    dmbUINT writeBufSize;
    dmbUINT writeLength;
    dmbBOOL needClose;
    dmbUINT timeout;
    dmbNode idleNode;
    dmbNode timeoutNode;
    dmbNode roundNode;
} dmbConnect;

typedef struct dmbNetworkListener{
    dmbCode (*onConnect)(void *);
    void (*onClosed)(void*);
    void *data;
} dmbNetworkListener;

typedef struct dmbNetworkContext {
    dmbEpollData *netData;
    dmbUINT connectSize;
    dmbList idleConnList;
    dmbList timeoutConnList;
    dmbList roundRobinList;
    dmbConnect *connects;
    dmbNetworkListener *listener;
} dmbNetworkContext;

dmbCode dmbNetworkInit(dmbNetworkContext *pCtx, dmbUINT uEventNum, dmbNetworkListener *pListener);

dmbCode dmbNetworkPurge(dmbNetworkContext *pCtx);

dmbCode dmbNetworkAddEvent(dmbNetworkContext *pCtx, dmbSOCKET iFd, dmbINT iMask, dmbConnect *pConn);

dmbCode dmbNetworkChangeEvent(dmbNetworkContext *pCtx, dmbINT iFd, dmbINT iMask, dmbConnect *pConn);

dmbCode dmbNetworkDelEvent(dmbNetworkContext *pCtx, dmbINT iFd, dmbINT iMask);

dmbCode dmbNetworkPoll(dmbNetworkContext *pCtx, dmbINT *iEventNum, dmbINT iTimeout);

dmbCode dmbNetworkOnLoop(dmbNetworkContext *pCtx, dmbSOCKET listener);

dmbCode dmbNetworkInitConnectPool(dmbNetworkContext *pCtx, dmbUINT uConnectSize, dmbUINT readBufSize, dmbUINT writeBufSize);

dmbCode dmbNetworkPurgeConnectPool(dmbNetworkContext *pCtx);

dmbCode dmbNetworkAccept(dmbSOCKET listener, dmbSOCKET *pSocket);

dmbCode dmbNetworkListen(dmbSOCKET *pFd, const char *addr, int port, int backlog);

dmbCode dmbNetworkInitNewConnect(dmbSOCKET client);

dmbCode dmbNetworkProcessNewConnect(dmbNetworkContext *pCtx, dmbSOCKET fd, dmbLONG timeout);

void dmbNetworkWatchTimeout(dmbNetworkContext *pCtx, dmbConnect *pConn, dmbLONG timeout);

dmbINT dmbNetworkCloseTimeoutConnect(dmbNetworkContext *pCtx);

dmbCode dmbNetworkCloseConnect(dmbNetworkContext *pCtx, dmbConnect *pConn);

#define dmbNetworkGetConnect(EVENT_PTR) ((dmbConnect*)(EVENT_PTR)->data.ptr)

#define dmbNetworkBadConnect(EVENT_PTR) (((EVENT_PTR)->events) & (EPOLLRDHUP | EPOLLHUP | EPOLLPRI | EPOLLERR))

#define dmbNetworkCanRead(EVENT_PTR) (((EVENT_PTR)->events) & EPOLLIN)

#define dmbNetworkCanWrite(EVENT_PTR) (((EVENT_PTR)->events) & EPOLLOUT)

#define dmbConnectCanRead(CONN_PTR) ((CONN_PTR)->canRead)

#define dmbConnectCanWrite(CONN_PTR) ((CONN_PTR)->canWrite)

#define dmbConnectIsBlocked(CONN_PTR) ((CONN_PTR)->isblocked)

#define dmbNetworkEventForeach(CTX, EVENT_PTR, INDEX, NUM) \
    for (INDEX=0, EVENT_PTR=&CTX->netData->events[INDEX]; \
            INDEX<NUM; \
        ({EVENT_PTR = &CTX->netData->events[INDEX]; INDEX++;}))

#endif // DMBNETWORK_H


text:
import sys

python3 = sys.version_info[0] >= 3

if python3:
    basestr = str
    range_ = range
else:
    basestr = basestring
    range_ = xrange

def iteritems(it):
    if python3:
        return it.items()
    else:
        return it.iteritems()

def iterkeys(it):
    if python3:
        return it.keys()
    else:
        return it.iterkeys()

def itervalues(it):
    if python3:
        return it.values()
    else:
        return it.itervalues()


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

namespace FrwSoftware
{

    [JEntity]
    public class TestDto3
    {
        [JPrimaryKey, JAutoIncrement]
        public string Id { get; set; }

        [JManyToMany]
        public IList<TestDto1> TestDto1s { get; set; }

    }
}


text:
var config       = require('../config');
var convert      = require('data2xml')();
var Topic        = require('../proxy').Topic;
var cache        = require('../common/cache');
var renderHelper = require('../common/render_helper');
var eventproxy   = require('eventproxy');

exports.index = function (req, res, next) {
  if (!config.rss) {
    res.statusCode = 404;
    return res.send('Please set `rss` in config.js');
  }
  res.contentType('application/xml');

  var ep = new eventproxy();
  ep.fail(next);

  cache.get('rss', ep.done(function (rss) {
    if (!config.debug && rss) {
      res.send(rss);
    } else {
      var opt = { limit: config.rss.max_rss_items, sort: '-create_at'};
      Topic.getTopicsByQuery({}, opt, function (err, topics) {
        if (err) {
          return next(err);
        }
        var rss_obj = {
          _attr: { version: '2.0' },
          channel: {
            title: config.rss.title,
            link: config.rss.link,
            language: config.rss.language,
            description: config.rss.description,
            item: []
          }
        };

        topics.forEach(function (topic) {
          rss_obj.channel.item.push({
            title: topic.title,
            link: config.rss.link + '/topic/' + topic._id,
            guid: config.rss.link + '/topic/' + topic._id,
            description: renderHelper.markdown(topic.content),
            author: topic.author.loginname,
            pubDate: topic.create_at.toUTCString()
          });
        });

        var rssContent = convert('rss', rss_obj);

        cache.set('rss', rssContent, 60 * 5); // 五分钟
        res.send(rssContent);
      });
    }
  }));
};


text:
module ClassCacher
  module ModelAdditions
    def unique_class_cache
      after_commit :flush_unique_class_cache_key
      after_destroy :flush_unique_class_cache_key
      after_save :flush_unique_class_cache_key

    private
      def flush_unique_class_cache_key
        puts "Flush"
        #Rails.cache.delete(["cached_unique_class_cache_key", self.class.name])
      end

      def self.unique_class_cache_key
        max_updated_at        = self.pluck("MAX(updated_at)").first.to_s
        parsed_max_updated_at = "#{ max_updated_at.present? ? DateTime.parse(max_updated_at).utc.to_s(:number) : nil }"
        count                 = self.count

        Digest::SHA1.hexdigest "#{ [parsed_max_updated_at, self.name, count] }"
      end

      def self.cached_unique_class_cache_key
        puts "cached"
        #Rails.cache.fetch(["cached_unique_class_cache_key", self.name]) { self.unique_class_cache_key }
      end
    end
  end
end