text:
Goal
====

With bundler it's easy for your project to depend on many gems.  This decomposition is nice, but managing licenses becomes difficult.  This tool gathers info about the licenses of the gems in your project.

Usage
=====

For a Rails project add license_finder to your Gemfile:
    gem 'license_finder', :git => "https://github.com/pivotal/LicenseFinder.git"

Run 'rake license:init'
This will create a config/license_finder.yml file that lets you configure license finder.  This is where you should add licenses which are allowed on the project, so they will be automatically approved.

Run 'rake license:generate_dependencies'
This will write out a dependencies.yml and dependencies.txt file in the root of your project.
It will also merge in an existing dependencies.yml file, if one exists.

Run 'rake license:action_items'
This will output a list of unapproved dependencies to the console

Run 'rake license:action_items:ok'
This will return a non-zero exit status if there are unapproved dependencies. Great for CI.

As a standalone script:

    cd ~
    git clone http://github.com/pivotal/LicenseFinder.git license_finder
    cd your/project
    ~/license_finder/bin/license_finder

Optionally add `--with-licenses` to include the full text of the licenses in the output.

Sample Output
=============

dependencies.yml:

    ---
    - name: "json_pure"
      version: "1.5.1"
      license: "other"
      approved: false

    - name: "rake"
      version: "0.8.7"
      license: "MIT"
      approved: true

dependencies.txt:

    json_pure 1.5.1, other
    rake 0.8.7, MIT

bin/license_finder:

    ---
    json_pure 1.5.1:
      dependency_name: json_pure
      dependency_version: 1.5.1
      install_path: /some/path/.rvm/gems/ruby-1.9.2-p180/gems/json_pure-1.5.1
      license_files:
      - file_name: COPYING
        header_type: other
        body_type: other
        disclaimer_of_liability: other
      - file_name: COPYING-json-jruby
        header_type: other
        body_type: other
        disclaimer_of_liability: other
      readme_files:
      - file_name: README
        mentions_license: true
      - file_name: README-json-jruby.markdown
        mentions_license: false
    ---
    rake 0.8.7:
      dependency_name: rake
      dependency_version: 0.8.7
      install_path: /some/path/.rvm/gems/ruby-1.9.2-p180/gems/rake-0.8.7
      license_files:
      - file_name: MIT-LICENSE
        header_type: other
        body_type: mit
        disclaimer_of_liability: "mit: THE AUTHORS OR COPYRIGHT HOLDERS"
      readme_files:
      - file_name: README
        mentions_license: true

Gem Maintainers
===============

Please add a license to your gemspec!

    Gem::Specification.new do |s|
      s.name = "my_great_gem"
      s.license = "MIT"
    end


text:
using System.ComponentModel.DataAnnotations;

using Newtonsoft.Json;

namespace SocialNetwork.Models
{
    /*ImageUrl which is required
    FileExtension with max length 4 which is required
    It has a User*/
    public class Image
    {
        public int Id { get; set; }

        [Required]
        public string ImageUrl { get; set; }

        [Required]
        [StringLength(4)]
        public string FileExtension { get; set; }

        [JsonIgnore]
        public User User { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
To build the docs, install [mdbook](https://github.com/rust-lang/mdBook).

You can build the HTML with `mdbook build`.

To serve the docs on `localhost:3000` and watch for changes, use `mdbook
serve`.


text:
using System;
using System.Data;
using Dapper.AmbientContext.Storage;
using Machine.Specifications;
using Moq;
using It = Machine.Specifications.It;

namespace Dapper.AmbientContext.Tests
{
    internal class AmbientDbContextFactoryTests
    {
        [Subject("Ambient DB Context Factory")]
        class When_calling_create_with_none_closed_database_connection
        {
            Establish context = () =>
            {
#if NET452
                AmbientDbContextStorageProvider.SetStorage(new LogicalCallContextStorage());
#else
                AmbientDbContextStorageProvider.SetStorage(new AsyncLocalContextStorage());
#endif

                var dbConnectionState = ConnectionState.Open;

                var dbConnectionMock = new Mock<IDbConnection>();
                dbConnectionMock.Setup(mock => mock.State).Returns(() => dbConnectionState);

                var dbConnectionFactoryMock = new Mock<IDbConnectionFactory>();
                dbConnectionFactoryMock.Setup(mock => mock.Create()).Returns(dbConnectionMock.Object);

                _ambientDatabaseContextFactory = new AmbientDbContextFactory(dbConnectionFactoryMock.Object);
            };

            Because of = () =>
            {
                _exception = Catch.Exception(() => _ambientDatabaseContextFactory.Create());
            };

            It should_throw_ambient_database_context_exception = () =>
            {
                _exception.ShouldBeOfExactType<AmbientDbContextException>();
                _exception.Message.ShouldEqual("The database connection factory returned a database connection in a non-closed state. This behavior is not allowed as the ambient database context will maintain database connection state as required.");
            };

            Cleanup test = () =>
            {
                AmbientDbContextStorageProvider.SetStorage(null);
            };

            private static Exception _exception;
            private static IAmbientDbContextFactory _ambientDatabaseContextFactory;
        }

        [Subject("Ambient DB Context Factory")]
        class When_calling_create_with_closed_database_connection
        {
            Establish context = () =>
            {
#if NET452
                AmbientDbContextStorageProvider.SetStorage(new LogicalCallContextStorage());
#else
                AmbientDbContextStorageProvider.SetStorage(new AsyncLocalContextStorage());
#endif

                _dbConnectionMock = new Mock<IDbConnection>();
                _dbConnectionMock.Setup(mock => mock.State).Returns(() => ConnectionState.Closed);

                var dbConnectionFactoryMock = new Mock<IDbConnectionFactory>();
                dbConnectionFactoryMock.Setup(mock => mock.Create()).Returns(_dbConnectionMock.Object);

                _ambientDatabaseContextFactory = new AmbientDbContextFactory(dbConnectionFactoryMock.Object);
            };

            Because of = () =>
            {
                _ambientDbContext = _ambientDatabaseContextFactory.Create();
            };

            It should_return_the_expected_ambient_database_context = () =>
            {
                _ambientDbContext.ShouldNotBeNull();
                _ambientDbContext.Connection.ShouldEqual(_dbConnectionMock.Object);
                _ambientDbContext.Connection.State.ShouldEqual(ConnectionState.Closed);
            };

            Cleanup test = () =>
            {
                AmbientDbContextStorageProvider.SetStorage(null);

                _ambientDbContext.Dispose();
            };

            private static IAmbientDbContext _ambientDbContext;
            private static IAmbientDbContextFactory _ambientDatabaseContextFactory;
            private static Mock<IDbConnection> _dbConnectionMock;
        }
    }
}


text:
package org.jetbrains.plugins.scala.lang.parser.parsing.expressions

import com.intellij.lang.PsiBuilder
import org.jetbrains.plugins.scala.ScalaBundle
import org.jetbrains.plugins.scala.lang.parser.parsing.ParsingRule
import org.jetbrains.plugins.scala.lang.parser.parsing.base.End
import org.jetbrains.plugins.scala.lang.parser.parsing.builder.ScalaPsiBuilder
import org.jetbrains.plugins.scala.lang.parser.parsing.statements.Def
import org.jetbrains.plugins.scala.lang.parser.parsing.top.ClassTemplateBlock
import org.jetbrains.plugins.scala.lang.parser.parsing.types.{Path, TypeArgs}
import org.jetbrains.plugins.scala.lang.parser.parsing.xml.XmlExpr
import org.jetbrains.plugins.scala.lang.parser.util.{InBracelessScala3, ParserUtils}
import org.jetbrains.plugins.scala.lang.parser.{ErrMsg, ScalaElementType}

import scala.annotation.tailrec

/*
 * Scala 2:
 * SimpleExpr ::= 'new' (ClassTemplate | TemplateBody)
 *              | BlockExpr
 *              | SimpleExpr1 ['_']
 *
 * SimpleExpr1 ::= Literal
 *               | Path
 *               | '_'
 *               | '(' [Exprs [',']] ')'
 *               | SimpleExpr '.' id
 *               | SimpleExpr TypeArgs
 *               | SimpleExpr1 ArgumentExprs
 *               | XmlExpr
 *
 * -------------------------------------------------------
 *
 * Scala 3:
 * SimpleExpr        ::=  SimpleRef
 *                     |  Literal
 *                     |  '_'
 *                     |  BlockExpr
 *                     |  '$' '{' Block '}'                                        -- unless inside quoted pattern
 *                     |  '$' '{' Pattern '}'                                      -- only inside quoted pattern
 *                     |  Quoted
 *                     |  quoteId                                                  -- only inside splices
 *                     |  'new' ConstrApp {'with' ConstrApp} [TemplateBody]
 *                     |  'new' TemplateBody
 *                     |  '(' ExprsInParens ')'
 *                     |  SimpleExpr '.' id
 *                     |  SimpleExpr '.' MatchClause
 *                     |  SimpleExpr TypeArgs
 *                     |  SimpleExpr ArgumentExprs
 *                     |  SimpleExpr ColonArgument -- scala 3 fewer braces
 */
object SimpleExpr extends ParsingRule {

  import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenType._
  import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes._

  override def parse(implicit builder: ScalaPsiBuilder): Boolean = {
    val simpleMarker = builder.mark()
    var newMarker: PsiBuilder.Marker = null
    var state: Boolean = false //false means SimpleExpr, true SimpleExpr1
    builder.getTokenType match {
      case NewKeyword =>
        val iw = builder.currentIndentationWidth
        builder.advanceLexer() //Ate new
        if (!ClassTemplateBlock()) {
          builder error ErrMsg("identifier.expected")
          simpleMarker.drop()
          return false
        }
        newMarker = simpleMarker.precede
        End(iw)
        simpleMarker.done(ScalaElementType.NewTemplate)
      case `tLBRACE` =>
        newMarker = simpleMarker.precede
        simpleMarker.drop()
        if (!BlockExpr()) {
          newMarker.drop()
          return false
        }
      case `tUNDER` =>
        state = true
        builder.advanceLexer() //Ate _
        newMarker = simpleMarker.precede
        simpleMarker.done(ScalaElementType.PLACEHOLDER_EXPR)
      case `SpliceStart` =>
        newMarker = simpleMarker.precede
        simpleMarker.drop()
        if (builder.isInQuotedPattern) {
          SplicedPatternExpr()
        }
        else {
          SplicedExpr()
        }
      case `QuoteStart` =>
        newMarker = simpleMarker.precede
        simpleMarker.drop()
        Quoted()
      case `tLPARENTHESIS` =>
        state = true
        builder.advanceLexer()
        builder.disableNewlines()
        builder.getTokenType match {
          case `tRPARENTHESIS` =>
            builder.advanceLexer()
            builder.restoreNewlinesState()
            newMarker = simpleMarker.precede
            simpleMarker.done(ScalaElementType.UNIT_EXPR)
          case _ =>
            if (!Expr()) {
              builder error ErrMsg("rparenthesis.expected")
              builder.restoreNewlinesState()
              newMarker = simpleMarker.precede
              simpleMarker.done(ScalaElementType.UNIT_EXPR)
            } else {
              var isTuple = false
              while (builder.getTokenType == tCOMMA &&
                !builder.lookAhead(tCOMMA, tRPARENTHESIS)) {
                isTuple = true
                builder.advanceLexer()
                if (!Expr()) {
                  builder error ErrMsg("wrong.expression")
                }
              }
              if (builder.getTokenType == tCOMMA && !builder.consumeTrailingComma(tRPARENTHESIS)) {
                builder.advanceLexer()
                isTuple = true
              }
              if (builder.getTokenType != tRPARENTHESIS) {
                builder error ErrMsg("rparenthesis.expected")
              } else {
                builder.advanceLexer()
              }
              builder.restoreNewlinesState()
              newMarker = simpleMarker.precede
              simpleMarker.done(if (isTuple) ScalaElementType.TUPLE else ScalaElementType.PARENT_EXPR)
            }
        }
      case _ =>
        state = true
        if (!Literal()) {
          if (!XmlExpr()) {
            if (!Path(ScalaElementType.REFERENCE_EXPRESSION)) {
              simpleMarker.drop()
              return false
            }
          }
        }
        newMarker = simpleMarker.precede
        simpleMarker.drop()
    }

    @tailrec
    def subparse(marker: PsiBuilder.Marker): Unit = {
      builder.getTokenType match {
        case `tUNDER` if !builder.newlineBeforeCurrentToken =>
          if (state) {
            builder.advanceLexer()
            val tMarker = marker.precede
            marker.done(ScalaElementType.PLACEHOLDER_EXPR)
            subparse(tMarker)
          }
          else {
            marker.drop()
          }
        case InBracelessScala3(`tCOLON`)
          if state &&
            builder.findPreviousNewLine.isEmpty &&
            ColonArgument(needArgNode = true) =>
          val tMarker = marker.precede
          marker.done(ScalaElementType.METHOD_CALL)
          subparse(tMarker)
        case InBracelessScala3(`tDOT`) if ParserUtils.isOutdent =>
          marker.drop()
        case `tDOT` =>
          state = true
          builder.advanceLexer() //Ate .
          builder.getTokenType match {
            case `tIDENTIFIER` =>
              builder.advanceLexer() //Ate id
              val tMarker = marker.precede
              marker.done(ScalaElementType.REFERENCE_EXPRESSION)
              subparse(tMarker)
            case `kMATCH` =>
              val tMarker = marker.precede()
              Expr1.parseMatch(marker)
              subparse(tMarker)
            case _ =>
              builder error ScalaBundle.message("identifier.expected")
              marker.drop()
          }
        case `tLPARENTHESIS` | `tLBRACE`
          if builder.getTokenType != tLPARENTHESIS ||
            !builder.newlineBeforeCurrentToken ||
            (builder.isScala3 && builder.isScala3IndentationBasedSyntaxEnabled && ParserUtils.isIndent) =>
          if (state && ArgumentExprs()) {
            val tMarker = marker.precede
            marker.done(ScalaElementType.METHOD_CALL)
            subparse(tMarker)
          }
          else {
            marker.drop()
          }
        case `tLSQBRACKET` =>
          state = true
          TypeArgs(isPattern = false)
          val tMarker = marker.precede
          marker.done(ScalaElementType.GENERIC_CALL)
          subparse(tMarker)
        case `kDEF` | `kPRIVATE` | `kPROTECTED` | `kIMPLICIT` if ParserUtils.hasTextBefore(builder, "inline") =>
          //This is kinda hack for cases when we have to build stubs for sources, that use meta and contain inline keyword
          //Without this we would get different count of stub elements and ast nodes (and exception as the result)
          marker.drop()
          Def()
        case _ =>
          marker.drop()
      }
    }

    subparse(newMarker)
    true
  }
}


text:
/**
 * Creates a rule that will be applied when an MDC Web component is within the context of an RTL layout.
 *
 * Usage Example:
 * ```scss
 * .mdc-foo {
 *   position: absolute;
 *   left: 0;
 *
 *   @include mdc-rtl {
 *     left: auto;
 *     right: 0;
 *   }
 *
 *   &__bar {
 *     margin-left: 4px;
 *     @include mdc-rtl(".mdc-foo") {
 *       margin-left: auto;
 *       margin-right: 4px;
 *     }
 *   }
 * }
 *
 * .mdc-foo--mod {
 *   padding-left: 4px;
 *
 *   @include mdc-rtl {
 *     padding-left: auto;
 *     padding-right: 4px;
 *   }
 * }
 * ```
 *
 * Note that this works by checking for [dir="rtl"] on an ancestor element. While this will work
 * in most cases, it will in some cases lead to false negatives, e.g.
 *
 * ```html
 * <html dir="rtl">
 *   <!-- ... -->
 *   <div dir="ltr">
 *     <div class="mdc-foo">Styled incorrectly as RTL!</div>
 *   </div>
 * </html>
 * ```
 *
 * In the future, selectors such as :dir (http://mdn.io/:dir) will help us mitigate this.
 */
/**
 * Takes a base box-model property - e.g. margin / border / padding - along with a default
 * direction and value, and emits rules which apply the value to the
 * "<base-property>-<default-direction>" property by default, but flips the direction
 * when within an RTL context.
 *
 * For example:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-box(margin, left, 8px);
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 * .mdc-foo {
 *   margin-left: 8px;
 *
 *   @include mdc-rtl {
 *     margin-right: 8px;
 *     margin-left: 0;
 *   }
 * }
 * ```
 * whereas:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-box(margin, right, 8px);
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 * .mdc-foo {
 *   margin-right: 8px;
 *
 *   @include mdc-rtl {
 *     margin-right: 0;
 *     margin-left: 8px;
 *   }
 * }
 * ```
 *
 * You can also pass a 4th optional $root-selector argument which will be forwarded to `mdc-rtl`,
 * e.g. `@include mdc-rtl-reflexive-box(margin, left, 8px, ".mdc-component")`.
 *
 * Note that this function will always zero out the original value in an RTL context. If you're
 * trying to flip the values, use mdc-rtl-reflexive-property().
 */
/**
 * Takes a base property and emits rules that assign <base-property>-left to <left-value> and
 * <base-property>-right to <right-value> in a LTR context, and vice versa in a RTL context.
 * For example:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-property(margin, auto, 12px);
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 * .mdc-foo {
 *   margin-left: auto;
 *   margin-right: 12px;
 *
 *   @include mdc-rtl {
 *     margin-left: 12px;
 *     margin-right: auto;
 *   }
 * }
 * ```
 *
 * A 4th optional $root-selector argument can be given, which will be passed to `mdc-rtl`.
 */
/**
 * Takes an argument specifying a horizontal position property (either "left" or "right") as well
 * as a value, and applies that value to the specified position in a LTR context, and flips it in a
 * RTL context. For example:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-position(left, 0);
 *   position: absolute;
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 *  .mdc-foo {
 *    position: absolute;
 *    left: 0;
 *    right: initial;
 *
 *    @include mdc-rtl {
 *      right: 0;
 *      left: initial;
 *    }
 *  }
 * ```
 * An optional third $root-selector argument may also be given, which is passed to `mdc-rtl`.
 */
/* TODO(sgomes): Figure out what to do about desktop font sizes. */
/* TODO(sgomes): Figure out what to do about i18n and i18n font sizes. */
/* postcss-bem-linter: define snackbar */
.lmdc-snackbar {
  display: flex;
  position: fixed;
  bottom: 0;
  left: 50%;
  align-items: center;
  justify-content: flex-start;
  box-sizing: border-box;
  padding-right: 24px;
  padding-left: 24px;
  -webkit-transform: translate(-50%, 100%);
          transform: translate(-50%, 100%);
  transition: -webkit-transform 0.25s 0ms cubic-bezier(0.4, 0, 1, 1);
  transition: transform 0.25s 0ms cubic-bezier(0.4, 0, 1, 1);
  transition: transform 0.25s 0ms cubic-bezier(0.4, 0, 1, 1), -webkit-transform 0.25s 0ms cubic-bezier(0.4, 0, 1, 1);
  background-color: #323232;
  pointer-events: none;
  will-change: transform; }
  @media (max-width: 599px) {
    .lmdc-snackbar {
      left: 0;
      width: 100%;
      -webkit-transform: translate(0, 100%);
              transform: translate(0, 100%); } }
  @media (min-width: 600px) {
    .lmdc-snackbar {
      min-width: 288px;
      max-width: 568px;
      border-radius: 2px; } }

@media (min-width: 600px) {
  .lmdc-snackbar--align-start {
    left: 24px;
    right: initial;
    bottom: 24px;
    -webkit-transform: translate(0, 200%);
            transform: translate(0, 200%); }
    [dir="rtl"] .lmdc-snackbar--align-start, .lmdc-snackbar--align-start[dir="rtl"] {
      left: initial;
      right: 24px; } }

@media (max-width: 599px) {
  .lmdc-snackbar--align-start {
    bottom: 0;
    left: 0;
    width: 100%;
    -webkit-transform: translate(0, 100%);
            transform: translate(0, 100%); } }

.lmdc-snackbar--active {
  -webkit-transform: translate(0);
          transform: translate(0);
  transition: -webkit-transform 0.25s 0ms cubic-bezier(0, 0, 0.2, 1);
  transition: transform 0.25s 0ms cubic-bezier(0, 0, 0.2, 1);
  transition: transform 0.25s 0ms cubic-bezier(0, 0, 0.2, 1), -webkit-transform 0.25s 0ms cubic-bezier(0, 0, 0.2, 1);
  pointer-events: auto; }
  .lmdc-snackbar--active:not(.lmdc-snackbar--align-start) {
    -webkit-transform: translate(-50%, 0);
            transform: translate(-50%, 0); }
    @media (max-width: 599px) {
      .lmdc-snackbar--active:not(.lmdc-snackbar--align-start) {
        bottom: 0;
        left: 0;
        width: 100%;
        -webkit-transform: translate(0);
                transform: translate(0); } }

.lmdc-snackbar__action-wrapper {
  padding-left: 24px;
  padding-right: 0; }
  [dir="rtl"] .lmdc-snackbar__action-wrapper, .lmdc-snackbar__action-wrapper[dir="rtl"] {
    padding-left: 0;
    padding-right: 24px; }

.lmdc-snackbar--action-on-bottom {
  flex-direction: column; }

.lmdc-snackbar__text {
  font-family: Roboto, sans-serif;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  font-size: 0.875rem;
  line-height: 1.25rem;
  font-weight: 400;
  letter-spacing: 0.04em;
  text-decoration: inherit;
  text-transform: inherit;
  margin-left: 0;
  margin-right: auto;
  display: flex;
  align-items: center;
  height: 48px;
  transition: opacity 0.3s 0ms cubic-bezier(0.4, 0, 1, 1);
  opacity: 0;
  color: white; }
  .lmdc-snackbar[dir="rtl"] .lmdc-snackbar__text,
  [dir="rtl"] .lmdc-snackbar .lmdc-snackbar__text {
    margin-left: auto;
    margin-right: 0; }
  @media (min-width: 600px) {
    .lmdc-snackbar__text {
      padding-left: 0;
      padding-right: 24px; }
      [dir="rtl"] .lmdc-snackbar__text, .lmdc-snackbar__text[dir="rtl"] {
        padding-left: 24px;
        padding-right: 0; } }

.lmdc-snackbar--action-on-bottom .lmdc-snackbar__text {
  margin-right: inherit; }

.lmdc-snackbar--action-on-bottom .lmdc-snackbar__action-wrapper {
  margin-left: auto;
  margin-right: 0;
  flex-direction: column;
  justify-content: flex-start;
  margin-top: -12px;
  margin-bottom: 8px; }
  [dir="rtl"] .lmdc-snackbar--action-on-bottom .lmdc-snackbar__action-wrapper, .lmdc-snackbar--action-on-bottom .lmdc-snackbar__action-wrapper[dir="rtl"] {
    margin-left: 0;
    margin-right: auto; }

.lmdc-snackbar--multiline .lmdc-snackbar__text {
  height: 80px; }

.lmdc-snackbar__action-button {
  font-family: Roboto, sans-serif;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  font-size: 0.875rem;
  line-height: 2.25rem;
  font-weight: 500;
  letter-spacing: 0.04em;
  text-decoration: none;
  text-transform: uppercase;
  /* @alternate */
  color: #018786;
  color: var(--mdc-theme-secondary, #018786);
  padding: 0;
  transition: opacity 0.3s 0ms cubic-bezier(0.4, 0, 1, 1);
  border: none;
  outline: none;
  background-color: transparent;
  opacity: 0;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
  -webkit-appearance: none;
  visibility: hidden; }
  .lmdc-snackbar__action-button::-moz-focus-inner {
    border: 0; }
  .lmdc-snackbar__action-button:hover {
    cursor: pointer; }
  .lmdc-snackbar__action-button:not([aria-hidden]) {
    visibility: inherit; }

.lmdc-snackbar--active .lmdc-snackbar__text,
.lmdc-snackbar--active .lmdc-snackbar__action-button:not([aria-hidden]) {
  transition: opacity 0.3s 0ms cubic-bezier(0.4, 0, 1, 1);
  opacity: 1; }

/* stylelint-disable plugin/selector-bem-pattern */
.lmdc-snackbar--multiline.lmdc-snackbar--action-on-bottom .lmdc-snackbar__text {
  margin: 0; }

/* stylelint-enable plugin/selector-bem-pattern */
/* postcss-bem-linter: end */


text:
"use strict";

define([
    './rand',
    './tweeny'
  ], function(
    rand,
    tweeny) {

  /**
   * The Goal.
   * @constructor
   */
  function Goal(services) {
    var globals = services.globals;
    this.services = services;

    this.services.entitySystem.addEntity(this);

    this.material = new THREE.MeshPhongMaterial({
      ambient: 0x808080,
      color: 0x8080FF,
      specular: 0xFFFFFF,
      shininess: 30,
      shading: THREE.FlatShading,
      //wireframe: true,
    });

    this.hue = rand.plusMinus(0.05) + 0.0
    this.material.color.setHSL(this.hue, 0.1, 0.2);
    this.origColor = this.material.color.clone();
    this.root = new THREE.Mesh(services.geometry.goalMesh, this.material);
    this.center = new THREE.Object3D();
    this.center.position.y = globals.goalSize;
    this.root.add(this.center);
    this.center.visible = false;
    this.rotateRate = 0;
    this.hueOffset = 0;
    this.satOffset = 0;
    this.petals = [];
    this.fallingPetals = [];
    this.falling = false;
    this.ripeTimer = 0;

    for (var ii = 0; ii < globals.numPetals; ++ii) {
      var u = ii / globals.numPetals;
      var petal = new THREE.Mesh(services.geometry.petalMesh, this.material);
      this.petals.push(petal);
//      petal.scale.z = 0.1;
//      petal.scale.x = 1;
//      petal.scale.y = 3;
      var angle = Math.PI * 2 * u;
      petal.position.x = Math.cos(angle) * globals.goalSize * 2.5;
      petal.position.y = Math.sin(angle) * globals.goalSize * 2.5;
      petal.rotation.z = angle + Math.PI * 0.5;
      this.center.add(petal);
      var fallingRoot = new THREE.Object3D();
      var falling = new THREE.Mesh(services.geometry.petalMesh, this.material);
      fallingRoot.visible = false;
      fallingRoot.add(falling);
      this.services.scene.add(fallingRoot);
      this.fallingPetals.push(fallingRoot);
    }

    this.services.scene.add(this.root);
    this.timer = rand.range(1000);
    this.animSpeed = rand.range(0.9, 1.1);
    this.vector = new THREE.Vector3();
    this.flashing = false;
    this.bloomTimer = 0;
    this.blooming = false;
  }

  Goal.prototype.remove = function() {
  };

  Goal.prototype.destroy = function() {
    this.services.entitySystem.removeEntity(this);
    this.services.scene.remove(this.root);
  };

  Goal.prototype.process = function() {
    var globals = this.services.globals;
    var tmgr = this.services.tmgr;

    //this.material.needsUpdate = true;
//    this.root.rotation.x += globals.elapsedTime * 2.1;
    this.root.rotation.y += globals.elapsedTime * 0.5;
    this.root.rotation.x = Math.sin(globals.gameTime * this.animSpeed + this.timer) * 0.5;
    this.center.rotation.z += globals.elapsedTime * this.rotateRate;

    var v = this.vector;
    v.set(0, globals.goalSize * 0.9, 0);
    this.root.localToWorld(v);

//    if (v.z > globals.areaBack && v.z < globals.areaFront) {
    if (v.z > globals.areaFront) {
      this.flashing = true;
      //var adjust = Math.sin(globals.gameTime * 40 + this.timer) * 0.25;
      this.material.color.setHSL(this.hue, 1, 0.2);
    } else {
      if (this.flashing) {
        this.flashing = false;
        this.material.color.set(this.origColor);
      }
    }

    // Yes I know all this timer shit is BS! :(

    if (this.bloomTimer > 0 || this.fallingTimer > 0 || this.ripeTimer > 0) {
      this.material.color.setHSL(this.hue + this.hueOffset, 1 + this.satOffset, 0.5);
    }

    if (this.ripeTimer > 0) {
      this.ripeTimer -= globals.elapsedTime;
    }

    if (this.fallingTimer > 0) {
      this.fallingTimer -= globals.elapsedTime;
      if (this.fallingTimer <= 0) {
        this.falling = false;
        this.blooming = false;
        this.ripeTimer = 3;
        tmgr.fromTo(this, 3,
           { satOffset: -1, ease: tweeny.fn.easeInExpo },
           { satOffset:  0 });
        tmgr.fromTo(
          this, 3,
          { hueOffset: 0 },
          { hueOffset: 10 });
        for (var ii = 0; ii < this.fallingPetals.length; ++ii) {
          var falling = this.fallingPetals[ii];
          falling.visible = false;
        }
      }
    }

    if (this.bloomTimer > 0) {
      this.bloomTimer -= globals.elapsedTime;
      if (this.bloomTimer <= 0) {
        // remove the petals
        this.center.visible = false;
        this.falling = true;
        this.fallingTimer = globals.fallDuration;
        tmgr.fromTo(this, globals.fallDuration,
           { satOffset: 0, ease: tweeny.fn.easeInExpo },
           { satOffset: -1 });
        for (var ii = 0; ii < this.petals.length; ++ii) {
          var petal = this.petals[ii];
          var falling = this.fallingPetals[ii];
          falling.visible = true;
          falling.matrix.identity();
          falling.applyMatrix(petal.matrixWorld);
          tmgr.to(falling.position, rand.range(globals.fallDuration - 1,  globals.fallDuration + 1),
             { x: falling.position.x + rand.plusMinus(10),
               y: globals.areaBottom - 6,
               ease: tweeny.fn.easeInCubic,
             });
          tmgr.fromTo(falling.children[0].rotation, globals.fallDuration,
              { z: 0, y: 0, ease: tweeny.fn.easeInCubic },
              { z: 10, y: rand.range(20, 25) });
        }
      }
    }

    if (this.flashing && !this.blooming && !this.falling && this.ripeTimer <= 0) {
      v.applyProjection(this.services.camera.projectionMatrix);
      var distSq = globals.goalHitSize * globals.goalHitSize;
      var players = this.services.playerManager.players;
      for (var ii = 0, len = players.length; ii < len; ++ii) {
        var player = players[ii];
        var dx = v.x - player.collision.x;
        var dy = v.y - player.collision.y;
        if (dx * dx + dy * dy < distSq) {
          if (globals.showCollision) {
            this.material.color.setHSL(this.hue + 0.5, 1, 0.5);
          }
          if (!this.blooming) {
            this.blooming = true;
            this.bloomTimer = globals.bloomDuration;
            this.center.visible = true;
            tmgr.fromTo(
              this.center.scale, 3,
              { x: 0, y: 0, z: 0 },
              { x: 1, y: 1, z: 1 });
            tmgr.fromTo(
              this, 5,
              { rotateRate: 0, ease: tweeny.fn.boomerangSmooth, },
              { rotateRate: 20 });
            tmgr.fromTo(
              this, 5,
              { hueOffset: 0 },
              { hueOffset: 5 });
          }
          break;
        }
      }
    }
  };

  return Goal;
});


text:
package mentalpoker;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Random;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * The Class RSAService.
 *
 * @author Benjamin Evans
 * @author Emile Victor
 * @version 1.0
 */
public class RSAService {

	/** The key size. */
	private static final int KEY_SIZE = 512;

	/** The max encryption size. */
	private static final int MAX_ENC_SIZE = 128;

	/* Standard RSA Variables. */

	/** The p. */
	private BigInteger p;

	/** The q. */
	private BigInteger q;

	/** The n. */
	private BigInteger n;

	/** The on. */
	private BigInteger on;

	/** The encryption key. */
	private BigInteger e = null;

	/** The decryption key. */
	private BigInteger d;

	/**
	 * Instantiates a new rsa service.
	 *
	 * @throws InvalidKeySpecException the invalid key spec exception
	 * @throws NoSuchAlgorithmException the no such algorithm exception
	 * @throws NoSuchPaddingException the no such padding exception
	 * @throws NoSuchProviderException the no such provider exception
	 */
	public RSAService() throws InvalidKeySpecException,
			NoSuchAlgorithmException, NoSuchPaddingException,
			NoSuchProviderException {

		Security.addProvider(new BouncyCastleProvider());
		p = genPrime(KEY_SIZE);
		q = genPrime(KEY_SIZE);
		n = p.multiply(q);
		BigInteger qSub = q.subtract(BigInteger.ONE);
		BigInteger pSub = p.subtract(BigInteger.ONE);
		on = pSub.multiply(qSub);

		genKeys();
		return;
	}

	/**
	 * Instantiates a new rsa service with given p and q.
	 *
	 * @param gp the given p
	 * @param gq the given q
	 * @throws InvalidKeySpecException the invalid key spec exception
	 * @throws NoSuchAlgorithmException the no such algorithm exception
	 * @throws NoSuchPaddingException the no such padding exception
	 * @throws NoSuchProviderException the no such provider exception
	 */
	public RSAService(BigInteger gp, BigInteger gq)
			throws InvalidKeySpecException, NoSuchAlgorithmException,
			NoSuchPaddingException, NoSuchProviderException {

		Security.addProvider(new BouncyCastleProvider());
		this.p = new BigInteger(gp.toString());
		this.q = new BigInteger(gq.toString());
		n = p.multiply(q);
		BigInteger qSub = q.subtract(BigInteger.ONE);
		BigInteger pSub = p.subtract(BigInteger.ONE);
		on = pSub.multiply(qSub);
		genKeys();
		return;
	}

	/**
	 * Instantiates a new rsa service. This constructor is only to be used
	 * during validation. It only allows decryption.
	 *
	 * @param gp the given p
	 * @param gq the given q
	 * @param gd the given decryption key
	 * @throws InvalidKeySpecException the invalid key spec exception
	 * @throws NoSuchAlgorithmException the no such algorithm exception
	 * @throws NoSuchPaddingException the no such padding exception
	 * @throws NoSuchProviderException the no such provider exception
	 */
	public RSAService(BigInteger gp, BigInteger gq, BigInteger gd)
			throws InvalidKeySpecException, NoSuchAlgorithmException,
			NoSuchPaddingException, NoSuchProviderException {
		Security.addProvider(new BouncyCastleProvider());
		this.p = new BigInteger(gp.toString());
		this.q = new BigInteger(gq.toString());
		n = p.multiply(q);
		BigInteger qSub = q.subtract(BigInteger.ONE);
		BigInteger pSub = p.subtract(BigInteger.ONE);
		on = pSub.multiply(qSub);
		this.d = new BigInteger(gd.toString());
		return;
	}

	/**
	 * Gets the p prime.
	 *
	 * @return the p value
	 */
	public BigInteger getP() {
		return new BigInteger(this.p.toString());
	}

	/**
	 * Gets the q prime.
	 *
	 * @return the q value
	 */
	public BigInteger getQ() {
		return new BigInteger(this.q.toString());
	}

	/**
	 * Gets the decryption key.
	 *
	 * @return the d value
	 */
	public BigInteger getD() {
		return new BigInteger(this.d.toString());
	}

	/**
	 * Generates a large prime.
	 *
	 * @param size the size of the prime
	 * @return the big integer prime
	 */
	private BigInteger genPrime(int size) {
		Random rnd = new Random();
		BigInteger bp = BigInteger.probablePrime(size, rnd);
		return bp;
	}

	/**
	 * Generates the keys.
	 *
	 * @throws NoSuchAlgorithmException the no such algorithm exception
	 * @throws InvalidKeySpecException the invalid key spec exception
	 */
	private void genKeys() throws NoSuchAlgorithmException,
			InvalidKeySpecException {

		BigInteger tmp;
		BigInteger testRes;
		while (true) {
			tmp = genPrime(KEY_SIZE);
			testRes = on.divideAndRemainder(tmp)[1];
			if (testRes.compareTo(BigInteger.ZERO) != 0) {
				e = tmp;
				d = e.modInverse(on);
				return;
			}
		}
	}

	/**
	 * Encrypts a byte string.
	 *
	 * @param data the data to encrypt
	 * @return the encrypted data
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	private byte[] encrypt(byte[] data) throws InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {

		if (data.length > MAX_ENC_SIZE) {
			System.err
					.println("Data to long to encrypt. Reason: Possible cheating! Fix: Exit");
			System.exit(1);
		}

		RSAKeyParameters kp = new RSAKeyParameters(false, n, e);
		RSAEngine engine = new RSAEngine();
		engine.init(true, kp);
		byte[] cText = engine.processBlock(data, 0, data.length);
		return cText;
	}

	/**
	 * Decrypts a byte String.
	 *
	 * @param data the data to decrypt
	 * @return the decrypted data
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	private byte[] decrypt(byte[] data) throws InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {

		if (data.length > MAX_ENC_SIZE) {
			System.err
					.println("Data to long to decrypt. Reason: Possible cheating! Fix: Exit");
			System.exit(1);
		}

		RSAKeyParameters kp = new RSAKeyParameters(true, n, d);
		RSAEngine engine = new RSAEngine();
		engine.init(false, kp);
		byte[] dText = engine.processBlock(data, 0, data.length);
		return dText;
	}

	/**
	 * Encrypts a card.
	 *
	 * @param card the card to encrypt
	 * @return the encrypted card
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	private EncryptedCard encryptCard(Card card) throws InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {

		if (e == null) {
			System.err
					.println("Cannot encrypt when using decrypting constructor RSAService(gp, gq, gd)");
			return null;
		}
		String encCardData = String.valueOf(card.cardType) + card.suit;
		EncryptedCard encCard = new EncryptedCard();
		encCard.cardData = encrypt(encCardData.getBytes());
		return encCard;
	}

	/**
	 * Decrypts a card.
	 *
	 * @param encCard the encrypted card
	 * @return the decrypted card
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	private Card decryptCard(EncryptedCard encCard) throws InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {

		String data = new String(decrypt(encCard.cardData));
		char type = data.charAt(0);
		String suit = data.substring(1).toString();
		Card card = new Card(type, suit);
		return card;
	}

	/**
	 * Encrypts an already encrypted card.
	 *
	 * @param card the encrypted card
	 * @return the encrypted, encrypted card
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	private EncryptedCard encryptEncCard(EncryptedCard card)
			throws InvalidKeyException, IllegalBlockSizeException,
			BadPaddingException {

		if (e == null) {
			System.err
					.println("Cannot encrypt when using decrypting constructor RSAService(gp, gq, gd)");
			return null;
		}
		EncryptedCard encCard = new EncryptedCard();
		encCard.cardData = encrypt(card.cardData);
		return encCard;
	}

	/**
	 * Decrypts an encrypted, encrypted card.
	 *
	 * @param encCard the encrypted, encrypted card
	 * @return the encrypted card
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	private EncryptedCard decryptEncCard(EncryptedCard encCard)
			throws InvalidKeyException, IllegalBlockSizeException,
			BadPaddingException {

		EncryptedCard card = new EncryptedCard();
		card.cardData = decrypt(encCard.cardData);
		return card;
	}

	/**
	 * Encrypt an encrypted deck.
	 *
	 * @param encDeck the encrypted deck
	 * @return the encrypted, encrypted deck
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	public EncryptedDeck encryptEncDeck(EncryptedDeck encDeck)
			throws InvalidKeyException, IllegalBlockSizeException,
			BadPaddingException {

		if (e == null) {
			System.err
					.println("Cannot encrypt when using decrypting constructor RSAService(gp, gq, gd)");
			return null;
		}
		for (int i = 0; i < Deck.NUM_CARDS; i++) {
			EncryptedCard tmp = encDeck.data.get(i);
			encDeck.data.set(i, encryptEncCard(tmp));
		}
		return encDeck;
	}

	/**
	 * Decyrpt an encrypted hand.
	 *
	 * @param hand the hand
	 * @return the encrypted hand
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	public EncryptedHand decyrptEncHand(EncryptedHand hand)
			throws InvalidKeyException, IllegalBlockSizeException,
			BadPaddingException {

		EncryptedHand ret = new EncryptedHand();
		for (int i = 0; i < Hand.NUM_CARDS; i++) {
			EncryptedCard tmp = hand.data.get(i);
			ret.data.add(decryptEncCard(tmp));
		}
		return ret;
	}

	/**
	 * Decyrpt a hand.
	 *
	 * @param hand the hand
	 * @return the hand
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	public Hand decyrptHand(EncryptedHand hand) throws InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {

		Hand ret = new Hand();
		for (int i = 0; i < Hand.NUM_CARDS; i++) {
			EncryptedCard tmp = hand.data.get(i);
			ret.data.add(decryptCard(tmp));
		}
		return ret;
	}

	/**
	 * Decyrpt encrypted, encrypted community cards.
	 *
	 * @param cards the cards
	 * @return the encrypted community cards
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	public EncryptedCommunityCards decyrptEncComCards(
			EncryptedCommunityCards cards) throws InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {

		EncryptedCommunityCards ret = new EncryptedCommunityCards();
		ret.setUserList(cards.getUserList());
		for (int i = 0; i < CommunityCards.NUM_CARDS; i++) {
			EncryptedCard tmp = cards.data.get(i);
			ret.data.add(decryptEncCard(tmp));
		}
		return ret;
	}

	/**
	 * Decyrpt community cards.
	 *
	 * @param cards the cards
	 * @return the community cards
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	public CommunityCards decyrptComCards(EncryptedCommunityCards cards)
			throws InvalidKeyException, IllegalBlockSizeException,
			BadPaddingException {

		CommunityCards ret = new CommunityCards();
		for (int i = 0; i < CommunityCards.NUM_CARDS; i++) {
			EncryptedCard tmp = cards.data.get(i);
			ret.data.add(decryptCard(tmp));
		}
		return ret;
	}

	/**
	 * Encrypt a deck.
	 *
	 * @param deck the deck
	 * @return the encrypted deck
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	public EncryptedDeck encryptDeck(Deck deck)
			throws InvalidKeyException, IllegalBlockSizeException,
			BadPaddingException {

		if (e == null) {
			System.err
					.println("Cannot encrypt when using decrypting constructor RSAService(gp, gq, gd)");
			return null;
		}
		EncryptedDeck encDeck = new EncryptedDeck();
		for (int i = 0; i < Deck.NUM_CARDS; i++) {
			EncryptedCard tmp = encryptCard(deck.getCardAtIndex(i));
			if (i >= encDeck.data.size()) {
				encDeck.data.add(tmp);
			} else {
				encDeck.data.set(i, tmp);
			}

		}
		return encDeck;
	}

	/**
	 * Encrypt an encrypted hand.
	 *
	 * @param encHand the encrypted hand
	 * @return the encrypted hand
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	public EncryptedHand encryptEncHand(EncryptedHand encHand) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
		if (e == null) {
			System.err
					.println("Cannot encrypt when using decrypting constructor RSAService(gp, gq, gd)");
			return null;
		}
		EncryptedHand ret = new EncryptedHand();
		for (int i = 0; i < Hand.NUM_CARDS; i++) {
			EncryptedCard tmp = encryptEncCard(encHand.data.get(i));
			ret.data.add(tmp);
		}
		return ret;
	}

	/**
	 * Verifies the winners hand.
	 *
	 * @param gameUser the game user
	 * @param userHands the users hands
	 * @param winner the winner
	 * @param rsaServ the rsa service
	 * @return true, if verified
	 * @throws InvalidKeySpecException the invalid key spec exception
	 * @throws NoSuchAlgorithmException the no such algorithm exception
	 * @throws NoSuchPaddingException the no such padding exception
	 * @throws NoSuchProviderException the no such provider exception
	 * @throws InvalidKeyException the invalid key exception
	 * @throws IllegalBlockSizeException the illegal block size exception
	 * @throws BadPaddingException the bad padding exception
	 */
	public boolean checkWinnersHand(User gameUser, ArrayList<User> userHands, User winner, RSAService rsaServ) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
		Hand uHand = winner.getUsersHand();
		Hand dHand;
		EncryptedHand eHand = winner.getUsersOriginalHand();
		BigInteger p = rsaServ.getP();
		BigInteger q = rsaServ.getQ();
		for (User usr: userHands){
			if (usr.getID().equals(gameUser.getID())){
				continue;
			}
			RSAService tmpRSA = new RSAService(p, q, usr.getDecryptionKey());
			eHand = tmpRSA.decyrptEncHand(eHand);
		}
		dHand = rsaServ.decyrptHand(eHand);

		//now compare the hands
		for(int i = 0; i < Hand.NUM_CARDS; i++){
			if(dHand.data.get(i).checkIfJibberish()){
				//cards are not valid
				return false;
			}
			if (uHand.data.get(i).cardType != dHand.data.get(i).cardType){
				return false;
			}
			if (!uHand.data.get(i).suit.equals(dHand.data.get(i).suit)){
				return false;
			}
		}
		System.out.println("Winners hand verified as:");
		for(int i = 0; i < Hand.NUM_CARDS; i++){
			System.out.println(Character.toString(dHand.data.get(i).cardType) + "-" + new String(dHand.data.get(i).suit));
		}
		return true;
	}

}


text:
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import autobind from 'autobind-decorator';
import highlight from 'highlight.js';
import * as misc from '../../common/misc';
import { markdownToHTML } from '../../common/markdown-to-html';

@autobind
class MarkdownPreview extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      compiled: '',
      renderError: '',
    };
  }

  /**
   * Debounce and compile the markdown (won't debounce first render)
   */
  _compileMarkdown(markdown) {
    clearTimeout(this._compileTimeout);
    this._compileTimeout = setTimeout(
      async () => {
        try {
          const { handleRender } = this.props;
          const rendered = handleRender ? await handleRender(markdown) : markdown;
          const compiled = markdownToHTML(rendered);
          this.setState({
            compiled,
            renderError: '',
          });
        } catch (err) {
          this.setState({
            renderError: err.message,
            compiled: '',
          });
        }
      },
      this.state.compiled ? this.props.debounceMillis : 0,
    );
  }

  _setPreviewRef(n) {
    this._preview = n;
  }

  _handleClickLink(e) {
    e.preventDefault();
    misc.clickLink(e.target.getAttribute('href'));
  }

  _highlightCodeBlocks() {
    if (!this._preview) {
      return;
    }

    const el = ReactDOM.findDOMNode(this._preview);
    for (const block of el.querySelectorAll('pre > code')) {
      highlight.highlightBlock(block);
    }

    for (const a of el.querySelectorAll('a')) {
      a.title = `Open ${a.getAttribute('href')} in browser`;
      a.removeEventListener('click', this._handleClickLink);
      a.addEventListener('click', this._handleClickLink);
    }
  }

  componentWillUnmount() {
    clearTimeout(this._compileTimeout);
  }

  componentWillMount() {
    this._compileMarkdown(this.props.markdown);
  }

  componentWillReceiveProps(nextProps) {
    this._compileMarkdown(nextProps.markdown);
  }

  componentDidUpdate() {
    this._highlightCodeBlocks();
  }

  componentDidMount() {
    this._highlightCodeBlocks();
  }

  render() {
    const { className, heading } = this.props;
    const { compiled, renderError } = this.state;

    let html = heading ? `<h1>${heading}</h1>\n${compiled}` : compiled;

    return (

        {renderError &&
Failed to render: {renderError}
}

          {/* Set from above */}

    );
  }
}

MarkdownPreview.propTypes = {
  // Required
  markdown: PropTypes.string.isRequired,

  // Optional
  handleRender: PropTypes.func,
  className: PropTypes.string,
  debounceMillis: PropTypes.number,
  heading: PropTypes.string,
};

export default MarkdownPreview;


text:
<?php namespace Hpolthof\Admin\Widget\Chart;

use Hpolthof\Admin\Dataset;
use Hpolthof\Admin\Widget\Widget;

abstract class AbstractChart extends Widget implements ChartInterface
{
    protected $labels = array();
    protected $datasets = array();

    public function addDataset(Dataset $dataset)
    {
        $this->datasets[] = $dataset;
        return $this;
    }

    public function getDatasets()
    {
        return $this->datasets;
    }

    /**
     * @return array
     */
    public function getLabels()
    {
        return $this->labels;
    }

    /**
     * @param array $labels
     * @return AbstractChart
     */
    public function setLabels($labels)
    {
        $this->labels = $labels;
        return $this;
    }

    public function addLabel($label)
    {
        $this->labels[] = $label;
        return $this;
    }

    protected function getDataArray()
    {
        $datasets = array();
        foreach($this->datasets as $ds) {
            $datasets[] = $ds->toArray();
        }

        return array(
            'labels' => $this->labels,
            'datasets' => $datasets,
        );
    }
}


text:
package org.nd4j.linalg.jcublas.util;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import jcuda.Pointer;
import jcuda.Sizeof;
import jcuda.driver.CUstream;
import jcuda.driver.CUstream_flags;
import jcuda.driver.JCudaDriver;
import jcuda.runtime.JCuda;
import jcuda.runtime.cudaMemcpyKind;
import jcuda.runtime.cudaStream_t;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.Accumulation;
import org.nd4j.linalg.api.ops.Op;
import org.nd4j.linalg.jcublas.CublasPointer;
import org.nd4j.linalg.jcublas.buffer.JCudaBuffer;
import org.nd4j.linalg.jcublas.complex.ComplexDouble;
import org.nd4j.linalg.jcublas.context.ContextHolder;
import org.nd4j.linalg.jcublas.context.CudaContext;
import org.nd4j.linalg.jcublas.gpumetrics.GpuMetrics;
import org.nd4j.linalg.jcublas.kernel.KernelFunctions;

import java.util.ArrayList;
import java.util.List;

import static jcuda.driver.JCudaDriver.cuMemGetInfo;

/**
 * Wraps the generation of kernel parameters
 * , creating, copying
 * and destroying any cuda device allocations
 *
 * @author bam4d
 *
 */
public class KernelParamsWrapper implements AutoCloseable {

    private boolean closeInvoked = false;

    private boolean closeContext;

    private CudaContext context;

    /**
     * List of processed kernel parameters ready to be passed to the kernel
     */
    final public Object[] kernelParameters;

    /**
     * The pointers that need to be freed as part of this closable resource
     */
    final List<CublasPointer> pointersToFree;

    /**
     * The pointers that have results that need to be passed back to host buffers
     */
    final List<CublasPointer> resultPointers;

    /**
     * The operation that should receive the result
     */
    private Op resultOp;

    /**
     * The list of processed kernel parameters, These should be get passed to the cuda kernel
     * @return
     */
    public Object[] getKernelParameters() {
        return kernelParameters;
    }

    /**
     * conversion list of arrays to their assigned cublas pointer
     */
    private Multimap<INDArray, CublasPointer> arrayToPointer;

    private int resultLength = 1;

    /**
     * set the array that will contain the results, If the array is not set, then data from the device will not be copied to the host
     * @param array
     * @return
     */
    public KernelParamsWrapper setResultArray(INDArray array) {
        CublasPointer resultPointer = arrayToPointer.get(array).iterator().next();
        resultPointer.setResultPointer(true);
        if(resultPointer == null) {
            throw new RuntimeException("Results array must be supplied as a kernel parameter");
        }

        resultPointers.add(resultPointer);

        return this;
    }

    /**
     * set the Op that this result is for
     * @param op
     * @param result
     * @return
     */
    public KernelParamsWrapper setResultOp(Accumulation op, INDArray result) {
        resultOp = op;
        setResultArray(result);
        return this;
    }
    /**
     * Create a new wrapper for the kernel parameters.
     *
     * This wrapper manages the host - and device communication and.
     *
     * To set the result on a specific operation, use setResultOp()
     * To set the array which is the result INDArray, use setResultArray()
     * @param kernelParams
     */
    public KernelParamsWrapper(Op op,Object... kernelParams) {
        this(op,false, kernelParams);
    }
    /**
     * Create a new wrapper for the kernel parameters.
     *
     * This wrapper manages the host - and device communication and.
     *
     * To set the result on a specific operation, use setResultOp()
     * To set the array which is the result INDArray, use setResultArray()
     * @param kernelParams
     */
    public KernelParamsWrapper(Op op,boolean closeContext,Object... kernelParams) {
        kernelParameters = new Object[kernelParams.length];
        arrayToPointer = ArrayListMultimap.create();
        pointersToFree = new ArrayList<>();
        resultPointers = new ArrayList<>();
        context = new CudaContext(closeContext);
        context.initOldStream();
        context.initStream();
        this.closeContext = closeContext;

        for(int i = 0; i < kernelParams.length; i++) {
            Object arg = kernelParams[i];

            // If the instance is a JCudaBuffer we should assign it to the device
            if(arg instanceof JCudaBuffer) {
                JCudaBuffer buffer = (JCudaBuffer) arg;
                CublasPointer pointerToFree = new CublasPointer(buffer,context);
                kernelParameters[i] = pointerToFree.getDevicePointer();
                pointersToFree.add(pointerToFree);
            }
            else if(arg instanceof INDArray) {
                INDArray array = (INDArray) arg;
                CublasPointer pointerToFree = new CublasPointer(array,context);
                kernelParameters[i] = pointerToFree.getDevicePointer();
                pointersToFree.add(pointerToFree);
                arrayToPointer.put(array, pointerToFree);
            }
            else
                kernelParameters[i] = arg;

        }

    }

    /**
     * Free all the buffers from this kernel's parameters
     */
    @Override
    public void close() throws Exception {
        if(closeInvoked)
            return;

        for(CublasPointer cublasPointer : pointersToFree) {
            if(resultPointers.contains(cublasPointer)) {
                //sets the result for the buffer
                //since this ends up being a scalar
                if(closeContext) {
                    if(cublasPointer.getBuffer().length() == 1 && resultOp instanceof Accumulation) {
                        setResultForOp(resultOp, cublasPointer);
                    }
                    else
                        cublasPointer.copyToHost();
                    cublasPointer.close();
                }
                else
                    context.setResultPointer(cublasPointer);
            }

        }

        if(closeContext)
            context.destroy();
        closeInvoked = true;
    }

    /**
     * Set the result within the accumulation operation
     * @param acc
     * @param devicePointer
     */
    private void setResultForOp(Op acc, CublasPointer devicePointer) {
        if (devicePointer.getBuffer().dataType() == DataBuffer.Type.DOUBLE) {
            double[] data = new double[resultLength];
            Pointer get = Pointer.to(data);

            JCuda.cudaMemcpyAsync(
                    get
                    , devicePointer.getDevicePointer()
                    , resultLength * Sizeof.DOUBLE
                    , cudaMemcpyKind.cudaMemcpyDeviceToHost
                    , context.getOldStream());
            context.syncOldStream();

            if(acc instanceof Accumulation) {
                Accumulation acc2 = (Accumulation) acc;
                acc2.setFinalResult(data[0]);
            }

        }
        else if (devicePointer.getBuffer().dataType() == DataBuffer.Type.FLOAT) {
            float[] data = new float[resultLength];
            Pointer get = Pointer.to(data);

            JCuda.cudaMemcpyAsync(
                    get
                    , devicePointer.getDevicePointer()
                    , resultLength * Sizeof.FLOAT
                    , cudaMemcpyKind.cudaMemcpyDeviceToHost
                    , context.getOldStream());
            context.syncOldStream();

            if(acc instanceof Accumulation) {
                Accumulation acc2 = (Accumulation) acc;
                acc2.setFinalResult(data[0]);
            }

        }
    }

    public CudaContext getContext() {
        return context;
    }

    /**
     * Sync the streams
     */
    public void sync() {
        context.syncStream();
    }

}


text:
module BlueConductor
  class Producer
    attr_reader :band, :title, :songs, :image, :error
    attr_accessor :url_generator, :request, :parser

    def initialize(band, record_title)
      @band = band
      @title = record_title
      @songs = nil
      @image = ''
      @error = ''
    end

    def record!
      url       = url_generator.generate(self)
      html      = request.fetch(url)
      tracklist = parser.parse(html)

      if tracklist.nil? || tracklist.empty?
        @error = 'The album requested is not available || there was a spelling error'
      else
        @image = parser.parse_image(html)

        @songs = tracklist.map do |song|
          BlueConductor.song_for(@band, song)
        end
      end

      self
    end
  end
end


text:
class IDEA121153 {
  String foo()
  {
    try (Resource r = getResource()) {
    }
    return <caret>r.get();
  }

  public Resource getResource() {
    return new Resource();
  }

  class Resource implements AutoCloseable{

    @Override
    public void close() {

    }

    public String get() {
      return "";
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2015 Waterloo Mobile Studio

  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.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_selector"
    android:orientation="horizontal"
    android:padding="5dip" >
    <!-- ListRow Left side thumbnail image -->
    <LinearLayout
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_marginEnd="5dp">
        <ImageView
            android:id="@+id/imageViewRepresentativeImage"
            android:contentDescription="@string/app_name"
            android:layout_width="60dip"
            android:layout_height="60dip"
            android:background="@drawable/image_border"
            android:src="@drawable/place_holder_image" />
    </LinearLayout>

    <ImageView
        android:id="@+id/imageViewArrow"
        android:contentDescription="@string/app_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:src="@drawable/arrow" />

    <TextView
        android:id="@+id/textViewTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="5dp"
        android:layout_marginEnd="5dp"
        android:layout_toStartOf="@+id/imageViewArrow"
        android:layout_toEndOf="@+id/thumbnail"
        android:paddingBottom="5dp"
        android:text="@string/productName"
        android:textColor="#040404"
        android:textSize="16sp"
        android:textStyle="bold"
        android:typeface="sans" />

    <TextView
        android:id="@+id/textViewDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/textViewTitle"
        android:layout_alignEnd="@+id/textViewTitle"
        android:layout_below="@+id/textViewTitle"
        android:paddingTop="5dp"
        android:layout_marginBottom="2dp"
        android:text="@string/productDesc"
        android:textColor="#343434"
        android:textSize="14sp" />

</RelativeLayout>


text:
namespace arangodb {
namespace graph {

template<class QueueImpl>
class QueueTracer {
  using Step = typename QueueImpl::Step;

 public:
  explicit QueueTracer(arangodb::ResourceMonitor& resourceMonitor);
  ~QueueTracer();

  void clear();
  void append(Step step);
  void setStartContent(std::vector<Step> startSteps);
  bool firstIsVertexFetched() const;
  bool hasProcessableElement() const;
  size_t size() const;
  bool isEmpty() const;
  std::vector<Step*> getLooseEnds();

  Step pop();

  // Return all Steps where the Provider needs to call fetchVertices()
  // for in order to be able to process them
  std::vector<Step*> getStepsWithoutFetchedVertex();

  // Return all Steps where the Provider needs to call fetchEdges()
  // for in order to be able to process them.
  // Note here, we hand in the vector of Steps, as in the place
  // we are using this method we have already popped the first
  // Step from the queue, but it cannot be processed.
  void getStepsWithoutFetchedEdges(std::vector<Step*>& stepsToFetch);

 private:
  QueueImpl _impl;

  // Mapping MethodName => Statistics
  // We make this mutable to not violate the captured API
  mutable containers::FlatHashMap<std::string, TraceEntry> _stats;
};

}  // namespace graph
}  // namespace arangodb


text:
package it.cnr.isti.vir.similarity;

import it.cnr.isti.vir.features.localfeatures.ALocalFeaturesGroup;

public interface ILFSimilarity<E> extends ISimilarity<E> {

	public Class<E> getRequestedFeatureClass();

	public Class<ALocalFeaturesGroup<?>> getRequestedFeatureGroupClass();
}


text:
export const UPDATE_STUDENT_SUCCESS = 'UPDATE_STUDENT_SUCCESS';
export const SET_PROJECT_ID = 'SET_PROJECT_ID';
export const SET_PAGE_TITLE = 'SET_PAGE_TITLE';
export const BEGIN_AJAX_CALL = 'BEGIN_AJAX_CALL';
export const END_AJAX_CALL = 'END_AJAX_CALL';
export const AJAX_CALL_ERROR = 'AJAX_CALL_ERROR';


text:
/*
 * (C) 2007-2012 Alibaba Group Holding Limited.
 *
 * 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.
 * Authors:
 *   dogun (yuexuqiang at gmail.com)
 */
package com.taobao.common.store.util;

import java.io.Serializable;

/**
 * ÓÉÓÚbyte[]×÷ΪmapµÄkeyʱ£¬»áÔì³Éÿ´ÎµÄkey¶¼²»Ò»Ñù£¬ËùÒÔ±ØÐë·âװһϡ£ <br />
 * ¸ÃÀà¾ÍÊÇ·â×°ÁËbyte[]
 *
 * @author dogun (yuexuqiang at gmail.com)
 */
public class BytesKey implements Serializable {
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -6296965387124592707L;

    private byte[] data;

    public BytesKey(final byte[] data) {
        this.data = data;
    }

    /**
     * @return the data
     */
    public byte[] getData() {
        return data;
    }

    /**
     * @param data
     *            the data to set
     */
    public void setData(final byte[] data) {
        this.data = data;
    }

    @Override
    public int hashCode() {
        int h = 0;
        if (null != this.data) {
            for (int i = 0; i < this.data.length; i++) {
                h = 31 * h + data[i++];
            }
        }
        return h;
    }

    @Override
    public boolean equals(final Object o) {
        if (null == o || !(o instanceof BytesKey)) {
            return false;
        }
        final BytesKey k = (BytesKey) o;
        if (null == k.getData() && null == this.getData()) {
            return true;
        }
        if (null == k.getData() || null == this.getData()) {
            return false;
        }
        if (k.getData().length != this.getData().length) {
            return false;
        }
        for (int i = 0; i < this.data.length; ++i) {
            if (this.data[i] != k.getData()[i]) {
                return false;
            }
        }
        return true;
    }
}


text:
Parse.Cloud.define("hello", function(request, response) {
  response.success("Hola " + request.params.nombre);
});


text:
package com.amazonaws.services.inspector.model;

import java.io.Serializable;

/**
 *

 * This data type is used in the LocalizedText data type.
 *

 */
public class LocalizedTextKey implements Serializable, Cloneable {

    /**
     *

     * The module response source of the text.
     *

     */
    private String facility;
    /**
     *

     * Part of the module response source of the text.
     *

     */
    private String id;

    /**
     *

     * The module response source of the text.
     *

     *
     * @param facility
     *        The module response source of the text.
     */
    public void setFacility(String facility) {
        this.facility = facility;
    }

    /**
     *

     * The module response source of the text.
     *

     *
     * @return The module response source of the text.
     */
    public String getFacility() {
        return this.facility;
    }

    /**
     *

     * The module response source of the text.
     *

     *
     * @param facility
     *        The module response source of the text.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public LocalizedTextKey withFacility(String facility) {
        setFacility(facility);
        return this;
    }

    /**
     *

     * Part of the module response source of the text.
     *

     *
     * @param id
     *        Part of the module response source of the text.
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     *

     * Part of the module response source of the text.
     *

     *
     * @return Part of the module response source of the text.
     */
    public String getId() {
        return this.id;
    }

    /**
     *

     * Part of the module response source of the text.
     *

     *
     * @param id
     *        Part of the module response source of the text.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public LocalizedTextKey withId(String id) {
        setId(id);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getFacility() != null)
            sb.append("Facility: " + getFacility() + ",");
        if (getId() != null)
            sb.append("Id: " + getId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof LocalizedTextKey == false)
            return false;
        LocalizedTextKey other = (LocalizedTextKey) obj;
        if (other.getFacility() == null ^ this.getFacility() == null)
            return false;
        if (other.getFacility() != null
                && other.getFacility().equals(this.getFacility()) == false)
            return false;
        if (other.getId() == null ^ this.getId() == null)
            return false;
        if (other.getId() != null
                && other.getId().equals(this.getId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getFacility() == null) ? 0 : getFacility().hashCode());
        hashCode = prime * hashCode
                + ((getId() == null) ? 0 : getId().hashCode());
        return hashCode;
    }

    @Override
    public LocalizedTextKey clone() {
        try {
            return (LocalizedTextKey) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
package org.unitime.localization.impl;

import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.unitime.localization.messages.Messages;

/**
 * @author Tomas Muller
 */
public class BundleTag extends BodyTagSupport {
	private static final long serialVersionUID = 8594907730878329848L;
	public static final String DEFAULT_ID = "MSG";

	private String iName = null;
	public String getName() { return iName; }
	public void setName(String name) { iName = name; }

	private String iId = DEFAULT_ID;
	public String getId() { return iId; }
	public void setId(String id) { iId = id; }

	@Override
	public int doStartTag() throws JspTagException {
		try {
			try {
				pageContext.setAttribute(getId(), Localization.create((Class<? extends Messages>)Class.forName(Localization.ROOT + getName())));
			} catch (ClassNotFoundException f) {
				pageContext.setAttribute(getId(), Localization.create((Class<? extends Messages>)Class.forName(getName())));
			}
		} catch (Exception e) {
            throw new JspTagException("Unable to find messages '" + getName() + "': " + e.getMessage(), e);
		}
		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doEndTag() {
		return EVAL_PAGE;
	}

	@Override
	public int doAfterBody() {
		return SKIP_BODY;
	}

}


text:
package com.github.blahord.integral.component.xml;

import com.github.blahord.bettercollections.list.ArrayList;
import com.github.blahord.bettercollections.list.List;
import com.github.blahord.bettercollections.list.MutableList;
import com.github.blahord.bettercollections.map.HashMap;
import com.github.blahord.bettercollections.map.Map;
import com.github.blahord.integral.ComponentException;
import com.github.blahord.integral.component.ProducerComponent;
import com.github.blahord.integral.data.DataRow;
import com.github.blahord.integral.data.DataRowBuilder;
import com.github.blahord.integral.schema.Schema;
import com.github.blahord.integral.schema.SchemaColumn;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.util.concurrent.Semaphore;

import static com.github.blahord.bettercollections.compatibility.ListWrappers.asJavaUtilList;
import static com.github.blahord.bettercollections.util.Lists.asList;

public class ReadXML extends ProducerComponent {

    private final InputStream inputStream;
    private final Map<? extends String, ? extends SchemaColumn> xPathMapping;
    private final List<? extends String> groupingXPaths;

    private final String outputName;

    private Exception readXmlException = null;
    private final MutableList<? extends String, ? super String> currentPath = ArrayList.create();
    private final MutableList<? extends DataRowBuilder, ? super DataRowBuilder> dataRowBuilderStack = ArrayList.create();
    private DataRow dataRowToOutput = null;
    private int currentGroupingLevel = -1;

    private final Semaphore readLock = new Semaphore(1);
    private final Semaphore outputLock = new Semaphore(1);

    public ReadXML(String name, InputStream inputStream, java.util.Map<? extends String, ? extends SchemaColumn> xPathMapping, java.util.List<? extends String> groupingXPaths, String outputName) {
        super(name);
        this.inputStream = inputStream;
        this.xPathMapping = HashMap.create(xPathMapping);
        this.groupingXPaths = ArrayList.create(groupingXPaths);
        this.outputName = outputName;

        addOutput(outputName, new Schema(xPathMapping.values()));
    }

    @Override
    public void onJobStarted() throws ComponentException {
        try {
            final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
            xmlReader.setContentHandler(new ReadXMLContentHandler());

            acquireLock(outputLock);
            new ReadXMLThread(xmlReader).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void runInternal() throws ComponentException {
        if (readXmlException != null) {
            throw new ComponentException("Could not read document", readXmlException);
        }

        acquireLock(outputLock);

        if (dataRowToOutput == DataRow.EOI) {
            finishProcessing();
        } else {
            addToOutput(outputName, dataRowToOutput);
        }

        dataRowToOutput = null;

        readLock.release();
    }

    private void acquireLock(Semaphore semaphore) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            throw new RuntimeException("Could not acquire lock", e);
        }
    }

    private String compileCurrentPath(String... additionalPathElements) {
        final String path = "/" + String.join("/", asJavaUtilList(currentPath)) +
                "/" + String.join("/", asJavaUtilList(asList(additionalPathElements)));

        return path.substring(0, path.length() - 1);
    }

    private final class ReadXMLThread extends Thread {

        private final XMLReader xmlReader;

        private ReadXMLThread(XMLReader xmlReader) {
            this.xmlReader = xmlReader;
        }

        @Override
        public void run() {
            try {
                xmlReader.parse(new InputSource(inputStream));
            } catch (Exception e) {
                readXmlException = e;
            } finally {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    private final class ReadXMLContentHandler extends DefaultHandler {

        private boolean readDone = false;

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            waitForReadLock();
            currentPath.add(localName);

            final String currentXPath = compileCurrentPath();

            if (currentGroupingLevel < groupingXPaths.size() - 1 && groupingXPaths.at(currentGroupingLevel + 1).equals(currentXPath)) {
                currentGroupingLevel++;

                if (currentGroupingLevel == 0) {
                    dataRowBuilderStack.add(new DataRowBuilder());
                } else {
                    dataRowBuilderStack.add(dataRowBuilderStack.at(currentGroupingLevel - 1).createCopy());
                }
            }

            if (currentGroupingLevel >= 0) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    final String attributeName = attributes.getLocalName(i);
                    final SchemaColumn schemaColumn = xPathMapping.get(currentXPath + "/@" + attributeName);

                    if (schemaColumn != null) {
                        addToDataRowBuilder(schemaColumn, attributes.getValue(i));
                    }
                }
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            waitForReadLock();

            final String currentXPath = compileCurrentPath();

            if (currentGroupingLevel == groupingXPaths.size() - 1 && currentXPath.equals(groupingXPaths.at(currentGroupingLevel))) {
                dataRowBuilderStack.at(currentGroupingLevel).fillWithNullValues(xPathMapping.values());
                dataRowToOutput = dataRowBuilderStack.at(currentGroupingLevel).build();

                outputLock.release();
                acquireLock(readLock);
            }

            if (currentGroupingLevel >= 0 && groupingXPaths.at(currentGroupingLevel).equals(currentXPath)) {
                dataRowBuilderStack.removeAt(currentGroupingLevel);
                currentGroupingLevel--;
            }

            currentPath.removeAt(currentPath.size() - 1);
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            waitForReadLock();

            final String text = new String(ch, start, length);
            final String currentXPath = compileCurrentPath() + "/text()";

            if (currentGroupingLevel >= 0) {
                final SchemaColumn schemaColumn = xPathMapping.get(currentXPath);

                if (schemaColumn != null) {
                    addToDataRowBuilder(schemaColumn, text);
                }

            }
        }

        @Override
        public void endDocument() throws SAXException {
            waitForReadLock();

            readDone = true;
            dataRowToOutput = DataRow.EOI;
            outputLock.release();
        }

        private void addToDataRowBuilder(SchemaColumn schemaColumn, String value) {
            final DataRowBuilder dataRowBuilder = dataRowBuilderStack.at(currentGroupingLevel);

            switch (schemaColumn.getDataType()) {
                case INTEGER:
                    dataRowBuilder.addValue(schemaColumn.getName(), Long.parseLong(value));
                    break;
                case FLOAT:
                    dataRowBuilder.addValue(schemaColumn.getName(), Double.parseDouble(value));
                    break;
                case STRING:
                    dataRowBuilder.addValue(schemaColumn.getName(), value);
                    break;
                case BOOLEAN:
                    dataRowBuilder.addValue(schemaColumn.getName(), Boolean.parseBoolean(value));
                    break;
                case TIME:
                    dataRowBuilder.addValue(schemaColumn.getName(), Instant.parse(value));
                    break;
            }
        }

        private void waitForReadLock() {
            if (!readDone) {
                acquireLock(readLock);
                readLock.release();
            }
        }

    }
}


text:
package sbtjaxws

import com.sun.tools.ws.WsImport
import sbt.Keys._
import sbt._

object Plugin extends sbt.Plugin {

  val SbtJaxWs = config("sbtjaxws")

  object SbtJaxWsKeys {

    val wsimport = TaskKey[Seq[File]]("jaxws-wsimport", "Generates Java code from WSDL")
    val wsdlFiles = SettingKey[Seq[File]]("jaxws-wsdl-files")
    val targetVersion = SettingKey[String]("jaxws-target-version", "Version of JAX-WS to target, default 2.2")
    val bindingFiles = SettingKey[Seq[File]]("jaxws-binding-files", "Files to use for bindings (-b)")
    val otherArgs = SettingKey[Seq[String]]("jaxws-other-args", "Other arguments to pass to wsimport")

  }

  import SbtJaxWsKeys._

  val sbtJaxWsSettings: Seq[Setting[_]] =
    Seq(
      javaSource in SbtJaxWs <<= sourceManaged in Compile,
      wsdlFiles := Nil,
      bindingFiles := Nil,
      targetVersion := "2.2",
      otherArgs := Nil,
      wsimport <<= (streams, wsdlFiles, javaSource in SbtJaxWs, bindingFiles, targetVersion, otherArgs) map { runWsImports },
      sourceGenerators in Compile <+= wsimport,
      managedSourceDirectories in Compile <+= (javaSource in SbtJaxWs),
      cleanFiles <+= (javaSource in SbtJaxWs))

  private case class WsImportSettings(dest: File, bindings: Seq[File], targetVersion: String, otherArgs: Seq[String])

  private def runWsImports(
    streams: TaskStreams,
    wsdlFiles: Seq[File],
    dest: File,
    bindings: Seq[File],
    targetVersion: String,
    otherArgs: Seq[String]): Seq[File] =
    wsdlFiles.flatMap(wsdl =>
      runWsImport(streams, wsdl, WsImportSettings(dest, bindings, targetVersion, otherArgs)))

  private def makeArgs(wsdlFile: File, settings: WsImportSettings): Seq[String] =
    Seq("-Xnocompile", "-quiet") ++
      settings.bindings.flatMap(binding => Seq("-b", binding.getAbsolutePath)) ++
      Seq("-s", settings.dest.getAbsolutePath) ++
      Seq("-target", settings.targetVersion) ++
      settings.otherArgs ++
      Seq(wsdlFile.getAbsolutePath)

  private def runWsImport(streams: TaskStreams, wsdlFile: File, settings: WsImportSettings): Seq[File] = {

    val sources = Seq(wsdlFile) ++ settings.bindings
    val generated = (settings.dest ** "*.java").get

    val upToDate = (sources, generated) match {
      case (Seq(), _)  => true
      case (_, Seq())  => false
      case (ins, outs) =>
        val inLastModified = ins.map(_.lastModified()).max
        val outLastModified = outs.map(_.lastModified()).min
        inLastModified < outLastModified
    }

    if (upToDate) {
      streams.log.info("Generated sources are up to date for " + wsdlFile)
    } else {
      streams.log.info("Generating Java from " + wsdlFile)
      streams.log.debug("Creating dir " + settings.dest)
      settings.dest.mkdirs()

      val args = makeArgs(wsdlFile, settings)
      streams.log.debug("wsimport " + args.mkString(" "))
      try {
        val result = WsImport.doMain(args.toArray)
        if (result != 0)
          throw new RuntimeException("Problem running wsimport")
      } catch {
        case t: Exception =>
          streams.log.error("Problem running wsimport " + args.mkString(" "))
          throw t
      }
    }
    (settings.dest ** "*.java").get
  }

}


text:
<?php

namespace Webforge\Doctrine\Compiler\Types;

use Webforge\Code\Generator\GClass;
use Webforge\Types\DoctrineExportableType;
use Webforge\Types\GClassAdapter;
use Webforge\Types\InterfacedType;
use Webforge\Types\ParameterHintedType;
use Webforge\Types\Psc;
use Webforge\Types\Type;

class DecimalType extends Type implements DoctrineExportableType, InterfacedType, ParameterHintedType
{
    /**
     * @var GClass
     */
    protected $interfaceClass;

    public function __construct()
    {
        parent::__construct();
        $this->interfaceClass = GClassAdapter::newGClass($this->getInterface());
    }

    /**
     * Returns a string that can be used as @Doctrine\ORM\Mapping\Column(type="%s")
     */
    public function getDoctrineExportType()
    {
        return 'decimal_object';
    }

    public function getDocType()
    {
        return '\\Decimal\\Decimal';
    }

    /**
     * Gibt das Interface zurück welches den Type implementiert
     *
     * @return string der FQN des Interfaces der Klasse ohne \ davor.
     */
    public function getInterface()
    {
        return 'Decimal\\Decimal';
    }

    /**
     * @inheritdoc
     */
    public function getParameterHint($useFQN = true)
    {
        if ($useFQN) {
            return '\\' . $this->interfaceClass->getFQN();
        } else {
            return $this->interfaceClass->getName();
        }
    }

    public function getParameterHintImport()
    {
        return $this->interfaceClass;
    }
}


text:
const ApplicationContext = require('../../context/application-context');

describe('context > ApplicationContext', () => {
  it('should call the init function with itself', async () => {
    expect.assertions(1);
    const context = new ApplicationContext();

    context.init((givenContext) => {
      expect(givenContext).toBe(context);
    });
  });

  it('should add a instance to the context', () => {
    expect.assertions(1);
    const propertyValue = Symbol('instance.value');
    const context = new ApplicationContext();

    context.init((givenContext) => givenContext.addInstance('instanceServiceName', {
      propertyName: propertyValue,
    }));

    const { instanceServiceName } = context.inject();

    expect(instanceServiceName.propertyName).toStrictEqual(propertyValue);
  });

  it('should add a class instance to the context', () => {
    expect.assertions(2);

    const clazz = class TestedClass {
      static staticMethod() {
        return 'staticMethod';
      }

      instanceMethod() {
        return `instanceMethod ${this}`;
      }
    };

    const context = new ApplicationContext();

    context.init((givenContext) => givenContext.addClass(clazz));

    const { testedClass } = context.inject();

    expect(testedClass.instanceMethod()).toStrictEqual('instanceMethod [object Object]');
    expect(clazz.staticMethod()).toStrictEqual('staticMethod');
  });

  it('should throw an error because overrides not forbidden', () => {
    expect.assertions(1);
    const staticMethodStubResult = Symbol('staticMethodStubResult');
    const instanceMethodStubResult = Symbol('instanceMethodStubResult');
    const clazz = class TestedClass {
      static staticMethod() {
        return 'staticMethod';
      }

      instanceMethod() {
        return `instanceMethod ${this}`;
      }
    };

    const context = new ApplicationContext();
    expect(() => context.init((givenContext) => givenContext.addClass(clazz, {
      staticMethod: () => staticMethodStubResult,
      instanceMethod: () => instanceMethodStubResult,
    }))).toThrow('overrides are forbidden in application-context. Use test-application-context.js');
  });

  it('should apply code via `with` method', () => {
    expect.assertions(1);
    function TestClass() {
      this.calledMethod = () => {};

      jest.spyOn(this, 'calledMethod').mockImplementation();

      this.testMethod = () => {
        this.calledMethod();
      };
    }

    const context = new ApplicationContext();
    context.init((givenContext) => givenContext
      .addClass(TestClass)
      .with('testClass', (testClass) => testClass.testMethod()));

    const { testClass } = context.inject();

    expect(testClass.calledMethod).toHaveBeenCalledWith();
  });

  describe('addValue', () => {
    it('should add the value to the context', () => {
      expect.assertions(1);

      const context = new ApplicationContext();
      context.init((givenContext) => givenContext
        .addValue('theValue', 42));

      expect(context.inject().theValue).toBe(42);
    });
  });

  describe('addFunction', () => {
    it('should add the function to the context', () => {
      expect.assertions(1);

      function theFunction() {}

      const context = new ApplicationContext();
      context.init((givenContext) => givenContext
        .addFunction('theFunction', theFunction));

      expect(context.inject().theFunction).toBe(theFunction);
    });
  });
});


text:
from flask import Flask, request, jsonify
import csv

app = Flask(__name__, static_url_path='/static')
app.config.from_object('config')

@app.route('/api/highscore_send', methods=['POST'])
def highscores_send():
    """Input POST requests highscores/username data and logs
    it into a file. This can easily be hacked!

    Usernames are converted into lowercase, so they are not
    case sensitive
    """
    FAIL_RESPONSE = jsonify({'status': False})
    SUCCESS_RESPONSE = jsonify({'status': True})
    score_dd = {}

    if 'name' not in request.form or \
       'score' not in request.form:
        return FAIL_RESPONSE

    username = request.form['name']
    username = username.lower()
    username = username.strip()
    username = username[:app.config['MAX_USERNAME']]

    if not username:
        return FAIL_RESPONSE

    try:
        score = int(request.form['score'])
    except ValueError:
        return FAIL_RESPONSE

    # 'rb+' allows us to read and write into the file on one
    # file access
    with open(app.config['HIGHSCORES_URI'], 'rb+') as csvfile:
        rd = csv.reader(csvfile)
        score_dd = {row[0]: int(row[1]) for row in rd}

        if len(score_dd) > app.config['MAX_HIGHSCORE_ENTRIES']:
            return FAIL_RESPONSE

        score = min(app.config['MAX_SCORE'], score)
        if username not in score_dd or score > score_dd[username]:
            score_dd[username] = score

        # empty out the entire file and write anew
        csvfile.seek(0)
        csvfile.truncate()
        wr = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)

        for k, v in score_dd.items():
            wr.writerow([k, v])

    return SUCCESS_RESPONSE

@app.route('/api/highscore_get', methods=['GET'])
def highscores_get():
    """Retrieve highscores data in JSON format.

    Actual scores are stored as a list of two-tuples (just lists
    with 2 elems in client JS). This endpoint performs sorting for
    now (not efficient). TODO: Cache scores and sort on a cronjob.
    """
    with open(app.config['HIGHSCORES_URI'], 'rb') as csvfile:
        rd = csv.reader(csvfile)
        scores = sorted([row for row in rd],
                        key=lambda x: int(x[1]),
                        reverse=True)
        scores = scores[:25]
    return jsonify({'scores': scores})

app.debug = app.config['DEBUG']

if __name__ == '__main__':
    app.run()


text:
// Code generated by protoc-gen-gogo.
// source: indexer.proto
// DO NOT EDIT!

/*
Package indexer is a generated protocol buffer package.

It is generated from these files:
	indexer.proto

It has these top-level messages:
	MetricFindItem
	MetricFindItemList
	MetricExpandItem
	MetricTagItem
	MetricTagItemList
*/
package indexer

import testing "testing"
import math_rand "math/rand"
import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "cadent/server/schemas/repr"
import _ "github.com/gogo/protobuf/gogoproto"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

func BenchmarkMetricFindItemProtoMarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricFindItem, 10000)
	for i := 0; i < 10000; i++ {
		pops[i] = NewPopulatedMetricFindItem(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000])
		if err != nil {
			panic(err)
		}
		total += len(data)
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricFindItemProtoUnmarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	datas := make([][]byte, 10000)
	for i := 0; i < 10000; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedMetricFindItem(popr, false))
		if err != nil {
			panic(err)
		}
		datas[i] = data
	}
	msg := &MetricFindItem{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += len(datas[i%10000])
		if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
			panic(err)
		}
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricFindItemListProtoMarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricFindItemList, 10000)
	for i := 0; i < 10000; i++ {
		pops[i] = NewPopulatedMetricFindItemList(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000])
		if err != nil {
			panic(err)
		}
		total += len(data)
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricFindItemListProtoUnmarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	datas := make([][]byte, 10000)
	for i := 0; i < 10000; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedMetricFindItemList(popr, false))
		if err != nil {
			panic(err)
		}
		datas[i] = data
	}
	msg := &MetricFindItemList{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += len(datas[i%10000])
		if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
			panic(err)
		}
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricExpandItemProtoMarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricExpandItem, 10000)
	for i := 0; i < 10000; i++ {
		pops[i] = NewPopulatedMetricExpandItem(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000])
		if err != nil {
			panic(err)
		}
		total += len(data)
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricExpandItemProtoUnmarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	datas := make([][]byte, 10000)
	for i := 0; i < 10000; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedMetricExpandItem(popr, false))
		if err != nil {
			panic(err)
		}
		datas[i] = data
	}
	msg := &MetricExpandItem{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += len(datas[i%10000])
		if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
			panic(err)
		}
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricTagItemProtoMarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricTagItem, 10000)
	for i := 0; i < 10000; i++ {
		pops[i] = NewPopulatedMetricTagItem(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000])
		if err != nil {
			panic(err)
		}
		total += len(data)
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricTagItemProtoUnmarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	datas := make([][]byte, 10000)
	for i := 0; i < 10000; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedMetricTagItem(popr, false))
		if err != nil {
			panic(err)
		}
		datas[i] = data
	}
	msg := &MetricTagItem{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += len(datas[i%10000])
		if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
			panic(err)
		}
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricTagItemListProtoMarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricTagItemList, 10000)
	for i := 0; i < 10000; i++ {
		pops[i] = NewPopulatedMetricTagItemList(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(pops[i%10000])
		if err != nil {
			panic(err)
		}
		total += len(data)
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricTagItemListProtoUnmarshal(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	datas := make([][]byte, 10000)
	for i := 0; i < 10000; i++ {
		data, err := github_com_gogo_protobuf_proto.Marshal(NewPopulatedMetricTagItemList(popr, false))
		if err != nil {
			panic(err)
		}
		datas[i] = data
	}
	msg := &MetricTagItemList{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += len(datas[i%10000])
		if err := github_com_gogo_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
			panic(err)
		}
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricFindItemSize(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricFindItem, 1000)
	for i := 0; i < 1000; i++ {
		pops[i] = NewPopulatedMetricFindItem(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += pops[i%1000].Size()
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricFindItemListSize(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricFindItemList, 1000)
	for i := 0; i < 1000; i++ {
		pops[i] = NewPopulatedMetricFindItemList(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += pops[i%1000].Size()
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricExpandItemSize(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricExpandItem, 1000)
	for i := 0; i < 1000; i++ {
		pops[i] = NewPopulatedMetricExpandItem(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += pops[i%1000].Size()
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricTagItemSize(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricTagItem, 1000)
	for i := 0; i < 1000; i++ {
		pops[i] = NewPopulatedMetricTagItem(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += pops[i%1000].Size()
	}
	b.SetBytes(int64(total / b.N))
}

func BenchmarkMetricTagItemListSize(b *testing.B) {
	popr := math_rand.New(math_rand.NewSource(616))
	total := 0
	pops := make([]*MetricTagItemList, 1000)
	for i := 0; i < 1000; i++ {
		pops[i] = NewPopulatedMetricTagItemList(popr, false)
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		total += pops[i%1000].Size()
	}
	b.SetBytes(int64(total / b.N))
}

//These tests are generated by github.com/gogo/protobuf/plugin/testgen