text:
package com.redhat.ceylon.compiler.java.loader;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.antlr.runtime.Token;

import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.cmr.impl.InvalidArchiveException;
import com.redhat.ceylon.common.Backend;
import com.redhat.ceylon.common.ModuleSpec;
import com.redhat.ceylon.common.StatusPrinter;
import com.redhat.ceylon.compiler.java.codegen.AnnotationModelVisitor;
import com.redhat.ceylon.compiler.java.codegen.BoxingDeclarationVisitor;
import com.redhat.ceylon.compiler.java.codegen.BoxingVisitor;
import com.redhat.ceylon.compiler.java.codegen.CeylonCompilationUnit;
import com.redhat.ceylon.compiler.java.codegen.CeylonTransformer;
import com.redhat.ceylon.compiler.java.codegen.CodeGenError;
import com.redhat.ceylon.compiler.java.codegen.CompilerBoxingDeclarationVisitor;
import com.redhat.ceylon.compiler.java.codegen.CompilerBoxingVisitor;
import com.redhat.ceylon.compiler.java.codegen.DeferredVisitor;
import com.redhat.ceylon.compiler.java.codegen.DefiniteAssignmentVisitor;
import com.redhat.ceylon.compiler.java.codegen.InterfaceVisitor;
import com.redhat.ceylon.compiler.java.codegen.JvmMissingNativeVisitor;
import com.redhat.ceylon.compiler.java.codegen.SmallDeclarationVisitor;
import com.redhat.ceylon.compiler.java.codegen.SmallVisitor;
import com.redhat.ceylon.compiler.java.codegen.TypeParameterCaptureVisitor;
import com.redhat.ceylon.compiler.java.codegen.UnsupportedVisitor;
import com.redhat.ceylon.compiler.java.tools.CeylonLog;
import com.redhat.ceylon.compiler.java.tools.CeylonPhasedUnit;
import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager;
import com.redhat.ceylon.compiler.java.tools.LanguageCompiler;
import com.redhat.ceylon.compiler.java.tools.LanguageCompiler.CompilerDelegate;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError;
import com.redhat.ceylon.compiler.typechecker.analyzer.UnsupportedError;
import com.redhat.ceylon.compiler.typechecker.analyzer.UsageWarning;
import com.redhat.ceylon.compiler.typechecker.analyzer.Warning;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits;
import com.redhat.ceylon.compiler.typechecker.parser.LexError;
import com.redhat.ceylon.compiler.typechecker.parser.ParseError;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilerAnnotation;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Statement;
import com.redhat.ceylon.compiler.typechecker.tree.TreeUtil;
import com.redhat.ceylon.compiler.typechecker.tree.UnexpectedError;

import com.redhat.ceylon.compiler.typechecker.util.AssertionVisitor;
import com.redhat.ceylon.compiler.typechecker.util.WarningSuppressionVisitor;
import com.redhat.ceylon.javax.tools.JavaFileManager;
import com.redhat.ceylon.javax.tools.JavaFileObject.Kind;
import com.redhat.ceylon.javax.tools.StandardLocation;
import com.redhat.ceylon.langtools.source.util.TaskEvent;
import com.redhat.ceylon.langtools.source.util.TaskListener;
import com.redhat.ceylon.langtools.tools.javac.code.Symbol;
import com.redhat.ceylon.langtools.tools.javac.code.Symtab;
import com.redhat.ceylon.langtools.tools.javac.code.Types;
import com.redhat.ceylon.langtools.tools.javac.code.Symbol.ClassSymbol;
import com.redhat.ceylon.langtools.tools.javac.code.Symbol.PackageSymbol;
import com.redhat.ceylon.langtools.tools.javac.code.Type.ClassType;
import com.redhat.ceylon.langtools.tools.javac.comp.Annotate;
import com.redhat.ceylon.langtools.tools.javac.comp.AttrContext;
import com.redhat.ceylon.langtools.tools.javac.comp.Check;
import com.redhat.ceylon.langtools.tools.javac.comp.Enter;
import com.redhat.ceylon.langtools.tools.javac.comp.Env;
import com.redhat.ceylon.langtools.tools.javac.comp.Todo;
import com.redhat.ceylon.langtools.tools.javac.file.Locations;
import com.redhat.ceylon.langtools.tools.javac.main.Option;
import com.redhat.ceylon.langtools.tools.javac.tree.EndPosTable;
import com.redhat.ceylon.langtools.tools.javac.tree.JCTree;
import com.redhat.ceylon.langtools.tools.javac.tree.JCTree.JCCompilationUnit;
import com.redhat.ceylon.langtools.tools.javac.util.Abort;
import com.redhat.ceylon.langtools.tools.javac.util.Context;
import com.redhat.ceylon.langtools.tools.javac.util.List;
import com.redhat.ceylon.langtools.tools.javac.util.Log;
import com.redhat.ceylon.langtools.tools.javac.util.Log.WriterKind;
import com.redhat.ceylon.langtools.tools.javac.util.Options;
import com.redhat.ceylon.langtools.tools.javac.util.Position;
import com.redhat.ceylon.langtools.tools.javac.util.SourceLanguage;
import com.redhat.ceylon.langtools.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.redhat.ceylon.langtools.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
import com.redhat.ceylon.langtools.tools.javac.util.SourceLanguage.Language;
import com.redhat.ceylon.model.cmr.ArtifactResult;
import com.redhat.ceylon.model.loader.AbstractModelLoader;
import com.redhat.ceylon.model.loader.Timer;
import com.redhat.ceylon.model.loader.model.LazyModule;
import com.redhat.ceylon.model.typechecker.model.Declaration;
import com.redhat.ceylon.model.typechecker.model.ModelUtil;
import com.redhat.ceylon.model.typechecker.model.Module;
import com.redhat.ceylon.model.typechecker.model.Package;
import com.redhat.ceylon.model.typechecker.model.Setter;
import com.redhat.ceylon.model.typechecker.model.Type;
import com.redhat.ceylon.model.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.model.typechecker.model.Unit;

public class CeylonEnter extends Enter {

    public static CeylonEnter instance(Context context) {
        CeylonEnter instance = (CeylonEnter)context.get(enterKey);
        if (instance == null){
            instance = new CeylonEnter(context);
            context.put(enterKey, instance);
        }
        return instance;
    }

    private CeylonTransformer gen;
    private boolean hasRun = false;
    private PhasedUnits phasedUnits;
    private CompilerDelegate compilerDelegate;
    private Log log;
    private AbstractModelLoader modelLoader;
    private Options options;
    private Timer timer;
    private CeyloncFileManager fileManager;
    private boolean verbose;
    private Check chk;
    private Types types;
    private Symtab symtab;
    private Todo todo;
    private boolean isBootstrap;
    private Annotate annotate;
    private Set<Module> modulesAddedToClassPath = new HashSet<Module>();
    private Set<ModuleSpec> modulesAddedToAptClassPath = new HashSet<ModuleSpec>();
    private TaskListener taskListener;
    private SourceLanguage sourceLanguage;
    private StatusPrinter sp;
    private boolean hasJavaAndCeylonSources;

    protected CeylonEnter(Context context) {
        super(context);
        // make sure it's loaded first
        CeylonClassReader.instance(context);
        try {
            gen = CeylonTransformer.getInstance(context);
        } catch (Exception e) {
            // FIXME
            e.printStackTrace();
        }

        phasedUnits = LanguageCompiler.getPhasedUnitsInstance(context);
        compilerDelegate = LanguageCompiler.getCompilerDelegate(context);
        log = CeylonLog.instance(context);
        modelLoader = CeylonModelLoader.instance(context);
        options = Options.instance(context);
        timer = com.redhat.ceylon.compiler.java.util.Timer.instance(context);
        fileManager = (CeyloncFileManager) context.get(JavaFileManager.class);
        verbose = options.get(Option.VERBOSE) != null;
        isBootstrap = options.get(Option.BOOTSTRAPCEYLON) != null;
        chk = Check.instance(context);
        types = Types.instance(context);
        symtab = Symtab.instance(context);
        todo = Todo.instance(context);
        annotate = Annotate.instance(context);
        taskListener = context.get(TaskListener.class);
        sourceLanguage = SourceLanguage.instance(context);

        // now superclass init
        init(context);

        boolean isProgressPrinted = options.get(Option.CEYLONPROGRESS) != null && StatusPrinter.canPrint();
        if(isProgressPrinted && taskListener == null){
            sp = LanguageCompiler.getStatusPrinterInstance(context);
        }else{
            sp = null;
        }
    }

    @Override
    public void main(List<JCCompilationUnit> trees) {
        // complete the javac AST with a completed ceylon model
        timer.startTask("prepareForTypeChecking");
        prepareForTypeChecking(trees);
        timer.endTask();
        List<JCCompilationUnit> javaTrees = List.nil();
        List<JCCompilationUnit> ceylonTrees = List.nil();
        // split them in two sets: java and ceylon
        for(JCCompilationUnit tree : trees){
            if(tree instanceof CeylonCompilationUnit)
                ceylonTrees = ceylonTrees.prepend(tree);
            else
                javaTrees = javaTrees.prepend(tree);
        }
        timer.startTask("Enter on Java trees");
        // enter java trees first to set up their ClassSymbol objects for ceylon trees to use during type-checking
        if(!javaTrees.isEmpty()){
            setupImportedPackagesForJavaTrees(javaTrees);
            hasJavaAndCeylonSources = true;
        }
        if(isBootstrap || hasJavaAndCeylonSources){
            super.main(trees);
        }
        // now we can type-check the Ceylon code
        completeCeylonTrees(trees);
        if(isBootstrap || hasJavaAndCeylonSources){
            // bootstrapping the language module is a bit more complex
            resetAndRunEnterAgain(trees);
        }else{
            timer.startTask("Enter on Ceylon trees");
            // and complete their new trees
            try {
                sourceLanguage.push(Language.CEYLON);
                super.main(ceylonTrees);
            } finally {
                sourceLanguage.pop();
            }
            timer.endTask();
        }
    }

    private void setupImportedPackagesForJavaTrees(List<JCCompilationUnit> javaTrees) {
        JCTree.Visitor visitor = new ImportScanner(modelLoader);
        for(JCCompilationUnit unit : javaTrees){
            unit.accept(visitor);
        }
    }

    private void resetAndRunEnterAgain(List<JCCompilationUnit> trees) {
        timer.startTask("Resetting all trees for bootstrap");

        // get rid of some caches and state
        chk.compiled.clear();
        types.reset();
        annotate.reset();
        super.reset();

        // reset all class symbols
        for(ClassSymbol classSymbol : symtab.classes.values()){
            if(Util.isLoadedFromSource(classSymbol)
                    || (classSymbol.sourcefile != null && classSymbol.sourcefile.getKind() == Kind.SOURCE)){
                PackageSymbol pkg = classSymbol.packge();
                String name = pkg.getQualifiedName().toString();
                if(name.startsWith(AbstractModelLoader.CEYLON_LANGUAGE) || name.startsWith("com.redhat.ceylon.compiler.java"))
                    resetClassSymbol(classSymbol);
            }
        }

        // reset the trees
        JCTypeResetter jcTypeResetter = new JCTypeResetter();
        for(JCCompilationUnit tree : trees){
            tree.accept(jcTypeResetter);
        }

        // and reset the list of things to compile, because we got rid of the Env key we used to look them up
        // so they'd appear as extra things to compile when we do Enter
        todo.reset();
        timer.endTask();

        timer.startTask("Enter on Java+Ceylon trees");
        // now do Enter on all the java+ceylon code
        try {
            sourceLanguage.push(Language.CEYLON);
            super.main(trees);
        } finally {
            sourceLanguage.pop();
        }
        timer.endTask();
    }

    /**
     * This resets a ClassSymbol recursively, for bootstrap
     */
    private void resetClassSymbol(ClassSymbol classSymbol) {
        // look for inner classes
        if(classSymbol.members_field != null){
            for(Symbol member : classSymbol.getEnclosedElements()){
                if(member instanceof ClassSymbol){
                    resetClassSymbol((ClassSymbol)member);
                }
            }
        }

        // reset its type, we need to keep it
        com.redhat.ceylon.langtools.tools.javac.code.Type.ClassType classType = (ClassType) classSymbol.type;
        classType.all_interfaces_field = null;
        classType.interfaces_field = null;
        classType.supertype_field = null;
        classType.typarams_field = null;

        // reset its members and completer
        classSymbol.members_field = null;
        classSymbol.completer = null;
    }

    @Override
    protected com.redhat.ceylon.langtools.tools.javac.code.Type classEnter(JCTree tree, Env<AttrContext> env) {
        if(tree instanceof CeylonCompilationUnit){
            sourceLanguage.push(Language.CEYLON);
            try{
                return super.classEnter(tree, env);
            }finally{
                sourceLanguage.pop();
            }
        }else
            return super.classEnter(tree, env);
    }

    public void prepareForTypeChecking(List<JCCompilationUnit> trees) {
        if (hasRun)
            throw new RuntimeException("Waaaaa, running twice!!!");
        //By now le language module version should be known (as local)
        //or we should use the default one.
        int numParserErrors = log.nerrors;
        // load the standard modules
        timer.startTask("loadStandardModules");
        compilerDelegate.loadStandardModules(modelLoader);
        timer.endTask();

        // load the modules we are compiling first
        hasRun = true;

        // make sure we don't load the files we are compiling from their class files
        timer.startTask("setupSourceFileObjects");
        compilerDelegate.setupSourceFileObjects(trees, modelLoader);
        timer.endTask();

        // resolve module dependencies
        timer.startTask("verifyModuleDependencyTree");
        compilerDelegate.resolveModuleDependencies(phasedUnits);
        timer.endTask();

        // now load package descriptors
        timer.startTask("loadPackageDescriptors");
        compilerDelegate.loadPackageDescriptors(modelLoader);
        timer.endTask();

        // at this point, abort if we had any errors logged due to module descriptors
        timer.startTask("collectTreeErrors");
        collectTreeErrors(false, false);
        timer.endTask();
        // check if we abort on errors or not
        if (options.get(Option.CEYLONCONTINUE) == null) {
            // if we didn't have any errors on module descriptors,
            // we can go on, none were logged so
            // they can't be re-logged and duplicated later on
            if(log.nerrors - numParserErrors > 0)
                throw new Abort();
        }
    }

    public void completeCeylonTrees(List<JCCompilationUnit> trees){
        // run the type checker
        timer.startTask("Ceylon type checking");
        typeCheck();
        // some debugging
        //printModules();
        timer.startTask("Ceylon code generation");
        /*
         * Here we convert the ceylon tree to its javac AST, after the typechecker has run
         */
        Timer nested = timer.nestedTimer();
        if(sp != null){
            sp.clearLine();
            sp.log("Generating AST");
        }
        int i=1;
        int size = trees.size();
        for (JCCompilationUnit tree : trees) {
            if (tree instanceof CeylonCompilationUnit) {
                CeylonCompilationUnit ceylonTree = (CeylonCompilationUnit) tree;
                gen.setMap(ceylonTree.lineMap);
                CeylonPhasedUnit phasedUnit = (CeylonPhasedUnit)ceylonTree.phasedUnit;

                if(sp != null){
                    sp.clearLine();
                    sp.log("Generating ["+(i++)+"/"+size+"] ");
                    sp.log(phasedUnit.getPathRelativeToSrcDir());
                }

                gen.setFileObject(phasedUnit.getFileObject());
                nested.startTask("Ceylon code generation for " + phasedUnit.getUnitFile().getName());
                TaskEvent event = new TaskEvent(TaskEvent.Kind.PARSE, tree);
                if (taskListener != null) {
                    taskListener.started(event);
                }
                ceylonTree.defs = gen.transformAfterTypeChecking(ceylonTree.ceylonTree).toList();
                if (taskListener != null) {
                    taskListener.finished(event);
                }
                nested.endTask();
                if(isVerbose("ast")){
                    log.printRawLines(WriterKind.ERROR, "Model tree for "+tree.getSourceFile());
                    log.printRawLines(WriterKind.ERROR, ceylonTree.ceylonTree.toString());
                }
                if(isVerbose("code")){
                    log.printRawLines(WriterKind.ERROR, "Java code generated for "+tree.getSourceFile());
                    log.printRawLines(WriterKind.ERROR, ceylonTree.toString());
                }
            }
        }
        timer.startTask("Ceylon error generation");
        printGeneratorErrors();
        timer.endTask();
        // write some stats
        if(verbose)
            modelLoader.printStats();
    }

    private boolean isVerbose(String key) {
        return verbose || options.get(Option.VERBOSE.text + ":" + key) != null;
    }

    public void addOutputModuleToClassPath(Module module){
        RepositoryManager repositoryManager = fileManager.getOutputRepositoryManager();
        ArtifactResult artifact = null;
        try {
            ArtifactContext ctx = new ArtifactContext(null, module.getNameAsString(), module.getVersion(), ArtifactContext.CAR, ArtifactContext.JAR);
            artifact = repositoryManager.getArtifactResult(ctx);
        } catch (InvalidArchiveException e) {
            log.error("ceylon", "Module car " + e.getPath()
                    +" obtained from repository " + e.getRepository()
                    +" has an invalid SHA1 signature: you need to remove it and rebuild the archive, since it"
                    +" may be corrupted.");
        } catch (Exception e) {
            String moduleName = module.getNameAsString();
            if(!module.isDefaultModule())
                moduleName += "/" + module.getVersion();
            log.error("ceylon", "Exception occured while trying to resolve module "+moduleName);
            e.printStackTrace();
        }
        addModuleToClassPath(module, false, artifact);
    }

    public boolean isModuleInClassPath(Module module){
        return modulesAddedToClassPath.contains(module);
    }

    public void addModuleToClassPath(Module module, boolean errorIfMissing, ArtifactResult result) {
        if(verbose)
            log.printRawLines(WriterKind.NOTICE, "[Adding module to classpath: "+module.getNameAsString()+"/"+module.getVersion()+"]");

        Collection<File> classPath = fileManager.getLocations().getLocation(StandardLocation.CLASS_PATH);

        File artifact = null;
        try {
            artifact = result != null ? result.artifact() : null;
        } catch (Exception e) {
            String moduleName = module.getNameAsString();
            if(!module.isDefaultModule())
                moduleName += "/" + module.getVersion();
            log.error("ceylon", "Exception occured while trying to resolve module "+moduleName);
            e.printStackTrace();
        }

        if(verbose){
            if(artifact != null)
                log.printRawLines(WriterKind.NOTICE, "[Found module at : "+artifact.getPath()+"]");
            else
                log.printRawLines(WriterKind.NOTICE, "[Could not find module]");
        }

        if(modulesAddedToClassPath.add(module)){
            if(artifact != null && artifact.exists()){
                ArrayList<File> newClassPath = new ArrayList<File>(classPath);
                newClassPath.add(artifact);
                try {
                    fileManager.getLocations().setLocation(StandardLocation.CLASS_PATH, newClassPath);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                ((LazyModule)module).loadPackageList(result);
            }else if(errorIfMissing){
                log.error("ceylon", "Failed to find module "+module.getNameAsString()+"/"+module.getVersion()+" in repositories");
            }
        }else if(verbose){
            log.printRawLines(WriterKind.NOTICE, "[Module already added to classpath]");
        }
    }

    public void addModuleToAptPath(ModuleSpec module, ArtifactResult result) {
        if(verbose)
            log.printRawLines(WriterKind.NOTICE, "[Adding APT module to APT classpath: "+module+"]");

        Collection<File> classPath = fileManager.getLocations().getLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH);

        File artifact = null;
        try {
            artifact = result != null ? result.artifact() : null;
        } catch (Exception e) {
            log.error("ceylon", "Exception occured while trying to resolve APT module "+module);
            e.printStackTrace();
        }

        if(verbose){
            if(artifact != null)
                log.printRawLines(WriterKind.NOTICE, "[Found APT module at : "+artifact.getPath()+"]");
            else
                log.printRawLines(WriterKind.NOTICE, "[Could not find APT module]");
        }

        if(modulesAddedToAptClassPath.add(module)){
            if(artifact != null && artifact.exists()){
                ArrayList<File> newClassPath = classPath == null
                        ? new ArrayList<File>(1)
                        : new ArrayList<File>(classPath);
                newClassPath.add(artifact);
                try {
                    fileManager.getLocations().setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH, newClassPath);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }else{
                log.error("ceylon", "Failed to find APT module "+module+" in repositories");
            }
        }else if(verbose){
            log.printRawLines(WriterKind.NOTICE, "[APT Module already added to APT classpath]");
        }
    }

    private void typeCheck() {
        final java.util.List<PhasedUnit> listOfUnits = phasedUnits.getPhasedUnits();

        Module jdk = modelLoader.getJDKBaseModule();
        Package javaLangPackage = jdk.getPackage("java.lang");
        for (PhasedUnit pu : listOfUnits) {
        	pu.getUnit().setJavaLangPackage(javaLangPackage);
        }

        // Delegate to an external typechecker (e.g. the IDE build)
        compilerDelegate.typeCheck(listOfUnits);

        if(sp != null){
            sp.clearLine();
            sp.log("Preparation phase");
        }

        int size = listOfUnits.size();

        int i=1;
        // This phase is proper to the Java backend
        ForcedCaptureVisitor fcv = new ForcedCaptureVisitor();

        for (PhasedUnit pu : listOfUnits) {
            if(sp != null)
                progressPreparation(1, i++, size, pu);
            Unit unit = pu.getUnit();
            final CompilationUnit compilationUnit = pu.getCompilationUnit();
            compilationUnit.visit(fcv);
            for (Declaration d: unit.getDeclarations()) {
                if (d instanceof TypedDeclaration
                        && !(d instanceof Setter)
                        // skip already captured members
                        && !d.isCaptured()) {
                    compilationUnit.visit(new MethodOrValueReferenceVisitor((TypedDeclaration) d));
                }
            }
        }

        UnsupportedVisitor uv = new UnsupportedVisitor();
        JvmMissingNativeVisitor mnv = new JvmMissingNativeVisitor(modelLoader);
        BoxingDeclarationVisitor boxingDeclarationVisitor = new CompilerBoxingDeclarationVisitor(gen);
        BoxingVisitor boxingVisitor = new CompilerBoxingVisitor(gen);
        SmallDeclarationVisitor smallDeclarationVisitor = new SmallDeclarationVisitor();
        SmallVisitor smallVisitor = new SmallVisitor();
        DeferredVisitor deferredVisitor = new DeferredVisitor();
        AnnotationModelVisitor amv = new AnnotationModelVisitor(gen);
        DefiniteAssignmentVisitor dav = new DefiniteAssignmentVisitor();
        TypeParameterCaptureVisitor tpCaptureVisitor = new TypeParameterCaptureVisitor();
        InterfaceVisitor localInterfaceVisitor = new InterfaceVisitor();
        // Extra phases for the compiler

        // boxing visitor depends on boxing decl
        i=1;
        for (PhasedUnit pu : listOfUnits) {
            if(sp != null)
                progressPreparation(2, i++, size, pu);
            pu.getCompilationUnit().visit(uv);
        }
        i=1;
        for (PhasedUnit pu : listOfUnits) {
            if(sp != null)
                progressPreparation(3, i++, size, pu);
            pu.getCompilationUnit().visit(boxingDeclarationVisitor);
            pu.getCompilationUnit().visit(smallDeclarationVisitor);
        }
        i=1;
        // the others can run at the same time
        for (PhasedUnit pu : listOfUnits) {
            if(sp != null)
                progressPreparation(4, i++, size, pu);
            CompilationUnit compilationUnit = pu.getCompilationUnit();
            compilationUnit.visit(mnv);
            compilationUnit.visit(boxingVisitor);
            compilationUnit.visit(smallVisitor);
            compilationUnit.visit(deferredVisitor);
            compilationUnit.visit(amv);
            compilationUnit.visit(dav);
            compilationUnit.visit(tpCaptureVisitor);
            compilationUnit.visit(localInterfaceVisitor);
        }

        i=1;
        for (PhasedUnit pu : listOfUnits) {
            if(sp != null)
                progressPreparation(5, i++, size, pu);
            CompilationUnit compilationUnit = pu.getCompilationUnit();
            compilationUnit.visit(new WarningSuppressionVisitor<Warning>(Warning.class, pu.getSuppressedWarnings()));
        }

        collectTreeErrors(true, true);
    }

    private void progressPreparation(int phase, int i, int size, PhasedUnit pu) {
        sp.clearLine();
        sp.log("Preparing "+phase+"/5 ["+(i++)+"/"+size+"] ");
        sp.log(pu.getPathRelativeToSrcDir());
    }

    private void collectTreeErrors(boolean runAssertions, final boolean reportWarnings) {
        final java.util.List<PhasedUnit> listOfUnits = phasedUnits.getPhasedUnits();

        for (PhasedUnit pu : listOfUnits) {
            pu.getCompilationUnit().visit(new JavacAssertionVisitor((CeylonPhasedUnit) pu, runAssertions){
                @Override
                protected void out(UnexpectedError err) {
                    setSource();
                    logError(getPosition(err.getTreeNode()), "ceylon", err.getMessage());
                }
                @Override
                protected void out(AnalysisError err) {
                    setSource();
                    Node node = getIdentifyingNode(err.getTreeNode());
                    logError(getPosition(node), "ceylon", err.getMessage());
                }
                @Override
                protected void out(Node that, LexError err) {
                    setSource();
                    DiagnosticPosition pos = getPosition((err.getLine()), err.getCharacterInLine());
                    logError(pos, "ceylon", err.getMessage());
                }
                @Override
                protected void out(Node that, ParseError err) {
                    setSource();
                    DiagnosticPosition pos = getPosition((err.getLine()), err.getCharacterInLine());
                    logError(pos, "ceylon", err.getMessage());
                }
                @Override
                protected void out(UnsupportedError err) {
                    setSource();
                    Node node = getIdentifyingNode(err.getTreeNode());
                    logError(getPosition(node), "ceylon", err.getMessage());
                }
                @Override
                protected void out(UsageWarning warning) {
                    if (reportWarnings && !warning.isSuppressed()) {
                        setSource();
                        Node node = getIdentifyingNode(warning.getTreeNode());
                        logWarning(getPosition(node), "ceylon", warning.getMessage());
                    }
                }
                @Override
                protected void out(Node that, String message) {
                    setSource();
                    logError(getPosition(that), "ceylon", message);
                }
            });
        }
    }

    /**
     * Visits the nodes of each unit calling
     * {@link #logError(int, String, String)} for each {@link CodeGenError}
     */
    private void printGeneratorErrors() {
        final java.util.List<PhasedUnit> listOfUnits = phasedUnits.getPhasedUnits();

        for (PhasedUnit pu : listOfUnits) {
            pu.getCompilationUnit().visit(new JavacAssertionVisitor((CeylonPhasedUnit) pu, false){
                @Override
                protected void out(UnexpectedError err) {
                    if(err instanceof CodeGenError){
                        CodeGenError error = ((CodeGenError)err);
                        String location = locationInfo(error);
                        logError(getPosition(err.getTreeNode()),
                                "ceylon.codegen.exception",
                                "compiler bug: "+error.getMessage()+" at " + location);
                    }
                }
                private String locationInfo(CodeGenError error) {
                    if (error.getCause() != null
                            && error.getCause().getStackTrace() != null
                            && error.getCause().getStackTrace().length > 0) {
                        return error.getCause().getStackTrace()[0].toString();
                    } else {
                        return "unknown";
                    }
                }
                // Ignore those
                @Override
                protected void out(AnalysisError err) {}
                @Override
                protected void out(UnsupportedError err) {}
                @Override
                protected void out(UsageWarning warn) {}
                @Override
                protected void out(Node that, ParseError err) {}
                @Override
                protected void out(Node that, LexError err) {}
                @Override
                protected void out(Node that, String message) {}
            });
        }
    }

    protected void logError(int position, String key, String message) {
        logError(toDiagnosticPosition(position), key, message);
    }

    protected void logError(DiagnosticPosition position, String key, String message) {
        boolean prev = log.multipleErrors;
        // we want multiple errors for Ceylon
        log.multipleErrors = true;
        try{
            log.error(position, key, message);
        }finally{
            log.multipleErrors = prev;
        }
    }

    protected void logWarning(int position, String key, String message) {
        logWarning(toDiagnosticPosition(position), key, message);
    }

    protected void logWarning(DiagnosticPosition position, String key, String message) {
        boolean prev = log.multipleErrors;
        // we want multiple errors for Ceylon
        log.multipleErrors = true;
        try{
            log.warning(position, key, message);
        }finally{
            log.multipleErrors = prev;
        }
    }

    protected void logStackTrace(String key, Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        pw.close();
        String tracktrace = sw.toString();
        boolean prev = log.multipleErrors;
        // we want multiple errors for Ceylon
        log.multipleErrors = true;
        try{
            log.printLines(WriterKind.ERROR, key, tracktrace);
        }finally{
            log.multipleErrors = prev;
        }
    }

    protected DiagnosticPosition toDiagnosticPosition(int pos) {
        return (pos == Position.NOPOS ? null : new SimpleDiagnosticPosition(pos));
    }

    private class JavacAssertionVisitor extends AssertionVisitor {
        private CeylonPhasedUnit cpu;
        protected final boolean runAssertions;
        JavacAssertionVisitor(CeylonPhasedUnit cpu, boolean runAssertions){
            this.cpu = cpu;
            this.runAssertions = runAssertions;
            this.includeUsageWarnings(true);
        }

        @Override
        protected void checkType(Statement that, Type type, Node typedNode) {
            if(runAssertions)
                super.checkType(that, type, typedNode);
        }

        @Override
        protected boolean includeError(Message err, int phase) {
            return err.getBackend() == null ||
                    ModelUtil.isForBackend(err.getBackend().asSet(), Backend.Java);
        }

        protected Node getIdentifyingNode(Node node) {
            return TreeUtil.getIdentifyingNode(node);
        }

        protected DiagnosticPosition getPosition(int line, int characterInLine) {
            int pos = getPositionAsInt(line, characterInLine);
            return toDiagnosticPosition(pos);
        }

        protected int getPositionAsInt(int line, int characterInLine) {
            if (line<1) {
                return -1;
            }
            try {
                return cpu.getLineMap().getPosition(line,characterInLine);
            }
            catch (ArrayIndexOutOfBoundsException aie) {
                if (line<2) {
                    return -1;
                }
                return cpu.getLineMap().getPosition(line-1, 0);
            }
        }

        protected DiagnosticPosition getPosition(Node node) {
            if(node != null) {
                Token token = node.getToken();
                if (token != null) {
                    final int startOffset = node.getStartIndex();
                    final int endOffset = node.getStopIndex();
                    final int startLine = token.getLine();
                    final int startCol = token.getCharPositionInLine();

                    if (startOffset < 0 || endOffset < 0) {
                        return getPosition(startLine,
                                startCol);
                    } else {
                        return new DiagnosticPosition() {
                            @Override
                            public JCTree getTree() {
                                return null;
                            }

                            @Override
                            public int getStartPosition() {
                                return startOffset;
                            }

                            @Override
                            public int getPreferredPosition() {
                                return startOffset;
                            }

                            @Override
                            public int getEndPosition(EndPosTable endPosTable) {
                                return endOffset;
                            }
                        };
                    }
                }
            }
            return null;
        }

        protected void setSource() {
            log.useSource(cpu.getFileObject());
        }

        @Override
        protected void initExpectingError(java.util.List<CompilerAnnotation> annotations) {
            if (runAssertions) {
                super.initExpectingError(annotations);
            }
        }
    }

    public boolean hasRun(){
        return hasRun;
    }

    public boolean isCompilingJavaAndCeylonSources() {
        return hasJavaAndCeylonSources;
    }
}


text:
#pragma once
#include <aws/gamelift/GameLift_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/gamelift/model/OperatingSystem.h>
#include <aws/gamelift/model/InstanceCredentials.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace GameLift
{
namespace Model
{

  /**
   *
Information required to remotely connect to a fleet instance. Access is
   * requested by calling GetInstanceAccess.

See Also:
   AWS
   * API Reference

   */
  class AWS_GAMELIFT_API InstanceAccess
  {
  public:
    InstanceAccess();
    InstanceAccess(Aws::Utils::Json::JsonView jsonValue);
    InstanceAccess& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
A unique identifier for the fleet containing the instance being accessed.

     */
    inline const Aws::String& GetFleetId() const{ return m_fleetId; }

    /**
     *
A unique identifier for the fleet containing the instance being accessed.

     */
    inline bool FleetIdHasBeenSet() const { return m_fleetIdHasBeenSet; }

    /**
     *
A unique identifier for the fleet containing the instance being accessed.

     */
    inline void SetFleetId(const Aws::String& value) { m_fleetIdHasBeenSet = true; m_fleetId = value; }

    /**
     *
A unique identifier for the fleet containing the instance being accessed.

     */
    inline void SetFleetId(Aws::String&& value) { m_fleetIdHasBeenSet = true; m_fleetId = std::move(value); }

    /**
     *
A unique identifier for the fleet containing the instance being accessed.

     */
    inline void SetFleetId(const char* value) { m_fleetIdHasBeenSet = true; m_fleetId.assign(value); }

    /**
     *
A unique identifier for the fleet containing the instance being accessed.

     */
    inline InstanceAccess& WithFleetId(const Aws::String& value) { SetFleetId(value); return *this;}

    /**
     *
A unique identifier for the fleet containing the instance being accessed.

     */
    inline InstanceAccess& WithFleetId(Aws::String&& value) { SetFleetId(std::move(value)); return *this;}

    /**
     *
A unique identifier for the fleet containing the instance being accessed.

     */
    inline InstanceAccess& WithFleetId(const char* value) { SetFleetId(value); return *this;}

    /**
     *
A unique identifier for the instance being accessed.

     */
    inline const Aws::String& GetInstanceId() const{ return m_instanceId; }

    /**
     *
A unique identifier for the instance being accessed.

     */
    inline bool InstanceIdHasBeenSet() const { return m_instanceIdHasBeenSet; }

    /**
     *
A unique identifier for the instance being accessed.

     */
    inline void SetInstanceId(const Aws::String& value) { m_instanceIdHasBeenSet = true; m_instanceId = value; }

    /**
     *
A unique identifier for the instance being accessed.

     */
    inline void SetInstanceId(Aws::String&& value) { m_instanceIdHasBeenSet = true; m_instanceId = std::move(value); }

    /**
     *
A unique identifier for the instance being accessed.

     */
    inline void SetInstanceId(const char* value) { m_instanceIdHasBeenSet = true; m_instanceId.assign(value); }

    /**
     *
A unique identifier for the instance being accessed.

     */
    inline InstanceAccess& WithInstanceId(const Aws::String& value) { SetInstanceId(value); return *this;}

    /**
     *
A unique identifier for the instance being accessed.

     */
    inline InstanceAccess& WithInstanceId(Aws::String&& value) { SetInstanceId(std::move(value)); return *this;}

    /**
     *
A unique identifier for the instance being accessed.

     */
    inline InstanceAccess& WithInstanceId(const char* value) { SetInstanceId(value); return *this;}

    /**
     *
IP address that is assigned to the instance.

     */
    inline const Aws::String& GetIpAddress() const{ return m_ipAddress; }

    /**
     *
IP address that is assigned to the instance.

     */
    inline bool IpAddressHasBeenSet() const { return m_ipAddressHasBeenSet; }

    /**
     *
IP address that is assigned to the instance.

     */
    inline void SetIpAddress(const Aws::String& value) { m_ipAddressHasBeenSet = true; m_ipAddress = value; }

    /**
     *
IP address that is assigned to the instance.

     */
    inline void SetIpAddress(Aws::String&& value) { m_ipAddressHasBeenSet = true; m_ipAddress = std::move(value); }

    /**
     *
IP address that is assigned to the instance.

     */
    inline void SetIpAddress(const char* value) { m_ipAddressHasBeenSet = true; m_ipAddress.assign(value); }

    /**
     *
IP address that is assigned to the instance.

     */
    inline InstanceAccess& WithIpAddress(const Aws::String& value) { SetIpAddress(value); return *this;}

    /**
     *
IP address that is assigned to the instance.

     */
    inline InstanceAccess& WithIpAddress(Aws::String&& value) { SetIpAddress(std::move(value)); return *this;}

    /**
     *
IP address that is assigned to the instance.

     */
    inline InstanceAccess& WithIpAddress(const char* value) { SetIpAddress(value); return *this;}

    /**
     *
Operating system that is running on the instance.

     */
    inline const OperatingSystem& GetOperatingSystem() const{ return m_operatingSystem; }

    /**
     *
Operating system that is running on the instance.

     */
    inline bool OperatingSystemHasBeenSet() const { return m_operatingSystemHasBeenSet; }

    /**
     *
Operating system that is running on the instance.

     */
    inline void SetOperatingSystem(const OperatingSystem& value) { m_operatingSystemHasBeenSet = true; m_operatingSystem = value; }

    /**
     *
Operating system that is running on the instance.

     */
    inline void SetOperatingSystem(OperatingSystem&& value) { m_operatingSystemHasBeenSet = true; m_operatingSystem = std::move(value); }

    /**
     *
Operating system that is running on the instance.

     */
    inline InstanceAccess& WithOperatingSystem(const OperatingSystem& value) { SetOperatingSystem(value); return *this;}

    /**
     *
Operating system that is running on the instance.

     */
    inline InstanceAccess& WithOperatingSystem(OperatingSystem&& value) { SetOperatingSystem(std::move(value)); return *this;}

    /**
     *
Credentials required to access the instance.

     */
    inline const InstanceCredentials& GetCredentials() const{ return m_credentials; }

    /**
     *
Credentials required to access the instance.

     */
    inline bool CredentialsHasBeenSet() const { return m_credentialsHasBeenSet; }

    /**
     *
Credentials required to access the instance.

     */
    inline void SetCredentials(const InstanceCredentials& value) { m_credentialsHasBeenSet = true; m_credentials = value; }

    /**
     *
Credentials required to access the instance.

     */
    inline void SetCredentials(InstanceCredentials&& value) { m_credentialsHasBeenSet = true; m_credentials = std::move(value); }

    /**
     *
Credentials required to access the instance.

     */
    inline InstanceAccess& WithCredentials(const InstanceCredentials& value) { SetCredentials(value); return *this;}

    /**
     *
Credentials required to access the instance.

     */
    inline InstanceAccess& WithCredentials(InstanceCredentials&& value) { SetCredentials(std::move(value)); return *this;}

  private:

    Aws::String m_fleetId;
    bool m_fleetIdHasBeenSet;

    Aws::String m_instanceId;
    bool m_instanceIdHasBeenSet;

    Aws::String m_ipAddress;
    bool m_ipAddressHasBeenSet;

    OperatingSystem m_operatingSystem;
    bool m_operatingSystemHasBeenSet;

    InstanceCredentials m_credentials;
    bool m_credentialsHasBeenSet;
  };

} // namespace Model
} // namespace GameLift
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
package se.rj.govie.firebase.listeners.search;

import com.google.firebase.database.DataSnapshot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import se.rj.govie.firebase.RequestType;
import se.rj.govie.model.Cinema;
import se.rj.govie.model.SearchCinemaRequest;
import se.rj.govie.search.repository.CinemaRepository;

import java.util.List;

import static se.rj.govie.firebase.RequestType.CINEMA_SEARCH;

@Component
public class SearchCinemaRequestListener extends SearchRequestListener<SearchCinemaRequest, Cinema> {

    @Autowired
    private CinemaRepository cinemaRepository;

    @Override
    protected RequestType getSearchType() {
        return CINEMA_SEARCH;
    }

    @Override
    protected List<Cinema> search(DataSnapshot dataSnapshot) {
        return cinemaRepository.findNearBy(getSearchRequest(dataSnapshot));
    }
}


text:
var DOPBSPFrontEndFees = new function(){
    'use strict';

    /*
     * Private variables.
     */
    var $ = jQuery.noConflict();

    /*
     * Constructor
     */
    this.__construct = function(){
    };

    /*
     * Get fees.
     *
     * @param ID (Number): calendar ID
     * @param reservationPrice (Number): reservation price
     * @param discountPrice (Number): discount price
     * @param extrasPrice (Number): extras price
     * @param ciDay (String): check in day
     * @param ciDay (String): check in day
     * @param startHour (String): start hour
     * @param endHour (String): start hour
     * @param noItems (Number): number of reserved items
     *
     * @retun fees
     */
    this.get = function(ID,
                        reservationPrice,
                        discountPrice,
                        extrasPrice,
                        ciDay,
                        coDay,
                        startHour,
                        endHour,
                        noItems){
        var dataDays = DOPBSPFrontEnd.calendar[ID]['days']['data'],
        dataFees = DOPBSPFrontEnd.calendar[ID]['fees']['data'],
        dataHours = DOPBSPFrontEnd.calendar[ID]['hours']['data'],
        dataWooCommerce = DOPBSPFrontEnd.calendar[ID]['woocommerce']['data'],
        fees = dataFees['fees'],
        i,
        timeLapse;

        /*
         * Fees are not used in WooCommerce.
         */
        if (dataWooCommerce['enabled']){
            return '';
        }

        /*
         * Verify days/hours.
         */
        coDay = coDay === '' ? ciDay:coDay;
        endHour = endHour === '' ? startHour:endHour;

        /*
         * Calculate price.
         */
        timeLapse = dataHours['enabled'] ? DOPPrototypes.getHoursDifference(startHour, endHour, 'hours')+(dataHours['addLastHourToTotalPrice'] ? 1:0):
                                           DOPPrototypes.getNoDays(ciDay, coDay)-(dataDays['morningCheckOut'] ? 1:0);

        for (i=0; i<fees.length; i++){
            fees[i]['price_total'] = this.getPrice(ID,
                                                   [fees[i]],
                                                   reservationPrice,
                                                   discountPrice,
                                                   extrasPrice,
                                                   ciDay,
                                                   coDay,
                                                   startHour,
                                                   endHour,
                                                   noItems);
        }

        return fees;
    };

    /*
     * Get fees value.
     *
     * @param ID (Number): calendar ID
     * @param fees (Array): list of fees
     * @param reservationPrice (Number): reservation price
     * @param discountPrice (Number): discount price
     * @param extrasPrice (Number): extras price
     * @param ciDay (String): check in day
     * @param ciDay (String): check in day
     * @param startHour (String): start hour
     * @param endHour (String): start hour
     * @param noItems (Number): number of reserved items
     *
     * @retun fees price value
     */
    this.getPrice = function(ID,
                             fees,
                             reservationPrice,
                             discountPrice,
                             extrasPrice,
                             ciDay,
                             coDay,
                             startHour,
                             endHour,
                             noItems){
        var dataDays = DOPBSPFrontEnd.calendar[ID]['days']['data'],
        dataHours = DOPBSPFrontEnd.calendar[ID]['hours']['data'],
        dataWooCommerce = DOPBSPFrontEnd.calendar[ID]['woocommerce']['data'],
        fee,
        i,
        price = 0,
        timeLapse;

        /*
         * Fees are not used in WooCommerce.
         */
        if (dataWooCommerce['enabled']){
            return price;
        }

        /*
         * Verify days/hours.
         */
        coDay = coDay === '' ? ciDay:coDay;
        endHour = endHour === '' ? startHour:endHour;

        /*
         * Calculate price.
         */
        timeLapse = dataHours['enabled'] ? DOPPrototypes.getHoursDifference(startHour, endHour, 'hours')+(dataHours['addLastHourToTotalPrice'] ? 1:0):
                                           DOPPrototypes.getNoDays(ciDay, coDay)-(dataDays['morningCheckOut'] ? 1:0);

        for (i=0; i<fees.length; i++){
            fee = fees[i];

            if (fee['included'] === 'false'){
                price += (fee['operation'] === '-' ? -1:1)
                         *(fee['price_by'] === 'once' ? 1:timeLapse)
                         *parseFloat(fee['price'])
                         *(fee['price_type'] === 'fixed' ? noItems:(reservationPrice+discountPrice+(fee['extras'] === 'true' ? extrasPrice:0)))/
                         (fee['price_type'] === 'fixed' ? 1:100);
            }
        }

        return price;
    };

    /*
     * Set fees details.
     *
     * @param ID (Number): calendar ID
     * @param type (String): set where to display fees details
     *                       "reservation" display details in reservation
     *                       "cart" display details in cart
     * @param fees (Array): list of fees
     * @param reservationPrice (Number): reservation price
     * @param discountPrice (Number): discount price
     * @param extrasPrice (Number): extras price
     * @param ciDay (String): check in day
     * @param ciDay (String): check in day
     * @param startHour (String): start hour
     * @param endHour (String): start hour
     * @param noItems (Number): number of reserved items
     *
     * @retun HTML
     */
    this.set = function(ID,
                        type,
                        fees,
                        ciDay,
                        coDay,
                        startHour,
                        endHour){
        var dataCart = DOPBSPFrontEnd.calendar[ID]['cart']['data'],
        dataHours = DOPBSPFrontEnd.calendar[ID]['hours']['data'],
        HTML = new Array(),
        i;

        /*
         * Verify days/hours.
         */
        coDay = coDay === '' ? ciDay:coDay;
        endHour = endHour === '' ? startHour:endHour;

        if (fees.length > 0){
            HTML.push('
');
            HTML.push('

	');
            HTML.push('

	');
            HTML.push('
');
        }

        for (i=0; i<fees.length; i++){
            if ((type === 'reservation'
                            && (fees[i]['cart'] === 'false'
                                    || !dataCart['enabled']))
                    || (type === 'cart'
                            && fees[i]['cart'] === 'true')){
                HTML.push('
');
                HTML.push('     '+fees[i]['translation']+'	');
                HTML.push('     ');

                /*
                 * Set fee rule.
                 */

                if (fees[i]['price_type'] !== 'fixed'
                        || fees[i]['price_by'] !== 'once'){
                    HTML.push('         ■ ');

                    if (fees[i]['price_type'] === 'fixed'){
                        HTML.push(fees[i]['operation']+DOPBSPFrontEnd.setPrice(ID, fees[i]['price']));
                    }
                    else{
                        HTML.push(fees[i]['operation']+fees[i]['price']+'%');
                    }

                    if (fees[i]['price_by'] !== 'once'){
                        HTML.push('/'+(dataHours['enabled'] ? DOPBSPFrontEnd.text(ID, 'fees', 'byHour'):DOPBSPFrontEnd.text(ID, 'fees', 'byDay')));
                    }
                    HTML.push('
');
                }
                HTML.push('         ');

                /*
                 * Set fee value.
                 */
                if (fees[i]['included'] === 'true'){
                    HTML.push(DOPBSPFrontEnd.text(ID, 'fees', 'included'));
                }
                else{
                    HTML.push(fees[i]['operation']+' '+DOPBSPFrontEnd.setPrice(ID, fees[i]['price_total']));
                }
                HTML.push('         ');
                HTML.push('     	');
                HTML.push('
');
            }
        }

        return HTML.join('');
    };

    return this.__construct();
};


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Univ. fenn. Aboënsis, Ser. A 1(no. 1): 12 (1922)

#### Original name
null

### Remarks
null


text:
using System;
using System.Linq;

namespace SerializersBenchmarks
{
	public class DataFiller
	{
		public static byte[] FillByteArray(int arraySize)
		{
			return FillByteArray(arraySize, 100);
		}

		public static byte[] FillByteArray(int arraySize, int seed)
		{
			Random rnd = new Random (seed);
			byte[] arr = new byte[arraySize];
			rnd.NextBytes (arr);

			return arr;
		}

		public static short[] FillShortArray(int arraySize)
		{
			Random rnd = new Random (100);
			short[] arr = new short[arraySize];

			for(int i=0;i<arraySize;i++)
				arr[i] = (short)(rnd.Next()%65536);

			return arr;
		}

		public static int[] FillIntArray(int arraySize)
		{
			Random rnd = new Random (100);
			int[] arr = new int[arraySize];

			for(int i=0;i<arraySize;i++)
				arr[i] = rnd.Next();

			return arr;
		}

		public static long[] FillLongArray(int arraySize)
		{
			Random rnd = new Random (100);
			long[] arr = new long[arraySize];

			for(int i=0;i<arraySize;i++)
				arr[i] = (long)rnd.Next() + ((long)rnd.Next())<<32;

			return arr;
		}

		public static float[] FillFloatArray(int arraySize)
		{
			Random rnd = new Random (100);
			float[] arr = new float[arraySize];

			for(int i=0;i<arraySize;i++)
				arr[i] = (float)rnd.NextDouble();

			return arr;
		}

		public static double[] FillDoubleArray(int arraySize)
		{
			Random rnd = new Random (100);
			double[] arr = new double[arraySize];

			for(int i=0;i<arraySize;i++)
				arr[i] = rnd.NextDouble();

			return arr;
		}

	}
}


text:
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements.  Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
/* NOCHKSRC */

//

// Author: Humberto Rivero (hurivero@us.ibm.com)

//

// Modified By:

//

//%/////////////////////////////////////////////////////////////////////////////

#ifndef Pegasus_LanguageElementContainer_h

#define Pegasus_LanguageElementContainer_h

#include <cstdlib>

#include <cctype>

#ifdef PEGASUS_OS_HPUX
# ifdef HPUX_IA64_NATIVE_COMPILER
#  include <iostream>
# else
#  include <iostream.h>
# endif
#else
# include <iostream>
#endif

#include <Pegasus/Common/Linkage.h>

#include <Pegasus/Common/Config.h>

#include <Pegasus/Common/String.h>

#include <Pegasus/Common/Array.h>

#include <Pegasus/Common/LanguageElement.h>

#include <Pegasus/Common/LanguageParser.h>

#ifdef PEGASUS_USE_EXPERIMENTAL_INTERFACES

PEGASUS_NAMESPACE_BEGIN

//////////////////////////////////////////////////////////////

//

// LanguageElementContainer::

//

//////////////////////////////////////////////////////////////

/** This class is a container class for AcceptLanguageElement

 */

class PEGASUS_COMMON_LINKAGE LanguageElementContainer{

public:

	/**	This member is used to represent an empty LanguageElementContainer. Using this

        member avoids construction of an empty LanguageElementContainer

        (e.g., LanguageElementContainer()).

	*/

	static const LanguageElementContainer EMPTY;

    /**

     * Default Constructor

     */

	LanguageElementContainer();

	/**

	 * Constructor

	 * @param container Array<LanguageElement> - contructs the object with the elements in the array

	 */

	LanguageElementContainer(Array<LanguageElement> container);

	/** Copy Constructor

	 * @param rhs LanguageElementContainer

	 */

	LanguageElementContainer(const LanguageElementContainer &rhs);

	/**

	 * Destructor

	 */

	virtual ~LanguageElementContainer();

	/**

	 * Deep copy

	 * @param rhs LanguageElementContainer

	 */

	LanguageElementContainer operator=(LanguageElementContainer rhs);

	/** Gets an AcceptLanguageElement object at position index

	 * @param index int position of AcceptLanguageElement

	 * @return AcceptLanguageElement

	 */

	LanguageElement getLanguageElement(int index) const;

	/** Gets all AcceptLanguageElement objects in the container

	 * @return Array<AcceptLanguageElement>

	 */

	Array<LanguageElement> getAllLanguageElements() const;

	/** Returns the String representation of this container

	 * @return String

	 */

	virtual String toString() const;

	/**

	 * Returns the length of the LanguageElementContainer object.

	 * @return Length of the container.

     */

    Uint32 size() const;

	/**

	 * True if the container has element (case INSENSITIVE match of element's language fields

	 * @param LanguageElement element

	 * @return Boolean

	 */

	Boolean contains(LanguageElement element)const;

	/**

	 * Resets this object's iterator, should be called once before using itrNext()

	 */

	void itrStart();

	/**

	 * Returns the next element in the container

	 * Callers should call itrStart() ONCE before making calls to this function and

	 * anytime callers want the iterator reset to the beginning of the container.

	 * @return LanguageElement - the next element the container or LanguageElement::EMPTY_REF

	 * if the end of the container has been reached.

	 */

	LanguageElement& itrNext();

	/**

	 * Removes the element at index from the container.

	 * @param index Uint32 - position of the element in the container to remove

	 */

	void remove(Uint32 index);

	/**

	 * Removes the element matching the parameter, returns -1 if not found

	 * @param element LanguageElement - element to remove

	 * @return int  -1 if element not found, otherwise returns the position of element before the remove.

	 */

	int remove(LanguageElement element);

	/**

	 * Clears the container of all elements

	 */

	void clear();

	/**

	 * Equality based on language fields only

	 */

	Boolean operator==(const LanguageElementContainer rhs)const;

	/**

	 * Inequality based on language fields only

	 */

	Boolean operator!=(const LanguageElementContainer rhs)const;

	/**

	 * Finds the element in the container and returns its position.

	 * @param element LanguageElement - element to find

	 * @return int index of element if found, otherwise -1

	 */

	int find(LanguageElement element)const;

protected:

  	Array<LanguageElement> container;        // holds AcceptLanguageElements

private:

	void buildLanguageElements(Array<String> values);

	void updateIterator();

    int itr_index;					// current position for iterator type access

}; // end LanguageElementContainer

PEGASUS_NAMESPACE_END

#endif  // PEGASUS_USE_EXPERIMENTAL_INTERFACE

#endif


text:
@interface HYVBasicDeleteRequest : HYVBasicRequest

@end


text:
// Copyright 2010-2022 Google LLC
// 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.

#include "ortools/pdlp/sharder.h"

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <numeric>
#include <random>
#include <vector>

#include "Eigen/Core"
#include "Eigen/SparseCore"
#include "absl/random/distributions.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ortools/base/logging.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/threadpool.h"

namespace operations_research::pdlp {
namespace {

using ::Eigen::DiagonalMatrix;
using ::Eigen::VectorXd;
using ::testing::DoubleNear;
using ::testing::ElementsAre;
using ::testing::Test;
using Shard = Sharder::Shard;

// Returns a sparse representation of the matrix
//  7 -0.5 . .
//  1   .  3 2
// -1  .   . 5
Eigen::SparseMatrix<double, Eigen::ColMajor, int64_t> TestSparseMatrix() {
  Eigen::SparseMatrix<double, Eigen::ColMajor, int64_t> mat(3, 4);
  mat.coeffRef(0, 0) = 7;
  mat.coeffRef(0, 1) = -0.5;
  mat.coeffRef(1, 0) = 1;
  mat.coeffRef(1, 2) = 3;
  mat.coeffRef(1, 3) = 2;
  mat.coeffRef(2, 0) = -1;
  mat.coeffRef(2, 3) = 5;
  mat.makeCompressed();
  return mat;
}

// A random matrix with a power law distribution of non-zeros per col.
// Specifically col i has order n/(i+1) non-zeros in expectation.
Eigen::SparseMatrix<double, Eigen::ColMajor, int64_t> LargeSparseMatrix(
    const int64_t size) {
  // Deterministic RNG.
  std::mt19937 rand(48709241);
  std::vector<Eigen::Triplet<double, int64_t>> triplets;
  for (int64_t col = 0; col < size; ++col) {
    int64_t row = -1;
    while (row < size) {
      row += absl::Uniform(rand, 1, col + 2);
      if (row < size) {
        double value = absl::Uniform(rand, 1, 10);
        triplets.emplace_back(row, col, value);
      }
    }
  }
  Eigen::SparseMatrix<double, Eigen::ColMajor, int64_t> mat(size, size);
  mat.setFromTriplets(triplets.begin(), triplets.end());
  return mat;
}

// Verify that the given sharder is consistent and has shards of reasonable
// mass. Requires target_num_shards > 0 and !element_masses.empty().
void VerifySharder(const Sharder& sharder, const int target_num_shards,
                   const std::vector<int64_t>& element_masses) {
  int64_t num_elements = element_masses.size();
  int num_shards = sharder.NumShards();
  ASSERT_EQ(sharder.NumElements(), num_elements);
  ASSERT_GE(num_elements, 1);
  ASSERT_GE(num_shards, 1);
  int64_t elements_so_far = 0;
  for (int shard = 0; shard < num_shards; ++shard) {
    int64_t shard_start = sharder.ShardStart(shard);
    EXPECT_EQ(shard_start, elements_so_far) << " in shard: " << shard;
    int64_t shard_mass = 0;
    EXPECT_GE(sharder.ShardSize(shard), 1) << " in shard: " << shard;
    EXPECT_GE(sharder.ShardMass(shard), 1) << " in shard: " << shard;
    for (int64_t i = 0; i < sharder.ShardSize(shard); ++i) {
      shard_mass += element_masses[shard_start + i];
    }
    EXPECT_EQ(shard_mass, sharder.ShardMass(shard)) << " in shard: " << shard;
    elements_so_far += sharder.ShardSize(shard);
  }
  EXPECT_EQ(elements_so_far, num_elements);

  EXPECT_LE(num_shards, 2 * target_num_shards);
  ASSERT_GE(target_num_shards, 1);
  const int64_t overall_mass =
      std::accumulate(element_masses.begin(), element_masses.end(), int64_t{0});
  const int64_t max_element_mass =
      *std::max_element(element_masses.begin(), element_masses.end());
  const int64_t upper_mass_limit = std::max(
      max_element_mass,
      MathUtil::CeilOfRatio(max_element_mass, int64_t{2}) +
          MathUtil::CeilOfRatio(overall_mass, int64_t{target_num_shards}));
  const int64_t lower_mass_limit =
      overall_mass / target_num_shards -
      MathUtil::CeilOfRatio(max_element_mass, int64_t{2});
  for (int shard = 0; shard < sharder.NumShards(); ++shard) {
    EXPECT_LE(sharder.ShardMass(shard), upper_mass_limit)
        << " in shard: " << shard;
    if (shard + 1 < sharder.NumShards()) {
      EXPECT_GE(sharder.ShardMass(shard), lower_mass_limit)
          << " in shard: " << shard;
    }
  }
}

TEST(SharderTest, SharderFromMatrix) {
  Eigen::SparseMatrix<double, Eigen::ColMajor, int64_t> mat =
      TestSparseMatrix();
  Sharder sharder(mat, /*num_shards=*/2, nullptr);
  VerifySharder(sharder, 2, {4, 2, 2, 3});
}

TEST(SharderTest, UniformSharder) {
  Sharder sharder(/*num_elements=*/10, /*num_shards=*/3, nullptr);
  VerifySharder(sharder, 3, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1});
}

TEST(SharderTest, UniformSharderFromOtherSharder) {
  Sharder other_sharder(/*num_elements=*/5, /*num_shards=*/3, nullptr);
  Sharder sharder(other_sharder, /*num_elements=*/10);
  VerifySharder(sharder, other_sharder.NumShards(),
                {1, 1, 1, 1, 1, 1, 1, 1, 1, 1});
}

TEST(SharderTest, UniformSharderExcessiveShards) {
  Sharder sharder(/*num_elements=*/5, /*num_shards=*/7, nullptr);
  EXPECT_THAT(sharder.ShardStartsForTesting(), ElementsAre(0, 1, 2, 3, 4, 5));
  VerifySharder(sharder, 7, {1, 1, 1, 1, 1});
}

// Regression test for b/225385276
TEST(SharderTest, UniformSharderHugeNumShards) {
  Sharder sharder(/*num_elements=*/5, /*num_shards=*/1'000'000'000, nullptr);
  EXPECT_THAT(sharder.ShardStartsForTesting(), ElementsAre(0, 1, 2, 3, 4, 5));
  VerifySharder(sharder, 7, {1, 1, 1, 1, 1});
}

TEST(SharderTest, UniformSharderOneShard) {
  Sharder sharder(/*num_elements=*/5, /*num_shards=*/1, nullptr);
  EXPECT_THAT(sharder.ShardStartsForTesting(), ElementsAre(0, 5));
  VerifySharder(sharder, 1, {1, 1, 1, 1, 1});
}

TEST(SharderTest, UniformSharderOneElementVector) {
  Sharder sharder(/*num_elements=*/1, /*num_shards=*/5, nullptr);
  EXPECT_THAT(sharder.ShardStartsForTesting(), ElementsAre(0, 1));
  VerifySharder(sharder, 5, {1});
}

TEST(SharderTest, UniformSharderZeroElementVector) {
  Sharder sharder(/*num_elements=*/0, /*num_shards=*/3, nullptr);
  EXPECT_THAT(sharder.ShardStartsForTesting(), ElementsAre(0));
  EXPECT_EQ(sharder.NumShards(), 0);
  EXPECT_EQ(sharder.NumElements(), 0);
  sharder.ParallelForEachShard([](const Shard& /*shard*/) {
    LOG(FATAL) << "There are no shards so this shouldn't be called.";
  });
}

TEST(SharderTest, UniformSharderFromOtherZeroElementSharder) {
  Sharder empty_sharder(/*num_elements=*/0, /*num_shards=*/3, nullptr);
  EXPECT_THAT(empty_sharder.ShardStartsForTesting(), ElementsAre(0));
  EXPECT_EQ(empty_sharder.NumShards(), 0);
  EXPECT_EQ(empty_sharder.NumElements(), 0);
  Sharder sharder(empty_sharder, /*num_elements=*/5);
  EXPECT_THAT(sharder.ShardStartsForTesting(), ElementsAre(0, 5));
  VerifySharder(sharder, 1, {1, 1, 1, 1, 1});
}

TEST(ParallelSumOverShards, SmallExample) {
  VectorXd vec(3);
  vec << 1, 2, 3;
  Sharder sharder(vec.size(), /*num_shards=*/2, nullptr);
  const double sum = sharder.ParallelSumOverShards(
      [&vec](const Shard& shard) { return shard(vec).sum(); });
  EXPECT_EQ(sum, 6.0);
}

TEST(ParallelSumOverShards, SmallExampleUsingVectorBlock) {
  VectorXd vec(3);
  vec << 1, 2, 3;
  auto vec_block = vec.segment(1, 2);
  Sharder sharder(vec_block.size(), /*num_shards=*/2, nullptr);
  const double sum = sharder.ParallelSumOverShards(
      [&vec_block](const Shard& shard) { return shard(vec_block).sum(); });
  EXPECT_EQ(sum, 5.0);
}

TEST(ParallelSumOverShards, SmallExampleUsingConstVectorBlock) {
  VectorXd vec(3);
  vec << 1, 2, 3;
  const VectorXd& const_vec = vec;
  auto vec_block = const_vec.segment(1, 2);
  Sharder sharder(vec_block.size(), /*num_shards=*/2, nullptr);
  const double sum = sharder.ParallelSumOverShards(
      [&vec_block](const Shard& shard) { return shard(vec_block).sum(); });
  EXPECT_EQ(sum, 5.0);
}

TEST(ParallelSumOverShards, SmallExampleUsingDiagonalMatrix) {
  DiagonalMatrix<double, Eigen::Dynamic> diag{{1, 2, 3}};
  Sharder sharder(diag.cols(), /*num_shards=*/2, nullptr);
  const double sum = sharder.ParallelSumOverShards(
      [&diag](const Shard& shard) { return shard(diag).diagonal().sum(); });
  EXPECT_EQ(sum, 6.0);
}

TEST(ParallelSumOverShards, SmallExampleUsingDiagonalMatrixMultiplication) {
  DiagonalMatrix<double, Eigen::Dynamic> diag{{1, 2, 3}};
  VectorXd vec{{1, 1, 1}};
  VectorXd answer(3);
  Sharder sharder(diag.cols(), /*num_shards=*/2, nullptr);
  sharder.ParallelForEachShard(
      [&](const Shard& shard) { shard(answer) = shard(diag) * shard(vec); });
  EXPECT_THAT(answer, ElementsAre(1.0, 2.0, 3.0));
}

TEST(ParallelTrueForAllShards, SmallTrueExample) {
  VectorXd vec(3);
  vec << 1, 2, 3;
  Sharder sharder(vec.size(), /*num_shards=*/2, nullptr);
  const bool result = sharder.ParallelTrueForAllShards(
      [&vec](const Shard& shard) { return (shard(vec).array() > 0.0).all(); });
  EXPECT_TRUE(result);
}

TEST(ParallelTrueForAllShards, SmallFalseExample) {
  VectorXd vec(3);
  vec << 1, 2, 3;
  Sharder sharder(vec.size(), /*num_shards=*/2, nullptr);
  const bool result = sharder.ParallelTrueForAllShards(
      [&vec](const Shard& shard) { return (shard(vec).array() < 2.5).all(); });
  EXPECT_FALSE(result);
}

TEST(MatrixVectorProductTest, SmallExample) {
  Eigen::SparseMatrix<double, Eigen::ColMajor, int64_t> mat =
      TestSparseMatrix();
  Sharder sharder(mat, /*num_shards=*/3, nullptr);
  VectorXd vec(3);
  vec << 1, 2, 3;
  VectorXd ans = TransposedMatrixVectorProduct(mat, vec, sharder);
  EXPECT_THAT(ans, ElementsAre(6.0, -0.5, 6.0, 19));
}

TEST(SetZeroTest, SmallExample) {
  Sharder sharder(3, /*num_shards=*/2, nullptr);
  VectorXd vec(2);
  vec << 1, 7;
  SetZero(sharder, vec);
  EXPECT_THAT(vec, ElementsAre(0.0, 0.0, 0.0));
}

TEST(ZeroVectorTest, SmallExample) {
  Sharder sharder(3, /*num_shards=*/2, nullptr);
  EXPECT_THAT(ZeroVector(sharder), ElementsAre(0.0, 0.0, 0.0));
}

TEST(OnesVectorTest, SmallExample) {
  Sharder sharder(3, /*num_shards=*/2, nullptr);
  EXPECT_THAT(OnesVector(sharder), ElementsAre(1.0, 1.0, 1.0));
}

TEST(AddScaledVectorTest, SmallExample) {
  Sharder sharder(3, /*num_shards=*/2, nullptr);
  VectorXd vec1(3), vec2(3);
  vec1 << 4, 5, 20;
  vec2 << 1, 7, 3;
  AddScaledVector(2.0, vec2, sharder, /*dest=*/vec1);
  EXPECT_THAT(vec1, ElementsAre(6, 19, 26));
}

TEST(AssignVectorTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec1, vec2(3);
  vec2 << 1, 7, 3;
  AssignVector(vec2, sharder, /*dest=*/vec1);
  EXPECT_THAT(vec1, ElementsAre(1, 7, 3));
}

TEST(CloneVectorTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec(3);
  vec << 1, 7, 3;
  EXPECT_THAT(CloneVector(vec, sharder), ElementsAre(1, 7, 3));
}

TEST(CoefficientWiseProductInPlaceTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec1(3), vec2(3);
  vec1 << 4, 5, 20;
  vec2 << 1, 2, 3;
  CoefficientWiseProductInPlace(/*scale=*/vec2, sharder,
                                /*dest=*/vec1);
  EXPECT_THAT(vec1, ElementsAre(4, 10, 60));
}

TEST(CoefficientWiseQuotientInPlaceTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec1(3), vec2(3);
  vec1 << 4, 6, 20;
  vec2 << 1, 2, 5;
  CoefficientWiseQuotientInPlace(/*scale=*/vec2, sharder,
                                 /*dest=*/vec1);
  EXPECT_THAT(vec1, ElementsAre(4, 3, 4));
}

TEST(DotTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec1(3), vec2(3);
  vec1 << 1, 2, 3;
  vec2 << 4, 5, 6;
  double ans = Dot(vec1, vec2, sharder);
  EXPECT_THAT(ans, DoubleNear(4 + 10 + 18, 1.0e-13));
}

TEST(LInfNormTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec(3);
  vec << -1, 2, -3;
  double ans = LInfNorm(vec, sharder);
  EXPECT_EQ(ans, 3);
}

TEST(LInfNormTest, EmptyExample) {
  Sharder sharder(/*num_elements=*/0, /*num_shards=*/2, nullptr);
  VectorXd vec(0);
  double ans = LInfNorm(vec, sharder);
  EXPECT_EQ(ans, 0);
}

TEST(L1NormTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec(3);
  vec << -1, 2, -3;
  double ans = L1Norm(vec, sharder);
  EXPECT_EQ(ans, 6);
}

TEST(L1NormTest, EmptyExample) {
  Sharder sharder(/*num_elements=*/0, /*num_shards=*/2, nullptr);
  VectorXd vec(0);
  double ans = L1Norm(vec, sharder);
  EXPECT_EQ(ans, 0);
}

TEST(SquaredNormTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec(3);
  vec << 1, 2, 3;
  double ans = SquaredNorm(vec, sharder);
  EXPECT_THAT(ans, DoubleNear(1 + 4 + 9, 1.0e-13));
}

TEST(NormTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec(3);
  vec << 1, 2, 3;
  double ans = Norm(vec, sharder);
  EXPECT_THAT(ans, DoubleNear(std::sqrt(1 + 4 + 9), 1.0e-13));
}

TEST(SquaredDistanceTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec1(3);
  VectorXd vec2(3);
  vec1 << 1, 1, 1;
  vec2 << 1, 2, 3;
  double ans = SquaredDistance(vec1, vec2, sharder);
  EXPECT_THAT(ans, DoubleNear(5, 1.0e-13));
}

TEST(DistanceTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec1(3);
  VectorXd vec2(3);
  vec1 << 1, 1, 1;
  vec2 << 1, 2, 3;
  double ans = Distance(vec1, vec2, sharder);
  EXPECT_THAT(ans, DoubleNear(std::sqrt(5), 1.0e-13));
}

TEST(ScaledLInfNormTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec(3);
  VectorXd scale(3);
  vec << -1, 2, -3;
  scale << 4, 6, 1;
  double ans = ScaledLInfNorm(vec, scale, sharder);
  EXPECT_EQ(ans, 12);
}

TEST(ScaledSquaredNormTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec(3);
  VectorXd scale(3);
  vec << -1, 2, -3;
  scale << 4, 6, 1;
  double ans = ScaledSquaredNorm(vec, scale, sharder);
  EXPECT_EQ(ans, 169);
}

TEST(ScaledNormTest, SmallExample) {
  Sharder sharder(/*num_elements=*/3, /*num_shards=*/2, nullptr);
  VectorXd vec(3);
  VectorXd scale(3);
  vec << -1, 2, -3;
  scale << 4, 6, 1;
  double ans = ScaledNorm(vec, scale, sharder);
  EXPECT_EQ(ans, std::sqrt(169));
}

TEST(ScaledColLInfNorm, SmallExample) {
  Eigen::SparseMatrix<double, Eigen::ColMajor, int64_t> mat =
      TestSparseMatrix();
  Sharder sharder(mat, /*num_shards=*/3, nullptr);
  VectorXd row_scaling_vec(3);
  VectorXd col_scaling_vec(4);
  row_scaling_vec << 1, -2, 1;
  col_scaling_vec << 1, 2, -1, -1;
  VectorXd answer =
      ScaledColLInfNorm(mat, row_scaling_vec, col_scaling_vec, sharder);
  EXPECT_THAT(answer, ElementsAre(7, 1, 6, 5));
}

TEST(ScaledColL2Norm, SmallExample) {
  Eigen::SparseMatrix<double, Eigen::ColMajor, int64_t> mat =
      TestSparseMatrix();
  Sharder sharder(mat, /*num_shards=*/3, nullptr);
  VectorXd row_scaling_vec(3);
  VectorXd col_scaling_vec(4);
  row_scaling_vec << 1, -2, 1;
  col_scaling_vec << 1, 2, -1, -1;
  VectorXd answer =
      ScaledColL2Norm(mat, row_scaling_vec, col_scaling_vec, sharder);
  EXPECT_THAT(answer, ElementsAre(std::sqrt(54), 1.0, 6.0, std::sqrt(41)));
}

class VariousSizesTest : public testing::TestWithParam<int64_t> {};

TEST_P(VariousSizesTest, LargeMatVec) {
  const int64_t size = GetParam();
  Eigen::SparseMatrix<double, Eigen::ColMajor, int64_t> mat =
      LargeSparseMatrix(size);
  const int num_threads = 5;
  const int shards_per_thread = 3;
  ThreadPool pool("MatrixVectorProductTest", num_threads);
  pool.StartWorkers();
  Sharder sharder(mat, shards_per_thread * num_threads, &pool);
  VectorXd rhs = VectorXd::Random(size);
  VectorXd direct = mat.transpose() * rhs;
  VectorXd threaded = TransposedMatrixVectorProduct(mat, rhs, sharder);
  EXPECT_LE((direct - threaded).norm(), 1.0e-8);
}

TEST_P(VariousSizesTest, LargeVectors) {
  const int64_t size = GetParam();
  const int num_threads = 5;
  ThreadPool pool("SquaredNormTest", num_threads);
  pool.StartWorkers();
  Sharder sharder(size, num_threads, &pool);
  VectorXd vec = VectorXd::Random(size);
  const double direct = vec.squaredNorm();
  const double threaded = SquaredNorm(vec, sharder);
  EXPECT_THAT(threaded, DoubleNear(direct, size * 1.0e-14));
}

INSTANTIATE_TEST_SUITE_P(VariousSizesTestInstantiation, VariousSizesTest,
                         testing::Values(10, 1000, 100 * 1000));

}  // namespace
}  // namespace operations_research::pdlp


text:
package com.teletalk.jserver.util;

/**
 * Interface for items to be placed in a {@link PriorityMessageQueue}.
 *
 * @author Tobias Löfstrand
 *
 * @since 2.1.5 (20070413)
 */
public interface PriorityMessageQueueItem
{
   /**
    * Gets the priority of this item. Items will be placed in the queue in ascending priority order.
    */
   public long getPriority();
}


text:
from twython import Twython
from config import APP_KEY, APP_SECRET

def obtain_auth_url():
    """Used to app to tweet to my account
    NOT CALLED ANYWHERE"""
    twitter = Twython(APP_KEY, APP_SECRET)
    auth = twitter.get_authentication_tokens()

    oauth_token = auth['oauth_token']
    oauth_token_secret = auth['oauth_token_secret']
    print "\n\n\nGo to the following URL to authorize app:"
    print auth['auth_url']
    oauth_verifier = raw_input("\nEnter the pin: ")

    twitter = Twython(APP_KEY, APP_SECRET, oauth_token, oauth_token_secret)
    authorized = twitter.get_authorized_tokens(oauth_verifier)

    #write confirmed tokens to disk
    with open("config.py", "a") as config_file:
        config_file.write("\n'OAUTH_TOKEN': '" + authorized['oauth_token']
            + "'\n'OAUTH_TOKEN_SECRET': '" + authorized['oauth_token_secret'] + "'")

obtain_auth_url()


text:
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/apps/vfh_nn_classifier.h>

int
main (int, char* argv[])
{
  // Load input file
  char* file_name = argv[1];
  pcl::PCLPointCloud2 cloud_blob;
  pcl::io::loadPCDFile (file_name, cloud_blob);

  // Declare variable to hold result
  pcl::NNClassification<pcl::VFHSignature308>::ResultPtr result;
  // same as: pcl::VFHClassifierNN::ResultPtr result;

  // Do general classification using NNClassification or use the VHClassiierNN helper class
  if (false)
  {
    // Estimate your favorite feature
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ());
    pcl::fromPCLPointCloud2 (cloud_blob, *cloud);
    /// NOTE: make sure to use same radius as for training data
    pcl::PointCloud<pcl::VFHSignature308>::Ptr feature = pcl::computeVFH<pcl::PointXYZ> (cloud, 0.03);

    // Nearest neighbors classification
    pcl::NNClassification<pcl::VFHSignature308> nn;
    //nn.setTrainingFeatures(cloud);
    //nn.setTrainingLabels(std::vector<std::string>(cloud->points.size(), "bla"));
    nn.loadTrainingFeatures (argv[2], argv[3]);
    result = nn.classify(feature->points[0], 300, 50);
  }
  else
  {
    pcl::VFHClassifierNN vfh_classifier;
    //vfh_classifier.loadTrainingData ("/home/marton/ros/pcl/trunk/apps/data/can.pcd", "can");
    //vfh_classifier.loadTrainingData ("/home/marton/ros/pcl/trunk/apps/data/salt.pcd", "salt");
    //vfh_classifier.loadTrainingData ("/home/marton/ros/pcl/trunk/apps/data/sugar.pcd", "sugar");
    //vfh_classifier.saveTrainingFeatures ("/tmp/vfhs.pcd", "/tmp/vfhs.labels");
    vfh_classifier.loadTrainingFeatures (argv[2], argv[3]);
    vfh_classifier.finalizeTraining ();
    result = vfh_classifier.classify(cloud_blob);
  }

  // Print results
  for (size_t i = 0; i < result->first.size(); ++i)
    std::cerr << result->first.at (i) << ": " << result->second.at (i) << std::endl;

  return 0;
}


text:
package r.b3.interfaces.banco;

public abstract class Conta implements Contabil {

	private String cpf;

	protected int quantia;

	public final static String NOVA_LINHA = System.lineSeparator();

	public Conta(String cpf, int quantia) {
		this.cpf = cpf;
		this.quantia = quantia;
	}

	protected void setQuantia(int quantia) {
		this.quantia -= quantia;
	}

	/* (non-Javadoc)
	 * @see Contabil#sacar(int)
	 */
	public abstract int sacar(int quantia);

	/* (non-Javadoc)
	 * @see Contabil#depositar(int)
	 */
	public void depositar(int quantia) {
		this.quantia += quantia;
	}

	public int getSaldo() {
		return quantia;
	}

	public String toString() {
		return this.cpf + " - " + quantia + " centavos.";
	}

	public String reprBancaria() {
		return this.getTipo() + " - " + this.quantia + " - " + this.getDetalhes();
	}

	public abstract String getTipo();

	public abstract String getDetalhes();

	public static String codigo() {
		return "C";
	}

}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PublicHoliday;

namespace PublicHolidayTests
{
    [TestClass]
    public class TestSouthAfricaPublicHoliday
    {
        [DataTestMethod]
        [DataRow(1, 2, "New year - observed on Monday")]
        [DataRow(3, 21, "Human Rights Day")]
        [DataRow(4, 14, "Good Friday")]
        [DataRow(4, 17, "Family Day")]
        [DataRow(4, 27, "Freedom Day")]
        [DataRow(5, 1, "Workers' Day")]
        [DataRow(6, 16, "Youth Day")]
        [DataRow(8, 9, "National Women's Day")]
        [DataRow(9, 25, "Heritage Day")]
        [DataRow(12, 25, "christmas")]
        [DataRow(12, 26, "boxing day")]
        public void TestHolidays2017(int month, int day, string name)
        {
            var holiday = new DateTime(2017, month, day);
            var holidayCalendar = new SouthAfricaPublicHoliday();
            var actual = holidayCalendar.IsPublicHoliday(holiday);
            Assert.IsTrue(actual, $"{holiday.ToString("D")} is not a holiday -{name}");
        }

        [TestMethod]
        public void TestHolidays2017Lists()
        {
            var holidayCalendar = new SouthAfricaPublicHoliday();
            var hols = holidayCalendar.PublicHolidays(2017);
            var holNames = holidayCalendar.PublicHolidayNames(2017);
            Assert.IsTrue(12 == hols.Count, "Should be 12 holidays in 2017");
            Assert.IsTrue(holNames.Count == hols.Count, "Names and holiday list are same");
        }

        [DataTestMethod]
        [DataRow(3, 22, "Human Rights Day - Observed on Monday")]
        [DataRow(4, 2, "Good Friday")]
        [DataRow(4, 5, "Family Day")]
        [DataRow(4, 27, "Freedom Day")]
        [DataRow(5, 1, "Workers' Day")]
        [DataRow(6, 16, "Youth Day")]
        [DataRow(8, 9, "National Women's Day")]
        [DataRow(9, 24, "Heritage Day")]
        [DataRow(12, 16, "Day of reconciliation")]
        [DataRow(12, 25, "Christmas")]
        [DataRow(12, 27, "Boxing day - Observed on Monday")]
        public void TestHolidays2021(int month, int day, string name)
        {
            var holiday = new DateTime(2021, month, day);
            var holidayCalendar = new SouthAfricaPublicHoliday();
            var actual = holidayCalendar.IsPublicHoliday(holiday);
            Assert.IsTrue(actual, $"{holiday.ToString("D")} is not a holiday -{name}");
        }

        [TestMethod]
        public void TestHolidays2021Lists()
        {
            var holidayCalendar = new SouthAfricaPublicHoliday();
            var hols = holidayCalendar.PublicHolidays(2021);
            var holNames = holidayCalendar.PublicHolidayNames(2021);
            Assert.IsTrue(12 == hols.Count, "Should be 12 holidays in 2021");
            Assert.IsTrue(holNames.Count == hols.Count, "Names and holiday list are same");
        }

        [TestMethod]
        public void TestChristmasAndBoxingDay2021()
        {
            var christmasDay = SouthAfricaPublicHoliday.Christmas(2021);
            var boxingDay = SouthAfricaPublicHoliday.BoxingDay(2021);

            Assert.AreNotEqual(new DateTime(2021, 12, 26), christmasDay, "Christmas day cannot move to Monday because Boxing day falls on Monday ");
            Assert.AreEqual(new DateTime(2021, 12, 27), boxingDay, "Boxing day should be observed on Monday 27 Dec 2021");
        }

        [DataTestMethod]
        [DataRow(3, 21, "Human Rights Day")]
        [DataRow(4, 15, "Good Friday")]
        [DataRow(4, 18, "Family Day")]
        [DataRow(4, 27, "Freedom Day")]
        [DataRow(5, 2, "Workers' Day - Observed on Monday")]
        [DataRow(6, 16, "Youth Day")]
        [DataRow(8, 9, "National Women's Day")]
        [DataRow(9, 24, "Heritage Day")]
        [DataRow(12, 16, "Day of reconciliation")]
        [DataRow(12, 25, "Christmas")]
        [DataRow(12, 26, "Boxing day")]
        public void TestHolidays2022(int month, int day, string name)
        {
            var holiday = new DateTime(2022, month, day);
            var holidayCalendar = new SouthAfricaPublicHoliday();
            var actual = holidayCalendar.IsPublicHoliday(holiday);
            Assert.IsTrue(actual, $"{holiday.ToString("D")} is not a holiday -{name}");
        }

        [TestMethod]
        public void TestHolidays2022Lists()
        {
            var holidayCalendar = new SouthAfricaPublicHoliday();
            var hols = holidayCalendar.PublicHolidays(2022);
            var holNames = holidayCalendar.PublicHolidayNames(2022);
            Assert.IsTrue(12 == hols.Count, "Should be 12 holidays in 2022");
            Assert.IsTrue(holNames.Count == hols.Count, "Names and holiday list are same");
        }

        [DataTestMethod]
        [DataRow(1, 2, "New Years Day - Observed on Monday")]
        [DataRow(3, 21, "Human Rights Day")]
        [DataRow(4, 7, "Good Friday")]
        [DataRow(4, 10, "Family Day")]
        [DataRow(4, 27, "Freedom Day")]
        [DataRow(5, 1, "Workers' Day")]
        [DataRow(6, 16, "Youth Day")]
        [DataRow(8, 9, "National Women's Day")]
        [DataRow(9, 25, "Heritage Day - Observed on Monday")]
        [DataRow(12, 16, "Day of reconciliation")]
        [DataRow(12, 25, "Christmas")]
        [DataRow(12, 26, "Boxing day")]
        public void TestHolidays2023(int month, int day, string name)
        {
            var holiday = new DateTime(2023, month, day);
            var holidayCalendar = new SouthAfricaPublicHoliday();
            var actual = holidayCalendar.IsPublicHoliday(holiday);
            Assert.IsTrue(actual, $"{holiday.ToString("D")} is not a holiday -{name}");
        }

        [DataTestMethod]
        [DataRow(1, 1, "New Years Day")]
        [DataRow(3, 21, "Human Rights Day")]
        [DataRow(3, 29, "Good Friday")]
        [DataRow(4, 1, "Family Day")]
        [DataRow(4, 27, "Freedom Day")]
        [DataRow(5, 1, "Workers' Day")]
        [DataRow(6, 17, "Youth Day - Observed on Monday")]
        [DataRow(8, 9, "National Women's Day")]
        [DataRow(9, 24, "Heritage Day")]
        [DataRow(12, 16, "Day of reconciliation")]
        [DataRow(12, 25, "Christmas")]
        [DataRow(12, 26, "Boxing day")]
        public void TestHolidays2024(int month, int day, string name)
        {
            var x = SouthAfricaPublicHoliday.GoodFriday(2024);
            var holiday = new DateTime(2024, month, day);
            var holidayCalendar = new SouthAfricaPublicHoliday();
            var actual = holidayCalendar.IsPublicHoliday(holiday);
            Assert.IsTrue(actual, $"{holiday.ToString("D")} is not a holiday -{name}");
        }
    }
}


text:
require 'acceptance_helper'

feature 'User sign out' do
  given(:user) { create(:user) }

  scenario 'Auth user try to sign out' do
    sign_in(user)

    click_on 'Sign out'
    expect(page).to_not have_content 'Sign out'
  end

  scenario 'Non-auth user try to sign out' do
    visit root_path
    expect(page).to_not have_content 'Sign out'
  end
end


text:
<node>
    <id>ebf2857c-9bd3-43b8-9563-a721f418e4eb</id>
    <childOrder>modifiedtime DESC</childOrder>
    <nodeType>content</nodeType>
    <timestamp>2016-02-25T21:54:40.633Z</timestamp>
    <inheritPermissions>true</inheritPermissions>
    <permissions>
        <principal key="role:cms.cm.app">
            <allow type="array">
                <value>READ</value>
            </allow>
            <deny type="array"/>
        </principal>
        <principal key="role:system.admin">
            <allow type="array">
                <value>READ</value>
                <value>CREATE</value>
                <value>MODIFY</value>
                <value>DELETE</value>
                <value>PUBLISH</value>
                <value>READ_PERMISSIONS</value>
                <value>WRITE_PERMISSIONS</value>
            </allow>
            <deny type="array"/>
        </principal>
        <principal key="role:cms.admin">
            <allow type="array">
                <value>READ</value>
                <value>CREATE</value>
                <value>MODIFY</value>
                <value>DELETE</value>
                <value>PUBLISH</value>
                <value>READ_PERMISSIONS</value>
                <value>WRITE_PERMISSIONS</value>
            </allow>
            <deny type="array"/>
        </principal>
    </permissions>
    <data>
        <boolean name="valid">true</boolean>
        <string name="displayName">Checkbox</string>
        <string name="type">no.vegard.it.xp.formbuilder:input-checkbox</string>
        <string name="owner">user:system:su</string>
        <dateTime name="modifiedTime">2016-02-25T21:20:44.387Z</dateTime>
        <string name="modifier">user:system:su</string>
        <string name="creator">user:system:su</string>
        <dateTime name="createdTime">2016-02-25T21:19:18.792Z</dateTime>
        <property-set name="data">
            <string name="id">checkbox-id</string>
            <string name="name">checkbox-name</string>
            <string name="label">Checkbox</string>
            <string name="title">Select or unselect</string>
            <string isNull="true" name="class"/>
            <string isNull="true" name="help"/>
            <boolean name="required">false</boolean>
            <string isNull="true" name="value"/>
            <string name="text">To check or not to check? That is the question.</string>
            <string name="state">indeterminate</string>
        </property-set>
    </data>
    <indexConfigs>
        <analyzer>document_index_default</analyzer>
        <defaultConfig>
            <decideByType>true</decideByType>
            <enabled>true</enabled>
            <nGram>false</nGram>
            <fulltext>false</fulltext>
            <includeInAllText>false</includeInAllText>
        </defaultConfig>
        <pathIndexConfigs>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>false</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>page.regions</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>true</nGram>
                    <fulltext>true</fulltext>
                    <includeInAllText>true</includeInAllText>
                    <indexValueProcessors>
                        <indexValueProcessor>htmlStripper</indexValueProcessor>
                    </indexValueProcessors>
                </indexConfig>
                <path>data.htmlarea_text</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>modifier</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>owner</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>attachment</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>x</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>true</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>data</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>page</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>false</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>site</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>type</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>creator</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>createdTime</path>
            </pathIndexConfig>
            <pathIndexConfig>
                <indexConfig>
                    <decideByType>false</decideByType>
                    <enabled>true</enabled>
                    <nGram>false</nGram>
                    <fulltext>false</fulltext>
                    <includeInAllText>false</includeInAllText>
                </indexConfig>
                <path>modifiedTime</path>
            </pathIndexConfig>
        </pathIndexConfigs>
    </indexConfigs>
</node>