text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using MonsterGame;

public class HudLayout : MonoBehaviour {

    public GameObject centerBoard;
    public GameObject background;
    private float screenWidth;
    private float screenHeight;
    private bool needsChange;
	// Use this for initialization
	void Start () {

        needsChange = true;
        screenWidth = screenHeight = 0.0f;
    }

	// Update is called once per frame
	void Update () {

        if (this.screenHeight != Screen.height ||
             this.screenWidth != Screen.width)
            needsChange = true;

        if (needsChange && centerBoard != null)
        {
            Vector3 boardPosition = centerBoard.transform.position;
            Vector3 boardPositionTopLeft = boardPosition;

            var canvasTransform = GetComponent<RectTransform>();

            float canvasWidth = canvasTransform.rect.width ;
            float canvasHeight = 720f; // / canvasTransform.localScale.y;

            float boardHeight = GameState.Instance.MazeConfiguration.Height;
            float boardWeight = GameState.Instance.MazeConfiguration.Width;
            float height, width;
            height = Screen.height;
            width = Screen.width;
            Vector3 boardPositionScreen = Camera.main.WorldToScreenPoint(boardPositionTopLeft);
            Vector3 boardPositionViewport = Camera.main.WorldToViewportPoint(boardPositionTopLeft);

            var gameObject = GameObject.Find(Constants.Maze_ScoreText );
            Text score = gameObject.GetComponent<Text>();
            RectTransform scoreTransform = score.GetComponent<RectTransform>();
            //Aligns top left so  x->   and y is negative offset from top..

            // scoreTransform.rect.xMin =  boardPositionViewport.x * canvasWidth;
            // scoreTransform.rect.y = boardPositionViewport.y * canvasHeight;
            scoreTransform.anchoredPosition = new Vector2(boardPositionViewport.x * canvasWidth,
                                                    ( boardPositionViewport.y * canvasHeight )   + scoreTransform.rect.height/2 );

            gameObject = GameObject.Find( Constants.Maze_NameText );
            //it is possible for this to not be Active if we are not using login
            if (gameObject != null)
            {
                Vector3 boardPositionTopRight = new Vector3(boardPositionTopLeft.x + boardWeight, boardPositionTopLeft.y, boardPositionTopLeft.z);
                boardPositionViewport = Camera.main.WorldToViewportPoint(boardPositionTopRight);
                Text name = gameObject.GetComponent<Text>();
                RectTransform nameTransform = name.GetComponent<RectTransform>();

                //Alighs top right
                nameTransform.anchoredPosition =
                    new Vector2((boardPositionViewport.x * canvasWidth) - nameTransform.rect.width,
                                (boardPositionViewport.y * canvasHeight) + scoreTransform.rect.height / 2);

            }
            gameObject = GameObject.Find(Constants.Maze_MonsterCountText);
            Vector3 boardPositionBottomLeft = new Vector3(boardPositionTopLeft.x, boardPositionTopLeft.y - boardHeight, boardPositionTopLeft.z);
            boardPositionViewport = Camera.main.WorldToViewportPoint(boardPositionBottomLeft);
            Image monster = gameObject.GetComponent<UnityEngine.UI.Image>();
            RectTransform monsterTransform = gameObject.GetComponent<RectTransform>();

            monsterTransform.anchoredPosition =
                            new Vector2((boardPositionViewport.x * canvasWidth) ,
                            (boardPositionViewport.y * canvasHeight) - (monsterTransform.rect.height/2) );

            gameObject = GameObject.Find(Constants.Maze_LivesText);

            Text lives = gameObject.GetComponent<Text>();
            RectTransform livesTransform = lives.GetComponent<RectTransform>();
            // Aligns bottom left so no need to map coords
            livesTransform.anchoredPosition =
                            new Vector2((boardPositionViewport.x * canvasWidth) + monsterTransform.rect.width + 10,
                            (boardPositionViewport.y * canvasHeight) - (monsterTransform.rect.height / 2));

            needsChange = false;
            this.screenHeight = Screen.height;
            this.screenWidth = Screen.width;
        }
    }

 }


text:
package org.springframework.cloud.netflix.ribbon.okhttp;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;
import org.junit.Test;

import org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext;
import org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer;
import org.springframework.util.LinkedMultiValueMap;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * @author Spencer Gibb
 */
public class OkHttpRibbonRequestTests {

	@Test
	public void testNullEntity() throws Exception {
		String uri = "http://example.com";
		LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		headers.add("my-header", "my-value");
		// headers.add(HttpEncoding.CONTENT_LENGTH, "5192");
		LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<>();
		params.add("myparam", "myparamval");
		RibbonCommandContext context = new RibbonCommandContext("example", "GET", uri,
				false, headers, params, null, new ArrayList<RibbonRequestCustomizer>());
		OkHttpRibbonRequest httpRequest = new OkHttpRibbonRequest(context);

		Request request = httpRequest.toRequest();

		assertThat(request.body()).as("body is not null").isNull();
		assertThat(request.url().toString()).as("uri is wrong").startsWith(uri);
		assertThat(request.header("my-header")).as("my-header is wrong")
				.isEqualTo("my-value");
		assertThat(request.url().queryParameter("myparam")).as("myparam is missing")
				.isEqualTo("myparamval");
	}

	@Test
	// this situation happens, see
	// https://github.com/spring-cloud/spring-cloud-netflix/issues/1042#issuecomment-227723877
	public void testEmptyEntityGet() throws Exception {
		String entityValue = "";
		testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), false,
				"GET");
	}

	@Test
	public void testNonEmptyEntityPost() throws Exception {
		String entityValue = "abcd";
		testEntity(entityValue, new ByteArrayInputStream(entityValue.getBytes()), true,
				"POST");
	}

	void testEntity(String entityValue, ByteArrayInputStream requestEntity,
			boolean addContentLengthHeader, String method) throws IOException {
		String lengthString = String.valueOf(entityValue.length());
		Long length = null;
		String uri = "http://example.com";
		LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		if (addContentLengthHeader) {
			headers.add("Content-Length", lengthString);
			length = (long) entityValue.length();
		}

		RibbonRequestCustomizer requestCustomizer = new RibbonRequestCustomizer<Request.Builder>() {
			@Override
			public boolean accepts(Class builderClass) {
				return builderClass == Request.Builder.class;
			}

			@Override
			public void customize(Request.Builder builder) {
				builder.addHeader("from-customizer", "foo");
			}
		};
		RibbonCommandContext context = new RibbonCommandContext("example", method, uri,
				false, headers, new LinkedMultiValueMap<String, String>(), requestEntity,
				Collections.singletonList(requestCustomizer));
		context.setContentLength(length);
		OkHttpRibbonRequest httpRequest = new OkHttpRibbonRequest(context);

		Request request = httpRequest.toRequest();

		assertThat(request.url().toString()).as("uri is wrong").startsWith(uri);
		if (addContentLengthHeader) {
			assertThat(request.header("Content-Length")).as("Content-Length is wrong")
					.isEqualTo(lengthString);
		}
		assertThat(request.header("from-customizer")).as("from-customizer is wrong")
				.isEqualTo("foo");

		if (!method.equalsIgnoreCase("get")) {
			assertThat(request.body()).as("body is null").isNotNull();
			RequestBody body = request.body();
			assertThat(body.contentLength()).as("contentLength is wrong")
					.isEqualTo((long) entityValue.length());
			Buffer content = new Buffer();
			body.writeTo(content);
			String string = content.readByteString().utf8();
			assertThat(string).as("content is wrong").isEqualTo(entityValue);
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Graze\CsvToken\Test\Unit\Buffer;

use Graze\CsvToken\Buffer\StreamBuffer;
use Graze\CsvToken\Test\TestCase;

class StreamBufferTest extends TestCase
{
    /**
     * @param string $string
     *
     * @return resource
     */
    private function makeStream($string)
    {
        $stream = fopen('php://memory', 'r+');
        fwrite($stream, $string);
        rewind($stream);
        return $stream;
    }

    public function testBasicProperties()
    {
        $stream = $this->makeStream('some text here and things');
        $buffer = new StreamBuffer($stream);

        static::assertEquals(0, $buffer->getPosition());
        static::assertEquals('', $buffer->getContents());
        static::assertEquals(0, $buffer->getLength());
        static::assertTrue($buffer->isEof());
        static::assertFalse($buffer->isSourceEof());

        $buffer->read();

        static::assertEquals(0, $buffer->getPosition());
        static::assertEquals('some text here and things', $buffer->getContents());
        static::assertEquals(25, $buffer->getLength());
        static::assertFalse($buffer->isEof());
        static::assertFalse($buffer->isSourceEof());

        $buffer->read();

        static::assertTrue($buffer->isSourceEof());
    }

    public function testReadSize()
    {
        $stream = $this->makeStream('first second third fourth fifth');
        $buffer = new StreamBuffer($stream, 6);

        $buffer->read();

        static::assertEquals('first ', $buffer->getContents());
    }

    public function testMinSize()
    {
        $stream = $this->makeStream('first second third fourth');
        $buffer = new StreamBuffer($stream, 10, 2);

        $buffer->read();
        static::assertEquals('first seco', $buffer->getContents());
        $buffer->read();
        static::assertEquals('first seco', $buffer->getContents());

        static::assertEquals(2, $buffer->getMinBufferSize());
        static::assertSame($buffer, $buffer->setMinBufferSize(-1));
        static::assertEquals(-1, $buffer->getMinBufferSize());
        $buffer->read();
        static::assertEquals('first second third f', $buffer->getContents());
    }

    public function testMove()
    {
        $stream = $this->makeStream('first second third fourth');
        $buffer = new StreamBuffer($stream, 10, 2);

        $buffer->read();
        static::assertEquals('first seco', $buffer->getContents());
        $buffer->move(9);
        static::assertEquals('o', $buffer->getContents());
        $buffer->read();
        static::assertEquals('ond third f', $buffer->getContents());
    }
}


text:
package webcrypt.crypto;

/**
 * The Vigenere class is a simple implementation of Kernel
 * which implements all the basic features of a secret key stream cipher.
 * All characters are capitalized, and then shifted around
 * according to their position and the relevant portion of the key word.
 * The key is a keyword which is used cyclically with A standing
 * for no shift while Z standing for -1 shift.
 *
 * EG:  Suppose the keyword is SECRET and the plaintext was ATTACK BAGDAD
 * Then the cipher text is computed as follows:
 *
 * plaintext--->          A  T  T  A  C  K  B  A  G  D  A  D
 * cycled key word --->   S  E  C  R  E  T  S  E  C  R  E  T
 *
 * which is equivalent to:
 * plaintext--->          A  T  T  A  C  K  B  A  G  D  A  D
 * numeric shift--->  +  18  4  2 17  4 19 18  4  2 17  4 19
 *                    ______________________________________
 * result --->            S  X  V  K  G  E  U  E  I  V  E  X
 *
 * The default operation on non-letters is to ignore the character
 * by not transforming it, and by not advancing the key cycling.
 *
 */
public class Vigenere extends Kernel{

    public String toString(){
	return "Vigenere"; //"Vigen\u008cre";
    }

    public Vigenere(){
	setAssociatedKeyClass("webcrypt.crypto.VigenereKey");
	setDomain(LETTERS);
    }

    /**
     * As the Vigenere cipher acts locally on the text without changing
     * the size, implement the void version
     */
    public void encryptOn(StringBuffer plaintext, Key e){
	VigenereKey vk = (VigenereKey)e;
	char[] ek = vk.getEffectiveKey();  //Effective Key
	if(ek == null || ek.length == 0) //trivializ bad key
	    ek = new char[] { (char)0 };
	int keylength = ek.length;
	int j = 0; // rotating key-index

	int len = plaintext.length();
	for (int i=0; i<len; i++){
	    char c = plaintext.charAt(i);
	    if(inDomain(c)){ //then operate on c
		if( (int)c > 90 ) // lower case
		    c -= 32; // convert to upper case
		c -= 65; // now can operate mod-26:
		c += ek[j];
		c %= 26;
		plaintext.setCharAt(i,(char)(c+65));

		j = (j+1)%keylength;  //next key element
	    }
	}
   }

    /**
     * Decryption is a simple variant of the above
     */
    public void decryptOn(StringBuffer ciphertext, Key e){
	encryptOn(ciphertext,e.reverseKey());
    }

    /**
     * Simple test of Vigenere on command line
     */
    public static void main(String[] args){
	//	System.out.println("got here");
	Vigenere vigenere = new Vigenere();
	System.out.println(""+vigenere);
	System.out.println("PLAINTEXT:\n"+args[0]);
	//	System.out.println("CIPHERTEXT:\n"+vigenere.encrypt(new StringBuffer(args[0]),));
	//	System.out.println("PLAINTEXT(CIPHERTEXT):\n"
	//	   +vigenere.decrypt(vigenere.encrypt(new StringBuffer(args[0]),"3")));
    }

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.15 at 08:44:39 PM EDT
//

package org.sierraecg.schema.jaxb._1_04;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <simpleContent>
 *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
 *       <attribute name="vcgname" use="required" type="{http://www3.medical.philips.com}TYPEvcgname" />
 *       <attribute name="duration" use="required" type="{http://www3.medical.philips.com}TYPEduration" />
 *     </extension>
 *   </simpleContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "value"
})
@XmlRootElement(name = "vcg")
public class Vcg {

    @XmlValue
    protected String value;
    @XmlAttribute(name = "vcgname", required = true)
    protected TYPEvcgname vcgname;
    @XmlAttribute(name = "duration", required = true)
    protected String duration;

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * Gets the value of the vcgname property.
     *
     * @return
     *     possible object is
     *     {@link TYPEvcgname }
     *
     */
    public TYPEvcgname getVcgname() {
        return vcgname;
    }

    /**
     * Sets the value of the vcgname property.
     *
     * @param value
     *     allowed object is
     *     {@link TYPEvcgname }
     *
     */
    public void setVcgname(TYPEvcgname value) {
        this.vcgname = value;
    }

    /**
     * Gets the value of the duration property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDuration() {
        return duration;
    }

    /**
     * Sets the value of the duration property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDuration(String value) {
        this.duration = value;
    }

}


text:
package org.elasticsearch.index.seqno;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.util.Objects;

/**
 * A "shard history retention lease" (or "retention lease" for short) is conceptually a marker containing a retaining sequence number such
 * that all operations with sequence number at least that retaining sequence number will be retained during merge operations (which could
 * otherwise merge away operations that have been soft deleted). Each retention lease contains a unique identifier, the retaining sequence
 * number, the timestamp of when the lease was created or renewed, and the source of the retention lease (e.g., "ccr").
 */
public final class RetentionLease implements ToXContentObject, Writeable {

    private final String id;

    /**
     * The identifier for this retention lease. This identifier should be unique per lease and is set during construction by the caller.
     *
     * @return the identifier
     */
    public String id() {
        return id;
    }

    private final long retainingSequenceNumber;

    /**
     * The retaining sequence number of this retention lease. The retaining sequence number is the minimum sequence number that this
     * retention lease wants to retain during merge operations. The retaining sequence number is set during construction by the caller.
     *
     * @return the retaining sequence number
     */
    public long retainingSequenceNumber() {
        return retainingSequenceNumber;
    }

    private final long timestamp;

    /**
     * The timestamp of when this retention lease was created or renewed.
     *
     * @return the timestamp used as a basis for determining lease expiration
     */
    public long timestamp() {
        return timestamp;
    }

    private final String source;

    /**
     * The source of this retention lease. The source is set during construction by the caller.
     *
     * @return the source
     */
    public String source() {
        return source;
    }

    /**
     * Constructs a new retention lease.
     *
     * @param id                      the identifier of the retention lease
     * @param retainingSequenceNumber the retaining sequence number
     * @param timestamp               the timestamp of when the retention lease was created or renewed
     * @param source                  the source of the retention lease
     */
    public RetentionLease(final String id, final long retainingSequenceNumber, final long timestamp, final String source) {
        Objects.requireNonNull(id);
        if (id.isEmpty()) {
            throw new IllegalArgumentException("retention lease ID can not be empty");
        }
        if (retainingSequenceNumber < 0) {
            throw new IllegalArgumentException("retention lease retaining sequence number [" + retainingSequenceNumber + "] out of range");
        }
        if (timestamp < 0) {
            throw new IllegalArgumentException("retention lease timestamp [" + timestamp + "] out of range");
        }
        Objects.requireNonNull(source);
        if (source.isEmpty()) {
            throw new IllegalArgumentException("retention lease source can not be empty");
        }
        this.id = id;
        this.retainingSequenceNumber = retainingSequenceNumber;
        this.timestamp = timestamp;
        this.source = source;
    }

    /**
     * Constructs a new retention lease from a stream. The retention lease should have been written via {@link #writeTo(StreamOutput)}.
     *
     * @param in the stream to construct the retention lease from
     * @throws IOException if an I/O exception occurs reading from the stream
     */
    public RetentionLease(final StreamInput in) throws IOException {
        id = in.readString();
        retainingSequenceNumber = in.readZLong();
        timestamp = in.readVLong();
        source = in.readString();
    }

    /**
     * Writes a retention lease to a stream in a manner suitable for later reconstruction via {@link #RetentionLease(StreamInput)}.
     *
     * @param out the stream to write the retention lease to
     * @throws IOException if an I/O exception occurs writing to the stream
     */
    @Override
    public void writeTo(final StreamOutput out) throws IOException {
        out.writeString(id);
        out.writeZLong(retainingSequenceNumber);
        out.writeVLong(timestamp);
        out.writeString(source);
    }

    private static final ParseField ID_FIELD = new ParseField("id");
    private static final ParseField RETAINING_SEQUENCE_NUMBER_FIELD = new ParseField("retaining_sequence_number");
    private static final ParseField TIMESTAMP_FIELD = new ParseField("timestamp");
    private static final ParseField SOURCE_FIELD = new ParseField("source");

    private static final ConstructingObjectParser<RetentionLease, Void> PARSER = new ConstructingObjectParser<>(
            "retention_leases",
            (a) -> new RetentionLease((String) a[0], (Long) a[1], (Long) a[2], (String) a[3]));

    static {
        PARSER.declareString(ConstructingObjectParser.constructorArg(), ID_FIELD);
        PARSER.declareLong(ConstructingObjectParser.constructorArg(), RETAINING_SEQUENCE_NUMBER_FIELD);
        PARSER.declareLong(ConstructingObjectParser.constructorArg(), TIMESTAMP_FIELD);
        PARSER.declareString(ConstructingObjectParser.constructorArg(), SOURCE_FIELD);
    }

    @Override
    public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException {
        builder.startObject();
        {
            builder.field(ID_FIELD.getPreferredName(), id);
            builder.field(RETAINING_SEQUENCE_NUMBER_FIELD.getPreferredName(), retainingSequenceNumber);
            builder.field(TIMESTAMP_FIELD.getPreferredName(), timestamp);
            builder.field(SOURCE_FIELD.getPreferredName(), source);
        }
        builder.endObject();
        return builder;
    }

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

    /**
     * Parses a retention lease from {@link org.elasticsearch.common.xcontent.XContent}. This method assumes that the retention lease was
     * converted to {@link org.elasticsearch.common.xcontent.XContent} via {@link #toXContent(XContentBuilder, Params)}.
     *
     * @param parser the parser
     * @return a retention lease
     */
    public static RetentionLease fromXContent(final XContentParser parser) {
        return PARSER.apply(parser, null);
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        final RetentionLease that = (RetentionLease) o;
        return Objects.equals(id, that.id) &&
                retainingSequenceNumber == that.retainingSequenceNumber &&
                timestamp == that.timestamp &&
                Objects.equals(source, that.source);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, retainingSequenceNumber, timestamp, source);
    }

    @Override
    public String toString() {
        return "RetentionLease{" +
                "id='" + id + '\'' +
                ", retainingSequenceNumber=" + retainingSequenceNumber +
                ", timestamp=" + timestamp +
                ", source='" + source + '\'' +
                '}';
    }

}


text:
package com.gs.fw.common.mithra.test.multivm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class RemoteSlaveVmImpl implements RemoteSlaveVm
{
    private static  Logger logger = LoggerFactory.getLogger(RemoteSlaveVmImpl.class.getName());

    private static MultiVmTest runningTest;
    private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
    private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];

    private static SlaveVmHeartbeat heartbeat;

    public RemoteSlaveVmImpl()
    {
        if (heartbeat == null)
        {
            heartbeat = new SlaveVmHeartbeat();
            heartbeat.start();
        }
    }

    public static void exitSlaveVm()
    {
        synchronized(heartbeat)
        {
            heartbeat.setDone(true);
            heartbeat.notify();
        }
    }

    public void ping()
    {
        this.heartbeat.setLastPingTime(System.currentTimeMillis());
    }

    public Object executeMethod(String methodName)
    {
        try
        {
            this.logger.debug("executing method "+methodName);
            Method method = runningTest.getClass().getMethod(methodName, EMPTY_CLASS_ARRAY);
            return method.invoke(runningTest, EMPTY_OBJECT_ARRAY);
        }
        catch(InvocationTargetException ite)
        {
            Throwable t = ite.getTargetException();
            if (t instanceof Error) throw (Error) t;
            if (t instanceof RuntimeException) throw (RuntimeException) t;
            throw new RemoteSlaveVmException("Could not execute method"+methodName+" on class "+runningTest.getClass().getName(), ite);
        }
        catch(Error e)
        {
            throw e;
        }
        catch(RuntimeException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            logger.error("Could not execute method "+methodName+" on class "+runningTest.getClass().getName(), e);
            throw new RemoteSlaveVmException("Could not execute method "+methodName+" on class "+runningTest.getClass().getName(), e);
        }
    }

    public Object executeMethod(String methodName, Class[] argumentTypes, Object[] args)
    {
        try
        {
            this.logger.debug("executing method "+methodName);
            Method method = runningTest.getClass().getMethod(methodName, argumentTypes);
            return method.invoke(runningTest, args);
        }
        catch(InvocationTargetException ite)
        {
            Throwable t = ite.getTargetException();
            if (t instanceof Error) throw (Error) t;
            if (t instanceof RuntimeException) throw (RuntimeException) t;
            throw new RemoteSlaveVmException("Could not execute method"+methodName+" on class "+runningTest.getClass().getName(), ite);
        }
        catch(Error e)
        {
            throw e;
        }
        catch(RuntimeException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            logger.error("Could not execute method "+methodName+" on class "+runningTest.getClass().getName(), e);
            throw new RemoteSlaveVmException("Could not execute method "+methodName+" on class "+runningTest.getClass().getName(), e);
        }
    }

    public static void setTestCase(MultiVmTest testCase)
    {
        runningTest = testCase;
    }

    private static class SlaveVmHeartbeat extends Thread
    {
        private boolean done = false;
        private long lastPingTime;

        public SlaveVmHeartbeat()
        {
            this.setDaemon(false);
            this.setPriority(Thread.MIN_PRIORITY);
            this.lastPingTime = System.currentTimeMillis();
        }

        public void setLastPingTime(long lastPingTime)
        {
            this.lastPingTime = lastPingTime;
        }

        public void setDone(boolean done)
        {
            this.done = done;
        }

        public void run()
        {
            while(!done)
            {
                try
                {
                    synchronized(this)
                    {
                        this.wait(SlaveVm.HEARTBEAT_INTERVAL_MS);
                        if (lastPingTime < System.currentTimeMillis() - SlaveVm.PING_INTERVAL_MS * 5)
                        {
                            System.out.println("Forcing SlaveVm shutdown.");
                            System.exit(-1);
                        }
                    }
                }
                catch(Throwable e)
                {
                    // ignore
                }
            }
        }
    }

}


text:
package com.dujay.jvm.typeclasses;

import java.util.List;

public interface Generatable {
  public List<Byte> generate();
}


text:
/* global define */
define([
	'scope'
], function (scope) {
	'use strict';
	return scope;
});


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>gl-fragcoord Test</title>
<link rel="stylesheet" href="../../../resources/js-test-style.css"/>

<canvas id="canvas" width="32" height="32">
</canvas>


text:
package com.siriusit.spezg.multilib.storage.jpa;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import com.siriusit.spezg.multilib.domain.Statistics;
import com.siriusit.spezg.multilib.domain.jpa.StatisticsDomainObject;
import com.siriusit.spezg.multilib.storage.StatisticsRepository;

@Repository("statisticsRepository")
public class JpaStatisticsRepository implements StatisticsRepository {

    @PersistenceContext(unitName = "multilib-db")
    private EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public Statistics getStatistics() {
        Statistics statistics = new StatisticsDomainObject();

        TypedQuery<Long> numberOfUsersQuery = entityManager.createNamedQuery("countNumberOfUsers", Long.class);
        Long numberOfUsers = numberOfUsersQuery.getSingleResult();
        TypedQuery<Long> numberOfLoansQuery = entityManager.createNamedQuery("countNumberOfLoans", Long.class);
        Long numberOfLoans = numberOfLoansQuery.getSingleResult();
        TypedQuery<Long> numberOfTitlesQuery = entityManager.createNamedQuery("countNumberOfTitles", Long.class);
        Long numberOfTitles = numberOfTitlesQuery.getSingleResult();
        TypedQuery<Long> numberOfActiveLoansQuery = entityManager.createNamedQuery("countNumberOfActiveLoans",
                Long.class);
        Long numberOfActiveLoans = numberOfActiveLoansQuery.getSingleResult();

        statistics.setNumberOfActiveLoans(Integer.parseInt(numberOfActiveLoans.toString()));
        statistics.setNumberOfLoans(Integer.parseInt(numberOfLoans.toString()));
        statistics.setNumberOfTitles(Integer.parseInt(numberOfTitles.toString()));
        statistics.setNumberOfUsers(Integer.parseInt(numberOfUsers.toString()));

        return statistics;
    }

    @Override
    public Statistics saveStatistics() {
        Statistics statistics = getStatistics();
        entityManager.persist(statistics);
        return statistics;
    }

    @Override
    public Integer getNumberOfStatistics() {
        TypedQuery<Long> numberOStatisticsQuery = entityManager.createNamedQuery("countNumberOfStatistics", Long.class);
        Long numberOfStatistics = numberOStatisticsQuery.getSingleResult();
        return numberOfStatistics.intValue();
    }

}


text:
ICA_TESTRUNNING="TestRunning"      # The test is running
ICA_TESTCOMPLETED="TestCompleted"  # The test completed successfully
ICA_TESTABORTED="TestAborted"      # Error during setup of test
ICA_TESTFAILED="TestFailed"        # Error while performing the test

CONSTANTS_FILE="constants.sh"

LogMsg()
{
    echo `date "+%a %b %d %T %Y"` : ${1}    # To add the timestamp to the log file
}

cd ~

UpdateTestState()
{
    echo $1 > $HOME/state.txt
}

if [ -e ~/summary.log ]; then
    LogMsg "Info: Cleaning up previous copies of summary.log"
    rm -rf ~/summary.log
fi

LogMsg "Info: Updating test case state to running"
UpdateTestState $ICA_TESTRUNNING

# Source the constants file
if [ -e ~/${CONSTANTS_FILE} ]; then
    source ~/${CONSTANTS_FILE}
else
    msg="Error: no ${CONSTANTS_FILE} file"
    echo $msg
    echo $msg >> ~/summary.log
    UpdateTestState $ICA_TESTABORTED
    exit 10
fi

#
# Make sure constants.sh contains the variables we expect
#
if [ "${TC_COVERED:-UNDEFINED}" = "UNDEFINED" ]; then
    msg="Error: The test parameter TC_COVERED is not defined in ${CONSTANTS_FILE}"
    echo $msg >> ~/summary.log
fi

#
# Echo TCs we cover
#
echo "Covers ${TC_COVERED}" > ~/summary.log

if [ "${fileSystems:-UNDEFINED}" = "UNDEFINED" ]; then
    msg="Error: The test parameter fileSystems is not defined in constants file."
    LogMsg "$msg"
    echo $msg >> ~/summary.log
    UpdateTestState $ICA_TESTABORTED
    exit 30
fi

#
# Verify if guest sees the new drive
#
if [ ! -e "/dev/sdb" ]; then
    msg="Error: The Linux guest cannot detect the drive"
    LogMsg $msg
    echo $msg >> ~/summary.log
    UpdateTestState $ICA_TESTABORTED
    exit 30
fi
LogMsg "Info: The Linux guest detected the drive"

#Prepare Read/Write script for execution
dos2unix STOR_VHDXResize_ReadWrite.sh
chmod +x STOR_VHDXResize_ReadWrite.sh

#If the script is being run a second time modify the following variables
if [ "$rerun" = "yes" ]; then
    LogMsg "Info: Second pass of the script."
    testPartition="/dev/sdb2"
    fdiskOption=2
else
    testPartition="/dev/sdb1"
    fdiskOption=1
fi

count=0
for fs in "${fileSystems[@]}"; do

    # Create the new partition
    # delete partition firstly maily used if partition size >2TB, after use parted
    # to rm partition, still can show in fdisk -l even it does not exist in fact.
    (echo d; echo w) | fdisk /dev/sdb 2> /dev/null
    (echo n; echo p; echo $fdiskOption; echo ; echo ;echo w) | fdisk /dev/sdb 2> /dev/null
    if [ $? -gt 0 ]; then
        LogMsg "Error: Failed to create partition"
        echo "Error: Creating partition: Failed" >> ~/summary.log
        UpdateTestState $ICA_TESTFAILED
        exit 10
    fi
    LogMsg "Info: Partition created"
    sleep 5

    # Format the partition
    LogMsg "Info: Start testing filesystem: $fs"
    command -v mkfs.$fs
    if [ $? -ne 0 ]; then
        echo "Error: File-system tools for $fs not present. Skipping filesystem $fs.">> ~/summary.log
        LogMsg "Error: File-system tools for $fs not present. Skipping filesystem $fs."
        count=`expr $count + 1`
    else
        #Use -f option for xfs filesystem, but ignore parameter for other filesystems
        option=""
        if [ "$fs" = "xfs" ]; then
            option="-f"
        fi
        mkfs -t $fs $option $testPartition 2> ~/summary.log
        if [ $? -ne 0 ]; then
            LogMsg "Error: Failed to format partition with $fs"
            echo "Error: Formating partition: Failed with $fs" >> ~/summary.log
            UpdateTestState $ICA_TESTFAILED
            exit 10
        fi
        LogMsg "Info: Successfully formated partition with $fs"
    fi

    if [ $count -eq ${#fileSystems[@]} ]; then
        LogMsg "Error: Failed to format partition with ${fileSystems[@]} "
        echo "Error: Formating partition: Failed with all filesystems proposed." >> ~/summary.log
        UpdateTestState $ICA_TESTFAILED
        exit 10
    fi

    # Mount partition
    if [ ! -e "/mnt" ]; then
        mkdir /mnt 2> ~/summary.log
        if [ $? -ne 0 ]; then
            LogMsg "Error: Failed to create mount point"
            echo "Error: Creating mount point: Failed" >> ~/summary.log
            UpdateTestState $ICA_TESTFAILED
            exit 10
        fi
        LogMsg "Info: Mount point /dev/mnt created"
    fi

    mount $testPartition /mnt 2> ~summary.log
    if [ $? -ne 0 ]; then
        LogMsg "Error: Failed to mount partition"
        echo "Error: Mounting partition: Failed" >> ~/summary.log
        UpdateTestState $ICA_TESTFAILED
        exit 10
    fi
    LogMsg "Info: Partition mount successful"

    # Read/Write mount point
    ./STOR_VHDXResize_ReadWrite.sh

    umount /mnt
    if [ $? -ne 0 ]; then
        LogMsg "Error: Failed to unmount partition"
        echo "Error: Unmounting partition: Failed" >> ~/summary.log
        UpdateTestState $ICA_TESTFAILED
        exit 10
    fi
    LogMsg "Info: Unmount partition successful"

    (echo d; echo w) | fdisk /dev/sdb 2> /dev/null
    if [ $? -ne 0 ]; then
        LogMsg "Error: Failed to delete partition"
        echo "Error: Deleting partition: Failed" >> ~/summary.log
        UpdateTestState $ICA_TESTFAILED
        exit 10
    fi
    LogMsg "Info: Succesfully deleted partition"

done

UpdateTestState $ICA_TESTCOMPLETED
exit 0;


text:
package org.wso2.andes.server;

import junit.framework.TestCase;
import org.wso2.andes.server.ack.UnacknowledgedMessageMapImpl;
import org.wso2.andes.server.queue.QueueEntry;
import org.wso2.andes.server.queue.SimpleQueueEntryList;
import org.wso2.andes.server.queue.MockAMQMessage;
import org.wso2.andes.server.queue.AMQQueue;
import org.wso2.andes.server.queue.MockAMQQueue;
import org.wso2.andes.server.message.AMQMessage;
import org.wso2.andes.server.queue.QueueEntryIterator;
import org.wso2.andes.server.subscription.Subscription;
import org.wso2.andes.server.subscription.MockSubscription;
import org.wso2.andes.server.store.MemoryMessageStore;
import org.wso2.andes.server.store.MessageStore;
import org.wso2.andes.AMQException;

import java.util.Map;
import java.util.LinkedHashMap;
import java.util.LinkedList;

/**
 * QPID-1385 : Race condition between added to unacked map and resending due to a rollback.
 *
 * In AMQChannel _unackedMap.clear() was done after the visit. This meant that the clear was not in the same
 * synchronized block as as the preparation to resend.
 *
 * This clearing/prep for resend was done as a result of the rollback call. HOWEVER, the delivery thread was still
 * in the process of sending messages to the client. It is therefore possible that a message could block on the
 * _unackedMap lock waiting for the visit to compelete so that it can add the new message to the unackedMap....
 * which is then cleared by the resend/rollback thread.
 *
 * This problem was encountered by the testSend2ThenRollback test.
 *
 * To try and increase the chance of the race condition occuring this test will send multiple messages so that the
 * delivery thread will be in progress while the rollback method is called. Hopefully this will cause the
 * deliveryTag to be lost
 */
public class ExtractResendAndRequeueTest extends TestCase
{

    UnacknowledgedMessageMapImpl _unacknowledgedMessageMap;
    private static final int INITIAL_MSG_COUNT = 10;
    private AMQQueue _queue = new MockAMQQueue(getName());
    private MessageStore _messageStore = new MemoryMessageStore();
    private LinkedList<QueueEntry> _referenceList = new LinkedList<QueueEntry>();

    @Override
    public void setUp() throws AMQException
    {
        _unacknowledgedMessageMap = new UnacknowledgedMessageMapImpl(100, null);

        long id = 0;
        SimpleQueueEntryList list = new SimpleQueueEntryList(_queue);

        // Add initial messages to QueueEntryList
        for (int count = 0; count < INITIAL_MSG_COUNT; count++)
        {
            AMQMessage msg = new MockAMQMessage(id);

            list.add(msg);

            //Increment ID;
            id++;
        }

        // Iterate through the QueueEntryList and add entries to unacknowledgeMessageMap and referecenList
        QueueEntryIterator queueEntries = list.iterator();
        while(queueEntries.advance())
        {
            QueueEntry entry = queueEntries.getNode();
            _unacknowledgedMessageMap.add(entry.getMessage().getMessageNumber(), entry);

            // Store the entry for future inspection
            _referenceList.add(entry);
        }

        assertEquals("Map does not contain correct setup data", INITIAL_MSG_COUNT, _unacknowledgedMessageMap.size());
    }

    /**
     * Helper method to create a new subscription and aquire the given messages.
     *
     * @param messageList The messages to aquire
     *
     * @return Subscription that performed the aquire
     */
    private Subscription createSubscriptionAndAquireMessages(LinkedList<QueueEntry> messageList)
    {
        Subscription subscription = new MockSubscription();

        // Aquire messages in subscription
        for (QueueEntry entry : messageList)
        {
            entry.acquire(subscription);
        }

        return subscription;
    }

    /**
     * This is the normal consumer rollback method.
     *
     * An active consumer that has aquired messages expects those messasges to be reset when rollback is requested.
     *
     * This test validates that the msgToResend map includes all the messages and none are left behind.
     *
     * @throws AMQException the visit interface throws this
     */
    public void testResend() throws AMQException
    {
        //We don't need the subscription object here.
        createSubscriptionAndAquireMessages(_referenceList);

        final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
        final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();

        // requeueIfUnabletoResend doesn't matter here.
        _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
                                                                    msgToResend, true, _messageStore));

        assertEquals("Message count for resend not correct.", INITIAL_MSG_COUNT, msgToResend.size());
        assertEquals("Message count for requeue not correct.", 0, msgToRequeue.size());
        assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());
    }

    /**
     * This is the normal consumer close method.
     *
     * When a consumer that has aquired messages expects closes the messages that it has aquired should be removed from
     * the unacknowledgeMap and placed in msgToRequeue
     *
     * This test validates that the msgToRequeue map includes all the messages and none are left behind.
     *
     * @throws AMQException the visit interface throws this
     */
    public void testRequeueDueToSubscriptionClosure() throws AMQException
    {
        Subscription subscription = createSubscriptionAndAquireMessages(_referenceList);

        // Close subscription
        subscription.close();

        final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
        final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();

        // requeueIfUnabletoResend doesn't matter here.
        _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
                                                                    msgToResend, true, _messageStore));

        assertEquals("Message count for resend not correct.", 0, msgToResend.size());
        assertEquals("Message count for requeue not correct.", INITIAL_MSG_COUNT, msgToRequeue.size());
        assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());
    }

    /**
     * If the subscription is null, due to message being retrieved via a GET, And we request that messages are requeued
     * requeueIfUnabletoResend(set to true) then all messages should be sent to the msgToRequeue map.
     *
     * @throws AMQException the visit interface throws this
     */

    public void testRequeueDueToMessageHavingNoConsumerTag() throws AMQException
    {
        final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
        final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();

        // requeueIfUnabletoResend = true so all messages should go to msgToRequeue
        _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
                                                                    msgToResend, true, _messageStore));

        assertEquals("Message count for resend not correct.", 0, msgToResend.size());
        assertEquals("Message count for requeue not correct.", INITIAL_MSG_COUNT, msgToRequeue.size());
        assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());
    }

    /**
     * If the subscription is null, due to message being retrieved via a GET, And we request that we don't
     * requeueIfUnabletoResend(set to false) then all messages should be dropped as we do not have a dead letter queue.
     *
     * @throws AMQException the visit interface throws this
     */

    public void testDrop() throws AMQException
    {
        final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
        final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();

        // requeueIfUnabletoResend = false so all messages should be dropped all maps should be empty
        _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
                                                                    msgToResend, false, _messageStore));

        assertEquals("Message count for resend not correct.", 0, msgToResend.size());
        assertEquals("Message count for requeue not correct.", 0, msgToRequeue.size());
        assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());

        for (QueueEntry entry : _referenceList)
        {
            assertTrue("Message was not discarded", entry.isDeleted());
        }

    }

    /**
     * If the subscription is null, due to message being retrieved via a GET, AND the queue upon which the message was
     * delivered has been deleted then it is not possible to requeue. Currently we simply discar the message but in the
     * future we may wish to dead letter the message.
     *
     * Validate that at the end of the visit all Maps are empty and all messages are marked as deleted
     *
     * @throws AMQException the visit interface throws this
     */
    public void testDiscard() throws AMQException
    {
        final Map<Long, QueueEntry> msgToRequeue = new LinkedHashMap<Long, QueueEntry>();
        final Map<Long, QueueEntry> msgToResend = new LinkedHashMap<Long, QueueEntry>();

        _queue.delete();

        // requeueIfUnabletoResend : value doesn't matter here as queue has been deleted
        _unacknowledgedMessageMap.visit(new ExtractResendAndRequeue(_unacknowledgedMessageMap, msgToRequeue,
                                                                    msgToResend, false, _messageStore));

        assertEquals("Message count for resend not correct.", 0, msgToResend.size());
        assertEquals("Message count for requeue not correct.", 0, msgToRequeue.size());
        assertEquals("Map was not emptied", 0, _unacknowledgedMessageMap.size());

        for (QueueEntry entry : _referenceList)
        {
            assertTrue("Message was not discarded", entry.isDeleted());
        }
    }

}


text:
describe 'Third task' do
  describe RationalSequence do
    it 'should return the empty set when initialized with 0' do
      expect(RationalSequence.new(0).to_a).to eq []
    end

    it 'can calculate the first rational number' do
      expect(RationalSequence.new(1).to_a).to eq ['1/1'.to_r]
    end

    it 'can calculate sequences of rational numbers, with length > 1' do
      expect(RationalSequence.new(4).to_a).to eq %w(1/1, 2/1, 1/2, 1/3).map(&:to_r)

      expect(RationalSequence.new(10).to_a).
        to eq %w(1/1, 2/1, 1/2, 1/3, 3/1, 4/1, 3/2, 2/3, 1/4, 1/5).map(&:to_r)

      expect(RationalSequence.new(20).to_a).
        to eq %w(1/1, 2/1, 1/2, 1/3, 3/1, 4/1, 3/2, 2/3, 1/4, 1/5,
                5/1, 6/1, 5/2, 4/3, 3/4, 2/5, 1/6, 1/7, 3/5, 5/3).map(&:to_r)
    end
  end

  describe FibonacciSequence do
    it 'should return the empty set when initialized with 0' do
      expect(FibonacciSequence.new(0).to_a).to eq []
    end

    it 'can calculate the first Fibonacci number' do
      expect(FibonacciSequence.new(1).to_a).to eq [1]
    end

    it 'can calculate the first 5 Fibonacci numbers' do
      expect(FibonacciSequence.new(5).to_a).to eq [1, 1, 2, 3, 5]
    end

    it 'can calculate the first 5 Fibonacci numbers starting from 0' do
      expect(FibonacciSequence.new(5, first: 0, second: 1).to_a).to eq [0, 1, 1, 2, 3]
    end
  end

  describe PrimeSequence do
    it 'should return the empty set when initialized with 0' do
      expect(PrimeSequence.new(0).to_a).to eq []
    end

    it 'can calculate the first prime (and it is not Optimus)' do
      expect(PrimeSequence.new(1).to_a).to eq [2]
    end

    it 'can calculate the first 5 prime numbers' do
      expect(PrimeSequence.new(5).to_a).to eq [2, 3, 5, 7, 11]
    end
  end

  describe DrunkenMathematician do
    describe '#meaningless' do
      it 'can calculate for 0' do
        expect(DrunkenMathematician.meaningless(0)).to eq 1
      end

      it 'can calculate for 1' do
        expect(DrunkenMathematician.meaningless(1)).to eq Rational(1, 1)
      end

      it 'can calculate for 6' do
        expect(DrunkenMathematician.meaningless(6)).to eq Rational(1, 4)
      end
    end

    describe '#aimless' do
      it 'can calculate for 0' do
        expect(DrunkenMathematician.aimless(0)).to eq 0
      end

      it 'can calculate for 2' do
        expect(DrunkenMathematician.aimless(2)).to eq '2/3'.to_r
      end

      it 'can calculate for 4' do
        expect(DrunkenMathematician.aimless(4)).to eq '29/21'.to_r
      end

      it 'can calculate for 5' do
        expect(DrunkenMathematician.aimless(5)).to eq '260/21'.to_r
      end
    end

    describe '#worthless' do
      it 'can calculate for 0' do
        expect(DrunkenMathematician.worthless(0)).to eq []
      end

      it 'can calculate for 1' do
        expect(DrunkenMathematician.worthless(1)).to eq %w(1/1).map(&:to_r)
      end

      it 'can calculate for 5' do
        expect(DrunkenMathematician.worthless(5)).to eq %w(1/1, 2/1, 1/2, 1/3).map(&:to_r)
      end
    end
  end
end


text:
namespace RampUp.Buffers
{
    /// <summary>
    /// A common denominator for <see cref="byte"/> array and <see cref="ByteChunk"/>.
    /// </summary>
    internal unsafe struct ByteSlice
    {
        private readonly byte[] _buffer;
        private readonly int _offset;
        public readonly int Count;
        private readonly byte* _chunk;

        public ByteSlice(byte[] buffer, int offset, int count)
        {
            _buffer = buffer;
            _offset = offset;
            Count = count;
            _chunk = null;
        }

        public ByteSlice(ByteChunk chunk)
        {
            _chunk = chunk.Pointer;
            _offset = 0;
            Count = chunk.Length;
            _buffer = null;
        }

        public void CopyFrom(int alreadyCopied, byte* segmentBuffer, int indexInSegment, int bytesToRead)
        {
            if (_buffer != null)
            {
                Native.MemcpyFromUnmanaged(_buffer, _offset + alreadyCopied, segmentBuffer, indexInSegment, bytesToRead);
            }
            else
            {
                Native.MemcpyUnmanaged(_chunk, segmentBuffer + indexInSegment, bytesToRead);
            }
        }

        public void CopyTo(byte* segmentBuffer, int currentSegmentIndex, int spaceToWrite, int additionalOffset)
        {
            if (_buffer != null)
            {
                Native.MemcpyToUnmanaged(segmentBuffer, currentSegmentIndex, _buffer, _offset + additionalOffset,
                    spaceToWrite);
            }
            else
            {
                Native.MemcpyUnmanaged(segmentBuffer + currentSegmentIndex, _chunk + additionalOffset, spaceToWrite);
            }
        }
    }
}


text:
use std::io::prelude::*;
use std::process::{
    Command,
    Stdio,
    Child,
};

use util::{
    Error,
    Result,
};

const AMIXER: &'static str = "amixer";
const FLAGS: &'static [&'static str] = &["-M"];
const SET: &'static str = "sset";
const GET: &'static str = "sget";
const DEVICE: &'static str = "DAC1";

pub fn set(val: u8) -> Result<u8> {
    let mut cmd = Command::new(AMIXER);
    cmd.arg(SET).args(FLAGS).arg(DEVICE).arg(format!("{}%", val));
    cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());

    let mut child = try!(cmd.spawn());
    let status = try!(child.wait());

    if !status.success() {
        let mut err = Error::new("failed to set sound level");
        if let Some(mut err_pipe) = child.stderr {
            let mut err_str = String::new();
            try!(err_pipe.read_to_string(&mut err_str));
            err.add_detail(&err_str);
            Err(err)
        } else {
            Err(err)
        }
    } else {
        if let Some(mut out_pipe) = child.stdout {
            let mut out_str = String::new();
            try!(out_pipe.read_to_string(&mut out_str));
            let val = try!(extract_volume(&out_str));
            Ok(val)
        } else {
            Err(Error::new("failed to get new sound level"))
        }
    }
}

pub fn get() -> Result<u8> {
    let mut cmd = Command::new(AMIXER);
    cmd.arg(GET).args(FLAGS).arg(DEVICE);
    cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());

    let mut child = try!(cmd.spawn());
    let status = try!(child.wait());

    if !status.success() {
        let mut err = Error::new("failed to get sound level");
        if let Some(mut err_pipe) = child.stderr {
            let mut err_str = String::new();
            try!(err_pipe.read_to_string(&mut err_str));
            err.add_detail(&err_str);
            Err(err)
        } else {
            Err(err)
        }
    } else {
        if let Some(mut out_pipe) = child.stdout {
            let mut out_str = String::new();
            try!(out_pipe.read_to_string(&mut out_str));
            let val = try!(extract_volume(&out_str));
            Ok(val)
        } else {
            Err(Error::new("failed to get sound level"))
        }
    }
}

fn extract_volume(string: &str) -> Result<u8> {
    let strval: String = string.chars()
                    .skip_while(|&c| c != '[').skip(1)
                    .take_while(|&c| c != '%')
                    .collect();
    if strval.is_empty() {
        Err(Error::new("failed to find sound level"))
    } else {
        let numval: u8 = try!(strval.parse());
        Ok(numval)
    }
}

pub fn increase(val: u8) -> Result<()> {
    unimplemented!();
}

pub fn decrease(val: u8) -> Result<()> {
    unimplemented!();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright 2005-2007 Open Source Applications Foundation Licensed under
	the Apache License, Version 2.0 (the "License"); you may not use this file
	except in compliance with the License. You may obtain a copy of the License
	at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
	law or agreed to in writing, software distributed under the License is distributed
	on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
	express or implied. See the License for the specific language governing permissions
	and limitations under the License. -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<parent>
		<groupId>net.oneandone.cosmo</groupId>
		<artifactId>cosmo-multimodule</artifactId>
		<version>3.7.10-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>
	<artifactId>cosmo-core</artifactId>

	<properties>
		<maven-compiler-plugin.version>2.3.2</maven-compiler-plugin.version>
		<maven-resources-plugin.version>2.5</maven-resources-plugin.version>
		<maven-eclipse-plugin.version>2.8</maven-eclipse-plugin.version>
		<maven-clean-plugin.version>2.1.1</maven-clean-plugin.version>
		<maven-war-plugin.version>2.2</maven-war-plugin.version>
		<maven-assembly-plugin.version>2.2.2</maven-assembly-plugin.version>
		<maven-pmd-plugin.failOnViolation>false</maven-pmd-plugin.failOnViolation>

	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>net.oneandone.cosmo</groupId>
			<artifactId>cosmo-api</artifactId>
			<version>${project.version}</version>
		</dependency>

		<!-- Apache commons -->
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
		</dependency>

		<!-- XML processing -->
		<dependency>
			<groupId>xerces</groupId>
			<artifactId>xercesImpl</artifactId>
		</dependency>
		<!-- <dependency>
			<groupId>org.reflections</groupId>
			<artifactId>reflections</artifactId>
		</dependency> -->
		<!-- Databases -->
		<dependency>
			<groupId>org.mariadb.jdbc</groupId>
			<artifactId>mariadb-java-client</artifactId>
		</dependency>

		<dependency>
				<groupId>ch.vorburger.mariaDB4j</groupId>
				<artifactId>mariaDB4j-core</artifactId>
				<scope>test</scope>
		</dependency>
		<dependency>
				<groupId>ch.vorburger.mariaDB4j</groupId>
				<artifactId>mariaDB4j-app</artifactId>
				<scope>test</scope>
		</dependency>

		<!-- abdera is the ATOM implementation. This library is still used for
			parsing eTags. -->
		<dependency>
			<groupId>org.apache.abdera</groupId>
			<artifactId>abdera-core</artifactId>
			<exclusions>
				<exclusion>
					<groupId>commons-codec</groupId>
					<artifactId>commons-codec</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.apache.abdera</groupId>
			<artifactId>abdera-i18n</artifactId>
			<exclusions>
				<exclusion>
					<groupId>commons-codec</groupId>
					<artifactId>commons-codec</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- ical4j related libs -->
		<dependency>
			<groupId>net.oneandone.ical4j</groupId>
			<artifactId>ical4j</artifactId>
			<exclusions>
				<exclusion>
					<groupId>commons-codec</groupId>
					<artifactId>commons-codec</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.apache.jackrabbit</groupId>
			<artifactId>jackrabbit-webdav</artifactId>
			<exclusions>
                <exclusion>
                    <groupId>commons-codec</groupId>
                    <artifactId>commons-codec</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>jcl-over-slf4j</artifactId>
                </exclusion>
            </exclusions>
		</dependency>

		<!-- Spring -->

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-beans</artifactId>
				</exclusion>
				<exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-beans</artifactId>
				</exclusion>
				<exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
			</exclusions>
		</dependency>
		<!-- used in applicationContext xmlns:security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
            </exclusions>
		</dependency>

		<!-- aspectj -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
		</dependency>

		<dependency>
			<groupId>org.hibernate.validator</groupId>
			<artifactId>hibernate-validator</artifactId>
		</dependency>

		<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
		</dependency>

		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
	</dependencies>

	<build>
		<testSourceDirectory>src/test/unit/java</testSourceDirectory>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<directory>src/test/unit/resources</directory>
				<includes>
					<include>logback.xml</include>
					<include>etc/cosmo.properties</include>
					<include>applicationContext-*.xml</include>
					<include>application-*.yaml</include>
				</includes>
			</testResource>
			<testResource>
				<directory>src/test/unit/resources/dav/caldav</directory>
				<includes>
					<include>*.ics</include>
				</includes>
			</testResource>
			<testResource>
				<directory>src/test/unit/resources/icalendar</directory>
				<includes>
					<include>*.ics</include>
				</includes>
			</testResource>
			<testResource>
				<directory>src/test/unit/resources/testdata</directory>
			</testResource>
		</testResources>

	</build>
</project>


text:
<?php

/** Zend_Form_Decorator_ViewHelper */
// require_once 'Zend/Form/Decorator/ViewHelper.php';

/**
 * Zend_Dojo_Form_Decorator_DijitElement
 *
 * Render a dojo dijit element via a view helper
 *
 * Accepts the following options:
 * - separator: string with which to separate passed in content and generated content
 * - placement: whether to append or prepend the generated content to the passed in content
 * - helper:    the name of the view helper to use
 *
 * Assumes the view helper accepts three parameters, the name, value, and
 * optional attributes; these will be provided by the element.
 *
 * @package    Zend_Dojo
 * @subpackage Form_Decorator
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Zend_Dojo_Form_Decorator_DijitElement extends Zend_Form_Decorator_ViewHelper
{
    /**
     * Element attributes
     * @var array
     */
    protected $_attribs;

    /**
     * Element types that represent buttons
     * @var array
     */
    protected $_buttonTypes = array(
        'Zend_Dojo_Form_Element_Button',
        'Zend_Form_Element_Button',
        'Zend_Form_Element_Reset',
        'Zend_Form_Element_Submit',
    );

    /**
     * Dijit option parameters
     * @var array
     */
    protected $_dijitParams = array();

    /**
     * Get element attributes
     *
     * @return array
     */
    public function getElementAttribs()
    {
        if (null === $this->_attribs) {
            $this->_attribs = parent::getElementAttribs();
            if (array_key_exists('dijitParams', $this->_attribs)) {
                $this->setDijitParams($this->_attribs['dijitParams']);
                unset($this->_attribs['dijitParams']);
            }
        }

        return $this->_attribs;
    }

    /**
     * Set a single dijit option parameter
     *
     * @param  string $key
     * @param  mixed $value
     * @return Zend_Dojo_Form_Decorator_DijitContainer
     */
    public function setDijitParam($key, $value)
    {
        $this->_dijitParams[(string) $key] = $value;
        return $this;
    }

    /**
     * Set dijit option parameters
     *
     * @param  array $params
     * @return Zend_Dojo_Form_Decorator_DijitContainer
     */
    public function setDijitParams(array $params)
    {
        $this->_dijitParams = array_merge($this->_dijitParams, $params);
        return $this;
    }

    /**
     * Retrieve a single dijit option parameter
     *
     * @param  string $key
     * @return mixed|null
     */
    public function getDijitParam($key)
    {
        $this->getElementAttribs();
        $key = (string) $key;
        if (array_key_exists($key, $this->_dijitParams)) {
            return $this->_dijitParams[$key];
        }

        return null;
    }

    /**
     * Get dijit option parameters
     *
     * @return array
     */
    public function getDijitParams()
    {
        $this->getElementAttribs();
        return $this->_dijitParams;
    }

    /**
     * Render an element using a view helper
     *
     * Determine view helper from 'helper' option, or, if none set, from
     * the element type. Then call as
     * helper($element->getName(), $element->getValue(), $element->getAttribs())
     *
     * @param  string $content
     * @return string
     * @throws Zend_Form_Decorator_Exception if element or view are not registered
     */
    public function render($content)
    {
        $element = $this->getElement();
        $view = $element->getView();
        if (null === $view) {
            // require_once 'Zend/Form/Decorator/Exception.php';
            throw new Zend_Form_Decorator_Exception('DijitElement decorator cannot render without a registered view object');
        }

        $options = null;
        $helper    = $this->getHelper();
        $separator = $this->getSeparator();
        $value     = $this->getValue($element);
        $attribs   = $this->getElementAttribs();
        $name      = $element->getFullyQualifiedName();

        $dijitParams = $this->getDijitParams();
        $dijitParams['required'] = $element->isRequired();

        $id = $element->getId();
        if ($view->dojo()->hasDijit($id)) {
            trigger_error(sprintf('Duplicate dijit ID detected for id "%s; temporarily generating uniqid"', $id), E_USER_NOTICE);
            $base = $id;
            do {
                $id = $base . '-' . uniqid();
            } while ($view->dojo()->hasDijit($id));
        }
        $attribs['id'] = $id;

        if (array_key_exists('options', $attribs)) {
               $options = $attribs['options'];
        }

        $elementContent = $view->$helper($name, $value, $dijitParams, $attribs, $options);
        switch ($this->getPlacement()) {
            case self::APPEND:
                return $content . $separator . $elementContent;
            case self::PREPEND:
                return $elementContent . $separator . $content;
            default:
                return $elementContent;
        }
    }
}


text:
package de.katzenpapst.amunra.block;

import net.minecraft.world.World;

/**
 * Interface for blocks to return a mass
 * @author katzenpapst
 *
 */
public interface IMassiveBlock {
    float getMass(World w, int x, int y, int z, int meta);
}


text:
import AnimeNotifier from "../AnimeNotifier"
import plural from "../Utils/plural"
import ServerEvent from "./ServerEvent"

const reconnectDelay = 3000

let supported: boolean
let eventSource: EventSource
let arn: AnimeNotifier
let etags: Map<string, string>

export default function receiveServerEvents(animeNotifier: AnimeNotifier) {
	supported = ("EventSource" in window)

	if(!supported) {
		return
	}

	arn = animeNotifier
	etags = new Map<string, string>()
	connect()
}

function connect() {
	if(eventSource) {
		eventSource.close()
	}

	eventSource = new EventSource("/api/sse/events", {
		withCredentials: true
	})

	eventSource.addEventListener("ping", (e: any) => ping(e))
	eventSource.addEventListener("etag", (e: any) => etag(e))
	eventSource.addEventListener("post activity", (e: any) => activity(e, "post"))
	eventSource.addEventListener("watch activity", (e: any) => activity(e, "watch"))
	eventSource.addEventListener("notificationCount", (e: any) => notificationCount(e))

	eventSource.onerror = () => {
		setTimeout(() => connect(), reconnectDelay)
	}
}

function ping(_: ServerEvent) {
	console.log("ping")
}

function etag(e: ServerEvent) {
	const data = JSON.parse(e.data)
	const oldETag = etags.get(data.url)
	const newETag = data.etag

	if(oldETag && newETag && oldETag !== newETag) {
		arn.statusMessage.showInfo("A new version of the website is available. Please refresh the page.", -1)
	}

	etags.set(data.url, newETag)
}

function activity(e: ServerEvent, activityType: string) {
	if(activityType === "post" && !location.pathname.endsWith("/activity")) {
		return
	}

	if(activityType === "watch" && !location.pathname.endsWith("/activity/watch")) {
		return
	}

	const showFollowedOnlyButton = document.getElementById("Activity.ShowFollowedOnly")

	if(!showFollowedOnlyButton) {
		return
	}

	const showFollowedOnly = (showFollowedOnlyButton.dataset.action === "disable")
	const isFollowingUser = JSON.parse(e.data)

	// If we're on the followed only feed and we receive an activity
	// about a user we don't follow, ignore the message.
	if(showFollowedOnly && !isFollowingUser) {
		return
	}

	const button = document.getElementById("load-new-activities")

	if(!button || !button.dataset.count) {
		return
	}

	const buttonText = document.getElementById("load-new-activities-text")

	if(!buttonText) {
		return
	}

	const newCount = parseInt(button.dataset.count, 10) + 1
	button.dataset.count = newCount.toString()
	buttonText.textContent = plural(newCount, "new activity")
}

function notificationCount(e: ServerEvent) {
	if(!arn.notificationManager) {
		return
	}

	arn.notificationManager.setCounter(parseInt(e.data, 10))
}


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

import javax.annotation.Generated;

/**
 * <p>
 * Cannot restore from VPC backup to non-VPC DB instance.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidRestoreException extends com.amazonaws.services.rds.model.AmazonRDSException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InvalidRestoreException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InvalidRestoreException(String message) {
        super(message);
    }

}


text:
#include "ocisession.h"
#include <algorithm>

#include "oci_lib_intf.h"

#include <oci.h>

void * ocisession::envhp = NULL;
list<ocisession*> ocisession::_sessions;

ocisession::ocisession(const char * connect_str, const int connect_str_len,
					   const char * user_name, const int user_name_len,
					   const char * password, const int password_len)
{
	intf_ret r;
	OCIAuthInfo *authp = NULL;

	init();

	r.handle = envhp;

	// allocate error handle
	checkenv(&r, OCIHandleAlloc((OCIEnv*)envhp,	/* environment handle */
                            (void **) &_errhp,	/* returned err handle */
                            OCI_HTYPE_ERROR,	/* typ of handle to allocate */
                            (size_t) 0,			/* optional extra memory size */
                            (void **) NULL));	/* returned extra memeory */

	if(r.fn_ret != SUCCESS) {
   		REMOTE_LOG("failed OCISessionGet %s\n", r.gerrbuf);
        throw r;
	}

	// allocate auth handle
	checkenv(&r, OCIHandleAlloc((OCIEnv*)envhp,
							(void**)&authp, OCI_HTYPE_AUTHINFO,
							(size_t)0, (void **) NULL));

	r.handle = _errhp;

	// usrname and password
	checkerr(&r, OCIAttrSet(authp, OCI_HTYPE_AUTHINFO,
								(void*) user_name, user_name_len,
								OCI_ATTR_USERNAME, (OCIError *)_errhp));
	checkerr(&r, OCIAttrSet(authp, OCI_HTYPE_AUTHINFO,
								(void*) password, password_len,
								OCI_ATTR_PASSWORD, (OCIError *)_errhp));

    /* get the database connection */
    checkerr(&r, OCISessionGet((OCIEnv*)envhp, (OCIError *)_errhp,
                               (OCISvcCtx**)&_svchp,					/* returned database connection */
                               authp,									/* initialized authentication handle */
                               (OraText *) connect_str, connect_str_len,/* connect string */
                               NULL, 0, NULL, NULL, NULL,				/* session tagging parameters: optional */
                               OCI_DEFAULT));					/* modes */
	if(r.fn_ret != SUCCESS) {
		REMOTE_LOG("failed OCISessionGet %s\n", r.gerrbuf);
        throw r;
	}

	(void) OCIHandleFree(authp, OCI_HTYPE_AUTHINFO);

	REMOTE_LOG("got session %p %.*s user %.*s\n", _svchp, connect_str_len, connect_str, user_name_len, user_name);

	_sessions.push_back(this);
}

ocistmt* ocisession::prepare_stmt(OraText *stmt, ub4 stmt_len)
{
	ocistmt * statement = new ocistmt(this, stmt, stmt_len);
	_statements.push_back(statement);
	return statement;
}

void ocisession::release_stmt(ocistmt *stmt)
{
	list<ocistmt*>::iterator it = std::find(_statements.begin(), _statements.end(), stmt);
	if (it != _statements.end()) {
		_statements.remove(*it);
	}
}

ocisession::~ocisession(void)
{
	intf_ret r;

	// delete all the statements
	for (list<ocistmt*>::const_iterator it = _statements.begin(); it != _statements.end(); it++)
		(*it)->close();
	_statements.clear();

	checkerr(&r, OCISessionRelease((OCISvcCtx*)_svchp, (OCIError*)_errhp, NULL, 0, OCI_DEFAULT));
	if(r.fn_ret != SUCCESS) {
		REMOTE_LOG("failed OCISessionRelease %s\n", r.gerrbuf);
        throw r;
	}

	(void) OCIHandleFree(_errhp, OCI_HTYPE_ERROR);

	// cleanup the environment if this is the last oci session from this environment
	_sessions.remove(this);

	//REMOTE_LOG("release session %p\n", _svchp);
}

void ocisession::init(void)
{
	intf_ret r;
 	r.fn_ret = SUCCESS;

	if(envhp == NULL) {
		sword ret = 0;
		ret = OCIEnvCreate((OCIEnv**)&envhp,		/* returned env handle */
						   OCI_THREADED,			/* initilization modes */
						   NULL, NULL, NULL, NULL,	/* callbacks, context */
						   (size_t) 0,				/* optional extra memory size: optional */
						   (void**) NULL);			/* returned extra memeory */

		r.handle = envhp;
		checkenv(&r, ret);
		if(r.fn_ret != SUCCESS)
        throw r;
	}
}


text:
		<fieldset id="menuItems">
			<button class="menuItem"/>
		</fieldset>


text:
var game = {
  monsters: ['mummy', 'revenant', 'ghost', 'skeleton', 'spectre', 'zombie', 'wraith', 'lich', 'necrolord', 'necrogod'],

  init: function(){
    if (!store.enabled) {
          alert('Local storage is not supported by your browser. Please disable "Private Mode", or upgrade to a modern browser.')
          return
    }

    character.init();

    $("#seed").val((""+Math.random()).substring(2,8));

    $('#submit').on('click', function() {
      var seed = $('#seed').val();
      if (seed == '') { return false }
      else { game.processTurn(seed) }
    });

    $('#new_game').on('click', function(){
      character.new();
    });

    console.log('Game initialized');
  },

  processTurn: function(seed){
    var log = [];

    if (character.isDead()){
      log.push('Player is dead. Please start a new game.');
      game.printTurn(log);
      return;
    }

    var seed = seed.split('');
    var data = {
                 mob:         parseInt(seed[0]),
                 mob_attack:  parseInt(seed[1]),
                 hero_attack: parseInt(seed[2]),
                 damage:      parseInt(seed[3]),
                 coins:       parseInt(seed[4])
               };

    // define monster
    log.push('A ' + game.monsters[data.mob] + ' appears!');

    // attack!
    if (data.hero_attack > data.mob_attack) {
      log.push('Player hits the ' + game.monsters[data.mob] + ' causing ' + data.damage +' damage points.');
      log.push(game.monsters[data.mob].capitalize() + ' dies.');

      // calculate XP
      xp = (data.hero_attack - data.mob_attack) * 2;
      character.update('xp', xp, '+');
      log.push('Earned ' + xp + ' experience points.');

      // loot
      character.update('coins', data.coins, '+');
      log.push('Looted ' + data.coins + ' coins.');
    }
    else {
      // if damage is zero, deal one point of damage
      if (data.damage == 0) { data.damage = 1; };

      log.push('The ' + game.monsters[data.mob] + ' hits the player, hiding in the darkness after it.')
      log.push(data.damage + ' points of damage taken.');

      character.update('hp', data.damage, '-');

      if (character.isDead()) { log.push('Game over.') };
    }
    // print output
    game.printTurn(log);
    $('document').focus();
  },

  printTurn: function(log){
    $('#turn_log').html(log.join('<br/>'));
    $('#turn_log').show();
    $("#seed").val((""+Math.random()).substring(2,8));
  }
}

var character = {
  init: function(){
    if (store.get('character') === undefined) {
      character.new();
    } else {
      console.log('character loaded');
      character.stats = store.get('character');
      character.updateDisplay();
    }
  },

  update: function(stat, number, operation){
    if (operation == '+')      { character.stats[stat] += number }
    else if (operation == '-') { character.stats[stat] = character.stats[stat] - number };

    $('#'+stat).text(character.stats[stat]);

    store.set('character', character.stats);
  },

  new: function(){
    character.stats = store.set('character', { hp: 50, lv: 1, coins:0, xp: 0, to_level: 100 });
    character.updateDisplay();
    $('#turn_log').hide();
  },

  updateDisplay: function(){
    $('#hp').text(character.stats.hp)
    $('#lv').text(character.stats.lv)
    $('#coins').text(character.stats.coins)
    $('#xp').text(character.stats.xp)
    $('#to_level').text(character.stats.to_level)
  },

  isDead: function(){
    return (character.stats.hp < 0);
  }
}


text:
package me.rafaskb.ticketmaster.models;

import java.util.Comparator;

public class SimpleTicketComparator implements Comparator<SimpleTicket> {

	@Override
	public int compare(SimpleTicket t1, SimpleTicket t2) {
		int compareNull = compareNull(t1, t2);
		if(compareNull != 0)
			return compareNull;

		int comparePriority = comparePriority(t1.getPriority(), t2.getPriority());
		if(comparePriority != 0)
			return comparePriority;

		int compareStatus = compareStatus(t1.getStatus(), t2.getStatus());
		if(compareStatus != 0)
			return compareStatus;

		int compareDate = compareDate(t1.getDate(), t2.getDate());
		return compareDate;
	}

	private int compareNull(SimpleTicket t1, SimpleTicket t2) {
		if(t1 != null && t2 == null) return -1;
		if(t1 == null && t2 != null) return 1;
		return 0;
	}

	private int comparePriority(TicketPriority p1, TicketPriority p2) {
		return -p1.compareTo(p2);
	}

	private int compareStatus(TicketStatus s1, TicketStatus s2) {
		return s1.compareTo(s2);
	}

	private int compareDate(long d1, long d2) {
		if(d1 > d2) return -1;
		if(d1 < d2) return 1;
		return 0;
	}

}


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
    <menu>
        <add id="Magento_Paypal::report_salesroot_paypal_settlement_reports" title="PayPal Settlement" module="Magento_Paypal" sortOrder="70" parent="Magento_Reports::report_salesroot" action="paypal/paypal_reports" resource="Magento_Paypal::paypal_settlement_reports"/>
        <add id="Magento_Paypal::paypal_billing_agreement" title="Billing Agreements" module="Magento_Paypal" sortOrder="60" parent="Magento_Sales::sales_operation" action="paypal/billing_agreement" resource="Magento_Paypal::billing_agreement"/>
    </menu>
</config>


text:
class DeeplyAssociatedRecord < ActiveRecord::Base
  include IdentityCache
  belongs_to :item
  belongs_to :associated_record
  default_scope { order("name DESC") }
end

class AssociatedRecord < ActiveRecord::Base
  belongs_to :item, inverse_of: :associated_records
  belongs_to :item_two, inverse_of: :associated_records
  has_many :related_items, as: :owner, inverse_of: :owner
  has_many :deeply_associated_records
  has_one :deeply_associated, class_name: "DeeplyAssociatedRecord"
  default_scope { order("id DESC") }
end

class NormalizedAssociatedRecord < ActiveRecord::Base
  include IdentityCache
  belongs_to :item
  default_scope { order("id DESC") }
end

class NotCachedRecord < ActiveRecord::Base
  belongs_to :item, touch: true
  default_scope { order("id DESC") }
end

class PolymorphicRecord < ActiveRecord::Base
  belongs_to :owner, polymorphic: true
end

class NoInverseOfRecord < ActiveRecord::Base
  include IdentityCache
  belongs_to :owner
end

module Deeply
  module Nested
    class AssociatedRecord < ActiveRecord::Base
      include IdentityCache
    end
  end
end

class RelatedItem < ActiveRecord::Base
  include IdentityCache
  belongs_to :owner, polymorphic: true
  belongs_to :item
end

class Item < ActiveRecord::Base
  include IdentityCache
  belongs_to :item
  has_many :associated_records, inverse_of: :item
  has_many :deeply_associated_records, inverse_of: :item
  has_many :normalized_associated_records
  has_many :not_cached_records
  has_many :polymorphic_records, as: "owner", inverse_of: :owner
  has_many :no_inverse_of_records
  has_one :polymorphic_record, as: "owner"
  has_one :associated, class_name: "AssociatedRecord"
  has_one :no_inverse_of_record
  has_one :related_item
end

class ItemTwo < ActiveRecord::Base
  include IdentityCache
  has_many :associated_records, inverse_of: :item_two, foreign_key: :item_two_id
  has_many :polymorphic_records, as: "owner", inverse_of: :owner
  self.table_name = "items2"
end

class KeyedRecord < ActiveRecord::Base
  include IdentityCache
  self.primary_key = "hashed_key"
end

class StiRecord < ActiveRecord::Base
  include IdentityCache
  has_many :polymorphic_records, as: "owner", inverse_of: :owner
end

class StiRecordTypeA < StiRecord
end

class CustomParentRecord < ActiveRecord::Base
  include IdentityCache
  has_many :custom_child_record, foreign_key: :parent_id
  self.primary_key = "parent_primary_key"
end

class CustomChildRecord < ActiveRecord::Base
  include IdentityCache
  belongs_to :custom_parent_record, foreign_key: :parent_id
  self.primary_key = "child_primary_key"
end


text:
<!DOCTYPE html>

	<title>Robot Sneaker NPCs</title>

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

		Robot Sneaker NPCs

View All NPCs

Create an NPC

Create an NPC

{{ HTML::ul($errors->all()) }}
{{ Form::open(array('url' => 'npcs')) }}

	{{ Form::label('name', 'Name') }}
	{{ Form::text('name', Input::old('name'), array('class'=>'form-control')) }}

	{{ Form::label('energy', 'Energy') }}
	{{Form::number('energy',Input::old('energy'),array('class'=>'form-control'))}}

	{{ Form::label('attack', 'Attack') }}
	{{Form::number('attack',Input::old('attack'),array('class'=>'form-control'))}}

	{{ Form::label('hp', 'HP') }}
	{{Form::number('hp',Input::old('hp'),array('class'=>'form-control'))}}

	{{ Form::label('description', 'Description') }}
	{{Form::text('description',Input::old('description'),array('class'=>'form-control'))}}

	{{ Form::submit('Create the NPC', array('class'=>'btn btn-primary')) }}
{{ Form::close() }}


text:
namespace TravelShare.Web.Areas.Administration.Models.NewsManagement
{
    using System.ComponentModel.DataAnnotations;
    using TravelShare.Data.Models;
    using TravelShare.Web.Mappings;

    public class NewCreateViewModel : IMapFrom<News>
    {
        [Required]
        [StringLength(25, ErrorMessage = "Title must be between 5 and 25", MinimumLength = 5)]
        public string Title { get; set; }

        [Required]
        [StringLength(255, ErrorMessage ="Content must be between 10 and 255", MinimumLength = 10)]
        public string Content { get; set; }
    }
}


text:
<?php

    extract($_POST);
    conectar();

    // consulta para que no se repitan las personas por numero de cedula
    $sql=mysql_query("SELECT * FROM persona WHERE cedula ='$cedula' OR email = '$email' ");

    if (mysql_num_rows($sql)>0) {
        echo "
La persona ya se encuentra registrada!
";
    }else{
        $insertar=mysql_query("INSERT INTO persona (cedula,nombre,apellido,email,telefono,genero,carrera_id) VALUES ('$cedula','$nombre','$apellido','$email','$telefono','$genero','$carrera')");

        if (mysql_affected_rows($insertar) > 0){
            echo "
No se pudieron guardar los datos!
";
        }
        else{
            echo "
Se han guardado los datos exitosamente!
";
        }

    }
    desconectar();

?>

            <button type="button" class="button button-secondary" onclick="window.history.back();">Agregar </button>
            Inicio


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;

using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

using Microsoft.Band.Portable;
using Microsoft.Band.Portable.Notifications;
using Microsoft.Band.Portable.Personalization;
using Microsoft.Band.Portable.Sensors;
using Microsoft.Band.Portable.Tiles;
using BandException = Microsoft.Band.BandException;
using Windows.UI.Xaml.Media.Imaging;

namespace FlightBand.Phone
{
    public sealed partial class MainPage : Page
    {
        private readonly FlightBandConnection bandConnection;
        private readonly FlightBandGame game;

        private readonly List<Image> enemies;
        private readonly List<Image> bullets;
        private Image player;

        public MainPage()
        {
            InitializeComponent();

            NavigationCacheMode = NavigationCacheMode.Required;

            bandConnection = new FlightBandConnection();
            game = new FlightBandGame(bandConnection);

            enemies = new List<Image>();
            bullets = new List<Image>();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            CompositionTarget.Rendering += OnRenderFrame;

            base.OnNavigatedTo(e);

            var manager = BandClientManager.Instance;
            var pairedBands = await manager.GetPairedBandsAsync();
            var bandInfo = pairedBands.FirstOrDefault();
            if (bandInfo != null)
            {
                await bandConnection.SetBandAsync(bandInfo);
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            CompositionTarget.Rendering -= OnRenderFrame;

            base.OnNavigatedFrom(e);
        }

        private void OnRenderFrame(object sender, object e)
        {
            // update frame

            var count = 0;
            var fps = game.Update();
            fpsTextBlock.Text = string.Format("FPS: {0:0.0}", fps);

            // update visual elements

            // the player
            if (game.Player != null)
            {
                if (player == null)
                {
                    player = new Image { Source = playerSprite.Source };
                    canvas.Children.Add(player);
                }

                velocityTextBlock.Text = string.Format(
                    "{0:0.00}, {1:0.00}",
                    game.Player.HorizontalVelocity.Velocity,
                    game.Player.ForwardVelocity.Velocity);

                MoveObject(player, game.Player);
            }

            // the enemies
            count = game.Enemies.Length;
            CreateElements(count, enemies, enemySprite.Source);
            for (int i = 0; i < count; i++)
            {
                MoveObject(enemies[i], game.Enemies[i]);
            }

            // the bullets
            count = game.Bullets.Length;
            CreateElements(count, bullets, enemySprite.Source);
            for (int i = 0; i < count; i++)
            {
                MoveObject(bullets[i], game.Bullets[i]);
            }
        }

        private void CreateElements(int count, List<Image> elements, ImageSource sprite)
        {
            while (count > elements.Count)
            {
                var enemy = new Image { Source = sprite };
                elements.Add(enemy);
                canvas.Children.Add(enemy);
            }
            while (count < elements.Count)
            {
                var enemy = elements[elements.Count - 1];
                elements.Remove(enemy);
                canvas.Children.Remove(enemy);
            }
        }

        private void MoveObject(Image sprite, FlightBandMovingObject movingObject)
        {
            Canvas.SetLeft(sprite, movingObject.X);
            Canvas.SetTop(sprite, movingObject.Y);
            sprite.Width = movingObject.Width;
            sprite.Height = movingObject.Height;
        }

        private void OnCanvasSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (game != null)
            {
                game.ViewportWidth = e.NewSize.Width;
                game.ViewportHeight = e.NewSize.Height;
                game.PlaneScale = Math.Min(e.NewSize.Width, e.NewSize.Height) / 5.0;
                game.BulletScale = game.PlaneScale / 5.0;
            }
        }

        private void OnPlayButtonClicked(object sender, RoutedEventArgs e)
        {
            if (game != null)
            {
                game.Start();

                menu.Visibility = Visibility.Collapsed;
                canvas.Visibility = Visibility.Visible;
            }
        }
    }
}


text:
Setup python virtual environment and install development dependencies

```bash
# Setup virtual environment
python3 -m venv venv
source venv/bin/activate

# Regenerate requirement files
pip-compile --extra=dev --generate-hashes --output-file=dev-requirements.txt pyproject.toml
pip-compile --generate-hashes --output-file=requirements.txt pyproject.toml

# Install dependencies
pip-sync
pip-sync dev-requirements.txt

# Build package
python -m build

# Install locally
pip install -e .

# Check pre-commit gates
pre-commit run --all-files

# Create test coverage
coverage run -m pytest && coverage report -m
coverage run -m pytest && coverage html

# Format code
black --line-length=120 .

# Run unit tests
pytest

# Static type checker
mypy
```

## molecule

[molecule](https://molecule.readthedocs.io/en/latest/) is used for testing Ansible roles

- `molecule` provides support for testing with multiple instances, operating systems and distributions, virtualization
  providers, test frameworks and testing scenarios.
- `molecule` encourages an approach that results in consistently developed roles that are well-written, easily
  understood and maintained.
- `molecule` is already part of the virtual environment installation.

Example execute molecule for all roles

```bash
./scripts/test-roles.sh
```

or use molecule for single roles

```bash
# Execute molecule on a single role
cd roles/<role>
molecule test
# Run some parts of the test sequence with debug output
molecule --debug test
# Run some parts of the test sequence
molecule converge
# If nothing works anymore, try to destroy running stuff
molecule destroy
```

## pre-commit

[pre-commit](https://pre-commit.com/) is used for several formatters and linters

Example execute pre-commit on all files

```bash
pre-commit run --all-files
```

But it's recommended to install the automatic git pre-commit hook by `pre-commit install`


text:
package implementation

import (
	"time"

	"github.com/jllopis/zbs/services"

	google_protobuf1 "github.com/golang/protobuf/ptypes/empty"
	"golang.org/x/net/context"
)

type ServerTime struct{}

func (st *ServerTime) GetServerTime(context.Context, *google_protobuf1.Empty) (*services.ServerTimeMessage, error) {
	return &services.ServerTimeMessage{Value: time.Now().UTC().UnixNano()}, nil
}


text:
'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Tag = mongoose.model('Tag'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Create a tag
 */
exports.create = function (req, res) {
  var tag = new Tag(req.body);

  tag.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(tag);
    }
  });
};

/**
 * Show the current tag
 */
exports.read = function (req, res) {
  res.json(req.tag);
};

/**
 * Update a tag
 */
exports.update = function (req, res) {
  var tag = req.tag;

  tag.label = req.body.label;

  tag.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(tag);
    }
  });
};

/**
 * Delete an tag
 */
exports.delete = function (req, res) {
  var tag = req.tag;

  tag.remove(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(tag);
    }
  });
};

/**
 * List of Tags
 */
exports.list = function (req, res) {
  Tag.find().sort('-created').exec(function (err, tags) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(tags);
    }
  });
};

/**
 * Tag middleware
 */
exports.tagByID = function (req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Tag is invalid'
    });
  }

  Tag.findById(id).exec(function (err, tag) {
    if (err) {
      return next(err);
    } else if (!tag) {
      return res.status(404).send({
        message: 'No tag with that identifier has been found'
      });
    }
    req.tag = tag;
    next();
  });
};


text:
<?php

/* forms/fields/formname/formname.html.twig */
class __TwigTemplate_ca885dbcb6f6702151137cd94dd54dab03d886c492043c1f9bd310e62c26e8ad extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "<input type=\"hidden\" name=\"__form-name__\" value=\"";
        echo $this->getAttribute((isset($context["form"]) ? $context["form"] : null), "name", array());
        echo "\" />";
    }

    public function getTemplateName()
    {
        return "forms/fields/formname/formname.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  19 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("<input type=\"hidden\" name=\"__form-name__\" value=\"{{ form.name }}\" />", "forms/fields/formname/formname.html.twig", "/home/moonwort/public_html/user/plugins/form/templates/forms/fields/formname/formname.html.twig");
    }
}


text:
#ifndef TOKENIZED_STRING_FILTER_HPP
#define TOKENIZED_STRING_FILTER_HPP

#include "i_item_filter.hpp"
#include <memory>

namespace wgt
{
/**
 *	TokenizedStringFilter
 *  A filter implementation, which uses a vector of strings to compare text against.
 */
class TokenizedStringFilter : public IItemFilter
{
public:
	TokenizedStringFilter();
	virtual ~TokenizedStringFilter();

	virtual void setRole(ItemRole::Id roleId) override;

	virtual bool checkFilter(const IItem* item) override;

	void updateFilterTokens(const char* filterText);
	const char* getFilterText();

	void setSplitterChar(const char* splitter);
	const char* getSplitterChar();

private:
	struct Implementation;
	std::unique_ptr<Implementation> impl_;
};
} // end namespace wgt
#endif // TOKENIZED_STRING_FILTER_HPP