text:
package groovy.lang;

import groovy.ui.GroovyMain;
import groovy.security.GroovyCodeSourcePermission;

import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.plugin.GroovyRunner;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.InvokerInvocationException;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.List;
import java.util.Map;

/**
 * Represents a groovy shell capable of running arbitrary groovy scripts
 *
 * @author James Strachan
 * @author Guillaume Laforge
 * @author Paul King
 * @version $Revision$
 */
public class GroovyShell extends GroovyObjectSupport {

    public static final String DEFAULT_CODE_BASE = "/groovy/shell";

    private Binding context;
    private int counter;
    private CompilerConfiguration config;
    private GroovyClassLoader loader;

    public static void main(String[] args) {
        GroovyMain.main(args);
    }

    public GroovyShell() {
        this(null, new Binding());
    }

    public GroovyShell(Binding binding) {
        this(null, binding);
    }

    public GroovyShell(ClassLoader parent, CompilerConfiguration config) {
        this(parent, new Binding(), config);
    }

    public GroovyShell(CompilerConfiguration config) {
        this(new Binding(), config);
    }

    public GroovyShell(Binding binding, CompilerConfiguration config) {
        this(null, binding, config);
    }

    public GroovyShell(ClassLoader parent, Binding binding) {
        this(parent, binding, CompilerConfiguration.DEFAULT);
    }

    public GroovyShell(ClassLoader parent) {
        this(parent, new Binding(), CompilerConfiguration.DEFAULT);
    }

    public GroovyShell(ClassLoader parent, Binding binding, final CompilerConfiguration config) {
        if (binding == null) {
            throw new IllegalArgumentException("Binding must not be null.");
        }
        if (config == null) {
            throw new IllegalArgumentException("Compiler configuration must not be null.");
        }
        final ClassLoader parentLoader = (parent!=null)?parent:GroovyShell.class.getClassLoader();
        this.loader = AccessController.doPrivileged(new PrivilegedAction<GroovyClassLoader>() {
            public GroovyClassLoader run() {
                return new GroovyClassLoader(parentLoader,config);
            }
        });
        this.context = binding;
        this.config = config;
    }

    public void resetLoadedClasses() {
        loader.clearCache();
    }

    /**
     * Creates a child shell using a new ClassLoader which uses the parent shell's
     * class loader as its parent
     *
     * @param shell is the parent shell used for the variable bindings and the parent class loader
     */
    public GroovyShell(GroovyShell shell) {
        this(shell.loader, shell.context);
    }

    public Binding getContext() {
        return context;
    }

    public GroovyClassLoader getClassLoader() {
        return loader;
    }

    public Object getProperty(String property) {
        Object answer = getVariable(property);
        if (answer == null) {
            answer = super.getProperty(property);
        }
        return answer;
    }

    public void setProperty(String property, Object newValue) {
        setVariable(property, newValue);
        try {
            super.setProperty(property, newValue);
        } catch (GroovyRuntimeException e) {
            // ignore, was probably a dynamic property
        }
    }

    //
    // FIXME: Use List<String> here, current version is not safe
    //

    /**
     * A helper method which runs the given script file with the given command line arguments
     *
     * @param scriptFile the file of the script to run
     * @param list       the command line arguments to pass in
     */
    public Object run(File scriptFile, List list) throws CompilationFailedException, IOException {
        String[] args = new String[list.size()];
        return run(scriptFile, (String[]) list.toArray(args));
    }

    /**
     * A helper method which runs the given cl script with the given command line arguments
     *
     * @param scriptText is the text content of the script
     * @param fileName   is the logical file name of the script (which is used to create the class name of the script)
     * @param list       the command line arguments to pass in
     */
    public Object run(String scriptText, String fileName, List list) throws CompilationFailedException {
        String[] args = new String[list.size()];
        list.toArray(args);
        return run(scriptText, fileName, args);
    }

    /**
     * Runs the given script file name with the given command line arguments
     *
     * @param scriptFile the file name of the script to run
     * @param args       the command line arguments to pass in
     */
    public Object run(final File scriptFile, String[] args) throws CompilationFailedException, IOException {
        String scriptName = scriptFile.getName();
        int p = scriptName.lastIndexOf(".");
        if (p++ >= 0) {
            if (scriptName.substring(p).equals("java")) {
                throw new CompilationFailedException(0, null);
            }
        }

        // Get the current context classloader and save it on the stack
        final Thread thread = Thread.currentThread();
        //ClassLoader currentClassLoader = thread.getContextClassLoader();

        class DoSetContext implements PrivilegedAction {
            ClassLoader classLoader;

            public DoSetContext(ClassLoader loader) {
                classLoader = loader;
            }

            public Object run() {
                thread.setContextClassLoader(classLoader);
                return null;
            }
        }

        AccessController.doPrivileged(new DoSetContext(loader));

        // Parse the script, generate the class, and invoke the main method.  This is a little looser than
        // if you are compiling the script because the JVM isn't executing the main method.
        Class scriptClass;
        try {
            scriptClass = AccessController.doPrivileged(new PrivilegedExceptionAction<Class>() {
                public Class run() throws CompilationFailedException, IOException {
                    return loader.parseClass(scriptFile);
                }
            });
        } catch (PrivilegedActionException pae) {
            Exception e = pae.getException();
            if (e instanceof CompilationFailedException) {
                throw (CompilationFailedException) e;
            } else if (e instanceof IOException) {
                throw (IOException) e;
            } else {
                throw (RuntimeException) pae.getException();
            }
        }

        return runScriptOrMainOrTestOrRunnable(scriptClass, args);

        // Set the context classloader back to what it was.
        //AccessController.doPrivileged(new DoSetContext(currentClassLoader));
    }

    /**
     * if (theClass is a Script) {
     * run it like a script
     * } else if (theClass has a main method) {
     * run the main method
     * } else if (theClass instanceof GroovyTestCase) {
     * use the test runner to run it
     * } else if (theClass implements Runnable) {
     * if (theClass has a constructor with String[] params)
     * instantiate theClass with this constructor and run
     * else if (theClass has a no-args constructor)
     * instantiate theClass with the no-args constructor and run
     * }
     */
    private Object runScriptOrMainOrTestOrRunnable(Class scriptClass, String[] args) {
        // Always set the "args" property, regardless of what path we take in the code.
        // Bad enough to have side effects but worse if their behavior is wonky.
        context.setProperty("args", args);

        if (scriptClass == null) {
            return null;
        }

        //TODO: This logic mostly duplicates InvokerHelper.createScript.  They should probably be unified.

        if (Script.class.isAssignableFrom(scriptClass)) {
            // treat it just like a script if it is one
            try {
                Constructor constructor = scriptClass.getConstructor(Binding.class);
                Script script = (Script) constructor.newInstance(context);
                return script.run();
            } catch (InstantiationException e) {
                // ignore instantiation errors,, try to do main
            } catch (IllegalAccessException e) {
               // ignore instantiation errors, try to do main
            } catch (NoSuchMethodException e) {
                try {
                    // Fallback for non-standard "Scripts" that don't have contextual constructor.
                    Script script = (Script) scriptClass.newInstance();
                    script.setBinding(context);
                    return script.run();
                } catch (InstantiationException e1) {
                    // ignore instantiation errors, try to do main
                } catch (IllegalAccessException e1) {
                    // ignore instantiation errors, try to do main
                }
            } catch (InvocationTargetException e) {
                // ignore instantiation errors, try to do main
            }
        }
        try {
            // let's find a main method
            scriptClass.getMethod("main", new Class[]{String[].class});
            // if that main method exist, invoke it
            return InvokerHelper.invokeMethod(scriptClass, "main", new Object[]{args});
        } catch (NoSuchMethodException e) {
            // if it implements Runnable, try to instantiate it
            if (Runnable.class.isAssignableFrom(scriptClass)) {
                return runRunnable(scriptClass, args);
            }
            // if it's a JUnit 3.8.x test, run it with an appropriate runner
            if (isJUnit3Test(scriptClass)) {
                return runJUnit3Test(scriptClass);
            }
            // if it's a JUnit 3.8.x test suite, run it with an appropriate runner
            if (isJUnit3TestSuite(scriptClass)) {
                return runJUnit3TestSuite(scriptClass);
            }
            // if it's a JUnit 4.x test, run it with an appropriate runner
            if (isJUnit4Test(scriptClass)) {
                return runJUnit4Test(scriptClass);
            }
            for (Map.Entry<String, GroovyRunner> entry : GroovySystem.RUNNER_REGISTRY.entrySet()) {
                GroovyRunner runner = entry.getValue();
                if (runner != null && runner.canRun(scriptClass, this.loader)) {
                    return runner.run(scriptClass, this.loader);
                }
            }
            String message = "This script or class could not be run.\n" +
                    "It should either:\n" +
                    "- have a main method,\n" +
                    "- be a JUnit test or extend GroovyTestCase,\n" +
                    "- implement the Runnable interface,\n" +
                    "- or be compatible with a registered script runner. Known runners:\n";
            if (GroovySystem.RUNNER_REGISTRY.isEmpty()) {
                message += "  * <none>";
            }
            for (Map.Entry<String, GroovyRunner> entry : GroovySystem.RUNNER_REGISTRY.entrySet()) {
                message += "  * " + entry.getKey() + "\n";
            }
            throw new GroovyRuntimeException(message);
        }
    }

    private Object runRunnable(Class scriptClass, String[] args) {
        Constructor constructor = null;
        Runnable runnable = null;
        Throwable reason = null;
        try {
            // first, fetch the constructor taking String[] as parameter
            constructor = scriptClass.getConstructor(new Class[]{(new String[]{}).getClass()});
            try {
                // instantiate a runnable and run it
                runnable = (Runnable) constructor.newInstance(new Object[]{args});
            } catch (Throwable t) {
                reason = t;
            }
        } catch (NoSuchMethodException e1) {
            try {
                // otherwise, find the default constructor
                constructor = scriptClass.getConstructor(new Class[]{});
                try {
                    // instantiate a runnable and run it
                    runnable = (Runnable) constructor.newInstance();
                } catch (InvocationTargetException ite) {
                    throw new InvokerInvocationException(ite.getTargetException());
                } catch (Throwable t) {
                    reason = t;
                }
            } catch (NoSuchMethodException nsme) {
                reason = nsme;
            }
        }
        if (constructor != null && runnable != null) {
            runnable.run();
        } else {
            throw new GroovyRuntimeException("This script or class was runnable but could not be run. ", reason);
        }
        return null;
    }

    /**
     * Run the specified class extending TestCase as a unit test.
     * This is done through reflection, to avoid adding a dependency to the JUnit framework.
     * Otherwise, developers embedding Groovy and using GroovyShell to load/parse/compile
     * groovy scripts and classes would have to add another dependency on their classpath.
     *
     * @param scriptClass the class to be run as a unit test
     */
    private Object runJUnit3Test(Class scriptClass) {
        try {
            Object testSuite = InvokerHelper.invokeConstructorOf("junit.framework.TestSuite", new Object[]{scriptClass});
            return InvokerHelper.invokeStaticMethod("junit.textui.TestRunner", "run", new Object[]{testSuite});
        } catch (ClassNotFoundException e) {
            throw new GroovyRuntimeException("Failed to run the unit test. JUnit is not on the Classpath.", e);
        }
    }

    /**
     * Run the specified class extending TestSuite as a unit test.
     * This is done through reflection, to avoid adding a dependency to the JUnit framework.
     * Otherwise, developers embedding Groovy and using GroovyShell to load/parse/compile
     * groovy scripts and classes would have to add another dependency on their classpath.
     *
     * @param scriptClass the class to be run as a unit test
     */
    private Object runJUnit3TestSuite(Class scriptClass) {
        try {
            Object testSuite = InvokerHelper.invokeStaticMethod(scriptClass, "suite", new Object[]{});
            return InvokerHelper.invokeStaticMethod("junit.textui.TestRunner", "run", new Object[]{testSuite});
        } catch (ClassNotFoundException e) {
            throw new GroovyRuntimeException("Failed to run the unit test. JUnit is not on the Classpath.", e);
        }
    }

    private Object runJUnit4Test(Class scriptClass) {
        try {
            return InvokerHelper.invokeStaticMethod("org.codehaus.groovy.vmplugin.v5.JUnit4Utils",
                    "realRunJUnit4Test", new Object[]{scriptClass, this.loader});
        } catch (ClassNotFoundException e) {
            throw new GroovyRuntimeException("Failed to run the JUnit 4 test.", e);
        }
    }

    /**
     * Utility method to check through reflection if the class appears to be a
     * JUnit 3.8.x test, i.e.&nsbp;checks if it extends JUnit 3.8.x's TestCase.
     *
     * @param scriptClass the class we want to check
     * @return true if the class appears to be a test
     */
    private boolean isJUnit3Test(Class scriptClass) {
        // check if the parsed class is a GroovyTestCase,
        // so that it is possible to run it as a JUnit test
        boolean isUnitTestCase = false;
        try {
            try {
                Class testCaseClass = this.loader.loadClass("junit.framework.TestCase");
                // if scriptClass extends testCaseClass
                if (testCaseClass.isAssignableFrom(scriptClass)) {
                    isUnitTestCase = true;
                }
            } catch (ClassNotFoundException e) {
                // fall through
            }
        } catch (Throwable e) {
            // fall through
        }
        return isUnitTestCase;
    }

     /**
     * Utility method to check through reflection if the class appears to be a
     * JUnit 3.8.x test suite, i.e.&nsbp;checks if it extends JUnit 3.8.x's TestSuite.
     *
     * @param scriptClass the class we want to check
     * @return true if the class appears to be a test
     */
    private boolean isJUnit3TestSuite(Class scriptClass) {
        // check if the parsed class is a TestSuite,
        // so that it is possible to run it as a JUnit test
        boolean isUnitTestSuite = false;
        try {
            try {
                Class testSuiteClass = this.loader.loadClass("junit.framework.TestSuite");
                // if scriptClass extends TestSuiteClass
                if (testSuiteClass.isAssignableFrom(scriptClass)) {
                    isUnitTestSuite = true;
                }
            } catch (ClassNotFoundException e) {
                // fall through
            }
        } catch (Throwable e) {
            // fall through
        }
        return isUnitTestSuite;
    }

    /**
     * Utility method to check via reflection if the parsed class appears to be a JUnit4
     * test, i.e.&nsbp;checks whether it appears to be using the relevant JUnit 4 annotations.
     *
     * @param scriptClass the class we want to check
     * @return true if the class appears to be a test
     */
    private boolean isJUnit4Test(Class scriptClass) {
        // if we are running under Java 1.4 don't bother trying to check
        char version = System.getProperty("java.version").charAt(2);
        if (version < '5') {
            return false;
        }

        // check if there are appropriate class or method annotations
        // that suggest we have a JUnit 4 test
        boolean isTest = false;

        try {
            if (InvokerHelper.invokeStaticMethod("org.codehaus.groovy.vmplugin.v5.JUnit4Utils",
                    "realIsJUnit4Test", new Object[]{scriptClass, this.loader}) == Boolean.TRUE) {
                isTest = true;
            }
        } catch (ClassNotFoundException e) {
            throw new GroovyRuntimeException("Failed to invoke the JUnit 4 helper class.", e);
        }
        return isTest;
    }

    /**
     * Runs the given script text with command line arguments
     *
     * @param scriptText is the text content of the script
     * @param fileName   is the logical file name of the script (which is used to create the class name of the script)
     * @param args       the command line arguments to pass in
     */
    public Object run(final String scriptText, final String fileName, String[] args) throws CompilationFailedException {
        GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction<GroovyCodeSource>() {
            public GroovyCodeSource run() {
                return new GroovyCodeSource(scriptText, fileName, DEFAULT_CODE_BASE);
            }
        });
        return run(gcs, args);
    }

    /**
     * Runs the given script source with command line arguments
     *
     * @param source    is the source content of the script
     * @param args      the command line arguments to pass in
     */
    public Object run(GroovyCodeSource source, List args) throws CompilationFailedException {
        return run(source, ((String[]) args.toArray(new String[args.size()])));
    }

    /**
     * Runs the given script source with command line arguments
     *
     * @param source    is the source content of the script
     * @param args      the command line arguments to pass in
     */
    public Object run(GroovyCodeSource source, String[] args) throws CompilationFailedException {
        Class scriptClass = parseClass(source);
        return runScriptOrMainOrTestOrRunnable(scriptClass, args);
    }

    /**
     * Runs the given script source with command line arguments
     *
     * @param source    is the source content of the script
     * @param args      the command line arguments to pass in
     */
    public Object run(URI source, List args) throws CompilationFailedException, IOException {
        return run(new GroovyCodeSource(source), ((String[]) args.toArray(new String[args.size()])));
    }

    /**
     * Runs the given script source with command line arguments
     *
     * @param source    is the source content of the script
     * @param args      the command line arguments to pass in
     */
    public Object run(URI source, String[] args) throws CompilationFailedException, IOException {
        return run(new GroovyCodeSource(source), args);
    }

    /**
     * Runs the given script with command line arguments
     *
     * @param in       the stream reading the script
     * @param fileName is the logical file name of the script (which is used to create the class name of the script)
     * @param list     the command line arguments to pass in
     */
    public Object run(final Reader in, final String fileName, List list) throws CompilationFailedException {
        return run(in, fileName, (String[]) list.toArray(new String[list.size()]));
    }

    /**
     * Runs the given script with command line arguments
     *
     * @param in       the stream reading the script
     * @param fileName is the logical file name of the script (which is used to create the class name of the script)
     * @param args     the command line arguments to pass in
     */
    public Object run(final Reader in, final String fileName, String[] args) throws CompilationFailedException {
        GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction<GroovyCodeSource>() {
                    public GroovyCodeSource run() {
                        return new GroovyCodeSource(in, fileName, DEFAULT_CODE_BASE);
                    }
        });
        Class scriptClass = parseClass(gcs);
        return runScriptOrMainOrTestOrRunnable(scriptClass, args);
    }

    public Object getVariable(String name) {
        return context.getVariables().get(name);
    }

    public void setVariable(String name, Object value) {
        context.setVariable(name, value);
    }

    /**
     * Evaluates some script against the current Binding and returns the result
     *
     * @param codeSource
     * @throws CompilationFailedException
     */
    public Object evaluate(GroovyCodeSource codeSource) throws CompilationFailedException {
        Script script = parse(codeSource);
        return script.run();
    }

    /**
     * Evaluates some script against the current Binding and returns the result
     *
     * @param scriptText the text of the script
     */
    public Object evaluate(final String scriptText) throws CompilationFailedException {
        return evaluate(scriptText, generateScriptName(), DEFAULT_CODE_BASE);
    }

    /**
     * Evaluates some script against the current Binding and returns the result
     *
     * @param scriptText the text of the script
     * @param fileName   is the logical file name of the script (which is used to create the class name of the script)
     */
    public Object evaluate(String scriptText, String fileName) throws CompilationFailedException {
        return evaluate(scriptText, fileName, DEFAULT_CODE_BASE);
    }

    /**
     * Evaluates some script against the current Binding and returns the result.
     * The .class file created from the script is given the supplied codeBase
     */
    public Object evaluate(final String scriptText, final String fileName, final String codeBase) throws CompilationFailedException {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new GroovyCodeSourcePermission(codeBase));
        }

        GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction<GroovyCodeSource>() {
            public GroovyCodeSource run() {
                return new GroovyCodeSource(scriptText, fileName, codeBase);
            }
        });

        return evaluate(gcs);
    }

    /**
     * Evaluates some script against the current Binding and returns the result
     *
     * @param file is the file of the script (which is used to create the class name of the script)
     */
    public Object evaluate(File file) throws CompilationFailedException, IOException {
        return evaluate(new GroovyCodeSource(file, config.getSourceEncoding()));
    }

    /**
     * Evaluates some script against the current Binding and returns the result
     *
     * @param uri is the URI of the script (which is used to create the class name of the script)
     */
    public Object evaluate(URI uri) throws CompilationFailedException, IOException {
        return evaluate(new GroovyCodeSource(uri));
    }

    /**
     * Evaluates some script against the current Binding and returns the result
     *
     * @param in the stream reading the script
     */
    public Object evaluate(Reader in) throws CompilationFailedException {
        return evaluate(in, generateScriptName());
    }

    /**
     * Evaluates some script against the current Binding and returns the result
     *
     * @param in       the stream reading the script
     * @param fileName is the logical file name of the script (which is used to create the class name of the script)
     */
    public Object evaluate(Reader in, String fileName) throws CompilationFailedException {
        Script script = null;
        try {
            script = parse(in, fileName);
            return script.run();
        } finally {
            if (script != null) {
                InvokerHelper.removeClass(script.getClass());
            }
        }
    }

    /**
     * Parses the given script and returns it ready to be run
     *
     * @param reader    the stream reading the script
     * @param fileName  is the logical file name of the script (which is used to create the class name of the script)
     * @return the parsed script which is ready to be run via {@link Script#run()}
     */
    public Script parse(final Reader reader, final String fileName) throws CompilationFailedException {
        return parse(new GroovyCodeSource(reader, fileName, DEFAULT_CODE_BASE));
    }

    /**
     * Parses the groovy code contained in codeSource and returns a java class.
     */
    private Class parseClass(final GroovyCodeSource codeSource) throws CompilationFailedException {
        // Don't cache scripts
        return loader.parseClass(codeSource, false);
    }

    /**
     * Parses the given script and returns it ready to be run.  When running in a secure environment
     * (-Djava.security.manager) codeSource.getCodeSource() determines what policy grants should be
     * given to the script.
     *
     * @param codeSource
     * @return ready to run script
     */
    public Script parse(final GroovyCodeSource codeSource) throws CompilationFailedException {
        return InvokerHelper.createScript(parseClass(codeSource), context);
    }

    /**
     * Parses the given script and returns it ready to be run
     *
     * @param file is the file of the script (which is used to create the class name of the script)
     */
    public Script parse(File file) throws CompilationFailedException, IOException {
        return parse(new GroovyCodeSource(file, config.getSourceEncoding()));
    }

    /**
     * Parses the given script and returns it ready to be run
     *
     * @param uri is the URI of the script (which is used to create the class name of the script)
     */
    public Script parse(URI uri) throws CompilationFailedException, IOException {
        return parse(new GroovyCodeSource(uri));
    }

    /**
     * Parses the given script and returns it ready to be run
     *
     * @param scriptText the text of the script
     */
    public Script parse(String scriptText) throws CompilationFailedException {
        return parse(scriptText, generateScriptName());
    }

    public Script parse(final String scriptText, final String fileName) throws CompilationFailedException {
        GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction<GroovyCodeSource>() {
            public GroovyCodeSource run() {
                return new GroovyCodeSource(scriptText, fileName, DEFAULT_CODE_BASE);
            }
        });
        return parse(gcs);
    }

    /**
     * Parses the given script and returns it ready to be run
     *
     * @param in the stream reading the script
     */
    public Script parse(Reader in) throws CompilationFailedException {
        return parse(in, generateScriptName());
    }

    protected synchronized String generateScriptName() {
        return "Script" + (++counter) + ".groovy";
    }
}


text:
package com.oskopek.transport.model.state;

import com.oskopek.transport.model.domain.action.Action;
import com.oskopek.transport.model.problem.Package;
import com.oskopek.transport.model.problem.graph.RoadGraph;
import com.oskopek.transport.model.problem.*;
import com.oskopek.transport.model.problem.graph.VisualRoadGraph;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;

/**
 * A default {@link PlanState} implementation for sequential and temporal domains.
 */
public class DefaultPlanState implements PlanState {

    private final transient Logger logger = LoggerFactory.getLogger(getClass());
    private Problem problem;

    /**
     * Default constructor.
     *
     * @param problem the problem
     */
    public DefaultPlanState(Problem problem) {
        this.problem = problem;
    }

    @Override
    public void applyPreconditions(Action action) {
        logger.trace("Checking preconditions of action {}.", action.getName());
        if (!action.arePreconditionsValid(problem)) {
            throw new IllegalStateException("Preconditions of action " + action + " are invalid in problem " + problem);
        }
        logger.trace("Applying preconditions of action {}.", action.getName());
        problem = action.applyPreconditions(problem);
        logger.trace("Applied preconditions of action {}.", action.getName());
    }

    @Override
    public void applyEffects(Action action) {
        logger.trace("Applying effects of action {}.", action.getName());
        Problem newProblem = action.applyEffects(problem);
        logger.trace("Checking effects of action {}.", action.getName());
        if (!action.areEffectsValid(newProblem)) {
            throw new IllegalStateException(
                    "Effects of action " + action + " are invalid after applying to problem " + problem + "(result: "
                            + newProblem + ").");
        }
        problem = newProblem;
    }

    @Override
    public String getName() {
        return problem.getName();
    }

    @Override
    public RoadGraph getRoadGraph() {
        return problem.getRoadGraph();
    }

    @Override
    public VisualRoadGraph getVisualRoadGraph() {
        return problem.getVisualRoadGraph();
    }

    @Override
    public Vehicle getVehicle(String name) {
        return problem.getVehicle(name);
    }

    /**
     * Utility method for getting a vehicle by its name.
     *
     * @param name the name of the vehicle to get
     * @return the vehicle
     * @throws IllegalArgumentException if a vehicle with that name wasn't found
     */
    public Vehicle getVehicleSafe(String name) {
        Vehicle vehicle = getVehicle(name);
        if (vehicle == null) {
            throw new IllegalArgumentException("Could not find vehicle with name \"" + name + "\".");
        }
        return vehicle;
    }

    @Override
    public Package getPackage(String name) {
        return problem.getPackage(name);
    }

    @Override
    public Locatable getLocatable(String name) {
        return problem.getLocatable(name);
    }

    @Override
    public ActionObject getActionObject(String name) {
        return problem.getActionObject(name);
    }

    @Override
    public Collection<Vehicle> getAllVehicles() {
        return problem.getAllVehicles();
    }

    @Override
    public Map<String, Vehicle> getVehicleMap() {
        return problem.getVehicleMap();
    }

    @Override
    public Collection<Package> getAllPackages() {
        return problem.getAllPackages();
    }

    @Override
    public Map<String, Package> getPackageMap() {
        return problem.getPackageMap();
    }

    @Override
    public Problem putVehicle(String name, Vehicle vehicle) {
        return problem.putVehicle(name, vehicle);
    }

    @Override
    public Problem putPackage(String name, Package pkg) {
        return problem.putPackage(name, pkg);
    }

    @Override
    public Problem changeActionObjectName(ActionObject actionObject, String newName) {
        return problem.changeActionObjectName(actionObject, newName);
    }

    @Override
    public Problem putName(String newName) {
        return problem.putName(newName);
    }

    @Override
    public Problem putLocation(String name, Location location) {
        return problem.putLocation(name, location);
    }

    @Override
    public Problem removeVehicle(String name) {
        return problem.removeVehicle(name);
    }

    @Override
    public Problem removePackage(String name) {
        return problem.removePackage(name);
    }

    @Override
    public Problem removeLocation(String name) {
        return problem.removeLocation(name);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof DefaultPlanState)) {
            return false;
        }
        DefaultPlanState that = (DefaultPlanState) o;
        return new EqualsBuilder().append(problem, that.problem).isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37).append(problem)
                .toHashCode();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import logging

from deluge import component, common
from deluge.plugins.pluginbase import WebPluginBase
from deluge.ui.client import client
from deluge.ui.web.json_api import export as export_api
from twisted.internet.defer import Deferred

from .common import get_resource

LOGGER = logging.getLogger(__name__)

class WebUI(WebPluginBase):

    scripts = [get_resource('webapi.js')]

    def enable(self):
        """Triggers when plugin is enabled."""
        LOGGER.info('Enabling WebAPI plugin WEB ...')

    def disable(self):
        """Triggers when plugin is disabled."""
        LOGGER.info('Disabling WebAPI plugin WEB ...')

    @export_api
    def get_torrents(self, ids=None, params=None):
        """Returns information about all or a definite torrent.
        Returned information can be filtered by supplying wanted parameter names.

        """

        if params is None:
            filter_fields = ['name', 'comment', 'hash', 'save_path']
        else:
            if isinstance(params, list):
                filter_fields = params
            else:
                filter_fields = params.replace(" ","").split(",")

        proxy = component.get('SessionProxy')

        filter_dict = {}
        if ids is not None:
            filter_dict['id'] = set(ids).intersection(set(proxy.torrents.keys()))

        document = {
            'torrents': []
        }
        response = Deferred()

        deffered_torrents = proxy.get_torrents_status(filter_dict, filter_fields)

        def on_complete(torrents_dict):
            document['torrents'] = list(torrents_dict.values())
            response.callback(document)
        deffered_torrents.addCallback(on_complete)

        return response

    @export_api
    def add_torrent(self, metainfo, options=None):
        """Adds a torrent with the given options.
        metainfo could either be base64 torrent data or a magnet link.

        Returns `torrent_id` string or None.

        Available options are listed in deluge.core.torrent.TorrentOptions.

        :rtype: None|str
        """
        if options is None:
            options = {}

        coreconfig = component.get('CoreConfig')

        if 'download_location' not in options.keys():
            options.update({'download_location': coreconfig.get("download_location")})

        if common.is_magnet(metainfo):
            LOGGER.info('Adding torrent from magnet URI `%s` using options `%s` ...', metainfo, options)
            result = client.core.add_torrent_magnet(metainfo, options)

        else:
            LOGGER.info('Adding torrent from base64 string using options `%s` ...', options)
            result = client.core.add_torrent_file(None, metainfo, options)

        return result

    @export_api
    def remove_torrent(self, torrent_id, remove_data=False):
        """Removes a given torrent. Optionally can remove data."""
        return client.core.remove_torrent(torrent_id, remove_data)

    @export_api
    def get_api_version(self):
        """Returns WebAPI plugin version."""
        from webapi import VERSION
        return '.'.join(map(str, VERSION))


text:
namespace NuPattern.VisualStudio.Solution
{
    /// <summary>
    /// An item that has a data collection.
    /// </summary>
    public interface IDataContainer
    {
        /// <summary>
        /// Arbitrary data associated with the item, using dynamic property syntax
        /// (i.e. solution.Data.MyValue = "Hello").
        /// </summary>
        dynamic Data { get; }
    }
}


text:
#include "config.h"
#include "DFGOSRExitCompiler.h"

#if ENABLE(DFG_JIT) && USE(JSVALUE32_64)

#include "DFGOperations.h"
#include "DFGOSRExitCompilerCommon.h"
#include "DFGSpeculativeJIT.h"
#include "JSCInlines.h"
#include <wtf/DataLog.h>

namespace JSC { namespace DFG {

void OSRExitCompiler::compileExit(VM& vm, const OSRExit& exit, const Operands<ValueRecovery>& operands, SpeculationRecovery* recovery)
{
    // Pro-forma stuff.
    if (Options::printEachOSRExit()) {
        SpeculationFailureDebugInfo* debugInfo = new SpeculationFailureDebugInfo;
        debugInfo->codeBlock = m_jit.codeBlock();
        debugInfo->kind = exit.m_kind;
        debugInfo->bytecodeOffset = exit.m_codeOrigin.bytecodeIndex;

        m_jit.debugCall(vm, debugOperationPrintSpeculationFailure, debugInfo);
    }

    // Perform speculation recovery. This only comes into play when an operation
    // starts mutating state before verifying the speculation it has already made.

    if (recovery) {
        switch (recovery->type()) {
        case SpeculativeAdd:
            m_jit.sub32(recovery->src(), recovery->dest());
            break;

        case SpeculativeAddImmediate:
            m_jit.sub32(AssemblyHelpers::Imm32(recovery->immediate()), recovery->dest());
            break;

        case BooleanSpeculationCheck:
            break;

        default:
            break;
        }
    }

    // Refine some value profile, if appropriate.

    if (!!exit.m_jsValueSource) {
        if (exit.m_kind == BadCache || exit.m_kind == BadIndexingType) {
            // If the instruction that this originated from has an array profile, then
            // refine it. If it doesn't, then do nothing. The latter could happen for
            // hoisted checks, or checks emitted for operations that didn't have array
            // profiling - either ops that aren't array accesses at all, or weren't
            // known to be array acceses in the bytecode. The latter case is a FIXME
            // while the former case is an outcome of a CheckStructure not knowing why
            // it was emitted (could be either due to an inline cache of a property
            // property access, or due to an array profile).

            // Note: We are free to assume that the jsValueSource is already known to
            // be a cell since both BadCache and BadIndexingType exits occur after
            // the cell check would have already happened.

            CodeOrigin codeOrigin = exit.m_codeOriginForExitProfile;
            if (ArrayProfile* arrayProfile = m_jit.baselineCodeBlockFor(codeOrigin)->getArrayProfile(codeOrigin.bytecodeIndex)) {
                GPRReg usedRegister1;
                GPRReg usedRegister2;
                if (exit.m_jsValueSource.isAddress()) {
                    usedRegister1 = exit.m_jsValueSource.base();
                    usedRegister2 = InvalidGPRReg;
                } else {
                    usedRegister1 = exit.m_jsValueSource.payloadGPR();
                    if (exit.m_jsValueSource.hasKnownTag())
                        usedRegister2 = InvalidGPRReg;
                    else
                        usedRegister2 = exit.m_jsValueSource.tagGPR();
                }

                GPRReg scratch1;
                GPRReg scratch2;
                scratch1 = AssemblyHelpers::selectScratchGPR(usedRegister1, usedRegister2);
                scratch2 = AssemblyHelpers::selectScratchGPR(usedRegister1, usedRegister2, scratch1);

                m_jit.push(scratch1);
                m_jit.push(scratch2);

                GPRReg value;
                if (exit.m_jsValueSource.isAddress()) {
                    value = scratch1;
                    m_jit.loadPtr(AssemblyHelpers::Address(exit.m_jsValueSource.asAddress()), value);
                } else
                    value = exit.m_jsValueSource.payloadGPR();

                m_jit.loadPtr(AssemblyHelpers::Address(value, JSCell::structureIDOffset()), scratch1);
                m_jit.storePtr(scratch1, arrayProfile->addressOfLastSeenStructureID());
                m_jit.load8(AssemblyHelpers::Address(scratch1, Structure::indexingTypeIncludingHistoryOffset()), scratch1);
                m_jit.move(AssemblyHelpers::TrustedImm32(1), scratch2);
                m_jit.lshift32(scratch1, scratch2);
                m_jit.or32(scratch2, AssemblyHelpers::AbsoluteAddress(arrayProfile->addressOfArrayModes()));

                m_jit.pop(scratch2);
                m_jit.pop(scratch1);
            }
        }

        if (MethodOfGettingAValueProfile profile = exit.m_valueProfile) {
            if (exit.m_jsValueSource.isAddress()) {
                // Save a register so we can use it.
                GPRReg scratchPayload = AssemblyHelpers::selectScratchGPR(exit.m_jsValueSource.base());
                GPRReg scratchTag = AssemblyHelpers::selectScratchGPR(exit.m_jsValueSource.base(), scratchPayload);
                m_jit.pushToSave(scratchPayload);
                m_jit.pushToSave(scratchTag);

                JSValueRegs scratch(scratchTag, scratchPayload);

                m_jit.loadValue(exit.m_jsValueSource.asAddress(), scratch);
                profile.emitReportValue(m_jit, scratch);

                m_jit.popToRestore(scratchTag);
                m_jit.popToRestore(scratchPayload);
            } else if (exit.m_jsValueSource.hasKnownTag()) {
                GPRReg scratchTag = AssemblyHelpers::selectScratchGPR(exit.m_jsValueSource.payloadGPR());
                m_jit.pushToSave(scratchTag);
                m_jit.move(AssemblyHelpers::TrustedImm32(exit.m_jsValueSource.tag()), scratchTag);
                JSValueRegs value(scratchTag, exit.m_jsValueSource.payloadGPR());
                profile.emitReportValue(m_jit, value);
                m_jit.popToRestore(scratchTag);
            } else
                profile.emitReportValue(m_jit, exit.m_jsValueSource.regs());
        }
    }

    // Do a simplified OSR exit. See DFGOSRExitCompiler64.cpp's comment regarding how and wny we
    // do this simple approach.

    // Save all state from GPRs into the scratch buffer.

    ScratchBuffer* scratchBuffer = vm.scratchBufferForSize(sizeof(EncodedJSValue) * operands.size());
    EncodedJSValue* scratch = scratchBuffer ? static_cast<EncodedJSValue*>(scratchBuffer->dataBuffer()) : 0;

    for (size_t index = 0; index < operands.size(); ++index) {
        const ValueRecovery& recovery = operands[index];

        switch (recovery.technique()) {
        case UnboxedInt32InGPR:
        case UnboxedBooleanInGPR:
        case UnboxedCellInGPR:
            m_jit.store32(
                recovery.gpr(),
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.payload);
            break;

        case InPair:
            m_jit.store32(
                recovery.tagGPR(),
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.tag);
            m_jit.store32(
                recovery.payloadGPR(),
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.payload);
            break;

        default:
            break;
        }
    }

    // Now all GPRs are free to reuse.

    // Save all state from FPRs into the scratch buffer.

    for (size_t index = 0; index < operands.size(); ++index) {
        const ValueRecovery& recovery = operands[index];

        switch (recovery.technique()) {
        case UnboxedDoubleInFPR:
        case InFPR:
            m_jit.move(AssemblyHelpers::TrustedImmPtr(scratch + index), GPRInfo::regT0);
            m_jit.storeDouble(recovery.fpr(), MacroAssembler::Address(GPRInfo::regT0));
            break;

        default:
            break;
        }
    }

    // Now all FPRs are free to reuse.

    // Save all state from the stack into the scratch buffer. For simplicity we
    // do this even for state that's already in the right place on the stack.
    // It makes things simpler later.

    for (size_t index = 0; index < operands.size(); ++index) {
        const ValueRecovery& recovery = operands[index];

        switch (recovery.technique()) {
        case DisplacedInJSStack:
        case Int32DisplacedInJSStack:
        case DoubleDisplacedInJSStack:
        case CellDisplacedInJSStack:
        case BooleanDisplacedInJSStack:
            m_jit.load32(
                AssemblyHelpers::tagFor(recovery.virtualRegister()),
                GPRInfo::regT0);
            m_jit.load32(
                AssemblyHelpers::payloadFor(recovery.virtualRegister()),
                GPRInfo::regT1);
            m_jit.store32(
                GPRInfo::regT0,
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.tag);
            m_jit.store32(
                GPRInfo::regT1,
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.payload);
            break;

        default:
            break;
        }
    }

    // Need to ensure that the stack pointer accounts for the worst-case stack usage at exit. This
    // could toast some stack that the DFG used. We need to do it before storing to stack offsets
    // used by baseline.
    m_jit.addPtr(
        CCallHelpers::TrustedImm32(
            -m_jit.codeBlock()->jitCode()->dfgCommon()->requiredRegisterCountForExit * sizeof(Register)),
        CCallHelpers::framePointerRegister, CCallHelpers::stackPointerRegister);

    // Restore the DFG callee saves and then save the ones the baseline JIT uses.
    m_jit.emitRestoreCalleeSaves();
    m_jit.emitSaveCalleeSavesFor(m_jit.baselineCodeBlock());

    if (exit.isExceptionHandler())
        m_jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(vm);

    // Do all data format conversions and store the results into the stack.

    for (size_t index = 0; index < operands.size(); ++index) {
        const ValueRecovery& recovery = operands[index];
        VirtualRegister reg = operands.virtualRegisterForIndex(index);

        if (reg.isLocal() && reg.toLocal() < static_cast<int>(m_jit.baselineCodeBlock()->calleeSaveSpaceAsVirtualRegisters()))
            continue;

        int operand = reg.offset();

        switch (recovery.technique()) {
        case InPair:
        case DisplacedInJSStack:
        case InFPR:
            m_jit.load32(
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.tag,
                GPRInfo::regT0);
            m_jit.load32(
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.payload,
                GPRInfo::regT1);
            m_jit.store32(
                GPRInfo::regT0,
                AssemblyHelpers::tagFor(operand));
            m_jit.store32(
                GPRInfo::regT1,
                AssemblyHelpers::payloadFor(operand));
            break;

        case UnboxedDoubleInFPR:
        case DoubleDisplacedInJSStack:
            m_jit.move(AssemblyHelpers::TrustedImmPtr(scratch + index), GPRInfo::regT0);
            m_jit.loadDouble(MacroAssembler::Address(GPRInfo::regT0), FPRInfo::fpRegT0);
            m_jit.purifyNaN(FPRInfo::fpRegT0);
            m_jit.storeDouble(FPRInfo::fpRegT0, AssemblyHelpers::addressFor(operand));
            break;

        case UnboxedInt32InGPR:
        case Int32DisplacedInJSStack:
            m_jit.load32(
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.payload,
                GPRInfo::regT0);
            m_jit.store32(
                AssemblyHelpers::TrustedImm32(JSValue::Int32Tag),
                AssemblyHelpers::tagFor(operand));
            m_jit.store32(
                GPRInfo::regT0,
                AssemblyHelpers::payloadFor(operand));
            break;

        case UnboxedCellInGPR:
        case CellDisplacedInJSStack:
            m_jit.load32(
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.payload,
                GPRInfo::regT0);
            m_jit.store32(
                AssemblyHelpers::TrustedImm32(JSValue::CellTag),
                AssemblyHelpers::tagFor(operand));
            m_jit.store32(
                GPRInfo::regT0,
                AssemblyHelpers::payloadFor(operand));
            break;

        case UnboxedBooleanInGPR:
        case BooleanDisplacedInJSStack:
            m_jit.load32(
                &bitwise_cast<EncodedValueDescriptor*>(scratch + index)->asBits.payload,
                GPRInfo::regT0);
            m_jit.store32(
                AssemblyHelpers::TrustedImm32(JSValue::BooleanTag),
                AssemblyHelpers::tagFor(operand));
            m_jit.store32(
                GPRInfo::regT0,
                AssemblyHelpers::payloadFor(operand));
            break;

        case Constant:
            m_jit.store32(
                AssemblyHelpers::TrustedImm32(recovery.constant().tag()),
                AssemblyHelpers::tagFor(operand));
            m_jit.store32(
                AssemblyHelpers::TrustedImm32(recovery.constant().payload()),
                AssemblyHelpers::payloadFor(operand));
            break;

        case DirectArgumentsThatWereNotCreated:
        case ClonedArgumentsThatWereNotCreated:
            // Don't do this, yet.
            break;

        default:
            break;
        }
    }

    // Now that things on the stack are recovered, do the arguments recovery. We assume that arguments
    // recoveries don't recursively refer to each other. But, we don't try to assume that they only
    // refer to certain ranges of locals. Hence why we need to do this here, once the stack is sensible.
    // Note that we also roughly assume that the arguments might still be materialized outside of its
    // inline call frame scope - but for now the DFG wouldn't do that.

    emitRestoreArguments(operands);

    // Adjust the old JIT's execute counter. Since we are exiting OSR, we know
    // that all new calls into this code will go to the new JIT, so the execute
    // counter only affects call frames that performed OSR exit and call frames
    // that were still executing the old JIT at the time of another call frame's
    // OSR exit. We want to ensure that the following is true:
    //
    // (a) Code the performs an OSR exit gets a chance to reenter optimized
    //     code eventually, since optimized code is faster. But we don't
    //     want to do such reentery too aggressively (see (c) below).
    //
    // (b) If there is code on the call stack that is still running the old
    //     JIT's code and has never OSR'd, then it should get a chance to
    //     perform OSR entry despite the fact that we've exited.
    //
    // (c) Code the performs an OSR exit should not immediately retry OSR
    //     entry, since both forms of OSR are expensive. OSR entry is
    //     particularly expensive.
    //
    // (d) Frequent OSR failures, even those that do not result in the code
    //     running in a hot loop, result in recompilation getting triggered.
    //
    // To ensure (c), we'd like to set the execute counter to
    // counterValueForOptimizeAfterWarmUp(). This seems like it would endanger
    // (a) and (b), since then every OSR exit would delay the opportunity for
    // every call frame to perform OSR entry. Essentially, if OSR exit happens
    // frequently and the function has few loops, then the counter will never
    // become non-negative and OSR entry will never be triggered. OSR entry
    // will only happen if a loop gets hot in the old JIT, which does a pretty
    // good job of ensuring (a) and (b). But that doesn't take care of (d),
    // since each speculation failure would reset the execute counter.
    // So we check here if the number of speculation failures is significantly
    // larger than the number of successes (we want 90% success rate), and if
    // there have been a large enough number of failures. If so, we set the
    // counter to 0; otherwise we set the counter to
    // counterValueForOptimizeAfterWarmUp().

    handleExitCounts(m_jit, exit);

    // Reify inlined call frames.

    reifyInlinedCallFrames(m_jit, exit);

    // And finish.
    adjustAndJumpToTarget(vm, m_jit, exit);
}

} } // namespace JSC::DFG

#endif // ENABLE(DFG_JIT) && USE(JSVALUE32_64)


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Highway.Data.Interceptors.Events;

namespace Highway.Data
{
    /// <summary>
    ///     The base query that allows for appending expressions, query extensions, and eventing
    /// </summary>
    public abstract class QueryBase : IExtendableQuery, IObservableQuery
    {
        private static readonly ReadOnlyCollection<MethodInfo> QueryableMethods;

        /// <summary>
        ///     Holds the expressions to be appended
        /// </summary>
        protected List<Tuple<MethodInfo, Expression[]>> ExpressionList = new List<Tuple<MethodInfo, Expression[]>>();

        static QueryBase()
        {
            QueryableMethods = new ReadOnlyCollection<MethodInfo>(typeof (Queryable)
                .GetMethods(BindingFlags.Public |
                            BindingFlags.Static).ToList());
        }

        /// <summary>
        ///     The reference to the <see cref="IDataContext" /> that gives data connection
        /// </summary>
        protected IDataContext Context { get; set; }

        /// <summary>
        ///     Adds a method to the expression in the query object
        /// </summary>
        /// <param name="methodName">The name of the method to be added i.e. GroupBy</param>
        /// <param name="generics">Any type parameters needed by the method to be added</param>
        /// <param name="parameters">Any object parameters needed by the method to be added</param>
        public virtual void AddMethodExpression(string methodName, Type[] generics, Expression[] parameters)
        {
            MethodInfo orderMethodInfo =
                QueryableMethods.First(m => m.Name == methodName && m.GetParameters().Length == parameters.Length + 1);

            orderMethodInfo = orderMethodInfo.MakeGenericMethod(generics);
            ExpressionList.Add(new Tuple<MethodInfo, Expression[]>(orderMethodInfo, parameters));
        }

        /// <summary>
        ///     The event fired just before the query goes to the database
        /// </summary>
        public event EventHandler<BeforeQuery> BeforeQuery;

        /// <summary>
        ///     The event fire just after the data is translated into objects but before the data is returned.
        /// </summary>
        public event EventHandler<AfterQuery> AfterQuery;

        /// <summary>
        ///     Checks the context and the Query for null
        /// </summary>
        /// <param name="query">The query to be executed</param>
        protected virtual void CheckContextAndQuery(object query)
        {
            if (Context == null) throw new InvalidOperationException("DataContext cannot be null.");
            if (query == null) throw new InvalidOperationException("Null Query cannot be executed.");
        }
    }
}


text:
cask "paparazzi" do
  version "1.0b11,868"
  sha256 "106c31b4297f3a9671648db75adfbb79c929de3af306b537aa141b7bac668a7c"

  url "https://derailer.org/paparazzi/Paparazzi!%20#{version.before_comma}.dmg"
  name "Paparazzi!"
  desc "Utility to take screenshots of webpages"
  homepage "https://derailer.org/paparazzi/"

  livecheck do
    url "https://derailer.org/paparazzi/appcast/"
    strategy :sparkle
  end

  app "Paparazzi!.app"

  zap trash: [
    "~/Library/Application Support/Paparazzi!",
    "~/Library/Caches/org.derailer.Paparazzi",
    "~/Library/Cookies/org.derailer.Paparazzi.binarycookies",
    "~/Library/Preferences/org.derailer.Paparazzi.plist",
    "~/Library/Saved Application State/org.derailer.Paparazzi.savedState",
  ]
end


text:
package org.apache.pdfbox.pdfparser;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdmodel.fdf.FDFDocument;

public class FDFParser extends COSParser
{
    private static final Log LOG = LogFactory.getLog(FDFParser.class);

    /**
     * Constructs parser for given file using memory buffer.
     *
     * @param source the source of the pdf to be parsed
     *
     * @throws IOException If something went wrong.
     */
    public FDFParser(RandomAccessRead source) throws IOException
    {
        super(source);
        init();
    }

    /**
     * Tell if the dictionary is a FDF catalog.
     *
     * @param dictionary
     * @return true if the dictionary is a FDF catalog
     */
    @Override
    protected final boolean isCatalog(COSDictionary dictionary)
    {
        return dictionary.containsKey(COSName.FDF);
    }

    private void init()
    {
        String eofLookupRangeStr = System.getProperty(SYSPROP_EOFLOOKUPRANGE);
        if (eofLookupRangeStr != null)
        {
            try
            {
                setEOFLookupRange(Integer.parseInt(eofLookupRangeStr));
            }
            catch (NumberFormatException nfe)
            {
                LOG.warn("System property " + SYSPROP_EOFLOOKUPRANGE
                        + " does not contain an integer value, but: '" + eofLookupRangeStr + "'");
            }
        }
        document = new COSDocument(this);
    }

    /**
     * The initial parse will first parse only the trailer, the xrefstart and all xref tables to have a pointer (offset)
     * to all the pdf's objects. It can handle linearized pdfs, which will have an xref at the end pointing to an xref
     * at the beginning of the file. Last the root object is parsed.
     *
     * @throws IOException If something went wrong.
     */
    private void initialParse() throws IOException
    {
        COSDictionary trailer = retrieveTrailer();

        COSDictionary root = trailer.getCOSDictionary(COSName.ROOT);
        if (root == null)
        {
            throw new IOException("Missing root object specification in trailer.");
        }
        initialParseDone = true;
    }

    /**
     * This will parse the stream and populate the FDFDocument object.
     *
     * @return the parsed FDFDocument
     * @throws IOException If there is an error reading from the stream or corrupt data is found.
     */
    public FDFDocument parse() throws IOException
    {
         // set to false if all is processed
         boolean exceptionOccurred = true;
         try
         {
            if (!parseFDFHeader())
            {
                throw new IOException( "Error: Header doesn't contain versioninfo" );
            }
            initialParse();
            exceptionOccurred = false;
            return new FDFDocument(document);
        }
        finally
        {
            if (exceptionOccurred && document != null)
            {
                IOUtils.closeQuietly(document);
                document = null;
            }
        }
    }
}


text:
package org.ovirt.engine.core.bll.scheduling.commands;

import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.scheduling.AffinityGroup;
import org.ovirt.engine.core.common.scheduling.parameters.AffinityGroupCRUDParameters;
import org.ovirt.engine.core.compat.Guid;

public class AddAffinityGroupCommand extends AffinityGroupCRUDCommand {

    public AddAffinityGroupCommand(AffinityGroupCRUDParameters parameters) {
        super(parameters);
    }

    @Override
    protected boolean validate() {
        if (getAffinityGroupDao().getByName(getParameters().getAffinityGroup().getName()) != null) {
            return failValidation(EngineMessage.ACTION_TYPE_FAILED_AFFINITY_GROUP_NAME_EXISTS);
        }
        return validateParameters();
    }

    @Override
    protected AffinityGroup getAffinityGroup() {
        return getParameters().getAffinityGroup();
    }

    @Override
    protected void executeCommand() {
        getAffinityGroup().setId(Guid.newGuid());
        getAffinityGroupDao().save(getAffinityGroup());
        getReturnValue().setActionReturnValue(getAffinityGroup().getId());
        setSucceeded(true);
    }

    @Override
    public AuditLogType getAuditLogTypeValue() {
        return getSucceeded() ? AuditLogType.USER_ADDED_AFFINITY_GROUP : AuditLogType.USER_FAILED_TO_ADD_AFFINITY_GROUP;
    }

    @Override
    protected void setActionMessageParameters() {
        super.setActionMessageParameters();
        addValidationMessage(EngineMessage.VAR__ACTION__ADD);
    }
}


text:
import { hop } from '../constants'

/**
 * Returns an object's own keys as an array of strings. It uses a for-in loop in the back in combination with hasOwnProperty.
 * @param { object } obj
 * @return { [string] }
 */
export function keys(obj) {
  const objKeys = []

  for (var key in obj) {
    if (hop(obj, key)) {
      objKeys.push(key)
    }
  }

  return objKeys
}

/**
 * Returns an object's own values as an array. It uses a for-in loop in the back in combination with hasOwnProperty.
 * @param { object } obj
 * @return { [*] }
 */
export function values(obj) {
  const objValues = []

  for (var key in obj) {
    if (hop(obj, key)) {
      objValues.push(obj[key])
    }
  }

  return objValues
}


text:
package events;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.junit.Assert.assertTrue;

/**
 * Created by v.chibrikov on 07.01.2015.
 */
public class EventSourceTest {
    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

    @Before
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
    }

    @Test
    public void fireTest() {
        EventSource source = new EventSource();
        source.subscribe(new MessageEventListener());
        final String message = "Hello!";
        source.fire(new MessageEvent(message));
        assertTrue(outContent.toString().contains(message));
    }

    @After
    public void cleanUpStreams() {
        System.setOut(null);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Alaska Gratin</title>
      <categories>
        <cat>Fish</cat>
        <cat>Main dish</cat>
        <cat>Microwave</cat></categories>
      <yield>4</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>213</qty>
          <unit>grams</unit></amt>
        <item>Canned pink Alaska salmon</item></ing>
      <ing>
        <amt>
          <qty>90</qty>
          <unit>mililiters</unit></amt>
        <item>Milk</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit>tablespoons</unit></amt>
        <item>Greek yogurt</item></ing>
      <ing>
        <amt>
          <qty>450</qty>
          <unit>grams</unit></amt>
        <item>Old potatoes peeled and thinly sliced</item></ing>
      <ing>
        <amt>
          <qty>15</qty>
          <unit>grams</unit></amt>
        <item>Butter or margarine</item></ing>
      <ing>
        <amt>
          <qty>100</qty>
          <unit>grams</unit></amt>
        <item>Button mushrooms, sliced</item></ing>
      <ing>
        <amt>
          <qty>100</qty>
          <unit>grams</unit></amt>
        <item>Courgettes; chopped</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Freshly chopped chives</item></ing>
      <ing>
        <amt>
          <qty>100</qty>
          <unit>grams</unit></amt>
        <item>Cheddar cheese, grated</item></ing></ingredients>
    <directions>
      <step>  Drain can of salmon. Mix juice with milk and yogurt. Melt butter on HIGH
  POWER for 30 seconds. Stir in mushrooms, courgette and chives, cook for 2
  minutes on HIGH POWER.

  Flake in salmon. Arrange one third of potato slices into base of microwave
  proof dish. Spread half salmon mixture over. Top with third of potatoes.
  Add remaining salmon, cover with rest of potatoes. Pour over salmon stock.
  Sprinkle with cheese and cover. Cook on MEDIUM POWER for 15 minutes.
  Uncover and cook for 5 minutes. Stand for 5 minutes. Brown under a
  conventional grill before serving.

  Serves 4. Approx. 340 kcals per serving

  From: On the Wild Side - Alaska Canned Salmon Recipes Reprinted with
  permission from Alaska Seafood Marketing Institute Meal-Master compatible
  recipe format courtesy of Karen Mintzias

  From Gemini's MASSIVE MealMaster collection at www.synapse.com/~gemini

</step></directions></recipe></recipeml>


text:
``` diff
 namespace System.Text.Json.Serialization {
+    public sealed class JsonRequiredAttribute : JsonAttribute {
+        public JsonRequiredAttribute();
+    }
-    [RequiresDynamicCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
-    public class JsonStringEnumConverter : JsonConverterFactory
+    [RequiresDynamicCodeAttribute("JsonStringEnumConverter cannot be statically analyzed and requires runtime code generation. Consider authoring a custom converter that is not a factory to work around the issue. See https://github.com/dotnet/runtime/issues/73124.")]
+    public class JsonStringEnumConverter : JsonConverterFactory
 }
```


text:
package com.zongtui.filter.bloom;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.zongtui.filter.IFilter;
import com.zongtui.filter.Page;

import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ClassName: BloomFilter

 * Function: BloomFilter实现

 * date: 2015-4-8 下午3:31:10

 *
 * @author Jason
 * @since JDK 1.7
 */
public class BloomFilterImpl implements IFilter {

    /**
     * 需要插入的数据量.
     */
    private int expectedInsertions;

    /**
     * 精准度.
     */
    private double fpp;

    /**
     * 当前数据量.
     */
    private AtomicInteger counter;

    public BloomFilterImpl() {
        this(1000, 0.01);
    }

    public BloomFilterImpl(int expectedInsertions) {
        this(expectedInsertions, 0.01);
    }

    public BloomFilterImpl(int expectedInsertions, double fpp) {
        this.expectedInsertions = expectedInsertions;
        this.fpp = fpp;
        this.bloomFilter = rebuildBloomFilter();
    }

    private final BloomFilter<CharSequence> bloomFilter;

    protected BloomFilter<CharSequence> rebuildBloomFilter() {
        counter = new AtomicInteger(0);
        return BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), expectedInsertions, fpp);
    }

    /**
     * similar:判断内容的相似性,为1表示已经存在,为0表示不存在,为浮点数则判断相似度的值.

     *
     * @param page
     * @return
     * @author feng
     * @since JDK 1.7
     */
    @Override
    public float similar(Page page) {
        float similarValue = 1;
        boolean isDuplicate = bloomFilter.mightContain(page.getUrl());
        if (!isDuplicate) {
            bloomFilter.put(page.getUrl());
            counter.incrementAndGet();
            similarValue = 0;
        }
        return similarValue;
    }

}


text:
class AddMlhToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :mlh, :boolean, :default => false
  end

  def self.down
    remove_column :users, :mlh
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>it.unical.mat.embasp.specializations.dlv.desktop</title>
<meta name="date" content="2020-01-23">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

it.unical.mat.embasp.specializations.dlv.desktop

Classes

DLVDesktopService


text:
include(${CMAKE_CURRENT_LIST_DIR}/config.cmake)

# 设置项目;
SET(DIOS_PROJECT_CURRENT_MODULE ${DIOS_CONFIG_MODULE}) # 设置项目; 为什么不直接用DIOS_CONFIG_MODULE? DIOS_CONFIG_MODULE会每次加载配置的时候都会重置.

# 添加9层目录,只为加载dios_cmake;
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../../../../../../..)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../../../../../..)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../../../../..)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../../../..)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../../..)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../../..)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../..)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/../..)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/..)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})

# 包含dios_cmake
include(dios_cmake.project)

# 构建;
dios_builder_android_build_module(${DIOS_PROJECT_CURRENT_MODULE} ${CMAKE_CURRENT_LIST_DIR})


text:
from django.db import models
from django.db.models import Count, Sum
from django.contrib.auth.models import AbstractUser
from sgce.models import Enrollment, Event, Payment

class Person(AbstractUser):
	MALE = 'M'
	FEMALE = 'F'

	SEX_CHOICES = (
		(MALE, 'M'),
		(FEMALE, 'F'),
	)

	PARTICIPANT = 'P'
	OPERATOR = 'O'
	RECEPTIONIST = 'R'

	STYPE_CHOICES = (
		(PARTICIPANT, 'Participante'),
		(OPERATOR, 'Operador'),
		(RECEPTIONIST, 'Recepcionista'),
	)

	name = models.CharField(verbose_name='Nome', max_length=30)
	cpf = models.CharField(verbose_name='CPF', max_length=11)
	nationality = models.CharField(verbose_name='Nacionalidade', max_length=64)
	sex = models.CharField(verbose_name='Sexo', max_length=1, choices=SEX_CHOICES, default=MALE)
	scholarity = models.CharField(verbose_name='Escolaridade', max_length=32)
	birth = models.DateField(verbose_name='Data de nascimento')
	stype = models.CharField(max_length=1, choices=STYPE_CHOICES, default=PARTICIPANT)

	USERNAME_FIELD = 'username'
	REQUIRED_FIELDS = ['name', 'email', 'cpf', 'nationality', 'sex', 'scholarity', 'birth']

	class Meta:
		verbose_name = 'Pessoa'
		verbose_name_plural = 'Pessoas'

	def __unicode__(self):
		return self.username

	def nof_events_enrolled(self):
		enrollments = Enrollment.objects.filter(person=self)
		return Event.objects.filter(enrollments__in=enrollments).distinct().count()

	def nof_activities_enrolled(self):
		act = 0
		for enrollment in Enrollment.objects.filter(person=self).annotate(act_count=Count('activities__id', distinct=True)):
			act += enrollment.act_count
		return act

	def nof_enrollments(self):
		return Enrollment.objects.filter(person=self).count()

	def money_spent(self):
		return Payment.objects.filter(enrollment__person=self).aggregate(Sum('price'))['price__sum']

	def points_earned(self):
		return Enrollment.objects.filter(person=self).aggregate(Sum('points'))['points__sum']


text:
package maniac.lee.shardy.config;

/**
 * Created by lipeng on 16/2/5.
 */
public class ShardResult {

    private String tableName;
    private String dbName;

    public ShardResult(String tableName, String dbName) {
        this.tableName = tableName;
        this.dbName = dbName;
    }

    public static ShardResult ofTable(String s) {
        return new ShardResult(s, null);
    }

    public ShardResult(String tableName) {
        this(tableName, null);
    }

    public static ShardResult create(String tableName, String dbName) {
        return new ShardResult(tableName, dbName);
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getDbName() {
        return dbName;
    }

    public void setDbName(String dbName) {
        this.dbName = dbName;
    }
}


text:
'use strict';

var bufrw = require('bufrw');
var TYPE = require('./TYPE');

var DoubleRW = bufrw.DoubleBE;

function ThriftDouble(annotations) {
    this.annotations = annotations;
}

ThriftDouble.prototype.rw = DoubleRW;
ThriftDouble.prototype.name = 'double';
ThriftDouble.prototype.typeid = TYPE.DOUBLE;
ThriftDouble.prototype.surface = Number;
ThriftDouble.prototype.models = 'type';

module.exports.DoubleRW = DoubleRW;
module.exports.ThriftDouble = ThriftDouble;


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Compara API Tutorial</title>

Compara API Tutorial

Introduction

This tutorial is an introduction to the EnsEMBL Compara API.
Knowledge of the
EnsEMBL Core API and of the concepts and conventions in the
EnsEMBL Core API tutorial is assumed.
Documentation about the Compara database schema is available at
http://cvs.sanger.ac.uk/cgi-bin/viewvc.cgi/ensembl-compara/docs/?root=ensembl
(or in ensembl-compara/docs/docs/schema_doc.html from the EnsEMBL CVS repository), and while is not necessary for this tutorial,
an understanding of the database tables may help as many of the adaptor modules are table-specific.

Installing the API

API installation and updating is the same as per the core API.

Connecting to an EnsEMBL Compara database

Connection parameters

Starting from rel.48 EnsEMBL is running two public MySQL servers on host=ensembldb.ensembl.org with two different port numbers. The server on port=3306 hosts all databases prior to rel.48 and the server on port=5306 hosts all newer databases starting from rel.48.

There are two API ways to connect to the EnsEMBL Compara database:

In most cases you will prefer the implicit way - using Bio::EnsEMBL::Registry module,
which can read either a global or a specific configuration file or auto-configure itself.

However there are cases where you might want more flexibility provided by the
explicit creation of a Bio::EnsEMBL::Compara::DBSQL::DBAdaptor.

Implicitly, using the Bio::EnsEMBL::Registry auto-configuration feature (recommended)

For using the auto-configuration feature, you will first need to supply the connection parameters to the
Registry loader. For instance, if you want to connect to the the public EnsEMBL databases you can
use the following command in your scripts:

use Bio::EnsEMBL::Registry;
Bio::EnsEMBL::Registry->load_registry_from_db(
    -host => 'ensembldb.ensembl.org',
    -user => 'anonymous',
    -port => 5306);

This will initialize the Registry, from which you will be able to create object-specific adaptors later.

Alternatively, you can use a shorter version based on a URL:

use Bio::EnsEMBL::Registry;
Bio::EnsEMBL::Registry->load_registry_from_url('mysql://anonymous@ensembldb.ensembl.org:5306/');

Implicitly, using the Bio::EnsEMBL::Registry configuration file

You will need to have a registry configuration file set up.
By default, it takes the file defined by the ENSEMBL_REGISTRY environment variable or
the file named .ensembl_init in your home directory if the former is not found.
Additionally, you can use a specific file
(see perldoc Bio::EnsEMBL::Registry or later in this document for some examples on how to use a different file).
Please, refer to the EnsEMBL registry documentation for details about this option.

Explicitly, using the Bio::EnsEMBL::Compara::DBSQL::DBAdaptor

EnsEMBL Compara data, like core data, is stored in a MySQL relational database.
If you want to access a Compara database, you will need to connect to it.
This is done in exactly the same way as to connect to an EnsEMBL core database,
but using a Compara-specific DBAdaptor. One parameter you have to supply
in addition to the ones needed by the Registry is the -dbname, which by convention contains the release number:

use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor

my $host   = 'ensembldb.ensembl.org';
my $user   = 'anonymous';
my $port   = 5306;
my $dbname = 'ensembl_compara_52';

my $comparadb= new Bio::EnsEMBL::Compara::DBSQL::DBAdaptor(
    -host   => $host,
    -port   => $port,
    -user   => $user,
    -dbname => $dbname,
);

EnsEMBL Compara object-specific adaptors

EnsEMBL Compara adaptors are used to fetch data from the database. Data are returned as EnsEMBL objects.
For instance, the GenomeDBAdaptor returns Bio::EnsEMBL::Compara::GenomeDB objects.

Below is a non-exhaustive list of EnsEMBL Compara adaptors that are most often used:

GenomeDBAdaptor to fetch Bio::EnsEMBL::Compara::GenomeDB objects

DnaFragAdaptor to fetch Bio::EnsEMBL::Compara::DnaFrag objects

GenomicAlignBlockAdaptor to fetch Bio::EnsEMBL::Compara::GenomicAlignBlock objects

DnaAlignFeatureAdaptor to fetch Bio::EnsEMBL::DnaDnaAlignFeature objects
(note that this adaptor returns an EnsEMBL Core object)

SyntenyAdaptor to fetch Bio::EnsEMBL::Compara::SyntenyRegion objects

MemberAdaptor to fetch Bio::EnsEMBL::Compara::Member objects

HomologyAdaptor to fetch Bio::EnsEMBL::Compara::Homology objects

FamilyAdaptor to fetch Bio::EnsEMBL::Compara::Family objects

PeptideAlignFeatureAdaptor to fetch Bio::EnsEMBL::Compara::PeptideAlignFeature objects

Only some of these adaptors will be used for illustration as part of this tutorial through commented perl scripts code.

You can get the adaptors from the Registry with the get_adaptor command. You need to specify three arguments: the
species name, the type of database and the type of object. Therefore, in order to get the GenomeDBAdaptor for the
Compara database, you will need the following command:

my $genome_db_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
    'Multi', 'compara', 'GenomeDB');

NB: As the EnsEMBL Compara DB is a multi-species database, the standard species name is 'Multi'. The type of the
database is 'compara'.

Code Conventions

Refer to the EnsEMBL core tutorial for a good description of the coding conventions normally used in EnsEMBL.

We can divide the fetching methods of the ObjectAdaptors into two categories: the fetch_by and fetch_all_by. The former return one single object while the latter return a reference to an array of objects.

my $this_genome_db = $genome_db_adaptor->fetch_by_name_assembly("Homo sapiens", "NCBI36");

my $all_genome_dbs = $genome_db_adaptor->fetch_all();
foreach my $this_genome_db (@{$all_genome_dbs}) {
  print $this_genome_db->name, "\n";
}

Whole Genome Alignments

The Compara database contains a number of different types of whole genome alignments.
A listing about what are these different types can be found in the ensembl-compara/docs/schema_doc.html document in method_link section.

GenomicAlignBlock objects

GenomicAlignBlocks are the preferred way to store and fetch genomic alignments.
A GenomicAlignBlock contains several GenomicAlign objects.
Every GenomicAlign object corresponds to a piece of genomic sequence aligned with the other GenomicAlign in the same GenomicAlignBlock.
A GenomicAlign object is always in relation with other GenomicAlign objects
and this relation is defined through the GenomicAlignBlock object.
Therefore the usual way to fetch genomic alignments is by fetching GenomicAlignBlock objects.
We have to start by getting the corresponding adaptor:

# Getting the GenomicAlignBlock adaptor:
my $genomic_align_block_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
    'Multi', 'compara', 'GenomicAlignBlock');

In order to fetch the right alignments we need to specify a couple of data:
the type of alignment and the piece of genomic sequence in which we are looking for alignments.
The type of alignment is a more tricky now:
you need to specify both the alignment method and the set of genomes.
In order to simply this task, you could use the new Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object.
The best way to use them is by fetching them from the database:

# Getting the GenomeDB adaptor:
my $genome_db_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
    'Multi', 'compara', 'GenomeDB');

# Fetching GenomeDB objects for human and mouse:
my $human_genome_db = $genome_db_adaptor->fetch_by_name_assembly('Homo sapiens');
my $mouse_genome_db = $genome_db_adaptor->fetch_by_name_assembly('Mus musculus');

# Getting the MethodLinkSpeciesSet adaptor:
my $method_link_species_set_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
    'Multi', 'compara', 'MethodLinkSpeciesSet');

# Fetching the MethodLinkSpeciesSet object corresponding to BLASTZ_NET alignments between human and mouse genomic sequences:
my $human_mouse_blastz_net_mlss =
    $method_link_species_set_adaptor->fetch_by_method_link_type_GenomeDBs(
        "BLASTZ_NET",
        [$human_genome_db, $mouse_genome_db]
    );

There are two ways to fetch GenomicAlignBlocks.
One uses Bio::EnsEMBL::Slice objects while the second one is based on
Bio::EnsEMBL::Compara::DnaFrag objects for specifying the piece of genomic
sequence in which we are looking for alignments.

my $query_species = 'human';
my $seq_region = '14';
my $seq_region_start = 75000000;
my $seq_region_end   = 75010000;

# Getting the Slice adaptor:
my $slice_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
    $query_species, 'core', 'Slice');

# Fetching a Slice object:
my $query_slice = $slice_adaptor->fetch_by_region(
    'toplevel',
    $seq_region,
    $seq_region_start,
    $seq_region_end);

# Fetching all the GenomicAlignBlock corresponding to this Slice:
my $genomic_align_blocks =
    $genomic_align_block_adaptor->fetch_all_by_MethodLinkSpeciesSet_Slice(
      $human_mouse_blastz_net_mlss,
      $query_slice);

Here is an example script with all of this:

use strict;
use Bio::EnsEMBL::Registry;
use Bio::EnsEMBL::Utils::Exception qw(throw);
use Bio::SimpleAlign;
use Bio::AlignIO;
use Bio::LocatableSeq;
use Getopt::Long;

my $usage = qq{
perl DumpMultiAlign.pl
  Getting help:
    [--help]

  For the query slice:
    [--species species]
        Query species. Default is "human"
    [--coord_system coordinates_name]
        Query coordinate system. Default is "chromosome"
    --seq_region region_name
        Query region name, i.e. the chromosome name
    --seq_region_start start
    --seq_region_end end

  For the alignments:
    [--alignment_type method_link_name]
        The type of alignment. Default is "BLASTZ_NET"
    [--set_of_species species1:species2:species3:...]
        The list of species used to get those alignments. Default is
        "human:mouse". The names should correspond to the name of the
        core database in the registry_configuration_file or any of its
        aliases

  Ouput:
    [--output_format clustalw|fasta|...]
        The type of output you want. "clustalw" is the default.
    [--output_file filename]
        The name of the output file. By default the output is the
        standard output
};

my $species = "human";
my $coord_system = "chromosome";
my $seq_region = "14";
my $seq_region_start = 75000000;
my $seq_region_end = 75010000;
my $alignment_type = "BLASTZ_NET";
my $set_of_species = "human:mouse";
my $output_file = undef;
my $output_format = "clustalw";
my $help;

GetOptions(
    "help" => \$help,
    "species=s" => \$species,
    "coord_system=s" => \$coord_system,
    "seq_region=s" => \$seq_region,
    "seq_region_start=i" => \$seq_region_start,
    "seq_region_end=i" => \$seq_region_end,
    "alignment_type=s" => \$alignment_type,
    "set_of_species=s" => \$set_of_species,
    "output_format=s" => \$output_format,
    "output_file=s" => \$output_file);

# Print Help and exit
if ($help) {
    print $usage;
    exit(0);
}

if ($output_file) {
    open(STDOUT, ">$output_file") or die("Cannot open $output_file");
}

Bio::EnsEMBL::Registry->load_registry_from_db(
    -host => 'ensembldb.ensembl.org', -user => 'anonymous');

# Getting all the Bio::EnsEMBL::Compara::GenomeDB objects
my $genome_dbs;
my $genome_db_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
    'Multi', 'compara', 'GenomeDB');

throw("Cannot connect to Compara") if (!$genome_db_adaptor);

foreach my $this_species (split(":", $set_of_species)) {
    my $this_meta_container_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
        $this_species, 'core', 'MetaContainer');

    throw("Registry configuration file has no data for connecting to <$this_species&")
        if (!$this_meta_container_adaptor);

    my $this_binomial_id = $this_meta_container_adaptor->get_Species->binomial;

    # Fetch Bio::EnsEMBL::Compara::GenomeDB object
    my $genome_db = $genome_db_adaptor->fetch_by_name_assembly($this_binomial_id);

    # Add Bio::EnsEMBL::Compara::GenomeDB object to the list
    push(@$genome_dbs, $genome_db);
}

# Getting Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object
my $method_link_species_set_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
    'Multi', 'compara', 'MethodLinkSpeciesSet');

my $method_link_species_set =
    $method_link_species_set_adaptor->fetch_by_method_link_type_GenomeDBs(
      $alignment_type,
      $genome_dbs);

throw("The database do not contain any $alignment_type data for $set_of_species!")
    if (!$method_link_species_set);

# Fetching the query Slice:
my $slice_adaptor = Bio::EnsEMBL::Registry->get_adaptor($species, 'core', 'Slice');

throw("Registry configuration file has no data for connecting to <$species>")
    if (!$slice_adaptor);

my $query_slice = $slice_adaptor->fetch_by_region('toplevel', $seq_region, $seq_region_start, $seq_region_end);

throw("No Slice can be created with coordinates $seq_region:$seq_region_start-".
    "$seq_region_end") if (!$query_slice);

# Fetching all the GenomicAlignBlock corresponding to this Slice:
my $genomic_align_block_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
    'Multi', 'compara', 'GenomicAlignBlock');

my $genomic_align_blocks =
    $genomic_align_block_adaptor->fetch_all_by_MethodLinkSpeciesSet_Slice(
      $method_link_species_set,
      $query_slice);

my $all_aligns;

# Get a Bio::SimpleAlign object from every GenomicAlignBlock
foreach my $this_genomic_align_block (@$genomic_align_blocks) {
    my $simple_align = $this_genomic_align_block->get_SimpleAlign;
    push(@$all_aligns, $simple_align);
}

# print all the genomic alignments using a Bio::AlignIO object
my $alignIO = Bio::AlignIO->newFh(
    -interleaved => 0,
    -fh => \*STDOUT,
    -format => $output_format,
    -idlength => 10
);

foreach my $this_align (@$all_aligns) {
    print $alignIO $this_align;
}

exit;

Homologies and Protein clusters

All the homologies and families refer to Members. Homology objects store orthologous and paralogous relationships between Members and Family objects are clusters of Members.

Member objects

A Member represent either a gene or a protein. Most of them
are defined in the corresponding EnsEMBL core database. For
instance, the sequence for the human gene ENSG00000004059
is stored in the human core database.

The fetch_by_source_stable_id method of the MemberAdaptor takes two arguments. The first one is the
source of the Member and can be:

ENSEMBLPEP, derived from an EnsEMBL translation

ENSEMBLGENE, derived from an EnsEMBL gene

Uniprot/SWISSPROT, derived from a Uniprot/Swissprot entry

Uniprot/SPTREMBL, derived from a Uniprot/SP-TrEMBL entry

The second argument is the identifier for the Member. Here is a simple example:

# get the MemberAdaptor
my $member_adaptor = Bio::EnsEMBL::Registry->get_adaptor(
    'Multi','compara','Member');

# fetch a Member
my $member = $member_adaptor->fetch_by_source_stable_id(
    'ENSEMBLGENE','ENSG00000004059');

# print out some information about the Member
print $member->chr_name, " ( ", $member->chr_start, " - ", $member->chr_end,
    " ): ", $member->description, "\n";

The Member object has several attributes:

source_name and stable_id define this Member.

chr_name, chr_start, chr_end, chr_strand locate this Member on the genome but
are only available for ENSEMBLGENE and ENSEMBLPEP.

taxon_id corresponds to the NCBI taxonomy identifier (see
http://www.ncbi.nlm.nih.gov/Taxonomy/taxonomyhome.html/
for more details).

taxon returns a Bio::EnsEMBL::Compara::NCBITaxon object.
From this object you can get additional information about the species.

my $taxon = $member->taxon;
print "common_name ", $taxon->common_name,"\n";
print "genus ", $taxon->genus,"\n";
print "species ", $taxon->species,"\n";
print "binomial ", $taxon->binomial,"\n";
print "classification ", $taxon->classification,"\n";

In our example the species is human, so the output will look like this:

common_name:    human
genus:          Homo
species:        sapiens
binomial:       Homo sapiens
classification:	sapiens Homo Hominidae Catarrhini Haplorrhini Primates Euarchontoglires Eutheria Mammalia Euteleostomi Vertebrata Craniata Chordata Metazoa Eukaryota

Homology Objects

A Homology object represents either an orthologous or paralogous relationships between two
or more Members.

Typically you want to get homologies for a given gene. The HomologyAdaptor has a
fetching method called fetch_all_by_Member(). You will need the Member object for your
query gene, therefore you will fetch the Member first like in this example:

# first you have to get a Member object. In case of homology is a gene, in
# case of family it can be a gene or a protein

my $member_adaptor = Bio::EnsEMBL::Registry->get_adaptor('Multi', 'compara', 'Member');
my $member = $member_adaptor->fetch_by_source_stable_id('ENSEMBLGENE','ENSG00000004059');

# then you get the homologies where the member is involved

my $homology_adaptor = Bio::EnsEMBL::Registry->get_adaptor('Multi', 'compara', 'Homology');
my $homologies = $homology_adaptor->fetch_all_by_Member($member);

# That will return a reference to an array with all homologies (orthologues in
# other species and paralogues in the same one)
# Then for each homology, you can get all the Members implicated

foreach my $homology (@{$homologies}) {
  # You will find different kind of description
  # UBRH, MBRH, RHS, YoungParalogues
  # see ensembl-compara/docs/docs/schema_doc.html for more details

  print $homology->description," ", $homology->subtype,"\n";

  # And if they are defined dN and dS related values

  print " dn ", $homology->dn,"\n";
  print " ds ", $homology->ds,"\n";
  print " dnds_ratio ", $homology->dnds_ratio,"\n";
}

Each homology relation has 2 or more members, you should find there the initial member used as a query.
The get_all_MemberAttribute method returns an array of pairs of Member and Attributes. The Member
corresponds to the gene or protein and the Attribute object contains information about how this
Member has been aligned.

my $homology = $homologies->[0]; # take one of the homologies and look into it

foreach my $member_attribute (@{$homology->get_all_Member_Attribute}) {

  # for each Member, you get information on the Member specifically and in
  # relation to the homology relation via Attribute object

  my ($member, $attribute) = @{$member_attribute};
  print (join " ", map { $member->$_ }  qw(stable_id taxon_id))."\n";
  print (join " ", map { $attribute->$_ } qw(perc_id perc_pos perc_cov))."\n";

}

You can get the original alignment used to define an homology:

use Bio::AlignIO;

my $simple_align = $homology->get_SimpleAlign();
my $alignIO = Bio::AlignIO->newFh(
    -interleaved => 0,
    -fh => \*STDOUT,
    -format => "clustalw",
    -idlength => 20);

print $alignIO $simple_align;

Family Objects

Families are clusters of proteins including all the EnsEMBL proteins plus all the
metazoan SwissProt and SP-Trembl entries. The object and the adaptor are really
similar to the previous ones.

my $member_adaptor = Bio::EnsEMBL::Registry->get_adaptor('Multi', 'compara', 'Member');
my $member = $member_adaptor->fetch_by_source_stable_id('ENSEMBLGENE','ENSG00000004059');

my $family_adaptor = Bio::EnsEMBL::Registry->get_adaptor('Multi','compara','Family');
my $families = $family_adaptor->fetch_all_by_Member($member);

foreach my $family (@{$families}) {
    print join(" ", map { $family->$_ }  qw(description description_score))."\n";

    foreach my $member_attribute (@{$family->get_all_Member_Attribute}) {
        my ($member, $attribute) = @{$member_attribute};
        print $member->stable_id," ",$member->taxon_id,"\n";
    }

    my $simple_align = $family->get_SimpleAlign();
    my $alignIO = Bio::AlignIO->newFh(
        -interleaved => 0,
        -fh          => \*STDOUT,
        -format      => "phylip",
        -idlength    => 20);

    print $alignIO $simple_align;

    $simple_align = $family->get_SimpleAlign('cdna');
    $alignIO = Bio::AlignIO->newFh(
        -interleaved => 0,
        -fh          => \*STDOUT,
        -format      => "phylip",
        -idlength    => 20);

    print $alignIO $simple_align;
}

Further help

For additional information or help mail the ensembl-dev mailing list.
You will need to subscribe to this mailing list to use it.


text:
require "rails_config/rack/reloader"

module RailsConfig
  # provide helper to register within your Sinatra app
  #
  # set :root, File.dirname(__FILE__)
  # register RailsConfig
  #
  def self.registered(app)
    app.configure do |inner_app|

      env = inner_app.environment || ENV["RACK_ENV"]
      root = inner_app.root

      # use Padrino settings if applicable
      if defined?(Padrino)
        env = Padrino.env
        root = Padrino.root
      end

      RailsConfig.load_and_set_settings(
        File.join(root.to_s, "config", "settings.yml").to_s,
        File.join(root.to_s, "config", "settings", "#{env}.yml").to_s,
        File.join(root.to_s, "config", "environments", "#{env}.yml").to_s,

        File.join(root.to_s, "config", "settings.local.yml").to_s,
        File.join(root.to_s, "config", "settings", "#{env}.local.yml").to_s,
        File.join(root.to_s, "config", "environments", "#{env}.local.yml").to_s
      )

      inner_app.use(::RailsConfig::Rack::Reloader) if inner_app.development?
    end
  end

end


text:
<?php

namespace src\Model\TradeBalance;

use HanischIt\KrakenApi\Call\TradeBalance\TradeBalanceResponse;
use PHPUnit\Framework\TestCase;

class TradeBalanceResponseTest extends TestCase
{
    public function testResponse()
    {
        $data = [];
        $data["eb"] = rand(1000, 99999) / 1000;
        $data["tb"] = rand(1000, 99999) / 1000;
        $data["m"] = rand(1000, 99999) / 1000;
        $data["n"] = rand(1000, 99999) / 1000;
        $data["c"] = rand(1000, 99999) / 1000;
        $data["v"] = rand(1000, 99999) / 1000;
        $data["e"] = rand(1000, 99999) / 1000;
        $data["mf"] = rand(1000, 99999) / 1000;

        $tradeBalanceRequest = new TradeBalanceResponse();
        $tradeBalanceRequest->manualMapping($data);

        self::assertEquals($data["eb"], $tradeBalanceRequest->getEquivavlentBalance());
        self::assertEquals($data["tb"], $tradeBalanceRequest->getTradeBalance());
        self::assertEquals($data["m"], $tradeBalanceRequest->getMarginAmount());
        self::assertEquals($data["n"], $tradeBalanceRequest->getUnrealizedNetProfitLoss());
        self::assertEquals($data["c"], $tradeBalanceRequest->getCostBasis());
        self::assertEquals($data["v"], $tradeBalanceRequest->getCurrentFloatingValuation());
        self::assertEquals($data["e"], $tradeBalanceRequest->getEquity());
        self::assertEquals($data["mf"], $tradeBalanceRequest->getFreeMargin());
    }
}


text:
    <?php if ($component->getWidget()->isShowCount()) : ?>
    <th rowspan="<?= $component->getWidget()->getColumnCount() ? ceil(count($component->getWidget()->getParts()) / $component->getWidget()->getColumnCount()) : 1 ?>">
            #	<?php endif; ?>
    <?php
    $count = 0;

    foreach ($component->getWidget()->getParts() as $name => $column) : ?>
    <?php
    $colspan = $column->getOption('colspan') ? $column->getOption('colspan') : 1;
    $count += $colspan;
    ?>
    <?php if ($count <= $component->getWidget()->getColumnCount()) : ?>
        <th<?php if ($column->getOption('rowspan')) : ?> rowspan="<?= $column->getOption('rowspan') ?>"<?php endif;
        ?><?php if ($column->getOption('colspan')) : ?> colspan="<?= $column->getOption('colspan') ?>"<?php endif;
        ?>><?php else : $count = $colspan ?>

    <th<?php if ($column->getOption('rowspan')) : ?> rowspan="<?= $column->getOption('rowspan') ?>"<?php endif;
    ?><?php if ($column->getOption('colspan')) : ?> colspan="<?= $column->getOption('colspan') ?>"<?php endif;
    ?>><?php endif; ?><?= $column->getLabel() ?><?php if ($column->getOption('sortable')) : ?>
        <a href="<?= $column['href'] ?>" onclick='<?= $column['onclick'] ?>'
           data-widget='<?= $dataWidget ?>'
           data-for="<?= $parentWidgetId ?>"
           data-name='<?= $column->getName() ?>'
           data-params='<?= $column['dataParams'] ?>'
           class="btn btn-default btn-sm<?php if ($column['dataValue']) : ?> active<?php endif; ?>">
            <?php if ($column['dataValue'] == 'ASC') : ?>
                ↓
            <?php elseif ($column['dataValue'] == 'DESC') : ?>
                ↑
            <?php else : ?>
                ↓↑
            <?php endif; ?>
            <?php endif; ?>
    <?php endforeach; ?>


text:
def is_fib_num?(num)
  fib_array = [1, 1]
  a = 0
  b = 1
  while fib_array.max <= num
    if a > b then b = b += a
      fib_array.push(b)
    else a = a += b
      fib_array.push(a)
    end
  end
    puts fib_array.include?(num)
end

# REFLECTION:

# What concepts did you review or learn in this challenge?
# What is still confusing to you about Ruby?
# What are you going to study to get more prepared for Phase 1?


text:
@extends('_2_logout_bar')

@section('content')

			Add Juice Recipe!

  @yield('main_content')
@stop


text: throw new Error('lol');