text:
"""
    test_build_text
    ~~~~~~~~~~~~~~~

    Test the build process with Text builder with the test root.

    :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

from docutils.utils import column_width
from sphinx.writers.text import MAXWIDTH

from util import with_app

def with_text_app(*args, **kw):
    default_kw = {
        'buildername': 'text',
        'srcdir': '(empty)',
        'confoverrides': {
            'project': 'text',
            'master_doc': 'contents',
        },
    }
    default_kw.update(kw)
    return with_app(*args, **default_kw)

@with_text_app()
def test_maxwitdh_with_prefix(app):
    long_string = u' '.join([u"ham"] * 30)
    contents = (
            u".. seealso:: %(long_string)s\n\n"
            u"* %(long_string)s\n"
            u"* %(long_string)s\n"
            u"\nspam egg\n"
            ) % locals()

    (app.srcdir / 'contents.rst').write_text(contents, encoding='utf-8')
    app.builder.build_all()
    result = (app.outdir / 'contents.txt').text(encoding='utf-8')

    lines = result.splitlines()
    line_widths = [column_width(line) for line in lines]
    assert max(line_widths) < MAXWIDTH
    assert lines[0].startswith('See also: ham')
    assert lines[1].startswith('  ham')
    assert lines[2] == ''
    assert lines[3].startswith('* ham')
    assert lines[4].startswith('  ham')
    assert lines[5] == ''
    assert lines[6].startswith('* ham')
    assert lines[7].startswith('  ham')
    assert lines[8] == ''
    assert lines[9].startswith('spam egg')

@with_text_app()
def test_lineblock(app):
    # regression test for #1109: need empty line after line block
    contents = (
            u"* one\n"
            u"\n"
            u"  | line-block 1\n"
            u"  | line-block 2\n"
            u"\n"
            u"followed paragraph.\n"
            )

    (app.srcdir / 'contents.rst').write_text(contents, encoding='utf-8')
    app.builder.build_all()
    result = (app.outdir / 'contents.txt').text(encoding='utf-8')

    expect = (
            u"* one\n"
            u"\n"
            u"     line-block 1\n"
            u"     line-block 2\n"
            u"\n"
            u"followed paragraph.\n"
            )

    assert result == expect

@with_text_app()
def test_multibyte_title_line(app):
    title = u'\u65e5\u672c\u8a9e'
    underline = u'=' * column_width(title)
    content = u'\n'.join((title, underline, u''))

    (app.srcdir / 'contents.rst').write_text(content, encoding='utf-8')
    app.builder.build_all()
    result = (app.outdir / 'contents.txt').text(encoding='utf-8')

    expect_underline = underline.replace('=', '*')
    result_underline = result.splitlines()[2].strip()
    assert expect_underline == result_underline

@with_text_app()
def test_multibyte_table(app):
    text = u'\u65e5\u672c\u8a9e'
    contents = (u"\n.. list-table::"
                 "\n"
                 "\n   - - spam"
                 "\n     - egg"
                 "\n"
                 "\n   - - %(text)s"
                 "\n     - %(text)s"
                 "\n" % locals())

    (app.srcdir / 'contents.rst').write_text(contents, encoding='utf-8')
    app.builder.build_all()
    result = (app.outdir / 'contents.txt').text(encoding='utf-8')

    lines = [line.strip() for line in result.splitlines() if line.strip()]
    line_widths = [column_width(line) for line in lines]
    assert len(set(line_widths)) == 1  # same widths

@with_text_app()
def test_multibyte_maxwidth(app):
    sb_text = u'abc'  #length=3
    mb_text = u'\u65e5\u672c\u8a9e'  #length=3

    sb_line = ' '.join([sb_text] * int(MAXWIDTH / 3))
    mb_line = ' '.join([mb_text] * int(MAXWIDTH / 3))
    mix_line = ' '.join([sb_text, mb_text] * int(MAXWIDTH / 6))

    contents = u'\n\n'.join((sb_line, mb_line, mix_line))

    (app.srcdir / 'contents.rst').write_text(contents, encoding='utf-8')
    app.builder.build_all()
    result = (app.outdir / 'contents.txt').text(encoding='utf-8')

    lines = [line.strip() for line in result.splitlines() if line.strip()]
    line_widths = [column_width(line) for line in lines]
    assert max(line_widths) < MAXWIDTH

redpajama_set_name: RedPajamaGithub


text:
CKEditor 4 - Releases
=====================

## Releases Code

This repository contains the official release versions of CKEditor.

There are three versions for each release - [basic, standard and full](http://ckeditor.com/demo#toolbar).
They differ by the number of compiled in plugins and configuration of the toolbar.

All versions available in this repository have been built using
[CKBuilder](http://ckeditor.com/builder), so they are ready
to be used in production environment.

## Documentation

The full editor documentation is available online at the following address:
http://docs.ckeditor.com

## Installation

To install one of available releases, just clone this repository and
switch to corresponding branch (see next section):

	git clone git://github.com/ckeditor/ckeditor-releases.git
	git co <release branch>

If you're using git for your project and you want to integrate CKEditor,
we recommend you adding this repository as a
[submodule](http://git-scm.com/book/en/Git-Tools-Submodules).

	git submodule add git://github.com/ckeditor/ckeditor-releases.git <clone dir>
	cd <clone dir>
	git co <release branch>
	cd <your repository dir>
	git commit -m "Added CKEditor submodule in <clone dir> directory."

### Available Branches

This repository contains the following branches:

  - **stable/(basic|standard|full)**: latest stable release tag point (non-beta).
  - **latest/(basic|standard|full)**: latest release tag point (including betas).
  - **A.B.x/(basic|standard|full)** (e.g. 4.0.x/basic): release freeze, tests and tagging. Hotfixing.

Additionally, all releases will have their relative tags in this form: 4.0, 4.0.1, etc.
For example: **4.0/(basic|standard|full)**.

## Checking Your Installation

The editor comes with a few sample pages that can be used to verify that
installation proceeded properly. Take a look at the `samples` directory.

To test your installation, just call the following page at your website:

	http://<your site>/<CKEditor installation path>/samples/index.html

For example:

	http://www.example.com/ckeditor/samples/index.html

### License

Licensed under the GPL, LGPL and MPL licenses, at your choice.

For full details about license, please check the LICENSE.md file.


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Server.Evolutions
{

	public class EvolutionBranch
	{
		#region Properties

		public string Name {get; set; }
		public int NewSpecies { get; set; }
		public int ReqScript { get; set; }
		public int Data1 { get; set; }
		public int Data2 { get; set; }
		public int Data3 { get; set; }

		#endregion

		public EvolutionBranch() {
			Name = "";
		}
	}
}


text:
package dhcp4

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"net"
	"sort"
)

// Option is a DHCP option.
type Option byte

// Some of the more commonly seen DHCP options. Refer to
// http://www.iana.org/assignments/bootp-dhcp-parameters/bootp-dhcp-parameters.xhtml
// for the full authoritative list.
const (
	OptSubnetMask         Option = 1  // IPMask
	OptTimeOffset         Option = 2  // int32
	OptRouters            Option = 3  // IPs
	OptDNSServers         Option = 6  // IPs
	OptHostname           Option = 12 // string
	OptBootFileSize       Option = 13 // uint16
	OptDomainName         Option = 15 // string
	OptInterfaceMTU       Option = 26 // uint16
	OptBroadcastAddr      Option = 28 // IP
	OptNTPServers         Option = 42 // IP
	OptVendorSpecific     Option = 43 // []byte
	OptRequestedIP        Option = 50 // IP
	OptLeaseTime          Option = 51 // uint32
	OptOverload           Option = 52 // byte
	OptServerIdentifier   Option = 54 // IP
	OptRequestedOptions   Option = 55 // []byte
	OptMessage            Option = 56 // string
	OptMaximumMessageSize Option = 57 // uint16
	OptRenewalTime        Option = 58 // uint32
	OptRebindingTime      Option = 59 // uint32
	OptVendorIdentifier   Option = 60 // string
	OptClientIdentifier   Option = 61 // string
	OptFQDN               Option = 81 // string

	// You shouldn't need to use the following directly. Instead,
	// refer to the fields in the Packet struct, and Marshal/Unmarshal
	// will handle encoding for you.

	OptTFTPServer      Option = 66 // string
	OptBootFile        Option = 67 // string
	OptDHCPMessageType Option = 53 // byte
)

// Options stores DHCP options.
type Options map[Option][]byte

var (
	errOptionNotPresent = errors.New("option not present in Options")
	errOptionWrongSize  = errors.New("option value is the wrong size")
)

// Unmarshal parses DHCP options into o.
func (o Options) Unmarshal(bs []byte) error {
	for len(bs) > 0 {
		opt := Option(bs[0])
		switch opt {
		case 0:
			// Padding byte
			bs = bs[1:]
		case 255:
			// End of options
			return nil
		default:
			// In theory, DHCP permits multiple instances of the same
			// option in a packet, as a way to have option values >255
			// bytes. Unfortunately, this is very loosely specified as
			// "up to individual options", and AFAICT, isn't at all
			// used in the wild.
			//
			// So, for now, seeing the same option twice in a packet
			// is going to be an error, until I get a bug report about
			// something that actually does it.
			if _, ok := o[opt]; ok {
				// Okay fine option 56 can be duped.
				if opt != 56 {
					return fmt.Errorf("packet has duplicate option %d (please file a bug with a pcap!)", opt)
				}
			}
			if len(bs) < 2 {
				return fmt.Errorf("option %d has no length byte", opt)
			}
			l := int(bs[1])
			if len(bs[2:]) < l {
				return fmt.Errorf("option %d claims to have %d bytes of payload, but only has %d bytes", opt, l, len(bs[2:]))
			}
			o[opt] = bs[2 : 2+l]
			bs = bs[2+l:]
		}
	}

	return errors.New("options are not terminated by a 255 byte")
}

// Marshal returns the wire encoding of o.
func (o Options) Marshal() ([]byte, error) {
	var ret bytes.Buffer
	opts, err := o.marshalLimited(&ret, 0, false)
	if err != nil {
		return nil, err
	}
	if len(opts) > 0 {
		return nil, errors.New("some options not written, but no limit was given (please file a bug)")
	}

	return ret.Bytes(), nil
}

// Copy returns a shallow copy of o.
func (o Options) Copy() Options {
	ret := make(Options, len(o))
	for k, v := range o {
		ret[k] = v
	}
	return ret
}

// marshalLimited serializes o into w. If nBytes > 0, as many options
// as possible are packed into that many bytes, inserting padding as
// needed, and the remaining unwritten options are returned.
func (o Options) marshalLimited(w io.Writer, nBytes int, skip52 bool) (Options, error) {
	ks := make([]int, 0, len(o))
	for n := range o {
		if n <= 0 || n >= 255 {
			return nil, fmt.Errorf("invalid DHCP option number %d", n)
		}
		ks = append(ks, int(n))
	}
	sort.Ints(ks)

	ret := make(Options)
	for _, n := range ks {
		opt := o[Option(n)]
		if len(opt) > 255 {
			return nil, fmt.Errorf("DHCP option %d has value >255 bytes", n)
		}

		// If space is limited, verify that we can fit the option plus
		// the final end-of-options marker.
		if nBytes > 0 && ((skip52 && n == 52) || len(opt)+3 > nBytes) {
			ret[Option(n)] = opt
			continue
		}

		w.Write([]byte{byte(n), byte(len(opt))})
		w.Write(opt)
		nBytes -= len(opt) + 2
	}

	w.Write([]byte{255})
	nBytes--
	if nBytes > 0 {
		w.Write(make([]byte, nBytes))
	}

	return ret, nil
}

// Bytes returns the value of option n as a byte slice.
func (o Options) Bytes(n Option) ([]byte, error) {
	bs := o[n]
	if bs == nil {
		return nil, errOptionNotPresent
	}
	return bs, nil
}

// String returns the value of option n as a string.
func (o Options) String(n Option) (string, error) {
	bs, err := o.Bytes(n)
	if err != nil {
		return "", err
	}
	return string(bs), err
}

// Byte returns the value of option n as a byte.
func (o Options) Byte(n Option) (byte, error) {
	bs, err := o.Bytes(n)
	if err != nil {
		return 0, err
	}
	if len(bs) != 1 {
		return 0, errOptionWrongSize
	}
	return bs[0], nil
}

// Uint16 returns the value of option n as a uint16.
func (o Options) Uint16(n Option) (uint16, error) {
	bs, err := o.Bytes(n)
	if err != nil {
		return 0, err
	}
	if len(bs) != 2 {
		return 0, errOptionWrongSize
	}
	return binary.BigEndian.Uint16(bs), nil
}

// Uint32 returns the value of option n as a uint32.
func (o Options) Uint32(n Option) (uint32, error) {
	bs, err := o.Bytes(n)
	if err != nil {
		return 0, err
	}
	if len(bs) != 4 {
		return 0, errOptionWrongSize
	}
	return binary.BigEndian.Uint32(bs), nil
}

// Int32 returns the value of option n as an int32.
func (o Options) Int32(n Option) (int32, error) {
	bs, err := o.Bytes(n)
	if err != nil {
		return 0, err
	}
	if len(bs) != 4 {
		return 0, errOptionWrongSize
	}
	return int32(binary.BigEndian.Uint32(bs)), nil
}

// IPs returns the value of option n as a list of IPv4 addresses.
func (o Options) IPs(n Option) ([]net.IP, error) {
	bs, err := o.Bytes(n)
	if err != nil {
		return nil, err
	}
	if len(bs) < 4 || len(bs)%4 != 0 {
		return nil, errOptionWrongSize
	}
	ret := make([]net.IP, 0, len(bs)/4)
	for i := 0; i < len(bs); i += 4 {
		ret = append(ret, net.IP(bs[i:i+4]))
	}
	return ret, nil
}

// IP returns the value of option n as an IPv4 address.
func (o Options) IP(n Option) (net.IP, error) {
	ips, err := o.IPs(n)
	if err != nil {
		return nil, err
	}
	if len(ips) != 1 {
		return nil, errOptionWrongSize
	}
	return ips[0], nil
}

// IPMask returns the value of option n as a net.IPMask.
func (o Options) IPMask(n Option) (net.IPMask, error) {
	bs := o[n]
	if bs == nil {
		return nil, fmt.Errorf("option %d not found", n)
	}
	if len(bs) != 4 {
		return nil, fmt.Errorf("option %d is the wrong size for an IPMask", n)
	}
	return net.IPMask(bs), nil
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>circle.svg bg</title>

...


text:
<?php

namespace Drafterbit\System\Log;

use Drafterbit\System\Log\EntityFormatterInterface;
use Symfony\Component\Translation\TranslatorInterface;

class DisplayFormatter
{
    protected $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * Log Entity Labels.
     *
     * @var array
     */
    protected $entityFormatters = [];

    function addEntityFormatter(EntityFormatterInterface $entityFormatter)
    {
        $this->entityFormatters[$entityFormatter->getName()] = $entityFormatter;
    }

    /**
     * Format log message
     *
     * @param  string $line
     * @return string
     */
    public function format($line, $context = null)
    {
        $context = json_decode($context, true);

        $replaces = [];
        foreach ($context as $key => $value) {
            $replaces['%'.$key.'%'] = $this->resolve($key, $value);
        }

        return $this->translator->trans($line, $replaces);
    }

    private function resolve($entityPlaceholder, $id)
    {
        $entity = trim($entityPlaceholder, '%');

        if($this->hasEntityFormatter($entity)) {
            return $this->getEntityFormatter($entity)->format($id);
        }

        return "$entity:$id";
    }

    public function getEntityFormatter($entity)
    {
        return $this->entityFormatters[$entity];
    }

    public function hasEntityFormatter($entity)
    {
        return isset($this->entityFormatters[$entity]);
    }
}


text:
<?php

/**
 * This is a mixin for the BaseFormDoctrine class.
 *
 * It is not necessary to provide this via inheritance, so we can give the user
 * as much freedom as possible in designing his inheritance structure.
 *
 * @package jmsFormsPlugin
 * @subpackage form
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class jmsBaseFormDoctrine
{
  /**
   * Listen to the form.method_not_found event
   *
   * @param sfEvent $event
   * @return void
   */
  public static function listenToFormMethodNotFound(sfEvent $event)
  {
    $form = $event->getSubject();

    // do not process events of non-object forms
    if (!$form instanceof BaseFormDoctrine || $form instanceof FakeObjectForm)
      return;

    switch (strtolower($event['method']))
    {
      case 'setobject':
        if (count($event['arguments']) !== 1)
          throw new InvalidArugmentException(
            'The number of arguments is invalid.');

        self::setObject($form, $event['arguments'][0]);
        $event->setProcessed(true);

        break;

      case 'embedcollection':
        if (count($event['arguments']) < 2 || count($event['arguments']) > 3)
          throw new InvalidArgumentException(
            'The number of arguments is invalid.');

        self::embedCollection(
          $form,
          $event['arguments'][0],
          $event['arguments'][1],
          isset($event['arguments'][2])? $event['arguments'][2] : array()
        );
        $event->setProcessed(true);

        break;
    }
  }

  /**
   * A convenience method for embedding collections.
   *
   * @param BaseFormDoctrine $form
   * @param string $formName
   * @param string $relationAlias
   * @param array $options
   * @return void
   */
  private static function embedCollection(BaseFormDoctrine $form,
                       $formName, $relationAlias, array $options)
  {
    // set required options
    $options['parent_object'] = $form->getObject();
    $options['relation_alias'] = $relationAlias;

    // initialize and embed the collection form
    $collectionForm = new jmsBaseCollectionForm(array(), $options);
    $form->embedForm($formName, $collectionForm);
  }

  /**
   * Sets the object of the given form. You should use this method with caution
   * and only when you know exactly what you are doing.
   *
   * @param BaseFormDoctrine $form
   * @param Doctrine_Record $object
   * @return void
   */
  private static function setObject(BaseFormDoctrine $form,
                                    Doctrine_Record $object)
  {
    // we need to do this via reflection since the property is declared
    // protected on sfFormObject
    $reflection = new ReflectionObject($form);
    $property = $reflection->getProperty('object');
    $property->setAccessible(true);
    $property->setValue($form, $object);
    $property->setAccessible(false);
  }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.06.29 at 09:03:32 AM BST
//

package org.xcri.profiles._1_2.catalog.terms;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import org.purl.dc.elements._1.DescriptionDType;

/**
 * Description refinement typically used to specify hours of study expected of a learner for successful completion
 *
 *
Java class for studyHours complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="studyHours">
 *   <complexContent>
 *     <restriction base="{http://purl.org/dc/elements/1.1/}descriptionDType">
 *       <sequence>
 *         <element ref="{http://www.w3.org/1999/xhtml}div" minOccurs="0"/>
 *       </sequence>
 *       <attribute ref="{http://www.w3.org/XML/1998/namespace}lang"/>
 *       <attribute name="href" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "studyHours")
public class StudyHours
    extends DescriptionDType
{

}


text:
package com.google.cloud.apigeeregistry.v1.samples;

// [START apigeeregistry_v1_generated_Registry_GetApiSpec_String_sync]
import com.google.cloud.apigeeregistry.v1.ApiSpec;
import com.google.cloud.apigeeregistry.v1.ApiSpecName;
import com.google.cloud.apigeeregistry.v1.RegistryClient;

public class SyncGetApiSpecString {

  public static void main(String[] args) throws Exception {
    syncGetApiSpecString();
  }

  public static void syncGetApiSpecString() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (RegistryClient registryClient = RegistryClient.create()) {
      String name =
          ApiSpecName.of("[PROJECT]", "[LOCATION]", "[API]", "[VERSION]", "[SPEC]").toString();
      ApiSpec response = registryClient.getApiSpec(name);
    }
  }
}
// [END apigeeregistry_v1_generated_Registry_GetApiSpec_String_sync]


text:
<?php

namespace Hyn\ManagementInterface\Http\Controllers;

use Illuminate\Contracts\Routing\ResponseFactory;
use Laraflock\Dashboard\Controllers\BaseDashboardController;
use Hyn\MultiTenant\Contracts\TenantRepositoryContract;
use Hyn\MultiTenant\Validators\TenantValidator;
use Hyn\MultiTenant\Models\Tenant;

class TenantController extends BaseDashboardController
{
    /**
     * Shows list of tenants.
     *
     * @param TenantRepositoryContract $tenant
     *
     * @return $this
     */
    public function index(TenantRepositoryContract $tenant)
    {
        return view('management-interface::tenant.index')->with(['tenants' => $tenant->paginated()]);
    }

    /**
     * Shows the delete tenant form.
     *
     * @param Tenant $tenant
     * @return \Illuminate\View\View
     */
    public function delete(Tenant $tenant)
    {
        $deleteRoute = route('management-interface.tenant.deleted', $tenant->present()->urlArguments);

        $name = $tenant->present()->name;

        return view('management-interface::layouts.delete', compact('tenant', 'deleteRoute', 'name'));
    }

    /**
     * Deletes the tenant after submit.
     *
     * @param Tenant $tenant
     * @return $this|bool|\Hyn\Framework\Models\AbstractModel|null
     */
    public function deleted(Tenant $tenant)
    {
        return (new TenantValidator())->catchFormRequest($tenant, redirect()->route('management-interface.tenant.index'));
    }

    /**
     * Shows tenant creation page.
     *
     * @return array|\Illuminate\View\View
     */
    public function create()
    {
        return view('management-interface::tenant.create');
    }

    /**
     * Creates tenant.
     *
     * @param TenantRepositoryContract $tenant
     *
     * @return $this|bool|\Hyn\Framework\Models\AbstractModel|null
     */
    public function store(TenantRepositoryContract $tenant)
    {
        return (new TenantValidator())->catchFormRequest($tenant->newInstance(), redirect()->route('management-interface.tenant.index'));
    }

    /**
     * Loads tenants for select2 fields and such.
     *
     * @param TenantRepositoryContract $tenant
     * @param ResponseFactory          $response
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajax(TenantRepositoryContract $tenant, ResponseFactory $response)
    {
        return $response->json($tenant->ajaxQuery('name'));
    }
}


text:
from .common import *

from av.video.frame import VideoFrame
from av.filter import Graph, Filter

class TestFilters(TestCase):

    def test_filter_descriptor(self):

        f = Filter('testsrc')
        self.assertEqual(f.name, 'testsrc')
        self.assertEqual(f.description, 'Generate test pattern.')
        self.assertFalse(f.dynamic_inputs)
        self.assertEqual(len(f.inputs), 0)
        self.assertFalse(f.dynamic_outputs)
        self.assertEqual(len(f.outputs), 1)
        self.assertEqual(f.outputs[0].name, 'default')
        self.assertEqual(f.outputs[0].type, 'video')

    def test_dynamic_filter_descriptor(self):

        f = Filter('split')
        self.assertFalse(f.dynamic_inputs)
        self.assertEqual(len(f.inputs), 1)
        self.assertTrue(f.dynamic_outputs)
        self.assertEqual(len(f.outputs), 0)

    def test_generator_graph(self):

        graph = Graph()
        src = graph.add('testsrc')
        lutrgb = graph.add('lutrgb', "r=maxval+minval-val:g=maxval+minval-val:b=maxval+minval-val", name='invert')
        sink = graph.add('buffersink')
        src.link_to(lutrgb)
        lutrgb.link_to(sink)

        # pads and links
        self.assertIs(src.outputs[0].link.output, lutrgb.inputs[0])
        self.assertIs(lutrgb.inputs[0].link.input, src.outputs[0])

        frame = sink.pull()
        self.assertIsInstance(frame, VideoFrame)
        frame.to_image().save('sandbox/mandelbrot2.png')

    def test_auto_find_sink(self):

        graph = Graph()
        src = graph.add('testsrc')
        src.link_to(graph.add('buffersink'))
        graph.configure()

        frame = graph.pull()
        frame.to_image().save('sandbox/mandelbrot3.png')

    def test_delegate_sink(self):

        graph = Graph()
        src = graph.add('testsrc')
        src.link_to(graph.add('buffersink'))
        graph.configure()

        print src.outputs

        frame = src.pull()
        frame.to_image().save('sandbox/mandelbrot4.png')

    def test_haldclut_graph(self):

        raise SkipTest()

        graph = Graph()

        img = Image.open(fate_suite('png1/lena-rgb24.png'))
        frame = VideoFrame.from_image(img)
        img_source = graph.add_buffer(frame)

        hald_img = Image.open('hald_7.png')
        hald_frame = VideoFrame.from_image(hald_img)
        hald_source = graph.add_buffer(hald_frame)

        try:
            hald_filter = graph.add('haldclut')
        except ValueError:
            # Not in Libav.
            raise SkipTest()

        sink = graph.add('buffersink')

        img_source.link(0, hald_filter, 0)
        hald_source.link(0, hald_filter, 1)
        hald_filter.link(0, sink, 0)
        graph.config()

        self.assertIs(img_source.outputs[0].linked_to, hald_filter.inputs[0])
        self.assertIs(hald_source.outputs[0].linked_to, hald_filter.inputs[1])
        self.assertIs(hald_filter.outputs[0].linked_to, sink.inputs[0])

        hald_source.push(hald_frame)

        img_source.push(frame)

        frame = sink.pull()
        self.assertIsInstance(frame, VideoFrame)
        frame.to_image().save('sandbox/filtered.png')


text:
namespace {

uint32_t parseWebSocketKey(const std::string& key) {
    uint32_t keyNumber = 0;
    uint32_t numSpaces = 0;
    for (auto c : key) {
        if (c >= '0' && c <= '9') {
            keyNumber = keyNumber * 10 + c - '0';
        } else if (c == ' ') {
            ++numSpaces;
        }
    }
    return numSpaces > 0 ? keyNumber / numSpaces : 0;
}

char* extractLine(uint8_t*& first, uint8_t* last, char** colon = nullptr) {
    for (uint8_t* ptr = first; ptr < last - 1; ++ptr) {
        if (ptr[0] == '\r' && ptr[1] == '\n') {
            ptr[0] = 0;
            uint8_t* result = first;
            first = ptr + 2;
            return reinterpret_cast<char*>(result);
        }
        if (colon && ptr[0] == ':' && *colon == nullptr) {
            *colon = reinterpret_cast<char*>(ptr);
        }
    }
    return nullptr;
}

const std::unordered_map<std::string, std::string> contentTypes = {
    {"txt", "text/plain"},
    {"css", "text/css"},
    {"csv", "text/csv"},
    {"htm", "text/html"},
    {"html", "text/html"},
    {"xml", "text/xml"},
    {"js", "text/javascript"}, // Technically it should be application/javascript (RFC 4329), but IE8 struggles with that
    {"xhtml", "application/xhtml+xml"},
    {"json", "application/json"},
    {"pdf", "application/pdf"},
    {"zip", "application/zip"},
    {"tar", "application/x-tar"},
    {"gif", "image/gif"},
    {"jpeg", "image/jpeg"},
    {"jpg", "image/jpeg"},
    {"tiff", "image/tiff"},
    {"tif", "image/tiff"},
    {"png", "image/png"},
    {"svg", "image/svg+xml"},
    {"ico", "image/x-icon"},
    {"swf", "application/x-shockwave-flash"},
    {"mp3", "audio/mpeg"},
    {"wav", "audio/x-wav"},
    {"ttf", "font/ttf"},
};

std::string getExt(const std::string& path) {
    auto lastDot = path.find_last_of('.');
    if (lastDot != std::string::npos) {
        return path.substr(lastDot + 1);
    }
    return "";
}

const std::string& getContentType(const std::string& path) {
    auto it = contentTypes.find(getExt(path));
    if (it != contentTypes.end()) {
        return it->second;
    }
    static const std::string defaultType("text/html");
    return defaultType;
}

// Cacheability is only set for resources that *REQUIRE* caching for browser support reasons.
// It's off for everything else to save on browser reload headaches during development, at
// least until we support ETags or If-Modified-Since: type checking, which we may never do.
bool isCacheable(const std::string& path) {
    std::string extension = getExt(path);
    if (extension == "mp3" || extension == "wav") {
        return true;
    }
    return false;
}

constexpr size_t ReadWriteBufferSize = 16 * 1024;
constexpr size_t MaxWebsocketMessageSize = 16384;
constexpr size_t MaxHeadersSize = 64 * 1024;

class PrefixWrapper : public seasocks::Logger {
    std::string _prefix;
    std::shared_ptr<Logger> _logger;

public:
    PrefixWrapper(const std::string& prefix, std::shared_ptr<Logger> logger)
            : _prefix(prefix), _logger(logger) {
    }

    void log(Level level, const char* message) override {
        _logger->log(level, (_prefix + message).c_str());
    }
};

bool hasConnectionType(const std::string& connection, const std::string& type) {
    for (auto conType : seasocks::split(connection, ',')) {
        while (!conType.empty() && isspace(conType[0]))
            conType = conType.substr(1);
        if (seasocks::caseInsensitiveSame(conType, type))
            return true;
    }
    return false;
}

} // namespace

namespace seasocks {

struct Connection::Writer : ResponseWriter {
    Connection* _connection;
    explicit Writer(Connection& connection)
            : _connection(&connection) {
    }

    void detach() {
        _connection = nullptr;
    }

    void begin(ResponseCode responseCode, TransferEncoding encoding) override {
        if (_connection)
            _connection->begin(responseCode, encoding);
    }
    void header(const std::string& header, const std::string& value) override {
        if (_connection)
            _connection->header(header, value);
    }
    void payload(const void* data, size_t size, bool flush) override {
        if (_connection)
            _connection->payload(data, size, flush);
    }
    void finish(bool keepConnectionOpen) override {
        if (_connection)
            _connection->finish(keepConnectionOpen);
    }
    void error(ResponseCode responseCode, const std::string& payload) override {
        if (_connection)
            _connection->error(responseCode, payload);
    }

    bool isActive() const override {
        return _connection;
    }
};

Connection::Connection(
    std::shared_ptr<Logger> logger,
    ServerImpl& server,
    NativeSocketType fd,
    const sockaddr_in& address)
        : _logger(std::make_shared<PrefixWrapper>(formatAddress(address) + " : ", logger)),
          _server(server),
          _fd(fd),
          _shutdown(false),
          _hadSendError(false),
          _closeOnEmpty(false),
          _registeredForWriteEvents(false),
          _address(address),
          _bytesSent(0),
          _bytesReceived(0),
          _shutdownByUser(false),
          _transferEncoding(TransferEncoding::Raw),
          _chunk(0u),
          _writer(std::make_shared<Writer>(*this)),
          _state(State::READING_HEADERS) {
}

Connection::~Connection() {
    _server.checkThread();
    finalise();
}

void Connection::close() {
    // This is the user-side close requests ONLY! You should Call closeInternal
    _shutdownByUser = true;
    closeInternal();
}

void Connection::closeWhenEmpty() {
    if (_outBuf.empty()) {
        closeInternal();
    } else {
        _closeOnEmpty = true;
    }
}

void Connection::closeInternal() {
    // It only actually only calls shutdown on the socket,
    // leaving the close of the FD and the cleanup until the destructor runs.
    _server.checkThread();
    if (_fd != -1 && !_shutdown && ::shutdown(_fd, SHUT_RDWR) == -1) {
        LS_WARNING(_logger, "Unable to shutdown socket : " << getLastError());
    }
    _shutdown = true;
}

void Connection::finalise() {
    if (_response) {
        _response->cancel();
        _response.reset();
        _writer->detach();
        _writer.reset();
    }
    if (_webSocketHandler) {
        _webSocketHandler->onDisconnect(this);
        _webSocketHandler.reset();
    }
    if (_fd != -1) {
        _server.remove(this);
        LS_DEBUG(_logger, "Closing socket");
#ifndef _WIN32
        ::close(_fd);
#else
        ::closesocket(_fd);
#endif
    }
    _fd = InvalidSocket;
}

ssize_t Connection::safeSend(const void* data, size_t size) {
    if (_fd == -1 || _hadSendError || _shutdown) {
        // Ignore further writes to the socket, it's already closed or has been shutdown
        return -1;
    }
#ifndef WIN32
    auto sendResult = ::send(_fd, data, size, MSG_NOSIGNAL);
#else
    auto sendResult = ::send(_fd, static_cast<const char*>(data),
                             static_cast<int>(size), MSG_NOSIGNAL);
#endif
    if (sendResult == -1) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            // Treat this as if zero bytes were written.
            return 0;
        }
        LS_WARNING(_logger, "Unable to write to socket : " << getLastError() << " - disabling further writes");
        closeInternal();
    } else {
        _bytesSent += sendResult;
    }
    return sendResult;
}

bool Connection::write(const void* data, size_t size, bool flushIt) {
    if (closed() || _closeOnEmpty) {
        return false;
    }
    if (size) {
        ssize_t bytesSent = 0;
        if (_outBuf.empty() && flushIt) {
            // Attempt fast path, send directly.
            bytesSent = safeSend(data, size);
            if (bytesSent == static_cast<int>(size)) {
                // We sent directly.
                return true;
            }
            if (bytesSent == -1) {
                return false;
            }
        }
        size_t bytesToBuffer = size - bytesSent;
        size_t endOfBuffer = _outBuf.size();
        size_t newBufferSize = endOfBuffer + bytesToBuffer;
        if (newBufferSize >= _server.clientBufferSize()) {
            LS_WARNING(_logger, "Closing connection: buffer size too large ("
                                    << newBufferSize << " >= " << _server.clientBufferSize() << ")");
            closeInternal();
            return false;
        }
        _outBuf.resize(newBufferSize);
        memcpy(&_outBuf[endOfBuffer], reinterpret_cast<const uint8_t*>(data) + bytesSent, bytesToBuffer);
    }
    if (flushIt) {
        return flush();
    }
    return true;
}

bool Connection::bufferLine(const char* line) {
    static const char crlf[] = {'\r', '\n'};
    if (!write(line, strlen(line), false))
        return false;
    return write(crlf, 2, false);
}

bool Connection::bufferLine(const std::string& line) {
    std::string lineAndCrlf = line + "\r\n";
    return write(lineAndCrlf.c_str(), lineAndCrlf.length(), false);
}

void Connection::handleDataReadyForRead() {
    if (closed()) {
        return;
    }
    size_t curSize = _inBuf.size();
    _inBuf.resize(curSize + ReadWriteBufferSize);
#ifndef _WIN32
    auto result = ::read(_fd, &_inBuf[curSize], ReadWriteBufferSize);
#else
    auto result = ::recv(_fd, reinterpret_cast<char*>(&_inBuf[curSize]), ReadWriteBufferSize, 0);
#endif
    if (result == -1) {
        LS_WARNING(_logger, "Unable to read from socket : " << getLastError());
        return;
    }
    if (result == 0) {
        LS_DEBUG(_logger, "Remote end closed connection");
        closeInternal();
        return;
    }
    _bytesReceived += result;
    _inBuf.resize(curSize + result);
    handleNewData();
}

void Connection::handleDataReadyForWrite() {
    if (closed()) {
        return;
    }
    flush();
}

bool Connection::flush() {
    if (_outBuf.empty()) {
        return true;
    }
    auto numSent = safeSend(&_outBuf[0], _outBuf.size());
    if (numSent == -1) {
        return false;
    }
    _outBuf.erase(_outBuf.begin(), _outBuf.begin() + numSent);
    if (!_outBuf.empty() && !_registeredForWriteEvents) {
        if (!_server.subscribeToWriteEvents(this)) {
            return false;
        }
        _registeredForWriteEvents = true;
    } else if (_outBuf.empty() && _registeredForWriteEvents) {
        if (!_server.unsubscribeFromWriteEvents(this)) {
            return false;
        }
        _registeredForWriteEvents = false;
    }
    if (_outBuf.empty() && !closed() && _closeOnEmpty) {
        LS_DEBUG(_logger, "Ready for close, now empty");
        closeInternal();
    }
    return true;
}

bool Connection::closed() const {
    return _fd == -1 || _shutdown;
}

void Connection::handleNewData() {
    switch (_state) {
        case State::READING_HEADERS:
            handleHeaders();
            break;
        case State::READING_WEBSOCKET_KEY3:
            handleWebSocketKey3();
            break;
        case State::HANDLING_HIXIE_WEBSOCKET:
            handleHixieWebSocket();
            break;
        case State::HANDLING_HYBI_WEBSOCKET:
            handleHybiWebSocket();
            break;
        case State::BUFFERING_POST_DATA:
            handleBufferingPostData();
            break;
        case State::AWAITING_RESPONSE_BEGIN:
        case State::SENDING_RESPONSE_BODY:
        case State::SENDING_RESPONSE_HEADERS:
            break;
        default:
            assert(false);
            break;
    }
}

void Connection::handleHeaders() {
    if (_inBuf.size() < 4) {
        return;
    }
    for (size_t i = 0; i <= _inBuf.size() - 4; ++i) {
        if (_inBuf[i] == '\r' &&
            _inBuf[i + 1] == '\n' &&
            _inBuf[i + 2] == '\r' &&
            _inBuf[i + 3] == '\n') {
            if (!processHeaders(&_inBuf[0], &_inBuf[i + 2])) {
                closeInternal();
                return;
            }
            _inBuf.erase(_inBuf.begin(), _inBuf.begin() + i + 4);
            handleNewData();
            return;
        }
    }
    if (_inBuf.size() > MaxHeadersSize) {
        sendUnsupportedError("Headers too big");
    }
}

void Connection::handleWebSocketKey3() {
    constexpr auto WebSocketKeyLen = 8u;
    if (_inBuf.size() < WebSocketKeyLen) {
        return;
    }

    struct {
        uint32_t key1;
        uint32_t key2;
        char key3[WebSocketKeyLen];
    } md5Source;

    auto key1 = parseWebSocketKey(_request->getHeader("Sec-WebSocket-Key1"));
    auto key2 = parseWebSocketKey(_request->getHeader("Sec-WebSocket-Key2"));

    LS_DEBUG(_logger, "Got a hixie websocket with key1=0x" << std::hex << key1 << ", key2=0x" << key2);

    md5Source.key1 = htonl(key1);
    md5Source.key2 = htonl(key2);
    memcpy(&md5Source.key3, &_inBuf[0], WebSocketKeyLen);

    uint8_t digest[16];
    md5_state_t md5state;
    md5_init(&md5state);
    md5_append(&md5state, reinterpret_cast<const uint8_t*>(&md5Source), sizeof(md5Source));
    md5_finish(&md5state, digest);

    LS_DEBUG(_logger, "Attempting websocket upgrade");

    bufferResponseAndCommonHeaders(ResponseCode::WebSocketProtocolHandshake);
    bufferLine("Upgrade: websocket");
    bufferLine("Connection: Upgrade");
    bool allowCrossOrigin = _server.isCrossOriginAllowed(_request->getRequestUri());
    if (_request->hasHeader("Origin") && allowCrossOrigin) {
        bufferLine("Sec-WebSocket-Origin: " + _request->getHeader("Origin"));
    }
    if (_request->hasHeader("Host")) {
        auto host = _request->getHeader("Host");
        if (!allowCrossOrigin) {
            bufferLine("Sec-WebSocket-Origin: http://" + host);
        }
        bufferLine("Sec-WebSocket-Location: ws://" + host + _request->getRequestUri());
    }
    pickProtocol();
    bufferLine("");

    write(&digest, 16, true);

    _state = State::HANDLING_HIXIE_WEBSOCKET;
    _inBuf.erase(_inBuf.begin(), _inBuf.begin() + 8);
    if (_webSocketHandler) {
        _webSocketHandler->onConnect(this);
    }
}

void Connection::pickProtocol() {
    static std::string protocolHeader = "Sec-WebSocket-Protocol";
    if (!_request->hasHeader(protocolHeader) || !_webSocketHandler)
        return;
    // Ideally we need o support this header being set multiple times...but the headers don't support that.
    auto protocols = split(_request->getHeader(protocolHeader), ',');
    LS_DEBUG(_logger, "Requested protocols:");
    std::transform(protocols.begin(), protocols.end(), protocols.begin(), trimWhitespace);
    for (auto&& p : protocols) {
        LS_DEBUG(_logger, "  " + p);
    }
    auto choice = _webSocketHandler->chooseProtocol(protocols);
    if (choice >= 0 && choice < static_cast<ssize_t>(protocols.size())) {
        LS_DEBUG(_logger, "Chose protocol " + protocols[choice]);
        bufferLine(protocolHeader + ": " + protocols[choice]);
    }
}

void Connection::handleBufferingPostData() {
    if (_request->consumeContent(_inBuf)) {
        _state = State::READING_HEADERS;
        if (!handlePageRequest()) {
            closeInternal();
        }
    }
}

void Connection::send(const char* webSocketResponse) {
    _server.checkThread();
    if (_shutdown) {
        if (_shutdownByUser) {
            LS_ERROR(_logger, "Server wrote to connection after closing it");
        }
        return;
    }
    auto messageLength = strlen(webSocketResponse);
    if (_state == State::HANDLING_HIXIE_WEBSOCKET) {
        uint8_t zero = 0;
        if (!write(&zero, 1, false))
            return;
        if (!write(webSocketResponse, messageLength, false))
            return;
        uint8_t effeff = 0xff;
        write(&effeff, 1, true);
        return;
    }
    sendHybi(static_cast<uint8_t>(HybiPacketDecoder::Opcode::Text),
             reinterpret_cast<const uint8_t*>(webSocketResponse), messageLength);
}

void Connection::send(const uint8_t* webSocketResponse, size_t length) {
    _server.checkThread();
    if (_shutdown) {
        if (_shutdownByUser) {
            LS_ERROR(_logger, "Client wrote to connection after closing it");
        }
        return;
    }
    if (_state == State::HANDLING_HIXIE_WEBSOCKET) {
        LS_ERROR(_logger, "Hixie does not support binary");
        return;
    }
    sendHybi(static_cast<uint8_t>(HybiPacketDecoder::Opcode::Binary), webSocketResponse, length);
}

void Connection::sendHybi(uint8_t opcode, const uint8_t* webSocketResponse, size_t messageLength) {
    uint8_t firstByte = 0x80 | opcode;
    if (_perMessageDeflate)
        firstByte |= 0x40;
    if (!write(&firstByte, 1, false))
        return;

    if (_perMessageDeflate) {
        std::vector<uint8_t> compressed;

        zlibContext.deflate(webSocketResponse, messageLength, compressed);

        LS_DEBUG(_logger, "Compression result: " << messageLength << " bytes -> " << compressed.size() << " bytes");
        sendHybiData(compressed.data(), compressed.size());
    } else {
        sendHybiData(webSocketResponse, messageLength);
    }
}

void Connection::sendHybiData(const uint8_t* webSocketResponse, size_t messageLength) {
    if (messageLength < 126) {
        const auto nextByte = static_cast<uint8_t>(messageLength); // No MASK bit set.
        if (!write(&nextByte, 1, false))
            return;
    } else if (messageLength < 65536) {
        const uint8_t nextByte = 126; // No MASK bit set.
        if (!write(&nextByte, 1, false))
            return;
        // htons in Windows takes a u_short
        const auto lengthBytes = htons(static_cast<uint16_t>(messageLength));
        if (!write(&lengthBytes, 2, false))
            return;
    } else {
        const uint8_t nextByte = 127; // No MASK bit set.
        if (!write(&nextByte, 1, false))
            return;
        const uint64_t lengthBytes = __bswap_64(messageLength);
        if (!write(&lengthBytes, 8, false))
            return;
    }
    write(webSocketResponse, messageLength, true);
}

std::shared_ptr<Credentials> Connection::credentials() const {
    _server.checkThread();
    return _request ? _request->credentials() : std::shared_ptr<Credentials>();
}

void Connection::handleHixieWebSocket() {
    if (_inBuf.empty()) {
        return;
    }
    size_t messageStart = 0;
    while (messageStart < _inBuf.size()) {
        if (_inBuf[messageStart] != 0) {
            LS_WARNING(_logger, "Error in WebSocket input stream (got " << (int) _inBuf[messageStart] << ")");
            closeInternal();
            return;
        }
        // TODO: UTF-8
        size_t endOfMessage = 0;
        for (size_t i = messageStart + 1; i < _inBuf.size(); ++i) {
            if (_inBuf[i] == 0xff) {
                endOfMessage = i;
                break;
            }
        }
        if (endOfMessage != 0) {
            _inBuf[endOfMessage] = 0;
            handleWebSocketTextMessage(reinterpret_cast<const char*>(&_inBuf[messageStart + 1]));
            messageStart = endOfMessage + 1;
        } else {
            break;
        }
    }
    if (messageStart != 0) {
        _inBuf.erase(_inBuf.begin(), _inBuf.begin() + messageStart);
    }
    if (_inBuf.size() > MaxWebsocketMessageSize) {
        LS_WARNING(_logger, "WebSocket message too long");
        closeInternal();
    }
}

void Connection::handleHybiWebSocket() {
    if (_inBuf.empty()) {
        return;
    }
    HybiPacketDecoder decoder(*_logger, _inBuf);
    bool done = false;
    while (!done) {
        std::vector<uint8_t> decodedMessage;
        bool deflateNeeded = false;

        auto messageState = decoder.decodeNextMessage(decodedMessage, deflateNeeded);

        if (deflateNeeded) {
            if (!_perMessageDeflate) {
                LS_WARNING(_logger, "Received deflated hybi frame but deflate wasn't negotiated");
                closeInternal();
                return;
            }

            size_t compressed_size = decodedMessage.size();

            std::vector<uint8_t> decompressed;
            int zlibError;

            // Note: inflate() alters decodedMessage
            bool success = zlibContext.inflate(decodedMessage, decompressed, zlibError);

            if (!success) {
                LS_WARNING(_logger, "Decompression error from zlib: " << zlibError);
                closeInternal();
                return;
            }

            LS_DEBUG(_logger, "Decompression result: " << compressed_size << " bytes -> " << decodedMessage.size() << " bytes");

            decodedMessage.swap(decompressed);
        }

        switch (messageState) {
            default:
                closeInternal();
                LS_WARNING(_logger, "Unknown HybiPacketDecoder state");
                return;
            case HybiPacketDecoder::MessageState::Error:
                closeInternal();
                return;
            case HybiPacketDecoder::MessageState::TextMessage:
                decodedMessage.push_back(0); // avoids a copy
                handleWebSocketTextMessage(reinterpret_cast<const char*>(&decodedMessage[0]));
                break;
            case HybiPacketDecoder::MessageState::BinaryMessage:
                handleWebSocketBinaryMessage(decodedMessage);
                break;
            case HybiPacketDecoder::MessageState::Ping:
                sendHybi(static_cast<uint8_t>(HybiPacketDecoder::Opcode::Pong),
                         &decodedMessage[0], decodedMessage.size());
                break;
            case HybiPacketDecoder::MessageState::Pong:
                // Pongs can be sent unsolicited (MSIE and Edge do this)
                // The spec says to ignore them.
                break;
            case HybiPacketDecoder::MessageState::NoMessage:
                done = true;
                break;
            case HybiPacketDecoder::MessageState::Close:
                LS_DEBUG(_logger, "Received WebSocket close");
                closeInternal();
                return;
        }
    }
    if (decoder.numBytesDecoded() != 0) {
        _inBuf.erase(_inBuf.begin(), _inBuf.begin() + decoder.numBytesDecoded());
    }
    if (_inBuf.size() > MaxWebsocketMessageSize) {
        LS_WARNING(_logger, "WebSocket message too long");
        closeInternal();
    }
}

void Connection::handleWebSocketTextMessage(const char* message) {
    LS_DEBUG(_logger, "Got text web socket message: '" << message << "'");
    if (_webSocketHandler) {
        _webSocketHandler->onData(this, message);
    }
}

void Connection::handleWebSocketBinaryMessage(const std::vector<uint8_t>& message) {
    LS_DEBUG(_logger, "Got binary web socket message (size: " << message.size() << ")");
    if (_webSocketHandler) {
        _webSocketHandler->onData(this, &message[0], message.size());
    }
}

bool Connection::sendError(ResponseCode errorCode, const std::string& body) {
    assert(_state != State::HANDLING_HIXIE_WEBSOCKET);
    auto errorNumber = static_cast<int>(errorCode);
    auto message = ::name(errorCode);
    bufferResponseAndCommonHeaders(errorCode);
    auto errorContent = findEmbeddedContent("/_error.html");
    std::string document;
    if (errorContent) {
        document.assign(errorContent->data, errorContent->data + errorContent->length);
        replace(document, "%%ERRORCODE%%", toString(errorNumber));
        replace(document, "%%MESSAGE%%", message);
        replace(document, "%%BODY%%", body);
    } else {
        std::stringstream documentStr;
        documentStr << "<html><head><title>" << errorNumber << " - " << message << "</title></head>"
                    << "<body><h1>" << errorNumber << " - " << message << "</h1>"
                    << "<div>" << body << "</div><hr/><div><i>Powered by "
                                          "<a href=\"https://github.com/mattgodbolt/seasocks\">Seasocks</a></i></div></body></html>";
        document = documentStr.str();
    }
    bufferLine("Content-Length: " + toString(document.length()));
    bufferLine("Connection: close");
    bufferLine("");
    bufferLine(document);
    if (!flush()) {
        return false;
    }
    closeWhenEmpty();
    return true;
}

bool Connection::sendUnsupportedError(const std::string& reason) {
    return sendError(ResponseCode::NotImplemented, reason);
}

bool Connection::send404() {
    auto path = getRequestUri();
    auto embedded = findEmbeddedContent(path);
    if (embedded) {
        return sendData(getContentType(path), embedded->data, embedded->length);
    } else if (strcmp(path.c_str(), "/_livestats.js") == 0) {
        auto stats = _server.getStatsDocument();
        return sendData("text/javascript", stats.c_str(), stats.length());
    } else {
        return sendError(ResponseCode::NotFound, "Unable to find resource for: " + path);
    }
}

bool Connection::sendBadRequest(const std::string& reason) {
    return sendError(ResponseCode::BadRequest, reason);
}

bool Connection::sendISE(const std::string& error) {
    return sendError(ResponseCode::InternalServerError, error);
}

bool Connection::processHeaders(uint8_t* first, uint8_t* last) {
    // Ideally we'd copy off [first, last] now into a header structure here.
    // Be careful about lifetimes though and multiple requests coming in, should
    // we ever support HTTP pipelining and/or long-lived requests.
    char* requestLine = extractLine(first, last);
    assert(requestLine != nullptr);

    LS_ACCESS(_logger, "Request: " << requestLine);

    const char* verbText = shift(requestLine);
    if (!verbText) {
        return sendBadRequest("Malformed request line");
    }
    auto verb = Request::verb(verbText);
    if (verb == Request::Verb::Invalid) {
        return sendBadRequest("Malformed request line");
    }
    const char* requestUri = shift(requestLine);
    if (requestUri == nullptr) {
        return sendBadRequest("Malformed request line");
    }

    const char* httpVersion = shift(requestLine);
    if (httpVersion == nullptr) {
        return sendBadRequest("Malformed request line");
    }
    if (strcmp(httpVersion, "HTTP/1.1") != 0) {
        return sendUnsupportedError("Unsupported HTTP version");
    }
    if (*requestLine != 0) {
        return sendBadRequest("Trailing crap after http version");
    }

    HeaderMap headers(31);
    while (first < last) {
        char* colonPos = nullptr;
        char* headerLine = extractLine(first, last, &colonPos);
        assert(headerLine != nullptr);
        if (colonPos == nullptr) {
            return sendBadRequest("Malformed header");
        }
        *colonPos = 0;
        const char* key = headerLine;
        const char* value = skipWhitespace(colonPos + 1);
        LS_DEBUG(_logger, "Key: " << key << " || " << value);
        headers.emplace(key, value);
    }

    if (headers.count("Connection") && headers.count("Upgrade") && hasConnectionType(headers["Connection"], "Upgrade") && caseInsensitiveSame(headers["Upgrade"], "websocket")) {
        LS_INFO(_logger, "Websocket request for " << requestUri << "'");
        if (verb != Request::Verb::Get) {
            return sendBadRequest("Non-GET WebSocket request");
        }
        _webSocketHandler = _server.getWebSocketHandler(requestUri);
        if (!_webSocketHandler) {
            LS_WARNING(_logger, "Couldn't find WebSocket end point for '" << requestUri << "'");
            return send404();
        }
        verb = Request::Verb::WebSocket;

        if (_server.server().getPerMessageDeflateEnabled() && headers.count("Sec-WebSocket-Extensions")) {
            parsePerMessageDeflateHeader(headers["Sec-WebSocket-Extensions"]);
        }
    }

    _request = std::make_unique<PageRequest>(_address, requestUri, _server.server(),
                                             verb, std::move(headers));

    const EmbeddedContent* embedded = findEmbeddedContent(requestUri);
    if (verb == Request::Verb::Get && embedded) {
        // MRG: one day, this could be a request handler.
        return sendData(getContentType(requestUri), embedded->data, embedded->length);
    } else if (verb == Request::Verb::Head && embedded) {
        return sendHeader(getContentType(requestUri), embedded->length);
    }

    if (_request->contentLength() > _server.clientBufferSize()) {
        return sendBadRequest("Content length too long");
    }
    if (_request->contentLength() == 0) {
        return handlePageRequest();
    }
    _state = State::BUFFERING_POST_DATA;
    return true;
}

bool Connection::handlePageRequest() {
    std::shared_ptr<Response> response;
    try {
        response = _server.handle(*_request);
    } catch (const std::exception& e) {
        LS_ERROR(_logger, "page error: " << e.what());
        return sendISE(e.what());
    } catch (...) {
        LS_ERROR(_logger, "page error: (unknown)");
        return sendISE("(unknown)");
    }
    auto uri = _request->getRequestUri();
    if (!response && _request->verb() == Request::Verb::WebSocket) {
        _webSocketHandler = _server.getWebSocketHandler(uri.c_str());
        int webSocketVersion{0};
        try {
            webSocketVersion = std::stoi(_request->getHeader("Sec-WebSocket-Version"));
        } catch (const std::logic_error& ex) {
            (void) ex;
            LS_WARNING(_logger, "Invalid Sec-WebSocket-Version '" << _request->getHeader("Sec-WebSocket-Version") << "'");
            return sendError(ResponseCode::UpgradeRequired, "Invalid Sec-WebSocket-Version received");
        }
        if (!_webSocketHandler) {
            LS_WARNING(_logger, "Couldn't find WebSocket end point for '" << uri << "'");
            return send404();
        }
        if (webSocketVersion == 0) {
            // Hixie
            _state = State::READING_WEBSOCKET_KEY3;
            return true;
        }
        auto hybiKey = _request->getHeader("Sec-WebSocket-Key");
        return handleHybiHandshake(webSocketVersion, hybiKey);
    }
    return sendResponse(response);
}

bool Connection::sendResponse(std::shared_ptr<Response> response) {
    if (response == Response::unhandled()) {
        return sendStaticData();
    }
    assert(_response.get() == nullptr);
    _state = State::AWAITING_RESPONSE_BEGIN;
    _transferEncoding = TransferEncoding::Raw;
    _chunk = 0;
    _response = response;
    _response->handle(_writer);
    return true;
}

void Connection::error(ResponseCode responseCode, const std::string& payload) {
    _server.checkThread();
    if (_state != State::AWAITING_RESPONSE_BEGIN) {
        LS_ERROR(_logger, "error() called when in wrong state");
        return;
    }
    if (isOk(responseCode)) {
        LS_ERROR(_logger, "error() called with a non-error code");
    }
    if (responseCode == ResponseCode::NotFound) {
        // TODO: better here; we use this purely to serve our own embedded content.
        send404();
    } else {
        sendError(responseCode, payload);
    }
}

void Connection::begin(ResponseCode responseCode, TransferEncoding encoding) {
    _server.checkThread();
    if (_state != State::AWAITING_RESPONSE_BEGIN) {
        LS_ERROR(_logger, "begin() called when in wrong state");
        return;
    }
    _state = State::SENDING_RESPONSE_HEADERS;
    bufferResponseAndCommonHeaders(responseCode);
    _transferEncoding = encoding;
    if (_transferEncoding == TransferEncoding::Chunked) {
        bufferLine("Transfer-encoding: chunked");
    }
}

void Connection::header(const std::string& header, const std::string& value) {
    _server.checkThread();
    if (_state != State::SENDING_RESPONSE_HEADERS) {
        LS_ERROR(_logger, "header() called when in wrong state");
        return;
    }
    bufferLine(header + ": " + value);
}
void Connection::payload(const void* data, size_t size, bool flush) {
    _server.checkThread();
    if (_state == State::SENDING_RESPONSE_HEADERS) {
        bufferLine("");
        _state = State::SENDING_RESPONSE_BODY;
    } else if (_state != State::SENDING_RESPONSE_BODY) {
        LS_ERROR(_logger, "payload() called when in wrong state");
        return;
    }
    if (size && _transferEncoding == TransferEncoding::Chunked) {
        writeChunkHeader(size);
    }
    write(data, size, flush);
}

void Connection::writeChunkHeader(size_t size) {
    std::ostringstream lengthStr;
    if (_chunk)
        lengthStr << "\r\n";
    lengthStr << std::hex << size << "\r\n";
    auto length = lengthStr.str();
    _chunk++;
    write(length.c_str(), length.size(), false);
}

void Connection::finish(bool keepConnectionOpen) {
    _server.checkThread();
    if (_state == State::SENDING_RESPONSE_HEADERS) {
        bufferLine("");
    } else if (_state != State::SENDING_RESPONSE_BODY) {
        LS_ERROR(_logger, "finish() called when in wrong state");
        return;
    }
    if (_transferEncoding == TransferEncoding::Chunked) {
        writeChunkHeader(0);
        write("\r\n", 2, false);
    }

    flush();

    if (!keepConnectionOpen) {
        closeWhenEmpty();
    }

    _state = State::READING_HEADERS;
    _response.reset();
}

bool Connection::handleHybiHandshake(
    int webSocketVersion,
    const std::string& webSocketKey) {
    if (webSocketVersion != 8 && webSocketVersion != 13) {
        return sendBadRequest("Invalid websocket version");
    }
    LS_DEBUG(_logger, "Got a hybi-8 websocket with key=" << webSocketKey);

    LS_DEBUG(_logger, "Attempting websocket upgrade");

    bufferResponseAndCommonHeaders(ResponseCode::WebSocketProtocolHandshake);
    bufferLine("Upgrade: websocket");
    bufferLine("Connection: Upgrade");
    bufferLine("Sec-WebSocket-Accept: " + getAcceptKey(webSocketKey));
    if (_perMessageDeflate)
        bufferLine("Sec-WebSocket-Extensions: permessage-deflate");
    pickProtocol();
    bufferLine("");
    flush();

    if (_webSocketHandler) {
        _webSocketHandler->onConnect(this);
    }
    _state = State::HANDLING_HYBI_WEBSOCKET;
    return true;
}

void Connection::parsePerMessageDeflateHeader(const std::string& header) {
    for (auto& extField : seasocks::split(header, ';')) {
        while (!extField.empty() && isspace(extField[0])) {
            extField = extField.substr(1);
        }

        if (seasocks::caseInsensitiveSame(extField, "permessage-deflate")) {
            LS_INFO(_logger, "Enabling per-message deflate");
            _perMessageDeflate = true;
            zlibContext.initialise();
        }
    }
}

#ifdef _MSC_VER
#pragma warning(disable : 4702) // unreachable code
#endif
bool Connection::parseRange(const std::string& rangeStr, Range& range) const {
    size_t minusPos = rangeStr.find('-');
    if (minusPos == std::string::npos) {
        LS_WARNING(_logger, "Bad range: '" << rangeStr << "'");
        return false;
    }
    if (minusPos == 0) {
        // A range like "-500" means 500 bytes from end of file to end.
        range.start = std::stoi(rangeStr);
        range.end = (std::numeric_limits<long>::max)();
        return true;
    } else {
        range.start = std::stoi(rangeStr.substr(0, minusPos));
        if (minusPos == rangeStr.size() - 1) {
            range.end = (std::numeric_limits<long>::max)();
        } else {
            range.end = std::stoi(rangeStr.substr(minusPos + 1));
        }
        return true;
    }
    return false;
}
#ifdef _MSC_VER
#pragma warning(default : 4702) // unreachable code
#endif

bool Connection::parseRanges(const std::string& range, std::list<Range>& ranges) const {
    static const std::string expectedPrefix = "bytes=";
    if (range.length() < expectedPrefix.length() || range.substr(0, expectedPrefix.length()) != expectedPrefix) {
        LS_WARNING(_logger, "Bad range request prefix: '" << range << "'");
        return false;
    }
    auto rangesText = split(range.substr(expectedPrefix.length()), ',');
    for (auto& it : rangesText) {
        Range r;
        if (!parseRange(it, r)) {
            return false;
        }
        ranges.push_back(r);
    }
    return !ranges.empty();
}

// Sends HTTP 200 or 206, content-length, and range info as needed. Returns the actual file ranges
// needing sending.
std::list<Connection::Range> Connection::processRangesForStaticData(const std::list<Range>& origRanges, long fileSize) {
    if (origRanges.empty()) {
        // Easy case: a non-range request.
        bufferResponseAndCommonHeaders(ResponseCode::Ok);
        bufferLine("Content-Length: " + toString(fileSize));
        return {Range{0, fileSize - 1}};
    }

    // Partial content request.
    bufferResponseAndCommonHeaders(ResponseCode::PartialContent);
    size_t contentLength = 0;
    std::ostringstream rangeLine;
    rangeLine << "Content-Range: bytes ";
    std::list<Range> sendRanges;
    for (auto actualRange : origRanges) {
        if (actualRange.start < 0) {
            actualRange.start += fileSize;
        }
        if (actualRange.start >= fileSize) {
            actualRange.start = fileSize - 1;
        }
        if (actualRange.end >= fileSize) {
            actualRange.end = fileSize - 1;
        }
        contentLength += actualRange.length();
        sendRanges.push_back(actualRange);
        rangeLine << actualRange.start << "-" << actualRange.end;
    }
    rangeLine << "/" << fileSize;
    bufferLine(rangeLine.str());
    bufferLine("Content-Length: " + toString(contentLength));
    return sendRanges;
}

#ifdef _MSC_VER
#pragma warning(disable : 6262) // Function uses '16808' bytes of stack (wants us to use < 16384)
#endif
bool Connection::sendStaticData() {
    // TODO: fold this into the handler way of doing things.
    std::string path = _server.getStaticPath() + getRequestUri();
    auto rangeHeader = getHeader("Range");
    // Trim any trailing queries.
    size_t queryPos = path.find('?');
    if (queryPos != std::string::npos) {
        path.resize(queryPos);
    }
    if (*path.rbegin() == '/') {
        path += "index.html";
    }
#ifndef O_BINARY
#define O_BINARY 0x8000 // is this needed sometimes (mingw?)
#endif
    RaiiFd input{::open(path.c_str(), O_RDONLY | O_BINARY)};
    if (!input.ok()) {
        std::string s = seasocks::getLastError();
        std::cout << s << std::endl;
        std::cout << std::endl;
    }
    // This took a while to find! Linux opens all files in binary mode by default,
    // Windows does not. So let's be explicit about this.

    struct stat fileStat;
    if (!input.ok() || ::fstat(input, &fileStat) == -1) {
        return send404();
    }
    std::list<Range> ranges;
    if (!rangeHeader.empty() && !parseRanges(rangeHeader, ranges)) {
        return sendBadRequest("Bad range header");
    }
    ranges = processRangesForStaticData(ranges, fileStat.st_size);
    bufferLine("Content-Type: " + getContentType(path));
    bufferLine("Connection: keep-alive");
    bufferLine("Accept-Ranges: bytes");
    bufferLine("Last-Modified: " + webtime(fileStat.st_mtime));
    if (!isCacheable(path)) {
        bufferLine("Cache-Control: no-store");
        bufferLine("Pragma: no-cache");
        bufferLine("Expires: " + now());
    }
    bufferLine("");
    if (!flush()) {
        return false;
    }

    for (auto range : ranges) {
        if (::lseek(input, static_cast<long>(range.start), SEEK_SET) == -1) {
            // We've (probably) already sent data.
            return false;
        }
        auto bytesLeft = range.length();
        while (bytesLeft) {
            char buf[ReadWriteBufferSize];

            auto bytesRead = ::read(input, buf,
                                    static_cast<unsigned int>(std::min(static_cast<long>(sizeof(buf)), bytesLeft)));
            if (bytesRead <= 0) {
                const static std::string unexpectedEof("Unexpected EOF");
                LS_ERROR(_logger, "Error reading file: " << (bytesRead == 0 ? unexpectedEof : getLastError()));
                // We can't send an error document as we've sent the header.
                return false;
            }
            bytesLeft -= bytesRead;
            if (!write(buf, bytesRead, true)) {
                return false;
            }
        }
    }
    return true;
}

#ifdef _MSC_VER
#pragma warning(default : 6262) // re-enable this warning from here on in
#endif

bool Connection::sendHeader(const std::string& type, size_t size) {
    bufferResponseAndCommonHeaders(ResponseCode::Ok);
    bufferLine("Content-Type: " + type);
    bufferLine("Content-Length: " + toString(size));
    bufferLine("Connection: keep-alive");
    return bufferLine("");
}

bool Connection::sendData(const std::string& type, const char* start, size_t size) {
    bufferResponseAndCommonHeaders(ResponseCode::Ok);
    bufferLine("Content-Type: " + type);
    bufferLine("Content-Length: " + toString(size));
    bufferLine("Connection: keep-alive");
    bufferLine("");
    bool result = write(start, size, true);
    return result;
}

void Connection::bufferResponseAndCommonHeaders(ResponseCode code) {
    auto responseCodeInt = static_cast<int>(code);
    auto responseCodeName = ::name(code);
    auto response = std::string("HTTP/1.1 " + toString(responseCodeInt) + " " + responseCodeName);
    LS_ACCESS(_logger, "Response: " << response);
    bufferLine(response);
    bufferLine("Server: " + std::string(Config::version));
    bufferLine("Date: " + now());
    bufferLine("Access-Control-Allow-Origin: *");
}

void Connection::setLinger() {
    if (_fd == -1) {
        return;
    }
    const int secondsToLinger = 1;
    struct linger linger = {true, secondsToLinger};
    // signature of ::setsockopt in Windows is:
    // int setsockopt(SOCKET, int level, int optname, const char *optval, int optlen);
    if (::setsockopt(_fd, SOL_SOCKET, SO_LINGER, reinterpret_cast<const char*>(&linger), sizeof(linger)) == -1) {
        LS_INFO(_logger, "Unable to set linger on socket");
    }
}

bool Connection::hasHeader(const std::string& header) const {
    return _request ? _request->hasHeader(header) : false;
}

std::string Connection::getHeader(const std::string& header) const {
    return _request ? _request->getHeader(header) : "";
}

const std::string& Connection::getRequestUri() const {
    static const std::string empty;
    return _request ? _request->getRequestUri() : empty;
}

Server& Connection::server() const {
    return _server.server();
}

} // seasocks


text:
<?php

namespace Greg\Support\Tests\Validation;

use Greg\Support\Validation\MinValidator;
use PHPUnit\Framework\TestCase;

class RequiredValidatorTest extends TestCase
{
    /** @test */
    public function it_should_validate_if_number_is_greater_or_equal_with()
    {
        $validation = new MinValidator(10);

        $this->assertTrue(!$validation->validate(10));

        $this->assertTrue(!$validation->validate(15));
    }

    /** @test */
    public function it_should_not_validate_if_number_is_less_than()
    {
        $validation = new MinValidator(10);

        $this->assertArrayHasKey('MinError', $validation->validate(5));
    }
}


text:
require "spec_helper"
require "support/test_target"

shared_examples "Evaluate the condition of MethodCallSituation" do
  it { expect(OkuribitoRails::MethodCallSituation.find_by(class_name: "TestTarget", method_symbol: ".", method_name: "deprecated_self_method")).to be_present }
  it { expect(OkuribitoRails::MethodCallSituation.find_by(class_name: "TestTarget", method_symbol: "#", method_name: "deprecated_method")).to be_present }
end

describe OkuribitoRails::RegistMethod do
  let(:setting_path) { "spec/support/test_config.yml" }

  describe "create MethodCallSituation" do
    context "registered none" do
      before do
        OkuribitoRails::RegistMethod.new.update_observe_methods(setting_path)
      end

      it_behaves_like "Evaluate the condition of MethodCallSituation"
    end

    context "registered one (Already registered)" do
      before do
        FactoryGirl.create(:method_call_situation, class_name: "TestTarget", method_symbol: "#", method_name: "deprecated_method")
        OkuribitoRails::RegistMethod.new.update_observe_methods(setting_path)
      end

      it_behaves_like "Evaluate the condition of MethodCallSituation"
    end

    context "registered one (Delete target)" do
      before do
        FactoryGirl.create(:method_call_situation, class_name: "TestTarget", method_symbol: "#", method_name: "delete_target_method")
        OkuribitoRails::RegistMethod.new.update_observe_methods(setting_path)
      end

      it_behaves_like "Evaluate the condition of MethodCallSituation"
      it { expect(OkuribitoRails::MethodCallSituation.find_by(class_name: "TestTarget", method_symbol: "#", method_name: "delete_target_method")).not_to be_present }
    end
  end
end


text:
use std::env;

fn main() {
    env::remove_var("HOME"); // make sure we enter the interesting codepath
    #[allow(deprecated)]
    env::home_dir().unwrap();
}


text:
module ActionController #:nodoc:
  class Base
    # adding to ActionController::Base so it can overrided in ApplicationController
    def deny_access
      head :unauthorized
    end
  end
end


text:
import json
from xml.dom.minidom import getDOMImplementation

from ipf.data import Data, Representation

from .entity import *

#######################################################################################################################

class Manager(Entity):
    def __init__(self):
        Entity.__init__(self)

        self.ProductName = "unknown"                  # string
        self.ProductVersion = None                    # string
        self.ServiceID = "urn:glue2:Service:unknown"  # string (ID)
        self.ResourceID = []                          # list of string (ID)

#######################################################################################################################

class ManagerTeraGridXml(EntityTeraGridXml):
    data_cls = Manager

    def __init__(self, data):
        EntityTeraGridXml.__init__(self,data)

    def get(self):
        return self.toDom().toxml()

    def toDom(self):
        doc = getDOMImplementation().createDocument("http://info.teragrid.org/glue/2009/02/spec_2.0_r02",
                                                    "Entities",None)
        root = doc.createElement("Manager")
        doc.documentElement.appendChild(root)
        self.addToDomElement(doc,root)

        return doc

    def addToDomElement(self, doc, element):
        EntityTeraGridXml.addToDomElement(self,doc,element)

        if self.data.ProductName != None:
            e = doc.createElement("ProductName")
            e.appendChild(doc.createTextNode(self.data.ProductName))
            element.appendChild(e)
        if self.data.ProductVersion != None:
            e = doc.createElement("ProductVersion")
            e.appendChild(doc.createTextNode(self.data.ProductVersion))
            element.appendChild(e)
        if self.data.ServiceID is not None:
            e = doc.createElement("Service")
            e.appendChild(doc.createTextNode(self.data.ServiceID))
            element.appendChild(e)
        for resource in self.data.ResourceID:
            e = doc.createElement("Resource")
            e.appendChild(doc.createTextNode(resource))
            element.appendChild(e)

#######################################################################################################################

class ManagerOgfJson(EntityOgfJson):
    data_cls = Manager

    def __init__(self, data):
        EntityOgfJson.__init__(self,data)

    def get(self):
        return json.dumps(self.toJson(),sort_keys=True,indent=4)

    def toJson(self):
        doc = EntityOgfJson.toJson(self)

        doc["ProductName"] = self.data.ProductName
        if self.data.ProductVersion != None:
            doc["ProductVersion"] = self.data.ProductVersion

        associations = {}
        associations["ServiceID"] = self.data.ServiceID
        associations["ResourceID"] = self.data.ResourceID
        doc["Associations"] = associations

        return doc

#######################################################################################################################


text:
package com.github.dreamhead.moco.internal;

import com.github.dreamhead.moco.MocoMonitor;
import com.github.dreamhead.moco.SocketRequest;
import com.github.dreamhead.moco.SocketResponse;
import com.github.dreamhead.moco.SocketResponseSetting;
import com.github.dreamhead.moco.model.DefaultSocketRequest;
import com.github.dreamhead.moco.model.DefaultSocketResponse;
import com.github.dreamhead.moco.model.MessageContent;
import com.github.dreamhead.moco.setting.Setting;
import com.google.common.collect.ImmutableList;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import static com.github.dreamhead.moco.model.MessageContent.content;
import static io.netty.channel.ChannelHandler.Sharable;
import static java.lang.String.format;

@Sharable
public class MocoSocketHandler extends SimpleChannelInboundHandler<String> {
    private final ImmutableList<Setting<SocketResponseSetting>> settings;
    private final Setting<SocketResponseSetting> anySetting;
    private final MocoMonitor monitor;

    public MocoSocketHandler(final ActualSocketServer server) {
        this.settings = server.getSettings();
        this.anySetting = server.getAnySetting();
        this.monitor = server.getMonitor();
    }

    @Override
    protected void channelRead0(final ChannelHandlerContext ctx, final String msg) throws Exception {
        try {
            MessageContent content = content(msg);
            SocketRequest request = new DefaultSocketRequest(content);
            this.monitor.onMessageArrived(request);
            SocketResponse response = new DefaultSocketResponse();
            handleSession(new SessionContext(request, response));
            this.monitor.onMessageLeave(response);
            ctx.write(response.getContent().toString());
        } catch (Exception e) {
            this.monitor.onException(e);
        }
    }

    @Override
    public void channelReadComplete(final ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    private void handleSession(final SessionContext context) {
        for (Setting setting : settings) {
            if (setting.match(context.getRequest())) {
                setting.writeToResponse(context);
                return;
            }
        }

        if (anySetting.match(context.getRequest())) {
            anySetting.writeToResponse(context);
            return;
        }

        this.monitor.onUnexpectedMessage(context.getRequest());
        throw new RuntimeException(format("No handler found for request: %s", context.getRequest().getContent()));
    }

    @Override
    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
        monitor.onException(cause);
    }
}


text:
using System.Collections.Specialized;

namespace SMSApi.Api.Action
{
    public class PhonebookContactDelete : BaseSimple<SMSApi.Api.Response.Base>
    {
        public PhonebookContactDelete() : base() { }

        protected override string Uri() { return "phonebook.do"; }

        protected string number;

        protected override NameValueCollection Values()
        {
            NameValueCollection collection = new NameValueCollection();

            collection.Add("format", "json");

            collection.Add("username", client.GetUsername());
            collection.Add("password", client.GetPassword());

            collection.Add("delete_contact", number);

            return collection;
        }

        public PhonebookContactDelete Number(string number)
        {
            this.number = number;
            return this;
        }
    }
}


text:
import * as bcrypt from 'bcrypt';
import {User} from '../db/db';
import {IUser} from '../db/interfaces';

export default function(screenName: string, password: string): Promise<Object> {
	screenName = screenName.trim();

	if (screenName === '') {
		return <Promise<any>>Promise.reject('empty-screen-name');
	}

	return new Promise<Object>((resolve, reject) => {
		User.findOne({
			screenNameLower: screenName.toLowerCase()
		}, (findErr: any, user: IUser) => {
			if (findErr !== null) {
				return reject(findErr);
			} else if (user === null) {
				return reject('user-not-found');
			}

			bcrypt.compare(password, user.encryptedPassword, (compareErr, same) => {
				if (compareErr !== undefined && compareErr !== null) {
					return reject(compareErr);
				} else if (!same) {
					return reject('failed');
				}

				resolve(user.toObject());
			});
		});
	});
}


text:
module Nokogiri
  module XML
    class Node

      attr_accessor :cstruct # :nodoc:

      def pointer_id # :nodoc:
        cstruct.pointer
      end

      def encode_special_chars(string) # :nodoc:
        char_ptr = LibXML.xmlEncodeSpecialChars(self[:doc], string)
        encoded = char_ptr.read_string
        # TODO: encoding?
        LibXML.xmlFree(char_ptr)
        encoded
      end

      def internal_subset # :nodoc:
        return nil if cstruct[:doc].null?
        doc = cstruct.document
        dtd = LibXML.xmlGetIntSubset(doc)
        return nil if dtd.null?
        Node.wrap(dtd)
      end

      def dup(deep = 1) # :nodoc:
        dup_ptr = LibXML.xmlDocCopyNode(cstruct, cstruct.document, deep)
        return nil if dup_ptr.null?
        Node.wrap(dup_ptr, self.class)
      end

      def unlink # :nodoc:
        LibXML.xmlUnlinkNode(cstruct)
        cstruct.keep_reference_from_document!
        self
      end

      def blank? # :nodoc:
        LibXML.xmlIsBlankNode(cstruct) == 1
      end

      def next_sibling # :nodoc:
        cstruct_node_from :next
      end

      def previous_sibling # :nodoc:
        cstruct_node_from :prev
      end

      def replace_with_node(new_node) # :nodoc:
        LibXML.xmlReplaceNode(cstruct, new_node.cstruct)
        Node.send(:relink_namespace, new_node.cstruct)
        self
      end

      def children # :nodoc:
        return NodeSet.new(nil) if cstruct[:children].null?
        child = Node.wrap(cstruct[:children])

        set = NodeSet.new child.document
        set_ptr = LibXML.xmlXPathNodeSetCreate(child.cstruct)

        set.cstruct = LibXML::XmlNodeSet.new(set_ptr)
        return set unless child

        child_ptr = child.cstruct[:next]
        while ! child_ptr.null?
          child = Node.wrap(child_ptr)
          LibXML.xmlXPathNodeSetAdd(set.cstruct, child.cstruct)
          child_ptr = child.cstruct[:next]
        end

        return set
      end

      def child # :nodoc:
        (val = cstruct[:children]).null? ? nil : Node.wrap(val)
      end

      def key?(attribute) # :nodoc:
        ! (prop = LibXML.xmlHasProp(cstruct, attribute.to_s)).null?
      end

      def namespaced_key?(attribute, namespace) # :nodoc:
        prop = LibXML.xmlHasNsProp(cstruct, attribute.to_s,
          namespace.nil? ? nil : namespace.to_s)
        prop.null? ? false : true
      end

      def []=(property, value) # :nodoc:
        LibXML.xmlSetProp(cstruct, property, value)
        value
      end

      def get(attribute) # :nodoc:
        return nil unless attribute
        propstr = LibXML.xmlGetProp(cstruct, attribute.to_s)
        return nil if propstr.null?
        rval = propstr.read_string # TODO: encoding?
        LibXML.xmlFree(propstr)
        rval
      end

      def set_namespace(namespace)
        LibXML.xmlSetNs(cstruct, namespace.cstruct)
        self
      end

      def attribute(name) # :nodoc:
        raise "Node#attribute not implemented yet"
      end

      def attribute_with_ns(name, namespace) # :nodoc:
        prop = LibXML.xmlHasNsProp(cstruct, name.to_s,
          namespace.nil? ? NULL : namespace.to_s)
        return prop if prop.null?
        Node.wrap(prop)
      end

      def attribute_nodes # :nodoc:
        attr = []
        prop_cstruct = cstruct[:properties]
        while ! prop_cstruct.null?
          prop = Node.wrap(prop_cstruct)
          attr << prop
          prop_cstruct = prop.cstruct[:next]
        end
        attr
      end

      def namespace # :nodoc:
        cstruct[:ns].null? ? nil : Namespace.wrap(cstruct.document, cstruct[:ns])
      end

      def namespace_definitions # :nodoc:
        list = []
        ns_ptr = cstruct[:nsDef]
        return list if ns_ptr.null?
        while ! ns_ptr.null?
          ns = Namespace.wrap(cstruct.document, ns_ptr)
          list << ns
          ns_ptr = ns.cstruct[:next]
        end
        list
      end

      def node_type # :nodoc:
        cstruct[:type]
      end

      def native_content=(content) # :nodoc:
        LibXML.xmlNodeSetContent(cstruct, content)
        content
      end

      def content # :nodoc:
        content_ptr = LibXML.xmlNodeGetContent(cstruct)
        return nil if content_ptr.null?
        content = content_ptr.read_string # TODO: encoding?
        LibXML.xmlFree(content_ptr)
        content
      end

      def add_child(child) # :nodoc:
        Node.reparent_node_with(child, self) do |child_cstruct, my_cstruct|
          LibXML.xmlAddChild(my_cstruct, child_cstruct)
        end
      end

      def parent # :nodoc:
        cstruct_node_from :parent
      end

      def node_name=(string) # :nodoc:
        LibXML.xmlNodeSetName(cstruct, string)
        string
      end

      def node_name # :nodoc:
        cstruct[:name] # TODO: encoding?
      end

      def path # :nodoc:
        path_ptr = LibXML.xmlGetNodePath(cstruct)
        val = path_ptr.null? ? nil : path_ptr.read_string # TODO: encoding?
        LibXML.xmlFree(path_ptr)
        val
      end

      def add_next_sibling(next_sibling) # :nodoc:
        Node.reparent_node_with(next_sibling, self) do |sibling_cstruct, my_cstruct|
          LibXML.xmlAddNextSibling(my_cstruct, sibling_cstruct)
        end
      end

      def add_previous_sibling(prev_sibling) # :nodoc:
        Node.reparent_node_with(prev_sibling, self) do |sibling_cstruct, my_cstruct|
          LibXML.xmlAddPrevSibling(my_cstruct, sibling_cstruct)
        end
      end

      def native_write_to(io, encoding, indent_string, options) # :nodoc:
        set_xml_indent_tree_output 1
        set_xml_tree_indent_string indent_string
        savectx = LibXML.xmlSaveToIO(IoCallbacks.writer(io), nil, nil, encoding, options)
        LibXML.xmlSaveTree(savectx, cstruct)
        LibXML.xmlSaveClose(savectx)
        io
      end

      def line # :nodoc:
        cstruct[:line]
      end

      def add_namespace_definition(prefix, href) # :nodoc:
        ns = LibXML.xmlNewNs(cstruct, href, prefix)
        LibXML.xmlSetNs(cstruct, ns) if prefix.nil?
        Namespace.wrap(cstruct.document, ns)
      end

      def self.new(name, document, *rest) # :nodoc:
        ptr = LibXML.xmlNewNode(nil, name.to_s)

        node_cstruct = LibXML::XmlNode.new(ptr)
        node_cstruct[:doc] = document.cstruct[:doc]
        node_cstruct.keep_reference_from_document!

        node = Node.wrap(node_cstruct, self)
        node.send :initialize, name, document, *rest
        yield node if block_given?
        node
      end

      def dump_html # :nodoc:
        return to_xml if type == DOCUMENT_NODE
        buffer = LibXML::XmlBuffer.new(LibXML.xmlBufferCreate())
        LibXML.htmlNodeDump(buffer, cstruct[:doc], cstruct)
        buffer[:content] # TODO: encoding?
      end

      def compare(other) # :nodoc:
        LibXML.xmlXPathCmpNodes(other.cstruct, self.cstruct)
      end

      def self.wrap(node_struct, klass=nil) # :nodoc:
        if node_struct.is_a?(FFI::Pointer)
          # cast native pointers up into a node cstruct
          return nil if node_struct.null?
          node_struct = LibXML::XmlNode.new(node_struct)
        end

        raise "wrapping a node without a document" unless node_struct.document

        document_struct = node_struct.document
        document = document_struct.nil? ? nil : document_struct.ruby_doc
        if node_struct[:type] == DOCUMENT_NODE || node_struct[:type] == HTML_DOCUMENT_NODE
          return document
        end

        ruby_node = node_struct.ruby_node
        return ruby_node unless ruby_node.nil?

        klasses = case node_struct[:type]
                  when ELEMENT_NODE then [XML::Element]
                  when TEXT_NODE then [XML::Text]
                  when ENTITY_REF_NODE then [XML::EntityReference]
                  when COMMENT_NODE then [XML::Comment]
                  when DOCUMENT_FRAG_NODE then [XML::DocumentFragment]
                  when PI_NODE then [XML::ProcessingInstruction]
                  when ATTRIBUTE_NODE then [XML::Attr]
                  when ENTITY_DECL then [XML::EntityDeclaration]
                  when CDATA_SECTION_NODE then [XML::CDATA]
                  when DTD_NODE then [XML::DTD, LibXML::XmlDtd]
                  else [XML::Node]
                  end

        if klass
          node = klass.allocate
        else
          node = klasses.first.allocate
        end
        node.cstruct = klasses[1] ? klasses[1].new(node_struct.pointer) : node_struct

        node.cstruct.ruby_node = node

        cache = document.instance_variable_get(:@node_cache)
        cache << node

        node.instance_variable_set(:@document, document)
        document.decorate(node)
        node
      end

      def document
        cstruct.document.ruby_doc
      end

      private

      def self.reparent_node_with(node, other, &block) # :nodoc:
        raise(ArgumentError, "node must be a Nokogiri::XML::Node") unless node.is_a?(Nokogiri::XML::Node)

        if node.cstruct[:doc] == other.cstruct[:doc]
          LibXML.xmlUnlinkNode(node.cstruct)
          if node.type == TEXT_NODE && other.type == TEXT_NODE && Nokogiri.is_2_6_16?
            other.cstruct.pointer.put_pointer(other.cstruct.offset_of(:content), LibXML.xmlStrdup(other.cstruct[:content]))
          end
          reparented_struct = block.call(node.cstruct, other.cstruct)
          raise(RuntimeError, "Could not reparent node (1)") unless reparented_struct
        else
          duped_node = LibXML.xmlDocCopyNode(node.cstruct, other.cstruct.document, 1)
          raise(RuntimeError, "Could not reparent node (xmlDocCopyNode)") unless duped_node
          reparented_struct = block.call(duped_node, other.cstruct)
          raise(RuntimeError, "Could not reparent node (2)") unless reparented_struct
          LibXML.xmlUnlinkNode(node.cstruct)
          node.cstruct.keep_reference_from_document!
        end

        reparented_struct = LibXML::XmlNode.new(reparented_struct)

        # the child was a text node that was coalesced. we need to have the object
        # point at SOMETHING, or we'll totally bomb out.
        if reparented_struct != node.cstruct
          node.cstruct = reparented_struct
        end

        relink_namespace reparented_struct

        reparented = Node.wrap(reparented_struct)
        reparented.decorate!
        reparented
      end

      def self.relink_namespace(reparented_struct) # :nodoc:
        # Make sure that our reparented node has the correct namespaces
        if reparented_struct[:doc] != reparented_struct[:parent]
          LibXML.xmlSetNs(reparented_struct, LibXML::XmlNode.new(reparented_struct[:parent])[:ns])
        end

        # Search our parents for an existing definition
        if ! reparented_struct[:nsDef].null?
          ns = LibXML.xmlSearchNsByHref(
            reparented_struct[:doc],
            reparented_struct[:parent],
            LibXML::XmlNs.new(reparented_struct[:nsDef])[:href]
            )
          reparented_struct[:nsDef] = nil unless ns.null?
        end

        # Only walk all children if there actually is a namespace we need to reparent.
        return if reparented_struct[:ns].null?

        # When a node gets reparented, walk it's children to make sure that
        # their namespaces are reparented as well.
        child_ptr = reparented_struct[:children]
        while ! child_ptr.null?
          child_struct = LibXML::XmlNode.new(child_ptr)
          relink_namespace child_struct
          child_ptr = child_struct[:next]
        end
      end

      def cstruct_node_from(sym) # :nodoc:
        (val = cstruct[sym]).null? ? nil : Node.wrap(val)
      end

      def set_xml_indent_tree_output(value) # :nodoc:
        LibXML.__xmlIndentTreeOutput.write_int(value)
      end

      def set_xml_tree_indent_string(value) # :nodoc:
        LibXML.__xmlTreeIndentString.write_pointer(LibXML.xmlStrdup(value.to_s))
      end

    end
  end
end


text:
<?xml version="1.0" ?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:sbol="http://sbols.org/v2#">
  <sbol:ComponentDefinition rdf:about="http://cellocad.org/pIcaRA">
    <sbol:persistentIdentity rdf:resource="http://cellocad.org/pIcaRA"/>
    <sbol:displayId>pIcaRA</sbol:displayId>
    <sbol:type rdf:resource="http://www.biopax.org/release/biopax-level3.owl#DnaRegion"/>
    <sbol:role rdf:resource="http://purl.obolibrary.org/obo/SO_0000167"/>
    <sbol:sequence rdf:resource="http://cellocad.org/pIcaRA_sequence"/>
  </sbol:ComponentDefinition>
  <sbol:Sequence rdf:about="http://cellocad.org/pIcaRA_sequence">
    <sbol:persistentIdentity rdf:resource="http://cellocad.org/pIcaRA_sequence"/>
    <sbol:displayId>pIcaRA_sequence</sbol:displayId>
    <sbol:elements>GTCAACTCATAAGATtctgattcgttaccaattgacaaTTCACCTACCTTTCGTTAGgTTAGGTTGT</sbol:elements>
    <sbol:encoding rdf:resource="http://www.chem.qmul.ac.uk/iubmb/misc/naseq.html"/>
  </sbol:Sequence>
</rdf:RDF>


text:
/**
 * Provides common datatypes related to persons.
 *
Datatype Person
 This package provides common datatypes related to persons.
 */
package net.sf.mmm.util.datatype.api.person;


text:
package org.hisp.dhis.programrule.engine;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.common.IdentifiableObjectStore;
import org.hisp.dhis.notification.logging.ExternalNotificationLogEntry;
import org.hisp.dhis.notification.logging.NotificationLoggingService;
import org.hisp.dhis.notification.logging.NotificationTriggerEvent;
import org.hisp.dhis.program.ProgramInstance;
import org.hisp.dhis.program.ProgramStageInstance;
import org.hisp.dhis.program.notification.ProgramNotificationInstance;
import org.hisp.dhis.program.notification.ProgramNotificationTemplate;
import org.hisp.dhis.rules.models.RuleAction;
import org.hisp.dhis.rules.models.RuleActionScheduleMessage;
import org.hisp.dhis.rules.models.RuleEffect;
import org.hisp.dhis.system.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * @Author Zubair Asghar.
 */
public class RuleActionScheduleMessageImplementer extends NotificationRuleActionImplementer
{
    private static final Log log = LogFactory.getLog( RuleActionScheduleMessageImplementer.class );

    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    @Autowired
    private NotificationLoggingService notificationLoggingService;

    @Autowired @Qualifier( "org.hisp.dhis.program.notification.ProgramNotificationInstanceStore" )
    private IdentifiableObjectStore<ProgramNotificationInstance> programNotificationInstanceStore;

    @Override
    public boolean accept( RuleAction ruleAction )
    {
        return ruleAction instanceof RuleActionScheduleMessage;
    }

    @Override
    public void implement( RuleEffect ruleEffect, ProgramInstance programInstance )
    {
        if ( !validate( ruleEffect, programInstance ) )
        {
            return;
        }

        ProgramNotificationTemplate template = getNotificationTemplate( ruleEffect.ruleAction() );

        String key = generateKey( template, programInstance );

        String date = ruleEffect.data();

        if ( !isDateValid( date ) )
        {
            return;
        }

        ProgramNotificationInstance notificationInstance = createNotificationInstance( template, date );
        notificationInstance.setProgramStageInstance( null );
        notificationInstance.setProgramInstance( programInstance );

        programNotificationInstanceStore.save( notificationInstance );

        log.info( String.format( "Notification with id:%s has been scheduled", template.getUid() ) );

        ExternalNotificationLogEntry entry = createLogEntry( key, template.getUid() );
        entry.setNotificationTriggeredBy( NotificationTriggerEvent.PROGRAM );
        notificationLoggingService.save( entry );
    }

    @Override
    public void implement( RuleEffect ruleEffect, ProgramStageInstance programStageInstance )
    {
        if ( !validate( ruleEffect, programStageInstance.getProgramInstance() ) )
        {
            return;
        }

        ProgramNotificationTemplate template = getNotificationTemplate( ruleEffect.ruleAction() );

        String key = generateKey( template, programStageInstance.getProgramInstance() );

        String date = ruleEffect.data();

        if ( !isDateValid( date ) )
        {
            return;
        }

        ProgramNotificationInstance notificationInstance = createNotificationInstance( template, date );
        notificationInstance.setProgramStageInstance( programStageInstance );
        notificationInstance.setProgramInstance( null );

        programNotificationInstanceStore.save( notificationInstance );

        log.info( String.format( "Notification with id:%s has been scheduled", template.getUid() ) );

        ExternalNotificationLogEntry entry = createLogEntry( key, template.getUid() );
        entry.setNotificationTriggeredBy( NotificationTriggerEvent.PROGRAM_STAGE );
        notificationLoggingService.save( entry );

    }

    private boolean isDateValid( String date )
    {
        if ( !date.isEmpty() )
        {
            if ( DateUtils.dateIsValid( date ) )
            {
                return true;
            }
        }

        log.error( "Invalid date: " + date );
        return false;
    }
}


text:
<?php

namespace Magento\Catalog\Test\Unit\Model\Product\Compare;

class ItemTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Catalog\Model\Product\Compare\Item
     */
    protected $model;

    protected function setUp()
    {
        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->model = $objectManager->getObject('Magento\Catalog\Model\Product\Compare\Item');
    }

    protected function tearDown()
    {
        $this->model = null;
    }

    public function testGetIdentities()
    {
        $id = 1;
        $this->model->setId($id);
        $this->assertEquals(
            [\Magento\Catalog\Model\Product\Compare\Item::CACHE_TAG . '_' . $id],
            $this->model->getIdentities()
        );
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/recyclerView_rowStyle"
    android:orientation="vertical">

    <TextView
        android:id="@+id/recyclerView_row_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="this is the title"
        android:textAlignment="center"
        android:textAllCaps="true"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/recyclerView_row_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="this is the row contents"
        android:textAlignment="center" />

</LinearLayout>


text:
require 'shellwords'
require 'travis/build/appliances/base'

module Travis
  module Build
    module Appliances
      class EtcHostsPinning < Base
        def apply
          Travis::Build.config.etc_hosts_pinning.split(',').each do |etchostsline|
            sh.raw %(echo #{Shellwords.escape(etchostsline.untaint)} | sudo tee -a /etc/hosts &>/dev/null)
          end
        end

        def apply?
          !Travis::Build.config.etc_hosts_pinning.strip.empty?
        end
      end
    end
  end
end


text:
<?php
namespace exussum12\CoverageChecker\tests;

use Exception;
use PHPUnit\Framework\TestCase;

/**
 * Ignored due to acceptance test needing to write values
 * @SuppressWarnings(PHPMD.Superglobals)
 */
class GenericDiffFilterTest extends TestCase
{
    use TestShim;

    public function testValid()
    {
        $GLOBALS['argv'] = [
            'diffFilter',
            '--phpcs',
            __DIR__ . '/fixtures/change.txt',
            __DIR__ . '/fixtures/phpcs.json'
        ];
        ob_start();
        require(__DIR__ . '/../src/Runners/generic.php');
        $output = ob_get_clean();
        $this->assertContainsString('100.00%', $output);
    }

    public function testMissingHandler()
    {
        $GLOBALS['argv'] = [
            'diffFilter',
            __DIR__ . '/fixtures/change.txt',
            __DIR__ . '/fixtures/phpcs.json'
        ];
        try {
            ob_start();
            require(__DIR__ . '/../src/Runners/generic.php');
        } catch (Exception $exception) {
            $output = ob_get_clean();
            $this->assertContainsString('--phpcs', $output);
            return true;
        }

        $this->fail('Exception not thrown when Expected');
    }
}