text:
package com.blazebit.persistence.testsuite;

import com.blazebit.persistence.CriteriaBuilder;
import com.blazebit.persistence.testsuite.base.jpa.category.NoDatanucleus;
import com.blazebit.persistence.testsuite.base.jpa.category.NoEclipselink;
import com.blazebit.persistence.testsuite.base.jpa.category.NoH2;
import com.blazebit.persistence.testsuite.base.jpa.category.NoHibernate42;
import com.blazebit.persistence.testsuite.base.jpa.category.NoHibernate43;
import com.blazebit.persistence.testsuite.base.jpa.category.NoHibernate50;
import com.blazebit.persistence.testsuite.base.jpa.category.NoHibernate51;
import com.blazebit.persistence.testsuite.base.jpa.category.NoMySQLOld;
import com.blazebit.persistence.testsuite.base.jpa.category.NoOpenJPA;
import com.blazebit.persistence.testsuite.base.jpa.category.NoOracle;
import com.blazebit.persistence.testsuite.entity.Document;
import com.blazebit.persistence.testsuite.entity.DocumentCTE;
import com.blazebit.persistence.testsuite.entity.IntIdEntity;
import com.blazebit.persistence.testsuite.entity.ParameterOrderCte;
import com.blazebit.persistence.testsuite.entity.ParameterOrderCteB;
import com.blazebit.persistence.testsuite.entity.ParameterOrderEntity;
import com.blazebit.persistence.testsuite.entity.Person;
import com.blazebit.persistence.testsuite.entity.RecursiveEntity;
import com.blazebit.persistence.testsuite.entity.TestAdvancedCTE1;
import com.blazebit.persistence.testsuite.entity.TestAdvancedCTE2;
import com.blazebit.persistence.testsuite.entity.TestCTE;
import com.blazebit.persistence.testsuite.entity.Version;
import com.blazebit.persistence.testsuite.entity.Workflow;
import com.blazebit.persistence.testsuite.tx.TxVoidWork;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import javax.persistence.EntityManager;
import java.util.Collections;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
 *
 * @author Christian Beikov
 * @author Jan-Willem Gmelig Meyling
 * @since 1.4.1
 */
public class InlineCTETest extends AbstractCoreTest {

    @Override
    protected Class<?>[] getEntityClasses() {
        return new Class<?>[] {
            Document.class,
            Version.class,
            Person.class,
            Workflow.class,
            IntIdEntity.class,
            DocumentCTE.class,
            RecursiveEntity.class,
            TestCTE.class,
            TestAdvancedCTE1.class,
            TestAdvancedCTE2.class,
            ParameterOrderCte.class,
            ParameterOrderCteB.class,
            ParameterOrderEntity.class
        };
    }

    @Override
    public void setUpOnce() {
        cleanDatabase();
        transactional(new TxVoidWork() {
            @Override
            public void work(EntityManager em) {
                RecursiveEntity root1 = new RecursiveEntity("root1");
                RecursiveEntity child1_1 = new RecursiveEntity("child1_1", root1);
                RecursiveEntity child1_2 = new RecursiveEntity("child1_2", root1);

                RecursiveEntity child1_1_1 = new RecursiveEntity("child1_1_1", child1_1);
                RecursiveEntity child1_2_1 = new RecursiveEntity("child1_2_1", child1_2);

                em.persist(root1);
                em.persist(child1_1);
                em.persist(child1_2);
                em.persist(child1_1_1);
                em.persist(child1_2_1);
                root1.getChildren2().add(child1_1);
                root1.getChildren2().add(child1_2);

                ParameterOrderEntity parameterOrderEntity = new ParameterOrderEntity();
                parameterOrderEntity.setOne((short) 1);
                parameterOrderEntity.setTwo(2);
                parameterOrderEntity.setThree(3L);
                em.persist(parameterOrderEntity);
            }
        });
    }

    // NOTE: Hibernate 4.2 and 4.3 interprets entity name tokens in string literals...
    // Prior to Hibernate 5.1 it wasn't possible reference other from clause elements in the ON clause which is required to support implicit joins in ON clauses
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoHibernate42.class, NoHibernate43.class, NoHibernate50.class, NoMySQLOld.class })
    public void testInliningFromSubqueryCte() {
        cbf.create(em, RecursiveEntity.class)
                .withRecursive(DocumentCTE.class)
                    .from(Document.class, "d")
                    .bind("id").select("d.id")
                    .bind("parent.id").select("d.parent.id")
                    .bind("root.id").select("d.id")
                    .where("d").eqExpression(":param_1")
                    .setParameter("param_1", em.getReference(Document.class, 1L))
                .unionAll()
                    .from(Document.class, "d")
                    .innerJoinOn(DocumentCTE.class, "parentDocument").on("parentDocument.id").eqExpression("d.parent.id").end()
                    .bind("id").select("d.id")
                    .bind("parent.id").select("d.parent.id")
                    .bind("root.id").select("parentDocument.root.id")
                .end()
                .select("document")
                .from(Document.class, "document")
                .where("document").in()
                    .fromSubquery(DocumentCTE.class, "de1")
                        .from(DocumentCTE.class, "d2")
                        .bind("id").select("d2.id")
                        .bind("parent.id").select("d2.parent.id")
                        .bind("root.id").select("d2.root.id")
                    .end()
                    .select("de1.document")
                .end()
                .getResultList();
    }

    // TODO: Oracle requires a cycle clause #295
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoMySQLOld.class, NoOracle.class })
    public void testReusedNestedCte() {
        CriteriaBuilder<ParameterOrderEntity> cteBuilder = cbf.create(em, ParameterOrderEntity.class)
                .withRecursive(TestCTE.class)
                    .from(RecursiveEntity.class, "re")
                    .bind("id").select("re.id")
                    .bind("name").select("re.name")
                    .bind("level").select("1")
                    .where("re.parent").isNull()
                .unionAll()
                    .from(RecursiveEntity.class, "re")
                    .innerJoinOn(TestCTE.class, "tcte").on("tcte.id").eqExpression("re.parent.id").end()
                    .bind("id").select("re.id")
                    .bind("name").select("re.name")
                    .bind("level").select("tcte.level + 1")
                .end()
                .with(TestAdvancedCTE1.class)
                    .from(TestCTE.class, "testcte")
                    .groupBy("id", "level", "name")
                    .bind("id").select("id")
                    .bind("level").select("level")
                    .bind("parentId").select("id")
                    .bind("embeddable.name").select("name")
                    .bind("embeddable.description").select("name")
                    .bind("embeddable.recursiveEntity.id").select("id")
                .end()
                .with(TestAdvancedCTE2.class)
                    .from(TestCTE.class, "testcte")
                    .where("id").in().from(TestAdvancedCTE1.class).select("id").end()
                    .where("id").in().from(TestCTE.class).select("id").end()
                    .groupBy("id", "name")
                    .bind("id").select("id")
                    .bind("embeddable.name").select("name")
                    .bind("embeddable.description").select("name")
                    .bind("embeddable.recursiveEntity.id").select("id")
                .end()
                .with(ParameterOrderEntity.class)
                    .from(TestAdvancedCTE1.class, "a")
                    .innerJoinOn(TestAdvancedCTE2.class, "b").on("a.id").eqExpression("b.id").end()
                    .bind("id").select("a.id")
                    .bind("one").select("1")
                    .bind("two").select("2")
                    .bind("three").select("a.id + b.id")
                .end();

        assertEquals(
                "WITH RECURSIVE TestCTE(id, name, level) AS(\n" +
                        "SELECT re.id, re.name, 1 FROM RecursiveEntity re WHERE re.parent IS NULL\n" +
                        "UNION ALL\n" +
                        "SELECT re.id, re.name, tcte.level + 1 FROM RecursiveEntity re JOIN TestCTE tcte" + onClause("tcte.id = re.parent.id") + "\n" +
                        ")\n" +
                        "SELECT parameterOrderEntity " +
                        "FROM ParameterOrderEntity(" +
                            "SELECT a.id, 1, 2, a.id + b.id " +
                            "FROM TestAdvancedCTE1(" +
                                "SELECT testcte.id, testcte.level, testcte.id, testcte.name, testcte.name, testcte.id " +
                                "FROM TestCTE testcte GROUP BY testcte.id, testcte.level, testcte.name" +
                            ") a(id, level, parentId, embeddable.name, embeddable.description, embeddable.recursiveEntity.id) " +
                            "JOIN TestAdvancedCTE2(" +
                                "SELECT testcte.id, testcte.name, testcte.name, testcte.id " +
                                "FROM TestCTE testcte " +
                                "WHERE testcte.id IN (" +
                                    "SELECT testAdvancedCTE1.id " +
                                    "FROM TestAdvancedCTE1(" +
                                        "SELECT testcte.id, testcte.level, testcte.id, testcte.name, testcte.name, testcte.id " +
                                        "FROM TestCTE testcte " +
                                        "GROUP BY testcte.id, testcte.level, testcte.name" +
                                    ") testAdvancedCTE1(id, level, parentId, embeddable.name, embeddable.description, embeddable.recursiveEntity.id)" +
                                ") " +
                                "AND testcte.id IN (" +
                                    "SELECT testCTE.id FROM TestCTE testCTE" +
                                ") " +
                                "GROUP BY testcte.id, testcte.name" +
                            ") b(id, embeddable.name, embeddable.description, embeddable.recursiveEntity.id)" + onClause("a.id = b.id") +
                        ") parameterOrderEntity(id, one, two, three)",
                cteBuilder.getQueryString()
        );
        cteBuilder.getResultList();
    }

    // TODO: Oracle requires a cycle clause #295
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoMySQLOld.class, NoOracle.class })
    public void testReusedNestedCte2() {
        CriteriaBuilder<ParameterOrderCte> cteBuilder = cbf.create(em, ParameterOrderCte.class)
                .withRecursive(TestCTE.class)
                    .from(RecursiveEntity.class, "re")
                    .bind("id").select("re.id")
                    .bind("name").select("re.name")
                    .bind("level").select("1")
                    .where("re.parent").isNull()
                .unionAll()
                    .from(RecursiveEntity.class, "re")
                    .innerJoinOn(TestCTE.class, "tcte").on("tcte.id").eqExpression("re.parent.id").end()
                    .bind("id").select("re.id")
                    .bind("name").select("re.name")
                    .bind("level").select("tcte.level + 1")
                .end()
                .with(TestAdvancedCTE1.class)
                    .from(TestCTE.class, "testcte")
                    .groupBy("id", "level", "name")
                    .bind("id").select("id")
                    .bind("level").select("level")
                    .bind("parentId").select("id")
                    .bind("embeddable.name").select("name")
                    .bind("embeddable.description").select("name")
                    .bind("embeddable.recursiveEntity.id").select("id")
                .end()
                .with(TestAdvancedCTE2.class)
                    .from(TestCTE.class, "testcte")
                    .where("id").in().from(TestAdvancedCTE1.class).select("id").end()
                    .where("id").in().from(TestCTE.class).select("id").end()
                    .groupBy("id", "name")
                    .bind("id").select("id")
                    .bind("embeddable.name").select("name")
                    .bind("embeddable.description").select("name")
                    .bind("embeddable.recursiveEntity.id").select("id")
                .end()
                .with(ParameterOrderEntity.class)
                    .from(TestAdvancedCTE1.class, "a")
                    .innerJoinOn(TestAdvancedCTE2.class, "b").on("a.id").eqExpression("b.id").end()
                    .bind("id").select("a.id")
                    .bind("one").select("1")
                    .bind("two").select("2")
                    .bind("three").select("a.id + b.id")
                .end()
                .with(ParameterOrderCte.class)
                    .from(ParameterOrderEntity.class)
                    .bind("four").select("one")
                    .bind("five").select("two")
                    .bind("six").select("three")
                    .end()
                ;

        cteBuilder.getResultList();
    }

    // NOTE: Hibernate 4.2 and 4.3 interprets entity name tokens in string literals...
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoHibernate42.class, NoHibernate43.class })
    public void testParameterBindingOrder() {
        CriteriaBuilder<ParameterOrderEntity> cteBuilder = cbf.create(em, ParameterOrderEntity.class)
                .with(ParameterOrderCte.class)
                .from(ParameterOrderEntity.class, "poe")
                .where("poe.one").eq((short) 1)
                .where("poe.two").eq(2)
                .where("poe.three").eq(3L)
                .bind("four").select("poe.one")
                .bind("five").select("poe.two")
                .bind("six").select("poe.three")
                .end();

        List<ParameterOrderEntity> resultList = cbf.create(em, ParameterOrderEntity.class)
                .withCtesFrom(cteBuilder)
                .from(ParameterOrderEntity.class, "poe2")
                .where("poe2.three").eq(3L)
                .where("poe2.two").eq(2)
                .where("poe2.one").eq((short) 1)
                .where("poe2.two").notIn(1, 3, 4)
                .where("poe2.one").in().from(ParameterOrderCte.class, "poc").select("poc.four").end()
                .getResultList();

        Assert.assertEquals(1, resultList.size());
    }

    // NOTE: Hibernate 4.2 and 4.3 interprets entity name tokens in string literals...
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoHibernate42.class, NoHibernate43.class })
    public void testParameterBindingOrderPaginated() {
        CriteriaBuilder<ParameterOrderEntity> cteBuilder = cbf.create(em, ParameterOrderEntity.class)
                .with(ParameterOrderCte.class)
                .from(ParameterOrderEntity.class, "poe")
                .where("poe.one").eq((short) 1)
                .where("poe.two").eq(2)
                .where("poe.three").eq(3L)
                .bind("four").select("poe.one")
                .bind("five").select("poe.two")
                .bind("six").select("poe.three")
                .end();

        List<ParameterOrderCte> resultList = cbf.create(em, ParameterOrderCte.class)
                .withCtesFrom(cteBuilder)
                .from(ParameterOrderCte.class, "poc2")
                .where("poc2.six").eq(3L)
                .where("poc2.five").eq(2)
                .where("poc2.four").eq((short) 1)
                .where("poc2.five").notIn(1, 3, 4)
                .orderByAsc("poc2.four")
                .page(0, 10)
                .getResultList();

        Assert.assertEquals(1, resultList.size());
    }

    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class })
    public void testParameterBindingOrderNested() {
        CriteriaBuilder<ParameterOrderEntity> cteBuilder = cbf.create(em, ParameterOrderEntity.class)
                .with(ParameterOrderCte.class)
                    .from(ParameterOrderEntity.class, "poe")
                    .where("poe.one").eq((short) 1)
                    .where("poe.two").eq(2)
                    .where("poe.three").eq(3L)
                    .bind("four").select("poe.one")
                    .bind("five").select("poe.two")
                    .bind("six").select("poe.three")
                .end()
                .with(ParameterOrderCteB.class)
                    .from(ParameterOrderCte.class, "poc2")
                    .where("poc2.six").eq(3L)
                    .where("poc2.five").eq(2)
                    .where("poc2.four").eq((short) 1)
                    .where("poc2.five").notIn(1, 3, 4)
                    .bind("seven").select("poc2.four")
                    .bind("eight").select("poc2.five")
                    .bind("nine").select("poc2.six")
                .end();

        List<ParameterOrderCteB> resultList = cbf.create(em, ParameterOrderCteB.class)
                .withCtesFrom(cteBuilder)
                .from(ParameterOrderCteB.class, "poc3")
                .getResultList();

        Assert.assertEquals(1, resultList.size());
    }

    // NOTE: Hibernate 4.2 and 4.3 interprets entity name tokens in string literals...
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoHibernate42.class, NoHibernate43.class })
    public void testParameterBindingOrderNestedPaginated() {
        CriteriaBuilder<ParameterOrderEntity> cteBuilder = cbf.create(em, ParameterOrderEntity.class)
                .with(ParameterOrderCte.class)
                    .from(ParameterOrderEntity.class, "poe")
                    .where("poe.one").eq((short) 1)
                    .where("poe.two").eq(2)
                    .where("poe.three").eq(3L)
                    .bind("four").select("poe.one")
                    .bind("five").select("poe.two")
                    .bind("six").select("poe.three")
                .end()
                .with(ParameterOrderCteB.class)
                    .from(ParameterOrderCte.class, "poc2")
                    .where("poc2.six").eq(3L)
                    .where("poc2.five").eq(2)
                    .where("poc2.four").eq((short) 1)
                    .where("poc2.five").notIn(1, 3, 4)
                    .bind("seven").select("poc2.four")
                    .bind("eight").select("poc2.five")
                    .bind("nine").select("poc2.six")
                .end();

        List<ParameterOrderCteB> resultList = cbf.create(em, ParameterOrderCteB.class)
                .withCtesFrom(cteBuilder)
                .from(ParameterOrderCteB.class, "poc3")
                .orderByAsc("poc3.seven")
                .orderByAsc("poc3.eight")
                .orderByAsc("poc3.nine")
                .page(0, 10)
                .getResultList();

        Assert.assertEquals(1, resultList.size());
    }

    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class })
    public void testInlineCTE() {
        CriteriaBuilder<TestCTE> cb = cbf.create(em, TestCTE.class, "t").where("t.level").ltExpression("2");
        cb.with(TestCTE.class, true)
            .from(RecursiveEntity.class, "e")
            .bind("id").select("e.id")
            .bind("name").select("e.name")
            .bind("level").select("0")
            .where("e.parent").isNull()
        .end();
        String subquery = "SELECT e.id, e.name, 0 FROM RecursiveEntity e WHERE e.parent IS NULL";
        String expected = ""
                + "SELECT t FROM TestCTE(" + subquery + ") t(id, name, level) WHERE t.level < 2";

        assertEquals(expected, cb.getQueryString());
        List<TestCTE> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
        assertEquals("root1", resultList.get(0).getName());
    }

    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class })
    public void testInlineCTENullExpression() {
        CriteriaBuilder<TestCTE> cb = cbf.create(em, TestCTE.class, "t").where("t.level").ltExpression("2");
        cb.with(TestCTE.class, true)
                .from(RecursiveEntity.class, "e")
                .bind("id").select("e.id")
                .bind("name").select("e.name")
                .bind("level").select("null")
                .where("e.parent").isNull()
                .end();
        String subquery = "SELECT e.id, e.name, NULL FROM RecursiveEntity e WHERE e.parent IS NULL";
        String expected = ""
                + "SELECT t FROM TestCTE(" + subquery + ") t(id, name, level) WHERE t.level < 2";

        assertEquals(expected, cb.getQueryString());
        List<TestCTE> resultList = cb.getResultList();
        assertEquals(0, resultList.size());
    }

    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class })
    public void testInlineCTEWithParam() {
        CriteriaBuilder<TestCTE> cb = cbf.create(em, TestCTE.class, "t").where("t.level").ltExpression("2");
        cb.with(TestCTE.class, true)
                .from(RecursiveEntity.class, "e")
                .bind("id").select("e.id")
                .bind("name").select("e.name")
                .bind("level").select("0")
                .where("e.parent.name").eq("root1")
                .end();
        String subquery = "SELECT e.id, e.name, 0 FROM RecursiveEntity e LEFT JOIN e.parent parent_1 WHERE parent_1.name = :param_0";
        String expected = ""
                + "SELECT t FROM TestCTE(" + subquery + ") t(id, name, level) WHERE t.level < 2";

        assertEquals(expected, cb.getQueryString());
        List<TestCTE> resultList = cb.getResultList();
        assertEquals(2, resultList.size());
    }

    // NOTE: Hibernate 4.2 and 4.3 interprets entity name tokens in string literals...
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoHibernate42.class, NoHibernate43.class })
    public void testInlineCTEInCorrelatedSubquery() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class, "r")
                .whereExists()
                    .from(TestCTE.class, "t")
                    .where("t.id").eqExpression("r.id")
                .end();
        cb.with(TestCTE.class, true)
                .from(RecursiveEntity.class, "e")
                .bind("id").select("e.id")
                .bind("name").select("e.name")
                .bind("level").select("0")
                .where("e.parent.name").eq("root1")
                .end();
        String subquery = "SELECT e.id, e.name, 0 FROM RecursiveEntity e LEFT JOIN e.parent parent_1 WHERE parent_1.name = :param_0";
        String expected = ""
                + "SELECT r FROM RecursiveEntity r WHERE EXISTS (SELECT 1 FROM TestCTE(" + subquery + ") t(id, name, level) WHERE t.id = r.id)";

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(2, resultList.size());
    }

    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class })
    public void testInlineEntityWithLimit() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class)
                .fromEntitySubquery(RecursiveEntity.class, "t")
                    .where("t.parent.name").eq("root1")
                    .orderByAsc("name")
                    .setMaxResults(1)
                .end();
        String subquery = "SELECT t.id, t.name, t.parent.id FROM RecursiveEntity t LEFT JOIN t.parent parent_1 WHERE parent_1.name = :param_0 ORDER BY t.name ASC LIMIT 1";
        String expected = ""
                + "SELECT t FROM RecursiveEntity(" + subquery + ") t(id, name, parent.id)";

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
    }

    // Test for #1285
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class })
    public void testJoinOnSubquery() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class)
                .from(RecursiveEntity.class, "t")
                .innerJoinOnSubquery(TestCTE.class, "cte")
                    .from(RecursiveEntity.class, "sub")
                    .bind("id").select("MAX(sub.id)", "id_")
                    .bind("name").select("'abc'", "name_")
                    .bind("level").select("1", "level_")
                    .where("sub.id").gtLiteral(0)
                .end().setOnExpression("t.id = cte.id")
                .where("t.id").gtLiteral(0);
        String expected = ""
                + "SELECT t FROM RecursiveEntity t JOIN TestCTE(" +
                "SELECT MAX(sub.id) AS id_, 'abc' AS name_, 1 AS level_ FROM RecursiveEntity sub WHERE sub.id > 0" +
                ") cte(id, name, level)" + onClause("t.id = cte.id") +
                " WHERE t.id > 0";

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
    }

    // NOTE: Entity joins are only supported on Hibernate 5.1+
    // NOTE: Hibernate 5.1 renders t.id = tSub.id rather than t = tSub
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoHibernate42.class, NoHibernate43.class, NoHibernate50.class, NoHibernate51.class})
    public void testMultipleInlineEntityWithLimitJoin() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class)
                .fromEntitySubquery(RecursiveEntity.class, "t")
                    .leftJoinOnEntitySubquery(RecursiveEntity.class, "subT")
                        .where("subT.parent.name").eq("root1")
                        .orderByAsc("name")
                        .setMaxResults(1)
                    .end().setOnExpression("t = subT")
                    .where("t.parent.name").eq("root1")
                    .orderByAsc("name")
                    .setMaxResults(1)
                .end()
                .leftJoinOnEntitySubquery(RecursiveEntity.class, "subT2")
                    .where("subT2.parent.name").eq("root1")
                    .orderByAsc("name")
                    .setMaxResults(1)
                .end().setOnExpression("t = subT2");
        String subquery = "SELECT t.id, t.name, t.parent.id FROM RecursiveEntity t LEFT JOIN t.parent parent_1 " +
                "LEFT JOIN RecursiveEntity(" +
                "SELECT subT.id, subT.name, subT.parent.id FROM RecursiveEntity subT LEFT JOIN subT.parent parent_1 WHERE parent_1.name = :param_0 ORDER BY subT.name ASC LIMIT 1" +
                ") subT(id, name, parent.id) ON (t = subT) WHERE parent_1.name = :param_1 ORDER BY t.name ASC LIMIT 1";
        String expected = ""
                + "SELECT t FROM RecursiveEntity(" + subquery + ") t(id, name, parent.id) LEFT JOIN RecursiveEntity(" +
                "SELECT subT2.id, subT2.name, subT2.parent.id FROM RecursiveEntity subT2 LEFT JOIN subT2.parent parent_1 WHERE parent_1.name = :param_2 ORDER BY subT2.name ASC LIMIT 1" +
                ") subT2(id, name, parent.id) ON (t = subT2)";

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
    }

    // NOTE: Entity joins are only supported on Hibernate 5.1+
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoHibernate42.class, NoHibernate43.class, NoHibernate50.class })
    public void testJoinInlineEntityWithLimit() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class)
                .fromValues(RecursiveEntity.class, "name", "val", Collections.singletonList("child1_1"))
                .leftJoinOnEntitySubquery(RecursiveEntity.class, "t")
                    .where("t.parent.name").eq("root1")
                    .orderByAsc("name")
                    .setMaxResults(1)
                .end()
                    .on("val").eqExpression("t.name")
                .end()
                .select("t");
        String subquery = "SELECT t.id, t.name, t.parent.id FROM RecursiveEntity t LEFT JOIN t.parent parent_1 WHERE parent_1.name = :param_0 ORDER BY t.name ASC LIMIT 1";
        String expected = ""
                + "SELECT t FROM String(1 VALUES LIKE RecursiveEntity.name) val LEFT JOIN RecursiveEntity(" + subquery + ") t(id, name, parent.id)" + onClause("val = t.name");

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
    }

    // NOTE: H2 and old MySQL do not support lateral joins
    // NOTE: Entity joins are only supported on Hibernate 5.1+
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoH2.class, NoMySQLOld.class, NoHibernate42.class, NoHibernate43.class, NoHibernate50.class })
    public void testJoinLateralEntityWithLimit() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class)
                .fromValues(RecursiveEntity.class, "name", "val", Collections.singletonList("child1_1"))
                .leftJoinLateralOnEntitySubquery(RecursiveEntity.class, "t", "r")
                    .where("r.parent.name").eq("root1")
                    .where("val").eqExpression("r.name")
                    .orderByAsc("name")
                    .setMaxResults(1)
                .end()
                    .on("1").eqExpression("1")
                .end()
                .select("t");
        String subquery = "SELECT r.id, r.name, r.parent.id FROM RecursiveEntity r LEFT JOIN r.parent parent_1 WHERE parent_1.name = :param_0 AND val = r.name ORDER BY r.name ASC LIMIT 1";
        String expected = ""
                + "SELECT t FROM String(1 VALUES LIKE RecursiveEntity.name) val LEFT JOIN LATERAL RecursiveEntity(" + subquery + ") t(id, name, parent.id)" + onClause("1 = 1");

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
    }

    // NOTE: H2 and old MySQL do not support lateral joins
    // NOTE: Entity joins are only supported on Hibernate 5.1+
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoH2.class, NoMySQLOld.class, NoHibernate42.class, NoHibernate43.class, NoHibernate50.class })
    public void testJoinLateralCorrelationEntityWithLimit() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class)
                .from(RecursiveEntity.class, "x")
                .where("x.name").eq("root1")
                .leftJoinLateralOnEntitySubquery("x.children", "t", "r")
                    .orderByAsc("name")
                    .setMaxResults(1)
                .end()
                    .on("1").eqExpression("1")
                .end()
                .select("t");
        String expectedSubquery = "SELECT r.id, r.name, r.parent.id FROM RecursiveEntity r WHERE r.parent.id = x.id ORDER BY r.name ASC LIMIT 1";
        String expected = ""
                + "SELECT t FROM RecursiveEntity x LEFT JOIN LATERAL RecursiveEntity(" + expectedSubquery + ") t(id, name, parent.id)" + onClause("1 = 1") + " WHERE x.name = :param_0";

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
    }

    // NOTE: H2 and old MySQL do not support lateral joins
    // NOTE: Entity joins are only supported on Hibernate 5.1+
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoH2.class, NoMySQLOld.class, NoHibernate42.class, NoHibernate43.class, NoHibernate50.class })
    public void testJoinLateralCorrelationEntityJoinTableWithLimit() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class)
                .from(RecursiveEntity.class, "x")
                .where("x.name").eq("root1")
                .leftJoinLateralOnEntitySubquery("x.children2", "t", "r")
                    .orderByAsc("name")
                    .setMaxResults(1)
                .end()
                    .on("1").eqExpression("1")
                .end()
                .select("t");
        String expectedSubquery = "SELECT r.id, r.name, r.parent.id FROM x.children2 r ORDER BY r.name ASC LIMIT 1";
        String expected = ""
                + "SELECT t FROM RecursiveEntity x LEFT JOIN LATERAL RecursiveEntity(" + expectedSubquery + ") t(id, name, parent.id)" + onClause("1 = 1") + " WHERE x.name = :param_0";

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
    }

    // Test for #1193
    // NOTE: H2 and old MySQL do not support lateral joins
    // NOTE: Entity joins are only supported on Hibernate 5.1+
    @Test
    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoH2.class, NoMySQLOld.class, NoHibernate42.class, NoHibernate43.class, NoHibernate50.class })
    public void testJoinLateralWithArrayExpressionImplicitJoin() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class)
                .from(RecursiveEntity.class, "x")
                .leftJoinLateralEntitySubquery("RecursiveEntity[name = x.parent.name]", "t", "r").end()
                .where("x.name").eq("root1")
                .select("t");
        String expectedSubquery = "SELECT r.id, r.name, r.parent.id FROM RecursiveEntity r, RecursiveEntity x_parent_base LEFT JOIN x_parent_base.parent parent_1 WHERE r.name = parent_1.name AND x.id = x_parent_base.id";
        String expected = ""
                + "SELECT t FROM RecursiveEntity x LEFT JOIN LATERAL RecursiveEntity(" + expectedSubquery + ") t(id, name, parent.id)" + onClause("1 = 1") + " WHERE x.name = :param_0";

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
    }

    // Additional test for #1193
    // NOTE: H2 and old MySQL do not support lateral joins
    // NOTE: Entity joins are only supported on Hibernate 5.1+
    @Test
//    @Category({ NoDatanucleus.class, NoEclipselink.class, NoOpenJPA.class, NoH2.class, NoMySQLOld.class, NoHibernate42.class, NoHibernate43.class, NoHibernate50.class })
    // NOTE: This requires joins to be ordered correctly which is only fixed in Hibernate 5.4.22+. Also see https://hibernate.atlassian.net/browse/HHH-14201
    @Ignore
    public void testJoinLateralWithElementArrayExpressionImplicitJoin() {
        CriteriaBuilder<RecursiveEntity> cb = cbf.create(em, RecursiveEntity.class)
                .from(RecursiveEntity.class, "x")
                .leftJoinLateralEntitySubquery("x.children[name = x.parent.name]", "t", "r").end()
                .where("x.name").eq("root1")
                .select("t");
        String expectedSubquery = "SELECT r.id, r.name, r.parent.id FROM RecursiveEntity x_children_base, RecursiveEntity x_parent_base LEFT JOIN x_parent_base.parent parent_1 JOIN x_children_base.children r ON (r.name = parent_1.name) WHERE x.id = x_children_base.id AND x.id = x_parent_base.id";
        String expected = ""
                + "SELECT t FROM RecursiveEntity x LEFT JOIN LATERAL RecursiveEntity(" + expectedSubquery + ") t(id, name, parent.id)" + onClause("1 = 1") + " WHERE x.name = :param_0";

        assertEquals(expected, cb.getQueryString());
        List<RecursiveEntity> resultList = cb.getResultList();
        assertEquals(1, resultList.size());
    }
}


text:
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from config import SQLALCHEMY_DATABASE_URI
from run import app
from app.users.models import db

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()

redpajama_set_name: RedPajamaGithub


text:
namespace Byndyusoft.Dotnet.Core.Samples.Web.DataAccess.Values.Commands
{
    using System;
    using Domain.CommandsContexts.Values;
    using Infrastructure.CQRS.Abstractions.Commands;
    using JetBrains.Annotations;
    using Repository;

    [UsedImplicitly]
    public class SetValueCommand : ICommand<SetValueCommandContext>
    {
        private readonly IValuesRepository _repository;

        public SetValueCommand(IValuesRepository repository)
        {
            if(repository == null)
                throw new ArgumentNullException();

            _repository = repository;
        }

        public void Execute(SetValueCommandContext commandContext)
        {
            _repository.Set(commandContext.Id, commandContext.Value);
        }
    }
}


text:
package org.wso2.msf4j.internal.router.beanconversion;

import org.junit.Assert;
import org.junit.Test;
import org.wso2.msf4j.internal.router.Category;
import org.wso2.msf4j.internal.router.Pet;
import org.wso2.msf4j.internal.router.XmlBean;

/**
 * Tests the functionality of BeanConverter.
 */
public class BeanConverterTest {

    @Test(expected = BeanConversionException.class)
    public void testUnsupportedMediaType() throws BeanConversionException {
        Object obj = BeanConverter.instance("unsupported/unsupported");
    }

    @Test
    public void testJsonBeanConversionTextJson() throws BeanConversionException {
        Pet pet = makePet();
        Object json = BeanConverter.instance("text/json").toMedia(pet);
        Assert.assertTrue(json instanceof String);
        Pet pet1 = (Pet) BeanConverter.instance("text/json").toObject((String) json, Pet.class);
        Assert.assertTrue(pet1 instanceof Pet);
        Assert.assertEquals(pet.getId(), pet1.getId());
        Assert.assertEquals(pet.getDetails(), pet1.getDetails());
        Assert.assertEquals(pet.getImage(), pet1.getImage());
        Assert.assertEquals(pet.getCategory().getName(), pet1.getCategory().getName());
        Assert.assertEquals(pet.getAgeMonths(), pet1.getAgeMonths());
        Assert.assertEquals(pet.getPrice(), pet1.getPrice(), 0);
        Assert.assertEquals(pet.getDateAdded(), pet1.getDateAdded());
    }

    @Test
    public void testJsonBeanConversionApplicationJson() throws BeanConversionException {
        Pet pet = makePet();
        Object json = BeanConverter.instance("application/json").toMedia(pet);
        Assert.assertTrue(json instanceof String);
        Pet pet1 = (Pet) BeanConverter.instance("application/json").toObject((String) json, Pet.class);
        Assert.assertTrue(pet1 instanceof Pet);
        Assert.assertEquals(pet.getId(), pet1.getId());
        Assert.assertEquals(pet.getDetails(), pet1.getDetails());
        Assert.assertEquals(pet.getImage(), pet1.getImage());
        Assert.assertEquals(pet.getCategory().getName(), pet1.getCategory().getName());
        Assert.assertEquals(pet.getAgeMonths(), pet1.getAgeMonths());
        Assert.assertEquals(pet.getPrice(), pet1.getPrice(), 0);
        Assert.assertEquals(pet.getDateAdded(), pet1.getDateAdded());
    }

    @Test
    public void testTextPlainBeanConversion() throws BeanConversionException {
        String val = "Test_String";
        Object media = BeanConverter.instance("text/plain").toMedia(val);
        Assert.assertTrue(media instanceof String);
        Object obj1 = BeanConverter.instance("text/plain").toObject((String) media, null);
        Assert.assertEquals(obj1, val);
    }

    @Test
    public void testAnyBeanConversion() throws BeanConversionException {
        String val = "Test_String";
        Object media = BeanConverter.instance("*/*").toMedia(val);
        Assert.assertTrue(media instanceof String);
        Object obj1 = BeanConverter.instance("*/*").toObject((String) media, null);
        Assert.assertEquals(obj1, val);
    }

    @Test
    public void testXmlBeanConversion() throws BeanConversionException {
        XmlBean xmlBean = makeXmlBan();
        Object xml = BeanConverter.instance("text/xml").toMedia(xmlBean);
        Assert.assertTrue(xml instanceof String);
        XmlBean xmlBean1 = (XmlBean) BeanConverter.instance("text/xml").toObject((String) xml, XmlBean.class);
        Assert.assertTrue(xmlBean1 instanceof XmlBean);
        Assert.assertEquals(xmlBean.getName(), xmlBean1.getName());
        Assert.assertEquals(xmlBean.getId(), xmlBean1.getId());
        Assert.assertEquals(xmlBean.getValue(), xmlBean1.getValue());
    }

    private XmlBean makeXmlBan() {
        XmlBean xmlBean = new XmlBean();
        xmlBean.setId(12);
        xmlBean.setName("xml-bean-name");
        xmlBean.setValue(457);
        return xmlBean;
    }

    private Pet makePet() {
        Pet pet = new Pet();
        pet.setCategory(new Category("dog"));
        pet.setAgeMonths(3);
        pet.setDetails("small-cat");
        pet.setPrice(10.5f);
        pet.setImage("cat.png");
        return pet;
    }

}


text:
import React, {Component} from 'react'
import { FormGroup, ControlLabel, FormControl } from 'react-bootstrap'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'

import { inputChange } from '../actions'

class Input extends Component {
  inputChange = (e) => {
    const { inputChange, title, name } = this.props
    inputChange(title, name, e.target.value)
  }

  render () {
    return (
      <div>
        <FormGroup controlId='formBasicText'>
          <ControlLabel>{this.props.controlLabel}</ControlLabel>
          <FormControl
            disabled={this.props.disabled}
            type={this.props.type || 'Text'}
            placeholder={this.props.controlLabel}
            onChange={this.inputChange}
            value={this.props.val}
          />
        </FormGroup>
      </div>
    )
  }
}

const mapDispatchToProps = dispatch => {
  return {
    inputChange: bindActionCreators(inputChange, dispatch)
  }
}

export default connect(null, mapDispatchToProps)(Input)


text:
import errno
import threading
import time
import random
import shared
import select
import socks
import socket
import sys
import tr

from class_sendDataThread import *
from class_receiveDataThread import *
from bmconfigparser import BMConfigParser
from helper_threading import *
import knownnodes
import queues
import state

# For each stream to which we connect, several outgoingSynSender threads
# will exist and will collectively create 8 connections with peers.

class outgoingSynSender(threading.Thread, StoppableThread):

    def __init__(self):
        threading.Thread.__init__(self, name="outgoingSynSender")
        self.initStop()
        random.seed()

    def setup(self, streamNumber, selfInitiatedConnections):
        self.streamNumber = streamNumber
        self.selfInitiatedConnections = selfInitiatedConnections

    def _getPeer(self):
        # If the user has specified a trusted peer then we'll only
        # ever connect to that. Otherwise we'll pick a random one from
        # the known nodes
        if state.trustedPeer:
            with knownnodes.knownNodesLock:
                peer = state.trustedPeer
                knownnodes.knownNodes[self.streamNumber][peer] = time.time()
        else:
            while not self._stopped:
                try:
                    with knownnodes.knownNodesLock:
                        peer, = random.sample(knownnodes.knownNodes[self.streamNumber], 1)
                        priority = (183600 - (time.time() - knownnodes.knownNodes[self.streamNumber][peer])) / 183600 # 2 days and 3 hours
                except ValueError: # no known nodes
                    self.stop.wait(1)
                    continue
                if BMConfigParser().get('bitmessagesettings', 'socksproxytype') != 'none':
                    if peer.host.find(".onion") == -1:
                        priority /= 10 # hidden services have 10x priority over plain net
                    else:
                        # don't connect to self
                        if peer.host == BMConfigParser().get('bitmessagesettings', 'onionhostname') and peer.port == BMConfigParser().getint("bitmessagesettings", "onionport"):
                            continue
                elif peer.host.find(".onion") != -1: # onion address and so proxy
                    continue
                if priority <= 0.001: # everyone has at least this much priority
                    priority = 0.001
                if (random.random() <=  priority):
                    break
                self.stop.wait(0.01) # prevent CPU hogging if something is broken
        try:
            return peer
        except NameError:
            return state.Peer('127.0.0.1', 8444)

    def stopThread(self):
        super(outgoingSynSender, self).stopThread()
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
        except:
            pass

    def run(self):
        while BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect') and not self._stopped:
            self.stop.wait(2)
        while BMConfigParser().safeGetBoolean('bitmessagesettings', 'sendoutgoingconnections') and not self._stopped:
            self.name = "outgoingSynSender"
            maximumConnections = 1 if state.trustedPeer else BMConfigParser().safeGetInt('bitmessagesettings', 'maxoutboundconnections')
            while len(self.selfInitiatedConnections[self.streamNumber]) >= maximumConnections and not self._stopped:
                self.stop.wait(10)
            if state.shutdown:
                break
            peer = self._getPeer()
            while peer in shared.alreadyAttemptedConnectionsList or peer.host in shared.connectedHostsList:
                # print 'choosing new sample'
                peer = self._getPeer()
                self.stop.wait(1)
                if self._stopped:
                    break
                # Clear out the shared.alreadyAttemptedConnectionsList every half
                # hour so that this program will again attempt a connection
                # to any nodes, even ones it has already tried.
                with shared.alreadyAttemptedConnectionsListLock:
                    if (time.time() - shared.alreadyAttemptedConnectionsListResetTime) > 1800:
                        shared.alreadyAttemptedConnectionsList.clear()
                        shared.alreadyAttemptedConnectionsListResetTime = int(
                            time.time())
            shared.alreadyAttemptedConnectionsList[peer] = 0
            if self._stopped:
                break
            self.name = "outgoingSynSender-" + peer.host.replace(":", ".") # log parser field separator
            address_family = socket.AF_INET
            # Proxy IP is IPv6. Unlikely but possible
            if BMConfigParser().get('bitmessagesettings', 'socksproxytype') != 'none':
                if ":" in BMConfigParser().get('bitmessagesettings', 'sockshostname'):
                    address_family = socket.AF_INET6
            # No proxy, and destination is IPv6
            elif peer.host.find(':') >= 0 :
                address_family = socket.AF_INET6
            try:
                self.sock = socks.socksocket(address_family, socket.SOCK_STREAM)
            except:
                """
                The line can fail on Windows systems which aren't
                64-bit compatiable:
                      File "C:\Python27\lib\socket.py", line 187, in __init__
                        _sock = _realsocket(family, type, proto)
                      error: [Errno 10047] An address incompatible with the requested protocol was used

                So let us remove the offending address from our knownNodes file.
                """
                with knownnodes.knownNodesLock:
                    try:
                        del knownnodes.knownNodes[self.streamNumber][peer]
                    except KeyError:
                        pass
                logger.debug('deleting ' + str(peer) + ' from knownnodes.knownNodes because it caused a socks.socksocket exception. We must not be 64-bit compatible.')
                continue
            # This option apparently avoids the TIME_WAIT state so that we
            # can rebind faster
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.sock.settimeout(20)
            if BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' and shared.verbose >= 2:
                logger.debug('Trying an outgoing connection to ' + str(peer))

                # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            elif BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'SOCKS4a':
                if shared.verbose >= 2:
                    logger.debug ('(Using SOCKS4a) Trying an outgoing connection to ' + str(peer))

                proxytype = socks.PROXY_TYPE_SOCKS4
                sockshostname = BMConfigParser().get(
                    'bitmessagesettings', 'sockshostname')
                socksport = BMConfigParser().getint(
                    'bitmessagesettings', 'socksport')
                rdns = True  # Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
                if BMConfigParser().getboolean('bitmessagesettings', 'socksauthentication'):
                    socksusername = BMConfigParser().get(
                        'bitmessagesettings', 'socksusername')
                    sockspassword = BMConfigParser().get(
                        'bitmessagesettings', 'sockspassword')
                    self.sock.setproxy(
                        proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
                else:
                    self.sock.setproxy(
                        proxytype, sockshostname, socksport, rdns)
            elif BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
                if shared.verbose >= 2:
                    logger.debug ('(Using SOCKS5) Trying an outgoing connection to ' + str(peer))

                proxytype = socks.PROXY_TYPE_SOCKS5
                sockshostname = BMConfigParser().get(
                    'bitmessagesettings', 'sockshostname')
                socksport = BMConfigParser().getint(
                    'bitmessagesettings', 'socksport')
                rdns = True  # Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
                if BMConfigParser().getboolean('bitmessagesettings', 'socksauthentication'):
                    socksusername = BMConfigParser().get(
                        'bitmessagesettings', 'socksusername')
                    sockspassword = BMConfigParser().get(
                        'bitmessagesettings', 'sockspassword')
                    self.sock.setproxy(
                        proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
                else:
                    self.sock.setproxy(
                        proxytype, sockshostname, socksport, rdns)

            try:
                self.sock.connect((peer.host, peer.port))
                if self._stopped:
                    self.sock.shutdown(socket.SHUT_RDWR)
                    self.sock.close()
                    return
                sendDataThreadQueue = Queue.Queue() # Used to submit information to the send data thread for this connection.

                sd = sendDataThread(sendDataThreadQueue)
                sd.setup(self.sock, peer.host, peer.port, self.streamNumber)
                sd.start()

                rd = receiveDataThread()
                rd.daemon = True  # close the main program even if there are threads left
                rd.setup(self.sock,
                         peer.host,
                         peer.port,
                         self.streamNumber,
                         self.selfInitiatedConnections,
                         sendDataThreadQueue,
                         sd.objectHashHolderInstance)
                rd.start()

                sd.sendVersionMessage()

                logger.debug(str(self) + ' connected to ' + str(peer) + ' during an outgoing attempt.')
            except socks.GeneralProxyError as err:
                if err[0][0] in [7, 8, 9]:
                    logger.error('Error communicating with proxy: %s', str(err))
                    queues.UISignalQueue.put((
                        'updateStatusBar',
                        tr._translate(
                            "MainWindow", "Problem communicating with proxy: %1. Please check your network settings.").arg(str(err[0][1]))
                        ))
                    self.stop.wait(1)
                    continue
                elif shared.verbose >= 2:
                    logger.debug('Could NOT connect to ' + str(peer) + ' during outgoing attempt. ' + str(err))

                deletedPeer = None
                with knownnodes.knownNodesLock:
                    """
                    It is remotely possible that peer is no longer in knownnodes.knownNodes.
                    This could happen if two outgoingSynSender threads both try to
                    connect to the same peer, both fail, and then both try to remove
                    it from knownnodes.knownNodes. This is unlikely because of the
                    alreadyAttemptedConnectionsList but because we clear that list once
                    every half hour, it can happen.
                    """
                    if peer in knownnodes.knownNodes[self.streamNumber]:
                        timeLastSeen = knownnodes.knownNodes[self.streamNumber][peer]
                        if (int(time.time()) - timeLastSeen) > 172800 and len(knownnodes.knownNodes[self.streamNumber]) > 1000:  # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownnodes.knownNodes data-structure.
                            del knownnodes.knownNodes[self.streamNumber][peer]
                            deletedPeer = peer
                if deletedPeer:
                    str ('deleting ' + str(peer) + ' from knownnodes.knownNodes because it is more than 48 hours old and we could not connect to it.')

            except socks.Socks5AuthError as err:
                queues.UISignalQueue.put((
                    'updateStatusBar', tr._translate(
                    "MainWindow", "SOCKS5 Authentication problem: %1. Please check your SOCKS5 settings.").arg(str(err))))
            except socks.Socks5Error as err:
                if err[0][0] in [3, 4, 5, 6]:
                    # this is a more bening "error": host unreachable, network unreachable, connection refused, TTL expired
                    logger.debug('SOCKS5 error: %s', str(err))
                else:
                    logger.error('SOCKS5 error: %s', str(err))
                if err[0][0] == 4 or err[0][0] == 2:
                    state.networkProtocolAvailability[protocol.networkType(peer.host)] = False
            except socks.Socks4Error as err:
                logger.error('Socks4Error: ' + str(err))
            except socket.error as err:
                if BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
                    logger.error('Bitmessage MIGHT be having trouble connecting to the SOCKS server. ' + str(err))
                else:
                    if err[0] == errno.ENETUNREACH:
                        state.networkProtocolAvailability[protocol.networkType(peer.host)] = False
                    if shared.verbose >= 1:
                        logger.debug('Could NOT connect to ' + str(peer) + 'during outgoing attempt. ' + str(err))

                deletedPeer = None
                with knownnodes.knownNodesLock:
                    """
                    It is remotely possible that peer is no longer in knownnodes.knownNodes.
                    This could happen if two outgoingSynSender threads both try to
                    connect to the same peer, both fail, and then both try to remove
                    it from knownnodes.knownNodes. This is unlikely because of the
                    alreadyAttemptedConnectionsList but because we clear that list once
                    every half hour, it can happen.
                    """
                    if peer in knownnodes.knownNodes[self.streamNumber]:
                        timeLastSeen = knownnodes.knownNodes[self.streamNumber][peer]
                        if (int(time.time()) - timeLastSeen) > 172800 and len(knownnodes.knownNodes[self.streamNumber]) > 1000:  # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownnodes.knownNodes data-structure.
                            del knownnodes.knownNodes[self.streamNumber][peer]
                            deletedPeer = peer
                if deletedPeer:
                    logger.debug('deleting ' + str(peer) + ' from knownnodes.knownNodes because it is more than 48 hours old and we could not connect to it.')

            except Exception as err:
                import traceback
                logger.exception('An exception has occurred in the outgoingSynSender thread that was not caught by other exception types:')
            self.stop.wait(0.1)


text:
import * as React from "react";
import * as Highcharts from "highcharts";
import ReactHighcharts from "react-highcharts";

const config: Highcharts.Options = {};

function callback(chart: Highcharts.ChartObject): void {}

export const _ = () => (
    <>
        <ReactHighcharts config={config} />
        <ReactHighcharts config={config} callback={callback} />
    </>
);


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.messaging.eventhubs.perf;

import com.microsoft.azure.eventhubs.PartitionRuntimeInformation;
import reactor.core.publisher.Mono;

import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
 * Gets partition information.
 */
public class GetPartitionInformationTest extends ServiceTest<EventHubsPartitionOptions> {
    /**
     * Creates an instance of performance test.
     *
     * @param options the options configured for the test.
     */
    public GetPartitionInformationTest(EventHubsPartitionOptions options) {
        super(options);
    }

    @Override
    public Mono<Void> setupAsync() {
        if (options.isSync() && client == null) {
            client = createEventHubClient();
        } else if (!options.isSync() && clientFuture == null) {
            clientFuture = createEventHubClientAsync();
        }

        return super.setupAsync();
    }

    @Override
    public void run() {
        PartitionRuntimeInformation information;
        try {
            information = client.getPartitionRuntimeInformation(options.getPartitionId()).get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException("Unable to get partition information for: " + options.getPartitionId(), e);
        }

        printRuntimeInformation(information);
    }

    @Override
    public Mono<Void> runAsync() {
        return Mono.fromCompletionStage(clientFuture
            .thenComposeAsync(client -> client.getPartitionRuntimeInformation(options.getPartitionId()))
            .thenAccept(information -> printRuntimeInformation(information)));
    }

    private static void printRuntimeInformation(PartitionRuntimeInformation information) {
        Objects.requireNonNull(information, "'PartitionRuntimeInformation' cannot be null.");
    }
}


text:
@implementation EPAYMetaResponse

+ (NSDictionary *)JSONMappingDictionary {
    return @{
             @"action": @"action",
             @"message": @"message",
             @"result": @"result"
             };
}

@end


text:
layout: habit
title: Create a 120 second workout
date: 2016-03-21T08:30:23-07:00
modified:
excerpt:
image:
  feature:
  teaser:
  thumb:
ads: false
comments: true
inline_comments: false
type: action
tags:
skills:
level: 2
author: stevo
---

In order to move more, we're going to practice create a 120 second workout.

### Why
This is a variation of an earlier habit where you created a 60-second workout. The reason is the same: long workouts are hard to work into a day. Now you have an opportunity to carve out a bit more time, either on top of an exercise routine you're already doing, or as a way to get back into a regular routine.

### How
Your workout doesn't have to be intense. It can be anything that fits you. Some people can find two minutes to walk around the block when they need to clear their heads. Or you might want to do a pushup plank for one minute next to your bed when you get up and then a minute of body-weight squats. Or, if you're still dancing for a minute in the shower each day, add another minute of dancing at the end of the workday.

### When
Figure out a time of day when you have an extra minute, extra privacy, or don't need to look fresh wherever you are next. This could be before you brush your teeth, before you go to bed, or on the way home from work.


text:
using System.IO;
using System.Net;

namespace NReadability
{
  /// <summary>
  /// Fetches web content.
  /// </summary>
  public class UrlFetcher : IUrlFetcher
  {
    #region IUrlFetcher members

    public string Fetch(string url)
    {
      var fetchRequest = (HttpWebRequest)WebRequest.Create(url);

      fetchRequest.Method = "GET";

      using (var resp = fetchRequest.GetResponse())
      using (var reader = new StreamReader(resp.GetResponseStream(), true))
      {
        return reader.ReadToEnd();
      }
    }

    #endregion
  }
}


text:
// *************************************************************************************************
//
// QPropertyEditor v 0.3
//
// --------------------------------------
// Copyright (C) 2007 Volker Wiendl
// Acknowledgements to Roman alias banal from qt-apps.org for the Enum
// enhancement
//
//
// The QPropertyEditor Library is free software; you can redistribute it and/or
// modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation version 3 of the License
//
// The Horde3D Scene Editor is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// *************************************************************************************************
#ifndef QPROPERTYMODEL_H_
#define QPROPERTYMODEL_H_

#include <QtCore/QAbstractItemModel>
#include <QRegularExpression>

class Property;

/**
 * The QPropertyModel handles the user defined properties of QObjects
 */
class QPropertyModel : public QAbstractItemModel {
  Q_OBJECT

public:
  /**
   * A typedef for a callback used to create user defined properties for custom
   * datatypes
   */
  typedef Property *(*UserTypeCB)(const QString &, QObject *, Property *);

  /**
   * Constructor
   * @param parent optional parent object
   */
  explicit QPropertyModel(QObject *parent = nullptr) noexcept;
  /// Destructor
  virtual ~QPropertyModel();

  QModelIndex
    index(int, int, const QModelIndex & = QModelIndex()) const override;

  QModelIndex parent(const QModelIndex &) const override;

  int rowCount(const QModelIndex & = QModelIndex()) const override;

  int columnCount(const QModelIndex & = QModelIndex()) const override;

  QVariant data(const QModelIndex &, int = Qt::DisplayRole) const override;

  bool
    setData(const QModelIndex &, const QVariant &, int = Qt::EditRole) override;

  Qt::ItemFlags flags(const QModelIndex &) const override;

  QVariant
    headerData(int, Qt::Orientation, int = Qt::DisplayRole) const override;

  QModelIndex buddy(const QModelIndex &) const override;

  /**
   * Adds the user properties of the given class to the QPropertyModel instance
   *
   * @param subject the QObject-derived object that contains user properties
   * that should be managed by this instance
   */
  void addItem(QObject *subject) noexcept;

  /**
   * Creates a dataChanged signal for the given object
   * @param subject the instance of a QObject based class that should be updated
   * @param parent optional model index the propertyObject is child of
   */
  void updateItem(
    QObject *subject, const QModelIndex &parent = QModelIndex()) noexcept;

  /**
   * Removes all objects from the model
   */
  void clear() noexcept;

  /**
   * Adds custom callback that will be used to create Property instances for
   * custom datatypes
   */
  void registerCustomPropertyCB(UserTypeCB callback) noexcept;

  /**
   * Adds custom callback that will be used to create Property instances for
   * custom datatypes
   */
  void unregisterCustomPropertyCB(UserTypeCB callback) noexcept;

  void setNameFilter(const QRegularExpression &filter) noexcept {
    m_filter = filter;
  }

  const QRegularExpression &getNameFilter() const noexcept {
    return m_filter;
  }

  // TODO: Add the ability to hide properties
  // TODO: Add the ability to remove objects
  // TODO: Set stuff in different roles (e.g. tooltips)
  // TODO: Add ability to sort properties

private:
  QColor _color;

  /// Adds dynamic properties to the model
  void addDynamicProperties(Property *parent, QObject *propertyObject) noexcept;

  /// The Root Property for all objects
  Property *m_rootItem;

  /// Any property names that match this filter will not be visible.
  QRegularExpression m_filter;

  /// Custom callback
  QList<UserTypeCB> m_userCallbacks;
};
#endif


text:
package com.jivesoftware.os.miru.bitmaps.roaring5.buffer;

import com.jivesoftware.os.filer.io.api.StackBuffer;
import com.jivesoftware.os.miru.api.MiruHost;
import com.jivesoftware.os.miru.api.MiruPartitionCoord;
import com.jivesoftware.os.miru.api.activity.MiruPartitionId;
import com.jivesoftware.os.miru.api.base.MiruTenantId;
import com.jivesoftware.os.miru.api.wal.RCVSSipCursor;
import com.jivesoftware.os.miru.bitmaps.roaring5.MiruBitmapsRoaring;
import com.jivesoftware.os.miru.plugin.bitmap.MiruBitmaps;
import com.jivesoftware.os.miru.plugin.bitmap.MiruIntIterator;
import com.jivesoftware.os.miru.service.IndexTestUtil;
import com.jivesoftware.os.miru.service.stream.MiruContext;
import java.util.Arrays;
import org.roaringbitmap.RoaringBitmap;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;

/**
 *
 */
public class MiruBitmapsTimeRangeTest {

    private final int numberOfChunkStores = 4;

    @Test(dataProvider = "evenTimeIndexDataProvider")
    public <BM extends IBM, IBM> void testBuildEvenTimeRangeMask(MiruBitmaps<BM, IBM> bitmaps,
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> miruTimeIndex) throws Exception {
        StackBuffer stackBuffer = new StackBuffer();
        final int size = (64 * 3) + 1;
        for (int lower = 0; lower <= size / 2; lower++) {
            int upper = size - 1 - lower;

            IBM bitmap = bitmaps.buildTimeRangeMask(miruTimeIndex.timeIndex, lower, upper, stackBuffer);
            if (lower == upper) {
                // the lower and upper are the same so there should be nothing left
                assertExpectedNumberOfConsecutiveBitsStartingFromN(bitmaps, bitmap, -1, 0);
            } else {
                assertExpectedNumberOfConsecutiveBitsStartingFromN(bitmaps, bitmap, lower + 1, size - 1 - 2 * lower);
            }
        }
    }

    @Test(dataProvider = "oddTimeIndexDataProvider")
    public <BM extends IBM, IBM> void testBuildOddTimeRangeMask(MiruBitmaps<BM, IBM> bitmaps,
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> miruTimeIndex) throws Exception {
        StackBuffer stackBuffer = new StackBuffer();
        final int size = 64 * 3;
        for (int lower = 0; lower < size / 2; lower++) {
            int upper = size - 1 - lower;

            IBM bitmap = bitmaps.buildTimeRangeMask(miruTimeIndex.timeIndex, lower, upper, stackBuffer);
            if (lower == upper) {
                fail();
            } else {
                assertExpectedNumberOfConsecutiveBitsStartingFromN(bitmaps, bitmap, lower + 1, size - 1 - 2 * lower);
            }
        }
    }

    @Test(dataProvider = "singleEntryTimeIndexDataProvider")
    public <BM extends IBM, IBM> void testSingleBitTimeRange(MiruBitmaps<BM, IBM> bitmaps,
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> miruTimeIndex) throws Exception {
        StackBuffer stackBuffer = new StackBuffer();
        IBM bitmap = bitmaps.buildTimeRangeMask(miruTimeIndex.timeIndex, 0, Long.MAX_VALUE, stackBuffer);

        assertExpectedNumberOfConsecutiveBitsStartingFromN(bitmaps, bitmap, 0, 1);
    }

    private <BM extends IBM, IBM> void assertExpectedNumberOfConsecutiveBitsStartingFromN(MiruBitmaps<BM, IBM> bitmaps, IBM bitmap, int expectedStartingFrom,
        int expectedCardinality) {
        int last = -1;
        int cardinality = 0;
        int startingFrom = -1;
        MiruIntIterator iter = bitmaps.intIterator(bitmap);
        while (iter.hasNext()) {
            int current = iter.next();
            if (last < 0) {
                startingFrom = current;
            } else if (last >= 0) {
                assertEquals(current - last, 1);
            }
            last = current;
            cardinality++;
        }
        assertEquals(startingFrom, expectedStartingFrom);
        assertEquals(cardinality, expectedCardinality);
    }

    @DataProvider(name = "evenTimeIndexDataProvider")
    public Object[][] evenTimeIndexDataProvider() throws Exception {
        StackBuffer stackBuffer = new StackBuffer();
        //MiruSchema schema = new Builder("test", 1).build();

        final int size = (64 * 3) + 1;
        final long[] timestamps = new long[size];
        for (int i = 0; i < size; i++) {
            timestamps[i] = i;
        }

        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> chunkInMemoryTimeIndex = buildInMemoryTimeIndex(false);
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> chunkOnDiskTimeIndex = buildOnDiskTimeIndex(false);
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> labInMemoryTimeIndex = buildInMemoryTimeIndex(true);
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> labOnDiskTimeIndex = buildOnDiskTimeIndex(true);

        int[] ids = new int[timestamps.length];
        long[] monotonics = new long[timestamps.length];
        Arrays.fill(ids, -1);
        Arrays.fill(monotonics, -1);
        chunkInMemoryTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());
        chunkOnDiskTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());
        labInMemoryTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());
        labOnDiskTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());

        return new Object[][] {
            { new MiruBitmapsRoaring(), chunkInMemoryTimeIndex },
            { new MiruBitmapsRoaring(), chunkOnDiskTimeIndex },
            { new MiruBitmapsRoaring(), labInMemoryTimeIndex },
            { new MiruBitmapsRoaring(), labOnDiskTimeIndex }
        };
    }

    @DataProvider(name = "oddTimeIndexDataProvider")
    public Object[][] oddTimeIndexDataProvider() throws Exception {
        StackBuffer stackBuffer = new StackBuffer();

        final int size = 64 * 3;
        final long[] timestamps = new long[size];
        for (int i = 0; i < size; i++) {
            timestamps[i] = i;
        }

        int[] ids = new int[timestamps.length];
        long[] monotonics = new long[timestamps.length];
        Arrays.fill(ids, -1);
        Arrays.fill(monotonics, -1);
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> chunkInMemoryTimeIndex = buildInMemoryTimeIndex(false);
        chunkInMemoryTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> chunkOnDiskTimeIndex = buildOnDiskTimeIndex(false);
        chunkOnDiskTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> labInMemoryTimeIndex = buildInMemoryTimeIndex(true);
        labInMemoryTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> labOnDiskTimeIndex = buildOnDiskTimeIndex(true);
        labOnDiskTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());

        return new Object[][] {
            { new MiruBitmapsRoaring(), chunkInMemoryTimeIndex },
            { new MiruBitmapsRoaring(), chunkOnDiskTimeIndex },
            { new MiruBitmapsRoaring(), labInMemoryTimeIndex },
            { new MiruBitmapsRoaring(), labOnDiskTimeIndex }
        };
    }

    @DataProvider(name = "singleEntryTimeIndexDataProvider")
    public Object[][] singleEntryTimeIndexDataProvider() throws Exception {
        StackBuffer stackBuffer = new StackBuffer();

        final long[] timestamps = new long[] { System.currentTimeMillis() };
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> chunkInMemoryTimeIndex = buildInMemoryTimeIndex(false);
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> labInMemoryTimeIndex = buildInMemoryTimeIndex(true);
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> chunkOnDiskTimeIndex = buildOnDiskTimeIndex(false);
        MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> labOnDiskTimeIndex = buildOnDiskTimeIndex(true);

        int[] ids = new int[timestamps.length];
        long[] monotonics = new long[timestamps.length];
        Arrays.fill(ids, -1);
        Arrays.fill(monotonics, -1);
        chunkInMemoryTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());
        labInMemoryTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());
        chunkOnDiskTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());
        labOnDiskTimeIndex.timeIndex.nextId(stackBuffer, timestamps, ids.clone(), monotonics.clone());

        return new Object[][] {
            { new MiruBitmapsRoaring(), chunkInMemoryTimeIndex },
            { new MiruBitmapsRoaring(), labInMemoryTimeIndex },
            { new MiruBitmapsRoaring(), chunkOnDiskTimeIndex },
            { new MiruBitmapsRoaring(), labOnDiskTimeIndex }
        };
    }

    private MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> buildInMemoryTimeIndex(boolean useLabIndexes) throws Exception {
        MiruBitmapsRoaring bitmaps = new MiruBitmapsRoaring();
        MiruPartitionCoord coord = new MiruPartitionCoord(new MiruTenantId("test".getBytes()), MiruPartitionId.of(0), new MiruHost("logicalName"));
        return IndexTestUtil.buildInMemoryContext(numberOfChunkStores, useLabIndexes, true, bitmaps, coord);
    }

    private MiruContext<RoaringBitmap, RoaringBitmap, RCVSSipCursor> buildOnDiskTimeIndex(boolean useLabIndexes) throws Exception {
        MiruBitmapsRoaring bitmaps = new MiruBitmapsRoaring();
        MiruPartitionCoord coord = new MiruPartitionCoord(new MiruTenantId("test".getBytes()), MiruPartitionId.of(0), new MiruHost("logicalName"));
        return IndexTestUtil.buildOnDiskContext(numberOfChunkStores, useLabIndexes, true, bitmaps, coord);
    }
}


text:
var sinon = require('sinon');

/**
 * Helper to unwrap and re-wrap a method with a callback.
 * @param  {object}   object Object to be stubbed
 * @param  {string}   method Method on the object to be stubbed
 * @param  {function} cb     Optional callback to be the stub
 * @return {undefined}
 */
module.exports = function reloadStub(object, method, cb) {
  if (typeof object === 'undefined' || typeof method === 'undefined') {
    throw new Error('reloadStub expects an object and method');
  } else {
    object[method].restore();
    typeof cb === 'function' ? sinon.stub(object, method, cb)
                             : sinon.stub(object, method);
  }
}


text:
LINK_RESOURCE_ID(0, 0)

// InfoBar resources.
LINK_RESOURCE_ID(IDR_INFOBAR_3D_BLOCKED, R.drawable.infobar_3d_blocked)
LINK_RESOURCE_ID(IDR_INFOBAR_AUTOFILL_CC, R.drawable.infobar_autofill_cc)
LINK_RESOURCE_ID(IDR_INFOBAR_MEDIA_STREAM_CAMERA, R.drawable.infobar_camera)
LINK_RESOURCE_ID(IDR_INFOBAR_MEDIA_STREAM_MIC, R.drawable.infobar_microphone)
LINK_RESOURCE_ID(IDR_INFOBAR_SAVE_PASSWORD, R.drawable.infobar_savepassword)
LINK_RESOURCE_ID(IDR_INFOBAR_TRANSLATE, R.drawable.infobar_translate)
LINK_RESOURCE_ID(IDR_BLOCKED_POPUPS, R.drawable.infobar_blocked_popups)

// Android only infobars.
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_FROZEN_TAB, R.drawable.infobar_restore)
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_GEOLOCATION,
                    R.drawable.infobar_geolocation)
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_MEDIA_STREAM_SCREEN,
                    R.drawable.infobar_screen_share)
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_MIDI, R.drawable.infobar_midi)
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_MULTIPLE_DOWNLOADS,
                    R.drawable.infobar_multiple_downloads)
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_NOTIFICATIONS,
                    R.drawable.infobar_desktop_notifications)
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_PREVIEWS,
                    R.drawable.infobar_chrome)
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_PROTECTED_MEDIA_IDENTIFIER,
                    R.drawable.infobar_protected_media_identifier)
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_SUBRESOURCE_FILTERING,
                    R.drawable.infobar_subresource_filtering)
DECLARE_RESOURCE_ID(IDR_ANDROID_INFOBAR_WARNING, R.drawable.infobar_warning)

// WebsiteSettingsUI images, used in ConnectionInfoPopup
// Good:
LINK_RESOURCE_ID(IDR_PAGEINFO_GOOD, R.drawable.pageinfo_good)
// Warnings:
LINK_RESOURCE_ID(IDR_PAGEINFO_WARNING_MINOR, R.drawable.pageinfo_warning)
// Bad:
LINK_RESOURCE_ID(IDR_PAGEINFO_BAD, R.drawable.pageinfo_bad)
// Should never occur, use warning just in case:
// Enterprise managed: ChromeOS only.
LINK_RESOURCE_ID(IDR_PAGEINFO_ENTERPRISE_MANAGED, R.drawable.pageinfo_warning)
// Info: Only shown on chrome:// urls, which don't show the connection info
// popup.
LINK_RESOURCE_ID(IDR_PAGEINFO_INFO, R.drawable.pageinfo_warning)
// Major warning: Used on insecure pages, which don't show the connection info
// popup.
LINK_RESOURCE_ID(IDR_PAGEINFO_WARNING_MAJOR, R.drawable.pageinfo_warning)

// Autofill popup and keyboard accessory images.
// We use Android's |VectorDrawableCompat| for the following images that are
// displayed using |DropdownAdapter|.
LINK_RESOURCE_ID(IDR_AUTOFILL_CC_AMEX, R.drawable.amex_card)
LINK_RESOURCE_ID(IDR_AUTOFILL_CC_DINERS, R.drawable.ic_credit_card_black)
LINK_RESOURCE_ID(IDR_AUTOFILL_CC_DISCOVER, R.drawable.discover_card)
LINK_RESOURCE_ID(IDR_AUTOFILL_CC_GENERIC, R.drawable.ic_credit_card_black)
LINK_RESOURCE_ID(IDR_AUTOFILL_CC_JCB, R.drawable.ic_credit_card_black)
LINK_RESOURCE_ID(IDR_AUTOFILL_CC_MASTERCARD, R.drawable.mc_card)
LINK_RESOURCE_ID(IDR_AUTOFILL_CC_MIR, R.drawable.mir_card)
LINK_RESOURCE_ID(IDR_AUTOFILL_CC_VISA, R.drawable.visa_card)
LINK_RESOURCE_ID(IDR_AUTOFILL_CC_SCAN_NEW, R.drawable.ic_photo_camera_black)
LINK_RESOURCE_ID(IDR_AUTOFILL_HTTP_WARNING, R.drawable.ic_info_outline_grey)
LINK_RESOURCE_ID(IDR_AUTOFILL_HTTPS_INVALID_WARNING, R.drawable.ic_warning_red)

// We display settings icon for keyboard accessory using Android's
// |VectorDrawableCompat|. We do not display settings icon for autofill popup.
LINK_RESOURCE_ID(IDR_AUTOFILL_SETTINGS, R.drawable.ic_settings_black)

// We use PNG files for the following images.
LINK_RESOURCE_ID(IDR_CREDIT_CARD_CVC_HINT, R.drawable.cvc_icon)
LINK_RESOURCE_ID(IDR_CREDIT_CARD_CVC_HINT_AMEX, R.drawable.cvc_icon_amex)

// PaymentRequest images.
LINK_RESOURCE_ID(IDR_AUTOFILL_PR_AMEX, R.drawable.pr_amex)
LINK_RESOURCE_ID(IDR_AUTOFILL_PR_DINERS, R.drawable.pr_dinersclub)
LINK_RESOURCE_ID(IDR_AUTOFILL_PR_DISCOVER, R.drawable.pr_discover)
LINK_RESOURCE_ID(IDR_AUTOFILL_PR_GENERIC, R.drawable.pr_generic)
LINK_RESOURCE_ID(IDR_AUTOFILL_PR_JCB, R.drawable.pr_jcb)
LINK_RESOURCE_ID(IDR_AUTOFILL_PR_MASTERCARD, R.drawable.pr_mc)
LINK_RESOURCE_ID(IDR_AUTOFILL_PR_MIR, R.drawable.pr_mir)
LINK_RESOURCE_ID(IDR_AUTOFILL_PR_UNIONPAY, R.drawable.pr_unionpay)
LINK_RESOURCE_ID(IDR_AUTOFILL_PR_VISA, R.drawable.pr_visa)


text:
var mifare = require("../build/Release/node_mifare");
var ndef = require("ndef");

console.log(mifare);

var readers = mifare.getReader();
console.log(readers);

readers["ACS ACR122U PICC Interface 00 00"].listen(function(err, reader, card) {
  reader.setLed(0x0C, 0, 0, 0, 0);
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NetFusion.Bootstrap.Plugins;

namespace NetFusion.Bootstrap.Health
{
    /// <summary>
    /// Contains a set of module associated aspects and information about
    /// their current health.
    /// </summary>
    public class ModuleHealthCheck
    {
        private readonly List<HealthAspectCheck> _aspectsChecks = new();

        /// <summary>
        /// The module type  associated with the health check.
        /// </summary>
        public Type PluginModuleType { get; }

        /// <summary>
        /// List of associated module aspects and their associated health status.
        /// </summary>
        public IReadOnlyCollection<HealthAspectCheck> AspectChecks { get; }

        /// <summary>
        /// The overall worst health-check reported for a module's associated aspects.
        /// </summary>
        public HealthCheckStatusType ModuleHealth => _aspectsChecks.Any() ?
            _aspectsChecks.Max(ac => ac.HealthCheckStatus) : HealthCheckStatusType.Healthy;

        internal ModuleHealthCheck(IModuleHealthCheck pluginModule)
        {
            PluginModuleType = pluginModule?.GetType() ?? throw new ArgumentNullException(nameof(pluginModule));
            AspectChecks = _aspectsChecks;
        }

        /// <summary>
        /// Records information about an aspect of a module with a given status used to determine
        /// its overall health.
        /// </summary>
        /// <param name="aspectCheck">The status associated with a specific aspect of the module.</param>
        public void RecordAspect(HealthAspectCheck aspectCheck)
        {
            if (aspectCheck == null) throw new ArgumentNullException(nameof(aspectCheck));
            _aspectsChecks.Add(aspectCheck);
        }
    }
}


text:
package org.activiti.engine.test.api.event;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.delegate.event.ActivitiEventDispatcher;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.BaseEntityEventListener;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.delegate.event.impl.ActivitiEventDispatcherImpl;
import org.activiti.engine.delegate.event.impl.ActivitiEventImpl;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.activiti.engine.impl.test.PluggableActivitiTestCase;
import org.activiti.engine.task.Task;

/**
 *
 */
public abstract class ActivitiEventDispatcherTest extends PluggableActivitiTestCase {

  protected ActivitiEventDispatcher dispatcher;

  @Override
  protected void setUp() throws Exception {
    super.setUp();

    dispatcher = new ActivitiEventDispatcherImpl();
  }

  /**
   * Test adding a listener and check if events are sent to it. Also checks that after removal, no events are received.
   */
  public void addAndRemoveEventListenerAllEvents() throws Exception {
    // Create a listener that just adds the events to a list
    TestActivitiEventListener newListener = new TestActivitiEventListener();

    // Add event-listener to dispatcher
    dispatcher.addEventListener(newListener);

    ActivitiEntityEventImpl event1 = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_CREATED);
    ActivitiEntityEventImpl event2 = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_CREATED);

    // Dispatch events
    dispatcher.dispatchEvent(event1);
    dispatcher.dispatchEvent(event2);

    assertThat(newListener.getEventsReceived()).hasSize(2);
    assertThat(newListener.getEventsReceived().get(0)).isEqualTo(event1);
    assertThat(newListener.getEventsReceived().get(1)).isEqualTo(event2);

    // Remove listener and dispatch events again, listener should not be
    // invoked
    dispatcher.removeEventListener(newListener);
    newListener.clearEventsReceived();
    dispatcher.dispatchEvent(event1);
    dispatcher.dispatchEvent(event2);

    assertThat(newListener.getEventsReceived().isEmpty()).isTrue();
  }

  /**
   * Test adding a listener and check if events are sent to it, for the types it was registered for. Also checks that after removal, no events are received.
   */
  public void addAndRemoveEventListenerTyped() throws Exception {
    // Create a listener that just adds the events to a list
    TestActivitiEventListener newListener = new TestActivitiEventListener();

    // Add event-listener to dispatcher
    dispatcher.addEventListener(newListener, ActivitiEventType.ENTITY_CREATED, ActivitiEventType.ENTITY_DELETED);

    ActivitiEntityEventImpl event1 = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_CREATED);
    ActivitiEntityEventImpl event2 = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_DELETED);
    ActivitiEntityEventImpl event3 = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_UPDATED);

    // Dispatch events, only 2 out of 3 should have entered the listener
    dispatcher.dispatchEvent(event1);
    dispatcher.dispatchEvent(event2);
    dispatcher.dispatchEvent(event3);

    assertThat(newListener.getEventsReceived()).hasSize(2);
    assertThat(newListener.getEventsReceived().get(0)).isEqualTo(event1);
    assertThat(newListener.getEventsReceived().get(1)).isEqualTo(event2);

    // Remove listener and dispatch events again, listener should not be
    // invoked
    dispatcher.removeEventListener(newListener);
    newListener.clearEventsReceived();
    dispatcher.dispatchEvent(event1);
    dispatcher.dispatchEvent(event2);

    assertThat(newListener.getEventsReceived().isEmpty()).isTrue();
  }

  /**
   * Test that adding a listener with a null-type is never called.
   */
  public void addAndRemoveEventListenerTypedNullType() throws Exception {

    // Create a listener that just adds the events to a list
    TestActivitiEventListener newListener = new TestActivitiEventListener();

    // Add event-listener to dispatcher
    dispatcher.addEventListener(newListener, (ActivitiEventType) null);

    ActivitiEntityEventImpl event1 = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_CREATED);
    ActivitiEntityEventImpl event2 = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_DELETED);

    // Dispatch events, all should have entered the listener
    dispatcher.dispatchEvent(event1);
    dispatcher.dispatchEvent(event2);

    assertThat(newListener.getEventsReceived().isEmpty()).isTrue();
  }

  /**
   * Test the {@link BaseEntityEventListener} shipped with Activiti.
   */
  public void baseEntityEventListener() throws Exception {
    TestBaseEntityEventListener listener = new TestBaseEntityEventListener();

    dispatcher.addEventListener(listener);

    ActivitiEntityEventImpl createEvent = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_CREATED);
    ActivitiEntityEventImpl deleteEvent = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_DELETED);
    ActivitiEntityEventImpl updateEvent = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.ENTITY_UPDATED);
    ActivitiEntityEventImpl otherEvent = new ActivitiEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), ActivitiEventType.CUSTOM);

    // Dispatch create event
    dispatcher.dispatchEvent(createEvent);
    assertThat(listener.isCreateReceived()).isTrue();
    assertThat(listener.isUpdateReceived()).isFalse();
    assertThat(listener.isCustomReceived()).isFalse();
    assertThat(listener.isInitializeReceived()).isFalse();
    assertThat(listener.isDeleteReceived()).isFalse();
    listener.reset();

    // Dispatch update event
    dispatcher.dispatchEvent(updateEvent);
    assertThat(listener.isUpdateReceived()).isTrue();
    assertThat(listener.isCreateReceived()).isFalse();
    assertThat(listener.isCustomReceived()).isFalse();
    assertThat(listener.isDeleteReceived()).isFalse();
    listener.reset();

    // Dispatch delete event
    dispatcher.dispatchEvent(deleteEvent);
    assertThat(listener.isDeleteReceived()).isTrue();
    assertThat(listener.isCreateReceived()).isFalse();
    assertThat(listener.isCustomReceived()).isFalse();
    assertThat(listener.isUpdateReceived()).isFalse();
    listener.reset();

    // Dispatch other event
    dispatcher.dispatchEvent(otherEvent);
    assertThat(listener.isCustomReceived()).isTrue();
    assertThat(listener.isCreateReceived()).isFalse();
    assertThat(listener.isUpdateReceived()).isFalse();
    assertThat(listener.isDeleteReceived()).isFalse();
    listener.reset();

    // Test typed entity-listener
    listener = new TestBaseEntityEventListener(Task.class);

    // Dispatch event for a task, should be received
    dispatcher.addEventListener(listener);
    dispatcher.dispatchEvent(createEvent);

    assertThat(listener.isCreateReceived()).isTrue();
    listener.reset();

    // Dispatch event for a execution, should NOT be received
    ActivitiEntityEventImpl createEventForExecution = new ActivitiEntityEventImpl(new ExecutionEntityImpl(), ActivitiEventType.ENTITY_CREATED);

    dispatcher.dispatchEvent(createEventForExecution);
    assertThat(listener.isCreateReceived()).isFalse();
  }

  /**
   * Test dispatching behavior when an exception occurs in the listener
   */
  public void exceptionInListener() throws Exception {
    // Create listener that doesn't force the dispatching to fail
    TestExceptionActivitiEventListener listener = new TestExceptionActivitiEventListener(false);
    TestActivitiEventListener secondListener = new TestActivitiEventListener();

    dispatcher.addEventListener(listener);
    dispatcher.addEventListener(secondListener);

    ActivitiEventImpl event = new ActivitiEventImpl(ActivitiEventType.ENTITY_CREATED);
    try {
      dispatcher.dispatchEvent(event);
      assertThat(secondListener.getEventsReceived()).hasSize(1);
    } catch (Throwable t) {
      fail("No exception expected");
    }

    // Remove listeners
    dispatcher.removeEventListener(listener);
    dispatcher.removeEventListener(secondListener);

    // Create listener that forces the dispatching to fail
    listener = new TestExceptionActivitiEventListener(true);
    secondListener = new TestActivitiEventListener();
    dispatcher.addEventListener(listener);
    dispatcher.addEventListener(secondListener);

    assertThatExceptionOfType(ActivitiException.class)
        .isThrownBy(() -> dispatcher.dispatchEvent(event))
        .withCauseInstanceOf(RuntimeException.class)
        .satisfies(ae -> assertThat(ae.getCause()).hasMessage("Test exception"));

    // Second listener should NOT have been called
    assertThat(secondListener.getEventsReceived()).hasSize(0);
  }

  /**
   * Test conversion of string-value (and list) in list of {@link ActivitiEventType}s, used in configuration of process-engine
   * {@link ProcessEngineConfigurationImpl#setTypedEventListeners(java.util.Map)} .
   */
  public void activitiEventTypeParsing() throws Exception {
    // Check with empty null
    ActivitiEventType[] types = ActivitiEventType.getTypesFromString(null);
    assertThat(types).isNotNull();
    assertThat(types.length).isEqualTo(0);

    // Check with empty string
    types = ActivitiEventType.getTypesFromString("");
    assertThat(types).isNotNull();
    assertThat(types.length).isEqualTo(0);

    // Single value
    types = ActivitiEventType.getTypesFromString("ENTITY_CREATED");
    assertThat(types).isNotNull();
    assertThat(types.length).isEqualTo(1);
    assertThat(types[0]).isEqualTo(ActivitiEventType.ENTITY_CREATED);

    // Multiple value
    types = ActivitiEventType.getTypesFromString("ENTITY_CREATED,ENTITY_DELETED");
    assertThat(types).isNotNull();
    assertThat(types.length).isEqualTo(2);
    assertThat(types[0]).isEqualTo(ActivitiEventType.ENTITY_CREATED);
    assertThat(types[1]).isEqualTo(ActivitiEventType.ENTITY_DELETED);

    // Additional separators should be ignored
    types = ActivitiEventType.getTypesFromString(",ENTITY_CREATED,,ENTITY_DELETED,,,");
    assertThat(types).isNotNull();
    assertThat(types.length).isEqualTo(2);
    assertThat(types[0]).isEqualTo(ActivitiEventType.ENTITY_CREATED);
    assertThat(types[1]).isEqualTo(ActivitiEventType.ENTITY_DELETED);

    // Invalid type name
    assertThatExceptionOfType(ActivitiIllegalArgumentException.class)
      .isThrownBy(() -> ActivitiEventType.getTypesFromString("WHOOPS,ENTITY_DELETED"))
      .withMessage("Invalid event-type: WHOOPS");
  }
}


text:
include Makefile.common

# Phony targets:
.PHONY: default src clean

# Default rule:
default: src

# Compile all srcs:
src:
	$(MAKE) -C src

# I probably should create a distclean as well but... too lazy right now.
clean:
	$(MAKE) -C src clean
	@echo -n '** Deleting directory $(BIN_DIR)... '
	@if [ -d $(BIN_DIR) ]; then $(RM) $(BIN_DIR); fi
	@echo 'done.'


text:
package org.xdi.oxauth.service.fido.u2f;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.xdi.oxauth.model.fido.u2f.exception.BadInputException;
import org.xdi.oxauth.model.fido.u2f.protocol.ClientData;

/**
 * Client data validation service
 *
 * @author Yuriy Movchan Date: 05/20/2015
 */
@Scope(ScopeType.STATELESS)
@Name("clientDataValidationService")
@AutoCreate
public class ClientDataValidationService {

	@Logger
	private Log log;

	public void checkContent(ClientData clientData, String type, String challenge, Set<String> facets) throws BadInputException {
		if (!type.equals(clientData.getTyp())) {
			throw new BadInputException("Bad clientData: wrong typ " + clientData.getTyp());
		}

		if (!challenge.equals(clientData.getChallenge())) {
			throw new BadInputException("Bad clientData: wrong challenge");
		}

		if (facets != null && !facets.isEmpty()) {
			Set<String> allowedFacets = canonicalizeOrigins(facets);
			String canonicalOrigin;
			try {
				canonicalOrigin = canonicalizeOrigin(clientData.getOrigin());
			} catch (RuntimeException e) {
				throw new BadInputException("Bad clientData: Malformed origin", e);
			}
			verifyOrigin(canonicalOrigin, allowedFacets);
		}
	}

	private static void verifyOrigin(String origin, Set<String> allowedOrigins) throws BadInputException {
		if (!allowedOrigins.contains(origin)) {
			throw new BadInputException(origin + " is not a recognized facet for this application");
		}
	}

	public static Set<String> canonicalizeOrigins(Set<String> origins) {
		Set<String> result = new HashSet<String>();
		for (String origin : origins) {
			result.add(canonicalizeOrigin(origin));
		}
		return result;
	}

	public static String canonicalizeOrigin(String url) {
		try {
			URI uri = new URI(url);
			if (uri.getAuthority() == null) {
				return url;
			}
			return uri.getScheme() + "://" + uri.getAuthority();
		} catch (URISyntaxException e) {
			throw new IllegalArgumentException("Specified bad origin", e);
		}
	}

}