text:
package org.apache.cassandra.distributed.test;

import java.io.IOException;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.distributed.api.ICoordinator;
import org.apache.cassandra.distributed.api.IInstanceConfig;
import org.apache.cassandra.distributed.api.IMessageFilters;
import org.apache.cassandra.exceptions.CasWriteTimeoutException;

import org.apache.cassandra.utils.FBUtilities;

import static org.apache.cassandra.distributed.api.ConsistencyLevel.ANY;
import static org.apache.cassandra.distributed.api.ConsistencyLevel.ONE;
import static org.apache.cassandra.distributed.api.ConsistencyLevel.QUORUM;
import static org.apache.cassandra.distributed.api.ConsistencyLevel.SERIAL;
import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows;
import static org.apache.cassandra.distributed.shared.AssertUtils.row;
import static org.apache.cassandra.net.Verb.PAXOS2_COMMIT_AND_PREPARE_REQ;
import static org.apache.cassandra.net.Verb.PAXOS2_PREPARE_REFRESH_REQ;
import static org.apache.cassandra.net.Verb.PAXOS2_PREPARE_REQ;
import static org.apache.cassandra.net.Verb.PAXOS2_PROPOSE_REQ;
import static org.apache.cassandra.net.Verb.PAXOS_COMMIT_REQ;
import static org.apache.cassandra.net.Verb.PAXOS_PREPARE_REQ;
import static org.apache.cassandra.net.Verb.PAXOS_PROPOSE_REQ;
import static org.apache.cassandra.net.Verb.READ_REQ;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class CASTest extends CASCommonTestCases
{
    /**
     * The {@code cas_contention_timeout} used during the tests
     */
    private static final String CONTENTION_TIMEOUT = "1000ms";

    /**
     * The {@code write_request_timeout} used during the tests
     */
    private static final String REQUEST_TIMEOUT = "1000ms";

    private static Cluster THREE_NODES;
    private static Cluster FOUR_NODES;

    @BeforeClass
    public static void beforeClass() throws Throwable
    {
        System.setProperty("cassandra.paxos.use_self_execution", "false");
        TestBaseImpl.beforeClass();
        Consumer<IInstanceConfig> conf = config -> config
                                                   .set("paxos_variant", "v2")
                                                   .set("write_request_timeout", REQUEST_TIMEOUT)
                                                   .set("cas_contention_timeout", CONTENTION_TIMEOUT)
                                                   .set("request_timeout", REQUEST_TIMEOUT);
        // TODO: fails with vnode enabled
        THREE_NODES = init(Cluster.build(3).withConfig(conf).withoutVNodes().start());
        FOUR_NODES = init(Cluster.build(4).withConfig(conf).withoutVNodes().start(), 3);
    }

    @AfterClass
    public static void afterClass()
    {
        if (THREE_NODES != null)
            THREE_NODES.close();
        if (FOUR_NODES != null)
            FOUR_NODES.close();
    }

    @Before
    public void before()
    {
        THREE_NODES.filters().reset();
        FOUR_NODES.filters().reset();
        // tests add/remove nodes from the ring, so attempt to add them back
        for (int i = 1 ; i <= 4 ; ++i)
        {
            for (int j = 1; j <= 4; j++)
            {
                FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingNormal).accept(FOUR_NODES.get(j));
            }
        }
    }

    /**
     * A write and a read that are able to witness different (i.e. non-linearizable) histories
     * See CASSANDRA-12126
     *
     *  - A Promised by {1, 2, 3}
     *  - A Acccepted by {1}
     *  - B (=>!A) Promised and Proposed to {2, 3}
     *  - Read from (or attempt C (=>!B)) to {1, 2} -> witness either A or B, not both
     */
    @Test
    public void testIncompleteWriteSupersededByConflictingRejectedCondition() throws Throwable
    {
        String tableName = tableName("tbl");
        THREE_NODES.schemaChange("CREATE TABLE " + KEYSPACE + "." + tableName + " (pk int, ck int, v int, PRIMARY KEY (pk, ck))");

        IMessageFilters.Filter drop1 = THREE_NODES.filters().verbs(PAXOS2_PROPOSE_REQ.id, PAXOS_PROPOSE_REQ.id).from(1).to(2, 3).drop();
        try
        {
            THREE_NODES.coordinator(1).execute("INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v) VALUES (1, 1, 1) IF NOT EXISTS", QUORUM);
            fail();
        }
        catch (Throwable t)
        {
            if (!t.getClass().getName().equals(CasWriteTimeoutException.class.getName()))
                throw t;
        }
        drop(THREE_NODES, 2, to(1), to(1), to());
        assertRows(THREE_NODES.coordinator(2).execute("UPDATE " + KEYSPACE + "." + tableName + " SET v = 2 WHERE pk = 1 and ck = 1 IF v = 1", QUORUM),
                   row(false));
        drop1.off();
        drop(THREE_NODES, 1, to(2), to(), to());
        assertRows(THREE_NODES.coordinator(1).execute("SELECT * FROM " + KEYSPACE + "." + tableName + " WHERE pk = 1", SERIAL));
    }

    /**
     * Two reads that are able to witness different (i.e. non-linearizable) histories
     *  - A Promised by {1, 2, 3}
     *  - A Accepted by {1}
     *  - Read from {2, 3} -> do not witness A?
     *  - Read from {1, 2} -> witnesses A?
     * See CASSANDRA-12126
     */
    @Ignore
    @Test
    public void testIncompleteWriteSupersededByRead() throws Throwable
    {
        String tableName = tableName();
        String fullTableName = KEYSPACE + "." + tableName;
        THREE_NODES.schemaChange("CREATE TABLE " + fullTableName + " (pk int, ck int, v int, PRIMARY KEY (pk, ck))");

        IMessageFilters.Filter drop1 = THREE_NODES.filters().verbs(PAXOS2_PROPOSE_REQ.id, PAXOS_PROPOSE_REQ.id).from(1).to(2, 3).drop();
        try
        {
            THREE_NODES.coordinator(1).execute("INSERT INTO " + fullTableName + " (pk, ck, v) VALUES (1, 1, 1) IF NOT EXISTS", QUORUM);
            fail();
        }
        catch (Throwable t)
        {
            if (!t.getClass().getName().equals(CasWriteTimeoutException.class.getName()))
                throw t;
        }
        drop(THREE_NODES, 2, to(1), to(), to());
        assertRows(THREE_NODES.coordinator(2).execute("SELECT * FROM " + fullTableName + " WHERE pk = 1", SERIAL));
        drop1.off();

        drop(THREE_NODES, 1, to(2), to(), to());
        assertRows(THREE_NODES.coordinator(1).execute("SELECT * FROM " + fullTableName + " WHERE pk = 1", SERIAL));
    }

    private static int[] paxosAndReadVerbs()
    {
        return new int[] {
            PAXOS_PREPARE_REQ.id,
            PAXOS2_PREPARE_REQ.id,
            PAXOS2_PREPARE_REFRESH_REQ.id,
            PAXOS2_COMMIT_AND_PREPARE_REQ.id,
            PAXOS_PROPOSE_REQ.id,
            PAXOS2_PROPOSE_REQ.id,
            PAXOS_COMMIT_REQ.id,
            READ_REQ.id
        };
    }

    /**
     * Tests that if a write timeouts and a following serial read does not see that write, then no following reads sees
     * it, even if some nodes still have the write in their paxos state.
     *
     *
This specifically test for the inconsistency described/fixed by CASSANDRA-12126.
     */
    @Test
    public void readConsistencyAfterWriteTimeoutTest() throws IOException
    {
        BiConsumer<String, ICoordinator> operation =
                (table, coordinator) -> assertRows(coordinator.execute("SELECT * FROM " + table + " WHERE k=0",
                        SERIAL));

        consistencyAfterWriteTimeoutTest(operation, operation, false, THREE_NODES);
        consistencyAfterWriteTimeoutTest(operation, operation, true, THREE_NODES);
    }

    /**
     * Tests that a sequence of reads exploit the fast read optimisation, as does a fail write, but that
     * a read after a failed write that does not propose successfully does not
     */
    @Test
    public void fastReadsAndFailedWrites() throws IOException
    {
        String tableName = tableName("t");
        String table = KEYSPACE + "." + tableName;
        THREE_NODES.schemaChange("CREATE TABLE " + table + " (k int PRIMARY KEY, v int)");

        // We do a CAS insertion, but have with the PROPOSE message dropped on node 1 and 2. The CAS will not get
        // through and should timeout. Importantly, node 3 does receive and answer the PROPOSE.
        IMessageFilters.Filter dropProposeFilter = THREE_NODES.filters()
                                                              .verbs(PAXOS_PROPOSE_REQ.id, PAXOS2_PROPOSE_REQ.id,
                                                                     PAXOS_COMMIT_REQ.id, PAXOS2_COMMIT_AND_PREPARE_REQ.id)
                                                              .to(1, 2)
                                                              .drop();

        try
        {
            // shouldn't timeout
            THREE_NODES.coordinator(1).execute("SELECT * FROM " + table + " WHERE k = 1", SERIAL);
            THREE_NODES.coordinator(1).execute("SELECT * FROM " + table + " WHERE k = 1", SERIAL);
            THREE_NODES.coordinator(1).execute("SELECT * FROM " + table + " WHERE k = 1", SERIAL);
            THREE_NODES.coordinator(1).execute("UPDATE " + table + " SET v = 1 WHERE k = 1 IF EXISTS", ANY);
            try
            {
                THREE_NODES.coordinator(1).execute("SELECT * FROM " + table + " WHERE k = 1", SERIAL);
                Assert.fail();
            }
            catch (AssertionError propagate)
            {
                throw propagate;
            }
            catch (Throwable maybeIgnore)
            {
                if (!maybeIgnore.getClass().getSimpleName().equals("ReadTimeoutException"))
                    throw maybeIgnore;
            }
        }
        finally
        {
            dropProposeFilter.off();
        }

        THREE_NODES.coordinator(1).execute("SELECT * FROM " + table + " WHERE k = 1", SERIAL);

        try
        {
            dropProposeFilter.on();
            // shouldn't timeout
            THREE_NODES.coordinator(1).execute("SELECT * FROM " + table + " WHERE k = 1", SERIAL);
            THREE_NODES.coordinator(1).execute("SELECT * FROM " + table + " WHERE k = 1", SERIAL);
            THREE_NODES.coordinator(1).execute("SELECT * FROM " + table + " WHERE k = 1", SERIAL);
        }
        finally
        {
            dropProposeFilter.off();
        }
    }

    /**
     * Tests that if a write timeouts, then a following CAS succeed but does not apply in a way that indicate the write
     * has not applied, then no following CAS can see that initial insert , even if some nodes still have the write in
     * their paxos state.
     *
     *
This specifically test for the inconsistency described/fixed by CASSANDRA-12126.
     */
    @Test
    public void nonApplyingCasConsistencyAfterWriteTimeout() throws IOException
    {
        // Note: we use CL.ANY so that the operation don't timeout in the case where we "lost" the operation1 commits.
        // The commit CL shouldn't have impact on this test anyway, so this doesn't diminishes the test.
        BiConsumer<String, ICoordinator> operation =
                (table, coordinator) -> assertCasNotApplied(coordinator.execute("UPDATE " + table + " SET v = 1 WHERE k = 0 IF v = 0",
                        ANY));
        consistencyAfterWriteTimeoutTest(operation, operation, false, THREE_NODES);
        consistencyAfterWriteTimeoutTest(operation, operation, true, THREE_NODES);
    }

    /**
     * Tests that if a write timeouts and a following serial read does not see that write, then no following CAS see
     * that initial insert, even if some nodes still have the write in their paxos state.
     *
     *
This specifically test for the inconsistency described/fixed by CASSANDRA-12126.
     */
    @Test
    public void mixedReadAndNonApplyingCasConsistencyAfterWriteTimeout() throws IOException
    {
        BiConsumer<String, ICoordinator> operation1 =
                (table, coordinator) -> assertRows(coordinator.execute("SELECT * FROM " + table + " WHERE k=0",
                        SERIAL));
        BiConsumer<String, ICoordinator> operation2 =
                (table, coordinator) -> assertCasNotApplied(coordinator.execute("UPDATE " + table + " SET v = 1 WHERE k = 0 IF v = 0",
                        QUORUM));
        consistencyAfterWriteTimeoutTest(operation1, operation2, false, THREE_NODES);
        consistencyAfterWriteTimeoutTest(operation1, operation2, true, THREE_NODES);
    }

    /**
     * Tests that if a write timeouts and a following CAS succeed but does not apply in a way that indicate the write
     * has not applied, then following serial reads do no see that write, even if some nodes still have the write in
     * their paxos state.
     *
     *
This specifically test for the inconsistency described/fixed by CASSANDRA-12126.
     */
    @Test
    public void mixedNonApplyingCasAndReadConsistencyAfterWriteTimeout() throws IOException
    {
        // Note: we use CL.ANY so that the operation don't timeout in the case where we "lost" the operation1 commits.
        // The commit CL shouldn't have impact on this test anyway, so this doesn't diminishes the test.
        BiConsumer<String, ICoordinator> operation1 =
                (table, coordinator) -> assertCasNotApplied(coordinator.execute("UPDATE " + table + " SET v = 1 WHERE k = 0 IF v = 0",
                        ANY));
        BiConsumer<String, ICoordinator> operation2 =
                (table, coordinator) -> assertRows(coordinator.execute("SELECT * FROM " + table + " WHERE k=0",
                        SERIAL));
        consistencyAfterWriteTimeoutTest(operation1, operation2, false, THREE_NODES);
        consistencyAfterWriteTimeoutTest(operation1, operation2, true, THREE_NODES);
    }

    // TODO: this shoud probably be moved into the dtest API.
    private void assertCasNotApplied(Object[][] resultSet)
    {
        assertFalse("Expected a CAS resultSet (with at least application result) but got an empty one.",
                resultSet.length == 0);
        assertFalse("Invalid empty first row in CAS resultSet.", resultSet[0].length == 0);
        Object wasApplied = resultSet[0][0];
        assertTrue("Expected 1st column of CAS resultSet to be a boolean, but got a " + wasApplied.getClass(),
                wasApplied instanceof Boolean);
        assertFalse("Expected CAS to not be applied, but was applied.", (Boolean)wasApplied);
    }

    private static Object[][] executeWithRetry(int attempts, ICoordinator coordinator, String query, ConsistencyLevel consistencyLevel, Object... boundValues)
    {
        while (--attempts > 0)
        {
            try
            {
                return coordinator.execute(query, consistencyLevel, boundValues);
            }
            catch (Throwable t)
            {
                if (!t.getClass().getName().equals(CasWriteTimeoutException.class.getName()))
                    throw t;
                FBUtilities.sleepQuietly(100);
            }
        }
        return coordinator.execute(query, consistencyLevel, boundValues);
    }

    private static Object[][] executeWithRetry(ICoordinator coordinator, String query, ConsistencyLevel consistencyLevel, Object... boundValues)
    {
        return executeWithRetry(2, coordinator, query, consistencyLevel, boundValues);
    }

    // failed write (by node that did not yet witness a range movement via gossip) is witnessed later as successful
    // conflicting with another successful write performed by a node that did witness the range movement
    // A Promised, Accepted and Committed by {1, 2}
    // Range moves to {2, 3, 4}
    // B (=> !A) Promised and Proposed to {3, 4}
    @Test
    public void testSuccessfulWriteBeforeRangeMovement() throws Throwable
    {
        String tableName = tableName("tbl");
        FOUR_NODES.schemaChange("CREATE TABLE " + KEYSPACE + "." + tableName + " (pk int, ck int, v1 int, v2 int, PRIMARY KEY (pk, ck))");

        // make it so {1} is unaware (yet) that {4} is an owner of the token
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::removeFromRing).accept(FOUR_NODES.get(4));

        int pk = pk(FOUR_NODES, 1, 2);

        // {1} promises and accepts on !{3} => {1, 2}; commits on !{2,3} => {1}
        drop(FOUR_NODES, 1, to(3), to(3), to(2, 3));
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        assertRows(executeWithRetry(FOUR_NODES.coordinator(1), "INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v1) VALUES (?, 1, 1) IF NOT EXISTS", ONE, pk),
                   row(true));
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));

        for (int i = 1; i <= 3; ++i)
        {
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingNormal).accept(FOUR_NODES.get(4));
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));
        }

        // {4} reads from !{2} => {3, 4}
        drop(FOUR_NODES, 4, to(2), to(2), to());
        assertRows(executeWithRetry(FOUR_NODES.coordinator(4), "INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v2) VALUES (?, 1, 2) IF NOT EXISTS", ONE, pk),
                   row(false, pk, 1, 1, null));
    }

    /**
     * Failed write (by node that did not yet witness a range movement via gossip) is witnessed later as successful
     * conflicting with another successful write performed by a node that did witness the range movement
     *  - Range moves from {1, 2, 3} to {2, 3, 4}, witnessed by X (not by !X)
     *  -  X: A Promised, Accepted and Committed by {3, 4}
     *  - !X: B (=>!A) Promised and Proposed to {1, 2}
     */
    @Test
    public void testConflictingWritesWithStaleRingInformation() throws Throwable
    {
        String tableName = tableName("tbl");
        FOUR_NODES.schemaChange("CREATE TABLE " + KEYSPACE + "." + tableName + " (pk int, ck int, v1 int, v2 int, PRIMARY KEY (pk, ck))");

        // make it so {1} is unaware (yet) that {4} is an owner of the token
        FOUR_NODES.get(1).acceptOnInstance(CASTestBase::removeFromRing, FOUR_NODES.get(4));
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));

        // {4} promises, accepts and commits on !{2} => {3, 4}
        int pk = pk(FOUR_NODES, 1, 2);
        drop(FOUR_NODES, 4, to(2), to(2), to(2));
        assertRows(executeWithRetry(FOUR_NODES.coordinator(4), "INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v1) VALUES (?, 1, 1) IF NOT EXISTS", ONE, pk),
                   row(true));

        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        // {1} promises, accepts and commmits on !{3} => {1, 2}
        drop(FOUR_NODES, 1, to(3), to(3), to(3));
        assertRows(executeWithRetry(FOUR_NODES.coordinator(1), "INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v2) VALUES (?, 1, 2) IF NOT EXISTS", ONE, pk),
                   row(false, pk, 1, 1, null));

        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));
    }

    /**
     * Successful write during range movement, not witnessed by read after range movement.
     * Very similar to {@link #testConflictingWritesWithStaleRingInformation}.
     *
     *  - Range moves from {1, 2, 3} to {2, 3, 4}; witnessed by X (not by !X)
     *  -  !X: Promised and Accepted by {1, 2}
     *  - Range movement witnessed by !X
     *  - Any: Promised and Read from {3, 4}
     */
    @Test
    public void testSucccessfulWriteDuringRangeMovementFollowedByRead() throws Throwable
    {
        String tableName = tableName("tbl");
        FOUR_NODES.schemaChange("CREATE TABLE " + KEYSPACE + "." + tableName + " (pk int, ck int, v int, PRIMARY KEY (pk, ck))");

        // make it so {4} is bootstrapping, and this has propagated to only a quorum of other nodes
        for (int i = 1 ; i <= 4 ; ++i)
        {
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::removeFromRing).accept(FOUR_NODES.get(4));
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        }
        for (int i = 2 ; i <= 4 ; ++i)
        {
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingBootstrapping).accept(FOUR_NODES.get(4));
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));
        }

        int pk = pk(FOUR_NODES, 1, 2);

        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        // {1} promises and accepts on !{3} => {1, 2}; commmits on !{2, 3} => {1}
        drop(FOUR_NODES, 1, to(3), to(3), to(2, 3));
        assertRows(executeWithRetry(FOUR_NODES.coordinator(1), "INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v) VALUES (?, 1, 1) IF NOT EXISTS", ONE, pk),
                   row(true));
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));

        // finish topology change
        for (int i = 1 ; i <= 4 ; ++i)
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingNormal).accept(FOUR_NODES.get(4));

        // {3} reads from !{2} => {3, 4}
        drop(FOUR_NODES, 3, to(2), to(), to());
        assertRows(FOUR_NODES.coordinator(3).execute("SELECT * FROM " + KEYSPACE + "." + tableName + " WHERE pk = ?", SERIAL, pk),
                   row(pk, 1, 1));
    }

    /**
     * Successful write during range movement not witnessed by write after range movement
     *
     *  - Range moves from {1, 2, 3} to {2, 3, 4}; witnessed by X (not by !X)
     *  -  !X: Promised and Accepted by {1, 2}
     *  - Range movement witnessed by !X
     *  - Any: Promised and Propose to {3, 4}
     */
    @Test
    public void testSuccessfulWriteDuringRangeMovementFollowedByConflicting() throws Throwable
    {
        FOUR_NODES.schemaChange("CREATE TABLE " + KEYSPACE + ".tbl (pk int, ck int, v1 int, v2 int, PRIMARY KEY (pk, ck))");

        // make it so {4} is bootstrapping, and this has propagated to only a quorum of other nodes
        for (int i = 1 ; i <= 4 ; ++i)
        {
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::removeFromRing).accept(FOUR_NODES.get(4));
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        }
        for (int i = 2 ; i <= 4 ; ++i)
        {
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingBootstrapping).accept(FOUR_NODES.get(4));
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));
        }

        int pk = pk(FOUR_NODES, 1, 2);

        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        // {1} promises and accepts on !{3} => {1, 2}; commits on !{2, 3} => {1}
        drop(FOUR_NODES, 1, to(3), to(3), to(2, 3));
        assertRows(executeWithRetry(FOUR_NODES.coordinator(1), "INSERT INTO " + KEYSPACE + ".tbl (pk, ck, v1) VALUES (?, 1, 1) IF NOT EXISTS", ONE, pk),
                   row(true));
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));

        // finish topology change
        for (int i = 1 ; i <= 4 ; ++i)
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingNormal).accept(FOUR_NODES.get(4));

        // {3} reads from !{2} => {3, 4}
        drop(FOUR_NODES, 3, to(2), to(), to());
        assertRows(FOUR_NODES.coordinator(3).execute("INSERT INTO " + KEYSPACE + ".tbl (pk, ck, v2) VALUES (?, 1, 2) IF NOT EXISTS", ONE, pk),
                   row(false, pk, 1, 1, null));

        // TODO: repair and verify base table state
    }

    /**
     * During a range movement, a CAS may fail leaving side effects that are not witnessed by another operation
     * being performed with stale ring information.
     * This is a particular special case of stale ring information sequencing, which probably would be resolved
     * by fixing each of the more isolated cases (but is unique, so deserving of its own test case).
     * See CASSANDRA-15745
     *
     *  - Range moves from {1, 2, 3} to {2, 3, 4}; witnessed by X (not by !X)
     *  -   X: Promised by {2, 3, 4}
     *  -   X: Accepted by {4}
     *  -  !X: Promised and Accepted by {1, 2}
     *  - Range move visible by !X
     *  - Any: Promised and Propose to {3, 4}
     */
    @Test
    public void testIncompleteWriteFollowedBySuccessfulWriteWithStaleRingDuringRangeMovementFollowedByRead() throws Throwable
    {
        String tableName = tableName("tbl");
        FOUR_NODES.schemaChange("CREATE TABLE " + KEYSPACE + "." + tableName + " (pk int, ck int, v1 int, v2 int, PRIMARY KEY (pk, ck))");

        // make it so {4} is bootstrapping, and this has propagated to only a quorum of other nodes
        for (int i = 1 ; i <= 4 ; ++i)
        {
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::removeFromRing).accept(FOUR_NODES.get(4));
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        }
        for (int i = 2 ; i <= 4 ; ++i)
        {
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingBootstrapping).accept(FOUR_NODES.get(4));
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));
        }

        int pk = pk(FOUR_NODES, 1, 2);

        // {4} promises !{1} => {2, 3, 4}, accepts on !{1, 2, 3} => {4}
        try (AutoCloseable drop = drop(FOUR_NODES, 4, to(1), to(1, 2, 3), to()))
        {
            FOUR_NODES.coordinator(4).execute("INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v1) VALUES (?, 1, 1) IF NOT EXISTS", QUORUM, pk);
            Assert.assertTrue(false);
        }
        catch (Throwable t)
        {
            if (!t.getClass().getName().equals(CasWriteTimeoutException.class.getName()))
                throw t;
        }

        // {1} promises and accepts on !{3} => {1, 2}; commits on !{2, 3} => {1}
        drop(FOUR_NODES, 1, to(3), to(3), to(2, 3));
        // two options: either we can invalidate the previous operation and succeed, or we can complete the previous operation
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        Object[][] result = executeWithRetry(FOUR_NODES.coordinator(1), "INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v2) VALUES (?, 1, 2) IF NOT EXISTS", ONE, pk);
        Object[] expectRow;
        if (result[0].length == 1)
        {
            assertRows(result, row(true));
            expectRow = row(pk, 1, null, 2);
        }
        else
        {
            assertRows(result, row(false, pk, 1, 1, null));
            expectRow = row(pk, 1, 1, null);
        }
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));

        // finish topology change
        for (int i = 1 ; i <= 4 ; ++i)
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingNormal).accept(FOUR_NODES.get(4));

        // {3} reads from !{2} => {3, 4}
        drop(FOUR_NODES, 3, to(2), to(2), to());
        assertRows(FOUR_NODES.coordinator(3).execute("SELECT * FROM " + KEYSPACE + "." + tableName + " WHERE pk = ?", SERIAL, pk),
                   expectRow);
    }

    /**
     * During a range movement, a CAS may fail leaving side effects that are not witnessed by another operation
     * being performed with stale ring information.
     * This is a particular special case of stale ring information sequencing, which probably would be resolved
     * by fixing each of the more isolated cases (but is unique, so deserving of its own test case).
     * See CASSANDRA-15745
     *
     *  - Range moves from {1, 2, 3} to {2, 3, 4}; witnessed by X (not by !X)
     *  -   X: Promised by {2, 3, 4}
     *  -   X: Accepted by {4}
     *  -  !X: Promised and Accepted by {1, 2}
     *  - Range move visible by !X
     *  - Any: Promised and Propose to {3, 4}
     */
    @Test
    public void testIncompleteWriteFollowedBySuccessfulWriteWithStaleRingDuringRangeMovementFollowedByWrite() throws Throwable
    {
        String tableName = tableName("tbl");
        FOUR_NODES.schemaChange("CREATE TABLE " + KEYSPACE + "." + tableName + " (pk int, ck int, v1 int, v2 int, PRIMARY KEY (pk, ck))");

        // make it so {4} is bootstrapping, and this has propagated to only a quorum of other nodes
        for (int i = 1; i <= 4; ++i)
        {
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::removeFromRing).accept(FOUR_NODES.get(4));
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        }
        for (int i = 2; i <= 4; ++i)
        {
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingBootstrapping).accept(FOUR_NODES.get(4));
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));
        }

        int pk = pk(FOUR_NODES, 1, 2);

        // {4} promises and accepts on !{1} => {2, 3, 4}; commits on !{1, 2, 3} => {4}
        drop(FOUR_NODES, 4, to(1), to(1, 2, 3), to());
        try
        {
            FOUR_NODES.coordinator(4).execute("INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v1) VALUES (?, 1, 1) IF NOT EXISTS", QUORUM, pk);
            Assert.assertTrue(false);
        }
        catch (Throwable t)
        {
            if (!t.getClass().getName().equals(CasWriteTimeoutException.class.getName()))
                throw t;
        }

        // {1} promises and accepts on !{3} => {1, 2}; commits on !{2, 3} => {1}
        drop(FOUR_NODES, 1, to(3), to(3), to(2, 3));
        // two options: either we can invalidate the previous operation and succeed, or we can complete the previous operation
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertNotVisibleInRing).accept(FOUR_NODES.get(4));
        Object[][] result = executeWithRetry(FOUR_NODES.coordinator(1), "INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v2) VALUES (?, 1, 2) IF NOT EXISTS", ONE, pk);
        Object[] expectRow;
        if (result[0].length == 1)
        {
            assertRows(result, row(true));
            expectRow = row(false, pk, 1, null, 2);
        }
        else
        {
            assertRows(result, row(false, pk, 1, 1, null));
            expectRow = row(false, pk, 1, 1, null);
        }
        FOUR_NODES.get(1).acceptsOnInstance(CASTestBase::assertVisibleInRing).accept(FOUR_NODES.get(4));

        // finish topology change
        for (int i = 1; i <= 4; ++i)
            FOUR_NODES.get(i).acceptsOnInstance(CASTestBase::addToRingNormal).accept(FOUR_NODES.get(4));

        // {3} reads from !{2} => {3, 4}
        FOUR_NODES.filters().verbs(PAXOS2_PREPARE_REQ.id, PAXOS_PREPARE_REQ.id, READ_REQ.id).from(3).to(2).drop();
        FOUR_NODES.filters().verbs(PAXOS2_PROPOSE_REQ.id, PAXOS_PROPOSE_REQ.id).from(3).to(2).drop();
        assertRows(FOUR_NODES.coordinator(3).execute("INSERT INTO " + KEYSPACE + "." + tableName + " (pk, ck, v2) VALUES (?, 1, 2) IF NOT EXISTS", ONE, pk),
                   expectRow);
    }

    // TODO: RF changes
    // TODO: Aborted range movements
    // TODO: Leaving ring

    static void consistencyAfterWriteTimeoutTest(BiConsumer<String, ICoordinator> postTimeoutOperation1, BiConsumer<String, ICoordinator> postTimeoutOperation2, boolean loseCommitOfOperation1, Cluster cluster)
    {
        String tableName = tableName("t");
        String table = KEYSPACE + "." + tableName;
        cluster.schemaChange("CREATE TABLE " + table + " (k int PRIMARY KEY, v int)");

        // We do a CAS insertion, but have with the PROPOSE message dropped on node 1 and 2. The CAS will not get
        // through and should timeout. Importantly, node 3 does receive and answer the PROPOSE.
        IMessageFilters.Filter dropProposeFilter = cluster.filters()
                                                          .verbs(PAXOS_PROPOSE_REQ.id, PAXOS2_PROPOSE_REQ.id)
                                                          .to(1, 2)
                                                          .drop();

        // Prepare A to {1, 2, 3}
        // Propose A to {3}
        // Timeout
        try
        {
            // NOTE: the consistency below is the "commit" one, so it doesn't matter at all here.
            cluster.coordinator(1)
                   .execute("INSERT INTO " + table + "(k, v) VALUES (0, 0) IF NOT EXISTS", ONE);
            Assert.fail("The insertion should have timed-out");
        }
        catch (Throwable t)
        {
            if (!t.getClass().getName().equals(CasWriteTimeoutException.class.getName()))
                throw t;
        }
        finally
        {
            dropProposeFilter.off();
        }

        // Prepare and Propose to {1, 2}
        // Commit(?) to either {1, 2, 3} or {3}
        // Isolates node 3 and executes the SERIAL operation. As neither node 1 or 2 got the initial insert proposal,
        // there is nothing to "replay" and the operation should assert the table is still empty.
        IMessageFilters.Filter ignoreNode3Filter = cluster.filters().verbs(paxosAndReadVerbs()).to(3).drop();
        IMessageFilters.Filter dropCommitFilter = null;
        if (loseCommitOfOperation1)
        {
            dropCommitFilter = cluster.filters().verbs(PAXOS_COMMIT_REQ.id).to(1, 2).drop();
        }
        try
        {
            postTimeoutOperation1.accept(table, cluster.coordinator(1));
        }
        finally
        {
            ignoreNode3Filter.off();
            if (dropCommitFilter != null)
                dropCommitFilter.off();
        }

        // Node 3 is now back and we isolate node 2 to ensure the next read hits node 1 and 3.
        // What we want to ensure is that despite node 3 having the initial insert in its paxos state in a position of
        // being replayed, that insert is _not_ replayed (it would contradict serializability since the previous
        // operation asserted nothing was inserted). It is this execution that failed before CASSANDRA-12126.
        IMessageFilters.Filter ignoreNode2Filter = cluster.filters().verbs(paxosAndReadVerbs()).to(2).drop();
        try
        {
            postTimeoutOperation2.accept(table, cluster.coordinator(1));
        }
        finally
        {
            ignoreNode2Filter.off();
        }
    }

    protected Cluster getCluster()
    {
        return THREE_NODES;
    }
}


text:
<!--

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2
          http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>bin</id>
    <includeBaseDirectory>true</includeBaseDirectory>
    <baseDirectory>sharing-registry</baseDirectory>
    <formats>
        <format>tar.gz</format>
    </formats>

    <fileSets>
        <fileSet>
            <directory>src/main/resources/bin</directory>
            <outputDirectory>bin</outputDirectory>
            <includes>
                <include>*.sh</include>
            </includes>
            <fileMode>755</fileMode>
        </fileSet>

        <!-- ********************** copy airavata-server.properties ********************** -->
        <fileSet>
            <directory>../../configuration/server/src/main/resources/</directory>
            <outputDirectory>bin</outputDirectory>
            <includes>
                <include>airavata-server.properties</include>
                <include>log4j.properties</include>
            </includes>
        </fileSet>

        <!-- ********************** copy database scripts ********************** -->
        <fileSet>
            <directory>../sharing-registry-server/src/main/resources/
            </directory>
            <outputDirectory>bin/database_scripts
            </outputDirectory>
            <includes>
                <include>*sql*</include>
            </includes>
        </fileSet>
    </fileSets>

    <dependencySets>
        <dependencySet>
            <outputDirectory>/lib</outputDirectory>
            <includes>
                <include>*:jar:*</include>
            </includes>
        </dependencySet>
    </dependencySets>
</assembly>

redpajama_set_name: RedPajamaGithub


text:
#if DEBUG
using NUnit.Framework;

namespace SCC.Modules.DotMap.Data.Test
{
	/// <summary>
	///
	/// </summary>
	[TestFixture]
	public class DataProviderTest
    {
        [Test]
        public void Connection()
        {
            DataProvider.CreateProvider();
        }

    }
}
#endif


text:
package io.restassured.itest.java;

import io.restassured.itest.java.support.WithJetty;
import io.restassured.itest.java.support.WriteLogsToDisk;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runners.MethodSorters;

import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import static io.restassured.RestAssured.given;
import static io.restassured.itest.java.support.WithJetty.JettyOption.DONT_RESET_REST_ASSURED_BEFORE_TEST;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LoggingToDiskTest extends WithJetty {

    public LoggingToDiskTest() {
        super(DONT_RESET_REST_ASSURED_BEFORE_TEST);
    }

    private static File directory;

    static {
        try {
            directory = Files.createTempDirectory("ra").toFile();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    @Rule
    public TestName testName = new TestName();

    @Rule
    public WriteLogsToDisk writeLogsToDisk = new WriteLogsToDisk(directory);

    @Test
    public void example1() {
        given().
                queryParam("firstName", "John").
                queryParam("lastName", "Doe").
        when().
                get("/greet").
        then().
                log().all().
                body("greeting", equalTo("Greetings John Doe"));
    }

    @Test
    public void example2() {
        given().
                queryParam("firstName", "Jane").
                queryParam("lastName", "Doe").
        when().
                get("/greet").
        then().
                log().all().
                body("greeting", equalTo("Greetings Jane Doe"));
    }

    // This test needs to be executed last, thus @FixMethodOrder
    @Test
    public void make_sure_logging_to_disk_works() throws Exception {
        List<FileAndContents> files = Files.list(directory.toPath())
                .filter(file -> !file.endsWith(testName.getMethodName() + ".log"))
                .map(file -> {
                    try {
                        return FileAndContents.of(file.getFileName().toString(), Files.readAllLines(file));
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                })
                .collect(Collectors.toList());

        FileAndContents example1Log = findByName(files, "example1.log");
        FileAndContents example2Log = findByName(files, "example2.log");

        assertThat(files.toString(), files, hasSize(2));
        assertThat(example1Log.content.getLast(), is("{\"greeting\":\"Greetings John Doe\"}"));
        assertThat(example2Log.content.getLast(), is("{\"greeting\":\"Greetings Jane Doe\"}"));
    }

    private FileAndContents findByName(List<FileAndContents> files, String name) {
        return files.stream().filter(f -> name.equals(f.fileName)).findFirst().orElse(null);
    }

    private static class FileAndContents {
        final String fileName;
        final LinkedList<String> content;

        FileAndContents(String fileName, List<String> content) {
            this.fileName = fileName;
            this.content = new LinkedList<>(content);
        }

        private static FileAndContents of(String fileName, List<String> content) {
            return new FileAndContents(fileName, content);
        }

        @Override
        public String toString() {
            return "FileAndContents{" +
                    "fileName='" + fileName + '\'' +
                    ", content='" + content + '\'' +
                    '}';
        }
    }
}


text:
namespace OpenTelemetry.Resources
{
    /// <summary>
    /// An interface for Resource detectors.
    /// </summary>
    public interface IResourceDetector
    {
        /// <summary>
        /// Called to get a resource with attributes from detector.
        /// </summary>
        /// <returns>An instance of <see cref="Resource"/>.</returns>
        Resource Detect();
    }
}


text:
Contributions are welcome, and they are greatly appreciated! Every
little bit helps, and credit will always be given.

You can contribute in many ways:

## Types of Contributions

### Report Bugs

Report bugs at <https://github.com/michaeljoseph/mould/issues>.

If you are reporting a bug, please include:

-   Your operating system name and version.
-   Any details about your local setup that might be helpful in
    troubleshooting.
-   Detailed steps to reproduce the bug.

### Fix Bugs

Look through the GitHub issues for bugs. Anything tagged with "bug" is
open to whoever wants to implement it.

### Implement Features

Look through the GitHub issues for features. Anything tagged with
"feature" is open to whoever wants to implement it.

### Write Documentation

We could always use more documentation, whether as part of the official
mould docs, in docstrings, or even on the web in blog posts and articles.

### Submit Feedback

The best way to send feedback is to file an issue at
<https://github.com/michaeljoseph/mould/issues>.

If you are proposing a feature:

-   Explain in detail how it would work.
-   Keep the scope as narrow as possible, to make it easier to
    implement.
-   Remember that this is a volunteer-driven project, and that
    contributions are welcome :)

## Documentation

[API Documentation][(https://mould.readthedocs.io)]

## Development Setup

Install development requirements:

    pip install -r requirements.txt

Tests can then be run with:

    pytest

Lint the project with:

    flake8 mould tests setup.py

## API documentation

Generate the documentation with:

    make -C docs html

To monitor changes to Python files and execute the tests
automatically, use [pytest-watch](https://github.com/joeyespo/pytest-watch):

    ptw

## Pull Request Guidelines

Before you submit a pull request, check that it meets these guidelines:

1.  The pull request should include tests.
2.  If the pull request adds functionality, the docs should be updated.
    Put your new functionality into a function with a docstring, and add
    the feature to the list in README.md.
3.  Check <https://travis-ci.org/michaeljoseph/mould/pull_requests> and make sure that
    the tests pass for all supported Python versions.


text:
package com.netflix.spectator.metrics5;

import com.netflix.spectator.api.Clock;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;

import java.util.Collections;

/** Counter implementation for the metrics5 registry. */
class MetricsCounter implements Counter {

  private final Clock clock;
  private final Id id;
  private final io.dropwizard.metrics5.Meter impl;

  /** Create a new instance. */
  MetricsCounter(Clock clock, Id id, io.dropwizard.metrics5.Meter impl) {
    this.clock = clock;
    this.id = id;
    this.impl = impl;
  }

  @Override public Id id() {
    return id;
  }

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

  @Override public Iterable<Measurement> measure() {
    long now = clock.wallTime();
    long v = impl.getCount();
    return Collections.singleton(new Measurement(id, now, v));
  }

  @Override public void add(double amount) {
    impl.mark((long) amount);
  }

  @Override public double actualCount() {
    return impl.getCount();
  }
}


text: module.exports = "#inline-sourcemap";


text:
/* Configuration of TWI Slave Example */
 /**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_TWI_SLAVE_EXAMPLE_H_INCLUDED
#define CONF_TWI_SLAVE_EXAMPLE_H_INCLUDED

/** Definition of TWI interrupt ID on board. */
#define BOARD_TWI_IRQn          FLEXCOM4_IRQn
#define BOARD_TWI_Handler       FLEXCOM4_Handler

/** TWI ID for SLAVE application to use */
#define BOARD_ID_TWI_SLAVE          ID_FLEXCOM4
/** TWI Base for TWI SLAVE application to use */
#define BOARD_BASE_TWI_SLAVE        TWI4

#endif /* CONF_TWI_SLAVE_EXAMPLE_H_INCLUDED */


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.20-9-c-iii-30
description: >
    Array.prototype.filter - return value (new Boolean(false)) of
    callbackfn is treated as true value
---*/

        function callbackfn(val, idx, obj) {
            return new Boolean(false);
        }

        var newArr = [11].filter(callbackfn);

assert.sameValue(newArr.length, 1, 'newArr.length');
assert.sameValue(newArr[0], 11, 'newArr[0]');


text:
namespace cc {

void TestRenderPass::AppendQuad(scoped_ptr<DrawQuad> quad) {
  quad_list.push_back(quad.Pass());
}

void TestRenderPass::AppendSharedQuadState(scoped_ptr<SharedQuadState> state) {
  shared_quad_state_list.push_back(state.Pass());
}

void TestRenderPass::AppendOneOfEveryQuadType(
    ResourceProvider* resource_provider,
    RenderPass::Id child_pass) {
  gfx::Rect rect(0, 0, 100, 100);
  gfx::Rect opaque_rect(10, 10, 80, 80);
  gfx::Rect visible_rect(0, 0, 100, 100);
  const float vertex_opacity[] = {1.0f, 1.0f, 1.0f, 1.0f};
  ResourceProvider::ResourceId resource1 = resource_provider->CreateResource(
      gfx::Size(45, 5),
      GL_CLAMP_TO_EDGE,
      ResourceProvider::TextureUsageAny,
      resource_provider->best_texture_format());
  resource_provider->AllocateForTesting(resource1);
  ResourceProvider::ResourceId resource2 = resource_provider->CreateResource(
      gfx::Size(346, 61),
      GL_CLAMP_TO_EDGE,
      ResourceProvider::TextureUsageAny,
      resource_provider->best_texture_format());
  resource_provider->AllocateForTesting(resource2);
  ResourceProvider::ResourceId resource3 = resource_provider->CreateResource(
      gfx::Size(12, 134),
      GL_CLAMP_TO_EDGE,
      ResourceProvider::TextureUsageAny,
      resource_provider->best_texture_format());
  resource_provider->AllocateForTesting(resource3);
  ResourceProvider::ResourceId resource4 = resource_provider->CreateResource(
      gfx::Size(56, 12),
      GL_CLAMP_TO_EDGE,
      ResourceProvider::TextureUsageAny,
      resource_provider->best_texture_format());
  resource_provider->AllocateForTesting(resource4);
  ResourceProvider::ResourceId resource5 = resource_provider->CreateResource(
      gfx::Size(73, 26),
      GL_CLAMP_TO_EDGE,
      ResourceProvider::TextureUsageAny,
      resource_provider->best_texture_format());
  resource_provider->AllocateForTesting(resource5);
  ResourceProvider::ResourceId resource6 = resource_provider->CreateResource(
      gfx::Size(64, 92),
      GL_CLAMP_TO_EDGE,
      ResourceProvider::TextureUsageAny,
      resource_provider->best_texture_format());
  resource_provider->AllocateForTesting(resource6);
  ResourceProvider::ResourceId resource7 = resource_provider->CreateResource(
      gfx::Size(9, 14),
      GL_CLAMP_TO_EDGE,
      ResourceProvider::TextureUsageAny,
      resource_provider->best_texture_format());
  resource_provider->AllocateForTesting(resource7);

  scoped_ptr<SharedQuadState> shared_state = SharedQuadState::Create();
  shared_state->SetAll(gfx::Transform(),
                       rect.size(),
                       rect,
                       rect,
                       false,
                       1,
                       SkXfermode::kSrcOver_Mode);

  scoped_ptr<CheckerboardDrawQuad> checkerboard_quad =
      CheckerboardDrawQuad::Create();
  checkerboard_quad->SetNew(
      shared_state.get(), rect, visible_rect, SK_ColorRED);
  AppendQuad(checkerboard_quad.PassAs<DrawQuad>());

  scoped_ptr<DebugBorderDrawQuad> debug_border_quad =
      DebugBorderDrawQuad::Create();
  debug_border_quad->SetNew(
      shared_state.get(), rect, visible_rect, SK_ColorRED, 1);
  AppendQuad(debug_border_quad.PassAs<DrawQuad>());

  scoped_ptr<IOSurfaceDrawQuad> io_surface_quad = IOSurfaceDrawQuad::Create();
  io_surface_quad->SetNew(shared_state.get(),
                          rect,
                          opaque_rect,
                          visible_rect,
                          gfx::Size(50, 50),
                          resource7,
                          IOSurfaceDrawQuad::FLIPPED);
  AppendQuad(io_surface_quad.PassAs<DrawQuad>());

  if (child_pass.layer_id) {
    scoped_ptr<RenderPassDrawQuad> render_pass_quad =
        RenderPassDrawQuad::Create();
    render_pass_quad->SetNew(shared_state.get(),
                             rect,
                             visible_rect,
                             child_pass,
                             false,
                             resource5,
                             rect,
                             gfx::RectF(),
                             FilterOperations(),
                             FilterOperations());
    AppendQuad(render_pass_quad.PassAs<DrawQuad>());

    scoped_ptr<RenderPassDrawQuad> render_pass_replica_quad =
        RenderPassDrawQuad::Create();
    render_pass_replica_quad->SetNew(shared_state.get(),
                                     rect,
                                     visible_rect,
                                     child_pass,
                                     true,
                                     resource5,
                                     rect,
                                     gfx::RectF(),
                                     FilterOperations(),
                                     FilterOperations());
    AppendQuad(render_pass_replica_quad.PassAs<DrawQuad>());
  }

  scoped_ptr<SolidColorDrawQuad> solid_color_quad =
      SolidColorDrawQuad::Create();
  solid_color_quad->SetNew(
      shared_state.get(), rect, visible_rect, SK_ColorRED, false);
  AppendQuad(solid_color_quad.PassAs<DrawQuad>());

  scoped_ptr<StreamVideoDrawQuad> stream_video_quad =
      StreamVideoDrawQuad::Create();
  stream_video_quad->SetNew(shared_state.get(),
                            rect,
                            opaque_rect,
                            visible_rect,
                            resource6,
                            gfx::Transform());
  AppendQuad(stream_video_quad.PassAs<DrawQuad>());

  scoped_ptr<TextureDrawQuad> texture_quad = TextureDrawQuad::Create();
  texture_quad->SetNew(shared_state.get(),
                       rect,
                       opaque_rect,
                       visible_rect,
                       resource1,
                       false,
                       gfx::PointF(0.f, 0.f),
                       gfx::PointF(1.f, 1.f),
                       SK_ColorTRANSPARENT,
                       vertex_opacity,
                       false);
  AppendQuad(texture_quad.PassAs<DrawQuad>());

  scoped_ptr<TileDrawQuad> scaled_tile_quad = TileDrawQuad::Create();
  scaled_tile_quad->SetNew(shared_state.get(),
                           rect,
                           opaque_rect,
                           visible_rect,
                           resource2,
                           gfx::RectF(0, 0, 50, 50),
                           gfx::Size(50, 50),
                           false);
  AppendQuad(scaled_tile_quad.PassAs<DrawQuad>());

  scoped_ptr<SharedQuadState> transformed_state = shared_state->Copy();
  gfx::Transform rotation;
  rotation.Rotate(45);
  transformed_state->content_to_target_transform =
      transformed_state->content_to_target_transform * rotation;
  scoped_ptr<TileDrawQuad> transformed_tile_quad = TileDrawQuad::Create();
  transformed_tile_quad->SetNew(transformed_state.get(),
                                rect,
                                opaque_rect,
                                visible_rect,
                                resource3,
                                gfx::RectF(0, 0, 100, 100),
                                gfx::Size(100, 100),
                                false);
  AppendQuad(transformed_tile_quad.PassAs<DrawQuad>());

  scoped_ptr<SharedQuadState> shared_state2 = SharedQuadState::Create();
  shared_state->SetAll(gfx::Transform(),
                       rect.size(),
                       rect,
                       rect,
                       false,
                       1,
                       SkXfermode::kSrcOver_Mode);

  scoped_ptr<TileDrawQuad> tile_quad = TileDrawQuad::Create();
  tile_quad->SetNew(shared_state2.get(),
                    rect,
                    opaque_rect,
                    visible_rect,
                    resource4,
                    gfx::RectF(0, 0, 100, 100),
                    gfx::Size(100, 100),
                    false);
  AppendQuad(tile_quad.PassAs<DrawQuad>());

  ResourceProvider::ResourceId plane_resources[4];
  for (int i = 0; i < 4; ++i) {
    plane_resources[i] =
        resource_provider->CreateResource(
            gfx::Size(20, 12),
            GL_CLAMP_TO_EDGE,
            ResourceProvider::TextureUsageAny,
            resource_provider->best_texture_format());
    resource_provider->AllocateForTesting(plane_resources[i]);
  }
  scoped_ptr<YUVVideoDrawQuad> yuv_quad = YUVVideoDrawQuad::Create();
  yuv_quad->SetNew(shared_state2.get(),
                   rect,
                   opaque_rect,
                   visible_rect,
                   gfx::Size(100, 100),
                   plane_resources[0],
                   plane_resources[1],
                   plane_resources[2],
                   plane_resources[3]);
  AppendQuad(yuv_quad.PassAs<DrawQuad>());

  AppendSharedQuadState(shared_state.Pass());
  AppendSharedQuadState(transformed_state.Pass());
  AppendSharedQuadState(shared_state2.Pass());
}

}  // namespace cc


text:
package net.evolutionaryarchitecture.jpa.inheritance;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "T_PERSONS")
public class Person {

    @Id
    @GeneratedValue
    @Column(name = "PERSON_ID")
    private Long id;

    @Column(name="PERSON_AGE")
    private int age;

    @Embedded
    private Name name;

    @ElementCollection
    @CollectionTable(name="T_ADDRESS")
    private Set<Address> addresses = new HashSet<Address>();

    @ElementCollection
    @CollectionTable(name="T_PERSON_EMAIL_ADDR")
    private Set<String> emailAddresses = new HashSet<String>();

    @ManyToMany
    @JoinTable(name="T_EVENT_REGISTRATIONS")
    private Set<Event> eventsRegisteredFor = new HashSet<Event>();

    protected Person() {
    }

    protected Person(Name name) {
        setName(name);
    }

    public void addRegistrationToEvent(Event event) {
        this.getEventsRegisteredFor().add(event);
        event.getParticipants().add(this);
    }

    public void removeRegistrationFromEvent(Event event) {
        this.getEventsRegisteredFor().remove(event);
        event.getParticipants().remove(this);
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Name getName() {
        return name;
    }

    public void setName(Name name) {
        this.name = name;
    }

    public Set<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(Set<Address> addresses) {
        this.addresses = addresses;
    }

    public Set<String> getEmailAddresses() {
        return emailAddresses;
    }

    public void setEmailAddresses(Set<String> emailAddresses) {
        this.emailAddresses = emailAddresses;
    }

    public Set<Event> getEventsRegisteredFor() {
        return eventsRegisteredFor;
    }

    @SuppressWarnings("unused")
    private void setEventsRegisteredFor(Set<Event> eventsRegisteredFor) {
        this.eventsRegisteredFor = eventsRegisteredFor;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Person [id=").append(id).append(", age=").append(age)
                .append(", name=").append(name).append(", addresses=")
                .append(addresses).append(", emailAddresses=")
                .append(emailAddresses).append("]");
        return builder.toString();
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">APOSTLES NOT IN THE QUORUM OF THE TWELVE APOSTLES</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/joseph-smith-jr</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/oliver-cowdery</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/david-whitmer</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/martin-harris</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/hyrum-smith</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/jedediah-m-grant</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/daniel-h-wells</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/john-willard-young</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/joseph-angell-young</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#broader</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/vrl/church-leaders/apostles-not-in-the-quorum-of-the-twelve-apostles/alvin-r-dyer</sem:object>
  </sem:triple>
</sem:triples>


text:
```JavaScript
'pi';
import { PIScheme } from 'polymorphic-identifiers';

// example scheme
class qa extends PIScheme {
  read() {
    const { elements } = this.parse();
    return elements;
  }
  write(v) {
    const { elements, type, prop } = this.parse();

    if (type === 'style') {
      return elements.forEach(e => e.style[prop] = v)
    }
    elements.forEach(e => e.innerHTML = v)
  }

  // helper
  parse() {
    const [selector, type, prop] = this.strings.first.split('/');
    const elements = this.query(selector);
    return { selector, type, prop, elements };
  }
  query(selector) {
    return Array.from(document.querySelectorAll(selector));
  }
}

// usage
// calls `read`
qa`lively-window`.forEach(lw => lively.showElement(lw))

// assignments with <<
// calls `write`
qa`#rect` << 'html'
qa`#rect/style/border-color` << 'green'
```


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  MAX_RAMCACHE_MB
  LibVT_Config.h

Searching...

No Matches


text:
#ifndef STD_MATH_H
#include "SheafSystem/std_cmath.h"
#endif

namespace sheaf
{

  // ===========================================================
  // FLOAT COMPARISION
  // ===========================================================

  ///
  /// Tolerance for float comparisons.
  ///
  const float float_tolerance = sqrt(std::numeric_limits<float>::epsilon());

  ///
  /// Absolute equality comparison of float xf0 to 0.0f using tolerance float_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool a_eql_0(float xf0)
  {
    return std::abs(xf0) <= float_tolerance;
  };

  ///
  /// Absolute equality comparison of float xf0 to 0.0f using tolerance xtolerance
  ///
  SHEAF_DLL_SPEC inline bool a_eql_0(float xf0, float xtolerance)
  {
    return std::abs(xf0) <= xtolerance;
  };

  ///
  /// Absolute equality comparison of float xf0 to 1.0f using tolerance float_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool a_eql_1(float xf0)
  {
    return std::abs(xf0 - 1.0f) <= float_tolerance;
  };

  ///
  /// Absolute equality comparison of float xf0 to 1.0f using tolerance xtolerance
  ///
  SHEAF_DLL_SPEC inline bool a_eql_1(float xf0, float xtolerance)
  {
    return std::abs(xf0 - 1.0f) <= xtolerance;
  };

  ///
  /// Absolute equality comparison of float xf0 to float xf1 using tolerance float_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool a_eql(float xf0, float xf1)
  {
    return std::abs(xf0 - xf1) <= float_tolerance;
  };

  ///
  /// Absolute equality comparison of float xf0 to float xf1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool a_eql(float xf0, float xf1, float xtolerance)
  {
    return std::abs(xf0 - xf1) <= xtolerance;
  };

  ///
  /// Relative equality comparison of float xf0 to float xf1 using tolerance float_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool r_eql(float xf0, float xf1)
  {
    return std::abs(xf0 - xf1) <= float_tolerance*(std::abs(xf0) + std::abs(xf1));
  };

  ///
  /// Relative equality comparison of float xf0 to float xf1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool r_eql(float xf0, float xf1, float xtolerance)
  {
    return std::abs(xf0 - xf1) <= xtolerance*(std::abs(xf0) + std::abs(xf1));
  };

  ///
  /// Combined equality comparison of float xf0 to float xf1 using tolerance float_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_eql(float xf0, float xf1)
  {
    return std::abs(xf0 - xf1) <= float_tolerance*(std::abs(xf0) + std::abs(xf1) + 1.0f);
  };

  ///
  /// Combined equality comparison of float xf0 to float xf1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_eql(float xf0, float xf1, float xtolerance)
  {
    return std::abs(xf0 - xf1) <= xtolerance*(std::abs(xf0) + std::abs(xf1) + 1.0f);
  };

  // ===========================================================
  // DOUBLE EQUALITY COMPARISION
  // ===========================================================

  ///
  /// Tolerance for double comparisons.
  ///
  const double double_tolerance = sqrt(std::numeric_limits<double>::epsilon());

  ///
  /// Absolute equality comparison of double xd0 to 0.0 using tolerance double_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool a_eql_0(double xd0)
  {
    return std::abs(xd0) <= double_tolerance;
  };

  ///
  /// Absolute equality comparison of double xd0 to 0.0 using tolerance xtolerance
  ///
  SHEAF_DLL_SPEC inline bool a_eql_0(double xd0, double xtolerance)
  {
    return std::abs(xd0) <= xtolerance;
  };

  ///
  /// Absolute equality comparison of double xd0 to 1.0 using tolerance double_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool a_eql_1(double xd0)
  {
    return std::abs(xd0 - 1.0) <= double_tolerance;
  };

  ///
  /// Absolute equality comparison of double xd0 to 1.0 using tolerance xtolerance
  ///
  SHEAF_DLL_SPEC inline bool a_eql_1(double xd0, double xtolerance)
  {
    return std::abs(xd0 - 1.0) <= xtolerance;
  };

  ///
  /// Absolute equality comparison of double xd0 to double xd1 using tolerance double_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool a_eql(double xd0, double xd1)
  {
    return std::abs(xd0 - xd1) <= double_tolerance;
  };

  ///
  /// Absolute equality comparison of double xd0 to double xd1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool a_eql(double xd0, double xd1, double xtolerance)
  {
    return std::abs(xd0 - xd1) <= xtolerance;
  };

  ///
  /// Relative equality comparison of double xd0 to double xd1 using tolerance double_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool r_eql(double xd0, double xd1)
  {
    return std::abs(xd0 - xd1) <= double_tolerance*(std::abs(xd0) + std::abs(xd1));
  };

  ///
  /// Relative equality comparison of double xd0 to double xd1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool r_eql(double xd0, double xd1, double xtolerance)
  {
    return std::abs(xd0 - xd1) <= xtolerance*(std::abs(xd0) + std::abs(xd1));
  };

  ///
  /// Combined equality equality comparison of double xd0 to double xd1 using tolerance double_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_eql(double xd0, double xd1)
  {
    return std::abs(xd0 - xd1) <= double_tolerance*(std::abs(xd0) + std::abs(xd1) + 1.0);
  };

  ///
  /// Combined equality equality comparison of double xd0 to double xd1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_eql(double xd0, double xd1, double xtolerance)
  {
    return std::abs(xd0 - xd1) <= xtolerance*(std::abs(xd0) + std::abs(xd1) + 1.0);
  };

  // ===========================================================
  // DOUBLE LESS THAN OR EQUAL COMPARISION
  // ===========================================================

  ///
  /// Combined less than or equal comparison of double xd0 to double xd1 using tolerance double_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_lte(double xd0, double xd1)
  {
    return xd0 <= (xd1 + double_tolerance*(std::abs(xd0) + std::abs(xd1) + 1.0));
  };

  ///
  /// Combined less than or equal comparison of double xd0 to double xd1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_lte(double xd0, double xd1, double xtolerance)
  {
    return xd0 <= (xd1 + xtolerance*(std::abs(xd0) + std::abs(xd1) + 1.0));
  };

  // ===========================================================
  // DOUBLE LESS THAN COMPARISION
  // ===========================================================

  ///
  /// Combined less than comparison of double xd0 to double xd1 using tolerance double_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_lt(double xd0, double xd1)
  {
    return xd0 < (xd1 - double_tolerance*(std::abs(xd0) + std::abs(xd1) + 1.0));
  };

  ///
  /// Combined less than comparison of double xd0 to double xd1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_lt(double xd0, double xd1, double xtolerance)
  {
    return xd0 < (xd1 - xtolerance*(std::abs(xd0) + std::abs(xd1) + 1.0));
  };

  // ===========================================================
  // DOUBLE GREATER THAN OR EQUAL COMPARISION
  // ===========================================================

  ///
  /// Combined greater than or equal comparison of double xd0 to double xd1 using tolerance double_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_gte(double xd0, double xd1)
  {
    return xd0 >= (xd1 - double_tolerance*(std::abs(xd0) + std::abs(xd1) + 1.0));
  };

  ///
  /// Combined greater than or equal comparison of double xd0 to double xd1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_gte(double xd0, double xd1, double xtolerance)
  {
    return xd0 >= (xd1 - xtolerance*(std::abs(xd0) + std::abs(xd1) + 1.0));
  };

  // ===========================================================
  // DOUBLE GREATER THAN COMPARISION
  // ===========================================================

  ///
  /// Combined greater than comparison of double xd0 to double xd1 using tolerance double_tolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_gt(double xd0, double xd1)
  {
    return xd0 > (xd1 + double_tolerance*(std::abs(xd0) + std::abs(xd1) + 1.0));
  };

  ///
  /// Combined greater than comparison of double xd0 to double xd1 using tolerance xtolerance.
  ///
  SHEAF_DLL_SPEC inline bool c_gt(double xd0, double xd1, double xtolerance)
  {
    return xd0 > (xd1 + xtolerance*(std::abs(xd0) + std::abs(xd1) + 1.0));
  };

} // end namespace sheaf

#endif // ifndef TOLERANCE_COMPARISON_H


text:
package com.rey.material.drawable;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.BoringLayout;
import android.text.Layout;
import android.text.TextPaint;
import android.text.TextUtils;

/**
 * Created by Rey on 1/21/2015.
 */
public class ContactChipDrawable extends Drawable{

    private Paint mPaint;
    private int mPaddingLeft;
    private int mPaddingRight;
    private int mBackgroundColor;

    private CharSequence mContactName;
    private BoringLayout mBoringLayout;
    private BoringLayout.Metrics mMetrics;
    private TextPaint mTextPaint;
    private RectF mRect;

    private BitmapShader mBitmapShader;
    private Bitmap mBitmap;
    private Matrix mMatrix;

    public ContactChipDrawable(int paddingLeft, int paddingRight, Typeface typeface, int textColor, int textSize, int backgroundColor) {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(textColor);
        mPaint.setTypeface(typeface);
        mPaint.setTextSize(textSize);

        mTextPaint = new TextPaint(mPaint);
        mMetrics = new BoringLayout.Metrics();
        Paint.FontMetricsInt temp = mTextPaint.getFontMetricsInt();
        mMetrics.ascent = temp.ascent;
        mMetrics.bottom = temp.bottom;
        mMetrics.descent = temp.descent;
        mMetrics.top = temp.top;
        mMetrics.leading = temp.leading;

        mRect = new RectF();

        mMatrix = new Matrix();

        mPaddingLeft = paddingLeft;
        mPaddingRight = paddingRight;
        mBackgroundColor = backgroundColor;
    }

    public void setContactName(CharSequence name){
        mContactName = name;
        updateLayout();
        invalidateSelf();
    }

    public void setImage(Bitmap bm){
        if(mBitmap != bm){
            mBitmap = bm;
            if(mBitmap != null) {
                mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
                updateMatrix();
            }
            invalidateSelf();
        }
    }

    private void updateLayout(){
        if(mContactName == null)
            return;

        Rect bounds = getBounds();
        if(bounds.width() == 0 || bounds.height() == 0)
            return;

        int outerWidth = Math.max(0, bounds.width() - bounds.height() - mPaddingLeft - mPaddingRight);
        mMetrics.width = Math.round(mTextPaint.measureText(mContactName, 0, mContactName.length()) + 0.5f);

        if(mBoringLayout == null)
            mBoringLayout = BoringLayout.make(mContactName, mTextPaint, outerWidth, Layout.Alignment.ALIGN_NORMAL, 1f, 1f, mMetrics, true, TextUtils.TruncateAt.END, outerWidth);
        else
            mBoringLayout = mBoringLayout.replaceOrMake(mContactName, mTextPaint, outerWidth, Layout.Alignment.ALIGN_NORMAL, 1f, 1f, mMetrics, true, TextUtils.TruncateAt.END, outerWidth);
    }

    private void updateMatrix(){
        if(mBitmap == null)
            return;

        Rect bounds = getBounds();
        if(bounds.width() == 0 || bounds.height() == 0)
            return;

        mMatrix.reset();
        float scale = bounds.height() / (float)Math.min(mBitmap.getWidth(), mBitmap.getHeight());
        mMatrix.setScale(scale, scale, 0, 0);
        mMatrix.postTranslate((bounds.height()  - mBitmap.getWidth() * scale) / 2, (bounds.height() - mBitmap.getHeight() * scale) / 2);

        mBitmapShader.setLocalMatrix(mMatrix);
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        updateLayout();
        updateMatrix();
    }

    @Override
    public void draw(Canvas canvas) {
        int saveCount = canvas.save();

        Rect bounds = getBounds();
        float halfHeight = bounds.height() / 2f;
        mPaint.setShader(null);
        mPaint.setColor(mBackgroundColor);
        mRect.set(1, 0, bounds.height() + 1, bounds.height());
        canvas.drawArc(mRect, 90, 180, true, mPaint);
        mRect.set(bounds.width() - bounds.height(), 0, bounds.width(), bounds.height());
        canvas.drawArc(mRect, 270, 180, true, mPaint);
        mRect.set(halfHeight, 0, bounds.width() - halfHeight, bounds.height());
        canvas.drawRect(mRect, mPaint);

        if(mBitmap != null){
            mPaint.setShader(mBitmapShader);
            canvas.drawCircle(halfHeight, halfHeight, halfHeight, mPaint);
        }

        if(mContactName != null && mBoringLayout != null) {
            canvas.translate(bounds.height() + mPaddingLeft, (bounds.height() - mBoringLayout.getHeight()) / 2f);
            mBoringLayout.draw(canvas);
        }

        canvas.restoreToCount(saveCount);
    }

    @Override
    public void setAlpha(int alpha) {
        mPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        mPaint.setColorFilter(cf);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }
}


text:
namespace Talifun.Web.Helper.Pooling
{
    public enum AccessMode { FIFO, LIFO, Circular };
}


text:
@interface UIApplication (tvout)
- (void) startTVOut;
- (void) stopTVOut;
- (void) updateTVOut;
@end

@interface MPTVOutWindow : UIWindow
- (id)initWithVideoView:(id)fp8;
@end

@interface MPVideoView : UIView
- (id)initWithFrame:(struct CGRect)fp8;
@end

@implementation MPVideoView (tvout)
- (void) addSubview: (UIView *) aView
{
    [super addSubview:aView];
}
@end

CGImageRef UIGetScreenImage();

@interface UIImage (tvout)
+ (UIImage *)imageWithScreenContents;
@end

@implementation UIImage (tvout)
+ (UIImage *)imageWithScreenContents
{
    CGImageRef cgScreen = UIGetScreenImage();
    if (cgScreen) {
        UIImage *result = [UIImage imageWithCGImage:cgScreen];
        CGImageRelease(cgScreen);
        return result;
    }
    return nil;
}
@end

UIWindow* deviceWindow;
MPTVOutWindow* tvoutWindow;
NSTimer *updateTimer;
UIImage *image;
UIImageView *mirrorView;
BOOL done;

@implementation UIApplication (tvout)

// if you uncomment this, you won't need to call startTVOut in your app.
// but the home button will no longer work! Other badness may follow!
//
// - (void)reportAppLaunchFinished;
//{
//	[self startTVOut];
//}

- (void) startTVOut;
{
	// you need to have a main window already open when you call start
	if (!tvoutWindow) {
		deviceWindow = [self keyWindow];

		MPVideoView *vidView = [[MPVideoView alloc] initWithFrame: CGRectZero];
		tvoutWindow = [[MPTVOutWindow alloc] initWithVideoView:vidView];
		[tvoutWindow makeKeyAndVisible];
		tvoutWindow.userInteractionEnabled = NO;

		mirrorView = [[UIImageView alloc] initWithFrame: [[UIScreen mainScreen] bounds]];

		if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait) {
			mirrorView.transform = CGAffineTransformRotate(mirrorView.transform, M_PI * 1.5);
		}
		mirrorView.center = vidView.center;
		[vidView addSubview: mirrorView];

		[deviceWindow makeKeyAndVisible];

		[NSThread detachNewThreadSelector:@selector(updateLoop) toTarget:self withObject:nil];
	}
}

- (void) stopTVOut;
{
	done = YES;
	if (updateTimer) {
		[updateTimer invalidate];
		[updateTimer release];
		updateTimer = nil;
	}
	if (tvoutWindow) {
		[tvoutWindow release];
		tvoutWindow = nil;
	}
}

- (void) updateTVOut;
{
	image = [UIImage imageWithScreenContents];
	mirrorView.image = image;
}

- (void)updateLoop;
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    done = NO;

    while ( ! done )
    {
		[self performSelectorOnMainThread:@selector(updateTVOut) withObject:nil waitUntilDone:NO];
        [NSThread sleepForTimeInterval: (1.0/kFPS) ];
    }
    [pool release];
}

@end


text:
namespace CohesionAndCoupling
{
    using System;

    public class Parallelepiped
    {
        private const string InvalidWidthException = "The width cannot be a negative number.";
        private const string InvalidHeightException = "The height cannot be a negative number.";
        private const string InvalidDepthException = "The depth cannot be a negative number.";

        private double width;
        private double height;
        private double depth;

        public Parallelepiped(double width, double height, double depth)
        {
            this.Width = width;
            this.Height = height;
            this.Depth = depth;
        }

        public double Width
        {
            get
            {
                return this.width;
            }

            set
            {
                if (value < 0)
                {
                    throw new ArgumentException(Parallelepiped.InvalidWidthException);
                }

                this.width = value;
            }
        }

        public double Height
        {
            get
            {
                return this.height;
            }

            set
            {
                if (value < 0)
                {
                    throw new ArgumentException(Parallelepiped.InvalidHeightException);
                }

                this.height = value;
            }
        }

        public double Depth
        {
            get
            {
                return this.depth;
            }

            set
            {
                if (value < 0)
                {
                    throw new ArgumentException(Parallelepiped.InvalidDepthException);
                }

                this.depth = value;
            }
        }

        public double CalcVolume()
        {
            double volume = this.Width * this.Height * this.Depth;
            return volume;
        }
    }
}


text:
<?php

/**
 * Handle action=render
 *
 * This is a wrapper that will call Article::render().
 *
 * @ingroup Actions
 */
class RenderAction extends FormlessAction {

	public function getName() {
		return 'render';
	}

	public function onView() {
		return null;
	}

	public function show() {

		$this->page->render();
	}
}


text:
// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
// snippet-sourcedescription:[MergeBranches.java demonstrates how to merge two branches.]
// snippet-keyword:[AWS SDK for Java v2]
// snippet-service:[AWS CodeCommit]

package com.example.commit;

// snippet-start:[codecommit.java2.merge.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.codecommit.CodeCommitClient;
import software.amazon.awssdk.services.codecommit.model.CodeCommitException;
import software.amazon.awssdk.services.codecommit.model.MergeBranchesByFastForwardRequest;
import software.amazon.awssdk.services.codecommit.model.MergeBranchesByFastForwardResponse;
// snippet-end:[codecommit.java2.merge.import]

/**
 * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials.
 *
 * For information, see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class MergeBranches {

    public static void main(String[] args) {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    <repoName> <targetBranch> <sourceReference> <destinationCommitId>\n\n" +
                "Where:\n" +
                "    repoName - the name of the repository.\n" +
                "    targetBranch -  the branch where the merge is applied.\n" +
                "    sourceReference  - the branch of the repository that contains the changes.\n" +
                "    destinationCommitId  - a full commit ID.\n" ;

        if (args.length != 4) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String repoName = args[0];
        String targetBranch = args[1];
        String sourceReference = args[2];
        String destinationCommitId = args[3];

        Region region = Region.US_EAST_1;
        CodeCommitClient codeCommitClient = CodeCommitClient.builder()
                .region(region)
                .build();

        merge(codeCommitClient, repoName, targetBranch, sourceReference, destinationCommitId) ;
        codeCommitClient.close();

    }

    // snippet-start:[codecommit.java2.merge.main]
    public static void merge(CodeCommitClient codeCommitClient,
                      String repoName,
                      String targetBranch,
                      String sourceReference,
                      String destinationCommitId) {

        try {
            MergeBranchesByFastForwardRequest fastForwardRequest = MergeBranchesByFastForwardRequest.builder()
                .destinationCommitSpecifier(destinationCommitId)
                .targetBranch(targetBranch)
                .sourceCommitSpecifier(sourceReference)
                .repositoryName(repoName)
                .build();

            MergeBranchesByFastForwardResponse response = codeCommitClient.mergeBranchesByFastForward(fastForwardRequest);
            System.out.println("The commit id is "+response.commitId());

        } catch (CodeCommitException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[codecommit.java2.merge.main]
}


text:
// SBT
import sbt._
import Keys._

// sbt-assembly
import sbtassembly._
import sbtassembly.AssemblyKeys._

/**
 * Common settings-patterns for Snowplow apps and libraries.
 * To enable any of these you need to explicitly add Settings value to build.sbt
 */
object BuildSettings {

  /**
   * Common set of useful and restrictive compiler flags
   */
  lazy val buildSettings = Seq(
    scalacOptions ++= Seq(
      "-deprecation",
      "-encoding", "UTF-8",
      "-feature",
      "-unchecked",
      "-Ywarn-unused-import",
      "-Ywarn-nullary-unit",
      "-Xfatal-warnings",
      "-Xlint",
      "-Yinline-warnings",
      "-language:higherKinds",
      "-Ypartial-unification",
      "-Xfuture"),

    scalacOptions in (Compile, console) := Seq(
      "-deprecation",
      "-encoding", "UTF-8"
    ),

    addCompilerPlugin("org.spire-math" % "kind-projector" % "0.9.4" cross CrossVersion.binary)
  )

  // sbt-assembly settings
  lazy val assemblySettings = Seq(
    assemblyJarName in assembly := { name.value + "-" + version.value + ".jar" },

    assemblyMergeStrategy in assembly := {
      case PathList("META-INF", _ @ _*) => MergeStrategy.discard
      case PathList("reference.conf", _ @ _*) => MergeStrategy.concat
      case x => MergeStrategy.first
    }
  )

  /**
   * Makes package (build) metadata available withing source code
   */
  lazy val scalifySettings = Seq(
    sourceGenerators in Compile += Def.task {
      val file = (sourceManaged in Compile).value / "settings.scala"
      IO.write(file, """package com.snowplowanalytics.snowplow.rdbloader.generated
                       |object ProjectMetadata {
                       |  val version = "%s"
                       |  val name = "%s"
                       |  val organization = "%s"
                       |  val scalaVersion = "%s"
                       |}
                       |""".stripMargin.format(version.value, name.value, organization.value, scalaVersion.value))
      Seq(file)
    }.taskValue
  )
}


text:
package io.cloudslang.content.microsoftAD.services;

import com.google.gson.JsonObject;
import io.cloudslang.content.microsoftAD.entities.AzureActiveDirectoryCommonInputs;
import io.cloudslang.content.microsoftAD.entities.UpdateUserInputs;
import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static io.cloudslang.content.constants.OutputNames.RETURN_RESULT;
import static io.cloudslang.content.microsoftAD.services.HttpCommons.httpPatch;
import static io.cloudslang.content.microsoftAD.utils.Constants.*;
import static io.cloudslang.content.microsoftAD.utils.Inputs.CommonInputs.*;
import static io.cloudslang.content.microsoftAD.utils.Inputs.CommonInputs.ACCOUNT_ENABLED;
import static org.apache.commons.lang3.CharEncoding.UTF_8;
import static org.apache.commons.lang3.StringUtils.EMPTY;

public class UpdateUserService {

    public static Map<String, String> updateUser(UpdateUserInputs updateUserInputs) {

        Map<String, String> result = new HashMap<>();
        String UPDATE_USERS_URL = getUpdateUserUrl(updateUserInputs);

        if (!updateUserInputs.getUserCommonInputs().getBody().equals(EMPTY))
            return httpPatch(updateUserInputs.getUserCommonInputs().getCommonInputs(), UPDATE_USERS_URL, updateUserInputs.getUserCommonInputs().getBody());

        JsonObject body = new JsonObject();
        if (!updateUserInputs.getUserCommonInputs().getAccountEnabled().isEmpty())
            body.addProperty(ACCOUNT_ENABLED, updateUserInputs.getUserCommonInputs().getAccountEnabled());
        if (!updateUserInputs.getUserCommonInputs().getDisplayName().isEmpty())
            body.addProperty(DISPLAY_NAME, updateUserInputs.getUserCommonInputs().getDisplayName());
        if (!updateUserInputs.getUserCommonInputs().getOnPremisesImmutableId().isEmpty())
            body.addProperty(ON_PREMISES_IMMUTABLE_ID, updateUserInputs.getUserCommonInputs().getOnPremisesImmutableId());
        if (!updateUserInputs.getUserCommonInputs().getMailNickname().isEmpty())
            body.addProperty(MAIL_NICKNAME, updateUserInputs.getUserCommonInputs().getMailNickname());
        if (!updateUserInputs.getUpdatedUserPrincipalName().isEmpty())
            body.addProperty(USER_PRINCIPAL_NAME, updateUserInputs.getUpdatedUserPrincipalName());

        if (!updateUserInputs.getUserCommonInputs().getPassword().isEmpty()) {
            JsonObject passwordProfile = new JsonObject();

            if (!updateUserInputs.getUserCommonInputs().getForceChangePassword().isEmpty())
                passwordProfile.addProperty(FORCE_CHANGE_PASSWORD, updateUserInputs.getUserCommonInputs().getForceChangePassword());
            else
                passwordProfile.addProperty(FORCE_CHANGE_PASSWORD, Boolean.FALSE);

            passwordProfile.addProperty(PASSWORD, updateUserInputs.getUserCommonInputs().getPassword());
            body.add(PASSWORD_PROFILE, passwordProfile);
        }

        if (body.size() == 0) {
            result.put(RETURN_RESULT, EXCEPTION_NO_PROPERTIES_SET);
            result.put(STATUS_CODE, CODE_404);
            return result;
        }

        return httpPatch(updateUserInputs.getUserCommonInputs().getCommonInputs(), UPDATE_USERS_URL, body.toString());
    }

    @NotNull
    public static String getUpdateUserUrl(@NotNull final UpdateUserInputs updateUserInputs) {

        String UPDATE_USERS_URL = USERS_URL + FORWARD_SLASH;

        if (!(updateUserInputs.getUserCommonInputs().getCommonInputs().getUserId().isEmpty()))
            UPDATE_USERS_URL += updateUserInputs.getUserCommonInputs().getCommonInputs().getUserId().trim();
        else
        {
            try {
                UPDATE_USERS_URL += URLEncoder.encode(updateUserInputs.getUserCommonInputs().getCommonInputs().getUserPrincipalName().trim(), UTF_8);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }

        return UPDATE_USERS_URL;
    }
}