text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Class: DisplayObjectContainer · Phaser CE</title>

	<link type="text/css" rel="stylesheet" href="styles/default.css">

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cerulean.css">

			Phaser API

						Read Me

						Change Log

					Namespaces

							Phaser

							PIXI

					Classes

							CreatureShader

							EarCut

							Event

							EventTarget

							Animation

							AnimationManager

							AnimationParser

							ArraySet

							ArrayUtils

							AudioSprite

							BitmapData

							BitmapText

							Bullet

							Button

							Cache

							Camera

							Canvas

							CanvasPool

							Circle

							Color

							Angle

							Animation

							AutoCull

							Bounds

							BringToTop

							Core

							Crop

							Delta

							Destroy

							FixedToCamera

							Health

							InCamera

							InputEnabled

							InWorld

							LifeSpan

							LoadTexture

							Overlap

							PhysicsBody

							Reset

							ScaleMinMax

							Smoothed

							Create

							Creature

							Device

							DeviceButton

							DOM

							Easing

							Back

							Bounce

							Circular

							Cubic

							Elastic

							Exponential

							Linear

							Quadratic

							Quartic

							Quintic

							Sinusoidal

							Ellipse

							Events

							Filter

							FlexGrid

							FlexLayer

							Frame

							FrameData

							Game

							GameObjectCreator

							GameObjectFactory

							Gamepad

							Graphics

							Group

							Hermite

							Image

							ImageCollection

							Input

							InputHandler

							Key

							Keyboard

							KeyCode

							Line

							LinkedList

							Loader

							LoaderParser

							Math

							Matrix

							Mouse

							MSPointer

							Net

							Particle

							Particles

							Arcade

							Emitter

							Path

							PathFollower

							PathPoint

							Physics

							Arcade

							Body

							TilemapCollision

							Ninja

							AABB

							Body

							Circle

							Tile

							P2

							Body

							BodyDebug

							CollisionGroup

							ContactMaterial

							DistanceConstraint

							FixtureList

							GearConstraint

							InversePointProxy

							LockConstraint

							Material

							PointProxy

							PrismaticConstraint

							RevoluteConstraint

							RotationalSpring

							Spring

							Plugin

							AStar

							AStarNode

							AStarPath

							ColorHarmony

							CSS3Filters

							Juicy

							ScreenFlash

							Trail

							KineticScrolling

							PathManager

							SamplePlugin

							TilemapWalker

							VirtualJoystick

							Webcam

							PluginManager

							Point

							Pointer

							PointerMode

							Polygon

							QuadTree

							RandomDataGenerator

							Rectangle

							RenderTexture

							RequestAnimationFrame

							RetroFont

							Rope

							RoundedRectangle

							ScaleManager

							Signal

							SignalBinding

							SinglePad

							Sound

							SoundManager

							Sprite

							SpriteBatch

							Stage

							State

							StateManager

							Text

							Tile

							Tilemap

							TilemapLayer

							TilemapParser

							Tileset

							TileSprite

							Time

							Timer

							TimerEvent

							Touch

							Tween

							TweenData

							TweenManager

							Utils

							Debug

							Video

							Weapon

							World

							BaseTexture

							CanvasBuffer

							CanvasGraphics

							CanvasMaskManager

							CanvasRenderer

							CanvasTinter

							ComplexPrimitiveShader

							DisplayObject

							DisplayObjectContainer

							FilterTexture

							Phaser.GraphicsData

							PIXI

							PixiFastShader

							PixiShader

							PrimitiveShader

							Sprite

							StripShader

							Texture

							WebGLBlendModeManager

							WebGLFastSpriteBatch

							WebGLFilterManager

							WebGLRenderer

					Global

							destroy

							init

							set

					Core

Game

Group

World

Loader

Cache

Time

Camera

State Manager

Tween Manager

Sound Manager

Input Manager

Scale Manager

					Game Objects

Factory (game.add)

Creator (game.make)

Sprite

Image

Sound

Video

Particle Emitter

Particle

Text

Tween

BitmapText

Tilemap

BitmapData

RetroFont

Button

Animation

Graphics

RenderTexture

TileSprite

					Geometry

Circle

Ellipse

Line

Matrix

Point

Polygon

Rectangle

Rounded Rectangle

					Physics

Arcade Physics

Body

Weapon

P2 Physics

Body

Spring

CollisionGroup

ContactMaterial

Ninja Physics

Body

					Input

Input Handler

Pointer

Device Button

Mouse

Keyboard

Key

Key Codes

Gamepad

					 Community

Phaser Web Site

Phaser CE Github

Phaser Examples

Phaser Plugins

Forum

Stack Overflow

Tutorials

Newsletter

Twitter

Slack

Donate

Texture Packer

        PIXI.

    DisplayObjectContainer

new DisplayObjectContainer()

A DisplayObjectContainer represents a collection of display objects.
It is the base class of all display objects that act as a container for other objects.

Source -
    pixi/display/DisplayObjectContainer.js, line 5

Extends

PIXI.DisplayObject

Members

alpha :Number

The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent.
Please note that an object with an alpha value of 0 is skipped during the render pass.

The value of this property does not reflect any alpha values set further up the display list.
To obtain that value please see the worldAlpha property.

Inherited From:

        PIXI.DisplayObject#alpha

Source -
    pixi/display/DisplayObject.js, line 63

cacheAsBitmap :Boolean

Sets if this DisplayObject should be cached as a bitmap.

When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it
in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a
performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children.

Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not
re-generate the cached bitmap automatically. To do that you need to call DisplayObject.updateCache.

To remove a cached bitmap, set this property to null.

Inherited From:

        PIXI.DisplayObject#cacheAsBitmap

Source -
    pixi/display/DisplayObject.js, line 794

<readonly> children :Array.<DisplayObject>

[read-only] The array of children of this container.

Type:

Array.<DisplayObject>

Source -
    pixi/display/DisplayObjectContainer.js, line 17

filterArea :Rectangle

The rectangular area used by filters when rendering a shader for this DisplayObject.

Inherited From:

        PIXI.DisplayObject#filterArea

Source -
    pixi/display/DisplayObject.js, line 195

filters :Array

Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas
Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter
using DisplayObject.filterArea.

To remove filters, set this property to null.

Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a
filter will reset this DisplayObjects blend mode to NORMAL.

Inherited From:

        PIXI.DisplayObject#filters

Source -
    pixi/display/DisplayObject.js, line 741

height :Number

The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set

Source -
    pixi/display/DisplayObjectContainer.js, line 600

hitArea :Rectangle|Circle|Ellipse|Polygon

This is the defined area that will pick up mouse / touch events. It is null by default.
Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children)

Type:

Rectangle
|

Circle
|

Ellipse
|

Polygon

Inherited From:

        PIXI.DisplayObject#hitArea

Source -
    pixi/display/DisplayObject.js, line 89

ignoreChildInput :Boolean

If ignoreChildInput  is false it will allow this objects children to be considered as valid for Input events.

If this property is true then the children will not be considered as valid for Input events.

Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down.

Source -
    pixi/display/DisplayObjectContainer.js, line 26

mask :PhaserGraphics

Sets a mask for this DisplayObject. A mask is an instance of a Graphics object.
When applied it limits the visible area of this DisplayObject to the shape of the mask.
Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer.
To remove a mask, set this property to null.

Inherited From:

        PIXI.DisplayObject#mask

Source -
    pixi/display/DisplayObject.js, line 706

<readonly> parent :PIXIDisplayObjectContainer

The parent DisplayObjectContainer that this DisplayObject is a child of.
All DisplayObjects must belong to a parent in order to be rendered.
The root parent is the Stage object. This property is set automatically when the
DisplayObject is added to, or removed from, a DisplayObjectContainer.

Inherited From:

        PIXI.DisplayObject#parent

Source -
    pixi/display/DisplayObject.js, line 107

pivot :PIXIPoint

The pivot point of this DisplayObject that it rotates around. The values are expressed
in pixel values.

Inherited From:

        PIXI.DisplayObject#pivot

Source -
    pixi/display/DisplayObject.js, line 43

position :PIXIPoint

The coordinates, in pixels, of this DisplayObject, relative to its parent container.

The value of this property does not reflect any positioning happening further up the display list.
To obtain that value please see the worldPosition property.

Inherited From:

        PIXI.DisplayObject#position

Source -
    pixi/display/DisplayObject.js, line 20

renderable :Boolean

Should this DisplayObject be rendered by the renderer? An object with a renderable value of
false is skipped during the render pass.

Inherited From:

        PIXI.DisplayObject#renderable

Source -
    pixi/display/DisplayObject.js, line 98

rotation :Number

The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on
a right-handed orientation.

The value of this property does not reflect any rotation happening further up the display list.
To obtain that value please see the worldRotation property.

Inherited From:

        PIXI.DisplayObject#rotation

Source -
    pixi/display/DisplayObject.js, line 51

scale :PIXIPoint

The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject
at its default size. A value of 0.5 would scale this DisplayObject by half, and so on.

The value of this property does not reflect any scaling happening further up the display list.
To obtain that value please see the worldScale property.

Inherited From:

        PIXI.DisplayObject#scale

Source -
    pixi/display/DisplayObject.js, line 31

visible :Boolean

The visibility of this DisplayObject. A value of false makes the object invisible.
A value of true makes it visible. Please note that an object with a visible value of
false is skipped during the render pass. Equally a DisplayObject with visible false will
not render any of its children.

The value of this property does not reflect any visible values set further up the display list.
To obtain that value please see the worldVisible property.

Inherited From:

        PIXI.DisplayObject#visible

Source -
    pixi/display/DisplayObject.js, line 75

width :Number

The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set

Source -
    pixi/display/DisplayObjectContainer.js, line 571

<readonly> worldAlpha :Number

The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent.
This value is the calculated total, based on the alpha values of all parents of this DisplayObjects
in the display list.

To obtain, and set, the local alpha value, see the alpha property.

Note: This property is only updated at the end of the updateTransform call, once per render. Until
that happens this property will contain values based on the previous frame. Be mindful of this if
accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.

Inherited From:

        PIXI.DisplayObject#worldAlpha

Source -
    pixi/display/DisplayObject.js, line 119

<readonly> worldPosition :PIXIPoint

The coordinates, in pixels, of this DisplayObject within the world.

This property contains the calculated total, based on the positions of all parents of this
DisplayObject in the display list.

Note: This property is only updated at the end of the updateTransform call, once per render. Until
that happens this property will contain values based on the previous frame. Be mindful of this if
accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.

Inherited From:

        PIXI.DisplayObject#worldPosition

Source -
    pixi/display/DisplayObject.js, line 150

<readonly> worldRotation :Number

The rotation, in radians, of this DisplayObject.

This property contains the calculated total, based on the rotations of all parents of this
DisplayObject in the display list.

Note: This property is only updated at the end of the updateTransform call, once per render. Until
that happens this property will contain values based on the previous frame. Be mindful of this if
accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.

Inherited From:

        PIXI.DisplayObject#worldRotation

Source -
    pixi/display/DisplayObject.js, line 180

<readonly> worldScale :PIXIPoint

The global scale of this DisplayObject.

This property contains the calculated total, based on the scales of all parents of this
DisplayObject in the display list.

Note: This property is only updated at the end of the updateTransform call, once per render. Until
that happens this property will contain values based on the previous frame. Be mindful of this if
accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.

Inherited From:

        PIXI.DisplayObject#worldScale

Source -
    pixi/display/DisplayObject.js, line 165

<readonly> worldTransform :PhaserMatrix

The current transform of this DisplayObject.

This property contains the calculated total, based on the transforms of all parents of this
DisplayObject in the display list.

Note: This property is only updated at the end of the updateTransform call, once per render. Until
that happens this property will contain values based on the previous frame. Be mindful of this if
accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.

Inherited From:

        PIXI.DisplayObject#worldTransform

Source -
    pixi/display/DisplayObject.js, line 135

worldVisible :Boolean

Indicates if this DisplayObject is visible, based on it, and all of its parents, visible property values.

Inherited From:

        PIXI.DisplayObject#worldVisible

Source -
    pixi/display/DisplayObject.js, line 663

x :Number

The horizontal position of the DisplayObject, in pixels, relative to its parent.
If you need the world position of the DisplayObject, use DisplayObject.worldPosition instead.

Inherited From:

        PIXI.DisplayObject#x

Source -
    pixi/display/DisplayObject.js, line 619

y :Number

The vertical position of the DisplayObject, in pixels, relative to its parent.
If you need the world position of the DisplayObject, use DisplayObject.worldPosition instead.

Inherited From:

        PIXI.DisplayObject#y

Source -
    pixi/display/DisplayObject.js, line 641

Methods

addChild(child) → {PIXI.DisplayObject}

Adds a child to the container.

Parameters:

		Name

		Type

		Description

                child

PIXI.DisplayObject

The DisplayObject to add to the container

Returns:

PIXI.DisplayObject

 -

The child that was added.

Source -
    pixi/display/DisplayObjectContainer.js, line 42

addChildAt(child, index) → {PIXI.DisplayObject}

Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown

Parameters:

		Name

		Type

		Description

                child

PIXI.DisplayObject

The child to add

                index

Number

The index to place the child in

Returns:

PIXI.DisplayObject

 -

The child that was added.

Source -
    pixi/display/DisplayObjectContainer.js, line 55

contains(child) → {Boolean}

Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself.

Parameters:

		Name

		Type

		Description

                child

PIXI.DisplayObject

-

Returns:

Boolean

 -

Source -
    pixi/display/DisplayObjectContainer.js, line 449

getBounds(targetCoordinateSpace) → {Rectangle}

Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration.

Parameters:

		Name

		Type

		Argument

		Description

                targetCoordinateSpace

PIXIDisplayObject
|

PhaserMatrix

                    <optional>

Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object.

Returns:

Rectangle

 -

The rectangular bounding area

Source -
    pixi/display/DisplayObjectContainer.js, line 280

getChildAt(index) → {PIXI.DisplayObject}

Returns the child at the specified index

Parameters:

		Name

		Type

		Description

                index

Number

The index to get the child from

Returns:

PIXI.DisplayObject

 -

The child at the given index, if any.

Source -
    pixi/display/DisplayObjectContainer.js, line 153

getChildIndex(child) → {Number}

Returns the index position of a child DisplayObject instance

Parameters:

		Name

		Type

		Description

                child

PIXI.DisplayObject

The DisplayObject instance to identify

Returns:

Number

 -

The index position of the child display object to identify

Source -
    pixi/display/DisplayObjectContainer.js, line 112

getLocalBounds() → {Rectangle}

Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration.

Returns:

Rectangle

 -

The rectangular bounding area

Source -
    pixi/display/DisplayObjectContainer.js, line 437

removeChild(child) → {PIXI.DisplayObject}

Removes a child from the container.

Parameters:

		Name

		Type

		Description

                child

PIXI.DisplayObject

The DisplayObject to remove

Returns:

PIXI.DisplayObject

 -

The child that was removed.

Source -
    pixi/display/DisplayObjectContainer.js, line 171

removeChildAt(index) → {PIXI.DisplayObject}

Removes a child from the specified index position.

Parameters:

		Name

		Type

		Description

                index

Number

The index to get the child from

Returns:

PIXI.DisplayObject

 -

The child that was removed.

Source -
    pixi/display/DisplayObjectContainer.js, line 191

removeChildren(beginIndex, endIndex)

Removes all children from this container that are within the begin and end indexes.

Parameters:

		Name

		Type

		Description

                beginIndex

Number

The beginning position. Default value is 0.

                endIndex

Number

The ending position. Default value is size of the container.

Source -
    pixi/display/DisplayObjectContainer.js, line 213

setChildIndex(child, index)

Changes the position of an existing child in the display object container

Parameters:

		Name

		Type

		Description

                child

PIXI.DisplayObject

The child DisplayObject instance for which you want to change the index number

                index

Number

The resulting index number for the child display object

Source -
    pixi/display/DisplayObjectContainer.js, line 132

swapChildren(child, child2)

Swaps the position of 2 Display Objects within this container.

Parameters:

		Name

		Type

		Description

                child

PIXI.DisplayObject

-

                child2

PIXI.DisplayObject

-

Source -
    pixi/display/DisplayObjectContainer.js, line 85

		Phaser Copyright © 2012-2016 Photon Storm Ltd.

		Documentation generated by JSDoc 3.5.3
		on Fri Jul 21 2017 07:19:26 GMT-0700 (PDT) using the DocStrap template.


text:
export function invoke (...args) {
  return global.UniServiceJSBridge.invokeCallbackHandler(...args)
}

export function publish (name, ...args) {
  return global.UniServiceJSBridge.emit('api.' + name, ...args)
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package com.mxgraph.swing.util (JGraph X 3.4.0.0 API Specification)</title>
<meta name="date" content="2015-08-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

JGraph X 3.4.0.0

Prev

Next

Frames

No Frames

All Classes

Uses of Package
com.mxgraph.swing.util

Packages that use com.mxgraph.swing.util

Package
Description

com.mxgraph.swing

This package contains the main component for JFC/Swing, namely the graph
  component and the outline component.

com.mxgraph.swing.handler

This package contains all classes required for mouse event handling in
  JFC/Swing.

com.mxgraph.swing.util

This package contains all utility classes that require JFC/Swing, namely for
  mouse event handling, drag and drop, actions and overlays.

Classes in com.mxgraph.swing.util used by com.mxgraph.swing

Class and Description

mxICellOverlay

Classes in com.mxgraph.swing.util used by com.mxgraph.swing.handler

Class and Description

mxGraphTransferable

mxMouseAdapter

Classes in com.mxgraph.swing.util used by com.mxgraph.swing.util

Class and Description

mxAnimation

Baseclass for all timer-based animations.

mxICellOverlay

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

JGraph X 3.4.0.0

Prev

Next

Frames

No Frames

All Classes

Copyright (c) 2010 Gaudenz Alder. All rights reserved.


text:
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif

using System;
using System.Collections.Generic;
using System.Reflection;

namespace XLua.CSObjectWrap
{
    public class XLua_Gen_Initer_Register__
	{
	    static XLua_Gen_Initer_Register__()
        {
		    XLua.LuaEnv.AddIniter((luaenv, translator) => {

				translator.DelayWrapLoader(typeof(LuaBehaviour), LuaBehaviourWrap.__Register);

				translator.DelayWrapLoader(typeof(XLuaTest.Pedding), XLuaTestPeddingWrap.__Register);

				translator.DelayWrapLoader(typeof(XLuaTest.MyStruct), XLuaTestMyStructWrap.__Register);

				translator.DelayWrapLoader(typeof(XLuaTest.MyEnum), XLuaTestMyEnumWrap.__Register);

				translator.DelayWrapLoader(typeof(XLuaTest.NoGc), XLuaTestNoGcWrap.__Register);

				translator.DelayWrapLoader(typeof(Coroutine_Runner), Coroutine_RunnerWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.WaitForSeconds), UnityEngineWaitForSecondsWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.WWW), UnityEngineWWWWrap.__Register);

				translator.DelayWrapLoader(typeof(Foo1Parent), Foo1ParentWrap.__Register);

				translator.DelayWrapLoader(typeof(Foo2Parent), Foo2ParentWrap.__Register);

				translator.DelayWrapLoader(typeof(Foo1Child), Foo1ChildWrap.__Register);

				translator.DelayWrapLoader(typeof(Foo2Child), Foo2ChildWrap.__Register);

				translator.DelayWrapLoader(typeof(Foo), FooWrap.__Register);

				translator.DelayWrapLoader(typeof(FooExtension), FooExtensionWrap.__Register);

				translator.DelayWrapLoader(typeof(object), SystemObjectWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Object), UnityEngineObjectWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Vector2), UnityEngineVector2Wrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Vector3), UnityEngineVector3Wrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Vector4), UnityEngineVector4Wrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Quaternion), UnityEngineQuaternionWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Color), UnityEngineColorWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Ray), UnityEngineRayWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Bounds), UnityEngineBoundsWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Ray2D), UnityEngineRay2DWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Time), UnityEngineTimeWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.GameObject), UnityEngineGameObjectWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Component), UnityEngineComponentWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Behaviour), UnityEngineBehaviourWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Transform), UnityEngineTransformWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Resources), UnityEngineResourcesWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.TextAsset), UnityEngineTextAssetWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Keyframe), UnityEngineKeyframeWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.AnimationCurve), UnityEngineAnimationCurveWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.AnimationClip), UnityEngineAnimationClipWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.MonoBehaviour), UnityEngineMonoBehaviourWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.ParticleSystem), UnityEngineParticleSystemWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.SkinnedMeshRenderer), UnityEngineSkinnedMeshRendererWrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Renderer), UnityEngineRendererWrap.__Register);

				translator.DelayWrapLoader(typeof(System.Collections.Generic.List<int>), SystemCollectionsGenericList_1_SystemInt32_Wrap.__Register);

				translator.DelayWrapLoader(typeof(UnityEngine.Debug), UnityEngineDebugWrap.__Register);

				translator.DelayWrapLoader(typeof(Tutorial.BaseClass), TutorialBaseClassWrap.__Register);

				translator.DelayWrapLoader(typeof(Tutorial.TestEnum), TutorialTestEnumWrap.__Register);

				translator.DelayWrapLoader(typeof(Tutorial.DrivenClass), TutorialDrivenClassWrap.__Register);

				translator.DelayWrapLoader(typeof(Tutorial.DrivenClass.TestEnumInner), TutorialDrivenClassTestEnumInnerWrap.__Register);

				translator.DelayWrapLoader(typeof(Tutorial.Calc), TutorialCalcWrap.__Register);

				translator.DelayWrapLoader(typeof(Tutorial.DrivenClassExtensions), TutorialDrivenClassExtensionsWrap.__Register);

				translator.AddInterfaceBridgeCreator(typeof(InvokeLua.ICalc), InvokeLuaICalcBridge.__Create);

				translator.AddInterfaceBridgeCreator(typeof(XLuaTest.IExchanger), XLuaTestIExchangerBridge.__Create);

				translator.AddInterfaceBridgeCreator(typeof(System.Collections.IEnumerator), SystemCollectionsIEnumeratorBridge.__Create);

				translator.AddInterfaceBridgeCreator(typeof(CSCallLua.ItfD), CSCallLuaItfDBridge.__Create);

			});
		}

	}

}
namespace XLua
{
	public partial class ObjectTranslator
	{
		static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ s_gen_reg_dumb_obj = new XLua.CSObjectWrap.XLua_Gen_Initer_Register__();
		static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ gen_reg_dumb_obj {get{return s_gen_reg_dumb_obj;}}
	}

	public static partial class Utils
    {

	    static Utils()
		{
		    extension_method_map = new Dictionary<Type, IEnumerable<MethodInfo>>()
			{

			};
		}
	}
}


text:
package com.amazonaws.services.guardduty.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetInvitationsCountResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The number of received invitations.
     *

     */
    private Integer invitationsCount;

    /**
     *

     * The number of received invitations.
     *

     *
     * @param invitationsCount
     *        The number of received invitations.
     */

    public void setInvitationsCount(Integer invitationsCount) {
        this.invitationsCount = invitationsCount;
    }

    /**
     *

     * The number of received invitations.
     *

     *
     * @return The number of received invitations.
     */

    public Integer getInvitationsCount() {
        return this.invitationsCount;
    }

    /**
     *

     * The number of received invitations.
     *

     *
     * @param invitationsCount
     *        The number of received invitations.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetInvitationsCountResult withInvitationsCount(Integer invitationsCount) {
        setInvitationsCount(invitationsCount);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getInvitationsCount() != null)
            sb.append("InvitationsCount: ").append(getInvitationsCount());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetInvitationsCountResult == false)
            return false;
        GetInvitationsCountResult other = (GetInvitationsCountResult) obj;
        if (other.getInvitationsCount() == null ^ this.getInvitationsCount() == null)
            return false;
        if (other.getInvitationsCount() != null && other.getInvitationsCount().equals(this.getInvitationsCount()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getInvitationsCount() == null) ? 0 : getInvitationsCount().hashCode());
        return hashCode;
    }

    @Override
    public GetInvitationsCountResult clone() {
        try {
            return (GetInvitationsCountResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
// Copyright 2012 The win Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build windows

package win

type VARIANT struct {
	Vt       VARTYPE
	reserved [22]byte
}

type VAR_I4 struct {
	vt        VARTYPE
	reserved1 [6]byte
	lVal      int32
	reserved2 [12]byte
}

type VAR_UI4 struct {
	vt        VARTYPE
	reserved1 [6]byte
	ulVal     uint32
	reserved2 [12]byte
}

type VAR_BOOL struct {
	vt        VARTYPE
	reserved1 [6]byte
	boolVal   VARIANT_BOOL
	reserved2 [14]byte
}

type VAR_BSTR struct {
	vt        VARTYPE
	reserved1 [6]byte
	bstrVal   *uint16 /*BSTR*/
	reserved2 [8]byte
}

type VAR_PDISP struct {
	vt        VARTYPE
	reserved1 [6]byte
	pdispVal  *IDispatch
	reserved2 [8]byte
}

type VAR_PSAFEARRAY struct {
	vt        VARTYPE
	reserved1 [6]byte
	parray    *SAFEARRAY
	reserved2 [8]byte
}

type VAR_PVAR struct {
	vt        VARTYPE
	reserved1 [6]byte
	pvarVal   *VARIANT
	reserved2 [8]byte
}

type VAR_PBOOL struct {
	vt        VARTYPE
	reserved1 [6]byte
	pboolVal  *VARIANT_BOOL
	reserved2 [8]byte
}

type VAR_PPDISP struct {
	vt        VARTYPE
	reserved1 [6]byte
	ppdispVal **IDispatch
	reserved2 [8]byte
}


text:
export default { title: 'Select/Cascade' };

export const RTL = () => `

        <select>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
        </select>
        <svg class="icon icon--dropdown" focusable="false" height="8" width="8" aria-hidden="true">
            <use xlink:href="#icon-dropdown"></use>
        </svg>

`;

export const fontSize = () => `

    <select>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
    </select>
    <svg class="icon icon--dropdown" focusable="false" height="8" width="8" aria-hidden="true">
        <use xlink:href="#icon-dropdown"></use>
    </svg>

`;

export const color = () => `

    <select>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
    </select>
    <svg class="icon icon--dropdown" focusable="false" height="8" width="8" aria-hidden="true">
        <use xlink:href="#icon-dropdown"></use>
    </svg>

`;


text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.lib.packages;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;

import com.google.devtools.build.lib.events.util.EventCollectionApparatus;
import com.google.devtools.build.lib.packages.util.PackageFactoryApparatus;
import com.google.devtools.build.lib.testutil.Scratch;
import com.google.devtools.build.lib.vfs.Path;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * A test for {@link InputFile}.
 */
@RunWith(JUnit4.class)
public class InputFileTest {

  private Path pathX;
  private Path pathY;
  private Package pkg;

  private EventCollectionApparatus events = new EventCollectionApparatus();
  private Scratch scratch = new Scratch("/workspace");
  private PackageFactoryApparatus packages = new PackageFactoryApparatus(events.reporter());

  @Before
  public final void writeFiles() throws Exception  {
    Path buildfile =
        scratch.file(
            "pkg/BUILD",
            "genrule(name = 'dummy', ",
            "        cmd = '', ",
            "        outs = [], ",
            "        srcs = ['x', 'subdir/y'])");
    pkg = packages.createPackage("pkg", buildfile);
    events.assertNoWarningsOrErrors();

    this.pathX = scratch.file("pkg/x", "blah");
    this.pathY = scratch.file("pkg/subdir/y", "blah blah");
  }

  private static void checkPathMatches(InputFile input, Path expectedPath) {
    assertEquals(expectedPath, input.getPath());
  }

  private static void checkName(InputFile input, String expectedName) {
    assertEquals(expectedName, input.getName());
  }

  private static void checkLabel(InputFile input, String expectedLabelString) {
    assertEquals(expectedLabelString, input.getLabel().toString());
  }

  @Test
  public void testGetAssociatedRule() throws Exception {
    assertNull(null, pkg.getTarget("x").getAssociatedRule());
  }

  @Test
  public void testInputFileInPackageDirectory() throws NoSuchTargetException {
    InputFile inputFileX = (InputFile) pkg.getTarget("x");
    checkPathMatches(inputFileX, pathX);
    checkName(inputFileX, "x");
    checkLabel(inputFileX, "//pkg:x");
    assertEquals("source file", inputFileX.getTargetKind());
  }

  @Test
  public void testInputFileInSubdirectory() throws NoSuchTargetException {
    InputFile inputFileY = (InputFile) pkg.getTarget("subdir/y");
    checkPathMatches(inputFileY, pathY);
    checkName(inputFileY, "subdir/y");
    checkLabel(inputFileY, "//pkg:subdir/y");
  }

  @Test
  public void testEquivalenceRelation() throws NoSuchTargetException {
    InputFile inputFileX = (InputFile) pkg.getTarget("x");
    assertSame(pkg.getTarget("x"), inputFileX);
    InputFile inputFileY = (InputFile) pkg.getTarget("subdir/y");
    assertSame(pkg.getTarget("subdir/y"), inputFileY);
    assertEquals(inputFileX, inputFileX);
    assertFalse(inputFileX.equals(inputFileY));
    assertFalse(inputFileY.equals(inputFileX));
  }
}


text:
package swarm

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"strconv"
	"sync"
	"testing"
	"time"

	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/test"
	"github.com/libp2p/go-libp2p-core/transport"

	ma "github.com/multiformats/go-multiaddr"
	mafmt "github.com/multiformats/go-multiaddr-fmt"
)

func addrWithPort(p int) ma.Multiaddr {
	return ma.StringCast(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", p))
}

// in these tests I use addresses with tcp ports over a certain number to
// signify 'good' addresses that will succeed, and addresses below that number
// will fail. This lets us more easily test these different scenarios.
func tcpPortOver(a ma.Multiaddr, n int) bool {
	port, err := a.ValueForProtocol(ma.P_TCP)
	if err != nil {
		panic(err)
	}

	pnum, err := strconv.Atoi(port)
	if err != nil {
		panic(err)
	}

	return pnum > n
}

func tryDialAddrs(ctx context.Context, l *dialLimiter, p peer.ID, addrs []ma.Multiaddr, res chan dialResult) {
	for _, a := range addrs {
		l.AddDialJob(&dialJob{
			ctx:  ctx,
			peer: p,
			addr: a,
			resp: res,
		})
	}
}

func hangDialFunc(hang chan struct{}) dialfunc {
	return func(ctx context.Context, p peer.ID, a ma.Multiaddr) (transport.CapableConn, error) {
		if mafmt.UTP.Matches(a) {
			return transport.CapableConn(nil), nil
		}

		_, err := a.ValueForProtocol(ma.P_CIRCUIT)
		if err == nil {
			return transport.CapableConn(nil), nil
		}

		if tcpPortOver(a, 10) {
			return transport.CapableConn(nil), nil
		}

		<-hang
		return nil, fmt.Errorf("test bad dial")
	}
}

func TestLimiterBasicDials(t *testing.T) {
	hang := make(chan struct{})
	defer close(hang)

	l := newDialLimiterWithParams(hangDialFunc(hang), ConcurrentFdDials, 4)

	bads := []ma.Multiaddr{addrWithPort(1), addrWithPort(2), addrWithPort(3), addrWithPort(4)}
	good := addrWithPort(20)

	resch := make(chan dialResult)
	pid := peer.ID("testpeer")
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	tryDialAddrs(ctx, l, pid, bads, resch)

	l.AddDialJob(&dialJob{
		ctx:  ctx,
		peer: pid,
		addr: good,
		resp: resch,
	})

	select {
	case <-resch:
		t.Fatal("no dials should have completed!")
	case <-time.After(time.Millisecond * 100):
	}

	// complete a single hung dial
	hang <- struct{}{}

	select {
	case r := <-resch:
		if r.Err == nil {
			t.Fatal("should have gotten failed dial result")
		}
	case <-time.After(time.Second):
		t.Fatal("timed out waiting for dial completion")
	}

	select {
	case r := <-resch:
		if r.Err != nil {
			t.Fatal("expected second result to be success!")
		}
	case <-time.After(time.Second):
	}
}

func TestFDLimiting(t *testing.T) {
	hang := make(chan struct{})
	defer close(hang)
	l := newDialLimiterWithParams(hangDialFunc(hang), 16, 5)

	bads := []ma.Multiaddr{addrWithPort(1), addrWithPort(2), addrWithPort(3), addrWithPort(4)}
	pids := []peer.ID{"testpeer1", "testpeer2", "testpeer3", "testpeer4"}
	goodTCP := addrWithPort(20)

	ctx := context.Background()
	resch := make(chan dialResult)

	// take all fd limit tokens with hang dials
	for _, pid := range pids {
		tryDialAddrs(ctx, l, pid, bads, resch)
	}

	// these dials should work normally, but will hang because we have taken
	// up all the fd limiting
	for _, pid := range pids {
		l.AddDialJob(&dialJob{
			ctx:  ctx,
			peer: pid,
			addr: goodTCP,
			resp: resch,
		})
	}

	select {
	case <-resch:
		t.Fatal("no dials should have completed!")
	case <-time.After(time.Millisecond * 100):
	}

	pid5 := peer.ID("testpeer5")
	utpaddr := ma.StringCast("/ip4/127.0.0.1/udp/7777/utp")

	// This should complete immediately since utp addresses arent blocked by fd rate limiting
	l.AddDialJob(&dialJob{ctx: ctx, peer: pid5, addr: utpaddr, resp: resch})

	select {
	case res := <-resch:
		if res.Err != nil {
			t.Fatal("should have gotten successful response")
		}
	case <-time.After(time.Second * 5):
		t.Fatal("timeout waiting for utp addr success")
	}

	// A relay address with tcp transport will complete because we do not consume fds for dials
	// with relay addresses as the fd will be consumed when we actually dial the relay server.
	pid6 := test.RandPeerIDFatal(t)
	relayAddr := ma.StringCast(fmt.Sprintf("/ip4/127.0.0.1/tcp/20/p2p-circuit/p2p/%s", pid6))
	l.AddDialJob(&dialJob{ctx: ctx, peer: pid6, addr: relayAddr, resp: resch})

	select {
	case res := <-resch:
		if res.Err != nil {
			t.Fatal("should have gotten successful response")
		}
	case <-time.After(time.Second * 5):
		t.Fatal("timeout waiting for relay addr success")
	}
}

func TestTokenRedistribution(t *testing.T) {
	var lk sync.Mutex
	hangchs := make(map[peer.ID]chan struct{})
	df := func(ctx context.Context, p peer.ID, a ma.Multiaddr) (transport.CapableConn, error) {
		if tcpPortOver(a, 10) {
			return (transport.CapableConn)(nil), nil
		}

		lk.Lock()
		ch := hangchs[p]
		lk.Unlock()
		<-ch
		return nil, fmt.Errorf("test bad dial")
	}
	l := newDialLimiterWithParams(df, 8, 4)

	bads := []ma.Multiaddr{addrWithPort(1), addrWithPort(2), addrWithPort(3), addrWithPort(4)}
	pids := []peer.ID{"testpeer1", "testpeer2"}

	ctx := context.Background()
	resch := make(chan dialResult)

	// take all fd limit tokens with hang dials
	for _, pid := range pids {
		hangchs[pid] = make(chan struct{})
	}

	for _, pid := range pids {
		tryDialAddrs(ctx, l, pid, bads, resch)
	}

	// add a good dial job for peer 1
	l.AddDialJob(&dialJob{
		ctx:  ctx,
		peer: pids[1],
		addr: ma.StringCast("/ip4/127.0.0.1/tcp/1001"),
		resp: resch,
	})

	select {
	case <-resch:
		t.Fatal("no dials should have completed!")
	case <-time.After(time.Millisecond * 100):
	}

	// unblock one dial for peer 0
	hangchs[pids[0]] <- struct{}{}

	select {
	case res := <-resch:
		if res.Err == nil {
			t.Fatal("should have only been a failure here")
		}
	case <-time.After(time.Millisecond * 100):
		t.Fatal("expected a dial failure here")
	}

	select {
	case <-resch:
		t.Fatal("no more dials should have completed!")
	case <-time.After(time.Millisecond * 100):
	}

	// add a bad dial job to peer 0 to fill their rate limiter
	// and test that more dials for this peer won't interfere with peer 1's successful dial incoming
	l.AddDialJob(&dialJob{
		ctx:  ctx,
		peer: pids[0],
		addr: addrWithPort(7),
		resp: resch,
	})

	hangchs[pids[1]] <- struct{}{}

	// now one failed dial from peer 1 should get through and fail
	// which will in turn unblock the successful dial on peer 1
	select {
	case res := <-resch:
		if res.Err == nil {
			t.Fatal("should have only been a failure here")
		}
	case <-time.After(time.Millisecond * 100):
		t.Fatal("expected a dial failure here")
	}

	select {
	case res := <-resch:
		if res.Err != nil {
			t.Fatal("should have succeeded!")
		}
	case <-time.After(time.Millisecond * 100):
		t.Fatal("should have gotten successful dial")
	}
}

func TestStressLimiter(t *testing.T) {
	df := func(ctx context.Context, p peer.ID, a ma.Multiaddr) (transport.CapableConn, error) {
		if tcpPortOver(a, 1000) {
			return transport.CapableConn(nil), nil
		}

		time.Sleep(time.Millisecond * time.Duration(5+rand.Intn(100)))
		return nil, fmt.Errorf("test bad dial")
	}

	l := newDialLimiterWithParams(df, 20, 5)

	var bads []ma.Multiaddr
	for i := 0; i < 100; i++ {
		bads = append(bads, addrWithPort(i))
	}

	addresses := append(bads, addrWithPort(2000))
	success := make(chan struct{})

	for i := 0; i < 20; i++ {
		go func(id peer.ID) {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

			resp := make(chan dialResult)
			time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond)
			for _, i := range rand.Perm(len(addresses)) {
				l.AddDialJob(&dialJob{
					addr: addresses[i],
					ctx:  ctx,
					peer: id,
					resp: resp,
				})
			}

			for res := range resp {
				if res.Err == nil {
					success <- struct{}{}
					return
				}
			}
		}(peer.ID(fmt.Sprintf("testpeer%d", i)))
	}

	for i := 0; i < 20; i++ {
		select {
		case <-success:
		case <-time.After(time.Minute):
			t.Fatal("expected a success within five seconds")
		}
	}
}

func TestFDLimitUnderflow(t *testing.T) {
	df := func(ctx context.Context, p peer.ID, addr ma.Multiaddr) (transport.CapableConn, error) {
		select {
		case <-ctx.Done():
		case <-time.After(5 * time.Second):
		}
		return nil, fmt.Errorf("df timed out")
	}

	const fdLimit = 20
	l := newDialLimiterWithParams(df, fdLimit, 3)

	var addrs []ma.Multiaddr
	for i := 0; i <= 1000; i++ {
		addrs = append(addrs, addrWithPort(i))
	}

	wg := sync.WaitGroup{}
	const num = 3 * fdLimit
	wg.Add(num)
	errs := make(chan error, num)
	for i := 0; i < num; i++ {
		go func(id peer.ID, i int) {
			defer wg.Done()
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

			resp := make(chan dialResult)
			l.AddDialJob(&dialJob{
				addr: addrs[i],
				ctx:  ctx,
				peer: id,
				resp: resp,
			})

			for res := range resp {
				if res.Err != nil {
					return
				}
				errs <- errors.New("got dial res, but shouldn't")
			}
		}(peer.ID(fmt.Sprintf("testpeer%d", i%20)), i)
	}

	go func() {
		wg.Wait()
		close(errs)
	}()

	for err := range errs {
		t.Fatal(err)
	}

	l.lk.Lock()
	fdConsuming := l.fdConsuming
	l.lk.Unlock()

	if fdConsuming < 0 {
		t.Fatalf("l.fdConsuming < 0")
	}
}


text:
package org.traccar.protocol;

import org.jboss.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.DeviceSession;
import org.traccar.helper.Parser;
import org.traccar.helper.PatternBuilder;
import org.traccar.helper.UnitsConverter;
import org.traccar.model.Position;

import java.net.SocketAddress;
import java.util.regex.Pattern;

public class CguardProtocolDecoder extends BaseProtocolDecoder {

    public CguardProtocolDecoder(CguardProtocol protocol) {
        super(protocol);
    }

    private static final Pattern PATTERN_NV = new PatternBuilder()
            .text("NV:")
            .number("(dd)(dd)(dd) ")             // date (yymmdd)
            .number("(dd)(dd)(dd)")              // time (hhmmss)
            .number(":(-?d+.d+)")                // longitude
            .number(":(-?d+.d+)")                // latitude
            .number(":(d+.?d*)")                 // speed
            .number(":(?:NAN|(d+.?d*))")         // accuracy
            .number(":(?:NAN|(d+.?d*))")         // course
            .number(":(?:NAN|(d+.?d*))").optional() // altitude
            .compile();

    private static final Pattern PATTERN_BC = new PatternBuilder()
            .text("BC:")
            .number("(dd)(dd)(dd) ")             // date (yymmdd)
            .number("(dd)(dd)(dd):")             // time (hhmmss)
            .expression("(.+)")                  // data
            .compile();

    private Position decodePosition(DeviceSession deviceSession, String sentence) {

        Parser parser = new Parser(PATTERN_NV, sentence);
        if (!parser.matches()) {
            return null;
        }

        Position position = new Position();
        position.setProtocol(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        position.setTime(parser.nextDateTime());

        position.setValid(true);
        position.setLatitude(parser.nextDouble(0));
        position.setLongitude(parser.nextDouble(0));
        position.setSpeed(UnitsConverter.knotsFromKph(parser.nextDouble(0)));

        position.setAccuracy(parser.nextDouble(0));

        position.setCourse(parser.nextDouble(0));
        position.setAltitude(parser.nextDouble(0));

        return position;
    }

    private Position decodeStatus(DeviceSession deviceSession, String sentence) {

        Parser parser = new Parser(PATTERN_BC, sentence);
        if (!parser.matches()) {
            return null;
        }

        Position position = new Position();
        position.setProtocol(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        getLastLocation(position, parser.nextDateTime());

        String[] data = parser.next().split(":");
        for (int i = 0; i < data.length / 2; i++) {
            String key = data[i * 2];
            String value = data[i * 2 + 1];
            switch (key) {
                case "CSQ1":
                    position.set(Position.KEY_RSSI, Integer.parseInt(value));
                    break;
                case "NSQ1":
                    position.set(Position.KEY_SATELLITES, Integer.parseInt(value));
                    break;
                case "BAT1":
                    position.set(Position.KEY_BATTERY_LEVEL, Integer.parseInt(value));
                    break;
                case "PWR1":
                    position.set(Position.KEY_POWER, Double.parseDouble(value));
                    break;
                default:
                    position.set(key.toLowerCase(), value);
                    break;
            }
        }

        return position;
    }

    @Override
    protected Object decode(
            Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

        String sentence = (String) msg;

        if (sentence.startsWith("ID:") || sentence.startsWith("IDRO:")) {
            getDeviceSession(channel, remoteAddress, sentence.substring(sentence.indexOf(':') + 1));
            return null;
        }

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
        if (deviceSession == null) {
            return null;
        }

        if (sentence.startsWith("NV:")) {
            return decodePosition(deviceSession, sentence);
        } else if (sentence.startsWith("BC:")) {
            return decodeStatus(deviceSession, sentence);
        }

        return null;
    }

}


text:
/**
 * Example 78 - Using continue to start a New Iteration (Not Recommended)
 */
public class UsingContinueStartIteration {

    static boolean substring1(String query, String target) {
        nextposition:
        for (int j = 0; j <= target.length() - query.length(); j++) {
            for (int k = 0; k < query.length(); k++)
                if (target.charAt(j + k) != query.charAt(k))
                    continue nextposition;
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(substring1("sub", "substring"));
        System.out.println(substring1("super", "substring"));
    }
}


text:
try: paraview.simple
except: from paraview.simple import *
paraview.simple._DisableFirstRenderCameraReset()

Box1 = Box()

RenderView1 = GetRenderView()

DataRepresentation1 = Show()
DataRepresentation1.ScaleFactor = 0.1
DataRepresentation1.SelectionPointFieldDataArrayName = 'Normals'
DataRepresentation1.EdgeColor = [0.0, 0.0, 0.5000076295109483]

RenderView1.CameraPosition = [0.0, 0.0, 3.964592284436349]
RenderView1.CameraClippingRange = [2.9299463615919854, 5.276561168702894]
RenderView1.CameraParallelScale = 1.0366549443070232

Elevation1 = Elevation()

Elevation1.LowPoint = [-0.5, -0.5, -0.5]
Elevation1.HighPoint = [0.5, 0.5, 0.5]

# toggle the 3D widget visibility.
active_objects.source.SMProxy.InvokeEvent('UserEvent', 'ShowWidget')
RenderView1.CameraClippingRange = [2.900576837470701, 5.318021827312761]

DataRepresentation2 = Show()
DataRepresentation2.EdgeColor = [0.0, 0.0, 0.5000076295109483]
DataRepresentation2.SelectionPointFieldDataArrayName = 'Elevation'
DataRepresentation2.ColorArrayName = ('POINT_DATA', 'Elevation')
DataRepresentation2.ScaleFactor = 0.1

a1_Elevation_PVLookupTable = GetLookupTableForArray( "Elevation", 1, RGBPoints=[0.0, 0.23, 0.299, 0.754, 0.5, 0.865, 0.865, 0.865, 1.0, 0.706, 0.016, 0.15], VectorMode='Magnitude', NanColor=[0.25, 0.0, 0.0], ColorSpace='Diverging', ScalarRangeInitialized=1.0 )

a1_Elevation_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] )

DataRepresentation1.Visibility = 0

DataRepresentation2.LookupTable = a1_Elevation_PVLookupTable

a1_Elevation_PVLookupTable.ScalarOpacityFunction = a1_Elevation_PiecewiseFunction

Sphere1 = Sphere()

DataRepresentation3 = Show()
DataRepresentation3.ScaleFactor = 0.1
DataRepresentation3.SelectionPointFieldDataArrayName = 'Normals'
DataRepresentation3.EdgeColor = [0.0, 0.0, 0.5000076295109483]

RenderView1.CameraClippingRange = [2.9299463615919854, 5.276561168702894]

Transform1 = Transform( Transform="Transform" )

Transform1.Transform = "Transform"

# toggle the 3D widget visibility.
active_objects.source.SMProxy.InvokeEvent('UserEvent', 'ShowWidget')
DataRepresentation4 = Show()
DataRepresentation4.ScaleFactor = 0.1
DataRepresentation4.SelectionPointFieldDataArrayName = 'Normals'
DataRepresentation4.EdgeColor = [0.0, 0.0, 0.5000076295109483]

DataRepresentation3.Visibility = 0

Transform1.Transform.Translate = [1.0, 0.0, 0.0]

DataRepresentation4.Opacity = 0.5
DataRepresentation4.DiffuseColor = [0.8192721446555276, 0.10840009155413138, 0.14145113298237583]

Render()


text:
(function (GGRC, can) {
  'use strict';

  var tag = 'assessment-urls-list';
  var template = can.view(GGRC.mustache_path +
    '/components/assessment/urls-list.mustache');

  /**
   * Wrapper Component for rendering and managing of url lists
   */
  GGRC.Components('assessmentUrlsListComponent', {
    tag: tag,
    template: template,
    viewModel: {
      define: {
        noItemsText: {
          type: 'string',
          value: ''
        }
      },
      mappedItems: []
    }
  });
})(window.GGRC, window.can);


text:
package uk.bl.dpt.pdfextractstreams;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.Inflater;

public class PDFExtractStreams {

	public class Stream {
		String gObjinfo;
		long gStart;
		long gLength;
		public Stream(String pObjinfo, long pStart, long pLength) {
			gObjinfo = pObjinfo;
			gStart = pStart;
			gLength = pLength;
		}
	}

	private Map<String, String> pdfDirectory = new HashMap<String, String>();
	private List<Stream> streams = new LinkedList<Stream>();
	private PrintWriter gLog = null;

	/**
	 * Deflate a file
	 * @param inf in filename
	 * @param out out filename
	 * @throws IOException
	 */
	private void deflateStream(String inf, String out) throws IOException {
		try {
			File test = new File(inf);
		     // Decompress the bytes
			FileInputStream fr = new FileInputStream(test);
			byte[] in = new byte[(int) test.length()];
			fr.read(in);
			fr.close();
			FileOutputStream fos = new FileOutputStream(out);//test.getName()+".deflate");
		     Inflater decompresser = new Inflater();
		     decompresser.setInput(in, 0, in.length);
		     byte[] buf = new byte[32768];
				int bytesRead = 0;
				while(!decompresser.finished()) {
					bytesRead = decompresser.inflate(buf);
					fos.write(buf, 0, bytesRead);
				}
			fos.close();
		     decompresser.end();
		 } catch(java.io.UnsupportedEncodingException ex) {
		     // handle
		 } catch (java.util.zip.DataFormatException ex) {
		     // handle
		 }
	}

	/**
	 * Copy an output stream (also deflate it and try and identify content type)
	 * @param in input file
	 * @param out output file
	 * @param offset offset in input file
	 * @param size size of output file
	 * @throws IOException
	 */
	private File copyStream(String in, String out, long offset, long size) throws IOException {
		File o = new File(out);
		if(!o.exists()) {
			//	System.out.println("copying from local fs");
			FileInputStream fis = new FileInputStream(in);
			FileOutputStream fos = new FileOutputStream(o);
			byte[] buffer = new byte[32768];
			fis.skip(offset);
			int bytesRead = 0;
			long count = 0;
			boolean deflate = false;
			boolean compressioncheck = false;
			while(/*fis.available()>0&&*/count<size) {
				bytesRead = fis.read(buffer);
				if(!compressioncheck) {
					if(buffer[0]==120) {
						if(buffer[1]==-100) {
							deflate = true;
						}
						if(buffer[1]==-38) {
							deflate = true;
						}
						compressioncheck = true;
					}
					if(buffer[0]==72&&buffer[1]==-119) {
						deflate = true;
					}
				}
				if(!(bytesRead+count<size)) {
					bytesRead = (int)(size-count);
				}
				fos.write(buffer, 0, bytesRead);
				count += bytesRead;
			}
			fis.close();
			fos.close();
			String newOut = out;
			if(deflate) {
				newOut += ".deflate";
				deflateStream(out, newOut);
				o.delete();
				o = new File(newOut);
			}
			String ext = FormatDetector.getExt(new File(newOut)).trim();
			if(ext!=null) {
				if(ext.equals("plain")) ext = "txt";
				File n = new File(newOut+"."+ext);
				//we need to run garbage collector here so that we can rename the file!?
				System.gc();
				o.renameTo(n);
				gLog.println(o+" -> "+n);
				return n;
			}
			return new File(newOut);
		}
		return null;//file exists
	}

	/**
	 * Keep reading until match is found
	 * @param match text to match
	 * @param buf buffer to read from
	 * @return matched string
	 */
	private String chompUntil(String match, PositionReader buf) {
		String endstream = "";
		//int count = 0;
		while(true) {
			char next = buf.nextChar();
			//count++;
			String potential = endstream+next;
			if(potential.equals(match.substring(0, potential.length()))) {
				endstream = endstream+next;
				//on the right track
				if(endstream.length()==match.length()) {
					//we have a match for "match"
					break;
				}
			} else {
				endstream = "";
			}
		}
		//System.out.println("Chomped: "+count);
		return endstream;
	}

	/**
	 * Extract the directory of streams and other objects
	 * @param file pdf file to read
	 * @throws IOException
	 */
	private void extractDirectory(String file) {
		PositionReader buf = new PositionReader(file);
		String line = buf.readLine();
		if(!line.toUpperCase().startsWith("%PDF")) return;
		while(buf.ready()) {
			line = buf.readLine().trim();
			if(line.contains(" obj")) {
				//System.out.println("obj @ "+buf.getPos()+" line: "+line);
				//start of object
				//read << until >> \n endobj
				String objinfo = line;
				boolean endLoop = false;
				if(line.contains("stream")||line.contains("endobj")) {
					endLoop = true;
				}
				int bracketDepth = 0;
				char c = '\0';
				while(!endLoop) {
					c = buf.nextChar();
					while(true) {
						//chomp whitespace
						if(c!='\n') {
							if(c!='\r') {
										break;
							}
						}
						c = buf.nextChar();
					}

					//start of a new bracket
					if(c=='<'&&buf.peekNextChar()=='<') {
						bracketDepth++;
						buf.nextChar();
						objinfo += "<< ";
						continue;
					}
					if(c=='>'&&buf.peekNextChar()=='>') {
						bracketDepth--;
						buf.nextChar();
						objinfo += ">> ";

						if(bracketDepth==0) {
							//end of object
							int count = 0;
							char nextChar = buf.peekNextChar();
							//i.e. endobj or stream
							while(true) {
								if(nextChar=='e') {
									endLoop = true;
									break;//endobj
								}
								if(nextChar=='s') {
									endLoop = true;
									break;//stream
								}
								//if we shouldn't skip the char then add it to the string
								char next = buf.nextChar();
								if(next!='\n') {
									if(next!='\r') {
										objinfo += next;
									}
								}
								nextChar = buf.peekNextChar();
								count++;
								if(count>300) System.exit(-1);
							}
							if(endLoop) objinfo += buf.readLine();
							break;
						}
					}

					if(c=='e'&buf.peekNextChar()=='n') {
						//endobj?
						char[] temp = new char[5];
						for(int j=0;j<temp.length;j++) {
							temp[j] = buf.nextChar();
						}
						if(temp[0]=='n'&
								   temp[1]=='d'&
								   temp[2]=='o'&
								   temp[3]=='b'&
								   temp[4]=='j') {
							objinfo += " endobj";
							endLoop = true;
						} else {
							objinfo += c;
							for(int j=0;j<temp.length;j++) {
								objinfo+=temp[j];
							}
						}
						continue;
					}

					if(c=='s'&buf.peekNextChar()=='t') {
						//endobj?
						char[] temp = new char[5];
						for(int j=0;j<temp.length;j++) {
							temp[j] = buf.nextChar();
						}
						if(temp[0]=='t'&
								   temp[1]=='r'&
								   temp[2]=='e'&
								   temp[3]=='a'&
								   temp[4]=='m') {
							objinfo += " stream";
							// chomp whitespace
							boolean chomp = true;
							while(chomp) {
								switch(buf.peekNextChar()) {
									case '\n':
									case '\r': {
										buf.nextChar();
										break;
									}
									default: {
										chomp = false;
										break;
									}
								}
							}
							endLoop = true;
						} else {
							objinfo += c;
							for(int j=0;j<temp.length;j++) {
								objinfo+=temp[j];
							}
						}
						continue;
					}

					if(c!='\n') {
						if(c!='\r') {
							objinfo += c;
						}
					}

				}

				if(objinfo.contains("stream")) {//&&!objinfo.endsWith("endstream")) {
					System.out.println("    Stream obj: "+/*line+" "+*/objinfo);
					gLog.println("    Stream obj: "+/*line+" "+*/objinfo);

					streams.add(new Stream(/*line+" "+*/objinfo, buf.getPos(), -1));

					if(!objinfo.endsWith("endobj")) {
						String endstream = chompUntil("endstream", buf);

						if(!buf.readLine().equals("endobj")) {
							System.err.println("ERROR??? No endobj?");
						}
					}

				} else {
					if(!objinfo.trim().endsWith("endobj")) {
						//System.out.println("objinfo? "+objinfo);
						//this probably shouldn't happen
						//System.out.println("Chomping");
						gLog.println("Chomping");
						chompUntil("endobj", buf);
						objinfo+=" endobj";
					}
					//objinfo = line+" "+objinfo;//+" "+s;
					gLog.println("Non-stream obj: "+objinfo);//
					//add to pdfDirectory here
					try {
						pdfDirectory.put(objinfo.substring(0, objinfo.indexOf("obj")).trim(), objinfo.substring(objinfo.indexOf("obj")+3, objinfo.lastIndexOf("endobj")).trim());
					} catch(StringIndexOutOfBoundsException e) {
						System.out.println("Exception@ obj: "+objinfo);
					}
				}
			} else {
				if(line.equals("xref")) {
					//ignore xref entries for now
					chompUntil("%%EOF", buf);
				} else {
					//System.out.println("non-obj/xref? @~"+buf.getPos()+"\""+line+"\"");
					gLog.println("non-obj/xref? @~"+buf.getPos()+"\""+line+"\"");
				}
			}

		}

		buf.close();
	}

	private void process(String file) {

		System.out.println("Processing: "+file);

		try {
			gLog = new PrintWriter(file+".log");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Generating directory...");
		extractDirectory(file);

		System.out.println("Updating references...");
		updateReferences(file);

		System.out.println("Extracting streams...");
		extractAllFiles(file);

		gLog.close();

	}

	//extract all files to a directory (to avoid clutter)
	private void extractAllFiles(String file) {
		int i = 1;
		File dir = new File(file+".dir");
		dir.mkdirs();
		for(Stream stream:streams) {
			try {
				//System.out.println("copying #"+i+" @"+stream.gStart+" len: "+stream.gLength);
				gLog.println("copying #"+i+" @"+stream.gStart+" len: "+stream.gLength);
				final String num = stream.gObjinfo.split(" ")[0].trim();
				// FIXME: look for FlateDecode and use it!
				copyStream(file, dir.getAbsolutePath()+"/"+new File(file).getName()+"."+num/*(i++)*/, stream.gStart, stream.gLength);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void updateReferences(String file) {
		for(Stream stream:streams) {
			String lenKey = "/Length ";
			int lenIndex = stream.gObjinfo.indexOf(lenKey);
			//try different combinations to find the value for the length attribute
			int end = stream.gObjinfo.indexOf('/', lenIndex+1);
			int tmp = stream.gObjinfo.indexOf('>', lenIndex+1);
			if(end<0||(tmp>0&&tmp<end)) {
				end = tmp;
			}
			//recover the length attribute
			//System.out.println("stream: "+stream.gObjinfo+" "+end);
			String lenValue = stream.gObjinfo.substring(lenIndex+lenKey.length(), end).trim();
			if(lenValue.endsWith("R")) {
				//this is a reference to a size object (eugh) - it only contains the size!!!
				//we will just store the objinfo here and reconcile it against the pdfDirectory
				//later as this may contain forward references
				long actualLength = new Integer(pdfDirectory.get(lenValue.substring(0, lenValue.lastIndexOf("R")).trim()));
				stream.gLength = actualLength;
			} else {
				stream.gLength = new Integer(lenValue);
			}
		}
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		PDFExtractStreams pdfe = null;
		for(String s:args) {
			if(new File(s).exists()) {
				pdfe = new PDFExtractStreams();
				pdfe.process(s);
			}
		}

	}

}


text:
<?=$Header;?>

                        <audio id="ctrlaudioMoreInfo" class="audio-control" controls="controls" runat="server" autoplay>
                               <source src='resources/audio/moreinfo/1.wav'></source>
                        </audio>

                            Start

<?=$Footer;?>


text:
#ifndef MODULES_CONGESTION_CONTROLLER_GOOG_CC_TRENDLINE_ESTIMATOR_H_
#define MODULES_CONGESTION_CONTROLLER_GOOG_CC_TRENDLINE_ESTIMATOR_H_

#include <stddef.h>
#include <stdint.h>

#include <deque>
#include <utility>

#include BOSS_WEBRTC_U_modules__congestion_controller__goog_cc__delay_increase_detector_interface_h //original-code:"modules/congestion_controller/goog_cc/delay_increase_detector_interface.h"
#include BOSS_WEBRTC_U_rtc_base__constructormagic_h //original-code:"rtc_base/constructormagic.h"

namespace webrtc {

class TrendlineEstimator : public DelayIncreaseDetectorInterface {
 public:
  // |window_size| is the number of points required to compute a trend line.
  // |smoothing_coef| controls how much we smooth out the delay before fitting
  // the trend line. |threshold_gain| is used to scale the trendline slope for
  // comparison to the old threshold. Once the old estimator has been removed
  // (or the thresholds been merged into the estimators), we can just set the
  // threshold instead of setting a gain.
  TrendlineEstimator(size_t window_size,
                     double smoothing_coef,
                     double threshold_gain);

  ~TrendlineEstimator() override;

  // Update the estimator with a new sample. The deltas should represent deltas
  // between timestamp groups as defined by the InterArrival class.
  void Update(double recv_delta_ms,
              double send_delta_ms,
              int64_t arrival_time_ms) override;

  BandwidthUsage State() const override;

  // Returns the estimated trend k multiplied by some gain.
  // 0 < k < 1   ->  the delay increases, queues are filling up
  //   k == 0    ->  the delay does not change
  //   k < 0     ->  the delay decreases, queues are being emptied
  double trendline_slope() const { return trendline_ * threshold_gain_; }

  // Returns the number of deltas which the current estimator state is based on.
  unsigned int num_of_deltas() const { return num_of_deltas_; }

 private:
  void Detect(double offset,
              double ts_delta,
              int num_of_deltas,
              int64_t now_ms);

  void UpdateThreshold(double modified_offset, int64_t now_ms);

  // Parameters.
  const size_t window_size_;
  const double smoothing_coef_;
  const double threshold_gain_;
  // Used by the existing threshold.
  unsigned int num_of_deltas_;
  // Keep the arrival times small by using the change from the first packet.
  int64_t first_arrival_time_ms_;
  // Exponential backoff filtering.
  double accumulated_delay_;
  double smoothed_delay_;
  // Linear least squares regression.
  std::deque<std::pair<double, double>> delay_hist_;
  double trendline_;

  const double k_up_;
  const double k_down_;
  double overusing_time_threshold_;
  double threshold_;
  int64_t last_update_ms_;
  double prev_offset_;
  double time_over_using_;
  int overuse_counter_;
  BandwidthUsage hypothesis_;

  RTC_DISALLOW_COPY_AND_ASSIGN(TrendlineEstimator);
};
}  // namespace webrtc

#endif  // MODULES_CONGESTION_CONTROLLER_GOOG_CC_TRENDLINE_ESTIMATOR_H_


text:
package com.github.antag99.retinazer.system;

import org.openjdk.jmh.infra.Blackhole;

import com.github.antag99.retinazer.EntityProcessorSystem;
import com.github.antag99.retinazer.Family;
import com.github.antag99.retinazer.Mapper;
import com.github.antag99.retinazer.SkipWire;
import com.github.antag99.retinazer.component.PlainPosition;

public class PlainPositionSystem extends EntityProcessorSystem {
    Mapper<PlainPosition> positionMapper;

    @SkipWire
    Blackhole voidness = new Blackhole();

    @SuppressWarnings("unchecked")
    public PlainPositionSystem() {
        super(Family.with(PlainPosition.class));
    }

    @Override
    protected void process(int e) {
        PlainPosition pos = positionMapper.get(e);
        pos.x += 1;
        pos.y -= 1;

        voidness.consume(e);
    }
}


text:
package nl.homeserver.energie.energycontract;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class EnergyContractControllerTest {

    @InjectMocks
    EnergyContractController energyContractController;

    @Mock
    EnergyContractService energyContractService;

    @Test
    void givenANewEnergyContractWhenSaveThenDelegatedToService() {
        when(energyContractService.save(any())).then(returnsFirstArg());
        final EnergyContractDto energieContractDto = mock(EnergyContractDto.class);
        when(energieContractDto.getId()).thenReturn(null);

        final EnergyContract savedEnergyContract = energyContractController.save(energieContractDto);

        assertThat(savedEnergyContract).isNotNull();
        verify(energyContractService).save(any());
    }

    @Test
    void givenAnExistingEnergyContractWhenSaveThenDelegatedToService() {
        when(energyContractService.save(any())).then(returnsFirstArg());

        final long id = 13451L;

        final EnergyContract existingEnergyContract = mock(EnergyContract.class);

        final EnergyContractDto energiecontractToUpdate = mock(EnergyContractDto.class);
        when(energiecontractToUpdate.getId()).thenReturn(id);

        when(energyContractService.getById(id)).thenReturn(existingEnergyContract);

        final EnergyContract savedEnergieContract = energyContractController.save(energiecontractToUpdate);

        assertThat(savedEnergieContract).isSameAs(existingEnergyContract);
    }

    @Test
    void whenDeleteThenDelegatedToService() {
        final long id = 1234L;

        energyContractController.delete(id);

        verify(energyContractService).delete(id);
    }

    @Test
    void whenGetAllThenDelegatedToService() {
        final List<EnergyContract> allEnergieContracts = List.of(mock(EnergyContract.class), mock(EnergyContract.class));
        when(energyContractService.getAll()).thenReturn(allEnergieContracts);

        assertThat(energyContractController.getAll()).isSameAs(allEnergieContracts);
    }

    @Test
    void whenGetCurrentlyValidEnergiecontractThenDelegatedToService() {
        final EnergyContract currentlyValid = mock(EnergyContract.class);
        when(energyContractService.getCurrent()).thenReturn(currentlyValid);

        assertThat(energyContractController.getCurrentlyValid()).isSameAs(currentlyValid);
    }
}


text:
<!DOCTYPE html>

		<title> SARA DEMO </title>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

 Echo POST

		<button type="button" onclick="myFunction('error')">Send</button>


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/spanner/admin/instance/v1/spanner_instance_admin.proto

package com.google.spanner.admin.instance.v1;

public interface ListInstancesRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.spanner.admin.instance.v1.ListInstancesRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The name of the project for which a list of instances is
   * requested. Values are of the form `projects/<project>`.
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The parent.
   */
  java.lang.String getParent();
  /**
   *
   *
   *

   * Required. The name of the project for which a list of instances is
   * requested. Values are of the form `projects/<project>`.
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for parent.
   */
  com.google.protobuf.ByteString getParentBytes();

  /**
   *
   *
   *

   * Number of instances to be returned in the response. If 0 or less, defaults
   * to the server's maximum allowed page size.
   *

   *
   * int32 page_size = 2;
   *
   * @return The pageSize.
   */
  int getPageSize();

  /**
   *
   *
   *

   * If non-empty, `page_token` should contain a
   * [next_page_token][google.spanner.admin.instance.v1.ListInstancesResponse.next_page_token]
   * from a previous
   * [ListInstancesResponse][google.spanner.admin.instance.v1.ListInstancesResponse].
   *

   *
   * string page_token = 3;
   *
   * @return The pageToken.
   */
  java.lang.String getPageToken();
  /**
   *
   *
   *

   * If non-empty, `page_token` should contain a
   * [next_page_token][google.spanner.admin.instance.v1.ListInstancesResponse.next_page_token]
   * from a previous
   * [ListInstancesResponse][google.spanner.admin.instance.v1.ListInstancesResponse].
   *

   *
   * string page_token = 3;
   *
   * @return The bytes for pageToken.
   */
  com.google.protobuf.ByteString getPageTokenBytes();

  /**
   *
   *
   *

   * An expression for filtering the results of the request. Filter rules are
   * case insensitive. The fields eligible for filtering are:
   *   * `name`
   *   * `display_name`
   *   * `labels.key` where key is the name of a label
   * Some examples of using filters are:
   *   * `name:*` --> The instance has a name.
   *   * `name:Howl` --> The instance's name contains the string "howl".
   *   * `name:HOWL` --> Equivalent to above.
   *   * `NAME:howl` --> Equivalent to above.
   *   * `labels.env:*` --> The instance has the label "env".
   *   * `labels.env:dev` --> The instance has the label "env" and the value of
   *                        the label contains the string "dev".
   *   * `name:howl labels.env:dev` --> The instance's name contains "howl" and
   *                                  it has the label "env" with its value
   *                                  containing "dev".
   *

   *
   * string filter = 4;
   *
   * @return The filter.
   */
  java.lang.String getFilter();
  /**
   *
   *
   *

   * An expression for filtering the results of the request. Filter rules are
   * case insensitive. The fields eligible for filtering are:
   *   * `name`
   *   * `display_name`
   *   * `labels.key` where key is the name of a label
   * Some examples of using filters are:
   *   * `name:*` --> The instance has a name.
   *   * `name:Howl` --> The instance's name contains the string "howl".
   *   * `name:HOWL` --> Equivalent to above.
   *   * `NAME:howl` --> Equivalent to above.
   *   * `labels.env:*` --> The instance has the label "env".
   *   * `labels.env:dev` --> The instance has the label "env" and the value of
   *                        the label contains the string "dev".
   *   * `name:howl labels.env:dev` --> The instance's name contains "howl" and
   *                                  it has the label "env" with its value
   *                                  containing "dev".
   *

   *
   * string filter = 4;
   *
   * @return The bytes for filter.
   */
  com.google.protobuf.ByteString getFilterBytes();
}


text:
package org.parceler;

import org.junit.Test;

import java.util.Collections;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
 * @author John Ericksen
 */
public class ABTest {

    @ParcelClasses({
            @ParcelClass(A.class),
            @ParcelClass(B.class)
    })
    public static class A {
    }

    public static class B {
        List<A> a;
    }

    @Test
    public void testList(){
        B b = new B();
        A a = new A();
        b.a = Collections.singletonList(a);

        B output = Parcels.unwrap(new ABTest$B$$Parcelable(b));
        assertEquals(1, output.a.size());
    }
}


text:
from django.shortcuts import render, redirect
from django.contrib import auth, messages
from django.core.urlresolvers import reverse
from django.db import IntegrityError
from django.http import HttpResponse

from pschool.db.models import *

from config import config

from django.conf import settings

from urllib.request import urlopen
import json, re

SMS_GATEWAYS = {
    'AT&T': 'txt.att.net',
    'MetroPCS': 'mymetropcs.com',
    'NexTel': 'messaging.nextel.com',
    'Pioneer': 'zsend.com',
    'Sprint PCS': 'messaging.sprintpcs.com',
    'Sprint NexTel': 'page.nextel.com',
    'T-Mobile': 'tmomail.net',
    'US Cellular': 'email.uscc.net',
    'Verizon': 'vtext.com',
    'Virgin Mobile': 'vmobl.com'
}

EMAIL_REGEX = re.compile(r'[^@]+@[^@]+\.[^@]+')

def get_teacher_website(firstname, lastname):
    return settings.TEACHER_PAGES_URL.format(firstinitial=firstname[0],
                                             lastinitial=lastname[0],
                                             firstname=firstname,
                                             lastname=lastname).lower()

def api_request(url, data=None, use_json=True):
    post = json.dumps(data) if use_json else data
    post = post.encode() if data else None
    fd = urlopen(settings.BACKEND_URL + url, data=post)
    result = fd.read().decode()
    if result:
        return json.loads(result)

def pull(request):
    if request.user.is_authenticated():
        res = api_request("/data/refresh/{}".format(request.user.id))
        if request.is_ajax():
            return HttpResponse(json.dumps(res))
        else:
            return redirect("data")
    else:
        return redirect(reverse(login) + "?next=" + request.path)

def purge(request):
    if request.user.is_authenticated():
        if request.REQUEST.get("all", None):
            Class.objects.filter(user=request.user).delete()
        elif request.REQUEST.get("class", None):
            Class.objects.filter(user=request.user, id=request.REQUEST["class"]).delete()
        elif request.REQUEST.get("assignment", None):
            Assignment.objects.filter(user=request.user, id=request.REQUEST["assignment"]).delete()
        return redirect("data")
    else:
        return redirect(reverse(login) + "?next=" + request.path)

def data(request):
    if not request.user.is_authenticated():
        return redirect(reverse(login) + "?next=" + request.path)
    else:
        data = {
            "user": request.user,
            "classes": list(Class.objects.filter(user=request.user, year=get_current_year()).values()),
            "periods": list(PeriodGrade.objects.filter(user=request.user,
                                                       for_class__year=get_current_year()).distinct().values_list(
                "period_obj__name", flat=True)),
        }
        config.clear_cache()
        if config.letter_day:
            data["lab_day"] = Class.objects.filter(
                user=request.user, lab_day__contains=config.letter_day).values_list(
                    "name", flat=True)
        data["classes"].sort(key=lambda x: (x["year"], x["expression"]))
        data["periods"].sort(key=lambda x: PERIOD_SORTING.get(x, 99))
        for i in data["classes"]:
            i["website"] = get_teacher_website(i["firstname"], i["lastname"])
            i["grades"] = []
            for fg in data["periods"]:
                pg = PeriodGrade.objects.filter(user=request.user, for_class=i["id"],
                                                period_obj__name=fg)
                i["grades"].append(pg[0] if pg.exists() else False)
            i["assignments"] = Assignment.objects.filter(user=request.user, for_class=i["id"]).order_by("-date")
        if request.user.pspass == "":
            messages.warning(request, "Please update your PowerSchool credentials here to allow PowerUpdate to continue checking for new grades.".format(reverse("profile")), extra_tags="html-safe")
        return render(request, "data.html", data)

def profile(request):
    if not request.user.is_authenticated():
        return redirect(reverse(login) + "?next=" + request.path)
    else:
        data = {
            "user": request.user,
            "gateways": sorted(SMS_GATEWAYS.items()),
            "notifs": sorted(NOTIFICATION_PREFERENCES.items()),
            "errors": [],
        }
        if request.method == "POST":
            for i in ("firstname", "lastname", "psuser", "carrier"):
                setattr(request.user, i, request.POST[i])
                if not request.POST[i]:
                    data["errors"].append(i)
            request.user.email = request.POST["email"]
            if not EMAIL_REGEX.fullmatch(request.user.email):
                data["errors"].append("email")
            if request.POST["new-password"]:
                if not request.user.check_password(request.POST["old-password"]):
                    data["errors"].append("old-password")
                else:
                    request.user.set_password(request.POST["new-password"])
            if request.POST["pspass"]:
                request.user.pspass = request.POST["pspass"]
            request.user.phone = request.POST["phone"].replace(" ","").replace("-","")
            if request.POST["phone"] and (not re.fullmatch(r'\d{10}', request.user.phone)):
                    data["errors"].append("phone")
            request.user.notify_grades = int(request.POST.get("grades-notify", 0))
            request.user.notify_labs = int(request.POST.get("labs-notify", 0))
            if (not request.user.phone) and (
                    (request.user.notify_grades & 0b10) or
                    (request.user.notify_labs & 0b10)):
                data["errors"].append("phone")
                data["error_message"] = ("You must provide your phone number and carrier to "
                                         + "receive SMS notifications.")

            if len(data["errors"]) < 1:
                try:
                    request.user.save()
                except IntegrityError as err:
                    data["error_message"] = "An account with that email address already exists"
                    data["errors"].append("email")

        data["pspass"] = "•" * len(request.user.pspass)
        if request.user.pspass == "":
            messages.warning(request, "Your PowerSchool credentials need to be updated.")
        return render(request, "profile.html", data)

def login(request, reset_email=None, reset_key=None):
    data = {
        "message": "",
        "next": request.REQUEST.get("next","/"),
        "last_action": request.REQUEST.get("action", "Login"),
    }
    email = request.POST.get("email")
    if reset_email:
        if request.POST.get("password"):
            result = api_request(request.path, request.POST["password"], False)
            data["form_action"] = reverse(login)
            data["last_action"] = "Login"
            if result["success"]:
                data["message"] = "Password changed successfully."
                data["message_class"] = "success"
            else:
                if result["error"] in ("bad key", "expired"):
                    data["message"] = "Invalid password reset link."
                else:
                    data["message"] = result["error"]
        else:
            data["email"] = reset_email
            data["forgot_password"] = request.path
    elif request.user.is_authenticated():
        return redirect(request.REQUEST.get("next","/"))
    elif request.POST.get("action") == "Register":
        if request.POST.get("data_email"):
            firstname, lastname = request.POST.get("firstname"), request.POST.get("lastname")
            data["data_email"] = request.POST.get("data_email")
            data["data_password"] = request.POST.get("data_password")
            if not (firstname or lastname):
                data["message"] = "Please enter your full name."
            else:
                result = api_request("/profile/new/", {
                    "email": request.POST["data_email"],
                    "password": request.POST["data_password"],
                    "firstname": firstname, "lastname": lastname,
                    "psuser": request.POST.get("email",""),
                    "pspass": request.POST.get("password","")
                })
                if result["success"]:
                    auth.login(request, auth.authenticate(
                        email=request.POST["data_email"],
                        password=request.POST["data_password"]))
                    return redirect(data["next"])
                else:
                    if result["error"] == "bad powerschool":
                        data["message"] = "Invalid PowerSchool username or password."
                    elif result["error"] == "exists":
                        del data["data_email"]
                        data["message"] = "An account with that email already exists."
                    else:
                        data["message"] = result["error"]
        else:
            data["data_password"] = request.POST.get("password")
            if not (email and EMAIL_REGEX.fullmatch(email)):
                data["message"] = "Please supply a valid email address."
            elif not data["data_password"]:
                data["message"] = "Please supply a login password."
            else:
                data["data_email"] = email
    elif request.POST.get("action") == "Forgot Password":
        if email:
            api_request("/profile/pwreset/{}/".format(email))
            data["message"] = "Password reset email sent to {}.".format(email)
            data["message_class"] = "success"
            data["form_action"] = reverse(login)
        else:
            data["last_action"] = "Forgot Password"
            data["message"] = "Please enter your email address and then press Forgot Password."
    else:
        if email:
            user = auth.authenticate(email=email, password=request.POST.get("password"))
            if user:
                auth.login(request, user)
                return redirect(request.REQUEST.get("next","/"))
            data["email"] = email
        if request.method == "POST":
            data["message"] = "Invalid email or password."
    return render(request, "login.html", data)

def logout(request):
    auth.logout(request)
    return redirect(reverse("login"))


text:
from friends.models import FriendshipInvitation

def invitations(request):
    if request.user.is_authenticated():
        return {'invitations_count': FriendshipInvitation.objects.filter(to_user=request.user, status="2").count(),}
    else:
        return {}


text:
<?php
class Kwc_NewsletterCategory_Update_35004 extends Kwf_Update
{
    private $_afterUpdateRequired = false;
    public function update()
    {
        $db = Kwf_Registry::get('db');
        $db->query("ALTER TABLE  `kwc_newsletter_categories` ADD  `newsletter_component_id` VARCHAR( 200 ) NOT NULL AFTER  `id`");
        $db->query("ALTER TABLE  `kwc_newsletter_categories` ADD INDEX (  `newsletter_component_id` )");
        if ($db->query("SELECT COUNT(*) FROM `kwc_newsletter_categories`")->fetchColumn()) {
            $nlCId = $db->query("SELECT component_id FROM `kwc_newsletter` LIMIT 1")->fetchColumn();
            if ($nlCId) {
                $db->query("UPDATE `kwc_newsletter_categories` SET newsletter_component_id='$nlCId'");
            } else {
                $this->_afterUpdateRequired = true;
            }
        }
    }

    public function postUpdate()
    {
        if ($this->_afterUpdateRequired) {
            $c = Kwf_Component_Data_Root::getInstance()
                ->getComponentByClass('Kwc_NewsletterCategory_Component', array('limit'=>1));
            Kwf_Registry::get('db')
                ->query("UPDATE `kwc_newsletter_categories` SET newsletter_component_id='$c->dbId'");
        }
    }

}


text:
import MCTS

MCTS.node_tag(a::OPCSPAction) = "[$(a.next)]"

MCTS.node_tag(s::OPCSPBelief) = "[$(s.i)]"
MCTS.tooltip_tag(s::OPCSPBelief) = "[$(s.i), $(s.remaining)] $(s.dist.mean) | $(s.open)]"

type HeuristicActionGenerator <: MCTS.ActionGenerator
    solver::OPSolver
    rng::AbstractRNG
    _action_space::AbstractSpace
end
HeuristicActionGenerator(solver::OPSolver, rng::AbstractRNG) = HeuristicActionGenerator(solver, rng, OPCSPActionSpace())

function MCTS.next_action(gen::HeuristicActionGenerator, mdp::OPCSPBeliefMDP, s::OPCSPBelief, snode::MCTS.DPWStateNode)
    tail = tail_problem(mdp, s, prohibit_first=filter(i->i!=mdp.stop, map(a->a.next, keys(snode.A))))
    move = OPCSPAction(first_move(gen.solver, tail))
    if haskey(snode.A, move) # the best move was to the stop node, so just select something randomly
        move = rand(gen.rng, actions(mdp, s, gen._action_space))
    end
    return move
end

type PreSolvedActionGenerator <: MCTS.ActionGenerator
    presolved::Dict{Int,Int}
    secondary_solver::OPSolver
    rng::AbstractRNG
    _action_space
end
function PreSolvedActionGenerator(op::Union{OPCSPBeliefMDP,OPCSP};
                                  rng::AbstractRNG=MersenneTwister(),
                                  presolver::OPSolver=GurobiExactSolver(),
                                  secondary_solver::OPSolver=HeuristicSolver())
    d = Dict{Int,Int}()
    path = solve_op(presolver, op)
    for i in 1:length(path)-1
        d[path[i]] = path[i+1]
    end
    return PreSolvedActionGenerator(d, secondary_solver, rng, actions(op))
end

function MCTS.next_action(gen::PreSolvedActionGenerator, mdp::OPCSPBeliefMDP, s::OPCSPBelief, snode::MCTS.DPWStateNode)
    fromdict = false
    if haskey(gen.presolved, s.i)
        next = gen.presolved[s.i]
        if next in s.open && within_range(mdp, s.i, mdp.stop, next, s.remaining)
            move = OPCSPAction(gen.presolved[s.i])
            fromdict = true
        end
    end
    if !fromdict
        tail = tail_problem(mdp, s, prohibit_first=filter(i->i!=mdp.stop, map(a->a.next, keys(snode.A))))
        move = OPCSPAction(first_move(gen.secondary_solver, tail))
    end
    if haskey(snode.A, move) # the best move was to the stop node, so just select something randomly
        move = rand(gen.rng, actions(mdp, s, gen._action_space))
    end
    return move
end

# Aggregators
type OldVoronoiOPCSPAg <: MCTS.Aggregator
    radius::Float64
    anchors::Dict{Tuple{Int,Float64,IntSet},Vector{OPCSPBelief}}
end
OldVoronoiOPCSPAg(radius::Float64) = OldVoronoiOPCSPAg(radius, Dict{Tuple{Int,Float64,IntSet},Vector{OPCSPBelief}}())

function MCTS.initialize!(ag::OldVoronoiOPCSPAg, mdp::OPCSPBeliefMDP)
    ag.anchors = Dict{Tuple{Int, Float64, IntSet},Vector{OPCSPBelief}}()
end

function MCTS.assign(ag::OldVoronoiOPCSPAg, b::OPCSPBelief)
    found = false
    len = length(b.dist.mean)
    # @assert length(b.dist.mean) < 32
    # @assert b.open.limit == 256
    # @assert b.open.fill1s == false
    if haskey(ag.anchors, (b.i, b.remaining, b.open))
        similar = ag.anchors[(b.i, b.remaining, b.open)]
        local anchor
        bestdist = ag.radius
        for anch in similar
            dist = 0.0
            for i in 1:len
                @inbounds dist += abs(anch.dist.mean[i]-b.dist.mean[i])
                if dist > bestdist
                    break
                end
            end
            if dist <= bestdist
                found = true
                anchor = anch
                bestdist = dist
            end
        end
    else
        similar = ag.anchors[(b.i, b.remaining, b.open)] = Vector{OPCSPBelief}()
    end
    if !found
        push!(similar, deepcopy(b))
        return b
    end
    return anchor
end

type VoronoiOPCSPAg <: MCTS.Aggregator
    radius::Float64
    map::NearestStateMap{OPCSPState}
end
VoronoiOPCSPAg(radius::Float64) = VoronoiOPCSPAg(radius, NearestStateMap{OPCSPState}())

function MCTS.initialize!(ag::VoronoiOPCSPAg, mdp::OPCSPBeliefMDP)
    ag.map = NearestStateMap(OPCSPState, mdp)
end

function MCTS.assign(ag::VoronoiOPCSPAg, b::OPCSPBelief)
    if has_similar(ag.map, b)
        anchor, dist = get_nearest(ag.map, b)
        if dist <= ag.radius
            return anchor
        end
    end
    insert!(ag.map, b, mean(b))
    return b
end

type VoxelOPCSPAg <: MCTS.Aggregator
    diam::Float64
    # agstates::Dict{Tuple{Int,IntSet,Vector{Int}},Int}
    # next_id::Int
end
# VoxelOPCSPAg(diam::Float64) = VoxelOPCSPAg(diam, Dict{Tuple{Int,IntSet,Vector{Int}},Int}(), 1)

function MCTS.initialize!(ag::VoxelOPCSPAg, mdp::OPCSPBeliefMDP)
    # ag.agstates = Dict{Tuple{Int,IntSet,Vector{Int}},Int}()
    # ag.next_id = 1
end

function MCTS.assign(ag::VoxelOPCSPAg, b::OPCSPBelief)
    voxel = floor(Int, b.dist.mean/ag.diam)
    return (b.i, b.open, b.remaining, voxel)
end