text:
package org.elasticsearch.test;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Checks that all tests in a directory are named according to our naming conventions. This is important because tests that do not follow
 * our conventions aren't run by gradle. This was once a glorious unit test but now that Elasticsearch is a multi-module project it must be
 * a class with a main method so gradle can call it for each project. This has the advantage of allowing gradle to calculate when it is
 * {@code UP-TO-DATE} so it can be skipped if the compiled classes haven't changed. This is useful on large modules for which checking all
 * the modules can be slow.
 */
public class NamingConventionsCheck {
    public static void main(String[] args) throws IOException {
        Class<?> testClass = null;
        Class<?> integTestClass = null;
        String rootPathList = null;
        boolean skipIntegTestsInDisguise = false;
        boolean checkMainClasses = false;
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            switch (arg) {
                case "--test-class":
                    testClass = loadClassWithoutInitializing(args[++i]);
                    break;
                case "--integ-test-class":
                    integTestClass = loadClassWithoutInitializing(args[++i]);
                    break;
                case "--skip-integ-tests-in-disguise":
                    skipIntegTestsInDisguise = true;
                    break;
                case "--main":
                    checkMainClasses = true;
                    break;
                case "--":
                    rootPathList = args[++i];
                    break;
                default:
                    fail("unsupported argument '" + arg + "'");
            }
        }
        if (rootPathList == null) {
            fail("No paths provided");
            return;
        }

        NamingConventionsCheck check = new NamingConventionsCheck(testClass, integTestClass);
        for (String rootDir : rootPathList.split(Pattern.quote(File.pathSeparator))) {
            Path rootPath = Paths.get(rootDir);
            if (checkMainClasses) {
                check.checkMain(rootPath);
            } else {
                check.checkTests(rootPath, skipIntegTestsInDisguise);
            }
        }

        // Now we should have no violations
        int exitCode  = 0 ;
        exitCode += countAndPrintViolations(
                "Not all subclasses of " + check.testClass.getSimpleName()
                    + " match the naming convention. Concrete classes must end with [Tests]",
                check.missingSuffix) ;
        exitCode += countAndPrintViolations(
            "Classes ending with [Tests] are abstract or interfaces",
            check.notRunnable
        );
        exitCode += countAndPrintViolations(
            "Found inner classes that are tests, which are excluded from the test runner",
            check.innerClasses
        );
        exitCode += countAndPrintViolations(
            "Pure Unit-Test found must subclass [" + check.testClass.getSimpleName() + "]",
            check.pureUnitTest
        );
        exitCode += countAndPrintViolations(
            "Classes ending with [Tests] must subclass [" + check.testClass.getSimpleName() + "]",
            check.notImplementing
        );
        exitCode += countAndPrintViolations(
                "Classes ending with [Tests] or [IT] or extending [" +
                    check.testClass.getSimpleName() + "] must be in src/test/java",
                check.testsInMain
        );
        if (skipIntegTestsInDisguise == false) {
            exitCode += countAndPrintViolations("Subclasses of " + check.integTestClass.getSimpleName() +
                        " should end with IT as they are integration tests",
                    check.integTestsInDisguise
                );
        }
        System.exit(exitCode);
    }

    private final Set<Class<?>> notImplementing = new HashSet<>();
    private final Set<Class<?>> pureUnitTest = new HashSet<>();
    private final Set<Class<?>> missingSuffix = new HashSet<>();
    private final Set<Class<?>> integTestsInDisguise = new HashSet<>();
    private final Set<Class<?>> notRunnable = new HashSet<>();
    private final Set<Class<?>> innerClasses = new HashSet<>();
    private final Set<Class<?>> testsInMain = new HashSet<>();

    private final Class<?> testClass;
    private final Class<?> integTestClass;

    public NamingConventionsCheck(Class<?> testClass, Class<?> integTestClass) {
        this.testClass = Objects.requireNonNull(testClass, "--test-class is required");
        this.integTestClass = integTestClass;
    }

    public void checkTests(Path rootPath, boolean skipTestsInDisguised) throws IOException {
        Files.walkFileTree(rootPath, new TestClassVisitor() {
            @Override
            protected void visitTestClass(Class<?> clazz) {
                if (skipTestsInDisguised == false &&
                    integTestClass.isAssignableFrom(clazz) &&
                    clazz != integTestClass) {
                    integTestsInDisguise.add(clazz);
                }
                if (Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())) {
                    notRunnable.add(clazz);
                } else if (isTestCase(clazz) == false) {
                    notImplementing.add(clazz);
                } else if (Modifier.isStatic(clazz.getModifiers())) {
                    innerClasses.add(clazz);
                }
            }

            @Override
            protected void visitIntegrationTestClass(Class<?> clazz) {
                if (isTestCase(clazz) == false) {
                    notImplementing.add(clazz);
                }
            }

            @Override
            protected void visitOtherClass(Class<?> clazz) {
                if (Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())) {
                    return;
                }
                if (isTestCase(clazz)) {
                    missingSuffix.add(clazz);
                } else if (junit.framework.Test.class.isAssignableFrom(clazz)) {
                    pureUnitTest.add(clazz);
                }
            }
        });
    }

    public void checkMain(Path rootPath) throws IOException {
        Files.walkFileTree(rootPath, new TestClassVisitor() {
            @Override
            protected void visitTestClass(Class<?> clazz) {
                testsInMain.add(clazz);
            }

            @Override
            protected void visitIntegrationTestClass(Class<?> clazz) {
                testsInMain.add(clazz);
            }

            @Override
            protected void visitOtherClass(Class<?> clazz) {
                if (Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())) {
                    return;
                }
                if (isTestCase(clazz)) {
                    testsInMain.add(clazz);
                }
            }
        });

    }

    private static int countAndPrintViolations(String message, Set<Class<?>> set) {
        if (false == set.isEmpty()) {
            System.err.println(message + ":");
            for (Class<?> bad : set) {
                System.err.println(" * " + bad.getName());
            }
            return 1;
        }
        return 0;
    }

    /**
     * Fail the process if we didn't detect a particular violation. Named to look like a junit assertion even though it isn't because it is
     * similar enough.
     */
    private static void assertViolation(String className, Set<Class<?>> set) {
        className = className.startsWith("org") ? className : "org.elasticsearch.test.NamingConventionsCheckBadClasses$" + className;
        if (false == set.remove(loadClassWithoutInitializing(className))) {
            System.err.println("Error in NamingConventionsCheck! Expected [" + className + "] to be a violation but wasn't.");
            System.exit(1);
        }
    }

    /**
     * Fail the process with the provided message.
     */
    private static void fail(String reason) {
        System.err.println(reason);
        System.exit(1);
    }

    static Class<?> loadClassWithoutInitializing(String name) {
        try {
            return Class.forName(name,
                    // Don't initialize the class to save time. Not needed for this test and this doesn't share a VM with any other tests.
                    false,
                    // Use our classloader rather than the bootstrap class loader.
                    NamingConventionsCheck.class.getClassLoader());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    abstract class TestClassVisitor implements FileVisitor<Path> {
        /**
         * The package name of the directory we are currently visiting. Kept as a string rather than something fancy because we load
         * just about every class and doing so requires building a string out of it anyway. At least this way we don't need to build the
         * first part of the string over and over and over again.
         */
        private String packageName;

        /**
         * Visit classes named like a test.
         */
        protected abstract void visitTestClass(Class<?> clazz);

        /**
         * Visit classes named like an integration test.
         */
        protected abstract void visitIntegrationTestClass(Class<?> clazz);

        /**
         * Visit classes not named like a test at all.
         */
        protected abstract void visitOtherClass(Class<?> clazz);
        @Override
        public final FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            // First we visit the root directory
            if (packageName == null) {
                // And it package is empty string regardless of the directory name
                packageName = "";
            } else {
                packageName += dir.getFileName() + ".";
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public final FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            // Go up one package by jumping back to the second to last '.'
            packageName = packageName.substring(0, 1 + packageName.lastIndexOf('.', packageName.length() - 2));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public final FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String filename = file.getFileName().toString();
            if (filename.endsWith(".class")) {
                String className = filename.substring(0, filename.length() - ".class".length());
                Class<?> clazz = loadClassWithoutInitializing(packageName + className);
                if (clazz.getName().endsWith("Tests")) {
                    visitTestClass(clazz);
                } else if (clazz.getName().endsWith("IT")) {
                    visitIntegrationTestClass(clazz);
                } else {
                    visitOtherClass(clazz);
                }
            }
            return FileVisitResult.CONTINUE;
        }

        /**
         * Is this class a test case?
         */
        protected boolean isTestCase(Class<?> clazz) {
            return testClass.isAssignableFrom(clazz);
        }

        @Override
        public final FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            throw exc;
        }

    }

}


text:
export { SideNav } from "./side-nav";
export { Forms } from "./forms";
export { Tabs } from "./tabs";
export { TabsRouting } from "./tabs-routing";
export { Dialogs } from "./dialogs";
export { Dropdown } from "./dropdown";
export { Collapsible } from "./collapsible";
export { Carousel } from "./carousel";
export { Chips } from "./chips";
export { DatePicker } from "./datepicker";
export { ModelBindings } from "./model-bindings/model-bindings";
export { Parallax } from './parallax'

redpajama_set_name: RedPajamaGithub


text:
/**
 * Singleton used as an event bus between multiple instances of Storage classes. This class raises events trigger by
 * instances on the same page or on different pages accessing the same storage location (like in a different browser's
 * tab)
 */
Aria.classDefinition({
    $classpath : "aria.storage.EventBus",
    $singleton : true,
    $events : {
        "change" : "Raised when a change happens in any of the linked instances"
    },
    $prototype : {
        /**
         * Notify that a change event happened on a specific storage location
         * @param {String} location Storage location where the event is happening, i.e. local/session
         * @param {String} key Id of the value that is changing, null if clear
         * @param {String} value Value being set, null if removed
         * @param {String} old Old value being changed, null if newly added
         * @param {String} nspace Namspace of the storage instance
         */
        notifyChange : function (location, key, value, old, nspace) {
            this.$raiseEvent({
                name : "change",
                location : location,
                namespace : nspace,
                key : key,
                newValue : value,
                oldValue : old,
                url : Aria.$window.location
            });
        }
    }
});


text:
[![Build Status][ci-img]][ci]
[![devDependency Status](https://david-dm.org/tcotton/portfolio/dev-status.svg?style=flat-square)](https://david-dm.org/tcotton/posthtml-head-elements#info=devDependencies)
[![npm version](https://badge.fury.io/js/posthtml-head-elements.svg)](http://badge.fury.io/js/posthtml-head-elements)
[![Coverage Status](https://coveralls.io/repos/posthtml/posthtml-head-elements/badge.svg?branch=master&service=github)](https://coveralls.io/github/posthtml/posthtml-head-elements?branch=master)

[ci-img]: https://travis-ci.org/posthtml/posthtml-head-elements.svg
[ci]: https://travis-ci.org/posthtml/posthtml-head-elements

This plugin is intended to work with [PostHTML](https://github.com/posthtml/posthtml). It will allow you to keep HTML head elements - title, script, link, base and meta - in a separate JSON file:

```json
{
  "meta": [
    {
      "charset": "utf-8"
    },
    {
      "http-equiv": "X-UA-Compatible",
      "content": "IE=edge"
    },
    {
      "name": "description",
      "content": "A front-end template that helps you build fast, modern mobile web apps."
    },
    {
      "name": "viewport",
      "content": "width=device-width, initial-scale=1"
    }
  ],
  "title": "Web Starter Kit",
  "link": [
    {
      "rel": "manifest",
      "href": "manifest.json"
    },
    {
      "rel": "icon",
      "sizes": "192x192",
      "href": "images/touch/chrome-touch-icon-192x192.png"
    }
  ],
  "script": [
    {
      "src": "//cdn.polyfill.io/v1/polyfill.min.js"
    }
  ],
  "base": [
    {
      "href": "/"
    }
  ]
}
```

A custom tag, which signifies where the HTML head elements should be inserted during the build process, needs to be placed in the document head:

```html

<!doctype html>
<html lang="en">
<head>

  <posthtml-head-elements></posthtml-head-elements>

  <!-- Add to homescreen for Chrome on Android -->
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="application-name" content="Web Starter Kit">

```

This is then configured like below if you are using [gulp-posthtml](https://www.npmjs.com/package/gulp-posthtml).
Please read the [PostHTML GitHub page](https://github.com/posthtml/posthtml) for plugin configuration guidelines.

```javascript

var posthtml = require('gulp-posthtml');
var gulp = require('gulp');
var jsonPath = '/data/posthtml-head-elements.json';

gulp.task('posthtml', function() {

  var plugins = [
    require('posthtml-head-elements')({headElements: jsonPath})
  ];

  return gulp.src('/app/index.html')
    .pipe(posthtml(plugins))
    .pipe(gulp.dest('/build/'));

});

```

Note that the HTML head elements are inserted into the document in the spatial order they are laid out - from top to bottom

It is possible to mix the head elements, but the JSON syntax requires a unique key. Therefore, if you are using more than one head element, place an underscore immediately afterwards.

An example of a JSON file with multiple head elements:

```json
{
  "meta": [
    {
      "charset": "utf-8"
    },
    {
      "http-equiv": "X-UA-Compatible",
      "content": "IE=edge"
    },
    {
      "name": "description",
      "content": "A front-end template that helps you build fast, modern mobile web apps."
    },
    {
      "name": "viewport",
      "content": "width=device-width, initial-scale=1"
    }
  ],
  "title": "Web Starter Kit",
  "link": [
    {
      "rel": "manifest",
      "href": "manifest.json"
    }
  ],
  "meta_1": [
    {
      "name": "mobile-web-app-capable",
      "content": "yes"
    },
    {
      "name": "application-name",
      "content": "Web Starter Kit"
    }
  ],
  "link_1": [
    {
      "rel": "icon",
      "sizes": "192x192",
      "href": "images/touch/chrome-touch-icon-192x192.png"
    }
  ],
  "meta_2": [
    {
      "name": "apple-mobile-web-app-capable",
      "content": "yes"
    },
    {
      "name": "apple-mobile-web-app-status-bar-style",
      "content": "black"
    },
    {
      "name": "apple-mobile-web-app-title",
      "content": "Web Starter Kit"
    }
  ],
  "link_2": [
    {
      "rel": "apple-touch-icon",
      "href": "images/touch/apple-touch-icon.png"
    }
  ],
  "meta_3": [
    {
      "name": "msapplication-TileImage",
      "content": "mages/touch/ms-touch-icon-144x144-precomposed.png"
    },
    {
      "name": "msapplication-TileColor",
      "content": "3372DF"
    },
    {
      "name": "theme-color",
      "content": "#3372DF"
    }
  ],
  "link_3": [
    {
      "rel": "stylesheet",
      "href": "styles/main.css"
    }
  ]
}
```


text:
package com.facebook.buck.cxx;

import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.Flavor;
import com.facebook.buck.core.model.InternalFlavor;
import com.facebook.buck.core.model.UnflavoredBuildTarget;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.model.impl.ImmutableBuildTarget;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.common.BuildRules;
import com.facebook.buck.core.rules.impl.DependencyAggregation;
import com.facebook.buck.core.rules.impl.NoopBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.Preprocessor;
import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkable;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.coercer.FrameworkPath;
import com.facebook.buck.util.RichStream;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

/**
 * Represents a precompilable header file, along with dependencies.
 *
 *
Rules which depend on this will inherit this rule's of dependencies. For example if a given
 * rule R uses a precompiled header rule P, then all of P's {@code deps} will get merged into R's
 * {@code deps} list.
 */
public abstract class PreInclude extends NoopBuildRuleWithDeclaredAndExtraDeps
    implements NativeLinkable, CxxPreprocessorDep {

  private static final Flavor AGGREGATED_PREPROCESS_DEPS_FLAVOR =
      InternalFlavor.of("preprocessor-deps");

  /**
   * The source path which was expressed as either: (1) the `prefix_header` attribute in a
   * `cxx_binary` or `cxx_library` (or similar) rule, or (2) the `src` in a `cxx_precompiled_header`
   * rule.
   *
   *
This could be any {@link SourcePath}: a target, a file, etc.
   */
  private final SourcePath sourcePath;

  /**
   * The path to the header file itself; i.e. the path which {@link #sourcePath} resolves to. This
   * is guaranteed to be an absolute path.
   */
  private final Path absoluteHeaderPath;

  /** @param buildRuleParams the params for this PCH rule, including {@code deps} */
  PreInclude(
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      ImmutableSortedSet<BuildRule> deps,
      SourcePath sourcePath,
      Path absoluteHeaderPath) {
    super(buildTarget, projectFilesystem, makeBuildRuleParams(deps));
    this.sourcePath = sourcePath;
    this.absoluteHeaderPath = absoluteHeaderPath;
  }

  /**
   * @return source path as specified in a {@code cxx_precompiled_header}'s {@code src} attribute,
   *     or of a rule's {@code prefix_header}.
   */
  public SourcePath getHeaderSourcePath() {
    return sourcePath;
  }

  /** @return path to the header file, guaranteed absolute */
  public Path getAbsoluteHeaderPath() {
    return absoluteHeaderPath;
  }

  /** @return path to the header file, relativized against the given project filesystem (cell) */
  public Path getRelativeHeaderPath(ProjectFilesystem relativizedTo) {
    return relativizedTo.relativize(getAbsoluteHeaderPath());
  }

  private static BuildRuleParams makeBuildRuleParams(ImmutableSortedSet<BuildRule> deps) {
    return new BuildRuleParams(() -> deps, () -> ImmutableSortedSet.of(), ImmutableSortedSet.of());
  }

  private ImmutableSortedSet<BuildRule> getExportedDeps() {
    return BuildRules.getExportedRules(getBuildDeps());
  }

  /**
   * Returns our {@link #getBuildDeps()}, limited to the subset of those which are {@link
   * NativeLinkable}.
   */
  @Override
  public Iterable<? extends NativeLinkable> getNativeLinkableDeps(BuildRuleResolver ruleResolver) {
    return RichStream.from(getBuildDeps()).filter(NativeLinkable.class).toImmutableList();
  }

  /**
   * Returns our {@link #getExportedDeps()}, limited to the subset of those which are {@link
   * NativeLinkable}.
   */
  @Override
  public Iterable<? extends NativeLinkable> getNativeLinkableExportedDeps(
      BuildRuleResolver ruleResolver) {
    return RichStream.from(getExportedDeps()).filter(NativeLinkable.class).toImmutableList();
  }

  /**
   * Linkage doesn't matter for PCHs, but use care not to change it from the rest of the builds'
   * rules' preferred linkage.
   */
  @Override
  public Linkage getPreferredLinkage(CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
    return Linkage.ANY;
  }

  /** Doesn't really apply to us. No shared libraries to add here. */
  @Override
  public ImmutableMap<String, SourcePath> getSharedLibraries(
      CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
    return ImmutableMap.of();
  }

  /**
   * This class doesn't add any native linkable code of its own, it just has deps which need to be
   * passed along (see {@link #getNativeLinkableDeps(BuildRuleResolver)} and {@link
   * #getNativeLinkableExportedDeps(BuildRuleResolver)} for the handling of those linkables).
   *
   * @return empty {@link NativeLinkableInput}
   */
  @Override
  public NativeLinkableInput getNativeLinkableInput(
      CxxPlatform cxxPlatform,
      Linker.LinkableDepType type,
      boolean forceLinkWhole,
      ActionGraphBuilder graphBuilder) {
    return NativeLinkableInput.of();
  }

  @Override
  public Iterable<CxxPreprocessorDep> getCxxPreprocessorDeps(
      CxxPlatform cxxPlatform, BuildRuleResolver ruleResolver) {
    return RichStream.from(getBuildDeps()).filter(CxxPreprocessorDep.class).toImmutableList();
  }

  @Override
  public CxxPreprocessorInput getCxxPreprocessorInput(
      CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
    return CxxPreprocessorInput.of();
  }

  private final TransitiveCxxPreprocessorInputCache transitiveCxxPreprocessorInputCache =
      new TransitiveCxxPreprocessorInputCache(this);

  @Override
  public ImmutableMap<BuildTarget, CxxPreprocessorInput> getTransitiveCxxPreprocessorInput(
      CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
    return transitiveCxxPreprocessorInputCache.getUnchecked(cxxPlatform, graphBuilder);
  }

  private ImmutableList<CxxPreprocessorInput> getCxxPreprocessorInputs(
      CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
    ImmutableList.Builder<CxxPreprocessorInput> builder = ImmutableList.builder();
    for (Map.Entry<BuildTarget, CxxPreprocessorInput> entry :
        getTransitiveCxxPreprocessorInput(cxxPlatform, graphBuilder).entrySet()) {
      builder.add(entry.getValue());
    }
    return builder.build();
  }

  private ImmutableList<CxxHeaders> getIncludes(
      CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
    return getCxxPreprocessorInputs(cxxPlatform, graphBuilder)
        .stream()
        .flatMap(input -> input.getIncludes().stream())
        .collect(ImmutableList.toImmutableList());
  }

  private ImmutableSet<FrameworkPath> getFrameworks(
      CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
    return getCxxPreprocessorInputs(cxxPlatform, graphBuilder)
        .stream()
        .flatMap(input -> input.getFrameworks().stream())
        .collect(ImmutableSet.toImmutableSet());
  }

  private ImmutableSortedSet<BuildRule> getPreprocessDeps(
      CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder, SourcePathRuleFinder ruleFinder) {
    ImmutableSortedSet.Builder<BuildRule> builder = ImmutableSortedSet.naturalOrder();
    for (CxxPreprocessorInput input : getCxxPreprocessorInputs(cxxPlatform, graphBuilder)) {
      builder.addAll(input.getDeps(graphBuilder, ruleFinder));
    }
    for (CxxHeaders cxxHeaders : getIncludes(cxxPlatform, graphBuilder)) {
      cxxHeaders.getDeps(ruleFinder).forEachOrdered(builder::add);
    }
    for (FrameworkPath frameworkPath : getFrameworks(cxxPlatform, graphBuilder)) {
      builder.addAll(frameworkPath.getDeps(ruleFinder));
    }

    builder.addAll(getBuildDeps());
    builder.addAll(getExportedDeps());

    return builder.build();
  }

  private BuildTarget createAggregatedDepsTarget(CxxPlatform cxxPlatform) {
    return getBuildTarget()
        .withAppendedFlavors(cxxPlatform.getFlavor(), AGGREGATED_PREPROCESS_DEPS_FLAVOR);
  }

  /**
   * Find or create a {@link DependencyAggregation} rule, representing a grouping of dependencies:
   * generally, those deps from the current {@link CxxPlatform}.
   */
  protected DependencyAggregation requireAggregatedDepsRule(
      CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder, SourcePathRuleFinder ruleFinder) {
    return (DependencyAggregation)
        graphBuilder.computeIfAbsent(
            createAggregatedDepsTarget(cxxPlatform),
            depAggTarget ->
                new DependencyAggregation(
                    depAggTarget,
                    getProjectFilesystem(),
                    getPreprocessDeps(cxxPlatform, graphBuilder, ruleFinder)));
  }

  /** @return newly-built delegate for this PCH build (if precompiling enabled) */
  protected PreprocessorDelegate buildPreprocessorDelegate(
      CxxPlatform cxxPlatform,
      Preprocessor preprocessor,
      CxxToolFlags preprocessorFlags,
      ActionGraphBuilder graphBuilder,
      SourcePathResolver pathResolver) {
    return new PreprocessorDelegate(
        cxxPlatform.getHeaderVerification(),
        PathSourcePath.of(getProjectFilesystem(), Paths.get("")),
        preprocessor,
        PreprocessorFlags.of(
            Optional.of(getHeaderSourcePath()),
            preprocessorFlags,
            getIncludes(cxxPlatform, graphBuilder),
            getFrameworks(cxxPlatform, graphBuilder)),
        CxxDescriptionEnhancer.frameworkPathToSearchPath(cxxPlatform, pathResolver),
        /* leadingIncludePaths */ Optional.empty(),
        Optional.empty(),
        ImmutableSortedSet.of());
  }

  public abstract CxxPrecompiledHeader getPrecompiledHeader(
      boolean canPrecompile,
      PreprocessorDelegate preprocessorDelegateForCxxRule,
      DependencyAggregation aggregatedPreprocessDepsRule,
      CxxToolFlags computedCompilerFlags,
      Function<CxxToolFlags, String> getHash,
      Function<CxxToolFlags, String> getBaseHash,
      CxxPlatform cxxPlatform,
      CxxSource.Type sourceType,
      ImmutableList<String> sourceFlags,
      ActionGraphBuilder graphBuilder,
      SourcePathRuleFinder ruleFinder,
      SourcePathResolver pathResolver);

  /**
   * Look up or build a precompiled header build rule which this build rule is requesting.
   *
   *
This method will first try to determine whether a matching PCH was already created; if so,
   * it will be reused. This is done by searching the cache in the {@link ActionGraphBuilder} owned
   * by this class. If this ends up building a new instance of {@link CxxPrecompiledHeader}, it will
   * be added to the graphBuilder cache.
   */
  protected CxxPrecompiledHeader requirePrecompiledHeader(
      boolean canPrecompile,
      PreprocessorDelegate preprocessorDelegate,
      CxxPlatform cxxPlatform,
      CxxSource.Type sourceType,
      CxxToolFlags compilerFlags,
      DepsBuilder depsBuilder,
      UnflavoredBuildTarget templateTarget,
      ImmutableSortedSet<Flavor> flavors,
      ActionGraphBuilder graphBuilder) {
    return (CxxPrecompiledHeader)
        graphBuilder.computeIfAbsent(
            ImmutableBuildTarget.of(templateTarget, flavors),
            target -> {
              // Give the PCH a filename that looks like a header file with .gch appended to it,
              // GCC-style.
              // GCC accepts an "-include" flag with the .h file as its arg, and auto-appends
              // ".gch" to
              // automagically use the precompiled header in place of the original header.  Of
              // course in
              // our case we'll only have the ".gch" file, which is alright; the ".h" isn't
              // truly needed.
              Path output = BuildTargetPaths.getGenPath(getProjectFilesystem(), target, "%s.h.gch");

              CompilerDelegate compilerDelegate =
                  new CompilerDelegate(
                      cxxPlatform.getCompilerDebugPathSanitizer(),
                      CxxSourceTypes.getCompiler(
                              cxxPlatform, CxxSourceTypes.getPreprocessorOutputType(sourceType))
                          .resolve(graphBuilder),
                      compilerFlags);
              depsBuilder.add(compilerDelegate);

              depsBuilder.add(getHeaderSourcePath());

              return new CxxPrecompiledHeader(
                  canPrecompile,
                  target,
                  getProjectFilesystem(),
                  depsBuilder.build(),
                  output,
                  preprocessorDelegate,
                  compilerDelegate,
                  compilerFlags,
                  getHeaderSourcePath(),
                  sourceType,
                  cxxPlatform.getCompilerDebugPathSanitizer());
            });
  }
}


text:
<!doctype html>

    <title>Code coverage report for eslint-plugin-angular/rules/definedundefined.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / eslint-plugin-angular/rules/ definedundefined.js

        100%
        Statements
        22/22

        96.88%
        Branches
        31/32

        100%
        Functions
        5/5

        100%
        Lines
        22/22

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

1×

1×
1×
15×

1×
12×

28×

11×

2×
1×
1×
1×

15×
14×
2×
12×
2×
10×
4×
6×
4×

1×

/**
 * use `angular.isDefined` and `angular.isUndefined` instead of other undefined checks
 *
 * You should use the angular.isUndefined or angular.isDefined methods instead of using the keyword undefined.
 * We also check the use of !angular.isUndefined and !angular.isDefined (should prefer the reverse function)
 *
 * @version 0.1.0
 * @category angularWrapper
 */
'use strict';

var utils = require('./utils/utils');

module.exports = function(context) {
    function isCompareOperator(operator) {
        return operator === '===' || operator === '!==' || operator === '==' || operator === '!=';
    }
    function reportError(node) {
        context.report(node, 'You should not use directly the "undefined" keyword. Prefer ' +
            'angular.isUndefined or angular.isDefined', {});
    }
    /**
    *    Rule that check if we use angular.is(Un)defined() instead of the undefined keyword
    */
    return {
        MemberExpression: function(node) {
            if (node.object.name === 'angular' &&
                    node.parent !== undefined &&
                    node.parent.parent !== undefined &&
                    node.parent.parent.operator === '!') {
                if (node.property.name === 'isDefined') {
                    context.report(node, 'Instead of !angular.isDefined, you can use the out-of-box angular.isUndefined method', {});
                } else Eif (node.property.name === 'isUndefined') {
                    context.report(node, 'Instead of !angular.isUndefined, you can use the out-of-box angular.isDefined method', {});
                }
            }
        },
        BinaryExpression: function(node) {
            if (isCompareOperator(node.operator)) {
                if (utils.isTypeOfStatement(node.left) && node.right.value === 'undefined') {
                    reportError(node);
                } else if (utils.isTypeOfStatement(node.right) && node.left.value === 'undefined') {
                    reportError(node);
                } else if (node.left.type === 'Identifier' && node.left.name === 'undefined') {
                    reportError(node);
                } else if (node.right.type === 'Identifier' && node.right.name === 'undefined') {
                    reportError(node);
                }
            }
        }
    };
};

module.exports.schema = [];

  Code coverage
  generated by istanbul at Sun Jul 24 2016 16:42:41 GMT+0200 (CEST)


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

namespace System.Runtime.CompilerServices
{
    /// <summary>
    /// !!!! DO NOT USE THIS INTERFACE DIRECTLY EXCEPT IN THE IMPLEMENTATION OF CASTABLEOBJECT!!!!
    /// </summary>
    internal interface ICastableObject
        // TODO!! BEGIN REMOVE THIS CODE WHEN WE REMOVE ICASTABLE
        : ICastable
    // TODO!! END REMOVE THIS CODE WHEN WE REMOVE ICASTABLE
    {
        object CastToInterface(EETypePtr interfaceType, bool produceCastErrorException, out Exception castError);
    }

    public abstract class CastableObject : ICastableObject
    {
        // THIS FIELD IS USED BY THE RUNTIME DIRECTLY! IT MUST NOT BE REMOVED BY THE REDUCER
        private object _hiddenCacheField;

        object ICastableObject.CastToInterface(EETypePtr interfaceType, bool produceCastErrorException, out Exception castError)
        {
            return CastToInterface(new RuntimeTypeHandle(interfaceType), produceCastErrorException, out castError);
        }

        // This is called if casting this object to the given interface type would otherwise fail. Casting
        // here means the IL isinst and castclass instructions in the case where they are given an interface
        // type as the target type. This function may also be called during interface dispatch.
        //
        // A return value of non-null indicates the cast is valid.
        // The return value (if non-null) must be an object instance that implements the specified interface.
        //
        // If null is returned when this is called as part of a castclass then the usual InvalidCastException
        // will be thrown unless an alternate exception is assigned to the castError output parameter. This
        // parameter is ignored on successful casts or during the evaluation of an isinst (which returns null
        // rather than throwing on error).
        //
        // The results of this call are cached
        //
        // The results of this call should be semantically  invariant for the same object, interface type pair.
        // That is because this is the only guard placed before an interface invocation at runtime. It is possible
        // that this call may occur more than once for a given pair, and it is possible that the results of multiple calls
        // may remain in use over time.
        protected abstract object CastToInterface(RuntimeTypeHandle interfaceType, bool produceCastErrorException, out Exception castError);

        // TODO!! BEGIN REMOVE THIS CODE WHEN WE REMOVE ICASTABLE
        RuntimeTypeHandle ICastable.GetImplType(RuntimeTypeHandle interfaceType)
        {
            // TODO! Remove this hack that forces the il2il pipeline to not remove the ICastableObject interface or the _hiddenCacheField
            Exception junk;
            _hiddenCacheField = ((ICastableObject)this).CastToInterface(default(EETypePtr), false, out junk);
            // ENDTODO!
            return default(RuntimeTypeHandle);
        }

        bool ICastable.IsInstanceOfInterface(RuntimeTypeHandle interfaceType, out Exception castError)
        {
            castError = null;
            return false;
        }
        // TODO!! END REMOVE THIS CODE WHEN WE REMOVE ICASTABLE
    }
}


text:
package model

import (
	"testing"
)

func TestProfile_Validate(t *testing.T) {
	config := &Profile{}
	valid := func(n int) {
		if err := config.Validate(); err == nil {
			t.Fatal("Test:", n, "this config need to be invalid")
		}
	}

	valid(0)

	config.Name = "x"
	valid(1)

	config.Channels = []string{""}
	valid(2)

	config.Channels = []string{"Channel 1"}
	valid(3)

	config.Channels = []string{"#channel1"}
	valid(4)

	config.LinesToPreview = new(int)
	*config.LinesToPreview = -1
	valid(5)

	*config.LinesToPreview = 10
	valid(6)

	config.Email = &Email{}
	valid(7)

	config.Email = &Email{
		ImapServer: "imap.example.com:143",
		Username:   "orders@example.com",
		Password:   "password",
	}
	valid(8)

	config.Mattermost = &Mattermost{}
	valid(9)

	config.Mattermost = &Mattermost{
		Server:   "https://mattermost.example.com",
		Team:     "team1",
		User:     "mattermail@example.com",
		Password: "password",
	}

	if err := config.Validate(); err != nil {
		t.Fatal(err)
	}

	config.Filter = &Filter{}
	valid(10)

	config.Filter = nil

	if err := config.Validate(); err != nil {
		t.Fatal(err)
	}
}

func TestProfile_Fix(t *testing.T) {
	p := &Profile{}
	p.Channels = []string{"  Test  "}

	p.Fix()

	if p.Channels[0] != "#test" {
		t.Fatal("Expected #test result:", p.Channels)
	}
	if *p.MailTemplate != defaultMailTemplate {
		t.Fatal("Expected MailTemplate:", defaultMailTemplate, " result:", *p.MailTemplate)
	}
	if *p.LinesToPreview != defaultLinesToPreview {
		t.Fatal("Expected LinesToPreview:", defaultLinesToPreview, " result:", *p.LinesToPreview)
	}
	if *p.RedirectBySubject != defaultRedirectBySubject {
		t.Fatal("Expected RedirectBySubject:", defaultRedirectBySubject, " result:", *p.RedirectBySubject)
	}
	if *p.Attachment != defaultAttachment {
		t.Fatal("Expected Attachment:", defaultAttachment, " result:", *p.Attachment)
	}
	if *p.Disabled != defaultDisabled {
		t.Fatal("Expected Disabled:", defaultDisabled, " result:", *p.Disabled)
	}
}

func TestProfile_FormatMailTemplate(t *testing.T) {
	type args struct {
		from    string
		subject string
		message string
	}

	assert := func(n int, template, expected string, wantErr bool, args args) {
		profile := &Profile{
			MailTemplate: new(string),
		}
		*profile.MailTemplate = template

		result, err := profile.FormatMailTemplate(args.from, args.subject, args.message)
		gotErr := (err != nil)
		if gotErr != wantErr {
			if gotErr {
				t.Fatal("Test:", n, "Expected Err:", wantErr, " Result Err:", gotErr, " err:", err.Error())
			} else {
				t.Fatal("Test:", n, "Expected Err:", wantErr, " Result Err:", gotErr)
			}
		}
		if result != expected {
			t.Fatal("Test:", n, "Expected:", expected, " Result:", result)
		}
	}

	assert(0, "", "", false, args{from: "", subject: "", message: ""})
	assert(1, ">{{.From}}", ">test@test.com", false, args{from: "test@test.com", subject: "", message: ""})
	assert(2, "{{.From}}{{.Subject}}{{.Message}}", "", false, args{from: "", subject: "", message: ""})
	assert(3, ">{{.From}}, {{.Subject}}, {{.Message}}", ">test@test.com, subject, message", false, args{from: "test@test.com", subject: "subject", message: "message"})
	assert(4, ">{{.Nothing}}", "", true, args{from: "test@test.com", subject: "", message: ""})
	assert(5, ">{{.Noth%ing}}", "", true, args{from: "test@test.com", subject: "", message: ""})
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- ViewPager小圆点 -->
    <bool name="default_circle_indicator_centered">true</bool>
    <color name="default_circle_indicator_fill_color">#FFFFFFFF</color>
    <color name="default_circle_indicator_page_color">#00000000</color>
    <integer name="default_circle_indicator_orientation">0</integer>
    <dimen name="default_circle_indicator_radius">3dp</dimen>
    <bool name="default_circle_indicator_snap">false</bool>
    <color name="default_circle_indicator_stroke_color">#FFDDDDDD</color>
    <dimen name="default_circle_indicator_stroke_width">1dp</dimen>

    <dimen name="default_line_indicator_line_width">12dp</dimen>
    <dimen name="default_line_indicator_gap_width">4dp</dimen>
    <dimen name="default_line_indicator_stroke_width">1dp</dimen>
    <color name="default_line_indicator_selected_color">#FF33B5E5</color>
    <color name="default_line_indicator_unselected_color">#FFBBBBBB</color>
    <bool name="default_line_indicator_centered">true</bool>

    <dimen name="default_title_indicator_clip_padding">4dp</dimen>
    <color name="default_title_indicator_footer_color">#FF33B5E5</color>
    <dimen name="default_title_indicator_footer_line_height">2dp</dimen>
    <integer name="default_title_indicator_footer_indicator_style">2</integer>
    <dimen name="default_title_indicator_footer_indicator_height">4dp</dimen>
    <dimen name="default_title_indicator_footer_indicator_underline_padding">20dp</dimen>
    <dimen name="default_title_indicator_footer_padding">7dp</dimen>
    <integer name="default_title_indicator_line_position">0</integer>
    <color name="default_title_indicator_selected_color">#FFFFFFFF</color>
    <bool name="default_title_indicator_selected_bold">true</bool>
    <color name="default_title_indicator_text_color">#BBFFFFFF</color>
    <dimen name="default_title_indicator_text_size">15dp</dimen>
    <dimen name="default_title_indicator_title_padding">5dp</dimen>
    <dimen name="default_title_indicator_top_padding">7dp</dimen>

    <bool name="default_underline_indicator_fades">true</bool>
    <integer name="default_underline_indicator_fade_delay">300</integer>
    <integer name="default_underline_indicator_fade_length">400</integer>
    <color name="default_underline_indicator_selected_color">#FF33B5E5</color>

    <!-- 刻度的视图 -->
    <color name="red">#FF1014</color>
    <color name="white">#FFFFFF</color>
    <color name="gray">#808080</color>
    <color name="black">#000000</color>
    <color name="blue">#608BDD</color>
    <color name="dark_red">#FF0000</color>
    <color name="orange_red">#EA5624</color>
    <color name="fulltransparent">#00FFFFFF</color>
    <color name="alert_dialog_title">#FF2CA9E8</color>
    <color name="alert_dialog_button_background">#FFF2F2F2</color>
    <color name="alert_dialog_content">#FF494A4C</color>
    <color name="alert_dialog_button_pressed">#FFCDD0d4</color>
    <color name="touming">#00000000</color>
    <color name="touming1">#00110011</color>
    <color name="gray_white">#D8D8D8</color>
    <color name="contents_text">#FF000000</color>
    <color name="encode_view">#FFFFFFFF</color>
    <color name="possible_result_points">#C0FFBD21</color>
    <color name="result_minor_text">#FFC0C0C0</color>
    <color name="result_points">#C099CC00</color>
    <color name="result_text">#FFFFFFFF</color>
    <color name="result_view">#BE000000</color>
    <color name="status_text">#FFFFFFFF</color>
    <color name="transparent">#00000000</color>
    <color name="viewfinder_laser">#FFCC0000</color>
    <color name="viewfinder_mask">#BE000000</color>
    <color name="button_click">#D8A520</color>
    <color name="register_tv_color">#5695D9</color>
    <color name="iamge_bg">#E7EFF8</color>
    <color name="purple_one">#640064</color>
    <color name="purple_two">#7E007E</color>
    <color name="purple_three">#980098</color>
    <color name="purple_four">#B200B2</color>
    <color name="purple_five">#CC00CC</color>
    <color name="blue1">#0000FF</color>
    <color name="blue2">#0000BD</color>
    <color name="blue3">#0000CE</color>
    <color name="blue4">#0000F0</color>
    <color name="blue5">#0202FF</color>
    <color name="blue6">#4646FF</color>
    <color name="blue7">#7171FF</color>
    <color name="transparent_background">#50000000</color>
    <color name="scan">#5695D9</color>
    <color name="exit_notselected">#5695D9</color>
    <color name="exit_selected">#9AD7EA</color>
    <color name="ranking_notselected">#FAFBFD</color>
    <color name="curves_text">#6A7883</color>
    <color name="curves_round">#67B8DE</color>
    <color name="curves_line">#3574B9</color>
    <color name="main_age">#5DA2DA</color>
    <color name="main_round_top">#D9DEE2</color>
    <color name="main_round_center">#E8EDEF</color>
    <color name="main_round_bottom">#F1F7FC</color>
    <color name="rank_ml_normal">#5695D9</color>
    <color name="rank_name_normal">#787878</color>
    <color name="rank_stroke">#6A9BD9</color>
    <color name="health_back">#5695D9</color>
    <color name="health_rank">#7EAEE2</color>
    <color name="temp_top">#4E88D2</color>
    <color name="temp_center">#7888DD</color>
    <color name="temp_bottom">#CB89ED</color>
    <color name="temp_line_other">#9CBED7</color>
    <color name="temp_line_center">#C6DDEF</color>
    <color name="waterdrop_blue">#6899D7</color>
    <color name="WaveColor">#A2C8ED</color>
    <color name="deep_blue">#6ea1e2</color>
    <color name="light_blue">#a2c8ed</color>
    <color name="griditems_bg">#ffe8ecef</color>
    <color name="commo_text_color">#ff333333</color>
    <color name="line">#ffd3dde6</color>
    <color name="public_bg">#f4f4f4</color>
    <color name="main_page_bg">#e9ebec</color>
    <color name="half_transparent">#40000000</color>
    <color name="topbg_green">#00acee</color>
    <color name="tab_light_gray">#939393</color>
    <color name="color_listview">#E1E1E1</color>
    <color name="pink">#F08394</color>
    <color name="gold">#b89766</color>
    <color name="green">#29969c</color>
    <color name="bottle_green">#54B76C</color>
    <color name="re_gray">#AAAAAA</color>
    <color name="re_gray2">#A8A8A8</color>
    <color name="zi_gray">#a5a5a5</color>
    <color name="light_gray">#9D9D9D</color>
    <color name="pressed_gray">#CDCDCD</color>
    <color name="reseda">#f4f4f4</color>
    <color name="driver">#e5e5e5</color>
    <color name="bg_gray">#FFFFFF</color>
    <color name="huise">#6c6c6c</color>
    <color name="light_red">#DD2F2F</color>
    <color name="default1">#448FC4</color>
    <color name="grayness">#898989</color>
    <color name="list_gray">#ffcccccc</color>
    <color name="orange_pressed">#E87A0F</color>

    <color name="default_title_color">#1EADE2</color>

    <drawable name="transparent_none">#00000000</drawable>

    <color name="umeng_fb_color_btn_pressed">#1495F7</color>
    <color name="umeng_fb_color_btn_normal">#333333</color>
    <color name="home_notice_pink">#ffb3b3</color>
    <color name="home_notice_green">#98d6a1</color>
    <color name="home_notice_blue">#9ec5e2</color>
    <color name="home_notice_yellow">#f3cb60</color>
    <color name="btn_gray_normal">#c0c0c0</color>
    <color name="btn_gray_pressed_status">#b5b5b6</color>
    <color name="btn_gray_pressed">#666667</color>
    <color name="btn_blue_normal">#1e90ff</color>
    <color name="btn_blue_pressed">#0066FF</color>
    <color name="orange">#FFA500</color>
    <color name="highlight_money">#92291A</color>
    <color name="blue_light">#ddf3fc</color>
    <color name="ground_light">#f5f5f5</color>
    <color name="text_color">#a5a5a5</color>
    <color name="app_text">#17b421</color>
    <color name="line2">#8B7500</color>
    <color name="line1">#D9D9D9</color>
    <color name="line3">#FFFF00</color>
    <color name="text_color1">#FFFFFF</color>
    <color name="divider_color">#11000000</color>
    <color name="msg_color">#FFFFFFFF</color>
    <color name="dialog_bg">#ffe74c3c</color>
    <color name="btn_press_color">#1c9dd8</color>
    <color name="btn_unpress_color">#48baed</color>
    <color name="text_color_gray">#aaaaaa</color>
    <color name="text_color_green">#54AF6C</color>
    <color name="list_search_color_blue">#00b7ff</color>
    <color name="btn_confirm_normal">#00acee</color>
    <color name="btn_confirm_pressed">#007fc6</color>
    <color name="list_item_background_pressed">#FCFCFC</color>
    <color name="main_black">#333</color>

    <!-- 下拉刷新时,颜色值 -->
    <color name="swiperefresh_color1">#ff00ddff</color>
    <color name="swiperefresh_color2">#ffffbb33</color>
    <color name="swiperefresh_color3">#ffff4444</color>
    <color name="swiperefresh_color4">#ffaa66cc</color>

    <color name="list_divider_color">#DADADA</color>
</resources>


text:
import os
import errno
import uuid

import paddle.v2.master

__all__ = ["save_model", "load_model"]

trainer_id = str(uuid.uuid4())

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

def save_model(parameters, path):
    need_request = "KUBERNETES_SERVICE_HOST" in os.environ.keys()

    if need_request:
        # TODO(helin): figure out how MPI trains, since MPI only save
        # model when trainer_id == "0", we can consolidate the logic
        # here.

        # TODO(helin): change this environment variable name from
        # MASTER_IP to ETCD_IP
        etcd_name = "MASTER_IP"
        if etcd_name not in os.environ.keys():
            raise Exception('not find ' + etcd_name +
                            ' in environment variable.')

        etcd_ip = os.environ.get(etcd_name)
        client = master.client("http://" + etcd_ip + ":2379", 5, 0)
        r = client.request_save_model(trainer_id, 5000)
        if r == 0:
            # do not need to save
            return
        elif r < 0:
            # error
            return
        else:
            # save model
            path = os.path.join(path, trainer_id)
            path = os.path.join(path, "model.tar")

    mkdir_p(path)

    with open(path, 'wb') as f:
        parameters.to_tar(f)

def load_model(parameters, path):
    with open(path, 'rb') as f:
        parameters.from_tar(f)


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('productdb', '0024_auto_20161227_1015'),
    ]

    operations = [
        migrations.AlterField(
            model_name='productcheck',
            name='input_product_ids',
            field=models.CharField(help_text='unordered Product IDs, separated by line breaks or semicolon', max_length=65536, verbose_name='Product ID list'),
        ),
    ]


text:
package com.sdc.play.module.plausc

class AuthException(message: String) extends Exception(message) {
    def this() = this(null)
}

case class AccessDeniedException(providerKey: String) extends AuthException
case class AccessTokenException(message: String) extends AuthException(message) {
    def this() = this(null)
}
case class RedirectUriMismatch() extends AuthException

case class NoOpenIdAuthException(message: String) extends AuthException(message)
case class OpenIdConnectException(message: String) extends AuthException(message)


text: This repository has been merged into [`xp-elements`](https://github.com/expandjs/xp-elements).


text:
import React from 'react';
import './TicTacToe.scss';
import { connect }            from 'react-redux';
import ticTacToeActions from 'actions/tictactoe';

import GameBoard from './components/GameBoard';
import { throttle } from 'lodash';

const mapStateToProps = (state) => {
  return {
    playerTurn: state.tictactoe.playerTurn,
    winner: state.tictactoe.winner,
    playerSigil: state.tictactoe.playerSigil,
    computerSigil: state.tictactoe.computerSigil
  };
};

class TicTacToe extends React.Component {
  static propTypes = {
    playerTurn: React.PropTypes.bool,
    computer_move: React.PropTypes.func,
    winner: React.PropTypes.bool,
    reset_game: React.PropTypes.func,
    player_move: React.PropTypes.func,
    playerSigil: React.PropTypes.string,
    init: React.PropTypes.func

  }

  constructor (props) {
    super(props);
    this.state = {
      gameKey: Date.now(),
      playerSigil: this.props.playerSigil
    };
    this.handleReset = this.handleReset.bind(this);
    this.firstReset = this.firstReset.bind(this);
    this.handleUserClickThrottled = throttle(this.handleUserClick.bind(this), 5000);
    this.throttledComputerMove = throttle(this.computerMove, 5000);
  }

  componentWillReceiveProps (propObj) {
    if (!propObj.winner) {
      if (!propObj.playerTurn) {
        setTimeout(() => {
          this.throttledComputerMove();
          this.handleUserClickThrottled.cancel();
        }, 200);
      }
    }
    // nothing else, the player can't win
  }

  componentWillUnmount () {
    this.props.reset_game();
  }

  computerMove () {
    this.props.computer_move();
  }

  handleUserClick (fun) {
    if (!this.props.winner) {
      fun();
      this.throttledComputerMove.cancel();
    }
  }

  firstReset () {
    this.props.reset_game();
    this.setState({playerSigil: ''});
  }

  handleReset () {
    this.handleUserClickThrottled.cancel();
    this.throttledComputerMove.cancel();
    this.props.reset_game();
    this.props.init({playerSigil: arguments[0]});
    this.setState({gameKey: Date.now(), playerSigil: arguments[0]});
    if (arguments[0] === 'O') {
      setTimeout(() => {
        this.throttledComputerMove();
      }, 200);
    }
  }

  render () {
    let notifier;

    if (this.props.winner.result) {
      const message = this.props.winner.result === 'draw'
              ? 'IT\'S A ' + this.props.winner.result.toUpperCase()
              : this.props.winner.result.toUpperCase().split(/-/).join(' ');
      notifier = (

{message}

            Reset

      );
    }

    if (!this.state.playerSigil) {
      return (

Make your choice...

            Play as X

            Play as O

      );
    } else {
      return (

Tic-Tac-Toe

You can't win

          <GameBoard key={this.state.gameKey}
                     tileClick={this.handleUserClickThrottled}  />

          {notifier}

      );
    }
  }
}

export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);


text:
#include <aws/codecommit/model/SourceFileSpecifier.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace CodeCommit
{
namespace Model
{

SourceFileSpecifier::SourceFileSpecifier() :
    m_filePathHasBeenSet(false),
    m_isMove(false),
    m_isMoveHasBeenSet(false)
{
}

SourceFileSpecifier::SourceFileSpecifier(JsonView jsonValue) :
    m_filePathHasBeenSet(false),
    m_isMove(false),
    m_isMoveHasBeenSet(false)
{
  *this = jsonValue;
}

SourceFileSpecifier& SourceFileSpecifier::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("filePath"))
  {
    m_filePath = jsonValue.GetString("filePath");

    m_filePathHasBeenSet = true;
  }

  if(jsonValue.ValueExists("isMove"))
  {
    m_isMove = jsonValue.GetBool("isMove");

    m_isMoveHasBeenSet = true;
  }

  return *this;
}

JsonValue SourceFileSpecifier::Jsonize() const
{
  JsonValue payload;

  if(m_filePathHasBeenSet)
  {
   payload.WithString("filePath", m_filePath);

  }

  if(m_isMoveHasBeenSet)
  {
   payload.WithBool("isMove", m_isMove);

  }

  return payload;
}

} // namespace Model
} // namespace CodeCommit
} // namespace Aws


text:
var sendHtml = require("send-data/html")

var homePage = require("../templates/home.js")

module.exports = home

function home(req, res) {
    sendHtml(req, res, homePage({ title: "Route seperation example"}))
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\modules\user\models\UserSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'username') ?>

    <?= $form->field($model, 'auth_key') ?>

    <?= $form->field($model, 'password_hash') ?>

    <?= $form->field($model, 'password_reset_token') ?>

    <?php // echo $form->field($model, 'email') ?>

    <?php // echo $form->field($model, 'status') ?>

    <?php // echo $form->field($model, 'created_at') ?>

    <?php // echo $form->field($model, 'updated_at') ?>

    <?php // echo $form->field($model, 'is_admin') ?>

    <?php // echo $form->field($model, 'email_validate_code') ?>

        <?= Html::submitButton(Yii::t('common', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('common', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="yifeiyuan.practice.practicedemos.info.DeviceInfoActivty">
    <item android:id="@+id/action_settings" android:title="@string/action_settings"
        android:orderInCategory="100" app:showAsAction="never" />
</menu>


text:
package org.apache.velocity.test.util.introspection;

import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.test.BaseTestCase;

/**
 * Tests DeprecatedCheckUberspector
 */
public class EnumConstantConversionTestCase extends BaseTestCase {

    public EnumConstantConversionTestCase(String name)
    	throws Exception
    {
        super(name);
    }

    public static Test suite()
    {
        return new TestSuite(EnumConstantConversionTestCase.class);
    }

    public static class Obj
    {
        public enum Color { RED, GREEN }

        public String getAction(Color color)
        {
            switch (color)
            {
                case RED: return "Stop";
                case GREEN: return "Go";
                default: return "???";
            }
        }
    }

    @Override
    protected void setUpContext(VelocityContext context)
    {
        context.put("obj", new Obj());
    }

    public void testStringToEnumConversion()
    	throws Exception
    {
        assertEvalEquals("Stop", "$obj.getAction('RED')");
        assertEvalEquals("Go", "$obj.getAction('GREEN')");
        try
        {
            String result = evaluate("$obj.getAction('BLUE')");
            fail();
        }
        catch(MethodInvocationException mie) {}
    }
}