text:
package com.polidea.rxandroidble2;

import android.bluetooth.BluetoothGattCallback;
import android.content.Context;

import com.polidea.rxandroidble2.internal.BleIllegalOperationException;

import java.util.concurrent.TimeUnit;

/**
 * Container for various connection parameters.
 */
public class ConnectionSetup {

    public static final int DEFAULT_OPERATION_TIMEOUT = 30;
    /**
     * Flag related with
     * {@link android.bluetooth.BluetoothDevice#connectGatt(Context, boolean, BluetoothGattCallback)} autoConnect flag.
     * In case of auto connect is enabled the observable will wait with the emission of RxBleConnection. Without
     * auto connect flag set to true the connection will fail
     * with {@link com.polidea.rxandroidble2.exceptions.BleGattException} if the device is not in range.
     */
    public final boolean autoConnect;
    /**
     * Flag describing the method of operation viability checking. If set to false,
     * a {@link BleIllegalOperationException} will be thrown everytime properties of the characteristic
     * don't match those required by the operation. If set to true, an event will be logged without interrupting the execution.
     */
    public final boolean suppressOperationCheck;
    /**
     * Timeout in seconds after which the operation will be considered as broken. Eventually the operation will be
     * canceled and removed from queue.
     */
    public final Timeout operationTimeout;

    ConnectionSetup(boolean autoConnect, boolean suppressOperationCheck, Timeout operationTimeout) {
        this.autoConnect = autoConnect;
        this.suppressOperationCheck = suppressOperationCheck;
        this.operationTimeout = operationTimeout;
    }

    public static class Builder {

        private boolean autoConnect = false;
        private boolean suppressOperationCheck = false;
        private Timeout operationTimeout = new Timeout(DEFAULT_OPERATION_TIMEOUT, TimeUnit.SECONDS);

        /**
         * Autoconnect concept may be misleading at first glance. In cases when the BLE device is available and it is advertising constantly
         * you won't need to use autoconnect. Use autoconnect for connections where the BLE device is not advertising at
         * the moment of {@link RxBleDevice#establishConnection(ConnectionSetup)} call.
         *
         * @param autoConnect Flag related to
         *                    {@link android.bluetooth.BluetoothDevice#connectGatt(Context, boolean, BluetoothGattCallback)} autoConnect
         *                    flag. In case of auto connect is enabled the observable will wait with the emission of RxBleConnection.
         *                    Without auto connect flag set to true the connection will fail
         *                    with {@link com.polidea.rxandroidble2.exceptions.BleGattException} if the device is not in range after a
         *                    30 seconds timeout.
         * @return this builder instance
         */
        public Builder setAutoConnect(boolean autoConnect) {
            this.autoConnect = autoConnect;
            return this;
        }

        /**
         * @param suppressOperationCheck Flag describing the method of operation viability checking. If set to false,
         *                               a {@link BleIllegalOperationException} will be
         *                               emitted every time properties of the characteristic don't match those required by the operation.
         *                               If set to true, an event will be logged without interrupting the execution.
         * @return this builder instance
         */
        public Builder setSuppressIllegalOperationCheck(boolean suppressOperationCheck) {
            this.suppressOperationCheck = suppressOperationCheck;
            return this;
        }

        /**
         * @param operationTimeout Timeout after which the operation will be considered as broken. Eventually the operation
         *                         will be canceled and removed from queue. Keep in mind that it will cancel the library's operation
         *                         only and may leave Android's BLE stack in an inconsistent state.
         * @return this builder instance
         */
        public Builder setOperationTimeout(Timeout operationTimeout) {
            this.operationTimeout = operationTimeout;
            return this;
        }

        public ConnectionSetup build() {
            return new ConnectionSetup(autoConnect, suppressOperationCheck, operationTimeout);
        }
    }
}


text:
// -----------------------------------------------------------------------
// <copyright file="CreateUserCommandHandler.cs">
// Copyright (c) 2013-2015 Andrey Veselov. All rights reserved.
// License: Apache License 2.0
// Contacts: http://andrey.moveax.com andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace LoreKeeper.Tests.DataAccess.CommandHandlers.Users
{
    using LoreKeeper.Tests.Core.Commands.Users;

    internal class CreateUserCommandHandler : ICommandHandlerSync<CreateUserCommand>, ICommandHandlerTransactionSupport
	{
		public void Execute(CreateUserCommand command)
		{
		}

		public void OnCommitted()
		{
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.cocomap.coco.dagger.component;

import com.cocomap.coco.activity.CreateTopicActivity;
import com.cocomap.coco.activity.GlobalViewActivity;
import com.cocomap.coco.activity.LogInActivity;
import com.cocomap.coco.activity.SignUpActivity;
import com.cocomap.coco.activity.TopicDetailActivity;
import com.cocomap.coco.base.BaseActivity;
import com.cocomap.coco.dagger.module.AppModule;
import com.cocomap.coco.dagger.module.NetModule;

import javax.inject.Singleton;

import dagger.Component;

/**
 * Created by Emrah on 20/11/2016.
 */
@Singleton
@Component(modules = {AppModule.class, NetModule.class})
public interface NetComponent {
    void inject(SignUpActivity activity);

    void inject(LogInActivity activity);

    void inject(TopicDetailActivity activity);

    void inject(CreateTopicActivity activity);

    void inject(GlobalViewActivity activity);

}


text:
import pyblish.api

class ValidateMindbenderDeadlineDone(pyblish.api.InstancePlugin):
    """Ensure render is finished before publishing the resulting images"""

    label = "Rendered Successfully"
    order = pyblish.api.ValidatorOrder
    hosts = ["shell"]
    families = ["mindbender.imagesequence"]
    optional = True

    def process(self, instance):
        from avalon import api
        from avalon.vendor import requests

        # From Deadline documentation
        # https://docs.thinkboxsoftware.com/products/deadline/8.0/
        # 1_User%20Manual/manual/rest-jobs.html#job-property-values
        states = {
            0: "Unknown",
            1: "Active",
            2: "Suspended",
            3: "Completed",
            4: "Failed",
            6: "Pending",
        }

        assert "AVALON_DEADLINE" in api.Session, ("Environment variable "
                                                  "missing: 'AVALON_DEADLINE")
        AVALON_DEADLINE = api.Session["AVALON_DEADLINE"]
        url = "{}/api/jobs?JobID=%s".format(AVALON_DEADLINE)

        for job in instance.data["metadata"]["jobs"]:
            response = requests.get(url % job["_id"])

            if response.ok:
                data = response.json()
                assert data, ValueError("Can't find information about "
                                        "this Deadline job: "
                                        "{}".format(job["_id"]))

                state = states.get(data[0]["Stat"])
                if state in (None, "Unknown"):
                    raise Exception("State of this render is unknown")

                elif state == "Active":
                    raise Exception("This render is still currently active")

                elif state == "Suspended":
                    raise Exception("This render is suspended")

                elif state == "Failed":
                    raise Exception("This render was not successful")

                elif state == "Pending":
                    raise Exception("This render is pending")
                else:
                    self.log.info("%s was rendered successfully" % instance)

            else:
                raise Exception("Could not determine the current status "
                                " of this render")


text:
//// [accessorsEmit.ts]
class Result { }

class Test {
    get Property(): Result {
        var x = 1;
        return null;
    }
}

class Test2 {
    get Property() {
        var x = 1;
        return null;
    }
}

//// [accessorsEmit.js]
var Result = /** @class */ (function () {
    function Result() {
    }
    return Result;
}());
var Test = /** @class */ (function () {
    function Test() {
    }
    Object.defineProperty(Test.prototype, "Property", {
        get: function () {
            var x = 1;
            return null;
        },
        enumerable: true,
        configurable: true
    });
    return Test;
}());
var Test2 = /** @class */ (function () {
    function Test2() {
    }
    Object.defineProperty(Test2.prototype, "Property", {
        get: function () {
            var x = 1;
            return null;
        },
        enumerable: true,
        configurable: true
    });
    return Test2;
}());


text: iOS Swift based Lib to develop fast forms


text:
module App.Models
{
    export interface IModel
    {
        ModelId: string;
        BrandId: string;
        Name: string;
        HelpLink: string;

        Brand: Brand;
        Jobs: Job[];
    }

    export class Model extends BaseModel implements IModel
    {
        //#region Private Static Properties
        //#endregion

        //#region Public Static Properties

        public static get cacheListName(): string { return "modelsLookup"; }
        public static get editUrl(): string { return "/" + Model.urlNamespace + "/:" + Model.lookupProperty + "/edit"; }
        public static get listUrl(): string { return "/" + Model.urlNamespace; }
        public static get lookupProperty(): string { return "ModelId"; }
        public static get urlNamespace(): string { return "models"; }
        public static get newUrl(): string { return "/" + Model.urlNamespace + "/new"; }
        public static get viewUrl(): string { return "/" + Model.urlNamespace + "/:" + Model.lookupProperty; }

        //#endregion

        //#region Private Properties
        //#endregion

        //#region Public Properties

        //#region Table Properties

        public ModelId: string;
        public BrandId: string;
        public Name: string;
        public HelpLink: string;

        public Brand: Brand;
        public Jobs: Job[];

        //#endregion

        public get editUrl(): string { return Model.editUrl.replace(":" + Model.lookupProperty, this.lookupValue); }
        public get fullName(): string
        {
            var companyName = "";
            var brandName = "";

            if (this.Brand)
            {
                brandName = this.Brand.Name || "";

                if (this.Brand.Company)
                {
                    companyName = this.Brand.Company.Name || "";
                }
            }

            return [companyName, brandName, this.Name].join(" ");
        }
        public get lookupValue(): any { return this.ModelId; }
        public get viewUrl(): string { return Model.viewUrl.replace(":" + Model.lookupProperty, this.lookupValue); }

        //#endregion

        //#region Constructors
        //#endregion

        //#region Public Static Methods

        public static getWipKey(...keys: any[]): string
        {
            let prefix = "ModelWipKey_";

            if (keys && keys.length > 0)
            {
                return prefix + keys.join("_");
            }

            return prefix + "New";
        }

        //#endregion

        //#region Private Methods
        //#endregion

        //#region Public Methods
        //#endregion
    }
}


text:
require 'test_helper'

class AlteregoTest < ActiveSupport::TestCase
  test "get alterego" do
    girl = Girl.find_by(slug: 'fugako')
    precure = Alterego.find_by(slug: 'curefuga')

    assert_equal girl, precure.girl
    assert girl.alteregos.include?(precure)
  end
end


text:
<?php

namespace Swaggest\GoCodeBuilder\JsonSchema;

use Swaggest\GoCodeBuilder\Templates\Constant\TypeConstBlock;
use Swaggest\GoCodeBuilder\Templates\Struct\FluentSetter;
use Swaggest\GoCodeBuilder\Templates\Struct\StructDef;
use Swaggest\GoCodeBuilder\Templates\Struct\StructProperty;
use Swaggest\GoCodeBuilder\Templates\Struct\StructType;
use Swaggest\GoCodeBuilder\Templates\Type\AnyType;
use Swaggest\GoCodeBuilder\Templates\Type\Map;
use Swaggest\GoCodeBuilder\Templates\Type\NamedType;
use Swaggest\GoCodeBuilder\Templates\Type\Pointer;
use Swaggest\GoCodeBuilder\Templates\Type\Slice;
use Swaggest\GoCodeBuilder\Templates\Type\TypeUtil;
use Swaggest\JsonSchema\Constraint\Format;
use Swaggest\JsonSchema\Constraint\Type;
use Swaggest\JsonSchema\JsonSchema;
use Swaggest\JsonSchema\Schema;
use Swaggest\GoCodeBuilder\Templates\Type\Type as GoType;
use Swaggest\JsonSchema\SchemaContract;
use Swaggest\JsonSchema\SchemaExporter;
use Swaggest\JsonSchemaMaker\SchemaMaker;

class TypeBuilder
{
    const X_GO_TYPE = 'x-go-type';
    const X_OMIT_EMPTY = 'x-omitempty';
    const X_NULLABLE = 'x-nullable';
    const X_GENERATE = 'x-generate';
    const NULLABLE = 'nullable';
    const EXAMPLES = 'examples';
    const EXAMPLE = 'example';

    const CONDITIONAL_META = 'conditional';

    const NAME_ANY = 'anything';

    /** @var Schema */
    private $schema;
    /** @var string */
    private $path;
    /** @var GoBuilder */
    private $goBuilder;
    /** @var AnyType[] */
    private $result;

    /** @var null|string|string[] JSON Schema type */
    private $type;

    private $nullable = false;

    /** @var StructDef|null parent structure if available */
    private $parentStruct;

    /** @var bool indicates type of required property */
    private $isRequired;

    /**
     * TypeBuilder constructor.
     * @param Schema $schema
     * @param string $path
     * @param GoBuilder $goBuilder
     * @param StructDef|null $parentStruct
     * @param bool $isRequired
     */
    public function __construct(Schema $schema, $path, GoBuilder $goBuilder, StructDef $parentStruct = null, $isRequired = false)
    {
        $this->schema = $schema;
        $this->path = $path;
        $this->goBuilder = $goBuilder;
        $this->parentStruct = $parentStruct;
        $this->isRequired = $isRequired;
    }

    private function makeName(AnyType $type)
    {
        $type = Pointer::tryDereferenceOnce($type);
        if ($type instanceof StructDef) {
            return $type->getName();
        }
        if ($type instanceof StructType) {
            $name = $type->getName();
            $name = $this->goBuilder->replace($name);

            return $name;
        }
        if ($type instanceof NamedType) {
            if ($type->getName() === 'interface{}') {
                return self::NAME_ANY;
            }
            return $type->getName();
        }
        if ($type->getTypeString() === '[]interface{}') {
            return 'SliceOf_' . self::NAME_ANY;
        }
        if ($type instanceof Slice) {
            $itemName = $this->makeName($type->getType());
            if ($itemName !== null) {
                return 'SliceOf_' . $itemName . '_Values';
            }
        }

        return null;
    }

    /**
     * @param Schema $schema
     * @return bool
     */
    private function isSimpleObject($schema)
    {
        if ($schema->type !== null && $schema->type !== Schema::OBJECT) {
            return false;
        }

        if (empty($schema->properties)) {
            return false;
        }

        if (isset($schema->additionalProperties) && $schema->additionalProperties !== true) {
            return false;
        }

        $names = Schema::names();
        // Not a simple object if has additional logical constraints.
        foreach ([
                     $names->anyOf,
                     $names->oneOf,
                     $names->if,
                     $names->not,
                     $names->patternProperties,
                     $names->else,
                 ] as $name) {
            if (isset($schema->$name)) {
                return false;
            }
        }

        return true;
    }

    /**
     * @param Schema[]|SchemaContract[] $allOfs
     */
    private function processAllOfEmbeddableObject($allOfs)
    {
        $allProperties = array();
        foreach ($allOfs as $allOf) {
            if (!$allOf instanceof Schema) {
                return false;
            }

            if (!$this->isSimpleObject($allOf) || null === $allOf->properties) {
                return false;
            }

            foreach ($allOf->properties as $propertyName => $property) {
                if (isset($allProperties[$propertyName])) {
                    return false;
                }

                $allProperties[$propertyName] = true;
            }
        }

        $result = $this->makeResultStruct();
        foreach ($allOfs as $i => $allOf) {
            if (!$allOf instanceof Schema) {
                return false;
            }

            $type = $this->goBuilder->getType($allOf, $this->path . '/allOf/' . $i, $result);
            $result->addProperty(new StructProperty(null, $type));
        }

        return true;
    }

    /**
     * @param Schema[]|SchemaContract[] $orSchemas
     * @param string|mixed $kind
     * @throws Exception
     * @throws \Swaggest\JsonSchema\Exception
     * @throws \Swaggest\JsonSchema\InvalidValue
     */
    private function processOr($orSchemas, $kind)
    {
        $types = [];
        foreach ($orSchemas as $i => $item) {
            if (!$item instanceof Schema && $item instanceof SchemaExporter) {
                $item = $item->exportSchema();
            }
            if ($item instanceof Schema) {
                $path = $this->path . '/' . $kind . '/' . $i;
                if ($kind === Schema::names()->type && is_string($item->type)) {
                    $path = $this->path . '[' . $item->type . ']';
                }
                $itemType = Pointer::tryDereferenceOnce($this->goBuilder->getType($item, $path));
                if ($itemType->getTypeString() === 'interface{}') {
                    continue;
                }
                $types [] = $itemType;
            }
        }
        if (count($types) == 1) {
            $this->result[] = $types[0];
            return;
        }

        $props = [];
        foreach ($orSchemas as $i => $item) {
            if ($item instanceof Schema) {
                $name = $this->goBuilder->codeBuilder->exportableName($kind . '/' . $i);
                $path = $this->path . '/' . $kind . '/' . $i;

                if ($kind === Schema::names()->type && is_string($item->type) && is_string($kind)) {
                    $path = $this->path . '[' . $item->type . ']';
                    $name = $this->goBuilder->codeBuilder->exportableName($kind . '/' . $item->type);
                }

                $betterName = null;
                if (($refs = $item->getFromRefs()) && (($kind !== Schema::names()->type) || $item->type === Schema::OBJECT)) {
                    $betterName = $this->goBuilder->pathToName($refs[0]);
                    $betterName = $this->goBuilder->codeBuilder->exportableName($betterName, true);
                    if (empty($betterName) || isset($props[$betterName])) {
                        $betterName = null;
                    }
                }

                $itemType = Pointer::tryDereferenceOnce($this->goBuilder->getType($item, $path));
                if (empty($betterName) &&
                    ($kind !== Schema::names()->type)) {
                    $betterName = $this->makeName($itemType);
                    $betterName = $this->goBuilder->codeBuilder->exportableName($betterName, true);
                }

                $betterName = $this->goBuilder->replace($betterName);

                if (!empty($betterName) && !isset($props[$betterName])) {
                    $name = $betterName;
                }

                $this->schema->addMeta(true, self::CONDITIONAL_META);
                $resultStruct = $this->makeResultStruct();

                if ($this->goBuilder->options->trimParentFromPropertyNames) {
                    $stripped = substr($name, strlen($resultStruct->getName()));
                    if (
                        strpos($name, $resultStruct->getName()) === 0
                        && $name !== $resultStruct->getName()
                        && $stripped === $this->goBuilder->codeBuilder->exportableName($stripped)
                    ) {
                        $name = $stripped;
                    }
                }

                if ((!$itemType instanceof Map) && (!$itemType instanceof Slice)) {
                    if ($itemType->getTypeString() === 'interface{}') {
                        continue;
                    }
                    $itemType = new Pointer($itemType);
                }

                $props[$name] = true;
                $structProperty = new StructProperty($name, $itemType);
//                $structProperty->setComment($path);
                $structProperty->getTags()->setTag('json', '-');
                $resultStruct->addProperty($structProperty);

                if ($this->goBuilder->options->fluentSetters) {
                    FluentSetter::addToStruct($resultStruct, $structProperty);
                }

                $generatedStruct = $this->getGeneratedStruct();
                $generatedStruct->marshalJson->addSomeOf($kind, $name);
            }
        }
    }

    private function processLogicType()
    {
        if (in_array($this->schema->type, [JsonSchema::STRING, JsonSchema::INTEGER, JsonSchema::NUMBER, JsonSchema::BOOLEAN], true)) {
            // Skip logical keywords if scalar type provided
            return;
        }
        if ($this->schema->allOf !== null) {
            if (!$this->processAllOfEmbeddableObject($this->schema->allOf)) {
                $this->processOr($this->schema->allOf, Schema::names()->allOf);
            }
        } elseif ($this->schema->anyOf !== null) {
            $this->processOr($this->schema->anyOf, Schema::names()->anyOf);
        } elseif ($this->schema->oneOf !== null) {
            $this->processOr($this->schema->oneOf, Schema::names()->oneOf);
        }
    }

    private function processArrayType()
    {
        $schema = $this->schema;

        $pathItems = Schema::names()->items;
        if ($schema->items instanceof Schema) {
            $items = array();
            $additionalItems = $schema->items;
        } elseif ($schema->items === null) { // items defaults to empty schema so everything is valid
            $items = array();
            $additionalItems = true;
        } else { // listed items
            $items = $schema->items;
            $additionalItems = $schema->additionalItems;
            $pathItems = Schema::names()->additionalItems;
        }

        $itemsLen = is_array($items) ? count($items) : 0;
        $index = 0;
        if ($index < $itemsLen) {
        } else {
            if ($additionalItems instanceof Schema) {
                $sliceType = new Slice(Pointer::tryDereferenceOnce(
                    $this->goBuilder->getType($additionalItems, $this->path . '->' . $pathItems))
                );
                if ($this->nullable) {
                    $sliceType = new Pointer($sliceType);
                }
                $this->result[] = $sliceType;
            }
        }
    }

    private function processObjectType()
    {
        $canBeObject = false;
        if ($this->type === null ||
            $this->type === Schema::OBJECT
        ) {
            $canBeObject = true;
        }

        if (!$canBeObject) {
            return;
        }

        if ($this->schema->patternProperties !== null) {
            foreach ($this->schema->patternProperties as $pattern => $schema) {
                if (!$schema instanceof Schema) {
                    continue;
                }
                $itemType = Pointer::tryDereferenceOnce($this->goBuilder->getType($schema, $this->path . '->' . $pattern));
                $name = $this->goBuilder->codeBuilder->exportableName('patternProperties_' . $pattern);
                if (null !== $betterName = $this->makeName($itemType)) {
                    if ($betterName === self::NAME_ANY) {
                        $name = $this->goBuilder->codeBuilder->exportableName('MapOf_' . $betterName);
                    } else {
                        $name = $this->goBuilder->codeBuilder->exportableName('MapOf_' . $betterName . '_Values');
                    }
                }
                $structProperty = new StructProperty(
                    $name,
                    new Map(
                        new GoType("string"),
                        $itemType
                    )
                );
                $structProperty->getTags()->setTag('json', '-');
                $structProperty->setComment('Key must match pattern: `' . $pattern . '`.');

                $resultStruct = $this->makeResultStruct();
                $resultStruct->addProperty($structProperty);

                if ($this->goBuilder->options->fluentSetters) {
                    FluentSetter::addToStruct($resultStruct, $structProperty);
                }

                $this->getGeneratedStruct()->marshalJson->addPatternProperty($pattern, $structProperty);
            }
        }

        /** @var null|boolean|Schema $additionalProperties */
        $additionalProperties = $this->schema->additionalProperties;
        if ($this->goBuilder->options->defaultAdditionalProperties && $additionalProperties === null) {
            $additionalProperties = true;
        }
        if (
            $additionalProperties instanceof Schema ||
            $additionalProperties === true
        ) {

            if ($additionalProperties instanceof Schema) {
                $goType = Pointer::tryDereferenceOnce(
                    $this->goBuilder->getType(
                        $additionalProperties,
                        $this->path . '->' . Schema::names()->additionalProperties)
                );
            } else {
                $goType = TypeUtil::fromString('interface{}');
            }

            if (
                $this->schema->properties !== null ||
                $this->schema->patternProperties !== null
            ) {
                $resultStruct = $this->makeResultStruct();
                $existingProperties = [];
                if ($this->schema->properties !== null) {
                    foreach ($this->schema->properties->toArray() as $propertyName => $property) {
                        $existingProperties[$this->goBuilder->codeBuilder->exportableName($propertyName)] = true;
                    }
                }

                $possibleNames = ['additionalProperties', 'extraProperties', 'unmatchedProperties'];
                foreach ($possibleNames as $name) {
                    $propName = $this->goBuilder->codeBuilder->exportableName($name);
                    if (!isset($existingProperties[$propName])) {
                        break;
                    }
                }
                $i = 1;
                while (isset($existingProperties[$propName])) {
                    $i++;
                    $propName = $this->goBuilder->codeBuilder->exportableName('additionalProperties' . $i);
                }

                if (!$this->getGeneratedStruct()->marshalJson->isAdditionalPropertiesEnabled()) {
                    $structProperty = new StructProperty(
                        $propName,
                        new Map(new GoType("string"), $goType)
                    );
                    $structProperty->setComment('All unmatched properties.');
                    $structProperty->getTags()->setTag('json', '-');
                    $resultStruct->addProperty($structProperty);

                    if ($this->goBuilder->options->fluentSetters) {
                        FluentSetter::addToStruct($resultStruct, $structProperty);
                    }

                    $this->getGeneratedStruct()->marshalJson->enableAdditionalProperties($structProperty);
                }
            } elseif ($additionalProperties instanceof Schema) {
                $mapType = new Map(new GoType('string'), $goType);
                if ($this->nullable) {
                    $mapType = new Pointer($mapType);
                }

                $this->result[] = $mapType;
            }
        }

        if ($additionalProperties === false) {
            $this->getGeneratedStruct()->marshalJson->forbidAdditionalProperties();
        }
    }

    private function typeSwitch($type, $minimum = null, $maximum = null, $format = null)
    {
        switch ($type) {
            case Type::INTEGER:
                if ($this->goBuilder->options->optimizeIntegers && $minimum !== null && $maximum !== null) {
                    if ($minimum >= 0 && $maximum <= 255) {
                        return new GoType('uint8');
                    }
                    if ($minimum >= 0 && $maximum <= 65535) {
                        return new GoType('uint16');
                    }
                    if ($minimum >= 0 && $maximum <= 4294967295) {
                        return new GoType('uint32');
                    }
                    if ($minimum >= 0) {
                        return new GoType('uint64');
                    }

                    if ($minimum >= -128 && $maximum <= 127) {
                        return new GoType('int8');
                    }

                    if ($minimum >= -32768 && $maximum <= 32767) {
                        return new GoType('int16');
                    }

                    if ($minimum >= -2147483648 && $maximum <= 2147483647) {
                        return new GoType('int32');
                    }
                }
                return new GoType('int64');

            case Type::NUMBER:
                return new GoType('float64');

            case TYPE::BOOLEAN:
                return new GoType('bool');

            case Type::STRING:
                if ($format === Format::DATE_TIME) {
                    return TypeUtil::fromString('*time.Time');
                }
                return new GoType('string');

            case Type::OBJECT:
                return TypeUtil::fromString('map[string]interface{}');

            case Type::ARR:
                return TypeUtil::fromString('[]interface{}');

            case Type::NULL:
                return new GoType('interface{}');

            default:
                return null;
        }
    }

    private function processNamedClass()
    {
        $canBeObject = false;
        if ($this->type === null ||
            $this->type === Schema::OBJECT) {
            $canBeObject = true;
        }

        if (!$canBeObject) {
            return;
        }

        if ($this->schema->properties !== null) {
            $this->result[] = $this->makeResultStruct()->getType();
        }
    }

    private function processConst()
    {
        if ($this->schema->const !== null) { // todo properly process null const
            $path = $this->goBuilder->pathToName($this->path);
            $typeName = $this->goBuilder->typeName($this->schema, $path, $this->parentStruct);
            if ($this->parentStruct && false !== $pos = strrpos($path, '->')) {
                $propertyName = substr($path, $pos);
                $typeName = $this->goBuilder->codeBuilder->exportableName($this->parentStruct->getName() . $propertyName);
            }

            $type = new GoType($typeName);

            $baseType = new GoType('interface{}');
            if (is_string($this->schema->const)) {
                $baseType = new GoType('string');
            } elseif (is_int($this->schema->const)) {
                $baseType = new GoType('int64');
            } elseif (is_float($this->schema->const)) {
                $baseType = new GoType('float64');
            } elseif (is_bool($this->schema->const)) {
                $baseType = new GoType('bool');
            }

            if ($this->goBuilder->options->hideConstProperties) {
                return $baseType;
            }

            $typeConstBlock = new TypeConstBlock($type);

            $this->goBuilder->getCode()->addSnippet(<<<GO
// $typeName is a constant type.
type $typeName {$baseType->getName()}

GO
            );

            $constName = $this->goBuilder->codeBuilder->exportableName($typeName . '_' . $this->schema->const);
            if ($constName === $typeName) {
                $constName .= 'Empty';
            }

            $constName = $this->goBuilder->replace($constName);

            $typeConstBlock->addValue(
                $constName,
                $this->schema->const
            );

            $this->goBuilder->getCode()->addSnippet($typeConstBlock);
            $this->goBuilder->getCode()->addSnippet(new MarshalEnum($type, $baseType, $typeConstBlock->getValues(), $this->goBuilder));
            return $type;
        }
        return null;
    }

    private function typeFromValue($val)
    {
        if (is_string($val)) {
            return "string";
        } elseif (is_int($val)) {
            return "integer";
        } elseif (is_bool($val)) {
            return "boolean";
        } elseif (is_numeric($val)) {
            return "number";
        }
        return null;
    }

    private function inferTypeFromEnumConst()
    {
        // Return early if the type is already defined.
        if ($this->type !== null) {
            return;
        }

        // Null type means no override.
        $type = null;

        // Check const.
        if (property_exists($this->schema, Schema::CONST_PROPERTY)) {
            $type = $this->typeFromValue($this->schema->const);
            if ($type !== null) {
                $this->type = $type;
                return;
            }
        }

        // Iterate enum to find if its values share same scalar type.
        if ($this->schema->enum !== null) {
            foreach ($this->schema->enum as $enumItem) {
                $itemType = $this->typeFromValue($enumItem);
                if ($type !== null && $type !== $itemType) {
                    // Break on types mismatch between items.
                    return;
                }
                $type = $itemType;
            }
        }

        // Apply the type found in enum iteration.
        if ($type !== null) {
            $this->type = $type;
        }
    }

    private function processEnum(NamedType $baseType)
    {
        $oneOfEnum = true;
        $enum = null;
        /** @var Schema[] $enumSchemas */
        $enumSchemas = null;
        if ($this->schema->oneOf !== null) {
            foreach ($this->schema->oneOf as $schema) {
                if ($schema instanceof Schema) {
                    if ($schema->const !== null) {
                        $enum[] = $schema->const;
                        $enumSchemas[] = $schema;
                    } else {
                        $oneOfEnum = false;
                    }
                }
            }
        } else {
            $oneOfEnum = false;
        }

        if (!$oneOfEnum) {
            $enum = $this->schema->enum;
            $enumSchemas = null;
        }

        if ($enum !== null && count($enum) === 2
            && $this->schema->type === Schema::BOOLEAN) {
            return $baseType;
        }

        if ($enum !== null) {
            if ($this->goBuilder->options->hideConstProperties && count($enum) === 1) {
                return $baseType;
            }

            if (isset($this->goBuilder->pathTypesDefined[$this->path])) {
                return $this->goBuilder->pathTypesDefined[$this->path];
            }
            $path = $this->goBuilder->pathToName($this->path);

            $typeName = $this->goBuilder->typeName($this->schema, $path, $this->parentStruct);
            $type = new GoType($typeName);
            $this->goBuilder->pathTypesDefined[$this->path] = $type;

            $typeConstBlock = new TypeConstBlock($type);

            $this->goBuilder->getCode()->addSnippet(<<<GO
// $typeName is an enum type.
type $typeName {$baseType->getName()}

GO
            );

            foreach ($enum as $index => $item) {
                $itemName = $this->goBuilder->codeBuilder->exportableName($typeName . '_' . $item);

                if ($itemName === $typeName) {
                    $itemName .= 'Empty';
                }

                $comment = null;
                if (isset($enumSchemas[$index])) {
                    $schema = $enumSchemas[$index];
                    if (isset($schema->title)) {
                        $itemName = $this->goBuilder->codeBuilder->exportableName($typeName . '_' . $schema->title);
                    }

                    if (isset($schema->description)) {
                        $comment = $schema->description;
                    }
                }

                $itemName = $this->goBuilder->replace($itemName);

                $typeConstBlock->addValue($itemName, $item, $comment);
            }

            $this->goBuilder->getCode()->addSnippet($typeConstBlock);
            $this->goBuilder->getCode()->addSnippet(new MarshalEnum($type, $baseType, $typeConstBlock->getValues(), $this->goBuilder));

            return $type;
        }

        return $baseType;
    }

    private function getGeneratedStruct()
    {
        return $this->goBuilder->getGeneratedStruct($this->schema, $this->path);
    }

    private function makeResultStruct()
    {
        if ($this->resultStruct === null) {
            $this->resultStruct = $this->goBuilder->getClass($this->schema, $this->path);
        }
        return $this->resultStruct;
    }

    /** @var StructDef */
    private $resultStruct;

    /**
     * @return AnyType
     * @throws Exception
     */
    public function build()
    {
        if (!$this->goBuilder->options->ignoreXGoType && $this->schema->{self::X_GO_TYPE}) {
            // go-swagger formatted type.
            /*
             * {
                  "import": {
                    "package": "github.com/my-org/my-service/internal/domain/orders"
                  },
                  "type": "Order"
                }
             */
            $xGoType = $this->schema->{self::X_GO_TYPE};
            if ($xGoType instanceof \stdClass) {
                $typeString = '';
                if (isset($xGoType->import) && isset($xGoType->import->package)) {
                    $typeString .= $xGoType->import->package . '.';
                }
                if (isset($xGoType->type)) {
                    $typeString .= $xGoType->type;
                }
                return TypeUtil::fromString($typeString);
            } elseif (is_string($xGoType)) {
                return TypeUtil::fromString($xGoType);
            }
        }

        if (
            $this->goBuilder->options->inheritSchemaFromExamples
            && empty($this->schema->type) && empty($this->schema->properties)
        ) {
            $schemaMaker = new SchemaMaker($this->schema);

            if (
                isset($this->schema->{self::EXAMPLES})
                && is_array($this->schema->{self::EXAMPLES})
            ) {
                foreach ($this->schema->{self::EXAMPLES} as $example) {
                    $schemaMaker->addInstanceValue($example);
                }
            }

            if (isset($this->schema->{self::EXAMPLE})) {
                $schemaMaker->addInstanceValue($this->schema->{self::EXAMPLE});
            }
        }

        $this->result = array();

        // TODO reduce structure complexity in Swaggest\JsonSchema.
        /** @var string[]|boolean[] $path */
        $path = $this->schema->getFromRefs();
        if (!empty($path)) {
            if (false === $path[count($path) - 1]) {
                $path = null;
            } else {
                $path = $path[0];
            }
        }
        if (!empty($path) && is_string($path)) {
            $this->path = $path;
        }

        $this->type = $this->schema->type;

        if ($this->goBuilder->options->enableXNullable) {
            if ($this->schema->{self::X_NULLABLE} === true || $this->schema->{self::NULLABLE} === true) {
                if (is_array($this->type) && !in_array(Schema::NULL, $this->type)) {
                    $this->type[] = Schema::NULL;
                } elseif (is_string($this->type) && $this->type !== Schema::NULL) {
                    $this->type = [$this->type, Schema::NULL];
                }
            }
        }

        if (is_array($this->type)) {
            foreach ($this->type as $k => $item) {
                if ($item === Schema::NULL) {
                    $this->nullable = true;
                    unset($this->type[$k]);
                    $this->type = array_values($this->type);
                    break;
                }
            }

            if (empty($this->type)) {
                $this->type = null;
            } elseif (count($this->type) === 1) {
                $this->type = $this->type[0];
            }
        }

        $this->inferTypeFromEnumConst();

        $this->processNamedClass();
        $this->processLogicType();
        $this->processArrayType();
        $this->processObjectType();

        if (is_array($this->type)) {
            $or = [];
            foreach ($this->type as $type) {
                $schema = clone $this->schema;
                $schema->setFromRef(false);
                $schema->type = $type;
                $or [] = $schema;
            }
            $this->processOr($or, Schema::names()->type);
        } elseif ($this->type) {
            $type = $this->typeSwitch($this->type, $this->schema->minimum, $this->schema->maximum, $this->schema->format);
            if ($type instanceof NamedType) { // todo properly process const = null
                $type = $this->processEnum($type);
            }
            if (
                $this->nullable ||
                ($this->goBuilder->options->withZeroValues && false !== $this->schema->{self::X_OMIT_EMPTY})
            ) {
                if (
                    (!$type instanceof Pointer) &&
                    (!$type instanceof Map) &&
                    (!$type instanceof Slice) &&
                    (!$this->isRequired || $this->goBuilder->options->ignoreRequired || $this->nullable) &&
                    ($type->getTypeString() !== 'interface{}')
                ) {
                    $type = new Pointer($type);
                    if ($this->nullable && !$this->goBuilder->options->ignoreNullable) {
                        $type->setNoOmitEmpty(true);
                    }
                }
            }
            $this->result[] = $type;
        }

        $hasConst = $this->schema->const !== null;
        if ($hasConst) {
            $type = $this->processConst();
            if (null !== $type) {
                $this->result[] = $type;
            }
        }

        if ($this->resultStruct !== null) {
            return $this->resultStruct->getType();
        }

        if (empty($this->result)) {
            return new GoType('interface{}');
        } else {
            if (1 === count($this->result)) {
                return $this->result[0];
            } else {
                return $this->result[0];
            }
        }
    }
}


text:
"""Tests for yapf.format_decision_state."""

import textwrap
import unittest

from yapf.yapflib import format_decision_state
from yapf.yapflib import pytree_utils
from yapf.yapflib import style
from yapf.yapflib import unwrapped_line

from yapftests import yapf_test_helper

class FormatDecisionStateTest(yapf_test_helper.YAPFTest):

  @classmethod
  def setUpClass(cls):
    style.SetGlobalStyle(style.CreateChromiumStyle())

  def testSimpleFunctionDefWithNoSplitting(self):
    code = textwrap.dedent(r"""
      def f(a, b):
        pass
      """)
    uwlines = yapf_test_helper.ParseAndUnwrap(code)
    uwline = unwrapped_line.UnwrappedLine(0, _FilterLine(uwlines[0]))
    uwline.CalculateFormattingInformation()

    # Add: 'f'
    state = format_decision_state.FormatDecisionState(uwline, 0)
    state.MoveStateToNextToken()
    self.assertEqual('f', state.next_token.value)
    self.assertFalse(state.CanSplit(False))

    # Add: '('
    state.AddTokenToState(False, True)
    self.assertEqual('(', state.next_token.value)
    self.assertFalse(state.CanSplit(False))
    self.assertFalse(state.MustSplit())

    # Add: 'a'
    state.AddTokenToState(False, True)
    self.assertEqual('a', state.next_token.value)
    self.assertTrue(state.CanSplit(False))
    self.assertFalse(state.MustSplit())

    # Add: ','
    state.AddTokenToState(False, True)
    self.assertEqual(',', state.next_token.value)
    self.assertFalse(state.CanSplit(False))
    self.assertFalse(state.MustSplit())

    # Add: 'b'
    state.AddTokenToState(False, True)
    self.assertEqual('b', state.next_token.value)
    self.assertTrue(state.CanSplit(False))
    self.assertFalse(state.MustSplit())

    # Add: ')'
    state.AddTokenToState(False, True)
    self.assertEqual(')', state.next_token.value)
    self.assertTrue(state.CanSplit(False))
    self.assertFalse(state.MustSplit())

    # Add: ':'
    state.AddTokenToState(False, True)
    self.assertEqual(':', state.next_token.value)
    self.assertFalse(state.CanSplit(False))
    self.assertFalse(state.MustSplit())

    clone = state.Clone()
    self.assertEqual(repr(state), repr(clone))

  def testSimpleFunctionDefWithSplitting(self):
    code = textwrap.dedent(r"""
      def f(a, b):
        pass
      """)
    uwlines = yapf_test_helper.ParseAndUnwrap(code)
    uwline = unwrapped_line.UnwrappedLine(0, _FilterLine(uwlines[0]))
    uwline.CalculateFormattingInformation()

    # Add: 'f'
    state = format_decision_state.FormatDecisionState(uwline, 0)
    state.MoveStateToNextToken()
    self.assertEqual('f', state.next_token.value)
    self.assertFalse(state.CanSplit(False))

    # Add: '('
    state.AddTokenToState(True, True)
    self.assertEqual('(', state.next_token.value)
    self.assertFalse(state.CanSplit(False))

    # Add: 'a'
    state.AddTokenToState(True, True)
    self.assertEqual('a', state.next_token.value)
    self.assertTrue(state.CanSplit(False))

    # Add: ','
    state.AddTokenToState(True, True)
    self.assertEqual(',', state.next_token.value)
    self.assertFalse(state.CanSplit(False))

    # Add: 'b'
    state.AddTokenToState(True, True)
    self.assertEqual('b', state.next_token.value)
    self.assertTrue(state.CanSplit(False))

    # Add: ')'
    state.AddTokenToState(True, True)
    self.assertEqual(')', state.next_token.value)
    self.assertTrue(state.CanSplit(False))

    # Add: ':'
    state.AddTokenToState(True, True)
    self.assertEqual(':', state.next_token.value)
    self.assertFalse(state.CanSplit(False))

    clone = state.Clone()
    self.assertEqual(repr(state), repr(clone))

def _FilterLine(uwline):
  """Filter out nonsemantic tokens from the UnwrappedLines."""
  return [
      ft for ft in uwline.tokens
      if ft.name not in pytree_utils.NONSEMANTIC_TOKENS
  ]

if __name__ == '__main__':
  unittest.main()


text:
using System;

namespace _2DeepEngine.Graphics
{
    /// <summary>
    /// A bundle of Vertex, Pixel, and optionaly Geometry <see cref="IShader"/>.
    /// </summary>
    public abstract class ShaderBundle
    {
        public abstract void Bind();
        public abstract void Unbind();

        public class Builder
        {
            private readonly IShader[] _shaders = new IShader[3];

            public Builder VertexShader(IShader shader)
            {
                _shaders[0] = shader;
                return this;
            }

            public Builder GeometryShader(IShader shader)
            {
                _shaders[1] = shader;
                return this;
            }

            public Builder PixelShader(IShader shader)
            {
                _shaders[2] = shader;
                return this;
            }

            public ShaderBundle Build()
            {
                if (_shaders[0] == null)
                    throw new InvalidOperationException("Missing Vertex Shader.");
                if (_shaders[2] == null)
                    throw new InvalidOperationException("Missing Pixel Shader.");
                return new Platform.GLShaderBundle(_shaders[0], _shaders[1], _shaders[2]);
            }
        }
    }
}


text:
@import '../../node_modules/normalize-styl/normalize'
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
* {
	box-sizing: border-box;
}
body {
	background:#eee;
	font-family: 'Open Sans', sans-serif;
}


text:
import operator
import warnings

from django import template
from django.template.defaultfilters import stringfilter
from django.utils import six
from django.utils.html import escape, format_html

register = template.Library()

@register.filter
@stringfilter
def trim(value, num):
    return value[:num]

@register.filter
def noop(value, param=None):
    """A noop filter that always return its first argument and does nothing with
    its second (optional) one.
    Useful for testing out whitespace in filter arguments (see #19882)."""
    return value

@register.simple_tag(takes_context=True)
def context_stack_length(context):
    return len(context.dicts)

@register.simple_tag
def no_params():
    """Expected no_params __doc__"""
    return "no_params - Expected result"
no_params.anything = "Expected no_params __dict__"

@register.simple_tag
def one_param(arg):
    """Expected one_param __doc__"""
    return "one_param - Expected result: %s" % arg
one_param.anything = "Expected one_param __dict__"

@register.simple_tag(takes_context=False)
def explicit_no_context(arg):
    """Expected explicit_no_context __doc__"""
    return "explicit_no_context - Expected result: %s" % arg
explicit_no_context.anything = "Expected explicit_no_context __dict__"

@register.simple_tag(takes_context=True)
def no_params_with_context(context):
    """Expected no_params_with_context __doc__"""
    return "no_params_with_context - Expected result (context value: %s)" % context['value']
no_params_with_context.anything = "Expected no_params_with_context __dict__"

@register.simple_tag(takes_context=True)
def params_and_context(context, arg):
    """Expected params_and_context __doc__"""
    return "params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)
params_and_context.anything = "Expected params_and_context __dict__"

@register.simple_tag
def simple_two_params(one, two):
    """Expected simple_two_params __doc__"""
    return "simple_two_params - Expected result: %s, %s" % (one, two)
simple_two_params.anything = "Expected simple_two_params __dict__"

@register.simple_tag
def simple_one_default(one, two='hi'):
    """Expected simple_one_default __doc__"""
    return "simple_one_default - Expected result: %s, %s" % (one, two)
simple_one_default.anything = "Expected simple_one_default __dict__"

@register.simple_tag
def simple_unlimited_args(one, two='hi', *args):
    """Expected simple_unlimited_args __doc__"""
    return "simple_unlimited_args - Expected result: %s" % (
        ', '.join(six.text_type(arg) for arg in [one, two] + list(args))
    )
simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__"

@register.simple_tag
def simple_only_unlimited_args(*args):
    """Expected simple_only_unlimited_args __doc__"""
    return "simple_only_unlimited_args - Expected result: %s" % ', '.join(six.text_type(arg) for arg in args)
simple_only_unlimited_args.anything = "Expected simple_only_unlimited_args __dict__"

@register.simple_tag
def simple_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
    """Expected simple_unlimited_args_kwargs __doc__"""
    # Sort the dictionary by key to guarantee the order for testing.
    sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))
    return "simple_unlimited_args_kwargs - Expected result: %s / %s" % (
        ', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
        ', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
    )
simple_unlimited_args_kwargs.anything = "Expected simple_unlimited_args_kwargs __dict__"

@register.simple_tag(takes_context=True)
def simple_tag_without_context_parameter(arg):
    """Expected simple_tag_without_context_parameter __doc__"""
    return "Expected result"
simple_tag_without_context_parameter.anything = "Expected simple_tag_without_context_parameter __dict__"

@register.simple_tag(takes_context=True)
def escape_naive(context):
    """A tag that doesn't even think about escaping issues"""
    return "Hello {0}!".format(context['name'])

@register.simple_tag(takes_context=True)
def escape_explicit(context):
    """A tag that uses escape explicitly"""
    return escape("Hello {0}!".format(context['name']))

@register.simple_tag(takes_context=True)
def escape_format_html(context):
    """A tag that uses format_html"""
    return format_html("Hello {0}!", context['name'])

@register.simple_tag(takes_context=True)
def current_app(context):
    return "%s" % context.current_app

@register.simple_tag(takes_context=True)
def use_l10n(context):
    return "%s" % context.use_l10n

@register.simple_tag(name='minustwo')
def minustwo_overridden_name(value):
    return value - 2

register.simple_tag(lambda x: x - 1, name='minusone')

with warnings.catch_warnings():
    warnings.simplefilter('ignore')

    @register.assignment_tag
    def assignment_no_params():
        """Expected assignment_no_params __doc__"""
        return "assignment_no_params - Expected result"
    assignment_no_params.anything = "Expected assignment_no_params __dict__"

    @register.assignment_tag(takes_context=True)
    def assignment_tag_without_context_parameter(arg):
        """Expected assignment_tag_without_context_parameter __doc__"""
        return "Expected result"
    assignment_tag_without_context_parameter.anything = "Expected assignment_tag_without_context_parameter __dict__"


text:
(function(ionic) {
'use strict';

  /**
   * The SideMenuController is a controller with a left and/or right menu that
   * can be slid out and toggled. Seen on many an app.
   *
   * The right or left menu can be disabled or not used at all, if desired.
   */
  ionic.controllers.SideMenuController = ionic.controllers.ViewController.inherit({
    initialize: function(options) {
      var self = this;

      this.left = options.left;
      this.right = options.right;
      this.content = options.content;
      this.dragThresholdX = options.dragThresholdX || 10;

      this._rightShowing = false;
      this._leftShowing = false;
      this._isDragging = false;

      if(this.content) {
        this.content.onDrag = function(e) {
          self._handleDrag(e);
        };

        this.content.onEndDrag =function(e) {
          self._endDrag(e);
        };
      }
    },
    /**
     * Set the content view controller if not passed in the constructor options.
     *
     * @param {object} content
     */
    setContent: function(content) {
      var self = this;

      this.content = content;

      this.content.onDrag = function(e) {
        self._handleDrag(e);
      };

      this.content.endDrag = function(e) {
        self._endDrag(e);
      };
    },

    isOpenLeft: function() {
      return this.getOpenAmount() > 0;
    },

    isOpenRight: function() {
      return this.getOpenAmount() < 0;
    },

    /**
     * Toggle the left menu to open 100%
     */
    toggleLeft: function(shouldOpen) {
      var openAmount = this.getOpenAmount();
      if (arguments.length === 0) {
        shouldOpen = openAmount <= 0;
      }
      this.content.enableAnimation();
      if(!shouldOpen) {
        this.openPercentage(0);
      } else {
        this.openPercentage(100);
      }
    },

    /**
     * Toggle the right menu to open 100%
     */
    toggleRight: function(shouldOpen) {
      var openAmount = this.getOpenAmount();
      if (arguments.length === 0) {
        shouldOpen = openAmount >= 0;
      }
      this.content.enableAnimation();
      if(!shouldOpen) {
        this.openPercentage(0);
      } else {
        this.openPercentage(-100);
      }
    },

    /**
     * Close all menus.
     */
    close: function() {
      this.openPercentage(0);
    },

    /**
     * @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative)
     */
    getOpenAmount: function() {
      return this.content && this.content.getTranslateX() || 0;
    },

    /**
     * @return {float} The ratio of open amount over menu width. For example, a
     * menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative
     * for right menu.
     */
    getOpenRatio: function() {
      var amount = this.getOpenAmount();
      if(amount >= 0) {
        return amount / this.left.width;
      }
      return amount / this.right.width;
    },

    isOpen: function() {
      return this.getOpenAmount() !== 0;
    },

    /**
     * @return {float} The percentage of open amount over menu width. For example, a
     * menu of width 100 open 50 pixels would be open 50%. Value is negative
     * for right menu.
     */
    getOpenPercentage: function() {
      return this.getOpenRatio() * 100;
    },

    /**
     * Open the menu with a given percentage amount.
     * @param {float} percentage The percentage (positive or negative for left/right) to open the menu.
     */
    openPercentage: function(percentage) {
      var p = percentage / 100;

      if(this.left && percentage >= 0) {
        this.openAmount(this.left.width * p);
      } else if(this.right && percentage < 0) {
        var maxRight = this.right.width;
        this.openAmount(this.right.width * p);
      }
    },

    /**
     * Open the menu the given pixel amount.
     * @param {float} amount the pixel amount to open the menu. Positive value for left menu,
     * negative value for right menu (only one menu will be visible at a time).
     */
    openAmount: function(amount) {
      var maxLeft = this.left && this.left.width || 0;
      var maxRight = this.right && this.right.width || 0;

      // Check if we can move to that side, depending if the left/right panel is enabled
      if(!(this.left && this.left.isEnabled) && amount > 0) {
        this.content.setTranslateX(0);
        return;
      }

      if(!(this.right && this.right.isEnabled) && amount < 0) {
        this.content.setTranslateX(0);
        return;
      }

      if(this._leftShowing && amount > maxLeft) {
        this.content.setTranslateX(maxLeft);
        return;
      }

      if(this._rightShowing && amount < -maxRight) {
        this.content.setTranslateX(-maxRight);
        return;
      }

      this.content.setTranslateX(amount);

      if(amount >= 0) {
        this._leftShowing = true;
        this._rightShowing = false;

        if(amount > 0) {
          // Push the z-index of the right menu down
          this.right && this.right.pushDown && this.right.pushDown();
          // Bring the z-index of the left menu up
          this.left && this.left.bringUp && this.left.bringUp();
        }
      } else {
        this._rightShowing = true;
        this._leftShowing = false;

        // Bring the z-index of the right menu up
        this.right && this.right.bringUp && this.right.bringUp();
        // Push the z-index of the left menu down
        this.left && this.left.pushDown && this.left.pushDown();
      }
    },

    /**
     * Given an event object, find the final resting position of this side
     * menu. For example, if the user "throws" the content to the right and
     * releases the touch, the left menu should snap open (animated, of course).
     *
     * @param {Event} e the gesture event to use for snapping
     */
    snapToRest: function(e) {
      // We want to animate at the end of this
      this.content.enableAnimation();
      this._isDragging = false;

      // Check how much the panel is open after the drag, and
      // what the drag velocity is
      var ratio = this.getOpenRatio();

      if(ratio === 0) {
        // Just to be safe
        this.openPercentage(0);
        return;
      }

      var velocityThreshold = 0.3;
      var velocityX = e.gesture.velocityX;
      var direction = e.gesture.direction;

      // Less than half, going left
      //if(ratio > 0 && ratio < 0.5 && direction == 'left' && velocityX < velocityThreshold) {
      //this.openPercentage(0);
      //}

      // Going right, less than half, too slow (snap back)
      if(ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {
        this.openPercentage(0);
      }

      // Going left, more than half, too slow (snap back)
      else if(ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) {
        this.openPercentage(100);
      }

      // Going left, less than half, too slow (snap back)
      else if(ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) {
        this.openPercentage(0);
      }

      // Going right, more than half, too slow (snap back)
      else if(ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {
        this.openPercentage(-100);
      }

      // Going right, more than half, or quickly (snap open)
      else if(direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) {
        this.openPercentage(100);
      }

      // Going left, more than half, or quickly (span open)
      else if(direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) {
        this.openPercentage(-100);
      }

      // Snap back for safety
      else {
        this.openPercentage(0);
      }
    },

    // End a drag with the given event
    _endDrag: function(e) {
      if(this._isDragging) {
        this.snapToRest(e);
      }
      this._startX = null;
      this._lastX = null;
      this._offsetX = null;
    },

    // Handle a drag event
    _handleDrag: function(e) {
      // If we don't have start coords, grab and store them
      if(!this._startX) {
        this._startX = e.gesture.touches[0].pageX;
        this._lastX = this._startX;
      } else {
        // Grab the current tap coords
        this._lastX = e.gesture.touches[0].pageX;
      }

      // Calculate difference from the tap points
      if(!this._isDragging && Math.abs(this._lastX - this._startX) > this.dragThresholdX) {
        // if the difference is greater than threshold, start dragging using the current
        // point as the starting point
        this._startX = this._lastX;

        this._isDragging = true;
        // Initialize dragging
        this.content.disableAnimation();
        this._offsetX = this.getOpenAmount();
      }

      if(this._isDragging) {
        this.openAmount(this._offsetX + (this._lastX - this._startX));
      }
    }
  });

})(ionic);


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-boot-test</artifactId>
        <groupId>com.whc</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-boot-chapter10</artifactId>
    <packaging>jar</packaging>

    <name>spring-boot-chapter10</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>us.codecraft</groupId>
            <artifactId>webmagic-core</artifactId>
        </dependency>
        <dependency>
            <groupId>us.codecraft</groupId>
            <artifactId>webmagic-extension</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
package com.google.ipc.invalidation.ticl.android2.channel;

import com.google.android.gcm.GCMRegistrar;
import com.google.ipc.invalidation.external.client.SystemResources.Logger;
import com.google.ipc.invalidation.external.client.android.service.AndroidLogger;
import com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener;
import com.google.ipc.invalidation.ticl.android2.AndroidTiclManifest;
import com.google.ipc.invalidation.ticl.android2.ProtocolIntents;
import com.google.ipc.invalidation.ticl.android2.channel.AndroidChannelConstants.C2dmConstants;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protos.ipc.invalidation.AndroidChannel.AddressedAndroidMessage;

import android.content.Context;
import android.content.Intent;
import android.util.Base64;

/**
 * Service that receives messages from  using GCM.
 *
 */
public class AndroidMessageReceiverService extends MultiplexingGcmListener.AbstractListener {
  /*
   * This class is public so that it can be instantiated by the Android runtime. All of the
   * {@code onYYY} methods are called holding a wakelock that will be automatically released when
   * they return, since this is a subclass of {@code AbstractListener}.
   */

  /**
   * Receiver for broadcasts by the multiplexed GCM service. It forwards them to
   * AndroidMessageReceiverService.
   */
  public static class Receiver extends MultiplexingGcmListener.AbstractListener.Receiver {
    /* This class is public so that it can be instantiated by the Android runtime. */
    @Override
    protected Class<?> getServiceClass() {
      return AndroidMessageReceiverService.class;
    }
  }

  private final Logger logger = AndroidLogger.forTag("MsgRcvrSvc");

  public AndroidMessageReceiverService() {
    super("AndroidMessageReceiverService");
  }

  @Override
  protected void onMessage(Intent intent) {
    // Forward the message to the Ticl service.
    if (intent.hasExtra(C2dmConstants.CONTENT_PARAM)) {
      String content = intent.getStringExtra(C2dmConstants.CONTENT_PARAM);
      byte[] msgBytes = Base64.decode(content, Base64.URL_SAFE);
      try {
        // Look up the name of the Ticl service class from the manifest.
        String serviceClass = new AndroidTiclManifest(this).getTiclServiceClass();
        AddressedAndroidMessage addrMessage = AddressedAndroidMessage.parseFrom(msgBytes);
        Intent msgIntent =
            ProtocolIntents.InternalDowncalls.newServerMessageIntent(addrMessage.getMessage());
        msgIntent.setClassName(this, serviceClass);
        startService(msgIntent);
      } catch (InvalidProtocolBufferException exception) {
        logger.warning("Failed parsing inbound message: %s", exception);
      }
    } else {
      logger.fine("GCM Intent has no message content: %s", intent);
    }

    // Store the echo token.
    String echoToken = intent.getStringExtra(C2dmConstants.ECHO_PARAM);
    if (echoToken != null) {
      AndroidChannelPreferences.setEchoToken(this, echoToken);
    }
  }

  @Override
  protected void onRegistered(String registrationId) {
    // Inform the sender service that the registration id has changed. If the sender service
    // had buffered a message because no registration id was previously available, this intent
    // will cause it to send that message.
    Intent sendBuffered = new Intent();
    final String ignoredData = "";
    sendBuffered.putExtra(AndroidChannelConstants.MESSAGE_SENDER_SVC_GCM_REGID_CHANGE, ignoredData);
    sendBuffered.setClass(this, AndroidMessageSenderService.class);
    startService(sendBuffered);

    // Inform the Ticl service that the registration id has changed. This will cause it to send
    // a message to the data center and update the GCM registration id stored at the data center.
    Intent updateServer = ProtocolIntents.InternalDowncalls.newNetworkAddrChangeIntent();
    updateServer.setClassName(this, new AndroidTiclManifest(this).getTiclServiceClass());
    startService(updateServer);
  }

  @Override
  protected void onUnregistered(String registrationId) {
    // Nothing to do.
  }

  @Override
  protected void onDeletedMessages(int total) {
    // This method must be implemented if we start using non-collapsable messages with GCM. For
    // now, there is nothing to do.
  }

  /**
   * Initializes GCM as a convenience method for tests. In production, applications should handle
   * this.
   */
  public static void initializeGcmForTest(Context context, Logger logger, String senderId) {
    // Initialize GCM.
    GCMRegistrar.checkDevice(context);
    GCMRegistrar.checkManifest(context);
    String regId = GCMRegistrar.getRegistrationId(context);
    if (regId.equals("")) {
      logger.info("Not registered with GCM; registering");
      GCMRegistrar.register(context, senderId);
    } else {
      logger.fine("Already registered with GCM: %s", regId);
    }
  }
}


text:
/**
 * @file libohiboard/include/i2c.h
 * @author Marco Giammarini <m.giammarini@warcomeb.it>
 * @brief I2C definitions and prototypes
 */

/**
 * @addtogroup LIBOHIBOARD_Driver
 * @{
 */

#ifdef LIBOHIBOARD_IIC

/**
 * @defgroup I2C I2C
 * @brief I2C HAL driver
 * @{
 */

#ifndef __I2C_H
#define __I2C_H

#ifdef __cplusplus
extern "C" {
#endif

#include "platforms.h"
#include "errors.h"
#include "types.h"
#include "system.h"

/**
 * @defgroup I2C_Configuration_Functions I2C configuration functions and types
 * @brief Functions and types to open, close and configure a I2C peripheral.
 * @{
 */

/**
 * Definition for possible device behavioral.
 */
typedef enum
{
    IIC_MASTER_MODE,
    IIC_SLAVE_MODE,

} Iic_DeviceType;

/**
 * Definition for possible address mode.
 */
typedef enum
{
    IIC_SEVEN_BIT,
    IIC_TEN_BIT,

} Iic_AddressMode;

/**
 * Useful definition to declare the register address dimension in bit during
 * read or write register operations.
 */
typedef enum _Iic_RegisterAddressSize
{
    IIC_REGISTERADDRESSSIZE_8BIT  = 1,
    IIC_REGISTERADDRESSSIZE_16BIT = 2,

} Iic_RegisterAddressSize;

/**
 * The list of the possible peripheral HAL state.
 */
typedef enum _Iic_DeviceState
{
    IIC_DEVICESTATE_RESET,
    IIC_DEVICESTATE_READY,
    IIC_DEVICESTATE_BUSY,
    IIC_DEVICESTATE_ERROR,

} Iic_DeviceState;

#if defined (LIBOHIBOARD_NXP_KINETIS)

typedef enum
{
    IIC_NO_STOP,
    IIC_STOP

} Iic_StopMode;

typedef enum
{
    IIC_LAST_BYTE,
    IIC_NO_LAST_BYTE

} Iic_LastByteMode;

#endif // LIBOHIBOARD_NXP_KINETIS

#if defined (LIBOHIBOARD_ST_STM32)

typedef enum _Iic_ClockSource
{
    IIC_CLOCKSOURCE_PCLK    = 0x00U,                  /**< PCLK clock source */
    IIC_CLOCKSOURCE_SYSCLK  = 0x01U,                /**< SYSCLK clock source */
    IIC_CLOCKSOURCE_HSI     = 0x02U,                   /**< HSI clock source */

} Iic_ClockSource;

/**
 * Useful define for choosing the dual address mode.
 */
typedef enum _Iic_DualAddress
{
    IIC_DUALADDRESS_ENABLE,
    IIC_DUALADDRESS_DISABLE,

} Iic_DualAddress;

/**
 * List of usable mask for second address.
 */
typedef enum _Iic_DualAddressMask
{
    IIC_DUALADDRESSMASK_NO_MASK = 0x00,
    IIC_DUALADDRESSMASK_MASK_01 = 0x01,
    IIC_DUALADDRESSMASK_MASK_02 = 0x02,
    IIC_DUALADDRESSMASK_MASK_03 = 0x03,
    IIC_DUALADDRESSMASK_MASK_04 = 0x04,
    IIC_DUALADDRESSMASK_MASK_05 = 0x05,
    IIC_DUALADDRESSMASK_MASK_06 = 0x06,
    IIC_DUALADDRESSMASK_MASK_07 = 0x07,

} Iic_DualAddressMask;

typedef enum _Iic_NoStretch
{
    IIC_NOSTRETCH_ENABLE,
    IIC_NOSTRETCH_DISABLE,

} Iic_NoStrech;

#endif // LIBOHIBOARD_ST_STM32

#if (LIBOHIBOARD_VERSION >= 0x20000u)
typedef struct _Iic_Device* Iic_DeviceHandle;
#else
typedef struct Iic_Device* Iic_DeviceHandle;
#endif

#if defined (LIBOHIBOARD_STM32L0)

#include "hardware/STM32L0/i2c_STM32L0.h"

#elif defined (LIBOHIBOARD_STM32L4)

#include "hardware/STM32L4/i2c_STM32L4.h"

#elif defined (LIBOHIBOARD_PIC24FJ)

#include "hardware/PIC24FJ/i2c_PIC24FJ.h"

#elif defined (LIBOHIBOARD_MKL)

#include "hardware/NXPMKL/i2c_MKL.h"

#else

typedef enum
{
	IIC_PINS_SCLNONE,

} Iic_SclPins;

typedef enum
{

	IIC_PINS_SDANONE,

} Iic_SdaPins;

#endif

typedef struct _Iic_Config
{
    Iic_SclPins           sclPin;
    Iic_SdaPins           sdaPin;

    uint32_t              baudrate;
    Iic_DeviceType        devType;
    Iic_AddressMode       addressMode;

    bool                  pullupEnable;

    uint16_t              sclTimeout;

#if defined LIBOHIBOARD_ST_STM32

    Iic_ClockSource clockSource;

    uint32_t address1;
    uint32_t address2;
    Iic_DualAddress dualAddressMode;
    Iic_DualAddressMask dualAddressMask;
    Iic_NoStrech noStretch;

#endif

} Iic_Config;

/**
  * @brief Initialize the I2C according to the specified parameters
  *         in the @ref Iic_Config and initialize the associated handle.
  * @param[in] dev I2C device handle
  * @param[in] config Configuration parameters list.
  * @return ERRORS_NO_ERROR The initialization is ok.
  */
System_Errors Iic_init (Iic_DeviceHandle dev, Iic_Config *config);

/**
 * This function de-initialize the selected peripheral.
 *
 * @param[in] dev I2C device handle
 */
System_Errors Iic_deInit (Iic_DeviceHandle dev);

/**
 * @}
 */

#if (LIBOHIBOARD_VERSION >= 0x20000u)

/**
 * @defgroup I2C_Read_Write_Master_Functions I2C read/write master functions
 * @brief Functions to read and write to I2C peripheral by master device.
 * @{
 */

/**
 * This function send a specified number of bytes to a selected
 * slave device into I2C bus.
 * This function is blocking.
 *
 * @param[in] dev I2C device handle
 * @param[in] address Slave device address
 * @param[in] data Pointer to data buffer
 * @param[in] length the number of byte to write
 * @param[in] timeout Max timeout in millisecond
 */
System_Errors Iic_writeMaster (Iic_DeviceHandle dev,
                               uint16_t address,
                               const uint8_t* data,
                               uint16_t length,
                               uint32_t timeout);

/**
 * This function read a specified number of bytes from a selected
 * slave device into I2C bus.
 * This function is blocking.
 *
 * @param[in] dev I2C device handle
 * @param[in] address Slave device address
 * @param[out] data Pointer to data buffer
 * @param[in] length the number of byte to read
 * @param[in] timeout Max timeout in millisecond
 */
System_Errors Iic_readMaster (Iic_DeviceHandle dev,
                              uint16_t address,
                              uint8_t* data,
                              uint8_t length,
                              uint32_t timeout);

/**
 * This function write a register or memory location to the selected
 * slave device into I2C bus.
 * This function is blocking.
 *
 * @param[in] dev I2C device handle
 * @param[in] devAddress Slave device address 7bit or 10bit
 * @param[in] regAddress The address of slave register/memory location
 * @param[in] addressSize The dimension, in byte, of register address
 * @param[in] data Pointer to data buffer
 * @param[in] length the number of byte to write
 * @param[in] timeout Max timeout in millisecond
 * @return ERRORS_NO_ERROR in case of success, specific errors otherwise
 */
System_Errors Iic_writeRegister (Iic_DeviceHandle dev,
                                 uint16_t devAddress,
                                 uint16_t regAddress,
                                 Iic_RegisterAddressSize addressSize,
                                 const uint8_t* data,
                                 uint16_t length,
                                 uint32_t timeout);

/**
 * This function read a register or memory location from the selected
 * slave device into I2C bus.
 * This function is blocking.
 *
 * @param[in]  dev I2C device handle
 * @param[in]  devAddress Slave device address 7bit or 10bit
 * @param[in]  regAddress The address of slave register/memory location
 * @param[in]  addressSize The dimension, in byte, of register address
 * @param[out] data Pointer to data buffer
 * @param[in]  length the number of byte to read
 * @param[in]  timeout Max timeout in millisecond
 * @return ERRORS_NO_ERROR in case of success, specific errors otherwise
 */
System_Errors Iic_readRegister (Iic_DeviceHandle dev,
                                uint16_t devAddress,
                                uint16_t regAddress,
                                Iic_RegisterAddressSize addressSize,
                                uint8_t* data,
                                uint16_t length,
                                uint32_t timeout);

/**
 * This function send start condition.
 *
 * @param[in] dev I2C device handle
 */
void Iic_start (Iic_DeviceHandle dev);

/**
 * This function send repeated start condition.
 *
 * @param[in] dev I2C device handle
 */
void Iic_repeatedStart (Iic_DeviceHandle dev);

/**
 * This function send stop condition.
 *
 * @param[in] dev I2C device handle
 */
void Iic_stop (Iic_DeviceHandle dev);

void Iic_forceReset (Iic_DeviceHandle dev);

/**
 * @}
 */

#else

#if defined (LIBOHIBOARD_KL25Z4)    || \
    defined (LIBOHIBOARD_FRDMKL25Z) || \
	defined (LIBOHIBOARD_KL15Z4)    || \
	defined (LIBOHIBOARD_K10D7)     || \
	defined (LIBOHIBOARD_K10D10)    || \
    defined (LIBOHIBOARD_K12D5)

void Iic_start (Iic_DeviceHandle dev);
void Iic_repeatedStart (Iic_DeviceHandle dev);
void Iic_stop (Iic_DeviceHandle dev);
void Iic_sendNack (Iic_DeviceHandle dev);
void Iic_sendAck (Iic_DeviceHandle dev);
System_Errors Iic_getAck (Iic_DeviceHandle dev);
void Iic_setReceiveMode (Iic_DeviceHandle dev);
void Iic_writeByte (Iic_DeviceHandle dev, uint8_t data);
void Iic_readByte (Iic_DeviceHandle dev, uint8_t *data);
System_Errors Iic_waitTransfer (Iic_DeviceHandle dev);

void Iic_readRegister (Iic_DeviceHandle dev,
                       uint8_t writeAddress,
                       uint8_t readAddress,
                       uint8_t registerAddress,
                       uint8_t *data);

void Iic_writeRegister (Iic_DeviceHandle dev,
                        uint8_t writeAddress,
                        uint8_t registerAddress,
                        uint8_t data);

void Iic_readMultipleRegisters (Iic_DeviceHandle dev,
                       uint8_t writeAddress,
                       uint8_t readAddress,
                       uint8_t firstRegisterAddress,
                       uint8_t *data,
					   uint8_t length);

void Iic_writeMultipleRegisters (Iic_DeviceHandle dev,
                        uint8_t writeAddress,
                        uint8_t firstRegisterAddress,
                        uint8_t* data,
						uint8_t length);

#else

void Iic_start (Iic_DeviceHandle dev);
void Iic_stop (Iic_DeviceHandle dev);

System_Errors Iic_writeByte (Iic_DeviceHandle dev, uint8_t data);
System_Errors Iic_writeBytes (Iic_DeviceHandle dev, uint8_t address,
        const uint8_t *data, uint8_t length, Iic_StopMode stopRequest);
System_Errors Iic_readByte (Iic_DeviceHandle dev, uint8_t *data,
        Iic_LastByteMode lastByte);
System_Errors Iic_readBytes (Iic_DeviceHandle dev, uint8_t address,
        uint8_t *data, uint8_t length, Iic_StopMode stopRequest);

#endif

#endif // ELSE LIBOHIBOARD_VERSION >= 0x20000

#if defined (LIBOHIBOARD_KL03Z4)     || \
    defined (LIBOHIBOARD_FRDMKL03Z)

#elif defined (LIBOHIBOARD_K10D7)   || \
      defined (LIBOHIBOARD_K10D10)  || \
      defined (LIBOHIBOARD_K12D5)

extern Iic_DeviceHandle OB_IIC0;
extern Iic_DeviceHandle OB_IIC1;

#elif defined (LIBOHIBOARD_K60DZ10) || \
      defined (LIBOHIBOARD_OHIBOARD_R1)

extern Iic_DeviceHandle IIC0;
extern Iic_DeviceHandle IIC1;

#elif defined (LIBOHIBOARD_K64F12)     || \
      defined (LIBOHIBOARD_FRDMK64F)

extern Iic_DeviceHandle IIC0;
extern Iic_DeviceHandle IIC1;
extern Iic_DeviceHandle IIC2;

#endif

#ifdef __cplusplus
}
#endif

#endif // __I2C_H

/**
 * @}
 */

#endif // LIBOHIBOARD_IIC

/**
 * @}
 */


text:
require 'test_helper'

class RobotRulesTest < Test::Unit::TestCase
  SITE_URL = "http://www.example.com"
  def setup
    @robot_rule = RobotRules.new('Ruby Spider 1.0')
    @robot_rule.parse(File.join(SITE_URL,'robots.txt'), %(User-agent:  *\nDisallow:    images))
  end
  def test_should_allow_path_imagination
    assert_equal true, @robot_rule.allowed?(File.join(SITE_URL, 'imagination/me.jpg'))
  end
  def test_should_disallow_path_images
    assert_equal false, @robot_rule.allowed?(File.join(SITE_URL, 'images/me.jpg'))
  end
  def test_should_allow_path_images_for_other_site
    assert_equal true, @robot_rule.allowed?(File.join("http://google.com", 'images/me.jpg'))
  end
  def test_should_disallow_path_images_for_other_site
    assert_equal true, @robot_rule.allowed?(File.join("http://google.com", 'images/me.jpg'))
  end

  def test_should_abide_by_disallowed_user_agent
    @robot_rule = RobotRules.new('Microsoft')
    robots_txt = %(/robots.txt:\nUser-agent: Microsoft\nDisallow:  google\nUser-agent:  *\nDisallow:    images)
    @robot_rule.parse(File.join(SITE_URL,'robots.txt'), robots_txt)

    assert_equal false, @robot_rule.allowed?(File.join(SITE_URL, 'google/hellow_world.txt'))
  end

  def test_should_allow_user_agent_to_specified_path
    @robot_rule = RobotRules.new('Google')
    robots_txt = %(/robots.txt:\nUser-agent: Microsoft\nDisallow:  google\nUser-agent:  *\nDisallow:    images)
    @robot_rule.parse(File.join(SITE_URL,'robots.txt'), robots_txt)

    assert_equal true, @robot_rule.allowed?(File.join(SITE_URL, 'google/hellow_world.txt'))
  end
end


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

<!--
This file is subject to the terms and conditions defined in the
files 'LICENSE' and 'NOTICE', which are part of this source
code package.
-->

<web-app version="3.0">
    <display-name>Apache OFBiz - Order Manager</display-name>
    <description>Order Manager Module of the Apache OFBiz Project</description>

    <context-param>
        <description>The Name of the Entity Delegator to use, defined in entityengine.xml</description>
        <param-name>entityDelegatorName</param-name>
        <param-value>default</param-value>
    </context-param>
    <context-param>
        <description>A unique name used to identify/recognize the local dispatcher for the Service Engine</description>
        <param-name>localDispatcherName</param-name>
        <param-value>order</param-value>
    </context-param>
    <context-param>
        <description>The location of the main-decorator screen to use for this webapp; referred to as a context variable in screen def XML files.</description>
        <param-name>mainDecoratorLocation</param-name>
        <param-value>component://order/widget/ordermgr/CommonScreens.xml</param-value>
    </context-param>
    <context-param>
        <description>SCIPIO: Whether shipping estimate selection should be allowed in the interface even if no estimate could be determined ("Calculated Offline") (default: false)</description>
        <param-name>orderAllowMissingShipEstimates</param-name>
        <param-value>true</param-value>
    </context-param>

    <filter>
        <display-name>ContextFilter</display-name>
        <filter-name>ContextFilter</filter-name>
        <filter-class>org.ofbiz.webapp.control.ContextFilter</filter-class>
        <init-param>
            <param-name>disableContextSecurity</param-name>
            <param-value>N</param-value>
        </init-param>
        <init-param>
            <param-name>allowedPaths</param-name>
            <!-- Beware, if you use the Birt component, allowedPaths are not defined here anymore but in Birt web.xml-->
            <param-value>/error:/control:/products:/select:/index.html:/index.jsp:/default.html:/default.jsp:/js:/includes/maincss.css:/ws</param-value>
        </init-param>
        <init-param>
            <param-name>errorCode</param-name>
            <param-value>403</param-value>
        </init-param>
        <init-param>
            <param-name>redirectPath</param-name>
            <param-value>/control/main</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>ContextFilter</filter-name>
            <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener><listener-class>org.ofbiz.webapp.control.ControlEventListener</listener-class></listener>
    <listener><listener-class>org.ofbiz.webapp.control.LoginEventListener</listener-class></listener>
    <!-- NOTE: not all app servers support mounting implementations of the HttpSessionActivationListener interface -->
    <!-- <listener><listener-class>org.ofbiz.webapp.control.ControlActivationEventListener</listener-class></listener> -->

    <servlet>
        <description>Main Control Servlet</description>
        <display-name>ControlServlet</display-name>
        <servlet-name>ControlServlet</servlet-name>
        <servlet-class>org.ofbiz.webapp.control.ControlServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
        <description>Catalog (Category/Product) URL Servlet</description>
        <display-name>CatalogUrlServlet</display-name>
        <servlet-name>CatalogUrlServlet</servlet-name>
        <servlet-class>org.ofbiz.product.category.CatalogUrlServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>ControlServlet</servlet-name>
        <url-pattern>/control/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>CatalogUrlServlet</servlet-name>
        <url-pattern>/products/*</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>60</session-timeout> <!-- in minutes -->
        <cookie-config>
            <http-only>true</http-only>
            <secure>true</secure>
        </cookie-config>
        <tracking-mode>COOKIE</tracking-mode>
    </session-config>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
    </welcome-file-list>
</web-app>


text:
namespace chrome {

// Canonical schemes you can use as input to GURL.SchemeIs().
// TODO(jam): some of these don't below in the content layer, but are accessed
// from there.
CONTENT_EXPORT extern const char kAboutScheme[];
CONTENT_EXPORT extern const char kBlobScheme[];
CONTENT_EXPORT extern const char kChromeDevToolsScheme[];
CONTENT_EXPORT extern const char kChromeInternalScheme[];
CONTENT_EXPORT extern const char kChromeUIScheme[];  // Used for WebUIs.
CONTENT_EXPORT extern const char kCrosScheme[];      // Used for ChromeOS.
CONTENT_EXPORT extern const char kDataScheme[];
CONTENT_EXPORT extern const char kFileScheme[];
CONTENT_EXPORT extern const char kFileSystemScheme[];
CONTENT_EXPORT extern const char kFtpScheme[];
CONTENT_EXPORT extern const char kHttpScheme[];
CONTENT_EXPORT extern const char kHttpsScheme[];
CONTENT_EXPORT extern const char kJavaScriptScheme[];
CONTENT_EXPORT extern const char kMailToScheme[];
CONTENT_EXPORT extern const char kMetadataScheme[];
CONTENT_EXPORT extern const char kSwappedOutScheme[];
CONTENT_EXPORT extern const char kViewSourceScheme[];

// Hosts for about URLs.
CONTENT_EXPORT extern const char kAboutBlankURL[];
CONTENT_EXPORT extern const char kChromeUIAppCacheInternalsHost[];
CONTENT_EXPORT extern const char kChromeUIBlobInternalsHost[];
CONTENT_EXPORT extern const char kChromeUIBrowserCrashHost[];
CONTENT_EXPORT extern const char kChromeUINetworkViewCacheHost[];
CONTENT_EXPORT extern const char kChromeUITcmallocHost[];

// Full about URLs (including schemes).
CONTENT_EXPORT extern const char kChromeUICrashURL[];
CONTENT_EXPORT extern const char kChromeUIGpuCleanURL[];
CONTENT_EXPORT extern const char kChromeUIGpuCrashURL[];
CONTENT_EXPORT extern const char kChromeUIGpuHangURL[];
CONTENT_EXPORT extern const char kChromeUIHangURL[];
CONTENT_EXPORT extern const char kChromeUIKillURL[];
CONTENT_EXPORT extern const char kChromeUINetworkViewCacheURL[];
CONTENT_EXPORT extern const char kChromeUIShorthangURL[];

}  // namespace chrome

namespace content {

// Used to separate a standard scheme and the hostname: "://".
CONTENT_EXPORT extern const char kStandardSchemeSeparator[];

// Special URL used to start a navigation to an error page.
extern const char kUnreachableWebDataURL[];

// Special URL used to swap out a view being rendered by another process.
extern const char kSwappedOutURL[];

// Null terminated list of schemes that are savable. This function can be
// invoked on any thread.
CONTENT_EXPORT const char** GetSavableSchemes();

// Note: ContentMainRunner calls this method internally as part of main
// initialziation, so this function generally should not be called by
// embedders. It's exported to facilitate test harnesses that do not
// utilize ContentMainRunner and that do not wish to lock the set
// of standard schemes at init time.
//
// Called near the beginning of startup to register URL schemes that should
// be parsed as "standard" with the googleurl library. Optionally, the set
// of standard schemes is locked down. The embedder can add additional
// schemes by overriding the ContentClient::AddAdditionalSchemes method.
CONTENT_EXPORT void RegisterContentSchemes(bool lock_standard_schemes);

}  // namespace content

#endif  // CONTENT_PUBLIC_COMMON_URL_CONSTANTS_H_


text:
<?php

namespace CupOfTea\WordPress\Foundation\Bootstrap;

use Illuminate\Config\Repository;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Config\Repository as RepositoryContract;

class ReadConfiguration
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Container $app)
    {
        $items = [];

        $app->instance('config', $config = new Repository($items));

        // Next we will spin through all of the configuration files in the configuration
        // directory and load each one into the repository. This will make all of the
        // options available to the developer for use in various parts of this app.
        $this->loadConfigurationFiles($app, $config);

        mb_internal_encoding('UTF-8');
    }

    /**
     * Load the configuration items from all of the files.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @param  \Illuminate\Contracts\Config\Repository  $config
     * @return void
     */
    protected function loadConfigurationFiles(Container $app, RepositoryContract $config)
    {
        foreach ($this->getConfigurationFiles($app) as $key => $path) {
            $config->set($key, require $path);
        }

        foreach ($this->getThemeConfigurationFiles($app) as $key => $path) {
            if ($config->has($key)) {
                $values = require $path;

                $config->set($key, array_merge($config->get($key), $values));
            } else {
                $config->set($key, require $path);
            }
        }
    }

    /**
     * Get all of the configuration files for the application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return array
     */
    protected function getConfigurationFiles(Container $app)
    {
        $files = [];

        foreach (Finder::create()->files()->name('*.php')->in($app->configPath()) as $file) {
            $nesting = $this->getConfigurationNesting($file);

            $files[$nesting . basename($file->getRealPath(), '.php')] = $file->getRealPath();
        }

        return $files;
    }

    /**
     * Get all of the configuration files for the theme.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return array
     */
    protected function getThemeConfigurationFiles(Container $app)
    {
        $files = [];
        $config_path = $app->make('config')->get('theme.config_path', realpath($app->make('wp.theme')->getRoot()) . '/config');

        if (file_exists($config_path) && is_dir($config_path)) {
            foreach (Finder::create()->files()->name('*.php')->in($config_path) as $file) {
                $nesting = $this->getThemeConfigurationNesting($file, $config_path);

                $files[$nesting . basename($file->getRealPath(), '.php')] = $file->getRealPath();
            }
        }

        return $files;
    }

    /**
     * Get the configuration file nesting path.
     *
     * @param  \Symfony\Component\Finder\SplFileInfo  $file
     * @return string
     */
    private function getConfigurationNesting(SplFileInfo $file)
    {
        $directory = dirname($file->getRealPath());

        if ($tree = trim(str_replace(config_path(), '', $directory), DIRECTORY_SEPARATOR)) {
            $tree = str_replace(DIRECTORY_SEPARATOR, '.', $tree) . '.';
        }

        return $tree;
    }

    /**
     * Get the theme configuration file nesting path.
     *
     * @param  \Symfony\Component\Finder\SplFileInfo  $file
     * @return string
     */
    private function getThemeConfigurationNesting(SplFileInfo $file, $config_path)
    {
        $directory = dirname($file->getRealPath());

        if ($tree = trim(str_replace($config_path, '', $directory), DIRECTORY_SEPARATOR)) {
            $tree = str_replace(DIRECTORY_SEPARATOR, '.', $tree) . '.';
        }

        return $tree;
    }
}


text:
using FluentAssertions;
using Xunit;

namespace Okanshi.Test
{
    public class AtomicDoubleTest
    {
        [Fact]
        public void Default_value_is_zero()
        {
            var atomicDouble = new AtomicDouble();

            var value = atomicDouble.Get();

            value.Should().Be(0);
        }

        [Theory]
        [InlineData(1.0)]
        [InlineData(10.2)]
        [InlineData(17.22)]
        [InlineData(1001.01)]
        [InlineData(-5.1)]
        public void Default_value_is_correctly_assigned_when_specified_in_constructor(double expectedValue)
        {
            var atomicDouble = new AtomicDouble(expectedValue);

            var value = atomicDouble.Get();

            value.Should().Be(expectedValue);
        }

        [Theory]
        [InlineData(1.0)]
        [InlineData(10.2)]
        [InlineData(17.22)]
        [InlineData(1001.01)]
        [InlineData(-5.1)]
        public void Get_and_set_returns_the_original_value(double originalValue)
        {
            var atomicDouble = new AtomicDouble(originalValue);

            var value = atomicDouble.GetAndSet(1000);

            value.Should().Be(originalValue);
        }

        [Theory]
        [InlineData(1.0)]
        [InlineData(10.2)]
        [InlineData(17.22)]
        [InlineData(1001.01)]
        [InlineData(-5.1)]
        public void Get_and_set_updates_the_value_as_specified(double newValue)
        {
            var atomicDouble = new AtomicDouble();

            atomicDouble.GetAndSet(newValue);

            var value = atomicDouble.Get();
            value.Should().Be(newValue);
        }

        [Theory]
        [InlineData(1.0)]
        [InlineData(10.2)]
        [InlineData(17.22)]
        [InlineData(1001.01)]
        [InlineData(-5.1)]
        public void Compare_and_set_updates_the_value_when_original_value_is_correct(double newValue)
        {
            var atomicDouble = new AtomicDouble();

            atomicDouble.CompareAndSet(newValue, 0);

            var value = atomicDouble.Get();
            value.Should().Be(newValue);
        }

        [Theory]
        [InlineData(1.0)]
        [InlineData(10.2)]
        [InlineData(17.22)]
        [InlineData(1001.01)]
        [InlineData(-5.1)]
        public void Compare_and_set_does_not_update_the_value_when_original_value_is_incorrect(double newValue)
        {
            var atomicDouble = new AtomicDouble();

            atomicDouble.CompareAndSet(newValue, 100);

            var value = atomicDouble.Get();
            value.Should().Be(0);
        }

        [Theory]
        [InlineData(1.0)]
        [InlineData(10.2)]
        [InlineData(17.22)]
        [InlineData(1001.01)]
        [InlineData(-5.1)]
        public void Setting_the_value_updates_the_value_as_expected(double newValue)
        {
            var atomicDouble = new AtomicDouble();

            atomicDouble.Set(newValue);

            var value = atomicDouble.Get();
            value.Should().Be(newValue);
        }

        [Theory]
        [InlineData(1.0, 2.0)]
        [InlineData(10.2, 11.2)]
        [InlineData(17.22, 18.22)]
        [InlineData(1001.01, 1002.01)]
        [InlineData(-5.1, -4.1)]
        public void Incrementing_the_value_increments_the_value(double originvalValue, double expectedValue)
        {
            var atomicDouble = new AtomicDouble(originvalValue);

            atomicDouble.Increment();

            var value = atomicDouble.Get();
            value.Should().Be(expectedValue);
        }

        [Theory]
        [InlineData(1.0, 2.0, 3.0)]
        [InlineData(10.2, 11.2, 21.4)]
        [InlineData(17.22, 18.22, 35.44)]
        [InlineData(1001.01, 1002.01, 2003.02)]
        [InlineData(-5.1, -1.1, -6.2)]
        public void Incrementing_the_value_by_the_specified_amount_increments_the_value_correctly(double originvalValue, double amount, double expectedValue)
        {
            var atomicDouble = new AtomicDouble(originvalValue);

            atomicDouble.Increment(amount);

            var value = atomicDouble.Get();
            value.Should().BeApproximately(expectedValue, 0.1);
        }
    }
}