text:
package org.gradle.api.tasks.testing;

import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.Incubating;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileTree;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.internal.ConventionTask;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.initialization.loadercache.ClassLoaderCache;
import org.gradle.api.internal.tasks.options.Option;
import org.gradle.api.internal.tasks.testing.DefaultTestTaskReports;
import org.gradle.api.internal.tasks.testing.NoMatchingTestsReporter;
import org.gradle.api.internal.tasks.testing.TestFramework;
import org.gradle.api.internal.tasks.testing.TestResultProcessor;
import org.gradle.api.internal.tasks.testing.detection.DefaultTestExecuter;
import org.gradle.api.internal.tasks.testing.detection.TestExecuter;
import org.gradle.api.internal.tasks.testing.filter.DefaultTestFilter;
import org.gradle.api.internal.tasks.testing.junit.JUnitTestFramework;
import org.gradle.api.internal.tasks.testing.junit.report.DefaultTestReport;
import org.gradle.api.internal.tasks.testing.junit.report.TestReporter;
import org.gradle.api.internal.tasks.testing.junit.result.*;
import org.gradle.api.internal.tasks.testing.logging.*;
import org.gradle.api.internal.tasks.testing.results.StateTrackingTestResultProcessor;
import org.gradle.api.internal.tasks.testing.results.TestListenerAdapter;
import org.gradle.api.internal.tasks.testing.results.TestListenerInternal;
import org.gradle.api.internal.tasks.testing.testng.TestNGTestFramework;
import org.gradle.api.logging.LogLevel;
import org.gradle.api.reporting.DirectoryReport;
import org.gradle.api.reporting.Reporting;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.*;
import org.gradle.api.tasks.testing.logging.TestLogging;
import org.gradle.api.tasks.testing.logging.TestLoggingContainer;
import org.gradle.api.tasks.util.PatternFilterable;
import org.gradle.api.tasks.util.PatternSet;
import org.gradle.internal.Factory;
import org.gradle.internal.concurrent.CompositeStoppable;
import org.gradle.internal.event.ListenerBroadcast;
import org.gradle.internal.event.ListenerManager;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.listener.ClosureBackedMethodInvocationDispatch;
import org.gradle.logging.ConsoleRenderer;
import org.gradle.logging.ProgressLoggerFactory;
import org.gradle.logging.StyledTextOutputFactory;
import org.gradle.messaging.actor.ActorFactory;
import org.gradle.process.JavaForkOptions;
import org.gradle.process.ProcessForkOptions;
import org.gradle.process.internal.DefaultJavaForkOptions;
import org.gradle.process.internal.WorkerProcessBuilder;
import org.gradle.util.ConfigureUtil;

import javax.inject.Inject;
import java.io.File;
import java.util.*;

/**
 * Executes JUnit (3.8.x or 4.x) or TestNG tests. Test are always run in (one or more) separate JVMs.
 * The sample below shows various configuration options.
 *
 *

 * apply plugin: 'java' // adds 'test' task
 *
 * test {
 *   // enable TestNG support (default is JUnit)
 *   useTestNG()
 *
 *   // set a system property for the test JVM(s)
 *   systemProperty 'some.prop', 'value'
 *
 *   // explicitly include or exclude tests
 *   include 'org/foo/**'
 *   exclude 'org/boo/**'
 *
 *   // show standard out and standard error of the test JVM(s) on the console
 *   testLogging.showStandardStreams = true
 *
 *   // set heap size for the test JVM(s)
 *   minHeapSize = "128m"
 *   maxHeapSize = "512m"
 *
 *   // set JVM arguments for the test JVM(s)
 *   jvmArgs '-XX:MaxPermSize=256m'
 *
 *   // listen to events in the test execution lifecycle
 *   beforeTest { descriptor ->
 *      logger.lifecycle("Running test: " + descriptor)
 *   }
 *
 *   // listen to standard out and standard error of the test JVM(s)
 *   onOutput { descriptor, event ->
 *      logger.lifecycle("Test: " + descriptor + " produced standard out/err: " + event.message )
 *   }
 * }
 *

 *

 * The test process can be started in debug mode (see {@link #getDebug()}) in an ad-hoc manner by supplying the `--debug-jvm` switch when invoking the build.
 *

 * gradle someTestTask --debug-jvm
 *

 */
@ParallelizableTask
public class Test extends ConventionTask implements JavaForkOptions, PatternFilterable, VerificationTask, Reporting<TestTaskReports> {

    private final ListenerBroadcast<TestListener> testListenerBroadcaster;
    private final ListenerBroadcast<TestOutputListener> testOutputListenerBroadcaster;
    private final ListenerBroadcast<TestListenerInternal> testListenerInternalBroadcaster;
    private final TestLoggingContainer testLogging;
    private final DefaultJavaForkOptions forkOptions;
    private final DefaultTestFilter filter;

    private TestExecuter testExecuter;
    private List<File> testSrcDirs = new ArrayList<File>();
    private File testClassesDir;
    private File binResultsDir;
    private PatternFilterable patternSet = new PatternSet();
    private boolean ignoreFailures;
    private FileCollection classpath;
    private TestFramework testFramework;
    private boolean scanForTestClasses = true;
    private long forkEvery;
    private int maxParallelForks = 1;
    private TestReporter testReporter;

    @Nested
    private final DefaultTestTaskReports reports;

    public Test() {
        ListenerManager listenerManager = getListenerManager();
        testListenerInternalBroadcaster = listenerManager.createAnonymousBroadcaster(TestListenerInternal.class);
        testListenerBroadcaster = listenerManager.createAnonymousBroadcaster(TestListener.class);
        testOutputListenerBroadcaster = listenerManager.createAnonymousBroadcaster(TestOutputListener.class);
        forkOptions = new DefaultJavaForkOptions(getFileResolver());
        forkOptions.setEnableAssertions(true);
        Instantiator instantiator = getInstantiator();
        testLogging = instantiator.newInstance(DefaultTestLoggingContainer.class, instantiator);

        reports = instantiator.newInstance(DefaultTestTaskReports.class, this);
        reports.getJunitXml().setEnabled(true);
        reports.getHtml().setEnabled(true);

        filter = instantiator.newInstance(DefaultTestFilter.class);
    }

    @Inject
    protected ProgressLoggerFactory getProgressLoggerFactory() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected Instantiator getInstantiator() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected ActorFactory getActorFactory() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected ClassLoaderCache getClassLoaderCache() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected Factory<WorkerProcessBuilder> getProcessBuilderFactory() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected FileResolver getFileResolver() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected StyledTextOutputFactory getTextOutputFactory() {
        throw new UnsupportedOperationException();
    }

    @Inject
    protected ListenerManager getListenerManager() {
        throw new UnsupportedOperationException();
    }

    /**
     * ATM. for testing only
     */
    void setTestReporter(TestReporter testReporter) {
        this.testReporter = testReporter;
    }

    void setTestExecuter(TestExecuter testExecuter) {
        this.testExecuter = testExecuter;
    }

    ListenerBroadcast<TestListener> getTestListenerBroadcaster() {
        return testListenerBroadcaster;
    }

    ListenerBroadcast<TestListenerInternal> getTestListenerInternalBroadcaster() {
        return testListenerInternalBroadcaster;
    }

    ListenerBroadcast<TestOutputListener> getTestOutputListenerBroadcaster() {
        return testOutputListenerBroadcaster;
    }

    /**
     * {@inheritDoc}
     */
    @Input
    public File getWorkingDir() {
        return forkOptions.getWorkingDir();
    }

    /**
     * {@inheritDoc}
     */
    public void setWorkingDir(Object dir) {
        forkOptions.setWorkingDir(dir);
    }

    /**
     * {@inheritDoc}
     */
    public Test workingDir(Object dir) {
        forkOptions.workingDir(dir);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Input
    public String getExecutable() {
        return forkOptions.getExecutable();
    }

    /**
     * {@inheritDoc}
     */
    public Test executable(Object executable) {
        forkOptions.executable(executable);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public void setExecutable(Object executable) {
        forkOptions.setExecutable(executable);
    }

    /**
     * {@inheritDoc}
     */
    @Input
    public Map<String, Object> getSystemProperties() {
        return forkOptions.getSystemProperties();
    }

    /**
     * {@inheritDoc}
     */
    public void setSystemProperties(Map<String, ?> properties) {
        forkOptions.setSystemProperties(properties);
    }

    /**
     * {@inheritDoc}
     */
    public Test systemProperties(Map<String, ?> properties) {
        forkOptions.systemProperties(properties);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public Test systemProperty(String name, Object value) {
        forkOptions.systemProperty(name, value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Input
    public FileCollection getBootstrapClasspath() {
        return forkOptions.getBootstrapClasspath();
    }

    /**
     * {@inheritDoc}
     */
    public void setBootstrapClasspath(FileCollection classpath) {
        forkOptions.setBootstrapClasspath(classpath);
    }

    /**
     * {@inheritDoc}
     */
    public Test bootstrapClasspath(Object... classpath) {
        forkOptions.bootstrapClasspath(classpath);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public String getMinHeapSize() {
        return forkOptions.getMinHeapSize();
    }

    /**
     * {@inheritDoc}
     */
    public String getDefaultCharacterEncoding() {
        return forkOptions.getDefaultCharacterEncoding();
    }

    /**
     * {@inheritDoc}
     */
    public void setDefaultCharacterEncoding(String defaultCharacterEncoding) {
        forkOptions.setDefaultCharacterEncoding(defaultCharacterEncoding);
    }

    /**
     * {@inheritDoc}
     */
    public void setMinHeapSize(String heapSize) {
        forkOptions.setMinHeapSize(heapSize);
    }

    /**
     * {@inheritDoc}
     */
    public String getMaxHeapSize() {
        return forkOptions.getMaxHeapSize();
    }

    /**
     * {@inheritDoc}
     */
    public void setMaxHeapSize(String heapSize) {
        forkOptions.setMaxHeapSize(heapSize);
    }

    /**
     * {@inheritDoc}
     */
    @Input
    public List<String> getJvmArgs() {
        return forkOptions.getJvmArgs();
    }

    /**
     * {@inheritDoc}
     */
    public void setJvmArgs(Iterable<?> arguments) {
        forkOptions.setJvmArgs(arguments);
    }

    /**
     * {@inheritDoc}
     */
    public Test jvmArgs(Iterable<?> arguments) {
        forkOptions.jvmArgs(arguments);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public Test jvmArgs(Object... arguments) {
        forkOptions.jvmArgs(arguments);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Input
    public boolean getEnableAssertions() {
        return forkOptions.getEnableAssertions();
    }

    /**
     * {@inheritDoc}
     */
    public void setEnableAssertions(boolean enabled) {
        forkOptions.setEnableAssertions(enabled);
    }

    /**
     * {@inheritDoc}
     */
    public boolean getDebug() {
        return forkOptions.getDebug();
    }

    /**
     * {@inheritDoc}
     */
    @Option(option = "debug-jvm", description = "Enable debugging for the test process. The process is started suspended and listening on port 5005. [INCUBATING]")
    public void setDebug(boolean enabled) {
        forkOptions.setDebug(enabled);
    }

    /**
     * {@inheritDoc}
     */
    public List<String> getAllJvmArgs() {
        return forkOptions.getAllJvmArgs();
    }

    /**
     * {@inheritDoc}
     */
    public void setAllJvmArgs(Iterable<?> arguments) {
        forkOptions.setAllJvmArgs(arguments);
    }

    /**
     * {@inheritDoc}
     */
    public Map<String, Object> getEnvironment() {
        return forkOptions.getEnvironment();
    }

    /**
     * {@inheritDoc}
     */
    public Test environment(Map<String, ?> environmentVariables) {
        forkOptions.environment(environmentVariables);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public Test environment(String name, Object value) {
        forkOptions.environment(name, value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public void setEnvironment(Map<String, ?> environmentVariables) {
        forkOptions.setEnvironment(environmentVariables);
    }

    /**
     * {@inheritDoc}
     */
    public Test copyTo(ProcessForkOptions target) {
        forkOptions.copyTo(target);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public Test copyTo(JavaForkOptions target) {
        forkOptions.copyTo(target);
        return this;
    }

    @TaskAction
    public void executeTests() {
        LogLevel currentLevel = getCurrentLogLevel();
        TestLogging levelLogging = testLogging.get(currentLevel);
        TestExceptionFormatter exceptionFormatter = getExceptionFormatter(levelLogging);
        TestEventLogger eventLogger = new TestEventLogger(getTextOutputFactory(), currentLevel, levelLogging, exceptionFormatter);
        addTestListener(eventLogger);
        addTestOutputListener(eventLogger);
        if (!getFilter().getIncludePatterns().isEmpty()) {
            addTestListener(new NoMatchingTestsReporter("No tests found for given includes: " + getFilter().getIncludePatterns()));
        }

        File binaryResultsDir = getBinResultsDir();
        getProject().delete(binaryResultsDir);
        getProject().mkdir(binaryResultsDir);

        Map<String, TestClassResult> results = new HashMap<String, TestClassResult>();
        TestOutputStore testOutputStore = new TestOutputStore(binaryResultsDir);

        TestOutputStore.Writer outputWriter = testOutputStore.writer();
        TestReportDataCollector testReportDataCollector = new TestReportDataCollector(results, outputWriter);

        addTestListener(testReportDataCollector);
        addTestOutputListener(testReportDataCollector);

        TestCountLogger testCountLogger = new TestCountLogger(getProgressLoggerFactory());
        addTestListener(testCountLogger);

        testListenerInternalBroadcaster.add(new TestListenerAdapter(testListenerBroadcaster.getSource(), testOutputListenerBroadcaster.getSource()));

        TestResultProcessor resultProcessor = new StateTrackingTestResultProcessor(testListenerInternalBroadcaster.getSource());

        if (testExecuter == null) {
            testExecuter = new DefaultTestExecuter(getProcessBuilderFactory(), getActorFactory());
        }

        try {
            testExecuter.execute(this, resultProcessor);
        } finally {
            testExecuter = null;
            testListenerBroadcaster.removeAll();
            testOutputListenerBroadcaster.removeAll();
            testListenerInternalBroadcaster.removeAll();
            outputWriter.close();
        }

        new TestResultSerializer(binaryResultsDir).write(results.values());

        TestResultsProvider testResultsProvider = new InMemoryTestResultsProvider(results.values(), testOutputStore.reader());

        try {
            if (testReporter == null) {
                testReporter = new DefaultTestReport();
            }

            JUnitXmlReport junitXml = reports.getJunitXml();
            if (junitXml.isEnabled()) {
                TestOutputAssociation outputAssociation = junitXml.isOutputPerTestCase()
                        ? TestOutputAssociation.WITH_TESTCASE
                        : TestOutputAssociation.WITH_SUITE;
                Binary2JUnitXmlReportGenerator binary2JUnitXmlReportGenerator = new Binary2JUnitXmlReportGenerator(junitXml.getDestination(), testResultsProvider, outputAssociation);
                binary2JUnitXmlReportGenerator.generate();
            }

            DirectoryReport html = reports.getHtml();
            if (!html.isEnabled()) {
                getLogger().info("Test report disabled, omitting generation of the HTML test report.");
            } else {
                testReporter.generateReport(testResultsProvider, html.getDestination());
            }
        } finally {
            CompositeStoppable.stoppable(testResultsProvider).stop();
            testReporter = null;
            testFramework = null;
        }

        if (testCountLogger.hadFailures()) {
            handleTestFailures();
        }
    }

    /**
     * Registers a test listener with this task. Consider also the following handy methods for quicker hooking into test execution: {@link #beforeTest(groovy.lang.Closure)}, {@link
     * #afterTest(groovy.lang.Closure)}, {@link #beforeSuite(groovy.lang.Closure)}, {@link #afterSuite(groovy.lang.Closure)}
 This listener will NOT be notified of tests executed by other tasks. To
     * get that behavior, use {@link org.gradle.api.invocation.Gradle#addListener(Object)}.
     *
     * @param listener The listener to add.
     */
    public void addTestListener(TestListener listener) {
        testListenerBroadcaster.add(listener);
    }

    /**
     * Registers a output listener with this task. Quicker way of hooking into output events is using the {@link #onOutput(groovy.lang.Closure)} method.
     *
     * @param listener The listener to add.
     */
    public void addTestOutputListener(TestOutputListener listener) {
        testOutputListenerBroadcaster.add(listener);
    }

    /**
     * Unregisters a test listener with this task.  This method will only remove listeners that were added by calling {@link #addTestListener(org.gradle.api.tasks.testing.TestListener)} on this task.
     * If the listener was registered with Gradle using {@link org.gradle.api.invocation.Gradle#addListener(Object)} this method will not do anything. Instead, use {@link
     * org.gradle.api.invocation.Gradle#removeListener(Object)}.
     *
     * @param listener The listener to remove.
     */
    public void removeTestListener(TestListener listener) {
        testListenerBroadcaster.remove(listener);
    }

    /**
     * Unregisters a test output listener with this task.  This method will only remove listeners that were added by calling {@link #addTestOutputListener(org.gradle.api.tasks.testing.TestOutputListener)}
     * on this task.  If the listener was registered with Gradle using {@link org.gradle.api.invocation.Gradle#addListener(Object)} this method will not do anything. Instead, use {@link
     * org.gradle.api.invocation.Gradle#removeListener(Object)}.
     *
     * @param listener The listener to remove.
     */
    public void removeTestOutputListener(TestOutputListener listener) {
        testOutputListenerBroadcaster.remove(listener);
    }

    /**
     *
Adds a closure to be notified before a test suite is executed. A {@link org.gradle.api.tasks.testing.TestDescriptor} instance is passed to the closure as a parameter.

     *
     *
This method is also called before any test suites are executed. The provided descriptor will have a null parent suite.

     *
     * @param closure The closure to call.
     */
    public void beforeSuite(Closure closure) {
        testListenerBroadcaster.add(new ClosureBackedMethodInvocationDispatch("beforeSuite", closure));
    }

    /**
     *
Adds a closure to be notified after a test suite has executed. A {@link org.gradle.api.tasks.testing.TestDescriptor} and {@link TestResult} instance are passed to the closure as a
     * parameter.

     *
     *
This method is also called after all test suites are executed. The provided descriptor will have a null parent suite.

     *
     * @param closure The closure to call.
     */
    public void afterSuite(Closure closure) {
        testListenerBroadcaster.add(new ClosureBackedMethodInvocationDispatch("afterSuite", closure));
    }

    /**
     * Adds a closure to be notified before a test is executed. A {@link org.gradle.api.tasks.testing.TestDescriptor} instance is passed to the closure as a parameter.
     *
     * @param closure The closure to call.
     */
    public void beforeTest(Closure closure) {
        testListenerBroadcaster.add(new ClosureBackedMethodInvocationDispatch("beforeTest", closure));
    }

    /**
     * Adds a closure to be notified after a test has executed. A {@link org.gradle.api.tasks.testing.TestDescriptor} and {@link TestResult} instance are passed to the closure as a parameter.
     *
     * @param closure The closure to call.
     */
    public void afterTest(Closure closure) {
        testListenerBroadcaster.add(new ClosureBackedMethodInvocationDispatch("afterTest", closure));
    }

    /**
     * Adds a closure to be notified when output from the test received. A {@link org.gradle.api.tasks.testing.TestDescriptor} and {@link org.gradle.api.tasks.testing.TestOutputEvent} instance are
     * passed to the closure as a parameter.
 apply plugin: 'java'
     *
     * test { onOutput { descriptor, event -> if (event.destination == TestOutputEvent.Destination.StdErr) { logger.error("Test: " + descriptor + ", error: " + event.message) } } }

     *
     * @param closure The closure to call.
     */
    public void onOutput(Closure closure) {
        testOutputListenerBroadcaster.add(new ClosureBackedMethodInvocationDispatch("onOutput", closure));
    }

    /**
     * Adds include patterns for the files in the test classes directory (e.g. '**&#2F;*Test.class')).
     *
     * @see #setIncludes(Iterable)
     */
    public Test include(String... includes) {
        patternSet.include(includes);
        return this;
    }

    /**
     * Adds include patterns for the files in the test classes directory (e.g. '**&#2F;*Test.class')).
     *
     * @see #setIncludes(Iterable)
     */
    public Test include(Iterable<String> includes) {
        patternSet.include(includes);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public Test include(Spec<FileTreeElement> includeSpec) {
        patternSet.include(includeSpec);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public Test include(Closure includeSpec) {
        patternSet.include(includeSpec);
        return this;
    }

    /**
     * Adds exclude patterns for the files in the test classes directory (e.g. '**&#2F;*Test.class')).
     *
     * @see #setExcludes(Iterable)
     */
    public Test exclude(String... excludes) {
        patternSet.exclude(excludes);
        return this;
    }

    /**
     * Adds exclude patterns for the files in the test classes directory (e.g. '**&#2F;*Test.class')).
     *
     * @see #setExcludes(Iterable)
     */
    public Test exclude(Iterable<String> excludes) {
        patternSet.exclude(excludes);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public Test exclude(Spec<FileTreeElement> excludeSpec) {
        patternSet.exclude(excludeSpec);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    public Test exclude(Closure excludeSpec) {
        patternSet.exclude(excludeSpec);
        return this;
    }

    /**
     * Sets the test name patterns to be included in execution.
     * Classes or method names are supported, wildcard '*' is supported.
     * For more information see the user guide chapter on testing.
     *
     * For more information on supported patterns see {@link TestFilter}
     */
    @Option(option = "tests", description = "Sets test class or method name to be included, '*' is supported.")
    @Incubating
    public Test setTestNameIncludePattern(String testNamePattern) {
        filter.setIncludePatterns(testNamePattern);
        return this;
    }

    /**
     * Returns the root folder for the compiled test sources.
     *
     * @return All test class directories to be used.
     */
    public File getTestClassesDir() {
        return testClassesDir;
    }

    /**
     * Sets the root folder for the compiled test sources.
     *
     * @param testClassesDir The root folder
     */
    public void setTestClassesDir(File testClassesDir) {
        this.testClassesDir = testClassesDir;
    }

    /**
     * Returns the root folder for the test results in internal binary format.
     *
     * @return the test result directory, containing the test results in binary format.
     */
    @OutputDirectory
    @Incubating
    public File getBinResultsDir() {
        return binResultsDir;
    }

    /**
     * Sets the root folder for the test results in internal binary format.
     *
     * @param binResultsDir The root folder
     */
    @Incubating
    public void setBinResultsDir(File binResultsDir) {
        this.binResultsDir = binResultsDir;
    }

    /**
     * Returns the include patterns for test execution.
     *
     * @see #include(String...)
     */
    public Set<String> getIncludes() {
        return patternSet.getIncludes();
    }

    /**
     * Sets the include patterns for test execution.
     *
     * @param includes The patterns list
     * @see #include(String...)
     */
    public Test setIncludes(Iterable<String> includes) {
        patternSet.setIncludes(includes);
        return this;
    }

    /**
     * Returns the exclude patterns for test execution.
     *
     * @see #exclude(String...)
     */
    public Set<String> getExcludes() {
        return patternSet.getExcludes();
    }

    /**
     * Sets the exclude patterns for test execution.
     *
     * @param excludes The patterns list
     * @see #exclude(String...)
     */
    public Test setExcludes(Iterable<String> excludes) {
        patternSet.setExcludes(excludes);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Input
    public boolean getIgnoreFailures() {
        return ignoreFailures;
    }

    /**
     * {@inheritDoc}
     */
    public void setIgnoreFailures(boolean ignoreFailures) {
        this.ignoreFailures = ignoreFailures;
    }

    public TestFramework getTestFramework() {
        return testFramework(null);
    }

    public TestFramework testFramework(Closure testFrameworkConfigure) {
        if (testFramework == null) {
            useJUnit(testFrameworkConfigure);
        }

        return testFramework;
    }

    /**
     * Returns test framework specific options. Make sure to call {@link #useJUnit()} or {@link #useTestNG()} before using this method.
     *
     * @return The test framework options.
     */
    @Nested
    public TestFrameworkOptions getOptions() {
        return options(null);
    }

    /**
     * Configures test framework specific options. Make sure to call {@link #useJUnit()} or {@link #useTestNG()} before using this method.
     *
     * @return The test framework options.
     */
    public TestFrameworkOptions options(Closure testFrameworkConfigure) {
        TestFrameworkOptions options = getTestFramework().getOptions();
        ConfigureUtil.configure(testFrameworkConfigure, options);
        return options;
    }

    TestFramework useTestFramework(TestFramework testFramework) {
        return useTestFramework(testFramework, null);
    }

    private TestFramework useTestFramework(TestFramework testFramework, Closure testFrameworkConfigure) {
        if (testFramework == null) {
            throw new IllegalArgumentException("testFramework is null!");
        }

        this.testFramework = testFramework;

        if (testFrameworkConfigure != null) {
            ConfigureUtil.configure(testFrameworkConfigure, this.testFramework.getOptions());
        }

        return this.testFramework;
    }

    /**
     * Specifies that JUnit should be used to execute the tests.
 To configure JUnit specific options, see {@link #useJUnit(groovy.lang.Closure)}.
     */
    public void useJUnit() {
        useJUnit(null);
    }

    /**
     * Specifies that JUnit should be used to execute the tests, configuring JUnit specific options.
 The supplied closure configures an instance of {@link
     * org.gradle.api.tasks.testing.junit.JUnitOptions}, which can be used to configure how JUnit runs.
     *
     * @param testFrameworkConfigure A closure used to configure the JUnit options.
     */
    public void useJUnit(Closure testFrameworkConfigure) {
        useTestFramework(new JUnitTestFramework(this, filter, getClassLoaderCache()), testFrameworkConfigure);
    }

    /**
     * Specifies that TestNG should be used to execute the tests.
 To configure TestNG specific options, see {@link #useTestNG(Closure)}.
     */
    public void useTestNG() {
        useTestNG(null);
    }

    /**
     * Specifies that TestNG should be used to execute the tests, configuring TestNG specific options.
 The supplied closure configures an instance of {@link
     * org.gradle.api.tasks.testing.testng.TestNGOptions}, which can be used to configure how TestNG runs.
     *
     * @param testFrameworkConfigure A closure used to configure the TestNG options.
     */
    public void useTestNG(Closure testFrameworkConfigure) {
        useTestFramework(new TestNGTestFramework(this, this.filter, getInstantiator(), getClassLoaderCache()), testFrameworkConfigure);
    }

    /**
     * Returns the classpath to use to execute the tests.
     */
    @InputFiles
    public FileCollection getClasspath() {
        return classpath;
    }

    public void setClasspath(FileCollection classpath) {
        this.classpath = classpath;
    }

    /**
     * Returns the directories containing the test source.
     */
    @InputFiles
    public List<File> getTestSrcDirs() {
        return testSrcDirs;
    }

    public void setTestSrcDirs(List<File> testSrcDir) {
        this.testSrcDirs = testSrcDir;
    }

    /**
     * Specifies whether test classes should be detected. When {@code true} the classes which match the include and exclude patterns are scanned for test classes, and any found are executed. When
     * {@code false} the classes which match the include and exclude patterns are executed.
     */
    @Input
    public boolean isScanForTestClasses() {
        return scanForTestClasses;
    }

    public void setScanForTestClasses(boolean scanForTestClasses) {
        this.scanForTestClasses = scanForTestClasses;
    }

    /**
     * Returns the maximum number of test classes to execute in a forked test process. The forked test process will be restarted when this limit is reached. The default value is 0 (no maximum).
     *
     * @return The maximum number of test classes. Returns 0 when there is no maximum.
     */
    public long getForkEvery() {
        return forkEvery;
    }

    /**
     * Sets the maximum number of test classes to execute in a forked test process. Use null or 0 to use no maximum.
     *
     * @param forkEvery The maximum number of test classes. Use null or 0 to specify no maximum.
     */
    public void setForkEvery(Long forkEvery) {
        if (forkEvery != null && forkEvery < 0) {
            throw new IllegalArgumentException("Cannot set forkEvery to a value less than 0.");
        }
        this.forkEvery = forkEvery == null ? 0 : forkEvery;
    }

    /**
     * Returns the maximum number of forked test processes to execute in parallel. The default value is 1 (no parallel test execution).
     *
     * @return The maximum number of forked test processes.
     */
    public int getMaxParallelForks() {
        return getDebug() ? 1 : maxParallelForks;
    }

    /**
     * Sets the maximum number of forked test processes to execute in parallel. Set to 1 to disable parallel test execution.
     *
     * @param maxParallelForks The maximum number of forked test processes.
     */
    public void setMaxParallelForks(int maxParallelForks) {
        if (maxParallelForks < 1) {
            throw new IllegalArgumentException("Cannot set maxParallelForks to a value less than 1.");
        }
        this.maxParallelForks = maxParallelForks;
    }

    /**
     * Returns the classes files to scan for test classes.
     *
     * @return The candidate class files.
     */
    @InputFiles
    @Input
    public FileTree getCandidateClassFiles() {
        return getProject().fileTree(getTestClassesDir()).matching(patternSet);
    }

    /**
     * Allows to set options related to which test events are logged to the console, and on which detail level. For example, to show more information about exceptions use:
     *
     *
 apply plugin: 'java'
     *
     * test.testLogging { exceptionFormat "full" }

     *
     * For further information see {@link TestLoggingContainer}.
     *
     * @return this
     */
    public TestLoggingContainer getTestLogging() {
        return testLogging;
    }

    /**
     * Allows configuring the logging of the test execution, for example log eagerly the standard output, etc.
 apply plugin: 'java'
     *
     * //makes the standard streams (err and out) visible at console when running tests test.testLogging { showStandardStreams = true }

     *
     * @param closure configure closure
     */
    public void testLogging(Closure closure) {
        ConfigureUtil.configure(closure, testLogging);
    }

    /**
     * The reports that this task potentially produces.
     *
     * @return The reports that this task potentially produces
     */
    public TestTaskReports getReports() {
        return reports;
    }

    /**
     * Configures the reports that this task potentially produces.
     *
     * @param closure The configuration
     * @return The reports that this task potentially produces
     */
    public TestTaskReports reports(Closure closure) {
        reports.configure(closure);
        return reports;
    }

    /**
     * Allows filtering tests for execution.
     *
     * @return filter object
     * @since 1.10
     */
    @Incubating
    @Nested
    public TestFilter getFilter() {
        return filter;
    }

    /**
     * Executes the action against the {@link #getFilter()}.
     *
     * @param action configuration of the test filter
     * @since 1.10
     */
    @Incubating
    public void filter(Action<TestFilter> action) {
        action.execute(filter);
    }

    // only way I know of to determine current log level
    private LogLevel getCurrentLogLevel() {
        for (LogLevel level : LogLevel.values()) {
            if (getLogger().isEnabled(level)) {
                return level;
            }
        }
        throw new AssertionError("could not determine current log level");
    }

    private TestExceptionFormatter getExceptionFormatter(TestLogging testLogging) {
        switch (testLogging.getExceptionFormat()) {
            case SHORT:
                return new ShortExceptionFormatter(testLogging);
            case FULL:
                return new FullExceptionFormatter(testLogging);
            default:
                throw new AssertionError();
        }
    }

    private void handleTestFailures() {
        String message = "There were failing tests";

        DirectoryReport htmlReport = reports.getHtml();
        if (htmlReport.isEnabled()) {
            String reportUrl = new ConsoleRenderer().asClickableFileUrl(htmlReport.getEntryPoint());
            message = message.concat(". See the report at: " + reportUrl);
        } else {
            DirectoryReport junitXmlReport = reports.getJunitXml();
            if (junitXmlReport.isEnabled()) {
                String resultsUrl = new ConsoleRenderer().asClickableFileUrl(junitXmlReport.getEntryPoint());
                message = message.concat(". See the results at: " + resultsUrl);
            }
        }

        if (getIgnoreFailures()) {
            getLogger().warn(message);
        } else {
            throw new GradleException(message);
        }
    }
}


text:
Chargement...
Loading...

Bienvenue

					Vous devez activer le Javascript pour utiliser le plugin.

					You have to enable Javascript in order to use the plugin.

redpajama_set_name: RedPajamaGithub


text:
package cmd

import (
	"os"
	"os/signal"
	"syscall"

	"github.com/kardianos/osext"
	"github.com/spf13/cobra"

	"github.com/skydive-project/skydive/logging"
)

var (
	analyzerUID uint32
	cfgPath     string
	cfgBackend  string
)

var AllInOne = &cobra.Command{
	Use:          "allinone",
	Short:        "Skydive All-In-One",
	Long:         "Skydive All-In-One (Analyzer + Agent)",
	SilenceUsage: true,
	Run: func(cmd *cobra.Command, args []string) {
		skydivePath, _ := osext.Executable()

		analyzerAttr := &os.ProcAttr{
			Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
			Env:   os.Environ(),
		}

		if analyzerUID != 0 {
			analyzerAttr.Sys = &syscall.SysProcAttr{
				Credential: &syscall.Credential{
					Uid: analyzerUID,
				},
			}
		}

		args = []string{"skydive"}

		if cfgPath != "" {
			args = append(args, "-c")
			args = append(args, cfgPath)
		}

		if cfgBackend != "" {
			args = append(args, "-b")
			args = append(args, cfgBackend)
		}

		analyzerArgs := make([]string, len(args))
		copy(analyzerArgs, args)

		analyzer, err := os.StartProcess(skydivePath, append(analyzerArgs, "analyzer"), analyzerAttr)
		if err != nil {
			logging.GetLogger().Fatalf("Can't start Skydive All-in-One : %v", err)
		}

		os.Setenv("SKYDIVE_AGENT_ANALYZERS", "localhost:8082")
		agentAttr := &os.ProcAttr{
			Files: []*os.File{os.Stdin, os.Stdout, os.Stderr},
			Env:   os.Environ(),
		}

		agentArgs := make([]string, len(args))
		copy(agentArgs, args)

		agent, err := os.StartProcess(skydivePath, append(agentArgs, "agent"), agentAttr)
		if err != nil {
			logging.GetLogger().Fatalf("Can't start Skydive All-in-One : %v", err)
		}

		logging.GetLogger().Notice("Skydive All-in-One starting !")
		ch := make(chan os.Signal)
		signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
		<-ch

		analyzer.Kill()
		agent.Kill()

		analyzer.Wait()
		agent.Wait()

		logging.GetLogger().Notice("Skydive All-in-One stopped.")
	},
}

func init() {
	var uid uint32

	skydivePath, _ := osext.Executable()

	fi, err := os.Stat(skydivePath)
	if err == nil {
		uid = fi.Sys().(*syscall.Stat_t).Uid
	}

	AllInOne.Flags().StringVarP(&cfgPath, "conf", "c", "", "location of Skydive agent config file")
	AllInOne.Flags().StringVarP(&cfgBackend, "config-backend", "b", "file", "configuration backend (defaults to file)")
	AllInOne.Flags().Uint32VarP(&analyzerUID, "analyzer-uid", "", uid, "uid used for analyzer process")
}


text:
package com.google.cloud.dataflow.sdk.io;

import com.google.cloud.dataflow.sdk.annotations.Experimental;
import com.google.cloud.dataflow.sdk.coders.Coder;
import com.google.cloud.dataflow.sdk.options.PipelineOptions;

import org.joda.time.Instant;

import java.io.IOException;
import java.util.List;
import java.util.NoSuchElementException;

import javax.annotation.Nullable;

/**
 * A {@link Source} that reads an unbounded amount of input and, because of that, supports
 * some additional operations such as checkpointing, watermarks, and record ids.
 *
 *

 *
 Checkpointing allows sources to not re-read the same data again in the case of failures.
 *
 Watermarks allow for downstream parts of the pipeline to know up to what point
 *   in time the data is complete.
 *
 Record ids allow for efficient deduplication of input records; many streaming sources
 *   do not guarantee that a given record will only be read a single time.
 *

 *
 *
See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} and
 * {@link com.google.cloud.dataflow.sdk.transforms.windowing.Trigger} for more information on
 * timestamps and watermarks.
 *
 * @param <OutputT> Type of records output by this source.
 * @param <CheckpointMarkT> Type of checkpoint marks used by the readers of this source.
 */
public abstract class UnboundedSource<
        OutputT, CheckpointMarkT extends UnboundedSource.CheckpointMark> extends Source<OutputT> {
  /**
   * Returns a list of {@code UnboundedSource} objects representing the instances of this source
   * that should be used when executing the workflow.  Each split should return a separate partition
   * of the input data.
   *
   *
For example, for a source reading from a growing directory of files, each split
   * could correspond to a prefix of file names.
   *
   *
Some sources are not splittable, such as reading from a single TCP stream.  In that
   * case, only a single split should be returned.
   *
   *
Some data sources automatically partition their data among readers.  For these types of
   * inputs, {@code n} identical replicas of the top-level source can be returned.
   *
   *
The size of the returned list should be as close to {@code desiredNumSplits}
   * as possible, but does not have to match exactly.  A low number of splits
   * will limit the amount of parallelism in the source.
   */
  public abstract List<? extends UnboundedSource<OutputT, CheckpointMarkT>> generateInitialSplits(
      int desiredNumSplits, PipelineOptions options) throws Exception;

  /**
   * Create a new {@link UnboundedReader} to read from this source, resuming from the given
   * checkpoint if present.
   */
  public abstract UnboundedReader<OutputT> createReader(
      PipelineOptions options, @Nullable CheckpointMarkT checkpointMark);

  /**
   * Returns a {@link Coder} for encoding and decoding the checkpoints for this source, or
   * null if the checkpoints do not need to be durably committed.
   */
  @Nullable
  public abstract Coder<CheckpointMarkT> getCheckpointMarkCoder();

  /**
   * Returns whether this source requires explicit deduping.
   *
   *
This is needed if the underlying data source can return the same record multiple times,
   * such a queuing system with a pull-ack model.  Sources where the records read are uniquely
   * identified by the persisted state in the CheckpointMark do not need this.
   */
  public boolean requiresDeduping() {
    return false;
  }

  /**
   * A marker representing the progress and state of an {@link UnboundedReader}.
   *
   *
For example, this could be offsets in a set of files being read.
   */
  public interface CheckpointMark {
    /**
     * Perform any finalization that needs to happen after a bundle of data read from
     * the source has been processed and committed.
     *
     *
For example, this could be sending acknowledgement requests to an external
     * data source such as Pub/Sub.
     *
     *
This may be called from any thread, potentially at the same time as calls to the
     * {@code UnboundedReader} that created it.
     */
    void finalizeCheckpoint() throws IOException;
  }

  /**
   * A {@code Reader} that reads an unbounded amount of input.
   *
   *
A given {@code UnboundedReader} object will only be accessed by a single thread at once.
   */
  @Experimental(Experimental.Kind.SOURCE_SINK)
  public abstract static class UnboundedReader<OutputT> extends Source.Reader<OutputT> {
    private static final byte[] EMPTY = new byte[0];

    /**
     * Initializes the reader and advances the reader to the first record.
     *
     *
This method should be called exactly once. The invocation should occur prior to calling
     * {@link #advance} or {@link #getCurrent}. This method may perform expensive operations that
     * are needed to initialize the reader.
     *
     *
Returns {@code true} if a record was read, {@code false} if there is no more input
     * currently available.  Future calls to {@link #advance} may return {@code true} once more data
     * is available. Regardless of the return value of {@code start}, {@code start} will not be
     * called again on the same {@code UnboundedReader} object; it will only be called again when a
     * new reader object is constructed for the same source, e.g. on recovery.
     */
    @Override
    public abstract boolean start() throws IOException;

    /**
     * Advances the reader to the next valid record.
     *
     *
Returns {@code true} if a record was read, {@code false} if there is no more input
     * available. Future calls to {@link #advance} may return {@code true} once more data is
     * available.
     */
    @Override
    public abstract boolean advance() throws IOException;

    /**
     * Returns a unique identifier for the current record.  This should be the same for each
     * instance of the same logical record read from the underlying data source.
     *
     *
It is only necessary to override this if {@link #requiresDeduping} has been overridden to
     * return true.
     *
     *
For example, this could be a hash of the record contents, or a logical ID present in
     * the record.  If this is generated as a hash of the record contents, it should be at least 16
     * bytes (128 bits) to avoid collisions.
     *
     *
This method has the same restrictions on when it can be called as {@link #getCurrent} and
     * {@link #getCurrentTimestamp}.
     *
     * @throws NoSuchElementException if the reader is at the beginning of the input and
     *         {@link #start} or {@link #advance} wasn't called, or if the last {@link #start} or
     *         {@link #advance} returned {@code false}.
     */
    public byte[] getCurrentRecordId() throws NoSuchElementException {
      if (getCurrentSource().requiresDeduping()) {
        throw new IllegalStateException(
            "getCurrentRecordId() must be overridden if requiresDeduping returns true()");
      }
      return EMPTY;
    }

    /**
     * Returns a lower bound on timestamps of future elements read by this reader.
     *
     *
This can be approximate.  If records are read that violate this guarantee, they will be
     * considered late, which will affect how they will be processed.  See
     * {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} for more information on
     * late data and how to handle it.
     *
     *
This bound should be as tight as possible.  Downstream windows will not be able to close
     * until this watermark passes the end of the window.
     *
     *
For example, a source may know that the records it reads will be in timestamp order.  In
     * this case, the watermark can be the timestamp of the last record read minus one.  For a
     * source that does not have natural timestamps, timestamps can be set to the time of
     * reading, in which case the watermark is the current clock time.
     *
     *
See {@link com.google.cloud.dataflow.sdk.transforms.windowing.Window} and
     * {@link com.google.cloud.dataflow.sdk.transforms.windowing.Trigger} for more
     * information on timestamps and watermarks.
     *
May be called after {@link #advance} or {@link #start} has returned false, but not before
     * {@link #start} has been called.
     */
    public abstract Instant getWatermark();

    /**
     * Returns a {@link CheckpointMark} representing the progress of this {@code UnboundedReader}.
     *
     *
The elements read up until this is called will be processed together as a bundle. Once
     * the result of this processing has been durably committed,
     * {@link CheckpointMark#finalizeCheckpoint} will be called on the {@link CheckpointMark}
     * object.
     *
     *
The returned object should not be modified.
     *
     *
May be called after {@link #advance} or {@link #start} has returned false, but not before
     * {@link #start} has been called.
     */
    public abstract CheckpointMark getCheckpointMark();

    /**
     * Constant representing an unknown amount of backlog.
     */
    public static final long BACKLOG_UNKNOWN = -1L;

    /**
     * Returns the size of the backlog of unread data in the underlying data source represented by
     * this split of this source.
     *
     *
One of this or {@link #getTotalBacklogBytes} should be overridden in order to allow the
     * runner to scale the amount of resources allocated to the pipeline.
     */
    public long getSplitBacklogBytes() {
      return BACKLOG_UNKNOWN;
    }

    /**
     * Returns the size of the backlog of unread data in the underlying data source represented by
     * all splits of this source.
     *
     *
One of this or {@link #getSplitBacklogBytes} should be overridden in order to allow the
     * runner to scale the amount of resources allocated to the pipeline.
     */
    public long getTotalBacklogBytes() {
      return BACKLOG_UNKNOWN;
    }

    /**
     * Returns the {@link UnboundedSource} that created this reader.  This will not change over the
     * life of the reader.
     */
    @Override
    public abstract UnboundedSource<OutputT, ?> getCurrentSource();
  }
}


text:
define(['app', 'model/candidate'], function(App, CandidateCollection){
    App.commands.setHandler('votePageDisplay', function(voter){
       require(['views/vote', 'backbone'], function(VoteView, Backbone){
           var list = new CandidateCollection();
           list.fetch();
           //Display only those candidates which are from the voter's constituency
           App.Main.show(new VoteView({
               collection: list
           }));
       }) ;
    });

});


text:
<?php

declare(strict_types=1);

namespace League\Flysystem\PhpseclibV2;

use phpseclib\Net\SFTP;

/**
 * @internal This is only used for testing purposes.
 *
 * @deprecated The "League\Flysystem\PhpseclibV2\SftpStub" class is deprecated since Flysystem 3.0, use "League\Flysystem\PhpseclibV3\SftpStub" instead.
 */
class SftpStub extends SFTP
{
    /**
     * @var array<string,bool>
     */
    private $tripWires = [];

    public function failOnChmod(string $filename): void
    {
        $key = $this->formatTripKey('chmod', $filename);
        $this->tripWires[$key] = true;
    }

    /**
     * @param int    $mode
     * @param string $filename
     * @param bool   $recursive
     *
     * @return bool|mixed
     */
    public function chmod($mode, $filename, $recursive = false)
    {
        $key = $this->formatTripKey('chmod', $filename);
        $shouldTrip = $this->tripWires[$key] ?? false;

        if ($shouldTrip) {
            unset($this->tripWires[$key]);

            return false;
        }

        return parent::chmod($mode, $filename, $recursive);
    }

    public function failOnPut(string $filename): void
    {
        $key = $this->formatTripKey('put', $filename);
        $this->tripWires[$key] = true;
    }

    /**
     * @param string          $remote_file
     * @param resource|string $data
     * @param int             $mode
     * @param int             $start
     * @param int             $local_start
     * @param null            $progressCallback
     *
     * @return bool
     */
    public function put(
        $remote_file,
        $data,
        $mode = self::SOURCE_STRING,
        $start = -1,
        $local_start = -1,
        $progressCallback = null
    ) {
        $key = $this->formatTripKey('put', $remote_file);
        $shouldTrip = $this->tripWires[$key] ?? false;

        if ($shouldTrip) {
            return false;
        }

        return parent::put($remote_file, $data, $mode, $start, $local_start, $progressCallback);
    }

    /**
     * @param array<int,mixed> $arguments
     *
     * @return string
     */
    private function formatTripKey(...$arguments): string
    {
        $key = '';

        foreach ($arguments as $argument) {
            $key .= var_export($argument, true);
        }

        return $key;
    }

    public function reset(): void
    {
        $this->tripWires = [];
    }
}


text:
package cappa

// UA contains all Browscap properties along with the Pattern structure, that
// used to be matched against. Most of the properties are self-describing, but
// you may consult with Browscap http://browscap.org/.
type UA struct {
	Pattern      *Pattern
	PropertyName string // 0
	MasterParent string // 1
	LiteMode     string // 2
	Parent       string // 3
	Comment      string // 4

	// TODO: Create Browser type
	Browser      string // 5
	BrowserType  string // 6
	BrowserBits  string // 7
	BrowserMaker string // 8
	BrowserModus string // 9

	Version  string // 10
	MajorVer string // 11
	MinorVer string // 12

	// TODO: Create Platform type
	Platform            string // 13
	PlatformVersion     string // 14
	PlatformDescription string // 15
	PlatformBits        string // 16
	PlatformMaker       string // 17

	Alpha               string // 18
	Beta                string // 19
	Win16               string // 20
	Win32               string // 21
	Win64               string // 22
	Frames              string // 23
	IFrames             string // 24
	Tables              string // 25
	Cookies             string // 26
	BackgroundSounds    string // 27
	JavaScript          string // 28
	VBScript            string // 29
	JavaApplets         string // 30
	ActiveXControls     string // 31
	IsMobileDevice      string // 32
	IsTablet            string // 33
	IsSyndicationReader string // 34
	Crawler             string // 35
	IsFake              string // 36
	IsAnonymized        string // 37
	IsModified          string // 38
	CSSVersion          string // 39
	AolVersion          string // 40

	// TODO: Create Device type
	DeviceName           string // 41
	DeviceMaker          string // 42
	DeviceType           string // 43
	DevicePointingMethod string // 44
	DeviceCodeName       string // 45
	DeviceBrandName      string // 46

	// TODO: Create RenderEngine type
	RenderingEngineName        string // 47
	RenderingEngineVersion     string // 48
	RenderingEngineDescription string // 49
	RenderingEngineMaker       string // 50
}

// NewUAFromLine creates a User-Agent from the slice of strings, that
// represents a parsed and separated line of the CSV file.
func NewUAFromLine(line []string) *UA {
	pattern, err := NewPattern(line[0])
	if err != nil {
		panic(err)
	}

	ua := &UA{Pattern: pattern}

	ua.PropertyName = line[0]
	ua.MasterParent = line[1]
	ua.LiteMode = line[2]
	ua.Parent = line[3]
	ua.Comment = line[4]

	ua.Browser = line[5]
	ua.BrowserType = line[6]
	ua.BrowserBits = line[7]
	ua.BrowserMaker = line[8]
	ua.BrowserModus = line[9]

	ua.Version = line[10]
	ua.MajorVer = line[11]
	ua.MinorVer = line[12]

	ua.Platform = line[13]
	ua.PlatformVersion = line[14]
	ua.PlatformDescription = line[15]
	ua.PlatformBits = line[16]
	ua.PlatformMaker = line[17]

	ua.Alpha = line[18]
	ua.Beta = line[19]
	ua.Win16 = line[20]
	ua.Win32 = line[21]
	ua.Win64 = line[22]
	ua.Frames = line[23]
	ua.IFrames = line[24]
	ua.Tables = line[25]
	ua.Cookies = line[26]
	ua.BackgroundSounds = line[27]
	ua.JavaScript = line[28]
	ua.VBScript = line[29]
	ua.JavaApplets = line[30]
	ua.ActiveXControls = line[31]
	ua.IsMobileDevice = line[32]
	ua.IsTablet = line[33]
	ua.IsSyndicationReader = line[34]
	ua.Crawler = line[35]
	ua.IsFake = line[36]
	ua.IsAnonymized = line[37]
	ua.IsModified = line[38]
	ua.CSSVersion = line[39]
	ua.AolVersion = line[40]

	ua.DeviceName = line[41]
	ua.DeviceMaker = line[42]
	ua.DeviceType = line[43]
	ua.DevicePointingMethod = line[44]
	ua.DeviceCodeName = line[45]
	ua.DeviceBrandName = line[46]

	ua.RenderingEngineName = line[47]
	ua.RenderingEngineVersion = line[48]
	ua.RenderingEngineDescription = line[49]
	ua.RenderingEngineMaker = line[50]

	return ua
}


text:
export const GET_HIS_LIST = 'GET_HIS_LIST';
export const GET_HIS_PAPER = 'GET_HIS_PAPER';

export const getHisList = details => ({
  type: GET_HIS_LIST,
  details,
});

export const getHisPaper = details => ({
  type: GET_HIS_PAPER,
  details,
});

export const asyncGetHisList = () => dispatch =>
  fetch('http://lab.songt.me:8080/smartpaper/paper/subjects/1')
    .then(response => response.json())
    .then(json => dispatch(getHisList(json)));

export const asyncGetHisPaper = id => dispatch =>
  fetch(`http://lab.songt.me:8080/smartpaper/paper/${id}`)
    .then(response => response.json())
    .then(json => dispatch(getHisPaper(json)));


text:
from django import forms
from django.template import loader
from django.utils.encoding import force_unicode
from django.utils import formats

class CodeEditorWidget(forms.Widget):
	'''A widget for using the ACE editor (ace.ajax.org) on the admin page'''
	@property
	def media(self):
		scripts = ["admin/ace/ace.js", "admin/ace/ace_editor.js"]
		if self.mode:
			scripts.append("admin/ace/mode-{0}.js".format(self.mode))

		stylesheets = {'all': ('admin/ace/ace_editor.css',)}
		return forms.Media(js=scripts, css=stylesheets)

	template_name = 'ace_editor.html'

	def __init__(self, mode = None, *args, **kwargs):
		self.mode = mode
		super(CodeEditorWidget, self).__init__(*args, **kwargs)

	def _format_value(self, value):
		if self.is_localized:
			value = formats.localize_input(value)
		return force_unicode(value)

	def get_context(self, name, value, attrs=None):
		context = {
			'name': name,
			'mode': self.mode,
			'required': self.is_required,
			'True': True,
			}
		# True is injected in the context to allow stricter comparisons
		# for widget attrs. See:
		# https://github.com/brutasse/django-floppyforms/issues/25
		if self.is_hidden:
			context['hidden'] = True

		if value is None:
			value = ''

		if not '\n' in value:
			# The code editor messes up if there's only a single line.
			value += '\n'

		context['value'] = self._format_value(value)
		context['attrs'] = self.build_attrs(attrs)

		for key in context['attrs']:
			attr = context['attrs'][key]
			if attr == 1:
				# 1 == True so 'key="1"' will show up only as 'key'
				# Casting to a string so that it doesn't equal to True
				# See:
				# https://github.com/brutasse/django-floppyforms/issues/25
				if not isinstance(attr, bool):
					context['attrs'][key] = str(attr)

		return context

	def render(self, name, value, attrs=None, **kwargs):
		context = self.get_context(name, value, attrs=attrs or {}, **kwargs)
		if not isinstance(value, basestring):
			value = ''
		if not '\n' in value:
			value += '\n'
		return loader.render_to_string(self.template_name, context)


text:
'use strict';

const
	express = require('express'),
	router =  express.Router(),
	posts = require('./controllers/posts');

router.get('/', function(req, res){
	res.status(200).send("Welcome to BasicAPI!");
});

router.get('/posts/:_id', posts.get);
router.get('/posts', posts.list);
router.put('/posts/:_id', posts.edit);
router.post('/posts', posts.add);
router.delete('/posts/:_id', posts.del);

module.exports = router;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.mskcc.shenkers.view;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.binding.DoubleExpression;
import javafx.beans.binding.NumberBinding;
import javafx.beans.binding.When;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.concurrent.Task;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.fxmisc.easybind.EasyBind;

/**
 *
 * @author sol
 */
public class LineHistogramView {

    private static final Logger logger = LogManager.getLogger();

    Pane graphic;

    // the range of data plotted
    DoubleProperty minProperty;
    DoubleProperty maxProperty;

    // whether or not the reference frames should be flipped
    BooleanProperty flipDomainProperty;
    BooleanProperty flipRangeProperty;

    Rectangle background;

    // the number of data points
    IntegerProperty n;

    // where the base of the histogram starts from
    NumberBinding zero;

    public LineHistogramView() {

        minProperty = new SimpleDoubleProperty(0);
        maxProperty = new SimpleDoubleProperty(1);

        flipDomainProperty = new SimpleBooleanProperty(false);
        flipRangeProperty = new SimpleBooleanProperty(true);

        graphic = new BorderPane();

        background = new Rectangle();

        background.setFill(Color.WHITE);
        background.setStroke(Color.WHITE);

        background.widthProperty().bind(graphic.widthProperty());
        background.heightProperty().bind(graphic.heightProperty());

        graphic.getChildren().add(background);

        zero = bindToRange(0);
        n = new SimpleIntegerProperty(0);
    }

    public Pane getGraphic() {
        return graphic;
    }

    public void setMin(double d) {
        minProperty.set(d);
    }

    public void setMax(double d) {
        maxProperty.set(d);
    }

    public void clearData() {
        n.setValue(0);
        graphic.getChildren().retainAll(background);
    }

    public void addData(double d) {
        n.set(n.get() + 1);
        graphic.getChildren().add(getLine(n.getValue() - 1, zero, d));
    }

    public void setData(double[] data, Task task) {
        n.set(data.length);

        for (int i = 0; i < data.length; i++) {
            graphic.getChildren().add(getLine(i, zero, data[i]));
            if (task.isCancelled()) {
                logger.info("recieved cancel");
                break;
            }
        }
    }

    /**
     *
     * @param i - the index
     * @param l - the number of data points
     * @param d - the value of the data point
     * @return
     */
    private Line getLine(int i, NumberBinding zero, double d) {

        Line line = new Line(0., 0., 0., 1.);

        NumberBinding domainBinding = new When(flipDomainProperty)
                .then(
                        n.subtract(i + 1.).divide(n.add(1.)))
                .otherwise(
                        new SimpleDoubleProperty(i + 1.).divide(n.add(1.))).multiply(graphic.widthProperty());

        line.startXProperty().bind(domainBinding);
        line.endXProperty().bind(domainBinding);

        line.startYProperty().bind(zero);
        line.endYProperty().bind(bindToRange(d));

        return line;
    }

//    /**
//     *
//     * @param i - the index
//     * @param l - the number of data points
//     * @param d - the value of the data point
//     * @return
//     */
//    private Line getLine(int i, int l, NumberBinding zero, double d) {
//
//        Line line = new Line(0., 0., 0., 1.);
//
//        DoubleBinding domainBinding = new When(flipDomainProperty).then((l - (i + 1.)) / (l + 1)).otherwise((i + 1.) / (l + 1)).multiply(graphic.widthProperty());
//
//        line.startXProperty().bind(domainBinding);
//        line.endXProperty().bind(domainBinding);
//
//        line.startYProperty().bind(zero);
//        line.endYProperty().bind(bindToRange(d));
//
//        return line;
//    }
    private NumberBinding bindToRange(double d) {

        NumberBinding whetherZeroGreaterThanMax = new When(maxProperty.lessThan(d)).then(maxProperty).otherwise(minProperty.multiply(-1).add(d).divide(maxProperty.subtract(minProperty)));
        NumberBinding base = new When(minProperty.greaterThan(d)).then(minProperty).otherwise(whetherZeroGreaterThanMax);
        NumberBinding flipped = new When(flipRangeProperty).then(base.multiply(-1).add(1)).otherwise(base);

        NumberBinding scaled = flipped.multiply(graphic.heightProperty());

        return scaled;
    }

    public ReadOnlyDoubleProperty widthProperty() {
        return graphic.widthProperty();
    }

    public ReadOnlyDoubleProperty heightProperty() {
        return graphic.heightProperty();
    }

    public BooleanProperty flipDomainProperty() {
        return flipDomainProperty;
    }

    public void setFlipDomain(boolean flip) {
        flipDomainProperty.set(flip);
    }

    public void setFlipRange(boolean flip) {
        flipRangeProperty.set(!flip);
    }
}


text:
package com.shc.silenceengine.scene.tiled;

import com.shc.silenceengine.core.SilenceException;
import com.shc.silenceengine.graphics.Color;
import com.shc.silenceengine.io.FilePath;
import com.shc.silenceengine.scene.tiled.layers.TmxImageLayer;
import com.shc.silenceengine.scene.tiled.layers.TmxMapLayer;
import com.shc.silenceengine.scene.tiled.layers.TmxObjectLayer;
import com.shc.silenceengine.scene.tiled.layers.TmxTileLayer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;

/**
 * A TiledMap represents the data format of the TMX file format, used by the Tiled Map Editor.
 *
 * @author Sri Harsha Chilakapati
 */
public class TmxMap
{
    public static final int FLIPPED_HORIZONTALLY_FLAG = 0x80000000;
    public static final int FLIPPED_VERTICALLY_FLAG   = 0x40000000;
    public static final int FLIPPED_DIAGONALLY_FLAG   = 0x20000000;

    private FilePath filePath;
    private Color    backgroundColor;

    private double version;

    private Orientation  orientation;
    private RenderOrder  renderOrder;
    private StaggerAxis  staggerAxis;
    private StaggerIndex staggerIndex;

    private int width;
    private int height;
    private int tileWidth;
    private int tileHeight;
    private int nextObjectID;
    private int hexSideLength;

    private List<TmxMapLayer>    layers;
    private List<TmxTileLayer>   tileLayers;
    private List<TmxImageLayer>  imageLayers;
    private List<TmxObjectLayer> objectLayers;
    private List<TmxTileSet>     tileSets;

    private TmxProperties properties;

    public TmxMap(FilePath filePath)
    {
        version = 1.0;

        layers = new ArrayList<>();
        tileLayers = new ArrayList<>();
        imageLayers = new ArrayList<>();
        objectLayers = new ArrayList<>();
        tileSets = new ArrayList<>();

        properties = new TmxProperties();

        orientation = Orientation.ORTHOGONAL;
        renderOrder = RenderOrder.RIGHT_DOWN;
        staggerAxis = StaggerAxis.NONE;
        staggerIndex = StaggerIndex.NONE;

        backgroundColor = Color.TRANSPARENT;

        this.filePath = filePath;

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        try
        {
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document document = dBuilder.parse(filePath.getInputStream());
            document.getDocumentElement().normalize();

            Node mapNode = document.getDocumentElement();

            if (!mapNode.getNodeName().equals("map"))
                throw new SilenceException("Invalid TMX map file. The first child must be a <map> element.");

            parse(mapNode);
        }
        catch (Exception e)
        {
            if (!(e instanceof SilenceException))
                SilenceException.reThrow(e);
        }
    }

    public Orientation getOrientation()
    {
        return orientation;
    }

    public RenderOrder getRenderOrder()
    {
        return renderOrder;
    }

    public StaggerAxis getStaggerAxis()
    {
        return staggerAxis;
    }

    public StaggerIndex getStaggerIndex()
    {
        return staggerIndex;
    }

    public FilePath getFilePath()
    {
        return filePath;
    }

    public Color getBackgroundColor()
    {
        return backgroundColor;
    }

    public double getVersion()
    {
        return version;
    }

    public int getWidth()
    {
        return width;
    }

    public int getHeight()
    {
        return height;
    }

    public int getTileWidth()
    {
        return tileWidth;
    }

    public int getTileHeight()
    {
        return tileHeight;
    }

    public int getNextObjectID()
    {
        return nextObjectID;
    }

    public int getHexSideLength()
    {
        return hexSideLength;
    }

    public TmxMapLayer getLayer(int index)
    {
        return layers.get(index);
    }

    public int getNumLayers()
    {
        return layers.size();
    }

    public List<TmxMapLayer> getLayers()
    {
        return layers;
    }

    public TmxTileLayer getTileLayer(int index)
    {
        return tileLayers.get(index);
    }

    public int getNumTileLayers()
    {
        return tileLayers.size();
    }

    public List<TmxTileLayer> getTileLayers()
    {
        return tileLayers;
    }

    public TmxObjectLayer getObjectLayer(int index)
    {
        return objectLayers.get(index);
    }

    public int getNumObjectLayers()
    {
        return objectLayers.size();
    }

    public List<TmxObjectLayer> getObjectLayers()
    {
        return objectLayers;
    }

    public TmxImageLayer getImageLayer(int index)
    {
        return imageLayers.get(index);
    }

    public int getNumImageLayers()
    {
        return imageLayers.size();
    }

    public List<TmxImageLayer> getImageLayers()
    {
        return imageLayers;
    }

    public int findTileSetIndex(int gid)
    {
        gid &= ~(FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG | FLIPPED_DIAGONALLY_FLAG);

        for (int i = getNumTileSets() - 1; i >= 0; i--)
        {
            if (gid >= getTileset(i).getFirstGID())
                return i;
        }

        return -1;
    }

    public TmxTileSet findTileset(int gid)
    {
        for (int i = getNumTileSets() - 1; i >= 0; i--)
        {
            if (gid >= getTileset(i).getFirstGID())
                return getTileset(i);
        }

        return null;
    }

    public TmxTileSet getTileset(int index)
    {
        return tileSets.get(index);
    }

    public int getNumTileSets()
    {
        return tileSets.size();
    }

    public List<TmxTileSet> getTileSets()
    {
        return tileSets;
    }

    public TmxProperties getProperties()
    {
        return properties;
    }

    private void parse(Node node)
    {
        Element element = (Element) node;

        version = Double.parseDouble(element.getAttribute("version"));
        width = Integer.parseInt(element.getAttribute("width"));
        height = Integer.parseInt(element.getAttribute("height"));
        tileWidth = Integer.parseInt(element.getAttribute("tilewidth"));
        tileHeight = Integer.parseInt(element.getAttribute("tileheight"));
        nextObjectID = Integer.parseInt(element.getAttribute("nextobjectid"));

        if (element.hasAttribute("background"))
        {
            String hexColor = element.getAttribute("background").trim();
            if (hexColor.startsWith("#"))
                hexColor = hexColor.substring(1);

            backgroundColor = new Color(Integer.parseInt(hexColor, 16));
        }

        orientation = Orientation.valueOf(element.getAttribute("orientation").trim().toUpperCase());

        if (element.hasAttribute("renderorder"))
        {
            switch (element.getAttribute("renderorder").trim().toLowerCase())
            {
                case "right-down":
                    renderOrder = RenderOrder.RIGHT_DOWN;
                    break;
                case "right-up":
                    renderOrder = RenderOrder.RIGHT_UP;
                    break;
                case "left-down":
                    renderOrder = RenderOrder.LEFT_DOWN;
                    break;
                case "left-up":
                    renderOrder = RenderOrder.LEFT_UP;
                    break;
            }
        }

        if (element.hasAttribute("staggeraxis"))
        {
            switch (element.getAttribute("staggeraxis").trim().toLowerCase())
            {
                case "x":
                    staggerAxis = StaggerAxis.AXIS_X;
                    break;
                case "y":
                    staggerAxis = StaggerAxis.AXIS_Y;
                    break;
            }
        }

        if (element.hasAttribute("staggerindex"))
        {
            switch (element.getAttribute("staggerindex").trim().toLowerCase())
            {
                case "even":
                    staggerIndex = StaggerIndex.EVEN;
                    break;
                case "odd":
                    staggerIndex = StaggerIndex.ODD;
                    break;
            }
        }

        if (element.hasAttribute("hexsidelength"))
            hexSideLength = Integer.parseInt(element.getAttribute("hexsidelength"));

        // Read all other elements
        Node child = node.getFirstChild();

        while (child != null)
        {
            switch (child.getNodeName().trim().toLowerCase())
            {
                case "properties":
                    properties.parse(child);
                    break;

                case "tileset":
                    TmxTileSet tileSet = new TmxTileSet();
                    tileSet.parse(child, filePath);
                    tileSets.add(tileSet);
                    break;

                case "layer":
                    TmxTileLayer tileLayer = new TmxTileLayer(this);
                    tileLayer.parse(child);
                    tileLayers.add(tileLayer);
                    break;

                case "imagelayer":
                    TmxImageLayer imageLayer = new TmxImageLayer(this);
                    imageLayer.parse(child);
                    imageLayers.add(imageLayer);
                    break;

                case "objectgroup":
                    TmxObjectLayer objectLayer = new TmxObjectLayer(this);
                    objectLayer.parse(child);
                    objectLayers.add(objectLayer);
                    break;
            }

            child = child.getNextSibling();
        }

        layers.addAll(tileLayers);
        layers.addAll(imageLayers);
        layers.addAll(objectLayers);
    }

    /**
     * The orientation of the TiledMap.
     */
    public enum Orientation
    {
        ORTHOGONAL, ISOMETRIC, STAGGERED, HEXAGONAL
    }

    /**
     * The render order of the TiledMap
     */
    public enum RenderOrder
    {
        RIGHT_DOWN, RIGHT_UP, LEFT_DOWN, LEFT_UP
    }

    /**
     * The stagger axis for the map (if the map is not hexagonal)
     */
    public enum StaggerAxis
    {
        AXIS_X, AXIS_Y, NONE
    }

    /**
     * The stagger index for the map. Applies to hexagonal and isometric staggered maps.
     */
    public enum StaggerIndex
    {
        NONE, EVEN, ODD
    }
}


text:
/*	$NetBSD: procfs_map.c,v 1.44 2014/03/18 18:20:43 riastradh Exp $	*/

/*
 * Copyright (c) 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Jan-Simon Pendry.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)procfs_status.c	8.3 (Berkeley) 2/17/94
 *
 *	$FreeBSD: procfs_map.c,v 1.18 1998/12/04 22:54:51 archie Exp $
 */

/*
 * Copyright (c) 1993 Jan-Simon Pendry
 *
 * This code is derived from software contributed to Berkeley by
 * Jan-Simon Pendry.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)procfs_status.c	8.3 (Berkeley) 2/17/94
 *
 *	$FreeBSD: procfs_map.c,v 1.18 1998/12/04 22:54:51 archie Exp $
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: procfs_map.c,v 1.44 2014/03/18 18:20:43 riastradh Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/vnode.h>
#include <sys/malloc.h>
#include <sys/namei.h>
#include <sys/filedesc.h>
#include <miscfs/procfs/procfs.h>

#include <sys/lock.h>

#include <uvm/uvm.h>

#define BUFFERSIZE (64 * 1024)
#define MAXBUFFERSIZE (256 * 1024)

/*
 * The map entries can *almost* be read with programs like cat.  However,
 * large maps need special programs to read.  It is not easy to implement
 * a program that can sense the required size of the buffer, and then
 * subsequently do a read with the appropriate size.  This operation cannot
 * be atomic.  The best that we can do is to allow the program to do a read
 * with an arbitrarily large buffer, and return as much as we can.  We can
 * return an error code if the buffer is too small (EFBIG), then the program
 * can try a bigger buffer.
 */
int
procfs_domap(struct lwp *curl, struct proc *p, struct pfsnode *pfs,
	     struct uio *uio, int linuxmode)
{
	int error;
	struct vmspace *vm;
	struct vm_map *map;
	struct vm_map_entry *entry;
	char *buffer = NULL;
	size_t bufsize = BUFFERSIZE;
	char *path;
	struct vnode *vp;
	struct vattr va;
	dev_t dev;
	long fileid;
	size_t pos;
	int width = (int)((curl->l_proc->p_flag & PK_32) ? sizeof(int32_t) :
	    sizeof(void *)) * 2;

	if (uio->uio_rw != UIO_READ)
		return EOPNOTSUPP;

	if (uio->uio_offset != 0) {
		/*
		 * we return 0 here, so that the second read returns EOF
		 * we don't support reading from an offset because the
		 * map could have changed between the two reads.
		 */
		return 0;
	}

	error = 0;

	if (linuxmode != 0)
		path = malloc(MAXPATHLEN * 4, M_TEMP, M_WAITOK);
	else
		path = NULL;

	if ((error = proc_vmspace_getref(p, &vm)) != 0)
		goto out;

	map = &vm->vm_map;
	vm_map_lock_read(map);

again:
	buffer = malloc(bufsize, M_TEMP, M_WAITOK);
	pos = 0;
	for (entry = map->header.next; entry != &map->header;
	    entry = entry->next) {

		if (UVM_ET_ISSUBMAP(entry))
			continue;

		if (linuxmode != 0) {
			*path = 0;
			dev = (dev_t)0;
			fileid = 0;
			if (UVM_ET_ISOBJ(entry) &&
			    UVM_OBJ_IS_VNODE(entry->object.uvm_obj)) {
				vp = (struct vnode *)entry->object.uvm_obj;
				vn_lock(vp, LK_SHARED | LK_RETRY);
				error = VOP_GETATTR(vp, &va, curl->l_cred);
				VOP_UNLOCK(vp);
				if (error == 0 && vp != pfs->pfs_vnode) {
					fileid = va.va_fileid;
					dev = va.va_fsid;
					error = vnode_to_path(path,
					    MAXPATHLEN * 4, vp, curl, p);
				}
			}
			pos += snprintf(buffer + pos, bufsize - pos,
			    "%.*"PRIxVADDR"-%.*"PRIxVADDR" %c%c%c%c "
			    "%.*lx %.2llx:%.2llx %-8ld %25.s %s\n",
			    width, entry->start,
			    width, entry->end,
			    (entry->protection & VM_PROT_READ) ? 'r' : '-',
			    (entry->protection & VM_PROT_WRITE) ? 'w' : '-',
			    (entry->protection & VM_PROT_EXECUTE) ? 'x' : '-',
			    (entry->etype & UVM_ET_COPYONWRITE) ? 'p' : 's',
			    width, (unsigned long)entry->offset,
			    (unsigned long long)major(dev),
			    (unsigned long long)minor(dev), fileid, "", path);
		} else {
			pos += snprintf(buffer + pos, bufsize - pos,
			    "%#"PRIxVADDR" %#"PRIxVADDR" "
			    "%c%c%c %c%c%c %s %s %d %d %d\n",
			    entry->start, entry->end,
			    (entry->protection & VM_PROT_READ) ? 'r' : '-',
			    (entry->protection & VM_PROT_WRITE) ? 'w' : '-',
			    (entry->protection & VM_PROT_EXECUTE) ? 'x' : '-',
			    (entry->max_protection & VM_PROT_READ) ? 'r' : '-',
			    (entry->max_protection & VM_PROT_WRITE) ? 'w' : '-',
			    (entry->max_protection & VM_PROT_EXECUTE) ?
				'x' : '-',
			    (entry->etype & UVM_ET_COPYONWRITE) ?
				"COW" : "NCOW",
			    (entry->etype & UVM_ET_NEEDSCOPY) ? "NC" : "NNC",
			    entry->inheritance, entry->wired_count,
			    entry->advice);
		}
		if (pos >= bufsize) {
			bufsize <<= 1;
			if (bufsize > MAXBUFFERSIZE) {
				error = ENOMEM;
				vm_map_unlock_read(map);
				uvmspace_free(vm);
				goto out;
			}
			free(buffer, M_TEMP);
			goto again;
		}
	}

	vm_map_unlock_read(map);
	uvmspace_free(vm);

	error = uiomove(buffer, pos, uio);
out:
	if (path != NULL)
		free(path, M_TEMP);
	if (buffer != NULL)
		free(buffer, M_TEMP);

	return error;
}

int
procfs_validmap(struct lwp *l, struct mount *mp)
{
	return ((l->l_flag & LW_SYSTEM) == 0);
}