text:
/*
 * 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.
 */
package com.facebook.presto.sql.gen;

import com.facebook.presto.byteCode.Block;
import com.facebook.presto.byteCode.ClassDefinition;
import com.facebook.presto.byteCode.CompilerContext;
import com.facebook.presto.byteCode.DynamicClassLoader;
import com.facebook.presto.byteCode.FieldDefinition;
import com.facebook.presto.byteCode.control.IfStatement;
import com.facebook.presto.byteCode.expression.ByteCodeExpression;
import com.facebook.presto.byteCode.instruction.JumpInstruction;
import com.facebook.presto.byteCode.instruction.LabelNode;
import com.facebook.presto.operator.JoinProbe;
import com.facebook.presto.operator.JoinProbeFactory;
import com.facebook.presto.operator.LookupJoinOperator;
import com.facebook.presto.operator.LookupJoinOperatorFactory;
import com.facebook.presto.operator.LookupSource;
import com.facebook.presto.operator.LookupSourceSupplier;
import com.facebook.presto.operator.OperatorFactory;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.BigintType;
import com.facebook.presto.spi.type.Type;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutionException;

import static com.facebook.presto.byteCode.Access.FINAL;
import static com.facebook.presto.byteCode.Access.PRIVATE;
import static com.facebook.presto.byteCode.Access.PUBLIC;
import static com.facebook.presto.byteCode.Access.a;
import static com.facebook.presto.byteCode.NamedParameterDefinition.arg;
import static com.facebook.presto.byteCode.ParameterizedType.type;
import static com.facebook.presto.byteCode.expression.ByteCodeExpressions.constantInt;
import static com.facebook.presto.byteCode.expression.ByteCodeExpressions.constantLong;
import static com.facebook.presto.byteCode.expression.ByteCodeExpressions.newInstance;
import static com.facebook.presto.sql.gen.Bootstrap.BOOTSTRAP_METHOD;
import static com.facebook.presto.sql.gen.CompilerUtils.defineClass;
import static com.facebook.presto.sql.gen.CompilerUtils.makeClassName;
import static com.facebook.presto.sql.gen.SqlTypeByteCodeExpression.constantType;

public class JoinProbeCompiler
{
    private final LoadingCache<JoinOperatorCacheKey, HashJoinOperatorFactoryFactory> joinProbeFactories = CacheBuilder.newBuilder().maximumSize(1000).build(
            new CacheLoader<JoinOperatorCacheKey, HashJoinOperatorFactoryFactory>()
            {
                @Override
                public HashJoinOperatorFactoryFactory load(JoinOperatorCacheKey key)
                        throws Exception
                {
                    return internalCompileJoinOperatorFactory(key.getTypes(), key.getProbeChannels(), key.getProbeHashChannel());
                }
            });

    public OperatorFactory compileJoinOperatorFactory(int operatorId,
            LookupSourceSupplier lookupSourceSupplier,
            List<? extends Type> probeTypes,
            List<Integer> probeJoinChannel,
            Optional<Integer> probeHashChannel,
            boolean enableOuterJoin)
    {
        try {
            HashJoinOperatorFactoryFactory operatorFactoryFactory = joinProbeFactories.get(new JoinOperatorCacheKey(probeTypes, probeJoinChannel, probeHashChannel, enableOuterJoin));
            return operatorFactoryFactory.createHashJoinOperatorFactory(operatorId, lookupSourceSupplier, probeTypes, probeJoinChannel, enableOuterJoin);
        }
        catch (ExecutionException | UncheckedExecutionException | ExecutionError e) {
            throw Throwables.propagate(e.getCause());
        }
    }

    public HashJoinOperatorFactoryFactory internalCompileJoinOperatorFactory(List<Type> types, List<Integer> probeJoinChannel, Optional<Integer> probeHashChannel)
    {
        Class<? extends JoinProbe> joinProbeClass = compileJoinProbe(types, probeJoinChannel, probeHashChannel);

        ClassDefinition classDefinition = new ClassDefinition(new CompilerContext(BOOTSTRAP_METHOD),
                a(PUBLIC, FINAL),
                makeClassName("JoinProbeFactory"),
                type(Object.class),
                type(JoinProbeFactory.class));

        classDefinition.declareDefaultConstructor(a(PUBLIC));

        classDefinition.declareMethod(new CompilerContext(BOOTSTRAP_METHOD),
                a(PUBLIC),
                "createJoinProbe",
                type(JoinProbe.class),
                arg("lookupSource", LookupSource.class),
                arg("page", Page.class))
                .getBody()
                .newObject(joinProbeClass)
                .dup()
                .getVariable("lookupSource")
                .getVariable("page")
                .invokeConstructor(joinProbeClass, LookupSource.class, Page.class)
                .retObject();

        DynamicClassLoader classLoader = new DynamicClassLoader(joinProbeClass.getClassLoader());
        Class<? extends JoinProbeFactory> joinProbeFactoryClass = defineClass(classDefinition, JoinProbeFactory.class, classLoader);
        JoinProbeFactory joinProbeFactory;
        try {
            joinProbeFactory = joinProbeFactoryClass.newInstance();
        }
        catch (Exception e) {
            throw Throwables.propagate(e);
        }

        Class<? extends OperatorFactory> operatorFactoryClass = IsolatedClass.isolateClass(
                classLoader,
                OperatorFactory.class,
                LookupJoinOperatorFactory.class,
                LookupJoinOperator.class);

        return new HashJoinOperatorFactoryFactory(joinProbeFactory, operatorFactoryClass);
    }

    @VisibleForTesting
    public JoinProbeFactory internalCompileJoinProbe(List<Type> types, List<Integer> probeChannels, Optional<Integer> probeHashChannel)
    {
        return new ReflectionJoinProbeFactory(compileJoinProbe(types, probeChannels, probeHashChannel));
    }

    private Class<? extends JoinProbe> compileJoinProbe(List<Type> types, List<Integer> probeChannels, Optional<Integer> probeHashChannel)
    {
        CallSiteBinder callSiteBinder = new CallSiteBinder();

        ClassDefinition classDefinition = new ClassDefinition(new CompilerContext(BOOTSTRAP_METHOD),
                a(PUBLIC, FINAL),
                makeClassName("JoinProbe"),
                type(Object.class),
                type(JoinProbe.class));

        // declare fields
        FieldDefinition lookupSourceField = classDefinition.declareField(a(PRIVATE, FINAL), "lookupSource", LookupSource.class);
        FieldDefinition positionCountField = classDefinition.declareField(a(PRIVATE, FINAL), "positionCount", int.class);
        List<FieldDefinition> blockFields = new ArrayList<>();
        for (int i = 0; i < types.size(); i++) {
            FieldDefinition channelField = classDefinition.declareField(a(PRIVATE, FINAL), "block_" + i, com.facebook.presto.spi.block.Block.class);
            blockFields.add(channelField);
        }
        List<FieldDefinition> probeBlockFields = new ArrayList<>();
        for (int i = 0; i < probeChannels.size(); i++) {
            FieldDefinition channelField = classDefinition.declareField(a(PRIVATE, FINAL), "probeBlock_" + i, com.facebook.presto.spi.block.Block.class);
            probeBlockFields.add(channelField);
        }
        FieldDefinition probeBlocksArrayField = classDefinition.declareField(a(PRIVATE, FINAL), "probeBlocks", com.facebook.presto.spi.block.Block[].class);
        FieldDefinition probePageField = classDefinition.declareField(a(PRIVATE, FINAL), "probePage", Page.class);
        FieldDefinition positionField = classDefinition.declareField(a(PRIVATE), "position", int.class);
        FieldDefinition probeHashBlockField = classDefinition.declareField(a(PRIVATE, FINAL), "probeHashBlock", com.facebook.presto.spi.block.Block.class);

        generateConstructor(classDefinition, probeChannels, probeHashChannel, lookupSourceField, blockFields, probeBlockFields, probeBlocksArrayField, probePageField, probeHashBlockField, positionField, positionCountField);
        generateGetChannelCountMethod(classDefinition, blockFields.size());
        generateAppendToMethod(classDefinition, callSiteBinder, types, blockFields, positionField);
        generateAdvanceNextPosition(classDefinition, positionField, positionCountField);
        generateGetCurrentJoinPosition(classDefinition, callSiteBinder, lookupSourceField, probePageField, probeHashChannel, probeHashBlockField, positionField);
        generateCurrentRowContainsNull(classDefinition, probeBlockFields, positionField);

        return defineClass(classDefinition, JoinProbe.class, callSiteBinder.getBindings(), getClass().getClassLoader());
    }

    private void generateConstructor(ClassDefinition classDefinition,
            List<Integer> probeChannels,
            Optional<Integer> probeHashChannel,
            FieldDefinition lookupSourceField,
            List<FieldDefinition> blockFields,
            List<FieldDefinition> probeChannelFields,
            FieldDefinition probeBlocksArrayField,
            FieldDefinition probePageField,
            FieldDefinition probeHashBlockField,
            FieldDefinition positionField,
            FieldDefinition positionCountField)
    {
        CompilerContext context = new CompilerContext(BOOTSTRAP_METHOD);
        Block constructor = classDefinition.declareConstructor(context,
                a(PUBLIC),
                arg("lookupSource", LookupSource.class),
                arg("page", Page.class))
                .getBody()
                .comment("super();")
                .pushThis()
                .invokeConstructor(Object.class);

        constructor.comment("this.lookupSource = lookupSource;")
                .append(context.getVariable("this").setField(lookupSourceField, context.getVariable("lookupSource")));

        constructor.comment("this.positionCount = page.getPositionCount();")
                .append(context.getVariable("this").setField(positionCountField, context.getVariable("page").invoke("getPositionCount", int.class)));

        constructor.comment("Set block fields");
        for (int index = 0; index < blockFields.size(); index++) {
            constructor.append(context.getVariable("this").setField(
                    blockFields.get(index),
                    context.getVariable("page").invoke("getBlock", com.facebook.presto.spi.block.Block.class, constantInt(index))));
        }

        constructor.comment("Set probe channel fields");
        for (int index = 0; index < probeChannelFields.size(); index++) {
            constructor.append(context.getVariable("this").setField(
                    probeChannelFields.get(index),
                    context.getVariable("this").getField(blockFields.get(probeChannels.get(index)))));
        }

        constructor.comment("this.probeBlocks = new Block[<probeChannelCount>];");
        constructor
                .pushThis()
                .push(probeChannelFields.size())
                .newArray(com.facebook.presto.spi.block.Block.class)
                .putField(probeBlocksArrayField);
        for (int index = 0; index < probeChannelFields.size(); index++) {
            constructor
                    .pushThis()
                    .getField(probeBlocksArrayField)
                    .push(index)
                    .pushThis()
                    .getField(probeChannelFields.get(index))
                    .putObjectArrayElement();
        }

        ByteCodeExpression page = newInstance(Page.class, context.getVariable("this").getField(probeBlocksArrayField));
        constructor.comment("this.probePage = new Page(probeBlocks)")
                .append(context.getVariable("this").setField(probePageField, page));

        if (probeHashChannel.isPresent()) {
            Integer index = probeHashChannel.get();
            constructor.comment("this.probeHashBlock = blocks[hashChannel.get()]")
                    .append(context.getVariable("this").setField(
                            probeHashBlockField,
                            context.getVariable("this").getField(blockFields.get(index))));
        }

        constructor.comment("this.position = -1;")
                .append(context.getVariable("this").setField(positionField, constantInt(-1)));

        constructor.ret();
    }

    private void generateGetChannelCountMethod(ClassDefinition classDefinition, int channelCount)
    {
        classDefinition.declareMethod(new CompilerContext(BOOTSTRAP_METHOD),
                a(PUBLIC),
                "getChannelCount",
                type(int.class))
                .getBody()
                .push(channelCount)
                .retInt();
    }

    private void generateAppendToMethod(
            ClassDefinition classDefinition,
            CallSiteBinder callSiteBinder,
            List<Type> types, List<FieldDefinition> blockFields,
            FieldDefinition positionField)
    {
        CompilerContext context = new CompilerContext(BOOTSTRAP_METHOD);
        Block appendToBody = classDefinition.declareMethod(context,
                a(PUBLIC),
                "appendTo",
                type(void.class),
                arg("pageBuilder", PageBuilder.class))
                .getBody();

        for (int index = 0; index < blockFields.size(); index++) {
            Type type = types.get(index);
            appendToBody
                    .comment("%s.appendTo(block_%s, position, pageBuilder.getBlockBuilder(%s));", type.getClass(), index, index)
                    .append(constantType(context, callSiteBinder, type).invoke("appendTo", void.class,
                            context.getVariable("this").getField(blockFields.get(index)),
                            context.getVariable("this").getField(positionField),
                            context.getVariable("pageBuilder").invoke("getBlockBuilder", BlockBuilder.class, constantInt(index))));
        }
        appendToBody.ret();
    }

    private void generateAdvanceNextPosition(ClassDefinition classDefinition, FieldDefinition positionField, FieldDefinition positionCountField)
    {
        CompilerContext context = new CompilerContext(BOOTSTRAP_METHOD);
        Block advanceNextPositionBody = classDefinition.declareMethod(context,
                a(PUBLIC),
                "advanceNextPosition",
                type(boolean.class))
                .getBody();

        advanceNextPositionBody
                .comment("this.position = this.position + 1;")
                .pushThis()
                .pushThis()
                .getField(positionField)
                .push(1)
                .intAdd()
                .putField(positionField);

        LabelNode lessThan = new LabelNode("lessThan");
        LabelNode end = new LabelNode("end");
        advanceNextPositionBody
                .comment("return position < positionCount;")
                .pushThis()
                .getField(positionField)
                .pushThis()
                .getField(positionCountField)
                .append(JumpInstruction.jumpIfIntLessThan(lessThan))
                .push(false)
                .gotoLabel(end)
                .visitLabel(lessThan)
                .push(true)
                .visitLabel(end)
                .retBoolean();
    }

    private void generateGetCurrentJoinPosition(ClassDefinition classDefinition,
            CallSiteBinder callSiteBinder,
            FieldDefinition lookupSourceField,
            FieldDefinition probePageField,
            Optional<Integer> probeHashChannel,
            FieldDefinition probeHashBlockField,
            FieldDefinition positionField)
    {
        CompilerContext context = new CompilerContext(BOOTSTRAP_METHOD);
//        Variable thisVariable = context.getVariable("this");
        Block body = classDefinition.declareMethod(context,
                a(PUBLIC),
                "getCurrentJoinPosition",
                type(long.class))
                .getBody()
                .append(new IfStatement(
                        context,
                        context.getVariable("this").invoke("currentRowContainsNull", boolean.class),
                        constantLong(-1).ret(),
                        null
                ));

        ByteCodeExpression position = context.getVariable("this").getField(positionField);
        ByteCodeExpression page = context.getVariable("this").getField(probePageField);
        ByteCodeExpression probeHashBlock = context.getVariable("this").getField(probeHashBlockField);
        if (probeHashChannel.isPresent()) {
            body.append(context.getVariable("this").getField(lookupSourceField).invoke("getJoinPosition", long.class,
                    position,
                    page,
                    constantType(context, callSiteBinder, BigintType.BIGINT).invoke("getLong",
                            long.class,
                            probeHashBlock,
                            position)
                            .cast(int.class)))
                    .retLong();
        }
        else {
            body.append(context.getVariable("this").getField(lookupSourceField).invoke("getJoinPosition", long.class, position, page)).retLong();
        }
    }

    private void generateCurrentRowContainsNull(ClassDefinition classDefinition, List<FieldDefinition> probeBlockFields, FieldDefinition positionField)
    {
        CompilerContext context = new CompilerContext(BOOTSTRAP_METHOD);
        Block body = classDefinition.declareMethod(context,
                a(PRIVATE),
                "currentRowContainsNull",
                type(boolean.class))
                .getBody();

        for (FieldDefinition probeBlockField : probeBlockFields) {
            LabelNode checkNextField = new LabelNode("checkNextField");
            body
                    .append(context.getVariable("this").getField(probeBlockField).invoke("isNull", boolean.class, context.getVariable("this").getField(positionField)))
                    .ifFalseGoto(checkNextField)
                    .push(true)
                    .retBoolean()
                    .visitLabel(checkNextField);
        }

        body.push(false).retInt();
    }

    public static class ReflectionJoinProbeFactory
            implements JoinProbeFactory
    {
        private final Constructor<? extends JoinProbe> constructor;

        public ReflectionJoinProbeFactory(Class<? extends JoinProbe> joinProbeClass)
        {
            try {
                constructor = joinProbeClass.getConstructor(LookupSource.class, Page.class);
            }
            catch (NoSuchMethodException e) {
                throw Throwables.propagate(e);
            }
        }

        @Override
        public JoinProbe createJoinProbe(LookupSource lookupSource, Page page)
        {
            try {
                return constructor.newInstance(lookupSource, page);
            }
            catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    }

    private static final class JoinOperatorCacheKey
    {
        private final List<Type> types;
        private final List<Integer> probeChannels;
        private final boolean enableOuterJoin;
        private final Optional<Integer> probeHashChannel;

        private JoinOperatorCacheKey(List<? extends Type> types,
                List<Integer> probeChannels,
                Optional<Integer> probeHashChannel,
                boolean enableOuterJoin)
        {
            this.probeHashChannel = probeHashChannel;
            this.types = ImmutableList.copyOf(types);
            this.probeChannels = ImmutableList.copyOf(probeChannels);
            this.enableOuterJoin = enableOuterJoin;
        }

        private List<Type> getTypes()
        {
            return types;
        }

        private List<Integer> getProbeChannels()
        {
            return probeChannels;
        }

        private Optional<Integer> getProbeHashChannel()
        {
            return probeHashChannel;
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(types, probeChannels, enableOuterJoin);
        }

        @Override
        public boolean equals(Object obj)
        {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof JoinOperatorCacheKey)) {
                return false;
            }
            JoinOperatorCacheKey other = (JoinOperatorCacheKey) obj;
            return Objects.equals(this.types, other.types) &&
                    Objects.equals(this.probeChannels, other.probeChannels) &&
                    Objects.equals(this.probeHashChannel, other.probeHashChannel) &&
                    Objects.equals(this.enableOuterJoin, other.enableOuterJoin);
        }
    }

    private static class HashJoinOperatorFactoryFactory
    {
        private final JoinProbeFactory joinProbeFactory;
        private final Constructor<? extends OperatorFactory> constructor;

        private HashJoinOperatorFactoryFactory(JoinProbeFactory joinProbeFactory, Class<? extends OperatorFactory> operatorFactoryClass)
        {
            this.joinProbeFactory = joinProbeFactory;

            try {
                constructor = operatorFactoryClass.getConstructor(int.class, LookupSourceSupplier.class, List.class, boolean.class, JoinProbeFactory.class);
            }
            catch (NoSuchMethodException e) {
                throw Throwables.propagate(e);
            }
        }

        public OperatorFactory createHashJoinOperatorFactory(
                int operatorId,
                LookupSourceSupplier lookupSourceSupplier,
                List<? extends Type> probeTypes,
                List<Integer> probeJoinChannel,
                boolean enableOuterJoin)
        {
            try {
                return constructor.newInstance(operatorId, lookupSourceSupplier, probeTypes, enableOuterJoin, joinProbeFactory);
            }
            catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    }

    public static void checkState(boolean left, boolean right)
    {
        if (left != right) {
            throw new IllegalStateException();
        }
    }
}


text:
FROM golang:1.13.6-buster as builder
LABEL maintainer="Motiv Labs <dev@motivsolutions.com>"
WORKDIR /app
COPY ./ ./

RUN go mod download

RUN make build

FROM ubuntu:20.04 as prod

COPY --from=builder /app/cassandra/schema.sql /usr/local/bin

COPY --from=builder /app/dist/janus /bin/janus
RUN chmod a+x /bin/janus && \
    mkdir -p /etc/janus/apis && \
    mkdir -p /etc/janus/auth

RUN apt-get update && apt-get install -y --no-install-recommends \
        ca-certificates \
        curl \
  && rm -rf /var/lib/apt/lists/*

HEALTHCHECK --interval=5s --timeout=5s --retries=3 CMD curl -f http://localhost:8081/status || exit 1

# Use nobody user + group
USER 65534:65534

EXPOSE 8080 8081 8443 8444
ENTRYPOINT ["/bin/janus", "start"]

# just to have it
RUN ["/bin/janus", "--version"]

redpajama_set_name: RedPajamaGithub


text:
package net.sf.jasperreports.charts.xml;

import net.sf.jasperreports.charts.design.JRDesignTimeSeries;
import net.sf.jasperreports.engine.xml.JRBaseFactory;

import org.xml.sax.Attributes;

/**
 * @author Teodor Danciu (teodord@users.sourceforge.net)
 * @version $Id: JRTimeSeriesFactory.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class JRTimeSeriesFactory extends JRBaseFactory
{

	/**
	 *
	 */
	public Object createObject(Attributes atts)
	{
		return new JRDesignTimeSeries();
	}

}


text:
namespace NuGetTemplate;

#if Comments
/// <summary>
/// Some class.
/// </summary>
#endif
public class Class1
{
}


text:
package org.xtuml.bp.als.oal.test;

//=====================================================================
//
//File:      $RCSfile: TestSelectWhere_Generics.java,v $
//Version:   $Revision: 1.4 $
//Modified:  $Date: 2013/05/10 04:52:47 $
//
//(c) Copyright 2012-2014 Mentor Graphics Corporation 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.
//=====================================================================
import java.io.StringReader;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.preference.IPreferenceStore;

import antlr.RecognitionException;
import antlr.TokenStreamException;
import antlr.TokenStreamRecognitionException;

import org.xtuml.bp.als.oal.OalLexer;
import org.xtuml.bp.als.oal.OalParser;
import org.xtuml.bp.als.oal.Oal_validate;
import org.xtuml.bp.core.Block_c;
import org.xtuml.bp.core.Body_c;
import org.xtuml.bp.core.BridgeBody_c;
import org.xtuml.bp.core.CorePlugin;
import org.xtuml.bp.core.DerivedAttributeBody_c;
import org.xtuml.bp.core.FunctionBody_c;
import org.xtuml.bp.core.Function_c;
import org.xtuml.bp.core.Oalconstants_c;
import org.xtuml.bp.core.Ooaofooa;
import org.xtuml.bp.core.OperationBody_c;
import org.xtuml.bp.core.StateActionBody_c;
import org.xtuml.bp.core.Statement_c;
import org.xtuml.bp.core.TransitionActionBody_c;
import org.xtuml.bp.core.Value_c;
import org.xtuml.bp.core.Variable_c;
import org.xtuml.bp.core.common.BridgePointPreferencesStore;
import org.xtuml.bp.core.common.ClassQueryInterface_c;
import org.xtuml.bp.core.common.IdAssigner;
import org.xtuml.bp.core.util.ContainerUtil;
import org.xtuml.bp.test.common.BaseTest;
import org.xtuml.bp.test.common.TestingUtilities;

public class TestSelectWhere_Generics extends BaseTest {

    private static boolean m_requiresClear = false;
    private static String m_projectName = "select_where_test";
    private static int m_funcType = 0;
    private static int m_funcNum = 0;
    private static boolean firstSetup = false;
    static public Ooaofooa modelRoot = BaseTest.getDefaultTestInstance();

    public TestSelectWhere_Generics(String arg0) {
        super(null, arg0);
    }

    /*
     * (non-Javadoc)
     *
     * @see junit.framework.TestCase#setUp()
     */
    protected void setUp() throws Exception {
        super.setUp();

        if (!firstSetup) {
            String pkgName = "CP";

            TestingUtilities.importTestingProjectIntoWorkspace(m_projectName);

            project = ResourcesPlugin.getWorkspace().getRoot().getProject(m_projectName);

            m_sys = getSystemModel(project.getName());

            String modelRootId = Ooaofooa.createModelRootId(project, pkgName, true);
            modelRoot = Ooaofooa.getInstance(modelRootId, true);

            populateFunctionInstances();
        }

        firstSetup = true;

        // NOTE - for this test class, unlike OalParserTest_Generics, we don't care
        // about testing the OAL inside various homes like bridges, class operations, or MDAs.
        // Thus, we don't need to populate that instance data like that class does.  However,
        // it could be useful at some point, so the code available in the history of this file
        // for future reference.
    }

    /*
     * (non-Javadoc)
     *
     * @see junit.framework.TestCase#tearDown()
     */
    protected void tearDown() throws Exception {
        try {
            super.tearDown();
            TestSelectWhere_Generics.tearDownActionData();
        } catch (RecognitionException re) {
            // do nothing
        } catch (TokenStreamException te) {
            // do nothing
        }
    }

    public void testSelectAnyFromWhereSelectedIOp1() throws RecognitionException, TokenStreamException {
        IPreferenceStore store = CorePlugin.getDefault().getPreferenceStore();
        store.setValue(BridgePointPreferencesStore.ALLOW_OPERATIONS_IN_WHERE, false);

        String act = "select any My_Class from instances of The_Class where (selected.get_A() == 0);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:71-71: Operation calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals(":1:77-77: Expression within Select Where clause does not yield boolean result", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:79: expecting Semicolon, found 'null'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 0);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedIOp2() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (0 == selected.get_A());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:76-76: Operation calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals(":1:77-77: Right hand operand not found for relational expression", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:79: expecting TOK_RPAREN, found 'null'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedIOp3() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (selected.getTrue());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:73-73: Operation calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:75: expecting TOK_RPAREN, found ';'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:76: unexpected token: null", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedCOp1() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (The_Class::class_based_op() == true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:82-82: Operation calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:87: expecting TOK_RPAREN, found 'true'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:91: expecting Semicolon, found ')'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedCOp2() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (true == The_Class::class_based_op());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:90-90: Operation calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals(":1:91-91: Right hand operand not found for relational expression", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:93: expecting TOK_RPAREN, found 'null'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedCOp3() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (The_Class::class_based_op());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:82-82: Operation calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:84: expecting TOK_RPAREN, found ';'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:85: unexpected token: null", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedMDA1() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (selected.Attr_B == 10);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:65-70: Accessing a derived base attribute value is not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals(":1:77-77: Expression within Select Where clause does not yield boolean result", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:79: expecting Semicolon, found 'null'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedMDA2() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (10 == selected.Attr_B);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:71-76: Accessing a derived base attribute value is not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals(":1:77-77: Right hand operand not found for relational expression", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:79: expecting TOK_RPAREN, found 'null'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 2);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedMDA3() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (selected.Attr_true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:65-73: Accessing a derived base attribute value is not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:75: expecting TOK_RPAREN, found ';'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:76: unexpected token: null", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 2);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedDomFunc1() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (::gfunc() == true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:64-64: Function calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:69: expecting TOK_RPAREN, found 'true'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:73: expecting Semicolon, found ')'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedDomFunc2() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (true == ::gfunc());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:72-72: Function calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals(":1:73-73: Right hand operand not found for relational expression", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:75: expecting TOK_RPAREN, found 'null'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedDomFunc3() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (::gfunc());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:64-64: Function calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:66: expecting TOK_RPAREN, found ';'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:67: unexpected token: null", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedBrg1() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (TEST::getTrue() == true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:70-70: Bridge calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:75: expecting TOK_RPAREN, found 'true'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:79: expecting Semicolon, found ')'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedBrg2() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (true == TEST::getTrue());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:78-78: Bridge calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals(":1:79-79: Right hand operand not found for relational expression", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:81: expecting TOK_RPAREN, found 'null'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedBrg3() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (TEST::getTrue());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:70-70: Bridge calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:72: expecting TOK_RPAREN, found ';'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:73: unexpected token: null", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedMsgOp1() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (my_if::if_op() == true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:69-69: Message calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:74: expecting TOK_RPAREN, found 'true'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:78: expecting Semicolon, found ')'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedMsgOp2() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (true == my_if::if_op());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:77-77: Message calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals(":1:78-78: Right hand operand not found for relational expression", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:80: expecting TOK_RPAREN, found 'null'", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedMsgOp3() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (my_if::if_op());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:69-69: Message calls are not allowed inside a where condition.", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:71: expecting TOK_RPAREN, found ';'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:72: unexpected token: null", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    public void testSelectAnyFromWhereSelectedMsgSig() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (my_if::if_sig());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        String lines[] = x.split("\n");//$NON-NLS-1$
        assertEquals(":1:63-68: Signal ->if_sig<- cannot be used in an expression", lines[0]); //$NON-NLS-1$
        assertEquals("line 1:72: expecting TOK_RPAREN, found ';'", lines[1]); //$NON-NLS-1$
        assertEquals("line 1:73: unexpected token: null", lines[2]); //$NON-NLS-1$
        validateBlkStmtVal(1, 0, 1);
        Variable_c[] vars = Variable_c.VariableInstances(modelRoot);
        assertEquals(0, vars.length);
    }

    // Now we test the above selects with the preference set to allow the behavior
    // and expect to not get syntax errors reported
    public void testSelectAnyFromWhereSelectedIOp1Allowed() throws RecognitionException, TokenStreamException {
        IPreferenceStore store = CorePlugin.getDefault().getPreferenceStore();
        store.setValue(BridgePointPreferencesStore.ALLOW_OPERATIONS_IN_WHERE, true);

        String act = "select any My_Class from instances of The_Class where (selected.get_A() == 0);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedIOp2Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (0 == selected.get_A());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedIOp3Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (selected.getTrue());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedCOp1Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (The_Class::class_based_op() == true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedCOp2Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (true == The_Class::class_based_op());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedCOp3Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (The_Class::class_based_op());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedMDA1Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (selected.Attr_B == 10);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedMDA2Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (10 == selected.Attr_B);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedMDA3Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (selected.Attr_true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedDomFunc1Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (::gfunc() == true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedDomFunc2Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (true == ::gfunc());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedDomFunc3Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (::gfunc());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedBrg1Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (TEST::getTrue() == true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedBrg2Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (true == TEST::getTrue());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedBrg3Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (TEST::getTrue());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedMsgOp1Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (my_if::if_op() == true);"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedMsgOp2Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (true == my_if::if_op());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    public void testSelectAnyFromWhereSelectedMsgOp3Allowed() throws RecognitionException, TokenStreamException {
        String act = "select any My_Class from instances of The_Class where (my_if::if_op());"; //$NON-NLS-1$
        String x = parseAction(act, ACTIVITY_TYPE_FUNC, TEST_OAL);
        assertEquals("", x); //$NON-NLS-1$
    }

    ////////////////////////////////////////////////////////////////////////////
    //
    //  Support data and functions for the tests follow
    //
    ////////////////////////////////////////////////////////////////////////////
    static final int ACTIVITY_TYPE_FUNC = 0;

    static public String parseAction(String stmts, int funcType, int funcNum) {
        m_requiresClear = true;
        m_funcType = funcType;
        m_funcNum = funcNum;
        OalLexer lexer = new OalLexer(new StringReader(stmts));
        OalParser parser = new OalParser(modelRoot, lexer);
        try {
            switch (funcType) {
            case ACTIVITY_TYPE_FUNC:
                parser.m_oal_context = new Oal_validate(ContainerUtil
                        .getContainer(m_testFunc[funcNum]));
                m_testFunc[funcNum].setAction_semantics_internal(stmts);
                parser.action(m_testFunc[funcNum].getSync_id(),
                        Oalconstants_c.FUNCTION_TYPE);
                break;
            default:
                fail("parseAction: Unknown Activity type constant");
            }
        } catch (TokenStreamException e) {
            Block_c.Clearcurrentscope(modelRoot, parser.m_oal_context.m_act_id);
            if (e instanceof TokenStreamRecognitionException) {
                TokenStreamRecognitionException tsre = (TokenStreamRecognitionException) e;
                parser.reportError(tsre.recog);
            } else {
                fail("Token stream exception in parser");
            }
        } catch (RecognitionException e) {
            Block_c.Clearcurrentscope(modelRoot, parser.m_oal_context.m_act_id);
            parser.reportError(e);
        } catch (InterruptedException ie) {
        }
        return parser.m_output;
    }

    static public void clearActionData(int funcType, int funcNum)
            throws RecognitionException, TokenStreamException {
        switch (funcType) {
        case ACTIVITY_TYPE_FUNC:
            Body_c actact = Body_c.getOneACT_ACTOnR698(FunctionBody_c
                    .getOneACT_FNBOnR695(m_testFunc[funcNum]));
            if (actact != null) {
                actact.Clear_blocks();
            }
            break;
        default:
            fail("clearAction: Unknown Activity type constant");
        }
        m_requiresClear = false;
    }

    static public void tearDownActionData() throws RecognitionException,
            TokenStreamException {
        if (m_requiresClear) {
            clearActionData(m_funcType, m_funcNum);
        }
    }

    public void validateBlkStmtVal(int numBlock, int numStmt, int numVal) {
        FunctionBody_c[] fb = FunctionBody_c.FunctionBodyInstances(modelRoot);
        BridgeBody_c[] bb = BridgeBody_c.BridgeBodyInstances(modelRoot);
        OperationBody_c[] ob = OperationBody_c
                .OperationBodyInstances(modelRoot);
        StateActionBody_c[] sab = StateActionBody_c
                .StateActionBodyInstances(modelRoot);
        DerivedAttributeBody_c[] dab = DerivedAttributeBody_c
                .DerivedAttributeBodyInstances(modelRoot);
        TransitionActionBody_c[] tab = TransitionActionBody_c
                .TransitionActionBodyInstances(modelRoot);
        Body_c b[] = Body_c.BodyInstances(modelRoot);
        assertEquals(b.length, fb.length + bb.length + ob.length + sab.length
                + dab.length + tab.length);
        Block_c[] blk = Block_c.BlockInstances(modelRoot);
        assertEquals(numBlock, blk.length);
        Body_c[] bods = Body_c.BodyInstances(modelRoot);
        for (int i = 0; i < bods.length; ++i)
            assertEquals(IdAssigner.NULL_UUID, bods[i].getCurrentscope_id());
        Statement_c[] st = Statement_c.StatementInstances(modelRoot);
        assertEquals(numStmt, st.length);
        Value_c[] val = Value_c.ValueInstances(modelRoot);
        assertEquals(numVal, val.length);
    }

    // Accessor IDs for domain functions in the model
    static public final int DBA_PARAM_FUNC = 0;
    static public final int GFUNC = 1;
    static public final int TEST_OAL = 2;
    static private String funcs[] = { "dba_param_func", //$NON-NLS-1$
            "gfunc", //$NON-NLS-1$
            "test_oal", //$NON-NLS-1$
            };
    public static Function_c[] m_testFunc = new Function_c[funcs.length];

    private void populateFunctionInstances() {
        class Function_test1_c implements ClassQueryInterface_c {
            Function_test1_c(String p) {
                m_p = p;
            }

            private String m_p;

            public boolean evaluate(Object inst) {
                Function_c selected = (Function_c) inst;
                return selected.getName().equals(m_p);
            }
        }
        for (int i = 0; i < funcs.length; ++i) {
            Function_c testFunc = Function_c.FunctionInstance(modelRoot,
                    new Function_test1_c(funcs[i]));
            if (testFunc != null) {
                if (m_testFunc[i] == null)
                    m_testFunc[i] = testFunc;
            } else
                fail("Missing function " + funcs[i]);//$NON-NLS-1$
        }
    }

}


text:
package water.api;

import hex.ModelMetricsBinomialGLM.ModelMetricsMultinomialGLM;
import hex.ModelMetricsMultinomial;
import water.api.API.Direction;

public class ModelMetricsMultinomialGLMV3 extends ModelMetricsMultinomialV3<ModelMetricsMultinomialGLM, ModelMetricsMultinomialGLMV3> {
  @API(help="residual deviance",direction = Direction.OUTPUT)
  public double residual_deviance;

  @API(help="null deviance",direction = Direction.OUTPUT)
  public double null_deviance;

  @API(help="AIC",direction = Direction.OUTPUT)
  public double AIC;

  @API(help="null DOF", direction= Direction.OUTPUT)
  public long null_degrees_of_freedom;

  @API(help="residual DOF", direction= Direction.OUTPUT)
  public long residual_degrees_of_freedom;

  @Override
  public ModelMetricsMultinomialV3 fillFromImpl(ModelMetricsMultinomial mms) {
    ModelMetricsMultinomialGLM modelMetrics = (ModelMetricsMultinomialGLM)mms;
    super.fillFromImpl(modelMetrics);
    this.AIC = modelMetrics._AIC;
    this.residual_deviance = modelMetrics._resDev;
    this.null_deviance = modelMetrics._nullDev;
    this.null_degrees_of_freedom = modelMetrics._nullDegressOfFreedom;
    this.residual_degrees_of_freedom = modelMetrics._residualDegressOfFreedom;
    return this;
  }

}


text:
namespace Anycmd.Repositories
{
    using Model;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Represents the domain repository that uses the <see cref="Anycmd.Repositories.IRepositoryContext"/>
    /// and <see cref="Anycmd.Repositories.IRepository<TAggregateRoot>"/> instances to perform aggregate
    /// operations.
    /// </summary>
    public class RegularDomainRepository : DomainRepository
    {
        #region Private Fields
        private readonly IRepositoryContext _context;
        private readonly HashSet<ISourcedAggregateRoot> _dirtyHash = new HashSet<ISourcedAggregateRoot>();
        #endregion

        #region Ctor
        /// <summary>
        /// Initializes a new instance of <c>RegularDomainRepository</c> class.
        /// </summary>
        /// <param name="context">The <see cref="Anycmd.Repositories.IRepositoryContext"/> instance to which the
        /// <c>RegularDomainRepository</c> forwards the repository operations.</param>
        public RegularDomainRepository(IRepositoryContext context)
        {
            this._context = context;
        }
        #endregion

        #region Public Properties
        /// <summary>
        /// Gets the <see cref="Anycmd.Repositories.IRepositoryContext"/> instance.
        /// </summary>
        public IRepositoryContext Context
        {
            get { return this._context; }
        }
        #endregion

        #region Protected Methods
        /// <summary>
        /// Commits the changes registered in the domain repository.
        /// </summary>
        protected override void DoCommit()
        {
            foreach (var aggregateRootObj in this.SaveHash)
            {
                this._context.RegisterNew(aggregateRootObj);
            }
            foreach (var aggregateRootObj in this._dirtyHash)
            {
                this._context.RegisterModified(aggregateRootObj);
            }

            this._context.Commit();

            this._dirtyHash.ToList().ForEach(this.DelegatedUpdateAndClearAggregateRoot);
            this._dirtyHash.Clear();
        }
        /// <summary>
        /// Disposes the object.
        /// </summary>
        /// <param name="disposing">A <see cref="System.Boolean"/> value which indicates whether
        /// the object should be disposed explicitly.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!this.Committed)
                {
                    try
                    {
                        this.Commit();
                    }
                    catch
                    {
                        this.Rollback();
                        throw;
                    }
                }
                this._context.Dispose();
            }
            base.Dispose(disposing);
        }
        #endregion

        #region IDomainRepository Members
        /// <summary>
        /// Gets the instance of the aggregate root with the specified identifier.
        /// </summary>
        /// <param name="id">The identifier of the aggregate root.</param>
        /// <returns>The instance of the aggregate root with the specified identifier.</returns>
        public override TAggregateRoot Get<TAggregateRoot>(Guid id)
        {
            var querySaveHash = from p in this.SaveHash
                                where p.Id.Equals(id)
                                select p;
            var queryDirtyHash = from p in this._dirtyHash
                                 where p.Id.Equals(id)
                                 select p;
            var sourcedAggregateRoots = querySaveHash as ISourcedAggregateRoot[] ?? querySaveHash.ToArray();
            if (sourcedAggregateRoots.Any())
                return sourcedAggregateRoots.FirstOrDefault() as TAggregateRoot;
            var aggregateRoots = queryDirtyHash as ISourcedAggregateRoot[] ?? queryDirtyHash.ToArray();
            if (aggregateRoots.Any())
                return aggregateRoots.FirstOrDefault() as TAggregateRoot;

            var result = _context.Query<TAggregateRoot>().FirstOrDefault(ar => ar.Id.Equals(id));
            // Clears the aggregate root since version info is not needed in regular repositories.
            this.DelegatedUpdateAndClearAggregateRoot(result);
            return result;
        }
        /// <summary>
        /// Saves the aggregate represented by the specified aggregate root to the repository.
        /// </summary>
        /// <param name="aggregateRoot">The aggregate root that is going to be saved.</param>
        public override void Save<TAggregateRoot>(TAggregateRoot aggregateRoot)
        {
            if (_context.Query<TAggregateRoot>().Any(ar => ar.Id.Equals(aggregateRoot.Id)))
            {
                if (!this._dirtyHash.Contains(aggregateRoot))
                    this._dirtyHash.Add(aggregateRoot);
                this.Committed = false;
            }
            else
            {
                base.Save<TAggregateRoot>(aggregateRoot);
            }

        }
        #endregion

        #region IUnitOfWork Members
        /// <summary>
        /// Gets a <see cref="System.Boolean"/> value which indicates
        /// whether the Unit of Work could support Microsoft Distributed
        /// Transaction Coordinator (MS-DTC).
        /// </summary>
        public override bool DistributedTransactionSupported
        {
            get { return _context.DistributedTransactionSupported; }
        }
        /// <summary>
        /// Rollback the transaction.
        /// </summary>
        public override void Rollback()
        {
            this._context.Rollback();
        }
        #endregion
    }
}


text:
package redis

import (
	"errors"
	"strconv"
	"testing"

	"fmt"

	"github.com/fagongzi/goetty"
)

func TestParserCommandReplyForStatus(t *testing.T) {
	status := "OK"

	buf := goetty.NewByteBuf(1024)
	WriteStatus([]byte(status), buf)
	checkStatusReply(buf, t, status)
}

func TestParserCommandReplyForStatusNotComplete(t *testing.T) {
	status := "OK"

	buf := goetty.NewByteBuf(1024)
	buf.WriteByte('+')
	buf.Write([]byte(status))

	checkNotComplete(buf, t)

	buf.Write(Delims)

	checkStatusReply(buf, t, status)
}

func TestParserCommandReplyForError(t *testing.T) {
	errInfo := "this is a error"

	buf := goetty.NewByteBuf(1024)
	WriteError([]byte(errInfo), buf)

	checkErrorReply(buf, t, fmt.Sprintf(" %s", errInfo))
}

func TestParserCommandReplyForErrorNotComplete(t *testing.T) {
	errInfo := "this is a error"

	buf := goetty.NewByteBuf(1024)
	buf.WriteByte('-')
	buf.WriteByte(' ')
	buf.Write([]byte(errInfo))
	checkNotComplete(buf, t)

	buf.Write(Delims)
	checkErrorReply(buf, t, fmt.Sprintf(" %s", errInfo))
}

func TestParserCommandReplyForInteger(t *testing.T) {
	var valueNumber int64
	valueNumber = 100
	value := fmt.Sprintf("%d", valueNumber)

	buf := goetty.NewByteBuf(1024)
	WriteInteger(valueNumber, buf)

	checkIntegerReply(buf, t, value)
}

func TestParserCommandReplyForNotComplete(t *testing.T) {
	var valueNumber int64
	valueNumber = 100
	value := fmt.Sprintf("%d", valueNumber)

	buf := goetty.NewByteBuf(1024)
	buf.WriteByte(':')
	buf.Write([]byte(value))
	checkNotComplete(buf, t)

	buf.Write(Delims)
	checkIntegerReply(buf, t, value)
}

func TestParserCommandReplyForBulk(t *testing.T) {
	buf := goetty.NewByteBuf(1024)
	WriteBulk(nil, buf)
	checkBulkNilReply(buf, t)

	data := "this is a bulk data"
	WriteBulk([]byte(data), buf)
	checkBulkReply(buf, t, data)
}

func TestParserCommandReplyForBulkNotComplete(t *testing.T) {
	buf := goetty.NewByteBuf(1024)
	buf.WriteByte('$')
	buf.Write(NullBulk)
	checkNotComplete(buf, t)

	buf.Write(Delims)
	checkBulkNilReply(buf, t)

	data := "this is a bulk data"
	buf.WriteByte('$')
	buf.Write(goetty.StringToSlice(strconv.Itoa(len(data))))
	buf.Write(Delims)
	buf.Write([]byte(data))

	checkNotComplete(buf, t)

	buf.Write(Delims)
	checkBulkReply(buf, t, data)
}

func TestParserCommandReplyForArray(t *testing.T) {
	buf := goetty.NewByteBuf(1024)
	status := "OK"
	errInfo := errors.New("this is a error")
	var integer int64
	integer = 100
	bulk := []byte("this is a bulk")

	lst := []interface{}{status, errInfo, integer, bulk}
	WriteArray(lst, buf)

	checkArrayReply(buf, t, len(lst))
}

func TestParserCommandReplyForArrayNotComplete(t *testing.T) {
	buf := goetty.NewByteBuf(1024)
	status := "OK"
	errInfo := errors.New("this is a error")
	var integer int64
	integer = 100
	bulk := []byte("this is a bulk")

	lst := []interface{}{status, errInfo, integer, bulk}

	buf.WriteByte('*')
	buf.Write(goetty.StringToSlice(strconv.Itoa(len(lst))))
	buf.Write(Delims)
	for i := 0; i < len(lst); i++ {
		switch v := lst[i].(type) {
		case []interface{}:
			WriteArray(v, buf)
		case [][]byte:
			WriteSliceArray(v, buf)
		case []byte:
			WriteBulk(v, buf)
		case nil:
			WriteBulk(nil, buf)
		case int64:
			WriteInteger(v, buf)
		case string:
			WriteStatus(goetty.StringToSlice(v), buf)
		case error:
			WriteError(goetty.StringToSlice(v.Error()), buf)
		default:
			panic(fmt.Sprintf("invalid array type %T %v", lst[i], v))
		}

		if i < len(lst)-1 {
			checkNotComplete(buf, t)
		}
	}

	checkArrayReply(buf, t, len(lst))
}

func checkNotComplete(buf *goetty.ByteBuf, t *testing.T) {
	complete, _, err := readCommandReply(buf)
	if err != nil {
		t.Failed()
	}

	if complete {
		t.Failed()
	}
}

func checkErrorReply(buf *goetty.ByteBuf, t *testing.T, info string) {
	complete, value, err := readCommandReply(buf)
	if err != nil {
		t.Error(err)
	}

	if !complete {
		t.Error("not complete")
	}

	rsp, ok := value.(ErrResp)
	if !ok {
		t.Error("type mis match")
	}

	if string(rsp) != info {
		t.Error("value mis match")
	}
}

func checkStatusReply(buf *goetty.ByteBuf, t *testing.T, info string) {
	complete, value, err := readCommandReply(buf)
	if err != nil {
		t.Error(err)
	}

	if !complete {
		t.Error("not complete")
	}

	rsp, ok := value.(StatusResp)
	if !ok {
		t.Error("type mis match")
	}

	if string(rsp) != info {
		t.Error("value mis match")
	}
}

func checkIntegerReply(buf *goetty.ByteBuf, t *testing.T, num string) {
	complete, value, err := readCommandReply(buf)
	if err != nil {
		t.Error(err)
	}

	if !complete {
		t.Error("not complete")
	}

	rsp, ok := value.(IntegerResp)
	if !ok {
		t.Error("type mis match")
	}

	if string(rsp) != num {
		t.Error("value mis match")
	}
}

func checkArrayReply(buf *goetty.ByteBuf, t *testing.T, num int) []interface{} {
	complete, value, err := readCommandReply(buf)
	if err != nil {
		t.Error(err)
	}

	if !complete {
		t.Error("not complete")
	}

	rsps, ok := value.([]interface{})
	if !ok {
		t.Error("type mis match")
	}

	if len(rsps) != num {
		t.Error("values mis match")
	}

	return rsps
}

func checkBulkNilReply(buf *goetty.ByteBuf, t *testing.T) {
	complete, value, err := readCommandReply(buf)
	if err != nil {
		t.Error(err)
	}

	if !complete {
		t.Error("not complete")
	}

	_, ok := value.(NullBulkResp)
	if !ok {
		t.Error("type mis match")
	}
}

func checkBulkReply(buf *goetty.ByteBuf, t *testing.T, data string) {
	complete, value, err := readCommandReply(buf)
	if err != nil {
		t.Error(err)
	}

	if !complete {
		t.Error("not complete")
	}

	rsp, ok := value.(BulkResp)
	if !ok {
		t.Error("type mis match")
	}

	if string(rsp) != data {
		t.Error("value mis match")
	}
}

func TestReadLine(t *testing.T) {
	buf := goetty.NewByteBuf(1024)
	buf.Write([]byte("*3\r\n"))

	_, _, err := readLine(buf)
	if err != nil {
		t.Error("read line error")
	}
}


text:
<?php

namespace Pyrech\ComposerChangelogs\UrlGenerator;

use Pyrech\ComposerChangelogs\Version;

class GitlabUrlGenerator extends AbstractUrlGenerator
{
    /** @var string */
    private $host;

    /**
     * @param string $host
     */
    public function __construct($host)
    {
        $this->host = $host;
    }

    /**
     * {@inheritdoc}
     */
    protected function getDomain()
    {
        return $this->host;
    }

    /**
     * {@inheritdoc}
     */
    public function generateCompareUrl($sourceUrlFrom, Version $versionFrom, $sourceUrlTo, Version $versionTo)
    {
        // Check if both urls come from the supported domain
        // It avoids problems when one url is from another domain or is local
        if (!$this->supports($sourceUrlFrom) || !$this->supports($sourceUrlTo)) {
            return false;
        }

        $sourceUrlFrom = $this->generateBaseUrl($sourceUrlFrom);
        $sourceUrlTo = $this->generateBaseUrl($sourceUrlTo);

        if ($sourceUrlFrom !== $sourceUrlTo) {
            // Comparison across forks is not supported
            return false;
        }

        return sprintf(
            '%s/compare/%s...%s',
            $sourceUrlTo,
            $this->getCompareVersion($versionFrom),
            $this->getCompareVersion($versionTo)
        );
    }

    /**
     * {@inheritdoc}
     */
    public function generateReleaseUrl($sourceUrl, Version $version)
    {
        if ($version->isDev()) {
            return false;
        }

        $baseUrl = $this->generateBaseUrl($sourceUrl);

        if (!$baseUrl) {
            return false;
        }

        return sprintf(
            '%s/tags/%s',
            $this->generateBaseUrl($sourceUrl),
            $version->getPretty()
        );
    }
}


text:
describe NodeProp::Version do

  it 'exists' do
    NodeProp::Version.should_not be_nil
  end

  it 'is a module' do
    NodeProp::Version.should be_a_kind_of(Module)
  end

  it 'returns the standard format for the version information it contains when to_standard_format is called' do
    NodeProp::Version.to_standard_format.should == [NodeProp::Version::MAJOR, NodeProp::Version::MINOR, NodeProp::Version::PATCH].join('.')
  end

end


text:
class MonitorParam < ApplicationRecord
  belongs_to :organization
  validates :organization, uniqueness: true
  after_save :reschedule_monitoring_for_all_organization_services
  after_destroy :reschedule_monitoring_for_all_organization_services

  def reschedule_monitoring_for_all_organization_services
    ServiceVersion.current.joins(:service).where(
      services: {organization_id: organization_id}
    ).each(&:reschedule_health_checks)
  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/FabMenu.iml" filepath="$PROJECT_DIR$/FabMenu.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/fabmenu/fabmenu.iml" filepath="$PROJECT_DIR$/fabmenu/fabmenu.iml" />
    </modules>
  </component>
</project>


text:
namespace gestures {

Vector2 Add(const Vector2& left, const Vector2& right) {
  return Vector2(left).Add(right);
}

Vector2 Sub(const Vector2& left, const Vector2& right) {
  return Vector2(left).Sub(right);
}

float Dot(const Vector2& left, const Vector2& right) {
  return left.x * right.x +  left.y * right.y;
}

MetricsProperties::MetricsProperties(PropRegistry* prop_reg)
    : two_finger_close_horizontal_distance_thresh(
          prop_reg,
          "Two Finger Horizontal Close Distance Thresh",
          50.0),
      two_finger_close_vertical_distance_thresh(
          prop_reg,
          "Two Finger Vertical Close Distance Thresh",
          45.0) {}

FingerMetrics::FingerMetrics()
    : tracking_id_(-1) {}

FingerMetrics::FingerMetrics(short tracking_id)
    : tracking_id_(tracking_id) {}

FingerMetrics::FingerMetrics(const FingerState& state,
                             MetricsProperties* properties,
                             stime_t timestamp)
    : tracking_id_(state.tracking_id),
      position_(state.position_x, state.position_y),
      origin_position_(state.position_x, state.position_y),
      origin_time_(timestamp),
      properties_(properties) {}

void FingerMetrics::Update(const FingerState& state, stime_t timestamp,
                           bool gesture_start) {
  Vector2 new_position = Vector2(state.position_x, state.position_y);
  delta_ = Sub(new_position, position_);
  position_ = new_position;

  if (gesture_start) {
    start_position_ = position_;
    start_time_ = timestamp;
  }
}

bool Metrics::CloseEnoughToGesture(const Vector2& pos_a,
                                   const Vector2& pos_b) const {
  float horiz_axis_sq =
      properties_->two_finger_close_horizontal_distance_thresh.val_ *
      properties_->two_finger_close_horizontal_distance_thresh.val_;
  float vert_axis_sq =
      properties_->two_finger_close_vertical_distance_thresh.val_ *
      properties_->two_finger_close_vertical_distance_thresh.val_;
  Vector2 delta = Sub(pos_a, pos_b);
  // Equation of ellipse:
  //    ,.--+--..
  //  ,'   V|    `.   x^2   y^2
  // |      +------|  --- + --- < 1
  //  \        H  /   H^2   V^2
  //   `-..__,,.-'
  return vert_axis_sq * delta.x * delta.x + horiz_axis_sq * delta.y * delta.y
         < vert_axis_sq * horiz_axis_sq;
}

Metrics::Metrics(MetricsProperties* properties) : properties_(properties) {}

const FingerMetrics* Metrics::GetFinger(short tracking_id) const {
  auto iter = fingers_.find(FingerMetrics(tracking_id));
  if (iter != fingers_.end())
    return iter;
  else
    return NULL;
}

const FingerMetrics* Metrics::GetFinger(const FingerState& state) const {
  return GetFinger(state.tracking_id);
}

void Metrics::Update(const HardwareState& hwstate) {
  int previous_count = fingers_.size();
  int existing_count = 0;
  int new_count = 0;

  // create metrics for new fingers
  for (int i=0; i<hwstate.finger_cnt; ++i) {
    const FingerState& state = hwstate.fingers[i];
    auto iter = fingers_.find(FingerMetrics(state.tracking_id));
    if (iter == fingers_.end()) {
      fingers_.push_back(FingerMetrics(state, properties_,
                                       hwstate.timestamp));
      ++new_count;
    } else {
      ++existing_count;
    }
  }

  // remove metrics for lifted fingers
  if (existing_count != previous_count) {
    auto iter = fingers_.begin();
    while (iter != fingers_.end()) {
      if (!hwstate.GetFingerState(iter->tracking_id()))
        iter = fingers_.erase(iter);
      else
        ++iter;
    }
  }

  // when a new finger has been added or a finger has been removed
  // we consider this to be a new gesture starting
  bool gesture_start = (existing_count != previous_count) || new_count > 0;
  for (FingerMetrics& finger: fingers_) {
    const FingerState* fs = hwstate.GetFingerState(finger.tracking_id());
    if (!fs) {
      Err("Unexpected missing finger state!");
      continue;
    }
    finger.Update(*fs, hwstate.timestamp, gesture_start);
  }
}

void Metrics::Clear() {
  fingers_.clear();
}

}  // namespace gestures


text:
namespace Neighbours.Data.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using Common.Models;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Neighbours.Common.GlobalConstants;
    using Neighbours.Common.ValidationAttributes;

    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class User : IdentityUser
    {
        private ICollection<Post> posts;
        private ICollection<Community> communities;
        private ICollection<Like> likes;

        public User()
        {
            this.posts = new HashSet<Post>();
            this.communities = new HashSet<Community>();
            this.likes = new HashSet<Like>();
            this.WaitingList = "|";
        }

        [Required]
        [DisplayName("First name")]
        [StringLength(25, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
        public string FirstName { get; set; }

        [Required]
        [DisplayName("Last name")]
        [StringLength(25, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
        public string LastName { get; set; }

        [DisplayName("Date of birth")]
        [BirthDate(GlobalValidationConstants.MinBirthDate, GlobalValidationConstants.MinAgeToRegister, ErrorMessage = "You are either too old or too young.")]
        public DateTime? BirthDate { get; set; }

        public int ProfileImageId { get; set; }

        [Display(Name = "Profile Image")]
        public virtual ProfileImage ProfileImage { get; set; }

        public Gender Gender { get; set; }

        public string WaitingList { get; set; }

        [NotMapped]
        public int[] WaitingListCommunities
        {
            get
            {
                return this.WaitingList.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
            }

            set
            {
                this.WaitingList = string.Join("|", value);
            }
        }

        public virtual ICollection<Post> Posts
        {
            get
            {
                return this.posts;
            }

            set
            {
                this.posts = value;
            }
        }

        public virtual ICollection<Community> Communities
        {
            get
            {
                return this.communities;
            }

            set
            {
                this.communities = value;
            }
        }

        public virtual ICollection<Like> Likes
        {
            get
            {
                return this.likes;
            }

            set
            {
                this.likes = value;
            }
        }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Add custom user claims here
            return userIdentity;
        }
    }
}


text:
In this small project I want to create an example of how to use the Spring Framework for Dependency Injection.
This is a reference for myself but if someone finds this helpful that would be great.

### Basic Idea of the example
We have a PC which has dependencies on keyboard, mouse, monitor, power supply and internet.

For testing purposes we might like to inject part of the periphery (maybe mocks).

Also I'd like to compare using the annotations vs. the XML configuration.

### License (MIT)
See LICENSE


text:
trait Ctx {
  trait Tree
}

trait Lst[+A] {
  def zip[A1 >: A, B](that: Lst[B]): Nothing
}

object Test {

  // both of these methods should be transformed by uncurry
  // such that List[c.Tree] becomes List[Ctx#Tree]:
  def foo1(c: Ctx)(l: Lst[c.Tree]) = l zip l
  def foo2[@specialized T](c: Ctx)(l: Lst[c.Tree], t: T) = l zip l

  // if this doesn't happen for the 2nd method, the specialization
  // transformation fails
}


text:
require File.expand_path('../support/helpers', __FILE__)

describe "runit_test::default" do
  include Helpers::RunitTest

  describe "packages" do
    it 'has been installed' do
      package("runit").must_be_installed
    end
  end
end


text:
class QRegExp;

/// Collection of loaded data sets for use with Qt's model view architecture
///
/// Data sets can be points, lines or meshes.
class GeometryCollection : public QAbstractListModel
{
    Q_OBJECT
    public:
        typedef std::vector<std::shared_ptr<Geometry>> GeometryVec;

        GeometryCollection(QObject * parent = 0);

        /// Get current list of geometries
        const GeometryVec& get() const { return m_geometries; }

        /// Remove all geometries from the list
        void clear();
        /// Remove and unload all geometries whose filenames matched by given QRegExp object
        void unloadFiles(const QRegExp & filenameRegex);

        /// Find the first index to a geometry with label matching the given pattern
        QModelIndex findLabel(const QRegExp & labelPattern);

        // Following implemented from QAbstractListModel:
        virtual int rowCount(const QModelIndex & parent = QModelIndex()) const;
        virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
        virtual Qt::ItemFlags flags(const QModelIndex& index) const;
        virtual bool setData(const QModelIndex & index, const QVariant & value,
                             int role = Qt::EditRole);

        virtual bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());

    public slots:
        /// Add to the list of loaded geometries
        ///
        /// If `reloaded` is true, search existing geometry for
        /// `geom->fileName()` and if found, replace the existing geometry.
        ///
        /// If `replaceLabel` is true, search existing geometry for a matching
        /// `geom->label()` and replace the existing geometry if found.
        void addGeometry(std::shared_ptr<Geometry> geom, bool replaceLabel = false, bool reloaded = false);
        void mutateGeometry(std::shared_ptr<GeometryMutator> mutator);

    private:
        void loadPointFilesImpl(const QStringList& fileNames, bool removeAfterLoad);
        int findMatchingRow(const QRegExp & filenameRegex);

        GeometryVec m_geometries;
};

#endif // DISPLAZ_GEOMETRYCOLLECTION_H_INCLUDED


text:
using System;
using System.Collections.Generic;
using System.Data;
using Aurora.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;

namespace Aurora.DataManager.Migration.Migrators
{
    public class EstateMigrator_2 : Migrator
    {
        public EstateMigrator_2()
        {
            Version = new Version(0, 0, 2);
            MigrationName = "Estate";

            schema = new List<SchemaDefinition>();

            AddSchema("estateregions", ColDefs(
                ColDef("RegionID", ColumnTypes.String36),
                ColDef("EstateID", ColumnTypes.Integer11)
            ), IndexDefs(
                IndexDef(new string[]{ "RegionID"}, IndexType.Primary)
            ));

            AddSchema("estatesettings", ColDefs(
                ColDef("EstateID", ColumnTypes.Integer11),
                ColDef("EstateName", ColumnTypes.String100),
                ColDef("EstateOwner", ColumnTypes.String36),
                ColDef("ParentEstateID", ColumnTypes.Integer11),
                ColDef("Settings", ColumnTypes.Text)
            ), IndexDefs(
                IndexDef(new string[]{ "EstateID" }, IndexType.Primary),
                IndexDef(new string[]{ "EstateOwner"}, IndexType.Index)
            ));
        }

        protected override void DoCreateDefaults(IDataConnector genericData)
        {
            EnsureAllTablesInSchemaExist(genericData);
        }

        protected override bool DoValidate(IDataConnector genericData)
        {
            return TestThatAllTablesValidate(genericData);
        }

        protected override void DoMigrate(IDataConnector genericData)
        {
            DoCreateDefaults(genericData);
        }

        protected override void DoPrepareRestorePoint(IDataConnector genericData)
        {
            CopyAllTablesToTempVersions(genericData);
        }
    }
}


text:
package org.apereo.cas.support.oauth.web;

import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.support.oauth.OAuthConstants;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.util.CommonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * This is {@link OAuth20ConsentApprovalViewResolver}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
public class OAuth20ConsentApprovalViewResolver implements ConsentApprovalViewResolver {
    private static final Logger LOGGER = LoggerFactory.getLogger(OAuth20ConsentApprovalViewResolver.class);

    @Override
    public ModelAndView resolve(final J2EContext context, final OAuthRegisteredService service) {

        final String bypassApprovalParameter = context.getRequestParameter(OAuthConstants.BYPASS_APPROVAL_PROMPT);
        LOGGER.debug("bypassApprovalParameter: {}", bypassApprovalParameter);

        /**
         * Inbound request; approval handled already.
         */
        if (StringUtils.isNotBlank(bypassApprovalParameter) || isConsentApprovalBypassed(context, service)) {
            return new ModelAndView();
        }
        return redirectToApproveView(context, service);
    }

    /**
     * Is consent approval bypassed?
     *
     * @param context the context
     * @param service the service
     * @return true/false
     */
    protected boolean isConsentApprovalBypassed(final J2EContext context, final OAuthRegisteredService service) {
        return service.isBypassApprovalPrompt();
    }

    /**
     * Redirect to approve view model and view.
     *
     * @param ctx the ctx
     * @param svc the svc
     * @return the model and view
     */
    protected ModelAndView redirectToApproveView(final J2EContext ctx, final OAuthRegisteredService svc) {
        String callbackUrl = ctx.getFullRequestURL();
        callbackUrl = CommonHelper.addParameter(callbackUrl, OAuthConstants.BYPASS_APPROVAL_PROMPT, "true");
        final Map<String, Object> model = new HashMap<>();
        model.put("callbackUrl", callbackUrl);
        model.put("serviceName", svc.getName());
        LOGGER.debug("callbackUrl: {}", callbackUrl);
        return new ModelAndView(OAuthConstants.CONFIRM_VIEW, model);
    }
}


text:
[![Package Version](https://img.shields.io/pypi/v/chatterbot-corpus.svg)](https://pypi.python.org/pypi/chatterbot-corpus/)
[![Build Status](https://travis-ci.org/gunthercox/chatterbot-corpus.svg?branch=master)](https://travis-ci.org/gunthercox/chatterbot-corpus)

These modules are used to quickly train ChatterBot to respond to various inputs in different languages.
Although much of ChatterBot is designed to be language independent, it is still useful to have these
training sets available to prime a fresh database and make the variety of responses that a bot can yield
much more diverse.

For instructions on how to use these data sets, please refer to the [project documentation](http://chatterbot.readthedocs.io/en/latest/training.html#training-with-corpus-data).

All training data contained within this corpus is user contributed.

If you are interested in contributing support for a new language please create a pull request. Additions are welcomed!

# Create your own Corpus Training data

Chatterbot is a very flexible and dynamic chatbot that you easily can create your own training data and structure.

Create or copy an existing .yml file and put that file in a existing or a new directory you created under `chatterbot_corpus\data\<NEW DIRECTORY>`
Edit that file with any text editor that you like to work with.

In the beginning of the file you set one or two categories.
```
categories:
- myown
- my own categories
````

Then can you start your actual training conversation data.

```
conversations:
- - Hello
  - Hello
- - Hi
  - Hello
```

# Install your training corpus data to Django
You need to install chatterbot as the [Quick Start Guide](http://chatterbot.readthedocs.io/en/stable/quickstart.html).
When the installation are done, please go to `(Virtual Env)/lib/pythonX.X/site-packages/chatterbot_corpus/data/` directory.
Here is the same structure as you can find in this GitHub repo, here is the area where you can create your own directories and conversation files.

When you are done with your files, then can you edit the Django `setting.py` file and locate the chatterbot training section.
Here do you need to add `chatterbot.corpus.<DIRECTORY>.<FILENAME>`

```
    'training_data': [
         'chatterbot.corpus.english.greeting',
         'chatterbot.corpus.custom.myown',
         'chatterbot.corpus.swedish.food'
    ]
```

When you are done, please proceed with the Django Chatterbot Training session.

# Unit Testing

"A true professional does not waste the time and money of other people by handing over software that is not reasonably free of obvious bugs; that has not undergone minimal unit testing; that does not meet the specifications and requirements; that is gold-plated with unnecessary features; or that looks like junk." – Daniel Read

```
pip install -r dev-requirements.txt
nosetests
```


text:
import _ from 'underscore';
import $ from 'jquery';
import {LayoutView} from 'backbone.marionette';
import {Model} from 'backbone';
import PlaylistsList from './Playlists';
import {localStorage} from '../../../utils';
import app from '../../../application';

const Playlists = LayoutView.extend({

    className: 'layout-playlists',

    template: require('../templates/playlists.ejs'),

    regions: {
        list: '.js-playlists'
    },

    behaviors: {
        BtnToTop: {},
        Search: {
            container: '.js-search-container',
            filterCheckboxBehavior: true,
            tags: false
        },
        Loader: {}
    },

    events: {
        'click @ui.link': '_onClickLink'
    },

    ui: {
        link: '.js-link',
        loader: '.js-loader'
    },

    model: new Model({
        search: '',
        filterByRBTV: true,
        filterByLP: true,
        _loading: false
    }),

    /** @returns {{search: String, rbtv: String|null, lp: String|null}} */
    getChannelFilter() {
        return {
            search: this.model.get('search'),
            rbtv: this.model.get('filterByRBTV'),
            lp: this.model.get('filterByLP')
        };
    },

    startLoading() {
        this.model.set('_loading', true);
    },

    stopLoading() {
        this.model.set('_loading', false);
    },

    modelEvents() {
        return {
            'change:search': () => {
                this.renderCollection(
                    _.extend(this.getChannelFilter(), { resetResults: true })
                );
            },

            'change:filterByRBTV change:filterByLP': () => {
                this.renderCollection(
                    _.extend(this.getChannelFilter(), { resetResults: true })
                );
            }
        };
    },

    /**
     * Lifecycle methods
     */

    constructor(options = {}) {
        if (options.disableSearch) {
            this.behaviors = _.omit(this.behaviors, 'Search');
        }

        if (options.disableBtnToTop) {
            this.behaviors = _.omit(this.behaviors, 'BtnToTop');
        }

        LayoutView.call(this, options);
    },

    initialize() {
        this.renderCollection = _.debounce(this.renderCollection, 150, { leading: false });
    },

    onRender() {
        this.getRegion('list').show(
            new PlaylistsList({
                collection: this.collection
            })
        );

        this.stickit();
    },

    onDestroy() {
        this._killScroll();
    },

    /**
     * Public methods
     */

    /**
     * @param {Boolean|Object} filter
     */
    renderCollection(filter = false) {
        if (filter === true) {
            filter = localStorage.get('playlists.filter');

            if (filter) {
                this.model.set({
                    search: filter.search,
                    filterByRBTV: filter.rbtv,
                    filterByLP: filter.lp
                });
            }
        }

        if (!filter) {
            filter = this.getChannelFilter();
        }

        // Cache filter
        localStorage.set('playlists.filter', _.omit(filter, 'increaseResults', 'resetResults'));

        this.stopLoading();

        // Search collection
        this.collection.search(filter);

        this._initScroll();
    },

    /**
     * Private methods
     */

    _initScroll() {
        this._killScroll();

        $(window).on('scroll.playlists', this._onScroll.bind(this));
    },

    _killScroll() {
        $(window).off('scroll.playlists');
    },

    /**
     * Event handler
     */

    _onClickLink(e) {
        const $link = $(e.currentTarget);
        const route = $link.attr('href').substr(1);

        app.navigate(route);

        e.preventDefault();
    },

    _onScroll() {
        const maxY = $(document).height() - window.innerHeight - 600;
        const y = window.scrollY;

        if (y >= maxY) {
            this._killScroll();

            this.renderCollection(
                _.extend(this.getChannelFilter(), { increaseResults: true })
            );
        }
    }
});

export default Playlists;


text:
package com.dataintuitive.luciuscore
package model.v4
package lenses

import filters._
import lenses.PerturbationLenses._

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should._

class LensesTestv4 extends AnyFlatSpec with Matchers {

  val p = Perturbation("123", Information(), Profiles(), TRT_EMPTY, Nil)

  "Minimal Instantiation" should "simply work" in {
    assert(p.id === "123")
  }

  it should "work with lenses for first-level attributes" in {
    val thisLens = PerturbationLenses.idLens
    assert(thisLens.get(p) === "123")
    assert(thisLens.get(thisLens.set(p, "456")) === "456")
  }

  it should "work with lenses for nested attributes" in {
    val profilesLens = PerturbationLenses.profilesLens
    val filtersLens = PerturbationLenses.filtersLens
    val trtTLens = PerturbationLenses.trtLens
    profilesLens.get(p) shouldBe a [Profiles]
    filtersLens.get(p) shouldBe a [Filters]
    trtLens.get(p) shouldBe a [Treatment]
  }

}


text:
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE FlexibleContexts  #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Leader
  ( StateId
  , Judge
  , Follower
  , LeaderFunction
  , FollowerFunction
  , mkInMemoryJudge
  , mkFollower
  , debounceLeader
  , killableFollower
  , runFollower
  ) where

import ClassyPrelude.Conduit
import Control.Monad.Trans.Unlift (askRunBase, MonadBaseUnlift)
import Control.Concurrent.Async.Lifted.Safe (Concurrently (..), withAsync)

newtype StateId = StateId Word
  deriving Eq

-- | Decides who will be the leader
newtype Judge m state = Judge (Follower m state -> m ())

mkInMemoryJudge :: forall state m n. (MonadIO m, MonadIO n, MonadBaseUnlift IO n) => m (Judge n state)
mkInMemoryJudge = liftIO $ do
  leaderBaton <- newMVar ()
  stateVar :: TVar (Maybe (StateId, state)) <- newTVarIO Nothing
  stateIdVar <- newTVarIO 0
  return $ Judge $ \Follower {..} -> do
    let beLeader = withMVar leaderBaton $ const $ do
          mstate <- atomically $ readTVar stateVar
          let setState state = atomically $ do
                next <- readTVar stateIdVar
                writeTVar stateIdVar $! next + 1
                writeTVar stateVar $ Just (StateId next, state)
          runConduit
             $ (followerOnLeader (snd <$> mstate) >>= yield)
            .| awaitForever setState
        beFollower = followerRun $ readTVar stateVar >>= maybe retrySTM return
    unlift <- askRunBase
    liftIO $
      runConcurrently $ Concurrently (unlift beLeader)
                     *> Concurrently (unlift beFollower)

type LeaderFunction m state = Maybe state -> ConduitM () state m state
type FollowerFunction m state = STM (StateId, state) -> m ()

data Follower m state = Follower
  { followerOnLeader :: !(LeaderFunction m state)
  , followerRun :: !(FollowerFunction m state)
  }

runFollower :: Judge m state -> Follower m state -> m ()
runFollower (Judge run) = run

mkFollower :: LeaderFunction m state
           -> FollowerFunction m state
           -> Follower m state
mkFollower = Follower

debounceLeader :: (Monad m, Eq state) => LeaderFunction m state -> LeaderFunction m state
debounceLeader inner mstate =
    (inner mstate >>= yield) .| debounce
  where
    debounce = await >>= maybe (error "impossible") (\state -> yield state *> loop state)

    loop state1 = await >>= maybe (return state1)
      (\state2 ->
        if state1 == state2
          then loop state1
          else yield state2 >> loop state2)

killableFollower :: (MonadIO m, MonadBaseUnlift IO m)
                 => (state -> m ()) -> FollowerFunction m state
killableFollower inner getState = do
  unlift <- askRunBase
  let loop (stateid, state) =
        join $ withAsync (unlift (inner state)) $ const $ atomically $ do
          (newid, newstate) <- getState
          checkSTM $ stateid /= newid
          return $ loop (newid, newstate)
  liftIO $ atomically getState >>= loop


text:
- [vim-jp/go-vim](http://github.com/vim-jp/go-vim) or [fatih/vim-go](http://github.com/fatih/vim-go) or other provider of drop command.
- [ToQoz/goimps](http://github.com/ToQoz/goimps)
	`go get github.com/ToQoz/goimps`
	Add `set rtp+=$GOPATH/src/github.com/ToQoz/goimps/misc/vim` to your vimrc

## Installation

### with NeoBundle

Add `NeoBundle 'ToQoz/unite-go-imports'`

### with Vundle

Add `Bundle 'ToQoz/unite-go-imports'`

## Configuration

If you want to use custom godrop/goimport command that is not :Drop/:Import nor :GoDrop/:GoImport.

```vim
g:godrop_command = "CustomeGoDrop"
g:goimport_command = "CustomeGoImport"
```

if you don't define `g:godrop_command`/`goimport_command`, there are defined by this script by following rules

```vim
if exists(":Import")
  g:goimport_command = "Import"
else
  g:goimport_command = "GoImport"
endif

if exists(":Drop")
  g:godrop_command = "Drop"
else
  g:godrop_command = "GoDrop"
endif
```

## Usage

```
:Unite go/import
:Unite go/drop
```


text:
namespace KeyPay.DomainModels.V2.PaySlip
{
    public class PaySlipLeaveModel
    {
        public string LeaveCategory { get; set; }
        public decimal Amount { get; set; }
        public string Notes { get; set; }
    }
}