text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/ec2/model/VolumeState.h>
#include <aws/ec2/model/VolumeType.h>
#include <aws/ec2/model/ResponseMetadata.h>
#include <aws/ec2/model/VolumeAttachment.h>
#include <aws/ec2/model/Tag.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{

  /**
   *
Describes a volume.

See Also:
   AWS API
   * Reference

   */
  class AWS_EC2_API Volume
  {
  public:
    Volume();
    Volume(const Aws::Utils::Xml::XmlNode& xmlNode);
    Volume& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
Information about the volume attachments.

     */
    inline const Aws::Vector<VolumeAttachment>& GetAttachments() const{ return m_attachments; }

    /**
     *
Information about the volume attachments.

     */
    inline bool AttachmentsHasBeenSet() const { return m_attachmentsHasBeenSet; }

    /**
     *
Information about the volume attachments.

     */
    inline void SetAttachments(const Aws::Vector<VolumeAttachment>& value) { m_attachmentsHasBeenSet = true; m_attachments = value; }

    /**
     *
Information about the volume attachments.

     */
    inline void SetAttachments(Aws::Vector<VolumeAttachment>&& value) { m_attachmentsHasBeenSet = true; m_attachments = std::move(value); }

    /**
     *
Information about the volume attachments.

     */
    inline Volume& WithAttachments(const Aws::Vector<VolumeAttachment>& value) { SetAttachments(value); return *this;}

    /**
     *
Information about the volume attachments.

     */
    inline Volume& WithAttachments(Aws::Vector<VolumeAttachment>&& value) { SetAttachments(std::move(value)); return *this;}

    /**
     *
Information about the volume attachments.

     */
    inline Volume& AddAttachments(const VolumeAttachment& value) { m_attachmentsHasBeenSet = true; m_attachments.push_back(value); return *this; }

    /**
     *
Information about the volume attachments.

     */
    inline Volume& AddAttachments(VolumeAttachment&& value) { m_attachmentsHasBeenSet = true; m_attachments.push_back(std::move(value)); return *this; }

    /**
     *
The Availability Zone for the volume.

     */
    inline const Aws::String& GetAvailabilityZone() const{ return m_availabilityZone; }

    /**
     *
The Availability Zone for the volume.

     */
    inline bool AvailabilityZoneHasBeenSet() const { return m_availabilityZoneHasBeenSet; }

    /**
     *
The Availability Zone for the volume.

     */
    inline void SetAvailabilityZone(const Aws::String& value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone = value; }

    /**
     *
The Availability Zone for the volume.

     */
    inline void SetAvailabilityZone(Aws::String&& value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone = std::move(value); }

    /**
     *
The Availability Zone for the volume.

     */
    inline void SetAvailabilityZone(const char* value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone.assign(value); }

    /**
     *
The Availability Zone for the volume.

     */
    inline Volume& WithAvailabilityZone(const Aws::String& value) { SetAvailabilityZone(value); return *this;}

    /**
     *
The Availability Zone for the volume.

     */
    inline Volume& WithAvailabilityZone(Aws::String&& value) { SetAvailabilityZone(std::move(value)); return *this;}

    /**
     *
The Availability Zone for the volume.

     */
    inline Volume& WithAvailabilityZone(const char* value) { SetAvailabilityZone(value); return *this;}

    /**
     *
The time stamp when volume creation was initiated.

     */
    inline const Aws::Utils::DateTime& GetCreateTime() const{ return m_createTime; }

    /**
     *
The time stamp when volume creation was initiated.

     */
    inline bool CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; }

    /**
     *
The time stamp when volume creation was initiated.

     */
    inline void SetCreateTime(const Aws::Utils::DateTime& value) { m_createTimeHasBeenSet = true; m_createTime = value; }

    /**
     *
The time stamp when volume creation was initiated.

     */
    inline void SetCreateTime(Aws::Utils::DateTime&& value) { m_createTimeHasBeenSet = true; m_createTime = std::move(value); }

    /**
     *
The time stamp when volume creation was initiated.

     */
    inline Volume& WithCreateTime(const Aws::Utils::DateTime& value) { SetCreateTime(value); return *this;}

    /**
     *
The time stamp when volume creation was initiated.

     */
    inline Volume& WithCreateTime(Aws::Utils::DateTime&& value) { SetCreateTime(std::move(value)); return *this;}

    /**
     *
Indicates whether the volume is encrypted.

     */
    inline bool GetEncrypted() const{ return m_encrypted; }

    /**
     *
Indicates whether the volume is encrypted.

     */
    inline bool EncryptedHasBeenSet() const { return m_encryptedHasBeenSet; }

    /**
     *
Indicates whether the volume is encrypted.

     */
    inline void SetEncrypted(bool value) { m_encryptedHasBeenSet = true; m_encrypted = value; }

    /**
     *
Indicates whether the volume is encrypted.

     */
    inline Volume& WithEncrypted(bool value) { SetEncrypted(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS)
     * customer master key (CMK) that was used to protect the volume encryption key for
     * the volume.

     */
    inline const Aws::String& GetKmsKeyId() const{ return m_kmsKeyId; }

    /**
     *
The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS)
     * customer master key (CMK) that was used to protect the volume encryption key for
     * the volume.

     */
    inline bool KmsKeyIdHasBeenSet() const { return m_kmsKeyIdHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS)
     * customer master key (CMK) that was used to protect the volume encryption key for
     * the volume.

     */
    inline void SetKmsKeyId(const Aws::String& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = value; }

    /**
     *
The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS)
     * customer master key (CMK) that was used to protect the volume encryption key for
     * the volume.

     */
    inline void SetKmsKeyId(Aws::String&& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS)
     * customer master key (CMK) that was used to protect the volume encryption key for
     * the volume.

     */
    inline void SetKmsKeyId(const char* value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS)
     * customer master key (CMK) that was used to protect the volume encryption key for
     * the volume.

     */
    inline Volume& WithKmsKeyId(const Aws::String& value) { SetKmsKeyId(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS)
     * customer master key (CMK) that was used to protect the volume encryption key for
     * the volume.

     */
    inline Volume& WithKmsKeyId(Aws::String&& value) { SetKmsKeyId(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS)
     * customer master key (CMK) that was used to protect the volume encryption key for
     * the volume.

     */
    inline Volume& WithKmsKeyId(const char* value) { SetKmsKeyId(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the Outpost.

     */
    inline const Aws::String& GetOutpostArn() const{ return m_outpostArn; }

    /**
     *
The Amazon Resource Name (ARN) of the Outpost.

     */
    inline bool OutpostArnHasBeenSet() const { return m_outpostArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the Outpost.

     */
    inline void SetOutpostArn(const Aws::String& value) { m_outpostArnHasBeenSet = true; m_outpostArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the Outpost.

     */
    inline void SetOutpostArn(Aws::String&& value) { m_outpostArnHasBeenSet = true; m_outpostArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the Outpost.

     */
    inline void SetOutpostArn(const char* value) { m_outpostArnHasBeenSet = true; m_outpostArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the Outpost.

     */
    inline Volume& WithOutpostArn(const Aws::String& value) { SetOutpostArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the Outpost.

     */
    inline Volume& WithOutpostArn(Aws::String&& value) { SetOutpostArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the Outpost.

     */
    inline Volume& WithOutpostArn(const char* value) { SetOutpostArn(value); return *this;}

    /**
     *
The size of the volume, in GiBs.

     */
    inline int GetSize() const{ return m_size; }

    /**
     *
The size of the volume, in GiBs.

     */
    inline bool SizeHasBeenSet() const { return m_sizeHasBeenSet; }

    /**
     *
The size of the volume, in GiBs.

     */
    inline void SetSize(int value) { m_sizeHasBeenSet = true; m_size = value; }

    /**
     *
The size of the volume, in GiBs.

     */
    inline Volume& WithSize(int value) { SetSize(value); return *this;}

    /**
     *
The snapshot from which the volume was created, if applicable.

     */
    inline const Aws::String& GetSnapshotId() const{ return m_snapshotId; }

    /**
     *
The snapshot from which the volume was created, if applicable.

     */
    inline bool SnapshotIdHasBeenSet() const { return m_snapshotIdHasBeenSet; }

    /**
     *
The snapshot from which the volume was created, if applicable.

     */
    inline void SetSnapshotId(const Aws::String& value) { m_snapshotIdHasBeenSet = true; m_snapshotId = value; }

    /**
     *
The snapshot from which the volume was created, if applicable.

     */
    inline void SetSnapshotId(Aws::String&& value) { m_snapshotIdHasBeenSet = true; m_snapshotId = std::move(value); }

    /**
     *
The snapshot from which the volume was created, if applicable.

     */
    inline void SetSnapshotId(const char* value) { m_snapshotIdHasBeenSet = true; m_snapshotId.assign(value); }

    /**
     *
The snapshot from which the volume was created, if applicable.

     */
    inline Volume& WithSnapshotId(const Aws::String& value) { SetSnapshotId(value); return *this;}

    /**
     *
The snapshot from which the volume was created, if applicable.

     */
    inline Volume& WithSnapshotId(Aws::String&& value) { SetSnapshotId(std::move(value)); return *this;}

    /**
     *
The snapshot from which the volume was created, if applicable.

     */
    inline Volume& WithSnapshotId(const char* value) { SetSnapshotId(value); return *this;}

    /**
     *
The volume state.

     */
    inline const VolumeState& GetState() const{ return m_state; }

    /**
     *
The volume state.

     */
    inline bool StateHasBeenSet() const { return m_stateHasBeenSet; }

    /**
     *
The volume state.

     */
    inline void SetState(const VolumeState& value) { m_stateHasBeenSet = true; m_state = value; }

    /**
     *
The volume state.

     */
    inline void SetState(VolumeState&& value) { m_stateHasBeenSet = true; m_state = std::move(value); }

    /**
     *
The volume state.

     */
    inline Volume& WithState(const VolumeState& value) { SetState(value); return *this;}

    /**
     *
The volume state.

     */
    inline Volume& WithState(VolumeState&& value) { SetState(std::move(value)); return *this;}

    /**
     *
The ID of the volume.

     */
    inline const Aws::String& GetVolumeId() const{ return m_volumeId; }

    /**
     *
The ID of the volume.

     */
    inline bool VolumeIdHasBeenSet() const { return m_volumeIdHasBeenSet; }

    /**
     *
The ID of the volume.

     */
    inline void SetVolumeId(const Aws::String& value) { m_volumeIdHasBeenSet = true; m_volumeId = value; }

    /**
     *
The ID of the volume.

     */
    inline void SetVolumeId(Aws::String&& value) { m_volumeIdHasBeenSet = true; m_volumeId = std::move(value); }

    /**
     *
The ID of the volume.

     */
    inline void SetVolumeId(const char* value) { m_volumeIdHasBeenSet = true; m_volumeId.assign(value); }

    /**
     *
The ID of the volume.

     */
    inline Volume& WithVolumeId(const Aws::String& value) { SetVolumeId(value); return *this;}

    /**
     *
The ID of the volume.

     */
    inline Volume& WithVolumeId(Aws::String&& value) { SetVolumeId(std::move(value)); return *this;}

    /**
     *
The ID of the volume.

     */
    inline Volume& WithVolumeId(const char* value) { SetVolumeId(value); return *this;}

    /**
     *
The number of I/O operations per second (IOPS). For gp3,
     * io1, and io2 volumes, this represents the number of
     * IOPS that are provisioned for the volume. For gp2 volumes, this
     * represents the baseline performance of the volume and the rate at which the
     * volume accumulates I/O credits for bursting.

     */
    inline int GetIops() const{ return m_iops; }

    /**
     *
The number of I/O operations per second (IOPS). For gp3,
     * io1, and io2 volumes, this represents the number of
     * IOPS that are provisioned for the volume. For gp2 volumes, this
     * represents the baseline performance of the volume and the rate at which the
     * volume accumulates I/O credits for bursting.

     */
    inline bool IopsHasBeenSet() const { return m_iopsHasBeenSet; }

    /**
     *
The number of I/O operations per second (IOPS). For gp3,
     * io1, and io2 volumes, this represents the number of
     * IOPS that are provisioned for the volume. For gp2 volumes, this
     * represents the baseline performance of the volume and the rate at which the
     * volume accumulates I/O credits for bursting.

     */
    inline void SetIops(int value) { m_iopsHasBeenSet = true; m_iops = value; }

    /**
     *
The number of I/O operations per second (IOPS). For gp3,
     * io1, and io2 volumes, this represents the number of
     * IOPS that are provisioned for the volume. For gp2 volumes, this
     * represents the baseline performance of the volume and the rate at which the
     * volume accumulates I/O credits for bursting.

     */
    inline Volume& WithIops(int value) { SetIops(value); return *this;}

    /**
     *
Any tags assigned to the volume.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
Any tags assigned to the volume.

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
Any tags assigned to the volume.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
Any tags assigned to the volume.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
Any tags assigned to the volume.

     */
    inline Volume& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
Any tags assigned to the volume.

     */
    inline Volume& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
Any tags assigned to the volume.

     */
    inline Volume& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
Any tags assigned to the volume.

     */
    inline Volume& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

    /**
     *
The volume type.

     */
    inline const VolumeType& GetVolumeType() const{ return m_volumeType; }

    /**
     *
The volume type.

     */
    inline bool VolumeTypeHasBeenSet() const { return m_volumeTypeHasBeenSet; }

    /**
     *
The volume type.

     */
    inline void SetVolumeType(const VolumeType& value) { m_volumeTypeHasBeenSet = true; m_volumeType = value; }

    /**
     *
The volume type.

     */
    inline void SetVolumeType(VolumeType&& value) { m_volumeTypeHasBeenSet = true; m_volumeType = std::move(value); }

    /**
     *
The volume type.

     */
    inline Volume& WithVolumeType(const VolumeType& value) { SetVolumeType(value); return *this;}

    /**
     *
The volume type.

     */
    inline Volume& WithVolumeType(VolumeType&& value) { SetVolumeType(std::move(value)); return *this;}

    /**
     *
Indicates whether the volume was created using fast snapshot restore.

     */
    inline bool GetFastRestored() const{ return m_fastRestored; }

    /**
     *
Indicates whether the volume was created using fast snapshot restore.

     */
    inline bool FastRestoredHasBeenSet() const { return m_fastRestoredHasBeenSet; }

    /**
     *
Indicates whether the volume was created using fast snapshot restore.

     */
    inline void SetFastRestored(bool value) { m_fastRestoredHasBeenSet = true; m_fastRestored = value; }

    /**
     *
Indicates whether the volume was created using fast snapshot restore.

     */
    inline Volume& WithFastRestored(bool value) { SetFastRestored(value); return *this;}

    /**
     *
Indicates whether Amazon EBS Multi-Attach is enabled.

     */
    inline bool GetMultiAttachEnabled() const{ return m_multiAttachEnabled; }

    /**
     *
Indicates whether Amazon EBS Multi-Attach is enabled.

     */
    inline bool MultiAttachEnabledHasBeenSet() const { return m_multiAttachEnabledHasBeenSet; }

    /**
     *
Indicates whether Amazon EBS Multi-Attach is enabled.

     */
    inline void SetMultiAttachEnabled(bool value) { m_multiAttachEnabledHasBeenSet = true; m_multiAttachEnabled = value; }

    /**
     *
Indicates whether Amazon EBS Multi-Attach is enabled.

     */
    inline Volume& WithMultiAttachEnabled(bool value) { SetMultiAttachEnabled(value); return *this;}

    /**
     *
The throughput that the volume supports, in MiB/s.

     */
    inline int GetThroughput() const{ return m_throughput; }

    /**
     *
The throughput that the volume supports, in MiB/s.

     */
    inline bool ThroughputHasBeenSet() const { return m_throughputHasBeenSet; }

    /**
     *
The throughput that the volume supports, in MiB/s.

     */
    inline void SetThroughput(int value) { m_throughputHasBeenSet = true; m_throughput = value; }

    /**
     *
The throughput that the volume supports, in MiB/s.

     */
    inline Volume& WithThroughput(int value) { SetThroughput(value); return *this;}

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline bool ResponseMetadataHasBeenSet() const { return m_responseMetadataHasBeenSet; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadataHasBeenSet = true; m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadataHasBeenSet = true; m_responseMetadata = std::move(value); }

    inline Volume& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline Volume& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:

    Aws::Vector<VolumeAttachment> m_attachments;
    bool m_attachmentsHasBeenSet;

    Aws::String m_availabilityZone;
    bool m_availabilityZoneHasBeenSet;

    Aws::Utils::DateTime m_createTime;
    bool m_createTimeHasBeenSet;

    bool m_encrypted;
    bool m_encryptedHasBeenSet;

    Aws::String m_kmsKeyId;
    bool m_kmsKeyIdHasBeenSet;

    Aws::String m_outpostArn;
    bool m_outpostArnHasBeenSet;

    int m_size;
    bool m_sizeHasBeenSet;

    Aws::String m_snapshotId;
    bool m_snapshotIdHasBeenSet;

    VolumeState m_state;
    bool m_stateHasBeenSet;

    Aws::String m_volumeId;
    bool m_volumeIdHasBeenSet;

    int m_iops;
    bool m_iopsHasBeenSet;

    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet;

    VolumeType m_volumeType;
    bool m_volumeTypeHasBeenSet;

    bool m_fastRestored;
    bool m_fastRestoredHasBeenSet;

    bool m_multiAttachEnabled;
    bool m_multiAttachEnabledHasBeenSet;

    int m_throughput;
    bool m_throughputHasBeenSet;

    ResponseMetadata m_responseMetadata;
    bool m_responseMetadataHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
<!DOCTYPE html>

<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700|Tangerine:700|Inconsolata" rel="stylesheet">
<link href="main.css" rel="stylesheet" type="text/css">

All type names in this reference belong to the Filament namespace. For example, init actually refers to Filament.init.

Classes

BufferDescriptor
Low level buffer wrapper.

BufferObject
Represents a single GPU buffer.

Camera
Represents the eye through which the scene is viewed.

Engine
Central manager and resource owner.

Entity
Handle to an object consisting of a set of components.

EntityManager
Singleton used for constructing entities in Filament's ECS.

Frustum
Represents the six planes of a truncated viewing pyramid

IcoSphere
Utility class for constructing spheres (requires glMatrix).

IndexBuffer
Array of 16-bit or 32-bit unsigned integers consumed by the GPU.

Ktx1Bundle
In-memory representation of a KTX file.

KtxInfo
Property accessor for KTX header.

LightManager$Instance
Component instance returned by LightManager

PixelBufferDescriptor
Low level pixel buffer wrapper.

RenderableManager
Allows access to properties of drawable objects.

RenderableManager$Instance
Component instance returned by RenderableManager

Renderer
Represents the platform's native window.

Scene
Flat container of renderables and lights.

SwapChain
Represents the platform's native rendering surface.

Texture
2D image or cubemap that can be sampled by the GPU, possibly mipmapped.

TransformManager
Adds transform components to entities.

TransformManager$Instance
Component instance returned by TransformManager

VertexBuffer
Bundle of buffers and associated vertex attributes.

View
Encompasses all the state needed for rendering a Scene.

Free Functions

Buffer
Constructs a BufferDescriptor by copying a typed array into the WASM heap.

CompressedPixelBuffer
Constructs a PixelBufferDescriptor for compressed texture

PixelBuffer
Constructs a PixelBufferDescriptor by copying a typed array into the WASM heap.

fetch
Downloads assets and invokes a callback when done.

getSupportedFormatSuffix
Generate a file suffix according to the texture format.

getSupportedFormats
Queries WebGL to check which compressed formats are supported.

init
Downloads assets, loads the Filament module, and invokes a callback when done.

loadMathExtensions
Extends the glMatrix math library.

packSnorm16
Converts a float in [-1, +1] into a half-float.

Enumerations

BufferObject$BindingType

Camera$Fov

Camera$Projection

ColorGrading$QualityLevel

ColorGrading$ToneMapping

CompareFunc

CompareMode

CompressedPixelDataType

CullingMode

Frustum$Plane

IndexBuffer$IndexType

LightManager$Type

MagFilter

MinFilter

PixelDataFormat

PixelDataType

RenderTarget$AttachmentPoint

RenderableManager$PrimitiveType

RgbType

RgbaType

Texture$CubemapFace

Texture$InternalFormat

Texture$Sampler

Texture$Usage

VertexAttribute

VertexBuffer$AttributeType

View$AmbientOcclusion

View$AntiAliasing

View$BlendMode

View$BloomOptions$BlendMode

View$DepthOfFieldOptions$Filter

View$QualityLevel

WrapMode

class BufferDescriptor

Low level buffer wrapper.

bufferDescriptor.getBytes()

Gets a view of the WASM heap referenced by the buffer descriptor.

returns Uint8Array

Clients should use the Buffer helper function to contruct BufferDescriptor objects.

class BufferObject

Represents a single GPU buffer.

bufferObject.setBuffer(engine, buffer, byteOffset)

engine Engine

buffer asset string, or Uint8Array, or Buffer

byteOffset non-negative integer

class Camera

Represents the eye through which the scene is viewed.

See also the Engine methods createCamera and destroyCamera.

class Engine

Central manager and resource owner.

engine.addEntities(entities)

entities array of entities

Engine.create(canvas, options)

Creates an Engine instance for the given canvas.

canvas the canvas DOM element

options optional WebGL 2.0 context configuration

returns an instance of Engine

engine.createAssetLoader()

returns an instance of AssetLoader

engine.createCamera(entity)

entity the Entity to add the camera component to

returns an instance of Camera

engine.createIblFromKtx(buffer, options)

Utility that creates an [IndirectLight] from a KTX file.

buffer asset string, or Uint8Array, or Buffer with KTX file contents

options Options dictionary.

returns IndirectLight

engine.createMaterial(package)

package asset string, or Uint8Array, or Buffer with filamat contents

returns an instance of createMaterial

engine.createRenderer()

returns an instance of Renderer

engine.createScene()

returns an instance of Scene

engine.createSkyFromKtx(buffer, options)

Utility function that creates a [Skybox] from a KTX file.

buffer asset string, or Uint8Array, or Buffer with KTX file contents

options Options dictionary.

returns Skybox

engine.createSwapChain()

returns an instance of SwapChain

engine.createTextureFromJpeg(buffer, options)

Creates a 2D [Texture] from the contents of a JPEG file.

buffer asset string, or Uint8Array, or Buffer with JPEG file contents

options JavaScript object with optional srgb and nomips keys.

returns Texture

engine.createTextureFromKtx(buffer, options)

Utility function that creates a [Texture] from a KTX file.

buffer asset string, or Uint8Array, or Buffer with KTX file contents

options Options dictionary.

returns Texture

engine.createTextureFromPng(buffer, options)

Creates a 2D [Texture] from the raw contents of a PNG file.

buffer asset string, or Uint8Array, or Buffer with PNG file contents

options object with optional srgb, noalpha, and nomips keys.

returns Texture

engine.createView()

returns an instance of View

Engine.destroy(engine)

Destroys an engine instance and cleans up resources.

engine the instance to destroy

engine.destroyCameraComponent(camera)

camera an Entity with a camera component

engine.destroyColorGrading(entity)

entity an ColorGrading

engine.destroyEntity(entity)

entity an Entity

engine.destroyIndexBuffer(ib)

ib the IndexBuffer to destroy

engine.destroyIndirectLight(light)

light the IndirectLight to destroy

engine.destroyMaterial(material)

material an instance of Material

engine.destroyMaterial(instance)

instance the MaterialInstance to destroy

engine.destroyRenderTarget(rt)

rt the RenderTarget to destroy

engine.destroyRenderer(renderer)

renderer an instance of Renderer

engine.destroyScene(scene)

scene an instance of Scene

engine.destroySkybox(skybox)

skybox the Skybox to destroy

engine.destroySwapChain(swapChain)

swapChain an instance of SwapChain

engine.destroyTexture(texture)

texture the Texture to destroy

engine.destroyVertexBuffer(vb)

vb the VertexBuffer to destroy

engine.destroyView(view)

view an instance of View

engine.getCameraComponent()

returns an instance of Camera

engine.getEntityManager()

engine.getLightManager()

returns an instance of LightManager

engine.getRenderableManager()

returns an instance of RenderableManager

engine.getTransformManager()

returns an instance of TransformManager

engine.loadFilamesh(buffer, definstance, matinstances)

Consumes the contents of a filamesh file and creates a renderable.

buffer asset string, or Uint8Array, or Buffer with filamesh contents

definstance Optional default MaterialInstance

matinstances Optional in-out object that gets populated with a name-to-MaterialInstance mapping. Clients can also optionally provide individual material instances using this argument.

returns JavaScript object with keys renderable, vertexBuffer, and indexBuffer. These are of type Entity, VertexBuffer, and IndexBuffer.

engine.removeEntities(entities)

entities array of entities

engine.setAmbientOcclusionOptions(overrides)

overrides Dictionary with one or more of the following properties: radius, power, bias, resolution, intensity, quality.

engine.setBloomOptions(overrides)

overrides Dictionary with one or more of the following properties: enabled, strength, resolution, anomorphism, levels, blendMode, threshold, highlight.

engine.setClearOptions(overrides)

overrides Dictionary with one or more of the following properties: clearColor, clear, discard.

engine.setDepthOfFieldOptions(overrides)

overrides Dictionary with one or more of the following properties: cocScale, maxApertureDiameter, enabled.

engine.setFogOptions(overrides)

overrides Dictionary with one or more of the following properties: distance, maximumOpacity, height, heightFalloff, color, density, inScatteringStart,

engine.setMultiSampleAntiAliasingOptions(overrides)

overrides Dictionary with one or more of the following properties: enabled, sampleCount, customResolve.

engine.setScreenSpaceReflectionsOptions(overrides)

overrides Dictionary with one or more of the following properties: thickness, bias, maxDistance, stride, enabled.

engine.setShadowOptions(instance, overrides)

instance Instance of a light component obtained from getInstance.

overrides Dictionary with one or more of the following properties: mapSize, shadowCascades, constantBias, normalBias, shadowFar, shadowNearHint, shadowFarHint, stable, polygonOffsetConstant, polygonOffsetSlope, \

engine.setTemporalAntiAliasingOptions(overrides)

overrides Dictionary with one or more of the following properties: filterWidth, feedback, enabled.

engine.setVignetteOptions(overrides)

overrides Dictionary with one or more of the following properties: midPoint, roundness, feather, color, enabled.

class Entity

Handle to an object consisting of a set of components.

entity.delete()

Frees an entity.

To create an entity with no components, use EntityManager.
TODO: It would be better to expose these as JS numbers rather than as JS objects.
This would also be more consistent with Filament's Java bindings.

class EntityManager

Singleton used for constructing entities in Filament's ECS.

entityManager.create()

returns an Entity without any components

EntityManager.get()

Gets the singleton entity manager instance.

returns the one and only entity manager

class Frustum

Represents the six planes of a truncated viewing pyramid

class IcoSphere

Utility class for constructing spheres (requires glMatrix).

The constructor takes an integer subdivision level, with 0 being an icosahedron.
Exposes three arrays as properties:

icosphere.vertices Float32Array of XYZ coordinates.

icosphere.tangents Uint16Array (interpreted as half-floats) encoding the surface orientation
as quaternions.

icosphere.triangles Uint16Array with triangle indices.

class IndexBuffer

Array of 16-bit or 32-bit unsigned integers consumed by the GPU.

indexBuffer.setBuffer(engine, buffer, byteOffset)

engine Engine

buffer asset string, or Uint8Array, or Buffer

byteOffset non-negative integer

class Ktx1Bundle

In-memory representation of a KTX file.

ktx1Bundle.getArrayLength()

Obtains length of the texture array.

returns The number of elements in the texture array

ktx1Bundle.getCompressedPixelDataType()

returns CompressedPixelDataType

ktx1Bundle.getInternalFormat(srgb)

srgb boolean that forces the resulting format to SRGB if possible.

returns Texture$InternalFormat

ktx1Bundle.getMetadata(key)

Obtains arbitrary metadata from the KTX file.

key string

returns string

ktx1Bundle.getPixelDataFormat()

returns PixelDataFormat

ktx1Bundle.getPixelDataType()

returns PixelDataType

ktx1Bundle.info()

Obtains properties of the KTX header.

returns The KtxInfo property accessor object.

ktx1Bundle.info()

Obtains properties of the KTX header.

returns The KtxInfo property accessor object.

ktx1Bundle.isCompressed()

returns boolean

Most clients should use one of the create*FromKtx utility methods in the JavaScript Engine
wrapper rather than interacting with Ktx1Bundle directly.

class KtxInfo

Property accessor for KTX header.

ktxInfo.createAssetFromBinary(buffer)

buffer asset string, or Uint8Array, or Buffer

returns an instance of FilamentAsset

ktxInfo.createAssetFromJson(buffer)

buffer asset string, or Uint8Array, or Buffer

returns an instance of FilamentAsset

ktxInfo.createInstancedAsset(buffer)

buffer asset string, or Uint8Array, or Buffer

returns an instance of FilamentAsset

For example, Ktx1Bundle.info().pixelWidth. See the
KTX spec for the list of
properties.

class LightManager$Instance

Component instance returned by LightManager

lightManager$Instance.delete()

Frees an instance obtained via getInstance

Be sure to call the instance's delete method when you're done with it.

class PixelBufferDescriptor

Low level pixel buffer wrapper.

pixelBufferDescriptor.getBytes()

Gets a view of the WASM heap referenced by the buffer descriptor.

returns Uint8Array

Clients should use the PixelBuffer helper function to contruct PixelBufferDescriptor objects.

class RenderableManager

Allows access to properties of drawable objects.

renderableManager.getInstance(entity)

Gets an instance of the renderable component for an entity.

entity an Entity

returns a renderable component

class RenderableManager$Instance

Component instance returned by RenderableManager

renderableManager$Instance.delete()

Frees an instance obtained via getInstance

Be sure to call the instance's delete method when you're done with it.

class Renderer

Represents the platform's native window.

renderer.render(swapChain, view)

requests rendering for a single frame on the given [View]

swapChain the SwapChain corresponding to the canvas

view the View corresponding to the canvas

See also the Engine methods createRenderer and destroyRenderer.

class Scene

Flat container of renderables and lights.

See also the Engine methods createScene and destroyScene.

class SwapChain

Represents the platform's native rendering surface.

See also the Engine methods createSwapChain and destroySwapChain.

class Texture

2D image or cubemap that can be sampled by the GPU, possibly mipmapped.

class TransformManager

Adds transform components to entities.

transformManager.getInstance(entity)

Gets an instance representing the transform component for an entity.

entity an Entity

returns a transform component that can be passed to setTransform.

transformManager.setTransform(instance, matrix)

Sets the mat4 value of a transform component.

instance The transform instance of entity, obtained via getInstance.

matrix Array of 16 numbers (mat4)

class TransformManager$Instance

Component instance returned by TransformManager

transformManager$Instance.delete()

Frees an instance obtained via getInstance

transformManager$Instance.getInstance(entity)

Gets an instance of the light component for an entity.

entity an Entity

returns a light source component

Be sure to call the instance's delete method when you're done with it.

class VertexBuffer

Bundle of buffers and associated vertex attributes.

vertexBuffer.setBufferAt(engine, bufferIndex, buffer, byteOffset)

engine Engine

bufferIndex non-negative integer

buffer asset string, or Uint8Array, or Buffer

byteOffset non-negative integer

class View

Encompasses all the state needed for rendering a Scene.

A view is associated with a particular Scene, Camera, and viewport.
See also the Engine methods createView and destroyView.

function Buffer(typedarray)

Constructs a BufferDescriptor by copying a typed array into the WASM heap.

typedarray

Data to consume (e.g. Uint8Array, Uint16Array, Float32Array)

returns

BufferDescriptor

function CompressedPixelBuffer(typedarray, cdatatype, faceSize)

Constructs a PixelBufferDescriptor for compressed texture

typedarray

Data to consume (e.g. Uint8Array, Uint16Array, Float32Array)

cdatatype

CompressedPixelDataType

faceSize

Number of bytes in each face (cubemaps only)

returns

PixelBufferDescriptor

data by copying a typed array into the WASM heap.

function PixelBuffer(typedarray, format, datatype)

Constructs a PixelBufferDescriptor by copying a typed array into the WASM heap.

typedarray

Data to consume (e.g. Uint8Array, Uint16Array, Float32Array)

format

PixelDataFormat

datatype

PixelDataType

returns

PixelBufferDescriptor

function fetch(assets, onDone, onFetched)

Downloads assets and invokes a callback when done.

assets

Array of strings containing URL's of required assets.

onDone

callback that gets invoked after all assets have been downloaded.

onFetched

optional callback that's invoked after each asset is downloaded.

This utility consumes an array of URI strings and invokes callbacks after each asset is
downloaded. Additionally, each downloaded asset becomes available in the Filament.assets
global object, which is a mapping from URI strings to Uint8Array. If desired, clients can
pre-populate entries in Filament.assets to circumvent HTTP requests (this should be done after
calling Filament.init).
This function is used internally by Filament.init and gltfio$FilamentAsset.loadResources.

function getSupportedFormatSuffix(desiredFormats)

Generate a file suffix according to the texture format.

desiredFormats

space-delimited string of desired formats

returns

empty string if there is no intersection of supported and desired formats.

Consumes a string describing desired formats and produces a file suffix depending on
which (if any) of the formats are actually supported by the WebGL implementation. This is
useful for compressed textures. For example, some platforms accept ETC and others accept S3TC.

function getSupportedFormats()

Queries WebGL to check which compressed formats are supported.

returns

object with boolean values and the following keys: s3tc, astc, etc

function init(assets, onready)

Downloads assets, loads the Filament module, and invokes a callback when done.

assets

Array of strings containing URL's of required assets.

onready

callback that gets invoked after all assets have been downloaded and the Filament WebAssembly module has been loaded.

All JavaScript clients must call the init function, passing in a list of asset URL's and a
callback. This callback gets invoked only after all assets have been downloaded and the Filament
WebAssembly module has been loaded. Clients should only pass asset URL's that absolutely must
be ready at initialization time.
When the callback is called, each downloaded asset is available in the Filament.assets global
object, which contains a mapping from URL's to Uint8Array objects.

function loadMathExtensions()

Extends the glMatrix math library.

Filament does not require its clients to use glMatrix, but if its usage is detected then
the init function will automatically call loadMathExtensions.
This defines the following functions:

vec4.packSnorm16 can be used to create half-floats (see packSnorm16)

mat3.fromRotation now takes an arbitrary axis

function packSnorm16(value)

Converts a float in [-1, +1] into a half-float.

value

float

returns

half-float

enum BufferObject$BindingType

VERTEX

enum Camera$Fov

VERTICAL

HORIZONTAL

enum Camera$Projection

PERSPECTIVE

ORTHO

enum ColorGrading$QualityLevel

LOW

MEDIUM

HIGH

ULTRA

enum ColorGrading$ToneMapping

LINEAR

ACES_LEGACY

ACES

FILMIC

DISPLAY_RANGE

enum CompareFunc

LESS_EQUAL

GREATER_EQUAL

LESS

GREATER

EQUAL

NOT_EQUAL

ALWAYS

NEVER

enum CompareMode

NONE

COMPARE_TO_TEXTURE

enum CompressedPixelDataType

EAC_R11

EAC_R11_SIGNED

EAC_RG11

EAC_RG11_SIGNED

ETC2_RGB8

ETC2_SRGB8

ETC2_RGB8_A1

ETC2_SRGB8_A1

ETC2_EAC_RGBA8

ETC2_EAC_SRGBA8

DXT1_RGB

DXT1_RGBA

DXT3_RGBA

DXT5_RGBA

RGBA_ASTC_4x4

RGBA_ASTC_5x4

RGBA_ASTC_5x5

RGBA_ASTC_6x5

RGBA_ASTC_6x6

RGBA_ASTC_8x5

RGBA_ASTC_8x6

RGBA_ASTC_8x8

RGBA_ASTC_10x5

RGBA_ASTC_10x6

RGBA_ASTC_10x8

RGBA_ASTC_10x10

RGBA_ASTC_12x10

RGBA_ASTC_12x12

SRGB8_ALPHA8_ASTC_4x4

SRGB8_ALPHA8_ASTC_5x4

SRGB8_ALPHA8_ASTC_5x5

SRGB8_ALPHA8_ASTC_6x5

SRGB8_ALPHA8_ASTC_6x6

SRGB8_ALPHA8_ASTC_8x5

SRGB8_ALPHA8_ASTC_8x6

SRGB8_ALPHA8_ASTC_8x8

SRGB8_ALPHA8_ASTC_10x5

SRGB8_ALPHA8_ASTC_10x6

SRGB8_ALPHA8_ASTC_10x8

SRGB8_ALPHA8_ASTC_10x10

SRGB8_ALPHA8_ASTC_12x10

SRGB8_ALPHA8_ASTC_12x12

enum CullingMode

NONE

FRONT

BACK

FRONT_AND_BACK

enum Frustum$Plane

LEFT

RIGHT

BOTTOM

TOP

FAR

NEAR

enum IndexBuffer$IndexType

USHORT

UINT

enum LightManager$Type

SUN

DIRECTIONAL

POINT

FOCUSED_SPOT

SPOT

enum MagFilter

NEAREST

LINEAR

enum MinFilter

NEAREST

LINEAR

NEAREST_MIPMAP_NEAREST

LINEAR_MIPMAP_NEAREST

NEAREST_MIPMAP_LINEAR

LINEAR_MIPMAP_LINEAR

enum PixelDataFormat

R

R_INTEGER

RG

RG_INTEGER

RGB

RGB_INTEGER

RGBA

RGBA_INTEGER

DEPTH_COMPONENT

DEPTH_STENCIL

ALPHA

enum PixelDataType

UBYTE

BYTE

USHORT

SHORT

UINT

INT

HALF

FLOAT

UINT_10F_11F_11F_REV

USHORT_565

enum RenderTarget$AttachmentPoint

COLOR0

COLOR1

COLOR2

COLOR3

COLOR

DEPTH

enum RenderableManager$PrimitiveType

POINTS

LINES

LINE_STRIP

TRIANGLES

TRIANGLE_STRIP

NONE

enum RgbType

sRGB

LINEAR

enum RgbaType

sRGB

LINEAR

PREMULTIPLIED_sRGB

PREMULTIPLIED_LINEAR

enum Texture$CubemapFace

POSITIVE_X

NEGATIVE_X

POSITIVE_Y

NEGATIVE_Y

POSITIVE_Z

NEGATIVE_Z

enum Texture$InternalFormat

R8

R8_SNORM

R8UI

R8I

STENCIL8

R16F

R16UI

R16I

RG8

RG8_SNORM

RG8UI

RG8I

RGB565

RGB9_E5

RGB5_A1

RGBA4

DEPTH16

RGB8

SRGB8

RGB8_SNORM

RGB8UI

RGB8I

DEPTH24

R32F

R32UI

R32I

RG16F

RG16UI

RG16I

R11F_G11F_B10F

RGBA8

SRGB8_A8

RGBA8_SNORM

UNUSED

RGB10_A2

RGBA8UI

RGBA8I

DEPTH32F

DEPTH24_STENCIL8

DEPTH32F_STENCIL8

RGB16F

RGB16UI

RGB16I

RG32F

RG32UI

RG32I

RGBA16F

RGBA16UI

RGBA16I

RGB32F

RGB32UI

RGB32I

RGBA32F

RGBA32UI

RGBA32I

EAC_R11

EAC_R11_SIGNED

EAC_RG11

EAC_RG11_SIGNED

ETC2_RGB8

ETC2_SRGB8

ETC2_RGB8_A1

ETC2_SRGB8_A1

ETC2_EAC_RGBA8

ETC2_EAC_SRGBA8

DXT1_RGB

DXT1_RGBA

DXT3_RGBA

DXT5_RGBA

RGBA_ASTC_4x4

RGBA_ASTC_5x4

RGBA_ASTC_5x5

RGBA_ASTC_6x5

RGBA_ASTC_6x6

RGBA_ASTC_8x5

RGBA_ASTC_8x6

RGBA_ASTC_8x8

RGBA_ASTC_10x5

RGBA_ASTC_10x6

RGBA_ASTC_10x8

RGBA_ASTC_10x10

RGBA_ASTC_12x10

RGBA_ASTC_12x12

SRGB8_ALPHA8_ASTC_4x4

SRGB8_ALPHA8_ASTC_5x4

SRGB8_ALPHA8_ASTC_5x5

SRGB8_ALPHA8_ASTC_6x5

SRGB8_ALPHA8_ASTC_6x6

SRGB8_ALPHA8_ASTC_8x5

SRGB8_ALPHA8_ASTC_8x6

SRGB8_ALPHA8_ASTC_8x8

SRGB8_ALPHA8_ASTC_10x5

SRGB8_ALPHA8_ASTC_10x6

SRGB8_ALPHA8_ASTC_10x8

SRGB8_ALPHA8_ASTC_10x10

SRGB8_ALPHA8_ASTC_12x10

SRGB8_ALPHA8_ASTC_12x12

enum Texture$Sampler

SAMPLER_2D

SAMPLER_CUBEMAP

SAMPLER_EXTERNAL

enum Texture$Usage

DEFAULT

COLOR_ATTACHMENT

DEPTH_ATTACHMENT

STENCIL_ATTACHMENT

UPLOADABLE

SAMPLEABLE

SUBPASS_INPUT

enum VertexAttribute

POSITION

TANGENTS

COLOR

UV0

UV1

BONE_INDICES

BONE_WEIGHTS

CUSTOM0

CUSTOM1

CUSTOM2

CUSTOM3

CUSTOM4

CUSTOM5

CUSTOM6

CUSTOM7

MORPH_POSITION_0

MORPH_POSITION_1

MORPH_POSITION_2

MORPH_POSITION_3

MORPH_TANGENTS_0

MORPH_TANGENTS_1

MORPH_TANGENTS_2

MORPH_TANGENTS_3

enum VertexBuffer$AttributeType

BYTE

BYTE2

BYTE3

BYTE4

UBYTE

UBYTE2

UBYTE3

UBYTE4

SHORT

SHORT2

SHORT3

SHORT4

USHORT

USHORT2

USHORT3

USHORT4

INT

UINT

FLOAT

FLOAT2

FLOAT3

FLOAT4

HALF

HALF2

HALF3

HALF4

enum View$AmbientOcclusion

NONE

SSAO

enum View$AntiAliasing

NONE

FXAA

enum View$BlendMode

OPAQUE

TRANSLUCENT

enum View$BloomOptions$BlendMode

ADD

INTERPOLATE

enum View$DepthOfFieldOptions$Filter

NONE

MEDIAN

enum View$QualityLevel

LOW

MEDIUM

HIGH

ULTRA

enum WrapMode

CLAMP_TO_EDGE

REPEAT

MIRRORED_REPEAT

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package com.excella.selenium.synchronization;

import static org.junit.Assert.assertTrue;

import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
 * @author sean
 *
 */
public class SeleniumSynchronizationDemoTestCase {

//	private static final String USER_INTERACTION_URL = "http://localhost:8080/SeleniumTrainingWebApp/ajaxForm";
	private static final String USER_INTERACTION_URL = "http://seleniumtrainingapp.elasticbeanstalk.com/ajaxForm";

	private static WebDriver driver;

	/**
	 * @throws java.lang.Exception
	 */
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		driver = new FirefoxDriver();
	}

	/**
	 * @throws java.lang.Exception
	 */
	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		driver.quit();
	}

	@Test
	public void testDemonstrateSynchronizationProblem() throws InterruptedException {
		driver.get(USER_INTERACTION_URL);

		WebElement europeOption = driver.findElement(By.cssSelector("option[value='Europe']"));
		europeOption.click();

		TimeUnit.SECONDS.sleep(4);

		WebElement italyOption = driver.findElement(By.cssSelector("option[value='Italy']"));
		italyOption.click();

		assertTrue(europeOption.isSelected());
		assertTrue(italyOption.isSelected());
	}
}


text:
package com.hxm.earlgrey.jobs

import java.text.SimpleDateFormat
import java.util.Date
import java.util.concurrent.TimeUnit

import com.typesafe.config.{Config, ConfigFactory}
import org.mongodb.scala.{Completed, Document, MongoClient}
import org.mongodb.scala.model.Filters._

import scala.concurrent.Await
import scala.concurrent.duration.Duration

/**
  * Created by hxm on 17-4-18.
  */
class Repository(mongoUri: String) {
  val mongoClient = MongoClient(mongoUri)
  val db = mongoClient.getDatabase("EarlGrey")
  val jobs = db.getCollection("Jobs")
  val dateFormet = new SimpleDateFormat(Job.TimeFormat)

  def insertJob(job: Job): Unit = {
    Await.result(jobs.insertOne(job.doc).toFuture(), Duration(10, TimeUnit.SECONDS))
  }

  def findJob(jobId: String): Option[Job] = {
    val jobDocOption = Option(Await.result(jobs.find(equal("_id", jobId)).first().toFuture(), Duration(10, TimeUnit.SECONDS)))
    jobDocOption.map(jobDoc => Job(jobDoc))
  }

  def deleteJob(jobId: String): Unit = {
    //Refactor: return value
    Await.result(jobs.deleteOne(equal("_id", jobId)).toFuture(), Duration(10, TimeUnit.SECONDS))
  }

  def startJob(jobId: String): Unit = {
    Await.result(jobs.updateOne(equal("_id", jobId),
      Document("$set" -> Document(Job.StatusString -> Job.Status.Started
        , Job.StartedTimeString -> dateFormet.format(new Date())))).toFuture(), Duration(10, TimeUnit.SECONDS))
  }

  def endJob(jobId: String): Unit = {
    Await.result(jobs.updateOne(equal("_id", jobId),
      Document("$set" -> Document(Job.StatusString -> Job.Status.End
        , Job.EndedTimeString -> dateFormet.format(new Date())))).toFuture(), Duration(10, TimeUnit.SECONDS))
  }

  def jobError(jobId: String, message: String): Unit = {
    Await.result(jobs.updateOne(equal("_id", jobId),
      Document("$set" -> Document(Job.StatusString -> Job.Status.Error
        , Job.StatusDetailString -> message))).toFuture(), Duration(10, TimeUnit.SECONDS))
  }

  private def updateJobStatus(jobId: String, status: String): Boolean = {
    val result = Await.result(jobs.updateOne(equal("_id", jobId),
      Document("$set" -> Document(Job.StatusString -> status))).toFuture(), Duration(10, TimeUnit.SECONDS))
    if (result.getModifiedCount == 1) true
    else false
  }

  def updateJobProgress(jobId: String, progress: Int): Boolean = {
    val result = Await.result(jobs.updateOne(equal("_id", jobId),
      Document("$set" -> Document(Job.ProgressString -> progress))).toFuture(),
      Duration(10, TimeUnit.SECONDS))
    if (result.getModifiedCount == 1) true
    else false
  }

  def insertFlow(collectionName: String, flow: Flow): Unit = {
    val collection = db.getCollection(collectionName)
    Await.result(collection.insertOne(flow.toDoc()).toFuture(), Duration(10, TimeUnit.SECONDS))
  }

  def dropCollection(collectionName: String): Unit = {
    Await.result(db.getCollection(collectionName).drop().toFuture(), Duration(10, TimeUnit.SECONDS))
  }

  def collectionSize(collectionName: String): Long = {
    Await.result(db.getCollection(collectionName).count().toFuture(), Duration(10, TimeUnit.SECONDS))
  }
}

object Repository {
  def apply(): Repository = {
    val config = ConfigFactory.load("application.properties")
    val mongoUri = config.getString("spring.data.mongodb.uri")
    new Repository(mongoUri)
  }
}


text:
#include "jerryscript-ext/module.h"

#include <string.h>

#include "jerryscript.h"

static const char *module_name_property_name = "moduleName";
static const char *module_not_found = "Module not found";
static const char *module_name_not_string = "Module name is not a string";

/**
 * Create an error related to modules
 *
 * Creates an error object of the requested type with the additional property "moduleName" the value of which is a
 * string containing the name of the module that was requested when the error occurred.
 *
 * @return the error
 */
static jerry_value_t
jerryx_module_create_error (jerry_error_t error_type, /**< the type of error to create */
                            const char *message, /**< the error message */
                            const jerry_value_t module_name) /**< the module name */
{
  jerry_value_t error_object = jerry_error_sz (error_type, message);
  jerry_value_t property_name = jerry_string_sz (module_name_property_name);

  jerry_value_free (jerry_object_set (error_object, property_name, module_name));

  jerry_value_free (property_name);
  return jerry_throw_value (error_object, true);
} /* jerryx_module_create_error */

/**
 * Initialize the module manager extension.
 */
static void
jerryx_module_manager_init (void *user_data_p)
{
  *((jerry_value_t *) user_data_p) = jerry_object ();
} /* jerryx_module_manager_init */

/**
 * Deinitialize the module manager extension.
 */
static void
jerryx_module_manager_deinit (void *user_data_p) /**< context pointer to deinitialize */
{
  jerry_value_free (*(jerry_value_t *) user_data_p);
} /* jerryx_module_manager_deinit */

/**
 * Declare the context data manager for modules.
 */
static const jerry_context_data_manager_t jerryx_module_manager = { .init_cb = jerryx_module_manager_init,
                                                                    .deinit_cb = jerryx_module_manager_deinit,
                                                                    .bytes_needed = sizeof (jerry_value_t) };

/**
 * Global static entry point to the linked list of available modules.
 */
static jerryx_native_module_t *first_module_p = NULL;

void
jerryx_native_module_register (jerryx_native_module_t *module_p)
{
  module_p->next_p = first_module_p;
  first_module_p = module_p;
} /* jerryx_native_module_register */

void
jerryx_native_module_unregister (jerryx_native_module_t *module_p)
{
  jerryx_native_module_t *parent_p = NULL, *iter_p = NULL;

  for (iter_p = first_module_p; iter_p != NULL; parent_p = iter_p, iter_p = iter_p->next_p)
  {
    if (iter_p == module_p)
    {
      if (parent_p)
      {
        parent_p->next_p = module_p->next_p;
      }
      else
      {
        first_module_p = module_p->next_p;
      }
      module_p->next_p = NULL;
    }
  }
} /* jerryx_native_module_unregister */

/**
 * Attempt to retrieve a module by name from a cache, and return false if not found.
 */
static bool
jerryx_module_check_cache (jerry_value_t cache, /**< cache from which to attempt to retrieve the module by name */
                           jerry_value_t module_name, /**< JerryScript string value holding the module name */
                           jerry_value_t *result) /**< Resulting value */
{
  bool ret = false;

  /* Check if the cache has the module. */
  jerry_value_t js_has_property = jerry_object_has (cache, module_name);

  /* If we succeed in getting an answer, we examine the answer. */
  if (!jerry_value_is_exception (js_has_property))
  {
    bool has_property = jerry_value_is_true (js_has_property);

    /* If the module is indeed in the cache, we return it. */
    if (has_property)
    {
      if (result != NULL)
      {
        (*result) = jerry_object_get (cache, module_name);
      }
      ret = true;
    }
  }

  jerry_value_free (js_has_property);

  return ret;
} /* jerryx_module_check_cache */

/**
 * Attempt to cache a loaded module.
 *
 * @return the module on success, otherwise the error encountered when attempting to cache. In the latter case, the
 * @p module is released.
 */
static jerry_value_t
jerryx_module_add_to_cache (jerry_value_t cache, /**< cache to which to add the module */
                            jerry_value_t module_name, /**< key at which to cache the module */
                            jerry_value_t module) /**< the module to cache */
{
  jerry_value_t ret = jerry_object_set (cache, module_name, module);

  if (jerry_value_is_exception (ret))
  {
    jerry_value_free (module);
  }
  else
  {
    jerry_value_free (ret);
    ret = module;
  }

  return ret;
} /* jerryx_module_add_to_cache */

static const char *on_resolve_absent = "Module on_resolve () must not be NULL";

/**
 * Declare and define the default module resolver - one which examines what modules are defined in the above linker
 * section and loads one that matches the requested name, caching the result for subsequent requests using the context
 * data mechanism.
 */
static bool
jerryx_resolve_native_module (const jerry_value_t canonical_name, /**< canonical name of the module */
                              jerry_value_t *result) /**< [out] where to put the resulting module instance */
{
  const jerryx_native_module_t *module_p = NULL;

  jerry_size_t name_size = jerry_string_size (canonical_name, JERRY_ENCODING_UTF8);
  JERRY_VLA (jerry_char_t, name_string, name_size);
  jerry_string_to_buffer (canonical_name, JERRY_ENCODING_UTF8, name_string, name_size);

  /* Look for the module by its name in the list of module definitions. */
  for (module_p = first_module_p; module_p != NULL; module_p = module_p->next_p)
  {
    if (module_p->name_p != NULL && strlen ((char *) module_p->name_p) == name_size
        && !strncmp ((char *) module_p->name_p, (char *) name_string, name_size))
    {
      /* If we find the module by its name we load it and cache it if it has an on_resolve () and complain otherwise. */
      (*result) =
        ((module_p->on_resolve_p) ? module_p->on_resolve_p ()
                                  : jerryx_module_create_error (JERRY_ERROR_TYPE, on_resolve_absent, canonical_name));
      return true;
    }
  }

  return false;
} /* jerryx_resolve_native_module */

jerryx_module_resolver_t jerryx_module_native_resolver = { .get_canonical_name_p = NULL,
                                                           .resolve_p = jerryx_resolve_native_module };

static void
jerryx_module_resolve_local (const jerry_value_t name, /**< name of the module to load */
                             const jerryx_module_resolver_t **resolvers_p, /**< list of resolvers */
                             size_t resolver_count, /**< number of resolvers in @p resolvers */
                             jerry_value_t *result) /**< location to store the result, or NULL to remove the module */
{
  size_t index;
  size_t canonical_names_used = 0;
  jerry_value_t instances;
  JERRY_VLA (jerry_value_t, canonical_names, resolver_count);
  jerry_value_t (*get_canonical_name_p) (const jerry_value_t name);
  bool (*resolve_p) (const jerry_value_t canonical_name, jerry_value_t *result);

  if (!jerry_value_is_string (name))
  {
    if (result != NULL)
    {
      *result = jerryx_module_create_error (JERRY_ERROR_COMMON, module_name_not_string, name);
    }
    goto done;
  }

  instances = *(jerry_value_t *) jerry_context_data (&jerryx_module_manager);

  /**
   * Establish the canonical name for the requested module. Each resolver presents its own canonical name. If one of
   * the canonical names matches a cached module, it is returned as the result.
   */
  for (index = 0; index < resolver_count; index++)
  {
    get_canonical_name_p = (resolvers_p[index] == NULL ? NULL : resolvers_p[index]->get_canonical_name_p);
    canonical_names[index] = ((get_canonical_name_p == NULL) ? jerry_value_copy (name) : get_canonical_name_p (name));
    canonical_names_used++;
    if (jerryx_module_check_cache (instances, canonical_names[index], result))
    {
      /* A NULL for result indicates that we are to delete the module from the cache if found. Let's do that here.*/
      if (result == NULL)
      {
        jerry_object_delete (instances, canonical_names[index]);
      }
      goto done;
    }
  }

  if (result == NULL)
  {
    goto done;
  }

  /**
   * Past this point we assume a module is wanted, and therefore result is not NULL. So, we try each resolver until one
   * manages to resolve the module.
   */
  for (index = 0; index < resolver_count; index++)
  {
    resolve_p = (resolvers_p[index] == NULL ? NULL : resolvers_p[index]->resolve_p);
    if (resolve_p != NULL && resolve_p (canonical_names[index], result))
    {
      if (!jerry_value_is_exception (*result))
      {
        *result = jerryx_module_add_to_cache (instances, canonical_names[index], *result);
      }
      goto done;
    }
  }

  /* If none of the resolvers manage to find the module, complain with "Module not found" */
  *result = jerryx_module_create_error (JERRY_ERROR_COMMON, module_not_found, name);

done:
  /* Release the canonical names as returned by the various resolvers. */
  for (index = 0; index < canonical_names_used; index++)
  {
    jerry_value_free (canonical_names[index]);
  }
} /* jerryx_module_resolve_local */

/**
 * Resolve a single module using the module resolvers available in the section declared above and load it into the
 * current context.
 *
 * @p name - name of the module to resolve
 * @p resolvers - list of resolvers to invoke
 * @p count - number of resolvers in the list
 *
 * @return a jerry_value_t containing one of the followings:
 *   - the result of having loaded the module named @p name, or
 *   - the result of a previous successful load, or
 *   - an error indicating that something went wrong during the attempt to load the module.
 */
jerry_value_t
jerryx_module_resolve (const jerry_value_t name, /**< name of the module to load */
                       const jerryx_module_resolver_t **resolvers_p, /**< list of resolvers */
                       size_t resolver_count) /**< number of resolvers in @p resolvers */
{
  /* Set to zero to circumvent fatal warning. */
  jerry_value_t ret = 0;
  jerryx_module_resolve_local (name, resolvers_p, resolver_count, &ret);
  return ret;
} /* jerryx_module_resolve */

void
jerryx_module_clear_cache (const jerry_value_t name, /**< name of the module to remove, or undefined */
                           const jerryx_module_resolver_t **resolvers_p, /**< list of resolvers */
                           size_t resolver_count) /**< number of resolvers in @p resolvers */
{
  void *instances_p = jerry_context_data (&jerryx_module_manager);

  if (jerry_value_is_undefined (name))
  {
    /* We were requested to clear the entire cache, so we bounce the context data in the most agnostic way possible. */
    jerryx_module_manager.deinit_cb (instances_p);
    jerryx_module_manager.init_cb (instances_p);
    return;
  }

  /* Delete the requested module from the cache if it's there. */
  jerryx_module_resolve_local (name, resolvers_p, resolver_count, NULL);
} /* jerryx_module_clear_cache */


text:
/**
 * @fileoverview Types for defining data objects.
 */

/**
 * Currently, the visualization knows how to process values that are primitive
 * types. In the future the data format may be more liberal, at which point this
 * type should be expanded.
 *
 * It reality, these may be null or undefined, or other types, and the
 * visualization should handle those gracefully, but it aids code readability to
 * be able to count on these as numbers or strings most of the time.
 */
export type DataFieldValue = number|string;

/**
 * A data object represents a single input example. It's an object with
 * key/value pairs representing one unit. A TFExample representing an image, for
 * example.
 *
 * To use a table analogy, an object of this type would be a singel row of data,
 * with each field being a column.
 */
export interface DataExample { [fieldName: string]: DataFieldValue; }


text:
namespace chess {

class PieceBank {
  typedef Piece::Type Type;
 public:
  static const Piece* get(Piece::Type type, Position pos) {
    return theBank_.piece(type, pos);
  }
  static const Piece* moveTo(const Piece* piece, Position pos) {
    return theBank_.piece(piece->type(), pos);
  }

 private:
  PieceBank() { init(); }

  const Piece* piece(Piece::Type type, Position pos) const {
    switch (type) {
      case Type::B_PAWN :  return &bpawns_[pos.first][pos.second];
      case Type::W_PAWN :  return &wpawns_[pos.first][pos.second];
      case Type::B_ROOK :  return &rooks_[0][pos.first][pos.second];
      case Type::W_ROOK :  return &rooks_[1][pos.first][pos.second];
      case Type::B_BISHOP: return &bishops_[0][pos.first][pos.second];
      case Type::W_BISHOP: return &bishops_[1][pos.first][pos.second];
      case Type::B_KNIGHT: return &knights_[0][pos.first][pos.second];
      case Type::W_KNIGHT: return &knights_[1][pos.first][pos.second];
      case Type::B_QUEEN:  return &queens_[0][pos.first][pos.second];
      case Type::W_QUEEN:  return &queens_[1][pos.first][pos.second];
      case Type::B_KING:   return &kings_[0][pos.first][pos.second];
      case Type::W_KING:   return &kings_[1][pos.first][pos.second];
      default: return nullptr;
    }
  }

  void init() {
    for (int row = 0; row < BOARD_SIZE; ++row) {
      for (int col = 0; col < BOARD_SIZE; ++col) {
        bpawns_[row][col].setPosition({row, col});
        wpawns_[row][col].setPosition({row, col});

        rooks_[0][row][col].setPosition({row, col});
        rooks_[0][row][col].type_ = Type::B_ROOK;
        rooks_[1][row][col].setPosition({row, col});
        rooks_[1][row][col].type_ = Type::W_ROOK;

        knights_[0][row][col].setPosition({row, col});
        knights_[0][row][col].type_ = Type::B_KNIGHT;
        knights_[1][row][col].setPosition({row, col});
        knights_[1][row][col].type_ = Type::W_KNIGHT;

        bishops_[0][row][col].setPosition({row, col});
        bishops_[0][row][col].type_ = Type::B_BISHOP;
        bishops_[1][row][col].setPosition({row, col});
        bishops_[1][row][col].type_ = Type::W_BISHOP;

        kings_[0][row][col].setPosition({row, col});
        kings_[0][row][col].type_ = Type::B_KING;
        kings_[1][row][col].setPosition({row, col});
        kings_[1][row][col].type_ = Type::W_KING;

        queens_[0][row][col].setPosition({row, col});
        queens_[0][row][col].type_ = Type::B_QUEEN;
        queens_[1][row][col].setPosition({row, col});
        queens_[1][row][col].type_ = Type::W_QUEEN;
      }
    }
  }

  static PieceBank theBank_;

  BPawn bpawns_[BOARD_SIZE][BOARD_SIZE];
  WPawn wpawns_[BOARD_SIZE][BOARD_SIZE];
  Rook rooks_[2][BOARD_SIZE][BOARD_SIZE];
  Bishop bishops_[2][BOARD_SIZE][BOARD_SIZE];
  King kings_[2][BOARD_SIZE][BOARD_SIZE];
  Queen queens_[2][BOARD_SIZE][BOARD_SIZE];
  Knight knights_[2][BOARD_SIZE][BOARD_SIZE];
};

}  // namespace chess

#endif


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-receiptfilter-ipfilter.html

module Stratosphere.ResourceProperties.SESReceiptFilterIpFilter where

import Stratosphere.ResourceImports

-- | Full data type definition for SESReceiptFilterIpFilter. See
-- 'sesReceiptFilterIpFilter' for a more convenient constructor.
data SESReceiptFilterIpFilter =
  SESReceiptFilterIpFilter
  { _sESReceiptFilterIpFilterCidr :: Val Text
  , _sESReceiptFilterIpFilterPolicy :: Val Text
  } deriving (Show, Eq)

instance ToJSON SESReceiptFilterIpFilter where
  toJSON SESReceiptFilterIpFilter{..} =
    object $
    catMaybes
    [ (Just . ("Cidr",) . toJSON) _sESReceiptFilterIpFilterCidr
    , (Just . ("Policy",) . toJSON) _sESReceiptFilterIpFilterPolicy
    ]

-- | Constructor for 'SESReceiptFilterIpFilter' containing required fields as
-- arguments.
sesReceiptFilterIpFilter
  :: Val Text -- ^ 'sesrfifCidr'
  -> Val Text -- ^ 'sesrfifPolicy'
  -> SESReceiptFilterIpFilter
sesReceiptFilterIpFilter cidrarg policyarg =
  SESReceiptFilterIpFilter
  { _sESReceiptFilterIpFilterCidr = cidrarg
  , _sESReceiptFilterIpFilterPolicy = policyarg
  }

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-receiptfilter-ipfilter.html#cfn-ses-receiptfilter-ipfilter-cidr
sesrfifCidr :: Lens' SESReceiptFilterIpFilter (Val Text)
sesrfifCidr = lens _sESReceiptFilterIpFilterCidr (\s a -> s { _sESReceiptFilterIpFilterCidr = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-receiptfilter-ipfilter.html#cfn-ses-receiptfilter-ipfilter-policy
sesrfifPolicy :: Lens' SESReceiptFilterIpFilter (Val Text)
sesrfifPolicy = lens _sESReceiptFilterIpFilterPolicy (\s a -> s { _sESReceiptFilterIpFilterPolicy = a })


text:
/**
 *
 */
package net.i2geo.comped.model;

/**
 * @author Martin
 *
 */
public interface URIAddressable {

	public String getUri();
	public String getUriSuffix();
}


text:
//! \file TransformChar.hpp
#ifndef MPAGSCIPHER_TRANSFORMCHAR_HPP
#define MPAGSCIPHER_TRANSFORMCHAR_HPP

#include <string>

//! Transform input char to string for character/word set of ciphers
/*!
  \param c The character to be transformed
  \return The transformed string
*/
std::string transformChar(const char c);

#endif // MPAGSCIPHER_TRANSFORMCHAR_HPP


text:
.. _tutorial:

******************************************************************************
Tutorial: Getting Started
******************************************************************************

This section provides tutorial-level information on how to get started with PDAL.

Contents:

.. toctree::
   :maxdepth: 1

   overview
   reading
   writing
   pcl_block_tutorial
   pcl_ground


text:
//
//  ZWQRCodeReaderView.m
//  ZWQRCodeDemo
//
//  Created by 郑亚伟 on 2017/2/21.
//  Copyright © 2017年 zhengyawei. All rights reserved.
//

#import "ZWQRCodeReaderView.h"
#import <AVFoundation/AVFoundation.h>

#import "NSBundle+ZWQRCode.h"
#import "ZWQRCodeConst.h"

@interface ZWQRCodeReaderView ()<AVCaptureMetadataOutputObjectsDelegate>
/** 1.中间扫描图片  带有四个角的图片*/
@property(nonatomic, strong)UIImageView *imageScanZone;
/** 2.扫描的尺寸 */
@property(nonatomic, assign)CGRect rectScanZone;
/** 3.获取会话 */
@property(nonatomic, strong)AVCaptureSession *captureSession;
/** 4.遮罩视图 */
@property(nonatomic, strong)UIView *viewMask;
/** 5.开启闪光灯 */
@property(nonatomic, strong)UIButton *buttonTurn;
/** 6.移动的图片 */
@property(nonatomic, strong)UIImageView *imageMove;
/** 7.提示语 */
@property(nonatomic, strong)UILabel *labelAlert;

@end

@implementation ZWQRCodeReaderView
- (instancetype)init{
    self = [super init];
    if (self) {
        [self setupDefault];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupDefault];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    self.imageScanZone.frame = self.rectScanZone;
    self.buttonTurn.center = CGPointMake(self.imageScanZone.center.x, CGRectGetMaxY(self.imageScanZone.frame) + 100);
    //self.buttonTurn.center = CGPointMake(100, 200);
    self.labelAlert.center = CGPointMake(self.imageScanZone.center.x, CGRectGetMaxY(self.imageScanZone.frame) + 20);
}
#pragma mark -AVCaptureMetadataOutputObjectsDelegate
//扫描到结果后回调的代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects && metadataObjects.count > 0 ) {
        AVMetadataMachineReadableCodeObject * metadataObject = metadataObjects[0];
        //输出扫描字符串
        if (self.delegate && [self.delegate respondsToSelector:@selector(qrcodeReaderView:readerScanResult:)]) {
            [self.delegate qrcodeReaderView:self readerScanResult:metadataObject.stringValue];
        }
    }

    [self stopScan];
}

#pragma mark- Action
//闪光灯按钮点击事件
- (void)turnTorchEvent:(UIButton *)button{
    button.selected = !button.selected;
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){

            [device lockForConfiguration:nil];
            if (button.selected) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}

#pragma mark- public
//开始扫描
- (void)startScan{
    [self.captureSession startRunning];
    [self startAnimation];
}
//停止扫描
- (void)stopScan{
    [self.captureSession stopRunning];
    [self stopAnimation];
}

#pragma mark- private私有方法
- (void)setupDefault{
    // 1.基本属性
    [self setFrame:CGRectMake(0, 0, ZW_QRCODE_ScreenWidth, ZW_QRCODE_ScreenHeight)];
    [self setBackgroundColor:[UIColor blackColor]];
    [self addSubview:self.viewMask];
    [self addSubview:self.imageMove];
    [self addSubview:self.imageScanZone];
    [self addSubview:self.buttonTurn];
    [self addSubview:self.labelAlert];

    // 2.采样的区域
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    layer.frame=self.layer.bounds;
    [self.layer insertSublayer:layer atIndex:0];

    // 3.如果不支持闪光灯,不显示闪光灯按钮
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    self.buttonTurn.hidden = !device.hasTorch;
}

//设置扫描区域
-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds{
    CGFloat x,y,width,height;
    x = (CGRectGetHeight(readerViewBounds)-CGRectGetHeight(rect))/2/CGRectGetHeight(readerViewBounds);
    y = (CGRectGetWidth(readerViewBounds)-CGRectGetWidth(rect))/2/CGRectGetWidth(readerViewBounds);
    width = CGRectGetHeight(rect)/CGRectGetHeight(readerViewBounds);
    height = CGRectGetWidth(rect)/CGRectGetWidth(readerViewBounds);
    return CGRectMake(x, y, width, height);
}
//开始扫描动画
- (void)startAnimation{
    CGFloat viewW = 200*ZW_QRCODE_WidthRate;
    CGFloat viewH = 3;
    CGFloat viewX = (ZW_QRCODE_ScreenWidth - viewW)/2;
    __block CGFloat viewY = (ZW_QRCODE_ScreenHeight- viewW)/2;
    __block CGRect rect = CGRectMake(viewX, viewY, viewW, viewH);
    [UIView animateWithDuration:1.5 delay:0 options:UIViewAnimationOptionRepeat animations:^{
        viewY = (ZW_QRCODE_ScreenHeight- viewW)/2 + 200*ZW_QRCODE_WidthRate - 5;
        rect = CGRectMake(viewX, viewY, viewW, viewH);
        self.imageMove.frame = rect;
    } completion:^(BOOL finished) {
        viewY = (ZW_QRCODE_ScreenHeight- viewW)/2;
        rect = CGRectMake(viewX, viewY, viewW, viewH);
        self.imageMove.frame = rect;
    }];
}
//关闭扫描动画
- (void)stopAnimation{
    CGFloat viewW = 200*ZW_QRCODE_WidthRate;
    CGFloat viewH = 3;
    CGFloat viewX = (ZW_QRCODE_ScreenWidth - viewW)/2;
    __block CGFloat viewY = (ZW_QRCODE_ScreenHeight- viewW)/2;
    __block CGRect rect = CGRectMake(viewX, viewY, viewW, viewH);
    [UIView animateWithDuration:0.01 animations:^{
        self.imageMove.frame = rect;
    }];
}
#pragma mark -getter方法
//设置有效扫描区域
- (CGRect)rectScanZone{
    //因为总共是320  左边空出60 右边空出60  中间是200 200+60+60=320
    return CGRectMake(60*ZW_QRCODE_WidthRate, (ZW_QRCODE_ScreenHeight-200*ZW_QRCODE_WidthRate)/2, 200*ZW_QRCODE_WidthRate, 200*ZW_QRCODE_WidthRate);
}

#pragma mark -setter方法
- (AVCaptureSession *)captureSession{
    if (!_captureSession) {
        //获取摄像设备
        AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        //创建输入流
        AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        //创建输出流
        AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
        //设置代理 在主线程里刷新
        [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        CGRect scanCrop=[self getScanCrop:self.rectScanZone readerViewBounds:self.frame];
        output.rectOfInterest = scanCrop;

        //初始化链接对象
        _captureSession = [[AVCaptureSession alloc]init];
        //高质量采集率
        [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];
        if (input) {
            [_captureSession addInput:input];
        }
        if (output) {
            [_captureSession addOutput:output];
            //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
            NSMutableArray *array = [[NSMutableArray alloc] init];
            if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {
                [array addObject:AVMetadataObjectTypeQRCode];
            }
            if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN13Code]) {
                [array addObject:AVMetadataObjectTypeEAN13Code];
            }
            if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN8Code]) {
                [array addObject:AVMetadataObjectTypeEAN8Code];
            }
            if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeCode128Code]) {
                [array addObject:AVMetadataObjectTypeCode128Code];
            }
            output.metadataObjectTypes = array;
        }
    }
    return _captureSession;
}
- (UIView *)viewMask{
    if (!_viewMask) {
        _viewMask = [[UIView alloc]initWithFrame:self.bounds];
        [_viewMask setBackgroundColor:[UIColor blackColor]];
        //设置透明度
        [_viewMask setAlpha:0.6];

        //=======================================
        //绘制 --->使扫描区域完全透明,不显示遮罩效果
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path appendPath:[UIBezierPath bezierPathWithRect:_viewMask.bounds]];
        //有效扫描区的图片显示和全透明区域完全重合
        //如果将.bezierPathByReversingPath则不会产生中间全透明部分
        [path appendPath:[UIBezierPath bezierPathWithRect:self.rectScanZone].bezierPathByReversingPath];
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.path = path.CGPath;
        _viewMask.layer.mask = maskLayer;
    }
    return _viewMask;
}

- (UIImageView *)imageScanZone{
    if (!_imageScanZone) {
        _imageScanZone = [[UIImageView alloc]initWithImage:[NSBundle zw_qrCodeImageWithName:@"scanBackground@2x"]];
    }
    return _imageScanZone;
}

- (UIImageView *)imageMove{
    if (!_imageMove) {
        CGFloat viewW = 200*ZW_QRCODE_WidthRate;
        CGFloat viewH = 3;
        CGFloat viewX = (ZW_QRCODE_ScreenWidth - viewW)/2;
        CGFloat viewY = (ZW_QRCODE_ScreenHeight- viewW)/2;
        _imageMove = [[UIImageView alloc]initWithFrame:CGRectMake(viewX, viewY, viewW, viewH)];
        _imageMove.image = [NSBundle zw_qrCodeImageWithName:@"scanLine@2x"];
    }
    return _imageMove;
}
- (UIButton *)buttonTurn{
    if (!_buttonTurn) {
        _buttonTurn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_buttonTurn setBackgroundImage:[NSBundle zw_qrCodeImageWithName:@"lightSelect@2x"] forState:UIControlStateNormal];
        [_buttonTurn setBackgroundImage:[NSBundle zw_qrCodeImageWithName:@"lightNormal@2x"] forState:UIControlStateSelected];
        [_buttonTurn sizeToFit];
        [_buttonTurn addTarget:self action:@selector(turnTorchEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buttonTurn;
}

- (UILabel *)labelAlert{
    if (!_labelAlert) {
        CGFloat viewW = ZW_QRCODE_ScreenWidth;
        CGFloat viewH = 17;
        CGFloat viewX = 0;
        CGFloat viewY = 0;
        _labelAlert = [[UILabel alloc]initWithFrame:CGRectMake(viewX, viewY, viewW, viewH)];
        [_labelAlert setText:@"将二维码/条形码放置框内,即开始扫描"];
        [_labelAlert setTextColor:[UIColor whiteColor]];
        [_labelAlert setFont:[UIFont systemFontOfSize:15]];
        [_labelAlert setTextAlignment:NSTextAlignmentCenter];
    }
    return _labelAlert;
}

@end


text:
All middleware is defined in files under the `src/support/middleware` path. If you write your own middleware it should also be stored under this path.

Each middleware file is expected to expose a single _initializer_ function which, when called, will return a generator function which is the actual middleware function.

For example:

```javascript
// file: <project folder>/src/support/middleware/example.js

module.exports = function(App, options) {
  return function*(next) {
    // do nothing and pass through
    yield next;
  };
};
```

The above middleware doesn't do anything and simply passes control to the next handler in the current request's middleware chain.

If we wanted to catch and handle any errors thrown by subsequent handlers in the chain we could do:

```javascript
module.exports = function(App, options) {
  return function*(next) {
  	try {
	  yield next;
  	} catch (err) {
  	  console.error(err);
	}
  };
};
```

Middleware functions in Waigo work in the same way as ones in Koa, in that they have a defined context and associated `request` and `response` objects:

```javascript
module.exports = function(App, options) {
  return function*(next) {
  	console.log(`URL: ${this.request.url}`);

	this.response.body = 'Hello world!';
  };
};
```

Thus, existing Koa middleware functions can be re-used very easily within Waigo.

## App object

Middleware functions in Waigo also have access to your application's `App` object, which is set on the context as well as being passed in during the construction phase:

```javascript
module.exports = function(App, options) {
  return function*(next) {
  	console.log(`Running in mode: ${this.App.config.mode}`);

	yield next;
  };
};
```


text:
package org.locationtech.geowave.analytic.mapreduce.nn;

public class NNData<T> implements Comparable<NNData<T>> {
  private T neighbor;
  private double distance;

  public NNData() {}

  public NNData(final T neighbor, final double distance) {
    super();
    this.neighbor = neighbor;
    this.distance = distance;
  }

  public double getDistance() {
    return distance;
  }

  public void setDistance(final double distance) {
    this.distance = distance;
  }

  protected T getNeighbor() {
    return neighbor;
  }

  protected void setNeighbor(final T neighbor) {
    this.neighbor = neighbor;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    long temp;
    temp = Double.doubleToLongBits(distance);
    result = (prime * result) + (int) (temp ^ (temp >>> 32));
    result = (prime * result) + ((neighbor == null) ? 0 : neighbor.hashCode());
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    @SuppressWarnings("unchecked")
    final NNData<T> other = (NNData<T>) obj;
    if (Double.doubleToLongBits(distance) != Double.doubleToLongBits(other.distance)) {
      return false;
    }
    if (neighbor == null) {
      if (other.neighbor != null) {
        return false;
      }
    } else if (!neighbor.equals(other.neighbor)) {
      return false;
    }
    return true;
  }

  @Override
  public int compareTo(final NNData<T> otherNNData) {
    final int dist = Double.compare(distance, otherNNData.distance);
    // do not care about the ordering based on the neighbor data.
    // just need to force some ordering if they are not the same.
    return dist == 0 ? hashCode() - otherNNData.hashCode() : dist;
  }
}


text:
    <button type="button" title="Cancel Changes" class="btn btn-primary pull-right" ng-click="cancel()"> Cancel</button>

Edit Highlight

    <form ng-submit="ok();" id="editLandingPages" style="overflow:hidden; margin: 0px;">

        Title

          <input type="text" class="form-control" id="title" placeholder="Title" ng-model="highlight.title">

        Highlight Code

          <select class="form-control" id="highlightType" ng-model="highlight.highlightType" ng-options="type.code as type.description for type in highlightCodes"></select>

        Highlight Link

          <input type="URL" class="form-control" id="link" placeholder="Link to highlight" ng-model="highlight.link">

        Security Type

          <select smartselect type="text" class="form-control" id="tag_securityType" name="securityType" ng-model="tagForm.securityMarkingType" data-min-length="0" data-html="1" data-animation="am-flip-x" ng-options="status.code as status.description for status in securityTypes">
            <option style="display:none" value="">Select a Type</option>
          </select>

      <textarea ckeditor="editorOptions" ng-model="editorContent" ng-watch="editorContentWatch"></textarea>

        <button type="submit" style="display:inline-block;" class="btn btn-default"> Save Changes</button>
        <button type="button" style="display:inline-block;" class="btn btn-primary" ng-click="cancel()">Cancel</button>

    </form>


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RawRabbit.Logging;
using RawRabbit.Pipe;

namespace RawRabbit.Operations.Publish.Middleware
{
	public class ReturnCallbackOptions
	{
		public Func<IPipeContext, EventHandler<BasicReturnEventArgs>> CallbackFunc { get; set; }
		public Func<IPipeContext, IModel> ChannelFunc { get; set; }
		public Action<IPipeContext, EventHandler<BasicReturnEventArgs>> PostInvokeAction { get; set; }
	}

	public class ReturnCallbackMiddleware : Pipe.Middleware.Middleware
	{
		protected Func<IPipeContext, EventHandler<BasicReturnEventArgs>> CallbackFunc;
		protected Func<IPipeContext, IModel> ChannelFunc;
		protected Action<IPipeContext, EventHandler<BasicReturnEventArgs>> PostInvoke;
		private readonly ILog _logger = LogProvider.For<ReturnCallbackMiddleware>();

		public ReturnCallbackMiddleware(ReturnCallbackOptions options = null)
		{
			CallbackFunc = options?.CallbackFunc ?? (context => context.GetReturnCallback());
			ChannelFunc = options?.ChannelFunc?? (context => context.GetTransientChannel());
			PostInvoke = options?.PostInvokeAction;
		}

		public override async Task InvokeAsync(IPipeContext context, CancellationToken token)
		{
			var callback = GetCallback(context);
			if (callback == null)
			{
				_logger.Debug("No Mandatory Callback registered.");
				await Next.InvokeAsync(context, token);
				return;
			}

			var channel = GetChannel(context);
			if (channel == null)
			{
				_logger.Warn("Channel not found in Pipe Context. Mandatory Callback not registered.");
				await Next.InvokeAsync(context, token);
				return;
			}

			_logger.Debug("Register Mandatory Callback on channel {channelNumber}", channel.ChannelNumber);
			channel.BasicReturn += callback;
			PostInvoke?.Invoke(context, callback);

			await Next.InvokeAsync(context, token);
			_logger.Debug("Removing Mandatory Callback on channel {channelNumber}", channel.ChannelNumber);
			channel.BasicReturn -= callback;
		}

		protected virtual IModel GetChannel(IPipeContext context)
		{
			return ChannelFunc(context);
		}

		protected virtual EventHandler<BasicReturnEventArgs> GetCallback(IPipeContext context)
		{
			return CallbackFunc(context);
		}
	}
}


text:
<?php

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
use Rubenwouters\CrmLauncher\Models\Reaction;
use Rubenwouters\CrmLauncher\Models\Message;
use Rubenwouters\CrmLauncher\Models\Configuration;

/**
 * Removes _normal from twitter profile link
 * @param  string $link
 * @return string
 */
function getOriginalImg($link)
{
    return str_replace('_normal', '', $link);
}

/**
 * Checks error code and returns appropriate error
 * @param  integer $code
 * @return string
 */
function getErrorMessage($code)
{
    $lang = 'crm-launcher::errors.' . $code;
    $error = trans($lang);

    if (strpos($error, 'crm-launcher') !== false) {
        Session::flash('flash_error', trans('crm-launcher::errors.default'));
    } else {
        Session::flash('flash_error', trans('crm-launcher::errors.' . $code));
    }
}

/**
 * Changes Twitter's date format to Y-m-d
 * @param  string $date
 * @return string
 */
function changeDateFormat($date)
{
    $convertedDate = new DateTime($date);
    $convertedDate->add(date_interval_create_from_date_string('2 hours'));

    return $convertedDate->format("Y-m-d H:i:s");
}

/**
 * Changes Facebook's date format Y-m-d
 * @param  string $date
 * @return string
 */
function changeFbDateFormat($date)
{
    return date("Y-m-d H:i:s", strtotime($date));
}

/**
 * Filter URL out of string
 *
 * @param  string $message
 * @return string
 */
function filterUrl($message)
{
    $pattern = "/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i";

    return preg_replace($pattern, '', $message);
}

/**
 * Initializes Facebook connection
 */
function initFb()
{
    $fb = new \Facebook\Facebook([
        'app_id' => config('crm-launcher.facebook_credentials.facebook_app_id'),
        'app_secret' => config('crm-launcher.facebook_credentials.facebook_app_secret'),
        'default_graph_version' => 'v2.6',
    ]);

    return $fb;
}

/**
 * Initializes Twitter connection
 */
function initTwitter()
{
    $stack = HandlerStack::create();

    $oauth = new Oauth1([
        'consumer_key' => config('crm-launcher.twitter_credentials.twitter_consumer_key'),
        'consumer_secret' => config('crm-launcher.twitter_credentials.twitter_consumer_secret'),
        'token' => config('crm-launcher.twitter_credentials.twitter_access_token'),
        'token_secret' => config('crm-launcher.twitter_credentials.twitter_access_token_secret')
    ]);

    $stack->push($oauth);

    $client = new Client([
        'base_uri' => 'https://api.twitter.com/1.1/',
        'handler' => $stack,
        'auth' => 'oauth'
    ]);

    return $client;
}

/**
 * Check if configurations are set
 * @return boolean
 */
function hasFbPermissions()
{
    return Configuration::exists() && Configuration::first()->facebook_access_token;
}

/**
 * Check if configuration is done and successful
 * @return boolean
 */
function isConfigured()
{
    if (Configuration::exists() && Configuration::first()->valid_credentials) {
        return true;
    }

    return false;
}

/**
 * Check if user still needs 'help' section
 * @return boolean
 */
function needsHelp(){

    if (Configuration::exists() && ! Configuration::first()->help_disabled) {
        return true;
    }

    return false;
}

/**
 * Check if Twitter is used
 * @return boolean
 */
function isTwitterLinked()
{
    if (Configuration::exists()) {
        return Configuration::first()->linked_twitter;
    }

    return false;
}

/**
 * Check if Facebook is linked
 * @return boolean
 */
function isFacebookLinked()
{
    if (Configuration::exists()) {
        return Configuration::first()->linked_facebook;
    }

    return false;
}

/**
 * Checks if .ENV file is filled out with Twitter credentials
 * @return boolean
 */
function isTwitterEnvFilledOut()
{
    if (!config('crm-launcher.twitter_credentials.twitter_consumer_key') ||
        !config('crm-launcher.twitter_credentials.twitter_consumer_secret') ||
        !config('crm-launcher.twitter_credentials.twitter_access_token') ||
        !config('crm-launcher.twitter_credentials.twitter_access_token_secret')
    ) {
        return false;
    }

    return true;
}

/**
 * Checks if .ENV file is filled out with FB credentials
 * @return boolean
 */
function isFbEnvFilledOut()
{
    if (!config('crm-launcher.facebook_credentials.facebook_app_id') ||
        !config('crm-launcher.facebook_credentials.facebook_app_secret') ||
        !config('crm-launcher.facebook_credentials.facebook_page_id')
    ) {
        return false;
    }

    return true;
}

/**
 * Get profile picture of user on Facebook
 * @param  integer $id
 * @return view
 */
function getProfilePicture($id)
{
    $fb = initFb();
    $token = Configuration::FbAccessToken();

    try {
        $picture = $fb->get('/' . $id . '/picture?redirect=false&type=large', $token);
        $picture = json_decode($picture->getBody());
        return $picture->data->url;
    } catch (Exception $e) {
        getErrorMessage($e->getCode());
        return back();
    }
}

/**
 * Gets latest inserted mention id (Twitter).
 * @return id
 */
function latestMentionId()
{
    $messageId = $reactionId = false;

    if (Message::where('tweet_id', '!=', '')->exists()) {
        $messageId = Message::latestMentionId();
    }
    if (Reaction::where('tweet_id', '!=', '')->exists()) {
        $reactionId = Reaction::latestMentionId();
    }

    return max($messageId, $reactionId);
}

/**
 * Get latest inserted direct message ID
 * @return integer
 */
function latestDirect()
{
    $tweet_id = 0;

    if (Message::where('direct_id', '!=', '')->where('direct_id', '!=', '0')->exists()) {
        $tweet_id = Message::LatestDirectId();
    }

    return $tweet_id;
}

/**
 * Get latest comment date (Facebook)
 * @return datetime
 */
function latestCommentDate()
{
    $messageId = $reactionId = false;

    if (Message::where('fb_reply_id', '!=', '')->exists()) {
        $messageId = Message::where('fb_reply_id', '!=', '')->orderBy('post_date', 'DESC')->first()->post_date;
    }
    if (Reaction::where('fb_post_id', '!=', '')->exists()) {
        $reactionId = Reaction::where('fb_post_id', '!=', '')->orderBy('post_date', 'DESC')->first()->post_date;
    }

    return max($messageId, $reactionId);
}