text:
.home .skyline-container {
    padding-left: 0;
    padding-right: 0
}

.home .value-props {
    background-color: #152740;
    padding-bottom: 3em
}

.home .row-download-typescript {
    padding: 3em 0
}

.home .row-download-typescript ul {
    padding-left: 0
}

.home .row-download-typescript ul>li {
    font-size: 1.6em;
    list-style: none;
    margin-left: -1em;
    padding: 1.5em 1.5em 1.5em 5.5em;
    background-position: 1em 50%;
    background-size: 3em 3em;
    background-repeat: no-repeat
}

.home .row-download-typescript ul .sublime {
    background-image: url(../assets/images/ideicons/sublime-text.svg)
}

.home .row-download-typescript ul .atom {
    background-image: url(../assets/images/ideicons/atom.svg)
}

.home .row-download-typescript ul .eclipse {
    background-image: url(../assets/images/ideicons/eclipse.svg)
}

.home .row-download-typescript ul .vscode {
    background-image: url(../assets/images/ideicons/vscode.svg)
}

.home .row-download-typescript ul .webstorm {
    background-image: url(../assets/images/ideicons/webstorm.svg)
}

.home .row-download-typescript ul .visualstudio-2017 {
    background-image: url(../assets/images/ideicons/visualstudio-2017.svg)
}

.home .row-download-typescript ul .visualstudio-2015 {
    background-image: url(../assets/images/ideicons/visualstudio-2015.svg)
}

.home .row-download-typescript ul .vim {
    background-image: url(../assets/images/ideicons/vim.svg)
}

.home .row-download-typescript ul .emacs {
    background-image: url(../assets/images/ideicons/emacs.svg)
}

.home .row-download-typescript .node-samples {
    margin-right: 2em
}

@media (max-width: 991px) {
    .home .row-download-typescript .node-samples {
        margin-right: 0
    }
}

.home .row-download-typescript .node-samples dd {
    width: 100%;
    height: 2.5em;
    line-height: 2.5em;
    padding-left: .625em;
    white-space: nowrap;
    font-family: Consolas, "Courier New", monospace;
    font-size: 1.6em;
    float: left;
    display: block;
    background-color: #152740;
    color: #fff
}

.home .row-download-typescript .node-samples dt {
    width: 100px;
    text-transform: uppercase;
    padding-top: 17px;
    font-size: 12pt;
    font-weight: 700;
    float: left;
    display: block;
    color: #152740
}

.home .row-download-typescript .dl-link {
    top: 270px;
    height: 34px;
    padding: 0 0 0 60px;
    font-size: 16pt;
    margin: 0;
    display: block;
    background: url(../assets/images/icon_sprite_download_dark.png) 8px 0 no-repeat;
    color: #152740
}

.home .row-download-typescript .others h3 {
    padding-left: .6em
}

.home .twitter-name {
    font-size: 1.2em;
}

.home .twitter-handle {
    font-size: 1em;
    color: grey;
    font-weight: 400;
}

.home .carousel-control {
    width: 8%;
}

.home .next-steps-container {
    margin-top: 0
}

.home .swimlane-alternate {
    background-color: rgba(0, 0, 0, .03)
}

.home .middle-row {
    padding: 2.5em 0 6em
}

.home .middle-row h1 {
    padding-bottom: .6em
}

.home .middle-row p {
    color: #000
}

.home .middle-row h2 {
    padding-top: .5em
}

.home .middle-row .opensource-list {
    text-decoration: none;
    list-style-type: square;
    padding-top: .6em;
    padding-bottom: 1em;
    color: #000
}

.home .middle-row .opensource-list li {
    font-size: .9em
}

.home .bottom-row {
    background-color: #fff;
    padding: 5em 0
}

.home .bottom-row p {
    color: #000
}

.home .bottom-row h1 {
    padding-bottom: .6em
}

.home .swimlane-carousel {
    padding: 20px;
}

.home .swimlane-carousel .container {
    padding: 0;
}

.home .swimlane-carousel .col-sm-12 {
    padding: 0;
}

.home .swimlane-carousel .friend-container {
    margin: 0;
    list-style: none;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-pack: distribute;
    justify-content: space-around;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    height: 200px;
    padding-bottom: 40px;
}

.home .swimlane-carousel .friendbar-content {
    position: relative;
    z-index: 5;
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    left: 30px;
}

.home .swimlane-carousel .friend-info {
    color: #666666;
}

.home .swimlane-carousel .friend-contentcontainer {
    width: 100%;
}

.home .swimlane-carousel .quote-container {
    padding-top: 30px;
}

.home .swimlane-carousel .quote-container p {
    padding: 0px;
}

.home .swimlane-carousel .author-container {
    padding-right: 30px;
    float: right;
}

.home .swimlane-carousel .image-container {
    width: 130px;
    margin-left: 10px;
    margin-right: 20px;
    float: left;
}

.home .swimlane-carousel .friend-item {
    padding: 10px 40px;
    height: 100%;
    color: black;
    margin: 10px 10px;
    line-height: 140px;
    background-color: white;
}

.home .swimlane-carousel .carousel-control.left, .home .swimlane-carousel .carousel-control.right {
    background-image: none;
}

.home .swimlane-carousel .carousel-control span {
    color: lightgray;
    text-shadow: none;
}

.home .swimlane-carousel .carousel-control.left {
    margin-left: -55px;
}

.home .swimlane-carousel .carousel-control.right {
    margin-right: -55px;
}

.home .swimlane-carousel #friend-carousel {
    border-radius: 8px;
}

@media (max-width: 550px) {
    .home .swimlane-carousel .friend-container {
        height: 390px;
    }
    .home .swimlane-carousel .image-container {
        float: none;
        margin: 0 auto;
    }
    .home .swimlane-carousel .author-container {
        float: none;
    }
    .home .swimlane-carousel .friend-item {
        padding: 10px 10px;
    }
    .home .swimlane-carousel .quote-container {
        padding-top: 10px;
    }
}

.home .swimlane-carousel .carousel-inner > .item {
    padding: 10px 5px;
}

.home .swimlane-carousel .carousel-indicators {
    bottom: -4px;
    opacity: 0.4;
    font-size: 30%;
}

.home .swimlane-carousel .carousel-indicators .active {
    width: 12px;
    height: 12px;
    margin: 0;
    background-color: #152740;
}

.home .swimlane-carousel .carousel-indicators li {
    display: inline-block;
    width: 10px;
    height: 10px;
    margin: 1px;
    text-indent: -999px;
    cursor: pointer;
    background-color: #000 \9;
    background-color: transparent;
    border: 1px solid;
    border-color: #152740;
    border-radius: 10px;
}

.home .swimlane-carousel h1 {
    padding: 20px 0 26px 0;
    text-align: center;
}

.home .swimlane-carousel .more-friends p {
    padding: 40px 0 20px 0;
}

.top_section {
    padding-bottom: 2em;
    background: linear-gradient(to bottom, #3CA7F2 0%, #152740 50%);
}

.skyline-img, .skyline-img-background, .skyline-img-foreground {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
    width: 100%;
    height: 100%;
    margin-top: 0em;
    background-size: 150em 32.589em;
    background-repeat: no-repeat;
    background-position: 50% 0;
}

.skyline-img-background {
    background-image: url("../assets/images/bg_blueprint_2.svg");
    background-repeat: repeat-x;
}

.skyline-img-foreground {
    background-image: url("../assets/images/foreground_bluprint.svg");
}

.bannerContainer {
    text-align: center;
    color: white;
    padding: 0;
}

.banner {
    padding-top: 35em;
}

.bannerLogo {
    padding-top: 5em;
    max-width: 34em;
    background-size: cover;
    background-position: top;
    background-repeat: no-repeat;
    text-align: center;
}

.bannerText {
    font-family: wf_segoe-ui_normal;
    font-size: 1em;
    padding: 1em 0;
}

.bannerText > p {
    font-weight: 500;
    padding: 0 3em 0 3em;
}

.bannerTextHeadline {
    color: #FFA700;
    font-size: 2.5em;
    font-weight: lighter;
    padding: 0 1.4em;
    padding-bottom: .5em;
    font-weight: 500;
}

.bannerButtons > .col-sm-4 {
    border-radius: 0;
    padding: 4px;
}

.value-props p {
    color: white;
}

.twitter-profile-image {
    width: 7.2rem;
    height: 7.2rem;
    background-size: 100%;
    background-position: 50% 25%;
    border-radius: 50%;
    box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, 0.2);
    background-image: url(".");
    float: left;
    margin: 20px 10px 75px 0;
}

#social-proof-carousel .col-md-4 {
    padding-left: 5px;
    padding-right: 5px;
}

blockquote.twitter-tweet {
    display: inline-block;
    font-family: "Helvetica Neue", Roboto, "Segoe UI", Calibri, sans-serif;
    font-size: 12px;
    font-weight: bold;
    line-height: 16px;
    border-radius: 0px;
    border-width: 0px;
    margin: 10px 5px;
    padding: 5px 10px 10px 10px;
    max-width: 640px;
    height: 140px;
}

blockquote.twitter-tweet p {
    font-size: 16px;
    font-weight: normal;
    line-height: 20px;
}

blockquote.twitter-tweet a:hover, blockquote.twitter-tweet a:focus {
    text-decoration: underline;
}

.btn {
    border-radius: 0;
    background-color: #FFA700;
    color: #000;
    padding: 10px 16px;
    font-size: 1.6em
}

.bannerButtons .btn {
    width: 12em;
    margin-bottom: 1em
}

.box-headline-img {
    margin-top: 5em
}

.js-icon {
    width: 80px
}

.crane-icon, .soa-icon {
    width: 69px
}

.line {
    display: inline-block
}

.box-text {
    text-align: left;
    padding: 0 7px
}

.middle-box {
    padding: 0
}

.centered {
    text-align: center;
}

.hashtag {
    color: #152740;
}

.box-text>h3 {
    text-align: center;
    font-size: 1.5em;
    padding-bottom: .5em
}

.box-text>h3 span {
    font-size: 1.4em
}

@media (min-width: 767px) {
    #navigation {
        position: fixed
    }
    .video {
        width: 720px;
        height: 405px;
    }
}

@media (max-width: 607px) {
    .navbar-spacer {
        height: 5em
    }
}

.container-fluid>.container-fluid {
    padding-left: 0;
    padding-right: 0
}

.girder-background {
    background-image: url(../assets/images/girder_repeat-x.svg);
    background-size: 63.1px 18px;
    background-repeat: repeat-x;
    background-position: 50% 50%;
    margin-top: 6em;
    margin-bottom: 2em
}

.girder-background .btn {
    min-width: 14em
}

.video {
    display: block;
    margin: 20px auto;
    margin-top: 10px;
}

.next-steps-container {
    background-color: #e6e6e6;
    padding: 5em 0;
    margin-top: 4em;
    color: #0c3645;
    width: 100%
}

.next-steps-container .row>div .content {
    padding: .7em 2em .7em .7em;
    font-size: 1.6em;
    line-height: 1.6em
}

.next-steps-container .row>div .next-step-link {
    font-size: 2.2em;
    color: #0c3645
}

.next-steps-container .row>div .next-step-link span {
    font-size: 1em
}

.next-steps-container .row>div .next-step-header {
    font-size: 2.25em;
    color: #0c3645;
    padding-left: .4em
}

.next-steps-container .row>div:nth-child(1) .spacer, .next-steps-container .row>div:nth-child(2) .spacer {
    padding: 0 6em
}

.next-steps-container .row>div:nth-child(2) .separator {
    padding: 0 3em;
    border-left: 1px solid #bbb;
    width: 2px;
    height: 14em;
    float: left
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<databaseChangeLog logicalFilePath="dummy" xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">

    <changeSet logicalFilePath="dummy" author="dvoet" id="billing_role">
        <addColumn tableName="PROJECT_USERS">
            <column name="ROLE" defaultValue="User" type="varchar(20)"><constraints nullable="false"/></column>
        </addColumn>
    </changeSet>

</databaseChangeLog>

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.cmdline;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.cmdline.LabelValidator.BadLabelException;
import com.google.devtools.build.lib.cmdline.LabelValidator.PackageAndTarget;
import com.google.devtools.build.lib.util.BatchCallback;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.util.StringUtilities;
import com.google.devtools.build.lib.vfs.PathFragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

import javax.annotation.concurrent.Immutable;

/**
 * Represents a target pattern. Target patterns are a generalization of labels to include
 * wildcards for finding all packages recursively beneath some root, and for finding all targets
 * within a package.
 *
 *
Note that this class does not handle negative patterns ("-//foo/bar"); these must be handled
 * one level up. In particular, the query language comes with built-in support for negative
 * patterns.
 *
 *
In order to resolve target patterns, you need an implementation of {@link
 * TargetPatternResolver}. This class is thread-safe if the corresponding instance is thread-safe.
 *
 *
See lib/blaze/commands/target-syntax.txt for details.
 */
public abstract class TargetPattern implements Serializable {

  private static final Splitter SLASH_SPLITTER = Splitter.on('/');
  private static final Joiner SLASH_JOINER = Joiner.on('/');

  private static final Parser DEFAULT_PARSER = new Parser("");

  private final Type type;
  private final String originalPattern;
  private final String offset;

  /**
   * Returns a parser with no offset. Note that the Parser class is immutable, so this method may
   * return the same instance on subsequent calls.
   */
  public static Parser defaultParser() {
    return DEFAULT_PARSER;
  }

  private static String removeSuffix(String s, String suffix) {
    if (s.endsWith(suffix)) {
      return s.substring(0, s.length() - suffix.length());
    } else {
      throw new IllegalArgumentException(s + ", " + suffix);
    }
  }

  /**
   * Normalizes the given relative path by resolving {@code //}, {@code /./} and {@code x/../}
   * pieces. Note that leading {@code ".."} segments are not removed, so the returned string can
   * have leading {@code ".."} segments.
   *
   * @throws IllegalArgumentException if the path is absolute, i.e. starts with a @{code '/'}
   */
  @VisibleForTesting
  static String normalize(String path) {
    Preconditions.checkArgument(!path.startsWith("/"));
    Preconditions.checkArgument(!path.startsWith("@"));
    Iterator<String> it = SLASH_SPLITTER.split(path).iterator();
    List<String> pieces = new ArrayList<>();
    while (it.hasNext()) {
      String piece = it.next();
      if (".".equals(piece) || piece.isEmpty()) {
        continue;
      }
      if ("..".equals(piece)) {
        if (pieces.isEmpty()) {
          pieces.add(piece);
          continue;
        }
        String predecessor = pieces.remove(pieces.size() - 1);
        if ("..".equals(predecessor)) {
          pieces.add(piece);
          pieces.add(piece);
        }
        continue;
      }
      pieces.add(piece);
    }
    return SLASH_JOINER.join(pieces);
  }

  private TargetPattern(Type type, String originalPattern, String offset) {
    // Don't allow inheritance outside this class.
    this.type = type;
    this.originalPattern = Preconditions.checkNotNull(originalPattern);
    this.offset = Preconditions.checkNotNull(offset);
  }

  /**
   * Return the type of the pattern. Examples include "below directory" like "foo/..." and "single
   * target" like "//x:y".
   */
  public Type getType() {
    return type;
  }

  /**
   * Return the string that was parsed into this pattern.
   */
  public String getOriginalPattern() {
    return originalPattern;
  }

  /**
   * Return the offset this target pattern was parsed with.
   */
  public String getOffset() {
    return offset;
  }

  /**
   * Evaluates the current target pattern and returns the result.
   */
  public <T, E extends Exception> void eval(
      TargetPatternResolver<T> resolver, BatchCallback<T, E> callback, Class<E> exceptionClass)
      throws TargetParsingException, E, InterruptedException {
    eval(resolver, ImmutableSet.<PathFragment>of(), callback, exceptionClass);
  }

  /**
   * Evaluates the current target pattern, excluding targets under directories in
   * {@code excludedSubdirectories}, and returns the result.
   *
   * @throws IllegalArgumentException if {@code excludedSubdirectories} is nonempty and this
   *      pattern does not have type {@code Type.TARGETS_BELOW_DIRECTORY}.
   */
  public abstract <T, E extends Exception> void eval(
      TargetPatternResolver<T> resolver,
      ImmutableSet<PathFragment> excludedSubdirectories,
      BatchCallback<T, E> callback, Class<E> exceptionClass)
      throws TargetParsingException, E, InterruptedException;

  /**
   * Returns {@code true} iff this pattern has type {@code Type.TARGETS_BELOW_DIRECTORY} and
   * {@code directory} is contained by or equals this pattern's directory. For example,
   * returns {@code true} for {@code this = TargetPattern ("//...")} and {@code directory
   * = "foo")}.
   */
  public abstract boolean containsBelowDirectory(PackageIdentifier directory);

  /**
   * Shorthand for {@code containsBelowDirectory(containedPattern.getDirectory())}.
   */
  public boolean containsBelowDirectory(TargetPattern containedPattern) {
    return containsBelowDirectory(containedPattern.getDirectory());
  }

  /**
   * Returns a {@link PackageIdentifier} identifying the most specific containing directory of the
   * patterns that could be matched by this pattern.
   *
   *
Note that we are using the {@link PackageIdentifier} type as a convenience; there may not
   * actually be a package corresponding to this directory!
   *
   *
For patterns of type {@code Type.TARGETS_BELOW_DIRECTORY}, this returns a
   * {@link PackageIdentifier} that identifies the referred-to directory. For example, for a
   * {@code Type.TARGETS_BELOW_DIRECTORY} corresponding to "//foo/bar/...", this method returns a
   * {@link PackageIdentifier} for "foo/bar".
   */
  public abstract PackageIdentifier getDirectory();

  /**
   * Returns {@code true} iff this pattern has type {@code Type.TARGETS_BELOW_DIRECTORY} or
   * {@code Type.TARGETS_IN_PACKAGE} and the target pattern suffix specified it should match
   * rules only.
   */
  public abstract boolean getRulesOnly();

  private static final class SingleTarget extends TargetPattern {

    private final String targetName;
    private final PackageIdentifier directory;

    private SingleTarget(
        String targetName, PackageIdentifier directory, String originalPattern, String offset) {
      super(Type.SINGLE_TARGET, originalPattern, offset);
      this.targetName = Preconditions.checkNotNull(targetName);
      this.directory = Preconditions.checkNotNull(directory);
    }

    @Override
    public <T, E extends Exception> void eval(
        TargetPatternResolver<T> resolver,
        ImmutableSet<PathFragment> excludedSubdirectories,
        BatchCallback<T, E> callback, Class<E> exceptionClass)
        throws TargetParsingException, E, InterruptedException {
      Preconditions.checkArgument(excludedSubdirectories.isEmpty(),
          "Target pattern \"%s\" of type %s cannot be evaluated with excluded subdirectories: %s.",
          getOriginalPattern(), getType(), excludedSubdirectories);
      callback.process(resolver.getExplicitTarget(label(targetName)).getTargets());
    }

    @Override
    public boolean containsBelowDirectory(PackageIdentifier directory) {
      return false;
    }

    @Override
    public PackageIdentifier getDirectory() {
      return directory;
    }

    @Override
    public boolean getRulesOnly() {
      return false;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (!(o instanceof SingleTarget)) {
        return false;
      }
      SingleTarget that = (SingleTarget) o;
      return targetName.equals(that.targetName) && directory.equals(that.directory);
    }

    @Override
    public int hashCode() {
      return Objects.hash(getType(), targetName, directory);
    }
  }

  private static final class InterpretPathAsTarget extends TargetPattern {

    private final String path;

    private InterpretPathAsTarget(String path, String originalPattern, String offset) {
      super(Type.PATH_AS_TARGET, originalPattern, offset);
      this.path = normalize(Preconditions.checkNotNull(path));
    }

    @Override
    public <T, E extends Exception> void eval(
        TargetPatternResolver<T> resolver,
        ImmutableSet<PathFragment> excludedSubdirectories,
        BatchCallback<T, E> callback, Class<E> exceptionClass)
        throws TargetParsingException, E, InterruptedException {
      Preconditions.checkArgument(excludedSubdirectories.isEmpty(),
          "Target pattern \"%s\" of type %s cannot be evaluated with excluded subdirectories: %s.",
          getOriginalPattern(), getType(), excludedSubdirectories);
      if (resolver.isPackage(PackageIdentifier.createInMainRepo(path))) {
        // User has specified a package name. lookout for default target.
        callback.process(resolver.getExplicitTarget(label("//" + path)).getTargets());
      } else {

        List<String> pieces = SLASH_SPLITTER.splitToList(path);

        // Interprets the label as a file target.  This loop stops as soon as the
        // first BUILD file is found (i.e. longest prefix match).
        for (int i = pieces.size() - 1; i >= 0; i--) {
          String packageName = SLASH_JOINER.join(pieces.subList(0, i));
          if (resolver.isPackage(PackageIdentifier.createInMainRepo(packageName))) {
            String targetName = SLASH_JOINER.join(pieces.subList(i, pieces.size()));
            callback.process(
                resolver
                    .getExplicitTarget(label("//" + packageName + ":" + targetName))
                    .getTargets());
            return;
          }
        }

        throw new TargetParsingException("couldn't determine target from filename '" + path + "'");
      }
    }

    @Override
    public boolean containsBelowDirectory(PackageIdentifier directory) {
      return false;
    }

    @Override
    public PackageIdentifier getDirectory() {
      int lastSlashIndex = path.lastIndexOf('/');
      // The package name cannot be illegal because we verified it during target parsing
      return PackageIdentifier.createInMainRepo(
          lastSlashIndex < 0 ? "" : path.substring(0, lastSlashIndex));
    }

    @Override
    public boolean getRulesOnly() {
      return false;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (!(o instanceof InterpretPathAsTarget)) {
        return false;
      }
      InterpretPathAsTarget that = (InterpretPathAsTarget) o;
      return path.equals(that.path);
    }

    @Override
    public int hashCode() {
      return Objects.hash(getType(), path);
    }
  }

  private static final class TargetsInPackage extends TargetPattern {

    private final PackageIdentifier packageIdentifier;
    private final String suffix;
    private final boolean wasOriginallyAbsolute;
    private final boolean rulesOnly;
    private final boolean checkWildcardConflict;

    private TargetsInPackage(String originalPattern, String offset,
        PackageIdentifier packageIdentifier, String suffix, boolean wasOriginallyAbsolute,
        boolean rulesOnly, boolean checkWildcardConflict) {
      super(Type.TARGETS_IN_PACKAGE, originalPattern, offset);
      Preconditions.checkArgument(!packageIdentifier.getRepository().isDefault());
      this.packageIdentifier = packageIdentifier;
      this.suffix = Preconditions.checkNotNull(suffix);
      this.wasOriginallyAbsolute = wasOriginallyAbsolute;
      this.rulesOnly = rulesOnly;
      this.checkWildcardConflict = checkWildcardConflict;
    }

    @Override
    public <T, E extends Exception> void eval(
        TargetPatternResolver<T> resolver,
        ImmutableSet<PathFragment> excludedSubdirectories,
        BatchCallback<T, E> callback, Class<E> exceptionClass)
        throws TargetParsingException, E, InterruptedException {
      Preconditions.checkArgument(excludedSubdirectories.isEmpty(),
          "Target pattern \"%s\" of type %s cannot be evaluated with excluded subdirectories: %s.",
          getOriginalPattern(), getType(), excludedSubdirectories);
      if (checkWildcardConflict) {
        ResolvedTargets<T> targets = getWildcardConflict(resolver);
        if (targets != null) {
          callback.process(targets.getTargets());
          return;
        }
      }

      callback.process(
          resolver
              .getTargetsInPackage(getOriginalPattern(), packageIdentifier, rulesOnly)
              .getTargets());
    }

    @Override
    public boolean containsBelowDirectory(PackageIdentifier directory) {
      return false;
    }

    @Override
    public PackageIdentifier getDirectory() {
      return packageIdentifier;
    }

    @Override
    public boolean getRulesOnly() {
      return rulesOnly;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (!(o instanceof TargetsInPackage)) {
        return false;
      }
      TargetsInPackage that = (TargetsInPackage) o;
      return wasOriginallyAbsolute == that.wasOriginallyAbsolute && rulesOnly == that.rulesOnly
          && checkWildcardConflict == that.checkWildcardConflict
          && getOriginalPattern().equals(that.getOriginalPattern())
          && packageIdentifier.equals(that.packageIdentifier) && suffix.equals(that.suffix);
    }

    @Override
    public int hashCode() {
      return Objects.hash(getType(), getOriginalPattern(), packageIdentifier, suffix,
          wasOriginallyAbsolute, rulesOnly, checkWildcardConflict);
    }

    /**
     * There's a potential ambiguity if '//foo/bar:all' refers to an actual target. In this case, we
     * use the the target but print a warning.
     *
     * @return the Target corresponding to the given pattern, if the pattern is absolute and there
     *         is such a target. Otherwise, return null.
     */
    private <T> ResolvedTargets<T> getWildcardConflict(TargetPatternResolver<T> resolver)
        throws InterruptedException {
      if (!wasOriginallyAbsolute) {
        return null;
      }

      T target;
      Label label;
      try {
        label = Label.create(packageIdentifier, suffix);
        target = resolver.getTargetOrNull(label);
      } catch (LabelSyntaxException e) {
        return null;
      }

      if (target != null) {
        resolver.warn(String.format("The target pattern '%s' is ambiguous: '%s' is " +
                                    "both a wildcard, and the name of an existing %s; " +
                                    "using the latter interpretation",
                                    getOriginalPattern(), ":" + suffix,
                                    resolver.getTargetKind(target)));
        try {
          return resolver.getExplicitTarget(label);
        } catch (TargetParsingException e) {
          throw new IllegalStateException(
              "getTargetOrNull() returned non-null, so target should exist", e);
        }
      }
      return null;
    }
  }

  private static final class TargetsBelowDirectory extends TargetPattern {

    private final PackageIdentifier directory;
    private final boolean rulesOnly;

    private TargetsBelowDirectory(
        String originalPattern, String offset, PackageIdentifier directory, boolean rulesOnly) {
      super(Type.TARGETS_BELOW_DIRECTORY, originalPattern, offset);
      Preconditions.checkArgument(!directory.getRepository().isDefault());
      this.directory = Preconditions.checkNotNull(directory);
      this.rulesOnly = rulesOnly;
    }

    @Override
    public <T, E extends Exception> void eval(
        TargetPatternResolver<T> resolver,
        ImmutableSet<PathFragment> excludedSubdirectories,
        BatchCallback<T, E> callback, Class<E> exceptionClass)
        throws TargetParsingException, E, InterruptedException {
      resolver.findTargetsBeneathDirectory(
          directory.getRepository(),
          getOriginalPattern(),
          directory.getPackageFragment().getPathString(),
          rulesOnly,
          excludedSubdirectories,
          callback,
          exceptionClass);
    }

    @Override
    public boolean containsBelowDirectory(PackageIdentifier containedDirectory) {
      // Note that merely checking to see if the directory startsWith the TargetsBelowDirectory's
      // directory is insufficient. "food" begins with "foo", but "//foo/..." does not contain
      // "//food/...".
      return containedDirectory.getRepository().equals(directory.getRepository())
          && containedDirectory.getPackageFragment().startsWith(directory.getPackageFragment());
    }

    @Override
    public PackageIdentifier getDirectory() {
      return directory;
    }

    @Override
    public boolean getRulesOnly() {
      return rulesOnly;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (!(o instanceof TargetsBelowDirectory)) {
        return false;
      }
      TargetsBelowDirectory that = (TargetsBelowDirectory) o;
      return rulesOnly == that.rulesOnly && getOriginalPattern().equals(that.getOriginalPattern())
          && directory.equals(that.directory);
    }

    @Override
    public int hashCode() {
      return Objects.hash(getType(), getOriginalPattern(), directory, rulesOnly);
    }
  }

  @Immutable
  public static final class Parser {
    // A valid pattern either starts with exactly 0 slashes (relative pattern) or exactly two
    // slashes (absolute pattern).
    private static final Pattern VALID_SLASH_PREFIX = Pattern.compile("(//)?([^/]|$)");

    // TODO(bazel-team): Merge the Label functionality that requires similar constants into this
    // class.
    /**
     * The set of target-pattern suffixes which indicate wildcards over all rules in a
     * single package.
     */
    private static final List<String> ALL_RULES_IN_SUFFIXES = ImmutableList.of(
        "all");

    /**
     * The set of target-pattern suffixes which indicate wildcards over all targets in a
     * single package.
     */
    private static final List<String> ALL_TARGETS_IN_SUFFIXES = ImmutableList.of(
        "*",
        "all-targets");

    private static final List<String> SUFFIXES;

    static {
      SUFFIXES = ImmutableList.<String>builder()
          .addAll(ALL_RULES_IN_SUFFIXES)
          .addAll(ALL_TARGETS_IN_SUFFIXES)
          .add("/...")
          .build();
    }

    /**
     * Returns whether the given pattern is simple, i.e., not starting with '-' and using none of
     * the target matching suffixes.
     */
    public static boolean isSimpleTargetPattern(String pattern) {
      if (pattern.startsWith("-")) {
        return false;
      }

      for (String suffix : SUFFIXES) {
        if (pattern.endsWith(":" + suffix)) {
          return false;
        }
      }
      return true;
    }

    /**
     * Directory prefix to use when resolving relative labels (rather than absolute ones). For
     * example, if the working directory is "<workspace root>/foo", then this should be "foo",
     * which will make patterns such as "bar:bar" be resolved as "//foo/bar:bar". This makes the
     * command line a bit more convenient to use.
     */
    private final String relativeDirectory;

    /**
     * Creates a new parser with the given offset for relative patterns.
     */
    public Parser(String relativeDirectory) {
      this.relativeDirectory = relativeDirectory;
    }

    /**
     * Parses the given pattern, and throws an exception if the pattern is invalid.
     *
     * @return a target pattern corresponding to the pattern parsed
     * @throws TargetParsingException if the pattern is invalid
     */
    public TargetPattern parse(String pattern) throws TargetParsingException {
      // The structure of this method is by cases, according to the usage string
      // constant (see lib/blaze/commands/target-syntax.txt).

      String originalPattern = pattern;
      final boolean includesRepo = pattern.startsWith("@");
      RepositoryName repository = null;
      if (includesRepo) {
        int pkgStart = pattern.indexOf("//");
        if (pkgStart < 0) {
          throw new TargetParsingException("Couldn't find package in target " + pattern);
        }
        try {
          repository = RepositoryName.create(pattern.substring(0, pkgStart));
        } catch (LabelSyntaxException e) {
          throw new TargetParsingException(e.getMessage());
        }

        pattern = pattern.substring(pkgStart);
      }

      if (!VALID_SLASH_PREFIX.matcher(pattern).lookingAt()) {
        throw new TargetParsingException("not a valid absolute pattern (absolute target patterns "
            + "must start with exactly two slashes): '" + pattern + "'");
      }

      final boolean wasOriginallyAbsolute = pattern.startsWith("//");
      // We now ensure the relativeDirectory is applied to relative patterns.
      pattern = absolutize(pattern).substring(2);

      if (pattern.isEmpty()) {
        throw new TargetParsingException("the empty string is not a valid target");
      }

      // Transform "/BUILD" suffix into ":BUILD" to accept //foo/bar/BUILD
      // syntax as a synonym to //foo/bar:BUILD.
      if (pattern.endsWith("/BUILD")) {
        pattern = pattern.substring(0, pattern.length() - 6) + ":BUILD";
      }

      int colonIndex = pattern.lastIndexOf(':');
      String packagePart = colonIndex < 0 ? pattern : pattern.substring(0, colonIndex);
      String targetPart = colonIndex < 0 ? "" : pattern.substring(colonIndex + 1);

      if (packagePart.equals("...")) {
        packagePart = "/...";  // special case this for easier parsing
      }

      if (packagePart.endsWith("/")) {
        throw new TargetParsingException("The package part of '" + originalPattern
            + "' should not end in a slash");
      }

      if (repository == null) {
        repository = RepositoryName.MAIN;
      }

      if (packagePart.endsWith("/...")) {
        String realPackagePart = removeSuffix(packagePart, "/...");
        PackageIdentifier packageIdentifier;
        try {
          packageIdentifier = PackageIdentifier.parse(
              repository.getName() + "//" + realPackagePart);
        } catch (LabelSyntaxException e) {
          throw new TargetParsingException(
              "Invalid package name '" + realPackagePart + "': " + e.getMessage());
        }
        if (targetPart.isEmpty() || ALL_RULES_IN_SUFFIXES.contains(targetPart)) {
          return new TargetsBelowDirectory(
              originalPattern, relativeDirectory, packageIdentifier, true);
        } else if (ALL_TARGETS_IN_SUFFIXES.contains(targetPart)) {
          return new TargetsBelowDirectory(
              originalPattern, relativeDirectory, packageIdentifier, false);
        }
      }

      if (ALL_RULES_IN_SUFFIXES.contains(targetPart)) {
        PackageIdentifier packageIdentifier;
        try {
          packageIdentifier = PackageIdentifier.parse(repository.getName() + "//" + packagePart);
        } catch (LabelSyntaxException e) {
          throw new TargetParsingException(
              "Invalid package name '" + packagePart + "': " + e.getMessage());
        }
        return new TargetsInPackage(originalPattern, relativeDirectory, packageIdentifier,
            targetPart, wasOriginallyAbsolute, true, true);
      }

      if (ALL_TARGETS_IN_SUFFIXES.contains(targetPart)) {
        PackageIdentifier packageIdentifier;
        try {
          packageIdentifier = PackageIdentifier.parse(repository.getName() + "//" + packagePart);
        } catch (LabelSyntaxException e) {
          throw new TargetParsingException(
              "Invalid package name '" + packagePart + "': " + e.getMessage());
        }
        return new TargetsInPackage(originalPattern, relativeDirectory, packageIdentifier,
            targetPart, wasOriginallyAbsolute, false, true);
      }

      if (includesRepo || wasOriginallyAbsolute || pattern.contains(":")) {
        PackageIdentifier packageIdentifier;
        String fullLabel = repository.getName() + "//" + pattern;
        try {
          PackageAndTarget packageAndTarget = LabelValidator.validateAbsoluteLabel(fullLabel);
          packageIdentifier = PackageIdentifier.create(repository,
              new PathFragment(packageAndTarget.getPackageName()));
        } catch (BadLabelException e) {
          String error = "invalid target format '" + originalPattern + "': " + e.getMessage();
          throw new TargetParsingException(error);
        }
        return new SingleTarget(
            fullLabel, packageIdentifier, originalPattern, relativeDirectory);
      }

      // This is a stripped-down version of interpretPathAsTarget that does no I/O.  We have a basic
      // relative path. e.g. "foo/bar/Wiz.java". The strictest correct check we can do here (without
      // I/O) is just to ensure that there is *some* prefix that is a valid package-name. It's
      // sufficient to test the first segment. This is really a rather weak check; perhaps we should
      // just eliminate it.
      int slashIndex = pattern.indexOf('/');
      String packageName = pattern;
      if (slashIndex > 0) {
        packageName = pattern.substring(0, slashIndex);
      }
      try {
        PackageIdentifier.parse("//" + packageName);
      } catch (LabelSyntaxException e) {
        throw new TargetParsingException(
            "Bad target pattern '" + originalPattern + "': " + e.getMessage());
      }
      return new InterpretPathAsTarget(pattern, originalPattern, relativeDirectory);
    }

    /**
     * Absolutizes the target pattern to the offset.
     * Patterns starting with "//" are absolute and not modified.
     * Assumes the given pattern is not invalid wrt leading "/"s.
     *
     * If the offset is "foo":
     *   absolutize(":bar") --> "//foo:bar"
     *   absolutize("bar") --> "//foo/bar"
     *   absolutize("//biz/bar") --> "//biz/bar" (absolute)
     *   absolutize("biz:bar") --> "//foo/biz:bar"
     *
     * @param pattern The target pattern to parse.
     * @return the pattern, absolutized to the offset if approprate.
     */
    public String absolutize(String pattern) {
      if (pattern.startsWith("//")) {
        return pattern;
      }

      // It seems natural to use {@link PathFragment#getRelative()} here,
      // but it doesn't work when the pattern starts with ":".
      // "foo".getRelative(":all") would return "foo/:all", where we
      // really want "foo:all".
      return pattern.startsWith(":") || relativeDirectory.isEmpty()
          ? "//" + relativeDirectory + pattern
          : "//" + relativeDirectory + "/" + pattern;
    }
  }

  // Parse 'label' as a Label, mapping LabelSyntaxException into
  // TargetParsingException.
  private static Label label(String label) throws TargetParsingException {
    try {
      return Label.parseAbsolute(label);
    } catch (LabelSyntaxException e) {
      throw new TargetParsingException("invalid target format: '"
          + StringUtilities.sanitizeControlChars(label) + "'; "
          + StringUtilities.sanitizeControlChars(e.getMessage()));
    }
  }

  /**
   * The target pattern type (targets below package, in package, explicit target, etc.)
   */
  public enum Type {
    /** A path interpreted as a target, eg "foo/bar/baz" */
    PATH_AS_TARGET,
    /** An explicit target, eg "//foo:bar." */
    SINGLE_TARGET,
    /** Targets below a directory, eg "foo/...". */
    TARGETS_BELOW_DIRECTORY,
    /** Target in a package, eg "foo:all". */
    TARGETS_IN_PACKAGE;
  }
}


text:
```mysql
CREATE DATABASE WoIstDerWagen
CREATE USER 'WoIstDerWagen'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON `WoIstDerWagen` . * TO 'WoIstDerWagen'@'localhost';
FLUSH PRIVILEGES;
```

## Download data from OpenDataPortal and unzip it

```bash
wget http://download-data.deutschebahn.com/static/datasets/wagenstand/Wagenreihungsplan_RawData_20160617.zip
unzip Wagenreihungsplan_RawData_20160617.zip
```

## Import data to database

### Plain data import
```bash
./stations2mysql.rb localhost WoIstDerWagen password WoIstDerWagen
./trains2mysql.rb localhost WoIstDerWagen password WoIstDerWagen
```

This will create: 6560 stations, 14808 train and 172415 waggon entiers.

### Optional: Save the datatabse
```bash
mysqldump -uWoIstDerWagen -ppassword WoIstDerWagen >dump-raw.sql
```

### Prepare the data and remove uggly data.
```bash
mysql -uWoIstDerWagen -ppassword WoIstDerWagen <prepare_db.sql
```

After this step there will be 6560 stations, 13246 train and 153938 waggon entiers.

### Optional: Save the datatabse
```bash
mysqldump -uWoIstDerWagen -ppassword WoIstDerWagen >dump-work.sql
```

(Please not that it is not relay good that we transport the database password in the command line, so perhabs do this on your development machine and afterwards do a database dump and put it to your productional machine)

## Weblinks

http://data.deutschebahn.com/dataset/data-wagenreihungsplan-soll-daten


text:
package com.gc.bordermenu.views;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.BounceInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.RelativeLayout;

import com.gc.bordermenu.activities.BorderMenuActivity;
import com.gc.bordermenu.utils.Utils;

public abstract class MenuItem extends RelativeLayout{

	public int id;
	BorderMenuActivity borderMenuActivity;
	int rippleColor = Color.parseColor("#88FFFFFF");
	int radius = 0;
	int x = -1,y = -1;
	int rippleSpeed;

	MenuItem nexItem;

	public MenuItem(BorderMenuActivity borderMenuActivity,int id) {
		super(borderMenuActivity);
		this.borderMenuActivity = borderMenuActivity;
		this.id = id;
		rippleSpeed = Utils.dpToPx(5, getResources());
		setVisibility(View.INVISIBLE);
		setWillNotDraw(false);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			if ((event.getX() <= getWidth() && event.getX() >= 0)
					&& (event.getY() <= getHeight() && event.getY() >= 0)) {
				x = getWidth() / 2;
				y = getHeight() / 2;
				radius = getWidth() / 4;
			}else{
				x = y = -1;
			}
		}
			return true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if(x != -1){
			radius += rippleSpeed;
			Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setColor(rippleColor);
			canvas.drawCircle(x, y, radius, paint);
		}
		invalidate();
	}

	/**
	 * Change color of push effect
	 * @param rippleColor
	 */
	public void setRippleColor(int rippleColor){
		this.rippleColor = rippleColor;
	}

	public void setNextItem(MenuItem nexItem){
		this.nexItem = nexItem;
	}

	public void show(){
		setVisibility(View.VISIBLE);
		ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1,getWidth() / 2, getHeight() / 2);
		scaleAnimation.setDuration(300);
		scaleAnimation.setInterpolator(new BounceInterpolator());
		scaleAnimation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				if(nexItem != null)
					nexItem.show();
			}
		});
		startAnimation(scaleAnimation);
	}

	public void hide(){
		ScaleAnimation scaleAnimation = new ScaleAnimation(1, 0, 1, 0,getWidth() / 2, getHeight() / 2);
		scaleAnimation.setDuration(300);
		scaleAnimation.setInterpolator(new BounceInterpolator());
		scaleAnimation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
				setVisibility(View.INVISIBLE);
			}
		});
		startAnimation(scaleAnimation);
	}

}


text: export { default } from './StatusLabel';


text:
var url = require("url");

module.exports = {
	init: function() {
		this.ALLOWED_DOMAINS = (process.env.ALLOWED_DOMAINS && process.env.ALLOWED_DOMAINS.split(',')) || [];
	},
    beforePhantomRequest: function(req, res, next) {
        var parsed = url.parse(req.prerender.url);

        if(this.ALLOWED_DOMAINS.indexOf(parsed.hostname) > -1) {
            next();
        } else {
            res.send(404);
        }
    }
}


text: <!DOCTYPE html>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NAverage;

namespace UnitTests.Averages
{
    [TestClass]
    public class GeometricMeanTest
    {
        private readonly double _epsilon;

        public GeometricMeanTest()
        {
            _epsilon = 0.0001;
        }

        [TestMethod]
        public void TestGeometricMeanOf3And30()
        {
            double[] numbers = { 3, 300 };

            double calculatedGeometricMean = numbers.GeometricMean();

            Assert.AreEqual(30, calculatedGeometricMean);
        }

        [TestMethod]
        public void TestGeometricMeanOfRange1To10()
        {
            IEnumerable<double> numbers =
                from number in Enumerable.Range(1, 10)
                select Convert.ToDouble(number);

            double calculatedValue = numbers.GeometricMean();
            const double expectedValue = 4.528728688;
            double differenceBetweenExpectedAndCalculatedValue = Math.Abs(expectedValue - calculatedValue);

            Assert.IsTrue(differenceBetweenExpectedAndCalculatedValue < _epsilon);
        }

        [TestMethod]
        public void TestGeometricMeanOfSingleNumberEqualsTheNumber()
        {
            // Use an arbitrary seed to achieve determinated behaviour
            Random random = new Random(1337);

            for (int i = 0; i < 50; i++)
            {
                double numberToTest = random.Next();
                double[] singleNumberCollection = { numberToTest };

                double calculatedGeometricMean = singleNumberCollection.GeometricMean();

                Assert.AreEqual(numberToTest, calculatedGeometricMean);
            }
        }

        [TestMethod]
        public void TestGeometricMeanOfNullCollectionThrowsNullArgumentException()
        {
            ExceptionAssert.Throws<ArgumentNullException>(CallGeometricMeanWithNullCollection);
        }

        private static void CallGeometricMeanWithNullCollection()
        {
            double[] emptyNumbersArray = null;
            emptyNumbersArray.GeometricMean();
        }

        [TestMethod]
        public void TestGeometricMeanOfEmptyNumbersArrayThrowsInvalidOperationException()
        {
            ExceptionAssert.Throws<InvalidOperationException>(CallGeometicMeanWithEmptyNumbersArray);
        }

        private static void CallGeometicMeanWithEmptyNumbersArray()
        {
            double[] emptyNumbersArray = { };
            emptyNumbersArray.GeometricMean();
        }

        [TestMethod]
        public void TestGeometricMeanOfCollectionContainingNegativeNumbersThrowsInvalidOperationException()
        {
            ExceptionAssert.Throws<InvalidOperationException>(CallGeometicMeanWithNegativeNumbersCollection);
        }

        private static void CallGeometicMeanWithNegativeNumbersCollection()
        {
            double[] collectionContainingNegativeNumbers = { 1, 2, 3, -4, 5 };
            collectionContainingNegativeNumbers.GeometricMean();
        }
    }
}


text:
Extract HJSON front matter from a string.

[HJSON](https://hjson.org/) is a human-friendly superset of JSON that has some sweet syntactic sugars and multiline strings, which is great! Don't worry, it's not going to overthrow JSON and, yes, we shouldn't encourage developers to slack off in writing proper code with proper commas. *However, there are some use cases where HJSON just makes sense.* For instance, I think it's a nicer (easier) markup for front matter than YAML when using templating libraries.

## Install
```shell
npm install hjson-matter
```

## Usage
```javascript
var hm = require('hjson-matter');
var fs = require('fs');

var file = fs.readFileSync('./some-file.html');
var content;

// pass in file contents as a String
content = hm(file.toString());

// pass in file contents as a Buffer
content = hm(file);

// specify a delimiter
content = hm(file, {delimiters: '***'});

// specify two different delimiters
content = hm(file, {delimiters: ['***', '@@@']});
```


text:
.moon-button-sample-wrapper .moon-button-caption-decorator,
.moon-button-sample-group button,
.moon-button-sample-wrapper > button {
	margin: 20px;
}

.moon-button-sample .moon-item.tap-area-toggle-container {
	width: 300px;
	margin: 20px 0px 0px 20px;
}

.moon-button-sample .visible-tap-area .small-button-tap-area {
	background: rgba(0, 100, 200, 0.2);
	border: 1px solid rgba(0, 100, 200, 0.4);
}


text:
package mesosphere.marathon

trait Normalization[T] extends AnyRef {
  def normalized(t: T): T
  def apply(n: Normalization[T]): Normalization[T] = Normalization { t => n.normalized(normalized(t)) }
}

object Normalization {

  implicit class Normalized[T](val a: T) extends AnyVal {
    def normalize(implicit f: Normalization[T]): T = f.normalized(a)
  }

  def apply[T](f: (T => T)): Normalization[T] = new Normalization[T] {
    override def normalized(t: T): T = f(t)
  }
}


text:
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO

migration=SQLALCHEMY_MIGRATE_REPO+'/versions/%03d_migration.py' % (api.db_version(SQLALCHEMY_DATABASE_URI,SQLALCHEMY_MIGRATE_REPO)+1)
tmp_module=imp.new_module('old_model')
old_model=api.create_model(SQLALCHEMY_DATABASE_URI,SQLALCHEMY_MIGRATE_REPO)
exec old_model in tmp_module.__dict__
script=api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI,SQLALCHEMY_MIGRATE_REPO,tmp_module.meta,db.metadata)
open(migration,'wt').write(script)
api.upgrade(SQLALCHEMY_DATABASE_URI,SQLALCHEMY_MIGRATE_REPO)
print 'New migration saved as '+migration
print 'Current database version:'+str(api.db_version(SQLALCHEMY_DATABASE_URI,SQLALCHEMY_MIGRATE_REPO))


text:
package jp.pycon.pyconjp2016app.Model.PyConJP;

import com.google.gson.annotations.SerializedName;

import java.util.List;

/**
 * Created by rhoboro on 7/11/16.
 */
public class PresentationListEntity {
    @SerializedName("presentations")
    public List<PresentationEntity> presentations;
}


text:
UNIX_SnapshotOfVirtualSystemProvider::UNIX_SnapshotOfVirtualSystemProvider()
{
}

UNIX_SnapshotOfVirtualSystemProvider::~UNIX_SnapshotOfVirtualSystemProvider()
{
}

CIMInstance UNIX_SnapshotOfVirtualSystemProvider::constructInstance(
	const CIMName &className,
	const CIMNamespaceName &nameSpace,
	const UNIX_SnapshotOfVirtualSystem &_p)
{
	CIMProperty p;

	CIMInstance inst(className);

	// Set path
	inst.setPath(CIMObjectPath(String(""), // hostname
			nameSpace,
			CIMName("UNIX_SnapshotOfVirtualSystem"),
			constructKeyBindings(_p)));

	//CIM_Dependency Properties
	if (_p.getAntecedent(p)) inst.addProperty(p);
	if (_p.getDependent(p)) inst.addProperty(p);

	//CIM_SnapshotOfVirtualSystem Properties

	return inst;
}

Array<CIMKeyBinding> UNIX_SnapshotOfVirtualSystemProvider::constructKeyBindings(const UNIX_SnapshotOfVirtualSystem& _p)

{

	Array<CIMKeyBinding> keys;

	keys.append(CIMKeyBinding(
		PROPERTY_ANTECEDENT,
		CIMValue(_p.getAntecedent()).toString(),
		CIMKeyBinding::REFERENCE));
	keys.append(CIMKeyBinding(
		PROPERTY_DEPENDENT,
		CIMValue(_p.getDependent()).toString(),
		CIMKeyBinding::REFERENCE));

	return keys;
}

#define UNIX_PROVIDER UNIX_SnapshotOfVirtualSystemProvider
#define UNIX_PROVIDER_NAME "UNIX_SnapshotOfVirtualSystemProvider"
#define CLASS_IMPLEMENTATION UNIX_SnapshotOfVirtualSystem
#define CLASS_IMPLEMENTATION_NAME "UNIX_SnapshotOfVirtualSystem"
#define BASE_CLASS_NAME "CIM_SnapshotOfVirtualSystem"
#define NUMKEYS_CLASS_IMPLEMENTATION 0

#include "UNIXProviderBase.hpp"


text:
using namespace Kodiak;
using namespace std;

ComputeConstantBuffer::ComputeConstantBuffer(const string& name)
	: m_name(name)
{}

void ComputeConstantBuffer::SetDataImmediate(size_t sizeInBytes, const byte* data)
{
	assert(m_size >= sizeInBytes);

	memcpy(m_binding, data, sizeInBytes);
}

void ComputeConstantBuffer::CreateRenderThreadData(shared_ptr<RenderThread::ComputeData> computeData, const ShaderReflection::CBVLayout& cbv)
{
	m_renderThreadData = computeData;

	m_size = cbv.sizeInBytes;

	if (cbv.byteOffset != kInvalid)
	{
		m_binding = computeData->cbufferData + cbv.byteOffset;
	}
}


text:
import cv2
import os

def save_frame_play(video_path, dir_path, basename, ext='jpg', delay=1, window_name='frame'):
    cap = cv2.VideoCapture(video_path)

    if not cap.isOpened():
        return

    os.makedirs(dir_path, exist_ok=True)
    base_path = os.path.join(dir_path, basename)

    digit = len(str(int(cap.get(cv2.CAP_PROP_FRAME_COUNT))))

    n = 0
    while True:
        ret, frame = cap.read()
        if ret:
            cv2.imshow(window_name, frame)
            key = cv2.waitKey(delay) & 0xFF
            if key == ord('c'):
                cv2.imwrite('{}_{}.{}'.format(base_path, str(n).zfill(digit), ext), frame)
            elif key == ord('q'):
                break
            n += 1
        else:
            cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
            n = 0

    cv2.destroyWindow(window_name)

save_frame_play('data/temp/sample_video.mp4', 'data/temp', 'sample_video_cap', delay=0)


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Avro
{
    public class AvroContext : IDisposable
    {
        public static AvroContext Default = new AvroContext();

        public static AvroContext Create()
        {
            return new PoolingAvroContext();
        }

        internal AvroContext() { }

        public virtual void Dispose() { }

        private static readonly char[] Empty = new char[0];
        public virtual void Reset() { }
        internal virtual char[] GetCharBuffer(int charCount, out int charOffset)
        {
            if (charCount == 0)
            {
                charOffset = 0;
                return Empty;
            }
            if (charCount > CharsPerPage) throw new ArgumentOutOfRangeException("charCount");
            charOffset = 0;
            return new char[charCount];
        }

        internal static readonly Encoding Encoding = Encoding.UTF8;

        // internal static readonly int MaxBytesPerCharacter = Encoding.GetMaxByteCount(1);
        internal const int MaxBytesPerCharacter = 4; // since rfc3629 (2003), we don't need to worry about the 5/6 byte ranges
        internal const int CharsPerPage = 1024;
    }

    class PoolingAvroContext : AvroContext
    { // object re-use; not present unless a custom context is used

        private readonly List<char[]> pages = new List<char[]>();
        private int page = -1, charsLeftOnPage = 0, charIndex = 0;
        public override void Reset()
        {
            lock(pages)
            {
                if (pages.Count != 0)
                {
                    page = 0;
                    charsLeftOnPage = CharsPerPage;
                    charIndex = 0;
                }
            }
        }

        internal override char[] GetCharBuffer(int charCount, out int charOffset)
        {
            if (charCount == 0) return base.GetCharBuffer(charCount, out charOffset);
            lock(pages)
            {
                if(charCount <= charsLeftOnPage)
                {
                    charOffset = charIndex;
                    charIndex += charCount;
                    charsLeftOnPage -= charCount;
                    return pages[page];
                }
                if (++page == pages.Count)
                {
                    // need a new buffer
                    pages.Add(base.GetCharBuffer(CharsPerPage, out charOffset));
                }
                charOffset = 0;
                charIndex = charCount;
                charsLeftOnPage = CharsPerPage - charCount;
                return pages[page];
            }
        }

        public override string ToString()
        {
            lock(pages)
            {
                return string.Format("{0} pages allocated", pages.Count);
            }
        }
    }
}


text:
void FrameBuffer::SetUp()
{
	glGenFramebuffers(1, &m_fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
	glGenTextures(1, &m_fboTexture);
	glBindTexture(GL_TEXTURE_2D, m_fboTexture);
	glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGB8, width, height);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, m_fboTexture, 0);
	glGenRenderbuffers(1, &m_fboDepth);
	glBindRenderbuffer(GL_RENDERBUFFER, m_fboDepth);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_fboDepth);
	GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0 };
	glDrawBuffers(1, drawBuffers);
	GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	if (status != GL_FRAMEBUFFER_COMPLETE)
		printf("Framebuffer Error!\n");
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

void FrameBuffer::RenderScene(Scene & scene,GameObject obj)
{
	glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
	glViewport(0, 0, width, height);
	glClearColor(0.7f, 0.8f, 1.0f, 1);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	scene.Draw(obj);
	aie::Gizmos::draw(scene.m_projectMat * scene.m_viewMat);
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glViewport(0, 0, 1280, 720);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void FrameBuffer::Draw(unsigned int shader, Model* model)
{
	// draw out full-screen quad
	glUseProgram(shader);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, m_fboTexture);
	int loc = glGetUniformLocation(shader, "target");
	glUniform1i(loc, 0);
	glBindVertexArray(model->m_glinfo[0].m_VAO);
	glDrawArrays(GL_TRIANGLES, 0, 6);
}


text:
package org.codehaus.xfire.test;

import java.lang.reflect.Method;

import javax.xml.namespace.QName;

import org.codehaus.xfire.XFireRuntimeException;
import org.codehaus.xfire.service.FaultInfo;
import org.codehaus.xfire.service.MessageInfo;
import org.codehaus.xfire.service.OperationInfo;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.ServiceInfo;

/**
 * Contains various ServiceEndpoint implementations. Mainly used throughout all the test classes which need
 * ServiceEndpoint to test their code.
 *
 * @author Arjen Poutsma
 * @see Service
 */
public class ServiceEndpoints
{
    private ServiceEndpoints()
    {
    }

    /**
     * Returns the endpoint for an echo service. The returned endpoint has the namespace
     * http://test.xfire.codehaus.org, and it's name is Echo. It has on operation named
     * echo, with an input message echoRequest and an output message
     * echoResponse. Both messages contain a single part, named echoRequestin0 and
     * echoResponseout respectively.
     *

     * The endpoints Class and Method are mapped to {@link EchoImpl}.
     *
     * @return an echo service endpoint.
     */
    public static Service getEchoService()
    {
        Class echoClass = EchoImpl.class;
        Method echoMethod = null;
        try
        {
            echoMethod = echoClass.getMethod("echo", new Class[]{String.class});
        }
        catch (NoSuchMethodException e)
        {
            throw new XFireRuntimeException("Could not find echo method on Echo class", e);
        }
        ServiceInfo serviceInfo = new ServiceInfo(new QName("http://test.xfire.codehaus.org", "EchoPortType"),
                                                  echoClass);
        OperationInfo operation = serviceInfo.addOperation("echo", echoMethod);
        MessageInfo inputMessage = operation.createMessage(new QName("echoRequest"));
        operation.setInputMessage(inputMessage);
        MessageInfo outputMessage = operation.createMessage(new QName("echoResponse"));
        operation.setOutputMessage(outputMessage);
        inputMessage.addMessagePart(new QName("echoRequestin0"), String.class);
        outputMessage.addMessagePart(new QName("echoResponseout"), String.class);

        Service service = new Service(serviceInfo);
        service.setName(new QName("http://test.xfire.codehaus.org", "Echo"));
        return service;
    }

    /**
     * Returns the endpoint for an echo service with faults. This method returns the same as {@link #getEchoService()},
     * but adds a fault to the operation. The fault is named echoFault, and has one part
     * echoFault0.
     *
     * @return the echo service endpoint.
     */
    public static Service getEchoFaultService()
    {
        Service endpoint = getEchoService();
        OperationInfo operation = endpoint.getServiceInfo().getOperation("echo");
        FaultInfo fault = operation.addFault("echoFault");
        fault.addMessagePart(new QName("echoFault0"), String.class);

        return endpoint;
    }
}


text:
@class UAEC2DHCPOptions;

@interface UAEC2CreateDHCPOptionsResponse : UAEC2Response

@property (nonatomic, copy) UAEC2DHCPOptions *dhcpOptions;

@end


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "work_centre".
 *
 * @property integer $id
 * @property string $name
 * @property string $location
 * @property integer $responsible_id
 * @property integer $created_at
 * @property integer $created_by
 * @property integer $updated_at
 * @property integer $updated_by
 *
 * @property User $responsible
 * @property User $createdBy
 * @property User $updatedBy
 */
class WorkCentre extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'work_centre';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'location', 'responsible_id', 'created_at', 'created_by', 'updated_at', 'updated_by'], 'required'],
            [['responsible_id', 'created_at', 'created_by', 'updated_at', 'updated_by'], 'integer'],
            [['name', 'location'], 'string', 'max' => 255],
            [['responsible_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['responsible_id' => 'id']],
            [['created_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['created_by' => 'id']],
            [['updated_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['updated_by' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'name' => Yii::t('app', 'Name'),
            'location' => Yii::t('app', 'Location'),
            'responsible_id' => Yii::t('app', 'Responsible ID'),
            'created_at' => Yii::t('app', 'Created At'),
            'created_by' => Yii::t('app', 'Created By'),
            'updated_at' => Yii::t('app', 'Updated At'),
            'updated_by' => Yii::t('app', 'Updated By'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getResponsible()
    {
        return $this->hasOne(User::className(), ['id' => 'responsible_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCreatedBy()
    {
        return $this->hasOne(User::className(), ['id' => 'created_by']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUpdatedBy()
    {
        return $this->hasOne(User::className(), ['id' => 'updated_by']);
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Confuser.Core {
	/// <summary>
	///     Provides a set of utility methods
	/// </summary>
	public static class Utils {
		static readonly char[] hexCharset = "0123456789abcdef".ToCharArray();

		/// <summary>
		///     Gets the value associated with the specified key, or default value if the key does not exists.
		/// </summary>
		/// <typeparam name="TKey">The type of the key.</typeparam>
		/// <typeparam name="TValue">The type of the value.</typeparam>
		/// <param name="dictionary">The dictionary.</param>
		/// <param name="key">The key of the value to get.</param>
		/// <param name="defValue">The default value.</param>
		/// <returns>The value associated with the specified key, or the default value if the key does not exists</returns>
		public static TValue GetValueOrDefault<TKey, TValue>(
			this Dictionary<TKey, TValue> dictionary,
			TKey key,
			TValue defValue = default(TValue)) {
			TValue ret;
			if (dictionary.TryGetValue(key, out ret))
				return ret;
			return defValue;
		}

		/// <summary>
		///     Gets the value associated with the specified key, or default value if the key does not exists.
		/// </summary>
		/// <typeparam name="TKey">The type of the key.</typeparam>
		/// <typeparam name="TValue">The type of the value.</typeparam>
		/// <param name="dictionary">The dictionary.</param>
		/// <param name="key">The key of the value to get.</param>
		/// <param name="defValueFactory">The default value factory function.</param>
		/// <returns>The value associated with the specified key, or the default value if the key does not exists</returns>
		public static TValue GetValueOrDefaultLazy<TKey, TValue>(
			this Dictionary<TKey, TValue> dictionary,
			TKey key,
			Func<TKey, TValue> defValueFactory) {
			TValue ret;
			if (dictionary.TryGetValue(key, out ret))
				return ret;
			return defValueFactory(key);
		}

		/// <summary>
		///     Adds the specified key and value to the multi dictionary.
		/// </summary>
		/// <typeparam name="TKey">The type of key.</typeparam>
		/// <typeparam name="TValue">The type of value.</typeparam>
		/// <param name="self">The dictionary to add to.</param>
		/// <param name="key">The key of the element to add.</param>
		/// <param name="value">The value of the element to add.</param>
		/// <exception cref="System.ArgumentNullException">key is <c>null</c>.</exception>
		public static void AddListEntry<TKey, TValue>(this IDictionary<TKey, List<TValue>> self, TKey key, TValue value) {
			if (key == null)
				throw new ArgumentNullException("key");
			List<TValue> list;
			if (!self.TryGetValue(key, out list))
				list = self[key] = new List<TValue>();
			list.Add(value);
		}

		/// <summary>
		///     Obtains the relative path from the specified base path.
		/// </summary>
		/// <param name="filespec">The file path.</param>
		/// <param name="folder">The base path.</param>
		/// <returns>The path of <paramref name="filespec" /> relative to <paramref name="folder" />.</returns>
		public static string GetRelativePath(string filespec, string folder) {
			//http://stackoverflow.com/a/703292/462805

			var pathUri = new Uri(filespec);
			// Folders must end in a slash
			if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) {
				folder += Path.DirectorySeparatorChar;
			}
			var folderUri = new Uri(folder);
			return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
		}

		/// <summary>
		///     If the input string is empty, return null; otherwise, return the original input string.
		/// </summary>
		/// <param name="val">The input string.</param>
		/// <returns><c>null</c> if the input string is empty; otherwise, the original input string.</returns>
		public static string NullIfEmpty(this string val) {
			if (string.IsNullOrEmpty(val))
				return null;
			return val;
		}

		/// <summary>
		///     Compute the SHA1 hash of the input buffer.
		/// </summary>
		/// <param name="buffer">The input buffer.</param>
		/// <returns>The SHA1 hash of the input buffer.</returns>
		public static byte[] SHA1(byte[] buffer) {
			var sha = new SHA1Managed();
			return sha.ComputeHash(buffer);
		}

		/// <summary>
		///     Xor the values in the two buffer together.
		/// </summary>
		/// <param name="buffer1">The input buffer 1.</param>
		/// <param name="buffer2">The input buffer 2.</param>
		/// <returns>The result buffer.</returns>
		/// <exception cref="System.ArgumentException">Length of the two buffers are not equal.</exception>
		public static byte[] Xor(byte[] buffer1, byte[] buffer2) {
			if (buffer1.Length != buffer2.Length)
				throw new ArgumentException("Length mismatched.");
			var ret = new byte[buffer1.Length];
			for (int i = 0; i < ret.Length; i++)
				ret[i] = (byte)(buffer1[i] ^ buffer2[i]);
			return ret;
		}

		/// <summary>
		///     Compute the SHA256 hash of the input buffer.
		/// </summary>
		/// <param name="buffer">The input buffer.</param>
		/// <returns>The SHA256 hash of the input buffer.</returns>
		public static byte[] SHA256(byte[] buffer) {
			var sha = new SHA256Managed();
			return sha.ComputeHash(buffer);
		}

		/// <summary>
		///     Encoding the buffer to a string using specified charset.
		/// </summary>
		/// <param name="buff">The input buffer.</param>
		/// <param name="charset">The charset.</param>
		/// <returns>The encoded string.</returns>
		public static string EncodeString(byte[] buff, char[] charset) {
			int current = buff[0];
			var ret = new StringBuilder();
			for (int i = 1; i < buff.Length; i++) {
				current = (current << 8) + buff[i];
				while (current >= charset.Length) {
					ret.Append(charset[current % charset.Length]);
					current /= charset.Length;
				}
			}
			if (current != 0)
				ret.Append(charset[current % charset.Length]);
			return ret.ToString();
		}

		/// <summary>
		///     Returns a new string in which all occurrences of a specified string in
		///     <paramref name="str" /><paramref name="str" /> are replaced with another specified string.
		/// </summary>
		/// <returns>
		///     A <see cref="string" /> equivalent to <paramref name="str" /> but with all instances of
		///     <paramref name="oldValue" />
		///     replaced with <paramref name="newValue" />.
		/// </returns>
		/// <param name="str">A string to do the replace in. </param>
		/// <param name="oldValue">A string to be replaced. </param>
		/// <param name="newValue">A string to replace all occurrences of <paramref name="oldValue" />. </param>
		/// <param name="comparison">One of the <see cref="StringComparison" /> values. </param>
		/// <remarks>Adopted from http://stackoverflow.com/a/244933 </remarks>
		public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison) {
			StringBuilder sb = new StringBuilder();

			int previousIndex = 0;
			int index = str.IndexOf(oldValue, comparison);
			while (index != -1) {
				sb.Append(str.Substring(previousIndex, index - previousIndex));
				sb.Append(newValue);
				index += oldValue.Length;
				previousIndex = index;
				index = str.IndexOf(oldValue, index, comparison);
			}
			sb.Append(str.Substring(previousIndex));

			return sb.ToString();
		}

		/// <summary>
		///     Encode the buffer to a hexadecimal string.
		/// </summary>
		/// <param name="buff">The input buffer.</param>
		/// <returns>A hexadecimal representation of input buffer.</returns>
		public static string ToHexString(byte[] buff) {
			var ret = new char[buff.Length * 2];
			int i = 0;
			foreach (byte val in buff) {
				ret[i++] = hexCharset[val >> 4];
				ret[i++] = hexCharset[val & 0xf];
			}
			return new string(ret);
		}

		/// <summary>
		///     Removes all elements that match the conditions defined by the specified predicate from a the list.
		/// </summary>
		/// <typeparam name="T">The type of the elements of <paramref name="self" />.</typeparam>
		/// <param name="self">The list to remove from.</param>
		/// <param name="match">The predicate that defines the conditions of the elements to remove.</param>
		/// <returns><paramref name="self" /> for method chaining.</returns>
		public static IList<T> RemoveWhere<T>(this IList<T> self, Predicate<T> match) {
			for (int i = self.Count - 1; i >= 0; i--) {
				if (match(self[i]))
					self.RemoveAt(i);
			}
			return self;
		}

		/// <summary>
		///     Returns a <see cref="IEnumerable{T}" /> that log the progress of iterating the specified list.
		/// </summary>
		/// <typeparam name="T">The type of list element</typeparam>
		/// <param name="enumerable">The list.</param>
		/// <param name="logger">The logger.</param>
		/// <returns>A wrapper of the list.</returns>
		public static IEnumerable<T> WithProgress<T>(this IEnumerable<T> enumerable, ILogger logger) {
			var list = new List<T>(enumerable);
			int i;
			for (i = 0; i < list.Count; i++) {
				logger.Progress(i, list.Count);
				yield return list[i];
			}
			logger.Progress(i, list.Count);
			logger.EndProgress();
		}
	}
}


text:
// [START securitycenter_create_notification_config]

import com.google.cloud.securitycenter.v1.CreateNotificationConfigRequest;
import com.google.cloud.securitycenter.v1.NotificationConfig;
import com.google.cloud.securitycenter.v1.NotificationConfig.StreamingConfig;
import com.google.cloud.securitycenter.v1.SecurityCenterClient;
import java.io.IOException;

public class CreateNotificationConfigSnippets {

  public static void main(String[] args) throws IOException {
    // parentId: must be in one of the following formats:
    //    "organizations/{organization_id}"
    //    "projects/{project_id}"
    //    "folders/{folder_id}"
    String parentId = String.format("organizations/%s", "ORG_ID");
    String notificationConfigId = "{config-id}";
    String projectId = "{your-project}";
    String topicName = "{your-topic}";

    createNotificationConfig(parentId, notificationConfigId, projectId, topicName);
  }

  // Crete a notification config.
  // Ensure the ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the new topic.
  public static NotificationConfig createNotificationConfig(
      String parentId, String notificationConfigId, String projectId, String topicName)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SecurityCenterClient client = SecurityCenterClient.create()) {

      // Ensure this ServiceAccount has the "pubsub.topics.setIamPolicy" permission on the topic.
      String pubsubTopic = String.format("projects/%s/topics/%s", projectId, topicName);

      CreateNotificationConfigRequest request =
          CreateNotificationConfigRequest.newBuilder()
              .setParent(parentId)
              .setConfigId(notificationConfigId)
              .setNotificationConfig(
                  NotificationConfig.newBuilder()
                      .setDescription("Java notification config")
                      .setPubsubTopic(pubsubTopic)
                      .setStreamingConfig(
                          StreamingConfig.newBuilder().setFilter("state = \"ACTIVE\"").build())
                      .build())
              .build();

      NotificationConfig response = client.createNotificationConfig(request);
      System.out.printf("Notification config was created: %s%n", response);
      return response;
    }
  }
}
// [END securitycenter_create_notification_config]


text:
namespace IsoscelesTriangle
{
    using System;
    using System.Text;

    class CopyRight
    {
        // Write a program that prints an isosceles triangle of 9 copyright symbols ©, something like this:

        static void Main()
        {
            char unicode = '\u00A9';
            Console.OutputEncoding = Encoding.UTF8;
            Console.WriteLine("   {0}\n  {0} {0}\n {0}   {0}\n{0} {0} {0} {0}", unicode);
        }
    }
}


text:
Conductor.card({
  activate: function () {
    this.consumers.height.autoUpdate = false;
    this.consumers.height.update({ width: 55, height: 55 });
  }
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RMUD;

namespace AdminModule
{
    internal class Reload : CommandFactory
    {
        public override void Create(CommandParser Parser)
        {
            Parser.AddCommand(
                Sequence(
                    RequiredRank(500),
                    KeyWord("!RELOAD"),
                    MustMatch("It helps if you give me a path.",
                        Path("TARGET"))))
                .Manual("Given a path, it attempts to recompile that object. The object will be replaced in-place if possible.")
                .ProceduralRule((match, actor) =>
                {
                    var target = match["TARGET"].ToString();
                    var newObject = Core.Database.ReloadObject(target);
                    if (newObject == null) MudObject.SendMessage(actor, "Failed to reload " + target);
                    else MudObject.SendMessage(actor, "Reloaded " + target);
                    return PerformResult.Continue;
                });

            Parser.AddCommand(
                 Sequence(
                     RequiredRank(500),
                     KeyWord("!RESET"),
                     MustMatch("It helps if you give me a path.",
                         Path("TARGET"))))
                 .Manual("Given a path, it attempts to reset that object without reloading or recompiling. The object will be replaced in-place if possible.")
                 .ProceduralRule((match, actor) =>
                 {
                     var target = match["TARGET"].ToString();
                     if (Core.Database.ResetObject(target) == null)
                         MudObject.SendMessage(actor, "Failed to reset " + target);
                     else MudObject.SendMessage(actor, "Reset " + target);
                     return PerformResult.Continue;
                 });

        }
    }
}


text:
package com.for_futrue.zxg.znews.datasource;

import android.os.Message;

import com.for_futrue.zxg.znews.bean.News;

import java.util.List;

/**
 * Created by zxg on 2016/4/5.
 */
public interface NewsDataSource {
    void loadNewsListByChannel(int channelDesc,int index,Message msg);
    void getNewsContentByUrl(String docId,Message msg);
}


text:
package algs.example.gui.canvas;

import algs.model.kdtree.DimensionalNode;

/**
 * Maintains AWT information about the regions associated with each point
 * in the KD tree.
 *
 * Ensures that drawing lines will be within their respective boundaries
 * as the KD tree is drawn.
 *
 * @author George Heineman
 * @version 1.0, 6/15/08
 * @since 1.0
 */
public class DrawingInfo {
	int minHorizontal;
	int maxHorizontal;

	int minVertical;
	int maxVertical;

	public DrawingInfo (int minh, int maxh, int minv, int maxv) {
		minHorizontal = minh;
		maxHorizontal = maxh;

		minVertical = minv;
		maxVertical = maxv;
	}

	public String toString () { return "H:" + minHorizontal + "," + maxHorizontal + ", V:" + minVertical + "," + maxVertical; }

	public DrawingInfo above(DimensionalNode node) {
		int d = node.dimension;
		if (d == 1) {
			return new DrawingInfo ((int) node.point.getCoordinate(d), maxHorizontal,
						minVertical, maxVertical);
		} else {
			return new DrawingInfo (
					minHorizontal, maxHorizontal,
					(int) node.point.getCoordinate(d), maxVertical);
		}
	}

	public DrawingInfo below(DimensionalNode node) {
		int d = node.dimension;
		if (d == 1) {
			return new DrawingInfo (minHorizontal, (int) node.point.getCoordinate(d),
						minVertical, maxVertical);
		} else {
			return new DrawingInfo (
					minHorizontal, maxHorizontal,
					minVertical, (int) node.point.getCoordinate(d));
		}
	}
}


text:
<?php

namespace Eventerza\Address\Models;

use Eventerza\Address\Exceptions\AddressException;
use Eventerza\Core\EntityObject\EntityObjectInterface;
use Ramsey\Uuid\UuidInterface;

/**
 * Class PostalCode
 * @package Eventerza\Address\Models
 */
class PostalCode implements EntityObjectInterface
{
    const TABLE = 'postal_codes';

    /** @var string */
    private $postalCode;
    /** @var string */
    private $city;
    /** @var string */
    private $state;
    /** @var string */
    private $district;
    /** @var float */
    private $latitude;
    /** @var float */
    private $longitude;
    /** @var string */
    private $format;

    /**
     * PostalCode constructor.
     *
     * @param string $postalCode
     * @param string $city
     * @param string $state
     * @param string $district
     * @param float $latitude
     * @param float $longitude
     * @param string|null $format
     */
    public function __construct(
        string $postalCode,
        string $city,
        string $state,
        string $district,
        float $latitude,
        float $longitude,
        string $format = null
    )
    {
        if ($format === null) {
            $format = '%postalCode% %city%';
        }

        $this->postalCode = $postalCode;
        $this->city = $city;
        $this->state = $state;
        $this->district = $district;
        $this->latitude = $latitude;
        $this->longitude = $longitude;
        $this->format = $format;
    }

    /**
     * @return UuidInterface
     */
    public function getId() : UuidInterface
    {
        throw new AddressException("PostalCode has no UUID");
    }

    /**
     * @return string
     */
    public function getPostalCode(): string
    {
        return $this->postalCode;
    }

    /**
     * @return string
     */
    public function getCity(): string
    {
        return $this->city;
    }

    /**
     * @return string
     */
    public function getState(): string
    {
        return $this->state;
    }

    /**
     * @return string
     */
    public function getDistrict(): string
    {
        return $this->district;
    }

    /**
     * @return float
     */
    public function getLatitude(): float
    {
        return $this->latitude;
    }

    /**
     * @return float
     */
    public function getLongitude(): float
    {
        return $this->longitude;
    }

    public function toAddressString(): string
    {
        $replacements = array(
            "%postalCode%" => $this->getPostalCode(),
            "%city%" => $this->getCity(),
        );

        $postalCodeString = str_replace(
            array_keys($replacements),
            array_values($replacements),
            $this->format
        );

        return $postalCodeString;
    }
}


text:
const test = require('tape');
const { readFile, rm } = require('fildes-extra');
const { resolve } = require('path');
const bundle = require('../bundle.js');

test('cleanup', t => {
  rm(resolve(__dirname, 'build/bundle'))
    .then(() => t.end())
    .catch(err => t.fail(err));
});

test('bundle es6 modules', t => {
  const src = resolve(__dirname, 'fixtures/entry.js');
  const dest = resolve(__dirname, 'build/bundle/bundle.js');
  const srcMapPath = '../../fixtures/entry.js';

  bundle({ src, dest, minify: false })
    .then(() => readFile(dest))
    .then(code => t.ok(Buffer.byteLength(code) > 1, 'has some length'))
    .then(() => readFile(dest + '.map', { encoding: 'utf8' }))
    .then(map => JSON.parse(map))
    .then(({ version, sources }) => {
      t.ok(version >= 3, 'sourcemap version >= 3');
      t.ok(sources.indexOf(srcMapPath) > -1, `sources contain ${srcMapPath}`);
    })
    .then(() => t.end())
    .catch(t.end);
});


text:
#include <aws/rekognition/model/DeleteProjectPolicyRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Rekognition::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DeleteProjectPolicyRequest::DeleteProjectPolicyRequest() :
    m_projectArnHasBeenSet(false),
    m_policyNameHasBeenSet(false),
    m_policyRevisionIdHasBeenSet(false)
{
}

Aws::String DeleteProjectPolicyRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_projectArnHasBeenSet)
  {
   payload.WithString("ProjectArn", m_projectArn);

  }

  if(m_policyNameHasBeenSet)
  {
   payload.WithString("PolicyName", m_policyName);

  }

  if(m_policyRevisionIdHasBeenSet)
  {
   payload.WithString("PolicyRevisionId", m_policyRevisionId);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection DeleteProjectPolicyRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "RekognitionService.DeleteProjectPolicy"));
  return headers;

}


text:
<?php

namespace JoBeetBundle\Controller;

use JoBeetBundle\Entity\Category;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * Category controller.
 *
 * @Route("/category")
 */
class CategoryController extends Controller
{
    /**
     * @Route(name="job_category", path="/{slug}/{page}")
     */
    public function showAction(Category $category, $page = 1)
    {
        $em = $this->getDoctrine()->getManager();
        $category->setActiveJobs($em->getRepository('JoBeetBundle:Job')->getActiveJobs($category->getId()));

        $total_jobs = $em->getRepository('JoBeetBundle:Job')->countActiveJobs($category->getId());
        $jobs_per_page = $this->container->getParameter('max_jobs_on_category');
        $last_page = ceil($total_jobs / $jobs_per_page);
        $previous_page = $page > 1 ? $page - 1 : 1;
        $next_page = $page < $last_page ? $page + 1 : $last_page;

        $category->setActiveJobs($em->getRepository('JoBeetBundle:Job')->getActiveJobs($category->getId(), $jobs_per_page, ($page - 1) * $jobs_per_page));

        return $this->render(':category:show.html.twig', array(
            'category' => $category,
            'last_page' => $last_page,
            'previous_page' => $previous_page,
            'current_page' => $page,
            'next_page' => $next_page,
            'total_jobs' => $total_jobs
        ));
    }
}


text:
const chai = require('chai')
	, should = chai.should();

const convert = require('../src/index');

describe('Convert from 20 to 29', () => {

	it('should convert 20', () => {
		const result = convert(20);
		result.should.equal('twenty');
	});

	it('should convert 21', () => {
		const result = convert(21);
		result.should.equal('twenty-one');
	});

	it('should convert 22', () => {
		const result = convert(22);
		result.should.equal('twenty-two');
	});

	it('should convert 23', () => {
		const result = convert(23);
		result.should.equal('twenty-three');
	});

	it('should convert 24', () => {
		const result = convert(24);
		result.should.equal('twenty-four');
	});

	it('should convert 25', () => {
		const result = convert(25);
		result.should.equal('twenty-five');
	});

	it('should convert 26', () => {
		const result = convert(26);
		result.should.equal('twenty-six');
	});

	it('should convert 27', () => {
		const result = convert(27);
		result.should.equal('twenty-seven');
	});

	it('should convert 28', () => {
		const result = convert(28);
		result.should.equal('twenty-eight');
	});

	it('should convert 29', () => {
		const result = convert(29);
		result.should.equal('twenty-nine');
	});

});


text:
using System.Xml.XPath;

using DotNetNuke.Common.Lists;
using DotNetNuke.Framework;

#endregion

namespace DotNetNuke.Services.Installer.Dependencies
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The DependencyFactory is a factory class that is used to instantiate the
    /// appropriate Dependency
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// -----------------------------------------------------------------------------
    public class DependencyFactory
    {
        #region Public Shared Methods

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The GetDependency method instantiates (and returns) the relevant Dependency
        /// </summary>
        /// <param name="dependencyNav">The manifest (XPathNavigator) for the dependency</param>
        /// -----------------------------------------------------------------------------
        public static IDependency GetDependency(XPathNavigator dependencyNav)
        {
            IDependency dependency = null;
            string dependencyType = Util.ReadAttribute(dependencyNav, "type");
            switch (dependencyType.ToLowerInvariant())
            {
                case "coreversion":
                    dependency = new CoreVersionDependency();
                    break;
                case "package":
                    dependency = new PackageDependency();
                    break;
                case "managedpackage":
                    dependency = new ManagedPackageDependency();
                    break;
                case "permission":
                    dependency = new PermissionsDependency();
                    break;
                case "type":
                    dependency = new TypeDependency();
                    break;
                default:
                    //Dependency type is defined in the List
                    var listController = new ListController();
                    ListEntryInfo entry = listController.GetListEntryInfo("Dependency", dependencyType);
                    if (entry != null && !string.IsNullOrEmpty(entry.Text))
                    {
                        //The class for the Installer is specified in the Text property
                        dependency = (DependencyBase)Reflection.CreateObject(entry.Text, "Dependency_" + entry.Value);
                    }
                    break;
            }
            if (dependency == null)
            {
                //Could not create dependency, show generic error message
                dependency = new InvalidDependency(Util.INSTALL_Dependencies);
            }
            //Read Manifest
            dependency.ReadManifest(dependencyNav);

            return dependency;
        }

        #endregion
    }
}