text:
$( document ).ready( function()
{

    $( '#bornDateGroup' ).datepicker( {
        format: "yyyy-mm-dd",
        autoclose: true
    } );

    $( '#author-add' ).submit( function( e )
    {
        e.preventDefault();

        var data = {
                name: $( '#name' ).val(),
                gender: $( '#gender' ).val(),
                recordingLabel: $( '#recordingLabel' ).val(),
                bornDate: $( '#bornDate' ).val(),
                notes: $( '#notes' ).val()
        };

        var stringData = JSON.stringify( data );

        $.ajax(
        {
            url : 'system/proxy.php/authors/',
            type : 'PUT',
            data: stringData,
            dataType: 'text',
            contentType: 'application/json',
            success: function( data, textStatus, jqXHR )
            {
                alert( 'Author successfully added!' );
                $( '#author-add' )[0].reset();
            },
            error: function( jqXHR, textStatus, errorThrown )
            {
                alert( 'An error occurred while adding the Author\n\nServer replied \''
                        + textStatus
                        + '\': '
                        + errorThrown );
            }
        } );

    } );

} );


text:
Parse.initialize("YvULQpWeWms3tGPYJYeFR37L1YhZus8T7v2joSvz", "X6uoBy1zoOanP51e08f0Cz396TzeqaQk4OVB7Jo2");

/*
	Print the username of the user currently logged on.
*/
function setUserName()
{
	var name;
	var currentUser = Parse.User.current();
	if(currentUser)
		name = currentUser.get("username");
	else
		name = "No one is signed in.";
	document.getElementById("loginStatus").innerHTML = name;
}

function logOut()
{
	if(Parse.User.current())
		Parse.User.logOut();
	setUserName();
	window.open("signIn.html","_self");
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @module authentication-controller
 */

const csrfProtection = require('csurf')({
    cookie: true,
});
const jwt = require('jwt-simple');
const express = require('express');

const router = express.Router();
// var debug = require( 'debug' )( 'authentication-controller' );

module.exports = (app) => {
    app.use(`${app.get('base path')}/`, router);
};

router
    .get('/login', csrfProtection, login)
    .get('/logout', logout)
    .post('/login', csrfProtection, setToken);

/**
 * @param {module:api-controller~ExpressRequest} req - HTTP request
 * @param {module:api-controller~ExpressResponse} res - HTTP response
 * @param {Function} next - Express callback
 */
function login(req, res, next) {
    let error;
    const authSettings = req.app.get(
        'linked form and data server'
    ).authentication;
    const returnUrl = req.query.return_url || '';

    if (authSettings.type.toLowerCase() !== 'basic') {
        if (authSettings.url) {
            // the url is expected to:
            // - authenticate the user,
            // - set a session cookie (cross-domain if necessary) or add a token as query parameter to the return URL,
            // - and return the user back to Enketo
            // - enketo will then pass the cookie or token along when requesting resources, or submitting data
            // Though returnUrl was encoded with encodeURIComponent, for some reason it appears to have been automatically decoded here.
            res.redirect(
                authSettings.url.replace(
                    '{RETURNURL}',
                    encodeURIComponent(returnUrl)
                )
            );
        } else {
            error = new Error(
                'Enketo configuration error. External authentication URL is missing.'
            );
            error.status = 500;
            next(error);
        }
    } else if (
        req.app.get('env') !== 'production' ||
        req.protocol === 'https' ||
        req.headers['x-forwarded-proto'] === 'https' ||
        req.app.get('linked form and data server').authentication[
            'allow insecure transport'
        ]
    ) {
        res.render('surveys/login', {
            csrfToken: req.csrfToken(),
            server: req.app.get('linked form and data server').name,
        });
    } else {
        error = new Error(
            'Forbidden. Enketo needs to use https in production mode to enable authentication.'
        );
        error.status = 405;
        next(error);
    }
}

/**
 * @param {module:api-controller~ExpressRequest} req - HTTP request
 * @param {module:api-controller~ExpressResponse} res - HTTP response
 */
function logout(req, res) {
    res.clearCookie(req.app.get('authentication cookie name'))
        .clearCookie('__enketo_meta_username')
        .clearCookie('__enketo_logout')
        .render('surveys/logout');
}

/**
 * @param {module:api-controller~ExpressRequest} req - HTTP request
 * @param {module:api-controller~ExpressResponse} res - HTTP response
 */
function setToken(req, res) {
    const username = req.body.username.trim();
    const maxAge = 30 * 24 * 60 * 60 * 1000;
    const returnUrl = req.query.return_url || '';

    const token = jwt.encode(
        {
            user: username,
            pass: req.body.password,
        },
        req.app.get('encryption key')
    );

    // Do not allow authentication cookies to be saved if enketo runs on http, unless 'allow insecure transport' is set to true
    // This is double because the check in login() already ensures the login screen isn't even shown.
    const secure =
        req.protocol === 'production' &&
        !req.app.get('linked form and data server').authentication[
            'allow insecure transport'
        ];

    const authOptions = {
        secure,
        signed: true,
        httpOnly: true,
        path: '/',
    };

    const uidOptions = {
        signed: true,
        maxAge: 30 * 24 * 60 * 60 * 1000,
        path: '/',
    };

    if (req.body.remember) {
        authOptions.maxAge = maxAge;
        uidOptions.maxAge = maxAge;
    }

    // store the token in a cookie on the client
    res.cookie(req.app.get('authentication cookie name'), token, authOptions)
        .cookie('__enketo_logout', true)
        .cookie('__enketo_meta_username', username, uidOptions);

    if (returnUrl) {
        res.redirect(returnUrl);
    } else {
        res.send(
            'Username and password are stored. You can close this page now.'
        );
    }
}


text:
import numpy as np

from .base import SolverFirstOrderSto
from .build.solver import SGDDouble as _SGDDouble
from .build.solver import SGDFloat as _SGDFloat

__author__ = "Stephane Gaiffas"

dtype_class_mapper = {
    np.dtype('float32'): _SGDFloat,
    np.dtype('float64'): _SGDDouble
}

# TODO: preparer methodes pour set et get attributes

class SGD(SolverFirstOrderSto):
    """Stochastic gradient descent solver

    For the minimization of objectives of the form

    .. math::
        \\frac 1n \\sum_{i=1}^n f_i(w) + g(w),

    where the functions :math:`f_i` have smooth gradients and :math:`g` is
    prox-capable. Function :math:`f = \\frac 1n \\sum_{i=1}^n f_i` corresponds
    to the ``model.loss`` method of the model (passed with ``set_model`` to the
    solver) and :math:`g` corresponds to the ``prox.value`` method of the
    prox (passed with the ``set_prox`` method).
    One iteration of :class:`SGD <tick.solver.SGD>` corresponds to the
    following iteration applied ``epoch_size`` times:

    .. math::
        w^{t+1} \\gets \\mathrm{prox}_{\\eta_t g} \\big(w^t - \\eta_t
        \\nabla f_i(w^t) \\big),

    where :math:`i` is sampled at random (strategy depends on ``rand_type``) at
    each iteration, where :math:`\\eta_t = \eta / (t + 1)`, with
    :math:`\\eta > 0` that can be tuned with ``step``. The seed of the random
    number generator for generation of samples :math:`i` can be seeded with
    ``seed``. The iterations stop whenever tolerance ``tol`` is achieved, or
    after ``max_iter`` epochs (namely ``max_iter``:math:`\\times` ``epoch_size``
    iterations).
    The obtained solution :math:`w` is returned by the ``solve`` method, and is
    also stored in the ``solution`` attribute of the solver.

    Parameters
    ----------
    step : `float`
        Step-size parameter, the most important parameter of the solver.
        A try-an-improve approach should be used.

    tol : `float`, default=1e-10
        The tolerance of the solver (iterations stop when the stopping
        criterion is below it)

    max_iter : `int`, default=100
        Maximum number of iterations of the solver, namely maximum number of
        epochs (by default full pass over the data, unless ``epoch_size`` has
        been modified from default)

    verbose : `bool`, default=True
        If `True`, solver verboses history, otherwise nothing is displayed,
        but history is recorded anyway

    seed : `int`, default=-1
        The seed of the random sampling. If it is negative then a random seed
        (different at each run) will be chosen.

    epoch_size : `int`, default given by model
        Epoch size, namely how many iterations are made before updating the
        variance reducing term. By default, this is automatically tuned using
        information from the model object passed through ``set_model``.

    rand_type : {'unif', 'perm'}, default='unif'
        How samples are randomly selected from the data

        * if ``'unif'`` samples are uniformly drawn among all possibilities
        * if ``'perm'`` a random permutation of all possibilities is
          generated and samples are sequentially taken from it. Once all of
          them have been taken, a new random permutation is generated

    print_every : `int`, default=10
        Print history information every time the iteration number is a
        multiple of ``print_every``. Used only is ``verbose`` is True

    record_every : `int`, default=1
        Save history information every time the iteration number is a
        multiple of ``record_every``

    Attributes
    ----------
    model : `Model`
        The model used by the solver, passed with the ``set_model`` method

    prox : `Prox`
        Proximal operator used by the solver, passed with the ``set_prox``
        method

    solution : `numpy.array`, shape=(n_coeffs,)
        Minimizer found by the solver

    history : `dict`-like
        A dict-type of object that contains history of the solver along
        iterations. It should be accessed using the ``get_history`` method

    time_start : `str`
        Start date of the call to ``solve()``

    time_elapsed : `float`
        Duration of the call to ``solve()``, in seconds

    time_end : `str`
        End date of the call to ``solve()``

    dtype : `{'float64', 'float32'}`, default='float64'
        Type of the arrays used. This value is set from model and prox dtypes.

    References
    ----------
    * https://en.wikipedia.org/wiki/Stochastic_gradient_descent
    """

    def __init__(self, step: float = None, epoch_size: int = None,
                 rand_type: str = "unif", tol: float = 1e-10,
                 max_iter: int = 100, verbose: bool = True,
                 print_every: int = 10, record_every: int = 1, seed: int = -1):

        SolverFirstOrderSto.__init__(self, step, epoch_size, rand_type, tol,
                                     max_iter, verbose, print_every,
                                     record_every, seed)

    def _set_cpp_solver(self, dtype_or_object_with_dtype):
        self.dtype = self._extract_dtype(dtype_or_object_with_dtype)
        solver_class = self._get_typed_class(dtype_or_object_with_dtype,
                                             dtype_class_mapper)

        # Type mapping None to unsigned long and double does not work...
        step = self.step
        if step is None:
            step = 0.
        epoch_size = self.epoch_size
        if epoch_size is None:
            epoch_size = 0

        self._set(
            '_solver',
            solver_class(epoch_size, self.tol, self._rand_type, step,
                         self.record_every, self.seed))


text: A site for my beloved wife.


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.smn.nlp</groupId>
		<artifactId>nlp-impl</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>ner-stanford</artifactId>
	<name>ner-stanford</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.10-FINAL</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.10-FINAL</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>3.10-FINAL</version>
		</dependency>
		<dependency>
			<groupId>org.apache.opennlp</groupId>
			<artifactId>opennlp-tools</artifactId>
			<version>1.5.3</version>
		</dependency>
		<dependency>
			<groupId>edu.stanford.nlp</groupId>
			<artifactId>stanford-corenlp</artifactId>
			<version>3.4</version>
		</dependency>
		<dependency>
			<groupId>edu.stanford.nlp</groupId>
			<artifactId>stanford-corenlp</artifactId>
			<version>3.4</version>
			<classifier>models</classifier>
		</dependency>
		<dependency>
			<groupId>edu.stanford.nlp</groupId>
			<artifactId>stanford-parser</artifactId>
			<version>3.4</version>
		</dependency>
	</dependencies>
</project>


text:
<?php

namespace PlumeWSService;

use Plume\WebSocket\Core\Event;
use Plume\WebSocket\Handler\HandlerException;

/**
 * WebSocket服务端集群节点之间交互逻辑实现类
 */
class Cluster extends Event{

    /**
     * ping->pong 实现.
     *
     * @param string $data client json message like {"url":"plumeWSService/cluster/ping","data":"ping"}
     */
    public function ping($data){
		$this->replay($data.'pong', false);
	}

   /**
    * 集群节点通知其他节点后的逻辑实现
    *
    * @param string $data server json message like {"url":"plumeWSService/cluster/notify","data":{"uid":"000001"}}
    */
	public function notify($data){
		if(!isset($data['data'])){
			$this->debug('notify', 'data is null');
			return;
		}
		$this->debug('notify - data', $data);
		if(isset($data['uid']) && !empty($data['uid'])){
			$this->broadcastself($data, $data['uid']);
		}else{
			$this->broadcastself($data);
		}
	}

}


text:
package org.darkstorm.darkbot.minecraftbot.protocol.v5x.play.client;

import java.io.*;

import org.darkstorm.darkbot.minecraftbot.protocol.*;
import org.darkstorm.darkbot.minecraftbot.protocol.ProtocolX.State;

public class PacketC17_PluginMessage extends AbstractPacketX implements WriteablePacket {
	private String channel;
	private byte[] data;

	public PacketC17_PluginMessage(String channel, byte[] data) {
		super(0x17, State.PLAY, Direction.UPSTREAM);

		this.channel = channel;
		this.data = data;
	}

	@Override
	public void writeData(DataOutputStream out) throws IOException {
		writeString(channel, out);
		writeByteArray(data, out);
	}

	public String getChannel() {
		return channel;
	}

	public byte[] getData() {
		return data;
	}
}


text:
FoundTruck is an app created for find the foodtrucks nearest you.

Built with AngularJS and Bootstrap, the system is currently being developed.

## Demo
https://luizbaldi.github.io/found-truck/frontend

## Contributors
- Luiz Baldi
- Leonardo Pego
- Luis Philipe Fidelis


text:
from twisted.trial import unittest
import types

class ReturnedAGeneratorError(Exception):
    pass

class TXJasonTestCase(unittest.TestCase):
    def _run(self, methodName, result):
        """
        Ensure that test cases don't return generators, as that basically
        always means someone forgot an @inlineCallbacks.
        """
        d = unittest.TestCase._run(self, methodName, result)

        def ensureNoGenerators(result):
            if isinstance(result, types.GeneratorType):
                raise ReturnedAGeneratorError(
                    'method %r returned a generator' % methodName)
            return result
        d.addCallback(ensureNoGenerators)
        return d


text:
This gem adds News, Rubrics, Issues, Companies, Galleries, Notices to site.
News HABTM Rubrics. News HABTM Issues. News HABTM Companies. Companies has_many Galleries. Companies HABTM Notices.

## Installation

Add this line to your application's Gemfile:

    gem 'c80_news_tz'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install c80_news_tz

Perform migrations:

    $ rake db:migrate

Copy example seed files from `<GEM_FOLDER>\db\seeds\` to `<HOST_PROJECT_FOLDER>\db\seeds\`,
remove `.example` extensions.

Copy seeds.sh.example file:

    cp <GEM_FOLDER>\seeds.sh.example <HOST_PROJECT_FOLDER>\seeds.sh; sudo chmod +x seeds.sh; ./seeds.sh

Add the line to application's routes file:

    mount C80NewsTz::Engine => '/'

Add this line to `application.js.coffee`:

    #= require c80_news_tz

Add this line to `application.scss`:

    @import "c80_news_tz/application";

Add this line to `application_controller.rb`:

    helper C80NewsTz::Engine.helpers

This gem uses: ActiveAdmin, Fontawesome. Add this to your `active_admin_custom.scss` file:

    @import "font-awesome";

Add these lines to `routes.rb` (optional):

    get '/companies/:company_slug' => 'site#company'
    get '/news/:fact_slug' => 'site#fact'
    get '/issues/:issue_slug' => 'site#issue'
    get '/notices/:notice_slug' => 'site#notice'
    get '/rubrics/:rubric_slug' => 'site#rubric'

Implement these methods in `site_controller.rb` (optional):

    def company
    end

    # просмотр новости на отдельной странице
    def fact
      @fact = C80NewsTz::Fact.where(:slug => params[:fact_slug]).first
      @vparams[:page_content] = @fact.full if @fact.full.present?
      @vparams[:body_id] = 'fact'
      add_title @fact.title
      # add_breadcrumb @page.title
      @vparams[:description] = @fact.short_meta_description if @fact.short_meta_description.present?
      override_with_seo
      # найти и подсветить родительский пункт меню
      @vparams[:active_menus] << MenuItem.where(:title => 'Новости').first.id
    end

    def issue
      # ...
    end

    def notice
      # ...
    end

    # просмотр рубрики на отдельной странице
    def rubric
      @rubric = C80NewsTz::Rubric.where(:slug => params[:rubric_slug]).first
      add_title(@rubric.title)
      override_with_seo
    end

Implement corresponding views (optional). For example `views/site/fact.html.erb`:

<%= @fact.title %>

    <%= check_page_art(@vparams[:page_content], @fact.fphotos, @fact.title).html_safe %>

## Available helper methods

    render_news_block
    render_one_fact

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/[my-github-username]/c80_news_tz/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
<?php
/**
 * The template for displaying archive pages.
 *
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package storefront
 *
 * @todo  replace archive header title / description with the_archive_title / the_archive_description when wp 4.1 lands
 */

get_header(); ?>

		<?php if ( have_posts() ) : ?>

					<?php
					if ( is_category() ) :
						single_cat_title();

					elseif ( is_tag() ) :
						single_tag_title();

					elseif ( is_author() ) :
						printf( __( 'Author: %s', 'storefront' ), '' . get_the_author() . '' );

					elseif ( is_day() ) :
						printf( __( 'Day: %s', 'storefront' ), '' . get_the_date() . '' );

					elseif ( is_month() ) :
						printf( __( 'Month: %s', 'storefront' ), '' . get_the_date( _x( 'F Y', 'monthly archives date format', 'storefront' ) ) . '' );

					elseif ( is_year() ) :
						printf( __( 'Year: %s', 'storefront' ), '' . get_the_date( _x( 'Y', 'yearly archives date format', 'storefront' ) ) . '' );

					elseif ( is_tax( 'post_format', 'post-format-aside' ) ) :
						_e( 'Asides', 'storefront' );

					elseif ( is_tax( 'post_format', 'post-format-gallery' ) ) :
						_e( 'Galleries', 'storefront' );

					elseif ( is_tax( 'post_format', 'post-format-image' ) ) :
						_e( 'Images', 'storefront' );

					elseif ( is_tax( 'post_format', 'post-format-video' ) ) :
						_e( 'Videos', 'storefront' );

					elseif ( is_tax( 'post_format', 'post-format-quote' ) ) :
						_e( 'Quotes', 'storefront' );

					elseif ( is_tax( 'post_format', 'post-format-link' ) ) :
						_e( 'Links', 'storefront' );

					elseif ( is_tax( 'post_format', 'post-format-status' ) ) :
						_e( 'Statuses', 'storefront' );

					elseif ( is_tax( 'post_format', 'post-format-audio' ) ) :
						_e( 'Audios', 'storefront' );

					elseif ( is_tax( 'post_format', 'post-format-chat' ) ) :
						_e( 'Chats', 'storefront' );

					else :
						_e( 'Archives', 'storefront' );

					endif;
					?>

				<?php
				// Show an optional term description.
				$term_description = term_description();
				if ( ! empty( $term_description ) ) :
					printf( '
%s
', $term_description );
				endif;
				?>

			<?php get_template_part( 'loop' ); ?>

		<?php else : ?>

			<?php get_template_part( 'content', 'none' ); ?>

		<?php endif; ?>

<?php do_action( 'storefront_sidebar' ); ?>
<?php get_footer(); ?>


text:
package org.hibernate.validator.constraints.impl;

import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.Pattern;

/**
 * @author Hardy Ferentschik
 */
public class PatternValidator implements ConstraintValidator<Pattern, CharSequence> {

	private java.util.regex.Pattern pattern;

	public void initialize(Pattern parameters) {
		Pattern.Flag flags[] = parameters.flags();
		int intFlag = 0;
		for ( Pattern.Flag flag : flags ) {
			intFlag = intFlag | flag.getValue();
		}

		try {
			pattern = java.util.regex.Pattern.compile( parameters.regexp(), intFlag );
		}
		catch ( PatternSyntaxException e ) {
			throw new IllegalArgumentException( "Invalid regular expression.", e );
		}
	}

	public boolean isValid(CharSequence value, ConstraintValidatorContext constraintValidatorContext) {
		if ( value == null ) {
			return true;
		}
		Matcher m = pattern.matcher( value );
		return m.matches();
	}
}


text:
package org.gradoop.flink.datagen.transactions.foodbroker.functions.masterdata;

import org.apache.flink.configuration.Configuration;
import org.gradoop.common.model.impl.pojo.Vertex;
import org.gradoop.common.model.impl.pojo.VertexFactory;
import org.gradoop.common.model.impl.properties.Properties;
import org.gradoop.flink.datagen.transactions.foodbroker.config.Constants;
import org.gradoop.flink.datagen.transactions.foodbroker.tuples.MasterDataSeed;

import java.util.List;
import java.util.Random;

/**
 * Creates a logistic vertex.
 */
public class Logistics extends MasterData {
  /**
   * List of possible adjectives.
   */
  private List<String> adjectives;
  /**
   * List of possible nouns.
   */
  private List<String> nouns;
  /**
   * List of possible cities.
   */
  private List<String> cities;
  /**
   * Amount of possible adjectives.
   */
  private Integer adjectiveCount;
  /**
   * Amount of possible nouns.
   */
  private Integer nounCount;
  /**
   * Amount of pissible cities.
   */
  private Integer cityCount;
  /**
   * EPGM vertex factory.
   */
  private final VertexFactory vertexFactory;

  /**
   * Valued constructor.
   *
   * @param vertexFactory EPGM vertex factory
   */
  public Logistics(VertexFactory vertexFactory) {
    this.vertexFactory = vertexFactory;
  }

  @Override
  public void open(Configuration parameters) throws Exception {
    super.open(parameters);
    //load broadcast lists
    adjectives = getRuntimeContext().getBroadcastVariable(Constants.ADJECTIVES_BC);
    nouns = getRuntimeContext().getBroadcastVariable(Constants.NOUNS_BC);
    cities = getRuntimeContext().getBroadcastVariable(Constants.CITIES_BC);
    //get their sizes
    nounCount = nouns.size();
    adjectiveCount = adjectives.size();
    cityCount = cities.size();
  }

  @Override
  public Vertex map(MasterDataSeed seed) throws  Exception {
    //create standard properties from acronym and seed
    Properties properties = createDefaultProperties(seed, getAcronym());
    Random random = new Random();
    //set rnd city and name
    String[] location = cities.get(random.nextInt(cityCount)).split("-");
    properties.set(Constants.CITY_KEY, location[0]);
    properties.set(Constants.STATE_KEY, location[1]);
    properties.set(Constants.COUNTRY_KEY, location[2]);

    properties.set(Constants.NAME_KEY, adjectives.get(random.nextInt(adjectiveCount)) + " " +
      nouns.get(random.nextInt(nounCount)));
    return vertexFactory.createVertex(getClassName(), properties);
  }

  @Override
  public String getAcronym() {
    return Constants.LOGISTICS_ACRONYM;
  }

  @Override
  public String getClassName() {
    return Constants.LOGISTICS_VERTEX_LABEL;
  }
}


text:
using System;
using System.Collections.Generic;
using SharpKit.JavaScript;
namespace Y_
{
    ///
    /// The WidgetAutohide class provides the hideOn attribute which can
    /// be used to hide the widget when certain events occur.
    ///
    public partial class WidgetAutohide
    {
        ///
        /// Default function called when hideOn Attribute is changed. Remove existing listeners and create new listeners.
        ///
        public void _afterHideOnChange(){}
        ///
        /// Default function called when the visibility of the widget changes. Determines
        /// whether to attach or detach event listeners based on the visibility of the widget.
        ///
        protected void _afterHostVisibleChangeAutohide(){}
        ///
        /// Iterates through all objects in the hideOn attribute and creates event listeners.
        ///
        protected void _attachUIHandlesAutohide(){}
        ///
        /// Binds event listeners to the widget.
        ///

        /// This method in invoked after bindUI is invoked for the Widget class
        /// using YUI's aop infrastructure.
        ///

        ///
        protected void _bindUIAutohide(){}
        ///
        /// Detaches all event listeners created by this extension
        ///
        protected void _detachUIHandlesAutohide(){}
        ///
        /// Syncs up the widget based on its current state. In particular, removes event listeners if
        /// widget is not visible, and attaches them otherwise.
        ///

        /// This method in invoked after syncUI is invoked for the Widget class
        /// using YUI's aop infrastructure.
        ///

        ///
        protected void _syncUIAutohide(){}
        ///
        /// Removes event listeners if widget is not visible, and attaches them otherwise.
        ///
        protected void _uiSetHostVisibleAutohide(){}
        ///
        /// Static property used to define the default attribute
        /// configuration introduced by WidgetAutohide.
        ///
        public object ATTRS{get;set;}
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title><?php echo SITENAME, ' - ', $template['title']; ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="<?php echo STATIC_URL; ?>images/favicon.ico">
    <link rel="apple-touch-icon-precomposed" href="<?php echo STATIC_URL; ?>images/favicon.png" />

    <link href="<?php echo STATIC_URL; ?>plugins/bootstrap/bootstrap.css" rel="stylesheet">
    <link href="<?php echo STATIC_URL; ?>styles/social.css" rel="stylesheet">
    <link href="<?php echo STATIC_URL; ?>styles/social.plugins.css" rel="stylesheet">
    <link href="<?php echo STATIC_URL; ?>styles/font-awesome.css" rel="stylesheet">
    <link href="<?php echo STATIC_URL; ?>plugins/bootstrap/bootstrap-responsive.css" rel="stylesheet">
<?php foreach($template['styles'] as $style): ?>
    <link href="<?php echo $style; ?>" rel="stylesheet" />
<?php endforeach; ?>

    <link rel="prerender" href="<?php echo STATIC_URL; ?>plugins/jquery.ui/jquery-ui.min.js">

<?php $this->load->view($template['content']); ?>

2013 © <?php echo SITENAME; ?> Inc.

<?php foreach($template['scripts'] as $script): ?>

<?php endforeach; ?>


text:
package router

import (
	"context"
	"fmt"
	"sync"
	"time"

	pb_broker "github.com/TheThingsNetwork/ttn/api/broker"
	"github.com/TheThingsNetwork/ttn/api/fields"
	pb_protocol "github.com/TheThingsNetwork/ttn/api/protocol"
	pb_lorawan "github.com/TheThingsNetwork/ttn/api/protocol/lorawan"
	pb "github.com/TheThingsNetwork/ttn/api/router"
	"github.com/TheThingsNetwork/ttn/api/trace"
	"github.com/TheThingsNetwork/ttn/core/band"
	"github.com/TheThingsNetwork/ttn/core/router/gateway"
	"github.com/TheThingsNetwork/ttn/utils/errors"
)

func (r *router) HandleActivation(gatewayID string, activation *pb.DeviceActivationRequest) (res *pb.DeviceActivationResponse, err error) {
	ctx := r.Ctx.WithField("GatewayID", gatewayID).WithFields(fields.Get(activation))
	start := time.Now()
	var gateway *gateway.Gateway
	var forwarded bool
	defer func() {
		if err != nil {
			activation.Trace = activation.Trace.WithEvent(trace.DropEvent, "reason", err)
			if forwarded {
				ctx.WithError(err).Debug("Did not handle activation")
			} else if gateway != nil && gateway.MonitorStream != nil {
				ctx.WithError(err).Warn("Could not handle activation")
				gateway.MonitorStream.Send(activation)
			}
		} else {
			ctx.WithField("Duration", time.Now().Sub(start)).Info("Handled activation")
		}
	}()
	r.status.activations.Mark(1)

	activation.Trace = activation.Trace.WithEvent(trace.ReceiveEvent, "gateway", gatewayID)

	gateway = r.getGateway(gatewayID)
	gateway.LastSeen = time.Now()

	uplink := &pb.UplinkMessage{
		Payload:          activation.Payload,
		ProtocolMetadata: activation.ProtocolMetadata,
		GatewayMetadata:  activation.GatewayMetadata,
		Trace:            activation.Trace,
	}

	if err = gateway.HandleUplink(uplink); err != nil {
		return nil, err
	}

	if !gateway.Schedule.IsActive() {
		return nil, errors.NewErrInternal(fmt.Sprintf("Gateway %s not available for downlink", gatewayID))
	}

	downlinkOptions := r.buildDownlinkOptions(uplink, true, gateway)
	activation.Trace = uplink.Trace.WithEvent(trace.BuildDownlinkEvent,
		"options", len(downlinkOptions),
	)

	// Find Broker
	brokers, err := r.Discovery.GetAll("broker")
	if err != nil {
		return nil, err
	}

	// Prepare request
	request := &pb_broker.DeviceActivationRequest{
		Payload:          activation.Payload,
		DevEui:           activation.DevEui,
		AppEui:           activation.AppEui,
		ProtocolMetadata: activation.ProtocolMetadata,
		GatewayMetadata:  activation.GatewayMetadata,
		ActivationMetadata: &pb_protocol.ActivationMetadata{
			Protocol: &pb_protocol.ActivationMetadata_Lorawan{
				Lorawan: &pb_lorawan.ActivationMetadata{
					AppEui: activation.AppEui,
					DevEui: activation.DevEui,
				},
			},
		},
		DownlinkOptions: downlinkOptions,
		Trace:           activation.Trace,
	}

	// Prepare LoRaWAN activation
	status, err := gateway.Status.Get()
	if err != nil {
		return nil, err
	}
	region := status.FrequencyPlan
	if region == "" {
		region = band.Guess(uplink.GatewayMetadata.Frequency)
	}
	band, err := band.Get(region)
	if err != nil {
		return nil, err
	}
	lorawan := request.ActivationMetadata.GetLorawan()
	lorawan.FrequencyPlan = pb_lorawan.FrequencyPlan(pb_lorawan.FrequencyPlan_value[region])
	lorawan.Rx1DrOffset = 0
	lorawan.Rx2Dr = uint32(band.RX2DataRate)
	lorawan.RxDelay = uint32(band.ReceiveDelay1.Seconds())
	if band.CFList != nil {
		lorawan.CfList = new(pb_lorawan.CFList)
		for _, freq := range band.CFList {
			lorawan.CfList.Freq = append(lorawan.CfList.Freq, freq)
		}
	}

	ctx = ctx.WithField("NumBrokers", len(brokers))
	request.Trace = request.Trace.WithEvent(trace.ForwardEvent,
		"brokers", len(brokers),
	)

	if gateway != nil && gateway.MonitorStream != nil {
		forwarded = true
		gateway.MonitorStream.Send(activation)
	}

	// Forward to all brokers and collect responses
	var wg sync.WaitGroup
	responses := make(chan *pb_broker.DeviceActivationResponse, len(brokers))
	for _, broker := range brokers {
		broker, err := r.getBroker(broker)
		if err != nil {
			continue
		}

		// Do async request
		wg.Add(1)
		go func() {
			ctx, cancel := context.WithTimeout(r.Component.GetContext(""), 5*time.Second)
			defer cancel()
			res, err := broker.client.Activate(ctx, request)
			if err == nil && res != nil {
				responses <- res
			}
			wg.Done()
		}()
	}

	// Make sure to close channel when all requests are done
	go func() {
		wg.Wait()
		close(responses)
	}()

	var gotFirst bool
	for res := range responses {
		if gotFirst {
			ctx.Warn("Duplicate Activation Response")
		} else {
			gotFirst = true
			downlink := &pb_broker.DownlinkMessage{
				Payload:        res.Payload,
				Message:        res.Message,
				DownlinkOption: res.DownlinkOption,
				Trace:          res.Trace,
			}
			err := r.HandleDownlink(downlink)
			if err != nil {
				ctx.Warn("Could not send downlink for Activation")
				gotFirst = false // try again
			}
		}
	}

	// Activation not accepted by any broker
	if !gotFirst {
		ctx.Debug("Activation not accepted at this gateway")
		return nil, errors.New("Activation not accepted at this Gateway")
	}

	// Activation accepted by (at least one) broker
	ctx.Debug("Activation accepted")
	return &pb.DeviceActivationResponse{}, nil
}


text:
Simple CMS written in Crystal lang

## Contributing

1. Fork it ( https://github.com/mauricioabreu/owl-cms/fork )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

## Contributors

- [mauricioabreu](https://github.com/mauricioabreu) Mauricio de Abreu Antunes - creator, maintainer
- [rzanluchi](https://github.com/rzanluchi) Raphael Zanluchi - creator, maintainer


text:
import Ember from 'ember';
import XFileInput from 'emberx-file-input/components/x-file-input';

const {testing} = Ember;

export default XFileInput.extend({
    change(e) {
        let files = testing ? (e.originalEvent || e).testingFiles : e.target.files;
        this.sendAction('action', files);
    }
});


text:
// Adapted from externs generated from TypeScript type definitions provided
// by DefinitelyTyped, which is licensed under the MIT license; see file
// DefinitelyTyped-LICENSE.
// Type definitions for Node.js 10.5.x
// Project: http://nodejs.org/
// Definitions by: Microsoft TypeScript <http://typescriptlang.org>
//                 DefinitelyTyped <https://github.com/DefinitelyTyped/DefinitelyTyped>
//                 Parambir Singh <https://github.com/parambirs>
//                 Christian Vaagland Tellnes <https://github.com/tellnes>
//                 Wilco Bakker <https://github.com/WilcoBakker>
//                 Nicolas Voigt <https://github.com/octo-sniffle>
//                 Chigozirim C. <https://github.com/smac89>
//                 Flarna <https://github.com/Flarna>
//                 Mariusz Wiktorczyk <https://github.com/mwiktorczyk>
//                 wwwy3y3 <https://github.com/wwwy3y3>
//                 Deividas Bakanas <https://github.com/DeividasBakanas>
//                 Kelvin Jin <https://github.com/kjin>
//                 Alvis HT Tang <https://github.com/alvis>
//                 Sebastian Silbermann <https://github.com/eps1lon>
//                 Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>
//                 Alberto Schiabel <https://github.com/jkomyno>
//                 Klaus Meinhardt <https://github.com/ajafff>
//                 Huw <https://github.com/hoo29>
//                 Nicolas Even <https://github.com/n-e>
//                 Bruno Scheufler <https://github.com/brunoscheufler>
//                 Mohsen Azimi <https://github.com/mohsen1>
//                 Hoàng Văn Khải <https://github.com/KSXGitHub>
//                 Alexander T. <https://github.com/a-tarasyuk>
//                 Lishude <https://github.com/islishude>
//                 Andrew Makarov <https://github.com/r3nya>
//                 Zane Hannan AU <https://github.com/ZaneHannanAU>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/**
 * @externs
 */

var fs = {};

/**
 * @param {string} filename
 * @param {string} encoding
 * @return {string}
 */
fs.readFileSync = function(filename, encoding) {};

module.exports = fs;


text:
namespace kudu {

// Convert the given snake_case string to camel case.
// Also treats '-' in a string like a '_'
// For example:
// - 'foo_bar' -> FooBar
// - 'foo-bar' -> FooBar
//
// This function cannot operate in-place -- i.e. 'camel_case' must not
// point to 'snake_case'.
void SnakeToCamelCase(const std::string &snake_case,
                      std::string *camel_case);

// Upper-case all of the characters in the given string.
// 'string' and 'out' may refer to the same string to replace in-place.
void ToUpperCase(const std::string &string,
                 std::string *out);

// Capitalizes a string containing a word in place.
// For example:
// - 'hiBerNATe' -> 'Hibernate'
void Capitalize(std::string *word);

} // namespace kudu
#endif


text:
/*\
title: $:/core/modules/widgets/keyboard.js
type: application/javascript
module-type: widget

Keyboard shortcut widget

\*/
(function(){

/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";

var Widget = require("$:/core/modules/widgets/widget.js").widget;

var KeyboardWidget = function(parseTreeNode,options) {
	this.initialise(parseTreeNode,options);
};

/*
Inherit from the base widget class
*/
KeyboardWidget.prototype = new Widget();

/*
Render this widget into the DOM
*/
KeyboardWidget.prototype.render = function(parent,nextSibling) {
	var self = this;
	// Remember parent
	this.parentDomNode = parent;
	// Compute attributes and execute state
	this.computeAttributes();
	this.execute();
	// Create element
	var domNode = this.document.createElement("div");
	// Assign classes
	var classes = (this["class"] || "").split(" ");
	classes.push("tc-keyboard");
	domNode.className = classes.join(" ");
	// Add a keyboard event handler
	domNode.addEventListener("keydown",function (event) {
		var result;
		$tw.utils.each(self.keyMappings, function(map, idx, data) {
			var keyInfo = map[0],
				message = map[1],
				param = map[2];
			if($tw.utils.checkKeyDescriptor(event,keyInfo)) {
				self.invokeActions(this,event);
				self.dispatchEvent({
					type: message,
					param: param,
					tiddlerTitle: self.getVariable("currentTiddler")
				});
				event.preventDefault();
				event.stopPropagation();
				result = true;
			}
			result = false;
		});
		return result;
	},false);
	// Insert element
	parent.insertBefore(domNode,nextSibling);
	// make sure we receive keyboard events
	domNode.setAttribute("tabindex", "0");
	domNode.focus();
	this.renderChildren(domNode,null);
	this.domNodes.push(domNode);
};

/*
Compute the internal state of the widget
*/
KeyboardWidget.prototype.execute = function() {
	var logger = new $tw.utils.Logger("$keyboard"),
		self = this;
	this.keyMappings = [];

	// evaluate key/message/param attributes (one key binding)
	var key = this.getAttribute("key"),
		message = this.getAttribute("message"),
		param = this.getAttribute("param");
	if (typeof(key) != "undefined" && typeof(message) != "undefined") {
		var keyInfo;
		try {
			keyInfo = $tw.utils.parseKeyDescriptor(key);
			this.keyMappings.push([keyInfo, message, param]);
		} catch(err) {
			logger.alert("[[" + this.getVariable("currentTiddler") + "]]: " + err + " in key=" + key);
		}
	}

	// evaluate mappings attribute (data tiddler containing key bindings)
	this.mappings = this.getAttribute("mappings");
	if (typeof(this.mappings) === "string") {
		$tw.utils.each(this.wiki.getTiddlerData(this.mappings, Object.create(null)), function(value, key, data) {
			var keyInfo, msg_param;
			try {
				keyInfo = $tw.utils.parseKeyDescriptor(key);
				msg_param = value.split(":");
				self.keyMappings.push([keyInfo, msg_param[0], msg_param[1]]);
			} catch(err) {
				logger.alert("[[" + self.mappings + "]]: " + err + " in key=" + key);
			}
		});
	}

	this["class"] = this.getAttribute("class");
	// Make child widgets
	this.makeChildWidgets();
};

/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
KeyboardWidget.prototype.refresh = function(changedTiddlers) {
	var changedAttributes = this.computeAttributes();
	if(changedAttributes.message || changedAttributes.param || changedAttributes.key || changedAttributes.mappings || changedAttributes["class"] || changedTiddlers[this.mappings]) {
		this.refreshSelf();
		return true;
	}
	return this.refreshChildren(changedTiddlers);
};

exports.keyboard = KeyboardWidget;

})();


text:
type SAMWriter{T<:IO} <: Bio.IO.AbstractWriter
    stream::T
end

function Base.close(writer::SAMWriter)
    close(writer.stream)
end

function Base.write(writer::SAMWriter, header::SAMHeader)
    n = 0
    if haskey(header, "HD")
        n += write_headerline(writer.stream, "HD", header["HD"])
    end

    for tag in keys(header)
        if tag == "HD"
            continue
        end
        for h in header[tag]
            n += write_headerline(writer.stream, tag, h)
        end
    end

    return n
end

function write_headerline(io, tag, line)
    n = 0
    n += write(io, '@', tag)
    for (t, val) in line
        checkkeytag(t)
        n += write(io, '\t', t, ':', string(val))
    end
    n += write(io, '\n')
    return n
end

function Base.write(writer::SAMWriter, record::SAMRecord)
    stream = writer.stream

    n = 0
    n += write(
        stream,
        record.name, '\t',
        string(record.flag), '\t',
        record.refname, '\t',
        string(record.pos), '\t',
        string(record.mapq), '\t',
        record.cigar, '\t',
        record.next_refname, '\t',
        string(record.next_pos), '\t',
        string(record.tlen), '\t',
        convert(String, record.seq), '\t',
        [UInt8(q + 33) for q in record.qual])
    n += write_optfields(stream, record.optional_fields)
    n += write(stream, '\n')

    return n
end

function write_optfields(io, optfields)
    n = 0
    for (tag, val) in optfields
        checkkeytag(tag)
        n += write(io, '\t', tag, ':', auxtypechar[typeof(val)], ':', string(val))
    end
    return n
end


text:
exports.action = {
  name: "getSession",
  description: "I get a session",
  inputs: {
    required: [],
    optional: [],
  },
  outputExample: {},
  version: 1.0,
  run: function(api, connection, next){
    console.log(connection.id);
    connection.response.sessionId = connection.id;
    next(connection, true);
  }
};


text:
package org.apache.jackrabbit.core.query.lucene;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.apache.jackrabbit.core.SearchManager;
import org.apache.jackrabbit.core.TestHelper;
import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.query.lucene.hits.AbstractHitCollector;
import org.apache.jackrabbit.core.state.NodeState;
import org.apache.jackrabbit.test.AbstractJCRTest;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;

public class SearchIndexConsistencyCheckTest extends AbstractJCRTest {

    private boolean keepRunning;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }

    public void testIndexMissesNode() throws Exception {

        Session s = getHelper().getSuperuserSession();
        SearchManager searchManager = TestHelper.getSearchManager(s);
        SearchIndex searchIndex = (SearchIndex) searchManager.getQueryHandler();

        Node foo = testRootNode.addNode("foo");
        testRootNode.getSession().save();
        NodeId fooId = new NodeId(foo.getIdentifier());

        Iterator<NodeId> remove = Collections.singletonList(fooId).iterator();
        Iterator<NodeState> add = Collections.<NodeState>emptyList().iterator();

        searchIndex.updateNodes(remove, add);

        ConsistencyCheck consistencyCheck = searchIndex.runConsistencyCheck();
        List<ConsistencyCheckError> errors = consistencyCheck.getErrors();
        assertEquals("Expected 1 index consistency error", 1, errors.size());

        ConsistencyCheckError error = errors.iterator().next();
        assertEquals("Different node was reported to be missing", error.id, fooId);

        consistencyCheck.repair(false);

        assertTrue("Index was not repaired properly", searchIndexContainsNode(searchIndex, fooId));

        assertTrue("Consistency check still reports errors", searchIndex.runConsistencyCheck().getErrors().isEmpty());
    }

    public void testMissingNodeDoubleCheck() throws Exception {
        Session s = getHelper().getSuperuserSession();
        SearchManager searchManager = TestHelper.getSearchManager(s);
        SearchIndex searchIndex = (SearchIndex) searchManager.getQueryHandler();

        Node foo = testRootNode.addNode("foo");
        testRootNode.getSession().save();
        NodeId fooId = new NodeId(foo.getIdentifier());

        Iterator<NodeId> remove = Collections.singletonList(fooId).iterator();
        Iterator<NodeState> add = Collections.<NodeState>emptyList().iterator();

        searchIndex.updateNodes(remove, add);

        ConsistencyCheck consistencyCheck = searchIndex.runConsistencyCheck();
        List<ConsistencyCheckError> errors = consistencyCheck.getErrors();
        assertEquals("Expected 1 index consistency error", 1, errors.size());

        // now add foo to the index again so that double check finds a false positive
        remove = Collections.<NodeId>emptyList().iterator();
        add = Collections.singletonList(new NodeState(fooId, null, null, 1, false)).iterator();

        searchIndex.updateNodes(remove, add);

        consistencyCheck.doubleCheckErrors();

        assertTrue("Consistency double check of missing node failed", consistencyCheck.getErrors().isEmpty());

    }

    public void testIndexContainsUnknownNode() throws Exception {

        Session s = getHelper().getSuperuserSession();
        SearchManager searchManager = TestHelper.getSearchManager(s);
        SearchIndex searchIndex = (SearchIndex) searchManager.getQueryHandler();

        NodeId nodeId = new NodeId(0, 0);
        NodeState nodeState = new NodeState(nodeId, null, null, 1, false);

        Iterator<NodeId> remove = Collections.<NodeId>emptyList().iterator();
        Iterator<NodeState> add = Collections.singletonList(nodeState).iterator();

        searchIndex.updateNodes(remove, add);

        ConsistencyCheck consistencyCheck = searchIndex.runConsistencyCheck();
        List<ConsistencyCheckError> errors = consistencyCheck.getErrors();
        assertEquals("Expected 1 index consistency error", 1, errors.size());

        ConsistencyCheckError error = errors.iterator().next();
        assertEquals("Different node was reported to be unknown", error.id, nodeId);

        consistencyCheck.repair(false);

        assertFalse("Index was not repaired properly", searchIndexContainsNode(searchIndex, nodeId));

        assertTrue("Consistency check still reports errors", searchIndex.runConsistencyCheck().getErrors().isEmpty());
    }

    public void testUnknownNodeDoubleCheck() throws Exception {

        Session s = getHelper().getSuperuserSession();
        SearchManager searchManager = TestHelper.getSearchManager(s);
        SearchIndex searchIndex = (SearchIndex) searchManager.getQueryHandler();

        NodeId nodeId = new NodeId(0, 0);
        NodeState nodeState = new NodeState(nodeId, null, null, 1, false);

        Iterator<NodeId> remove = Collections.<NodeId>emptyList().iterator();
        Iterator<NodeState> add = Collections.singletonList(nodeState).iterator();

        searchIndex.updateNodes(remove, add);

        ConsistencyCheck consistencyCheck = searchIndex.runConsistencyCheck();
        List<ConsistencyCheckError> errors = consistencyCheck.getErrors();
        assertEquals("Expected 1 index consistency error", 1, errors.size());

        // now remove the unknown node from the index again so that double check finds a false positive
        remove = Collections.singletonList(nodeId).iterator();
        add = Collections.<NodeState>emptyList().iterator();

        searchIndex.updateNodes(remove, add);

        consistencyCheck.doubleCheckErrors();

        assertTrue("Consistency double check of deleted node failed", consistencyCheck.getErrors().isEmpty());
    }

    public void testIndexMissesAncestor() throws Exception {
        Session s = getHelper().getSuperuserSession();
        SearchManager searchManager = TestHelper.getSearchManager(s);
        SearchIndex searchIndex = (SearchIndex) searchManager.getQueryHandler();

        Node foo = testRootNode.addNode("foo");
        Node bar = foo.addNode("bar");
        testRootNode.getSession().save();
        NodeId fooId = new NodeId(foo.getIdentifier());
        NodeId barId = new NodeId(bar.getIdentifier());

        Iterator<NodeId> remove = Collections.singletonList(fooId).iterator();
        Iterator<NodeState> add = Collections.<NodeState>emptyList().iterator();

        searchIndex.updateNodes(remove, add);

        ConsistencyCheck consistencyCheck = searchIndex.runConsistencyCheck();
        List<ConsistencyCheckError> errors = consistencyCheck.getErrors();

        assertEquals("Expected 2 index consistency errors", 2, errors.size());

        assertEquals("Different node was reported to have missing parent", errors.get(0).id, barId);
        assertEquals("Different node was reported to be missing", errors.get(1).id, fooId);

        consistencyCheck.repair(false);

        assertTrue("Index was not repaired properly", searchIndexContainsNode(searchIndex, fooId));

        assertTrue("Consistency check still reports errors", searchIndex.runConsistencyCheck().getErrors().isEmpty());
    }

    public void testMissingAncestorDoubleCheck() throws Exception {

        Session s = getHelper().getSuperuserSession();
        SearchManager searchManager = TestHelper.getSearchManager(s);
        SearchIndex searchIndex = (SearchIndex) searchManager.getQueryHandler();

        Node foo = testRootNode.addNode("foo");
        foo.addNode("bar");
        testRootNode.getSession().save();
        NodeId fooId = new NodeId(foo.getIdentifier());

        Iterator<NodeId> remove = Collections.singletonList(fooId).iterator();
        Iterator<NodeState> add = Collections.<NodeState>emptyList().iterator();

        searchIndex.updateNodes(remove, add);

        ConsistencyCheck consistencyCheck = searchIndex.runConsistencyCheck();
        List<ConsistencyCheckError> errors = consistencyCheck.getErrors();

        assertEquals("Expected 2 index consistency errors", 2, errors.size());

        remove = Collections.<NodeId>emptyList().iterator();
        add = Collections.singletonList(new NodeState(fooId, null, null, 1, true)).iterator();

        searchIndex.updateNodes(remove, add);

        consistencyCheck.doubleCheckErrors();

        assertTrue("Consistency double check of missing ancestor failed", consistencyCheck.getErrors().isEmpty());
    }

    public void testIndexContainsMultipleEntries() throws Exception {
        Session s = getHelper().getSuperuserSession();
        SearchManager searchManager = TestHelper.getSearchManager(s);
        SearchIndex searchIndex = (SearchIndex) searchManager.getQueryHandler();

        Node foo = testRootNode.addNode("foo");
        testRootNode.getSession().save();
        NodeId fooId = new NodeId(foo.getIdentifier());

        NodeState nodeState = new NodeState(fooId, null, null, 1, false);
        Iterator<NodeId> remove = Collections.<NodeId>emptyList().iterator();
        Iterator<NodeState> add = Arrays.asList(nodeState).iterator();

        searchIndex.updateNodes(remove, add);

        searchIndex.flush();

        remove = Collections.<NodeId>emptyList().iterator();
        add = Arrays.asList(nodeState).iterator();

        searchIndex.updateNodes(remove, add);

        ConsistencyCheck consistencyCheck = searchIndex.runConsistencyCheck();
        List<ConsistencyCheckError> errors = consistencyCheck.getErrors();

        assertEquals("Expected 1 index consistency error", 1, errors.size());
        assertEquals("Different node was reported to be duplicate", errors.get(0).id, fooId);

        consistencyCheck.doubleCheckErrors();
        errors = consistencyCheck.getErrors();

        assertEquals("Expected 1 index consistency error after double check", 1, errors.size());
        assertEquals("Different node was reported to be duplicate after double check", errors.get(0).id, fooId);

        consistencyCheck.repair(false);

        assertTrue("Index was not repaired properly", searchIndexContainsNode(searchIndex, fooId));

        consistencyCheck.doubleCheckErrors();
        errors = consistencyCheck.getErrors();

        assertTrue("Consistency double check of multiple entries failed", errors.isEmpty());
        assertTrue("Consistency check still finds errors", searchIndex.runConsistencyCheck().getErrors().isEmpty());

    }

    /**
     * Stress test on the double check mechanism
     */
    public void testDoubleCheckStressTest() throws Exception {
        Thread t = new Thread(new Runnable() {
            private Session s = getHelper().getReadWriteSession();
            @Override
            public void run() {
                while (keepRunning) {
                    try {
                        Node foo = s.getRootNode().getNode(testPath).addNode("foo");
                        s.save();
                        foo.remove();
                        s.save();
                    } catch (RepositoryException e) {
                        System.out.println(e);
                    }
                }
            }
        });

        Session s = getHelper().getSuperuserSession();
        SearchManager searchManager = TestHelper.getSearchManager(s);
        SearchIndex searchIndex = (SearchIndex) searchManager.getQueryHandler();

        keepRunning = true;
        try {
            t.start();
            Thread.sleep(100);
            for (int i = 100; i > 0; i--) {
                final ConsistencyCheck consistencyCheck = searchIndex.runConsistencyCheck();
                consistencyCheck.doubleCheckErrors();
                final List<ConsistencyCheckError> errors = consistencyCheck.getErrors();
                assertTrue(errors.isEmpty());
            }
        } finally {
            keepRunning = false;
        }

    }

    private boolean searchIndexContainsNode(SearchIndex searchIndex, NodeId nodeId) throws IOException {
        final List<Integer> docs = new ArrayList<Integer>(1);
        final IndexReader reader = searchIndex.getIndexReader();
        try {
            IndexSearcher searcher = new IndexSearcher(reader);
            try {
                Query q = new TermQuery(new Term(FieldNames.UUID, nodeId.toString()));
                searcher.search(q, new AbstractHitCollector() {
                    @Override
                    protected void collect(final int doc, final float score) {
                        docs.add(doc);
                    }
                });
            } finally {
                searcher.close();
            }
        } finally {
            Util.closeOrRelease(reader);
        }
        return !docs.isEmpty();

    }

}


text:
"""A soccer pitch with home/away goals and one field with position detection."""

import colorsys
import os

from absl import logging
from dm_control import composer
from dm_control import mjcf
from dm_control.composer.variation import distributions
from dm_control.entities import props
from dm_control.locomotion.soccer import team
import numpy as np

from dm_control.utils import io as resources

_ASSETS_PATH = os.path.join(os.path.dirname(__file__), 'assets', 'pitch')

def _get_texture(name):
  contents = resources.GetResource(
      os.path.join(_ASSETS_PATH, '{}.png'.format(name)))
  return mjcf.Asset(contents, '.png')

_TOP_CAMERA_Y_PADDING_FACTOR = 1.1
_TOP_CAMERA_DISTANCE = 95.
_WALL_HEIGHT = 10.
_WALL_THICKNESS = .5
_SIDE_WIDTH = 32. / 6.
_GROUND_GEOM_GRID_RATIO = 1. / 100  # Grid size for lighting.
_FIELD_BOX_CONTACT_BIT = 1 << 7  # Use a higher bit to prevent potential clash.

_DEFAULT_PITCH_SIZE = (12, 9)
_DEFAULT_GOAL_LENGTH_RATIO = 0.33  # Goal length / pitch width.

_GOALPOST_RELATIVE_SIZE = 0.07  # Ratio of the goalpost radius to goal size.
_NET_RELATIVE_SIZE = 0.01  # Ratio of the net thickness to goal size.
_SUPPORT_POST_RATIO = 0.75  # Ratio of support post to goalpost radius.
# Goalposts defined in the unit box [-1, 1]**3 facing to the positive X.
_GOALPOSTS = {'right_post': (1, -1, -1, 1, -1, 1),
              'left_post': (1, 1, -1, 1, 1, 1),
              'top_post': (1, -1, 1, 1, 1, 1),
              'right_base': (1, -1, -1, -1, -1, -1),
              'left_base': (1, 1, -1, -1, 1, -1),
              'back_base': (-1, -1, -1, -1, 1, -1),
              'right_support': (-1, -1, -1, .2, -1, 1),
              'right_top_support': (.2, -1, 1, 1, -1, 1),
              'left_support': (-1, 1, -1, .2, 1, 1),
              'left_top_support': (.2, 1, 1, 1, 1, 1)}
# Vertices of net polygons, reshaped to 4x3 arrays.
_NET = {'top': _GOALPOSTS['right_top_support'] + _GOALPOSTS['left_top_support'],
        'back': _GOALPOSTS['right_support'] + _GOALPOSTS['left_support'],
        'left': _GOALPOSTS['left_base'] + _GOALPOSTS['left_top_support'],
        'right': _GOALPOSTS['right_base'] + _GOALPOSTS['right_top_support']}
_NET = {key: np.array(value).reshape(4, 3) for key, value in _NET.items()}

# Number of visual hoarding boxes per side of the pitch.
_NUM_HOARDING = 30

def _top_down_cam_fovy(size, top_camera_distance):
  return (360 / np.pi) * np.arctan2(_TOP_CAMERA_Y_PADDING_FACTOR * max(size),
                                    top_camera_distance)

def _wall_pos_xyaxes(size):
  """Infers position and size of bounding walls given pitch size.

  Walls are placed around `ground_geom` that represents the pitch. Note that
  the ball cannot travel beyond `field` but walkers can walk outside of the
  `field` but not the surrounding walls.

  Args:
    size: a tuple of (length, width) of the pitch.

  Returns:
    a list of 4 tuples, each representing the position and xyaxes of a wall
    plane. In order, walls are placed along x-negative, x-positive, y-negative,
    y-positive relative the center of the pitch.
  """
  return [
      ((0., -size[1], 0.), (-1, 0, 0, 0, 0, 1)),
      ((0., size[1], 0.), (1, 0, 0, 0, 0, 1)),
      ((-size[0], 0., 0.), (0, 1, 0, 0, 0, 1)),
      ((size[0], 0., 0.), (0, -1, 0, 0, 0, 1)),
  ]

def _fieldbox_pos_size(field_size, goal_size):
  """Infers position and size of fieldbox given pitch size.

  Walls are placed around the field so that the ball cannot travel beyond
  `field` but walkers can walk outside of the `field` but not the surrounding
  pitch. Holes are left in the fieldbox at the goal positions to enable scoring.

  Args:
    field_size: a tuple of (length, width) of the field.
    goal_size: a tuple of (unused_depth, width, height) of the goal.

  Returns:
    a list of 8 tuples, each representing the position and size of a wall box.
  """

  box_half_height = 20.
  corner_pos_y = 0.5 * (field_size[1] + goal_size[1])
  corner_size_y = 0.5 * (field_size[1] - goal_size[1])
  thickness = 1.0
  top_pos_z = box_half_height + goal_size[2]
  top_size_z = box_half_height - goal_size[2]
  wall_offset_x = field_size[0] + thickness
  wall_offset_y = field_size[1] + thickness
  return [
      ((0., -wall_offset_y, box_half_height),
       (field_size[0], thickness, box_half_height)),  # near side
      ((0., wall_offset_y, box_half_height),
       (field_size[0], thickness, box_half_height)),  # far side
      ((-wall_offset_x, -corner_pos_y, box_half_height),
       (thickness, corner_size_y, box_half_height)),  # left near corner
      ((-wall_offset_x, 0., top_pos_z),
       (thickness, goal_size[1], top_size_z)),  # left top corner
      ((-wall_offset_x, corner_pos_y, box_half_height),
       (thickness, corner_size_y, box_half_height)),  # left far corner
      ((wall_offset_x, -corner_pos_y, box_half_height),
       (thickness, corner_size_y, box_half_height)),  # right near corner
      ((wall_offset_x, 0., top_pos_z),
       (thickness, goal_size[1], top_size_z)),  # right top corner
      ((wall_offset_x, corner_pos_y, box_half_height),
       (thickness, corner_size_y, box_half_height)),  # right far corner
  ]

def _roof_size(size):
  return (size[0], size[1], _WALL_THICKNESS)

def _reposition_corner_lights(lights, size):
  """Place four lights at the corner of the pitch."""
  mean_size = 0.5 * sum(size)
  height = mean_size * 2/3
  counter = 0
  for x in [-size[0], size[0]]:
    for y in [-size[1], size[1]]:
      position = np.array((x, y, height))
      direction = -np.array((x, y, height*2))
      lights[counter].pos = position
      lights[counter].dir = direction
      counter += 1

def _goalpost_radius(size):
  """Compute goal post radius as scaled average goal size."""
  return _GOALPOST_RELATIVE_SIZE * sum(size) / 3.

def _post_radius(goalpost_name, goalpost_radius):
  """Compute the radius of a specific goalpost."""
  radius = goalpost_radius
  if 'top' in goalpost_name:
    radius *= 1.01  # Prevent z-fighting at the corners.
  if 'support' in goalpost_name:
    radius *= _SUPPORT_POST_RATIO  # Suport posts are a bit narrower.
  return radius

def _goalpost_fromto(unit_fromto, size, pos, direction):
  """Rotate, scale and translate the `fromto` attribute of a goalpost.

  The goalposts are defined in the unit cube [-1, 1]**3 using MuJoCo fromto
  specifier for capsules, they are then flipped according to whether they face
  in the +x or -x, scaled and moved.

  Args:
    unit_fromto: two concatenated 3-vectors in the unit cube in xyzxyz order.
    size: a 3-vector, scaling of the goal.
    pos: a 3-vector, goal position.
    direction: a 3-vector, either (1,1,1) or (-1,-1,1), direction of the goal
      along the x-axis.

  Returns:
    two concatenated 3-vectors, the `fromto` of a goal geom.
  """
  fromto = np.array(unit_fromto) * np.hstack((direction, direction))
  return fromto*np.array(size+size) + np.array(pos+pos)

class Goal(props.PositionDetector):
  """Goal for soccer-like games: A PositionDetector with goalposts."""

  def _make_net_vertices(self, size=(1, 1, 1)):
    """Make vertices for the four net meshes by offsetting net polygons."""
    thickness = _NET_RELATIVE_SIZE * sum(size) / 3
    # Get mesh offsets, compensate for mesh.scale deformation.
    dx = np.array((thickness / size[0], 0, 0))
    dy = np.array((0, thickness / size[1], 0))
    dz = np.array((0, 0, thickness / size[2]))
    # Make mesh vertices with specified thickness.
    top = [v+dz for v in _NET['top']] + [v-dz for v in _NET['top']]
    right = [v+dy for v in _NET['right']] + [v-dy for v in _NET['right']]
    left = [v+dy for v in _NET['left']] + [v-dy for v in _NET['left']]
    back = ([v+dz for v in _NET['back'] if v[2] == 1] +
            [v-dz for v in _NET['back'] if v[2] == 1] +
            [v+dx for v in _NET['back'] if v[2] == -1] +
            [v-dx for v in _NET['back'] if v[2] == -1])
    vertices = {'top': top, 'back': back, 'left': left, 'right': right}
    return  {key: (val*self._direction).flatten()
             for key, val in vertices.items()}

  def _move_goal(self, pos, size):
    """Translate and scale the goal."""
    for geom in self._goal_geoms:
      unit_fromto = _GOALPOSTS[geom.name]
      geom.fromto = _goalpost_fromto(unit_fromto, size, pos, self._direction)
      geom.size = (_post_radius(geom.name, self._goalpost_radius),)
    if self._make_net:
      net_vertices = self._make_net_vertices(size)
      for geom in self._net_geoms:
        geom.pos = pos
        geom.mesh.vertex = net_vertices[geom.mesh.name]
        geom.mesh.scale = size

  def _build(self, direction, net_rgba=(1, 1, 1, .15), make_net=True, **kwargs):
    """Builds the goalposts and net.

    Args:
      direction: Is the goal oriented towards positive or negative x-axis.
      net_rgba: rgba value of the net geoms.
      make_net: Where to add net geoms.
      **kwargs: arguments of PositionDetector superclass, see therein.

    Raises:
      ValueError: If either `pos` or `size` arrays are not of length 3.
      ValueError: If direction in not 1 or -1.
    """
    if len(kwargs['size']) != 3 or len(kwargs['pos']) != 3:
      raise ValueError('Only 3D Goals are supported.')
    if direction not in [1, -1]:
      raise ValueError('direction must be either 1 or -1.')
    # Flip both x and y, to maintain left / right name correctness.
    self._direction = np.array((direction, direction, 1))
    self._make_net = make_net

    # Force the underlying PositionDetector to a non visible site group.
    kwargs['visible'] = False
    # Make a Position_Detector.
    super()._build(retain_substep_detections=True, **kwargs)

    # Add goalpost geoms.
    size = kwargs['size']
    pos = kwargs['pos']
    self._goalpost_radius = _goalpost_radius(size)
    self._goal_geoms = []
    for geom_name, unit_fromto in _GOALPOSTS.items():
      geom_fromto = _goalpost_fromto(unit_fromto, size, pos, self._direction)
      geom_size = (_post_radius(geom_name, self._goalpost_radius),)
      self._goal_geoms.append(
          self._mjcf_root.worldbody.add(
              'geom',
              type='capsule',
              name=geom_name,
              size=geom_size,
              fromto=geom_fromto,
              rgba=self.goalpost_rgba))

    # Add net meshes and geoms.
    if self._make_net:
      net_vertices = self._make_net_vertices()
      self._net_geoms = []
      for name, vertex in net_vertices.items():
        mesh = self._mjcf_root.asset.add('mesh', name=name, vertex=vertex)
        geom = self._mjcf_root.worldbody.add('geom', type='mesh', mesh=mesh,
                                             name=name, rgba=net_rgba,
                                             contype=0, conaffinity=0)
        self._net_geoms.append(geom)

  def resize(self, pos, size):
    """Call PositionDetector.resize(), move the goal."""
    super().resize(pos, size)
    self._goalpost_radius = _goalpost_radius(size)
    self._move_goal(pos, size)

  def set_position(self, physics, pos):
    """Call PositionDetector.set_position(), move the goal."""
    super().set_position(pos)
    size = 0.5*(self.upper - self.lower)
    self._move_goal(pos, size)

  def _update_detection(self, physics):
    """Call PositionDetector._update_detection(), then recolor the goalposts."""
    super()._update_detection(physics)
    if self._detected and not self._previously_detected:
      physics.bind(self._goal_geoms).rgba = self.goalpost_detected_rgba
    elif self._previously_detected and not self._detected:
      physics.bind(self._goal_geoms).rgba = self.goalpost_rgba

  @property
  def goalpost_rgba(self):
    """Goalposts are always opaque."""
    rgba = self._rgba.copy()
    rgba[3] = 1
    return rgba

  @property
  def goalpost_detected_rgba(self):
    """Goalposts are always opaque."""
    detected_rgba = self._detected_rgba.copy()
    detected_rgba[3] = 1
    return detected_rgba

class Pitch(composer.Arena):
  """A pitch with a plane, two goals and a field with position detection."""

  def _build(self,
             size=_DEFAULT_PITCH_SIZE,
             goal_size=None,
             top_camera_distance=_TOP_CAMERA_DISTANCE,
             field_box=False,
             field_box_offset=0.0,
             hoarding_color_scheme_id=0,
             name='pitch'):
    """Construct a pitch with walls and position detectors.

    Args:
      size: a tuple of (length, width) of the pitch.
      goal_size: optional (depth, width, height) indicating the goal size.
        If not specified, the goal size is inferred from pitch size with a fixed
        default ratio.
      top_camera_distance: the distance of the top-down camera to the pitch.
      field_box: adds a "field box" that collides with the ball but not the
        walkers.
      field_box_offset: offset for the fieldbox if used.
      hoarding_color_scheme_id: An integer with value 0, 1, 2, or 3, specifying
        a preset scheme for the hoarding colors.
      name: the name of this arena.
    """
    super()._build(name=name)
    self._size = size
    self._goal_size = goal_size
    self._top_camera_distance = top_camera_distance
    self._hoarding_color_scheme_id = hoarding_color_scheme_id

    self._top_camera = self._mjcf_root.worldbody.add(
        'camera',
        name='top_down',
        pos=[0, 0, top_camera_distance],
        zaxis=[0, 0, 1],
        fovy=_top_down_cam_fovy(self._size, top_camera_distance))

    # Set the `extent`, an "average distance" to 0.1 * pitch length.
    extent = 0.1 * max(self._size)
    self._mjcf_root.statistic.extent = extent
    self._mjcf_root.statistic.center = (0, 0, extent)
    # The near and far clipping planes are scaled by `extent`.
    self._mjcf_root.visual.map.zfar = 50             # 5 pitch lengths
    self._mjcf_root.visual.map.znear = 0.1 / extent  # 10 centimeters

    # Add skybox.
    self._mjcf_root.asset.add(
        'texture',
        name='skybox',
        type='skybox',
        builtin='gradient',
        rgb1=(.7, .9, .9),
        rgb2=(.03, .09, .27),
        width=400,
        height=400)

    # Add and position corner lights.
    self._corner_lights = [self._mjcf_root.worldbody.add('light', cutoff=60)
                           for _ in range(4)]
    _reposition_corner_lights(self._corner_lights, size)

    # Increase shadow resolution, (default is 1024).
    self._mjcf_root.visual.quality.shadowsize = 8192

    # Build groundplane.
    if len(self._size) != 2:
      raise ValueError('`size` should be a sequence of length 2: got {!r}'
                       .format(self._size))
    self._field_texture = self._mjcf_root.asset.add(
        'texture',
        type='2d',
        file=_get_texture('pitch_nologo_l'),
        name='fieldplane')
    self._field_material = self._mjcf_root.asset.add(
        'material', name='fieldplane', texture=self._field_texture)

    self._ground_geom = self._mjcf_root.worldbody.add(
        'geom',
        name='ground',
        type='plane',
        material=self._field_material,
        size=list(self._size) + [max(self._size) * _GROUND_GEOM_GRID_RATIO])

    # Build walls.
    self._walls = []
    for wall_pos, wall_xyaxes in _wall_pos_xyaxes(self._size):
      self._walls.append(
          self._mjcf_root.worldbody.add(
              'geom',
              type='plane',
              rgba=[.1, .1, .1, .8],
              pos=wall_pos,
              size=[1e-7, 1e-7, 1e-7],
              xyaxes=wall_xyaxes))

    # Build goal position detectors.
    # If field_box is enabled, offset goal by 1.0 such that ball reaches the
    # goal position detector before bouncing off the field_box.
    self._fb_offset = field_box_offset if field_box else 0.0
    goal_size = self._get_goal_size()
    self._home_goal = Goal(
        direction=1,
        make_net=False,
        pos=(-self._size[0] + goal_size[0] + self._fb_offset, 0,
             goal_size[2]),
        size=goal_size,
        rgba=(.2, .2, 1, 0.5),
        visible=True,
        name='home_goal')
    self.attach(self._home_goal)

    self._away_goal = Goal(
        direction=-1,
        make_net=False,
        pos=(self._size[0] - goal_size[0] - self._fb_offset, 0, goal_size[2]),
        size=goal_size,
        rgba=(1, .2, .2, 0.5),
        visible=True,
        name='away_goal')
    self.attach(self._away_goal)

    # Build inverted field position detectors.
    self._field = props.PositionDetector(
        pos=(0, 0),
        size=(self._size[0] - 2 * goal_size[0],
              self._size[1] - 2 * goal_size[0]),
        inverted=True,
        visible=False,
        name='field')
    self.attach(self._field)

    # Build field perimeter.
    def _visual_plane():
      return self._mjcf_root.worldbody.add(
          'geom',
          type='plane',
          size=(1, 1, 1),
          rgba=(0.306, 0.682, 0.223, 1),
          contype=0,
          conaffinity=0)

    self._perimeter = [_visual_plane() for _ in range(8)]
    self._update_perimeter()

    # Build field box.
    self._field_box = []
    if field_box:
      for box_pos, box_size in _fieldbox_pos_size(
          (self._field.upper - self._field.lower) / 2.0, goal_size):
        self._field_box.append(
            self._mjcf_root.worldbody.add(
                'geom',
                type='box',
                rgba=[.3, .3, .3, .0],
                pos=box_pos,
                size=box_size))

    # Build hoarding sites.
    def _box_site():
      return self._mjcf_root.worldbody.add('site', type='box', size=(1, 1, 1))
    self._hoarding = [_box_site() for _ in range(4 * _NUM_HOARDING)]
    self._update_hoarding()

  def _update_hoarding(self):
    # Resize, reposition and re-color visual perimeter box geoms.
    num_boxes = _NUM_HOARDING
    counter = 0
    for dim in [0, 1]:  # Semantics are [x, y]
      width = self._get_goal_size()[2] / 8  # Eighth of the goal height.
      height = self._get_goal_size()[2] / 2  # Half of the goal height.
      length = self._size[dim]
      if dim == 1:  # Stretch the y-dim length in order to cover the corners.
        length += 2 * width
      box_size = height * np.ones(3)
      box_size[dim] = length / num_boxes
      box_size[1-dim] = width
      dim_pos = np.linspace(-length, length, num_boxes, endpoint=False)
      dim_pos += length / num_boxes  # Offset to center.
      for sign in [-1, 1]:
        alt_pos = sign * (self._size[1-dim] * np.ones(num_boxes) + width)
        dim_alt = (dim_pos, alt_pos)
        for box in range(num_boxes):
          box_pos = np.array((dim_alt[dim][box], dim_alt[1-dim][box], width))
          if self._hoarding_color_scheme_id == 0:
            # Red to blue through green + blue hoarding behind blue goal
            angle = np.pi + np.arctan2(box_pos[0], -np.abs(box_pos[1]))
          elif self._hoarding_color_scheme_id == 1:
            # Red to blue through green + blue hoarding behind red goal
            angle = np.arctan2(box_pos[0], np.abs(box_pos[1]))
          elif self._hoarding_color_scheme_id == 2:
            # Red to blue through purple + blue hoarding behind red goal
            angle = np.arctan2(box_pos[0], -np.abs(box_pos[1]))
          elif self._hoarding_color_scheme_id == 3:
            # Red to blue through purple + blue hoarding behind blue goal
            angle = np.pi + np.arctan2(box_pos[0], np.abs(box_pos[1]))
          hue = 0.5 + angle / (2*np.pi)  # In [0, 1]
          hue_offset = .25
          hue = (hue - hue_offset) % 1.0  # Apply offset and wrap back to [0, 1]
          saturation = .7
          value = 1.0
          col_r, col_g, col_b = colorsys.hsv_to_rgb(hue, saturation, value)
          self._hoarding[counter].pos = box_pos
          self._hoarding[counter].size = box_size
          self._hoarding[counter].rgba = (col_r, col_g, col_b, 1.)
          counter += 1

  def _update_perimeter(self):
    # Resize and reposition visual perimeter plane geoms.
    width = self._get_goal_size()[0]
    counter = 0
    for x in [-1, 0, 1]:
      for y in [-1, 0, 1]:
        if x == 0 and y == 0:
          continue
        size_0 = self._size[0]-2*width if x == 0 else width
        size_1 = self._size[1]-2*width if y == 0 else width
        size = [size_0, size_1, max(self._size) * _GROUND_GEOM_GRID_RATIO]
        pos = (x*(self._size[0]-width), y*(self._size[1]-width), 0)
        self._perimeter[counter].size = size
        self._perimeter[counter].pos = pos
        counter += 1

  def _get_goal_size(self):
    goal_size = self._goal_size
    if goal_size is None:
      goal_size = (
          _SIDE_WIDTH / 2,
          self._size[1] * _DEFAULT_GOAL_LENGTH_RATIO,
          _SIDE_WIDTH / 2,
      )
    return goal_size

  def register_ball(self, ball):
    self._home_goal.register_entities(ball)
    self._away_goal.register_entities(ball)

    if self._field_box:
      # Geoms a and b collides if:
      #   (a.contype & b.conaffinity) || (b.contype & a.conaffinity) != 0.
      #   See: http://www.mujoco.org/book/computation.html#Collision
      ball.geom.contype = (ball.geom.contype or 1) | _FIELD_BOX_CONTACT_BIT
      for wall in self._field_box:
        wall.conaffinity = _FIELD_BOX_CONTACT_BIT
        wall.contype = _FIELD_BOX_CONTACT_BIT
    else:
      self._field.register_entities(ball)

  def detected_goal(self):
    """Returning the team that scored a goal."""
    if self._home_goal.detected_entities:
      return team.Team.AWAY
    if self._away_goal.detected_entities:
      return team.Team.HOME
    return None

  def detected_off_court(self):
    return self._field.detected_entities

  @property
  def size(self):
    return self._size

  @property
  def home_goal(self):
    return self._home_goal

  @property
  def away_goal(self):
    return self._away_goal

  @property
  def field(self):
    return self._field

  @property
  def ground_geom(self):
    return self._ground_geom

class RandomizedPitch(Pitch):
  """RandomizedPitch that randomizes its size between (min_size, max_size)."""

  def __init__(self,
               min_size,
               max_size,
               randomizer=None,
               keep_aspect_ratio=False,
               goal_size=None,
               field_box=False,
               field_box_offset=0.0,
               top_camera_distance=_TOP_CAMERA_DISTANCE,
               name='randomized_pitch'):
    """Construct a randomized pitch.

    Args:
      min_size: a tuple of minimum (length, width) of the pitch.
      max_size: a tuple of maximum (length, width) of the pitch.
      randomizer: a callable that returns ratio between [0., 1.] that scales
        between min_size, max_size.
      keep_aspect_ratio: if `True`, keep the aspect ratio constant during
        randomization.
      goal_size: optional (depth, width, height) indicating the goal size.
        If not specified, the goal size is inferred from pitch size with a fixed
        default ratio.
      field_box: optional indicating if we should construct field box containing
        the ball (but not the walkers).
      field_box_offset: offset for the fieldbox if used.
      top_camera_distance: the distance of the top-down camera to the pitch.
      name: the name of this arena.
    """
    super().__init__(
        size=max_size,
        goal_size=goal_size,
        top_camera_distance=top_camera_distance,
        field_box=field_box,
        field_box_offset=field_box_offset,
        name=name)

    self._min_size = min_size
    self._max_size = max_size

    self._randomizer = randomizer or distributions.Uniform()
    self._keep_aspect_ratio = keep_aspect_ratio

    # Sample a new size and regenerate the soccer pitch.
    logging.info('%s between (%s, %s) with %s', self.__class__.__name__,
                 min_size, max_size, self._randomizer)

  def _resize_goals(self, goal_size):
    self._home_goal.resize(
        pos=(-self._size[0] + goal_size[0] + self._fb_offset, 0, goal_size[2]),
        size=goal_size)
    self._away_goal.resize(
        pos=(self._size[0] - goal_size[0] - self._fb_offset, 0, goal_size[2]),
        size=goal_size)

  def initialize_episode_mjcf(self, random_state):
    super().initialize_episode_mjcf(random_state)
    min_len, min_wid = self._min_size
    max_len, max_wid = self._max_size

    if self._keep_aspect_ratio:
      len_ratio = self._randomizer(random_state=random_state)
      wid_ratio = len_ratio
    else:
      len_ratio = self._randomizer(random_state=random_state)
      wid_ratio = self._randomizer(random_state=random_state)

    self._size = (min_len + len_ratio * (max_len - min_len),
                  min_wid + wid_ratio * (max_wid - min_wid))

    # Reset top_down camera field of view.
    self._top_camera.fovy = _top_down_cam_fovy(self._size,
                                               self._top_camera_distance)

    # Resize ground perimeter.
    self._update_perimeter()

    # Resize and reposition walls and roof geoms.
    for i, (wall_pos, _) in enumerate(_wall_pos_xyaxes(self._size)):
      self._walls[i].pos = wall_pos

    goal_size = self._get_goal_size()
    self._resize_goals(goal_size)

    # Resize inverted field position detectors.
    field_size = (self._size[0] -2*goal_size[0], self._size[1] -2*goal_size[0])
    self._field.resize(pos=(0, 0), size=field_size)

    # Resize ground geom size.
    self._ground_geom.size = list(
        field_size) + [max(self._size) * _GROUND_GEOM_GRID_RATIO]

    # Resize and reposition field box geoms.
    if self._field_box:
      for i, (pos, size) in enumerate(
          _fieldbox_pos_size((self._field.upper - self._field.lower) / 2.0,
                             goal_size)):
        self._field_box[i].pos = pos
        self._field_box[i].size = size

    # Reposition corner lights.
    _reposition_corner_lights(
        self._corner_lights,
        size=(self._size[0] - 2 * goal_size[0],
              self._size[1] - 2 * goal_size[0]))

    # Resize, reposition and recolor hoarding geoms.
    self._update_hoarding()

# Mini-football (5v5) dimensions.
_GOAL_LENGTH = 3.66
_GOAL_SIDE = 1.22

MINI_FOOTBALL_MIN_AREA_PER_HUMANOID = 100.0
MINI_FOOTBALL_MAX_AREA_PER_HUMANOID = 350.0
MINI_FOOTBALL_GOAL_SIZE = (_GOAL_SIDE / 2, _GOAL_LENGTH / 2, _GOAL_SIDE / 2)


text:
//
//  TTPlayer_ios.h
//  TTPlayerExample
//
//  Created by liang on 19/7/17.
//  Copyright © 2017年 tina. All rights reserved.
//

#ifndef TTPlayer_ios_h
#define TTPlayer_ios_h

#include "TTPlayer.hpp"
#include "TTRender.hpp"

#import "TTOpenGLView.h"

TT::Player *createPlayer_ios();

BOOL bindGLView_ios(TT::Player *player, TTOpenGLView *view);

#endif /* TTPlayer_ios_h */


text:
/*table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
    width:100%;
    text-align: center;
    color: midnightblue;
}
th, td {
    padding: 50px;
}*/
body {
	background-color: mistyrose;
	color: midnightblue;
    word-wrap: break-word;
}
h1{
	color: midnightblue;
    word-wrap: break-word;
}
table{
    table-layout: fixed;
    word-wrap: break-word;
}
/*#header {
    background-color:lightsalmon;
    color:white;
    text-align:center;
    padding:5px;
}
#navigation {
    line-height:30px;
    background-color:lightsalmon;
    height:150px;
    width:100px;
    float:left;
    padding:5px;
}
*/


text:
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;

import com.github.sarxos.webcam.Webcam;

/**
 * This is controller for WebCamPreview FXML.
 *
 * @author Rakesh Bhatt (rakeshbhatt10)
 */
public class WebCamPreviewController implements Initializable {

	@FXML
	Button btnStartCamera;

	@FXML
	Button btnStopCamera;

	@FXML
	Button btnDisposeCamera;

	@FXML
	ComboBox<WebCamInfo> cbCameraOptions;

	@FXML
	BorderPane bpWebCamPaneHolder;

	@FXML
	FlowPane fpBottomPane;

	@FXML
	ImageView imgWebCamCapturedImage;

	private class WebCamInfo {

		private String webCamName;
		private int webCamIndex;

		public String getWebCamName() {
			return webCamName;
		}

		public void setWebCamName(String webCamName) {
			this.webCamName = webCamName;
		}

		public int getWebCamIndex() {
			return webCamIndex;
		}

		public void setWebCamIndex(int webCamIndex) {
			this.webCamIndex = webCamIndex;
		}

		@Override
		public String toString() {
			return webCamName;
		}
	}

	private BufferedImage grabbedImage;
	private Webcam selWebCam = null;
	private boolean stopCamera = false;
	private ObjectProperty<Image> imageProperty = new SimpleObjectProperty<Image>();

	private String cameraListPromptText = "Choose Camera";

	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {

		fpBottomPane.setDisable(true);
		ObservableList<WebCamInfo> options = FXCollections.observableArrayList();
		int webCamCounter = 0;
		for (Webcam webcam : Webcam.getWebcams()) {
			WebCamInfo webCamInfo = new WebCamInfo();
			webCamInfo.setWebCamIndex(webCamCounter);
			webCamInfo.setWebCamName(webcam.getName());
			options.add(webCamInfo);
			webCamCounter++;
		}
		cbCameraOptions.setItems(options);
		cbCameraOptions.setPromptText(cameraListPromptText);
		cbCameraOptions.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<WebCamInfo>() {

			@Override
			public void changed(ObservableValue<? extends WebCamInfo> arg0, WebCamInfo arg1, WebCamInfo arg2) {
				if (arg2 != null) {
					System.out.println("WebCam Index: " + arg2.getWebCamIndex() + ": WebCam Name:" + arg2.getWebCamName());
					initializeWebCam(arg2.getWebCamIndex());
				}
			}
		});
		Platform.runLater(new Runnable() {

			@Override
			public void run() {
				setImageViewSize();
			}
		});

	}

	protected void setImageViewSize() {

		double height = bpWebCamPaneHolder.getHeight();
		double width = bpWebCamPaneHolder.getWidth();
		imgWebCamCapturedImage.setFitHeight(height);
		imgWebCamCapturedImage.setFitWidth(width);
		imgWebCamCapturedImage.prefHeight(height);
		imgWebCamCapturedImage.prefWidth(width);
		imgWebCamCapturedImage.setPreserveRatio(true);

	}

	protected void initializeWebCam(final int webCamIndex) {

		Task<Void> webCamIntilizer = new Task<Void>() {

			@Override
			protected Void call() throws Exception {

				if (selWebCam == null) {
					selWebCam = Webcam.getWebcams().get(webCamIndex);
					selWebCam.open();
				} else {
					closeCamera();
					selWebCam = Webcam.getWebcams().get(webCamIndex);
					selWebCam.open();
				}
				startWebCamStream();
				return null;
			}

		};

		new Thread(webCamIntilizer).start();
		fpBottomPane.setDisable(false);
		btnStartCamera.setDisable(true);
	}

	protected void startWebCamStream() {

		stopCamera = false;
		Task<Void> task = new Task<Void>() {

			@Override
			protected Void call() throws Exception {

				while (!stopCamera) {
					try {
						if ((grabbedImage = selWebCam.getImage()) != null) {

							Platform.runLater(new Runnable() {

								@Override
								public void run() {
									final Image mainiamge = SwingFXUtils
										.toFXImage(grabbedImage, null);
									imageProperty.set(mainiamge);
								}
							});

							grabbedImage.flush();

						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				return null;
			}

		};
		Thread th = new Thread(task);
		th.setDaemon(true);
		th.start();
		imgWebCamCapturedImage.imageProperty().bind(imageProperty);

	}

	private void closeCamera() {
		if (selWebCam != null) {
			selWebCam.close();
		}
	}

	public void stopCamera(ActionEvent event) {
		stopCamera = true;
		btnStartCamera.setDisable(false);
		btnStopCamera.setDisable(true);
	}

	public void startCamera(ActionEvent event) {
		stopCamera = false;
		startWebCamStream();
		btnStartCamera.setDisable(true);
		btnStopCamera.setDisable(false);
	}

	public void disposeCamera(ActionEvent event) {
		stopCamera = true;
		closeCamera();
		btnStopCamera.setDisable(true);
		btnStartCamera.setDisable(true);
	}
}


text:
package org.apache.eagle.alert.engine.sorter.impl;

import org.apache.eagle.alert.engine.model.PartitionedEvent;
import org.apache.eagle.alert.engine.utils.SerializableUtils;
import org.jetbrains.annotations.NotNull;
import org.mapdb.DataInput2;
import org.mapdb.DataOutput2;
import org.mapdb.Serializer;
import org.mapdb.serializer.GroupSerializer;

import java.io.IOException;
import java.util.Comparator;

public class PartitionedEventGroupSerializer implements GroupSerializer<PartitionedEvent[]> {
    private static final GroupSerializer<byte[]> delegate = Serializer.BYTE_ARRAY;

    @Override
    public int valueArraySearch(Object keys, PartitionedEvent[] key) {
        return delegate.valueArraySearch(keys, serialize(key));
    }

    @SuppressWarnings("rawtypes")
    @Override
    public int valueArraySearch(Object keys, PartitionedEvent[] key, Comparator comparator) {
        return delegate.valueArraySearch(keys, serialize(key), comparator);
    }

    @Override
    public void valueArraySerialize(DataOutput2 out, Object vals) throws IOException {
        delegate.valueArraySerialize(out, vals);
    }

    @Override
    public Object valueArrayDeserialize(DataInput2 in, int size) throws IOException {
        return delegate.valueArrayDeserialize(in, size);
    }

    @Override
    public PartitionedEvent[] valueArrayGet(Object vals, int pos) {
        return deserialize(delegate.valueArrayGet(vals, pos));
    }

    @Override
    public int valueArraySize(Object vals) {
        return delegate.valueArraySize(vals);
    }

    @Override
    public Object valueArrayEmpty() {
        return delegate.valueArrayEmpty();
    }

    @Override
    public Object valueArrayPut(Object vals, int pos, PartitionedEvent[] newValue) {
        return delegate.valueArrayPut(vals, pos, serialize(newValue));
    }

    @Override
    public Object valueArrayUpdateVal(Object vals, int pos, PartitionedEvent[] newValue) {
        return delegate.valueArrayUpdateVal(vals, pos, serialize(newValue));
    }

    @Override
    public Object valueArrayFromArray(Object[] objects) {
        return delegate.valueArrayFromArray(objects);
    }

    @Override
    public Object valueArrayCopyOfRange(Object vals, int from, int to) {
        return delegate.valueArrayCopyOfRange(vals, from, to);
    }

    @Override
    public Object valueArrayDeleteValue(Object vals, int pos) {
        return delegate.valueArrayDeleteValue(vals, pos);
    }

    @Override
    public void serialize(@NotNull DataOutput2 out, @NotNull PartitionedEvent[] value) throws IOException {
        delegate.serialize(out, serialize(value));
    }

    private static byte[] serialize(PartitionedEvent[] events) {
        return SerializableUtils.serializeToCompressedByteArray(events);
    }

    @Override
    public PartitionedEvent[] deserialize(@NotNull DataInput2 input, int available) throws IOException {
        return deserialize(delegate.deserialize(input, available));
    }

    private static PartitionedEvent[] deserialize(byte[] bytes) {
        return (PartitionedEvent[]) SerializableUtils.deserializeFromCompressedByteArray(bytes, "deserialize as stream event");
    }

}


text:
module Accountly
  class UsernameForm
    include ActiveModel::Model

    attr_accessor :original_password, :new_username, :new_username_confirmation

    validate :verify_original_password, if: Proc.new { |u| u.original_password.present? }
    validates :original_password, presence: true
    validate :verify_unique_username

    validates :new_username, presence: true
    validates :new_username, length: { minimum: 5 }
    validates :new_username, confirmation: true

    def initialize(user)
      @user = user
    end

    def submit(params)
      self.original_password = params[:original_password]
      self.new_username = params[:new_username]
      self.new_username_confirmation = params[:new_username_confirmation]

      if valid?
        @user.username = new_username
        @user.save!
        true
      else
        false
      end
    end

    def verify_unique_username
      unless @user.confirmed_duplicate_username(self.new_username)
        errors.add :new_username, I18n.t('activemodel.errors.models.accountly/username_form.attributes.new_username.duplicate')
      end
    end

    def verify_original_password
      if @user.authenticate(original_password)
        true
      else
        errors.add :original_password, I18n.t('activemodel.errors.models.accountly/username_form.attributes.original_password.invalid')
        false
      end
    end
  end
end


text:
package VMOMI::VmInstanceUuidChangedEvent;
use parent 'VMOMI::VmEvent';

use strict;
use warnings;

our @class_ancestors = (
    'VmEvent',
    'Event',
    'DynamicData',
);

our @class_members = (
    ['oldInstanceUuid', undef, 0, ],
    ['newInstanceUuid', undef, 0, ],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;