text:
package org.drools.compiler.lang.api;

import org.drools.compiler.Cheese;
import org.drools.compiler.CommonTestMethodBase;
import org.drools.compiler.StockTick;
import org.drools.compiler.lang.DrlDumper;
import org.drools.compiler.lang.descr.AttributeDescr;
import org.drools.compiler.lang.descr.PackageDescr;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.drools.core.io.impl.ByteArrayResource;
import org.drools.core.rule.GroupElement;
import org.drools.core.rule.Pattern;
import org.drools.core.rule.RuleConditionElement;
import org.junit.Test;
import org.kie.api.definition.KiePackage;
import org.kie.api.definition.type.FactType;
import org.kie.api.event.rule.AfterMatchFiredEvent;
import org.kie.api.event.rule.AgendaEventListener;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.EntryPoint;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.mockito.ArgumentCaptor;

import java.util.*;

import static org.drools.compiler.compiler.xml.rules.DumperTestHelper.assertEqualsIgnoreWhitespace;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

/**
 * DescrBuilderTest
 */
public class DescrBuilderTest extends CommonTestMethodBase {

    @Test
    public void testPackage() {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools" )
                .attribute( "dialect" ).value( "mvel" ).end()
                .getDescr();

        assertEquals( "org.drools",
                      pkg.getName() );
        assertEquals( "mvel",
                      pkg.getAttribute( "dialect" ).getValue() );
        assertNull( pkg.getAttribute( "salience" ) );

        KiePackage kpkg = compilePkgDescr( pkg );

        assertEquals( "org.drools",
                      kpkg.getName() );
    }

    @Test
    public void testPackageAttributes() {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools" )
                // first syntax
                .attribute( "dialect" ).value( "mvel" ).end()
                // second syntax
                .attribute( "salience",
                            "10" )
                // third syntax
                .attribute( "lock-on-active",
                            "true",
                            AttributeDescr.Type.BOOLEAN )
                .getDescr();

        assertEquals( "org.drools",
                      pkg.getName() );
        assertEquals( 3,
                      pkg.getAttributes().size() );
        assertEquals( "mvel",
                      pkg.getAttribute( "dialect" ).getValue() );
        assertEquals( "10",
                      pkg.getAttribute( "salience" ).getValue() );
        assertEquals( "true",
                      pkg.getAttribute( "lock-on-active" ).getValue() );
        assertEquals( AttributeDescr.Type.BOOLEAN,
                      pkg.getAttribute( "lock-on-active" ).getType() );
        assertNull( pkg.getAttribute( "no-loop" ) );

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools",
                      kpkg.getName() );
    }

    @Test
    public void testPackageImports() {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools" )
                .newImport().target( "java.util.List" ).end()
                .newImport().target( "org.drools.examples.*" ).end()
                .getDescr();

        assertEquals( 2,
                      pkg.getImports().size() );
        assertEquals( "java.util.List",
                      pkg.getImports().get( 0 ).getTarget() );
        assertEquals( "org.drools.examples.*",
                      pkg.getImports().get( 1 ).getTarget() );
    }

    @Test
    public void testGlobals() {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools.compiler" )
                .newGlobal().type( "java.util.List" ).identifier( "list" ).end()
                .newGlobal().type( "Person" ).identifier( "bob" ).end()
                .getDescr();

        assertEquals( 2,
                      pkg.getGlobals().size() );
        assertEquals( "java.util.List",
                      pkg.getGlobals().get( 0 ).getType() );
        assertEquals( "list",
                      pkg.getGlobals().get( 0 ).getIdentifier() );
        assertEquals( "Person",
                      pkg.getGlobals().get( 1 ).getType() );
        assertEquals( "bob",
                      pkg.getGlobals().get( 1 ).getIdentifier() );

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools.compiler",
                      kpkg.getName() );
    }

    @Test
    public void testFunctions() {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools" )
                // functions
                .newFunctionImport().target( "java.lang.Math.max" ).end()
                .newFunction().returnType( "long" ).name( "myMax" )
                    .parameter( "long",
                                "v1" ).parameter( "long",
                                                  "v2" )
                    .body( "return max(v1, v2);" )
                .end()
                // rule
                .newRule().name( "test" )
                    .lhs()
                        .eval().constraint( "myMax(5, 10) == 10" ).end()
                    .end()
                    .rhs( "// do something" )
                .end()
                .getDescr();

        assertEquals( 1,
                      pkg.getFunctionImports().size() );
        assertEquals( 1,
                      pkg.getFunctions().size() );
        assertEquals( 1,
                      pkg.getRules().size() );

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools",
                      kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );
        KieSession ksession = createKnowledgeSession(kbase);
        int rules = ksession.fireAllRules();
        assertEquals( 1,
                      rules );
    }

    @Test
    public void testNamedConsequence() {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools.compiler" )
                .newRule().name( "test" )
                    .lhs()
                        .pattern("Cheese").constraint( "type == \"stilton\"" ).end()
                        .namedConsequence().name("c1").end()
                        .pattern("Cheese").constraint( "type == \"cheddar\"" ).end()
                    .end()
                    .rhs( "// do something" )
                    .namedRhs( "c1", "// do something else" )
                .end()
                .getDescr();

        assertEquals( 1,
                      pkg.getRules().size() );

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools.compiler",
                kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );
        KieSession ksession = createKnowledgeSession(kbase);

        Cheese stilton = new Cheese( "stilton", 5 );
        Cheese cheddar = new Cheese( "cheddar", 7 );
        Cheese brie = new Cheese( "brie", 5 );

        ksession.insert( stilton );
        ksession.insert( cheddar );
        ksession.insert( brie );

        int rules = ksession.fireAllRules();
        assertEquals( 2,
                      rules );
    }

    @Test
    public void testConditionalBranch() {
        String expected = "packageorg.drools.compiler\n" +
                          "rule \"test\"\n" +
                          "when\n" +
                          "    Cheese( type == \"stilton\" )  \n" +
                          "    if ( price < 10 ) do[c1] \n" +
                          "    Cheese( type == \"cheddar\" )  \n" +
                          "then\n" +
                          "// do something\n" +
                          "then[c1]\n" +
                          "// do something else\n" +
                          "end";

        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools.compiler" )
                .newRule().name( "test" )
                    .lhs()
                        .pattern("Cheese").constraint( "type == \"stilton\"" ).end()
                        .conditionalBranch()
                            .condition().constraint("price < 10").end()
                            .consequence().name("c1").end()
                        .end()
                        .pattern("Cheese").constraint( "type == \"cheddar\"" ).end()
                    .end()
                    .rhs( "// do something" )
                    .namedRhs( "c1", "// do something else" )
                .end()
                .getDescr();

        assertEquals( 1,
                      pkg.getRules().size() );

        String drl = new DrlDumper().dump( pkg );
        assertEqualsIgnoreWhitespace(expected, drl);

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools.compiler",
                kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );
        KieSession ksession = createKnowledgeSession(kbase);

        Cheese stilton = new Cheese( "stilton", 5 );
        Cheese cheddar = new Cheese( "cheddar", 7 );
        Cheese brie = new Cheese( "brie", 5 );

        ksession.insert( stilton );
        ksession.insert( cheddar );
        ksession.insert( brie );

        int rules = ksession.fireAllRules();
        assertEquals( 2,
                      rules );
    }

    @Test
    public void testDeclare() throws InstantiationException,
                             IllegalAccessException {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.beans" )
                // declare
                .newDeclare()
                    .type().name( "StockTick" )
                    .newAnnotation( "role" ).value( "event" ).end()
                    .newAnnotation( "author" ).value( "bob" ).end()
                    .newField( "symbol" ).type( "String" ).end()
                    .newField( "price" ).type( "double" ).end()
                .end()
                .newDeclare()
                    .enumerative().name( "Planets" )
                    .newAnnotation( "kind" ).value( "enum" ).end()
                    .newEnumLiteral( "earth" ).constructorArg( "6.0" ).constructorArg( "10.0" ).end()
                    .newEnumLiteral( "jupiter" ).constructorArg( "44.0" ).constructorArg( "50.0" ).end()
                    .newField( "mass" ).type( "double" ).end()
                    .newField( "radius" ).type( "double" ).end()
                .end()
                .getDescr();

        assertEquals( 1,
                      pkg.getTypeDeclarations().size() );

        assertEquals( 1,
                      pkg.getEnumDeclarations().size() );

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.beans",
                      kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );

        FactType stType = kbase.getFactType( "org.beans",
                                             "StockTick" );
        assertNotNull( stType );
        Object st = stType.newInstance();
        stType.set( st,
                    "symbol",
                    "RHT" );
        stType.set( st,
                    "price",
                    10 );

        assertEquals( "RHT",
                      stType.get( st,
                                  "symbol" ) );

        //stType.getAnnotation("author"); TODO: implement support for this

    }

    @Test
    public void testDeclareEntryPoint() throws InstantiationException,
                                       IllegalAccessException {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools" )
                // declare
                .newDeclare().entryPoint()
                    .entryPointId( "ep1" )
                .end()
                .newDeclare().entryPoint()
                    .entryPointId( "ep3" )
                .end()
                .getDescr();

        assertEquals( 2,
                      pkg.getEntryPointDeclarations().size() );

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools",
                      kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );

        assertEquals( 2,
                      kbase.getEntryPointIds().size() );

    }

    @Test
    public void testRuleRHSOptional() throws InstantiationException,
                                       IllegalAccessException {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools.compiler" )
                .newRule().name( "r1" )
                    .lhs()
                        .pattern("StockTick").constraint( "company == \"RHT\"" ).end()
                    .end()
                .end()
                .getDescr();

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools.compiler",
                      kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );

        KieSession ksession = kbase.newKieSession();
        ksession.insert( new StockTick(1, "RHT", 80, 1 ) );
        int rules = ksession.fireAllRules();
        assertEquals( 1, rules );
    }

    @Test
    public void testRuleRHSComment() throws InstantiationException,
                                       IllegalAccessException {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools.compiler" )
                .newRule().name( "r1" )
                    .lhs()
                        .pattern("StockTick").constraint( "company == \"RHT\"" ).end()
                    .end()
                    .rhs( "// some comment" )
                .end()
                .getDescr();

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools.compiler",
                      kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );

        KieSession ksession = kbase.newKieSession();
        ksession.insert( new StockTick(1, "RHT", 80, 1 ) );
        int rules = ksession.fireAllRules();
        assertEquals( 1, rules );
    }

    @Test
    public void testTopLevelAccumulate() throws InstantiationException,
                                       IllegalAccessException {
        PackageDescr pkg = DescrFactory.newPackage()
                .name( "org.drools.compiler" )
                .newRule().name( "r1" )
                    .lhs()
                        .accumulate()
                            .source()
                                .pattern("StockTick").constraint( "company == \"RHT\"" ).bind( "$p", "price", false ).end()
                            .end()
                            .function( "sum", "$sum", false, "$p" )
                            .function( "count", "$cnt", false, "$p" )
                        .end()
                    .end()
                    .rhs( "// some comment" )
                .end()
                .getDescr();

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools.compiler",
                      kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );

        KieSession ksession = kbase.newKieSession();
        AgendaEventListener ael = mock( AgendaEventListener.class );
        ksession.addEventListener( ael );

        ksession.insert( new StockTick(1, "RHT", 80, 1 ) );
        ksession.insert( new StockTick(2, "RHT", 100, 10 ) );
        int rules = ksession.fireAllRules();
        assertEquals( 1, rules );

        ArgumentCaptor<AfterMatchFiredEvent> cap = ArgumentCaptor.forClass( AfterMatchFiredEvent.class );
        verify( ael ).afterMatchFired(cap.capture());

        assertThat( ((Number) cap.getValue().getMatch().getDeclarationValue( "$sum" )).intValue(), is( 180 ) );
        assertThat( ((Number) cap.getValue().getMatch().getDeclarationValue( "$cnt" )).intValue(), is( 2 ) );
    }

    @Test
    public void testRule() throws InstantiationException,
                                       IllegalAccessException {

        PackageDescrBuilder packBuilder =
                DescrFactory.newPackage()
                .name( "org.drools.compiler" )
                .newRule().name( "r1" )
                    .lhs()
                        .and()
                            .or()
                                .pattern( "StockTick" ).constraint( "price > 100" ).end()
                                .pattern( "StockTick" ).constraint( "price < 10" ).end()
                            .end()
                            .pattern("StockTick").constraint( "company == \"RHT\"" ).end()
                        .end()
                    .end()
                    .rhs( "    System.out.println(\"foo\");\n" )
                .end();

        PackageDescr pkg = packBuilder.getDescr();

                String drl = new DrlDumper().dump( packBuilder.getDescr() );
        System.out.println(drl);

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools.compiler",
                      kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );

        KieSession ksession = createKnowledgeSession(kbase);
        ksession.insert( new StockTick(1, "RHT", 80, 1 ) );
        int rules = ksession.fireAllRules();
        assertEquals( 0, rules );

        ksession = kbase.newKieSession();
        ksession.insert( new StockTick(2, "RHT", 150, 1 ) );
        rules = ksession.fireAllRules();
        assertEquals( 1, rules );
    }

    @Test
    public void testFromEntryPoint() throws InstantiationException,
                                            IllegalAccessException {
        PackageDescr pkg = DescrFactory
                .newPackage().name("org.drools")
                .newRule().name("from rule")
                    .lhs()
                        .pattern("String").id("s", false).from().entryPoint("EventStream").end()
                    .end()
                .rhs("//System.out.println(s);")
                .end().getDescr();

        KiePackage kpkg = compilePkgDescr( pkg );
        assertEquals( "org.drools",
                      kpkg.getName() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( Collections.singletonList( kpkg ) );

        KieSession ksession = createKnowledgeSession(kbase);
        EntryPoint ep = ksession.getEntryPoint( "EventStream" );
        ep.insert( "Hello World!" );
        int rules = ksession.fireAllRules();
        assertEquals( 1, rules );

    }

    @Test
    public void testDumperFromPkg() {
        //DROOLS-109
        PackageDescr pkg = DescrFactory.newPackage().name( "org.test" )
                                       .newRule().name( "org.test" )
                                       .lhs().and()
                                       .or()
                                       .pattern().id( "$x", false ).type( "Integer" ).constraint( "this > 10" ).end()
                                       .pattern().id( "$x", false ).type( "Integer" ).constraint( "this < 20" ).end()
                                       .end()
                                       .pattern().type( "Integer" ).constraint( "this == $x" ).constraint( "this == 42" ).end()
                                       .end().end()
                                       .rhs( "" )
                                       .end()
                                       .end().getDescr();

        String drl = new DrlDumper().dump( pkg );
        System.out.println( drl );
        KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        knowledgeBuilder.add( new ByteArrayResource( drl.getBytes() ), ResourceType.DRL );
        System.err.println( knowledgeBuilder.getErrors() );
        assertFalse(  knowledgeBuilder.getErrors().toString(), knowledgeBuilder.hasErrors() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( knowledgeBuilder.getKnowledgePackages() );
        KieSession knowledgeSession = kbase.newKieSession();

        KiePackage rebuiltPkg = knowledgeBuilder.getKnowledgePackages().iterator().next();
        org.kie.api.definition.rule.Rule rule = rebuiltPkg.getRules().iterator().next();
        RuleImpl r = ((RuleImpl) rule);

        assertEquals( 2, r.getLhs().getChildren().size() );
        Iterator<RuleConditionElement> iter = r.getLhs().getChildren().iterator();

        RuleConditionElement arg1 = iter.next();
        assertTrue( arg1 instanceof GroupElement && ((GroupElement) arg1).getType() == GroupElement.Type.OR );
        assertEquals( 2, ((GroupElement) arg1).getChildren().size() );

        RuleConditionElement arg2 = iter.next();
        assertTrue( arg2 instanceof Pattern);

    }

    @Test
    public void testAccumulate() throws InstantiationException,
            IllegalAccessException {

        PackageDescrBuilder packBuilder =
                DescrFactory.newPackage()
                        .newGlobal().identifier( "list" ).type( List.class.getName() ).end()
                        .name( "org.drools.compiler" )
                            .newRule().name( "r1" )
                                .lhs()
                                    .pattern().id( "$tot", true ).type( Double.class.getName() ).end()
                                    .accumulate().source().pattern().id( "$i", false ).type( Integer.class.getName() ).end().end()
                                        .function( "sum", "$tot", true, "$i" )
                                        .constraint( "$tot > 15" )
                                .end()
                            .end()
                            .rhs( "list.add( $tot );" )
                            .end()
                            .newRule().name( "r2" )
                                .attribute( "dialect", "mvel" )
                                .lhs()
                                    .pattern().id( "$tot", true ).type( Double.class.getName() ).end()
                                    .accumulate().source().pattern().id( "$i", false ).type( Integer.class.getName() ).end().end()
                                        .function( "sum", "$tot", true, "$i" )
                                        .constraint( "$tot > 15" )
                                .end()
                            .end()
                            .rhs( "list.add( $tot * 2 );" )
                        .end();

        String drl = new DrlDumper().dump( packBuilder.getDescr() );
        System.out.println(drl);

        KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        knowledgeBuilder.add( new ByteArrayResource( drl.getBytes() ), ResourceType.DRL );
        System.err.println( knowledgeBuilder.getErrors() );
        assertFalse(  knowledgeBuilder.getErrors().toString(), knowledgeBuilder.hasErrors() );

        InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addPackages( knowledgeBuilder.getKnowledgePackages() );
        KieSession knowledgeSession = kbase.newKieSession();
        List list = new ArrayList();
        knowledgeSession.setGlobal( "list", list );

        knowledgeSession.insert( 3 );
        knowledgeSession.insert( 39 );
        knowledgeSession.insert( 24.0 );
        knowledgeSession.insert( 42.0 );

        knowledgeSession.fireAllRules();
        assertEquals( Arrays.asList( 42.0, 84.0 ), list );
    }

    @Test
    public void testDumperPositional() {
        PackageDescr pkg = DescrFactory.newPackage().name( "org.test" )
                .newRule().name( "org.test" )
                .lhs()
                .pattern().type( "Integer" ).constraint( "this > 10", true ).constraint( "this > 11", true ).constraint( "this > 12", false).constraint( "this > 13", false).end()
                .end()
                .rhs( "" )
                .end()
                .end().getDescr();

        String drl = new DrlDumper().dump( pkg );
        assertTrue(drl.contains("Integer( this > 10, this > 11; this > 12, this > 13 )"));
    }

    @Test
    public void testDumperDuration() {
        PackageDescr pkg = DescrFactory.newPackage().name("org.test")
                .newRule().name("org.test").attribute("duration").value("int: 0 3600000; repeat-limit = 6").end()
                .lhs()
                .end()
                .rhs( "" )
                .end()
                .end().getDescr();

        String drl = new DrlDumper().dump( pkg );
        assertTrue( drl.contains("duration (int: 0 3600000; repeat-limit = 6)" ) );
    }

    @Test
    public void testDumperTimer() {
        PackageDescr pkg = DescrFactory.newPackage().name("org.test")
                .newRule().name("org.test").attribute("timer").value("cron:0/5 * * * * ?").end()
                .lhs()
                .end()
                .rhs( "" )
                .end()
                .end().getDescr();

        String drl = new DrlDumper().dump( pkg );
        assertTrue( drl.contains("timer (cron:0/5 * * * * ?)" ) );
    }

    private KiePackage compilePkgDescr( PackageDescr pkg ) {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( ResourceFactory.newDescrResource( pkg ),
                      ResourceType.DESCR );

        assertFalse( kbuilder.getErrors().toString(),
                     kbuilder.hasErrors() );
        Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();
        assertEquals( 1,
                      kpkgs.size() );

        return kpkgs.iterator().next();

    }

    @Test
    public void testBehaviorForSlidingWindow() throws InstantiationException, IllegalAccessException {
        // DROOLS-852
        List<String> myParams = new LinkedList<String>();
        myParams.add("5s");

        PackageDescr pkg = DescrFactory
                .newPackage().name( "org.drools" )
                .newRule().name( "from rule" )
                .lhs()
                .not().pattern().type( "StockTick" ).constraint( "price > 10" ).behavior().type( "window", "time" ).parameters( myParams ).end().end().end()
                .end()
                .rhs("//System.out.println(s);")
                .end().getDescr();

        String drl = new DrlDumper().dump( pkg );
        assertTrue( drl.contains("window:time(5s)" ) );
    }
}


text:
PACKAGE_NAME=mimemail
CORE_PACKAGE_NAME=drupal
PACKAGE_URL=https://git.drupalcode.org/project/mimemail
CORE_PACKAGE_URL=https://github.com/drupal/drupal
#PACKAGE_VERSION is configurable can be passed as an argument.
PACKAGE_VERSION=${1:-8.x-1.0-alpha3}

yum module enable php:7.4 -y
yum install -y git php php-json php-dom php-mbstring zip unzip gd gd-devel php-gd php-pdo php-mysqlnd
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && php composer-setup.php --install-dir=/bin --filename=composer

OS_NAME=`cat /etc/os-release | grep PRETTY_NAME | cut -d '=' -f2 | tr -d '"'`

#Check if package exists
if [ -d "$CORE_PACKAGE_NAME" ] ; then
  rm -rf $CORE_PACKAGE_NAME
  echo "$CORE_PACKAGE_NAME  | $PACKAGE_VERSION | $OS_NAME | GitHub | Removed existing package if any"

fi

if ! git clone $CORE_PACKAGE_URL $CORE_PACKAGE_NAME; then
  echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
  echo "$CORE_PACKAGE_URL $CORE_PACKAGE_NAME"
  echo "$CORE_PACKAGE_NAME  |  $CORE_PACKAGE_URL |  $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Clone_Fails"
  exit 1
fi

cd $CORE_PACKAGE_NAME
git checkout 8.9.0
composer update --no-interaction

if ! composer install --no-interaction; then
  echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
  echo "$PACKAGE_URL $PACKAGE_NAME"
  echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_Fails"
  exit 1
fi

composer require --dev phpunit/phpunit --with-all-dependencies ^7 --no-interaction

cd modules/

#Check if package exists
if [ -d "$PACKAGE_NAME" ] ; then
  rm -rf $PACKAGE_NAME
  echo "$PACKAGE_NAME  | $PACKAGE_VERSION | $OS_NAME | GitHub | Removed existing package if any"

fi

 if ! git clone $PACKAGE_URL $PACKAGE_NAME; then
   echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
   echo "$PACKAGE_URL $PACKAGE_NAME"
   echo "$PACKAGE_NAME  |  $PACKAGE_URL |  $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Clone_Fails"
   exit 1
fi

#Install dependency module mailsystem
git clone https://git.drupalcode.org/project/mailsystem

cd $PACKAGE_NAME
git checkout $PACKAGE_VERSION
cd ../../
cd core/
if ! ../vendor/phpunit/phpunit/phpunit ../modules/mimemail/tests; then
  echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------"
  echo "$PACKAGE_URL $PACKAGE_NAME"
  echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_success_but_test_Fails"
  exit 1
else
  echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
  echo "$PACKAGE_URL $PACKAGE_NAME"
  echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub  | Pass |  Both_Install_and_Test_Success"
  exit 0
fi

# drupal-mimemail has 2 types of test Functional/Kernel. Drupal framework is needed to run it.
# Please follow README file for more information to run Functional/kernel testcases .

#Time: 1.21 minutes, Memory: 4.00 MB
#OK (23 tests, 177 assertions)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=struct.RangeTo.html">

Redirecting to struct.RangeTo.html...


text:
using System;
using System.Web.UI.WebControls;

#endregion

namespace DotNetNuke.UI.WebControls
{
    [AttributeUsage(AttributeTargets.Property)]
    public sealed class ControlStyleAttribute : Attribute
    {
        private readonly string _CssClass;
        private readonly Unit _Height;
        private readonly Unit _Width;

        /// <summary>
        /// Initializes a new instance of the StyleAttribute class.
        /// </summary>
        /// <param name="cssClass">The css class to apply to the associated property</param>
        public ControlStyleAttribute(string cssClass)
        {
            _CssClass = cssClass;
        }

        /// <summary>
        /// Initializes a new instance of the StyleAttribute class.
        /// </summary>
        /// <param name="cssClass">The css class to apply to the associated property</param>
        /// <param name="width">control width.</param>
        public ControlStyleAttribute(string cssClass, string width)
        {
            _CssClass = cssClass;
            _Width = Unit.Parse(width);
        }

        /// <summary>
        /// Initializes a new instance of the StyleAttribute class.
        /// </summary>
        /// <param name="cssClass">The css class to apply to the associated property</param>
		/// <param name="width">control width.</param>
		/// <param name="height">control height.</param>
        public ControlStyleAttribute(string cssClass, string width, string height)
        {
            _CssClass = cssClass;
            _Height = Unit.Parse(height);
            _Width = Unit.Parse(width);
        }

        public string CssClass
        {
            get
            {
                return _CssClass;
            }
        }

        public Unit Height
        {
            get
            {
                return _Height;
            }
        }

        public Unit Width
        {
            get
            {
                return _Width;
            }
        }
    }
}


text:
#ifndef _GASNET_EXTENDED_REFCOLL_H
#define _GASNET_EXTENDED_REFCOLL_H

#include <gasnet_handler.h>

/*---------------------------------------------------------------------------------*/
/* ***  Parameters *** */
/*---------------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------------*/
/* ***  Handlers *** */
/*---------------------------------------------------------------------------------*/
/* conduits may override this to relocate the ref-coll handlers */
#ifndef GASNETE_COLL_HANDLER_BASE
#define GASNETE_COLL_HANDLER_BASE 119
#endif

#define _hidx_gasnete_coll_p2p_memcpy_reqh  (GASNETE_COLL_HANDLER_BASE+0)
#define _hidx_gasnete_coll_p2p_short_reqh   (GASNETE_COLL_HANDLER_BASE+1)
#define _hidx_gasnete_coll_p2p_med_reqh	    (GASNETE_COLL_HANDLER_BASE+2)
#define _hidx_gasnete_coll_p2p_long_reqh    (GASNETE_COLL_HANDLER_BASE+3)
#define _hidx_gasnete_coll_p2p_med_tree_reqh (GASNETE_COLL_HANDLER_BASE+4)
#define _hidx_gasnete_coll_p2p_advance_reqh (GASNETE_COLL_HANDLER_BASE+5)
#define _hidx_gasnete_coll_p2p_put_and_advance_reqh (GASNETE_COLL_HANDLER_BASE+6)
#define _hidx_gasnete_coll_p2p_med_counting_reqh (GASNETE_COLL_HANDLER_BASE+7)
#define _hidx_gasnete_coll_p2p_seg_put_reqh (GASNETE_COLL_HANDLER_BASE+8)

/*---------------------------------------------------------------------------------*/
/*four args: team id, node id, seq number, head, tail*/
#define GASNETE_COLL_NUM_SCRATCH_HANDLERS 1
#ifndef GASNETE_COLL_SCRATCH_HANDLER_BASE
#define GASNETE_COLL_SCRATCH_HANDLER_BASE (GASNETE_COLL_HANDLER_BASE-GASNETE_COLL_NUM_SCRATCH_HANDLERS)
#endif

#define _hidx_gasnete_coll_scratch_update_reqh (GASNETE_COLL_SCRATCH_HANDLER_BASE+0)

#define GASNETE_COLL_NUM_TEAM_HANDLERS 1
#ifndef GASNETE_COLL_TEAM_HANDLER_BASE
#define GASNETE_COLL_TEAM_HANDLER_BASE (GASNETE_COLL_SCRATCH_HANDLER_BASE-GASNETE_COLL_NUM_SCRATCH_HANDLERS)
#endif
#define _hidx_gasnete_coll_teamid_reqh (GASNETE_COLL_TEAM_HANDLER_BASE+0)

#ifndef GASNETE_COLL_P2P_OVERRIDE

  MEDIUM_HANDLER_DECL(gasnete_coll_p2p_memcpy_reqh,4,5);
  SHORT_HANDLER_NOBITS_DECL(gasnete_coll_p2p_short_reqh, 5);
  MEDIUM_HANDLER_NOBITS_DECL(gasnete_coll_p2p_med_reqh,6);
MEDIUM_HANDLER_NOBITS_DECL(gasnete_coll_p2p_med_counting_reqh,5);
  LONG_HANDLER_NOBITS_DECL(gasnete_coll_p2p_long_reqh,5);

  MEDIUM_HANDLER_NOBITS_DECL(gasnete_coll_p2p_med_tree_reqh,2);
  SHORT_HANDLER_NOBITS_DECL(gasnete_coll_p2p_advance_reqh,3);
  LONG_HANDLER_NOBITS_DECL(gasnete_coll_p2p_put_and_advance_reqh,3);
  LONG_HANDLER_NOBITS_DECL(gasnete_coll_p2p_seg_put_reqh,3);

  #define GASNETE_COLL_P2P_HANDLERS() \
      gasneti_handler_tableentry_with_bits(gasnete_coll_p2p_memcpy_reqh), \
      gasneti_handler_tableentry_no_bits(gasnete_coll_p2p_short_reqh),    \
      gasneti_handler_tableentry_no_bits(gasnete_coll_p2p_med_reqh),      \
      gasneti_handler_tableentry_no_bits(gasnete_coll_p2p_long_reqh),     \
      gasneti_handler_tableentry_no_bits(gasnete_coll_p2p_med_tree_reqh), \
      gasneti_handler_tableentry_no_bits(gasnete_coll_p2p_advance_reqh), \
      gasneti_handler_tableentry_no_bits(gasnete_coll_p2p_put_and_advance_reqh), \
      gasneti_handler_tableentry_no_bits(gasnete_coll_p2p_med_counting_reqh), \
      gasneti_handler_tableentry_no_bits(gasnete_coll_p2p_seg_put_reqh),

#elif !defined(GASNETE_COLL_P2P_HANDLERS)
  #define GASNETE_COLL_P2P_HANDLERS()
#endif

#ifndef GASNETE_COLL_SCRATCH_OVERRIDE
SHORT_HANDLER_NOBITS_DECL(gasnete_coll_scratch_update_reqh, 2);
#define GASNETE_COLL_SCRATCH_HANDLERS() gasneti_handler_tableentry_no_bits(gasnete_coll_scratch_update_reqh),
#endif

#ifndef GASNETE_COLL_TEAM_OVERRIDE
SHORT_HANDLER_NOBITS_DECL(gasnete_coll_teamid_reqh, 1);
#define GASNETE_COLL_TEAM_HANDLERS() gasneti_handler_tableentry_no_bits(gasnete_coll_teamid_reqh),
#endif

#define GASNETE_REFCOLL_HANDLERS()                           \
  /* ptr-width independent handlers */                       \
  /*  gasneti_handler_tableentry_no_bits(gasnete__reqh) */   \
                                                             \
  /* ptr-width dependent handlers */                         \
  /*  gasneti_handler_tableentry_with_bits(gasnete__reqh) */ \
                                                             \
  GASNETE_COLL_P2P_HANDLERS() GASNETE_COLL_SCRATCH_HANDLERS() GASNETE_COLL_TEAM_HANDLERS()

extern int gasnete_coll_init_done;
extern int gasnete_coll_opt_enabled;
#endif


text:
package net.techreadiness.batch;

import javax.inject.Inject;

import net.techreadiness.service.BatchJobSchedulerService;
import net.techreadiness.service.ServiceContext;

import com.google.common.base.Objects;

public abstract class AbstractServiceContextProvider {
	@Inject
	private BatchJobSchedulerService batchJobSchedulerService;
	@Inject
	protected ServiceContext serviceContext;

	private Long scopeId;
	private Long userId;
	private Long orgId;
	private Long fileId;
	private String jobMode;

	public Long getScopeId() {
		return scopeId;
	}

	public void setScopeId(Long scopeId) {
		this.scopeId = scopeId;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public Long getOrgId() {
		return orgId;
	}

	public void setOrgId(Long orgId) {
		this.orgId = orgId;
	}

	public Long getFileId() {
		return fileId;
	}

	public void setFileId(Long fileId) {
		this.fileId = fileId;
	}

	public String getJobMode() {
		return jobMode;
	}

	public void setJobMode(String jobMode) {
		this.jobMode = jobMode;
	}

	public ServiceContext getServiceContext() {

		// do we already have the correct service context?
		if (Objects.equal(serviceContext.getScopeId(), scopeId) && Objects.equal(serviceContext.getOrgId(), orgId)
				&& Objects.equal(serviceContext.getUserId(), userId)) {

			return serviceContext;
		}

		ServiceContext sc = batchJobSchedulerService.buildServiceContext(scopeId, userId, orgId);

		serviceContext.setOrg(sc.getOrg());
		serviceContext.setScope(sc.getScope());
		serviceContext.setUser(sc.getUser());

		return serviceContext;
	}

	public void setBatchJobSchedulerService(BatchJobSchedulerService batchJobSchedulerService) {
		this.batchJobSchedulerService = batchJobSchedulerService;
	}
}


text:
 ![Travis CI](https://travis-ci.org/OpenFurry/honeycomb.svg?branch=master) [![Coverage Status](https://coveralls.io/repos/github/OpenFurry/honeycomb/badge.svg?branch=master)](https://coveralls.io/github/OpenFurry/honeycomb?branch=master)

⎔ Honeycomb is a site designed specifically for the written word, aiming
to provide the best experience for both authors and readers.


text:
Twig HTML Extension
===================

This package is a Twig extension that provides the following:

 * [`data_uri`][1] filter: generates a URL using the data scheme as defined in
   RFC 2397;

 * [`html_classes`][2] function: returns a string by conditionally joining class
   names together.

[1]: https://twig.symfony.com/data_uri
[2]: https://twig.symfony.com/html_classes


text:
package com.opengamma.strata.measure.fxopt;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.CurrencyPair;
import com.opengamma.strata.calc.Measure;
import com.opengamma.strata.calc.runner.CalculationFunction;
import com.opengamma.strata.calc.runner.CalculationParameters;
import com.opengamma.strata.calc.runner.FunctionRequirements;
import com.opengamma.strata.collect.result.FailureReason;
import com.opengamma.strata.collect.result.Result;
import com.opengamma.strata.data.scenario.ScenarioMarketData;
import com.opengamma.strata.measure.Measures;
import com.opengamma.strata.measure.rate.RatesMarketDataLookup;
import com.opengamma.strata.measure.rate.RatesScenarioMarketData;
import com.opengamma.strata.product.fxopt.FxVanillaOption;
import com.opengamma.strata.product.fxopt.FxVanillaOptionTrade;
import com.opengamma.strata.product.fxopt.ResolvedFxVanillaOptionTrade;

/**
 * Perform calculations on an FX vanilla option trade for each of a set of scenarios.
 *

 * This uses Black FX option volatilities, which must be specified using {@link FxOptionMarketDataLookup}.
 * An instance of {@link RatesMarketDataLookup} must also be specified.
 *

 * Two pricing methods are available, 'Black' and 'VannaVolga'.
 * By default, 'Black' will be used. To control the method, pass an instance of
 * {@link FxVanillaOptionMethod} in the calculation parameters.
 *

 * The supported built-in measures are:
 *

 *
{@linkplain Measures#PRESENT_VALUE Present value}
 *
{@linkplain Measures#PV01_CALIBRATED_SUM PV01 calibrated sum on rate curves}
 *
{@linkplain Measures#PV01_CALIBRATED_BUCKETED PV01 calibrated bucketed on rate curves}
 *
{@linkplain Measures#PV01_MARKET_QUOTE_SUM PV01 market quote sum on rate curves}
 *
{@linkplain Measures#PV01_MARKET_QUOTE_BUCKETED PV01 market quote bucketed on rate curves}
 *
{@linkplain Measures#CURRENCY_EXPOSURE Currency exposure}
 *
{@linkplain Measures#CURRENT_CASH Current cash}
 *
{@linkplain Measures#VEGA_MARKET_QUOTE_BUCKETED Vega market quote bucketed on volatility curves/surfaces}
 *
{@linkplain Measures#RESOLVED_TARGET Resolved trade}
 *

 *

 * The "natural" currency is the market convention base currency of the underlying FX.
 */
public class FxVanillaOptionTradeCalculationFunction
    implements CalculationFunction<FxVanillaOptionTrade> {

  /**
   * The calculations by measure.
   */
  private static final ImmutableMap<Measure, SingleMeasureCalculation> CALCULATORS =
      ImmutableMap.<Measure, SingleMeasureCalculation>builder()
          .put(Measures.PRESENT_VALUE, FxVanillaOptionMeasureCalculations.DEFAULT::presentValue)
          .put(Measures.PV01_CALIBRATED_SUM, FxVanillaOptionMeasureCalculations.DEFAULT::pv01RatesCalibratedSum)
          .put(Measures.PV01_CALIBRATED_BUCKETED, FxVanillaOptionMeasureCalculations.DEFAULT::pv01RatesCalibratedBucketed)
          .put(Measures.PV01_MARKET_QUOTE_SUM, FxVanillaOptionMeasureCalculations.DEFAULT::pv01RatesMarketQuoteSum)
          .put(Measures.PV01_MARKET_QUOTE_BUCKETED, FxVanillaOptionMeasureCalculations.DEFAULT::pv01RatesMarketQuoteBucketed)
          .put(Measures.CURRENCY_EXPOSURE, FxVanillaOptionMeasureCalculations.DEFAULT::currencyExposure)
          .put(Measures.CURRENT_CASH, FxVanillaOptionMeasureCalculations.DEFAULT::currentCash)
          .put(Measures.VEGA_MARKET_QUOTE_BUCKETED, FxVanillaOptionMeasureCalculations.DEFAULT::vegaMarketQuoteBucketed)
          .put(Measures.RESOLVED_TARGET, (rt, smd, m, meth) -> rt)
          .build();

  private static final ImmutableSet<Measure> MEASURES = CALCULATORS.keySet();

  /**
   * Creates an instance.
   */
  public FxVanillaOptionTradeCalculationFunction() {
  }

  //-------------------------------------------------------------------------
  @Override
  public Class<FxVanillaOptionTrade> targetType() {
    return FxVanillaOptionTrade.class;
  }

  @Override
  public Set<Measure> supportedMeasures() {
    return MEASURES;
  }

  @Override
  public Optional<String> identifier(FxVanillaOptionTrade target) {
    return target.getInfo().getId().map(id -> id.toString());
  }

  @Override
  public Currency naturalCurrency(FxVanillaOptionTrade trade, ReferenceData refData) {
    return trade.getProduct().getCurrencyPair().getBase();
  }

  //-------------------------------------------------------------------------
  @Override
  public FunctionRequirements requirements(
      FxVanillaOptionTrade trade,
      Set<Measure> measures,
      CalculationParameters parameters,
      ReferenceData refData) {

    // extract data from product
    FxVanillaOption product = trade.getProduct();
    CurrencyPair currencyPair = product.getCurrencyPair();

    // use lookup to build requirements
    RatesMarketDataLookup ratesLookup = parameters.getParameter(RatesMarketDataLookup.class);
    FunctionRequirements ratesReqs = ratesLookup.requirements(
        ImmutableSet.of(currencyPair.getBase(), currencyPair.getCounter()));
    FxOptionMarketDataLookup optionLookup = parameters.getParameter(FxOptionMarketDataLookup.class);
    FunctionRequirements optionReqs = optionLookup.requirements(currencyPair);
    return ratesReqs.combinedWith(optionReqs);
  }

  //-------------------------------------------------------------------------
  @Override
  public Map<Measure, Result<?>> calculate(
      FxVanillaOptionTrade trade,
      Set<Measure> measures,
      CalculationParameters parameters,
      ScenarioMarketData scenarioMarketData,
      ReferenceData refData) {

    // expand the trade once for all measures and all scenarios
    ResolvedFxVanillaOptionTrade resolved = trade.resolve(refData);
    RatesMarketDataLookup ratesLookup = parameters.getParameter(RatesMarketDataLookup.class);
    RatesScenarioMarketData ratesMarketData = ratesLookup.marketDataView(scenarioMarketData);
    FxOptionMarketDataLookup optionLookup = parameters.getParameter(FxOptionMarketDataLookup.class);
    FxOptionScenarioMarketData optionMarketData = optionLookup.marketDataView(scenarioMarketData);
    FxVanillaOptionMethod method = parameters.findParameter(FxVanillaOptionMethod.class).orElse(FxVanillaOptionMethod.BLACK);

    // loop around measures, calculating all scenarios for one measure
    Map<Measure, Result<?>> results = new HashMap<>();
    for (Measure measure : measures) {
      results.put(measure, calculate(measure, resolved, ratesMarketData, optionMarketData, method));
    }
    return results;
  }

  // calculate one measure
  private Result<?> calculate(
      Measure measure,
      ResolvedFxVanillaOptionTrade trade,
      RatesScenarioMarketData ratesMarketData,
      FxOptionScenarioMarketData optionMarketData,
      FxVanillaOptionMethod method) {

    SingleMeasureCalculation calculator = CALCULATORS.get(measure);
    if (calculator == null) {
      return Result.failure(FailureReason.UNSUPPORTED, "Unsupported measure for FxVanillaOptionTrade: {}", measure);
    }
    return Result.of(() -> calculator.calculate(trade, ratesMarketData, optionMarketData, method));
  }

  //-------------------------------------------------------------------------
  @FunctionalInterface
  interface SingleMeasureCalculation {
    public abstract Object calculate(
        ResolvedFxVanillaOptionTrade trade,
        RatesScenarioMarketData ratesMarketData,
        FxOptionScenarioMarketData optionMarketData,
        FxVanillaOptionMethod method);
  }

}


text:
class GamesController < ApplicationController

	def index
		@games = Game.all
	end

	def show
		@games = Game.all
		@game = Game.where(current_user)
		# @game = Game.find(params[:id])
		# @game.current_user
	end

	def new
		@game = Game.new
	end

	def create
	     if request.xhr?
               if current_user
                 @game = current_user.games.create(game_params)
                 render :json => @game
               end
           else
               render :new
           end
	end

	private

	def game_params
		params.require(:game).permit(:score, :scrabble_score, :level, :lines, :user_id)
	end
end


text:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="style.css" />
    <title>CodeFellow Practice</title>

James Ralph Branca

         My web site!

 <pc>The Legend of Life</pc>

 A bit of a globe-trotter, James was born in New Haven Connecticut and grew to love the allure of the ocean,
      outdoors and his fellow human brothers and sisters. He spent time back-packing in SouthEast Asia and Europe before
      deciding to serve his country in the United States Navy as a PhotoJournalist. While in Asia he grew to love kind-hearted
      attitude of the Thai locals on the island of Koh Tao where he fell in love with sport diving. After the military h
      decided to attend the Diver's Institute of Technology in Seattle. Now, he is immersing himself into a new lifestyle at
      Code Fellows where his is learning    coding, soft skills and how Unbutu is the shiit!!

 Top Travel Destinations

Switzerland

Alaska

Finland

 South Africa

Dubrovnik, Croatia

 Favorite Hobbies

 weightlifting

sailing

basketball

Diving

 Wathing movies


text:
"use strict";

let Hello = /*#__PURE__*/function () {
  function Hello() {
    babelHelpers.classCallCheck(this, Hello);
  }

  babelHelpers.createClass(Hello, [{
    key: "toString",
    value: function toString() {
      return 'hello';
    }
  }]);
  return Hello;
}();

let Outer = /*#__PURE__*/function (_Hello) {
  babelHelpers.inherits(Outer, _Hello);

  var _super = babelHelpers.createSuper(Outer);

  function Outer() {
    let _babelHelpers$get$cal;

    var _thisSuper, _this;

    babelHelpers.classCallCheck(this, Outer);
    _this = _super.call(this);
    _babelHelpers$get$cal = babelHelpers.get((_thisSuper = babelHelpers.assertThisInitialized(_this), babelHelpers.getPrototypeOf(Outer.prototype)), "toString", _thisSuper).call(_thisSuper);

    let Inner = function Inner() {
      babelHelpers.classCallCheck(this, Inner);
      babelHelpers.defineProperty(this, _babelHelpers$get$cal, 'hello');
    };

    return babelHelpers.possibleConstructorReturn(_this, new Inner());
  }

  return Outer;
}(Hello);

expect(new Outer().hello).toBe('hello');


text:
<?php

namespace Zend\ProgressBar\Exception;

/**
 * Exception for Zend_Progressbar component.
 *
 * @category   Zend
 * @package    Zend_ProgressBar
 */
class InvalidArgumentException extends \InvalidArgumentException implements
    ExceptionInterface
{}


text:
package org.springframework.cloud.dataflow.server.repository;

import javax.sql.DataSource;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.dataflow.server.config.features.FeaturesProperties;
import org.springframework.cloud.dataflow.server.repository.support.DataflowRdbmsInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

/**
 * @author Ilayaperumal Gopinathan
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {EmbeddedDataSourceConfiguration.class,
		PropertyPlaceholderAutoConfiguration.class, RdbmsDeploymentIdRepositoryTests.TestConfig.class})
public class RdbmsDeploymentIdRepositoryTests {

	@Autowired
	private DataSource dataSource;

	private DeploymentIdRepository repository;

	private JdbcTemplate template;

	@Before
	public void setup() throws Exception{
		repository = new RdbmsDeploymentIdRepository(dataSource);
		template = new JdbcTemplate(dataSource);
		template.execute("DELETE FROM DEPLOYMENT_IDS");
	}

	@Test
	public void testFindOne() {
		repository.save("key1", "time.1");
		repository.save("key2", "log.0");

		assertEquals("log.0", repository.findOne("key2"));
	}

	@Test
	public void testDelete() {
		repository.save("key1", "time.1");
		repository.save("key2", "log.0");

		assertEquals("log.0", repository.findOne("key2"));
		repository.delete("key2");
		assertNull(repository.findOne("key2"));
	}

	@Configuration
	protected static class TestConfig {

		@Bean
		public FeaturesProperties featuresProperties() {
			return new FeaturesProperties();
		}

		@Bean
		public DataflowRdbmsInitializer definitionRepositoryInitializer(DataSource dataSource) {
			DataflowRdbmsInitializer definitionRepositoryInitializer = new DataflowRdbmsInitializer(featuresProperties());
			definitionRepositoryInitializer.setDataSource(dataSource);
			return definitionRepositoryInitializer;
		}
	}
}


text:
<dom-module id="style-outside-template">
  <template>Hello</template>
  <style>:host {}</style>
  <script>
    Polymer({ is: 'style-outside-template' });
  </script>
</dom-module>


text:
@interface OtherViewController ()

@end

@implementation OtherViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    SameNameView *view = [SameNameView instantiateFromNib];
    if (view != nil) {
        view.frame = CGRectMake(100, 100, 100, 100);
        [self.view addSubview:view];
    }
}

@end


text:
"""
Payload Voice Application
"""

from tornado.ioloop import IOLoop

from payloadvoice import asterisk
from payloadvoice.openstack.common import log

LOG = log.getLogger(__name__)

class Application(asterisk.Connection):

    def __init__(self):
        state_machine = {
            'initial': 'ring',
            'events': [
                {'name': 'start', 'src': 'ring', 'dst': 'answer'},
                {'name': 'channel_up', 'src': 'answer', 'dst': 'hold'},
                {'name': 'queue', 'src': 'hold', 'dst': 'connect'},
                {'name': 'end', 'src': '*', 'dst': 'disconnect'},
            ],
            'callbacks': {
                'onchannel_up': self.on_channel_up,
                'onend': self.on_end,
                'onqueue': self.on_queue,
                'onstart': self.on_start,
            },
        }
        super(Application, self).__init__(state_machine)

    def on_channel_up(self, e):
        self.bridge_create(e.channel)

    def on_queue(self, e):
        LOG.info("Channel '%s' entered bridge '%s'" % (e.channel, e.bridge))

    def on_end(self, e):
        LOG.info("Channel '%s' hungup" % e.channel)
        self.bridge_delete(e.channel)

    def on_start(self, e):
        LOG.info("Channel '%s' start" % e.channel)
        self.answer(e.channel)

    def start(self):
        IOLoop.instance().start()


text:
verify.codeFix({
    description: "Change 'number?' to 'number | null'",
    errorCode: 8020,
    index: 0,
    newRangeContent: "number | null",
});


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    android:background="@color/white"
    android:layout_margin="@dimen/dp_15"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:orientation="vertical"
    app:cardCornerRadius="@dimen/dp_5"
    app:cardElevation="5dp">
    <RelativeLayout
        android:id="@+id/rl_videoview_container_main"
        android:layout_width="match_parent"
        android:layout_height="200dp">
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_50"
        android:layout_gravity="bottom"
        android:gravity="center_vertical">

        <ImageView
            android:id="@+id/iv_main_bottom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/dp_10"
            android:src="@drawable/person_blue"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/dp_15"
            android:layout_toRightOf="@id/iv_main_bottom"
            android:text="Kevel"/>

        <TextView
            android:id="@+id/tv_like_main_bottom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/dp_10"
            android:text="110 Like"/>

        <ImageView
            android:id="@+id/iv_heart_main"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/dp_10"
            android:layout_toLeftOf="@id/tv_like_main_bottom"
            android:src="@drawable/heart_black"/>
    </RelativeLayout>
</android.support.v7.widget.CardView>


text:
<?php

namespace app\modules\user\models\forms;

use Yii;
use yii\base\Model;

/**
 * Forgot password form
 */
class ResendForm extends Model
{
    /**
     * @var string Username and/or email
     */
    public $email;

    /**
     * @var \app\modules\user\models\User
     */
    protected $user = false;

    /**
     * @var \app\modules\user\Module
     */
    public $module;

    /**
     * @inheritdoc
     */
    public function init()
    {
        if (!$this->module) {
            $this->module = Yii::$app->getModule("user");
        }
    }

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            ["email", "required"],
            ["email", "email"],
            ["email", "validateEmailInactive"],
            ["email", "filter", "filter" => "trim"],
        ];
    }

    /**
     * Validate email exists and set user property
     */
    public function validateEmailInactive()
    {
        // check for valid user
        $user = $this->getUser();
        if (!$user) {
            $this->addError("email", Yii::t("user", "Email not found"));
        } elseif ($user->status == $user::STATUS_ACTIVE) {
            $this->addError("email", Yii::t("user", "Email is already active"));
        } else {
            $this->user = $user;
        }
    }

    /**
     * Get user based on email
     * @return \app\modules\user\models\User|null
     */
    public function getUser()
    {
        // get and store user
        if ($this->user === false) {

            /** @var \app\modules\user\models\User $user */
            /** @var \app\modules\user\models\UserToken $userToken */
            $user = $this->module->model("User");
            $userToken = $this->module->model("UserToken");

            // check email first and then userToken
            $this->user = $user::findOne(["email" => $this->email]);
            if (!$this->user) {
                $userToken = $userToken->findByData($this->email, $userToken::TYPE_EMAIL_CHANGE);
                if ($userToken) {
                    $this->user = $user::findOne($userToken->user_id);
                }
            }
        }
        return $this->user;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            "email" => Yii::t("user", "Email"),
        ];
    }

    /**
     * Send forgot email
     * @return bool
     */
    public function sendEmail()
    {
        if (!$this->validate()) {
            return false;
        }

        /** @var \app\modules\user\models\UserToken $userToken */
        $user = $this->getUser();
        $userToken = $this->module->model("UserToken");

        // calculate type based on user status
        if ($user->status == $user::STATUS_INACTIVE) {
            $type = $userToken::TYPE_EMAIL_ACTIVATE;
        } //elseif ($user->status == $user::STATUS_UNCONFIRMED_EMAIL) {
        else {
            $type = $userToken::TYPE_EMAIL_CHANGE;
        }

        // generate userToken and send email confirmation
        $userToken = $userToken::generate($user->id, $type);
        return $user->sendEmailConfirmation($userToken);
    }
}


text:
set -eo pipefail

NODE_VERSION=${1:?Nodejs version missing NODE_VERSION is not set}

## If the nvm has not been installed yet locally or in the CI then let's install it.
if ! command -v nvm; then
  echo 'Installing nvm'
  curl --silent -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
  # shellcheck source=/dev/null
  source "${HOME}/.nvm/nvm.sh"
fi

TARGET_FOLDER=target

mkdir -p ${TARGET_FOLDER}

nvm install "${NODE_VERSION}"
node --version
npm --version
nvm --version
npm install
npm test | tee ${TARGET_FOLDER}/test-suite-output.tap
npm run coverage


text:
package ddl

import (
	"context"
	"sort"
	"testing"

	"github.com/corestoreio/pkg/sql/dmltest"
	"github.com/corestoreio/pkg/util/assert"
)

func TestIsCreateStmt(t *testing.T) {
	t.Parallel()
	tests := []struct {
		tableName string
		stmt      string
		ok        bool
	}{
		{"tableA", "CREATE TABLE `tableA` ( `config_id` int(10) );", true},
		{"tableA2", "ALTER TABLE `tableA2` ( `config_id` int(10) );", false},
		{"tableB", "CREATE TABLE tableB ( `config_id` int(10) );", true},
		{"tableV1", "CREATE VIEW tableV1 ( `config_id` int(10) );", true},
		{"tableV2", "CREATE VIEW `tableV2` ( `config_id` int(10) );", true},
		{"tableV3", "create view `tableV2` ( `config_id` int(10) );", false},
		{"tableC", "CREATE TABLE\nIF NOT\tEXISTS\ntableC ( `config_id` int(10) );", true},
		{"tableC", "CREATE\tVIEW\nIF NOT\tEXISTS\ntableC ( `config_id` int(10) );", true},
	}

	for i, test := range tests {
		haveOK := isCreateStmt(test.tableName, test.stmt) && isCreateStmtBytes([]byte(test.tableName), []byte(test.stmt))
		assert.Exactly(t, test.ok, haveOK, "Index %d %q", i, test.tableName)
	}
}

func TestWithTableDB(t *testing.T) {
	t.Parallel()
	dbc, dbMock := dmltest.MockDB(t)
	defer dmltest.MockClose(t, dbc, dbMock)

	dbMock.ExpectQuery("SELECT.+FROM information_schema.COLUMNS WHERE").
		WillReturnRows(
			dmltest.MustMockRows(dmltest.WithFile("testdata/core_config_data_columns.csv")))

	ts := MustNewTables(
		WithDB(dbc.DB),
		WithTable("tableA"),
		WithCreateTable(context.TODO(), "tableB", ""),
	) // +=2

	assert.Exactly(t, dbc.DB, ts.MustTable("tableA").dcp.DB)
	assert.Exactly(t, dbc.DB, ts.MustTable("tableB").dcp.DB)
	haveTS := ts.Tables()
	sort.Strings(haveTS)
	assert.Exactly(t, []string{"tableA", "tableB"}, haveTS)
}


text:
namespace ESRI.ArcGIS.Geodatabase
{

    #region Enumerations

    /// <summary>
    ///     Enumeration of the comparison operators supported in SQL statements.
    /// </summary>
    public enum ComparisonOperator
    {
        /// <summary>
        ///     This is the equals operator for strict equality comparisons. The framework automatically
        ///     uses the correct syntax for null value comparisons.
        /// </summary>
        Equals,

        /// <summary>
        ///     This is the negated equals operator. The framework automatically uses the correct syntax
        ///     for null value comparisons.
        /// </summary>
        NotEquals,

        /// <summary>
        ///     This is the equals operator for partial equality comparisons. The parameter value
        ///     should be a string to match with percent characters used as wildcards.
        /// </summary>
        Like,

        /// <summary>
        ///     This is the equals operator for partial equality comparisons. The parameter value
        ///     should be a string to match with percent characters used as wildcards.
        /// </summary>
        Contains,

        /// <summary>
        ///     This is the equals operator for partial equality comparisons. The parameter value
        ///     should be a string to match with percent characters used as wildcards.
        /// </summary>
        StartsWith,

        /// <summary>
        ///     This is the equals operator for partial equality comparisons. The parameter value
        ///     should be a string to match with percent characters used as wildcards.
        /// </summary>
        EndsWith,

        /// <summary>
        ///     This is the negated equals operator for partial equality comparisons. The parameter value
        ///     should be a string to match with percent characters used as wildcards.
        /// </summary>
        NotLike,

        /// <summary>
        ///     This is the less than operator.
        /// </summary>
        LessThan,

        /// <summary>
        ///     This is the less than or equals operator.
        /// </summary>
        LessThanOrEquals,

        /// <summary>
        ///     This is the greater than operator.
        /// </summary>
        GreaterThan,

        /// <summary>
        ///     This is the greater than or equals operator.
        /// </summary>
        GreaterThanOrEquals,

        /// <summary>
        ///     This is the in operator which tests for set membership. Constraints using Operator.In can
        ///     only be added by specifying a list of elements (though the lists may contain 0 or 1 elements).
        /// </summary>
        In,

        /// <summary>
        ///     This is the negated in operator which tests for set non-membership.
        /// </summary>
        NotIn
    }

    /// <summary>
    ///     Enumeration of the logic operators supported in SQL statements.
    /// </summary>
    public enum LogicalOperator
    {
        /// <summary>
        ///     This is the AND operator. Combines two conditions together. Selects a record if both conditions are true.
        /// </summary>
        And,

        /// <summary>
        ///     This is the OR operator. Combines two conditions together. Selects a record if at least one condition is true.
        /// </summary>
        Or,

        /// <summary>
        ///     This is the NOT operator. Selects a record if it doesn't match the following expression.
        /// </summary>
        Not
    }

    #endregion
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;

namespace Txt.Core
{
    public class TextScanner : ITextScanner
    {
        private readonly ITextSource textSource;

        private bool disposed;

        public TextScanner([NotNull] ITextSource textSource)
        {
            this.textSource = textSource ?? throw new ArgumentNullException(nameof(textSource));
        }

        public int Column => textSource.Column;

        public Encoding Encoding => textSource.Encoding;

        public int Line => textSource.Line;

        public long Offset => textSource.Offset;

        /// This method calls <see cref="Dispose(bool)" />, specifying <c>true</c> to release all resources.
        public void Close()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public ITextContext GetContext()
        {
            return new Cursor(Offset, Line, Column);
        }

        public ITextSource TextSource => this.textSource;

        public int Peek()
        {
            return textSource.Peek();
        }

        public int Read()
        {
            return textSource.Read();
        }

        public int Read(char[] buffer, int startIndex, int maxCount)
        {
            return textSource.Read(buffer, startIndex, maxCount);
        }

        public Task<int> ReadAsync(char[] buffer, int startIndex, int maxCount)
        {
            return textSource.ReadAsync(buffer, startIndex, maxCount);
        }

        public int ReadBlock(char[] buffer, int startIndex, int maxCount)
        {
            return textSource.ReadBlock(buffer, startIndex, maxCount);
        }

        public Task<int> ReadBlockAsync(char[] buffer, int startIndex, int maxCount)
        {
            return textSource.ReadBlockAsync(buffer, startIndex, maxCount);
        }

        public void Seek(long offset)
        {
            textSource.Seek(offset);
        }

        public void StartRecording()
        {
            textSource.StartRecording();
        }

        public void StopRecording()
        {
            textSource.StopRecording();
        }

        ///
        ///     Advances the scanner's position if the next available character matches the conditions defined by the specified
        ///     predicate.
        ///
        /// <param name="predicate">The <see cref="Predicate{T}" /> that defines the conditions of the character to match.</param>
        /// <returns>
        ///     A value container that contains the next available character and another value indicating whether it matches
        ///     the conditions defined by the predicate.
        /// </returns>
        public MatchResult TryMatch([NotNull] Predicate<char> predicate)
        {
            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }
            if (disposed)
            {
                throw new ObjectDisposedException(nameof(TextScanner));
            }
            var head = textSource.Peek();
            if (head == -1)
            {
                return MatchResult.None;
            }
            var next = (char)head;
            if (!predicate(next))
            {
                return MatchResult.None;
            }
            textSource.Read();
            return MatchResult.Match(char.ToString(next));
        }

        public virtual MatchResult TryMatch(string s)
        {
            return TryMatch(s, StringComparer.Ordinal);
        }

        public MatchResult TryMatch(string s, IEqualityComparer<string> comparer)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }
            if (string.IsNullOrEmpty(s))
            {
                throw new ArgumentException($"Value cannot be empty. Test {nameof(Peek)} for -1 instead.", nameof(s));
            }
            if (disposed)
            {
                throw new ObjectDisposedException(nameof(TextScanner));
            }
            var offset = Offset;
            StartRecording();
            try
            {
                var buffer = new char[s.Length];
                var len = textSource.ReadBlock(buffer, 0, buffer.Length);
                if (len == 0)
                {
                    return MatchResult.None;
                }
                var next = new string(buffer, 0, len);
                if (comparer.Equals(s, next))
                {
                    return MatchResult.Match(next);
                }
                Seek(offset);
                return MatchResult.None;
            }
            finally
            {
                StopRecording();
            }
        }

        /// <inheritdoc />
        public virtual MatchResult TryMatch(char c)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(nameof(TextScanner));
            }
            var head = textSource.Peek();
            if (head == -1)
            {
                return MatchResult.None;
            }
            var next = (char)head;
            if (c != next)
            {
                return MatchResult.None;
            }
            textSource.Read();
            return MatchResult.Match(char.ToString(next));
        }

        void IDisposable.Dispose()
        {
            Close();
        }

        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// <param name="disposing">
        ///     <c>true</c> to clean up both managed and unmanaged resources; otherwise, <c>false</c> to clean up only unmanaged
        ///     resources.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }
            disposed = true;
        }
    }
}


text:
<?php

namespace Port\Steps;

use Port\Exception;
use Port\Reader;
use Port\Result;
use Port\Steps\Step\PriorityStep;
use Port\Workflow;
use Port\Writer;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
use Seld\Signal\SignalHandler;

/**
 * A mediator between a reader and one or more writers and converters
 *
 * @author David de Boer <david@ddeboer.nl>
 */
class StepAggregator implements Workflow, LoggerAwareInterface
{
    use LoggerAwareTrait;

    /**
     * @var Reader
     */
    private $reader;

    /**
     * Identifier for the Import/Export
     *
     * @var string|null
     */
    private $name = null;

    /**
     * @var boolean
     */
    private $skipItemOnFailure = false;

    /**
     * @var array
     */
    private $steps = [];

    /**
     * @var Writer[]
     */
    private $writers = [];

    /**
     * @param Reader $reader
     * @param string $name
     */
    public function __construct(Reader $reader, $name = null)
    {
        $this->name = $name;
        $this->reader = $reader;

        // Defaults
        $this->logger = new NullLogger();
    }

    /**
     * Add a step to the current workflow
     *
     * @param Step         $step
     * @param integer|null $priority
     *
     * @return $this
     */
    public function addStep(Step $step, $priority = null)
    {
        $priority = null === $priority && $step instanceof PriorityStep ? $step->getPriority() : $priority;
        $priority = null === $priority ? 0 : $priority;

        $this->steps[$priority][] = $step;

        return $this;
    }

    /**
     * Add a new writer to the current workflow
     *
     * @param Writer $writer
     *
     * @return $this
     */
    public function addWriter(Writer $writer)
    {
        array_push($this->writers, $writer);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function process()
    {
        $count      = 0;
        $exceptions = new \SplObjectStorage();
        $startTime  = new \DateTime;

        $signal = SignalHandler::create(['SIGTERM', 'SIGINT'], $this->logger);

        foreach ($this->writers as $writer) {
            $writer->prepare();
        }

        $pipeline = $this->buildPipeline();

        // Read all items
        foreach ($this->reader as $index => $item) {
            try {
                if ($signal->isTriggered()) {
                    break;
                }

                if (false === $pipeline($item)) {
                    continue;
                }
            } catch(Exception $e) {
                if (!$this->skipItemOnFailure) {
                    throw $e;
                }

                $exceptions->attach($e, $index);
                $this->logger->error($e->getMessage());
            }

            $count++;
        }

        foreach ($this->writers as $writer) {
            $writer->finish();
        }

        return new Result($this->name, $startTime, new \DateTime, $count, $exceptions);
    }

    /**
     * Sets the value which determines whether the item should be skipped when error occures
     *
     * @param boolean $skipItemOnFailure When true skip current item on process exception and log the error
     *
     * @return $this
     */
    public function setSkipItemOnFailure($skipItemOnFailure)
    {
        $this->skipItemOnFailure = $skipItemOnFailure;

        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Builds the pipeline
     *
     * @return callable
     */
    private function buildPipeline()
    {
        $nextCallable = function ($item) {
            // the final callable is a no-op
        };

        foreach ($this->getStepsSortedDescByPriority() as $step) {
            $nextCallable = function ($item) use ($step, $nextCallable) {
                return $step->process($item, $nextCallable);
            };
        }

        return $nextCallable;
    }

    /**
     * Sorts the internal list of steps and writers by priority in reverse order.
     *
     * @return Step[]
     */
    private function getStepsSortedDescByPriority()
    {
        $steps = $this->steps;
        // Use illogically large and small priorities
        $steps[-255][] = new Step\ArrayCheckStep;
        foreach ($this->writers as $writer) {
            $steps[-256][] = new Step\WriterStep($writer);
        }

        krsort($steps);

        $sortedStep = [];
        /** @var Step[] $stepsAtSamePriority */
        foreach ($steps as $stepsAtSamePriority) {
            foreach ($stepsAtSamePriority as $step) {
                $sortedStep[] = $step;
            }
        }

        return array_reverse($sortedStep);
    }
}


text:
package org.aludratest.content.xml;

/** Enumerates the kinds of difference that may be diagnosed on the lowest level of comparison, the {@link XmlDiffDetail}.
 * @author Volker Bergmann */
public enum XmlDiffDetailType {

    /** An expected element was found but differs in some way. */
    DIFFERENT,

    /** An element was which was not expected at this place. */
    UNEXPECTED,

    /** An expected element was not found. */
    MISSING,

    /** An expected element was found at an unexpected place. */
    MOVED

}


text:
package org.wso2.carbon.humantask.core.store;

import org.apache.axis2.context.ConfigurationContext;
import org.wso2.carbon.humantask.core.HumanTaskConstants;
import org.wso2.carbon.utils.CarbonUtils;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Contains all the tenant task stores. Also responsible for creation of new task stores when new tenant is loading,
 * re-load and un-load of tenant task stores.
 */
public class HumanTaskStoreManager {

    private Map<Integer, HumanTaskStore> tenantTaskStoreMap = new ConcurrentHashMap<Integer, HumanTaskStore>();

    /**
     * Create Human Task for a tenant and add it to the internal task store map.
     * @param tenantId  ID of the tenant which requested a task store
     * @param configContext axis configuration of the tenant which requested a task store
     * @return HumanTaskStore instance
     */
    public HumanTaskStore createHumanTaskStoreForTenant(int tenantId, ConfigurationContext configContext) {
        HumanTaskStore taskStore = new HumanTaskStore(tenantId, configContext);
        taskStore.setHumanTaskDeploymentRepo(new File(CarbonUtils.getCarbonHome() +
                File.separator + "repository" + File.separator + HumanTaskConstants.HUMANTASK_REPO_DIRECTORY));
        tenantTaskStoreMap.put(tenantId, taskStore);

        return taskStore;
    }

    /**
     * Returns the HumanTaskStore instance of tenant specified, null if the HumanTaskStore instance is not available for
     * that tenant.
     * @param tenantId Tenant's Identifier
     * @return HumanTaskStore instance
     */
    public HumanTaskStore getHumanTaskStore(int tenantId){
        return tenantTaskStoreMap.get(tenantId);
    }

    /**
     * Tenant unloading logic for human tasks.
     *
     * @param tenantId : tenant id  being unloaded.
     */
    public void unloadTenantTaskStore(int tenantId) {
        if (tenantTaskStoreMap.get(tenantId) != null) {
            HumanTaskStore taskStore = tenantTaskStoreMap.get(tenantId);
            for(HumanTaskBaseConfiguration taskBaseConfig : taskStore.getTaskConfigurations()) {
                taskStore.removeAxisServiceForTaskConfiguration(taskBaseConfig);
            }
            taskStore.unloadCaches();
            tenantTaskStoreMap.remove(tenantId);
        }
    }
}


text:
package rapture.table.postgres;

import rapture.dsl.idef.IndexFieldType;

/**
 * @author bardhi
 * @since 4/14/15.
 */
public class FieldTypeMapper {
    static String getPgType(IndexFieldType fieldType) {
        String type;
        switch (fieldType) {
            case BOOLEAN:
                type = "boolean";
                break;
            case INTEGER:
                type = "int";
                break;
            case LONG:
                type = "bigint";
                break;
            case DOUBLE:
                type = "double";
                break;
            default:
                type = "text";
        }
        return type;
    }
}


text:
'''
MIT License

Copyright (c) 2017 Kasemsanm

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

'''

# Show Output Text On Terminal.
print ("Hello World")

# Get Input On Terminal And Show input.
A = input("Enter the text : ")
print (A)

# Basic Condition
# Condition must be a comparison and the results are only true or false.
# Comparison uses the symbol.
# == 	->  equal to
# !=	-> 	not equal
# >		-> 	greater than
# <		-> 	less than
# >=	-> 	greater than or equal to
# <=	-> 	less than or equal to
# Logic is used.
# and
# or
# not
A = 5
B = 10
if A > B and B > 0 : #
	print(A)

# If you are writing more than one line, use this.
if A > B and \
   B > 0 :
	print(A)

# Basic Loop
# Show Hello World 10 times
# for loop
for x in range(0,10):
 	print("Hello World")

# while loop
x = 0
while x < 10:
	print("Hello World")
	x += 1 # you can't x++


text:
CREATE DEFINER=`root`@`localhost` PROCEDURE `ReportComment`(IN ruid varchar(9), IN puid varchar(9), IN an varchar(9),
	IN pn varchar(9), IN cid varchar(9), IN rl varchar(50), IN rc varchar(300))
BEGIN
    DECLARE result INTEGER DEFAULT 1;
	declare x integer default 0;
    declare original_cover varchar(200);
    declare test_cover varchar(200);
	DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET result=0;

	START TRANSACTION;
    insert into comment_report(report_user_id, picture_user_id, album_name, picture_name, comment_id, report_label, report_content)
		values(ruid, puid, an, pn, convert(cid, signed), rl, rc);
	IF result = 0 THEN
		ROLLBACK;
	ELSE
		COMMIT;
	END IF;
select result;
END


text:
#!/usr/bin/python

'''
The MIT License (MIT)

(c) Juergen Simon 2014 (juergen.simon@uni-bonn.de)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''

import os
import sys
import getopt

import meanie3D
import meanie3D.app
import meanie3D.app.external
import meanie3D.app.tracking
import meanie3D.app.utils
import meanie3D.app.postprocessing

# Make sure the C++ executables are installed
meanie3D.app.external.locateCommands(["meanie3D-detect","meanie3D-track","meanie3D-cfm2vtk","meanie3D-trackstats","rm"])

# ----------------------------------------------------------------------------
## Prints usage and exits
#
def usage():
    print "meanie3D -c=<json file> -f=<netcdf directory> [-s=<scale>] [--start=t1 --end=t2]  [--resume,-r] [--help,-h] [--version] [--time-operations]"
    print "runs a complete set of netcdf files through the clustering/tracking"
    print "-c : json config file specifying variables etc."
    print "-f : directory containing the files. It is assumed that"
    print "           the files are in the correct order when sorted alphabetically."
    print "--scales,-s  : comma separated list of scale parameters."
    print "--ranges,-r  : comma separated list of bandwidths, one for each spatial and value range variable."
    print "--json-example : prints an example .json configuration and exits"
    print "--start index of time step to start with in files with time dimension"
    print "--end   index of time step to end at in files with time dimension"
    print "--resume     : if this flag is present, the algorithm assumes to resume"
    print "              operations where it last left off. If not present, previous"
    print "              results will be erased before starting"
    print "--help, -h  : print this message and exit."
    print "--version   : prints the version information and exits"
    print "--time-operations: time operations and print out their elapsed time"
    print "--skip-trackstats: skip meanie3D-trackstats, even if the configuration is present"
    sys.exit(1)
    return
# ----------------------------------------------------------------------------

# ----------------------------------------------------------------------------
## Prints the configuration file .json file description and exits
#
def print_configuration_format():
    print '''{'''
    print '''   "description" : "...",  /* Description of file content */'''
    print '''   "data" : {...},         /* call --help config.data for help on this section */'''
    print '''   "detection" : {...},    /* call --help config.detection for help on this section */'''
    print '''   "tracking" : {...},     /* call --help config.tracking for help on this section */'''
    print '''   "postprocessing" : {...} /* call --help config.postprocessing for help on this section */'''
    print '''}'''
    sys.exit(1)
# ----------------------------------------------------------------------------

# ----------------------------------------------------------------------------
## Prints version info and exits
#
def print_version():
    print "meanie3D: " + meanie3D.getVersion() + "\n"
    sys.exit(1)
    return
# ----------------------------------------------------------------------------

# ----------------------------------------------------------------------------
## Main function
def main():
    # Parse command line
    try:
        argv = sys.argv[1:]
        long_args = ["json-example",
                     "resume",
                     "help",
                     "version",
                     "start=",
                     "end=",
                     "time-operations",
                     "skip-trackstats",
                     "inline-tracking",
                     "ranges=",
                     "scales="]
        opts, args = getopt.getopt(argv, "c:f:s:o:r:h", long_args)
    except getopt.GetoptError as detail:
        print detail
        sys.exit(2)

    scales = []
    ranges = []
    resume = False
    time_operations = False
    skip_trackstats = False
    inline_tracking = False
    config_file = ""
    output_dir = "."
    netcdf_dir = ""
    num_params = 0

    start_time_index = -1;
    end_time_index = -1;

    for o, a in opts:

        if o == "-c":
            config_file = os.path.expandvars(a)
            num_params = num_params + 1

        elif o == "-f":
            netcdf_dir = a
            num_params = num_params + 1

        elif o in ["--scales","-s"]:
            scales = str(a).split(',')

        elif o in ["--ranges","-r"]:
            ranges = a

        elif o == "-o":
            output_dir = a

        elif o in ["--json-example"]:
            print_configuration_format()

        elif o in ["--resume"]:
            resume = True

        elif o in ["--start"]:
            start_time_index = int(float(a))

        elif o in ["--end"]:
            end_time_index = int(float(a))

        elif o in ["--help"]:
            usage()
            sys.exit()

        elif o in ["--version"]:
            print_version()

        elif o in ["--time-operations"]:
            time_operations = True

        elif o in ["--skip-trackstats"]:
            skip_trackstats = True

        elif o in ["--inline-tracking"]:
            inline_tracking = True

        else:
            usage()

    if num_params < 2:
        usage()

    uses_time = False

    # sanity checks on time range

    if start_time_index != -1 or end_time_index != -1 :

        if (start_time_index == -1 and end_time_index != -1) or (start_time_index != -1 and end_time_index == -1):
            print "start-time-index and end-time-index must both be set"
            sys.exit(2)

        if start_time_index > end_time_index:
            print "start-time-index is after end-time-index!"
            sys.exit(2)

        uses_time = True

    # Parse configuration data and expand

    configuration = meanie3D.app.utils.load_configuration(config_file);

    print "-------------------------------------------------------------------------------------"
    print "Configuration: " + configuration['description']
    print "-------------------------------------------------------------------------------------"

    # Enrich the configuration with env/command line stuff
    configuration["source_directory"] = os.path.abspath(netcdf_dir)
    configuration["output_dir"] = os.path.abspath(output_dir)
    configuration["resume"] = resume
    configuration['config_file'] = os.path.abspath(config_file)
    configuration['time_operations'] = time_operations
    configuration['skip_trackstats'] = skip_trackstats
    configuration['scales'] = scales
    configuration['ranges'] = ranges
    configuration['uses_time'] = uses_time
    configuration['start_time_index'] = start_time_index
    configuration['end_time_index'] = end_time_index
    configuration['inline_tracking'] = inline_tracking

    # Remove previous results
    if resume == False:
        if not meanie3D.app.utils.removeOutputDirectories(configuration):
            return

    # Run the detection and tracking steps
    detection = meanie3D.app.utils.getSafe(configuration,'detection')
    tracking = meanie3D.app.utils.getSafe(configuration,'tracking')
    if (detection or tracking):

        # run the actual clustering/tracking script
        if not scales:
            if uses_time == False:
                meanie3D.app.tracking.run(configuration,-1)
            else:
                for time_index in range(start_time_index,end_time_index):
                    meanie3D.app.tracking.run(configuration,time_index)

        else:
            for scale in scales:
                configuration["scale"] = scale
                if uses_time == False:
                    meanie3D.app.tracking.run(configuration,-1)
                else:
                    for time_index in range(start_time_index,end_time_index):
                        meanie3D.app.tracking.run(configuration,time_index)

    # Run the postprocessing steps
    if (configuration['postprocessing']):
        meanie3D.app.postprocessing.run(configuration)

    return
# ----------------------------------------------------------------------------

# ----------------------------------------------------------------------------
# entry point
# ----------------------------------------------------------------------------

if __name__ == "__main__":
    main()


text:
package com.cloudrobotics.framework;

import com.google.common.util.concurrent.Service;
import com.google.common.util.concurrent.ServiceManager;
import com.sun.net.httpserver.HttpHandler;
import dagger.Module;
import dagger.Provides;
import dagger.multibindings.IntoMap;
import dagger.multibindings.IntoSet;
import dagger.multibindings.StringKey;
import java.util.Map;
import java.util.Set;
import javax.inject.Provider;
import javax.inject.Singleton;

@Module
public class FrameworkModule {
  private static final int HTTP_PORT = 9090;

  private final int httpPort;

  public FrameworkModule() {
    this.httpPort = HTTP_PORT;
  }

  public FrameworkModule(int httpPort) {
    this.httpPort = httpPort;
  }

  @Provides
  @Singleton
  static ServiceManager provideServiceManager(Set<Service> services) {
    return new ServiceManager(services);
  }

  @Provides
  @IntoSet
  Service provideHttpService(Map<String, HttpHandler> handlers) {
    return new HttpService(httpPort, handlers);
  }

  @Provides
  @IntoMap
  @StringKey("/")
  HttpHandler providesOverviewHandler(Provider<Map<String, HttpHandler>> handlers) {
    return new OverviewHandler(handlers);
  }
}


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifndef FLINT_EXEC_H_
#define FLINT_EXEC_H_

#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>

#include "sqlite3.h"

#include "cli.pb.h"

namespace flint {

namespace ctrl {
struct Argument;
}

namespace exec {

/*
 * Return true in case of success, false otherwise.
 */
bool Exec(const cli::ExecOption &option, const boost::filesystem::path &dir,
		  ctrl::Argument *arg);

}
}

#endif


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TimepickerComponent } from './timepicker.component';
import { TimepickerActions } from './reducer/timepicker.actions';
import { TimepickerConfig } from './timepicker.config';
import { TimepickerStore } from './reducer/timepicker.store';
var TimepickerModule = (function () {
    function TimepickerModule() {
    }
    TimepickerModule_1 = TimepickerModule;
    TimepickerModule.forRoot = function () {
        return {
            ngModule: TimepickerModule_1,
            providers: [TimepickerConfig, TimepickerActions, TimepickerStore]
        };
    };
    TimepickerModule = TimepickerModule_1 = __decorate([
        NgModule({
            imports: [CommonModule],
            declarations: [TimepickerComponent],
            exports: [TimepickerComponent]
        })
    ], TimepickerModule);
    return TimepickerModule;
    var TimepickerModule_1;
}());
export { TimepickerModule };
//# sourceMappingURL=timepicker.module.js.map


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

namespace AeroSuite.AnimationEngine
{
    public static partial class EasingMethods
    {
        /// <summary>
        /// Some more easing methods that are best for special effects.
        /// </summary>
        /// <remarks>
        ///     <para>These methods are based on "Robert Penner's Easing Functions", too.</para>
        ///     <para>They can be found at http://robertpenner.com/easing/ and they are distributed as open source under the BSD License.</para>
        /// </remarks>
        public static partial class Extended
        {

        }
    }
}


text:
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using Google.Cloud.Spanner.V1.Internal.Logging;
using Xunit.Abstractions;

namespace Google.Cloud.Spanner.Data.IntegrationTests
{
    internal class TestLogger : Logger
    {
        private static readonly TestLogger s_instance = new TestLogger();

        private TestLogger()
        {
        }

        public static void Install()
        {
            SetDefaultLogger(s_instance);
        }

        // ReSharper disable once MemberCanBePrivate.Global
        // ReSharper disable once UnusedAutoPropertyAccessor.Global
        public static ITestOutputHelper TestOutputHelper { get; set; }

        protected override void WriteLine(string message)
        {
            try
            {
                TestOutputHelper?.WriteLine(message);
            }
            catch (Exception)
            {
                //Eat the exception.  This can happen if we try to output a log
                //after a test has completed (some action ocurred asynchronously).
            }
        }
    }
}