text:
#include <spine/CCSkeleton.h>
#include <spine/spine-cocos2dx.h>

USING_NS_CC;
using std::min;
using std::max;

namespace cocos2d { namespace extension {

CCSkeleton* CCSkeleton::createWithData (SkeletonData* skeletonData, bool ownsSkeletonData) {
	CCSkeleton* node = new CCSkeleton(skeletonData, ownsSkeletonData);
	node->autorelease();
	return node;
}

CCSkeleton* CCSkeleton::createWithFile (const char* skeletonDataFile, Atlas* atlas, float scale) {
	CCSkeleton* node = new CCSkeleton(skeletonDataFile, atlas, scale);
	node->autorelease();
	return node;
}

CCSkeleton* CCSkeleton::createWithFile (const char* skeletonDataFile, const char* atlasFile, float scale) {
	CCSkeleton* node = new CCSkeleton(skeletonDataFile, atlasFile, scale);
	node->autorelease();
	return node;
}

void CCSkeleton::initialize () {
	atlas = 0;
	debugSlots = false;
	debugBones = false;
	timeScale = 1;

	blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
	setOpacityModifyRGB(true);

	setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
	scheduleUpdate();
}

void CCSkeleton::setSkeletonData (SkeletonData *skeletonData, bool ownsSkeletonData) {
	skeleton = Skeleton_create(skeletonData);
	rootBone = skeleton->bones[0];
	this->ownsSkeletonData = ownsSkeletonData;
}

CCSkeleton::CCSkeleton () {
	initialize();
}

CCSkeleton::CCSkeleton (SkeletonData *skeletonData, bool ownsSkeletonData) {
	initialize();

	setSkeletonData(skeletonData, ownsSkeletonData);
}

CCSkeleton::CCSkeleton (const char* skeletonDataFile, Atlas* atlas, float scale) {
	initialize();

	SkeletonJson* json = SkeletonJson_create(atlas);
	json->scale = scale;
	SkeletonData* skeletonData = SkeletonJson_readSkeletonDataFile(json, skeletonDataFile);
	CCASSERT(skeletonData, json->error ? json->error : "Error reading skeleton data.");
	SkeletonJson_dispose(json);

	setSkeletonData(skeletonData, true);
}

CCSkeleton::CCSkeleton (const char* skeletonDataFile, const char* atlasFile, float scale) {
	initialize();

	atlas = Atlas_readAtlasFile(atlasFile);
	CCASSERT(atlas, "Error reading atlas file.");

	SkeletonJson* json = SkeletonJson_create(atlas);
	json->scale = scale;
	SkeletonData* skeletonData = SkeletonJson_readSkeletonDataFile(json, skeletonDataFile);
	CCASSERT(skeletonData, json->error ? json->error : "Error reading skeleton data file.");
	SkeletonJson_dispose(json);

	setSkeletonData(skeletonData, true);
}

CCSkeleton::~CCSkeleton () {
	if (ownsSkeletonData) SkeletonData_dispose(skeleton->data);
	if (atlas) Atlas_dispose(atlas);
	Skeleton_dispose(skeleton);
}

void CCSkeleton::update (float deltaTime) {
	Skeleton_update(skeleton, deltaTime * timeScale);
}

void CCSkeleton::draw () {
	CC_NODE_DRAW_SETUP();

	GL::blendFunc(blendFunc.src, blendFunc.dst);
	Color3B color = getColor();
	skeleton->r = color.r / (float)255;
	skeleton->g = color.g / (float)255;
	skeleton->b = color.b / (float)255;
	skeleton->a = getOpacity() / (float)255;
	if (premultipliedAlpha) {
		skeleton->r *= skeleton->a;
		skeleton->g *= skeleton->a;
		skeleton->b *= skeleton->a;
	}

	TextureAtlas* textureAtlas = 0;
	V3F_C4B_T2F_Quad quad;
	quad.tl.vertices.z = 0;
	quad.tr.vertices.z = 0;
	quad.bl.vertices.z = 0;
	quad.br.vertices.z = 0;
	for (int i = 0, n = skeleton->slotCount; i < n; i++) {
		Slot* slot = skeleton->slots[i];
		if (!slot->attachment || slot->attachment->type != ATTACHMENT_REGION) continue;
		RegionAttachment* attachment = (RegionAttachment*)slot->attachment;
		TextureAtlas* regionTextureAtlas = getTextureAtlas(attachment);
		if (regionTextureAtlas != textureAtlas) {
			if (textureAtlas) {
				textureAtlas->drawQuads();
				textureAtlas->removeAllQuads();
			}
		}
		textureAtlas = regionTextureAtlas;
		if (textureAtlas->getCapacity() == textureAtlas->getTotalQuads() &&
			!textureAtlas->resizeCapacity(textureAtlas->getCapacity() * 2)) return;
		RegionAttachment_updateQuad(attachment, slot, &quad, premultipliedAlpha);
		textureAtlas->updateQuad(&quad, textureAtlas->getTotalQuads());
	}
	if (textureAtlas) {
		textureAtlas->drawQuads();
		textureAtlas->removeAllQuads();
	}

	if (debugSlots) {
		// Slots.
		DrawPrimitives::setDrawColor4B(0, 0, 255, 255);
		glLineWidth(1);
		Point points[4];
		V3F_C4B_T2F_Quad quad;
		for (int i = 0, n = skeleton->slotCount; i < n; i++) {
			Slot* slot = skeleton->slots[i];
			if (!slot->attachment || slot->attachment->type != ATTACHMENT_REGION) continue;
			RegionAttachment* attachment = (RegionAttachment*)slot->attachment;
			RegionAttachment_updateQuad(attachment, slot, &quad);
			points[0] = Point(quad.bl.vertices.x, quad.bl.vertices.y);
			points[1] = Point(quad.br.vertices.x, quad.br.vertices.y);
			points[2] = Point(quad.tr.vertices.x, quad.tr.vertices.y);
			points[3] = Point(quad.tl.vertices.x, quad.tl.vertices.y);
			DrawPrimitives::drawPoly(points, 4, true);
		}
	}
	if (debugBones) {
		// Bone lengths.
		glLineWidth(2);
		DrawPrimitives::setDrawColor4B(255, 0, 0, 255);
		for (int i = 0, n = skeleton->boneCount; i < n; i++) {
			Bone *bone = skeleton->bones[i];
			float x = bone->data->length * bone->m00 + bone->worldX;
			float y = bone->data->length * bone->m10 + bone->worldY;
			DrawPrimitives::drawLine(Point(bone->worldX, bone->worldY), Point(x, y));
		}
		// Bone origins.
		DrawPrimitives::setPointSize(4);
		DrawPrimitives::setDrawColor4B(0, 0, 255, 255); // Root bone is blue.
		for (int i = 0, n = skeleton->boneCount; i < n; i++) {
			Bone *bone = skeleton->bones[i];
			DrawPrimitives::drawPoint(Point(bone->worldX, bone->worldY));
			if (i == 0) DrawPrimitives::setDrawColor4B(0, 255, 0, 255);
		}
	}
}

TextureAtlas* CCSkeleton::getTextureAtlas (RegionAttachment* regionAttachment) const {
	return (TextureAtlas*)((AtlasRegion*)regionAttachment->rendererObject)->page->rendererObject;
}

Rect CCSkeleton::getBoundingBox() const {
	float minX = FLT_MAX, minY = FLT_MAX, maxX = FLT_MIN, maxY = FLT_MIN;
	float scaleX = getScaleX();
	float scaleY = getScaleY();
	float vertices[8];
	for (int i = 0; i < skeleton->slotCount; ++i) {
		Slot* slot = skeleton->slots[i];
		if (!slot->attachment || slot->attachment->type != ATTACHMENT_REGION) continue;
		RegionAttachment* attachment = (RegionAttachment*)slot->attachment;
		RegionAttachment_computeVertices(attachment, slot->skeleton->x, slot->skeleton->y, slot->bone, vertices);
		minX = min(minX, vertices[VERTEX_X1] * scaleX);
		minY = min(minY, vertices[VERTEX_Y1] * scaleY);
		maxX = max(maxX, vertices[VERTEX_X1] * scaleX);
		maxY = max(maxY, vertices[VERTEX_Y1] * scaleY);
		minX = min(minX, vertices[VERTEX_X4] * scaleX);
		minY = min(minY, vertices[VERTEX_Y4] * scaleY);
		maxX = max(maxX, vertices[VERTEX_X4] * scaleX);
		maxY = max(maxY, vertices[VERTEX_Y4] * scaleY);
		minX = min(minX, vertices[VERTEX_X2] * scaleX);
		minY = min(minY, vertices[VERTEX_Y2] * scaleY);
		maxX = max(maxX, vertices[VERTEX_X2] * scaleX);
		maxY = max(maxY, vertices[VERTEX_Y2] * scaleY);
		minX = min(minX, vertices[VERTEX_X3] * scaleX);
		minY = min(minY, vertices[VERTEX_Y3] * scaleY);
		maxX = max(maxX, vertices[VERTEX_X3] * scaleX);
		maxY = max(maxY, vertices[VERTEX_Y3] * scaleY);
	}
	Point position = getPosition();
	return Rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY);
}

// --- Convenience methods for Skeleton_* functions.

void CCSkeleton::updateWorldTransform () {
	Skeleton_updateWorldTransform(skeleton);
}

void CCSkeleton::setToSetupPose () {
	Skeleton_setToSetupPose(skeleton);
}
void CCSkeleton::setBonesToSetupPose () {
	Skeleton_setBonesToSetupPose(skeleton);
}
void CCSkeleton::setSlotsToSetupPose () {
	Skeleton_setSlotsToSetupPose(skeleton);
}

Bone* CCSkeleton::findBone (const char* boneName) const {
	return Skeleton_findBone(skeleton, boneName);
}

Slot* CCSkeleton::findSlot (const char* slotName) const {
	return Skeleton_findSlot(skeleton, slotName);
}

bool CCSkeleton::setSkin (const char* skinName) {
	return Skeleton_setSkinByName(skeleton, skinName) ? true : false;
}

Attachment* CCSkeleton::getAttachment (const char* slotName, const char* attachmentName) const {
	return Skeleton_getAttachmentForSlotName(skeleton, slotName, attachmentName);
}
bool CCSkeleton::setAttachment (const char* slotName, const char* attachmentName) {
	return Skeleton_setAttachment(skeleton, slotName, attachmentName) ? true : false;
}

// --- BlendProtocol

const BlendFunc& CCSkeleton::getBlendFunc() const
{
    return blendFunc;
}

void CCSkeleton::setBlendFunc( const BlendFunc &blendFunc) {
    this->blendFunc = blendFunc;
}

void CCSkeleton::setOpacityModifyRGB (bool value) {
	premultipliedAlpha = value;
}

bool CCSkeleton::isOpacityModifyRGB () const {
	return premultipliedAlpha;
}

}} // namespace cocos2d { namespace extension {


text:
package galileo.event;

import java.io.IOException;

import galileo.net.GalileoMessage;
import galileo.net.NetworkDestination;

/**
 * Tracks the context of an event and allows retrieving event metadata.  Allows
 * replies to be sent directly to their originating source.
 *
 * @author malensek
 */
public class EventContext {

    private GalileoMessage message;
    private EventWrapper wrapper;

    public EventContext(GalileoMessage message, EventWrapper wrapper) {
        this.message = message;
        this.wrapper = wrapper;
    }

    /**
     * Send a reply back to the source that created the original event.
     */
    public void sendReply(Event e)
    throws IOException {
        GalileoMessage m = wrapper.wrap(e);
        this.message.getContext().sendMessage(m);
    }

    /**
     * @return Server port number that this event was sent to.
     */
    public int getServerPort() {
        return message.getContext().getServerPort();
    }

    /**
     * @return NetworkDestination of the client that generated the event.
     */
    public NetworkDestination getSource() {
        return message.getContext().getSource();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Projeto TO DO LIST</title>

    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/offcanvas.css" rel="stylesheet">
    <link href="css/estilo.css" rel="stylesheet">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

              </button>
              TO DO LIST

Inicio

TO DO

Sobre

Configurações

                        <button type="button" class="btn btn-primary btn-xs" data-toggle="offcanvas">
                            Toggle nav
                        </button>

Minhas Tarefas!

                                Adicionar
                                Remover

                                        #
                                        Tarefa

                                        1
                                        Cortar a Grama

                                        2
                                        Lavar o Carro

                                        3
                                        Catar Coquinho

                            Tudo

                            Hoje

                            Próximos 7 dias

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Nova Tarefa

Topo

© 2014 Company, Inc. ·


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.1.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-4.1.xsd
    http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"
     default-lazy-init="false">

	<bean id="myjdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="casDataSource"/>
	</bean>

	<!-- 事务配置 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="druidDataSource" />
	</bean>

	<bean id="userSupDao" class="org.jasig.cas.thrift.server.UserSupDao">
		<property name="myjdbcTemplate" ref="myjdbcTemplate"/>
	</bean>

</beans>


text:
/**
 * @module node-opcua-address-space.Private
 */
import { assert } from "node-opcua-assert";
import * as _ from "underscore";
import * as util from "util";

import { BinaryStream, OutputBinaryStream } from "node-opcua-binary-stream";
import { BrowseDirection, NodeClass, QualifiedName } from "node-opcua-data-model";
import {checkDebugFlag, make_debugLog} from "node-opcua-debug";
import {
    BaseUAObject, FieldCategory,
    findBuiltInType,
    initialize_field
} from "node-opcua-factory";
import { DataTypeFactory } from "node-opcua-factory";
// import {     getEnumeration,getConstructor, hasConstructor } from "node-opcua-factory";
import { NodeId, resolveNodeId } from "node-opcua-nodeid";
import { StatusCodes } from "node-opcua-status-code";
import { lowerFirstLetter } from "node-opcua-utils";
import { Variant } from "node-opcua-variant";
import { DataType } from "node-opcua-variant";
import { VariantArrayType } from "node-opcua-variant";

import { ExtensionObject } from "node-opcua-extension-object";
import {
    AddressSpace,
    UADynamicVariableArray,
    UAObject,
    UAReferenceType,
    UAVariable as UAVariablePublic} from "../source/address_space_ts";

import { AddressSpacePrivate } from "./address_space_private";
import { UADataType } from "./ua_data_type";
import { UAVariable } from "./ua_variable";

const doDebug = checkDebugFlag(__filename);
const debugLog = make_debugLog(__filename);

function makeStructure(
    dataTypeFactory: DataTypeFactory,
    dataType: UADataType,
    bForce?: boolean
): any {

    bForce = !!bForce;
    const addressSpace = dataType.addressSpace;

    // istanbul ignore next
    if (!dataType.binaryEncodingNodeId) {
        throw new Error("DataType with name " + dataType.browseName.toString() +
          " has no binaryEncoding node\nplease check your nodeset file");
    }

    // if binaryEncodingNodeId is in the standard factory => no need to overwrite
    if (!bForce && (dataTypeFactory.hasConstructor(dataType.binaryEncodingNodeId) || dataType.binaryEncodingNodeId.namespace === 0)) {
        return dataTypeFactory.getConstructor(dataType.binaryEncodingNodeId);
    }

    // istanbul ignore next
    if (doDebug) {
        debugLog("buildConstructorFromDefinition => ", dataType.browseName.toString());
    }
    // etc ..... please fix me
    const namespaceUri = addressSpace.getNamespaceUri(dataType.nodeId.namespace);
    return buildConstructorFromDefinition(addressSpace, dataType);
}

function _extensionobject_construct(this: any, options: any): void {

    options = options || {};
    const dataType = this.constructor.dataType;
    const obj = this;

    for (const field of dataType.definition) {
        const fieldName = field.$$name$$;
        obj[fieldName] = field.$$initialize$$(options[fieldName]);
    }
}

(global as any)._extensionobject_construct = _extensionobject_construct;

function initialize_Structure(field: any, options: any): any {
    return new field.$$Constructor$$(options);
}

function _extensionobject_encode(this: any, stream: OutputBinaryStream) {

    BaseUAObject.prototype.encode.call(this, stream);
    const definition = this.constructor.dataType.definition;
    for (const field of definition) {
        const fieldName = field.$$name$$;
        field.$$func_encode$$.call(this[fieldName], stream);
    }
}

function struct_encode(this: any, stream: OutputBinaryStream) {
    this.encode(stream);
}

function struct_decode(this: any, stream: BinaryStream) {
    this.decode(stream);
    return this;
}

function _extensionobject_decode(this: any, stream: BinaryStream) {
    const definition = this.constructor.definition;
    assert(definition, "expected a definition for this class ");
    for (const field of definition) {
        const fieldName = field.$$name$$;
        this[fieldName] = field.$$func_decode$$.call(this[fieldName], stream);
    }
}

function initialize_array(func: any, options: any[]) {
    options = options || [];
    const result = options.map((element: any) => func(element));
    return result;
}

function encode_array(
  fun_encode_element: (el: any, stream: OutputBinaryStream) => void,
  arr: any[],
  stream: BinaryStream
) {
    stream.writeUInt32(arr.length);
    for (const el of arr) {
        fun_encode_element(el, stream);
    }
}

function decode_array(
  fun_decode_element: (stream: BinaryStream) => any,
  arr: any[],
  stream: BinaryStream
): any[] | null {
    const n = stream.readUInt32();
    if (n === 0xFFFFFFFF) {
        return null;
    }
    const result = [];
    for (let i = 0; i < n; i++) {
        result.push(fun_decode_element(stream));
    }
    return result;
}

function buildConstructorFromDefinition(
  addressSpace: AddressSpace,
  dataType: UADataType
) {

    if (doDebug) {
        debugLog("buildConstructorFromDefinition nodeId=", dataType.nodeId.toString(), dataType.browseName.toString());
    }

    const extraDataTypeManager = (addressSpace as AddressSpacePrivate).getDataTypeManager();
    const dataTypeFactory = extraDataTypeManager.getDataTypeFactory(dataType.nodeId.namespace);

    assert(dataType.definition && _.isArray(dataType.definition));
    const enumeration = addressSpace.findDataType("Enumeration");

    const className = dataType.browseName.name!.replace("DataType", "");

    assert(enumeration, "Enumeration Type not found: please check your nodeset file");
    const structure = addressSpace.findDataType("Structure");
    assert(structure, "Structure Type not found: please check your nodeset file");

    const Constructor = new Function("options", "_extensionobject_construct.apply(this,arguments);");
    assert(_.isFunction(Constructor));
    Object.defineProperty(Constructor, "name", { value: className });

    (Constructor as any).definition = dataType.definition;
    (Constructor as any).dataType = dataType;
    util.inherits(Constructor, ExtensionObject);
    Constructor.prototype.encode = _extensionobject_encode;
    Constructor.prototype.decode = _extensionobject_decode;

    for (const field of dataType.definition) {

        if (field.valueRank === 1) {
            field.$$name$$ = lowerFirstLetter(field.name.replace("ListOf", ""));
        } else {
            field.$$name$$ = lowerFirstLetter(field.name);
        }
        const dataTypeId = resolveNodeId(field.dataType);
        const fieldDataType = addressSpace.findDataType(dataTypeId) as UADataType;
        if (!fieldDataType) {
            debugLog(field);
            throw new Error(" cannot find description for object " + dataTypeId +
              " => " + field.dataType + ". Check that this node exists in the nodeset.xml file");
        }
        // check if  dataType is an enumeration or a structure or  a basic type
        field.$$dataTypeId$$ = dataTypeId;
        field.$$dataType$$ = fieldDataType;
        field.$$isEnum$$ = false;
        field.$$isStructure$$ = false;
        if (fieldDataType.isSupertypeOf(enumeration as any)) {
            field.$$isEnum$$ = true;
            // todo repair
            // makeEnumeration(fieldDataType);
        } else if (fieldDataType.isSupertypeOf(structure as any)) {
            field.$$isStructure$$ = true;
            const FieldConstructor = makeStructure(dataTypeFactory, fieldDataType);
            assert(_.isFunction(FieldConstructor));
            // xx field
            field.$$func_encode$$ = struct_encode;
            field.$$func_decode$$ = struct_decode;
            field.$$Constructor$$ = FieldConstructor;
            field.$$initialize$$ = initialize_Structure.bind(null, field);
        } else {
            const stuff = findBuiltInType(fieldDataType.browseName.name);
            field.$$func_encode$$ = stuff.encode;
            field.$$func_decode$$ = stuff.decode;
            assert(_.isFunction(field.$$func_encode$$));
            assert(_.isFunction(field.$$func_decode$$));
            field.schema = stuff;
            field.$$initialize$$ = initialize_field.bind(null, field);
        }
        if (field.valueRank === 1) {
            field.$$initialize$$ = initialize_array.bind(null, field.$$initialize$$);
            field.$$func_encode$$ = encode_array.bind(null, field.$$func_encode$$);
            field.$$func_decode$$ = decode_array.bind(null, field.$$func_decode$$);
        }
    }

    // reconstruct _schema form
    const fields = [];
    for (const field of dataType.definition) {
        const data: any = {
            fieldType: field.$$dataType$$.browseName.name,
            isArray: (field.valueRank === 1),
            name: field.$$name$$
        };
        if (field.$$isEnum$$) {
            data.category = FieldCategory.enumeration;
        } else if (field.$$isStructure$$) {
            data.category = FieldCategory.complex;
            data.fieldTypeConstructor = field.$$Constructor$$;
        } else {
            data.category = FieldCategory.basic;
        }
        fields.push(data);
    }

    Constructor.prototype.schema = {
        fields,
        id: -1,
        name: className
    };
    return Constructor;
}

/*
 * define a complex Variable containing a array of extension objects
 * each element of the array is also accessible as a component variable.
 *
 */

function getExtObjArrayNodeValue(
  this: any
) {
    return new Variant({
        arrayType: VariantArrayType.Array,
        dataType: DataType.ExtensionObject,
        value: this.$$extensionObjectArray
    });
}

function removeElementByIndex<T extends ExtensionObject>(
  uaArrayVariableNode: UADynamicVariableArray<T>,
  elementIndex: number
) {

    const _array = uaArrayVariableNode.$$extensionObjectArray;

    assert(_.isNumber(elementIndex));

    const addressSpace = uaArrayVariableNode.addressSpace;
    const extObj = _array[elementIndex];
    const browseName = uaArrayVariableNode.$$getElementBrowseName(extObj);

    // remove element from global array (inefficient)
    uaArrayVariableNode.$$extensionObjectArray.splice(elementIndex, 1);

    // remove matching component
    const node = uaArrayVariableNode.getComponentByName(browseName);
    if (!node) {
        throw new Error(" cannot find component ");
    }

    const hasComponent =
      uaArrayVariableNode.addressSpace.findReferenceType("HasComponent")! as UAReferenceType;

    // remove the hasComponent reference toward node
    uaArrayVariableNode.removeReference({
        isForward: true,
        nodeId: node.nodeId,
        referenceType: hasComponent.nodeId
    });

    // now check if node has still some parent
    const parents = node.findReferencesEx("HasChild", BrowseDirection.Inverse);
    if (parents.length === 0) {
        addressSpace.deleteNode(node.nodeId);
    }
}

/**
 * @method prepareDataType
 * @private
 * @param dataType
 */
export function prepareDataType(
    addressSpace: AddressSpace,
    dataType: UADataType
): void {

    if (!dataType._extensionObjectConstructor) {

        const extraDataTypeManager = (addressSpace as AddressSpacePrivate).getDataTypeManager();
        const dataTypeFactory = extraDataTypeManager.getDataTypeFactory(dataType.nodeId.namespace);
        if (doDebug) {
            debugLog("prepareDataType ", dataType.nodeId.toString() , dataType.browseName.toString());
        }
        dataType._extensionObjectConstructor = makeStructure(dataTypeFactory, dataType);
        if (!dataType._extensionObjectConstructor) {
            // tslint:disable:no-console
            console.warn("AddressSpace#constructExtensionObject : cannot make structure for " + dataType.toString());
        }
    }
}
/**
 *
 * create a node Variable that contains a array of ExtensionObject of a given type
 * @method createExtObjArrayNode
 * @param parentFolder
 * @param options
 * @param options.browseName
 * @param options.complexVariableType
 * @param options.variableType        the type of Extension objects stored in the array.
 * @param options.indexPropertyName
 * @return {Object|UAVariable}
 */
export function createExtObjArrayNode<T extends ExtensionObject>(
  parentFolder: UAObject,
  options: any
): UADynamicVariableArray<T> {

    assert(typeof options.variableType === "string");
    assert(typeof options.indexPropertyName === "string");

    const addressSpace = parentFolder.addressSpace;
    const namespace = parentFolder.namespace;

    const complexVariableType = addressSpace.findVariableType(options.complexVariableType);
    if (!complexVariableType) {
        throw new Error("cannot find complex variable type");
    }
    assert(!complexVariableType.nodeId.isEmpty());

    const variableType = addressSpace.findVariableType(options.variableType);
    if (!variableType) {
        throw new Error("cannot find variable Type");
    }
    assert(!variableType.nodeId.isEmpty());

    const structure = addressSpace.findDataType("Structure");
    assert(structure, "Structure Type not found: please check your nodeset file");

    const dataType = addressSpace.findDataType(variableType.dataType);
    if (!dataType) {
        throw new Error("cannot find Data Type");
    }

    assert(dataType.isSupertypeOf(structure as any), "expecting a structure (= ExtensionObject) here ");

    const inner_options = {

        componentOf: parentFolder,

        browseName: options.browseName,
        dataType: dataType.nodeId,
        typeDefinition: complexVariableType.nodeId,
        value: { dataType: DataType.ExtensionObject, value: [], arrayType: VariantArrayType.Array },
        valueRank: 1
    };

    const uaArrayVariableNode = namespace.addVariable(inner_options) as UADynamicVariableArray<T>;

    bindExtObjArrayNode(
      uaArrayVariableNode,
      options.variableType,
      options.indexPropertyName);

    return uaArrayVariableNode;

}

/**
 * @method bindExtObjArrayNode
 * @param uaArrayVariableNode
 * @param variableTypeNodeId
 * @param indexPropertyName
 * @return
 */
export function bindExtObjArrayNode<T extends ExtensionObject>(
  uaArrayVariableNode: UADynamicVariableArray<T>,
  variableTypeNodeId: string | NodeId,
  indexPropertyName: string
): UAVariablePublic {

    const addressSpace = uaArrayVariableNode.addressSpace;

    const variableType = addressSpace.findVariableType(variableTypeNodeId);
    if (!variableType) {
        throw new Error("Cannot find VariableType " + variableTypeNodeId.toString());
    }
    assert(!variableType.nodeId.isEmpty());

    let structure = addressSpace.findDataType("Structure");
    assert(structure, "Structure Type not found: please check your nodeset file");

    let dataType = addressSpace.findDataType(variableType.dataType);
    if (!dataType) {
        throw new Error("Cannot find DataType " + variableType.dataType.toString());
    }
    assert(dataType.isSupertypeOf(structure as any), "expecting a structure (= ExtensionObject) here ");

    assert(!uaArrayVariableNode.$$variableType, "uaArrayVariableNode has already been bound !");

    uaArrayVariableNode.$$variableType = variableType;

    structure = addressSpace.findDataType("Structure");
    assert(structure, "Structure Type not found: please check your nodeset file");

    // verify that an object with same doesn't already exist
    dataType = addressSpace.findDataType(variableType.dataType)! as UADataType;
    assert(dataType.isSupertypeOf(structure as any), "expecting a structure (= ExtensionObject) here ");

    uaArrayVariableNode.$$dataType = dataType as UADataType;
    uaArrayVariableNode.$$extensionObjectArray = [];
    uaArrayVariableNode.$$indexPropertyName = indexPropertyName;

    prepareDataType(addressSpace, dataType as UADataType);

    uaArrayVariableNode.$$getElementBrowseName = function(this: any, extObj: ExtensionObject) {

        const indexPropertyName1 = this.$$indexPropertyName;

        if (!extObj.hasOwnProperty(indexPropertyName1)) {
            console.log(" extension object do not have ", indexPropertyName1, extObj);
        }
        // assert(extObj.constructor === addressSpace.constructExtensionObject(dataType));
        assert(extObj.hasOwnProperty(indexPropertyName1));
        const browseName = (extObj as any)[indexPropertyName1].toString();
        return browseName;
    };

    const options = {
        get: getExtObjArrayNodeValue,
        set: undefined // readonly
    };

    // bind the readonly
    uaArrayVariableNode.bindVariable(options, true);

    return uaArrayVariableNode;
}

/**
 * @method addElement
 * add a new element in a ExtensionObject Array variable
 * @param options {Object}   data used to construct the underlying ExtensionObject
 * @param uaArrayVariableNode {UAVariable}
 * @return {UAVariable}
 *
 * @method addElement
 * add a new element in a ExtensionObject Array variable
 * @param nodeVariable a variable already exposing an extension objects
 * @param uaArrayVariableNode {UAVariable}
 * @return {UAVariable}
 *
 * @method addElement
 * add a new element in a ExtensionObject Array variable
 * @param constructor  constructor of the extension object to create
 * @param uaArrayVariableNode {UAVariable}
 * @return {UAVariable}
 */
export function addElement<T extends ExtensionObject>(
  options: any /* ExtensionObjectConstructor | ExtensionObject | UAVariable*/,
  uaArrayVariableNode: UADynamicVariableArray<T>
): UAVariable {

    assert(uaArrayVariableNode, " must provide an UAVariable containing the array");
     // verify that arr has been created correctly
    assert(!!uaArrayVariableNode.$$variableType && !!uaArrayVariableNode.$$dataType,
      "did you create the array Node with createExtObjArrayNode ?");
    assert(uaArrayVariableNode.$$dataType.nodeClass === NodeClass.DataType);
    assert((uaArrayVariableNode.$$dataType as UADataType)._extensionObjectConstructor instanceof Function);

    const addressSpace = uaArrayVariableNode.addressSpace;

    let extensionObject: T;
    let elVar = null;
    let browseName;

    if (options instanceof UAVariable) {
        elVar = options;
        extensionObject = elVar.$extensionObject; // get shared extension object
        assert(extensionObject instanceof (uaArrayVariableNode.$$dataType as UADataType)._extensionObjectConstructor,
          "the provided variable must expose a Extension Object of the expected type ");
        // add a reference
        uaArrayVariableNode.addReference({
            isForward: true,
            nodeId: elVar.nodeId,
            referenceType: "HasComponent"
        });
        // xx elVar.bindExtensionObject();

    } else {
        if (options instanceof (uaArrayVariableNode.$$dataType as UADataType)._extensionObjectConstructor) {
            // extension object has already been created
            extensionObject = options as T;
        } else {
            extensionObject = addressSpace.constructExtensionObject(uaArrayVariableNode.$$dataType, options) as T;
        }
        browseName = uaArrayVariableNode.$$getElementBrowseName(extensionObject);
        elVar = uaArrayVariableNode.$$variableType.instantiate({
            browseName,
            componentOf: uaArrayVariableNode.nodeId,
            value: { dataType: DataType.ExtensionObject, value: extensionObject }
        }) as UAVariable;
        elVar.bindExtensionObject();
        elVar.$extensionObject = extensionObject;
    }

    // also add the value inside
    uaArrayVariableNode.$$extensionObjectArray.push(extensionObject);

    return elVar;
}

/**
 *
 * @method removeElement
 * @param uaArrayVariableNode {UAVariable}
 * @param element {number}   index of element to remove in array
 *
 *
 * @method removeElement
 * @param uaArrayVariableNode {UAVariable}
 * @param element {UAVariable}   node of element to remove in array
 *
 * @method removeElement
 * @param uaArrayVariableNode {UAVariable}
 * @param element {ExtensionObject}   extension object of the node of element to remove in array
 *
 */
export function removeElement<T extends ExtensionObject>(
  uaArrayVariableNode: UADynamicVariableArray<T>,
  element: any /* number | UAVariable | (a any) => boolean | ExtensionObject */
): void {

    assert(element, "element must exist");
    const _array = uaArrayVariableNode.$$extensionObjectArray;
    if (_array.length === 0) {
        throw new Error(" cannot remove an element from an empty array ");
    }
    let elementIndex = -1;

    if (_.isNumber(element)) {

        // find element by index
        elementIndex = element;
        assert(elementIndex >= 0 && elementIndex < _array.length);

    } else if (element && element.nodeClass ) {

        // find element by name
        const browseNameToFind = element.browseName.name!.toString();
        elementIndex = _array.findIndex((obj: any, i: number) => {
            const browseName = uaArrayVariableNode.$$getElementBrowseName(obj).toString();
            return (browseName === browseNameToFind);
        });

    } else if (_.isFunction(element)) {

        // find element by functor
        elementIndex = _array.findIndex(element);

    } else {

        // find element by inner extension object
        assert(_array[0].constructor.name === (element as any).constructor.name, "element must match");
        elementIndex = _array.findIndex((x: any) => x === element);
    }
    if (elementIndex < 0) {
        throw new Error(" cannot find element matching " + element.toString());
    }
    return removeElementByIndex(uaArrayVariableNode, elementIndex);
}


text:
package org.newdawn.slick.geom;

/**
 * A beizer curve implementation. The curve is defined by a start point, an end point
 * and two control points that it will tend towards. This is implementation is fixed
 * segmenting meaning it doesn't scale too well.
 *
 * @author kevin
 */
public class Curve extends Shape {
	/** The start point of the curve */
	private Vector2f p1;
	/** The first control point */
	private Vector2f c1;
	/** The second control point */
	private Vector2f c2;
	/** The end point of the curve */
	private Vector2f p2;
	/** The number of lines segments the curve is built out of */
	private int segments;

	/**
	 * Create a new curve with the default segments (20)
	 *
	 * @param p1 The start of the curve
	 * @param c1 The first control point
	 * @param c2 The second control point
	 * @param p2 The end of the curve
	 */
	public Curve(Vector2f p1, Vector2f c1, Vector2f c2, Vector2f p2) {
		this(p1,c1,c2,p2,20);
	}

	/**
	 * Create a new curve
	 *
	 * @param p1 The start of the curve
	 * @param c1 The first control point
	 * @param c2 The second control point
	 * @param p2 The end of the curve
	 * @param segments The number of segments to use
	 */
	public Curve(Vector2f p1, Vector2f c1, Vector2f c2, Vector2f p2, int segments) {
		this.p1 = new Vector2f(p1);
		this.c1 = new Vector2f(c1);
		this.c2 = new Vector2f(c2);
		this.p2 = new Vector2f(p2);

		this.segments = segments;
		pointsDirty = true;
	}

	/**
	 * Get the point at a particular location on the curve
	 *
	 * @param t A value between 0 and 1 defining the location of the curve the point is at
	 * @return The point on the curve
	 */
	public Vector2f pointAt(float t) {
		float a = 1 - t;
		float b = t;

		float f1 = a * a * a;
		float f2 = 3 * a * a * b;
		float f3 = 3 * a * b * b;
		float f4 = b * b * b;

		float nx = (p1.x * f1) + (c1.x * f2) + (c2.x * f3) + (p2.x * f4);
		float ny = (p1.y * f1) + (c1.y * f2) + (c2.y * f3) + (p2.y * f4);

		return new Vector2f(nx,ny);
	}

	/**
	 * @see org.newdawn.slick.geom.Shape#createPoints()
	 */
	protected void createPoints() {
		float step = 1.0f / segments;
		points = new float[(segments+1) * 2];
		for (int i=0;i<segments+1;i++) {
			float t = i * step;

			Vector2f p = pointAt(t);
			points[i*2] = p.x;
			points[(i*2)+1] = p.y;
		}
	}

	/**
	 * @see org.newdawn.slick.geom.Shape#transform(org.newdawn.slick.geom.Transform)
	 */
	public Shape transform(Transform transform) {
		float[] pts = new float[8];
		float[] dest = new float[8];
		pts[0] = p1.x; pts[1] = p1.y;
		pts[2] = c1.x; pts[3] = c1.y;
		pts[4] = c2.x; pts[5] = c2.y;
		pts[6] = p2.x; pts[7] = p2.y;
		transform.transform(pts, 0, dest, 0, 4);

		return new Curve(new Vector2f(dest[0],dest[1]), new Vector2f(dest[2],dest[3]),
						 new Vector2f(dest[4],dest[5]), new Vector2f(dest[6],dest[7]));
	}

    /**
     * True if this is a closed shape
     *
     * @return True if this is a closed shape
     */
    public boolean closed() {
    	return false;
    }
}


text:
Pattern: Malformed PHP `filter_*` function

Issue: -

## Description

Ensures that proper sanitization is occurring when PHP's `filter_*` functions are used.

## Further Reading

* [WordPressVIPMinimum.Security.PHPFilterFunctions](https://github.com/Automattic/VIP-Coding-Standards/tree/develop/WordPressVIPMinimum/Sniffs/Security/PHPFilterFunctionsSniff.php)


text:
import {createStore} from 'redux';
import {combineForms} from 'react-redux-form';

const outputInitialState = {value: 'No Data'};

const outputReducer = (state = outputInitialState, payload) => {
    switch(payload.type) {
        case 'DATA_LOADED': {
            const {data, type} = payload.response;
            return {data, type};
        }
        case 'DATA_ERROR': {
            return {data: payload.error};
        }
        default: {
            return state;
        }
    }
};

export default createStore(combineForms({
    search: {
        url: 'http://www.reddit.com/r/javascript/.json',
        sort: {
            field: 'count',
            direction: 'desc'
        },
        output: {type: 'csv'}
    },
    output: outputReducer
}));


text:
namespace mojo {
namespace dart {

Dart_NativeFunction MojoIoNativeLookup(Dart_Handle name,
                                     int argument_count,
                                     bool* auto_setup_scope);

const uint8_t* MojoIoNativeSymbol(Dart_NativeFunction nf);

}  // namespace dart
}  // namespace mojo

#endif  // MOJO_DART_EMBEDDER_MOJO_IO_NATIVES_H_


text:
package it.sephiroth.android.library.imagezoom;

import it.sephiroth.android.library.imagezoom.easing.Cubic;
import it.sephiroth.android.library.imagezoom.easing.Easing;
import it.sephiroth.android.library.imagezoom.graphics.FastBitmapDrawable;
import it.sephiroth.android.library.imagezoom.utils.IDisposable;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

/**
 * Base View to manage image zoom/scrool/pinch operations
 *
 * @author alessandro
 *
 */
public class ImageViewTouchBase extends ImageView implements IDisposable {

	public interface OnBitmapChangedListener {

		void onBitmapChanged( Drawable drawable );
	};

	public static final String LOG_TAG = "image";

	protected static final float MIN_ZOOM = 0.9f;
	protected Easing mEasing = new Cubic();
	protected Matrix mBaseMatrix = new Matrix();
	protected Matrix mSuppMatrix = new Matrix();
	protected Handler mHandler = new Handler();
	protected Runnable mOnLayoutRunnable = null;
	protected float mMaxZoom;
	protected float mMinZoom = -1;
	protected final Matrix mDisplayMatrix = new Matrix();
	protected final float[] mMatrixValues = new float[9];
	protected int mThisWidth = -1, mThisHeight = -1;
	protected boolean mFitToScreen = false;
	final protected float MAX_ZOOM = 2.0f;
	final protected int DEFAULT_ANIMATION_DURATION = 200;

	protected RectF mBitmapRect = new RectF();
	protected RectF mCenterRect = new RectF();
	protected RectF mScrollRect = new RectF();

	private OnBitmapChangedListener mListener;

	public ImageViewTouchBase( Context context ) {
		super( context );
		init();
	}

	public ImageViewTouchBase( Context context, AttributeSet attrs ) {
		super( context, attrs );
		init();
	}

	public void setOnBitmapChangedListener( OnBitmapChangedListener listener ) {
		mListener = listener;
	}

	protected void init() {
		setScaleType( ImageView.ScaleType.MATRIX );
	}

	public void clear() {
		setImageBitmap( null, true );
	}

	public void setFitToScreen( boolean value ) {
		if ( value != mFitToScreen ) {
			mFitToScreen = value;
			requestLayout();
		}
	}

	public void setMinZoom( float value ) {
		Log.d( LOG_TAG, "minZoom: " + value );
		mMinZoom = value;
	}

	@Override
	protected void onLayout( boolean changed, int left, int top, int right, int bottom ) {
		super.onLayout( changed, left, top, right, bottom );
		mThisWidth = right - left;
		mThisHeight = bottom - top;
		Runnable r = mOnLayoutRunnable;
		if ( r != null ) {
			mOnLayoutRunnable = null;
			r.run();
		}
		if ( getDrawable() != null ) {
			if ( mFitToScreen ) {
				getProperBaseMatrix2( getDrawable(), mBaseMatrix );
				setMinZoom( 1.0f );
			} else {
				getProperBaseMatrix( getDrawable(), mBaseMatrix );
				setMinZoom( getMinZoom() );
			}
			setImageMatrix( getImageViewMatrix() );
			zoomTo( getMinZoom() );
		}
	}

	@Override
	public void setImageBitmap( Bitmap bm ) {
		setImageBitmap( bm, true );
	}

	@Override
	public void setImageResource( int resId ) {
		setImageDrawable( getContext().getResources().getDrawable( resId ) );
	}

	/**
	 * Set the new image to display and reset the internal matrix.
	 *
	 * @param bitmap
	 *           - the {@link Bitmap} to display
	 * @param reset
	 *           - if true the image bounds will be recreated, otherwise the old {@link Matrix} is used to display the new bitmap
	 * @see #setImageBitmap(Bitmap)
	 */
	public void setImageBitmap( final Bitmap bitmap, final boolean reset ) {
		setImageBitmap( bitmap, reset, null );
	}

	/**
	 * Similar to {@link #setImageBitmap(Bitmap, boolean)} but an optional view {@link Matrix} can be passed to determine the new
	 * bitmap view matrix.<br />
	 * This method is useful if you need to restore a Bitmap with the same zoom/pan values from a previous state
	 *
	 * @param bitmap
	 *           - the {@link Bitmap} to display
	 * @param reset
	 * @param matrix
	 *           - the {@link Matrix} to be used to display the new bitmap
	 *
	 * @see #setImageBitmap(Bitmap, boolean)
	 * @see #setImageBitmap(Bitmap)
	 * @see #getImageViewMatrix()
	 * @see #getDisplayMatrix()
	 */
	public void setImageBitmap( final Bitmap bitmap, final boolean reset, Matrix matrix ) {
		setImageBitmap( bitmap, reset, matrix, -1 );
	}

	/**
	 *
	 * @param bitmap
	 * @param reset
	 * @param matrix
	 * @param maxZoom
	 *           - maximum zoom allowd during zoom gestures
	 *
	 * @see #setImageBitmap(Bitmap, boolean, Matrix)
	 */
	public void setImageBitmap( final Bitmap bitmap, final boolean reset, Matrix matrix, float maxZoom ) {

		if ( bitmap != null )
			setImageDrawable( new FastBitmapDrawable( bitmap ), reset, matrix, maxZoom );
		else
			setImageDrawable( null, reset, matrix, maxZoom );
	}

	@Override
	public void setImageDrawable( Drawable drawable ) {
		setImageDrawable( drawable, true, null, -1 );
	}

	public void setImageDrawable( final Drawable drawable, final boolean reset, final Matrix initial_matrix, final float maxZoom ) {

		final int viewWidth = getWidth();

		if ( viewWidth <= 0 ) {
			mOnLayoutRunnable = new Runnable() {

				@Override
				public void run() {
					setImageDrawable( drawable, reset, initial_matrix, maxZoom );
				}
			};
			return;
		}

		_setImageDrawable( drawable, reset, initial_matrix, maxZoom );
	}

	protected void _setImageDrawable( final Drawable drawable, final boolean reset, final Matrix initial_matrix, final float maxZoom ) {

		if ( drawable != null ) {
			if ( mFitToScreen ) {
				getProperBaseMatrix2( drawable, mBaseMatrix );
				setMinZoom( getScale( mBaseMatrix ) );
			} else {
				getProperBaseMatrix( drawable, mBaseMatrix );
				setMinZoom( getMinZoom() );
			}
			super.setImageDrawable( drawable );
		} else {
			mBaseMatrix.reset();
			super.setImageDrawable( null );
		}

		if ( reset ) {
			mSuppMatrix.reset();
			if ( initial_matrix != null ) {
				mSuppMatrix = new Matrix( initial_matrix );
			}
		}

		setImageMatrix( getImageViewMatrix() );

		if ( maxZoom < 1 )
			mMaxZoom = maxZoom();
		else
			mMaxZoom = maxZoom;

		onBitmapChanged( drawable );
	}

	protected void onBitmapChanged( final Drawable bitmap ) {
		if ( mListener != null ) {
			mListener.onBitmapChanged( bitmap );
		}
	}

	/**
	 * compute the max allowed zoom fator
	 *
	 * @return
	 */
	protected float maxZoom() {
		final Drawable drawable = getDrawable();

		if ( drawable == null ) {
			return 1F;
		}

		float fw = (float) drawable.getIntrinsicWidth() / (float) mThisWidth;
		float fh = (float) drawable.getIntrinsicHeight() / (float) mThisHeight;
		float max = Math.max( fw, fh ) * 4;
		return max;
	}

	protected float minZoom() {
		return 1F;
	}

	public float getMaxZoom() {
		if ( mMaxZoom < 1 ) {
			mMaxZoom = maxZoom();
		}
		return mMaxZoom;
	}

	public float getMinZoom() {
		if ( mMinZoom < 0 ) {
			mMinZoom = minZoom();
		}
		return mMinZoom;
	}

	public Matrix getImageViewMatrix() {
		return getImageViewMatrix( mSuppMatrix );
	}

	public Matrix getImageViewMatrix( Matrix supportMatrix ) {
		mDisplayMatrix.set( mBaseMatrix );
		mDisplayMatrix.postConcat( supportMatrix );
		return mDisplayMatrix;
	}

	/**
	 * Returns the current image display matrix. This matrix can be used in the next call to the
	 * {@link #setImageBitmap(Bitmap, boolean, Matrix)} to restore the same view state of the previous {@link Bitmap}
	 *
	 * @return
	 */
	public Matrix getDisplayMatrix() {
		return new Matrix( mSuppMatrix );
	}

	/**
	 * Setup the base matrix so that the image is centered and scaled properly.
	 *
	 * @param bitmap
	 * @param matrix
	 */
	protected void getProperBaseMatrix( Drawable drawable, Matrix matrix ) {
		Log.i( LOG_TAG, "getProperBaseMatrix" );
		float viewWidth = getWidth();
		float viewHeight = getHeight();
		float w = drawable.getIntrinsicWidth();
		float h = drawable.getIntrinsicHeight();
		matrix.reset();

		if ( w > viewWidth || h > viewHeight ) {
			float widthScale = Math.min( viewWidth / w, 2.0f );
			float heightScale = Math.min( viewHeight / h, 2.0f );
			float scale = Math.min( widthScale, heightScale );
			Log.d( LOG_TAG, "scale: " + scale );
			matrix.postScale( scale, scale );
			float tw = ( viewWidth - w * scale ) / 2.0f;
			float th = ( viewHeight - h * scale ) / 2.0f;
			matrix.postTranslate( tw, th );
		} else {
			float tw = ( viewWidth - w ) / 2.0f;
			float th = ( viewHeight - h ) / 2.0f;
			matrix.postTranslate( tw, th );
			Log.d( LOG_TAG, "scale: null" );
		}
	}

	/**
	 * Setup the base matrix so that the image is centered and scaled properly.
	 *
	 * @param bitmap
	 * @param matrix
	 */
	protected void getProperBaseMatrix2( Drawable bitmap, Matrix matrix ) {
		float viewWidth = getWidth();
		float viewHeight = getHeight();
		float w = bitmap.getIntrinsicWidth();
		float h = bitmap.getIntrinsicHeight();
		matrix.reset();
		float widthScale = Math.min( viewWidth / w, MAX_ZOOM );
		float heightScale = Math.min( viewHeight / h, MAX_ZOOM );
		float scale = Math.min( widthScale, heightScale );
		matrix.postScale( scale, scale );
		matrix.postTranslate( ( viewWidth - w * scale ) / MAX_ZOOM, ( viewHeight - h * scale ) / MAX_ZOOM );
	}

	protected float getValue( Matrix matrix, int whichValue ) {
		matrix.getValues( mMatrixValues );
		return mMatrixValues[whichValue];
	}

	protected RectF getBitmapRect() {
		return getBitmapRect( mSuppMatrix );
	}

	protected RectF getBitmapRect( Matrix supportMatrix ) {
		final Drawable drawable = getDrawable();

		if ( drawable == null ) return null;
		Matrix m = getImageViewMatrix( supportMatrix );
		mBitmapRect.set( 0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight() );
		m.mapRect( mBitmapRect );
		return mBitmapRect;
	}

	protected float getScale( Matrix matrix ) {
		return getValue( matrix, Matrix.MSCALE_X );
	}

	public float getRotation() {
		return 0;
	}

	public float getScale() {
		return getScale( mSuppMatrix );
	}

	protected void center( boolean horizontal, boolean vertical ) {
		final Drawable drawable = getDrawable();

		if ( drawable == null ) return;
		RectF rect = getCenter( mSuppMatrix, horizontal, vertical );
		if ( rect.left != 0 || rect.top != 0 ) {
			Log.d( LOG_TAG, "center.rect: " + rect.left + "x" + rect.top );
			postTranslate( rect.left, rect.top );
		}
	}

	protected RectF getCenter( Matrix supportMatrix, boolean horizontal, boolean vertical ) {
		final Drawable drawable = getDrawable();

		if ( drawable == null ) return new RectF( 0, 0, 0, 0 );

		mCenterRect.set( 0, 0, 0, 0 );
		RectF rect = getBitmapRect( supportMatrix );
		float height = rect.height();
		float width = rect.width();
		float deltaX = 0, deltaY = 0;
		if ( vertical ) {
			int viewHeight = getHeight();
			if ( height < viewHeight ) {
				deltaY = ( viewHeight - height ) / 2 - rect.top;
			} else if ( rect.top > 0 ) {
				deltaY = -rect.top;
			} else if ( rect.bottom < viewHeight ) {
				deltaY = getHeight() - rect.bottom;
			}
		}
		if ( horizontal ) {
			int viewWidth = getWidth();
			if ( width < viewWidth ) {
				deltaX = ( viewWidth - width ) / 2 - rect.left;
			} else if ( rect.left > 0 ) {
				deltaX = -rect.left;
			} else if ( rect.right < viewWidth ) {
				deltaX = viewWidth - rect.right;
			}
		}
		mCenterRect.set( deltaX, deltaY, 0, 0 );
		return mCenterRect;
	}

	protected void postTranslate( float deltaX, float deltaY ) {
		mSuppMatrix.postTranslate( deltaX, deltaY );
		setImageMatrix( getImageViewMatrix() );
	}

	protected void postScale( float scale, float centerX, float centerY ) {
		mSuppMatrix.postScale( scale, scale, centerX, centerY );
		setImageMatrix( getImageViewMatrix() );
	}

	protected void zoomTo( float scale ) {
		float cx = getWidth() / 2F;
		float cy = getHeight() / 2F;
		zoomTo( scale, cx, cy );
	}

	public void zoomTo( float scale, float durationMs ) {
		float cx = getWidth() / 2F;
		float cy = getHeight() / 2F;
		zoomTo( scale, cx, cy, durationMs );
	}

	protected void zoomTo( float scale, float centerX, float centerY ) {
		if ( scale > mMaxZoom ) scale = mMaxZoom;
		float oldScale = getScale();
		float deltaScale = scale / oldScale;
		Log.d( LOG_TAG, "zoomTo: " + scale + ", center: " + centerX + "x" + centerY );
		postScale( deltaScale, centerX, centerY );
		onZoom( getScale() );
		center( true, true );
	}

	protected void onZoom( float scale ) {}

	protected void onZoomAnimationCompleted( float scale ) {}

	public void scrollBy( float x, float y ) {
		panBy( x, y );
	}

	protected void panBy( double dx, double dy ) {
		RectF rect = getBitmapRect();
		mScrollRect.set( (float) dx, (float) dy, 0, 0 );
		updateRect( rect, mScrollRect );
		postTranslate( mScrollRect.left, mScrollRect.top );
		center( true, true );
	}

	protected void updateRect( RectF bitmapRect, RectF scrollRect ) {
		float width = getWidth();
		float height = getHeight();

		if ( bitmapRect.top >= 0 && bitmapRect.bottom <= height ) scrollRect.top = 0;
		if ( bitmapRect.left >= 0 && bitmapRect.right <= width ) scrollRect.left = 0;
		if ( bitmapRect.top + scrollRect.top >= 0 && bitmapRect.bottom > height ) scrollRect.top = (int) ( 0 - bitmapRect.top );
		if ( bitmapRect.bottom + scrollRect.top <= ( height - 0 ) && bitmapRect.top < 0 )
			scrollRect.top = (int) ( ( height - 0 ) - bitmapRect.bottom );
		if ( bitmapRect.left + scrollRect.left >= 0 ) scrollRect.left = (int) ( 0 - bitmapRect.left );
		if ( bitmapRect.right + scrollRect.left <= ( width - 0 ) ) scrollRect.left = (int) ( ( width - 0 ) - bitmapRect.right );
	}

	protected void scrollBy( float distanceX, float distanceY, final double durationMs ) {
		final double dx = distanceX;
		final double dy = distanceY;
		final long startTime = System.currentTimeMillis();
		mHandler.post( new Runnable() {

			double old_x = 0;
			double old_y = 0;

			@Override
			public void run() {
				long now = System.currentTimeMillis();
				double currentMs = Math.min( durationMs, now - startTime );
				double x = mEasing.easeOut( currentMs, 0, dx, durationMs );
				double y = mEasing.easeOut( currentMs, 0, dy, durationMs );
				panBy( ( x - old_x ), ( y - old_y ) );
				old_x = x;
				old_y = y;
				if ( currentMs < durationMs ) {
					mHandler.post( this );
				} else {
					RectF centerRect = getCenter( mSuppMatrix, true, true );
					if ( centerRect.left != 0 || centerRect.top != 0 ) scrollBy( centerRect.left, centerRect.top );
				}
			}
		} );
	}

	protected void zoomTo( float scale, float centerX, float centerY, final float durationMs ) {
		if ( scale > getMaxZoom() ) scale = getMaxZoom();
		final long startTime = System.currentTimeMillis();
		final float oldScale = getScale();

		final float deltaScale = scale - oldScale;

		Matrix m = new Matrix( mSuppMatrix );
		m.postScale( scale, scale, centerX, centerY );
		RectF rect = getCenter( m, true, true );

		final float destX = centerX + rect.left * scale;
		final float destY = centerY + rect.top * scale;

		mHandler.post( new Runnable() {

			@Override
			public void run() {
				long now = System.currentTimeMillis();
				float currentMs = Math.min( durationMs, now - startTime );
				float newScale = (float) mEasing.easeInOut( currentMs, 0, deltaScale, durationMs );
				zoomTo( oldScale + newScale, destX, destY );
				if ( currentMs < durationMs ) {
					mHandler.post( this );
				} else {
					onZoomAnimationCompleted( getScale() );
					center( true, true );
				}
			}
		} );
	}

	@Override
	public void dispose() {
		clear();
	}
}


text:
<?php

namespace hiapi\endpoints\Module\Middleware;

use Closure;

/**
 * Interface MiddlewareBuilderInterface
 *
 * @template T of MiddlewareBuilderInterface
 *
 * @author Dmytro Naumenko <d.naumenko.a@gmail.com>
 */
interface MiddlewareBuilderInterface
{
    /**
     * @param string|Closure ...$middlewares
     * @return T
     */
    public function middlewares(...$middlewares);
}


text:
You can use Material-UI's styling solution in your app, whether or not you are using Material-UI components.

Material-UI aims to provide a strong foundation for building dynamic UIs. For the sake of simplicity, **we expose the styling solution used in Material-UI components** as the `@material-ui/styles` package. You can use it, but you don't have to, since Material-UI is also [interoperable with](/guides/interoperability/) all the other major styling solutions.

## Why use Material-UI's styling solution?

In previous versions, Material-UI has used LESS, then a custom inline-style solution to write the component styles, but these approaches have proven to be limited. [A *CSS-in-JS* solution](https://github.com/oliviertassinari/a-journey-toward-better-style) overcomes many of those limitations, and **unlocks many great features** (theme nesting, dynamic styles, self-support, etc.).

Material-UI's styling solution is inspired by many other styling libraries such as [styled-components](https://www.styled-components.com/) and [emotion](https://emotion.sh/).

- 💅 You can expect [the same advantages](https://www.styled-components.com/docs/basics#motivation) as styled-components.
- 🚀 It's [blazing fast](https://github.com/mui-org/material-ui/blob/master/packages/material-ui-benchmark/README.md#material-uistyles).
- 🧩 It's extensible via a [plugin](https://github.com/cssinjs/jss/blob/master/docs/plugins.md) API.
- ⚡ It uses [JSS](https://github.com/cssinjs/jss) at its core – a [high performance](https://github.com/cssinjs/jss/blob/master/docs/performance.md) JavaScript to CSS compiler which works at runtime and server-side.
- 📦 Less than [15 KB gzipped](https://bundlephobia.com/result?p=@material-ui/styles); and no bundle size increase if used alongside Material-UI.

## Instalación

Para instalarlo y guardarlo en las dependencias de tu ` package.json `, ejecuta:

```sh
// with npm
npm install @material-ui/styles

// with yarn
yarn add @material-ui/styles
```

## Getting started

There are 3 possible APIs you can use to generate and apply styles, however they all share the same underlying logic.

### Hook API

```jsx
import React from 'react';
import { makeStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

export default function Hook() {
  const classes = useStyles();
  return <Button className={classes.root}>Hook</Button>;
}
```

{{"demo": "pages/styles/basics/Hook.js"}}

### Styled components API

Note: this only applies to the calling syntax – style definitions still use a JSS object. You can also [change this behavior](/styles/advanced/#string-templates), with some limitations.

```jsx
import React from 'react';
import { styled } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const MyButton = styled(Button)({
  background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
  border: 0,
  borderRadius: 3,
  boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
  color: 'white',
  height: 48,
  padding: '0 30px',
});

export default function StyledComponents() {
  return <MyButton>Styled Components</MyButton>;
}
```

{{"demo": "pages/styles/basics/StyledComponents.js"}}

### Higher-order component API

```jsx
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const styles = {
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
};

function HigherOrderComponent(props) {
  const { classes } = props;
  return <Button className={classes.root}>Higher-order component</Button>;
}

HigherOrderComponent.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponent);
```

{{"demo": "pages/styles/basics/HigherOrderComponent.js"}}

## Nesting selectors

You can nest selectors to target elements inside the current class or component. The following example uses the Hook API, but it works the same way with the other APIs.

```js
const useStyles = makeStyles({
  root: {
    padding: 16,
    color: 'red',
    '& p': {
      color: 'green',
      '& span': {
        color: 'blue'
      }
    }
  },
});
```

{{"demo": "pages/styles/basics/NestedStylesHook.js"}}

## Adapting based on props

You can pass a function to `makeStyles` ("interpolation") in order to adapt the generated value based on the component's props. The function can be provided at the style rule level, or at the CSS property level:

```jsx
const useStyles = makeStyles({
  // style rule
  foo: props => ({
    backgroundColor: props.backgroundColor,
  }),
  bar: {
    // CSS property
    color: props => props.color,
  },
});

function MyComponent() {
  // Simulated props for the purpose of the example
  const props = { backgroundColor: 'black', color: 'white' };
  // Pass the props as the first argument of useStyles()
  const classes = useStyles(props);

  return <div className={`${classes.foo} ${classes.bar}`} />
}
```

This button component has a color property that changes its color:

### Adapting the hook API

{{"demo": "pages/styles/basics/AdaptingHook.js", "react":"next"}}

### Adapting the styled components API

{{"demo": "pages/styles/basics/AdaptingStyledComponents.js"}}

### Adapting the higher-order component API

{{"demo": "pages/styles/basics/AdaptingHOC.js"}}

## Stress test

In the following stress test, you can update the *theme color* and the *background-color property* live:

```js
const useStyles = makeStyles(theme => ({
  root: props => ({
    backgroundColor: props.backgroundColor,
    color: theme.color,
  }),
}));
```

{{"demo": "pages/styles/basics/StressTest.js"}}


text:
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::count_if;
using std::bind;
using namespace std::placeholders;

bool check_size(const string &s, string::size_type sz) {
  return s.size() <= sz;
}

size_t NotLargerThanSix(vector<string> &svec) {
  return count_if(svec.begin(), svec.end(),
                bind(check_size, _1, 6));
}

int main()
{
  vector<string> svec{"abc", "abcd", "abcdefghi", "abcdefghijklm"};
  cout << NotLargerThanSix(svec) << endl;
  return 0;
}


text:
<?php
/**
 *
 * This file is part of the Aura for PHP.
 *
 * @package Aura.Router
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Router;

use ArrayAccess;
use ArrayIterator;
use Countable;
use IteratorAggregate;

/**
 *
 * A collection of route objects.
 *
 * @package Aura.Router
 *
 */
class RouteCollection extends AbstractSpec implements
    ArrayAccess,
    Countable,
    IteratorAggregate
{
    /**
     *
     * An array of route objects.
     *
     * @var array
     *
     */
    protected $routes = array();

    /**
     *
     * A factory to create route objects.
     *
     * @var RouteFactory
     *
     */
    protected $route_factory;

	protected $name_prefix = null;
	protected $path_prefix = null;
	protected $resource_callable = null;
	protected $route_callable = null;

	/**
	 *
	 * Constructor.
	 *
	 * @param RouteFactory $route_factory A factory to create route objects.
	 *
	 * @param array $routes An array of route objects.
	 *
	 */
	public function __construct(
	    RouteFactory $route_factory,
	    array $routes = array()
	) {
	    $this->route_factory = $route_factory;
        $this->routes = $routes;
        $this->setResourceCallable(array($this, 'resourceCallable'));
        $this->setRouteCallable(array($this, 'routeCallable'));
	}

	/**
	 *
	 * ArrayAccess: gets a route by name.
	 *
	 * @param string $name The route name.
	 *
	 * @return Route
	 *
	 */
	public function offsetGet($name)
	{
        return $this->routes[$name];
	}

	/**
	 *
	 * ArrayAccess: sets a route by name.
	 *
	 * @param string $name The route name.
	 *
	 * @param Route $route The route object.
	 *
	 * @return null
	 *
	 */
	public function offsetSet($name, $route)
	{
	    if (! $route instanceof Route) {
	        throw new Exception\UnexpectedValue;
	    }

	    $this->routes[$name] = $route;
	}

	/**
	 *
	 * ArrayAccess: does a route name exist?
	 *
	 * @param string $name The route name.
	 *
	 * @return bool
	 *
	 */
	public function offsetExists($name)
	{
	    return isset($this->routes[$name]);
	}

	/**
	 *
	 * ArrayAccess: removes a route by name.
	 *
	 * @param string $name The route name to remove.
	 *
	 * @return null
	 *
	 */
	public function offsetUnset($name)
	{
	    unset($this->routes[$name]);
	}

	/**
	 *
	 * Countable: returns the number of routes in the collection.
	 *
	 * @return int
	 *
	 */
	public function count()
	{
	    return count($this->routes);
	}

	/**
	 *
	 * IteratorAggregate: returns the iterator object.
	 *
	 * @return ArrayIterator
	 *
	 */
	public function getIterator()
	{
	    return new ArrayIterator($this->routes);
	}

    /**
     *
     * Adds a route.
     *
     * @param string $name The route name.
     *
     * @param string $path The route path.
     *
     * @return Route The newly-added route object.
     *
     */
    public function add($name, $path)
    {
        // create the route with the full path, name, and spec
        $route = $this->route_factory->newInstance(
            $path,
            $name,
            $this->getSpec()
        );

        // add the route
        if (! $route->name) {
            $this->routes[] = $route;
        } else {
            $this->routes[$route->name] = $route;
        }

        // modify newly-added route
        call_user_func($this->route_callable, $route);

        // done; return for further modification
        return $route;
    }

    /**
     *
     * Adds a GET route.
     *
     * @param string $name The route name.
     *
     * @param string $path The route path.
     *
     * @return Route The newly-added route object.
     *
     */
    public function addGet($name, $path)
    {
        $route = $this->add($name, $path);
        $route->addServer(array('REQUEST_METHOD' => 'GET'));
        return $route;
    }

    /**
     *
     * Adds a DELETE route.
     *
     * @param string $name The route name.
     *
     * @param string $path The route path.
     *
     * @return Route The newly-added route object.
     *
     */
    public function addDelete($name, $path)
    {
        $route = $this->add($name, $path);
        $route->addServer(array('REQUEST_METHOD' => 'DELETE'));
        return $route;
    }

    /**
     *
     * Adds an Options route.
     *
     * @param string $name The route name.
     *
     * @param string $path The route path.
     *
     * @return Route The newly-added route object.
     *
     */
    public function addOptions($name, $path)
    {
        $route = $this->add($name, $path);
        $route->addServer(array('REQUEST_METHOD' => 'OPTIONS'));
        return $route;
    }

    /**
     *
     * Adds a PATCH route.
     *
     * @param string $name The route name.
     *
     * @param string $path The route path.
     *
     * @return Route The newly-added route object.
     *
     */
    public function addPatch($name, $path)
    {
        $route = $this->add($name, $path);
        $route->addServer(array('REQUEST_METHOD' => 'PATCH'));
        return $route;
    }

    /**
     *
     * Adds a POST route.
     *
     * @param string $name The route name.
     *
     * @param string $path The route path.
     *
     * @return Route The newly-added route object.
     *
     */
    public function addPost($name, $path)
    {
        $route = $this->add($name, $path);
        $route->addServer(array('REQUEST_METHOD' => 'POST'));
        return $route;
    }

    /**
     *
     * Adds a PUT route.
     *
     * @param string $name The route name.
     *
     * @param string $path The route path.
     *
     * @return Route The newly-added route object.
     *
     */
    public function addPut($name, $path)
    {
        $route = $this->add($name, $path);
        $route->addServer(array('REQUEST_METHOD' => 'PUT'));
        return $route;
    }

    /**
     *
     * Sets the callable for modifying a newly-added route before it is
     * returned.
     *
     * @param callable $callable The callable to modify the route.
     *
     * @return $this
     *
     */
    public function setRouteCallable($callable)
    {
        $this->route_callable = $callable;
        return $this;
    }

    /**
     *
     * Modifies the newly-added route to set 'controller' and 'action' values
     * if they are not already present.  Uses the route name to do so.
     *
     * @param Route $route The newly-added route.
     *
     * @return null
     *
     */
    protected function routeCallable(Route $route)
    {
        $action = $route->name;
        if (! $action) {
            return;
        }

        $controller = null;
        $pos = strrpos($action, '.');
        if ($pos !== false) {
            $controller = substr($action, 0, $pos);
            $action = substr($action, $pos + 1);
        }

        if (! isset($route->values['controller'])) {
            $route->addValues(array('controller' => $controller));
        }

        if (! isset($route->values['action'])) {
            $route->addValues(array('action' => $action));
        }
    }

    /**
     *
     * Attaches routes to a specific path prefix, and prefixes the attached
     * route names.
     *
     * @param string $name The prefix for all route names being
     * attached.
     *
     * @param string $path The prefix for all route paths being
     * attached.
     *
     * @param callable $callable A callable that uses the Router to add new
     * routes. Its signature is `function (\Aura\Router\Router $router)`; this
     * Router instance will be passed to the callable.
     *
     * @return null
     *
     */
    public function attach($name, $path, $callable)
    {
        // save current spec
        $spec = $this->getSpec();

        // append to the name prefix, with delimiter if needed
        if ($this->name_prefix) {
            $this->name_prefix .= '.';
        }
        $this->name_prefix .= $name;

        // append to the path prefix
        $this->path_prefix .= $path;

        // invoke the callable, passing this RouteCollection as the only param
        call_user_func($callable, $this);

        // restore previous spec
        $this->setSpec($spec);
    }

    protected function getSpec()
    {
        $vars = array(
            'tokens',
            'server',
            'values',
            'secure',
            'wildcard',
            'routable',
            'is_match',
            'generate',
            'name_prefix',
            'path_prefix',
            'resource_callable',
            'route_callable',
        );

        $spec = array();
        foreach ($vars as $var) {
            $spec[$var] = $this->$var;
        }

        return $spec;
    }

    protected function setSpec($spec)
    {
        foreach ($spec as $key => $val) {
            $this->$key = $val;
        }
    }
    /**
     *
     * Use the `$resourceCallable` to attach a resource.
     *
     * @param string $name The resource name; used as a route name prefix.
     *
     * @param string $path The path to the resource; used as a route path
     * prefix.
     *
     * @return null
     *
     */
    public function attachResource($name, $path)
    {
        $this->attach($name, $path, $this->resource_callable);
    }

    /**
     *
     * Sets the callable for attaching resource routes.
     *
     * @param callable $resource The resource callable.
     *
     * @return $this
     *
     */
    public function setResourceCallable($resource)
    {
        $this->resource_callable = $resource;
        return $this;
    }

    /**
     *
     * Callable for `attachResource()` that adds resource routes.
     *
     * @param RouteCollection $router A RouteCollection, probably $this.
     *
     * @return null
     *
     */
    protected function resourceCallable(RouteCollection $router)
    {
        // add 'id' and 'format' if not already defined
        $tokens = array();
        if (! isset($router->tokens['id'])) {
            $tokens['id'] = '\d+';
        }
        if (! isset($router->tokens['format'])) {
            $tokens['format'] = '(\.[^/]+)?';
        }
        if ($tokens) {
            $router->addTokens($tokens);
        }

        // add the routes
        $router->addGet('browse', '{format}');
        $router->addGet('read', '/{id}{format}');
        $router->addGet('edit', '/{id}/edit{format}');
        $router->addGet('add', '/add');
        $router->addDelete('delete', '/{id}');
        $router->addPost('create', '');
        $router->addPatch('update', '/{id}');
        $router->addPut('replace', '/{id}');
    }
}


text:
/*
 * bits32/stddef.h
 */

#ifndef _BITSIZE_STDDEF_H
#define _BITSIZE_STDDEF_H

#define _SIZE_T
typedef unsigned int size_t;

#define _PTRDIFF_T
typedef signed long ptrdiff_t;

#endif /* _BITSIZE_STDDEF_H */


text:
import {Resource} from 'node-odata';
import {photo} from '../models/photo';
import isAdmin from '../auth/isAdmin';

export default Resource('photo', photo)
  .orderBy('createDate desc')
  .post().auth(isAdmin)
  .put().auth(isAdmin)
  .delete().auth(isAdmin);


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using DevExpress.Mvvm.Native;

namespace DevExpress.Mvvm.UI.Native {
    public delegate void UnregisterCallback<E>(EventHandler<E> eventHandler) where E : EventArgs;
    public interface IAnotherWeakEventHandler<E> where E : EventArgs {
        EventHandler<E> Handler { get; }
    }
    public class AnotherWeakEventHandler<T, E> : IAnotherWeakEventHandler<E> where T : class where E : EventArgs {
        private delegate void OpenEventHandler(T @this, object sender, E e);
        private WeakReference m_TargetRef;
        private OpenEventHandler m_OpenHandler;
        private EventHandler<E> m_Handler;
        private UnregisterCallback<E> m_Unregister;
        public AnotherWeakEventHandler(EventHandler<E> eventHandler, UnregisterCallback<E> unregister) {
            m_TargetRef = new WeakReference(eventHandler.Target);
            m_OpenHandler = (OpenEventHandler)Delegate.CreateDelegate(typeof(OpenEventHandler), null, eventHandler.Method);
            m_Handler = Invoke;
            m_Unregister = unregister;
        }
        public void Invoke(object sender, E e) {
            T target = (T)m_TargetRef.Target;
            if(target != null)
                m_OpenHandler.Invoke(target, sender, e);
            else if(m_Unregister != null) {
                m_Unregister(m_Handler);
                m_Unregister = null;
            }
        }
        public EventHandler<E> Handler { get { return m_Handler; } }
        public static implicit operator EventHandler<E>(AnotherWeakEventHandler<T, E> weh) { return weh.m_Handler; }
    }
    public static class AnotherEventHandlerUtils {
        public static EventHandler<E> MakeWeak<E>(EventHandler<E> eventHandler, UnregisterCallback<E> unregister) where E : EventArgs {
            if(eventHandler == null)
                throw new ArgumentNullException("eventHandler");
            if(eventHandler.Method.IsStatic || eventHandler.Target == null)
                throw new ArgumentException("Only instance methods are supported.", "eventHandler");
            Type wehType = typeof(AnotherWeakEventHandler<,>).MakeGenericType(eventHandler.Method.DeclaringType, typeof(E));
            ConstructorInfo wehConstructor = wehType.GetConstructor(new Type[] { typeof(EventHandler<E>), typeof(UnregisterCallback<E>) });
            IAnotherWeakEventHandler<E> weh = (IAnotherWeakEventHandler<E>)wehConstructor.Invoke(new object[] { eventHandler, unregister });
            return weh.Handler;
        }
    }

    public interface IScreen {
        Rect GetWorkingArea();
        event Action WorkingAreaChanged;
    }

    public class PrimaryScreen : IScreen {
        static PrimaryScreen() {
            Microsoft.Win32.SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
        }

        static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e) {
            if(DisplaySettingsChanged != null)
                DisplaySettingsChanged(sender, e);
        }

        static event EventHandler<EventArgs> DisplaySettingsChanged;

        public PrimaryScreen() {
            DisplaySettingsChanged += AnotherEventHandlerUtils.MakeWeak<EventArgs>((s, e) => {
                if(WorkingAreaChanged != null)
                    WorkingAreaChanged();
            }, handler => DisplaySettingsChanged -= handler);
        }

        double GetDpiScaleProperty(string name) {
            PropertyInfo pi = typeof(FrameworkElement).GetProperty(name, BindingFlags.NonPublic | BindingFlags.Static);
            if (pi != null)
                return (double) pi.GetValue(null, null);
            return 1d;
        }

        public Rect GetWorkingArea(System.Windows.Point point) {
            double xScale = GetDpiScaleProperty("DpiScaleX");
            double yScale = GetDpiScaleProperty("DpiScaleY");
            var area = Screen.GetWorkingArea(new System.Drawing.Point((int)point.X, (int)point.Y));
            return new Rect(area.X / xScale, area.Y / yScale, area.Width / xScale, area.Height / yScale);
        }

        public Rect GetWorkingArea() {
            return GetWorkingArea(new System.Windows.Point());
        }
        public event Action WorkingAreaChanged;
    }

    public class CustomNotifier {
        internal class ToastInfo {
            public Window win;
            public CustomNotification toast;
            public Timer timer;
            public TaskCompletionSource<NotificationResult> source;
        }

        readonly List<ToastInfo> toastsQueue = new List<ToastInfo>();
        const int maxVisibleToasts = 3;
        internal static NotificationPositioner<ToastInfo> positioner;
        IScreen screen;

        public Style Style { get; set; }

        public CustomNotifier(IScreen screen = null) {
            this.screen = screen ?? new PrimaryScreen();
            this.screen.WorkingAreaChanged += screen_WorkingAreaChanged;
            UpdatePositioner(NotificationPosition.TopRight, maxVisibleToasts);
        }

        void screen_WorkingAreaChanged() {
            positioner.Update(screen.GetWorkingArea());
            List<ToastInfo> visible = positioner.Items.Where(i => i != null).ToList();
            foreach (ToastInfo info in visible) {
                info.timer.Stop();
                info.timer.Start();
                var newPos = positioner.GetItemPosition(info);
                info.win.Left = newPos.X;
                info.win.Top = newPos.Y;
            }
        }

        public void UpdatePositioner(NotificationPosition position, int maxCount) {
            if(positioner == null) {
                positioner = new NotificationPositioner<ToastInfo>();
            }
            positioner.Update(screen.GetWorkingArea(), position, maxCount);
        }

        public Task<NotificationResult> ShowAsync(CustomNotification toast, int msDuration = 3000) {
            var info = new ToastInfo {
                toast = toast,
                timer = new Timer() { Interval = msDuration },
                source = new TaskCompletionSource<NotificationResult>()
            };
            toastsQueue.Add(info);
            ShowNext();
            return info.source.Task;
        }

        void ShowNext() {
            if(!positioner.HasEmptySlot() || !toastsQueue.Any())
                return;

            ToastInfo info = toastsQueue[0];
            toastsQueue.RemoveAt(0);
            info.win = new ToastWindow();

            var content = new ToastContentControl() { Toast = info.toast };
            content.Content = info.toast.ViewModel;
            content.Style = Style;
            if(ContentTemplateSelector == null) {
                content.ContentTemplate = ContentTemplate ?? NotificationServiceTemplatesHelper.DefaultCustomToastTemplate;
            }
            content.ContentTemplateSelector = ContentTemplateSelector;

            info.win.Content = content;
            info.win.DataContext = info.toast.ViewModel;

            if(double.IsNaN(content.Width) || double.IsNaN(content.Height))
                throw new InvalidOperationException("The height or width of a custom notification can not be set to Auto");

            System.Windows.Point position = positioner.Add(info, content.Width, content.Height);

            info.win.Left = position.X;
            info.win.Top = position.Y;

            try {
                info.win.Show();
            }
            catch(System.ComponentModel.Win32Exception) {
                content.TimeOutCommand.Execute(null);
                return;
            }
            info.timer.Tick += (s, e) => {
                content.TimeOutCommand.Execute(null);
                info.timer.Stop();
            };
            info.timer.Start();
        }

        internal void Activate(CustomNotification toast) {
            RemoveVisibleToast(toast, NotificationResult.Activated);
            ShowNext();
        }

        internal void Dismiss(CustomNotification toast) {
            RemoveVisibleToast(toast, NotificationResult.UserCanceled);
            ShowNext();
        }

        internal void TimeOut(CustomNotification toast) {
            RemoveVisibleToast(toast, NotificationResult.TimedOut);
            ShowNext();
        }

        internal void Hide(CustomNotification toast) {
            ToastInfo info = toastsQueue.FirstOrDefault(i => i.toast == toast);
            if(info != null) {
                toastsQueue.Remove(info);
                info.source.SetResult(NotificationResult.ApplicationHidden);
                return;
            }
            RemoveVisibleToast(toast, NotificationResult.ApplicationHidden);
            ShowNext();
        }

        void RemoveVisibleToast(CustomNotification toast, NotificationResult result) {
            ToastInfo info = GetVisibleToastInfo(toast);
            if(info == null) {
                return;
            }
            info.win.Close();
            info.timer.Stop();
            positioner.Remove(info);
            info.source.SetResult(result);
        }

        private ToastInfo GetVisibleToastInfo(CustomNotification toast) {
            return positioner.Items.FirstOrDefault(t => t != null && t.toast == toast);
        }

        internal void StopTimer(CustomNotification toast) {
            GetVisibleToastInfo(toast).Do(t => t.timer.Stop());
        }

        internal void ResetTimer(CustomNotification toast) {
            GetVisibleToastInfo(toast).Do(t => t.timer.Start());
        }

        public DataTemplate ContentTemplate { get; set; }
        public DataTemplateSelector ContentTemplateSelector { get; set; }
    }
}


text:
import wx

class ChangeDepthDialog(wx.Dialog):
    def __init__(self, *args, **kw):
        super(ChangeDepthDialog, self).__init__(*args, **kw)

        self.InitUI()
        self.SetSize((250, 200))
        self.SetTitle("Change Color Depth")

    def InitUI(self):
        pnl = wx.Panel(self)
        vbox = wx.BoxSizer(wx.VERTICAL)

        sb = wx.StaticBox(pnl, label='Colors')
        sbs = wx.StaticBoxSizer(sb, orient=wx.VERTICAL)
        sbs.Add(wx.RadioButton(pnl, label='256 Colors',
                               style=wx.RB_GROUP))
        sbs.Add(wx.RadioButton(pnl, label='16 Colors'))
        sbs.Add(wx.RadioButton(pnl, label='2 Colors'))

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox1.Add(wx.RadioButton(pnl, label='Custom'))
        hbox1.Add(wx.TextCtrl(pnl), flag=wx.LEFT, border=5)
        sbs.Add(hbox1)

        pnl.SetSizer(sbs)

        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        okButton = wx.Button(self, label='Ok')
        closeButton = wx.Button(self, label='Close')
        hbox2.Add(okButton)
        hbox2.Add(closeButton, flag=wx.LEFT, border=5)

        vbox.Add(pnl, proportion=1,
                 flag=wx.ALL | wx.EXPAND, border=5)
        vbox.Add(hbox2,
                 flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, border=10)

        self.SetSizer(vbox)

        okButton.Bind(wx.EVT_BUTTON, self.OnClose)
        closeButton.Bind(wx.EVT_BUTTON, self.OnClose)

    def OnClose(self, e):
        self.Destroy()

class Example(wx.Frame):
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)

        self.InitUI()

    def InitUI(self):
        wx.CallLater(5000, self.ShowMessage) # postpone 5 secs
        # add grid sizer buttons
        panel = wx.Panel(self)
        hbox = wx.BoxSizer()
        sizer = wx.GridSizer(2, 2, 2, 2)
        btn1 = wx.Button(panel, label='Info')
        btn2 = wx.Button(panel, label='Error')
        btn3 = wx.Button(panel, label='Question')
        btn4 = wx.Button(panel, label='Alert')
        sizer.AddMany([btn1, btn2, btn3, btn4])
        hbox.Add(sizer, 0, wx.ALL, 15)
        panel.SetSizer(hbox)
        btn1.Bind(wx.EVT_BUTTON, self.ShowMessage1)
        btn2.Bind(wx.EVT_BUTTON, self.ShowMessage2)
        btn3.Bind(wx.EVT_BUTTON, self.ShowMessage3)
        btn4.Bind(wx.EVT_BUTTON, self.ShowMessage4)

        menu = wx.MenuBar()
        help = wx.Menu()
        help.Append(100, '&About')
        self.Bind(wx.EVT_MENU, self.OnAboutBox, id = 100)
        menu.Append(help, '&Help\tCtrl+H')
        self.SetMenuBar(menu)

        self.SetSize((300, 200))
        self.SetTitle('Message box')
        self.Centre()
        self.Show(True)

    def OnAboutBox(self, e):
        chgdep = ChangeDepthDialog(None, title='Change Color Depth')
        chgdep.ShowModal()
        chgdep.Destroy()

    def ShowMessage(self):
        wx.MessageBox('Download completed', 'Info',
                      wx.OK | wx.ICON_INFORMATION)

    def ShowMessage1(self, event):
        dial = wx.MessageDialog(None, 'Download completed', 'Info', wx.OK)
        dial.ShowModal()

    def ShowMessage2(self, event):
        dial = wx.MessageDialog(None, 'Error loading file', 'Error',
                                wx.OK | wx.ICON_ERROR)
        dial.SetIcon(wx.Icon('exit.png', wx.BITMAP_TYPE_PNG))  # not effect
        dial.ShowModal()

    def ShowMessage3(self, event):
        dial = wx.MessageDialog(None, 'Are you sure to quit?', 'Question',
                                wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
        dial.ShowModal()

    def ShowMessage4(self, event):
        dial = wx.MessageDialog(None, 'Unallowed operation', 'Exclamation',
                                wx.OK | wx.ICON_EXCLAMATION)
        dial.ShowModal()

def main():
    ex = wx.App()
    Example(None)
    ex.MainLoop()

if __name__ == '__main__':
    main()


text:
"""Tests for the SkyBell integration."""

from unittest.mock import AsyncMock, patch

from homeassistant.const import CONF_EMAIL, CONF_PASSWORD

USERNAME = "user"
PASSWORD = "password"
USER_ID = "123456789012345678901234"

CONF_CONFIG_FLOW = {
    CONF_EMAIL: USERNAME,
    CONF_PASSWORD: PASSWORD,
}

def _patch_skybell_devices() -> None:
    mocked_skybell = AsyncMock()
    mocked_skybell.user_id = USER_ID
    return patch(
        "homeassistant.components.skybell.config_flow.Skybell.async_get_devices",
        return_value=[mocked_skybell],
    )

def _patch_skybell() -> None:
    return patch(
        "homeassistant.components.skybell.config_flow.Skybell.async_send_request",
        return_value={"id": USER_ID},
    )


text:
using System.Windows;
using System.Windows.Controls;

namespace Pulse.UI
{
    public sealed class UiGameFileCommanderSettingsWindow : UiWindow
    {
        public UiGameFileCommanderSettingsWindow(bool isExtracting)
        {
            #region Construct

            SizeToContent = SizeToContent.WidthAndHeight;
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            WindowStyle = WindowStyle.None;

            UiGrid root = UiGridFactory.Create(3, 1);
            {
                Thickness margin = new Thickness(3);

                UiStackPanel maskPanel = UiStackPanelFactory.Create(Orientation.Horizontal);
                {
                    UiTextBlock maskLabel = UiTextBlockFactory.Create("Ìàñêà: ");
                    {
                        maskLabel.Margin = margin;
                        maskLabel.VerticalAlignment = VerticalAlignment.Center;
                        maskPanel.AddUiElement(maskLabel);
                    }

                    _wildcardBox = UiTextBoxFactory.Create("*");
                    {
                        _wildcardBox.Width = 300;
                        _wildcardBox.Margin = margin;
                        maskPanel.AddUiElement(_wildcardBox);
                    }

                    root.AddUiElement(maskPanel, 0, 0);
                }

                UiStackPanel settingsPanel = UiStackPanelFactory.Create(Orientation.Horizontal);
                {
                    if (!isExtracting)
                    {
                        _compressBox = UiCheckBoxFactory.Create("Ñæàòü", false);
                        {
                            _compressBox.Margin = margin;
                            _compressBox.IsThreeState = true;
                            _compressBox.IsChecked = null;
                            settingsPanel.AddUiElement(_compressBox);
                        }
                    }

                    _convertBox = UiCheckBoxFactory.Create("Êîíâåðòèðîâàòü", false);
                    {
                        _convertBox.Margin = margin;
                        _convertBox.IsThreeState = true;
                        _convertBox.IsChecked = null;
                        settingsPanel.AddUiElement(_convertBox);
                    }

                    root.AddUiElement(settingsPanel, 1, 0);
                }

                UiStackPanel buttonsPanel = UiStackPanelFactory.Create(Orientation.Horizontal);
                {
                    buttonsPanel.HorizontalAlignment = HorizontalAlignment.Right;

                    UiButton okButton = UiButtonFactory.Create("OK");
                    {
                        okButton.Width = 100;
                        okButton.Margin = margin;
                        okButton.Click += OnOkButtonClick;
                        buttonsPanel.AddUiElement(okButton);
                    }

                    UiButton cancelButton = UiButtonFactory.Create("Îòìåíà");
                    {
                        cancelButton.Width = 100;
                        cancelButton.Margin = margin;
                        cancelButton.Click += OnCancelButtonClick;
                        buttonsPanel.AddUiElement(cancelButton);
                    }

                    root.AddUiElement(buttonsPanel, 2, 0);
                }
            }

            Content = root;

            #endregion
        }

        private readonly UiTextBox _wildcardBox;
        private readonly UiCheckBox _compressBox;
        private readonly UiCheckBox _convertBox;

        public string Wildcard { get; private set; }
        public bool? Compression { get; private set; }
        public bool? Convert { get; private set; }

        private void OnOkButtonClick(object sender, RoutedEventArgs e)
        {
            Wildcard = _wildcardBox.Text;
            if (_compressBox != null) Compression = _compressBox.IsChecked;
            if (_convertBox != null) Convert = _convertBox.IsChecked;

            DialogResult = true;
        }

        private void OnCancelButtonClick(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jdbi.v3.core.mapper;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.UnaryOperator;

import org.jdbi.v3.core.config.ConfigRegistry;
import org.jdbi.v3.core.generic.GenericType;
import org.jdbi.v3.core.generic.GenericTypes;
import org.jdbi.v3.core.result.ResultBearing;
import org.jdbi.v3.core.statement.StatementContext;
import org.jdbi.v3.meta.Beta;

/**
 * Factory for a RowMapper that can map resultset rows to column name/generic value {@link Map}s.
 *
 * Each row in the resultset becomes a distinct {@link Map}, in which the keys are all distinct column names and the values are the corresponding cell contents.
 * All values are mapped to the same generic type {@code T} (e.g. {@link java.math.BigDecimal}) by a {@link ColumnMapper} from the {@link ConfigRegistry}.
 *
 * This differs from {@link MapMapper} by supporting a concrete type instead of only {@link Object}, and from {@code collecting} into a {@link Map}
 * in that the latter maps an entire resultset to a single {@link Map} and can only keep 1 key and 1 value from each row.
 *
 * Use cases for this are mainly single-row results like numeric reports (e.g. the price components,
 * taxes, etc of a product for sale, or a set of possible labeled values for a user setting), and matrices.
 *
 * @see ResultBearing#mapToMap(GenericType)
 *
 * @see MapMapper
 * @see ResultBearing#mapToMap()
 *
 * @see ResultBearing#collectInto(GenericType)
 */
@Beta
// TODO jdbi4: integrate with MapMapper? check if registering by default is compatible with other Map-mapping features
public class GenericMapMapperFactory implements RowMapperFactory {
    // invoked by sqlobject
    @Override
    public Optional<RowMapper<?>> build(Type mapType, ConfigRegistry config) {
        return Optional.of(mapType)
            .filter(ParameterizedType.class::isInstance)
            .map(ParameterizedType.class::cast)
            .filter(maybeMap -> Map.class.equals(maybeMap.getRawType()))
            .filter(map -> String.class.equals(GenericTypes.findGenericParameter(map, Map.class, 0).orElse(null)))
            .flatMap(map -> GenericTypes.findGenericParameter(map, Map.class, 1))
            .filter(value -> !Object.class.equals(value))
            .flatMap(config.get(ColumnMappers.class)::findFor)
            .map(GenericMapMapper::new);
    }

    // invoked manually or by fluent api
    @Beta
    public static <T> RowMapper<Map<String, T>> getMapperForValueType(Class<T> valueType, ConfigRegistry config) {
        return config.get(ColumnMappers.class)
            .findFor(valueType)
            .map(GenericMapMapper::new)
            .orElseThrow(() -> new RuntimeException("no column mapper found for type " + valueType));
    }

    // invoked manually or by fluent api
    @Beta
    public static <T> RowMapper<Map<String, T>> getMapperForValueType(GenericType<T> valueType, ConfigRegistry config) {
        return config.get(ColumnMappers.class)
            .findFor(valueType)
            .map(GenericMapMapper::new)
            .orElseThrow(() -> new RuntimeException("no column mapper found for type " + valueType));
    }

    private static class GenericMapMapper<T> implements RowMapper<Map<String, T>> {
        private final ColumnMapper<T> mapper;

        private GenericMapMapper(ColumnMapper<T> mapper) {
            this.mapper = mapper;
        }

        @Override
        public Map<String, T> map(ResultSet rs, StatementContext ctx) throws SQLException {
            return specialize(rs, ctx).map(rs, ctx);
        }

        @Override
        public RowMapper<Map<String, T>> specialize(ResultSet rs, StatementContext ctx) throws SQLException {
            List<String> keyNames = getMapKeys(rs.getMetaData(), ctx.getConfig(MapMappers.class).getCaseChange());

            return (r, c) -> {
                Map<String, T> row = new HashMap<>();

                for (int i = 0; i < keyNames.size(); i++) {
                    T value = mapper.map(r, i + 1, ctx);
                    row.put(keyNames.get(i), value);
                }

                return row;
            };
        }

        private static List<String> getMapKeys(ResultSetMetaData meta, UnaryOperator<String> caseChange) throws SQLException {
            // important: ordered, not sorted, and unique
            Set<String> names = new LinkedHashSet<>();
            int columnCount = meta.getColumnCount();

            for (int i = 0; i < columnCount; i++) {
                String columnName = meta.getColumnName(i + 1);
                String columnLabel = meta.getColumnLabel(i + 1);

                String key = columnLabel == null ? columnName : columnLabel;
                String renamedKey = caseChange.apply(key);

                boolean added = names.add(renamedKey);
                if (!added) {
                    throw new RuntimeException(String.format("map key \"%s\" (from column \"%s\") appears twice in this resultset!", renamedKey, key));
                }
            }

            return new ArrayList<>(names);
        }
    }
}