text:
package org.apache.rya.indexing.pcj.matching;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.rya.indexing.IndexPlanValidator.IndexedExecutionPlanGenerator;
import org.apache.rya.indexing.external.tupleSet.ExternalTupleSet;
import org.apache.rya.indexing.external.tupleSet.SimpleExternalTupleSet;
import org.apache.rya.indexing.mongodb.pcj.MongoPcjIndexSetProvider;
import org.apache.rya.indexing.pcj.matching.provider.AbstractPcjIndexSetProvider;
import org.apache.rya.indexing.pcj.matching.provider.AccumuloIndexSetProvider;
import org.apache.rya.mongodb.StatefulMongoDBRdfConfiguration;
import org.apache.rya.test.mongo.EmbeddedMongoSingleton;
import org.eclipse.rdf4j.query.algebra.Projection;
import org.eclipse.rdf4j.query.algebra.QueryModelNode;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.eclipse.rdf4j.query.algebra.helpers.AbstractQueryModelVisitor;
import org.eclipse.rdf4j.query.parser.ParsedQuery;
import org.eclipse.rdf4j.query.parser.sparql.SPARQLParser;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

@RunWith(Parameterized.class)
public class PCJOptimizerTest {
    private final AbstractPcjIndexSetProvider provider;

    @Parameterized.Parameters
    public static Collection providers() throws Exception {
        final StatefulMongoDBRdfConfiguration conf = new StatefulMongoDBRdfConfiguration(new Configuration(), EmbeddedMongoSingleton.getNewMongoClient());
        return Lists.<AbstractPcjIndexSetProvider> newArrayList(
                new AccumuloIndexSetProvider(new Configuration()),
                new MongoPcjIndexSetProvider(conf)
                );
    }

    public PCJOptimizerTest(final AbstractPcjIndexSetProvider provider) {
        this.provider = provider;
    }

    @Test
    public void testBasicSegment() throws Exception {

        final String query1 = ""//
                + "SELECT ?e ?c ?l" //
                + "{" //
                + "  ?e a ?c . "//
                + "  OPTIONAL {?e <uri:talksTo> ?l}  . "//
                + "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l "//
                + "}";//

        final String query2 = ""//
                + "SELECT ?a ?b ?m" //
                + "{" //
                + "  ?a a ?b . "//
                + "  OPTIONAL {?a <uri:talksTo> ?m}  . "//
                + "}";//

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq1 = parser.parseQuery(query1, null);
        final ParsedQuery pq2 = parser.parseQuery(query2, null);
        final TupleExpr te1 = pq1.getTupleExpr();
        final TupleExpr te2 = pq2.getTupleExpr();

        final TupleExpr unOpt = te1.clone();
        final List<QueryModelNode> remainingNodes = getNodes(te1);
        final Set<QueryModelNode> unMatchedNodes = new HashSet<>();
        unMatchedNodes.add(remainingNodes.get(2));

        final SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection) te2);
        final List<ExternalTupleSet> externalList = new ArrayList<>();
        externalList.add(pcj);

        provider.setIndices(externalList);
        final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
        optimizer.optimize(te1, null, null);

        Assert.assertEquals(true, validatePcj(te1, unOpt, externalList, unMatchedNodes));

    }

    @Test
    public void testSegmentWithUnion() throws Exception {

        final String query1 = ""//
                + "SELECT ?e ?c ?l" //
                + "{" //
                + " {?e <uri:p1> <uri:o1>. } UNION { ?e a ?c. OPTIONAL {?e <uri:talksTo> ?l}. ?e <uri:p5> <uri:o4>. ?e <uri:p4> <uri:o3> }  . "//
                + "  ?e <uri:p2> ?c . "//
                + "  ?e <uri:p3> <uri:o2>  . "//
                + "}";//

        final String query2 = ""//
                + "SELECT ?a ?b ?m" //
                + "{" //
                + " ?a <uri:p5> <uri:o4> ." //
                + " ?a <uri:p4> <uri:o3> ." //
                + "  OPTIONAL {?a <uri:talksTo> ?m} . "//
                + "  ?a a ?b . "//
                + "}";//

        final String query3 = ""//
                + "SELECT ?h ?i" //
                + "{" //
                + "  ?h <uri:p2> ?i . "//
                + "  ?h <uri:p3> <uri:o2>  . "//
                + "}";//

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq1 = parser.parseQuery(query1, null);
        final ParsedQuery pq2 = parser.parseQuery(query2, null);
        final ParsedQuery pq3 = parser.parseQuery(query3, null);
        final TupleExpr te1 = pq1.getTupleExpr();
        final TupleExpr te2 = pq2.getTupleExpr();
        final TupleExpr te3 = pq3.getTupleExpr();

        final TupleExpr unOpt = te1.clone();
        final List<QueryModelNode> remainingNodes = getNodes(te1);
        final Set<QueryModelNode> unMatchedNodes = new HashSet<>();
        unMatchedNodes.add(remainingNodes.get(0));

        final SimpleExternalTupleSet pcj1 = new SimpleExternalTupleSet((Projection) te2);
        final SimpleExternalTupleSet pcj2 = new SimpleExternalTupleSet((Projection) te3);
        final List<ExternalTupleSet> externalList = new ArrayList<>();
        externalList.add(pcj1);
        externalList.add(pcj2);

        provider.setIndices(externalList);
        final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
        optimizer.optimize(te1, null, null);

        Assert.assertEquals(true, validatePcj(te1, unOpt, externalList, unMatchedNodes));

    }

    @Test
    public void testExactMatchLargeReOrdered() throws Exception {

        final String query1 = ""//
                + "SELECT ?a ?b ?c ?d ?e ?f ?g ?h" //
                + "{" //
                + "  ?a <uri:p0> ?b ." //
                + "  OPTIONAL{?b <uri:p2> ?c. ?c <uri:p1> ?d} . " //
                + "  OPTIONAL{?b <uri:p3> ?e. ?e <uri:p1> ?f} . "//
                + "  OPTIONAL{?b <uri:p4> ?g. ?g <uri:p1> ?h} . "//
                + "  OPTIONAL{?b <uri:p4> ?i. ?i <uri:p1> ?j} . "//
                + "  OPTIONAL{?b <uri:p4> ?k. ?k <uri:p1> ?l} . "//
                + "  OPTIONAL{?b <uri:p4> ?m. ?m <uri:p1> ?n} . "//
                + "  OPTIONAL{?b <uri:p4> ?o. ?o <uri:p1> ?p} . "//
                + "}";//

        final String query2 = ""//
                + "SELECT ?a ?b ?c ?d ?e ?f ?g ?h" //
                + "{" //
                + "  ?a <uri:p0> ?b ." //
                + "  OPTIONAL{?b <uri:p4> ?o. ?o <uri:p1> ?p} . "//
                + "  OPTIONAL{?b <uri:p4> ?g. ?g <uri:p1> ?h} . "//
                + "  OPTIONAL{?b <uri:p2> ?c. ?c <uri:p1> ?d} . " //
                + "  OPTIONAL{?b <uri:p4> ?i. ?i <uri:p1> ?j} . "//
                + "  OPTIONAL{?b <uri:p4> ?m. ?m <uri:p1> ?n} . "//
                + "  OPTIONAL{?b <uri:p4> ?k. ?k <uri:p1> ?l} . "//
                + "  OPTIONAL{?b <uri:p3> ?e. ?e <uri:p1> ?f} . "//
                + "}";//

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq1 = parser.parseQuery(query1, null);
        final ParsedQuery pq2 = parser.parseQuery(query2, null);
        final TupleExpr te1 = pq1.getTupleExpr();
        final TupleExpr te2 = pq2.getTupleExpr();

        final TupleExpr unOpt = te1.clone();

        final SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection) te2);
        final List<ExternalTupleSet> externalList = new ArrayList<>();
        externalList.add(pcj);

        provider.setIndices(externalList);
        final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
        optimizer.optimize(te1, null, null);

        Assert.assertEquals(true, validatePcj(te1, unOpt, externalList, new HashSet<QueryModelNode>()));
    }

    @Test
    public void testSubsetMatchLargeReOrdered() throws Exception {

        final String query1 = ""//
                + "SELECT ?a ?b ?c ?d ?e ?f ?g ?h" //
                + "{" //
                + "  ?a <uri:p0> ?b ." //
                + "  OPTIONAL{?b <uri:p2> ?c. ?c <uri:p1> ?d} . " //
                + "  OPTIONAL{?b <uri:p3> ?e. ?e <uri:p1> ?f} . "//
                + "  OPTIONAL{?b <uri:p4> ?g. ?g <uri:p1> ?h} . "//
                + "  OPTIONAL{?b <uri:p5> ?i. ?i <uri:p6> ?j} . "//
                + "  OPTIONAL{?b <uri:p5> ?k. ?k <uri:p6> ?l} . "//
                + "  OPTIONAL{?b <uri:p5> ?m. ?m <uri:p6> ?n} . "//
                + "  OPTIONAL{?b <uri:p4> ?o. ?o <uri:p1> ?p} . "//
                + "}";//

        final String query2 = ""//
                + "SELECT ?a ?b ?c ?d ?e ?f ?g ?h" //
                + "{" //
                + "  ?a <uri:p0> ?b ." //
                + "  OPTIONAL{?b <uri:p4> ?o. ?o <uri:p1> ?p} . "//
                + "  OPTIONAL{?b <uri:p4> ?g. ?g <uri:p1> ?h} . "//
                + "  OPTIONAL{?b <uri:p2> ?c. ?c <uri:p1> ?d} . " //
                + "  OPTIONAL{?b <uri:p3> ?e. ?e <uri:p1> ?f} . "//
                + "}";//

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq1 = parser.parseQuery(query1, null);
        final ParsedQuery pq2 = parser.parseQuery(query2, null);
        final TupleExpr te1 = pq1.getTupleExpr();
        final TupleExpr te2 = pq2.getTupleExpr();

        final TupleExpr unOpt = te1.clone();
        final List<QueryModelNode> remainingNodes = getNodes(te1);
        final Set<QueryModelNode> unMatchedNodes = new HashSet<>();
        unMatchedNodes.add(remainingNodes.get(8));
        unMatchedNodes.add(remainingNodes.get(9));
        unMatchedNodes.add(remainingNodes.get(10));
        unMatchedNodes.add(remainingNodes.get(11));
        unMatchedNodes.add(remainingNodes.get(12));
        unMatchedNodes.add(remainingNodes.get(7));

        final SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection) te2);
        final List<ExternalTupleSet> externalList = new ArrayList<>();
        externalList.add(pcj);

        provider.setIndices(externalList);
        final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
        optimizer.optimize(te1, null, null);

        Assert.assertEquals(true, validatePcj(te1, unOpt, externalList, unMatchedNodes));
    }

    @Test
    public void testSwitchTwoBoundVars() throws Exception {

        final String query1 = ""//
                + "SELECT ?a ?b ?c " //
                + "{" //
                + "  ?a <uri:p0> ?c ." //
                + "  ?c <uri:p5> <uri:o5> ." //
                + " OPTIONAL{?c <uri:p4> <uri:o4>} ."
                + " ?b<uri:p1> ?c ." //
                + " OPTIONAL{ ?a <uri:p1> ?b } ." //
                + " ?a <uri:p2> <uri:o2>. " //
                + " ?b <uri:p3> <uri:o3> " //
                + "}";//

        final String query2 = ""//
                + "SELECT ?a ?b ?c " //
                + "{" //
                + " ?a <uri:p2> <uri:o2>. " //
                + " ?b <uri:p3> <uri:o3>. " //
                + " OPTIONAL{ ?a <uri:p1> ?b } ." //
                + "  ?a <uri:p0> ?c ." //
                + "  ?b<uri:p1> ?c " //
                + "}";//

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq1 = parser.parseQuery(query1, null);
        final ParsedQuery pq2 = parser.parseQuery(query2, null);
        final TupleExpr te1 = pq1.getTupleExpr();
        final TupleExpr te2 = pq2.getTupleExpr();

        final TupleExpr unOpt = te1.clone();
        final List<QueryModelNode> remainingNodes = getNodes(te1);
        final Set<QueryModelNode> unMatchedNodes = new HashSet<>();
        unMatchedNodes.add(remainingNodes.get(1));
        unMatchedNodes.add(remainingNodes.get(2));

        final SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection) te2);
        final List<ExternalTupleSet> externalList = new ArrayList<>();
        externalList.add(pcj);

        provider.setIndices(externalList);
        final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
        optimizer.optimize(te1, null, null);

        Assert.assertEquals(true, validatePcj(te1, unOpt, externalList, unMatchedNodes));
    }

    @Test
    public void testSegmentWithLargeUnion() throws Exception {

        final String query1 = ""//
                + "SELECT ?e ?c ?l" //
                + "{" //
                + " {?e <uri:p1> <uri:o1>. } UNION { " //
                + "  ?e <uri:p0> ?l ." //
                + "  ?l <uri:p5> <uri:o5> ." //
                + " OPTIONAL{?l <uri:p4> <uri:o4>} ." + "  ?c<uri:p1> ?l ." //
                + " OPTIONAL{ ?e <uri:p1> ?c } ." //
                + " ?e <uri:p2> <uri:o2>. " //
                + " ?c <uri:p3> <uri:o3> " //
                + " }  . "//
                + "  ?e <uri:p2> ?c . "//
                + "  ?e <uri:p3> <uri:o2>  . "//
                + "}";//

        final String query2 = ""//
                + "SELECT ?a ?b ?c " //
                + "{" //
                + " ?a <uri:p2> <uri:o2>. " //
                + " ?b <uri:p3> <uri:o3>. " //
                + " OPTIONAL{ ?a <uri:p1> ?b } ." //
                + "  ?a <uri:p0> ?c ." //
                + "  ?b<uri:p1> ?c " //
                + "}";//

        final String query3 = ""//
                + "SELECT ?h ?i" //
                + "{" //
                + "  ?h <uri:p2> ?i . "//
                + "  ?h <uri:p3> <uri:o2>  . "//
                + "}";//

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq1 = parser.parseQuery(query1, null);
        final ParsedQuery pq2 = parser.parseQuery(query2, null);
        final ParsedQuery pq3 = parser.parseQuery(query3, null);
        final TupleExpr te1 = pq1.getTupleExpr();
        final TupleExpr te2 = pq2.getTupleExpr();
        final TupleExpr te3 = pq3.getTupleExpr();

        final TupleExpr unOpt = te1.clone();
        final List<QueryModelNode> remainingNodes = getNodes(te1);
        final Set<QueryModelNode> unMatchedNodes = new HashSet<>();
        unMatchedNodes.add(remainingNodes.get(0));
        unMatchedNodes.add(remainingNodes.get(2));
        unMatchedNodes.add(remainingNodes.get(3));

        final SimpleExternalTupleSet pcj1 = new SimpleExternalTupleSet((Projection) te2);
        final SimpleExternalTupleSet pcj2 = new SimpleExternalTupleSet((Projection) te3);
        final List<ExternalTupleSet> externalList = new ArrayList<>();
        externalList.add(pcj1);
        externalList.add(pcj2);

        provider.setIndices(externalList);
        final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
        optimizer.optimize(te1, null, null);

        Assert.assertEquals(true, validatePcj(te1, unOpt, externalList, unMatchedNodes));

    }

    @Test
    public void testSegmentWithUnionAndFilters() throws Exception {

        final String query1 = ""//
                + "SELECT ?e ?c ?l" //
                + "{" //
                + " Filter(?e = <uri:s1>) " //
                + " Filter(?c = <uri:s2>) " //
                + " {?e <uri:p1> <uri:o1>. } UNION { ?e a ?c. OPTIONAL {?e <uri:talksTo> ?l}. ?e <uri:p5> <uri:o4>. ?e <uri:p4> <uri:o3> }  . "//
                + "  ?e <uri:p2> ?c . "//
                + "  ?e <uri:p3> <uri:o2>  . "//
                + "}";//

        final String query2 = ""//
                + "SELECT ?a ?b ?m" //
                + "{" //
                + " Filter(?b = <uri:s2>) " //
                + " ?a <uri:p5> <uri:o4> ." //
                + " ?a <uri:p4> <uri:o3> ." //
                + "  OPTIONAL {?a <uri:talksTo> ?m} . "//
                + "  ?a a ?b . "//
                + "}";//

        final String query3 = ""//
                + "SELECT ?h ?i" //
                + "{" //
                + " Filter(?h = <uri:s1>) " //
                + "  ?h <uri:p2> ?i . "//
                + "  ?h <uri:p3> <uri:o2>  . "//
                + "}";//

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq1 = parser.parseQuery(query1, null);
        final ParsedQuery pq2 = parser.parseQuery(query2, null);
        final ParsedQuery pq3 = parser.parseQuery(query3, null);
        final TupleExpr te1 = pq1.getTupleExpr();
        final TupleExpr te2 = pq2.getTupleExpr();
        final TupleExpr te3 = pq3.getTupleExpr();

        final TupleExpr unOpt = te1.clone();
        final List<QueryModelNode> remainingNodes = getNodes(te1);
        final Set<QueryModelNode> unMatchedNodes = new HashSet<>();
        unMatchedNodes.add(remainingNodes.get(0));

        final SimpleExternalTupleSet pcj1 = new SimpleExternalTupleSet((Projection) te2);
        final SimpleExternalTupleSet pcj2 = new SimpleExternalTupleSet((Projection) te3);
        final List<ExternalTupleSet> externalList = new ArrayList<>();
        externalList.add(pcj1);
        externalList.add(pcj2);

        provider.setIndices(externalList);
        final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
        optimizer.optimize(te1, null, null);

        Assert.assertEquals(true, validatePcj(te1, unOpt, externalList, unMatchedNodes));

    }

    @Test
    public void testSegmentWithLeftJoinsAndFilters() throws Exception {

        final String query1 = ""//
                + "SELECT ?e ?c ?l" //
                + "{" //
                + " Filter(?e = <uri:s1>) " //
                + " Filter(?c = <uri:s2>) " //
                + " ?e <uri:p1> <uri:o1>. " + " OPTIONAL {?e <uri:p2> ?l}. " + " ?c <uri:p3> <uri:o3>  . "//
                + "  ?c <uri:p4> ?e  . "//
                + " OPTIONAL {?e <uri:p2> ?c } . "//
                + "}";//

        final String query2 = ""//
                + "SELECT ?e ?c ?l" //
                + "{" //
                + " Filter(?c = <uri:s2>) " //
                + " ?e <uri:p1> <uri:o1>. " + " OPTIONAL {?e <uri:p2> ?l}. " + " ?c <uri:p3> <uri:o3>  . "//
                + "}";//

        final String query3 = ""//
                + "SELECT ?e ?c" //
                + "{" //
                + " Filter(?e = <uri:s1>) " //
                + "  ?c <uri:p4> ?e  . "//
                + " OPTIONAL {?e <uri:p2> ?c } . "//
                + "}";//

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq1 = parser.parseQuery(query1, null);
        final ParsedQuery pq2 = parser.parseQuery(query2, null);
        final ParsedQuery pq3 = parser.parseQuery(query3, null);
        final TupleExpr te1 = pq1.getTupleExpr();
        final TupleExpr te2 = pq2.getTupleExpr();
        final TupleExpr te3 = pq3.getTupleExpr();

        final TupleExpr unOpt = te1.clone();

        final SimpleExternalTupleSet pcj1 = new SimpleExternalTupleSet((Projection) te2);
        final SimpleExternalTupleSet pcj2 = new SimpleExternalTupleSet((Projection) te3);
        final List<ExternalTupleSet> externalList = new ArrayList<>();
        externalList.add(pcj1);
        externalList.add(pcj2);

        provider.setIndices(externalList);
        final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
        optimizer.optimize(te1, null, null);

        Assert.assertEquals(true, validatePcj(te1, unOpt, externalList, new HashSet<QueryModelNode>()));
    }

    @Test
    public void testJoinMatcherRejectsLeftJoinPcj() throws Exception {

        final String query1 = ""//
                + "SELECT ?e ?c ?l" //
                + "{" //
                + "  ?e a ?c . "//
                + "  ?e <uri:talksTo> ?l . "//
                + "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l "//
                + "}";//

        final String query2 = ""//
                + "SELECT ?a ?b ?m" //
                + "{" //
                + "  ?a a ?b . "//
                + "  ?a <uri:talksTo> ?m . "//
                + "  OPTIONAL {?a <http://www.w3.org/2000/01/rdf-schema#label> ?m}  . "//
                + "}";//

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq1 = parser.parseQuery(query1, null);
        final ParsedQuery pq2 = parser.parseQuery(query2, null);
        final TupleExpr te1 = pq1.getTupleExpr();
        final TupleExpr te2 = pq2.getTupleExpr();
        final TupleExpr expected = te1.clone();

        final SimpleExternalTupleSet pcj = new SimpleExternalTupleSet((Projection) te2);
        final List<ExternalTupleSet> externalList = new ArrayList<>();
        externalList.add(pcj);

        provider.setIndices(externalList);
        final PCJOptimizer optimizer = new PCJOptimizer(externalList, false, provider);
        optimizer.optimize(te1, null, null);
        Assert.assertEquals(expected, te1);

    }

    private List<QueryModelNode> getNodes(final TupleExpr te) {
        final NodeCollector collector = new NodeCollector();
        te.visit(collector);
        return collector.getNodes();
    }

    private boolean validatePcj(final TupleExpr optTupleExp, final TupleExpr unOptTup, final List<ExternalTupleSet> pcjs, final Set<QueryModelNode> expUnmatchedNodes) {

        final IndexedExecutionPlanGenerator iep = new IndexedExecutionPlanGenerator(
                unOptTup, pcjs);
        final List<ExternalTupleSet> indexList = iep.getNormalizedIndices();
        final Set<QueryModelNode> indexSet = new HashSet<>();
        for(final ExternalTupleSet etup: indexList) {
            indexSet.add(etup);
        }

        final Set<QueryModelNode> tupNodes = Sets.newHashSet(getNodes(optTupleExp));

        final Set<QueryModelNode> diff =  Sets.difference(tupNodes, indexSet);
        return diff.equals(expUnmatchedNodes);
    }

    public static class NodeCollector extends AbstractQueryModelVisitor<RuntimeException> {

        List<QueryModelNode> qNodes = new ArrayList<>();

        @Override
        public void meetNode(final QueryModelNode node) {
            if (node instanceof StatementPattern || node instanceof ExternalTupleSet) {
                qNodes.add(node);
            }
            super.meetNode(node);

        }

        public List<QueryModelNode> getNodes() {
            return qNodes;
        }

    }

}


text:
<?php

namespace Treffynnon\Navigator;

use Treffynnon\Navigator as N;

/**
 * A representation of a latitude and longitude coordinate
 */
class LatLong {

    /**
     * Latitude coordinate store
     * @var Coordinate
     */
    protected $latitude = null;

    /**
     * Longitude coordinate store
     * @var Coordinate
     */
    protected $longitude = null;

    /**
     * Setup a new LatLng instance by passing in the latitude and longitude
     * @param Coordinate $latitude
     * @param Coordinate $longitude
     */
    public function __construct(Coordinate $latitude, Coordinate $longitude) {
        $this->latitude = $latitude;
        $this->longitude = $longitude;
        $this->primeCoordinateParsers();
    }

    /**
     * Prime the coordinate parser with any additional information
     * necessary
     */
    protected function primeCoordinateParsers() {
        $this->latitude->getParser()->setDirection(N::LAT);
        $this->longitude->getParser()->setDirection(N::LONG);
    }

    /**
     * Get the latitude coordinate object
     * @return Coordinate
     */
    public function getLatitude() {
        return $this->latitude;
    }

    /**
     * Get the longitude coordinate object
     * @return Coordinate
     */
    public function getLongitude() {
        return $this->longitude;
    }

    /**
     * Get string representation
     * @return string
     */
    public function __toString() {
        return $this->getLatitude() . ',' . $this->getLongitude();
    }

    /**
     * Create a LatLong object based on a comma separated coordinates string (latitude, longitude)
     *
     * @param  string $string
     * @return LatLong
     */
    public static function createFromString($string) {
        list($latitude, $longitude) = explode(',', $string);
        return new static(new Coordinate($latitude), new Coordinate($longitude));
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace PeinearyDevelopment.Framework.Filtering.FilterCriteria.Nullables.Sets
{
  using FilterTypes;

  using System;
  using System.Collections.Generic;
  using System.Data.SqlClient;
  using System.Linq;
  using System.Linq.Expressions;

  public abstract class NullableSetCriterionBase<TFilterable, TFilterableProperty> : BaseCriterion<TFilterable, TFilterableProperty, SetFilterType, IEnumerable<TFilterableProperty>> where TFilterable : class, IFilterable
  {
    protected NullableSetCriterionBase()
    {
    }

    protected NullableSetCriterionBase(string propertyName, SetFilterType filterType, IEnumerable<TFilterableProperty> filterValue) : base(propertyName, filterType, filterValue)
    {
    }

    protected NullableSetCriterionBase(Expression<Func<TFilterable, TFilterableProperty>> propertyNameExpression, SetFilterType filterType, IEnumerable<TFilterableProperty> filterValue) : base(propertyNameExpression, filterType, filterValue)
    {
    }

    internal override string CreateWhere(IDictionary<string, string> objectPropertyToColumnNameMapper, int parameterIndex)
    {
      if (objectPropertyToColumnNameMapper == null) throw new ArgumentNullException(nameof(objectPropertyToColumnNameMapper));
      if (FilterType == SetFilterType.Between && FilterValue.Count() != 2) throw new ArgumentOutOfRangeException(nameof(objectPropertyToColumnNameMapper), "The 'Between' search type may only be used with exactly 2 values.");

      var columnName = objectPropertyToColumnNameMapper[PropertyName];
      var parametersString = FilterType == SetFilterType.Between ? $"@p{parameterIndex++} AND @p{parameterIndex++}" : string.Join(", ", FilterValue.Select(value => $"@p{parameterIndex++}"));

      switch (FilterType)
      {
        case SetFilterType.In:
          return $"[{columnName}] IN ({parametersString})";
        case SetFilterType.Between:
          return $"[{columnName}] BETWEEN {parametersString}";
        case SetFilterType.NotIn:
          return $"[{columnName}] NOT IN ({parametersString})";
        default:
          throw new NotImplementedException();
      }
    }

    internal override IEnumerable<SqlParameter> CreateParameters(int startingParameterIndex)
    {
      return FilterValue.Select(value => new SqlParameter($"p{startingParameterIndex++}", value));
    }
  }
}


text:
<?php

namespace Molajo\IoC;

use PHPUnit_Framework_TestCase;

/**
 * Factory Method Namespace Test
 *
 * @package    Molajo
 * @copyright  2014-2015 Amy Stephen. All rights reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @since      1.0.0
 */
class NamespaceTest extends PHPUnit_Framework_TestCase
{
    /**
     * Pass in Full namespace
     *
     * @covers  Molajo\IoC\Product\SetNamespace::__construct
     * @covers  Molajo\IoC\Product\SetNamespace::get
     * @covers  Molajo\IoC\Product\SetNamespace::processNamespaceOptions
     * @covers  Molajo\IoC\Product\SetNamespace::getFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::testFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::getFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::checkClassExists
     * @covers  Molajo\IoC\Product\SetNamespace::getLastFolder
     *
     * @return  void
     * @since   1.0.0
     */
    public function testPassInNamespaceFull()
    {
        $options                  = array();
        $options['product_name']  = 'Dispatcher';
        $options['container_key'] = 'Molajo\\Factories\\Dispatcher';
        $options['ioc_id']        = 1;
        $options['factory_method_namespace']
                                  = $options['container_key'] . '\\' . 'DispatcherFactoryMethod';

        $standard_adapter_namespace = 'Molajo\\IoC\\FactoryMethod\\Standard';

        $class                    = 'Molajo\\IoC\\Product\\SetNamespace';
        $factory_method_namespace = new $class($standard_adapter_namespace);

        $this->assertEquals($factory_method_namespace->get($options), $options);
    }

    /**
     * Pass in namespace
     *
     * @covers  Molajo\IoC\Product\SetNamespace::__construct
     * @covers  Molajo\IoC\Product\SetNamespace::get
     * @covers  Molajo\IoC\Product\SetNamespace::processNamespaceOptions
     * @covers  Molajo\IoC\Product\SetNamespace::getFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::testFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::getFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::checkClassExists
     * @covers  Molajo\IoC\Product\SetNamespace::getLastFolder
     *
     * @return  void
     * @since   1.0.0
     */
    public function testPassInNamespacePlus()
    {
        $options                             = array();
        $options['product_name']             = 'Dispatcher';
        $options['container_key']            = 'Molajo\\Factories\\Dispatcher';
        $options['ioc_id']                   = 1;
        $options['factory_method_namespace'] = $options['container_key'];

        $standard_adapter_namespace = 'Molajo\\IoC\\FactoryMethod\\Standard';

        $class                    = 'Molajo\\IoC\\Product\\SetNamespace';
        $factory_method_namespace = new $class($standard_adapter_namespace);

        $options['factory_method_namespace'] .= '\\DispatcherFactoryMethod';

        $this->assertEquals($factory_method_namespace->get($options), $options);
    }

    /**
     * Test product name as namespace + folder + 'FactoryMethod'
     *
     * @covers  Molajo\IoC\Product\SetNamespace::__construct
     * @covers  Molajo\IoC\Product\SetNamespace::get
     * @covers  Molajo\IoC\Product\SetNamespace::processNamespaceOptions
     * @covers  Molajo\IoC\Product\SetNamespace::getFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::testFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::getFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::checkClassExists
     * @covers  Molajo\IoC\Product\SetNamespace::getLastFolder
     *
     * @return  void
     * @since   1.0.0
     */
    public function testProductNamePlus()
    {
        $options                    = array();
        $options['product_name']    = 'Molajo\\Factories\\Dispatcher';
        $options['ioc_id']          = 1;
        $standard_adapter_namespace = 'Molajo\\IoC\\FactoryMethod\\Standard';

        $class                    = 'Molajo\\IoC\\Product\\SetNamespace';
        $factory_method_namespace = new $class($standard_adapter_namespace);

        $options['factory_method_namespace']
            = $options['product_name'] . '\\' . 'DispatcherFactoryMethod';

        $this->assertEquals($factory_method_namespace->get($options), $options);
    }

    /**
     * Test container_key as namespace  + folder + 'FactoryMethod'
     *
     * @covers  Molajo\IoC\Product\SetNamespace::__construct
     * @covers  Molajo\IoC\Product\SetNamespace::get
     * @covers  Molajo\IoC\Product\SetNamespace::processNamespaceOptions
     * @covers  Molajo\IoC\Product\SetNamespace::getFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::testFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::getFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::checkClassExists
     * @covers  Molajo\IoC\Product\SetNamespace::getLastFolder
     *
     * @return  void
     * @since   1.0.0
     */
    public function testContainerKeyNamespace()
    {
        $options                    = array();
        $options['product_name']    = 'Dispatcher';
        $options['container_key']   = 'Molajo\\Factories\\Dispatcher';
        $options['ioc_id']          = 1;
        $standard_adapter_namespace = 'Molajo\\IoC\\FactoryMethod\\Standard';

        $class                    = 'Molajo\\IoC\\Product\\SetNamespace';
        $factory_method_namespace = new $class($standard_adapter_namespace);

        $options['factory_method_namespace']
            = $options['container_key'] . '\\' . $options['product_name'] . 'FactoryMethod';

        $this->assertEquals($factory_method_namespace->get($options), $options);
    }

    /**
     * No namespace
     *
     * @covers  Molajo\IoC\Product\SetNamespace::__construct
     * @covers  Molajo\IoC\Product\SetNamespace::get
     * @covers  Molajo\IoC\Product\SetNamespace::processNamespaceOptions
     * @covers  Molajo\IoC\Product\SetNamespace::getFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::testFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::getFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::checkClassExists
     * @covers  Molajo\IoC\Product\SetNamespace::getLastFolder
     *
     * @return  void
     * @since   1.0.0
     */
    public function testNoNamespace()
    {
        $options                             = array();
        $options['product_name']             = 'Whoknows';
        $options['container_key']            = 'Whoknows';
        $options['ioc_id']                   = 1;
        $options['factory_method_namespace'] = null;
        $options['product_namespace']        = 'Molajo\\Who\\Whoknows';

        $standard_adapter_namespace = 'Molajo\\IoC\\FactoryMethod\\Standard';

        $class                    = 'Molajo\\IoC\\Product\\SetNamespace';
        $factory_method_namespace = new $class($standard_adapter_namespace);

        $options['factory_method_namespace'] = $standard_adapter_namespace;

        $this->assertEquals($factory_method_namespace->get($options), $options);
    }

    /**
     * No default namespace
     *
     * @covers  Molajo\IoC\Product\SetNamespace::__construct
     * @covers  Molajo\IoC\Product\SetNamespace::get
     * @covers  Molajo\IoC\Product\SetNamespace::processNamespaceOptions
     * @covers  Molajo\IoC\Product\SetNamespace::getFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::testFactoryNamespaceFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::getFolderFile
     * @covers  Molajo\IoC\Product\SetNamespace::checkClassExists
     * @covers  Molajo\IoC\Product\SetNamespace::getLastFolder
     *
     * @return  void
     * @since   1.0.0
     */
    public function testNoDefaultNamespace()
    {
        $options                             = array();
        $options['product_name']             = 'Whoknows';
        $options['container_key']            = 'Whoknows';
        $options['ioc_id']                   = 1;
        $options['factory_method_namespace'] = null;
        $options['product_namespace']        = 'Molajo\\Who\\Whoknows';

        $standard_adapter_namespace = null;

        $class                    = 'Molajo\\IoC\\Product\\SetNamespace';
        $factory_method_namespace = new $class($standard_adapter_namespace);

        $options['factory_method_namespace'] = 'Molajo\IoC\FactoryMethod\Standard';

        $this->assertEquals($factory_method_namespace->get($options), $options);
    }
}


text:
package org.apache.shardingsphere.scaling.distsql.handler;

import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
import org.apache.shardingsphere.scaling.distsql.statement.ShowScalingCheckAlgorithmsStatement;
import org.apache.shardingsphere.scaling.distsql.util.PipelineContextUtil;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

@RunWith(MockitoJUnitRunner.class)
public final class ShowScalingCheckAlgorithmsQueryResultSetTest {

    @Mock
    private ShardingSphereMetaData shardingSphereMetaData;

    @Mock
    private ShowScalingCheckAlgorithmsStatement showScalingCheckAlgorithmsStatement;

    @BeforeClass
    public static void beforeClass() {
        PipelineContextUtil.mockModeConfig();
    }

    @Test
    public void assertGetRowData() {
        ShowScalingCheckAlgorithmsQueryResultSet resultSet = new ShowScalingCheckAlgorithmsQueryResultSet();
        resultSet.init(shardingSphereMetaData, showScalingCheckAlgorithmsStatement);
        Set<Object> algorithmTypes = new LinkedHashSet<>();
        while (resultSet.next()) {
            Collection<Object> actual = resultSet.getRowData();
            assertThat(actual.size(), is(4));
            Iterator<Object> rowData = actual.iterator();
            algorithmTypes.add(rowData.next());
        }
        assertTrue(algorithmTypes.contains("DATA_MATCH"));
        assertTrue(algorithmTypes.contains("CRC32_MATCH"));
    }
}


text:
package recursion.tree.generate;

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

import algorithms.structures.BinaryTree;
import algorithms.structures.BinaryTree.TreeNode;

public class Solution1
{
	@SuppressWarnings("unchecked")
	public static List<BinaryTree<String>> getBinaryTrees(int totalNodes)
	{
		List<BinaryTree<String>.TreeNode> roots = generateBinaryTrees(totalNodes);

		List<BinaryTree<String>> result = new ArrayList<BinaryTree<String>>();

		for (@SuppressWarnings("rawtypes") TreeNode root : roots)
		{
			BinaryTree<String> tree = new BinaryTree<>();
			tree.makeRoot(root);
			result.add(tree);
		}

		return result;
	}

	/**
	 * Generates all possible binary trees with the specified number of nodes
	 *
	 * @param totalNodes number of nodes
	 * @return list of all valid binary trees
	 *
	 * @time O(2n!/n!(n+1)!)
	 * @space O(2n!/n!(n+1)!)
	 *
	 * @see Catalan Numbers
	 **/
	public static List<BinaryTree<String>.TreeNode> generateBinaryTrees(int totalNodes)
	{
		List<BinaryTree<String>.TreeNode> result = new ArrayList<BinaryTree<String>.TreeNode>();

		if (totalNodes == 1)
		{
			BinaryTree<String>.TreeNode root = new BinaryTree<String>().new TreeNode();
			root.setData("x");
			result.add(root);
		}
		else
		{
			for (int leftNodes = 0; leftNodes < totalNodes; leftNodes++)
			{
				int rightNodes = totalNodes - leftNodes - 1;

				List<BinaryTree<String>.TreeNode> leftSubtrees = generateBinaryTrees(leftNodes);
				List<BinaryTree<String>.TreeNode> rightSubtrees = generateBinaryTrees(rightNodes);

//				List<BinaryTree<String>.TreeNode> maxSubtree = leftSubtrees.size() > rightSubtrees.size() ? leftSubtrees : rightSubtrees;
//				List<BinaryTree<String>.TreeNode> minSubtree = leftSubtrees.size() <= rightSubtrees.size() ? leftSubtrees : rightSubtrees;

				for (BinaryTree<String>.TreeNode right : rightSubtrees)
				{
					for (BinaryTree<String>.TreeNode left : leftSubtrees)
					{
						BinaryTree<String>.TreeNode root = new BinaryTree<String>().new TreeNode();
						root.setData("x");

						if (left != null)
						{
							root.setLeft(left);
						}

						if (right != null)
						{
							root.setRight(right);
						}

						result.add(root);
					}
				}
			}
		}

		return result;
	}
}


text:
package com.xinyu.mwp.activity.base;

import android.content.Context;
import android.view.View;

import com.xinyu.mwp.listener.OnRefreshListener;
import com.xinyu.mwp.util.DisplayUtil;
import com.xinyu.mwp.R;

import org.xutils.view.annotation.ViewInject;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;

/**
 * Created by yaowang on 16/3/30.
 */
public class RefreshController<TContentView extends View> extends BaseController implements PtrHandler {

    @ViewInject(R.id.refreshFrameLayout)
    protected PtrFrameLayout refreshFrameLayout;
    @ViewInject(R.id.contentView)
    protected TContentView contentView;
    private OnRefreshListener onRefreshListener;
    private boolean isAutoPullDownRefresh = true;

    /**
     * 设置下拉刷新监听
     *
     * @param onRefreshListener
     */
    public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
        this.onRefreshListener = onRefreshListener;
    }

    public RefreshController(Context context) {
        super(context);
    }

    /**
     * 设置是否启用下拉刷新
     *
     * @param enabled
     */
    public void setPullDownRefreshEnabled(boolean enabled) {
        refreshFrameLayout.setEnabled(enabled);
    }

    /**
     * 设置是否生命周期initData自动下拉刷新
     *
     * @param autoPullDownRefresh
     */
    public void setAutoPullDownRefresh(boolean autoPullDownRefresh) {
        isAutoPullDownRefresh = autoPullDownRefresh;
    }

    @Override
    public void initView() {
        super.initView();
        if (refreshFrameLayout != null) {
            refreshFrameLayout.setHeaderView(getHeaderView());
            refreshFrameLayout.setPtrHandler(this);
            refreshFrameLayout.setResistance(1.7f);
            refreshFrameLayout.setRatioOfHeaderHeightToRefresh(1.2f);
            refreshFrameLayout.setDurationToClose(200);
            refreshFrameLayout.setDurationToCloseHeader(100);
            refreshFrameLayout.setPullToRefresh(false);
            refreshFrameLayout.setKeepHeaderWhenRefresh(true);
        }
    }

    @Override
    public void initListener() {
        super.initListener();
    }

    @Override
    public void initData() {
        super.initData();
        if (isAutoPullDownRefresh) {
            refreshBegin();
        }
    }

    /**
     * check刷新位置
     */
    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, contentView, header);
    }

    /**
     * 开发刷新
     */
    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        onRefreshBegin();
    }

    /**
     * 开发刷新
     */
    protected void onRefreshBegin() {
        if (onRefreshListener != null)
            onRefreshListener.onRefresh();
    }

    /**
     * 手动调用下拉刷新
     */
    public void refreshBegin() {
        if (refreshFrameLayout != null) {
            refreshFrameLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    refreshFrameLayout.autoRefresh(true, 500);
                }
            }, 200);
        }

    }

    /**
     * 刷新完成
     */
    public void refreshComplete() {
        if (refreshFrameLayout != null) {
            refreshFrameLayout.refreshComplete();
        }
    }

    /**
     * 刷新错误
     *
     * @param ex
     */
    public void refreshError(Throwable ex) {
        refreshComplete();
    }

    /**
     * 下接刷新样式view
     *
     * @return
     */
    protected View getHeaderView() {
        MaterialHeader header = new MaterialHeader(context);
        int colors[] = context.getResources().getIntArray(R.array.google_colors);
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPadding(0, DisplayUtil.dip2px(15, context), 0, DisplayUtil.dip2px(10, context));
        header.setPtrFrameLayout(refreshFrameLayout);
        refreshFrameLayout.addPtrUIHandler(header);
        refreshFrameLayout.setPinContent(true);
        return header;
    }

    /**
     * 下接刷新显示的ContentView
     *
     * @return
     */
    public TContentView getContentView() {
        return contentView;
    }

}


text:
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Web;
using Rainbow.Framework.Design;
using Rainbow.Framework;
using Rainbow.Framework.Configuration;
using Rainbow.Framework.Site.Configuration;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Settings.Cache;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Web.UI.WebControls;
using Path = Rainbow.Framework.Settings.Path;

namespace Rainbow.Framework.Site.Configuration
{
	/// <summary>
	/// PageSettings Class encapsulates the detailed settings
	/// for a specific Page in the Portal
	/// </summary>
	public class PageSettings
	{
		/// <summary>
		///
		/// </summary>
		public string AuthorizedRoles;

		/// <summary>
		///
		/// </summary>
		public string MobilePageName;

		/// <summary>
		///
		/// </summary>
		public ArrayList Modules = new ArrayList();

		/// <summary>
		///
		/// </summary>
		public int ParentPageID;

		/// <summary>
		///
		/// </summary>
		public bool ShowMobile;

		/// <summary>
		///
		/// </summary>
		public int PageID;

		/// <summary>
		///
		/// </summary>
		public string PageLayout;

		/// <summary>
		///
		/// </summary>
		public int PageOrder;

		/// <summary>
		///
		/// </summary>
		private PortalSettings _portalSettings;

		/// <summary>
		///
		/// </summary>
		private Hashtable customSettings;

		/// <summary>
		///
		/// </summary>
		private string m_tabName;

		// Jes1111
		//		public int			TemplateId;
		/// <remarks>
		/// thierry (tiptopweb)
		/// to have dropdown list for the themes and layout, we need the data path for the portal (for private theme and layout)
		/// we need the portalPath here for this use and it has to be set from the current portalSettings before getting the
		/// CustomSettings for a tab
		/// </remarks>
		private string portalPath = null;

        /// <summary>
        /// The PageSettings.GetPageCustomSettings Method returns a hashtable of
        /// custom Page specific settings from the database. This method is
        /// used by Portals to access misc Page settings.
        /// </summary>
        /// <param name="pageID">The page ID.</param>
        /// <returns></returns>
		public Hashtable GetPageCustomSettings(int pageID)
		{
			Hashtable _baseSettings;

			if (!CurrentCache.Exists(Key.TabSettings(pageID)))
			{
				_baseSettings = GetPageBaseSettings();
				// Get Settings for this Page from the database
				Hashtable _settings = new Hashtable();

				// Create Instance of Connection and Command Object
				using (SqlConnection myConnection = Config.SqlConnectionString)
				{
					using (SqlCommand myCommand = new SqlCommand("rb_GetTabCustomSettings", myConnection))
					{
						// Mark the Command as a SPROC
						myCommand.CommandType = CommandType.StoredProcedure;
						// Add Parameters to SPROC
						SqlParameter parameterPageID = new SqlParameter("@TabID", SqlDbType.Int, 4);
						parameterPageID.Value = pageID;
						myCommand.Parameters.Add(parameterPageID);
						// Execute the command
						myConnection.Open();
						SqlDataReader dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

						try
						{
							while (dr.Read())
							{
								_settings[dr["SettingName"].ToString()] = dr["SettingValue"].ToString();
							}
						}

						finally
						{
							dr.Close(); //by Manu, fixed bug 807858
							myConnection.Close();
						}
					}
				}

				// Thierry (Tiptopweb)
				// TODO : put back the cache in GetPageBaseSettings() and reset values not found in the database
				foreach (string key in _baseSettings.Keys)
				{
					if (_settings[key] != null)
					{
						SettingItem s = ((SettingItem)_baseSettings[key]);

						if (_settings[key].ToString().Length != 0)
							s.Value = _settings[key].ToString();
					}

					else //by Manu
					// Thierry (Tiptopweb), see the comment in Hashtable GetPageBaseSettings()
					// this is not resetting key not found in the database
					{
						SettingItem s = ((SettingItem)_baseSettings[key]);
						//s.Value = string.Empty; 3_aug_2004 Cory Isakson.  This line caused an error with booleans
					}
				}
				CurrentCache.Insert(Key.TabSettings(pageID), _baseSettings);
			}

			else
			{
				_baseSettings = (Hashtable)CurrentCache.Get(Key.TabSettings(pageID));
			}
			return _baseSettings;
		}

        /// <summary>
        /// Read Current Page subtabs
        /// </summary>
        /// <param name="PageID">The page ID.</param>
        /// <returns></returns>
		[Obsolete("Replace me and move to DAL")]
		public static SqlDataReader GetPageSettings(int PageID)
		{
			// Create Instance of Connection and Command Object
			using (SqlConnection myConnection = Config.SqlConnectionString)
			{
				using (SqlCommand myCommand = new SqlCommand("rb_GetTabSettings", myConnection))
				{
					// Mark the Command as a SPROC
					myCommand.CommandType = CommandType.StoredProcedure;
					//PageID passed type FIXED by Bill Anderson (reedtek)
					//see: http://sourceforge.net/tracker/index.php?func=detail&aid=813789&group_id=66837&atid=515929
					// Add Parameters to SPROC
					SqlParameter parameterPageID = new SqlParameter("@TabID", SqlDbType.Int);
					parameterPageID.Value = PageID;
					myCommand.Parameters.Add(parameterPageID);
					// The new paramater "PortalLanguage" has been added to sp rb_GetPageSettings
					// Onur Esnaf
					SqlParameter parameterPortalLanguage = new SqlParameter("@PortalLanguage", SqlDbType.NVarChar, 12);
					parameterPortalLanguage.Value = Thread.CurrentThread.CurrentUICulture.Name;
					myCommand.Parameters.Add(parameterPortalLanguage);
					// Open the database connection and execute the command
					myConnection.Open();
					SqlDataReader dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
					return dr;
				}
			}
		}

        /// <summary>
        /// Read Current Page subtabs
        /// </summary>
        /// <param name="PageID">The page ID.</param>
        /// <returns>PagesBox</returns>
        public static PagesBox GetPageSettingsPagesBox(int PageID)
		{
			// Create Instance of Connection and Command Object
			using (SqlConnection myConnection = Config.SqlConnectionString)
			{
				using (SqlCommand myCommand = new SqlCommand("rb_GetTabSettings", myConnection))
				{
					// Mark the Command as a SPROC
					myCommand.CommandType = CommandType.StoredProcedure;
					//PageID passed type FIXED by Bill Anderson (reedtek)
					//see: http://sourceforge.net/tracker/index.php?func=detail&aid=813789&group_id=66837&atid=515929
					// Add Parameters to SPROC
					SqlParameter parameterPageID = new SqlParameter("@PageID", SqlDbType.Int);
					parameterPageID.Value = PageID;
					myCommand.Parameters.Add(parameterPageID);
					// The new paramater "PortalLanguage" has been added to sp rb_GetPageSettings
					// Onur Esnaf
					SqlParameter parameterPortalLanguage = new SqlParameter("@PortalLanguage", SqlDbType.NVarChar, 12);
					parameterPortalLanguage.Value = Thread.CurrentThread.CurrentUICulture.Name;
					myCommand.Parameters.Add(parameterPortalLanguage);
					// Open the database connection and execute the command
					myConnection.Open();

					using (SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection))
					{
						PagesBox tabs = new PagesBox();

						try
						{
							while (result.Read())
							{
								PageStripDetails tabDetails = new PageStripDetails();
								tabDetails.PageID = (int)result["PageID"];
								Hashtable cts = new PageSettings().GetPageCustomSettings(tabDetails.PageID);
								tabDetails.PageImage = cts["CustomMenuImage"].ToString();
								tabDetails.ParentPageID = Int32.Parse("0" + result["ParentPageID"]);
								tabDetails.PageName = (string)result["PageName"];
								tabDetails.PageOrder = (int)result["PageOrder"];
								tabDetails.AuthorizedRoles = (string)result["AuthorizedRoles"];
								tabs.Add(tabDetails);
							}
						}

						finally
						{
							result.Close(); //by Manu, fixed bug 807858
						}
						return tabs;
					}
				}
			}
		}

		/// <summary>
		/// Update Page Custom Settings
		/// </summary>
		/// <param name="pageID">The page ID.</param>
		/// <param name="key">The key.</param>
		/// <param name="value">The value.</param>
		public static void UpdatePageSettings(int pageID, string key, string value)
		{
			// Create Instance of Connection and Command Object
			using (SqlConnection myConnection = Config.SqlConnectionString)
			{
				using (SqlCommand myCommand = new SqlCommand("rb_UpdateTabCustomSettings", myConnection))
				{
					// Mark the Command as a SPROC
					myCommand.CommandType = CommandType.StoredProcedure;
					// Add Parameters to SPROC
					SqlParameter parameterPageID = new SqlParameter("@TabID", SqlDbType.Int, 4);
					parameterPageID.Value = pageID;
					myCommand.Parameters.Add(parameterPageID);
					SqlParameter parameterKey = new SqlParameter("@SettingName", SqlDbType.NVarChar, 50);
					parameterKey.Value = key;
					myCommand.Parameters.Add(parameterKey);
					SqlParameter parameterValue = new SqlParameter("@SettingValue", SqlDbType.NVarChar, 1500);
					parameterValue.Value = value;
					myCommand.Parameters.Add(parameterValue);
					myConnection.Open();

					try
					{
						myCommand.ExecuteNonQuery();
					}

					finally
					{
						myConnection.Close();
					}
				}
			}

			//Invalidate cache
			if (CurrentCache.Exists(Key.TabSettings(pageID)))
				CurrentCache.Remove(Key.TabSettings(pageID));

			// Clear url builder elements
			HttpUrlBuilder.Clear(pageID);
		}

		/// <summary>
		/// Gets the image menu.
		/// </summary>
		/// <returns>A System.Collections.Hashtable value...</returns>
		private Hashtable GetImageMenu()
		{
			Hashtable imageMenuFiles;

			if (!CurrentCache.Exists(Key.ImageMenuList(portalSettings.CurrentLayout)))
			{
				imageMenuFiles = new Hashtable();
				imageMenuFiles.Add("-Default-", string.Empty);
				string menuDirectory = string.Empty;
				LayoutManager layoutManager = new LayoutManager(PortalPath);

				menuDirectory = Path.WebPathCombine(layoutManager.PortalLayoutPath, portalSettings.CurrentLayout);
				if (Directory.Exists(menuDirectory))
				{
					menuDirectory = Path.WebPathCombine(menuDirectory, "menuimages");
				}
				else
				{
					menuDirectory = Path.WebPathCombine(LayoutManager.Path, portalSettings.CurrentLayout, "menuimages");
				}

				if (Directory.Exists(menuDirectory))
				{
					FileInfo[] menuImages = (new DirectoryInfo(menuDirectory)).GetFiles("*.gif");

					foreach (FileInfo fi in menuImages)
					{
						if (fi.Name != "spacer.gif" && fi.Name != "icon_arrow.gif")
							imageMenuFiles.Add(fi.Name, fi.Name);
					}
				}
				CurrentCache.Insert(Key.ImageMenuList(portalSettings.CurrentLayout), imageMenuFiles, null);
			}
			else
			{
				imageMenuFiles = (Hashtable)CurrentCache.Get(Key.ImageMenuList(portalSettings.CurrentLayout));
			}
			return imageMenuFiles;
		}

		/// <summary>
		/// Changed by Thierry@tiptopweb.com.au
		/// Page are different for custom page layout an theme, this cannot be static
		/// Added by john.mandia@whitelightsolutions.com
		/// Cache by Manu
		/// non static function, Thierry : this is necessary for page custom layout and themes
		/// </summary>
		/// <returns>A System.Collections.Hashtable value...</returns>
		private Hashtable GetPageBaseSettings()
		{
			//Define base settings
			Hashtable _baseSettings = new Hashtable();
			int _groupOrderBase;
			SettingItemGroup _Group;

			#region Navigation Settings

			// 2_aug_2004 Cory Isakson
			_groupOrderBase = (int)SettingItemGroup.NAVIGATION_SETTINGS;
			_Group = SettingItemGroup.NAVIGATION_SETTINGS;

			SettingItem TabPlaceholder = new SettingItem(new BooleanDataType());
			TabPlaceholder.Group = _Group;
			TabPlaceholder.Order = _groupOrderBase;
			TabPlaceholder.Value = "False";
			TabPlaceholder.EnglishName = "Act as a Placeholder?";
			TabPlaceholder.Description = "Allows this tab to act as a navigation placeholder only.";
			_baseSettings.Add("TabPlaceholder", TabPlaceholder);

			SettingItem TabLink = new SettingItem(new StringDataType());
			TabLink.Group = _Group;
			TabLink.Value = string.Empty;
			TabLink.Order = _groupOrderBase + 1;
			TabLink.EnglishName = "Static Link URL";
			TabLink.Description = "Allows this tab to act as a navigation link to any URL.";
			_baseSettings.Add("TabLink", TabLink);

			SettingItem TabUrlKeyword = new SettingItem(new StringDataType());
			TabUrlKeyword.Group = _Group;
			TabUrlKeyword.Order = _groupOrderBase + 2;
			TabUrlKeyword.EnglishName = "Url Keyword";
			TabUrlKeyword.Description = "Allows you to specify a keyword that would appear in your url.";
			_baseSettings.Add("TabUrlKeyword", TabUrlKeyword);

			SettingItem UrlPageName = new SettingItem(new StringDataType());
			UrlPageName.Group = _Group;
			UrlPageName.Order = _groupOrderBase + 3;
			UrlPageName.EnglishName = "Url Page Name";
			UrlPageName.Description = "This setting allows you to specify a name for this tab that will show up in the url instead of default.aspx";
			_baseSettings.Add("UrlPageName", UrlPageName);

			#endregion

			#region Metadata Management

			_groupOrderBase = (int)SettingItemGroup.META_SETTINGS;
			_Group = SettingItemGroup.META_SETTINGS;
			SettingItem TabTitle = new SettingItem(new StringDataType());
			TabTitle.Group = _Group;
			TabTitle.EnglishName = "Tab / Page Title";
			TabTitle.Description = "Allows you to enter a title (Shows at the top of your browser) for this specific Tab / Page. Enter something here to override the default portal wide setting.";
			_baseSettings.Add("TabTitle", TabTitle);

			SettingItem TabMetaKeyWords = new SettingItem(new StringDataType());
			TabMetaKeyWords.Group = _Group;
			TabMetaKeyWords.EnglishName = "Tab / Page Keywords";
			TabMetaKeyWords.Description = "This setting is to help with search engine optimisation. Enter 1-15 Default Keywords that represent what this Tab / Page is about.Enter something here to override the default portal wide setting.";
			_baseSettings.Add("TabMetaKeyWords", TabMetaKeyWords);
			SettingItem TabMetaDescription = new SettingItem(new StringDataType());
			TabMetaDescription.Group = _Group;
			TabMetaDescription.EnglishName = "Tab / Page Description";
			TabMetaDescription.Description = "This setting is to help with search engine optimisation. Enter a description (Not too long though. 1 paragraph is enough) that describes this particular Tab / Page. Enter something here to override the default portal wide setting.";
			_baseSettings.Add("TabMetaDescription", TabMetaDescription);
			SettingItem TabMetaEncoding = new SettingItem(new StringDataType());
			TabMetaEncoding.Group = _Group;
			TabMetaEncoding.EnglishName = "Tab / Page Encoding";
			TabMetaEncoding.Description = "Every time your browser returns a page it looks to see what format it is retrieving. This allows you to specify the content type for this particular Tab / Page. Enter something here to override the default portal wide setting.";
			_baseSettings.Add("TabMetaEncoding", TabMetaEncoding);
			SettingItem TabMetaOther = new SettingItem(new StringDataType());
			TabMetaOther.Group = _Group;
			TabMetaOther.EnglishName = "Additional Meta Tag Entries";
			TabMetaOther.Description = "This setting allows you to enter new tags into this Tab / Page's HEAD Tag. Enter something here to override the default portal wide setting.";
			_baseSettings.Add("TabMetaOther", TabMetaOther);
			SettingItem TabKeyPhrase = new SettingItem(new StringDataType());
			TabKeyPhrase.Group = _Group;
			TabKeyPhrase.EnglishName = "Tab / Page Keyphrase";
			TabKeyPhrase.Description = "This setting can be used by a module or by a control. It allows you to define a message/phrase for this particular Tab / Page This can be used for search engine optimisation. Enter something here to override the default portal wide setting.";
			_baseSettings.Add("TabKeyPhrase", TabKeyPhrase);

			#endregion

			#region Layout and Theme

			// changed Thierry (Tiptopweb) : have a dropdown menu to select layout and themes
			_groupOrderBase = (int)SettingItemGroup.THEME_LAYOUT_SETTINGS;
			_Group = SettingItemGroup.THEME_LAYOUT_SETTINGS;
			// get the list of available layouts
			// changed: Jes1111 - 2004-08-06
			ArrayList layoutsList = new ArrayList(new LayoutManager(portalSettings.PortalPath).GetLayouts());
			LayoutItem _noCustomLayout = new LayoutItem();
			_noCustomLayout.Name = string.Empty;
			layoutsList.Insert(0, _noCustomLayout);
			// get the list of available themes
			// changed: Jes1111 - 2004-08-06
			ArrayList themesList = new ArrayList(new ThemeManager(portalSettings.PortalPath).GetThemes());
			ThemeItem _noCustomTheme = new ThemeItem();
			_noCustomTheme.Name = string.Empty;
			themesList.Insert(0, _noCustomTheme);
			// changed: Jes1111 - 2004-08-06
			SettingItem CustomLayout = new SettingItem(new CustomListDataType(layoutsList, "Name", "Name"));
			CustomLayout.Group = _Group;
			CustomLayout.Order = _groupOrderBase + 11;
			CustomLayout.EnglishName = "Custom Layout";
			CustomLayout.Description = "Set a custom layout for this tab only";
			_baseSettings.Add("CustomLayout", CustomLayout);
			//SettingItem CustomTheme = new SettingItem(new StringDataType());
			// changed: Jes1111 - 2004-08-06
			SettingItem CustomTheme = new SettingItem(new CustomListDataType(themesList, "Name", "Name"));
			CustomTheme.Group = _Group;
			CustomTheme.Order = _groupOrderBase + 12;
			CustomTheme.EnglishName = "Custom Theme";
			CustomTheme.Description = "Set a custom theme for the modules in this tab only";
			_baseSettings.Add("CustomTheme", CustomTheme);
			//SettingItem CustomThemeAlt = new SettingItem(new StringDataType());
			// changed: Jes1111 - 2004-08-06
			SettingItem CustomThemeAlt = new SettingItem(new CustomListDataType(themesList, "Name", "Name"));
			CustomThemeAlt.Group = _Group;
			CustomThemeAlt.Order = _groupOrderBase + 13;
			CustomThemeAlt.EnglishName = "Custom Alt Theme";
			CustomThemeAlt.Description = "Set a custom alternate theme for the modules in this tab only";
			_baseSettings.Add("CustomThemeAlt", CustomThemeAlt);

			SettingItem CustomMenuImage = new SettingItem(new CustomListDataType(GetImageMenu(), "Key", "Value"));
			CustomMenuImage.Group = _Group;
			CustomMenuImage.Order = _groupOrderBase + 14;
			CustomMenuImage.EnglishName = "Custom Image Menu";
			CustomMenuImage.Description = "Set a custom menu image for this tab";
			_baseSettings.Add("CustomMenuImage", CustomMenuImage);

			#endregion

			#region Language/Culture Management

			_groupOrderBase = (int)SettingItemGroup.CULTURE_SETTINGS;
			_Group = SettingItemGroup.CULTURE_SETTINGS;
            CultureInfo[] cultureList = Rainbow.Framework.Localization.LanguageSwitcher.GetLanguageList(true);
			//Localized tab title
			int counter = _groupOrderBase + 11;

			foreach (CultureInfo c in cultureList)
			{
				//Ignore invariant
				if (c != CultureInfo.InvariantCulture && !_baseSettings.ContainsKey(c.Name))
				{
					SettingItem LocalizedTabKeyPhrase = new SettingItem(new StringDataType());
					LocalizedTabKeyPhrase.Order = counter;
					LocalizedTabKeyPhrase.Group = _Group;
					LocalizedTabKeyPhrase.EnglishName = "Tab Key Phrase (" + c.Name + ")";
					LocalizedTabKeyPhrase.Description = "Key Phrase this Tab/Page for " + c.EnglishName + " culture.";
					_baseSettings.Add("TabKeyPhrase_" + c.Name, LocalizedTabKeyPhrase);
					SettingItem LocalizedTitle = new SettingItem(new StringDataType());
					LocalizedTitle.Order = counter;
					LocalizedTitle.Group = _Group;
					LocalizedTitle.EnglishName = "Title (" + c.Name + ")";
					LocalizedTitle.Description = "Set title for " + c.EnglishName + " culture.";
					_baseSettings.Add(c.Name, LocalizedTitle);
					counter++;
				}
			}

			#endregion

			return _baseSettings;
		}

		/// <summary>
		/// Page Settings For Search Engines
		/// </summary>
		/// <value>The custom settings.</value>
		public Hashtable CustomSettings
		{
			get
			{
				if (customSettings == null)
					customSettings = GetPageCustomSettings(PageID);
				return customSettings;
			}
		}

		/// <summary>
		/// Gets or sets the portal path.
		/// </summary>
		/// <value>The portal path.</value>
		/// <remarks>
		/// </remarks>
		public string PortalPath
		{
			set
			{
				portalPath = value;

				if (!portalPath.EndsWith("/")) portalPath += "/";
			}
			get { return portalPath; }
		}

		/// <summary>
		/// Stores current portal settings
		/// </summary>
		/// <value>The portal settings.</value>
		public PortalSettings portalSettings
		{
			get
			{
				if (_portalSettings == null)
				{
					// Obtain PortalSettings from Current Context
					if (HttpContext.Current != null)
						_portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"];
				}
				return _portalSettings;
			}
			set { _portalSettings = value; }
		}

		/// <summary>
		/// Gets or sets the name of the page.
		/// </summary>
		/// <value>The name of the page.</value>
		/// <remarks>
		/// </remarks>
		public string PageName
		{
			get { return m_tabName; }
			set { m_tabName = value; }
		}
	}
}


text:
export PROJ_TARGET=iOS

export IOS_PLATFORM=iPhoneOS
export IOS_ARCH=armv7

# XXX edit to actual installed version
export IOS_VERSION=10.3

# XXX may need to edit to actual location
export IOS_XCODE_PATH=/Applications/Xcode.app/Contents/Developer

# XXX edit to actual installed source version and location
# Download from https://www.libsdl.org
export IOS_SDL2_PATH=$HOME/OpenSource/SDL2-2.0.5

export XCODE_DEVELOPER_USR_PATH=$IOS_XCODE_PATH/usr

PATH=$PATH:$IOS_XCODE_PATH/usr/bin

echo
echo "Target platform     : ${IOS_PLATFORM} v${IOS_VERSION}"
echo "Target architecture : ${IOS_ARCH}"
echo "XCode path          : ${IOS_XCODE_PATH}"
echo "SDL2 source path    : ${IOS_SDL2_PATH}"
echo


text:
package com.yeepay.g3.sdk.yop.client.router;

import com.google.common.collect.Sets;
import com.yeepay.g3.sdk.yop.client.YopRequest;
import com.yeepay.g3.sdk.yop.config.AppSdkConfig;
import com.yeepay.g3.sdk.yop.config.AppSdkConfigProviderRegistry;
import com.yeepay.g3.sdk.yop.config.enums.ModeEnum;
import com.yeepay.g3.sdk.yop.exception.YopClientException;
import com.yeepay.g3.sdk.yop.utils.CharacterConstants;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Set;

public class SimpleGateWayRouter implements GateWayRouter {

    private static final String SYSTEM_SDK_MODE_KEY = "yop.sdk.mode";

    private final ServerRootSpace space;

    private final Set<String> independentApiGroups;

    private final ModeEnum systemMode;

    public SimpleGateWayRouter(ServerRootSpace space) {
        this.space = space;
        this.independentApiGroups = Collections.unmodifiableSet(Sets.newHashSet("bank-encryption"));
        String systemModeConfig = System.getProperty(SYSTEM_SDK_MODE_KEY);
        this.systemMode = StringUtils.isEmpty(systemModeConfig) ? null : ModeEnum.valueOf(systemModeConfig);
    }

    @Override
    public String route(String apiUri, YopRequest request) {
        String serverRoot;
        if (isAppInSandbox(request.getAppSdkConfig().getAppKey())) {
            serverRoot = space.getSandboxServerRoot();
        } else {
            String apiGroup = extractApiGroupFromApiUri(apiUri);
            if (independentApiGroups.contains(apiGroup)) {
                boolean isYosRequest = isYosRequest(request);
                URL serverRootURL = isYosRequest ? space.getYosServerRootURL() : space.getServerRootURL();
                URL independentServerRootURL;
                try {
                    independentServerRootURL = new URL(serverRootURL.getProtocol(), getIndependentApiGroupHost(apiGroup, serverRootURL.getHost(), isYosRequest),
                            serverRootURL.getPort(), serverRootURL.getFile());
                } catch (MalformedURLException e) {
                    throw new YopClientException("route request failure");
                }
                serverRoot = independentServerRootURL.toString();
            } else {
                serverRoot = isYosRequest(request) ? space.getYosServerRoot() : space.getServerRoot();
            }
        }
        return serverRoot;
    }

    private boolean isYosRequest(YopRequest request) {
        return MapUtils.isNotEmpty(request.getMultipartFiles());
    }

    private String extractApiGroupFromApiUri(String apiUri) {
        int startIndex = StringUtils.ordinalIndexOf(apiUri, CharacterConstants.SLASH, 3);
        if (startIndex < -1 || startIndex == apiUri.length() - 1) {
            throw new YopClientException("illegal apiUri:" + apiUri);
        }
        int endIndex = StringUtils.indexOf(apiUri, CharacterConstants.SLASH, startIndex + 1);
        if (endIndex < -1) {
            throw new YopClientException("illegal apiUri:" + apiUri);
        }
        return StringUtils.mid(apiUri, startIndex + 1, endIndex - startIndex - 1);
    }

    private boolean isAppInSandbox(String appKey) {
        if (systemMode == null) {
            AppSdkConfig appSdkConfig = AppSdkConfigProviderRegistry.getProvider().getConfig(appKey);
            if (appSdkConfig == null) {
                return false;
            }
            return appSdkConfig.getMode() == ModeEnum.sandbox;
        }
        return systemMode == ModeEnum.sandbox;
    }

    private String getIndependentApiGroupHost(String apiGroup, String originHost, boolean isYosRequest) {
        if (isYosRequest) {
            return originHost;
        }
        int index = StringUtils.indexOf(originHost, CharacterConstants.DOT);
        return StringUtils.substring(originHost, 0, index) + CharacterConstants.DASH_LINE + apiGroup + StringUtils.substring(originHost, index);
    }
}


text:
.slider {
    width: 100px;
    height: 19px;
    user-select: none;
    cursor: ew-resize;
}

.slider-root {
    background-color: #FFF;
    vertical-align: bottom;
    display: inline-block;
    border: 1px solid #AAA;
}

.slider-left {
    background-color: #27b0ff;
}


text:
package com.intellij.openapi.vfs.newvfs;

public interface CachingVirtualFileSystem {
  void refreshWithoutFileWatcher(boolean asynchronous);
}


text:
Guestbook Example

Showing off how to implement a guestbook in Lara. Now saving to database.

<form action="<?=$form_action?>" method='post'>

    Message:

    <textarea name='newEntry'></textarea>

    <input type='submit' name='doAdd' value='Add message' />
    <input type='submit' name='doClear' value='Clear all messages' />

</form>

Current messages

<?php foreach($entries as $val):?>

At: <?=$val['created']?>

<?=htmlent($val['entry'])?>

<?php endforeach;?>


text:
package com.amazonaws.services.worklink.model;

import javax.annotation.Generated;

/**
 * <p>
 * The request is not valid.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidRequestException extends com.amazonaws.services.worklink.model.AmazonWorkLinkException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InvalidRequestException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InvalidRequestException(String message) {
        super(message);
    }

}


text:
'''
The user login module for SaltBot
'''
import requests
import os

URL_SIGNIN = 'https://www.saltybet.com/authenticate?signin=1'

def login():
    """
    Authenticate SaltBot on the SaltyBet website.

    Login to SaltyBet by using the EMAIL and PASSWORD stored in the .env
    file. Successfully logging in returns session and request objects/

    .env Format:
        EMAIL = "example@example.com"
        PASSWORD = "examplePassword123"

    Args:
        None

    Returns:
        session (session): A requests library session.
        request (request): A requests library request.

    """
    session = requests.session()

    # This is the form data that the page sends when logging in
    login_data = {
        'email': os.environ.get('SALTBOT_EMAIL'),
        'pword': os.environ.get('SALTBOT_PASSWORD'),
        'authenticate': 'signin'
    }

    # Authenticate
    request = session.post(URL_SIGNIN, data=login_data)

    # Check for successful login & redirect
    if ( request.url != "https://www.saltybet.com/" and request.url !=
            "http://www.saltybet.com/" ):
        raise RuntimeError("Error: Wrong URL: " + request.url)

    return session, request


text:
const SymPoly = Sym

Base.divrem(p::Sym, q::Sym) = sympy_meth(:div, p, q)
Base.div(p::Sym, q::Sym) = divrem(p,q)[1]
Base.rem(p::Sym, q::Sym) = divrem(p,q)[2]

## rename these, their use is special to polynomials, so we prefix
## Renamed polynomial methods.

## The functions `div`, `rem, `divrem` had slightly different meaning in
## Julia than SymPy, where they are polynomial methods. Here we rename
## them by prefixing with "poly". We do the same for `roots`, so as to
## not conflict with the `roots` function from `Polynomials.jl`.

## [This isn't really needed. We do keep the `polyroots`, as `roots` does not live in base.]

"""

Polynomial division. Renamed from `div` in SymPy to avoid confusion with Julia's `div`. Also, same as `divrem`.

"""
polydiv(ex::Sym, args...; kwargs...) = sympy_meth(:div, ex, args...; kwargs...)

"""

Polynomial division remainer.

"""

polyrem(ex::Sym, args...; kwargs...) = rem(ex, args...; kwargs...)

"""

Polynomial division with remainder. Renamed from `divrem` in SymPy to avoid confusion with Julia's `divrem`

"""
polydivrem(ex::Sym, args...; kwargs...) = sympy_meth(:div, ex, args...; kwargs...)

## deprecate these
Base.@deprecate polydivrem(p::Sym, q::Sym) divrem(p::Sym, q::Sym)
Base.@deprecate polydiv(p::Sym, q::Sym) divrem(p::Sym, q::Sym)
Base.@deprecate polyrem(p::Sym, q::Sym) rem(p::Sym, q::Sym)

"""

Find roots of a polynomial. Renamed from `roots` in
SymPy to avoid confusion with the `roots` function of `Polynomials`

"""
polyroots(ex::Sym, args...; kwargs...) = sympy_meth(:roots, ex, args...; kwargs...)
export polydiv, polyrem, polydivrem, polyroots

polynomial_sympy_methods = (
                            :sqf_list,
                            :groebner,
                            :solve_poly_system,
                            :resultant,
                            :cancel,
                            :apart, :together,
                            :poly,
                            :poly_from_expr,
                            :degree, :degree_list,
                            :LC, :LM, :LT,
                            :pdiv, :prem, :pquo, :pexquo,
                            :quo, :exquo,
                            :half_gcdex, :gcdex,
                            :invert,
                            :subresultants,
                            :discriminant,
                            :terms_gcd,
                            :cofactors,
                            :gcd_list,
                            :lcm_list,
                            :monic,
                            :content,
                            :compose, :decompose,
                            :sturm,
                            :gff_list, :gff,
                            :sqf_norm, :sqf_part, :sqf_list, :sqf,
                            :factor_list,
                            :intervals,
                            :refine_root,
                            :count_roots,
                            :real_roots,
                            :nroots,
                            :ground_roots,
                            :nth_power_roots_poly,
                            :reduced,
                            :is_zero_dimensional,
                            :symmetrize,
                            :horner,
                            :interpolate,
                            :viete,
                            :construct_domain,
                            :minimal_polynomial,
                            :minpoly, :primitive_element,
                            :field_isomorphism, :to_number_field
#                            :numer#, :denom
#                            :roots ## conflict with Roots.roots and functionality provided by solve
                            )

denom(x::Sym) = sympy_meth(:denom, x)
numer(x::Sym) = sympy_meth(:numer, x)
export denom, numer

polynomial_sympy_methods_import = (:expand,
                                   :factor #,
                                   #:trunc
                                   )

for meth in polynomial_sympy_methods_import
    meth_name = string(meth)
    @eval ($meth)(ex::Sym, args...; kwargs...) = sympy_meth($meth_name, ex, args...; kwargs...)
end

## SymPy Poly class

"""

Constructor for polynomials. This allows certain polynomial-specifec
methods to be called, such as `coeffs`. There is also `poly` that does
the same thing. (We keep `Poly`, as it is named like a constructor.)

Examples:
```
p = Poly(x^2 + 2x + 1, x)  #  a poly in x over Z
coeffs(p)  # [1, 2, 1]
p = Poly(a*x^2 + b*x + c, x)  # must specify variable that polynomial is over.
coeffs(p)  ## [a,b,c]
```

"""
Poly(x::Sym) = sympy[:Poly](x)
Poly(x::Sym, args...; kwargs...) = sympy_meth(:Poly, x, args...; kwargs...)
export Poly

## Poly class methods that aren't sympy methods
## e.g., must be called as obj.method(...), but not method(obj, ...)
## not coeffs(x^2 -1), rather poly(x^2 - 1)  |> coeffs
## or poly(a*x^2 + b*x + c, x) |> coeffs to specify a specific variable
polynomial_instance_methods = (:EC, :ET, :LC, :LM, :LT, :TC, ## no .abs()
                              :add_ground,
                              :all_coeffs,
                              :all_monoms, :all_roots, :all_terms,
                              :as_dict, :as_expr, :as_list,
                              :clear_denoms,
                              :coeffs,
                              :deflate,
                              :exclude,
                              :l1_norm,
                              :lift,
                              :ltrim,
                              :max_norm,
                              :monoms,
                              :mul_ground,
                              :neg,
                              :nth, :nth_power_roots_poly,
                              :per,
                              :rat_clear_denoms,
                              :retract,
                              :root,
                              :set_domain, :set_modulus,
                              :sqr, :sub_ground,
                              :to_exact, :to_field, :to_ring, :total_degree,
                              :unify
                              )

polynomial_predicates = (
                         :is_cyclotomic,
                         :is_ground,
                         :is_homogeneous,
                         :is_irreducible,
                         :is_linear,
                         :is_monic,
                         :is_monomial,
                         :is_multivariate,
                         :is_one,
                         :is_primitive,
                         :is_quadratic,
                         :is_sqf,
                         :is_univariate,
                         :is_zero)

## special cases due to output

## {Sym => val} dictionary
#roots(p::Sym, args...; kwargs...) = sympy.roots(project(p), args...; kwargs...)


text:
package com.marverenic.music.ui.library.genre;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.marverenic.adapter.HeterogeneousAdapter;
import com.marverenic.music.JockeyApplication;
import com.marverenic.music.R;
import com.marverenic.music.data.store.MusicStore;
import com.marverenic.music.data.store.PlaylistStore;
import com.marverenic.music.model.Genre;
import com.marverenic.music.player.PlayerController;
import com.marverenic.music.ui.BaseFragment;
import com.marverenic.music.ui.common.LibraryEmptyState;
import com.marverenic.music.view.BackgroundDecoration;
import com.marverenic.music.view.DividerDecoration;
import com.marverenic.music.view.HeterogeneousFastScrollAdapter;
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView;

import java.util.List;

import javax.inject.Inject;

import timber.log.Timber;

public class GenreListFragment extends BaseFragment {

    @Inject MusicStore mMusicStore;
    @Inject PlaylistStore mPlaylistStore;
    @Inject PlayerController mPlayerController;

    private FastScrollRecyclerView mRecyclerView;
    private HeterogeneousAdapter mAdapter;
    private GenreSection mGenreSection;
    private List<Genre> mGenres;
    private Boolean mLibraryHasSongs;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JockeyApplication.getComponent(this).inject(this);

        mMusicStore.getSongs()
                .compose(bindToLifecycle())
                .map(List::isEmpty)
                .subscribe(
                        isLibraryEmpty -> {
                            mLibraryHasSongs = !isLibraryEmpty;
                            setupAdapter();
                        }, throwable -> {
                            Timber.e(throwable, "Failed to check if MusicStore has songs");
                        }
                );

        mMusicStore.getGenres()
                .compose(bindToLifecycle())
                .subscribe(
                        genres -> {
                            mGenres = genres;
                            setupAdapter();
                        }, throwable -> {
                            Timber.e(throwable, "Failed to get all genres from MusicStore");
                        });
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_library_page, container, false);
        mRecyclerView = view.findViewById(R.id.library_page_list);
        mRecyclerView.addItemDecoration(new BackgroundDecoration());
        mRecyclerView.addItemDecoration(new DividerDecoration(getContext(), R.id.empty_layout));

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        if (mAdapter == null) {
            setupAdapter();
        } else {
            mRecyclerView.setAdapter(mAdapter);
        }

        int paddingH = (int) getActivity().getResources().getDimension(R.dimen.global_padding);
        view.setPadding(paddingH, 0, paddingH, 0);

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mRecyclerView = null;
        mAdapter = null;
        mGenreSection = null;
    }

    private void setupAdapter() {
        if (mRecyclerView == null || mGenres == null || mLibraryHasSongs == null) {
            return;
        }

        if (mGenreSection != null) {
            mGenreSection.setData(mGenres);
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter = new HeterogeneousFastScrollAdapter();
            mAdapter.setHasStableIds(true);
            mRecyclerView.setAdapter(mAdapter);

            mGenreSection = new GenreSection(mGenres, getContext(), getFragmentManager(),
                    mMusicStore, mPlaylistStore, mPlayerController);
            mAdapter.addSection(mGenreSection);

            mAdapter.setEmptyState(new LibraryEmptyState(getActivity(), mMusicStore, mPlaylistStore) {
                @Override
                public String getEmptyMessage() {
                    if (mLibraryHasSongs) {
                        return getString(R.string.empty_genres);
                    } else {
                        return super.getEmptyMessage();
                    }
                }

                @Override
                public String getEmptyMessageDetail() {
                    if (mLibraryHasSongs) {
                        return getString(R.string.empty_genres_detail);
                    } else {
                        return super.getEmptyMessageDetail();
                    }
                }
            });
        }
    }
}


text:
package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;

/**
 * Check for 0 length translations
 */

public class TranslationCheckZeroLength extends SingleDatabaseTestCase {

	/**
	 * Create a new TranslationCheckZeroLength testcase
	 */
	public TranslationCheckZeroLength() {

		setDescription("Check for 0 length translations");
		setTeamResponsible(Team.GENEBUILD);

	}

	/**
	 * This only really applies to core databases
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.CDNA);
		removeAppliesToType(DatabaseType.RNASEQ);

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return true if the test passed.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		//Join the translation table with the exon table twice (to select start exon and end exon details),
		//Get the seq_region_start and seq_region_end from exon tables and based on the strand calculate the cds_end and cds_start and then calculate the difference of them (cds_length)

		String sql = "SELECT t.*,exon_start.exon_id,exon_start.seq_region_strand ,exon_start.seq_region_start as exon_start_seq_start,exon_start.seq_region_end as exon_start_seq_end,"
				+ "exon_end.exon_id,exon_end.seq_region_strand,exon_end.seq_region_start as exon_end_seq_start,exon_end.seq_region_end as exon_end_seq_end,"
				+ "IF(exon_end.seq_region_strand>0,exon_end.seq_region_start+t.seq_end-1,exon_start.seq_region_end-t.seq_start+1) as cds_end, "
				+ "IF(exon_start.seq_region_strand>0,exon_start.seq_region_start+t.seq_start-1,exon_end.seq_region_end-t.seq_end+1) as cds_start, "
				+ "(IF(exon_end.seq_region_strand>0,exon_end.seq_region_start+t.seq_end-1,exon_start.seq_region_end-t.seq_start+1)  - IF(exon_start.seq_region_strand>0,exon_start.seq_region_start+t.seq_start-1,cast(exon_end.seq_region_end as signed)-t.seq_end+1)+1) as cds_length "
				+ "FROM translation t "
				+ "INNER JOIN exon exon_start on t.start_exon_id = exon_start.exon_id "
				+ "INNER JOIN exon exon_end on t.end_exon_id=exon_end.exon_id "
				+ "HAVING cds_length < 3";

		int rows = DBUtils.getRowCount(con, sql);
		if (rows != 0) {
			result = false;

			try {

				Statement stmt = con.createStatement();
				ResultSet rs = stmt.executeQuery(sql);

				while (rs != null && rs.next()) {
					String translation_stableID = rs.getString(7);
					ReportManager.problem(this, con, "Translation with stableID " +  translation_stableID  + " have 0 length translations.");

				} // while rs

				stmt.close();

			} catch (SQLException e) {
				e.printStackTrace();
			}

		} else {

			ReportManager.correct(this, con, "No translations have 0 length");

		}

		return result;

	} // run

} // TranslationCheckZeroLength


text:
This example illustrates the Deadline QoS feature on a Fast DDS Application.

To launch this example open two different consoles:

In the first one launch: ./DeadlineQoSExample publisher
In the second one launch: ./DeadlineQoSExample subscriber

## Application behaviour

The application will use a topic with three different keys,
one of which (the third one) sends a sample only half of the times.

By default the deadline period is set to 2000 ms and the publisher write rate to 1000 ms, so
that the third instance misses the deadline 50% of the time. The number of samples that will be written is set to 10.

The default behaviour can be changed by providing the following command line arguments:

./DeadlineQoSExample publisher [--deadline <deadline_ms>] [--sleep <writer_sleep_ms>] [--samples <samples>]
./DeadlineQoSExample subscriber [--deadline <deadline_ms>]

For example:

./DeadlineQoSExample publisher --deadline 1000 --sleep 500 --samples 5
./DeadlineQosExample subscriber --deadline 1000

will setup the publisher and subscriber to use a deadline period of 1000 ms, the publisher will write a new sample every 500 ms for the first two keys and every 1000 ms for the third one, and a total of 5 samples will be sent.


text:
class PatientProgram < ActiveRecord::Base
  belongs_to :patient, :class_name => 'Patient', :foreign_key => :patient_id
  belongs_to :creator, :class_name => 'User', :foreign_key => :creator
  belongs_to :program, :class_name => 'Program', :foreign_key => :program_id
  belongs_to :changed_by, :class_name => 'User', :foreign_key => :changed_by
  belongs_to :voided_by, :class_name => 'User', :foreign_key => :voided_by
  belongs_to :patient_program, :class_name => 'PatientProgram', :foreign_key => :patient_program_id
  has_many :patient_programs, :class_name => 'PatientProgram', :foreign_key => :patient_program_id
  has_many :patient_states, :class_name => 'PatientState', :foreign_key => :patient_program_id
  has_many :programs, :through => :patient_programs
  has_many :creators, :through => :patient_programs_as_creator
  has_many :changed_bies, :through => :patient_programs_as_changed_by
  has_many :patients, :through => :patient_programs
  has_many :voided_bies, :through => :patient_programs_as_voided_by
  has_many :creators, :through => :patient_states_as_creator
  has_many :changed_bies, :through => :patient_states_as_changed_by
  has_many :patient_states, :through => :patient_states
  has_many :voided_bies, :through => :patient_states_as_voided_by
  has_many :states, :through => :patient_states_as_state
  validates_presence_of :creator
  validates_numericality_of :creator, :allow_nil => false, :only_integer => true
  validates_presence_of :date_created
  validates_numericality_of :changed_by, :allow_nil => true, :only_integer => true
  validates_inclusion_of :voided, :in => [true, false], :allow_nil => false, :message => ActiveRecord::Errors.default_error_messages[:blank]
  validates_numericality_of :voided_by, :allow_nil => true, :only_integer => true
  validates_length_of :void_reason, :allow_nil => true, :maximum => 255
end


text:
class Board {

    private final boolean[][] boardFields;
    private final UnionFind unionFind;
    private final int boardHorizontalSize;
    private final int boardVerticalSize;
    private final boolean winHorizontally;

    Board(int boardHorizontalSize, int boardVerticalSize, boolean winHorizontally) {

        this.boardHorizontalSize = boardHorizontalSize;
        this.boardVerticalSize = boardVerticalSize;
        this.winHorizontally = winHorizontally;

        //The fields of the board. A field has a stone if it is set to true, otherwise it is set to false.
        boardFields = new boolean[boardVerticalSize][boardHorizontalSize];

        //The number of fields on the board is equal to the board's length multiply by its height.
        //Here the fields also represent the elements of our UnionFind (Disjoint-set) data structure.
        unionFind = new UnionFind(boardHorizontalSize * boardVerticalSize);

        int indexOfTopLeftField = 0;
        if (winHorizontally) {
            //If the player wins horizontally, then we;
            //Make the top left field the representative of all the fields of the left. And makes the top right field
            //the representation of all the fields of the right. In the future, by just checking if the top left field
            //and the top right field have the same representatives (are connected), we will be able to determine if
            //the left and right side are connected, therefore determine if player X won.
            int indexOfTopRightField = boardHorizontalSize - 1;
            for (int i = 1; i < boardVerticalSize; i++) {
                unionFind.union(indexOfTopLeftField, i * boardHorizontalSize);
                unionFind.union(indexOfTopRightField, indexOfTopRightField + (i * boardHorizontalSize));
            }
        } else {
            //If the player wins vertically, then we;
            //Make the top left field the representative of all the fields of the top. And makes the bottom left field
            //the representation of all the fields of the bottom. In the future, by just checking if the top left field
            //and the bottom left field have the same representatives (are connected), we will be able to determine if
            //the top and bottom side are connected, therefore determine if player O won.
            int indexOfBottomLeftField = boardHorizontalSize * (boardVerticalSize - 1);
            for (int i = 1; i < boardHorizontalSize; i++) {
                unionFind.union(indexOfTopLeftField, i);
                unionFind.union(indexOfBottomLeftField, indexOfBottomLeftField + i);
            }
        }

    }

    void placeStone(int row, int col) {
        if (hasStone(row, col)) {
            return;
        }
        boardFields[row][col] = true;

        //Check if the player has a stone on the field at the top, then connect it to this field
        if (row > 0 && hasStone(row - 1, col)) {
            connect(row, col, row - 1, col);
        }
        //Check if the player has a stone on the field at the top-right, then connect it to this field
        if (row > 0 && col < boardHorizontalSize - 1 && hasStone(row - 1, col + 1)) {
            connect(row, col, row - 1, col + 1);
        }

        //Check if the player has a stone on the field at the bottom, then connect it to this field
        if (row < boardVerticalSize - 1 && hasStone(row + 1, col)) {
            connect(row, col, row + 1, col);
        }
        //Check if the player has a stone on the field at the bottom-left, then connect it to this field
        if (row < boardVerticalSize - 1 && col > 0 && hasStone(row + 1, col - 1)) {
            connect(row, col, row + 1, col - 1);
        }

        //Check if the player has a stone on the field on the left, then connect it to this field
        if (col > 0 && hasStone(row, col - 1)) {
            connect(row, col, row, col - 1);
        }
        //Check if the player has a stone on the field on the right, then connect it to this field
        if (col < boardHorizontalSize - 1 && hasStone(row, col + 1)) {
            connect(row, col, row, col + 1);
        }
    }

    boolean hasStone(int row, int col) {
        return boardFields[row][col];
    }

    void connect(int rowa, int cola, int rowb, int colb) {
        int indexOfFieldA = rowa * boardHorizontalSize + cola;
        int indexOfFieldB = rowb * boardHorizontalSize + colb;
        unionFind.union(indexOfFieldA, indexOfFieldB);
    }

    boolean playerWins() {
        int topLeftRepresentative = unionFind.find(0);
        if (winHorizontally) {
            //If top-left field is connected to top-right field, then left side is connected to right side and player X
            // wins
            return topLeftRepresentative == unionFind.find(boardHorizontalSize - 1);
        } else {
            //If top-left field is connected to bottom-left field, then top side is connected to bottom side and
            // player O wins
            return topLeftRepresentative == unionFind.find(boardHorizontalSize * (boardVerticalSize - 1));
        }
    }
}


text:
package org.apache.directory.api.ldap.extras.extended.ads_impl.cancel;

import org.apache.directory.api.asn1.ber.grammar.Grammar;
import org.apache.directory.api.asn1.ber.grammar.States;

/**
 * This class store the Cancel's grammar constants. It is also used
 * for debugging purposes.
 *
 * @author Apache Directory Project
 */
public enum CancelStatesEnum implements States
{
    // ~ Static fields/initializers
    // -----------------------------------------------------------------

    /** The END_STATE */
    END_STATE,

    // =========================================================================
    // Cancel grammar states
    // =========================================================================
    /** Initial state */
    START_STATE,

    /** Sequence */
    CANCEL_SEQUENCE_STATE,

    /** cancelId */
    CANCEL_ID_STATE,

    /** terminal state */
    LAST_CANCEL_STATE;

    /**
     * Get the grammar name
     *
     * @param grammar The grammar code
     * @return The grammar name
     */
    public String getGrammarName( int grammar )
    {
        return "CANCEL_GRAMMAR";
    }

    /**
     * Get the grammar name
     *
     * @param grammar The grammar class
     * @return The grammar name
     */
    public String getGrammarName( Grammar<CancelContainer> grammar )
    {
        return "CANCEL_GRAMMAR";
    }

    /**
     * Get the string representing the state
     *
     * @param state The state number
     * @return The String representing the state
     */
    public String getState( int state )
    {
        return ( ( state == END_STATE.ordinal() ) ? "CANCEL_END_STATE" : this.name() );
    }

    /**
     * {@inheritDoc}
     */
    public boolean isEndState()
    {
        return this == END_STATE;
    }

    /**
     * {@inheritDoc}
     */
    public CancelStatesEnum getStartState()
    {
        return START_STATE;
    }
}