text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sydowia 2(1-6): 49 (1948)

#### Original name
Thrinacospora insignis Petr., 1948

### Remarks
null


text:
PYTHON ?= python3
PYTHON_FLAGS += -OO

ASSIGNMENT = 05
GROUP = gr1
PACKFILE = uebung$(ASSIGNMENT)-$(GROUP).tar.xz

rwildcard=$(foreach d,$(wildcard $1*),$(call rwildcard,$d/,$2) $(filter $(subst *,%,$2),$d))
MODULES = $(call rwildcard, src, *.py)

.PHONY: optimized unittests clean pack

optimized: $(MODULES)
	$(PYTHON) $(PYTHON_FLAGS) -m compileall $^

unittests:
	export PYTHONPATH=src; \
	find tests -name test\*.py | while read -r test; do \
		$(PYTHON) "$$test" || exit $$?; \
	done

clean:
	rm -rf $(addsuffix c, $(MODULES)) $(addsuffix o, $(MODULES)) $(call rwildcard, tests, *.pyc *.pyo)

$(PACKFILE): $(MODULES) $(call rwildcard, tests, test*.py) Makefile README | tests
	tar -caf $@ -- $^

pack: $(PACKFILE)

redpajama_set_name: RedPajamaGithub


text:
{{< layout}}

{{$propositionHeader}}{{/propositionHeader}}

{{$pageTitle}}Information about urgent passport{{/pageTitle}}

{{$header}}
{{/header}}

{{$main-content}}

Apply with online Premium

This is a new service – it's only available for some kinds of applications.

You'll need to:

1
Choose an appointment time to collect your new passport

2
Take a digital passport photo - we'll show you how

3
Apply online and pay with a debit or credit card

4
Collect your new passport

The earliest appointment is in 2 days. If you need your passport sooner,

	check the paper Premium (1 day) service.

<input class="button" type="submit" value="Check if you can use this service">

{{/main-content}}

{{/ layout}}


text:
package org.terasology.math.geom;

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

public abstract class VectorPoolBaseTest<T extends VectorPool<Y>,Y> {
    public abstract T getVectorPool();

    @Test
    public void reuseVectorTest() {
        T pool = getVectorPool();
        Y v1 = pool.getVector();
        pool.free(v1);
        Y v2 = pool.getVector();
        assertSame(v1, v2);

    }
}


text:
function Add-VSApiGatewayMethodMethodResponse {
    <#
    .SYNOPSIS
        Adds an AWS::ApiGateway::Method.MethodResponse resource property to the template. MethodResponse is a property of the AWS::ApiGateway::Method: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html resource that defines the responses that can be sent to the client that calls a method.

    .DESCRIPTION
        Adds an AWS::ApiGateway::Method.MethodResponse resource property to the template.
MethodResponse is a property of the AWS::ApiGateway::Method: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html resource that defines the responses that can be sent to the client that calls a method.

    .LINK
        http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-methodresponse.html

    .PARAMETER ResponseModels
        The resources used for the response's content type. Specify response models as key-value pairs string-to-string maps, with a content type as the key and a Model: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-model.html resource name as the value.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-methodresponse.html#cfn-apigateway-method-methodresponse-responsemodels
        DuplicatesAllowed: False
        PrimitiveItemType: String
        Type: Map
        UpdateType: Mutable

    .PARAMETER ResponseParameters
        Response parameters that API Gateway sends to the client that called a method. Specify response parameters as key-value pairs string-to-Boolean maps, with a destination as the key and a Boolean as the value. Specify the destination using the following pattern: method.response.header.name, where *name* is a valid, unique header name. The Boolean specifies whether a parameter is required.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-methodresponse.html#cfn-apigateway-method-methodresponse-responseparameters
        DuplicatesAllowed: False
        PrimitiveItemType: Boolean
        Type: Map
        UpdateType: Mutable

    .PARAMETER StatusCode
        The method response's status code, which you map to an IntegrationResponse: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration-integrationresponse.html.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-methodresponse.html#cfn-apigateway-method-methodresponse-statuscode
        PrimitiveType: String
        UpdateType: Mutable

    .FUNCTIONALITY
        Vaporshell
    #>
    [OutputType('Vaporshell.Resource.ApiGateway.Method.MethodResponse')]
    [cmdletbinding()]
    Param
    (
        [parameter(Mandatory = $false)]
        [System.Collections.Hashtable]
        $ResponseModels,
        [parameter(Mandatory = $false)]
        [System.Collections.Hashtable]
        $ResponseParameters,
        [parameter(Mandatory = $true)]
        [ValidateScript( {
                $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $StatusCode
    )
    Begin {
        $obj = [PSCustomObject]@{}
        $commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable')
    }
    Process {
        foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) {
            switch ($key) {
                Default {
                    $obj | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters.$key
                }
            }
        }
    }
    End {
        $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.ApiGateway.Method.MethodResponse'
        Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
    }
}


text:
/* CUAHSI Faceted Discovery HTTP API endpoints */
var vis = appDomain + '/Vis/Index';
var FacetsAPI = appDomain + '/api/facets/';
var OntologyAPI = appDomain + '/api/ontologyitems/';
var SearchAPI = appDomain + '/api/seriesmetadata/';
var DataAPI = appDomain + '/api/seriesdata/';
var SitesAPI = appDomain + '/api/sites/';

var appName = 'prototype-cuahsidata'; // controls objectStore used for this application
var appVersion = 6; // controls active database schema

/* non inter-session persisting object store names */
var ontologyitems = 'ontologyitems'; // stores ontologyitems ingested by user by id => enables immediate back-button regeneration
var series = 'series';   // stores seriesmetadata and includes client-side info like date/time last values acquisition attempt from server was made, and acquisition state (failed - with reasons, success)
var sites = 'sites';     // stores sites accessed by users
var history = 'history'; // stores user progression within this session, enabling back button
var myselections = 'myselections'; // DEPRECATED v6 => not fast enough for quick UI operations. stores user's current vocabulary selections within the ui

/* inter-session persisting object store names */
var values = 'values';   // stores downloaded series. Not cleaned out after every page reload, and it is the exclusive data source for the data vis pane, enabling offline functionality.
var datasets = 'datasets'; // stores user's collections of seriesdata. Not cleaned out after every page reload, enabling offline functionality.
var mysettings = 'mysettings'; // stores user's UI preferences. Not cleaned out after every page reload, so users can save their settings between sessions.

function debugConsole(message) {
    if (typeof console != "undefined") {
        console.log(message);
    }
}

// courtesy: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date#Example:_ISO_8601_formatted_dates
function ISODateString(d) {
    function pad(n) { return n < 10 ? '0' + n : n }
    return d.getUTCFullYear() + '-'
      + pad(d.getUTCMonth() + 1) + '-'
      + pad(d.getUTCDate())
}

/* helper utility function used for distinct() operations on javascript collections (e.g. distinct facets of ontologyitems/ response) */
Array.prototype.getUnique = function () {
    var u = {}, a = [];
    for (var i = 0, l = this.length; i < l; ++i) {
        if (u.hasOwnProperty(this[i])) {
            continue;
        }
        a.push(this[i]);
        u[this[i]] = 1;
    }
    return a;
}

/* helper function used for removing items of any key from an array */
Array.prototype.remove = function () {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

/* central location for data management tasks in the CUAHSIData app */
function InitDb() {
    /* indexeddb jquery use based on https://github.com/axemclion/jquery-indexeddb/blob/master/example/index.html */
    var key = null;
    /* remember: export my journey: add datetime persistence value to each object, with index, cluster on ranges, produce step-by-step interaction replay */
    var request = $.indexedDB(appName, {
        'version': appVersion,
        'schema': {
            '1': function (trans) {

                var seriesStore = trans.createObjectStore(series, {
                    'keypath': 'SeriesID',
                    'autoIncrement': false
                });

                var sitesStore = trans.createObjectStore(sites, {
                    'keypath': 'SiteID',
                    'autoIncrement': false
                });
                // sitesStore.createIndex('SiteName'); /* use in autocomplete? */

                var valuesStore = trans.createObjectStore(values, {
                    'keypath': 'myMetadata.SeriesID',
                    'autoIncrement': false
                });
            },
            '2': function (trans) {
                var stateStore = trans.createObjectStore(history, {
                    'keypath': 'Id',
                    'autoIncrement': true
                });

                var ontologyStore = trans.createObjectStore(ontologyitems, {
                    'keypath': 'Id',
                    'autoIncrement': false
                });

                trans.deleteObjectStore(series);
                var seriesStore = trans.createObjectStore(series, {
                    'keypath': 'SeriesID',
                    'autoIncrement': false
                });
                seriesStore.createIndex('LastDataRequest'); // tracks last time data values for this series were requested

                var datasetStore = trans.createObjectStore(datasets, {
                    'keypath': 'Id',
                    'autoIncrement': true
                });
                datasetStore.createIndex('CreationTime');
                datasetStore.createIndex('myTags',
                    {
                        'unique': true,
                        'multientry': true // all tags for all objects listed in get() of this index, for single-loop search
                    });

                // ontologyStore.createIndex('FacetID');
            },
            '3': function (trans) {
                var settingsStore = trans.createObjectStore(mysettings, {
                    'keypath': 'Id',
                    'autoIncrement': true
                });
                settingsStore.add({
                    'showTooltips': true,
                    'showIntroMovie': true
                });

                var selectionsStore = trans.createObjectStore(myselections, {
                    'keypath': 'Id',
                    'autoIncrement': false
                });
            },
            '4': function (trans) {
                var ontologyStore = trans.objectStore(ontologyitems);
                ontologyStore.createIndex('FacetID');
            },
            '5': function (trans) {
                var theNow = Date.now();
                var valueStore = trans.objectStore(values);
                var iter = valueStore.each(function (item) {
                    var newItem = item;
                    newItem.value.AccessTime = theNow; /* all data accessed before this update considered accessed at moment of update */
                    item.update(newItem);
                });

                iter.done(function (result, event) {
                    valueStore.createIndex('AccessTime');
                });

                iter.fail(function (error, event) {
                    debugConsole('failed on insert of datetimes into valuestore objects during upgrade to schema 5. AccessTime index never created.');
                    debugConsole(error);
                    debugConsole(event);
                });

            },
            '6': function (trans) {
                trans.deleteObjectStore(myselections);
            }
        }
    });
    return request;
}


text:
def getReading(obxDict):
    """Get reading part from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        dict: Dictionary contaning a reading
    """
    return obxDict.get('reading')

def getReadingCode(obxDict):
    """Get reading code from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        str: Reading code of the observation.  Value of the code depends on the reading system used.
    """
    reading = getReading(obxDict)
    readingType = reading.get('readingType')
    readingCode = readingType.get('code')
    return str(readingCode)

def getReadingCodeSystem(obxDict):
    """Get reading code system from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        str: Code system used to describe the reading type.  The platform's system code is streamsx.heath/1.0
    """
    reading = getReading(obxDict)
    readingType = reading.get('readingType')
    codeSystem = readingType.get('system')
    return str(codeSystem)

def getReadingValue(obxDict):
    """Get reading value from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        float: Value of the reading
    """
    reading = getReading(obxDict)
    return float(reading.get('value'))

def getReadingValueString(obxDict):
    """Get reading value from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        float: Value of the reading
    """
    reading = getReading(obxDict)
    return str(reading.get('valueString'))

def getUom(obxDict):
    """Get the unit of measure from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        str: The unit of measure fo the observation
    """
    reading = getReading(obxDict)
    return str(reading.get('uom'))

def getReadingTs(obxDict):
    """Get the timestamp from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        int: Timestamp of when the observation is taken
    """
    reading = getReading(obxDict)
    return int(reading.get('ts'))

# Get Reading Source Information

def getReadingSource(obxDict):
    """Get reading source part from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        dict: Dictionary containing information about reading source of the observation
    """
    return obxDict.get('readingSource')

def getReadingSourceId(obxDict):
    """Get reading source id from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        str: Reading source ID - If the device contains multiple channels, reading source Id will represent the channel of which the observation is taken.
    """
    readingSrc = getReadingSource(obxDict)
    return str(readingSrc.get('id'))

def getReadingSourceType(obxDict):
    """Get reading source type from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        str: Type of reading source
    """
    readingSrc = getReadingSource(obxDict)
    return str(readingSrc.get('sourceType'))

# Get Device Information
def getDevice(obxDict):
    """Get device part from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        dict: Device information from the observation
    """
    return obxDict.get('device')

def getDeviceId(obxDict):
    """Get device id from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        str: Device ID from the observation
    """
    return getDevice(obxDict).get('id')

def getLocationId(obxDict):
    """Get locationId of the device from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        str: Location Id of the device
    """
    return str(getDevice(obxDict).get('locationId'))

# Get Patient Id

def getPatientId(obxDict):
    """Get patientId from the observation
    Args:
        obxDict(dict): Observation in dictionary
    Returns:
        str: Patient Id
    """
    return str(obxDict.get('patientId'))


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model common\models\CustomerCreditDetail */

$this->title = Yii::t('app', 'Update {modelClass}: ', [
    'modelClass' => 'Customer Credit Detail',
]) . ' ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Customer Credit Details'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="customer-credit-detail-update">

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>

</div>


text:
package models

type SwapSpaceMonitorMemoryUsage2 struct {

	Class string `json:"_class,omitempty"`

	AvailablePhysicalMemory int32 `json:"availablePhysicalMemory,omitempty"`

	AvailableSwapSpace int32 `json:"availableSwapSpace,omitempty"`

	TotalPhysicalMemory int32 `json:"totalPhysicalMemory,omitempty"`

	TotalSwapSpace int32 `json:"totalSwapSpace,omitempty"`
}


text:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session

  respond_to :json

  def health_check
    render text:  'ok', status: :ok
  end

  def layout
    render text: nil, layout: true
  end

  def pagination(page, limit, total)
    { pagination:
        {
          page: page.to_i,
          limit: limit,
          total: total
        }
    }
  end

  protected

  def render_error_message(model)
    full_messages = model.errors.full_messages.join("\n")
    logger.error full_messages
    render json: { errorMessage: full_messages }, status: :bad_request
  end
end


text:
from django.conf.urls import patterns, url
from clothstream.lib.rest import SharedAPIRootRouter
from .views import register_by_access_token, get_csrf_cookie, user_logout

urlpatterns = patterns(
    '',
    url(r'^register/(?P<backend>[^/]+)/', register_by_access_token, name='api.login'),
    url(r'^logout', user_logout, name='api.logout'),
    url(r'^csrf/', get_csrf_cookie, name='api.csrf_cookie'),
)

router = SharedAPIRootRouter()


text:
#include "config.h"
#include "core/layout/compositing/CompositingLayerAssigner.h"

#include "core/inspector/InspectorTraceEvents.h"
#include "core/layout/LayoutView.h"
#include "core/layout/compositing/CompositedDeprecatedPaintLayerMapping.h"
#include "core/page/Page.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
#include "platform/TraceEvent.h"

namespace blink {

// We will only allow squashing if the bbox-area:squashed-area doesn't exceed
// the ratio |gSquashingSparsityTolerance|:1.
static uint64_t gSquashingSparsityTolerance = 6;

CompositingLayerAssigner::CompositingLayerAssigner(DeprecatedPaintLayerCompositor* compositor)
    : m_compositor(compositor)
    , m_layersChanged(false)
{
}

CompositingLayerAssigner::~CompositingLayerAssigner()
{
}

void CompositingLayerAssigner::assign(DeprecatedPaintLayer* updateRoot, Vector<DeprecatedPaintLayer*>& layersNeedingPaintInvalidation)
{
    TRACE_EVENT0("blink", "CompositingLayerAssigner::assign");

    SquashingState squashingState;
    assignLayersToBackingsInternal(updateRoot, squashingState, layersNeedingPaintInvalidation);
    if (squashingState.hasMostRecentMapping)
        squashingState.mostRecentMapping->finishAccumulatingSquashingLayers(squashingState.nextSquashedLayerIndex);
}

void CompositingLayerAssigner::SquashingState::updateSquashingStateForNewMapping(CompositedDeprecatedPaintLayerMapping* newCompositedDeprecatedPaintLayerMapping, bool hasNewCompositedDeprecatedPaintLayerMapping)
{
    // The most recent backing is done accumulating any more squashing layers.
    if (hasMostRecentMapping)
        mostRecentMapping->finishAccumulatingSquashingLayers(nextSquashedLayerIndex);

    nextSquashedLayerIndex = 0;
    boundingRect = IntRect();
    mostRecentMapping = newCompositedDeprecatedPaintLayerMapping;
    hasMostRecentMapping = hasNewCompositedDeprecatedPaintLayerMapping;
    haveAssignedBackingsToEntireSquashingLayerSubtree = false;
}

bool CompositingLayerAssigner::squashingWouldExceedSparsityTolerance(const DeprecatedPaintLayer* candidate, const CompositingLayerAssigner::SquashingState& squashingState)
{
    IntRect bounds = candidate->clippedAbsoluteBoundingBox();
    IntRect newBoundingRect = squashingState.boundingRect;
    newBoundingRect.unite(bounds);
    const uint64_t newBoundingRectArea = newBoundingRect.size().area();
    const uint64_t newSquashedArea = squashingState.totalAreaOfSquashedRects + bounds.size().area();
    return newBoundingRectArea > gSquashingSparsityTolerance * newSquashedArea;
}

bool CompositingLayerAssigner::needsOwnBacking(const DeprecatedPaintLayer* layer) const
{
    if (!m_compositor->canBeComposited(layer))
        return false;

    return requiresCompositing(layer->compositingReasons()) || (m_compositor->staleInCompositingMode() && layer->isRootLayer());
}

CompositingStateTransitionType CompositingLayerAssigner::computeCompositedLayerUpdate(DeprecatedPaintLayer* layer)
{
    CompositingStateTransitionType update = NoCompositingStateChange;
    if (needsOwnBacking(layer)) {
        if (!layer->hasCompositedDeprecatedPaintLayerMapping()) {
            update = AllocateOwnCompositedDeprecatedPaintLayerMapping;
        }
    } else {
        if (layer->hasCompositedDeprecatedPaintLayerMapping())
            update = RemoveOwnCompositedDeprecatedPaintLayerMapping;

        if (!layer->subtreeIsInvisible() && m_compositor->canBeComposited(layer) && requiresSquashing(layer->compositingReasons())) {
            // We can't compute at this time whether the squashing layer update is a no-op,
            // since that requires walking the paint layer tree.
            update = PutInSquashingLayer;
        } else if (layer->groupedMapping() || layer->lostGroupedMapping()) {
            update = RemoveFromSquashingLayer;
        }
    }
    return update;
}

CompositingReasons CompositingLayerAssigner::getReasonsPreventingSquashing(const DeprecatedPaintLayer* layer, const CompositingLayerAssigner::SquashingState& squashingState)
{
    if (!squashingState.haveAssignedBackingsToEntireSquashingLayerSubtree)
        return CompositingReasonSquashingWouldBreakPaintOrder;

    ASSERT(squashingState.hasMostRecentMapping);
    const DeprecatedPaintLayer& squashingLayer = squashingState.mostRecentMapping->owningLayer();

    // FIXME: this special case for video exists only to deal with corner cases
    // where a LayoutVideo does not report that it needs to be directly composited.
    // Video does not currently support sharing a backing, but this could be
    // generalized in the future. The following layout tests fail if we permit the
    // video to share a backing with other layers.
    //
    // compositing/video/video-controls-layer-creation.html
    if (layer->layoutObject()->isVideo() || squashingLayer.layoutObject()->isVideo())
        return CompositingReasonSquashingVideoIsDisallowed;

    // Don't squash iframes, frames or plugins.
    // FIXME: this is only necessary because there is frame code that assumes that composited frames are not squashed.
    if (layer->layoutObject()->isLayoutPart() || squashingLayer.layoutObject()->isLayoutPart())
        return CompositingReasonSquashingLayoutPartIsDisallowed;

    if (layer->reflectionInfo())
        return CompositingReasonSquashingReflectionIsDisallowed;

    if (squashingWouldExceedSparsityTolerance(layer, squashingState))
        return CompositingReasonSquashingSparsityExceeded;

    if (layer->layoutObject()->style()->hasBlendMode())
        return CompositingReasonSquashingBlendingIsDisallowed;

    // FIXME: this is not efficient, since it walks up the tree. We should store these values on the CompositingInputsCache.
    if (layer->clippingContainer() != squashingLayer.clippingContainer() && !squashingLayer.compositedDeprecatedPaintLayerMapping()->containingSquashedLayer(layer->clippingContainer(), squashingState.nextSquashedLayerIndex))
        return CompositingReasonSquashingClippingContainerMismatch;

    // Composited descendants need to be clipped by a child containment graphics layer, which would not be available if the layer is
    // squashed (and therefore has no CLM nor a child containment graphics layer).
    if (m_compositor->clipsCompositingDescendants(layer))
        return CompositingReasonSquashedLayerClipsCompositingDescendants;

    if (layer->scrollsWithRespectTo(&squashingLayer))
        return CompositingReasonScrollsWithRespectToSquashingLayer;

    if (layer->scrollParent() && layer->hasCompositingDescendant())
        return CompositingReasonScrollChildWithCompositedDescendants;

    const DeprecatedPaintLayer::AncestorDependentCompositingInputs& compositingInputs = layer->ancestorDependentCompositingInputs();
    const DeprecatedPaintLayer::AncestorDependentCompositingInputs& squashingLayerCompositingInputs = squashingLayer.ancestorDependentCompositingInputs();

    if (compositingInputs.opacityAncestor != squashingLayerCompositingInputs.opacityAncestor)
        return CompositingReasonSquashingOpacityAncestorMismatch;

    if (compositingInputs.transformAncestor != squashingLayerCompositingInputs.transformAncestor)
        return CompositingReasonSquashingTransformAncestorMismatch;

    if (layer->hasFilter() || compositingInputs.filterAncestor != squashingLayerCompositingInputs.filterAncestor)
        return CompositingReasonSquashingFilterMismatch;

    if (layer->layoutObject()->style()->position() == FixedPosition)
        return CompositingReasonSquashingPositionFixedIsDisallowed;

    return CompositingReasonNone;
}

void CompositingLayerAssigner::updateSquashingAssignment(DeprecatedPaintLayer* layer, SquashingState& squashingState, const CompositingStateTransitionType compositedLayerUpdate,
    Vector<DeprecatedPaintLayer*>& layersNeedingPaintInvalidation)
{
    // NOTE: In the future as we generalize this, the background of this layer may need to be assigned to a different backing than
    // the squashed DeprecatedPaintLayer's own primary contents. This would happen when we have a composited negative z-index element that needs
    // to paint on top of the background, but below the layer's main contents. For now, because we always composite layers
    // when they have a composited negative z-index child, such layers will never need squashing so it is not yet an issue.
    if (compositedLayerUpdate == PutInSquashingLayer) {
        // A layer that is squashed with other layers cannot have its own CompositedDeprecatedPaintLayerMapping.
        ASSERT(!layer->hasCompositedDeprecatedPaintLayerMapping());
        ASSERT(squashingState.hasMostRecentMapping);

        bool changedSquashingLayer =
            squashingState.mostRecentMapping->updateSquashingLayerAssignment(layer, squashingState.nextSquashedLayerIndex);
        if (!changedSquashingLayer)
            return;

        // If we've modified the collection of squashed layers, we must update
        // the graphics layer geometry.
        squashingState.mostRecentMapping->setNeedsGraphicsLayerUpdate(GraphicsLayerUpdateSubtree);

        layer->clipper().clearClipRectsIncludingDescendants();

        // Issue a paint invalidation, since |layer| may have been added to an already-existing squashing layer.
        TRACE_LAYER_INVALIDATION(layer, InspectorLayerInvalidationTrackingEvent::AddedToSquashingLayer);
        layersNeedingPaintInvalidation.append(layer);
        m_layersChanged = true;
    } else if (compositedLayerUpdate == RemoveFromSquashingLayer) {
        if (layer->groupedMapping()) {
            // Before removing |layer| from an already-existing squashing layer that may have other content, issue a paint invalidation.
            m_compositor->paintInvalidationOnCompositingChange(layer);
            layer->groupedMapping()->setNeedsGraphicsLayerUpdate(GraphicsLayerUpdateSubtree);
            layer->setGroupedMapping(nullptr, DeprecatedPaintLayer::InvalidateLayerAndRemoveFromMapping);
        }

        // If we need to issue paint invalidations, do so now that we've removed it from a squashed layer.
        TRACE_LAYER_INVALIDATION(layer, InspectorLayerInvalidationTrackingEvent::RemovedFromSquashingLayer);
        layersNeedingPaintInvalidation.append(layer);
        m_layersChanged = true;

        layer->setLostGroupedMapping(false);
    }
}

void CompositingLayerAssigner::assignLayersToBackingsForReflectionLayer(DeprecatedPaintLayer* reflectionLayer, Vector<DeprecatedPaintLayer*>& layersNeedingPaintInvalidation)
{
    CompositingStateTransitionType compositedLayerUpdate = computeCompositedLayerUpdate(reflectionLayer);
    if (compositedLayerUpdate != NoCompositingStateChange) {
        TRACE_LAYER_INVALIDATION(reflectionLayer, InspectorLayerInvalidationTrackingEvent::ReflectionLayerChanged);
        layersNeedingPaintInvalidation.append(reflectionLayer);
        m_layersChanged = true;
        m_compositor->allocateOrClearCompositedDeprecatedPaintLayerMapping(reflectionLayer, compositedLayerUpdate);
    }
    m_compositor->updateDirectCompositingReasons(reflectionLayer);

    // FIXME: Why do we updateGraphicsLayerConfiguration here instead of in the GraphicsLayerUpdater?
    if (reflectionLayer->hasCompositedDeprecatedPaintLayerMapping())
        reflectionLayer->compositedDeprecatedPaintLayerMapping()->updateGraphicsLayerConfiguration();
}

static ScrollingCoordinator* scrollingCoordinatorFromLayer(DeprecatedPaintLayer& layer)
{
    Page* page = layer.layoutObject()->frame()->page();
    return (!page) ? nullptr : page->scrollingCoordinator();
}

void CompositingLayerAssigner::assignLayersToBackingsInternal(DeprecatedPaintLayer* layer, SquashingState& squashingState, Vector<DeprecatedPaintLayer*>& layersNeedingPaintInvalidation)
{
    if (requiresSquashing(layer->compositingReasons())) {
        CompositingReasons reasonsPreventingSquashing = getReasonsPreventingSquashing(layer, squashingState);
        if (reasonsPreventingSquashing)
            layer->setCompositingReasons(layer->compositingReasons() | reasonsPreventingSquashing);
    }

    CompositingStateTransitionType compositedLayerUpdate = computeCompositedLayerUpdate(layer);

    if (m_compositor->allocateOrClearCompositedDeprecatedPaintLayerMapping(layer, compositedLayerUpdate)) {
        TRACE_LAYER_INVALIDATION(layer, InspectorLayerInvalidationTrackingEvent::NewCompositedLayer);
        layersNeedingPaintInvalidation.append(layer);
        m_layersChanged = true;
        if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(*layer)) {
            if (layer->layoutObject()->style()->hasViewportConstrainedPosition())
                scrollingCoordinator->frameViewFixedObjectsDidChange(layer->layoutObject()->view()->frameView());
        }
    }

    // FIXME: special-casing reflection layers here is not right.
    if (layer->reflectionInfo())
        assignLayersToBackingsForReflectionLayer(layer->reflectionInfo()->reflectionLayer(), layersNeedingPaintInvalidation);

    // Add this layer to a squashing backing if needed.
    updateSquashingAssignment(layer, squashingState, compositedLayerUpdate, layersNeedingPaintInvalidation);

    const bool layerIsSquashed = compositedLayerUpdate == PutInSquashingLayer || (compositedLayerUpdate == NoCompositingStateChange && layer->groupedMapping());
    if (layerIsSquashed) {
        squashingState.nextSquashedLayerIndex++;
        IntRect layerBounds = layer->clippedAbsoluteBoundingBox();
        squashingState.totalAreaOfSquashedRects += layerBounds.size().area();
        squashingState.boundingRect.unite(layerBounds);
    }

    if (layer->stackingNode()->isStackingContext()) {
        DeprecatedPaintLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
        while (DeprecatedPaintLayerStackingNode* curNode = iterator.next())
            assignLayersToBackingsInternal(curNode->layer(), squashingState, layersNeedingPaintInvalidation);
    }

    // At this point, if the layer is to be separately composited, then its backing becomes the most recent in paint-order.
    if (layer->compositingState() == PaintsIntoOwnBacking) {
        ASSERT(!requiresSquashing(layer->compositingReasons()));
        squashingState.updateSquashingStateForNewMapping(layer->compositedDeprecatedPaintLayerMapping(), layer->hasCompositedDeprecatedPaintLayerMapping());
    }

    if (layer->scrollParent())
        layer->scrollParent()->scrollableArea()->setTopmostScrollChild(layer);

    if (layer->needsCompositedScrolling())
        layer->scrollableArea()->setTopmostScrollChild(nullptr);

    DeprecatedPaintLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
    while (DeprecatedPaintLayerStackingNode* curNode = iterator.next())
        assignLayersToBackingsInternal(curNode->layer(), squashingState, layersNeedingPaintInvalidation);

    if (squashingState.hasMostRecentMapping && &squashingState.mostRecentMapping->owningLayer() == layer)
        squashingState.haveAssignedBackingsToEntireSquashingLayerSubtree = true;
}

}


text:
require 'rubygems'
require 'test/unit'
require 'test/zentest_assertions'

$TESTING = true
$TESTING_CM = true

RAILS_ENV = 'production'

module Rails; end
module Rails::VERSION
  MAJOR = 1
  MINOR = 1
  TINY = 2
end

module ActiveRecord; end

class ActiveRecord::Base

  @count = 1000

  attr_accessor :id, :attributes

  def self.abstract_class=(arg)
    @abstract_class = arg
  end

  def self.abstract_class?
    @abstract_class ||= false
    return !!@abstract_class
  end

  ##
  # Need doco, blech

  def self.find(*args)
    args.flatten!
    case args.first
    when :first then
      return find(:all, *args).first
    when :all then
      return find_by_sql("SELECT * FROM #{table_name} WHERE (#{table_name}.#{primary_key} = '#{args.last}')  LIMIT 1")
    else
      case args.length
      when 1 then
        return find(:first, *args) if Fixnum === args.first
        raise "Dunno what to do"
      when 2 then
        return find(args.first) if Hash === args.last
        return new
      when 3 then
        return [new, new, new]
      else
        raise "Dunno what to do"
      end
    end
  end

  def self.find_by_sql(query)
    return [] if query =~ /concrete\.id = -1/
    return [new]
  end

  def self.next_id
    @count += 1
    return @count
  end

  def self.table_name
    name.downcase
  end

  def self.transaction(*a)
    yield
  end

  def self.primary_key
    'id'
  end

  def initialize
    @id = ActiveRecord::Base.next_id
    @attributes = { :data => 'data' }
  end

  def ==(other)
    self.class == other.class and
    id == other.id and
    attributes_before_type_cast == other.attributes_before_type_cast
  end

  def attributes_before_type_cast
    { :data => @attributes[:data] }
  end

  def destroy
  end

  def reload(*args)
    @attributes[:data].succ!
    @attributes[:extra] = nil
  end

  def save
    update
  end

  def transaction(*a, &b)
    self.class.transaction(*a, &b)
  end

  def update
    true
  end

end

require 'cached_model'

class Concrete < CachedModel; end
class STILameness < Concrete; end

module Cache

  @cache = {}
  @ttl = {}

  class << self; attr_accessor :cache, :ttl; end

  def self.delete(key)
    @cache.delete key
    @ttl.delete key
    return nil
  end

  def self.get(key)
    @cache[key]
  end

  def self.put(key, value, ttl)
    value = Marshal.load Marshal.dump(value)
    @cache[key] = value
    @ttl[key] = ttl
  end

end

class << CachedModel

  attr_writer :cache_local
  attr_writer :cache_delay_commit

end

class TestCachedModel < Test::Unit::TestCase

  DEFAULT_USE_LOCAL_CACHE = CachedModel.use_local_cache?
  DEFAULT_USE_MEMCACHE = CachedModel.use_memcache?

  def setup
    @model = Concrete.new
    Cache.cache = {}
    Cache.ttl = {}
    CachedModel.cache_delay_commit = {}
    CachedModel.cache_local = {}
    CachedModel.use_local_cache = DEFAULT_USE_LOCAL_CACHE
    CachedModel.use_memcache = DEFAULT_USE_MEMCACHE
  end

  def teardown
    CachedModel.use_local_cache = DEFAULT_USE_LOCAL_CACHE
    CachedModel.use_memcache = DEFAULT_USE_MEMCACHE
  end

  def test_class_abstract_class_eh
    assert_equal true, CachedModel.abstract_class?, 'CachedModel is abstract'
    assert_equal false, Concrete.abstract_class?, 'Concrete is not abstract'
  end

  def test_class_cache_delete
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = true
    util_set

    CachedModel.cache_delete @model.class, @model.id

    assert_empty CachedModel.cache_local
    assert_empty Cache.cache
  end

  def test_class_cache_delete_without_local_cache
    CachedModel.use_local_cache = false
    CachedModel.use_memcache = true
    util_set

    CachedModel.cache_delete @model.class, @model.id

    deny_empty CachedModel.cache_local
    assert_empty Cache.cache
  end

  def test_class_cache_delete_without_memcache
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = false
    util_set

    CachedModel.cache_delete @model.class, @model.id

    assert_empty CachedModel.cache_local
    deny_empty Cache.cache
  end

  def test_class_cache_reset
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = true
    util_set

    CachedModel.cache_reset

    assert_empty CachedModel.cache_local
    deny_empty Cache.cache
  end

  def test_class_cache_reset_without_local_cache
    CachedModel.use_local_cache = false
    CachedModel.use_memcache = true
    util_set

    CachedModel.cache_reset

    deny_empty CachedModel.cache_local
    deny_empty Cache.cache
  end

  def test_class_cache_reset_without_memcache
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = false
    util_set

    CachedModel.cache_reset

    assert_empty CachedModel.cache_local
    deny_empty Cache.cache
  end

  def test_class_find_complex
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = true

    record = Concrete.find(1, :order => 'lock_version')

    assert_equal @model.id + 1, record.id

    assert_equal record, util_local(record)
    assert_equal record, util_memcache(record)
  end

  def test_class_find_complex_without_local_cache
    CachedModel.use_local_cache = false
    CachedModel.use_memcache = true

    record = Concrete.find(1, :order => 'lock_version')

    assert_equal @model.id + 1, record.id

    assert_equal nil, util_local(record)
    assert_equal record, util_memcache(record)
  end

  def test_class_find_complex_without_memcache
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = false

    record = Concrete.find(1, :order => 'lock_version')

    assert_equal @model.id + 1, record.id

    assert_equal record, util_local(record)
    assert_equal nil, util_memcache(record)
  end

  def test_class_find_in_local_cache
    CachedModel.use_local_cache = true
    util_set

    record = Concrete.find(1, :order => 'lock_version')
    assert_equal @model.id + 1, record.id

    assert_equal record, util_local(record)
  end

  def test_class_find_in_memcache
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = true
    util_set
    CachedModel.cache_reset

    record = Concrete.find @model.id

    assert_equal @model, record

    assert_equal record, util_local(record)
  end

  def test_class_find_multiple
    CachedModel.use_local_cache = true
    ids = [@model.id + 1, @model.id + 2, @model.id + 3]
    records = Concrete.find(*ids)
    assert_equal ids, records.map { |r| r.id }

    assert_equal ids.map { |i| "#{@model.class}:#{i}" }.sort,
                 CachedModel.cache_local.keys.sort
    assert_equal ids.map { |i| "active_record:#{@model.class}:#{i}" }.sort,
                 Cache.cache.keys.sort
  end

  def test_class_find_not_cached
    CachedModel.use_local_cache = true
    record = Concrete.find @model.id + 1
    assert_equal @model.id + 1, record.id

    assert_equal record, util_local(record)
    assert_equal record, util_memcache(record)
  end

  def test_class_find_by_sql_1_1_x
    CachedModel.use_local_cache = true
    util_set

    q = "SELECT * FROM concrete WHERE (concrete.id = #{@model.id}) LIMIT 1"
    record = Concrete.find_by_sql(q).first
    assert_equal @model.id, record.id

    q = "SELECT * FROM concrete WHERE (concrete.id = #{@model.id + 1}) LIMIT 1"
    record = Concrete.find_by_sql(q).first
    assert_equal @model.id + 1, record.id

    assert_equal record, util_local(record)
    assert_equal record, util_memcache(record)
  end

  def test_class_find_by_sql_1_2_x
    CachedModel.use_local_cache = true
    util_set
    q = "SELECT * FROM concrete WHERE (concrete.id = #{@model.id})"
    record = Concrete.find_by_sql(q).first
    assert_equal @model.id, record.id

    q = "SELECT * FROM concrete WHERE (concrete.id = #{@model.id + 1})"
    record = Concrete.find_by_sql(q).first
    assert_equal @model.id + 1, record.id

    assert_equal record, util_local(record)
    assert_equal record, util_memcache(record)
  end

  def test_class_find_by_sql_extra_space
    CachedModel.use_local_cache = true
    q = "SELECT * FROM concrete WHERE (concrete.id = #{@model.id + 1})  LIMIT 1"
    record = Concrete.find_by_sql(q).first
    assert_equal @model.id + 1, record.id

    assert_equal record, util_local(record)
    assert_equal record, util_memcache(record)
  end

  def test_class_find_by_sql_trailing_stuff
    CachedModel.use_local_cache = true
    util_set

    q = "SELECT * FROM concrete WHERE (concrete.id = #{@model.id}) AND 1 = 1"
    record = Concrete.find_by_sql(q).first
    assert_equal @model.id + 1, record.id

    assert_equal nil, util_local(record)
    assert_equal nil, util_memcache(record)
  end

  def test_class_find_by_sql_no_record
    q = "SELECT * FROM concrete WHERE (concrete.id = -1) LIMIT 1"

    records = Concrete.find_by_sql q

    assert_equal [], records
  end

  def test_class_ttl
    assert_equal 900, CachedModel.ttl
    CachedModel.ttl = 800
    assert_equal 800, CachedModel.ttl
  end

  def test_class_use_local_cache_eh
    CachedModel.use_local_cache = true
    assert_equal true, CachedModel.use_local_cache?
    CachedModel.use_local_cache = false
    assert_equal false, CachedModel.use_local_cache?
  end

  def test_class_use_memcache_eh
    CachedModel.use_memcache = true
    assert_equal true, CachedModel.use_memcache?
    CachedModel.use_memcache = false
    assert_equal false, CachedModel.use_memcache?
  end

  def test_cache_delete
    CachedModel.use_local_cache = true
    util_set

    @model.cache_delete

    assert_empty CachedModel.cache_local
    assert_empty Cache.cache
  end

  def test_cache_key_local
    assert_equal "#{@model.class}:#{@model.id}", @model.cache_key_local
  end

  def test_cache_key_memcache
    assert_equal "active_record:#{@model.class}:#{@model.id}",
                 @model.cache_key_memcache
  end

  def test_cache_local
    assert_same CachedModel.cache_local, @model.cache_local
  end

  def test_cache_store
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = true

    @model.cache_store

    deny_empty CachedModel.cache_local
    deny_empty Cache.cache

    assert_equal @model, util_local(@model)
    assert_equal @model, util_memcache(@model)
    assert_equal CachedModel.ttl, Cache.ttl[@model.cache_key_memcache]
  end

  def test_cache_store_in_transaction
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = true
    CachedModel.cache_delay_commit[0] = []

    @model.cache_store

    deny_empty CachedModel.cache_delay_commit
    assert_empty CachedModel.cache_local
    assert_empty Cache.cache
  end

  def test_cache_store_without_local_cache
    CachedModel.use_local_cache = false
    CachedModel.use_memcache = true

    @model.cache_store

    assert_empty CachedModel.cache_local
    deny_empty Cache.cache

    assert_equal nil, util_local(@model)
    assert_equal @model, util_memcache(@model)
    assert_equal CachedModel.ttl, Cache.ttl[@model.cache_key_memcache]
  end

  def test_cache_store_without_memcache
    CachedModel.use_local_cache = true
    CachedModel.use_memcache = false

    @model.cache_store

    deny_empty CachedModel.cache_local
    assert_empty Cache.cache

    assert_equal @model, util_local(@model)
    assert_equal nil, util_memcache(@model)
  end

  def test_cache_store_with_attributes
    CachedModel.use_local_cache = true
    @model.attributes[:extra] = 'extra'
    @model.cache_store

    deny_empty CachedModel.cache_local
    deny_empty Cache.cache

    local_model = util_local(@model)
    mem_model = util_memcache(@model)
    assert_equal @model, local_model
    assert_equal @model, mem_model
    assert_equal CachedModel.ttl, Cache.ttl[@model.cache_key_memcache]

    expected = {:data => 'data'}

    assert_equal expected, local_model.attributes
    assert_equal expected, mem_model.attributes
  end

  def test_destroy
    CachedModel.use_local_cache = true
    util_set

    @model.destroy

    assert_empty CachedModel.cache_local
    assert_empty Cache.cache
  end

  def test_reload
    util_set

    @model.reload

    deny_empty CachedModel.cache_local
    deny_empty Cache.cache

    assert_equal 'datb',
                 util_local(@model).attributes[:data]
    assert_equal 'datb',
                 util_memcache(@model).attributes[:data]
  end

  def test_reload_with_attribs
    util_set

    @model.reload(:lock => true)

    deny_empty CachedModel.cache_local
    deny_empty Cache.cache

    assert_equal 'datb',
                 util_local(@model).attributes[:data]
    assert_equal 'datb',
                 util_memcache(@model).attributes[:data]
  end

  def test_transaction_fail
    CachedModel.use_local_cache = true

    e = assert_raise RuntimeError do
      @model.transaction do
        @model.attributes[:data] = 'atad'
        @model.save
        raise 'Oh nos!'
      end
    end

    assert_equal 'Oh nos!', e.message
    assert_equal nil, util_local(@model)
    assert_equal nil, util_memcache(@model)
  end

  def test_transaction_nested
    CachedModel.use_local_cache = true

    @model.transaction do
      @model.transaction do
        @model.attributes[:data] = 'value1'
        @model.save

        assert_equal nil, util_local(@model), 'in t1 local'
        assert_equal nil, util_memcache(@model), 'in t1 memcache'
      end

      assert_equal 'value1', util_local(@model).attributes[:data],
                   'completed t1 local'
      assert_equal 'value1', util_memcache(@model).attributes[:data],
                   'completed t1 memcache'

      @model.attributes[:data] = 'value2'
      @model.save

      assert_equal 'value1', util_local(@model).attributes[:data],
                   'in t2 local'
      assert_equal 'value1', util_memcache(@model).attributes[:data],
                   'in t2 memcache'
    end

    assert_equal 'value2', util_local(@model).attributes[:data],
                 'completed t2 local'
    assert_equal 'value2', util_memcache(@model).attributes[:data],
                 'completed t2 local'
  end

  def test_transaction_pass
    CachedModel.use_local_cache = true

    result = @model.transaction do
      @model.attributes[:data] = 'atad'
      @model.save

      assert_equal nil, util_local(@model)
      assert_equal nil, util_memcache(@model)

      :some_value
    end

    assert_equal :some_value, result

    assert_equal 'atad', util_local(@model).attributes[:data]
    assert_equal 'atad',
                 util_memcache(@model).attributes[:data]

  end

  def test_update
    util_set

    @model.attributes[:data] = 'atad'
    assert_equal true, @model.update, "Updates should return true"

    deny_empty CachedModel.cache_local
    deny_empty Cache.cache

    assert_equal 'atad',
                 util_local(@model).attributes[:data]
    assert_equal 'atad',
                 util_memcache(@model).attributes[:data]
  end

  def util_local(model)
    CachedModel.cache_local[model.cache_key_local]
  end

  def util_memcache(model)
    Cache.cache[model.cache_key_memcache]
  end

  def util_set(klass = @model.class, id = @model.id, data = @model)
    key = "#{klass}:#{id}"
    CachedModel.cache_local[key] = data
    Cache.cache["active_record:#{key}"] = data
  end

end


text:
package com.pcloud.sdk.internal.networking.serialization;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

public class UnmodifiableListTypeFactory implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType) {
        final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, tokenType);

        return new TypeAdapter<T>() {
            @Override
            public void write(JsonWriter out, T value) throws IOException {
                delegate.write(out, value);
            }

            @SuppressWarnings("unchecked")
            @Override
            public T read(JsonReader arg0) throws IOException {
                T t = delegate.read(arg0);
                if (List.class.isAssignableFrom(tokenType.getRawType())) {
                    List<?> list = (List<?>) t;

                    return (T) Collections.unmodifiableList(list);
                }

                return t;
            }
        };
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Splanchnonema plantani

### Remarks
null


text:
//
// A client-side library for interacting with Context.IO.
//
package contextio

import (
	"encoding/json"
	"fmt"
	"github.com/mrjones/oauth"
	"io/ioutil"
	"net/http"
	"strings"
)

const (
	API_URL     = "https://api.context.io"
	API_VERSION = "2.0"
)

func New(key, secret string) *Client {
	oc := oauth.NewConsumer(key, secret, oauth.ServiceProvider{})
	return &Client{consumer: oc, key: key, secret: secret}
}

type Client struct {
	consumer *oauth.Consumer
	key      string
	secret   string
}

/*
Enables debugging of the OAuth consumer when set to true. Providing a value of
false disables debugging.
*/
func (c *Client) EnableDebugging(debug bool) {
	c.consumer.Debug(debug)
}

/*
Perform a two-legged OAuth 1.0 request against the context.io API.

The supported values for the method are "GET", "POST", "PUT", and "DELETE".

The params string-string map is for any extra parameters you wish to provide to
an endpoint, that will be URL-encoded.

The rest of the arguments are the various parts of the API endpoint's URI, done
like a print-like function:

	var account Account
	...
	c.Do("GET", nil, "accounts", account.Id, "files")

...this is so that you do not have to constantly re-create the a URI string to
pass to this function.
*/
func (c *Client) Do(method string, params map[string]string, parts ...string) (resp *http.Response, err error) {
	// Build the URL.
	url := fmt.Sprintf("%s/%s/%s", API_URL, API_VERSION, strings.Join(parts, "/"))

	// The access token
	accessToken := &oauth.AccessToken{}

	// Call the appropriate function on the consumer, depending on the provided
	// value of `method`.
	switch strings.ToUpper(method) {
	case "GET":
		resp, err = c.consumer.Get(url, params, accessToken)

	case "POST":
		resp, err = c.consumer.Post(url, params, accessToken)

	case "PUT":
		resp, err = c.consumer.Put(url, "", params, accessToken)

	case "DELETE":
		resp, err = c.consumer.Delete(url, params, accessToken)
	}

	return
}

/*
Unmarshals the body of the provided HTTP response, into the provided type.

For example, if you called:

	response, err := c.Do("GET", "accounts")

...you would call *c.Unmarshal() like so:

	var accounts []contextio.Account
	err = c.Unmarshal(response, &accounts)
*/
func (c *Client) Unmarshal(response *http.Response, v interface{}) error {
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	return json.Unmarshal(body, v)
}

/*
 Copies the details of the existing client into a the new one.
*/
func (c *Client) CopyTo(newclient *Client) {
	*newclient = *c
}


text:
class PageHandler {
    handle(collection, page, size) {
        let i = 1;
        const filteredCollection = [];
        let pagesNum = Math.ceil(collection.length / size);
        if (pagesNum < 1) {
            pagesNum = 1;
        }
        if (page < 1 || page > pagesNum) {
            const error = 'Page is above / bellow range.';
            return { error };
        }

        let index = (i + ((page - 1) * size) - 1);
        while (index < collection.length && i <= size) {
            filteredCollection.push(collection[index++]);
            i++;
        }
        const showPages = [];
        if (page > 1 && page < pagesNum) {
            showPages.push(page - 1, page, page + 1);
        } else if (page === 1 && pagesNum > 2) {
            showPages.push(page, page + 1, page + 2);
        } else if (page === pagesNum && pagesNum > 2) {
            showPages.push(page - 2, page - 1, page);
        } else {
            for (let j = 1; j <= pagesNum; j += 1) {
                showPages.push(j);
            }
        }

        return {
            filteredCollection: filteredCollection,
            numberOfPages: pagesNum,
            navigationNumbers: showPages,
        };
    }

    choosePage(page) {
        if (!page) {
            page = 1;
        } else if (isNaN(page)) {
            const error = 'Page is not a number.';
            return { error };
        } else {
            page = parseInt(page, 10);
        }

        return page;
    }
}

// @ts-ignore
module.exports = new PageHandler();


text:
from typing import Optional

import pandas as pd
import pygeos as geos

from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.exceptions import InvalidExpectationConfigurationError
from great_expectations.execution_engine import (
    PandasExecutionEngine,
    SparkDFExecutionEngine,
    SqlAlchemyExecutionEngine,
)
from great_expectations.expectations.expectation import ColumnMapExpectation
from great_expectations.expectations.metrics import (
    ColumnMapMetricProvider,
    column_condition_partial,
)

# This class defines a Metric to support your Expectation.
# For most ColumnMapExpectations, the main business logic for calculation will live in this class.
class ColumnValuesGeometryCentroidsWithinShape(ColumnMapMetricProvider):

    # This is the id string that will be used to reference your metric.
    condition_metric_name = "column_values.geometry.centroids_within_shape"
    condition_value_keys = ("shape", "shape_format", "column_shape_format")

    # This method implements the core logic for the PandasExecutionEngine
    @column_condition_partial(engine=PandasExecutionEngine)
    def _pandas(cls, column, **kwargs):

        shape = kwargs.get("shape")
        shape_format = kwargs.get("shape_format")
        column_shape_format = kwargs.get("column_shape_format")

        # Check that shape is given and given in the correct format
        if shape is not None:
            try:
                if shape_format == "wkt":
                    shape_ref = geos.from_wkt(shape)
                elif shape_format == "wkb":
                    shape_ref = geos.from_wkb(shape)
                elif shape_format == "geojson":
                    shape_ref = geos.from_geojson(shape)
                else:
                    raise NotImplementedError(
                        "Shape constructor method not implemented. Must be in WKT, WKB, or GeoJSON format."
                    )
            except:
                raise Exception("A valid reference shape was not given.")
        else:
            raise Exception("A shape must be provided for this method.")

        # Load the column into a pygeos Geometry vector from numpy array (Series not supported).
        if column_shape_format == "wkt":
            shape_test = geos.from_wkt(column.to_numpy(), on_invalid="ignore")
        elif column_shape_format == "wkb":
            shape_test = geos.from_wkb(column.to_numpy(), on_invalid="ignore")
        else:
            raise NotImplementedError("Column values shape format not implemented.")

        # Allow for an array of reference shapes to be provided. Return a union of all the shapes in the array (Polygon or Multipolygon)
        shape_ref = geos.union_all(shape_ref)

        # Prepare the geometries
        geos.prepare(shape_ref)
        geos.prepare(shape_test)
        column_centroids = geos.centroid(shape_test)

        print(column_centroids)

        return pd.Series(geos.within(column_centroids, shape_ref))

    # This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
    # @column_condition_partial(engine=SqlAlchemyExecutionEngine)
    # def _sqlalchemy(cls, column, _dialect, **kwargs):
    #     raise NotImplementedError

    # This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
    # @column_condition_partial(engine=SparkDFExecutionEngine)
    # def _spark(cls, column, **kwargs):
    #     raise NotImplementedError

# This class defines the Expectation itself
class ExpectColumnValuesGeometryCentroidsToBeWithinShape(ColumnMapExpectation):
    """
    Expect that column values as geometries each have a centroid that are within a given reference shape.

    expect_column_values_geometry_centroids_to_be_within_shape is a :func:`column_map_expectation <great_expectations.dataset.dataset.MetaDataset.column_map_expectation>`.

    Args:
        column (str): \
            The column name.
            Column values must be provided in WKT or WKB format, which are commom formats for GIS Database formats.
            WKT can be accessed thhrough the ST_AsText() or ST_AsBinary() functions in queries for PostGIS and MSSQL.

    Keyword Args:
        shape: str or list(str)
            The reference geometry

        shape_format: str
            Geometry format for 'shape' string(s). Can be provided as 'Well Known Text' (WKT), 'Well Known Binary' (WKB), or as GeoJSON.
            Must be one of: [wkt, wkb, geojson]
            Default: wkt

        column_shape_format: str
            Geometry format for 'column'. Column values must be provided in WKT or WKB format, which are commom formats for GIS Database formats.
            WKT can be accessed thhrough the ST_AsText() or ST_AsBinary() functions in queries for PostGIS and MSSQL.

    Returns:
        An ExpectationSuiteValidationResult

    Notes:
        Convention is (X Y Z) for points, which would map to (Longitude Latitude Elevation) for geospatial cases.
        Any convention can be followed as long as the test and reference shapes are consistent.
        The reference shape allows for an array, but will union (merge) all the shapes into 1 and check the contains condition.
        MultiLinestrings and Multipolygons area weighted by their length and areas, respectively. See the pygeos docs for reference.
    """

    # These examples will be shown in the public gallery.
    # They will also be executed as unit tests for your Expectation.
    examples = [
        {
            "data": {
                "lines": [
                    "LINESTRING(0 0, 10 10)",
                    "LINESTRING(5 5, 8 10)",
                    "LINESTRING(0 0, 18 2)",
                    "LINESTRING(3 4, 0 7, 10 0, 15 10)",
                ],
                "polygons": [
                    "POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))",
                    "POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))",
                    "POLYGON ((10 10, 10 15, 15 15, 15 10, 10 10))",
                    None,
                ],
            },
            "tests": [
                {
                    "title": "positive_test_with_lines",
                    "exact_match_out": False,
                    "include_in_gallery": True,
                    "in": {
                        "column": "lines",
                        "shape": "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))",
                        "shape_format": "wkt",
                    },
                    "out": {
                        "success": True,
                    },
                },
                {
                    "title": "negative_test_with_polygons",
                    "exact_match_out": False,
                    "include_in_gallery": True,
                    "in": {
                        "column": "polygons",
                        "shape": "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))",
                        "shape_format": "wkt",
                    },
                    "out": {
                        "success": False,
                    },
                },
            ],
        }
    ]

    # This is the id string of the Metric used by this Expectation.
    # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
    map_metric = "column_values.geometry.centroids_within_shape"

    # This is a list of parameter names that can affect whether the Expectation evaluates to True or False
    success_keys = ("mostly", "shape", "shape_format", "column_shape_format")

    # This dictionary contains default values for any parameters that should have default values
    default_kwarg_values = {
        "mostly": 1,
        "shape_format": "wkt",
        "column_shape_format": "wkt",
    }

    def validate_configuration(self, configuration: Optional[ExpectationConfiguration]):
        """
        Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that
        necessary configuration arguments have been provided for the validation of the expectation.

        Args:
            configuration (OPTIONAL[ExpectationConfiguration]): \
                An optional Expectation Configuration entry that will be used to configure the expectation
        Returns:
            True if the configuration has been validated successfully. Otherwise, raises an exception
        """

        super().validate_configuration(configuration)
        if configuration is None:
            configuration = self.configuration

        # # Check other things in configuration.kwargs and raise Exceptions if needed
        # try:
        #     assert (
        #         ...
        #     ), "message"
        #     assert (
        #         ...
        #     ), "message"
        # except AssertionError as e:
        #     raise InvalidExpectationConfigurationError(str(e))

        return True

    # This object contains metadata for display in the public Gallery
    library_metadata = {
        "tags": [
            "geospatial",
            "hackathon-2022",
        ],  # Tags for this Expectation in the Gallery
        "contributors": [  # Github handles for all contributors to this Expectation.
            "@pjdobson",  # Don't forget to add your github handle here!
        ],
        "requirements": ["pygeos"],
    }

if __name__ == "__main__":
    ExpectColumnValuesGeometryCentroidsToBeWithinShape().print_diagnostic_checklist()


text:
/*
 * Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;

using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Response Unmarshaller for LaunchSpecification Object
    /// </summary>
    public class LaunchSpecificationUnmarshaller : IUnmarshaller<LaunchSpecification, XmlUnmarshallerContext>, IUnmarshaller<LaunchSpecification, JsonUnmarshallerContext>
    {
        public LaunchSpecification Unmarshall(XmlUnmarshallerContext context)
        {
            LaunchSpecification unmarshalledObject = new LaunchSpecification();
            int originalDepth = context.CurrentDepth;
            int targetDepth = originalDepth + 1;

            if (context.IsStartOfDocument)
               targetDepth += 2;

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("addressingType", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.AddressingType = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("groupSet/item", targetDepth))
                    {
                        var unmarshaller = GroupIdentifierUnmarshaller.Instance;
                        var item = unmarshaller.Unmarshall(context);
                        unmarshalledObject.AllSecurityGroups.Add(item);
                        continue;
                    }
                    if (context.TestExpression("blockDeviceMapping/item", targetDepth))
                    {
                        var unmarshaller = BlockDeviceMappingUnmarshaller.Instance;
                        var item = unmarshaller.Unmarshall(context);
                        unmarshalledObject.BlockDeviceMappings.Add(item);
                        continue;
                    }
                    if (context.TestExpression("ebsOptimized", targetDepth))
                    {
                        var unmarshaller = BoolUnmarshaller.Instance;
                        unmarshalledObject.EbsOptimized = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("iamInstanceProfile", targetDepth))
                    {
                        var unmarshaller = IamInstanceProfileSpecificationUnmarshaller.Instance;
                        unmarshalledObject.IamInstanceProfile = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("imageId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.ImageId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("instanceType", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.InstanceType = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("kernelId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.KernelId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("keyName", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.KeyName = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("monitoring/enabled", targetDepth))
                    {
                        var unmarshaller = BoolUnmarshaller.Instance;
                        unmarshalledObject.MonitoringEnabled = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("networkInterfaceSet/item", targetDepth))
                    {
                        var unmarshaller = InstanceNetworkInterfaceSpecificationUnmarshaller.Instance;
                        var item = unmarshaller.Unmarshall(context);
                        unmarshalledObject.NetworkInterfaces.Add(item);
                        continue;
                    }
                    if (context.TestExpression("placement", targetDepth))
                    {
                        var unmarshaller = SpotPlacementUnmarshaller.Instance;
                        unmarshalledObject.Placement = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("ramdiskId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.RamdiskId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("securityGroup/GroupName", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        var item = unmarshaller.Unmarshall(context);
                        unmarshalledObject.SecurityGroups.Add(item);
                        continue;
                    }
                    if (context.TestExpression("subnetId", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.SubnetId = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("userData", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.UserData = unmarshaller.Unmarshall(context);
                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return unmarshalledObject;
                }
            }

            return unmarshalledObject;
        }

        public LaunchSpecification Unmarshall(JsonUnmarshallerContext context)
        {
            return null;
        }

        private static LaunchSpecificationUnmarshaller _instance = new LaunchSpecificationUnmarshaller();

        public static LaunchSpecificationUnmarshaller Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}


text:
using System;
using Security;
using Foundation;
using Xamarin.Forms;
using XamarinForms.QbChat.iOS;
using QbChat.Pcl.Interfaces;

[assembly: Dependency(typeof(IOSDeviceUid))]
namespace XamarinForms.QbChat.iOS
{
	public class IOSDeviceUid : IDeviceIdentifier
	{
		public string GetIdentifier()
		{
			string serial = string.Empty;
			var rec = new SecRecord(SecKind.GenericPassword)
			{
				Generic = NSData.FromString("uidNumber")
			};

			SecStatusCode res;
			var match = SecKeyChain.QueryAsRecord(rec, out res);
			if (res == SecStatusCode.Success)
			{
				serial = match.ValueData.ToString();
			}
			else
			{
				var uidNumberRecord = new SecRecord(SecKind.GenericPassword)
				{
					Label = "uid",
					ValueData = NSData.FromString(Guid.NewGuid().ToString()),
					Generic = NSData.FromString("uidNumber")
				};

				var err = SecKeyChain.Add(uidNumberRecord);
				serial = uidNumberRecord.ValueData.ToString();
			}

			return serial;

		}
	}
}


text:
#import <Foundation/Foundation.h>
#import <CoreObject/COType.h>

@class COObject, COItem;

NS_ASSUME_NONNULL_BEGIN

@interface COCachedRelationship : NSObject
{
@public
    NSString *_targetProperty;
    COObject *__weak _sourceObject;
    NSString *_sourceProperty;
}

@property (nonatomic, readonly) NSDictionary *descriptionDictionary;
@property (readwrite, nonatomic, weak) __kindof COObject *sourceObject;
@property (readwrite, nonatomic, copy) NSString *sourceProperty;
/**
 * The property whose value is looked up with the incoming relationship cache of the target object.
 *
 * For a unidirectional relationship without opposite, the target property is nil, since there is an
 * outgoing relationship (from source to target), but no incoming relationship in the reverse
 * direction.
 */
@property (readwrite, nonatomic, copy, nullable) NSString *targetProperty;

- (BOOL)isSourceObjectTrackingSpecificBranchForTargetObject: (COObject *)aTargetObject;

@property (nonatomic, readonly, getter=isSourceObjectBranchDeleted) BOOL sourceObjectBranchDeleted;

@end

/**
 * An instance of this class is owned by each COObject,
 * to cache incoming relationships for that object.
 */
@interface CORelationshipCache : NSObject
{
@private
    NSMutableArray *_cachedRelationships;
    COObject *__weak _owner;
}

- (instancetype)initWithOwner: (COObject *)owner NS_DESIGNATED_INITIALIZER;

@property (nonatomic, readonly) NSSet<__kindof COObject *> *referringObjects;

/**
 * Returns an array of COObject which have a reference to the
 * owning COObject through the given property in the owning COObject.
 */
- (NSSet *)referringObjectsForPropertyInTarget: (NSString *)aProperty;
- (__kindof COObject *)referringObjectForPropertyInTarget: (NSString *)aProperty;

- (void)removeAllEntries;

@property (nonatomic, readonly) NSArray *allEntries;

// FIXME: aTargetProperty sounds like an incorrect argument name... should be aSourceProperty?
- (void)removeReferencesForPropertyInSource: (NSString *)aTargetProperty
                               sourceObject: (COObject *)anObject;
- (void)addReferenceFromSourceObject: (COObject *)aReferrer
                      sourceProperty: (NSString *)aSource
                      targetProperty: (nullable NSString *)aTarget;

@end

NS_ASSUME_NONNULL_END


text:
var DocDBUtils = {
    getOrCreateDatabase: function (client, databaseId, callback) {
        var querySpec = {
            query: 'SELECT * FROM root r WHERE r.id=@id',
            parameters: [{
                    name: '@id',
                    value: databaseId
                }]
        };

        client.queryDatabases(querySpec).toArray(function (err, results) {
            if (err) {
                callback(err);
            } else {
                if (results.length === 0) {
                    var databaseSpec = {
                        id: databaseId
                    };

                    client.createDatabase(databaseSpec, function (err, created) {
                        callback(null, created);
                    });

                } else {
                    callback(null, results[0]);
                }
            }
        });
    },

    getOrCreateCollection: function (client, databaseLink, collectionId, callback) {
        var querySpec = {
            query: 'SELECT * FROM root r WHERE r.id=@id',
            parameters: [{
                    name: '@id',
                    value: collectionId
                }]
        };

        client.queryCollections(databaseLink, querySpec).toArray(function (err, results) {
            if (err) {
                callback(err);
            } else {
                if (results.length === 0) {
                    var collectionSpec = {
                        id: collectionId
                    };

                    var requestOptions = {
                        offerType: 'S1'
                    };

                    client.createCollection(databaseLink, collectionSpec, requestOptions, function (err, created) {
                        callback(null, created);
                    });

                } else {
                    callback(null, results[0]);
                }
            }
        });
    },

    initCollection: function (client, databaseId, collectionId, callback) {
        var self = this;

        DocDBUtils.getOrCreateDatabase(client, databaseId, function (err, db) {
            if (err) {
                callback(err);
            } else {
                DocDBUtils.getOrCreateCollection(client, db._self, collectionId, callback);
            }
        });
    }
};

module.exports = DocDBUtils;


text:
package es.itecban.deployment.model.validation.result.util;

import es.itecban.deployment.model.validation.result.*;

import java.util.List;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;

/**
 *
 * The Switch for the model's inheritance hierarchy.
 * It supports the call {@link #doSwitch(EObject) doSwitch(object)}
 * to invoke the caseXXX method for each class of the model,
 * starting with the actual class of the object
 * and proceeding up the inheritance hierarchy
 * until a non-null result is returned,
 * which is the result of the switch.
 *
 * @see es.itecban.deployment.model.validation.result.ResultPackage
 * @generated
 */
public class ResultSwitch<T> {
	/**
	 * The cached model package
	 *
	 *
	 * @generated
	 */
	protected static ResultPackage modelPackage;

	/**
	 * Creates an instance of the switch.
	 *
	 *
	 * @generated
	 */
	public ResultSwitch() {
		if (modelPackage == null) {
			modelPackage = ResultPackage.eINSTANCE;
		}
	}

	/**
	 * Calls caseXXX for each class of the model until one returns a non null result; it yields that result.
	 *
	 *
	 * @return the first non-null result returned by a caseXXX call.
	 * @generated
	 */
	public T doSwitch(EObject theEObject) {
		return doSwitch(theEObject.eClass(), theEObject);
	}

	/**
	 * Calls caseXXX for each class of the model until one returns a non null result; it yields that result.
	 *
	 *
	 * @return the first non-null result returned by a caseXXX call.
	 * @generated
	 */
	protected T doSwitch(EClass theEClass, EObject theEObject) {
		if (theEClass.eContainer() == modelPackage) {
			return doSwitch(theEClass.getClassifierID(), theEObject);
		}
		else {
			List<EClass> eSuperTypes = theEClass.getESuperTypes();
			return
				eSuperTypes.isEmpty() ?
					defaultCase(theEObject) :
					doSwitch(eSuperTypes.get(0), theEObject);
		}
	}

	/**
	 * Calls caseXXX for each class of the model until one returns a non null result; it yields that result.
	 *
	 *
	 * @return the first non-null result returned by a caseXXX call.
	 * @generated
	 */
	protected T doSwitch(int classifierID, EObject theEObject) {
		switch (classifierID) {
			case ResultPackage.DOCUMENT_ROOT: {
				DocumentRoot documentRoot = (DocumentRoot)theEObject;
				T result = caseDocumentRoot(documentRoot);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case ResultPackage.PLAN_VALIDATION_RESULT: {
				PlanValidationResult planValidationResult = (PlanValidationResult)theEObject;
				T result = casePlanValidationResult(planValidationResult);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			default: return defaultCase(theEObject);
		}
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Document Root'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Document Root'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseDocumentRoot(DocumentRoot object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Plan Validation Result'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Plan Validation Result'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T casePlanValidationResult(PlanValidationResult object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'EObject'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch, but this is the last case anyway.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'EObject'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject)
	 * @generated
	 */
	public T defaultCase(EObject object) {
		return null;
	}

} //ResultSwitch


text:
<?php

?>

<form class="form-horizontal" role="form"  id="tasksTypes" action="<?php echo url_for('tasksTypes/'.($form->getObject()->isNew() ? 'create' : 'update').(!$form->getObject()->isNew() ? '?id='.$form->getObject()->getId() : '')) ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?>>

    <?php if (!$form->getObject()->isNew()): ?>
    <input type="hidden" name="sf_method" value="put" />
    <?php endif; ?>

    <?php echo $form->renderHiddenFields(false) ?>
    <?php echo $form->renderGlobalErrors() ?>

    	* <?php echo $form['name']->renderLabel() ?>

    		<?php echo $form['name'] ?>

    	<?php echo $form['active']->renderLabel() ?>

<?php echo $form['active'] ?>

    	<?php echo $form['default_value']->renderLabel() ?>

<?php echo $form['default_value'] ?>

    	<?php echo $form['sort_order']->renderLabel() ?>

    		<?php echo $form['sort_order'] ?>

<?php echo ajax_modal_template_footer() ?>

</form>

<?php include_partial('global/formValidator',array('form_id'=>'tasksTypes')); ?>


text:
const autoprefixer = require('autoprefixer');

module.exports = () => ({
  plugins: [
    autoprefixer({
      overrideBrowserslist: [
        '> 1%',
        'last 4 versions',
        'last 20 Chrome versions',
        'last 20 Firefox versions',
      ],
    }),
  ],
});


text:
The legendary bowling kata in Go.

[![Build Status](https://travis-ci.org/jehrhardt/bowling-game-go.svg?branch=master)](https://travis-ci.org/jehrhardt/bowling-game-go)


text:
package gui;

import com.googlecode.dex2jar.reader.DexFileReader;
import parser.apk.APK;
import parser.dex.DexClass;
import parser.dex.DexFileAdapter;
import utils.ComparatorClass;
import utils.FileDrop;
import utils.UtilLocal;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: lai
 * Date: 8/5/13
 * Time: 9:53 AM
 */
public class FeatureCode extends JPanel {
    final JTextArea stringList;
    JTree treePkg;

    public FeatureCode() {
        setLayout(new BorderLayout(0, 0));

        // 添加分割面板
        final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setDividerLocation(250);
        add(splitPane, BorderLayout.CENTER);

        treePkg = new JTree();
        treePkg.setRootVisible(false);
        treePkg.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
        JScrollPane jScrollPaneLeft = new JScrollPane(treePkg);
        splitPane.setLeftComponent(jScrollPaneLeft);

        stringList = new JTextArea();
        stringList.setText("功能:提取类的字符串。\n" +
                "\n" +
                "使用方法:\n" +
                "将 APK 文件拉入左边的框即可。\n" +
                "点击相应的类,则可以显示该类中出现的字符串。");
        JScrollPane jScrollPaneRight = new JScrollPane(stringList);
        jScrollPaneRight.setViewportView(stringList);
        splitPane.setRightComponent(jScrollPaneRight);

        //监听拖动文件
        new FileDrop(System.out, treePkg, /* dragBorder, */new FileDrop.Listener() {
            @Override
            public void filesDropped(java.io.File[] files) {
                createNodes(files);
            }
        });

        //左部被点击后动作
        treePkg.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent treeSelectionEvent) {

                JTree treeSource = (JTree) treeSelectionEvent.getSource();
                TreePath[] treePaths = treeSource.getSelectionPaths();

                if (treePaths == null) {
                    return;
                }

                ArrayList<ClassNode> classNodes = new ArrayList<>();
                stringList.setText("");

                // 遍历下面的所有的叶子节点
                for (TreePath treePath : treePaths) {
                    final DefaultMutableTreeNode treeNode =
                            (DefaultMutableTreeNode) treePath.getLastPathComponent();
                    if (treeNode.getUserObject() instanceof DexClass) {
                        classNodes.add((ClassNode) treeNode);
                    } else {

                        classNodes.addAll(getClassNodes(treeNode));
                    }
                }

                stringList.append(getStrings(classNodes).replace("[", "").replace(", ", ""));

                //get the current lead path
                final TreePath newPath = treeSelectionEvent.getNewLeadSelectionPath();
                if (newPath == null)
                    return;

                final DefaultMutableTreeNode selectNode =
                        (DefaultMutableTreeNode) newPath.getLastPathComponent();
                if (selectNode.getUserObject() instanceof DexFileReader) {
                    final DexFileReader dexFile = (DexFileReader) selectNode.getUserObject();
                    System.out.println("dexFile.getClassSize : " + dexFile.getClassSize());
                } else if (selectNode.getUserObject() instanceof DexClass) {
                    DexClass classDefItem = (DexClass) selectNode.getUserObject();

                    StringBuilder sb = new StringBuilder();
                    List<String> strList = classDefItem.stringData;
                    Collections.sort(strList);
                    for (String str : strList) {
                        sb.append("").append(str).append("").append('\n');
                    }
                    stringList.setText(sb.toString());
                } else {
                    stringList.setText(getStrings(getClassNodes(selectNode))
                            .replace("[", "").replace(", ", ""));
                }

            }
        });

    }

    /**
     * @param parent      父节点
     * @param packageName 查找或插入的节点名
     * @return 查找或插入的节点
     */
    public static DefaultMutableTreeNode findOrAddNode(TreePath parent, String packageName) {
        final DefaultMutableTreeNode node = (DefaultMutableTreeNode) parent.getLastPathComponent();

        for (final Enumeration e = node.children(); e.hasMoreElements(); ) {
            final DefaultMutableTreeNode mutableTreeNode = (DefaultMutableTreeNode) e.nextElement();
            if (packageName.equals(mutableTreeNode.toString()))
                return mutableTreeNode;
        }

        final DefaultMutableTreeNode nodeCls = new DefaultMutableTreeNode(packageName);
        node.add(nodeCls);
        return nodeCls;
    }

    /**
     * 获取类节点
     *
     * @param selectNode 节点
     * @return 类节点列表
     */
    ArrayList<ClassNode> getClassNodes(DefaultMutableTreeNode selectNode) {
        ArrayList<ClassNode> classNodes = new ArrayList<>();

        for (final Enumeration ee = selectNode.children(); ee.hasMoreElements(); ) {
            final DefaultMutableTreeNode n = (DefaultMutableTreeNode) ee.nextElement();

            if (n.isLeaf()) {
                classNodes.add((ClassNode) n);
            } else {
                ArrayList<ClassNode> subClassNodes = getClassNodes(n);
                classNodes.addAll(subClassNodes);
            }
        }

        return classNodes;
    }

    /**
     * 获取字符串
     *
     * @param classNodes 节点列表
     * @return 字符串
     */
    private String getStrings(ArrayList<ClassNode> classNodes) {
        HashSet<String> hashSet = new HashSet<>();
        for (ClassNode classNode : classNodes) {
            List<String> strList = classNode.dexClass.stringData;
            for (String str : strList) {
                hashSet.add("" + str + "" + '\n');
            }

        }

        ArrayList<String> arrayList = new ArrayList<>(hashSet);
        Collections.sort(arrayList);

        return arrayList.toString();
    }

    /**
     * 添加包和类节点(可以添加多个文件)
     *
     * @param files drop files...
     */
    private void createNodes(File[] files) {
        final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Files");
        APK apk;
        // 1.parse files
        for (final File file : files) {
            DexFileReader dexFileReader;
            try {
                dexFileReader = new DexFileReader(file);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }

            // 创建根节点.
            DefaultMutableTreeNode fileNode = new FileNode(dexFileReader, file.getAbsolutePath());
            rootNode.add(fileNode);

            final List<DexClass> classList = new ArrayList<>();

            try {
                dexFileReader.accept(new DexFileAdapter(classList),
                        DexFileReader.SKIP_DEBUG | DexFileReader.SKIP_ANNOTATION);
            } catch (Exception e) {
                System.out.println("Accept Code Failed." + e.getMessage());
                return;
            }

            //sort
            Collections.sort(classList, new ComparatorClass());

            for (final DexClass dexClass : classList) {
                // 完整类名(com.pkg1.pkg2.cls;)
                String className = dexClass.className;

                // 获得节点字符串数组(com pkg1 pkg2 cls)
                final String[] strings = className.substring(1, className.length() - 1).split("/");

                if (UtilLocal.DEBUG) {
                    System.out.print(className + " ");
                    for (String name : strings) {
                        System.out.print(name + " ");
                    }
                    System.out.println();
                }

                int len = strings.length;
                DefaultMutableTreeNode pkgNode = fileNode;
                for (int i = 0; i < len - 1; i++) {
                    pkgNode = findOrAddNode(new TreePath(pkgNode), strings[i]);
                }

                ClassNode classNode = new ClassNode(dexClass);

                pkgNode.add(classNode);
            }

            treePkg.setModel(new DefaultTreeModel(rootNode));

        }
    }

    private class FileNode extends DefaultMutableTreeNode {
        String fileName;

        public FileNode(DexFileReader dexFileReader, String filePath) {
            super(dexFileReader, true);
            fileName = new File(filePath).getName();
        }

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

    class ClassNode extends DefaultMutableTreeNode {
        String className;
        DexClass dexClass;

        ClassNode(DexClass dexClass) {
            super(dexClass, true);
            final String[] strings = dexClass.className.substring
                    (1, dexClass.className.length() - 1).split("/");

            className = strings[strings.length - 1];
            this.dexClass = dexClass;
        }

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

}


text:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.Map.Entry;

public class TokenCount {
    private static final ConcurrentHashMap<String, AtomicInteger> tokenFreq = new ConcurrentHashMap<String, AtomicInteger>();

    public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("usage: java TokenCount number-of-pages XML-file");
        System.exit(0);
    }
    System.out.println("Assignment4_3");
    Integer numPages = Integer.parseInt(args[0]);

    final int queueLength = 100;

    // print number of available processors
    System.out.println(Runtime.getRuntime().availableProcessors() + " available processors");
    int numProcessors = Runtime.getRuntime().availableProcessors();

    ArrayBlockingQueue<Page> sharedQueue = new ArrayBlockingQueue<Page>(queueLength);
    Thread th_producer = new Thread(new producer(sharedQueue, numPages, args[1]));
    ExecutorService pool = Executors.newCachedThreadPool();

/* begin timed code ... */
    final long before = System.nanoTime();
    th_producer.start();
    for (int i = 0; i < numProcessors - 1; ++i) {
        pool.execute(new consumer(sharedQueue, tokenFreq));
    }
    th_producer.join();
    pool.shutdown();
    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    final long after = System.nanoTime();
/* ... end  timed code */

    System.out.println("Time to process " + numPages + " pages = " + (after - before)/1000000 + " milliseconds");

    // sort tokenFreq by value & print top 30 most common tokens
    Set<Entry<String, AtomicInteger>> entries = tokenFreq.entrySet();
        ArrayList<Entry<String, AtomicInteger>> list = new ArrayList<Entry<String, AtomicInteger>>(entries);
        Collections.sort(list, new Comparator<Map.Entry<String, AtomicInteger>>()
              {
                  public int compare(Map.Entry<String, AtomicInteger> obj1, Map.Entry<String, AtomicInteger> obj2)
                  {
                  return (new Integer(obj2.getValue().get())).compareTo(new Integer(obj1.getValue().get()));
                  }
              } );
        System.out.println(list.size());
        for(int i=0; i<30; i++)
            System.out.println(list.get(i).getKey() + " appears " + list.get(i).getValue() + " times");
    }
}

class producer implements Runnable {
    private BlockingQueue<Page> sharedQueue;
    private String fileName;
    private Integer numPages;

    public producer(BlockingQueue<Page> q, Integer num, String f) {
        sharedQueue = q;
        numPages = num;
        fileName = f;
	}

	public void run() {
        Iterable<Page> allPages = new Pages(numPages, fileName);
        int numProcessors = Runtime.getRuntime().availableProcessors();
        try {
        	for (Page pg: allPages)
        		sharedQueue.put(pg);
            for (int i = 0; i < numProcessors - 1; ++i)
            	sharedQueue.put(new PoisonPill());
        } catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class consumer implements Runnable {
	private BlockingQueue<Page> sharedQueue;
	private ConcurrentHashMap<String, AtomicInteger> tokenFreq;

	public consumer(BlockingQueue<Page> q, ConcurrentHashMap<String, AtomicInteger> map) {
		sharedQueue = q;
		tokenFreq = map;
	}

	public void run() {
		try {
			while (true) {
				Page pg = sharedQueue.take();
				if (pg instanceof PoisonPill)
					break;
				Iterable<String> allTokens = new Words(pg.getText());
				for (String s : allTokens) {
					tokenFreq.putIfAbsent(s, new AtomicInteger(0));
					tokenFreq.get(s).incrementAndGet();
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


text:
<?php

   class Upload extends CI_Controller {

      public function __construct() {
         parent::__construct();
         $this->load->helper(array('form', 'url'));
      }

      public function index() {
         $this->load->view('upload_form', array('error' => ' ' ));
      }

      public function do_upload() {
         $config['upload_path']   = './uploads/';
         $config['allowed_types'] = 'gif|jpg|png';
         $config['max_size']      = 100;
         $config['max_width']     = 1024;
         $config['max_height']    = 768;
         $this->load->library('upload', $config);

         if ( ! $this->upload->do_upload('userfile')) {

             echo "File was not uploaded";

         }

         else {
            $this->load->view('upload_success');
         }
      }
   }
?>


text:
package me.mazeika.explodingkittens.game.states.lobby;

import com.google.inject.BindingAnnotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@BindingAnnotation
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Lobby { }


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

namespace Metis.ClientSdk.Entities
{
    internal class ApiCallEntity : LogEntity
    {
        public ApiCallEntity()
        {
            this.LogType = "api";
        }
        /// <summary>
        /// 调用AppId
        /// </summary>
        public int CallAppId { get; set; }
        /// <summary>
        /// 调用API的APP的AccessToken
        /// </summary>
        public string CallAccessToken { get; set; }
        /// <summary>
        /// 请求状态码
        /// </summary>
        public int StatusCode { get; set; }
        /// <summary>
        /// 调用地址
        /// </summary>
        public string CallUrl { get; set; }
        /// <summary>
        /// 响应时间(ms)
        /// </summary>
        public long ResponseTime { get; set; }
        /// <summary>
        /// 请求大小(byte)
        /// </summary>
        public long RequestSize { get; set; }
        /// <summary>
        /// 响应大小(byte)
        /// </summary>
        public long ResponseSize { get; set; }
    }
}