text:
#pragma once
#include <aws/kinesisanalyticsv2/KinesisAnalyticsV2_EXPORTS.h>
#include <aws/kinesisanalyticsv2/model/RecordFormat.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/kinesisanalyticsv2/model/RecordColumn.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace KinesisAnalyticsV2
{
namespace Model
{

  /**
   *
Describes updates for an SQL-based Kinesis Data Analytics application's input
   * schema.

See Also:
   AWS
   * API Reference

   */
  class AWS_KINESISANALYTICSV2_API InputSchemaUpdate
  {
  public:
    InputSchemaUpdate();
    InputSchemaUpdate(Aws::Utils::Json::JsonView jsonValue);
    InputSchemaUpdate& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Specifies the format of the records on the streaming source.

     */
    inline const RecordFormat& GetRecordFormatUpdate() const{ return m_recordFormatUpdate; }

    /**
     *
Specifies the format of the records on the streaming source.

     */
    inline bool RecordFormatUpdateHasBeenSet() const { return m_recordFormatUpdateHasBeenSet; }

    /**
     *
Specifies the format of the records on the streaming source.

     */
    inline void SetRecordFormatUpdate(const RecordFormat& value) { m_recordFormatUpdateHasBeenSet = true; m_recordFormatUpdate = value; }

    /**
     *
Specifies the format of the records on the streaming source.

     */
    inline void SetRecordFormatUpdate(RecordFormat&& value) { m_recordFormatUpdateHasBeenSet = true; m_recordFormatUpdate = std::move(value); }

    /**
     *
Specifies the format of the records on the streaming source.

     */
    inline InputSchemaUpdate& WithRecordFormatUpdate(const RecordFormat& value) { SetRecordFormatUpdate(value); return *this;}

    /**
     *
Specifies the format of the records on the streaming source.

     */
    inline InputSchemaUpdate& WithRecordFormatUpdate(RecordFormat&& value) { SetRecordFormatUpdate(std::move(value)); return *this;}

    /**
     *
Specifies the encoding of the records in the streaming source; for example,
     * UTF-8.

     */
    inline const Aws::String& GetRecordEncodingUpdate() const{ return m_recordEncodingUpdate; }

    /**
     *
Specifies the encoding of the records in the streaming source; for example,
     * UTF-8.

     */
    inline bool RecordEncodingUpdateHasBeenSet() const { return m_recordEncodingUpdateHasBeenSet; }

    /**
     *
Specifies the encoding of the records in the streaming source; for example,
     * UTF-8.

     */
    inline void SetRecordEncodingUpdate(const Aws::String& value) { m_recordEncodingUpdateHasBeenSet = true; m_recordEncodingUpdate = value; }

    /**
     *
Specifies the encoding of the records in the streaming source; for example,
     * UTF-8.

     */
    inline void SetRecordEncodingUpdate(Aws::String&& value) { m_recordEncodingUpdateHasBeenSet = true; m_recordEncodingUpdate = std::move(value); }

    /**
     *
Specifies the encoding of the records in the streaming source; for example,
     * UTF-8.

     */
    inline void SetRecordEncodingUpdate(const char* value) { m_recordEncodingUpdateHasBeenSet = true; m_recordEncodingUpdate.assign(value); }

    /**
     *
Specifies the encoding of the records in the streaming source; for example,
     * UTF-8.

     */
    inline InputSchemaUpdate& WithRecordEncodingUpdate(const Aws::String& value) { SetRecordEncodingUpdate(value); return *this;}

    /**
     *
Specifies the encoding of the records in the streaming source; for example,
     * UTF-8.

     */
    inline InputSchemaUpdate& WithRecordEncodingUpdate(Aws::String&& value) { SetRecordEncodingUpdate(std::move(value)); return *this;}

    /**
     *
Specifies the encoding of the records in the streaming source; for example,
     * UTF-8.

     */
    inline InputSchemaUpdate& WithRecordEncodingUpdate(const char* value) { SetRecordEncodingUpdate(value); return *this;}

    /**
     *
A list of RecordColumn objects. Each object describes the
     * mapping of the streaming source element to the corresponding column in the
     * in-application stream.

     */
    inline const Aws::Vector<RecordColumn>& GetRecordColumnUpdates() const{ return m_recordColumnUpdates; }

    /**
     *
A list of RecordColumn objects. Each object describes the
     * mapping of the streaming source element to the corresponding column in the
     * in-application stream.

     */
    inline bool RecordColumnUpdatesHasBeenSet() const { return m_recordColumnUpdatesHasBeenSet; }

    /**
     *
A list of RecordColumn objects. Each object describes the
     * mapping of the streaming source element to the corresponding column in the
     * in-application stream.

     */
    inline void SetRecordColumnUpdates(const Aws::Vector<RecordColumn>& value) { m_recordColumnUpdatesHasBeenSet = true; m_recordColumnUpdates = value; }

    /**
     *
A list of RecordColumn objects. Each object describes the
     * mapping of the streaming source element to the corresponding column in the
     * in-application stream.

     */
    inline void SetRecordColumnUpdates(Aws::Vector<RecordColumn>&& value) { m_recordColumnUpdatesHasBeenSet = true; m_recordColumnUpdates = std::move(value); }

    /**
     *
A list of RecordColumn objects. Each object describes the
     * mapping of the streaming source element to the corresponding column in the
     * in-application stream.

     */
    inline InputSchemaUpdate& WithRecordColumnUpdates(const Aws::Vector<RecordColumn>& value) { SetRecordColumnUpdates(value); return *this;}

    /**
     *
A list of RecordColumn objects. Each object describes the
     * mapping of the streaming source element to the corresponding column in the
     * in-application stream.

     */
    inline InputSchemaUpdate& WithRecordColumnUpdates(Aws::Vector<RecordColumn>&& value) { SetRecordColumnUpdates(std::move(value)); return *this;}

    /**
     *
A list of RecordColumn objects. Each object describes the
     * mapping of the streaming source element to the corresponding column in the
     * in-application stream.

     */
    inline InputSchemaUpdate& AddRecordColumnUpdates(const RecordColumn& value) { m_recordColumnUpdatesHasBeenSet = true; m_recordColumnUpdates.push_back(value); return *this; }

    /**
     *
A list of RecordColumn objects. Each object describes the
     * mapping of the streaming source element to the corresponding column in the
     * in-application stream.

     */
    inline InputSchemaUpdate& AddRecordColumnUpdates(RecordColumn&& value) { m_recordColumnUpdatesHasBeenSet = true; m_recordColumnUpdates.push_back(std::move(value)); return *this; }

  private:

    RecordFormat m_recordFormatUpdate;
    bool m_recordFormatUpdateHasBeenSet;

    Aws::String m_recordEncodingUpdate;
    bool m_recordEncodingUpdateHasBeenSet;

    Aws::Vector<RecordColumn> m_recordColumnUpdates;
    bool m_recordColumnUpdatesHasBeenSet;
  };

} // namespace Model
} // namespace KinesisAnalyticsV2
} // namespace Aws


text:
package org.xdi.oxauth.model.token;

import org.xdi.oxauth.model.error.IErrorType;

/**
 * @author Javier Rojas Blum Date: 10.27.2011
 */
public enum ValidateTokenErrorResponseType implements IErrorType {
    /**
     * The request is missing a required parameter, includes an unsupported
     * parameter or parameter value, repeats a parameter, includes multiple
     * credentials, utilizes more than one mechanism for authenticating the
     * client, or is otherwise malformed.
     */
    INVALID_REQUEST("invalid_request"),
    /**
     * The provided access token is invalid, or was issued to another client.
     */
    INVALID_GRANT("invalid_grant");

    private final String paramName;

    private ValidateTokenErrorResponseType(String paramName) {
        this.paramName = paramName;
    }

    public static ValidateTokenErrorResponseType fromString(String param) {
        if (param != null) {
            for (ValidateTokenErrorResponseType err : ValidateTokenErrorResponseType
                    .values()) {
                if (param.equals(err.paramName)) {
                    return err;
                }
            }
        }
        return null;
    }

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

    @Override
    public String getParameter() {
        return paramName;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Patterns\Creational;

final class Infrutifera{

	private function __construct(){

	}

}


text:
namespace v8_webgl {

class WebGLFramebuffer : public WebGLObject<WebGLFramebuffer, GLuint> {
 public:
  static const char* const ClassName() { return "WebGLFramebuffer"; }

 protected:
  WebGLFramebuffer(WebGLRenderingContext* context, GLuint framebuffer_id)
      : WebGLObject<WebGLFramebuffer, GLuint>(context, framebuffer_id) {}

  friend class WebGLRenderingContext;
};

}

#endif


text:
using Demo.Domain.Configuration.AccountType.Events;
using Demo.Library.Extensions;
using Demo.Library.SSE;
using Nest;
using NServiceBus;
using System;

namespace Demo.Application.ServiceStack.Configuration.AccountType.Handlers
{
    public class Index :
        IHandleMessages<Created>,
        IHandleMessages<Destroyed>,
        IHandleMessages<NameChanged>,
        IHandleMessages<DeferralChanged>
    {
        private readonly IElasticClient _elastic;
        private readonly ISubscriptionManager _manager;

        public Index(IElasticClient elastic, ISubscriptionManager manager)
        {
            _elastic = elastic;
            _manager = manager;
        }

        public void Handle(Created e)
        {
            var index = new Responses.Index
            {
                Id = e.AccountTypeId,
                Name = e.Name,
                DeferralMethod = e.DeferralMethod,
                ParentId = e.ParentId,
            };
            var status = _elastic.Index(index);
        }

        public void Handle(Destroyed e)
        {
            _elastic.Delete<Responses.Index>(e.AccountTypeId);
        }

        public void Handle(NameChanged e)
        {
            _elastic.Update<Responses.Index, Object>(x => x
                .Id(e.AccountTypeId)
                .Doc(new { Name = e.Name })
                .RetryOnConflict(3)
                .Refresh()
                );
        }

        public void Handle(DeferralChanged e)
        {
            _elastic.Update<Responses.Index, Object>(x => x
                .Id(e.AccountTypeId)
                .Doc(new { DeferralMethod = e.DeferralMethod })
                .RetryOnConflict(3)
                .Refresh()
                );
        }
    }
}


text:
We are a team based in the [School of Computing, National University of Singapore](http://www.comp.nus.edu.sg).

## Project Team

#### [Kelly Li](http://github.com/kellyli)

 Roles: Deliverables and Deadlines, Scheduling and Task Tracking, GUI Component Lead

 Responsibilities: Ensure project deliverables are done on time and in the right format. In charge of defining, assigning, and tracking project tasks. Oversees the development of the GUI component.

#### [Joshua Ching](http://github.com/joshuaching)

 Roles: Team Lead, Testing Lead, Model Component Lead

 Responsibilities: Responsible for overall project coordination. Ensures the testing of the project is done properly and on time. Oversees the development of the model component.

#### [Evan Yeung](http://github.com/evanyeung)

 Roles: Integration, Code quality, Storage Component Lead

 Responsibilities: In charge of versioning of the code, maintaining the code repository, integrating various parts of the software to create a whole. Looks after code quality, ensures adherence to coding standards, etc. Oversees the development of the storage component.

#### [Matt Ye](https://github.com/yefenyi)

Roles: Documentation, Git Expert, Eclipse Expert

Responsibilities: Responsible for the quality of various project documents. Expert in Git and Eclipse.

 -----

# Contributors

We welcome contributions. See [Contact Us](ContactUs.md) page for more info.

* [Akshay Narayan](https://github.com/se-edu/addressbook-level4/pulls?q=is%3Apr+author%3Aokkhoy)
* [Sam Yong](https://github.com/se-edu/addressbook-level4/pulls?q=is%3Apr+author%3Amauris)


text:
"""
models.py

User module models.
"""
from app.mod_auth.models import MyAdventure

api = MyAdventure()

class User:
    email = None
    facebook_id = None
    name = None

    def __init__(self, user_id):
        self.id = user_id

    @property
    def is_active(self):
        return True

    @property
    def is_authenticated(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        try:
            return unicode(self.id)
        except AttributeError:
            raise NotImplementedError('No `id` attribute - override `get_id`')


text:
package com.networknt.eventuate.customer.command.handler;

import com.networknt.client.Http2Client;
import com.networknt.eventuate.account.common.model.customer.Address;
import com.networknt.eventuate.account.common.model.customer.CustomerInfo;
import com.networknt.eventuate.account.common.model.customer.Name;
import com.networknt.eventuate.account.common.model.customer.UserCredentials;
import com.networknt.eventuate.common.impl.JSonMapper;
import com.networknt.exception.ApiException;
import com.networknt.exception.ClientException;
import io.undertow.UndertowOptions;
import io.undertow.client.ClientConnection;
import io.undertow.client.ClientRequest;
import io.undertow.client.ClientResponse;
import io.undertow.util.Headers;
import io.undertow.util.Methods;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xnio.IoUtils;
import org.xnio.OptionMap;

import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

public class CreatecustomerPostHandlerTest {
    @ClassRule
    public static TestServer server = TestServer.getInstance();

    static final Logger logger = LoggerFactory.getLogger(CreatecustomerPostHandlerTest.class);
    static final boolean enableHttp2 = server.getServerConfig().isEnableHttp2();
    static final boolean enableHttps = server.getServerConfig().isEnableHttps();
    static final int httpPort = server.getServerConfig().getHttpPort();
    static final int httpsPort = server.getServerConfig().getHttpsPort();
    static final String url = enableHttp2 || enableHttps ? "https://localhost:" + httpsPort : "http://localhost:" + httpPort;

    @Test
    public void testCreatecustomerPostHandlerTest() throws ClientException, ApiException {

        final Http2Client client = Http2Client.getInstance();
        final CountDownLatch latch = new CountDownLatch(1);
        final ClientConnection connection;
        try {
            connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true): OptionMap.EMPTY).get();
        } catch (Exception e) {
            throw new ClientException(e);
        }
        final AtomicReference<ClientResponse> reference = new AtomicReference<>();
        Name name = new Name("Google", "Com");
        Address address = new Address("Yonge St" , "2556 unit", "toronto", "ON", "Canada", "L3R, 5F5");
        UserCredentials userCredentials = new UserCredentials ("aaa.bbb@google.com", "password");
        CustomerInfo customerInfo = new CustomerInfo(name, userCredentials, "9999999999", "4166666666", address);

        String json = JSonMapper.toJson(customerInfo);
        try {
            ClientRequest request = new ClientRequest().setPath("/v1/createcustomer").setMethod(Methods.POST);

            request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
            request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
            connection.sendRequest(request, client.createClientCallback(reference, latch, json));

            latch.await();
        } catch (Exception e) {
            logger.error("Exception: ", e);
            throw new ClientException(e);
        } finally {
            IoUtils.safeClose(connection);
        }
        int statusCode = reference.get().getResponseCode();
        String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
        System.out.println("response:" + body);
        Assert.assertEquals(200, statusCode);
        Assert.assertNotNull(body);

    }
}


text:
function hidepop(){
  $("#popup").fadeOut("slow");
}

function showpop(){
  $("#popup").fadeIn("slow");
  setTimeout("hidepop()",12000);
}

$(function() {

  $(window).bind('hashchange', function() {

    var hash = window.location.hash.substring(1);

    $("nav li").removeClass("active");
    $("html").scrollTop();
    $("window").scrollTop();

    if(window.location.hash != ""){
      $("main").load(hash);
    }else{
      window.location.hash = "#pages";
    }
    $("nav a[href='" + window.location.hash + "']").parent().addClass("active");
  });

$(window).trigger('hashchange');

$("nav li").removeClass("active");
$("nav a[href='" + window.location.hash + "']").parent().addClass("active");

});


text:
default['autoconf']['version']   = '2.69'
default['autoconf']['url']       = "http://ftp.gnu.org/gnu/autoconf/autoconf-#{node['autoconf']['version']}.tar.gz"
default['autoconf']['make_opts'] = %w{ -j2 }


text:
"""
Author: Marusa Zerjal, 2019 - 08 - 21

Manage background overlaps:
Prepare list of stars that don't have component overlaps yet
Compute bg ols with the external code (multiprocessing)
Insert bg ols back into the file
"""

import numpy as np
from astropy.table import Table
import sys

sys.path.insert(0, '/Users/marusa/chronostar/')
from chronostar import tabletool
from astropy.table import Table, vstack

def prepare_stars_that_need_bg_ols():
    """
    Bg ols for some stars have been computed in the earlier analyses. Use these bg ols and insert them into the table.
    Find stars that don't have bg ols yet.
    """

    wanted = Table.read(
        '/priv/mulga1/marusa/chronostar_projects/solar_neighbourhood/data/ScoCen_box_result_15M_ready_for_bg_ols.fits')

    old = Table.read('../scocen/data/data_table_cartesian_including_tims_stars_with_bg_ols_and_component_overlaps.fits')
    old_scocen = Table.read(
        '/priv/mulga1/marusa/chronostar_projects/scocen/data/scocen_candidates_300k_only_spatial_cut.fits')

    old_solar_neighbourhood_bg_ols = np.loadtxt('bgols_multiprocessing_0.dat')
    wanted0 = wanted[:len(old_solar_neighbourhood_bg_ols)]

    # DELETE THIS!!!
    wanted = wanted[len(old_solar_neighbourhood_bg_ols):]

    mask = np.in1d(wanted['source_id'], old['source_id'])
    mask = np.logical_or(mask, np.in1d(wanted['source_id'], old_scocen['source_id']))
    # ~ mask = np.logical_or(mask, np.in1d(wanted['source_id'], old_solar_neighbourhood['source_id']))

    # Looking for stars that do NOT have bg ols yet
    mask = ~mask

    todo = wanted[mask]
    print
    len(todo)
    print
    len(old), len(wanted), len(wanted) - len(old)

    todo.write('solar_neighbourhood_determine_bg_ols_for_these_stars.fits', format='fits')

def match_bg_ols_from_textfile_and_sobject_id():
    n = [0, 1, 2, 3]  # filenumbers

    datafile = 'solar_neighbourhood_determine_bg_ols_for_these_stars.fits'
    data0 = Table.read(datafile)
    N = 10  # that many chunks. DON'T CHANGE THIS, this number should be the same as in the bg_ols_multiprocessing.py!!
    indices_chunks = np.array_split(range(len(data)), N)

    for NI in n:
        bg_ols_filename = 'bgols_multiprocessing_round2_%d.dat' % NI
        bgols = np.loadtxt(bg_ols_filename)

        data = data0[indices_chunks[NI]]
        ids = data['source_id']

        print
        len(bgols), len(ids)

        if NI == 0:
            tab = Table([ids], names=['source_id'])
            tab['background_log_overlap'] = bgols
        else:
            tab0 = Table([ids], names=['source_id'])
            tab0['background_log_overlap'] = bgols

            tab = vstack([tab, tab0])

    print tab

def insert_bg_ols_into_table():
    bg_ols_filename = 'bgols_multiprocessing_0.dat'
    ln_bg_ols = np.loadtxt(bg_ols_filename)

    #    for

    datafile = 'data/ScoCen_box_result_15M_ready_for_bg_ols.fits'
    data_table = Table.read(datafile)

    bg_lnol_colname = 'background_log_overlap'
    print('Background overlaps: insert column')
    tabletool.insert_column(data_table, ln_bg_ols, bg_lnol_colname, filename=datafile)

    print('Print bg ols to cartesian table')
    data_table.write(datafile, overwrite=True, format='fits')

def merge_both_tables():
    """
    Use bg ols from 'old' and 'additional' to insert into 'wanted'.
    """
    old = Table.read('data/data_table_cartesian_including_tims_stars_with_bg_ols_and_component_overlaps.fits')
    wanted = Table.read('data/scocen_candidates_300k_only_spatial_cut.fits')
    additional = Table.read('data/scocen_candidates_300k_only_spatial_cut_200k_to_determine_bg_ols.fits')

    d_old = dict(zip(old['source_id'], old['background_log_overlap']))
    d_add = dict(zip(additional['source_id'], additional['background_log_overlap']))
    d_old.update(d_add)
    dct = d_old

    ln_bg_ols = [dct[source_id] for source_id in wanted['source_id']]
    print
    len(ln_bg_ols), len(wanted)

    wanted['background_log_overlap'] = ln_bg_ols
    print
    wanted

    wanted.write('data/scocen_candidates_300k_only_spatial_cut.fits', overwrite=True, format='fits')

if __name__ == '__main__':
    prepare_stars_that_need_bg_ols()
    # ~ insert_bg_ols_into_table()
    # merge_both_tables()


text:
using System;
using System.Numerics;
using OpenSage.Mathematics;
using Viewport = Veldrid.Viewport;

namespace OpenSage.Graphics.Cameras
{
    public sealed class Camera
    {
        private readonly Func<Viewport> _getViewport;
        private Viewport _viewport;

        private float _nearPlaneDistance;
        private float _farPlaneDistance;

        private Matrix4x4 _world, _projection;

        private float _fieldOfView = MathUtility.ToRadians(50);

        /// <summary>
        /// Gets or sets a value that represents the camera's field of view in radians.
        /// </summary>
        public float FieldOfView
        {
            get { return _fieldOfView; }
            set
            {
                _fieldOfView = value;
                UpdateProjection();
            }
        }

        /// <summary>
        /// Gets or sets a value that specifies the distance from the camera of the camera's far clip plane.
        /// </summary>
        public float FarPlaneDistance
        {
            get { return _farPlaneDistance; }
            set
            {
                _farPlaneDistance = value;
                UpdateProjection();
            }
        }

        /// <summary>
        /// Gets or sets a value that specifies the distance from the camera of the camera's near clip plane.
        /// </summary>
        public float NearPlaneDistance
        {
            get { return _nearPlaneDistance; }
            set
            {
                _nearPlaneDistance = value;
                UpdateProjection();
            }
        }

        /// <summary>
        /// Gets the frustum covered by this camera. The frustum is calculated from the camera's
        /// view and projection matrices.
        /// </summary>
        public BoundingFrustum BoundingFrustum { get; }

        /// <summary>
        /// Gets the View matrix for this camera.
        /// </summary>
        public Matrix4x4 View { get; private set; }

        /// <summary>
        /// Gets the Projection matrix for this camera.
        /// </summary>
        public Matrix4x4 Projection => _projection;

        public Matrix4x4 ViewProjection { get; private set; }

        public Vector3 Position { get; private set; }
        public Vector3 Target { get; private set; }
        public Vector3 Up { get; private set; }

        public Camera(Func<Viewport> getViewport)
        {
            _getViewport = getViewport;
            _viewport = getViewport();

            View = Matrix4x4.Identity;
            BoundingFrustum = new BoundingFrustum(Matrix4x4.Identity);

            _nearPlaneDistance = 4.0f;
            _farPlaneDistance = 10000.0f;

            UpdateProjection();
        }

        public void SetMirrorX(float pivot)
        {
            // Used for rendering reflection without stencil clipping
            var position = Position - new Vector3(0, 0, 2 * (Position.Z - pivot));
            var target = Target - new Vector3(0, 0, 2 * (Target.Z - pivot));
            var up = Up - new Vector3(0, 0, 2 * Up.Z);

            SetLookAt(position, target, up);
            ViewProjection *= Matrix4x4.CreateScale(-1, 1, 1);
            BoundingFrustum.Matrix = ViewProjection;
        }

        public void SetLookAt(in Vector3 cameraPosition, in Vector3 cameraTarget, in Vector3 up)
        {
            View = Matrix4x4.CreateLookAt(cameraPosition, cameraTarget, up);
            _world = Matrix4x4Utility.Invert(View);
            Position = cameraPosition;
            Target = cameraTarget;
            Up = up;

            UpdateViewProjection();
        }

        private void UpdateViewProjection()
        {
            ViewProjection = View * _projection;
            BoundingFrustum.Matrix = ViewProjection;
        }

        private void UpdateProjection()
        {
            CreateProjection(out _projection);
            UpdateViewProjection();
        }

        private float GetVerticalFieldOfView() => _fieldOfView / (_viewport.Width / _viewport.Height);

        private void CreateProjection(out Matrix4x4 projection)
        {
            projection = Matrix4x4.CreatePerspectiveFieldOfView(
                GetVerticalFieldOfView(), _viewport.Width / _viewport.Height,
                NearPlaneDistance, FarPlaneDistance);
        }

        /// <summary>
        /// Creates a ray going from the camera's near plane, through the specified screen position, to the camera's far plane.
        /// </summary>
        public Ray ScreenPointToRay(Vector2 position)
        {
            var near = _viewport.Unproject(new Vector3(position, 0), Projection, View, Matrix4x4.Identity);
            var far = _viewport.Unproject(new Vector3(position, 1), Projection, View, Matrix4x4.Identity);

            return new Ray(near, Vector3.Normalize(far - near));
        }

        /// <summary>
        /// Converts a world-space point to screen-space.
        /// </summary>
        public Vector3 WorldToScreenPoint(Vector3 position)
        {
            return _viewport.Project(position, Projection, View, Matrix4x4.Identity);
        }

        internal RectangleF? WorldToScreenRectangle(in Vector3 position, in SizeF screenSize)
        {
            var screenPosition = WorldToScreenPoint(position);

            // Check if point is behind camera, or too far away.
            if (!IsWithinViewportDepth(screenPosition))
            {
                return null;
            }

            return new RectangleF(
                screenPosition.X - screenSize.Width / 2.0f,
                screenPosition.Y - screenSize.Height / 2.0f,
                screenSize.Width, screenSize.Height);
        }

        internal bool IsWithinViewportDepth(in Vector3 screenPosition)
        {
            return screenPosition.Z >= _viewport.MinDepth && screenPosition.Z <= _viewport.MaxDepth;
        }

        /// <summary>
        /// Converts a screen-space point to world-space. The value of <paramref name="position.Z"/>
        /// will be used to determine the depth in camera space of the world-space point.
        /// </summary>
        public Vector3 ScreenToWorldPoint(in Vector3 position)
        {
            var ray = ScreenPointToRay(new Vector2(position.X, position.Y));
            return ray.Position + ray.Direction * position.Z;
        }

        internal void OnViewportSizeChanged()
        {
            _viewport = _getViewport();
            UpdateProjection();
        }

        /// <summary>
        /// Get size in screen space of world-space bounding sphere.
        /// </summary>
        public float GetScreenSize(in BoundingSphere boundingSphere)
        {
            var distance = Vector3.Distance(boundingSphere.Center, Position);
            return (boundingSphere.Radius / (MathF.Tan(GetVerticalFieldOfView() / 2) * distance)) * (_viewport.Height / 2);
        }

        /// <summary>
        /// Converts the bounding box from world space into a screen space bounding rectangle.
        /// </summary>
        public Rectangle GetBoundingRectangle(in AxisAlignedBoundingBox boundingBox)
        {
            var topLeft = new Vector3(float.MaxValue);
            var bottomRight = new Vector3(float.MinValue);

            Span<Vector3> vertices = stackalloc Vector3[8];

            var min = boundingBox.Min;
            var max = boundingBox.Max;

            // Bottom plane
            vertices[0] = min;
            vertices[1] = min.WithX(max.X);
            vertices[2] = min.WithY(max.Y);
            vertices[3] = max.WithZ(min.Z);

            // Top plane
            vertices[4] = max;
            vertices[5] = max.WithX(min.X);
            vertices[6] = max.WithY(min.Y);
            vertices[7] = min.WithZ(max.Z);

            for (var i = 0; i < 8; i++)
            {
                var screenPos = WorldToScreenPoint(vertices[i]);
                topLeft = Vector3.Min(topLeft, screenPos);
                bottomRight = Vector3.Max(bottomRight, screenPos);
            }

            var size = bottomRight - topLeft;
            return new Rectangle((int) topLeft.X, (int) topLeft.Y, (int) size.X, (int) size.Y);
        }
    }
}


text:
package redis

import (
	"errors"
	"fmt"
	"net/url"
	"strconv"
	"strings"

	"github.com/go-redis/redis/v7"
	"github.com/koron/nvgd/internal/httperror"
	"github.com/koron/nvgd/resource"
)

type getHandler func(*redis.Client, string, []string) (*resource.Resource, error)

var getHandlers = map[string]getHandler{
	"string": getString,
	"list":   getList,
	"set":    getSet,
	"zset":   getZset,
	"hash":   getHash,
	"none":   getNone,
}

func get(c *redis.Client, args []string) (*resource.Resource, error) {
	if len(args) < 1 {
		return nil, errors.New("require a key at least")
	}
	key, err := url.PathUnescape(args[0])
	if err != nil {
		return nil, fmt.Errorf("key contains invalid sequence: %s", err)
	}

	typ, err := c.Type(key).Result()
	if err != nil {
		return nil, fmt.Errorf("failed to TYPE: %s", err)
	}
	h, ok := getHandlers[strings.ToLower(typ)]
	if !ok {
		return nil, fmt.Errorf("unsupported redis value type: %s", typ)
	}
	return h(c, key, args[1:])
}

func getString(c *redis.Client, k string, args []string) (*resource.Resource, error) {
	// GET
	if len(args) == 0 {
		s, err := c.Get(k).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(s), nil
	}

	// GETBIT
	if len(args) == 1 {
		off, err := strconv.ParseInt(args[0], 10, 64)
		if err != nil {
			return nil, err
		}
		n, err := c.GetBit(k, off).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(strconv.FormatInt(n, 10)), nil
	}

	// GETRANGE
	if len(args) == 2 {
		start, err := strconv.ParseInt(args[0], 10, 64)
		if err != nil {
			return nil, err
		}
		end, err := strconv.ParseInt(args[1], 10, 64)
		if err != nil {
			return nil, err
		}
		s, err := c.GetRange(k, start, end).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(s), nil
	}

	return nil, errors.New("too many arguments")
}

func getList(c *redis.Client, k string, args []string) (*resource.Resource, error) {
	// LLEN
	if len(args) == 0 {
		n, err := c.LLen(k).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(strconv.FormatInt(n, 10)), nil
	}

	// LINDEX
	if len(args) == 1 {
		index, err := strconv.ParseInt(args[0], 10, 64)
		if err != nil {
			return nil, err
		}
		s, err := c.LIndex(k, index).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(s), nil
	}

	// LRANGE
	if len(args) == 2 {
		start, err := strconv.ParseInt(args[0], 10, 64)
		if err != nil {
			return nil, err
		}
		stop, err := strconv.ParseInt(args[1], 10, 64)
		if err != nil {
			return nil, err
		}
		ss, err := c.LRange(k, start, stop).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(strings.Join(ss, "\n")), nil
	}

	return nil, errors.New("too many arguments")
}

func getSet(c *redis.Client, k string, args []string) (*resource.Resource, error) {
	// SCARD
	if len(args) == 0 {
		n, err := c.SCard(k).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(strconv.FormatInt(n, 10)), nil
	}

	// SISMEMBER
	if len(args) == 1 {
		member := args[0]
		b, err := c.SIsMember(k, member).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(strconv.FormatBool(b)), nil
	}

	return nil, errors.New("too many arguments")
}

func getZset(c *redis.Client, k string, args []string) (*resource.Resource, error) {
	// ZCARD
	if len(args) == 0 {
		n, err := c.ZCard(k).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(strconv.FormatInt(n, 10)), nil
	}

	// ZRANK
	if len(args) == 1 {
		member := args[0]
		n, err := c.ZRank(k, member).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(strconv.FormatInt(n, 10)), nil
	}

	// ZRANGE
	if len(args) == 2 {
		start, err := strconv.ParseInt(args[0], 10, 64)
		if err != nil {
			return nil, err
		}
		stop, err := strconv.ParseInt(args[1], 10, 64)
		if err != nil {
			return nil, err
		}
		ss, err := c.ZRange(k, start, stop).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(strings.Join(ss, "\n")), nil
	}

	return nil, errors.New("too many arguments")
}

func getHash(c *redis.Client, k string, args []string) (*resource.Resource, error) {
	// HLEN
	if len(args) == 0 {
		n, err := c.HLen(k).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(strconv.FormatInt(n, 10)), nil
	}

	// HGET
	if len(args) == 1 {
		member := args[0]
		s, err := c.HGet(k, member).Result()
		if err != nil {
			return nil, err
		}
		return resource.NewString(s), nil
	}

	return nil, errors.New("too many arguments")
}

func getNone(c *redis.Client, k string, args []string) (*resource.Resource, error) {
	return nil, httperror.Newf(404, "not found a key: %s", k)
}


text:
namespace System.Web.UI {
    using System;
    using System.Web.UI;

    internal sealed class ClientUrlResolverWrapper : IClientUrlResolver {
        private readonly Control _control;

        public ClientUrlResolverWrapper(Control control) {
            _control = control;
        }

        #region IClientUrlResolver Members
        // DevDiv Bugs 197242: AppRelativeTemplateSourceDirectory needed for
        // CompositeReference url resolution
        string IClientUrlResolver.AppRelativeTemplateSourceDirectory {
            get {
                return _control.AppRelativeTemplateSourceDirectory;
            }
        }

        string IClientUrlResolver.ResolveClientUrl(string relativeUrl) {
            IClientUrlResolver resolver = _control as IClientUrlResolver;
            if (resolver != null) {
                return resolver.ResolveClientUrl(relativeUrl);
            }
            else {
                return _control.ResolveClientUrl(relativeUrl);
            }
        }
        #endregion
    }
}


text:
package knightthrough.model;

import knightthrough.error.GameException;

/**
 * @author Fabian Braun
 *
 */
public class BoardFactory {

	public static Board createStandardBoard() {
		Board b = new Board(8, 8);
		for (int i = 0; i < 1; i++) {
			for (int x = 0; x < 8; x++) {
				b.set(i, x, PlayerType.DOWN);
				b.set(i + 1, x, PlayerType.DOWN);
				b.set(i + 6, x, PlayerType.UP);
				b.set(i + 7, x, PlayerType.UP);
			}
		}
		return b;
	}

	public static Board createBoard(int ySize, int xSize, int pieceRowsCount) {
		if (ySize < 2 || xSize < 2 || ySize > 16 || xSize > 20) {
			throw new GameException(
					"fieldsize out of allowed range. Do you want to drive the AI crazy???");
		}
		if (pieceRowsCount < 1 || pieceRowsCount > ySize / 2) {
			throw new GameException(
					"pieceRowsCount out of allowed range. Must be in [1,ySize/2]");
		}
		Board b = new Board(ySize, xSize);
		for (int i = 0; i < pieceRowsCount; i++) {
			for (int x = 0; x < xSize; x++) {
				b.set(i, x, PlayerType.DOWN);
				b.set(ySize - i - 1, x, PlayerType.UP);
			}
		}
		return b;
	}
}


text:
#include <set>
#include <map>
#include <vector>
#include <unordered_set>
#include <iostream>
#include "graph.h"
#include "node.h"
using namespace std;
typedef vector<Link*> Loop;
// Return only the Node* that have multiple connections
unordered_set<Node*> Graph::getJunctions() {
    unordered_set<Node*> juncSet;
    for (unordered_set<Node*>::iterator i = begin(); i != end(); ++i) {
        if ((*i)->getLinkCount() > 2) juncSet.insert(*i);
    }
    return juncSet;
}

vector<vector<Link*>> Graph::getLoops() {
    // initialisation for loop-finding algorithm
    vector<vector<Link*>> loopList;
    vector<vector<Link*>> solution;
    for (Node * node : nodes) {
        for (Link * link: node->getLinks()) {
            vector<Link*> initialVector;
            initialVector.push_back(link);
            loopList.push_back(initialVector);
        }
    }
    unsigned int length = 0;
    unsigned int initialSize = loopList.size();
    // Now, loopList is a vector of vectors, each containing one of the links.
    while (length < initialSize) {
        /**
        Summary: 1 For each vector in loopList...
                  2 Take the last Link in the vector...
                  3 And to the newLoopList, add the following:
                   3.1 All possible vectors containing the original (from step 1.) plus one neighbour of the Link (from step 2.) to newLoopList
                 6 For each vector in newLoopList...
                  7 If it contains the same Link twice, but that Link isn't the first one...
                   7.1 Remove that vector
                  8 If the vector's first and last elements are the same...
                   8.1 Remove it from newLoopList and add it to the solution
                 9 Set loopList to be equal to newLoopList
        */
        vector<vector<Link*>> newLoopList;
        for (unsigned int i = 0; i < initialSize; i++) { // 1. loop through the vectors in loopList
            vector<Link*> ithVector = loopList.at(i);
            if (ithVector.size() == 0) {
                continue;
            }
            Link * l = ithVector.at(ithVector.size() - 1); // 2. get the last link of the vector being looked at

            Component * c = l->getComponent();
            for (Link * componentLink : c->getAllLinks()) {
                if (componentLink != l) {
                    if (ithVector.size() > 1) {
                        if (componentLink == ithVector.at(ithVector.size() - 2)) {
                            continue;
                        }
                    }
                    vector<Link*> newVector = ithVector; // copy ithVector
                    newVector.push_back(componentLink);// 4. add the new link to newVector
                    newLoopList.push_back(newVector);  // 3. add newVector to the newLoopList
                }
            }

            Node * n = l->getNode();
            for (Link * nodeLink : n->getLinks()) {
                if (nodeLink != l) {
                    if (ithVector.size() > 1) {
                        if (nodeLink == ithVector.at(ithVector.size() - 2)) {
                            continue;
                        }
                    }
                    vector<Link*> newVector = ithVector; // copy ithVector
                    newVector.push_back(nodeLink);// add the new link to newVector
                    newLoopList.push_back(newVector);  // add newVector to the newLoopList
                }
            }
        }
        loopList = newLoopList;
        for (unsigned int i = 0; i < loopList.size(); i++) {
            vector<Link*> ithVector = loopList.at(i);
            if (ithVector.at(0) == ithVector.at(ithVector.size() - 1) && ithVector.size() != 1) {
                solution.push_back(ithVector);
                ithVector.clear();
            }
        }

        length += 1;
    }

    vector<vector<Link*>> newSolution;

    for (unsigned int i = 0; i < solution.size(); ++i) {
        vector<Link*> ithVector = solution.at(i);
        bool valid = true;
        for (unsigned int j1 = 0; j1 < ithVector.size(); ++j1) {
            for (unsigned int j2 = 0; j2 < j1 + 1; ++j2) {
                if (j1 != j2 && ithVector.at(j1) == ithVector.at(j2)) {
                    if (! ((j1 == 0 && j2 == ithVector.size() - 1) || (j1 == ithVector.size() - 1 && j2 == 0))) {
                        valid = false;
                    }
                }
            }
        }
        if (valid) {
            newSolution.push_back(ithVector);
        }
    }

    return newSolution;
}

// This gets all loops inside the graph, including non-unique ones and non-independent ones
void Graph::updateLoops() {
    for (unordered_set<Node*>::iterator i = begin(); i != end(); ++i) {
        for (unordered_set<Link*>::iterator j = (*i)->begin(); j != (*i)->end(); ++j) {

        }
    }
}
#include <iostream>
using namespace std;

void Graph::updateMatrices() {
    equationCoefficients.clear();
    equationSums.clear();
    unsigned short c = 0;
    unsigned short maxLoopLength = 0;
    for (vector<Loop>::iterator i = loops.begin(); i != loops.end(); ++i) {
        double rhs = 0; // right hand side
        vector<double> coefficients;
        cerr<<"Loop #"<<++c<<endl;
        for (Loop::iterator j = i->begin(); j != i->end(); ++j) {
            cerr<<(*j)->getLabel()<<endl;
            cerr<<"Type: "<<short((*j)->getComponent()->getType())<<endl;
            switch ((*j)->getComponent()->getType()) {
                case Type::CELL:
                    if ((*j)->getPos() == 0) rhs-=(*j)->getComponent()->getVoltage();
                    else rhs+=(*j)->getComponent()->getVoltage();
                    break;
                case Type::RESISTOR:
                case Type::BULB:
                default:
                    coefficients.push_back((*j)->getComponent()->getResistance());

            }
            ++j; // temporary hack - breaks components with over 2 links
        }
        maxLoopLength = coefficients.size()>maxLoopLength?coefficients.size():maxLoopLength;
        equationCoefficients.push_back(coefficients);
        equationSums.push_back(rhs);
    }

    // Now pad all the equationCoefficients with zeroes so they can be solved simultaneously
    for (vector<vector<double> >::iterator i = equationCoefficients.begin(); i != equationCoefficients.end(); ++i) {
        i->resize(maxLoopLength, 0);
    }
}

void printLoop(vector<Link*> & loop) {
    for (Link * l : loop) {
        cout << l->getLabel() << "-";
    }
    cout << endl;
}


text:
import json
import pickle
from unittest import mock

import pytest

from praw.exceptions import MediaPostFailed
from praw.models import InlineGif, InlineImage, InlineVideo, Subreddit, WikiPage
from praw.models.reddit.subreddit import SubredditFlairTemplates

from ... import UnitTest

class TestSubreddit(UnitTest):
    def test_equality(self):
        subreddit1 = Subreddit(self.reddit, _data={"display_name": "dummy1", "n": 1})
        subreddit2 = Subreddit(self.reddit, _data={"display_name": "Dummy1", "n": 2})
        subreddit3 = Subreddit(self.reddit, _data={"display_name": "dummy3", "n": 2})
        assert subreddit1 == subreddit1
        assert subreddit2 == subreddit2
        assert subreddit3 == subreddit3
        assert subreddit1 == subreddit2
        assert subreddit2 != subreddit3
        assert subreddit1 != subreddit3
        assert "dummy1" == subreddit1
        assert subreddit2 == "dummy1"

    def test_construct_failure(self):
        message = "Either 'display_name' or '_data' must be provided."
        with pytest.raises(TypeError) as excinfo:
            Subreddit(self.reddit)
        assert str(excinfo.value) == message

        with pytest.raises(TypeError) as excinfo:
            Subreddit(self.reddit, "dummy", {"id": "dummy"})
        assert str(excinfo.value) == message

        with pytest.raises(ValueError):
            Subreddit(self.reddit, "")

    def test_fullname(self):
        subreddit = Subreddit(
            self.reddit, _data={"display_name": "name", "id": "dummy"}
        )
        assert subreddit.fullname == "t5_dummy"

    def test_hash(self):
        subreddit1 = Subreddit(self.reddit, _data={"display_name": "dummy1", "n": 1})
        subreddit2 = Subreddit(self.reddit, _data={"display_name": "Dummy1", "n": 2})
        subreddit3 = Subreddit(self.reddit, _data={"display_name": "dummy3", "n": 2})
        assert hash(subreddit1) == hash(subreddit1)
        assert hash(subreddit2) == hash(subreddit2)
        assert hash(subreddit3) == hash(subreddit3)
        assert hash(subreddit1) == hash(subreddit2)
        assert hash(subreddit2) != hash(subreddit3)
        assert hash(subreddit1) != hash(subreddit3)

    @mock.patch(
        "praw.Reddit.post", return_value={"json": {"data": {"websocket_url": ""}}}
    )
    @mock.patch(
        "praw.models.Subreddit._upload_media",
        return_value=("fake_media_url", "fake_websocket_url"),
    )
    @mock.patch("websocket.create_connection")
    def test_invalid_media(self, connection_mock, _mock_upload_media, _mock_post):
        connection_mock().recv.return_value = json.dumps(
            {"payload": {}, "type": "failed"}
        )
        with pytest.raises(MediaPostFailed):
            self.reddit.subreddit("test").submit_image("Test", "dummy path")

    @mock.patch("praw.models.Subreddit._read_and_post_media")
    @mock.patch(
        "praw.Reddit.post",
        return_value={
            "json": {"data": {"websocket_url": ""}},
            "args": {"action": "", "fields": []},
        },
    )
    @mock.patch("websocket.create_connection")
    def test_media_upload_500(self, connection_mock, _mock_post, mock_method):
        from prawcore.exceptions import ServerError
        from requests.exceptions import HTTPError

        http_response = mock.Mock()
        http_response.status_code = 500

        response = mock.Mock()
        response.ok = True
        response.raise_for_status = mock.Mock(
            side_effect=HTTPError(response=http_response)
        )
        mock_method.return_value = response
        with pytest.raises(ServerError):
            self.reddit.subreddit("test").submit_image("Test", "/dev/null")

    def test_notes_delete__invalid_args(self):
        with pytest.raises(TypeError) as excinfo:
            self.reddit.subreddit("SubTestBot1").mod.notes.delete(note_id="111")
        assert excinfo.value.args[0] == (
            "Either the 'redditor' parameter must be provided or this method must be"
            " called from a Redditor instance (e.g., 'redditor.notes')."
        )

    def test_pickle(self):
        subreddit = Subreddit(
            self.reddit, _data={"display_name": "name", "id": "dummy"}
        )
        for level in range(pickle.HIGHEST_PROTOCOL + 1):
            other = pickle.loads(pickle.dumps(subreddit, protocol=level))
            assert subreddit == other

    def test_repr(self):
        subreddit = Subreddit(self.reddit, display_name="name")
        assert repr(subreddit) == "Subreddit(display_name='name')"

    def test_search__params_not_modified(self):
        params = {"dummy": "value"}
        subreddit = Subreddit(self.reddit, display_name="name")
        generator = subreddit.search(None, params=params)
        assert generator.params["dummy"] == "value"
        assert params == {"dummy": "value"}

    def test_str(self):
        subreddit = Subreddit(
            self.reddit, _data={"display_name": "name", "id": "dummy"}
        )
        assert str(subreddit) == "name"

    def test_submit_failure(self):
        message = "Either 'selftext' or 'url' must be provided."
        subreddit = Subreddit(self.reddit, display_name="name")

        with pytest.raises(TypeError) as excinfo:
            subreddit.submit("Cool title")
        assert str(excinfo.value) == message

        with pytest.raises(TypeError) as excinfo:
            subreddit.submit("Cool title", selftext="a", url="b")
        assert str(excinfo.value) == message

        with pytest.raises(TypeError) as excinfo:
            subreddit.submit("Cool title", selftext="", url="b")
        assert str(excinfo.value) == message

    def test_submit_gallery__missing_path(self):
        message = "'image_path' is required."
        subreddit = Subreddit(self.reddit, display_name="name")

        with pytest.raises(TypeError) as excinfo:
            subreddit.submit_gallery(
                "Cool title", [{"caption": "caption"}, {"caption": "caption2"}]
            )
        assert str(excinfo.value) == message

    def test_submit_gallery__invalid_path(self):
        message = "'invalid_image_path' is not a valid image path."
        subreddit = Subreddit(self.reddit, display_name="name")

        with pytest.raises(TypeError) as excinfo:
            subreddit.submit_gallery(
                "Cool title", [{"image_path": "invalid_image_path"}]
            )
        assert str(excinfo.value) == message

    def test_submit_gallery__too_long_caption(self):
        message = "Caption must be 180 characters or less."
        subreddit = Subreddit(self.reddit, display_name="name")
        caption = (
            "wayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
            "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
            "yyyyyyyyyyyyyyyy too long caption"
        )
        with pytest.raises(TypeError) as excinfo:
            subreddit.submit_gallery(
                "Cool title", [{"image_path": __file__, "caption": caption}]
            )
        assert str(excinfo.value) == message

    def test_submit_inline_media__invalid_path(self):
        message = "'invalid_image_path' is not a valid file path."
        subreddit = Subreddit(self.reddit, display_name="name")
        gif = InlineGif("invalid_image_path", "optional caption")
        image = InlineImage("invalid_image_path", "optional caption")
        video = InlineVideo("invalid_image_path", "optional caption")
        selftext = "Text with {gif1}, {image1}, and {video1} inline"
        media = {"gif1": gif, "image1": image, "video1": video}
        with pytest.raises(ValueError) as excinfo:
            subreddit.submit("title", inline_media=media, selftext=selftext)
        assert str(excinfo.value) == message

    def test_upload_banner_additional_image(self):
        subreddit = Subreddit(self.reddit, display_name="name")
        with pytest.raises(ValueError):
            subreddit.stylesheet.upload_banner_additional_image(
                "dummy_path", align="asdf"
            )

class TestSubredditFlair(UnitTest):
    def test_set(self):
        subreddit = self.reddit.subreddit(pytest.placeholders.test_subreddit)
        with pytest.raises(TypeError):
            subreddit.flair.set(
                "a_redditor", css_class="myCSS", flair_template_id="gibberish"
            )

class TestSubredditFlairTemplates(UnitTest):
    def test_not_implemented(self):
        with pytest.raises(NotImplementedError):
            SubredditFlairTemplates(
                Subreddit(self.reddit, pytest.placeholders.test_subreddit)
            ).__iter__()

class TestSubredditWiki(UnitTest):
    def test__getitem(self):
        subreddit = Subreddit(self.reddit, display_name="name")
        wikipage = subreddit.wiki["Foo"]
        assert isinstance(wikipage, WikiPage)
        assert "foo" == wikipage.name

class TestSubredditModmailConversationsStream(UnitTest):
    def test_conversation_stream_init(self):
        submodstream = self.reddit.subreddit("mod").mod.stream
        submodstream.modmail_conversations()
        assert submodstream.subreddit == "all"

    def test_conversation_stream_capitalization(self):
        submodstream = self.reddit.subreddit("Mod").mod.stream
        submodstream.modmail_conversations()
        assert submodstream.subreddit == "all"


text:
def mixed_case(name)
  name.gsub(/\b\w/) {|first| first.upcase }
end

mixed_case("fats waller")
mixed_case("louis armstrong")
mixed_case("strength in numbers")


text:
<?php

if (class_exists('PHP_CodeSniffer_Standards_AbstractPatternSniff', true) === false) {
    throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_Standards_AbstractPatternSniff not found');
}

/**
 * Verifies that control statements conform to their coding standards.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @author    Marc McIntyre <mmcintyre@squiz.net>
 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class PEAR_Sniffs_ControlStructures_ControlSignatureSniff extends PHP_CodeSniffer_Standards_AbstractPatternSniff
{

    /**
     * If true, comments will be ignored if they are found in the code.
     *
     * @var boolean
     */
    public $ignoreComments = true;

    /**
     * Returns the patterns that this test wishes to verify.
     *
     * @return string[]
     */
    protected function getPatterns()
    {
        return array(
                'do {EOL...} while (...);EOL',
                'while (...) {EOL',
                'for (...) {EOL',
                'if (...) {EOL',
                'foreach (...) {EOL',
                '} else if (...) {EOL',
                '} elseif (...) {EOL',
                '} else {EOL',
                'do {EOL',
               );

    }//end getPatterns()

}//end class

?>


text:
package com.fasterxml.jackson.failing;

import java.math.BigDecimal;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import com.fasterxml.jackson.databind.*;

public class RecursiveIgnoreProperties1755Test extends BaseMapTest
{
    // for [databind#1755]
    static class JackBase1755 {
        public String id;
    }

    static class JackExt extends JackBase1755 {
        public BigDecimal quantity;
        public String ignoreMe;

        @JsonIgnoreProperties({"ignoreMe"})
        public List<JackExt> linked;

        public List<KeyValue> metadata;
    }

    static class KeyValue {
        public String key;
        public String value;
    }

    // for [databind#1755]

    private final ObjectMapper MAPPER = newJsonMapper();

    public void testRecursiveIgnore1755() throws Exception
    {
        final String JSON = a2q("{\n"
                +"'id': '1',\n"
                +"'quantity': 5,\n"
                +"'ignoreMe': 'yzx',\n"
                +"'metadata': [\n"
                +"           {\n"
                +"              'key': 'position',\n"
                +"              'value': '2'\n"
                +"          }\n"
                +"       ],\n"
                +"'linked': [\n"
                +"     {\n"
                +"         'id': '1',\n"
                +"         'quantity': 5,\n"
                +"         'ignoreMe': 'yzx',\n"
                +"         'metadata': [\n"
                +"          {\n"
                +"              'key': 'position',\n"
                +"             'value': '2'\n"
                +"         }\n"
                +"     ]\n"
                +"   }\n"
                +"  ]\n"
                +"}");
        JackExt value = MAPPER.readValue(JSON, JackExt.class);
        assertNotNull(value);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/txtNome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="24dp"
        android:text="Maxwell Augusto Cravo"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txtIdade"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="26 Anos"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/txtVitima"
        android:layout_marginRight="60dp" />

    <TextView
        android:id="@+id/txtTipo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp"
        android:layout_marginTop="24dp"
        android:text="Condutor"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txtVitima"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Vítima - "
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="24dp"
        app:layout_constraintRight_toLeftOf="@+id/txtTipo"
        android:layout_marginRight="130dp" />

</android.support.constraint.ConstraintLayout>


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Lookup Column.
 */
public class LookupColumn implements IJsonBackedObject {

    /** the OData type of the object as returned by the service */
    @SerializedName("@odata.type")
    @Expose
    @Nullable
    public String oDataType;

    private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);

    @Override
    @Nonnull
    public final AdditionalDataManager additionalDataManager() {
        return additionalDataManager;
    }

    /**
     * The Allow Multiple Values.
     * Indicates whether multiple values can be selected from the source.
     */
    @SerializedName(value = "allowMultipleValues", alternate = {"AllowMultipleValues"})
    @Expose
	@Nullable
    public Boolean allowMultipleValues;

    /**
     * The Allow Unlimited Length.
     * Indicates whether values in the column should be able to exceed the standard limit of 255 characters.
     */
    @SerializedName(value = "allowUnlimitedLength", alternate = {"AllowUnlimitedLength"})
    @Expose
	@Nullable
    public Boolean allowUnlimitedLength;

    /**
     * The Column Name.
     * The name of the lookup source column.
     */
    @SerializedName(value = "columnName", alternate = {"ColumnName"})
    @Expose
	@Nullable
    public String columnName;

    /**
     * The List Id.
     * The unique identifier of the lookup source list.
     */
    @SerializedName(value = "listId", alternate = {"ListId"})
    @Expose
	@Nullable
    public String listId;

    /**
     * The Primary Lookup Column Id.
     * If specified, this column is a secondary lookup, pulling an additional field from the list item looked up by the primary lookup. Use the list item looked up by the primary as the source for the column named here.
     */
    @SerializedName(value = "primaryLookupColumnId", alternate = {"PrimaryLookupColumnId"})
    @Expose
	@Nullable
    public String primaryLookupColumnId;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

    }
}


text:
from __future__ import unicode_literals

from django.utils.translation import ugettext_lazy as _
from django.db import models
from cms.models import CMSPlugin
from cms.models.fields import PageField
from filer.fields.image import FilerImageField
from filer.fields.file import FilerFileField
from filer.utils.compatibility import python_2_unicode_compatible
from cmsplugin_filer_utils import FilerPluginManager
from .conf import settings

@python_2_unicode_compatible
class FilerImage(CMSPlugin):
    LEFT = "left"
    RIGHT = "right"
    FLOAT_CHOICES = ((LEFT, _("left")),
                     (RIGHT, _("right")),
                     )
    STYLE_CHOICES = settings.CMSPLUGIN_FILER_IMAGE_STYLE_CHOICES
    DEFAULT_STYLE = settings.CMSPLUGIN_FILER_IMAGE_DEFAULT_STYLE
    style = models.CharField(
        _('Style'), choices=STYLE_CHOICES, default=DEFAULT_STYLE, max_length=50, blank=True)
    caption_text = models.CharField(_("caption text"), null=True, blank=True, max_length=255)
    image = FilerImageField(null=True, blank=True, default=None, verbose_name=_("image"))
    image_url = models.URLField(_("alternative image url"), null=True, blank=True, default=None)
    alt_text = models.CharField(_("alt text"), null=True, blank=True, max_length=255)
    use_original_image = models.BooleanField(_("use the original image"), default=False,
        help_text=_('do not resize the image. use the original image instead.'))
    thumbnail_option = models.ForeignKey('ThumbnailOption', null=True, blank=True, verbose_name=_("thumbnail option"),
                                        help_text=_('overrides width, height, crop and upscale with values from the selected thumbnail option'))
    use_autoscale = models.BooleanField(_("use automatic scaling"), default=False,
                                        help_text=_('tries to auto scale the image based on the placeholder context'))
    width = models.PositiveIntegerField(_("width"), null=True, blank=True)
    height = models.PositiveIntegerField(_("height"), null=True, blank=True)
    crop = models.BooleanField(_("crop"), default=True)
    upscale = models.BooleanField(_("upscale"), default=True)
    alignment = models.CharField(_("image alignment"), max_length=10, blank=True, null=True, choices=FLOAT_CHOICES)

    free_link = models.CharField(_("link"), max_length=255, blank=True, null=True,
                                 help_text=_("if present image will be clickable"))
    page_link = PageField(null=True, blank=True,
                          help_text=_("if present image will be clickable"),
                          verbose_name=_("page link"))
    file_link = FilerFileField(null=True, blank=True, default=None, verbose_name=_("file link"), help_text=_("if present image will be clickable"), related_name='+')
    original_link = models.BooleanField(_("link original image"), default=False, help_text=_("if present image will be clickable"))
    description = models.TextField(_("description"), blank=True, null=True)
    target_blank = models.BooleanField(_('Open link in new window'), default=False)

    # we only add the image to select_related. page_link and file_link are FKs
    # as well, but they are not used often enough to warrant the impact of two
    # additional LEFT OUTER JOINs.
    objects = FilerPluginManager(select_related=('image',))

    class Meta:
        verbose_name = _("filer image")
        verbose_name_plural = _("filer images")

    def clean(self):
        from django.core.exceptions import ValidationError
        # Make sure that either image or image_url is set
        if (not self.image and not self.image_url) or (self.image and self.image_url):
            raise ValidationError(_('Either an image or an image url must be selected.'))

    def __str__(self):
        if self.image:
            return self.image.label
        else:
            return _("Image Publication %(caption)s") % {'caption': self.caption or self.alt}
        return ''
    @property
    def caption(self):
        if self.image:
            return self.caption_text or self.image.default_caption
        else:
            return self.caption_text
    @property
    def alt(self):
        if self.image:
            return self.alt_text or self.image.default_alt_text or self.image.label
        else:
            return self.alt_text
    @property
    def link(self):
        if self.free_link:
            return self.free_link
        elif self.page_link:
            return self.page_link.get_absolute_url()
        elif self.file_link:
            return self.file_link.url
        elif self.original_link:
            if self.image:
                return self.image.url
            else:
                return self.image_url
        else:
            return ''

@python_2_unicode_compatible
class ThumbnailOption(models.Model):
    """
    This class defines the option use to create the thumbnail.
    """
    name = models.CharField(_("name"), max_length=100)
    width = models.IntegerField(_("width"), help_text=_('width in pixel.'))
    height = models.IntegerField(_("height"), help_text=_('height in pixel.'))
    crop = models.BooleanField(_("crop"), default=True)
    upscale = models.BooleanField(_("upscale"), default=True)

    class Meta:
        ordering = ('width', 'height')
        verbose_name = _("thumbnail option")
        verbose_name_plural = _("thumbnail options")

    def __str__(self):
        return '%s -- %s x %s' % (self.name, self.width, self.height)

    @property
    def as_dict(self):
        """
        This property returns a dictionary suitable for Thumbnailer.get_thumbnail()

        Sample code:
            # thumboption_obj is a ThumbnailOption instance
            # filerimage is a Image instance
            option_dict = thumboption_obj.as_dict
            thumbnailer = filerimage.easy_thumbnails_thumbnailer
            thumb_image = thumbnailer.get_thumbnail(option_dict)
        """
        return {"size":(self.width,self.height), "width":self.width,
                "height":self.height,"crop":self.crop,"upscale":self.upscale}


text:
canvasTutorial
==============

canvasTutorial is small python based web server that runs a few pages that showcase the HTML5 canvas element.

It is also my first GitHub repo.

Main reason I did this is to learn more about Web, Python & Github development.

Version
-------

1.0

Installation
------------
For Linux, with git, python & pip installed
```sh
cd /path/of/your/choice
git clone https://github.com/jackharrhy/canvasTutorial
pip install bottle

```

Usage
-----
```sh
cd /path/of/your/choice
python canvasTut.py
```
Once this is ran, go to this link

http://localhost:8080

If you see nothing, there must be a problem.


text:
REPORTER = spec

test: test-unit

test-unit:
	@NODE_ENV=test ./node_modules/.bin/mocha \
		--reporter $(REPORTER)

test-cov: lib-cov
	@EXPRESS_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html

lib-cov:
	@jscoverage lib lib-cov

.PHONY: test test-unit


text:
'use strict';

import crypto from 'crypto';
import Class from './class.model';
import Request from './request.schema';
import SkillStatus from './skillstatus.schema';
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
var Schema = mongoose.Schema;
var authTypes = ['github', 'twitter', 'facebook', 'google'];

var UserSchema = new Schema({
  name: String,
  email: {
    type: String,
    lowercase: true
  },
  role: {
    type: String,
    default: 'user'
  },
  password: String,
  provider: String,
  salt: String,
  facebook: {},
  google: {},
  github: {},

  //start custom properties
  type: String,
  joined: {
    type: Date,
    default: Date.now
  },
  //student properties
  //we keep these in a nested object both for cleanness and security - this way we can ensure that only this data can be arbitrarily updated
  studentData: {
    points: { //total earned points
      type: Number,
      default: 0
    },
    skills: [SkillStatus], //array of SkillStatusSchemas, each containing a reference to a skill and the user's progress
    badges: [{ //array of earned badges
      type: Schema.Types.ObjectId,
      ref: 'Badge'
    }],
    skillRoot: { //the skilltree node from which skills should be displayed for this user
      type: Schema.Types.ObjectId,
      ref: 'Skilltree'
    },
    requests: [Request], //array of requests from teachers
    teacher: { //this student's teacher
      type: Schema.Types.ObjectId,
      ref: 'User'
    },
    myClass: { //this student's class
      name: String,
        _id: Schema.Types.ObjectId
    },
    modifications: { // UI/behavior modifications to apply to this student
      loaded: {
        type: Boolean,
        default: true
      },
      showTimer: { //whether a timer should be shown on the problems page
        type: Boolean
      },
      showWhiteboard: { //whether the student can use the whiteboard on the problems page
        type: Boolean
      },
      showLeaderboard: { //whether to show the student a leaderboard of the points of other students in her class
        type: Boolean
      }
    },
    times: {}
  },

  //teacher properties
  teacherData: {
    classes: [Class.schema], //list of the teachers classes, with student information for each
    pendingStudents: [Request] //list of requests sent to students but not yet accepted
  }
});

/**
 * Virtuals
 */

// Public profile information
UserSchema
  .virtual('profile')
  .get(function() {
    return {
      'name': this.name,
      'role': this.role
    };
  });

// Non-sensitive info we'll be putting in the token
UserSchema
  .virtual('token')
  .get(function() {
    return {
      '_id': this._id,
      'role': this.role
    };
  });

/**
 * Validations
 */

// Validate empty email
UserSchema
  .path('email')
  .validate(function(email) {
    if (authTypes.indexOf(this.provider) !== -1) {
      return true;
    }
    return email.length;
  }, 'Email cannot be blank');

// Validate empty password
UserSchema
  .path('password')
  .validate(function(password) {
    if (authTypes.indexOf(this.provider) !== -1) {
      return true;
    }
    return password.length;
  }, 'Password cannot be blank');

// Validate email is not taken
UserSchema
  .path('email')
  .validate(function(value, respond) {
    var self = this;
    return this.constructor.findOneAsync({
        email: value
      })
      .then(function(user) {
        if (user) {
          if (self.id === user.id) {
            return respond(true);
          }
          return respond(false);
        }
        return respond(true);
      })
      .catch(function(err) {
        throw err;
      });
  }, 'The specified email address is already in use.');

var validatePresenceOf = function(value) {
  return value && value.length;
};

/**
 * Pre-save hook
 */
UserSchema
  .pre('save', function(next) {
    // Handle new/update passwords
    if (this.isModified('password')) {
      if (!validatePresenceOf(this.password) && authTypes.indexOf(this.provider) === -1) {
        next(new Error('Invalid password'));
      }

      // Make salt with a callback
      var _this = this;
      this.makeSalt(function(saltErr, salt) {
        if (saltErr) {
          next(saltErr);
        }
        _this.salt = salt;
        _this.encryptPassword(_this.password, function(encryptErr, hashedPassword) {
          if (encryptErr) {
            next(encryptErr);
          }
          _this.password = hashedPassword;
          next();
        });
      });
    } else {
      next();
    }
  });

/**
 * Methods
 */
UserSchema.methods = {
  /**
   * Authenticate - check if the passwords are the same
   *
   * @param {String} password
   * @param {Function} callback
   * @return {Boolean}
   * @api public
   */
  authenticate: function(password, callback) {
    if (!callback) {
      return this.password === this.encryptPassword(password);
    }

    var _this = this;
    this.encryptPassword(password, function(err, pwdGen) {
      if (err) {
        callback(err);
      }

      if (_this.password === pwdGen) {
        callback(null, true);
      } else {
        callback(null, false);
      }
    });
  },

  /**
   * Make salt
   *
   * @param {Number} byteSize Optional salt byte size, default to 16
   * @param {Function} callback
   * @return {String}
   * @api public
   */
  makeSalt: function(byteSize, callback) {
    var defaultByteSize = 16;

    if (typeof arguments[0] === 'function') {
      callback = arguments[0];
      byteSize = defaultByteSize;
    } else if (typeof arguments[1] === 'function') {
      callback = arguments[1];
    }

    if (!byteSize) {
      byteSize = defaultByteSize;
    }

    if (!callback) {
      return crypto.randomBytes(byteSize).toString('base64');
    }

    return crypto.randomBytes(byteSize, function(err, salt) {
      if (err) {
        callback(err);
      }
      return callback(null, salt.toString('base64'));
    });
  },

  /**
   * Encrypt password
   *
   * @param {String} password
   * @param {Function} callback
   * @return {String}
   * @api public
   */
  encryptPassword: function(password, callback) {
    if (!password || !this.salt) {
      return null;
    }

    var defaultIterations = 10000;
    var defaultKeyLength = 64;
    var salt = new Buffer(this.salt, 'base64');

    if (!callback) {
      return crypto.pbkdf2Sync(password, salt, defaultIterations, defaultKeyLength)
        .toString('base64');
    }

    return crypto.pbkdf2(password, salt, defaultIterations, defaultKeyLength, function(err, key) {
      if (err) {
        callback(err);
      }
      return callback(null, key.toString('base64'));
    });
  }
};

module.exports = mongoose.model('User', UserSchema);


text:
import 'babel-polyfill'

const renderer = new THREE.WebGLRenderer({antialias: true})
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(window.devicePixelRatio)
document.getElementById('app').appendChild(renderer.domElement)

const scene = new THREE.Scene()
const gridHelper = new THREE.GridHelper(1000, 50)
gridHelper.rotation.x = Math.PI / 2 // Grid should be placed as xy-plane
scene.add(gridHelper)
scene.add(new THREE.AxesHelper(200))

const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.01, 10000)
camera.position.set(360, 360, 240)
camera.up.set(0, 0, 1)
camera.add(new THREE.PointLight(0xffffff))
scene.add(camera)

const controls = new THREE.OrbitControls(camera, renderer.domElement)

const geometry = new THREE.Geometry()
const material = new THREE.MeshLambertMaterial({color: 0xffffff, side: THREE.DoubleSide})
const mesh = new THREE.Mesh(geometry, material)
mesh.scale.z = 2 // Magnify cell's thickness
scene.add(mesh)

const animate = () => {
  window.requestAnimationFrame(animate)
  controls.update()
  renderer.render(scene, camera)
}

let frames = []
let time = 0

const updateFrame = () => {
  const frame = frames[time]
  document.getElementById('frame-counter').innerText = `time: ${frame.time}`
  geometry.vertices = frame.vertices
  geometry.faces = frame.faces
  geometry.verticesNeedUpdate = true
  geometry.elementsNeedUpdate = true
  geometry.computeFaceNormals()
}

document.getElementById('time').oninput = e => {
  time = Math.floor((e.target.value / 100) * frames.length)
  updateFrame()
}

document.getElementById('auto').onchange = e => {
  if (!e.target.checked) return clearInterval(window.interval)

  window.interval = setInterval(() => {
    time = (time + 1) % frames.length
    document.getElementById('time').value = (time / frames.length) * 100
    updateFrame()
  }, 200)
}

document.querySelector('select[name="type"]').onchange = async e => {
  document.getElementById('frame-counter').innerText = 'Loading...'
  const res = await (await window.fetch(`./dist/components/${e.target.value}.json`)).json()
  frames = res.frames.map(frame => ({
    time: frame.time,
    vertices: frame.positions.map(v => new THREE.Vector3(...v)),
    faces: frame.cells.map(f => new THREE.Face3(...f))
  }))
  updateFrame()
  animate()
}


text:
<?php

namespace Tests\Unit\Community;

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;

class GroupMembershipTest extends TestCase
{
    use DatabaseTransactions;

    /** @test */
    public function itIsPossibleToJoinACommunityGroup()
    {
        $user = factory(\App\Models\Mship\Account::class)->create();
        $division = \App\Models\Mship\State::findByCode('DIVISION');
        $user->addState($division);

        $group = \App\Models\Community\Group::first();

        $user->fresh()->addCommunityGroup($group);

        $this->assertDatabaseHas('community_membership', [
            'account_id' => $user->id,
            'group_id' => $group->id,
        ]);
    }

    /** @test */
    public function itListsAllMembersInAGroup()
    {
        $userA = factory(\App\Models\Mship\Account::class)->create();
        $userB = factory(\App\Models\Mship\Account::class)->create();

        $division = \App\Models\Mship\State::findByCode('DIVISION');

        $userA->addState($division);
        $userB->addState($division);

        $group = \App\Models\Community\Group::first();

        $userA->fresh()->addCommunityGroup($group);
        $userB->fresh()->addCommunityGroup($group);

        $groupMembers = $group->fresh()->accounts;

        $this->assertTrue($groupMembers->contains($userA->id));
        $this->assertTrue($groupMembers->contains($userB->id));
    }

    /** @test */
    public function itCorrectlyDeterminesIfAMemberIsInAGroup()
    {
        $userA = factory(\App\Models\Mship\Account::class)->create();
        $userB = factory(\App\Models\Mship\Account::class)->create();

        $division = \App\Models\Mship\State::findByCode('DIVISION');

        $userA->addState($division);
        $userB->addState($division);

        $group = \App\Models\Community\Group::first();

        $userA->fresh()->addCommunityGroup($group);
        $userB->fresh()->addCommunityGroup($group);

        $this->assertTrue($group->fresh()->hasMember($userA));
        $this->assertTrue($group->fresh()->hasMember($userB));
    }

    /** @test */
    public function itIsNotPossibleToJoinACommunityGroupAsANonDivisionMember()
    {
        $this->expectException(\App\Exceptions\Community\MustBeADivisionMemberException::class);

        $user = factory(\App\Models\Mship\Account::class)->create();
        $international = \App\Models\Mship\State::findByCode('INTERNATIONAL');
        $user->addState($international);

        $defaultGroup = \App\Models\Community\Group::isDefault()->first();

        $user->fresh()->addCommunityGroup($defaultGroup);
    }

    /** @test */
    public function itIsPossibleToJoinMultipleGroupsAcrossTiers()
    {
        $user = factory(\App\Models\Mship\Account::class)->create();
        $divisionState = \App\Models\Mship\State::findByCode('DIVISION');
        $user->addState($divisionState);

        $tier1 = \App\Models\Community\Group::inTier(1)->first();
        $tier2 = \App\Models\Community\Group::inTier(2)->first();

        $user->fresh()->addCommunityGroup($tier1);
        $user->fresh()->addCommunityGroup($tier2);

        $this->assertTrue($user->fresh()->communityGroups->contains($tier1) && $user->fresh()->communityGroups->contains($tier2));
    }

    /** @test */
    public function itIsNotPossibleToJoinTheSameGroupTwice()
    {
        $this->expectException(\App\Exceptions\Community\AlreadyAGroupTierMemberException::class);

        $user = factory(\App\Models\Mship\Account::class)->create();
        $divisionState = \App\Models\Mship\State::findByCode('DIVISION');
        $user->addState($divisionState);

        $defaultGroup = \App\Models\Community\Group::isDefault()->first();

        $user->fresh()->addCommunityGroup($defaultGroup);
        $user->fresh()->addCommunityGroup($defaultGroup);
    }

    /** @test */
    public function itIsNotPossibleToJoinMoreThanOneGroupFromTheSameTier()
    {
        $this->expectException(\App\Exceptions\Community\AlreadyAGroupTierMemberException::class);

        $user = factory(\App\Models\Mship\Account::class)->create();
        $divisionState = \App\Models\Mship\State::findByCode('DIVISION');
        $user->addState($divisionState);

        $tier2A = \App\Models\Community\Group::inTier(2)->first();
        $tier2B = \App\Models\Community\Group::inTier(2)
            ->where('id', '!=', $tier2A->id)
            ->first();

        $user->fresh()->addCommunityGroup($tier2A);
        $user->fresh()->addCommunityGroup($tier2B);
    }
}


text:
package val.com.ciclodevida;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class ActivityB extends Activity {

    private String mActivityName;
    private TextView mStatusView;
    private TextView mStatusAllView;
    private PilaMensajes mPilaMensajes = PilaMensajes.getInstance();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);
        mActivityName = getString(R.string.activity_b_label);
        mStatusView = (TextView)findViewById(R.id.status_view_b);
        mStatusAllView = (TextView)findViewById(R.id.status_view_all_b);
        mPilaMensajes.setStatus(mActivityName, getString(R.string.on_create));
        Utils.Mostrar(mStatusView, mStatusAllView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mPilaMensajes.setStatus(mActivityName, getString(R.string.on_start));
        Utils.Mostrar(mStatusView, mStatusAllView);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mPilaMensajes.setStatus(mActivityName, getString(R.string.on_restart));
        Utils.Mostrar(mStatusView, mStatusAllView);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPilaMensajes.setStatus(mActivityName, getString(R.string.on_resume));
        Utils.Mostrar(mStatusView, mStatusAllView);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPilaMensajes.setStatus(mActivityName, getString(R.string.on_pause));
        Utils.Mostrar(mStatusView, mStatusAllView);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPilaMensajes.setStatus(mActivityName, getString(R.string.on_stop));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPilaMensajes.setStatus(mActivityName, getString(R.string.on_destroy));
    }

    public void startDialog(View v) {
        Intent intent = new Intent(ActivityB.this, DialogActivity.class);
        startActivity(intent);
    }

    public void startActivityA(View v) {
        Intent intent = new Intent(ActivityB.this, ActivityA.class);
        startActivity(intent);
    }

    public void startActivityC(View v) {
        Intent intent = new Intent(ActivityB.this, ActivityC.class);
        startActivity(intent);
    }

    public void finishActivityB(View v) {
        ActivityB.this.finish();
    }
}


text:
      {{'APPLICATIONS.RUNTIME.DEPLOYMENT' | translate}}
       /
      {{selectedNodeTemplate.name}}
       / {{selectedInstance.id}}

    <button id="backToInstanceListButton" type="button" class="btn btn-default btn-xs" ng-click="clearInstanceSelection()"
            uib-tooltip="{{ 'APPLICATIONS.RUNTIME.BACK' | translate }}" tooltip-placement="left">

    </button>

  {{'COMMON.PROPERTIES' | translate}}

          {{ 'APPLICATIONS.RUNTIME.KEY' | translate }}
          {{ 'VALUE' | translate }}

          {{property.key}}
          {{property.value.value}}

  {{'COMMON.ATTRIBUTES' | translate}}

          {{ 'APPLICATIONS.RUNTIME.KEY' | translate }}
          {{ 'VALUE' | translate }}

          {{propKey}}
          {{propVal}}

  {{'APPLICATIONS.RUNTIME.RUNTIMEPROPS' | translate}}

          {{ 'APPLICATIONS.RUNTIME.KEY' | translate }}
          {{ 'VALUE' | translate }}

          {{propKey}}
          {{propVal}}

<ng-include src="'views/_ref/applications/includes/runtime_editor_details_selected_operations.html'"></ng-include>


text:
<?php
/**
 * Aliases for AccountCaptcha
 */

$specialPageAliases = array();

/** English
 * @author Lethosor
 */
$specialPageAliases[ 'en' ] = array(
    'AccountCaptcha' => array( 'AccountCaptcha', 'AccountCaptcha' ),
);


text:
@implementation XCDictionaryDemoPrinter

+ (NSString *)stringFromData:(id)data
{
    if ([data isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict = (NSDictionary *)data;

        NSMutableString *string = [NSMutableString stringWithString:@"@{\n"];

        [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            NSString *subDataKeyStr = [super stringFromData:key];
            NSString *subDataValStr = [super stringFromData:obj];

            [string appendString:subDataKeyStr];
            [string appendString:@" : "];
            [string appendString:subDataValStr];

            [string appendString:@",\n"];
        }];

        [string appendString:@"}"];

        return string;
    }
    else
    {
        NSLog(@"data is not a string");
        return nil;
    }
}

@end


text:
'use strict'

const express = require('express');

const app = express();

const socketio = require('socket.io');
const io = socketio()

io.on('connection', socket => {
  console.log('user connected')

  socket.on('disconnect', () => {
    console.log('user disconnected')
  })
})

// sockets.init(io)

const server = app.listen('4000', () => {
  console.log(`Server started at port 4000`)
})

io.attach(server)


text:
<?php
namespace Gwa\Wordpress\Zero\Module;

use Gwa\Wordpress\WpBridge\Traits\WpBridgeTrait;
use Gwa\Wordpress\Zero\Module\AbstractThemeModule;

class CleanUpModule extends AbstractThemeModule
{
    use WpBridgeTrait;

    /**
     * The default WordPress head is a mess. Let's clean it up.
     */
    public function wpHeadCleanup()
    {
        // index link
        $this->getWpBridge()->removeAction('wp_head', 'index_rel_link');
        // previous link
        $this->getWpBridge()->removeAction('wp_head', 'parent_post_rel_link', 10, 0);
        // start link
        $this->getWpBridge()->removeAction('wp_head', 'start_post_rel_link', 10, 0);
        // remove WP version from css
        $this->getWpBridge()->addFilter('style_loader_src', [$this, 'removeWpVerCssJs'], 9999);
        // remove Wp version from scripts
        $this->getWpBridge()->addFilter('script_loader_src', [$this, 'removeWpVerCssJs'], 9999);
    }

    public function removeRssVersion()
    {
        return '';
    }

    public function removeWpVerCssJs($src)
    {
        if (strpos($src, 'ver=')) {
            $src = $this->getWpBridge()->removeQueryArg('ver', $src);
        }

        return $src;
    }

    /**
     * Clean the output of attributes of images in editor.
     * Courtesy of SitePoint. http://www.sitepoint.com/wordpress-change-img-tag-html/
     *
     * @param string $class
     * @param string $id
     * @param string $align
     * @param string $size
     *
     * @return string
     */
    public function imageTagClassClean($class, $id, $align, $size)
    {
        return 'align'.esc_attr($align);
    }

    /**
     * Remove width and height in editor, for a better responsive world.
     *
     * @param string $html
     * @param string $id
     * @param string $alt
     * @param string $title
     *
     * @return string
     */
    public function imageEditorRemoveHightAndWidth($html, $id, $alt, $title)
    {
        return preg_replace([
            '/\s+width="\d+"/i',
            '/\s+height="\d+"/i',
            '/alt=""/i'
        ], [
            '',
            '',
            '',
            'alt="'.$title.'"'
        ], $html);
    }

    /**
     * Remove image attributes
     *
     * @param  string $html
     *
     * @return string
     */
    public function removeImageAttributes($html)
    {
        $html = preg_replace('/(width|height)="\d*"\s/', '', $html);

        return $html;
    }

    public function shortcodeParagraphFix($content)
    {
        // Suchen und Ersetzen Strings festlegen
        $array = [
            '
[' => '[',
            ']
' => ']',
            ']
' => ']'
        ];

        return strtr($content, $array);
    }

    protected function getActionMap()
    {
        return [
            [
                'hooks'  => 'init',
                'class'  => $this,
                'method' => 'wpHeadCleanup',
                'prio'   => 10,
                'args'   => 1,
            ],
        ];
    }

    /**
     * Override in concrete subclass.
     *
     * @return array
     */
    protected function getFilterMap()
    {
        return [
            [
                'hooks'  => 'the_generator',
                'class'  => $this,
                'method' => 'removeRssVersion',
                'prio'   => 10,
                'args'   => 1,
            ], [
                'hooks'  => 'get_image_tag_class',
                'class'  => $this,
                'method' => 'imageTagClassClean',
                'prio'   => 0,
                'args'   => 4,
            ], [
                'hooks'  => 'get_image_tag',
                'class'  => $this,
                'method' => 'imageEditorRemoveHightAndWidth',
                'prio'   => 0,
                'args'   => 4,
            ], [
                'hooks'  => 'the_content',
                'class'  => $this,
                'method' => 'shortcodeParagraphFix',
                'prio'   => 10,
                'args'   => 1,
            ], [
                'hooks'  => ['post_thumbnail_html', 'removeImageAttributes'],
                'class'  => $this,
                'method' => 'removeImageAttributes',
                'prio'   => 10,
                'args'   => 1,
            ],
        ];
    }
}


text:
package br.com.caelum.vraptor.restfulie;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Arrays;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import br.com.caelum.vraptor.config.Configuration;
import br.com.caelum.vraptor.restfulie.hypermedia.HypermediaController;
import br.com.caelum.vraptor.restfulie.relation.Relation;
import br.com.caelum.vraptor.restfulie.relation.RelationBuilder;
import br.com.caelum.vraptor.restfulie.serialization.LinkConverter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;

public class LinkConverterTest {

	private @Mock Restfulie restfulie;
	private @Mock RelationBuilder builder;
	private @Mock HypermediaController controller;

	private XStream xstream;

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);

		this.restfulie = mock(Restfulie.class);
		when(restfulie.newRelationBuilder()).thenReturn(builder);

		Configuration config = mock(Configuration.class);
		when(config.getApplicationPath()).thenReturn("http://www.caelum.com.br");

		xstream = new XStream();
		ReflectionConverter base = new ReflectionConverter(xstream.getMapper(), xstream.getReflectionProvider());

		xstream.registerConverter(new LinkConverter(base, restfulie, config));
	}

	@Test
	public void shouldSetupRelations() {
		xstream.toXML(controller);
		verify(controller).configureRelations(builder);
	}

	@Test
	public void shouldSerializeNoLinksIfThereIsNoTransition() {
		String xml = xstream.toXML(controller);
		assertThat(xml, not(containsString("atom:link")));
	}

	@Test
	public void shouldSerializeOneLinkIfThereIsATransition() {
		Relation kill = mock(Relation.class);
		when(kill.getName()).thenReturn("kill");
		when(kill.getUri()).thenReturn("/kill");

		when(builder.getRelations()).thenReturn(Arrays.asList(kill));
		String xml = xstream.toXML(controller);
		assertThat(xml, containsString("<atom:link rel=\"kill\" href=\"http://www.caelum.com.br/kill\" xmlns:atom=\"http://www.w3.org/2005/Atom\"/>"));
	}

	@Test
	public void shouldSerializeAllLinksIfThereAreTransitions() {
		Relation kill = mock(Relation.class);
		when(kill.getName()).thenReturn("kill");
		when(kill.getUri()).thenReturn("/kill");

		Relation ressurect = mock(Relation.class);
		when(ressurect.getName()).thenReturn("ressurect");
		when(ressurect.getUri()).thenReturn("/ressurect");

		when(builder.getRelations()).thenReturn(Arrays.asList(kill, ressurect));
		String xml = xstream.toXML(controller);
		assertThat(xml, containsString("<atom:link rel=\"kill\" href=\"http://www.caelum.com.br/kill\" xmlns:atom=\"http://www.w3.org/2005/Atom\"/>"));
		assertThat(xml, containsString("<atom:link rel=\"ressurect\" href=\"http://www.caelum.com.br/ressurect\" xmlns:atom=\"http://www.w3.org/2005/Atom\"/>"));
	}

}


text:
package oauth2

import (
	"testing"
	"time"

	jwtbase "github.com/dgrijalva/jwt-go"
	"github.com/hellofresh/janus/pkg/jwt"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestJWTManagerValidKey(t *testing.T) {
	signingMethod := jwt.SigningMethod{Alg: "HS256", Key: "secret"}
	config := jwt.NewParserConfig(signingMethod)
	parser := jwt.NewParser(config)
	manager := NewJWTManager(parser)

	token, err := issueToken(signingMethod, 1*time.Hour)
	require.NoError(t, err)

	assert.True(t, manager.IsKeyAuthorized(token))
}

func TestJWTManagerInvalidKey(t *testing.T) {
	signingMethod := jwt.SigningMethod{Alg: "HS256", Key: "secret"}
	config := jwt.NewParserConfig(signingMethod)
	parser := jwt.NewParser(config)
	manager := NewJWTManager(parser)

	assert.False(t, manager.IsKeyAuthorized("wrong"))
}

func issueToken(signingMethod jwt.SigningMethod, expireIn time.Duration) (string, error) {
	token := jwtbase.New(jwtbase.GetSigningMethod(signingMethod.Alg))
	claims := token.Claims.(jwtbase.MapClaims)

	expire := time.Now().Add(expireIn)
	claims["exp"] = expire.Unix()
	claims["iat"] = time.Now().Unix()

	// currently only HSXXX algorithms are supported for issuing admin token, so we cast key to bytes array
	return token.SignedString([]byte(signingMethod.Key))
}