text:
ANGLE_TYPED_TEST_CASE(CompressedTextureTest, ES2_D3D9, ES2_D3D11);

template<typename T>
class CompressedTextureTest : public ANGLETest
{
protected:
    CompressedTextureTest() : ANGLETest(T::GetGlesMajorVersion(), T::GetPlatform())
    {
        setWindowWidth(512);
        setWindowHeight(512);
        setConfigRedBits(8);
        setConfigGreenBits(8);
        setConfigBlueBits(8);
        setConfigAlphaBits(8);
    }

    virtual void SetUp()
    {
        ANGLETest::SetUp();

        const std::string vsSource = SHADER_SOURCE
        (
            precision highp float;
            attribute vec4 position;
            varying vec2 texcoord;

            void main()
            {
                gl_Position = position;
                texcoord = (position.xy * 0.5) + 0.5;
                texcoord.y = 1.0 - texcoord.y;
            }
        );

        const std::string textureFSSource = SHADER_SOURCE
        (
            precision highp float;
            uniform sampler2D tex;
            varying vec2 texcoord;

            void main()
            {
                gl_FragColor = texture2D(tex, texcoord);
            }
        );

        mTextureProgram = CompileProgram(vsSource, textureFSSource);
        if (mTextureProgram == 0)
        {
            FAIL() << "shader compilation failed.";
        }

        mTextureUniformLocation = glGetUniformLocation(mTextureProgram, "tex");

        ASSERT_GL_NO_ERROR();
    }

    virtual void TearDown()
    {
        glDeleteProgram(mTextureProgram);

        ANGLETest::TearDown();
    }

    GLuint mTextureProgram;
    GLint mTextureUniformLocation;
};

TYPED_TEST(CompressedTextureTest, CompressedTexImage)
{
    if (getClientVersion() < 3 && !extensionEnabled("GL_EXT_texture_compression_dxt1"))
    {
        return;
    }

    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_0_width, pixel_0_height, 0, pixel_0_size, pixel_0_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 1, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_1_width, pixel_1_height, 0, pixel_1_size, pixel_1_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 2, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_2_width, pixel_2_height, 0, pixel_2_size, pixel_2_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 3, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_3_width, pixel_3_height, 0, pixel_3_size, pixel_3_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 4, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_4_width, pixel_4_height, 0, pixel_4_size, pixel_4_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 5, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_5_width, pixel_5_height, 0, pixel_5_size, pixel_5_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 6, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_6_width, pixel_6_height, 0, pixel_6_size, pixel_6_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 7, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_7_width, pixel_7_height, 0, pixel_7_size, pixel_7_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 8, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_8_width, pixel_8_height, 0, pixel_8_size, pixel_8_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 9, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_9_width, pixel_9_height, 0, pixel_9_size, pixel_9_data);

    EXPECT_GL_NO_ERROR();

    glUseProgram(mTextureProgram);
    glUniform1i(mTextureUniformLocation, 0);

    drawQuad(mTextureProgram, "position", 0.5f);

    EXPECT_GL_NO_ERROR();

    glDeleteTextures(1, &texture);

    EXPECT_GL_NO_ERROR();
}

TYPED_TEST(CompressedTextureTest, CompressedTexStorage)
{
    if (getClientVersion() < 3 && !extensionEnabled("GL_EXT_texture_compression_dxt1"))
    {
        return;
    }

    if (getClientVersion() < 3 && (!extensionEnabled("GL_EXT_texture_storage") || !extensionEnabled("GL_OES_rgb8_rgba8")))
    {
        return;
    }

    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    if (getClientVersion() < 3)
    {
        glTexStorage2DEXT(GL_TEXTURE_2D, pixel_levels, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_0_width, pixel_0_height);
    }
    else
    {
        glTexStorage2D(GL_TEXTURE_2D, pixel_levels, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_0_width, pixel_0_height);
    }
    EXPECT_GL_NO_ERROR();

    glCompressedTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, pixel_0_width, pixel_0_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_0_size, pixel_0_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 1, 0, 0, pixel_1_width, pixel_1_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_1_size, pixel_1_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 2, 0, 0, pixel_2_width, pixel_2_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_2_size, pixel_2_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 3, 0, 0, pixel_3_width, pixel_3_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_3_size, pixel_3_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 4, 0, 0, pixel_4_width, pixel_4_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_4_size, pixel_4_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 5, 0, 0, pixel_5_width, pixel_5_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_5_size, pixel_5_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 6, 0, 0, pixel_6_width, pixel_6_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_6_size, pixel_6_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 7, 0, 0, pixel_7_width, pixel_7_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_7_size, pixel_7_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 8, 0, 0, pixel_8_width, pixel_8_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_8_size, pixel_8_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 9, 0, 0, pixel_9_width, pixel_9_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_9_size, pixel_9_data);

    EXPECT_GL_NO_ERROR();

    glUseProgram(mTextureProgram);
    glUniform1i(mTextureUniformLocation, 0);

    drawQuad(mTextureProgram, "position", 0.5f);

    EXPECT_GL_NO_ERROR();

    glDeleteTextures(1, &texture);

    EXPECT_GL_NO_ERROR();
}

// Use this to select which configurations (e.g. which renderer, which GLES major version) these tests should be run against.
ANGLE_TYPED_TEST_CASE(CompressedTextureTestES3, ES3_D3D11);

template<typename T>
class CompressedTextureTestES3 : public CompressedTextureTest<T> { };

ANGLE_TYPED_TEST_CASE(CompressedTextureTestD3D11, ES2_D3D11, ES3_D3D11);

template<typename T>
class CompressedTextureTestD3D11 : public CompressedTextureTest<T> { };

TYPED_TEST(CompressedTextureTestES3, PBOCompressedTexImage)
{
    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER, buffer);
    glBufferData(GL_PIXEL_UNPACK_BUFFER, pixel_0_size, NULL, GL_STREAM_DRAW);
    EXPECT_GL_NO_ERROR();

    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_0_size, pixel_0_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_0_width, pixel_0_height, 0, pixel_0_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_1_size, pixel_1_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 1, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_1_width, pixel_1_height, 0, pixel_1_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_2_size, pixel_2_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 2, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_2_width, pixel_2_height, 0, pixel_2_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_3_size, pixel_3_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 3, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_3_width, pixel_3_height, 0, pixel_3_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_4_size, pixel_4_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 4, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_4_width, pixel_4_height, 0, pixel_4_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_5_size, pixel_5_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 5, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_5_width, pixel_5_height, 0, pixel_5_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_6_size, pixel_6_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 6, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_6_width, pixel_6_height, 0, pixel_6_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_7_size, pixel_7_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 7, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_7_width, pixel_7_height, 0, pixel_7_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_8_size, pixel_8_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 8, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_8_width, pixel_8_height, 0, pixel_8_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_9_size, pixel_9_data);
    glCompressedTexImage2D(GL_TEXTURE_2D, 9, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_9_width, pixel_9_height, 0, pixel_9_size, NULL);

    EXPECT_GL_NO_ERROR();

    glUseProgram(mTextureProgram);
    glUniform1i(mTextureUniformLocation, 0);

    drawQuad(mTextureProgram, "position", 0.5f);

    EXPECT_GL_NO_ERROR();

    glDeleteTextures(1, &buffer);
    glDeleteTextures(1, &texture);

    EXPECT_GL_NO_ERROR();
}

TYPED_TEST(CompressedTextureTestD3D11, PBOCompressedTexStorage)
{
    if (getClientVersion() < 3 && !extensionEnabled("GL_EXT_texture_compression_dxt1"))
    {
        return;
    }

    if (getClientVersion() < 3 && (!extensionEnabled("GL_EXT_texture_storage") || !extensionEnabled("GL_OES_rgb8_rgba8")))
    {
        return;
    }

    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    if (getClientVersion() < 3)
    {
        glTexStorage2DEXT(GL_TEXTURE_2D, pixel_levels, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_0_width, pixel_0_height);
    }
    else
    {
        glTexStorage2D(GL_TEXTURE_2D, pixel_levels, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_0_width, pixel_0_height);
    }
    EXPECT_GL_NO_ERROR();

    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER, buffer);
    glBufferData(GL_PIXEL_UNPACK_BUFFER, pixel_0_size, NULL, GL_STREAM_DRAW);
    EXPECT_GL_NO_ERROR();

    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_0_size, pixel_0_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, pixel_0_width, pixel_0_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_0_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_1_size, pixel_1_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 1, 0, 0, pixel_1_width, pixel_1_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_1_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_2_size, pixel_2_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 2, 0, 0, pixel_2_width, pixel_2_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_2_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_3_size, pixel_3_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 3, 0, 0, pixel_3_width, pixel_3_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_3_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_4_size, pixel_4_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 4, 0, 0, pixel_4_width, pixel_4_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_4_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_5_size, pixel_5_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 5, 0, 0, pixel_5_width, pixel_5_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_5_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_6_size, pixel_6_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 6, 0, 0, pixel_6_width, pixel_6_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_6_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_7_size, pixel_7_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 7, 0, 0, pixel_7_width, pixel_7_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_7_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_8_size, pixel_8_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 8, 0, 0, pixel_8_width, pixel_8_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_8_size, NULL);
    glBufferSubData(GL_PIXEL_UNPACK_BUFFER, 0, pixel_9_size, pixel_9_data);
    glCompressedTexSubImage2D(GL_TEXTURE_2D, 9, 0, 0, pixel_9_width, pixel_9_height, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, pixel_9_size, NULL);

    EXPECT_GL_NO_ERROR();

    glUseProgram(mTextureProgram);
    glUniform1i(mTextureUniformLocation, 0);

    drawQuad(mTextureProgram, "position", 0.5f);

    EXPECT_GL_NO_ERROR();

    glDeleteTextures(1, &texture);

    EXPECT_GL_NO_ERROR();
}


text:
package com.github.common.string;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.github.common.exception.ErrorCode;
import com.github.common.exception.GithubException;

public class StringValidator {
	public static void verifyEmpty(String paraName, String parameter) {
		if (parameter == null || parameter.trim().isEmpty()) {
			throw new GithubException(ErrorCode.COMMON_EMPTY_STRING, paraName);
		}
	}

	public static void verifyNotNull(String paraName, String parameter) {
		if (parameter == null || parameter.isEmpty()) {
			throw new GithubException(ErrorCode.COMMON_EMPTY_STRING, paraName);
		}
	}

	public static void verifyLength(String paraName, String parameter, int lengthLimit) {
		if (parameter != null && parameter.length() > lengthLimit) {
			throw new GithubException(ErrorCode.COMMON_LENGTH_EXCEED, paraName, lengthLimit);
		}
	}

	public static void verifyPattern(String paraName, String parameter,
			String pattern) {
		if (parameter != null && !parameter.matches(pattern)) {
			throw new GithubException(ErrorCode.COMMON_ILLEGAL_STRING,
					paraName, parameter, pattern);
		}
	}

	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

	public static Date verifyDate(String date) {
		return verifyDate(date, DEFAULT_DATE_FORMAT);
	}

	public static Date verifyDate(String date, String dateFormat) {
		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		if (date == null || date.isEmpty()) {
			throw new GithubException(ErrorCode.COMMON_EMPTY_STRING, "date");
		}
		try {
			format.setLenient(false);
			return format.parse(date);
		} catch (ParseException e) {
			throw new GithubException(ErrorCode.COMMON_DATEFORMAT_ILLEGAL,
					date, dateFormat);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Tomahawk\Forms\Element;

class Search extends Element
{
    /**
     * @param array $attributes
     * @return mixed
     */
    public function render(array $attributes = array())
    {
        $current_attributes = array(
            'name'  => $this->getName(),
            'value' => $this->getValue()
        );

        $attributes = array_merge($current_attributes, $attributes);

        return sprintf('<input type="search"%s>', $this->attributes($attributes));
    }
}


text:
import React, { PropTypes as T } from "react"
import Renderer from "react-test-renderer"
import portalMixin from "../lib/react-layer-mixin"

class ContextProvider extends React.Component {
  static propTypes = {
    children: T.node,
  }
  static defaultProps = {
    children: null,
  }
  static childContextTypes = {
    x: T.string,
  }
  getChildContext () {
    return ({
      x: "value-from-context",
    })
  }
  render () {
    return (
      this.props.children
    )
  }
}

class ContextDependent extends React.Component {
  static contextTypes = {
    x: T.string,
  }
  render () {
    return (
      <span>{this.context.x}</span>
    )
  }
}

const Portal = React.createClass({
  propTypes: {
    children: T.node
  },
  mixins: [portalMixin()],
  renderLayer () {
    return (
      this.props.children
    )
  },
  render () {
    return null
  }
})

beforeEach(() => {
  document.body.innerHTML = ""
})

it("Pass context through to layer", () => {
  Renderer.create(
    <ContextProvider>
      <Portal>
        <ContextDependent />
      </Portal>
    </ContextProvider>
  )
  expect(document.body.innerHTML).toMatchSnapshot()
})


text:
package org.beanio;

import java.util.*;

/**
 * Exception thrown when one or more records fail validation while unmarshalling
 * a record group.
 *
 *
The {@link #getRecordName()} method will return the name of the group (from
 * the mapping file) that failed validation.
 *
 *
An invalid record group does not affect the state of a {@link BeanReader}, and
 * subsequent calls to <tt>read()</tt> are not affected.
 *
 * @author Kevin Seim
 * @since 2.0
 */
public class InvalidRecordGroupException extends InvalidRecordException {

    private static final long serialVersionUID = 1L;

    private String groupName;

    /**
     * Constructs a new <tt>InvalidRecordGroupException</tt>.
     * @param context one or more record contexts that make up the group
     * @param message the error message
     * @param groupName the group name
     */
    public InvalidRecordGroupException(RecordContext[] context, String message, String groupName) {
        super(message);
        this.groupName = groupName;
        setRecordContext(context);
    }

    @Override
    public String getRecordName() {
        return groupName;
    }

    @Override
    protected void appendMessageDetails(StringBuilder s) {
        for (int i=0, j=getRecordCount(); i<j; i++) {
            RecordContext context = getRecordContext(i);
            if (!context.hasErrors()) {
                continue;
            }

            s.append("\n ==> Invalid '")
                .append(context.getRecordName())
                .append("' record at line ")
                .append(context.getLineNumber());

            if (context.hasRecordErrors()) {
                for (String error : context.getRecordErrors()) {
                    s.append("\n     - ");
                    s.append(error);
                }
            }
            if (context.hasFieldErrors()) {
                for (Map.Entry<String, Collection<String>> entry : context.getFieldErrors().entrySet()) {
                    String fieldName = entry.getKey();
                    for (String error : entry.getValue()) {
                        s.append("\n     - Invalid '");
                        s.append(fieldName);
                        s.append("':  ");
                        s.append(error);
                    }
                }
            }
        }
    }
}


text:
import generateId from 'shortid';
import { createAction } from 'helpers/actions';
import * as actionTypes from './actionTypes';

const action = createAction(actionTypes);

export const push = action('PUSH', notification => ({
  ...notification,
  uid: generateId(),
}));

export const shift = action('SHIFT', uid => ({ uid }));


text:
package com.eaw1805.www.controllers;

import com.eaw1805.data.managers.beans.EngineProcessManagerBean;
import com.eaw1805.data.model.EngineProcess;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Reports engine status in timeline XML format.
 */
public class EngineStatusController
        implements Controller {

    /**
     * a log4j logger to print messages.
     */
    private static final Logger LOGGER = LogManager.getLogger(GenericController.class);

    public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {

        // retrieve user
        LOGGER.debug("Engine Status (XML)");

        // Set the content type
        response.setContentType("application/xml");

        final PrintWriter pwr = response.getWriter();

        // header
        pwr.write("<data \n" +
                "    wiki-url=\"http://www.eaw1805.com/\"\n" +
                "    wiki-section=\"Empires at War Engine Status\"\n" +
                "    >\n");

        // iterate list of turn processes
        final List<EngineProcess> lstExecutions = engineManager.list();
        for (final EngineProcess process : lstExecutions) {
            // Get real date
            final Calendar realCal = Calendar.getInstance();
            realCal.setTime(process.getDateStart());
            final String realStart = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z").format(new Date());

            realCal.add(Calendar.SECOND, process.getDuration());
            final String realEnd = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z").format(new Date());

            // Get game date
            final Calendar turnCal = Calendar.getInstance();
            turnCal.set(1805, Calendar.JANUARY, 1);
            turnCal.add(Calendar.MONTH, process.getTurn());
            final String turnTitle = "Game " + process.getGameId() + " / " + turnCal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH);

            pwr.write("    <event start=\"" + realStart + "\"\n" +
                    "        end=\"" + realEnd + "\"\n" +
                    "        isDuration=\"true\"\n" +
                    "        title=\"'" + turnTitle + "'\">");

            pwr.write("        </event>\n");
        }

        // footer
        pwr.write("</data>");

        pwr.flush();
        pwr.close();
        return null;
    }

    /**
     * Instance EngineProcessManager class to perform queries
     * about engineProcess objects.
     */
    private transient EngineProcessManagerBean engineManager;

    /**
     * Setter method used by spring to inject a EngineProcessManagerBean bean.
     *
     * @param injEngineManager a EngineProcessManagerBean bean.
     */
    public void setEngineProcessManager(final EngineProcessManagerBean injEngineManager) {
        engineManager = injEngineManager;
    }

}


text:
#include <QMainWindow>
#include "PipeFollow.h"

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

protected:
    void changeEvent(QEvent *e);

private:
    Ui::MainWindow *ui;
    PipeFollow pipeFollow;
    QString videoFile;
private slots:
    void on_loadVideoButton_clicked();
    void on_detLineButton_clicked();
    void on_loadPictureButton_clicked();

};

#endif // MAINWINDOW_H


text:
__author__ = 'LennonChin'
__date__ = '2017/10/18 23:48'

from django.contrib.auth import get_user_model
User = get_user_model()

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        password = instance.password
        instance.set_password(password)
        instance.save()


text:
/*
 * 05/12/2010
 *
 * SearchEngineTest.java - Test cases for SearchEngine.java
 *
 * This library is distributed under a modified BSD license.  See the included
 * RSyntaxTextArea.License.txt file for details.
 */
package org.fife.ui.rtextarea;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.text.BadLocationException;

import junit.framework.TestCase;

import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rtextarea.SearchEngine;

/**
 * Some very basic unit tests for the {@link SearchEngine} used by
 * RTextArea/RSyntaxTextArea.
 *
 * @author Robert Futrell
 * @version 1.0
 */
public class SearchEngineTest extends TestCase {

	private RSyntaxTextArea textArea = new RSyntaxTextArea();

	private static String text;

	/**
	 * Asserts that two strings are equal, ignoring case.
	 *
	 * @param expected
	 * @param actual
	 */
	private void assertEqualsIgnoreCase(String expected, String actual) {
		expected = expected != null ? expected.toLowerCase() : null;
		actual = actual != null ? actual.toLowerCase() : null;
		assertEquals(expected, actual);
	}

	/**
	 * Asserts that the text area's selection is at the expected location and
	 * has the expected value.
	 *
	 * @param expected
	 * @param offs
	 * @param matchCase
	 */
	private void assertSelected(String expected, int offs, boolean matchCase) {
		String actual = textArea.getSelectedText();
		if (matchCase) {
			assertEquals(expected, actual);
		} else {
			assertEqualsIgnoreCase(expected, actual);
		}
		int selOffs = textArea.getSelectionStart();
		assertEquals("unexpected selection offset: ", offs, selOffs);
	}

	/**
	 * {@inheritDoc}
	 */
	protected void setUp() throws Exception {

		// setUp() is called once per test, each with a new instantiation of
		// SearchEngineTest, so check a static variable to ensure that
		// initialization is only done once.

		if (text == null || text.length() <= 0) {

			StringBuffer sb = new StringBuffer();
			InputStream in = getClass().getResourceAsStream("text.txt");
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String s = null;
			try {
				while ((s=br.readLine())!=null) {
					sb.append(s).append("\n");
				}
			} finally {
				br.close();
			}

			// Strip off last newline
			text = sb.toString().substring(0, sb.length()-1);

		}

		super.setUp();

	}

	/**
	 * Tests SearchEngine.find() when searching backward.
	 */
	public void testSearchEngineFindBackward() throws BadLocationException {

		textArea.setText(text);

		int end = text.length();
		SearchContext context = new SearchContext();
		context.setSearchForward(false);

		// Search for "chuck", ignoring case.
		context.setSearchFor("chuck");
		context.setMatchCase(false);
		textArea.setCaretPosition(end);
		boolean found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 60, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 48, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 32, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 26, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for "Chuck", matching case.
		context.setSearchFor("Chuck");
		context.setMatchCase(true);
		textArea.setCaretPosition(end);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("Chuck", 26, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for "chuck", ignoring case, whole word
		context.setSearchFor("Chuck");
		context.setMatchCase(false);
		context.setWholeWord(true);
		textArea.setCaretPosition(end);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 60, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 32, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for "wood", matching case, whole word
		context.setSearchFor("wood");
		context.setMatchCase(true);
		context.setWholeWord(true);
		textArea.setCaretPosition(end);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("wood", 9, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for ".ould", regex, ignoring case
		context.setSearchFor(".ould");
		context.setMatchCase(false);
		context.setWholeWord(false);
		context.setRegularExpression(true);
		textArea.setCaretPosition(end);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("could", 54, true);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("wOuld", 14, true);
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for ".ould", regex, matching case
		context.setSearchFor(".ould");
		context.setMatchCase(true);
		context.setWholeWord(false);
		context.setRegularExpression(true);
		textArea.setCaretPosition(end);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("could", 54, true);
		found = SearchEngine.find(textArea,context);
		assertEquals(false, found);

		// Search for "[cd]huck", regex, ignoring case, whole word
		context.setSearchFor("[cd]hUCk");
		context.setMatchCase(false);
		context.setWholeWord(true);
		context.setRegularExpression(true);
		textArea.setCaretPosition(end);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 60, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 32, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for "[cd]huck", regex, matching case, whole word
		context.setSearchFor("[cd]huck");
		context.setMatchCase(true);
		context.setWholeWord(true);
		context.setRegularExpression(true);
		textArea.setCaretPosition(end);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 60, true);
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

	}

	/**
	 * Tests SearchEngine.find() when searching forward.
	 */
	public void testSearchEngineFindForward() throws BadLocationException {

		textArea.setText(text);

		SearchContext context = new SearchContext();

		// Search for "chuck", ignoring case.
		context.setSearchFor("chuck");
		boolean found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 26, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 32, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 48, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 60, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for "Chuck", matching case.
		context.setSearchFor("Chuck");
		context.setMatchCase(true);
		textArea.setCaretPosition(0);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("Chuck", 26, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for "chuck", ignoring case, whole word
		context.setSearchFor("chuck");
		context.setMatchCase(false);
		context.setWholeWord(true);
		textArea.setCaretPosition(0);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 32, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 60, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for "wood", matching case, whole word
		context.setSearchFor("wood");
		context.setMatchCase(true);
		context.setWholeWord(true);
		textArea.setCaretPosition(0);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("wood", 9, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for ".ould", regex, ignoring case
		context.setSearchFor(".ould");
		context.setMatchCase(false);
		context.setWholeWord(false);
		context.setRegularExpression(true);
		textArea.setCaretPosition(0);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("wOuld", 14, true);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("could", 54, true);
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for ".ould", regex, matching case
		context.setSearchFor(".ould");
		context.setMatchCase(true);
		context.setWholeWord(false);
		context.setRegularExpression(true);
		textArea.setCaretPosition(0);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("could", 54, true);
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for "[cd]huck", regex, ignoring case, whole word
		context.setSearchFor("[cd]hUCk");
		context.setMatchCase(false);
		context.setWholeWord(true);
		context.setRegularExpression(true);
		textArea.setCaretPosition(0);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 32, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 60, context.getMatchCase());
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

		// Search for "[cd]huck", regex, matching case, whole word
		context.setSearchFor("[cd]huck");
		context.setMatchCase(true);
		context.setWholeWord(true);
		context.setRegularExpression(true);
		textArea.setCaretPosition(0);
		found = SearchEngine.find(textArea, context);
		assertEquals(true, found);
		assertSelected("chuck", 60, true);
		found = SearchEngine.find(textArea, context);
		assertEquals(false, found);

	}

	/**
	 * Tests SearchEngine.replace().
	 *
	 * @param forward Whether to test searching forward or backward.
	 */
	private void testSearchEngineReplace(boolean forward)
										throws BadLocationException {

		int offs = forward ? 0 : text.length();
		SearchContext context = new SearchContext();
		context.setSearchForward(forward);
		context.setReplaceWith("FOOBAR");

		// Search for "chuck", ignoring case.
		context.setSearchFor("chuck");
		textArea.setText(text);
		String expected = textArea.getText().replaceAll("(?i:" + context.getSearchFor() +  ")", context.getReplaceWith());
		textArea.setCaretPosition(offs);
		boolean found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(false, found);
		assertEquals(expected, textArea.getText());

		// Search for "chuck", matching case.
		context.setSearchFor("chuck");
		textArea.setText(text);
		expected = textArea.getText().replaceAll(context.getSearchFor(), context.getReplaceWith());
		context.setMatchCase(true);
		context.setWholeWord(false);
		context.setRegularExpression(false);
		textArea.setCaretPosition(offs);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(false, found);
		assertEquals(expected, textArea.getText());

		// Search for "chuck", ignoring case, whole word.
		context.setSearchFor("chuck");
		textArea.setText(text);
		expected = "How much wood wOuld a woodChuck FOOBAR, if a woodchuck could FOOBAR wOod?";
		context.setMatchCase(false);
		context.setWholeWord(true);
		context.setRegularExpression(false);
		textArea.setCaretPosition(offs);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(false, found);
		assertEquals(expected, textArea.getText());

		// Search for "chuck", matching case, whole word.
		context.setSearchFor("chuck");
		textArea.setText(text);
		expected = "How much wood wOuld a woodChuck chUck, if a woodchuck could FOOBAR wOod?";
		context.setMatchCase(true);
		context.setWholeWord(true);
		context.setRegularExpression(false);
		textArea.setCaretPosition(offs);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(false, found);
		assertEquals(expected, textArea.getText());

		// Search for ".huck", regex, ignoring case
		context.setSearchFor(".huck");
		textArea.setText(text);
		expected = textArea.getText().replaceAll("(?i:" + context.getSearchFor() +  ")", context.getReplaceWith());
		context.setMatchCase(false);
		context.setWholeWord(false);
		context.setRegularExpression(true);
		textArea.setCaretPosition(offs);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(false, found);
		assertEquals(expected, textArea.getText());

		// Search for ".huck", regex, matching case
		context.setSearchFor(".huck");
		textArea.setText(text);
		expected = textArea.getText().replaceAll(context.getSearchFor(), context.getReplaceWith());
		context.setMatchCase(true);
		context.setWholeWord(false);
		context.setRegularExpression(true);
		textArea.setCaretPosition(offs);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(false, found);
		assertEquals(expected, textArea.getText());

		// Search for "[cd]huck", regex, ignoring case, whole word
		context.setSearchFor("[cd]huck");
		textArea.setText(text);
		expected = "How much wood wOuld a woodChuck FOOBAR, if a woodchuck could FOOBAR wOod?";
		context.setMatchCase(false);
		context.setWholeWord(true);
		context.setRegularExpression(true);
		textArea.setCaretPosition(offs);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(false, found);
		assertEquals(expected, textArea.getText());

		// Search for "[cd]hUck", regex, matching case, whole word
		context.setSearchFor("[cd]hUck");
		textArea.setText(text);
		expected = "How much wood wOuld a woodChuck FOOBAR, if a woodchuck could chuck wOod?";
		context.setMatchCase(true);
		context.setWholeWord(false);
		context.setRegularExpression(true);
		textArea.setCaretPosition(offs);
		found = SearchEngine.replace(textArea, context);
		assertEquals(true, found);
		found = SearchEngine.replace(textArea, context);
		assertEquals(false, found);
		assertEquals(expected, textArea.getText());

	}

	/**
	 * Tests SearchEngine.replace() when searching backward.
	 */
	public void testSearchEngineReplaceBackward() throws BadLocationException {
		testSearchEngineReplace(false);
	}

	/**
	 * Tests SearchEngine.replace() when searching forward.
	 */
	public void testSearchEngineReplaceForward() throws BadLocationException {
		testSearchEngineReplace(true);
	}

	/**
	 * Tests SearchEngine.replaceAll().
	 */
	public void testSearchEngineReplaceAll() throws BadLocationException {

		SearchContext context = new SearchContext();
		context.setReplaceWith("FOOBAR");

		// Replace "chuck", ignoring case.
		context.setSearchFor("chuck");
		textArea.setText(text);
		String expected = textArea.getText().replaceAll("(?i:" + context.getSearchFor() +  ")", context.getReplaceWith());
		int count = SearchEngine.replaceAll(textArea, context);
		assertEquals(4, count);
		assertEquals(expected, textArea.getText());

		// Replace "wood", matching case.
		context.setSearchFor("wood");
		textArea.setText(text);
		expected = textArea.getText().replaceAll(context.getSearchFor(), context.getReplaceWith());
		context.setMatchCase(true);
		context.setWholeWord(false);
		context.setRegularExpression(false);
		count = SearchEngine.replaceAll(textArea, context);
		assertEquals(3, count);
		assertEquals(expected, textArea.getText());

		// Replace "wood", ignoring case, whole word.
		context.setSearchFor("wood");
		textArea.setText(text);
		expected = "How much FOOBAR wOuld a woodChuck chUck, if a woodchuck could chuck FOOBAR?";
		context.setMatchCase(false);
		context.setWholeWord(true);
		context.setRegularExpression(false);
		count = SearchEngine.replaceAll(textArea, context);
		assertEquals(2, count);
		assertEquals(expected, textArea.getText());

		// Replace "chUck", matching case, whole word.
		context.setSearchFor("chUck");
		textArea.setText(text);
		expected = "How much wood wOuld a woodChuck FOOBAR, if a woodchuck could chuck wOod?";
		context.setMatchCase(true);
		context.setWholeWord(true);
		context.setRegularExpression(false);
		count = SearchEngine.replaceAll(textArea, context);
		assertEquals(1, count);
		assertEquals(expected, textArea.getText());

		// Replace "wo(?:o|ul)d", regex, ignoring case.
		context.setSearchFor("wo(?:o|ul)d");
		textArea.setText(text);
		expected = textArea.getText().replaceAll("(?i:" + context.getSearchFor() +  ")", context.getReplaceWith());
		context.setMatchCase(false);
		context.setWholeWord(false);
		context.setRegularExpression(true);
		count = SearchEngine.replaceAll(textArea, context);
		assertEquals(5, count);
		assertEquals(expected, textArea.getText());

		// Replace "wo(?:o|ul)d", regex, matching case.
		context.setSearchFor("wo(?:o|ul)d");
		textArea.setText(text);
		expected = textArea.getText().replaceAll(context.getSearchFor(), context.getReplaceWith());
		context.setMatchCase(true);
		context.setWholeWord(false);
		context.setRegularExpression(true);
		count = SearchEngine.replaceAll(textArea, context);
		assertEquals(3, count);
		assertEquals(expected, textArea.getText());

		// Replace "wo(?:o|ul)d", regex, ignoring case, whole word
		context.setSearchFor("wo(?:o|ul)d");
		textArea.setText(text);
		expected = "How much FOOBAR FOOBAR a woodChuck chUck, if a woodchuck could chuck FOOBAR?";
		context.setMatchCase(false);
		context.setWholeWord(true);
		context.setRegularExpression(true);
		count = SearchEngine.replaceAll(textArea, context);
		assertEquals(3, count);
		assertEquals(expected, textArea.getText());

		// Replace "wO(?:o|ul)d", regex, matching case, whole word
		context.setSearchFor("wO(?:o|ul)d");
		textArea.setText(text);
		expected = "How much wood FOOBAR a woodChuck chUck, if a woodchuck could chuck FOOBAR?";
		context.setMatchCase(true);
		context.setWholeWord(true);
		context.setRegularExpression(true);
		count = SearchEngine.replaceAll(textArea, context);
		assertEquals(2, count);
		assertEquals(expected, textArea.getText());

	}

	/**
	 * Tests SearchEngine.replaceAll() when the replacement string
	 * has captured groups.
	 */
	public void testSearchEngineRegexReplaceAllWithCapturedGroups() throws BadLocationException {

		SearchContext context = new SearchContext();
		context.setRegularExpression(true);

		// A single captured group.
		context.setSearchFor("r(o+)t");
		textArea.setText("root roOt root");
		String expected = "oo oO oo";
		context.setMatchCase(false);
		context.setWholeWord(false);
		context.setReplaceWith("$1");
		int count = SearchEngine.replaceAll(textArea, context);
		assertEquals(3, count);
		assertEquals(expected, textArea.getText());

		// Multiple captured groups.
		context.setSearchFor("(\\d)(\\d+)[kM]");
		textArea.setText("152k 5271143M 3985k");
		expected = "1.52 5.271143 3.985";
		context.setMatchCase(false);
		context.setWholeWord(false);
		context.setReplaceWith("$1.$2");
		count = SearchEngine.replaceAll(textArea, context);
		assertEquals(3, count);
		assertEquals(expected, textArea.getText());

		// No matches
		context.setSearchFor("(\\d)(\\d+)ABC");
		expected = "152k 5271143M 3985k";
		textArea.setText(expected);
		textArea.setCaretPosition(8);
		context.setMatchCase(false);
		context.setWholeWord(false);
		context.setReplaceWith("$1.$2");
		count = SearchEngine.replaceAll(textArea, context);
		assertEquals(0, count);
		assertEquals(expected, textArea.getText());
		assertEquals(8, textArea.getCaretPosition()); // Caret doesn't move

	}

}


text:
module Lint {
    export class RuleWalker extends Lint.SyntaxWalker {
        private limit: number;
        private position: number;
        private options: any[];
        private failures: RuleFailure[];
        private sourceFile: ts.SourceFile;
        private disabledIntervals: Lint.IDisabledInterval[];
        private ruleName: string;

        constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
            super();

            this.position = 0;
            this.failures = [];
            this.options = options.ruleArguments;
            this.sourceFile = sourceFile;
            this.limit = this.sourceFile.getFullWidth();
            this.disabledIntervals = options.disabledIntervals;
            this.ruleName = options.ruleName;
        }

        public getSourceFile(): ts.SourceFile {
            return this.sourceFile;
        }

        public getFailures(): RuleFailure[] {
            return this.failures;
        }

        public getLimit() {
            return this.limit;
        }

        public getOptions(): any {
            return this.options;
        }

        public hasOption(option: string): boolean {
            if (this.options) {
                return this.options.indexOf(option) !== -1;
            } else {
                return false;
            }
        }

        public skip(node: ts.Node) {
            this.position += node.getFullWidth();
        }

        public createFailure(start: number, width: number, failure: string): RuleFailure {
            const from = (start > this.limit) ? this.limit : start;
            const to = ((start + width) > this.limit) ? this.limit : (start + width);
            return new Lint.RuleFailure(this.sourceFile, from, to, failure, this.ruleName);
        }

        public addFailure(failure: RuleFailure) {
            // don't add failures for a rule if the failure intersects an interval where that rule is disabled
            if (!this.existsFailure(failure) && !Lint.doesIntersect(failure, this.disabledIntervals)) {
                this.failures.push(failure);
            }
        }

        private existsFailure(failure: RuleFailure) {
            return this.failures.some((f) => f.equals(failure));
        }
    }

}


text:
package afirsraftgarrier.demoandroid.androidapi.view;

import afirsraftgarrier.demoandroid.R;

import android.app.Activity;
import android.os.Bundle;

/**
 * Baseline alignment in LinearLayout with mixed gravities.
 */
public class Baseline4 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baseline_4);
    }
}


text:
<?php

/**
 * Tests for the verb object of Sintax
 */

class Verb_Test extends Kohana_Unittest_TestCase {
	public function provider_verb() {
		return array(
			array( 'is', 'is' ),
			array( 'was walking', 'was walking' ),
		);
	}

	/**
	 * @dataProvider provider_verb
	 */
	public function test_verb( $word, $expected ) {
		$verb = new Verb( $word );
		$this->assertEquals( $expected, (string) $verb );
	}

	public function provider_verb_with_adverbs() {
		return array(
			array( 'is walking', array( 'effervesently' ), 'is walking effervesently' ),
			array( 'is walking', array( NULL, 'effervesently' ), 'is walking effervesently' ),
			array( 'is walking', array( 'effervesently', 'quickly' ), 'is walking effervesently and quickly' ),
			array( 'is walking', array( 'effervesently', 'quickly', 'efficiently' ), 'is walking effervesently, quickly and efficiently' ),
		);
	}

	/**
	 * @dataProvider provider_verb_with_adverbs
	 */
	public function test_verb_with_adverbs( $word, $adverb_list, $expected ) {
		$verb = new Verb( $word );
		foreach( $adverb_list as $adverb ) {
			$verb->adverb( $adverb );
		}
		$this->assertEquals( $expected, (string) $verb );
	}
}


text:
require 'mongo'
require 'singleton'

class MongoClientSingleton
  include Singleton

  attr_reader :client

  def initialize
    @client = Mongo::MongoClient.new('localhost')
  end

  def method_missing(method, *args)
    self.client.send(method, *args)
  end
end


text:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <input type="text" id="mobile" name="" value="">
        <button type="button" id="btn" name="button">点击查询</button>
        <div class="box">

        </div>
        <script src="js/jquery.js" charset="utf-8"></script>
        <script src="js/ajax.js" charset="utf-8"></script>
        <script type="text/javascript">
            $("#btn").click(function(){
                var mobile = $("#mobile").val();
                var url = "api/guishudi.php";
                sajax.get(url,{mobile:mobile},function(data,err){
                    console.log(data);
                    if (data.status == 1 && data.data != '{}') {
                        data = JSON.parse(data.data);
                        var info = data.areaName +'-'+ data.providerName;
                        $(".box").html(info);
                    }
                })
            })
        </script>
    </body>
</html>


text:
Poki.Drawable.Pokemon = function() {
  this.number;
  this.base;
  this.gender;
  this.abilities;
  this.stats={
    hp:null,
    atk:null,
    def:null,
    spAtk:null,
    spDef:null,
    spd:null
  };
  this.x = 200;
  this.y = 200;
  this.rnd;
  this.fleeDistance = 100;
  this.battleDistance = 10;
};
Poki.Drawable.Pokemon.prototype = new Poki.Drawable();
Poki.Drawable.Pokemon.prototype.create = function(number) {
  this.base = Poki.PokemonList[number];
  this.number = this.base.number;
  this.name = this.base.name;
  this.stats = this.base.baseStats;
  this.sprite = Poki.game.add.sprite(this.x, this.y, this.name);
  this.anim = this.sprite.animations.add('up', [0, 2], 5, false);
  this.anim = this.sprite.animations.add('down', [4, 6], 5, false);
  this.anim = this.sprite.animations.add('left', [1, 3], 5, false);
  this.anim = this.sprite.animations.add('right', [5, 7], 5, false);
  Poki.game.physics.arcade.enable(this.sprite);
}
Poki.Drawable.Pokemon.prototype.update=function(player){
  if(this.twoPointDistance(player.sprite.x,player.sprite.y,this.sprite.x,this.sprite.y)>=this.fleeDistance)
    this.move();
  else
    this.flee(player.sprite.x,player.sprite.y);
}
/**
 *	déplacement aléatoire du pokemon
 */
Poki.Drawable.Pokemon.prototype.move = function() {
  this.sprite.body.velocity.y = 0;
  this.sprite.body.velocity.x = 0;

  if(this.timeout())
    this.rnd = Math.floor((Math.random() * 4) + 1);

  if (this.rnd===1) {
      this.sprite.body.velocity.y -= this.stats.spd;
      this.sprite.animations.play('up');
  } else if (this.rnd===2) {
      this.sprite.body.velocity.y += this.stats.spd;
      this.sprite.animations.play('down');
  }else if (this.rnd===3) {
      this.sprite.body.velocity.x -= this.stats.spd;
      this.sprite.animations.play('left');
  } else if (this.rnd===4) {
      this.sprite.body.velocity.x += this.stats.spd;
      this.sprite.animations.play('right');
  }
}
/*
	déplacement pour échaper au joueur
*/
Poki.Drawable.Pokemon.prototype.flee = function(px,py) {
  this.sprite.body.velocity.y = 0;
  this.sprite.body.velocity.x = 0;
  var x = this.sprite.x;
  var y = this.sprite.y;

  if(this.twoPointDistance(px,py,x,y)<=this.battleDistance){
    console.log("battle!");
  }else if((x-px)>=0 && (y-py)>=0){
    this.sprite.body.velocity.y += this.stats.spd;
    this.sprite.animations.play('down');
  }else if((x-px)<=0 && (y-py)>=0){
    this.sprite.body.velocity.x -= this.stats.spd;
    this.sprite.animations.play('left');
  }else if((x-px)>=0 && (y-py)<=0){
    this.sprite.body.velocity.x += this.stats.spd;
    this.sprite.animations.play('right');
  }else if((x-px)<=0 && (y-py)<=0){
    this.sprite.body.velocity.y -= this.stats.spd;
    this.sprite.animations.play('up');
  }
}
/*
	le pokemon disparait de la map...il s'est échaper
*/
Poki.Drawable.Pokemon.prototype.escaped = function() {

}
Poki.Drawable.Pokemon.prototype.test = function(number) {
  console.log(this.number + " - " + this.name + " - " + this.hp + " - " + this.atk + " - " + this.def + " - " + this.spAtk + " - " + this.spDef + " - " + this.speed);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;

#if SERVERFX
namespace OpenRiaServices.DomainServices.Server
#else
namespace OpenRiaServices.DomainServices.Client
#endif
{
    /// <summary>
    /// The data contract of an error that has occurred
    /// during the execution of an operation on the server.
    /// This is sent back along with the domain operation
    /// result(s) to the client.
    /// </summary>
    [DataContract(Namespace = "DomainServices")]
    public sealed class ValidationResultInfo : IEquatable<ValidationResultInfo>
    {
        private string _message;
        private string _stackTrace;
        private int _errorCode;
        private IEnumerable<string> _sourceMemberNames;

        /// <summary>
        /// Default constructor
        /// </summary>
        public ValidationResultInfo()
        {
        }

        /// <summary>
        /// Constructor accepting an optional localized error message and and collection
        /// of the names of the members the error originated from.
        /// </summary>
        /// <param name="message">The localized message</param>
        /// <param name="sourceMemberNames">A collection of the names of the members the error originated from.</param>
        public ValidationResultInfo(string message, IEnumerable<string> sourceMemberNames)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (sourceMemberNames == null)
            {
                throw new ArgumentNullException("sourceMemberNames");
            }

            this._message = message;
            this._sourceMemberNames = sourceMemberNames;
        }

        /// <summary>
        /// Constructor accepting an optional localized error message, error code, stack trace,
        /// and collection of the names of the members the error originated from.
        /// </summary>
        /// <param name="message">The localized error message</param>
        /// <param name="errorCode">The custom error code</param>
        /// <param name="stackTrace">The error stack trace</param>
        /// <param name="sourceMemberNames">A collection of the names of the members the error originated from.</param>
        public ValidationResultInfo(string message, int errorCode, string stackTrace, IEnumerable<string> sourceMemberNames)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (sourceMemberNames == null)
            {
                throw new ArgumentNullException("sourceMemberNames");
            }

            this._message = message;
            this._errorCode = errorCode;
            this._stackTrace = stackTrace;
            this._sourceMemberNames = sourceMemberNames;
        }

        /// <summary>
        /// Gets or sets the error message
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string Message
        {
            get { return this._message; }
            set { this._message = value; }
        }

        /// <summary>
        /// Gets or sets custom error code
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public int ErrorCode
        {
            get { return this._errorCode; }
            set { this._errorCode = value; }
        }

        /// <summary>
        /// Gets or sets the stack trace of the error
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string StackTrace
        {
            get { return this._stackTrace; }
            set { this._stackTrace = value; }
        }

        /// <summary>
        /// Gets or sets the names of the members the error originated from.
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public IEnumerable<string> SourceMemberNames
        {
            get { return this._sourceMemberNames; }
            set { this._sourceMemberNames = value; }
        }

        /// <summary>
        /// Returns the hash code for this object.
        /// </summary>
        /// <returns>The hash code for this object.</returns>
        public override int GetHashCode()
        {
            return this.Message.GetHashCode();
        }

        #region IEquatable<ValidationResultInfo> Members

        /// <summary>
        /// Test the current instance against the specified instance for equality
        /// </summary>
        /// <param name="other">The ValidationResultInfo to compare to</param>
        /// <returns>True if the instances are equal, false otherwise</returns>
        bool IEquatable<ValidationResultInfo>.Equals(ValidationResultInfo other)
        {
            if (object.ReferenceEquals(this, other))
            {
                return true;
            }
            if (object.ReferenceEquals(null, other))
            {
                return false;
            }
            return ((this.Message == other.Message) &&
                    (this.ErrorCode == other.ErrorCode) &&
                    (this.StackTrace == other.StackTrace) &&
                    (this.SourceMemberNames.SequenceEqual(other.SourceMemberNames)));
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.googlecode.forplay</groupId>
    <artifactId>forplay-demos</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <groupId>com.googlecode.forplay</groupId>
  <artifactId>forplay-hello-project</artifactId>
  <packaging>pom</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Forplay Hello Project</name>
  <description>Forplay Hello Project</description>

  <modules>
    <module>core</module>
    <module>html</module>
  </modules>
</project>


text:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';

import store from '../shared/store/configureStore';

import AppRoutes from '../shared/routes/index';

render(
  <Provider store={store}>
    <AppRoutes />
  </Provider>,
  document.getElementById('app')
);


text:
package pages;

import javax.inject.Named;

import authentification.AuthenticationBean;
import baseClasses.Product;
import baseClasses.Rating;
import baseClasses.Page;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.SessionScoped;
/**
 * View for watching a selected item from the shop
 * Henry and Ben 22-04-16
 */

@Named("productView")
@SessionScoped
public class ProductView extends Page implements Serializable {

	private static final long serialVersionUID = 1L;

	// Array with hopefully 1 product
	private List<Product> products = new ArrayList<Product>();
	private int id;
	private Rating nRating = new Rating();

	public void init() {
		setProduct(id);
	}

	public void setID(int id){
		this.id = id;
	}

	public int getID(){
		return id;
	}

	/**
	 * Sets the productView product array to input product ID. Array will be size of 1, if the product exists
	 * @param product ID you want to fetch
	 */
	public void setProduct(int id) {
		try {
			setContent("SELECT * FROM product WHERE id="+id);
			products = toProducts(content);
			products.get(0).setQuantity(1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Creates a product array with ID wanting to fetch, return product at index 0
	 * @param product ID you want to fetch
	 * @return product that fits ID, otherwise dummy
	 */
	public Product getOneProduct(int id){

		//Dummy class if enter illegal ID
		if(products.size()==0){
			Product prod = new Product();
			return prod;
		}
		return products.get(0);
	}
	/**
	 * returns the total quantity for the product defined by the ID (Stock in the database)
	 */
	@Override
    public int getQuantity(String productID){
		if (productID.isEmpty()) return 0;
    	return super.getQuantity(productID);
    }

	public void notifyQuantity(){
		if (Basket.productInBasket(Integer.toString(id))) {
			if (Basket.productFromBasket(Integer.toString(id)).getQuantity() > getQuantity(Integer.toString(products.get(0).getId()))) {
				Basket.productFromBasket(Integer.toString(id)).setQuantity(getQuantity(Integer.toString(products.get(0).getId())));
	    		super.notify("Error","Sorry, we do not have this amount on stock. The quantity got reset to the maximum.");
			}
		}
		else if (products.get(0).getQuantity() > getQuantity(Integer.toString(products.get(0).getId()))) {
    		products.get(0).setQuantity(getQuantity(Integer.toString(products.get(0).getId())));
    		super.notify("Error","Sorry, we do not have this amount on stock. The quantity got reset to the maximum.");
    	}
	}

	public void submitRating(){
		nRating.setAuthor(AuthenticationBean.activeUser);
		insertDB(nRating);
		// read the generated id from DB
		setContent("SELECT id FROM rating");
		try {
			content.last();
			nRating.setId(content.getInt("id"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		for (int i=0;i<products.get(0).getRatings().size();i++) System.out.println("ID Rating: " + products.get(0).getRatings().get(i).getId());
		products.get(0).getRatings().add(nRating);
		products.get(0).setQuantity(super.getQuantity(Integer.toString(products.get(0).getId())));
		updateDB(products.get(0));
		products.get(0).setQuantity(1);
		nRating = new Rating();
	}

	public Rating getnRating() {
		return nRating;
	}

	public void setnRating(Rating nRating) {
		this.nRating = nRating;
	}

}


text:
package org.synyx.urlaubsverwaltung.web.statistics;

import org.joda.time.DateMidnight;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.synyx.urlaubsverwaltung.core.sicknote.statistics.SickNoteStatistics;
import org.synyx.urlaubsverwaltung.core.sicknote.statistics.SickNoteStatisticsService;
import org.synyx.urlaubsverwaltung.security.SecurityRules;

/**
 * Controller for statistics of sick notes resp. sick days.
 *
 * @author  Aljona Murygina - murygina@synyx.de
 */
@Controller
@RequestMapping("/web")
public class SickNoteStatisticsController {

    private final SickNoteStatisticsService statisticsService;

    @Autowired
    public SickNoteStatisticsController(SickNoteStatisticsService statisticsService) {
        this.statisticsService = statisticsService;
    }

    @PreAuthorize(SecurityRules.IS_OFFICE)
    @GetMapping("/sicknote/statistics")
    public String sickNotesStatistics(@RequestParam(value = "year", required = false) Integer requestedYear,
        Model model) {

        Integer year = requestedYear == null ? DateMidnight.now().getYear() : requestedYear;

        SickNoteStatistics statistics = statisticsService.createStatistics(year);

        model.addAttribute("statistics", statistics);

        return "sicknote/sick_notes_statistics";
    }
}


text:
package org.aslak.github.merge.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.websocket.Session;

import org.aslak.github.merge.model.Notification;
import org.aslak.github.merge.model.PullRequestKey;

@ApplicationScoped
public class NotificationCentral {

    private Map<PullRequestKey, List<Session>> sessions = new HashMap<>();

    public void register(Session session, PullRequestKey request) {
        synchronized (sessions) {
            List<Session> registered = new ArrayList<>();
            if(sessions.containsKey(request)) {
                registered = sessions.get(request);
            }
            registered.add(session);
            sessions.put(request, registered);
        }
    }

    public void unregister(Session session, PullRequestKey request) {
        synchronized (sessions) {
            if(sessions.containsKey(request)) {
                List<Session> registered = sessions.get(request);
                registered.remove(session);
                if(registered.size() == 0) {
                    sessions.remove(request);
                }
            }
        }
    }

    public void notifyListeners(@Observes Notification notification) {
        List<Session> registered = sessions.get(notification.getKey());
        if(registered == null) {
            return;
        }
        for(Session session : registered) {
            if(session.isOpen()) {
                session.getAsyncRemote().sendText(notificationToJson(notification));
            }
        }
    }

    private String notificationToJson(Notification n) {
        StringBuilder sb = new StringBuilder();
        sb.append("{\n")
            .append("\"type\": \"").append(n.getType()).append("\",\n")
            .append("\"key\": \"").append(n.getKey()).append("\",\n")
            .append("\"message\": \"").append(n.getMessage()).append("\"\n")
        .append("}\n");
        return sb.toString();
    }
}


text:
<base-page equal-panes>

[[getTitleText_(status_)]]

      <iron-icon icon="shimless-icon:warning"
          class="warning-icon small-icon" hidden="[[!shouldShowWarning_]]">
      </iron-icon>

        [[statusString_]]

      <paper-spinner-lite class="large-spinner"
          hidden$="[[!shouldShowSpinner_]]" active>
      </paper-spinner-lite>

</base-page>


text:
function PLAYER:GetRankString()

	if self:GetLevel() == 200 then
		return "Guest";
	elseif self:GetLevel() == 100 then
		return "Bronze VIP";
	elseif self:GetLevel() == 99 then
		return "Silver VIP";
	elseif self:GetLevel() == 98 then
		return "Gold VIP";
	elseif self:GetLevel() == 97 then
		return "Diamond VIP";
	elseif self:GetLevel() == 96 then
		return "Premium VIP";
	elseif self:GetLevel() == 3 then
		return "Mod";
	elseif self:GetLevel() == 2 or self:GetLevel() == 10 then
		return "Admin";
	elseif self:GetLevel() == 1 then
		return "Super Admin";
	elseif self:GetLevel() == 0 then
		return "Owner";
	elseif self:GetLevel() == 255 then
		return "Banned";
	else
		return "ERROR GETTING RANK";
	end

end

local function MonitorDrowning ( )
	for k, v in pairs(player.GetAll()) do
		if (SERVER || v == LocalPlayer()) then
			if (v:WaterLevel() >= 3) then
				v.UnderwaterStart = v.UnderwaterStart or CurTime();
				local availableUnderwaterTime = GAMEMODE.DrownTime * (1 + ((v:GetPERPLevel(SKILL_SWIMMING) - 1) * .2));

				if (v:Alive() && v.UnderwaterStart + availableUnderwaterTime <= CurTime()) then
					v.LastWaterDamage = v.LastWaterDamage or 0;

					if (v.LastWaterDamage + GAMEMODE.DrowningDelay <= CurTime()) then
						v.LastWaterDamage = CurTime();

						if SERVER then
							local ProspectiveHealth = v:Health() - GAMEMODE.DrowningDamage;

							if (ProspectiveHealth <= 0) then
								v:Kill();
							else
								v:SetHealth(ProspectiveHealth);
							end
						else
							surface.PlaySound(Sound("player/pl_drown" .. math.random(1, 3) .. ".wav"));
							vgui.Create("perp2_drown");
						end
					end
				end

				v.LastSwimmingAllowance = v.LastSwimmingAllowance or 0;
				local realSpeed = v:GetVelocity():Length();

				if (realSpeed >= 50 && v.LastSwimmingAllowance + 1 <= CurTime()) then
					v:GiveExperience(SKILL_SWIMMING, GAMEMODE.ExperienceForSwimming, true);
					v.LastSwimmingAllowance = CurTime();
				end
			else
				if (v:InVehicle() && v:GetVehicle():GetClass() == "prop_vehicle_jeep") then
					v.LastDrivingAllowance = v.LastDrivingAllowance or 0;
					local realSpeed = v:GetVehicle():GetVelocity():Length();

					if (realSpeed >= 10 && v.LastDrivingAllowance <= CurTime()) then
						v:GiveExperience(SKILL_DRIVING, GAMEMODE.ExperienceForDriving, true);
						v.LastDrivingAllowance = CurTime() + 5;
					end
				end

				v.UnderwaterStart = nil;
			end
		end
	end
end
hook.Add("Think", "MonitorDrowning", MonitorDrowning);

function IsValid( object )
	if (!object) then return false; end
	if (!object.IsValid) then return false; end

	return object:IsValid();
end;

function ScaleToWideScreen(size)
	return math.min(math.max( ScreenScale(size / 2.62467192), math.min(size, 14) ), size);
end;

function FindPlayer(info)
	local pls = player.GetAll()

	-- Find by Index Number (status in console)
	for k = 1, #pls do -- Proven to be faster than pairs loop.
		local v = pls[k]
		if tonumber(info) == v:UserID() then
			return v
		end

		if info == v:SteamID() then
			return v
		end

		if string.find(string.lower(v:GetRPName()), string.lower(tostring(info)), 1, true) ~= nil then
			return v
		end
	end
	return nil
end


text:
=head1 NAME

  delete_transcripts.pl

=head1 DESCRIPTION

Deletes transcripts from given database whose IDs are passed in through
standard input or in a file named on the command line.

=head1 OPTIONS

=head1

=head2 Database connection options

  -dbhost   Host name for database.
  -dbport   What port to connect to.
  -dbname   What name to connect to.
  -dbuser   What username to connect as.
  -dbpass   What password to use.

=head2 Database connection options (alternative method)

  --config_dbname   The alias for the database you
                    want to connect to, as defined in
                    Bio::EnsEMBL::Analysis::Config::Databases
                    configuration file.  Use this option or the
                    dbhost/dbport/dbname etc. options above, but not
                    both.

=head2 Other options

  --stable_id   A boolean flag to indicate that the IDs passed in are
                transcript stable IDs.

=head1 EXAMPLES

  ./delete_transcripts.pl --dbhost=genebuild2 \
    --dbuser=ensadmin --dbpass=**** \
    --dbname=rat_Jun03_mk2 transcripts_to_delete.list

=cut

use strict;
use warnings;

use Getopt::Long qw(:config no_ignore_case);
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Analysis::Tools::Utilities;
use Bio::EnsEMBL::Utils::Exception;

$Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor::SILENCE_CACHE_WARNINGS = 1;

my $host;
my $port = 3306;
my $dbname;
my $user;
my $pass;
my $use_stable_ids;
my $config_dbname;

GetOptions( 'dbhost|host|h:s' => \$host,
            'dbport|port|P:n' => \$port,
            'dbname|db|D:s'   => \$dbname,
            'dbuser|user|u:s' => \$user,
            'dbpass|pass|p:s' => \$pass,
            'stable_id!'      => \$use_stable_ids,
            'config_dbname:s' => \$config_dbname ) ||
  die('Command line parsing error');

my $db;

if ( defined($config_dbname) ) {
  $db = get_db_adaptor_by_string($config_dbname);
}
elsif ( defined($dbname) && defined($host) ) {
  $db =
    new Bio::EnsEMBL::DBSQL::DBAdaptor( -host     => $host,
                                        -user     => $user,
                                        -port     => $port,
                                        -dbname   => $dbname,
                                        -pass     => $pass,
                                        -no_cache => 1 );
}
else {
  throw( "Need to pass either --dbhost, --dbuser, and --dbname, " .
         "or -config_dbname" );
}

my $ta = $db->get_TranscriptAdaptor();
my $ga = $db->get_GeneAdaptor();

my %gene_ids;

while ( my $transcript_id = <> ) {
  chomp($transcript_id);

  if ( !defined($transcript_id) || $transcript_id eq '' ) {
    last;
  }

  my $transcript;

  if ( defined($use_stable_ids) ) {
    $transcript = $ta->fetch_by_stable_id($transcript_id);
  }
  else {
    $transcript = $ta->fetch_by_dbID($transcript_id);
  }

  if ( !defined($transcript) ) {
    print("Can't fetch transcript $transcript_id\n");
    next;
  }

  my $gene_id =
    $ga->fetch_by_transcript_id( $transcript->dbID() )->dbID();

  my $has_transcript_stable_id = defined( $transcript->stable_id() );
  my $copy_of_dbID = $transcript->dbID();

  eval {
    # We want to update the gene in case the boundaries have changed
    $ta->remove($transcript, 1);
    if ($has_transcript_stable_id) {
      printf( "Deleted transcript %s (id = %d)\n",
              $transcript->stable_id(), $copy_of_dbID );
    }
    else {
      printf( "Deleted transcript (id = %d)\n", $copy_of_dbID );
    }
  };

  if ($@) {
    if ($has_transcript_stable_id) {
      printf( "Could not remove transcript %s (id = %d): %s\n",
              $transcript->stable_id(),
              $transcript->dbID(), $@ );
    }
    else {
      printf( "Could not remove transcript (id = %d): %s\n",
              $transcript->dbID(), $@ );
    }
    next;
  }

  $gene_ids{$gene_id}{ $copy_of_dbID } = 1;
} ## end while ( my $transcript_id...)

# Now get all those genes again and see if they are empty or split.

foreach my $gene_id ( keys(%gene_ids) ) {
  my $gene = $ga->fetch_by_dbID($gene_id);

  # See if gene is now empty.

  my $has_gene_stable_id = defined( $gene->stable_id() );

  my @transcripts = @{ $gene->get_all_Transcripts() };

  if ( !@transcripts ) {
    if ($has_gene_stable_id) {
      printf( "Gene %s (id = %d) is now empty, delete it!\n",
              $gene->stable_id(), $gene->dbID() );
    }
    else {
      printf( "Gene (id = %d) is now empty, delete it!\n",
              $gene->dbID() );
    }
    next;
  }

  # See if gene is now split.

  my $max_end;
  my @cluster;

  foreach my $t ( sort { $a->start() <=> $b->start() } @transcripts ) {
    if ( exists( $gene_ids{$gene_id}{ $t->dbID() } ) ) {
      next;
    }

    if ( !defined($max_end) ) {
      $max_end = $t->end();
    }
    elsif ( $t->start() > $max_end ) {
      # There's a gap between the ending of the last transcript and the
      # beginning of this, which means that the transcripts in @cluster
      # should now be removed from $gene and put into a new gene object.

      if ($has_gene_stable_id) {
        printf( "WARNING:\tFrom gene %s (id = %d),\n" .
                  "\t\ta new gene should be created\n" .
                  "\t\twith the following %d trancript(s):\n",
                $gene->stable_id(), $gene->dbID(), scalar(@cluster) );
        print(
          map {
            sprintf( "\t%s (id = %d)\n", $_->stable_id(), $_->dbID() )
          } @cluster );
      }
      else {
        printf( "WARNING:\tFrom gene (id = %d),\n" .
                  "\t\ta new gene should be created\n" .
                  "\t\twith the following %d trancript(s):\n",
                $gene->dbID(), scalar(@cluster) );
        print( map { sprintf( "\t(id = %d)\n", $_->dbID() ) }
               @cluster );

      }
      @cluster = ();
    } ## end elsif ( $t->start() > $max_end) [ if ( !defined($max_end...))]

    if ( $max_end < $t->end() ) {
      $max_end = $t->end();
    }

    push( @cluster, $t );
  } ## end foreach my $t ( sort { $a->start...})

} ## end foreach my $gene_id ( keys(...))


text:
<?php
/*
 * Controller for manage messages from user
 * @author Thomas Elvin
 */

use Datalaere\PHPMvcFramework\Controller;
use Datalaere\PHPHttp\Router;
use Datalaere\PHPHttp\Redirect;
use Datalaere\PHPHttp\Input;
use Datalaere\PHPSecurity\Session;
use Datalaere\PHPSecurity\Validator;
use Datalaere\PHPScrud\DB;
use Datalaere\PHPMultilingual\I18n;

class MessagesController extends Controller
{
    public $data;

    public function __construct()
    {
        // construct controller
        parent::__construct();
        // get project url
        $this->data['project_url'] = Router::getProjectUrl();
        $this->data['current_url'] = Router::getUrl();
    }

    public function index()
    {
        Redirect::back();
    }

    public function create()
    {
        if (Input::exists()) {
            $validation = $this->validate();

            if ($validation->passed()) {
                DB::load()->insert('Messages', array(
                    'Created' => time(),
                    'Name'    => Input::get('name'),
                    'Email'   => Input::get('email'),
                    'Content' => Input::get('content'),
                ));
                Session::set('SUCCESS', I18n::get('MESSAGES_CREATE_SUCCESS'));
                Redirect::to($this->data['project_url']);
            } else {
                // gather the errorrs and echo them out
                foreach ($validation->errors() as $error) {
                    $_SESSION['ERRORS'][] = $error;
                }

                Redirect::to($this->data['project_url']);
            }
        }
        Redirect::to($this->data['project_url']);
    }

    private function validate()
    {
        $validate   = Validator::load(DB::load());
        $validation = $validate->checkPost($_POST, array(
            'name'    => array(
                'required'   => true,
                'min'        => 1,
                'max'        => 32,
                'validInput' => Input::get('name')
            ),
            'email'   => array(
                'required'   => true,
                'min'        => 5,
                'max'        => 32,
                'validEmail' => Input::get('email')
            ),
            'content' => array(
                'required' => false,
                'max'      => 500
            )
        ));
        return $validation;
    }

    public function delete()
    {
        if (Input::exists()) {
            DB::load()->delete('Messages', array(
                array('ID', '=', Input::get('ID'))
            ));
        }

        Redirect::to($this->data['project_url'] . 'admin/read/messages');
    }

    public function read($type, $start = 1, $end, $max)
    {
        $messages = DB::load()->query(
            "SELECT ID, Created, Name, Email, Content FROM Messages ORDER BY ID DESC",
            null,
            'Messages',
            array('start' => $start, 'end' => $end, 'max' => $max)
        )->results();

        return (object) array(
                    'data'  => $messages,
                    'total' => DB::load()->_records
        );
    }
}


text:
FactoryGirl.define do
  factory :import, class: Synchronisable::Import do
    remote_id { generate :integer }
  end
end


text:
using System.Linq;
using NRules.Fluent;
using NRules.IntegrationTests.TestRules;
using NRules.RuleModel;
using NUnit.Framework;

namespace NRules.IntegrationTests
{
    [TestFixture]
    public class RuleMetadataTest
    {
        private RuleRepository _repository;

        [SetUp]
        public void SetUp()
        {
            _repository = new RuleRepository();
        }

        [Test]
        public void Name_NameAttributePresent_CustomValue()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            string actual = rule.Name;

            //Assert
            Assert.AreEqual("Rule with metadata", actual);
        }

        [Test]
        public void Description_DescriptionAttributePresent_CustomValue()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            string actual = rule.Description;

            //Assert
            Assert.AreEqual("Rule description", actual);
        }

        [Test]
        public void Tags_TagAttributesPresent_CustomValues()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            string[] actual = rule.Tags.ToArray();

            //Assert
            Assert.AreEqual(2, actual.Length);
            Assert.Contains("Test", actual);
            Assert.Contains("Metadata", actual);
        }

        [Test]
        public void Priority_PriorityAttributePresent_CustomValue()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            int actual = rule.Priority;

            //Assert
            Assert.AreEqual(100, actual);
        }

        [Test]
        public void Tags_TagAttributesAndParentAttributesPresent_CustomValues()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithMetadataAndParentMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            string[] actual = rule.Tags.ToArray();

            //Assert
            Assert.AreEqual(4, actual.Length);
            Assert.Contains("ChildTag", actual);
            Assert.Contains("ChildMetadata", actual);
            Assert.Contains("ParentTag", actual);
            Assert.Contains("ParentMetadata", actual);
        }

        [Test]
        public void Priority_PriorityParentAttributePresent_CustomValue()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithMetadataAndParentMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            int actual = rule.Priority;

            //Assert
            Assert.AreEqual(200, actual);
        }

        [Test]
        public void Priority_PriorityAttributeOverriden_CustomValue()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithMetadataAndParentMetadataAndOverrides)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            int actual = rule.Priority;

            //Assert
            Assert.AreEqual(500, actual);
        }

        [Test]
        public void Name_NoAttributes_TypeName()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithoutMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            string actual = rule.Name;

            //Assert
            Assert.AreEqual(typeof(RuleWithoutMetadata).FullName, actual);
        }

        [Test]
        public void Description_NoAttributes_Empty()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithoutMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            string actual = rule.Description;

            //Assert
            Assert.AreEqual(string.Empty, actual);
        }

        [Test]
        public void Tags_NoAttributes_Empty()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithoutMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            string[] actual = rule.Tags.ToArray();

            //Assert
            Assert.AreEqual(0, actual.Length);
        }

        [Test]
        public void Priority_NoAttribute_Default()
        {
            //Arrange
            _repository.Load(x => x.From(typeof(RuleWithoutMetadata)));
            IRuleDefinition rule = _repository.GetRules().Single();

            //Act
            int actual = rule.Priority;

            //Assert
            Assert.AreEqual(0, actual);
        }
    }
}


text:
package org.openmrs.module.shrclient.web.controller;

import org.apache.log4j.Logger;
import org.openmrs.api.APIAuthenticationException;
import org.openmrs.module.shrclient.service.FacilityCatchmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping(value = "/facilityCatchments")
public class FacilityCatchmentController {
    private static final Logger log = Logger.getLogger(FacilityCatchmentController.class);

    @Autowired
    private FacilityCatchmentService facilityCatchmentService;

    @RequestMapping(method = RequestMethod.GET, value = "/findByFacility")
    @ResponseBody
    public Object findByFacility(@RequestParam int locationId, HttpServletResponse response) throws IOException {
        try {
            return facilityCatchmentService.getCatchmentsForFacility(locationId);
        } catch (APIAuthenticationException e) {
            log.info("Not authorized to access national registry");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
            return null;
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/findByCatchment")
    @ResponseBody
    public Object findByCatchment(@RequestParam String catchment, HttpServletResponse response) throws IOException {
        try {
            return facilityCatchmentService.getFacilitiesForCatchment(catchment);
        } catch (APIAuthenticationException e) {
            log.info("Not authorized to access national registry");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
            return null;
        }
    }

}


text:
hs.loadSpoon("SpoonInstall")
spoon.SpoonInstall.use_syncinstall = true
Install=spoon.SpoonInstall

hs.loadSpoon('ControlEscape'):start() -- Load Hammerspoon bits from https://github.com/jasonrudolph/ControlEscape.spoon
require('windows')

hs.notify.show("Welcome to Hammerspoon", "Have fun?!", "")


text:
namespace ash {
namespace {

// Maximum wait time for merge session process.
constexpr base::TimeDelta kTotalWaitTime = base::Seconds(10);

OAuth2LoginManager* GetOAuth2LoginManager(content::WebContents* web_contents) {
  content::BrowserContext* browser_context = web_contents->GetBrowserContext();
  if (!browser_context)
    return nullptr;

  Profile* profile = Profile::FromBrowserContext(browser_context);
  if (!profile)
    return nullptr;

  return OAuth2LoginManagerFactory::GetInstance()->GetForProfile(profile);
}

}  // namespace

// static
std::unique_ptr<content::NavigationThrottle>
MergeSessionNavigationThrottle::Create(content::NavigationHandle* handle) {
  return std::unique_ptr<content::NavigationThrottle>(
      new MergeSessionNavigationThrottle(handle));
}

MergeSessionNavigationThrottle::MergeSessionNavigationThrottle(
    content::NavigationHandle* handle)
    : NavigationThrottle(handle) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}

MergeSessionNavigationThrottle::~MergeSessionNavigationThrottle() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}

content::NavigationThrottle::ThrottleCheckResult
MergeSessionNavigationThrottle::WillStartRequest() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  if (!merge_session_throttling_utils::ShouldDelayUrl(
          navigation_handle()->GetURL()) ||
      !merge_session_throttling_utils::ShouldDelayRequestForWebContents(
          navigation_handle()->GetWebContents())) {
    return content::NavigationThrottle::PROCEED;
  }

  if (BeforeDefer())
    return content::NavigationThrottle::DEFER;

  return content::NavigationThrottle::PROCEED;
}

content::NavigationThrottle::ThrottleCheckResult
MergeSessionNavigationThrottle::WillRedirectRequest() {
  return WillStartRequest();
}

const char* MergeSessionNavigationThrottle::GetNameForLogging() {
  return "MergeSessionNavigationThrottle";
}

void MergeSessionNavigationThrottle::OnSessionRestoreStateChanged(
    Profile* user_profile,
    OAuth2LoginManager::SessionRestoreState state) {
  auto* manager = GetOAuth2LoginManager(navigation_handle()->GetWebContents());
  if (!manager->ShouldBlockTabLoading()) {
    Proceed();
  }
}

bool MergeSessionNavigationThrottle::BeforeDefer() {
  auto* manager = GetOAuth2LoginManager(navigation_handle()->GetWebContents());
  if (manager && manager->ShouldBlockTabLoading()) {
    login_manager_observation_.Observe(manager);
    proceed_timer_.Start(FROM_HERE, kTotalWaitTime, this,
                         &MergeSessionNavigationThrottle::Proceed);
    return true;
  }
  return false;
}

void MergeSessionNavigationThrottle::Proceed() {
  proceed_timer_.Stop();
  auto* manager = GetOAuth2LoginManager(navigation_handle()->GetWebContents());
  if (manager) {
    DCHECK(login_manager_observation_.IsObservingSource(manager));
    login_manager_observation_.Reset();
  }
  Resume();
}

}  // namespace ash


text:
gaetaskhelper
=============

Generic helper functions for using tasks in Google App Engine


text:
published: true
title: Space Explorer is now in the App Store
layout: post
---
I couldn't be more excited than in that moment I saw the approval email from the review team in my inbox. So long story short, my [Space-Explorer](https://itunes.apple.com/us/app/space-explorer/id1053165651) app is now alive in the `App Store`! Please take a look at it and leave me some useful feedback either in `iTunes` or on this blog, under the `Contact` section. Thanks, and I do hope you will enjoy it :-)

![Space-Explorer](https://github.com/mhorga/mhorga.github.io/blob/master/images/app.png?raw=true "Space-Explorer")

Until next time!