text:
using namespace std;
using namespace glm;

static GLFWwindow* window = nullptr;

size_t GetFreeMemNvidia() {
    // TODO: AMD version w/ GL_ATI_meminfo
    GLint currMem = 0;
    glGetIntegerv(GL_GPU_MEM_INFO_CURRENT_AVAILABLE_MEM_NVX, &currMem);
    return (size_t)currMem * 1024;
}

size_t GetMainMemUsage() {
    PROCESS_MEMORY_COUNTERS_EX pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
    return pmc.PrivateUsage;
}

PerfRecord RunPerf(std::function<void()> setupFn, std::function<void()> drawFn, std::function<void()> teardownFn) {
    int discardFrames = FRAMES_TO_DISCARD;
    int frameCount = FRAMES_TO_RECORD;

    if (!glfwInit()) {
        exit(EXIT_FAILURE);
    }

    window = glfwCreateWindow(1920, 1080, "Voxel Perf", NULL, NULL);

    if (!window) {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glewInit();
    glfwSwapInterval(0);

    glEnable(GL_DEPTH_TEST);
    glCullFace(GL_BACK);
    glEnable(GL_CULL_FACE);
	CheckGLErrors();

    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);
    glClearColor(0.1f, 0.12f, 0.6f, 1.0f);
	CheckGLErrors();

    size_t gpuFreeBefore = GetFreeMemNvidia();
    size_t memUsedBefore = GetMainMemUsage();
    CheckGLErrors();

    setupFn();
    CheckGLErrors();

    glFinish();

    //size_t gpuFreeAfter = GetFreeMemNvidia();
    //size_t memUsedAfter = GetMainMemUsage();

    size_t gpuFreeAfter;
    size_t memUsedAfter;

    double totalFrameTime = 0.0;
    double totalRecordedFrames = frameCount;

    PerfTimer timer;
    timer.Start();
    while (frameCount > 0) {
        double frameTime = timer.Stop();
        timer.Start();
        if (discardFrames == 0) {
            if (frameCount > 0) {
                totalFrameTime += frameTime * 1000.0f;
                frameCount--;
            }
        } else {
            discardFrames--;

            if (discardFrames == 0) {
                gpuFreeAfter = GetFreeMemNvidia();
                memUsedAfter = GetMainMemUsage();
            }
        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        drawFn();
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    teardownFn();

    glfwDestroyWindow(window);
    glfwTerminate();

    PerfRecord record;

    record.averageFrameTimeMs = totalFrameTime / totalRecordedFrames;
    record.gpuMemUsed = gpuFreeBefore - gpuFreeAfter;
    record.mainMemUsed = memUsedAfter - memUsedBefore;

    return record;
}

void CheckGLErrors() {
    GLenum err;
    while ((err = glGetError()) != GL_NO_ERROR) {
        cerr << "OpenGL error: " << err << endl;
    }
}

glm::vec3 CameraPosition() {
    return vec3(-16, 0, -16);
}

mat4 MakeModelView() {
    mat4 view = lookAt(CameraPosition(), vec3(0, 0, 0), vec3(0, 1, 0));
    if (ROTATE) {
        view *= glm::rotate((float)glfwGetTime(), vec3(0, 1, 0));
    }
    return view;
}

mat4 MakeProjection() {
    mat4 projection = perspective(GetFovY(), GetAspectRatio(), 1.0f, 10000.0f);

    return projection;
}

mat4 MakeMvp() {
    return MakeProjection() * MakeModelView();
}

float GetAspectRatio() {
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    return (float)width / (float)height;
}

float GetFovY() {
	return radians(45.0f);
}

glm::vec3 GetNearPlane() {
    float nearZ = 1.0f;

    float top = nearZ / sin(GetFovY());
    float bottom = -top;

    float left = bottom * GetAspectRatio();
    float right = top * GetAspectRatio();

    vec3 nearPlane(right - left, top - bottom, nearZ);
	return nearPlane;
}

void PrintMatrix(glm::mat4 matrix) {
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            if (j > 0) {
                cout << ", ";
            }
            cout << matrix[i][j];
        }
        cout << endl;
    }
}

GLuint MakeShaderProgram(std::vector<std::pair<std::string, GLenum>> shaders) {
    GLuint program = glCreateProgram();

    for (auto& s : shaders) {
        string src = ReadTextFile(s.first);
        GLuint shaderId = glCreateShader(s.second);
        const GLchar* srcGlChar = (const GLchar*)src.c_str();
        glShaderSource(shaderId, 1, &srcGlChar, NULL);

        glCompileShader(shaderId);
        GLint success = 0;
        glGetShaderiv(shaderId, GL_COMPILE_STATUS, &success);

        if (success == GL_FALSE) {
            GLint logSize = 0;
            GLint maxLength = 0;
            glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &maxLength);

            // The maxLength includes the NULL character
            std::vector<GLchar> errorLog(maxLength);
            glGetShaderInfoLog(shaderId, maxLength, &maxLength, &errorLog[0]);
            cerr << "*************************************************" << endl;
            cerr << "Shader \"" << s.first << "\" failed to compile:" << endl;
            cerr << &errorLog[0] << endl;
            cerr << endl;

            glDeleteShader(shaderId);
            glDeleteProgram(program);
            return 0;
        }

        glAttachShader(program, shaderId);
        glDeleteShader(shaderId);
        CheckGLErrors();
    }

    glLinkProgram(program);
    return program;
}

std::string ReadTextFile(std::string filename) {
    ifstream textStream(filename, std::ifstream::in);

    if (textStream.fail()) {
        cerr << "Failed to open file \"" << filename << "\"";
        return{};
    }

    string str(static_cast<stringstream const&>(stringstream() << textStream.rdbuf()).str());
    return str;
}

int Round10BitSigned(float value) {
    if (value < 0) {
        return (int)round(value * 512);
    } else {
        return (int)round(value * 511);
    }
}

int Round2BitSigned(float value) {
    if (value < 0) {
        return (int)round(value * 2);
    } else {
        return (int)round(value * 1);
    }
}

PackedVec PackVec3(vec3 v) {
    PackedVec packed;
    packed.w = 0;
    packed.x = Round10BitSigned(v.x);
    packed.y = Round10BitSigned(v.y);
    packed.z = Round10BitSigned(v.z);
    return packed;
}

PackedVec PackVec4(glm::vec4 v) {
    PackedVec packed;
    packed.w = Round2BitSigned(v.w);
    packed.x = Round10BitSigned(v.x);
    packed.y = Round10BitSigned(v.y);
    packed.z = Round10BitSigned(v.z);
    return packed;
}

PackedColor PackColor(vec3 color) {
    PackedColor packed;
    packed.a = 3;
    packed.r = (unsigned int)(color.r * 1023);
    packed.g = (unsigned int)(color.g * 1023);
    packed.b = (unsigned int)(color.b * 1023);
    return packed;
}

std::map<string, string> g_commandLineOptions;

bool IsOptionSet(std::string optionName) {
	return g_commandLineOptions.count(optionName) > 0;
}

std::string GetOption(std::string optionName) {
	if (g_commandLineOptions.count(optionName) == 0) {
		return "";
	} else {
		return g_commandLineOptions[optionName];
	}
}


text:
package org.elasticsearch.search.aggregations.bucket;

import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentParseException;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.search.aggregations.BaseAggregationTestCase;
import org.elasticsearch.search.aggregations.bucket.range.GeoDistanceAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.range.GeoDistanceAggregationBuilder.Range;
import org.elasticsearch.test.geo.RandomShapeGenerator;

import java.io.IOException;

import static org.hamcrest.Matchers.containsString;

public class GeoDistanceRangeTests extends BaseAggregationTestCase<GeoDistanceAggregationBuilder> {

    @Override
    protected GeoDistanceAggregationBuilder createTestAggregatorBuilder() {
        int numRanges = randomIntBetween(1, 10);
        GeoPoint origin = RandomShapeGenerator.randomPoint(random());
        GeoDistanceAggregationBuilder factory = new GeoDistanceAggregationBuilder("foo", origin);
        for (int i = 0; i < numRanges; i++) {
            String key = null;
            if (randomBoolean()) {
                key = randomAlphaOfLengthBetween(1, 20);
            }
            double from = randomBoolean() ? 0 : randomIntBetween(0, Integer.MAX_VALUE - 1000);
            double to = randomBoolean() ? Double.POSITIVE_INFINITY
                    : (Double.compare(from, 0) == 0 ? randomIntBetween(0, Integer.MAX_VALUE)
                            : randomIntBetween((int) from, Integer.MAX_VALUE));
            factory.addRange(new Range(key, from, to));
        }
        factory.field(randomAlphaOfLengthBetween(1, 20));
        if (randomBoolean()) {
            factory.keyed(randomBoolean());
        }
        if (randomBoolean()) {
            factory.missing("0, 0");
        }
        if (randomBoolean()) {
            factory.unit(randomFrom(DistanceUnit.values()));
        }
        if (randomBoolean()) {
            factory.distanceType(randomFrom(GeoDistance.values()));
        }
        return factory;
    }

    public void testParsingRangeStrict() throws IOException {
        final String rangeAggregation = "{\n" +
                "\"field\" : \"location\",\n" +
                "\"origin\" : \"52.3760, 4.894\",\n" +
                "\"unit\" : \"m\",\n" +
                "\"ranges\" : [\n" +
                "    { \"from\" : 10000, \"to\" : 20000, \"badField\" : \"abcd\" }\n" +
                "]\n" +
            "}";
        XContentParser parser = createParser(JsonXContent.jsonXContent, rangeAggregation);
        XContentParseException ex = expectThrows(XContentParseException.class,
            () -> GeoDistanceAggregationBuilder.parse("aggregationName", parser));
        assertThat(ExceptionsHelper.detailedMessage(ex), containsString("badField"));
    }

    /**
     * We never render "null" values to xContent, but we should test that we can parse them (and they return correct defaults)
     */
    public void testParsingNull() throws IOException {
        final String rangeAggregation = "{\n" +
                "\"field\" : \"location\",\n" +
                "\"origin\" : \"52.3760, 4.894\",\n" +
                "\"unit\" : \"m\",\n" +
                "\"ranges\" : [\n" +
                "    { \"from\" : null, \"to\" : null }\n" +
                "]\n" +
            "}";
        XContentParser parser = createParser(JsonXContent.jsonXContent, rangeAggregation);
        GeoDistanceAggregationBuilder aggregationBuilder = (GeoDistanceAggregationBuilder) GeoDistanceAggregationBuilder
                .parse("aggregationName", parser);
        assertEquals(1, aggregationBuilder.range().size());
        assertEquals(0.0, aggregationBuilder.range().get(0).getFrom(), 0.0);
        assertEquals(Double.POSITIVE_INFINITY, aggregationBuilder.range().get(0).getTo(), 0.0);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.projectlounge.json;

import lombok.Data;

/**
 * Created by main on 24.08.17.
 */
@Data
public class ClientInfo {
    private final String clientId;
    private final String clientVersion;
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace LibOwin.Owin
{
    using System;
    using Shouldly;
    using Xunit;
    using Xunit.Extensions;

    public class QueryStringTests
    {
        [Theory]
        [InlineData("one=two")]
        [InlineData("one=two&three&four=five")]
        [InlineData("/unusual?but#tolerable")]
        [InlineData("/")]
        [InlineData("")]
        [InlineData(null)]
        public void ConstructorAndValuePropertyArePassThrough(string value)
        {
            var queryString = new QueryString(value);
            queryString.Value.ShouldBe(value);
        }

        [Theory]
        [InlineData("one=two", "?one=two")]
        [InlineData("one=two&three&four=five", "?one=two&three&four=five")]
        [InlineData("/unusual?but#tolerable", "?/unusual?but%23tolerable")]
        [InlineData("/", "?/")]
        [InlineData("", "")]
        [InlineData(null, "")]
        public void ToUriComponentWillPrependQueryDelimiterAndEscapeFragmentDelimeter(string value, string uriComponent)
        {
            var queryString = new QueryString(value);
            queryString.ToUriComponent().ShouldBe(uriComponent);
            queryString.ToString().ShouldBe(uriComponent);
        }

        [Theory]
        [InlineData("?one=two", "one=two")]
        [InlineData("???one=two", "??one=two")]
        [InlineData("?one=two&thr$ee&four=five", "one=two&thr$ee&four=five")]
        [InlineData("?one=two&thr%24ee&four=five", "one=two&thr%24ee&four=five")]
        [InlineData("?/unusual?but#tolerable", "/unusual?but#tolerable")]
        [InlineData("?/unusual?but%23tolerable", "/unusual?but%23tolerable")]
        [InlineData("?", "")]
        [InlineData("???", "??")]
        [InlineData("", "")]
        [InlineData(null, "")]
        public void FromUriComponentWillRemoveQueryDelimiterAsAppropriate(string uriComponent, string value)
        {
            var queryString = QueryString.FromUriComponent(uriComponent);
            queryString.Value.ShouldBe(value);
        }

        [Theory]
        [InlineData("http://example.com/?one=two%2B", "one=two%2B")]
        [InlineData("http://example.com/???one=two", "??one=two")]
        [InlineData("http://example.com/?one=two&thr$ee&four=five", "one=two&thr$ee&four=five")]
        [InlineData("http://example.com/?one=two&thr%24ee&four=five", "one=two&thr%24ee&four=five")]
        [InlineData("http://example.com/?/unusual?but#tolerable", "/unusual?but")]
        [InlineData("http://example.com/?/unusual?but%23tolerable", "/unusual?but%23tolerable")]
        [InlineData("http://example.com/?", "")]
        [InlineData("http://example.com/???", "??")]
        [InlineData("http://example.com/", "")]
        [InlineData("http://example.com", "")]
        public void FromUriObjectTakesQueryStringValueAsAppropriate(string uriComponent, string value)
        {
            var queryString = QueryString.FromUriComponent(new Uri(uriComponent));
            queryString.Value.ShouldBe(value);
        }

        [Fact]
        public void LeadingDelimiterIsNotOptionalWhenDataPresent()
        {
            Should.Throw<ArgumentException>(() => QueryString.FromUriComponent("one=two"));
        }
    }
}


text:
/*!
@file
@brief This file contains all of the enums and definitions that are used for the
       CRYS POLY APIs, as well as the APIs themselves.
@defgroup crys_poly CryptoCell POLY APIs
@{
@ingroup cryptocell_api

*/
#ifndef CRYS_POLY_H
#define CRYS_POLY_H

#include "ssi_pal_types.h"
#include "crys_error.h"

#ifdef __cplusplus
extern "C"
{
#endif

/************************ Defines ******************************/
/*! POLY KEY size in words. */
#define CRYS_POLY_KEY_SIZE_IN_WORDS     8
/*! POLY KEY size in bytes. */
#define CRYS_POLY_KEY_SIZE_IN_BYTES     (CRYS_POLY_KEY_SIZE_IN_WORDS*SASI_32BIT_WORD_SIZE)

/*! POLY MAC size in words. */
#define CRYS_POLY_MAC_SIZE_IN_WORDS     4
/*! POLY MAC size in bytes. */
#define CRYS_POLY_MAC_SIZE_IN_BYTES     (CRYS_POLY_MAC_SIZE_IN_WORDS*SASI_32BIT_WORD_SIZE)

/************************ Typedefs  ****************************/

/*! CHACHA MAC buffer definition. */
typedef uint32_t CRYS_POLY_Mac_t[CRYS_POLY_MAC_SIZE_IN_WORDS];

/*! CHACHA key buffer definition. */
typedef uint32_t CRYS_POLY_Key_t[CRYS_POLY_KEY_SIZE_IN_WORDS];

/************************ Public Functions **********************/

/****************************************************************************************************/
/*!
@brief This function is used to perform the POLY MAC Calculation.

@return CRYS_OK on success.
@return A non-zero value on failure as defined crys_poly_error.h.
*/
CIMPORT_C CRYSError_t  CRYS_POLY(
                            CRYS_POLY_Key_t       pKey,            /*!< [in] A pointer to the user's key buffer. */
                uint8_t              *pDataIn,        /*!< [in] A pointer to the buffer of the input data to the CHACHA.
                                                                             must not be null. */
                            size_t                dataInSize,      /*!< [in]  The size of the input data. must not be 0. */
                CRYS_POLY_Mac_t   macRes       /*!< [in/out] Pointer to the MAC result buffer.*/
);

#ifdef __cplusplus
}
#endif
/**
@}
 */
#endif /* #ifndef CRYS_POLY_H */


text:
<?php
class authentications extends controller {
	function authenticatewith( $provider )
	{
		// set on application.config.php
		GLOBAL $hybridauth_config;

		try{
		// create an instance for Hybridauth with the configuration file path as parameter
			$hybridauth = new Hybrid_Auth( $hybridauth_config );

		// try to authenticate the selected $provider
			$adapter = $hybridauth->authenticate( $provider );

		// grab the user profile
			$user_profile = $adapter->getUserProfile();

		// load user and authentication models, we will need them...
			$authentication = $this->loadModel( "authentication" );
			$user = $this->loadModel( "user" );

		# 1 - check if user already have authenticated using this provider before
			$authentication_info = $authentication->find_by_provider_uid( $provider, $user_profile->identifier );

		# 2 - if authentication exists in the database, then we set the user as connected and redirect him to his profile page
			if( $authentication_info ){
				// 2.1 - store user_id in session
				$_SESSION["user"] = $authentication_info["user_id"];

				// 2.2 - redirect to user/profile
				$this->redirect( "users/profile" );
			}

		# 3 - else, here lets check if the user email we got from the provider already exists in our database ( for this example the email is UNIQUE for each user )
			// if authentication does not exist, but the email address returned  by the provider does exist in database,
			// then we tell the user that the email  is already in use
			// but, its up to you if you want to associate the authentication with the user having the adresse email in the database
			if( $user_profile->email ){
				$user_info = $user->find_by_email( $user_profile->email );

				if( $user_info ) {
					die( '
Well! the email returned by the provider ('. $user_profile->email .') already exist in our database, so in this case you might use the Sign-in to login using your email and password.' );
				}
			}

		# 4 - if authentication does not exist and email is not in use, then we create a new user
			$provider_uid  = $user_profile->identifier;
			$email         = $user_profile->email;
			$first_name    = $user_profile->firstName;
			$last_name     = $user_profile->lastName;
			$display_name  = $user_profile->displayName;
			$website_url   = $user_profile->webSiteURL;
			$profile_url   = $user_profile->profileURL;
			$password      = rand( ) ; # for the password we generate something random

			// 4.1 - create new user
			$new_user_id = $user->create( $email, $password, $first_name, $last_name );

			// 4.2 - creat a new authentication for him
			$authentication->create( $new_user_id, $provider, $provider_uid, $email, $display_name, $first_name, $last_name, $profile_url, $website_url );

			// 4.3 - store the new user_id in session
			$_SESSION["user"] = $new_user_id;

			// 4.4 - redirect to user/profile
			$this->redirect( "users/profile" );
		}
		catch( Exception $e ){
			// Display the recived error
			switch( $e->getCode() ){
				case 0 : $error = "Unspecified error."; break;
				case 1 : $error = "Hybriauth configuration error."; break;
				case 2 : $error = "Provider not properly configured."; break;
				case 3 : $error = "Unknown or disabled provider."; break;
				case 4 : $error = "Missing provider application credentials."; break;
				case 5 : $error = "Authentication failed. The user has canceled the authentication or the provider refused the connection."; break;
				case 6 : $error = "User profile request failed. Most likely the user is not connected to the provider and he should to authenticate again.";
					     $adapter->logout();
					     break;
				case 7 : $error = "User not connected to the provider.";
					     $adapter->logout();
					     break;
			}

			// well, basically your should not display this to the end user, just give him a hint and move on..
			$error .= "

Original error message: " . $e->getMessage();
			$error .= "

Trace:
" . $e->getTraceAsString() . "
";

			// load error view
			$data = array( "error" => $error );
			$this->loadView( "pages/error", $data );
		}
	}
}


text:
{# Disabled due to poor support for embeds in feed readers
{% if video.embed %}
<embed src="{{ video.embed.url }}" type="{{ video.embed.type }}">
<noembed>

</noembed>
</embed>
{% elif video.image %}
#}
{% if video.image %}

{% else %}
Video: {{ video.displayName|default(video.url) }}
{% endif %}


text:
<?php
namespace Lawoole\Stream;

use Lawoole\Contracts\Stream\Stream as StreamContract;
use RuntimeException;

class MemoryStream extends Stream implements StreamContract
{
    /**
     * The memory stream.
     *
     * @var resource
     */
    protected $stream;

    /**
     * The size of stream.
     *
     * @var int
     */
    protected $size = 0;

    /**
     * Create a memory stream.
     */
    public function __construct()
    {
        $this->stream = @fopen('php://memory', 'w+');

        if ($this->stream == false) {
            throw new RuntimeException('Cannot open the php://memory stream.');
        }
    }

    /**
     * Return whether the stream is seekable.
     *
     * @return bool
     */
    public function isSeekable()
    {
        return true;
    }

    /**
     * Return whether the pointer is at the end of the stream.
     *
     * @return bool
     */
    public function eof()
    {
        return ! $this->stream || feof($this->stream);
    }

    /**
     * Return the current position of the read/write pointer.
     *
     * @return int|bool
     */
    public function tell()
    {
        return $this->stream ? ftell($this->stream) : false;
    }

    /**
     * Seek to a position in the stream.
     *
     * @param int $offset Stream offset.
     * @param int $whence Specifies how the cursor position will be calculated.
     *
     * @return bool
     */
    public function seek($offset, $whence = SEEK_SET)
    {
        return $this->stream && fseek($this->stream, $offset, $whence) === 0;
    }

    /**
     * Rewind the read/write pointer to the head of the stream.
     *
     * @return bool
     */
    public function rewind()
    {
        return $this->stream && rewind($this->stream);
    }

    /**
     * Get the size of the stream if available.
     *
     * @return int|null
     */
    public function getSize()
    {
        if ($this->size !== null) {
            return $this->size;
        }

        $stats = fstat($this->stream);

        if (isset($stats['size'])) {
            $this->size = $stats['size'];

            return $this->size;
        }

        return null;
    }

    /**
     * Return whether the stream is writable.
     *
     * @return bool
     */
    public function isWritable()
    {
        return true;
    }

    /**
     * Write data to the stream.
     *
     * @param string $string The string that is to be written.
     *
     * @return int|bool
     */
    public function write($string)
    {
        if ($this->stream == null) {
            return false;
        }

        $this->size = null;

        return fwrite($this->stream, $string);
    }

    /**
     * Return whether the stream is readable.
     *
     * @return bool
     */
    public function isReadable()
    {
        return true;
    }

    /**
     * Read data from the stream.
     *
     * @param int $length Length for the data to be read.
     *
     * @return string|bool
     */
    public function read($length)
    {
        return $this->stream ? fread($this->stream, $length) : false;
    }

    /**
     * Return the remaining contents of the stream as a string.
     *
     * @return string
     */
    public function getContents()
    {
        return $this->stream ? (string) stream_get_contents($this->stream) : '';
    }

    /**
     * Attempts to seek to the beginning of the stream and reads all data into
     * a string until the end of the stream is reached.
     *
     * @return string
     */
    public function __toString()
    {
        if ($this->stream == null) {
            return '';
        }

        $this->seek(0);

        return (string) stream_get_contents($this->stream);
    }

    /**
     * Closes the stream and any underlying resources.
     */
    public function close()
    {
        parent::close();

        if ($this->stream) {
            fclose($this->stream);

            $this->stream = null;
            $this->size = 0;
        }
    }

    /**
     * Destroy the memory stream.
     */
    public function __destruct()
    {
        if (! $this->isClosed()) {
            $this->close();
        }
    }
}


text:
#if !defined(_SCHED_H)
#define _SCHED_H

#if defined(_MSC_VER)
#  if _MSC_VER < 1300
#    define PTW32_CONFIG_MSVC6
#  endif
#  if _MSC_VER < 1400
#    define PTW32_CONFIG_MSVC7
#  endif
#endif

#undef PTW32_SCHED_LEVEL

#if defined(_POSIX_SOURCE)
#define PTW32_SCHED_LEVEL 0
/* Early POSIX */
#endif

#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309
#undef PTW32_SCHED_LEVEL
#define PTW32_SCHED_LEVEL 1
/* Include 1b, 1c and 1d */
#endif

#if defined(INCLUDE_NP)
#undef PTW32_SCHED_LEVEL
#define PTW32_SCHED_LEVEL 2
/* Include Non-Portable extensions */
#endif

#define PTW32_SCHED_LEVEL_MAX 3

#if ( defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112 )  || !defined(PTW32_SCHED_LEVEL)
#define PTW32_SCHED_LEVEL PTW32_SCHED_LEVEL_MAX
/* Include everything */
#endif

#if defined(__GNUC__) && !defined(__declspec)
# error Please upgrade your GNU compiler to one that supports __declspec.
#endif

/*
 * When building the library, you should define PTW32_BUILD so that
 * the variables/functions are exported correctly. When using the library,
 * do NOT define PTW32_BUILD, and then the variables/functions will
 * be imported correctly.
 */
#if !defined(PTW32_STATIC_LIB)
#  if defined(PTW32_BUILD)
#    define PTW32_DLLPORT __declspec (dllexport)
#  else
#    define PTW32_DLLPORT __declspec (dllimport)
#  endif
#else
#  define PTW32_DLLPORT
#endif

/*
 * The Open Watcom C/C++ compiler uses a non-standard calling convention
 * that passes function args in registers unless __cdecl is explicitly specified
 * in exposed function prototypes.
 *
 * We force all calls to cdecl even though this could slow Watcom code down
 * slightly. If you know that the Watcom compiler will be used to build both
 * the DLL and application, then you can probably define this as a null string.
 * Remember that sched.h (this file) is used for both the DLL and application builds.
 */
#if !defined(PTW32_CDECL)
# define PTW32_CDECL __cdecl
#endif

/*
 * This is a duplicate of what is in the autoconf config.h,
 * which is only used when building the pthread-win32 libraries.
 */

#if !defined(PTW32_CONFIG_H)
#  if defined(WINCE)
#    define NEED_ERRNO
#    define NEED_SEM
#  endif
#  if defined(__MINGW64__)
#    define HAVE_STRUCT_TIMESPEC
#    define HAVE_MODE_T
#  elif defined(_UWIN) || defined(__MINGW32__)
#    define HAVE_MODE_T
#  endif
#endif

/*
 *
 */

#include <stdlib.h>

#if PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX
#if defined(NEED_ERRNO)
#include "need_errno.h"
#else
#include <errno.h>
#endif
#endif /* PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX */

#if (defined(__MINGW64__) || defined(__MINGW32__)) || defined(_UWIN)
# if PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX
/* For pid_t */
#  include <sys/types.h>
/* Required by Unix 98 */
#  include <time.h>
# else
   typedef int pid_t;
# endif
#else
 /* [i_a] fix for using pthread_win32 with mongoose code, which #define's its own pid_t akin to     typedef HANDLE pid_t; */
 #undef pid_t
# if defined(_MSC_VER)
  typedef void *pid_t;
# else
  typedef int pid_t;
# endif
#endif

/*
 * Microsoft VC++6.0 lacks these *_PTR types
 */
#if defined(_MSC_VER) && _MSC_VER < 1300 && !defined(PTW32_HAVE_DWORD_PTR)
typedef unsigned long ULONG_PTR;
typedef ULONG_PTR DWORD_PTR;
#endif

/* Thread scheduling policies */

enum {
  SCHED_OTHER = 0,
  SCHED_FIFO,
  SCHED_RR,
  SCHED_MIN   = SCHED_OTHER,
  SCHED_MAX   = SCHED_RR
};

struct sched_param {
  int sched_priority;
};

/*
 * CPU affinity
 *
 * cpu_set_t:
 * Considered opaque but cannot be an opaque pointer
 * due to the need for compatibility with GNU systems
 * and sched_setaffinity() et.al. which include the
 * cpusetsize parameter "normally set to sizeof(cpu_set_t)".
 */

#define CPU_SETSIZE (sizeof(size_t)*8)

#define CPU_COUNT(setptr) (_sched_affinitycpucount(setptr))

#define CPU_ZERO(setptr) (_sched_affinitycpuzero(setptr))

#define CPU_SET(cpu, setptr) (_sched_affinitycpuset((cpu),(setptr)))

#define CPU_CLR(cpu, setptr) (_sched_affinitycpuclr((cpu),(setptr)))

#define CPU_ISSET(cpu, setptr) (_sched_affinitycpuisset((cpu),(setptr)))

#define CPU_AND(destsetptr, srcset1ptr, srcset2ptr) (_sched_affinitycpuand((destsetptr),(srcset1ptr),(srcset2ptr)))

#define CPU_OR(destsetptr, srcset1ptr, srcset2ptr) (_sched_affinitycpuor((destsetptr),(srcset1ptr),(srcset2ptr)))

#define CPU_XOR(destsetptr, srcset1ptr, srcset2ptr) (_sched_affinitycpuxor((destsetptr),(srcset1ptr),(srcset2ptr)))

#define CPU_EQUAL(set1ptr, set2ptr) (_sched_affinitycpuequal((set1ptr),(set2ptr)))

typedef union
{
  char cpuset[CPU_SETSIZE/8];
  size_t _align;
} cpu_set_t;

#if defined(__cplusplus)
extern "C"
{
#endif                          /* __cplusplus */

PTW32_DLLPORT int PTW32_CDECL sched_yield (void);

PTW32_DLLPORT int PTW32_CDECL sched_get_priority_min (int policy);

PTW32_DLLPORT int PTW32_CDECL sched_get_priority_max (int policy);

PTW32_DLLPORT int PTW32_CDECL sched_setscheduler (pid_t pid, int policy);

PTW32_DLLPORT int PTW32_CDECL sched_getscheduler (pid_t pid);

/* Compatibility with Linux - not standard */

PTW32_DLLPORT int PTW32_CDECL sched_setaffinity (pid_t pid, size_t cpusetsize, cpu_set_t *mask);

PTW32_DLLPORT int PTW32_CDECL sched_getaffinity (pid_t pid, size_t cpusetsize, cpu_set_t *mask);

/*
 * Support routines and macros for cpu_set_t
 */
PTW32_DLLPORT int PTW32_CDECL _sched_affinitycpucount (const cpu_set_t *set);

PTW32_DLLPORT void PTW32_CDECL _sched_affinitycpuzero (cpu_set_t *pset);

PTW32_DLLPORT void PTW32_CDECL _sched_affinitycpuset (int cpu, cpu_set_t *pset);

PTW32_DLLPORT void PTW32_CDECL _sched_affinitycpuclr (int cpu, cpu_set_t *pset);

PTW32_DLLPORT int PTW32_CDECL _sched_affinitycpuisset (int cpu, const cpu_set_t *pset);

PTW32_DLLPORT void PTW32_CDECL _sched_affinitycpuand(cpu_set_t *pdestset, const cpu_set_t *psrcset1, const cpu_set_t *psrcset2);

PTW32_DLLPORT void PTW32_CDECL _sched_affinitycpuor(cpu_set_t *pdestset, const cpu_set_t *psrcset1, const cpu_set_t *psrcset2);

PTW32_DLLPORT void PTW32_CDECL _sched_affinitycpuxor(cpu_set_t *pdestset, const cpu_set_t *psrcset1, const cpu_set_t *psrcset2);

PTW32_DLLPORT int PTW32_CDECL _sched_affinitycpuequal (const cpu_set_t *pset1, const cpu_set_t *pset2);

/*
 * Note that this macro returns ENOTSUP rather than
 * ENOSYS as might be expected. However, returning ENOSYS
 * should mean that sched_get_priority_{min,max} are
 * not implemented as well as sched_rr_get_interval.
 * This is not the case, since we just don't support
 * round-robin scheduling. Therefore I have chosen to
 * return the same value as sched_setscheduler when
 * SCHED_RR is passed to it.
 */
#define sched_rr_get_interval(_pid, _interval) \
  ( errno = ENOTSUP, (int) -1 )

#if defined(__cplusplus)
}                               /* End of extern "C" */
#endif                          /* __cplusplus */

#undef PTW32_SCHED_LEVEL
#undef PTW32_SCHED_LEVEL_MAX

#endif                          /* !_SCHED_H */


text:
Graphics and Multimedia
---------

**Slide Show** - Make an application that shows various pictures in a slide show format. *Optional: Try adding various effects like fade in/out, star wipe and window blinds transitions.*

**Stream Video from Online** - Try to create your own online streaming video player.

**Mp3 Player** - A simple program for playing your favorite music files. Add features you though are missing from your favorite music player.

**Watermarking Application** - Have some pictures you want copyright protected? Add your own logo or text lightly across the background so that no one can simply steal your graphics off your site. Make a program that will add this watermark to the picture. *Optional: Use threading to process multiple images simultaneously.*

**Turtle Graphics** - This is a common project where you create a floor of 20 x 20 squares. Using various commands you tell a turtle to draw a line on the floor. You have move forward, left or right, lift or drop pen etc. Do a search online for "Turtle Graphics" for more information. *Optional: Allow the program to read in the list of commands from a file.*


text:
from django import forms

from .models.address import Address
from .models.order import Order

class ShippingAddressForm(forms.ModelForm):
    class Meta:
        model = Address
        fields = ['street', 'city', 'postcode', 'country']

class CustomerOrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ['full_name', 'email', 'phone']


text:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

//custom to get rid of create button on events

class SugarWidgetSubPanelTopButton_c extends SugarWidget
{
    var $module;
	var $title;
	var $access_key;
	var $form_value;
	var $additional_form_fields;
	var $acl;

//TODO rename defines to layout defs and make it a member variable instead of passing it multiple layers with extra copying.

	/** Take the keys for the strings and look them up.  Module is literal, the rest are label keys
	*/
	function SugarWidgetSubPanelTopButton($module='', $title='', $access_key='', $form_value='')
	{
		global $app_strings;

		if(is_array($module))
		{
			// it is really the class details from the mapping
			$class_details = $module;

			// If keys were passed into the constructor, translate them from keys to values.
			if(!empty($class_details['module']))
				$this->module = $class_details['module'];
			if(!empty($class_details['title']))
				$this->title = $app_strings[$class_details['title']];
			if(!empty($class_details['access_key']))
				$this->access_key = $app_strings[$class_details['access_key']];
			if(!empty($class_details['form_value']))
				$this->form_value = translate($class_details['form_value'], $this->module);
			if(!empty($class_details['additional_form_fields']))
				$this->additional_form_fields = $class_details['additional_form_fields'];
			if(!empty($class_details['ACL'])){
				$this->acl = $class_details['ACL'];
			}
		}
		else
		{
			$this->module = $module;

			// If keys were passed into the constructor, translate them from keys to values.
			if(!empty($title))
				$this->title = $app_strings[$title];
			if(!empty($access_key))
				$this->access_key = $app_strings[$access_key];
			if(!empty($form_value))
				$this->form_value = translate($form_value, $module);
		}
	}

    public function getWidgetId($buttonSuffix = true)
    {
    	$widgetID = parent::getWidgetId() . '_'.preg_replace('[ ]', '', strtolower($this->form_value));
    	if($buttonSuffix){
    		$widgetID .= '_button';
    	}
        return $widgetID;
    }

    function &_get_form($defines, $additionalFormFields = null, $asUrl = false)
    {
        global $app_strings;
        global $currentModule;

        // Create the additional form fields with real values if they were not passed in
        if(empty($additionalFormFields) && $this->additional_form_fields)
        {
            foreach($this->additional_form_fields as $key=>$value)
            {
                if(!empty($defines['focus']->$value))
                {
                    $additionalFormFields[$key] = $defines['focus']->$value;
                }
                else
                {
                    $additionalFormFields[$key] = '';
                }
            }
        }

		if(!empty($this->module))
        {
            $defines['child_module_name'] = $this->module;
        }
        else
        {
            $defines['child_module_name'] = $defines['module'];
        }

        $defines['parent_bean_name'] = get_class( $defines['focus']);
		$relationship_name = $this->get_subpanel_relationship_name($defines);

        $formValues = array();

        //module_button is used to override the value of module name
        $formValues['module'] = $defines['child_module_name'];
        $formValues[strtolower($defines['parent_bean_name'])."_id"] = $defines['focus']->id;

        if(isset($defines['focus']->name))
        {
            $formValues[strtolower($defines['parent_bean_name'])."_name"] = $defines['focus']->name;
            // #26451,add these fields for custom one-to-many relate field.
            if(!empty($defines['child_module_name'])){
                $formValues[$relationship_name."_name"] = $defines['focus']->name;
            	$childFocusName = !empty($GLOBALS['beanList'][$defines['child_module_name']]) ? $GLOBALS['beanList'][$defines['child_module_name']] : "";
            	if(!empty($GLOBALS['dictionary'][ $childFocusName ]["fields"][$relationship_name .'_name']['id_name'])){
            		$formValues[$GLOBALS['dictionary'][ $childFocusName ]["fields"][$relationship_name .'_name']['id_name']] = $defines['focus']->id;
            	}
            }
        }

        $formValues['return_module'] = $currentModule;

        if($currentModule == 'Campaigns'){
            $formValues['return_action'] = "DetailView";
        }else{
            $formValues['return_action'] = $defines['action'];
            if ( $formValues['return_action'] == 'SubPanelViewer' ) {
                $formValues['return_action'] = 'DetailView';
            }
        }

        $formValues['return_id'] = $defines['focus']->id;
        $formValues['return_relationship'] = $relationship_name;
        switch ( strtolower( $currentModule ) )
        {
            case 'prospects' :
                $name = $defines['focus']->account_name ;
                break ;
            case 'documents' :
                $name = $defines['focus']->document_name ;
                break ;
            case 'kbdocuments' :
                $name = $defines['focus']->kbdocument_name ;
                break ;
            case 'leads' :
            case 'contacts' :
                $name = $defines['focus']->first_name . " " .$defines['focus']->last_name ;
                break ;
            default :
               $name = (isset($defines['focus']->name)) ? $defines['focus']->name : "";
        }
        $formValues['return_name'] = $name;

        // TODO: move this out and get $additionalFormFields working properly
        if(empty($additionalFormFields['parent_type']))
        {
            if($defines['focus']->object_name=='Contact') {
                $additionalFormFields['parent_type'] = 'Accounts';
            }
            else {
                $additionalFormFields['parent_type'] = $defines['focus']->module_dir;
            }
        }
        if(empty($additionalFormFields['parent_name']))
        {
            if($defines['focus']->object_name=='Contact') {
                $additionalFormFields['parent_name'] = $defines['focus']->account_name;
                $additionalFormFields['account_name'] = $defines['focus']->account_name;
            }
            else {
                $additionalFormFields['parent_name'] = $defines['focus']->name;
            }
        }
        if(empty($additionalFormFields['parent_id']))
        {
            if($defines['focus']->object_name=='Contact') {
                $additionalFormFields['parent_id'] = $defines['focus']->account_id;
                $additionalFormFields['account_id'] = $defines['focus']->account_id;
            } else if($defines['focus']->object_name=='Contract') {
            	$additionalFormFields['contract_id'] = $defines['focus']->id;
            } else {
                $additionalFormFields['parent_id'] = $defines['focus']->id;
            }
        }

        if ($defines['focus']->object_name=='Opportunity') {
            $additionalFormFields['account_id'] = $defines['focus']->account_id;
            $additionalFormFields['account_name'] = $defines['focus']->account_name;
        }

        if (!empty($defines['child_module_name']) and $defines['child_module_name']=='Contacts' and !empty($defines['parent_bean_name']) and $defines['parent_bean_name']=='contact' ) {
            if (!empty($defines['focus']->id ) and !empty($defines['focus']->name)) {
                $formValues['reports_to_id'] = $defines['focus']->id;
                $formValues['reports_to_name'] = $defines['focus']->name;
            }
        }
        $formValues['action'] = "EditView";

        if ( $asUrl ) {
            $returnLink = '';
            foreach($formValues as $key => $value ) {
                $returnLink .= $key.'='.$value.'&';
            }
            foreach($additionalFormFields as $key => $value ) {
                $returnLink .= $key.'='.$value.'&';
            }
            $returnLink = rtrim($returnLink,'&');

            return $returnLink;
        } else {

            $form = 'form' . $relationship_name;
            $button = '<form action="index.php" method="post" name="form" id="' . $form . "\">\n";
            foreach($formValues as $key => $value) {
                $button .= "<input type='hidden' name='" . $key . "' value='" . $value . "' />\n";
            }

            // fill in additional form fields for all but action
            foreach($additionalFormFields as $key => $value) {
                if($key != 'action') {
                    $button .= "<input type='hidden' name='" . $key . "' value='" . $value . "' />\n";
                }
            }

        return $button;
        }
    }

	/** This default function is used to create the HTML for a simple button */
	function display($defines, $additionalFormFields = null, $nonbutton = false)
	{
		$temp='';
		$inputID = $this->getWidgetId();

		if(!empty($this->acl) && ACLController::moduleSupportsACL($defines['module'])  &&  !ACLController::checkAccess($defines['module'], $this->acl, true)){
			return $temp;
		}

		global $app_strings;

        if ( isset($_REQUEST['layout_def_key']) && $_REQUEST['layout_def_key'] == 'UserEAPM' ) {
            // Subpanels generally don't go on the editview, so we have to handle this special
            $megaLink = $this->_get_form($defines, $additionalFormFields,true);
            //$button = "<input title='$this->title' accesskey='$this->access_key' class='button' type='submit' name='$inputID' id='$inputID' value='$this->form_value' onclick='javascript:document.location=\"index.php?".$megaLink."\"; return false;'/>";
        } else {
            $button = $this->_get_form($defines, $additionalFormFields);
            //$button .= "<input title='$this->title' accesskey='$this->access_key' class='' type='submit' name='$inputID' id='$inputID' value='$this->form_value' />\n</form>";
            $button .= "\n</form>";
        }

        if ($nonbutton) {
           // $button = "<a onclick=''>$this->form_value";
        }
        return $button;
	}

	/**
	 * Returns a string that is the JSON encoded version of the popup request.
	 * Perhaps this function should be moved to a more globally accessible location?
	 */
	function _create_json_encoded_popup_request($popup_request_data)
	{
	    return json_encode($popup_request_data);
	}

	/**
	 * get_subpanel_relationship_name
	 * Get the relationship name based on the subapnel definition
	 * @param mixed $defines The subpanel definition
	 */
	function get_subpanel_relationship_name($defines) {
		 $relationship_name = '';
		 if(!empty($defines)) {
		 	$relationship_name = isset($defines['module']) ? $defines['module'] : '';
	     	$dataSource = $defines['subpanel_definition']->get_data_source_name(true);
         	if (!empty($dataSource)) {
				$relationship_name = $dataSource;
				//Try to set the relationship name to the real relationship, not the link.
				if (!empty($defines['subpanel_definition']->parent_bean->field_defs[$dataSource])
				 && !empty($defines['subpanel_definition']->parent_bean->field_defs[$dataSource]['relationship']))
				{
					$relationship_name = $defines['subpanel_definition']->parent_bean->field_defs[$dataSource]['relationship'];
				}
			}
		 }
		 return $relationship_name;
	}

}
?>


text:
class Nearest : public HLF::Model
{
    private:

	// Model parameters ////////////////////////////////////////////////////////
	std::vector <MatrixXd> m_data;
	std::vector <VectorXd> m_targets;

	// Training ////////////////////////////////////////////////////////////////
	void train(std::vector <MatrixXd> &data, std::vector <VectorXd> &targets)
	{
		m_data = data;
		m_targets = targets;
	}

	// Inference ///////////////////////////////////////////////////////////////
	VectorXd predict(MatrixXd &sample)
	{
		int neighbour_index = 0;
		double neighbour_cost = +INFINITY;

		// Loop over the dataset
		for (size_t i = 0; i < m_data.size(); i++) {
			double cost = (m_data[i] - sample).squaredNorm();

			if (cost < neighbour_cost) {
				neighbour_index = i;
				neighbour_cost = cost;
			}
		}

		return m_targets[neighbour_index];
	}
};


text: body {background-color: #ffecf0; }


text:
using System.Text.RegularExpressions;
using System.Web;

namespace BoilerPlate.App.Extensions
{
    public static class HttpContextBaseExtension
    {
        public static string Token(this HttpRequestBase httpContext)
        {
            HttpCookie cookie = httpContext.Cookies["token"];

            if (cookie == null)
            {
                return null;
            }

            string token = cookie.Value;

            if (!Regex.IsMatch(token, "^[0-9A-F]{32}$"))
            {
                return null;
            }

            return token;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">Paginize</string>
  <string name="action_about">About</string>
  <string name="test_menu">设置菜单</string>
  <string name="loading">Loading...</string>
  <string name="loading_failed">Loading failed.</string>
  <string name="retry">Retry</string>
</resources>


text:
import json, logging

from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView
from django.views.generic.edit import FormView

from apps.dasforms.utils import get_form, SendFormEmail

class SentPage(TemplateView):
    template_name = "sent.html"

class JsRequiredPage(TemplateView):
    template_name = "jsrequired.html"

class AjaxableResponseMixin(object):
    """
    Mixin to add AJAX (only) support to a form.
    """
    def render_to_json_response(self, context, **response_kwargs):
        data = json.dumps(context)
        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(data, **response_kwargs)

    def form_invalid(self, form):
        # Ajax only
        if self.request.is_ajax():
            return self.render_to_json_response(form.errors, status=400)
        else:
            return HttpResponseRedirect(reverse('jsrequired'))

    def form_valid(self, form):
        """
        Compile and send result to relevant email recipients.
        """
        keys = form.cleaned_data.keys()
        try:
            result = ','.join(["%s:%s" % (k, form.cleaned_data[k]) for k in keys])
        except:
            logger = logging.getLogger('django.request')
            logger.error('FormResult could not be processed properly.')

        sfe = SendFormEmail(form.cleaned_data)
        sfe.send_email()

        if self.request.is_ajax():
            data = {
                'message': 'success',
            }
            return self.render_to_json_response(data)
        else:
            return HttpResponseRedirect(reverse('jsrequired'))

class InstaFormView(AjaxableResponseMixin, FormView):
    """
    Ajax only view.
    """

    def get(self, request, *args, **kwargs):
        """
        Render inline template tag only for form rendering.
        """
        raise Http404

    def get_form_class(self):
        """
        Returns the form class to use in this view.
        """
        formtype = self.kwargs.get('formtype', None)
        try:
            return get_form(formtype)
        except:
            raise Http404


text:
package org.eclipse.wst.json.core.databinding;

import org.eclipse.json.jsonpath.IJSONPath;

public interface IExtendedJSONPath extends IJSONPath {

	boolean isArray(int index);
}


text:
namespace IECorePython
{

void bindFrameListParameter();

}

#endif // IECOREPYTHON_FRAMELISTPARAMETERBINDING_H


text:
module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    module Integrations #:nodoc:
      module Alipay
        autoload :Common, File.dirname(__FILE__) + '/alipay/common'
        autoload :Helper, File.dirname(__FILE__) + '/alipay/helper'
        autoload :Return, File.dirname(__FILE__) + '/alipay/return'
        autoload :Notification, File.dirname(__FILE__) + '/alipay/notification'

        # Set this if you want to change the Alipay test url
        mattr_accessor :test_url

        # Overwrite this if you want to change the Alipay production url
        mattr_accessor :production_url
        self.production_url = 'https://www.alipay.com/cooperate/gateway.do'

        def self.service_url
          mode = ActiveMerchant::Billing::Base.integration_mode
          case mode
          when :production
            self.production_url
          when :test
            self.test_url || self.production_url
          else
            raise StandardError, "Integration mode set to an invalid value: #{mode}"
          end
        end

        def self.notification(post, options = {})
          Notification.new(post)
        end

        def self.return(query_string, options = {})
          Return.new(query_string)
        end
      end
    end
  end
end


text:
package org.ovirt.engine.core.common.businessentities;

public interface Commented {
    String getComment();

    void setComment(String value);
}


text:
"""
Models for tincture.views.generic tests
"""
from sqlalchemy import Column, Integer, String

from tests.db import Base

class Person(Base):
    __tablename__ = 'people'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))


text:
@interface HTTPReverseResponse : NSObject <HTTPResponse>
{
}

@end


text:
import contextlib
import datetime

import mock
from oslo_utils import timeutils
import testscenarios

from neutron.common import constants
from neutron.common import topics
from neutron import context
from neutron.db import agents_db
from neutron.db import agentschedulers_db as sched_db
from neutron.db import models_v2
from neutron.extensions import dhcpagentscheduler
from neutron.scheduler import dhcp_agent_scheduler
from neutron.tests.unit import testlib_api

# Required to generate tests from scenarios. Not compatible with nose.
load_tests = testscenarios.load_tests_apply_scenarios

class TestDhcpSchedulerBaseTestCase(testlib_api.SqlTestCase):

    def setUp(self):
        super(TestDhcpSchedulerBaseTestCase, self).setUp()
        self.ctx = context.get_admin_context()
        self.network = {'id': 'foo_network_id'}
        self.network_id = 'foo_network_id'
        self._save_networks([self.network_id])

    def _get_agents(self, hosts):
        return [
            agents_db.Agent(
                binary='neutron-dhcp-agent',
                host=host,
                topic=topics.DHCP_AGENT,
                configurations="",
                agent_type=constants.AGENT_TYPE_DHCP,
                created_at=timeutils.utcnow(),
                started_at=timeutils.utcnow(),
                heartbeat_timestamp=timeutils.utcnow())
            for host in hosts
        ]

    def _save_agents(self, agents):
        for agent in agents:
            with self.ctx.session.begin(subtransactions=True):
                self.ctx.session.add(agent)

    def _create_and_set_agents_down(self, hosts, down_agent_count=0):
        dhcp_agents = self._get_agents(hosts)
        # bring down the specified agents
        for agent in dhcp_agents[:down_agent_count]:
            old_time = agent['heartbeat_timestamp']
            hour_old = old_time - datetime.timedelta(hours=1)
            agent['heartbeat_timestamp'] = hour_old
            agent['started_at'] = hour_old
        self._save_agents(dhcp_agents)
        return dhcp_agents

    def _save_networks(self, networks):
        for network_id in networks:
            with self.ctx.session.begin(subtransactions=True):
                self.ctx.session.add(models_v2.Network(id=network_id))

    def _test_schedule_bind_network(self, agents, network_id):
        scheduler = dhcp_agent_scheduler.ChanceScheduler()
        scheduler._schedule_bind_network(self.ctx, agents, network_id)
        results = self.ctx.session.query(
            sched_db.NetworkDhcpAgentBinding).filter_by(
            network_id=network_id).all()
        self.assertEqual(len(agents), len(results))
        for result in results:
            self.assertEqual(network_id, result.network_id)

class TestDhcpScheduler(TestDhcpSchedulerBaseTestCase):

    def test_schedule_bind_network_single_agent(self):
        agents = self._create_and_set_agents_down(['host-a'])
        self._test_schedule_bind_network(agents, self.network_id)

    def test_schedule_bind_network_multi_agents(self):
        agents = self._create_and_set_agents_down(['host-a', 'host-b'])
        self._test_schedule_bind_network(agents, self.network_id)

    def test_schedule_bind_network_multi_agent_fail_one(self):
        agents = self._create_and_set_agents_down(['host-a'])
        self._test_schedule_bind_network(agents, self.network_id)
        with mock.patch.object(dhcp_agent_scheduler.LOG, 'info') as fake_log:
            self._test_schedule_bind_network(agents, self.network_id)
            self.assertEqual(1, fake_log.call_count)

class TestAutoScheduleNetworks(TestDhcpSchedulerBaseTestCase):
    """Unit test scenarios for ChanceScheduler.auto_schedule_networks.

    network_present
        Network is present or not

    enable_dhcp
        Dhcp is enabled or disabled in the subnet of the network

    scheduled_already
        Network is already scheduled to the agent or not

    agent_down
        Dhcp agent is down or alive

    valid_host
        If true, then an valid host is passed to schedule the network,
        else an invalid host is passed.
    """
    scenarios = [
        ('Network present',
         dict(network_present=True,
              enable_dhcp=True,
              scheduled_already=False,
              agent_down=False,
              valid_host=True)),

        ('No network',
         dict(network_present=False,
              enable_dhcp=False,
              scheduled_already=False,
              agent_down=False,
              valid_host=True)),

        ('Network already scheduled',
         dict(network_present=True,
              enable_dhcp=True,
              scheduled_already=True,
              agent_down=False,
              valid_host=True)),

        ('Agent down',
         dict(network_present=True,
              enable_dhcp=True,
              scheduled_already=False,
              agent_down=False,
              valid_host=True)),

        ('dhcp disabled',
         dict(network_present=True,
              enable_dhcp=False,
              scheduled_already=False,
              agent_down=False,
              valid_host=False)),

        ('Invalid host',
         dict(network_present=True,
              enable_dhcp=True,
              scheduled_already=False,
              agent_down=False,
              valid_host=False)),
    ]

    def test_auto_schedule_network(self):
        plugin = mock.MagicMock()
        plugin.get_subnets.return_value = (
            [{"network_id": self.network_id, "enable_dhcp": self.enable_dhcp}]
            if self.network_present else [])
        scheduler = dhcp_agent_scheduler.ChanceScheduler()
        if self.network_present:
            down_agent_count = 1 if self.agent_down else 0
            agents = self._create_and_set_agents_down(
                ['host-a'], down_agent_count=down_agent_count)
            if self.scheduled_already:
                self._test_schedule_bind_network(agents, self.network_id)

        expected_result = (self.network_present and self.enable_dhcp)
        expected_hosted_agents = (1 if expected_result and
                                  self.valid_host else 0)
        host = "host-a" if self.valid_host else "host-b"
        observed_ret_value = scheduler.auto_schedule_networks(
            plugin, self.ctx, host)
        self.assertEqual(expected_result, observed_ret_value)
        hosted_agents = self.ctx.session.query(
            sched_db.NetworkDhcpAgentBinding).all()
        self.assertEqual(expected_hosted_agents, len(hosted_agents))

class TestNetworksFailover(TestDhcpSchedulerBaseTestCase,
                           sched_db.DhcpAgentSchedulerDbMixin):
    def test_reschedule_network_from_down_agent(self):
        agents = self._create_and_set_agents_down(['host-a', 'host-b'], 1)
        self._test_schedule_bind_network([agents[0]], self.network_id)
        self._save_networks(["foo-network-2"])
        self._test_schedule_bind_network([agents[1]], "foo-network-2")
        with contextlib.nested(
            mock.patch.object(self, 'remove_network_from_dhcp_agent'),
            mock.patch.object(self, 'schedule_network',
                              return_value=[agents[1]]),
            mock.patch.object(self, 'get_network', create=True,
                              return_value={'id': self.network_id})
        ) as (rn, sch, getn):
            notifier = mock.MagicMock()
            self.agent_notifiers[constants.AGENT_TYPE_DHCP] = notifier
            self.remove_networks_from_down_agents()
            rn.assert_called_with(mock.ANY, agents[0].id, self.network_id)
            sch.assert_called_with(mock.ANY, {'id': self.network_id})
            notifier.network_added_to_agent.assert_called_with(
                mock.ANY, self.network_id, agents[1].host)

    def _test_failed_rescheduling(self, rn_side_effect=None):
        agents = self._create_and_set_agents_down(['host-a'], 1)
        self._test_schedule_bind_network([agents[0]], self.network_id)
        with contextlib.nested(
            mock.patch.object(
                self, 'remove_network_from_dhcp_agent',
                side_effect=rn_side_effect),
            mock.patch.object(self, 'schedule_network',
                              return_value=None),
            mock.patch.object(self, 'get_network', create=True,
                              return_value={'id': self.network_id})
        ) as (rn, sch, getn):
            notifier = mock.MagicMock()
            self.agent_notifiers[constants.AGENT_TYPE_DHCP] = notifier
            self.remove_networks_from_down_agents()
            rn.assert_called_with(mock.ANY, agents[0].id, self.network_id)
            sch.assert_called_with(mock.ANY, {'id': self.network_id})
            self.assertFalse(notifier.network_added_to_agent.called)

    def test_reschedule_network_from_down_agent_failed(self):
        self._test_failed_rescheduling()

    def test_reschedule_network_from_down_agent_concurrent_removal(self):
        self._test_failed_rescheduling(
            rn_side_effect=dhcpagentscheduler.NetworkNotHostedByDhcpAgent(
                network_id='foo', agent_id='bar'))

    def test_filter_bindings(self):
        bindings = [
            sched_db.NetworkDhcpAgentBinding(network_id='foo1',
                                             dhcp_agent={'id': 'id1'}),
            sched_db.NetworkDhcpAgentBinding(network_id='foo2',
                                             dhcp_agent={'id': 'id1'}),
            sched_db.NetworkDhcpAgentBinding(network_id='foo3',
                                             dhcp_agent={'id': 'id2'}),
            sched_db.NetworkDhcpAgentBinding(network_id='foo4',
                                             dhcp_agent={'id': 'id2'})]
        with mock.patch.object(self, 'agent_starting_up',
                               side_effect=[True, False]):
            res = [b for b in self._filter_bindings(None, bindings)]
            # once per each agent id1 and id2
            self.assertEqual(2, len(res))
            res_ids = [b.network_id for b in res]
            self.assertIn('foo3', res_ids)
            self.assertIn('foo4', res_ids)

    def test_remove_networks_from_down_agents_catches_all(self):
        with contextlib.nested(
            mock.patch.object(
                self, 'remove_network_from_dhcp_agent',
                side_effect=Exception("Unexpected exception!")),
            mock.patch.object(
                self, '_filter_bindings',
                return_value=[sched_db.NetworkDhcpAgentBinding(
                                  network_id='foo', dhcp_agent_id='bar')])
        ):
            self.remove_networks_from_down_agents()


text:
package com.fuzz.emptyhusk.looping;

import android.database.DataSetObserver;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;

import com.fuzz.indicator.proxy.IndicatorOffsetEvent;
import com.fuzz.indicator.proxy.ProxyReference;
import com.fuzz.indicator.proxy.StateProxy;

import java.lang.ref.WeakReference;
import java.util.Map;

/**
 * This StateProxy works much like an automaton - it announces positions from 0 to
 * {@link #getCellCount()} in increments of {@link #DIFF} every
 * {@link #DELAY_MILLIS} milliseconds.
 *
 * @author Philip Cohn-Cort (Fuzz)
 */
public class LoopingStateProxy implements StateProxy {

    public static final long DELAY_MILLIS = 100L;
    public static final float DIFF = .01f;

    /**
     * This thread is where the {@link LoopingRunnable} gets run
     */
    @NonNull
    protected final LoopingThread preferredMailThread = new LoopingThread();

    /**
     * Initialize as half of {@link #getCellCount()}.
     */
    protected float currentPosition = getCellCount() / 2.0f;

    protected final Map<Integer, Runnable> callbacks = new ArrayMap<>();

    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    public LoopingStateProxy() {
        preferredMailThread.start();
    }

    @Override
    public float getCurrentPosition() {
        return currentPosition;
    }

    @Override
    public int getCellCount() {
        return 3;
    }

    @Override
    public IndicatorOffsetEvent resendPositionInfo(ProxyReference cvi, float assumedIndicatorPosition) {
        return IndicatorOffsetEvent.from(cvi, assumedIndicatorPosition);
    }

    @Override
    public void associateWith(DataSetObserver observer) {
        Runnable runnable = new LoopingRunnable(observer);
        callbacks.put(observer.hashCode(), runnable);
        preferredMailThread.repost(runnable, DELAY_MILLIS);
    }

    @Override
    public void disassociateFrom(DataSetObserver observer) {
        Runnable removed = callbacks.remove(observer.hashCode());
        preferredMailThread.stopPosting(removed);
    }

    @Override
    public boolean canObserve(DataSetObserver observer) {
        return observer != null;
    }

    /**
     * Simple runnable that
     *

     *
Updates {@link #currentPosition}

     *
Checks whether {@link LoopingRunnable#o} has been garbage-collected
     *

     *
If so, it sends itself into {@link LoopingThread#stopPosting(Runnable)}

     *
If not, it calls {@link DataSetObserver#onChanged()} and
     *             {@link LoopingThread#repost(Runnable, long) reposts} itself

     *

     *

     *

     * @see #DELAY_MILLIS
     */
    private class LoopingRunnable implements Runnable {
        private final WeakReference<DataSetObserver> o;

        public LoopingRunnable(DataSetObserver observer) {
            this.o = new WeakReference<>(observer);
        }

        @Override
        public void run() {
            currentPosition += DIFF;
            currentPosition %= (getCellCount() * 1.0f);

            final DataSetObserver ref = o.get();
            if (ref != null) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        ref.onChanged();
                    }
                });
                preferredMailThread.repost(this, DELAY_MILLIS);
            } else {
                preferredMailThread.stopPosting(this);
            }
        }
    }
}


text:
Packaging [winston-keenio](https://github.com/mstn/winston-keenio) for [Meteor.js](http://meteor.com).

# Meteor

If you're new to Meteor, here's what the excitement is all about -
[watch the first two minutes](https://www.youtube.com/watch?v=fsi0aJ9yr2o); you'll be hooked by 1:28.

That screencast is from 2012. In the meantime, Meteor has become a mature JavaScript-everywhere web
development framework. Read more at [Why Meteor](http://www.meteorpedia.com/read/Why_Meteor).


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="KlyphMessenger.Dark.Button" parent="KlyphMessenger.Button">
        <item name="android:background">@drawable/btn_default_holo_light_blue</item>
    </style>

    <style name="KlyphMessenger.Dark.Button.Borderless">
        <item name="android:background">?android:attr/selectableItemBackground</item>
    </style>

</resources>


text:
angular.module('WaffleApp').controller('mainCtrl', [ 'UserStateService', function(userStateService) {
	this.userState = userStateService.state;
} ]);


text:
'use strict';

describe('Stimuli.shared.Viewport', function() {

    var stimuli, viewport;

    before(function(done) {
        stimuli = (new Stimuli);
        stimuli
        .browser
            .navigateTo('/base/test/fixtures/divinfront.html')
            .then(function() {
                viewport = this.viewport;
                done();
            });
    });

    after(function() {
        stimuli.destroy();
        viewport = null;
    });

    describe('getVisibleElementAt', function() {

        it('should find the #yellow_10x10_10x10 element at coordinates 19, 19', function() {
            var el = viewport.$('#yellow');
            expect(viewport.getVisibleElementAt(10, 10)).to.be(el);
            expect(viewport.getVisibleElementAt(10, 11)).to.be(el);
            expect(viewport.getVisibleElementAt(19, 10)).to.be(el);
            expect(viewport.getVisibleElementAt(19, 19)).to.be(el);
        });

        it('should find the edges of blue', function() {
            var el = viewport.$('#blue');

            expect(viewport.getVisibleElementAt(0, 0)).to.be(el);
            expect(viewport.getVisibleElementAt(0, 49)).to.be(el);
            expect(viewport.getVisibleElementAt(49, 0)).to.be(el);
            expect(viewport.getVisibleElementAt(49, 49)).to.be(el);
        });

    });

});