text:
.. _writers.bpf:

writers.bpf
===========

The **BPF Writer** supports writing of version 3 BPF format files.

Example
-------

.. code-block:: xml

  <?xml version="1.0" encoding="utf-8"?>
  <Pipeline version="1.0">
    <Writer type="writers.bpf">
      <Option name="filename">
        outputfile.bpf
      </Option>
      <Reader type="readers.las">
        <Option name="filename">
          inputfile.las
        </Option>
      </Reader>
    </Writer>
  </Pipeline>

Options
-------

filename
  BPF file to read.  The writer will accept a filename containing
  a single placeholder character ('#').  If input to the writer consists
  of multiple PointViews, each will be written to a separate file, where
  the placeholder will be replaced with an incrementing integer.  If no
  placeholder is found, all PointViews provided to the writer are
  aggregated into a single file for output.  Multiple PointViews are usually
  the result of using :ref:`filters.splitter` or :ref:`filters.chipper`.
  [Required]

compression
  This option can be set to true to cause the file to be written with Zlib
  compression as described in the BPF specification.  [Default: false]

format
  Specifies the format for storing points in the file. [Default: dim]

  * dim == Dimension-major (non-interleaved).  All data for a single dimension
    are stored contiguously.
  * point == Point-major (interleaved).  All data for a single point are stored
    contiguously.
  * byte == Byte-major (byte-segregated).  All data for a single dimension are
    stored contiguously, but bytes are arranged such that the first bytes for
    all points are stored contiguously, followed by the second bytes of all
    points, etc.  See the BPF specification for further information.

bundledfile
  Path of file to be written as a bundled file (see specification).  The path
  part of the filespec is removed and the filename is stored as part of the
  data.  This option can be specified as many times as desired.

header_data
  Base64-encoded data that will be decoded and written following the
  standard BPF header.

coord_id
  The coordinate ID (UTM zone) of the data.  NOTE: Only the UTM coordinate
  type is currently supported. [Default: 0, with coordinate type set to none]

scale_x, scale_y, scale_z
  Scale to be divided from the X, Y and Z nominal values, respectively, after
  the offset has been applied.  The special value "auto" can be specified,
  which causes the writer to select a scale to set the stored values of the
  dimensions to range from [0, 2147483647].  [Default: .01]

  Note: written value = (nominal value - offset) / scale.

offset_x, offset_y, offset_z
   Offset to be subtracted from the X, Y and Z nominal values, respectively,
   before the value is scaled.  The special value "auto" can be specified,
   which causes the writer to set the offset to the minimum value of the
   dimension.  [Default: 0]

   Note: written value = (nominal value - offset) / scale.


text:
import * as dateFns from 'date-fns'
import * as R from 'ramda'
import * as React from 'react'

import pipeThru from 'utils/pipeThru'

import { COLUMN_IDS, EMPTY_VALUE } from './constants'

const serializeAddress = (addressPath) => addressPath.join(', ')

const getAddressPath = (key, parentPath) =>
  key === '' ? parentPath : (parentPath || []).concat(key)

const getSchemaType = R.prop('type')

const getSchemaItem = ({ item, sortIndex, key, parentPath, required }) => ({
  address: getAddressPath(key, parentPath),
  required,
  valueSchema: item,
  sortIndex,
  type: getSchemaType(item),
})

const assocObjValue = R.assocPath

export const getJsonDictValue = (objPath, jsonDict) =>
  R.prop(serializeAddress(objPath), jsonDict)

export const getObjValue = R.path

function moveObjValue(oldObjPath, key, obj) {
  const oldItem = getObjValue(oldObjPath, obj)
  const oldValue = oldItem === undefined ? EMPTY_VALUE : oldItem
  return assocObjValue(
    R.append(key, R.init(oldObjPath)),
    oldValue,
    dissocObjValue(oldObjPath, obj),
  )
}

const dissocObjValue = R.dissocPath

// NOTE: memo is mutated, sortOrder is React.ref and mutated too
export function iterateSchema(schema, sortOrder, parentPath, memo) {
  if (!schema.properties) return memo

  const requiredKeys = schema.required
  getSchemaItemKeys(schema).forEach((key) => {
    // eslint-disable-next-line no-param-reassign
    sortOrder.current.counter += 1

    const rawItem = schema.properties[key]
    const required = requiredKeys ? requiredKeys.includes(key) : false
    const item = getSchemaItem({
      item: rawItem,
      key,
      parentPath,
      required,
      sortIndex: sortOrder.current.counter,
    })
    // eslint-disable-next-line no-param-reassign
    memo[serializeAddress(item.address)] = item

    // eslint-disable-next-line no-param-reassign
    sortOrder.current.counter += 1
    iterateSchema(rawItem, sortOrder, item.address, memo)
  })

  return memo
}

// NOTE: memo is mutated
function objToDict(obj, parentPath, memo) {
  const isObjArray = Array.isArray(obj)
  if (isObjArray) {
    obj.forEach((value, index) => {
      const address = getAddressPath(index, parentPath)
      // eslint-disable-next-line no-param-reassign
      memo[serializeAddress(address)] = value

      objToDict(value, address, memo)
    })
    return memo
  }

  if (typeof obj === 'object' && obj !== null && !isObjArray) {
    const keys = Object.keys(obj)

    if (!keys.length) return memo

    keys.forEach((key) => {
      const address = getAddressPath(key, parentPath)
      // eslint-disable-next-line no-param-reassign
      memo[serializeAddress(address)] = obj[key]

      // weird eslint bug?
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      objToDict(obj[key], address, memo)
    })
    return memo
  }

  return memo
}

function calcReactId(valuePath, value) {
  const pathPrefix = serializeAddress(valuePath)
  // TODO: store preview for value, and reuse it for Preview
  return `${pathPrefix}+${JSON.stringify(value)}`
}

function getDefaultValue(jsonDictItem) {
  if (!jsonDictItem || !jsonDictItem.valueSchema) return EMPTY_VALUE

  const schema = jsonDictItem.valueSchema
  try {
    if (schema.format === 'date' && schema.dateformat)
      return dateFns.format(new Date(), schema.dateformat)
  } catch (error) {
    // eslint-disable-next-line no-console
    console.error(error)
  }
  if (schema.default !== undefined) return schema.default
  return EMPTY_VALUE
}

function getJsonDictItem(jsonDict, obj, parentPath, key, sortOrder) {
  const itemAddress = serializeAddress(getAddressPath(key, parentPath))
  const item = jsonDict[itemAddress]
  // NOTE: can't use R.pathOr, because Ramda thinks `null` is `undefined` too
  const valuePath = getAddressPath(key, parentPath)
  const storedValue = R.path(valuePath, obj)
  const value = storedValue === undefined ? getDefaultValue(item) : storedValue
  return {
    [COLUMN_IDS.KEY]: key,
    [COLUMN_IDS.VALUE]: value,
    reactId: calcReactId(valuePath, storedValue),
    sortIndex: (item && item.sortIndex) || sortOrder.current.dict[itemAddress] || 0,
    ...(item || {}),
  }
}

const noKeys = []

function getObjValueKeys(objValue) {
  if (Array.isArray(objValue)) return R.range(0, objValue.length)
  if (R.is(Object, objValue)) return Object.keys(objValue)
  return noKeys
}

function getObjValueKeysByPath(obj, objPath, rootKeys) {
  if (!objPath.length) return rootKeys

  const objValue = R.path(objPath, obj)
  return getObjValueKeys(objValue)
}

function getSchemaItemKeys(schemaItem) {
  if (!schemaItem || !schemaItem.properties) return noKeys
  const keys = Object.keys(schemaItem.properties)

  if (!schemaItem.required) return keys

  const sortOrder = schemaItem.required.reduce(
    (memo, key, index) => ({
      [key]: index,
      ...memo,
    }),
    {},
  )
  const getSortIndex = (key) =>
    R.ifElse(R.has(key), R.prop(key), R.always(Infinity))(sortOrder)
  return R.sortBy(getSortIndex, keys)
}

function getSchemaItemKeysByPath(jsonDict, objPath) {
  const itemAddress = serializeAddress(objPath)
  const item = jsonDict[itemAddress]
  return item && item.valueSchema ? getSchemaItemKeys(item.valueSchema) : noKeys
}

function getSchemaAndObjKeys(obj, jsonDict, objPath, rootKeys) {
  return R.uniq([
    ...getSchemaItemKeysByPath(jsonDict, objPath),
    ...getObjValueKeysByPath(obj, objPath, rootKeys),
  ])
}

export function iterateJsonDict(jsonDict, obj, fieldPath, rootKeys, sortOrder) {
  if (!fieldPath.length)
    return [
      pipeThru(rootKeys)(
        R.map((key) => getJsonDictItem(jsonDict, obj, fieldPath, key, sortOrder)),
        R.sortBy(R.prop('sortIndex')),
        (items) => ({
          parent: obj,
          items,
        }),
      ),
    ]

  return ['', ...fieldPath].map((_, index) => {
    const pathPart = R.slice(0, index, fieldPath)

    const keys = getSchemaAndObjKeys(obj, jsonDict, pathPart, rootKeys)
    return pipeThru(keys)(
      R.map((key) => getJsonDictItem(jsonDict, obj, pathPart, key, sortOrder)),
      R.sortBy(R.prop('sortIndex')),
      (items) => ({
        parent: R.path(pathPart, obj),
        items,
      }),
    )
  })
}

export function mergeSchemaAndObjRootKeys(schema, obj) {
  const schemaKeys = getSchemaItemKeys(schema)
  const objKeys = getObjValueKeys(obj)
  return R.uniq([...schemaKeys, ...objKeys])
}

export default function JsonEditorState({ children, jsonObject, schema }) {
  // NOTE: fieldPath is like URL for editor columns
  //       `['a', 0, 'b']` means we are focused to `{ a: [ { b: %HERE% }, ... ], ... }`
  const [fieldPath, setFieldPath] = React.useState([])

  // NOTE: incremented sortIndex counter,
  //       and cache for sortIndexes: { [keyA]: sortIndexA, [keyB]: sortIndexB }
  //       it's required to place new fields below existing ones
  const sortOrder = React.useRef({ counter: 0, dict: {} })

  // NOTE: stores additional info about every object field besides value, like sortIndex, schema etc.
  //       it's a main source of data after actual JSON object
  const jsonDict = React.useMemo(() => {
    sortOrder.current.counter = Number.MIN_SAFE_INTEGER
    const result = iterateSchema(schema, sortOrder, [], {})
    sortOrder.current.counter = 0
    return result
  }, [schema, sortOrder])

  // NOTE: list of root object keys + root schema keys
  const rootKeys = React.useMemo(
    () => mergeSchemaAndObjRootKeys(schema, jsonObject),
    [schema, jsonObject],
  )

  // NOTE: this data represents table columns shown to user
  //       it's the main source of UI data
  const columns = React.useMemo(
    () => iterateJsonDict(jsonDict, jsonObject, fieldPath, rootKeys, sortOrder),
    [jsonObject, jsonDict, fieldPath, rootKeys],
  )

  // TODO: Use `sortIndex: -1` to "remove" fields that cannot be removed,
  //       like properties from JSON Schema
  const removeField = React.useCallback(
    (removingFieldPath) => dissocObjValue(removingFieldPath, jsonObject),
    [jsonObject],
  )

  const changeValue = React.useCallback(
    (editingFieldPath, columnId, str) => {
      // TODO: str is not string, it's any value
      // TODO: make this `safeStr` conversion inside component
      const safeStr = str === EMPTY_VALUE ? '' : str
      if (columnId === COLUMN_IDS.KEY) {
        return moveObjValue(editingFieldPath, safeStr, jsonObject)
      }

      if (columnId === COLUMN_IDS.VALUE) {
        return assocObjValue(editingFieldPath, safeStr, jsonObject)
      }

      return jsonObject
    },
    [jsonObject],
  )

  const addRow = React.useCallback(
    (addFieldPath, key, value) => {
      // NOTE: value can't be `Symbol('empty')`
      //       because it's imposible to have `{ [newKey]: Symbol('empty') }` object
      sortOrder.current.counter += 1

      const newKeyPath = addFieldPath.concat([key])
      const itemAddress = serializeAddress(newKeyPath)
      sortOrder.current.dict[itemAddress] = sortOrder.current.counter
      return assocObjValue(newKeyPath, value, jsonObject)
    },
    [jsonObject, sortOrder],
  )

  return children({
    addRow,
    changeValue,
    columns,
    fieldPath,
    jsonDict,
    removeField,
    setFieldPath,
  })
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>contentful.errors — Contentful 1.13.2 documentation</title>
    <link rel="stylesheet" href="../../_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />

  <link rel="stylesheet" href="../../_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

Source code for contentful.errors

"""
contentful.errors
~~~~~~~~~~~~~~~~~

This module implements the Error classes.

API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/introduction/errors

:copyright: (c) 2016 by Contentful GmbH.
:license: MIT, see LICENSE for more details.
"""

[docs]class HTTPError(Exception):
    """
    Base HTTP Error Class
    """

    def __init__(self, response):
        self.response = response
        self.status_code = response.status_code

        message = self._best_available_message(response)
        super(HTTPError, self).__init__(message)

    def _default_error_message(self):
        return "The following error was received: {0}".format(self.response.text)

    def _handle_details(self, details):
        return "{0}".format(details)

    def _has_additional_error_info(self):
        return False

    def _additional_error_info(self):
        return []

    def _best_available_message(self, response):
        from .utils import json_error_class

        response_json = None
        error_message = [
          "HTTP status code: {0}".format(self.status_code),
        ]
        try:
            response_json = response.json()

            message = response_json.get('message', None)
            details = response_json.get('details', None)
            request_id = response_json.get('requestId', None)

            if message is not None:
                error_message.append("Message: {0}".format(message))
            else:
                error_message.append("Message: {0}".format(self._default_error_message()))
            if details is not None:
                error_message.append("Details: {0}".format(self._handle_details(details)))
            if request_id is not None:
                error_message.append("Request ID: {0}".format(request_id))
        except json_error_class():
            error_message.append("Message: {0}".format(self._default_error_message()))

        if self._has_additional_error_info():
            error_message += self._additional_error_info()

        return "\n".join(error_message)

[docs]class BadRequestError(HTTPError):
    """
    400
    """

    def _default_error_message(self):
        return "The request was malformed or missing a required parameter."

    def _handle_details(self, details):
        from .utils import string_class
        if isinstance(details, string_class()):
            return details

        def _handle_detail(detail):
            if isinstance(detail, string_class()):
                return detail
            return detail.get('details', None)

        inner_details = [_handle_detail(detail) for detail in details['errors']]
        inner_details = [detail for detail in inner_details if detail is not None]  # This works in both Py2 and Py3
        return "\n\t".join(inner_details)

[docs]class UnauthorizedError(HTTPError):
    """
    401
    """

    def _default_error_message(self):
        return "The authorization token was invalid."

[docs]class AccessDeniedError(HTTPError):
    """
    403
    """

    def _default_error_message(self):
        return "The specified token does not have access to the requested resource."

    def _handle_details(self, details):
        return "\n\tReasons:\n\t\t{0}".format("\n\t\t".join(details['reasons']))

[docs]class NotFoundError(HTTPError):
    """
    404
    """

    def _default_error_message(self):
        return "The requested resource or endpoint could not be found."

    def _handle_details(self, details):
        from .utils import string_class
        if isinstance(details, string_class()):
            return details

        resource_type = None
        resource_id = None
        if 'sys' in details:
            resource_type = details['sys'].get('type', None)
            resource_id = details['sys'].get('id', None)
        else:
            resource_type = details['type']
            resource_id = details.get('id', None)

        message = "The requested {0} could not be found.".format(resource_type)
        if resource_id is not None:
            message += " ID: {0}.".format(resource_id)

        return message

[docs]class RateLimitExceededError(HTTPError):
    """
    429
    """

    RATE_LIMIT_RESET_HEADER_KEY = 'x-contentful-ratelimit-reset'

    def _has_reset_time(self):
        return self.RATE_LIMIT_RESET_HEADER_KEY in self.response.headers

[docs]    def reset_time(self):
        """Returns the reset time in seconds until next available request."""

        return int(self.response.headers[
            self.RATE_LIMIT_RESET_HEADER_KEY
        ])

    def _has_additional_error_info(self):
        return self._has_reset_time()

    def _additional_error_info(self):
        return ["Time until reset (seconds): {0}".format(self.reset_time())]

    def _default_error_message(self):
        return "Rate limit exceeded. Too many requests."

[docs]class ServerError(HTTPError):
    """
    500
    """

    def _default_error_message(self):
        return "Internal server error."

[docs]class BadGatewayError(HTTPError):
    """
    502
    """

    def _default_error_message(self):
        return "The requested space is hibernated."

[docs]class ServiceUnavailableError(HTTPError):
    """
    503
    """

    def _default_error_message(self):
        return "The request was malformed or missing a required parameter."

[docs]class EntryNotFoundError(Exception):
    """
    Error for entry not found.
    """
    pass

[docs]def get_error(response):
    """Gets Error by HTTP Status Code"""

    errors = {
        400: BadRequestError,
        401: UnauthorizedError,
        403: AccessDeniedError,
        404: NotFoundError,
        429: RateLimitExceededError,
        500: ServerError,
        502: BadGatewayError,
        503: ServiceUnavailableError
    }

    error_class = HTTPError
    if response.status_code in errors:
        error_class = errors[response.status_code]

    return error_class(response)

Related Topics

Documentation overview

Module code

Quick search

    <form class="search" action="../../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2016, Contentful GmbH.


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

// @ts-nocheck
// TODO(crbug.com/1011811): Enable TypeScript compiler checks

import {TabbedPane} from './TabbedPane.js';  // eslint-disable-line no-unused-vars
import {ItemsProvider, Toolbar, ToolbarItem, ToolbarMenuButton} from './Toolbar.js';  // eslint-disable-line no-unused-vars
import {ViewManager} from './ViewManager.js';
import {VBox, Widget} from './Widget.js';

/**
 * @interface
 */
export class View {
  /**
   * @return {string}
   */
  viewId() {
  }

  /**
   * @return {string}
   */
  title() {
  }

  /**
   * @return {boolean}
   */
  isCloseable() {
  }

  /**
   * @return {boolean}
   */
  isTransient() {
  }

  /**
   * @return {!Promise<!Array<!ToolbarItem>>}
   */
  toolbarItems() {
  }

  /**
   * @return {!Promise<!Widget>}
   */
  widget() {
  }

  /**
   * @return {!Promise<void>|void}
   */
  disposeView() {}
}

export const _symbol = Symbol('view');
export const _widgetSymbol = Symbol('widget');

// Closure is unhappy with the private access of _widgetSymbol,
// so re-export it under a public symbol.
export const widgetSymbol = _widgetSymbol;

/**
 * @implements {View}
 * @unrestricted
 */
export class SimpleView extends VBox {
  /**
   * @param {string} title
   * @param {boolean=} isWebComponent
   */
  constructor(title, isWebComponent) {
    super(isWebComponent);
    this._title = title;
    this[_symbol] = this;
  }

  /**
   * @override
   * @return {string}
   */
  viewId() {
    return this._title;
  }

  /**
   * @override
   * @return {string}
   */
  title() {
    return this._title;
  }

  /**
   * @override
   * @return {boolean}
   */
  isCloseable() {
    return false;
  }

  /**
   * @override
   * @return {boolean}
   */
  isTransient() {
    return false;
  }

  /**
   * @override
   * @return {!Promise<!Array<!ToolbarItem>>}
   */
  toolbarItems() {
    return Promise.resolve([]);
  }

  /**
   * @override
   * @return {!Promise<!Widget>}
   */
  widget() {
    return (
        /** @type {!Promise<!Widget>} */ (Promise.resolve(this)));
  }

  /**
   * @return {!Promise<void>}
   */
  revealView() {
    return ViewManager.instance().revealView(this);
  }

  /**
   * @override
   */
  disposeView() {
  }
}

/**
 * @implements {View}
 * @unrestricted
 */
export class ProvidedView {
  /**
   * @param {!Root.Runtime.Extension} extension
   */
  constructor(extension) {
    this._extension = extension;
  }

  /**
   * @override
   * @return {string}
   */
  viewId() {
    return this._extension.descriptor()['id'];
  }

  /**
   * @override
   * @return {string}
   */
  title() {
    return this._extension.title();
  }

  /**
   * @override
   * @return {boolean}
   */
  isCloseable() {
    return this._extension.descriptor()['persistence'] === 'closeable';
  }

  /**
   * @override
   * @return {boolean}
   */
  isTransient() {
    return this._extension.descriptor()['persistence'] === 'transient';
  }

  /**
   * @override
   * @return {!Promise<!Array<!ToolbarItem>>}
   */
  toolbarItems() {
    const actionIds = this._extension.descriptor()['actionIds'];
    if (actionIds) {
      const result = actionIds.split(',').map(id => Toolbar.createActionButtonForId(id.trim()));
      return Promise.resolve(result);
    }

    if (this._extension.descriptor()['hasToolbar']) {
      return this.widget().then(widget => /** @type {!ItemsProvider} */ (widget).toolbarItems());
    }
    return Promise.resolve([]);
  }

  /**
   * @override
   * @return {!Promise<!Widget>}
   */
  async widget() {
    this._widgetRequested = true;
    const widget = await this._extension.instance();
    if (!(widget instanceof Widget)) {
      throw new Error('view className should point to a UI.Widget');
    }
    widget[_symbol] = this;
    return (
        /** @type {!Widget} */ (widget));
  }

  /**
   * @override
   */
  async disposeView() {
    if (!this._widgetRequested) {
      return;
    }
    const widget = await this.widget();
    widget.ownerViewDisposed();
  }
}

/**
 * @interface
 */
export class ViewLocation {
  /**
   * @param {string} locationName
   */
  appendApplicableItems(locationName) {
  }

  /**
   * @param {!View} view
   * @param {?View=} insertBefore
   */
  appendView(view, insertBefore) {
  }

  /**
   * @param {!View} view
   * @param {?View=} insertBefore
   * @param {boolean=} userGesture
   * @return {!Promise<*>}
   */
  showView(view, insertBefore, userGesture) {
  }

  /**
   * @param {!View} view
   */
  removeView(view) {
  }

  /**
   * @return {!Widget}
   */
  widget() {
  }
}

/**
 * @interface
 */
export class TabbedViewLocation extends ViewLocation {
  /**
   * @return {!TabbedPane}
   */
  tabbedPane() {
  }

  /**
   * @return {!ToolbarMenuButton}
   */
  enableMoreTabsButton() {
  }
}

/**
 * @interface
 */
export class ViewLocationResolver {
  /**
   * @param {string} location
   * @return {?ViewLocation}
   */
  resolveLocation(location) {
  }
}


text:
require 'mock.gfx.asset.ParticleHelper'
require 'mock.gfx.asset.ParticleProcs'

--GRAPHICS
require 'mock.gfx.asset.TextureBase'
require 'mock.gfx.asset.ThreadTextureLoadTask'
require 'mock.gfx.asset.PrebuiltAtlas'
require 'mock.gfx.asset.Texture'
require 'mock.gfx.asset.MultiTexture'
require 'mock.gfx.asset.Deck2D'
require 'mock.gfx.asset.DefaultFont'
require 'mock.gfx.asset.Font'
require 'mock.gfx.asset.TextStyle'
require 'mock.gfx.asset.RenderMaterial'

--GRAPHICS ADV
require 'mock.gfx.asset.RenderTargetTexture'
require 'mock.gfx.asset.ShaderConfig'
require 'mock.gfx.asset.Shader'
require 'mock.gfx.asset.ShaderScript'
require 'mock.gfx.asset.CodeTileset'
require 'mock.gfx.asset.NamedTileset'
require 'mock.gfx.asset.DeckPack'
require 'mock.gfx.asset.QuadsDeck'
require 'mock.gfx.asset.MQuadDeck'
require 'mock.gfx.asset.MTileset'

--PARTICLE
require 'mock.gfx.asset.Particle'
require 'mock.gfx.asset.SimpleParticle'
require 'mock.gfx.asset.PexParticle'

--ANIMATIONS
require 'mock.gfx.asset.Spine'
require 'mock.gfx.asset.MSpriteAsset'
require 'mock.gfx.asset.AuroraSprite'

--Mesh
require 'mock.gfx.asset.Mesh'

--------------------------------------------------------------------
--------------------------------------------------------------------
--Common
require 'mock.gfx.RenderComponent'
require 'mock.gfx.UVTransform'
require 'mock.gfx.GraphicsPropComponent'

--------------------------------------------------------------------
--Camera
require 'mock.gfx.camera'

--------------------------------------------------------------------
---- Base
require 'mock.gfx.DeckComponent'
require 'mock.gfx.DeckComponentArray'
require 'mock.gfx.DeckComponentGrid'
require 'mock.gfx.DeckComponentSequence'
require 'mock.gfx.DeckCanvas'

--------------------------------------------------------------------
---- Graphics
require 'mock.gfx.Prop'
-- require 'mock.gfx.Text'
require 'mock.gfx.TextLabel'
require 'mock.gfx.PatchSprite'

require 'mock.gfx.DrawScript'

require 'mock.gfx.Geometry'
require 'mock.gfx.TexturePlane'
require 'mock.gfx.TiledTextureRect'
require 'mock.gfx.TexturePolygon'
require 'mock.gfx.TextureCircle'
require 'mock.gfx.SubTexturePlane'
require 'mock.gfx.PatchTexturePlane'

require 'mock.gfx.TileMap'
require 'mock.gfx.NamedTileMap'
require 'mock.gfx.TileMap2D'
require 'mock.gfx.CodeTileMapLayer'

require 'mock.gfx.ParticleSystem'
require 'mock.gfx.ParticleEmitter'

--------------------------------------------------------------------
---- Extended
require 'mock.gfx.AuroraSprite'

require 'mock.gfx.MSprite'
require 'mock.gfx.MSpriteCopy'
require 'mock.gfx.MSpriteAnimatorTrack'

require 'mock.gfx.SpineSpriteBase'
require 'mock.gfx.SpineSprite'
require 'mock.gfx.SpineSpriteSimple'

--------------------------------------------------------------------
---Camera Fx
require 'mock.gfx.camerafx'

--------------------------------------------------------------------
--PaintCanvas
require 'mock.gfx.paintcanvas'

--------------------------------------------------------------------
--Movie
require 'mock.gfx.movie'


text:
package org.basex.query.util.regex;

/**
 * Character group.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Leo Woerteler
 */
public final class CharGroup extends RegExp {
  /** Negation flag, set after construction. */
  public boolean negative;
  /** Sub-ranges. */
  private final RegExp[] subs;
  /**
   * Constructor.
   * @param subs sub-ranges
   */
  public CharGroup(final RegExp[] subs) {
    this.subs = subs;
  }

  @Override
  void toRegEx(final StringBuilder sb) {
    sb.append(negative ? "^" : "");
    for(final RegExp sub : subs) sub.toRegEx(sb);
  }
}


text:
#ifndef __CHAPTERSEDITOR__
#define __CHAPTERSEDITOR__

int addChapters(const char *mp4, NSArray *chapters);

#endif // __CHAPTERSEDITOR__


text:
<html>
<body>
This intention removes unnecessary escape characters from a selected string.
</body>
</html>


text:
[dumb-cat](http://mrucci.github.io/dumb-cat/)
=============================================

As technological advances allow us to implement more and more complex applications, our brains' desire of dumb cats increases exponentially.  Scientists say.

In particular, this dumb cat is dumb.  And he should feel dumb.

<small>
Photo courtesy of [dat'](http://www.flickr.com/photos/dat-pics/)
</small>


text:
package com.apcera.servicegateway.model;

import java.net.MalformedURLException;
import java.net.URL;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

public class ProviderState {

	// URL holds the value of the required parameter.
	private String url;

	// DefaultTablespace holds the default tablespace name for the user.
	@JsonProperty("default-tablespace")
	private String defaultTablespace;

	// TemporaryTablespace holds the temporary tablespace name for the user.
	@JsonProperty("temporary-tablespace")
	private String temporaryTablespace;

	@JsonIgnore
	private String host;

	public String getHost() {
		if (host == null) {
			try {
				backend();
			} catch (MalformedURLException e) {
				// Ignore, was called to find host.
			}
		}
		return host;
	}

	public String getUrl() {
		return url;
	}

	public String getDefaultTablespace() {
		return defaultTablespace;
	}

	public String getTemporaryTablespace() {
		return temporaryTablespace;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setDefaultTablespace(String defaultTablespace) {
		this.defaultTablespace = defaultTablespace;
	}

	public void setTemporaryTablespace(String temporaryTablespace) {
		this.temporaryTablespace = temporaryTablespace;
	}

	@Override
	public String toString() {
		return "[URL: "+url+" default-tablespace: "+defaultTablespace+" temporary-tablespace: "+temporaryTablespace+"]";
	}

	/*
	 * Convert URL to jdbc URI.
	 * Sample URL: oracle://<user>:<pass>@localhost:1521/XE.
	 */
	public String backend() throws MalformedURLException {
		// oracle is an unknown protocol.
		URL u = new URL(url.replaceFirst("oracle", "http"));
		StringBuilder sb = new StringBuilder("jdbc:oracle:thin:");

		// Username and passwd.
		String userinfo = u.getUserInfo();
		if (userinfo != null) {
			String[] creds = userinfo.split(":");
			sb.append(creds[0]).append('/').append(creds[1]);
		}

		// Host, port and rest.
		host = u.getHost();
		sb.append("@");
		sb.append(host).append(':').append(u.getPort());
		if (u.getPath() != null) {
			sb.append(u.getPath());
		}
		if (u.getQuery() != null) {
			sb.append(u.getQuery());
		}
		return sb.toString();
	}
}


text:
package templates

const Dockerfile = `
# {{.ImageName}}
FROM openshift/base-centos7

# TODO: Put the maintainer name in the image metadata
# MAINTAINER Your Name <your@email.com>

# TODO: Rename the builder environment variable to inform users about application you provide them
# ENV BUILDER_VERSION 1.0

# TODO: Set labels used in OpenShift to describe the builder image
#LABEL io.k8s.description="Platform for building xyz" \
#      io.k8s.display-name="builder x.y.z" \
#      io.openshift.expose-services="8080:http" \
#      io.openshift.tags="builder,x.y.z,etc."

# TODO: Install required packages here:
# RUN yum install -y ... && yum clean all -y

# TODO (optional): Copy the builder files into /opt/openshift
# COPY ./<builder_folder>/ /opt/openshift/

# TODO: Copy the S2I scripts to /usr/local/sti, since openshift/base-centos7 image sets io.openshift.s2i.scripts-url label that way, or update that label
# COPY ./.sti/bin/ /usr/local/sti

# TODO: Drop the root user and make the content of /opt/openshift owned by user 1001
# RUN chown -R 1001:1001 /opt/openshift

# This default user is created in the openshift/base-centos7 image
USER 1001

# TODO: Set the default port for applications built using this image
# EXPOSE 8080

# TODO: Set the default CMD for the image
# CMD ["usage"]
`


text:
package mb.nabl2.constraints.messages;

import static mb.nabl2.terms.build.TermBuild.B;
import static mb.nabl2.terms.matching.TermMatch.M;

import mb.nabl2.terms.ITerm;
import mb.nabl2.terms.matching.TermMatch.IMatcher;

public enum MessageKind {

    ERROR, WARNING, NOTE;

    private static final String ERROR_OP = "Error";
    private static final String WARNING_OP = "Warning";
    private static final String NOTE_OP = "Note";

    public static IMatcher<MessageKind> matcher() {
        // @formatter:off
        return M.cases(
            M.appl0(ERROR_OP, e -> ERROR),
            M.appl0(WARNING_OP, e -> WARNING),
            M.appl0(NOTE_OP, e -> NOTE)
        );
        // @formatter:on
    }

    public static ITerm build(MessageKind kind) {
        switch(kind) {
            case ERROR:
                return B.newAppl(ERROR_OP);
            case WARNING:
                return B.newAppl(WARNING_OP);
            case NOTE:
                return B.newAppl(NOTE_OP);
            default:
                throw new IllegalArgumentException();
        }
    }

}


text:
#include "emulate-fns.h"

#include "emulator.h"
#include "regression.h"

/**
 * emulates the model at through emulate_min -> emulate_max in each dimension
 * @param results -> malloc'd and filled by testPts.txt
 * @return results has the calculted new_x, emulated_mean, emulated_var
 */
void emulate_model_results(modelstruct *the_model, optstruct* options, resultstruct* results){

	int i;
	double determinant_c = 0.0;

	gsl_matrix *c_matrix = gsl_matrix_alloc(options->nmodel_points, options->nmodel_points);
	gsl_matrix *cinverse = gsl_matrix_alloc(options->nmodel_points, options->nmodel_points);

	gsl_vector *beta_vector = gsl_vector_alloc(options->nregression_fns);
	gsl_matrix *h_matrix = gsl_matrix_alloc(options->nmodel_points, options->nregression_fns);

	gsl_matrix *temp_matrix = gsl_matrix_alloc(options->nmodel_points, options->nmodel_points);

	// create the covariance matrix and save a copy in temp_matrix
	makeCovMatrix(c_matrix, the_model->xmodel, the_model->thetas,options->nmodel_points, options->nthetas, options->nparams);
	gsl_matrix_memcpy(temp_matrix, c_matrix);

	//print_matrix(temp_matrix, options->nmodel_points, options->nmodel_points);

	chol_inverse_cov_matrix(options, temp_matrix, cinverse, &determinant_c);

	// regression cpts
	makeHMatrix(h_matrix, the_model->xmodel, options->nmodel_points, options->nparams, options->nregression_fns);
	estimateBeta(beta_vector, h_matrix, cinverse, the_model->training_vector, options->nmodel_points, options->nregression_fns);

	fprintf(stderr, "regression cpts: ");
	for(i = 0; i < options->nregression_fns; i++)
		fprintf(stderr, "%g ", gsl_vector_get(beta_vector, i));
	fprintf(stderr, "\n");

	// set the new_x values
	// NO longer, now we will use the values given in the resultstruct
	/* initialise_new_x(results->new_x, options->nparams, options->nemulate_points, options->emulate_min, options->emulate_max); */

	for(i = 0; i < options->nemulate_points; i++){
		printf("%g\n", gsl_matrix_get(results->new_x, i,0));
	}

	for(i = 0; i < options->nemulate_points; i++){
		emulate_ith_location(the_model, options, results, i, h_matrix, cinverse, beta_vector);
	}

	gsl_matrix_free(c_matrix);
	gsl_matrix_free(cinverse);
	gsl_matrix_free(h_matrix);
	gsl_matrix_free(temp_matrix);
	gsl_vector_free(beta_vector);
}

/**
 * this is the same as calling emulateAtPoint a bunch of times but you
 * save on the setup costs of init'ing all the memory, should be quite
 * a lot faster for a large number of points
 *
 * emulate the model at a list of points
 * @return *the_variance is set to the variance of each location in the list
 * @return *the_mean is set to the mean at each loc
 */
void emulateAtPointList(modelstruct *the_model, gsl_matrix* point_list, optstruct* options,
												double* the_mean, double* the_variance){
	int i;
	double determinant_c = 0.0;

	resultstruct results;

	gsl_matrix *c_matrix = gsl_matrix_alloc(options->nmodel_points, options->nmodel_points);
	gsl_matrix *cinverse = gsl_matrix_alloc(options->nmodel_points, options->nmodel_points);

	gsl_vector *beta_vector = gsl_vector_alloc(options->nregression_fns);
	gsl_matrix *h_matrix = gsl_matrix_alloc(options->nmodel_points, options->nregression_fns);

	gsl_matrix *temp_matrix = gsl_matrix_alloc(options->nmodel_points, options->nmodel_points);

	// allocate the resultsstruct
	alloc_resultstruct(&results, options);
	//results.new_x = gsl_matrix_alloc(options->nemulate_points, options->nparams);

	//fprintf(stderr, "%d %d\n", point_list->size1, point_list->size2);
	// copy in the x-values we want
	gsl_matrix_memcpy(results.new_x, point_list);

	/* for(i = 0; i < options->nparams; i++){ */
	/* 	printf("%g", gsl_matrix_get(results.new_x,0,i)); */
	/* } */
	/* printf("\n"); */

	// create the covariance matrix and save a copy in temp_matrix
	makeCovMatrix_fnptr(c_matrix, the_model->xmodel, the_model->thetas,options->nmodel_points, options->nthetas, options->nparams, the_model->covariance_fn);
	gsl_matrix_memcpy(temp_matrix, c_matrix);

	chol_inverse_cov_matrix(options, temp_matrix, cinverse, &determinant_c);

	// regression cpts
	makeHMatrix(h_matrix, the_model->xmodel, options->nmodel_points, options->nparams, options->nregression_fns);
	estimateBeta(beta_vector, h_matrix, cinverse, the_model->training_vector, options->nmodel_points, options->nregression_fns);

	for(i = 0; i < options->nemulate_points; i++){
		emulate_ith_location(the_model, options, &results, i, h_matrix, cinverse, beta_vector);
		the_mean[i] = gsl_vector_get(results.emulated_mean, i);
		the_variance[i] = gsl_vector_get(results.emulated_var, i);
	}

	gsl_matrix_free(c_matrix);
	gsl_matrix_free(cinverse);
	gsl_matrix_free(h_matrix);
	gsl_matrix_free(temp_matrix);
	gsl_vector_free(beta_vector);

	free_resultstruct(&results);
}

/**
 * emulate the model at the location of the_point
 * @return *the_variance is set to the variance at this location
 * @return *the_mean is set to the emulated mean at this loc
 */
void emulateAtPoint(modelstruct *the_model, gsl_vector* the_point, optstruct* options, double* the_mean, double* the_variance){

	double determinant_c = 0.0;

	gsl_matrix *c_matrix = gsl_matrix_alloc(options->nmodel_points, options->nmodel_points);
	gsl_matrix *cinverse = gsl_matrix_alloc(options->nmodel_points, options->nmodel_points);
	gsl_vector *beta_vector = gsl_vector_alloc(options->nregression_fns);
	gsl_matrix *h_matrix = gsl_matrix_alloc(options->nmodel_points, options->nregression_fns);
	gsl_matrix *temp_matrix = gsl_matrix_alloc(options->nmodel_points, options->nmodel_points);
	double kappa;
	double temp_mean, temp_var;
	gsl_vector *kplus = gsl_vector_alloc(options->nmodel_points);
	gsl_vector *h_vector = gsl_vector_alloc(options->nregression_fns);

	// create the covariance matrix and save a copy in temp_matrix
	makeCovMatrix(c_matrix, the_model->xmodel, the_model->thetas,options->nmodel_points, options->nthetas, options->nparams);
	gsl_matrix_memcpy(temp_matrix, c_matrix);

	chol_inverse_cov_matrix(options, temp_matrix, cinverse, &determinant_c);

	// regression cpts
	makeHMatrix(h_matrix, the_model->xmodel, options->nmodel_points, options->nparams, options->nregression_fns);
	estimateBeta(beta_vector, h_matrix, cinverse, the_model->training_vector, options->nmodel_points, options->nregression_fns);

	makeKVector(kplus, the_model->xmodel, the_point, the_model->thetas, options->nmodel_points, options->nthetas, options->nparams);
	makeHVector(h_vector, the_point, options->nparams);

	temp_mean = makeEmulatedMean(cinverse, the_model->training_vector, kplus, h_vector, h_matrix, beta_vector, options->nmodel_points);
	kappa = covariance_fn(the_point, the_point, the_model->thetas, options->nthetas, options->nparams);
	temp_var = makeEmulatedVariance(cinverse, kplus, h_vector, h_matrix, kappa, options->nmodel_points, options->nregression_fns);

	if(temp_mean > 100){
		printf("EF:mean:%lf\tvar:%lf\n", temp_mean, temp_var);
		print_vector_quiet(the_point,options->nparams);
		printf("kplus:\n");
		print_vector_quiet(kplus, options->nmodel_points);
		printf("hvector:\n");
		print_vector_quiet(h_vector, options->nregression_fns);
		printf("beta:\n");
		print_vector_quiet(beta_vector, options->nregression_fns);
		//exit(1);
	}

	*the_mean = temp_mean;
	*the_variance = temp_var;

	gsl_vector_free(kplus);
	gsl_vector_free(h_vector);
	gsl_matrix_free(c_matrix);
	gsl_matrix_free(cinverse);
	gsl_matrix_free(h_matrix);
	gsl_matrix_free(temp_matrix);
	gsl_vector_free(beta_vector);

}

/**
 * emulate the model at the location the_point using the precomputed inverse cov_matrix, beta_vector, h_matrix and
 * so forth
 */

void emulateQuick( modelstruct *the_model, gsl_vector* the_point, optstruct* options,
									 double* mean_out, double* var_out, gsl_matrix *h_matrix, gsl_matrix *cinverse, gsl_vector* beta_vector ){

	double kappa;
	double temp_mean, temp_var;
	gsl_vector *kplus = gsl_vector_alloc(options->nmodel_points);
	gsl_vector *h_vector = gsl_vector_alloc(options->nregression_fns);

	makeKVector(kplus, the_model->xmodel, the_point, the_model->thetas, options->nmodel_points, options->nthetas, options->nparams);

	makeHVector(h_vector, the_point, options->nparams);

	temp_mean = makeEmulatedMean(cinverse, the_model->training_vector, kplus, h_vector, h_matrix, beta_vector, options->nmodel_points);

	kappa = covariance_fn(the_point, the_point, the_model->thetas, options->nthetas, options->nparams);

	temp_var = makeEmulatedVariance(cinverse, kplus, h_vector, h_matrix, kappa, options->nmodel_points, options->nregression_fns);

	//fprintf(stderr, "temp_mean %lf\ttemp_var %lf\n", temp_mean, temp_var);
	// save the results
	*mean_out = temp_mean;
	*var_out = temp_var;

	gsl_vector_free(kplus);
	gsl_vector_free(h_vector);

}

/**
 * emulate the model at the ith entry in results->new_x
 */
void emulate_ith_location(modelstruct *the_model, optstruct *options, resultstruct *results,int i, gsl_matrix* h_matrix, gsl_matrix* cinverse, gsl_vector *beta_vector){
	double kappa;
	double temp_mean, temp_var;
	gsl_vector_view new_x_row;
	gsl_vector *kplus = gsl_vector_alloc(options->nmodel_points);
	gsl_vector *h_vector = gsl_vector_alloc(options->nregression_fns);

	// read the new x location
	new_x_row = gsl_matrix_row(results->new_x, i);
	//fprintf(stderr, "i(%d) new_x_row: ", i);
	//print_vector_quiet(&new_x_row.vector, options->nparams);

	makeKVector(kplus, the_model->xmodel, &new_x_row.vector, the_model->thetas, options->nmodel_points, options->nthetas, options->nparams);

	makeHVector(h_vector, &new_x_row.vector, options->nparams);

	temp_mean = makeEmulatedMean(cinverse, the_model->training_vector, kplus, h_vector, h_matrix, beta_vector, options->nmodel_points);

	kappa = covariance_fn(&new_x_row.vector, &new_x_row.vector, the_model->thetas, options->nthetas, options->nparams);

	temp_var = makeEmulatedVariance(cinverse, kplus, h_vector, h_matrix, kappa, options->nmodel_points, options->nregression_fns);

	//fprintf(stderr, "temp_mean %lf\ttemp_var %lf\n", temp_mean, temp_var);

	gsl_vector_set(results->emulated_mean, i, temp_mean);
	gsl_vector_set(results->emulated_var, i, temp_var);

	gsl_vector_free(kplus);
	gsl_vector_free(h_vector);
}

/**
 * cholesky decompose temp_matrix, invert it and copy the result into result_matrix
 * the determinant of the cholesky decomp is also calculated
 *
 * it might be worth adding a little noise here, or catching the gsl error and trying to
 * recover?
 */

void chol_inverse_cov_matrix(optstruct* options, gsl_matrix* temp_matrix, gsl_matrix* result_matrix, double* final_determinant_c){
	int cholesky_test, i;
	double determinant_c = 0.0;
	gsl_error_handler_t *temp_handler; // disable the default handler
	// do a cholesky decomp of the cov matrix, LU is not stable for ill conditioned matrices
	temp_handler = gsl_set_error_handler_off();
	cholesky_test = gsl_linalg_cholesky_decomp(temp_matrix);
	if(cholesky_test == GSL_EDOM){
		fprintf(stderr, "trying to cholesky a non postive def matrix, in emulate-fns.c sorry...\n");
		exit(1);
	}
	gsl_set_error_handler(temp_handler);

	// find the determinant and then invert
	// the determinant is just the trace squared
	determinant_c = 1.0;
	for(i = 0; i < options->nmodel_points; i++)
		determinant_c *= gsl_matrix_get(temp_matrix, i, i);
	determinant_c = determinant_c * determinant_c;

	//printf("det CHOL:%g\n", determinant_c);
	gsl_linalg_cholesky_invert(temp_matrix);
	gsl_matrix_memcpy(result_matrix, temp_matrix);
	*final_determinant_c = determinant_c;
}


text:
                        {{account.name}}

                                基本信息

                              公众号管理

                              注销


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Semaphore (Quartz Enterprise Job Scheduler 2.2.0 API)
</TITLE>

<META NAME="date" CONTENT="2013-06-29">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.quartz.impl.jdbcjobstore

Interface Semaphore

All Known Implementing Classes:
DBSemaphore, JTANonClusteredSemaphore, SimpleSemaphore, StdRowLockSemaphore, UpdateLockRowSemaphore

public interface Semaphore

An interface for providing thread/resource locking in order to protect
 resources from being altered by multiple threads at the same time.

Author:

jhouse

Method Summary

 boolean
obtainLock(Connection conn,
           String lockName)

          Grants a lock on the identified resource to the calling thread (blocking
 until it is available).

 void
releaseLock(String lockName)

          Release the lock on the identified resource if it is held by the calling
 thread.

 boolean
requiresConnection()

          Whether this Semaphore implementation requires a database connection for
 its lock management operations.

Method Detail

obtainLock

boolean obtainLock(Connection conn,
                   String lockName)
                   throws LockException

Grants a lock on the identified resource to the calling thread (blocking
 until it is available).

Parameters:
conn - Database connection used to establish lock.  Can be null if
 requiresConnection() returns false.

Returns:
true if the lock was obtained.

Throws:

LockException

releaseLock

void releaseLock(String lockName)
                 throws LockException

Release the lock on the identified resource if it is held by the calling
 thread.

Throws:

LockException

requiresConnection

boolean requiresConnection()

Whether this Semaphore implementation requires a database connection for
 its lock management operations.

See Also:
obtainLock(Connection, String),
releaseLock(String)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 2001-2013, Terracotta, Inc.


text:
"""
A Python helper library for `Alfred 2 <http://www.alfredapp.com/>`_ Workflow
authors.

Alfred Workflows typically take user input, fetch data from the Web or
elsewhere, filter them and display results to the user. **Alfred-Workflow**
helps you do these things.

There are convenience methods for:

- Parsing script arguments.
- Text decoding/normalisation.
- Storing data and settings.
- Caching data from, e.g., web services with a simple API for updating expired
  data.
- Securely storing (and syncing) passwords using OS X Keychain.
- Generating XML output for Alfred.
- Including external libraries (adding directories to ``sys.path``).
- Filtering results using an Alfred-like, fuzzy search algorithm.
- Generating log output for debugging.
- Running background processes to keep your workflow responsive.
- Capturing errors, so the workflow doesn't fail silently.

Quick Example
=============

Here's how to show recent `Pinboard.in <https://pinboard.in/>`_ posts in Alfred.

Create a new Workflow in Alfred's preferences. Add a **Script Filter** with
Language ``/usr/bin/python`` and paste the following into the **Script** field
(changing ``API_KEY``):

.. code-block:: python
   :emphasize-lines: 4

    import sys
    from workflow import Workflow, ICON_WEB, web

    API_KEY = 'your-pinboard-api-key'

    def main(wf):
        url = 'https://api.pinboard.in/v1/posts/recent'
        params = dict(auth_token=API_KEY, count=20, format='json')
        r = web.get(url, params)
        r.raise_for_status()
        for post in r.json()['posts']:
            wf.add_item(post['description'], post['href'], arg=post['href'],
                        uid=post['hash'], valid=True, icon=ICON_WEB)
        wf.send_feedback()

    if __name__ == u"__main__":
        wf = Workflow()
        sys.exit(wf.run(main))

Add an **Open URL** action to your Workflow with ``{query}`` as the **URL**,
connect your **Script Filter** to it, and you can now hit **ENTER** on a
Pinboard item in Alfred to open it in your browser.

Installation
============

With pip
--------

You can install **Alfred-Workflow** directly into your workflow with::

    pip install --target=/path/to/my/workflow Alfred-Workflow

**Note**: If you intend to distribute your workflow to other users, you should
include **Alfred-Workflow** (and other Python libraries your workflow requires)
within your workflow as described. Do not ask users to install anything into
their system Python.

From source
-----------

Download the ``alfred-workflow-X.X.zip`` file from the
`GitHub releases page <https://github.com/deanishe/alfred-workflow/releases>`_
and either extract the ZIP to the root directory of your workflow (where
``info.plist`` is) or place the ZIP in the root directory and add
``sys.path.insert(0, 'alfred-workflow-X.X.zip')`` to the top of your
Python scripts.

Alternatively, you can download
`the source code <https://github.com/deanishe/alfred-workflow/archive/master.zip>`_
from the `GitHub repository <https://github.com/deanishe/alfred-workflow>`_ and
copy the ``workflow`` subfolder to the root directory of your Workflow.

Your Workflow directory should look something like this (where
``yourscript.py`` contains your Workflow code and ``info.plist`` is
the Workflow information file generated by Alfred)::

    Your Workflow/
        info.plist
        icon.png
        workflow/
            __init__.py
            background.py
            workflow.py
            web.py
        yourscript.py
        etc.

Or like this::

    Your Workflow/
        info.plist
        icon.png
        workflow-1.X.X.zip
        yourscript.py
        etc.

"""

__version__ = '1.8.5'

from .workflow import Workflow, PasswordNotFound, KeychainError
from .workflow import (ICON_ERROR, ICON_WARNING, ICON_NOTE, ICON_INFO,
                       ICON_FAVORITE, ICON_FAVOURITE, ICON_USER, ICON_GROUP,
                       ICON_HELP, ICON_NETWORK, ICON_WEB, ICON_COLOR,
                       ICON_COLOUR, ICON_SYNC, ICON_SETTINGS, ICON_TRASH,
                       ICON_MUSIC, ICON_BURN, ICON_ACCOUNT, ICON_ERROR)
from .workflow import (MATCH_ALL, MATCH_ALLCHARS, MATCH_ATOM,
                       MATCH_CAPITALS, MATCH_INITIALS,
                       MATCH_INITIALS_CONTAIN, MATCH_INITIALS_STARTSWITH,
                       MATCH_STARTSWITH, MATCH_SUBSTRING)


text:
import * as React from "react";
import * as Scrivito from "scrivito";
import Helmet from "react-helmet";

class Snipcart extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isSnipcartInstalled: false
    };
  }

  componentDidMount() {
    Scrivito.load(() => getSnipcartKey()).then(snipcartKey => {
      if (snipcartKey) {
        this.setState({ isSnipcartInstalled: true });
      }
    });
  }

  render() {
    if (!this.state.isSnipcartInstalled) {
      return null;
    }

    return (
      <Helmet>
        <script
          src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"
        />
        <script
          src="https://cdn.snipcart.com/scripts/2.0/snipcart.js"
          id="snipcart"
          data-api-key={`${getSnipcartKey()}`}
        />
        <link
          href="https://cdn.snipcart.com/themes/2.0/base/snipcart.min.css"
          type="text/css"
          rel="stylesheet"
        />
      </Helmet>
    );
  }
}

function getSnipcartKey() {
  const rootPage = Scrivito.Obj.root();

  if (!rootPage) {
    return;
  }
  return rootPage.get("snipcartApiKey");
}

export default Scrivito.connect(Snipcart);


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');

abstract class Auth extends Kohana_Auth {

	public function check_password($password)
	{
		$user = $this->get_user();

		if ( ! $user) {
			return false;
		}

		return password_verify($password, $this->hash($password));
	}

	/**
	 * Perform a hmac hash, using the configured method.
	 *
	 * @param   string  $str  string to hash
	 * @return  string
	 */
	public function hash($str)
	{
		if ( ! $this->_config['hash_algorihtm'])
			throw new Kohana_Exception('A valid hash algorithm must be set in your auth config.');

		return password_hash(
			$str,
			$this->_config['hash_algorihtm'],
			Arr::get($this->_config, 'hash_options', array())
		);
	}

} // End Auth


text:
package io.netty.handler.codec.mqtt;

import io.netty.handler.codec.DecoderException;

/**
 * A {@link MqttIdentifierRejectedException} which is thrown when a CONNECT request contains invalid client identifier.
 */
public final class MqttIdentifierRejectedException extends DecoderException {

    private static final long serialVersionUID = -1323503322689614981L;

    /**
     * Creates a new instance
     */
    public MqttIdentifierRejectedException() { }

    /**
     * Creates a new instance
     */
    public MqttIdentifierRejectedException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Creates a new instance
     */
    public MqttIdentifierRejectedException(String message) {
        super(message);
    }

    /**
     * Creates a new instance
     */
    public MqttIdentifierRejectedException(Throwable cause) {
        super(cause);
    }

}


text:
import constants from "../actions/constants";

const iniState = {
    name: 'default',
    id: ''
};

const selectArticle = (state = iniState, action) => {
    const article = action.param;
    switch (action.type) {

        case constants.selectArticle: {
            return article;
        }

        default:
            return state;
    }
};

export default selectArticle;


text:
package com.ab.download;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import com.ab.util.AbLogUtil;

// TODO: Auto-generated Javadoc

/**
 * © 2012 amsoft.cn
 * 名称:AbDownloadThread.java
 * 描述:下载线程类.
 *
 * @author 还如一梦中
 * @version v1.0
 * @date:2013-10-16 下午1:33:39
 */
public class AbDownloadThread extends Thread {

	/** The save file. */
	private File saveFile;

	/** The m down file. */
	private DownFile mDownFile = null;

	/** The finish. */
	private boolean finish = false;

	/** The flag. */
	private boolean flag = false;

	/** The downloader. */
	private AbFileDownloader downloader;

	/**
	 * Instantiates a new download thread.
	 *
	 * @param downloader the downloader
	 * @param downFile the down file
	 * @param saveFile the save file
	 */
	public AbDownloadThread(AbFileDownloader downloader, DownFile downFile, File saveFile) {
		this.saveFile = saveFile;
		this.downloader = downloader;
		this.mDownFile = downFile;
	}

	/**
	 * 描述:运行.
	 *
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		flag = true;
		InputStream inStream = null;
		RandomAccessFile threadfile = null;
		//未下载完成
		if(mDownFile.getDownLength() < mDownFile.getTotalLength()){
			try {
				//使用Get方式下载
				URL mUrl = new URL(mDownFile.getDownUrl());
				HttpURLConnection http = (HttpURLConnection) mUrl.openConnection();
				http.setConnectTimeout(5 * 1000);
				http.setRequestMethod("GET");
				http.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
				http.setRequestProperty("Accept-Language", "zh-CN");
				http.setRequestProperty("Referer", mDownFile.getDownUrl());
				http.setRequestProperty("Charset", "UTF-8");
				//设置获取实体数据的范围
				http.setRequestProperty("Range", "bytes=" + mDownFile.getDownLength() + "-"+ mDownFile.getTotalLength());
				http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
				http.setRequestProperty("Connection", "Keep-Alive");

				inStream = http.getInputStream();
				byte[] buffer = new byte[1024];
				int offset = 0;
				threadfile = new RandomAccessFile(this.saveFile, "rwd");
				threadfile.seek(mDownFile.getDownLength());

				while (flag && (offset = inStream.read(buffer, 0, 1024)) != -1) {
					AbLogUtil.d(AbDownloadThread.class, "offset:"+offset);
					if(offset!=0){
						threadfile.write(buffer, 0, offset);
						mDownFile.setDownLength(mDownFile.getDownLength()+offset);
						offset = 0;
						AbLogUtil.d(AbDownloadThread.class, "DownLength:"+mDownFile.getDownLength()+"/"+mDownFile.getTotalLength());
						downloader.update(mDownFile);

						if(mDownFile.getDownLength() == mDownFile.getTotalLength()){
							this.finish = true;
							flag = false;
							break;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				mDownFile.setDownLength(-1);
			} finally{
				try {
					if(threadfile!=null){
						threadfile.close();
					}
					if(inStream!=null){
						inStream.close();
					}
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * 下载是否完成.
	 *
	 * @return true, if is finish
	 */
	public boolean isFinish() {
		return finish;
	}

	/**
	 * Gets the save file.
	 *
	 * @return the save file
	 */
	public File getSaveFile() {
		return saveFile;
	}

	/**
	 * Sets the flag.
	 *
	 * @param flag the new flag
	 */
	public void setFlag(boolean flag) {
		this.flag = flag;
	}

}


text:
package com.afollestad.appthemeengine.inflation;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.view.menu.ActionMenuItemView;
import android.support.v7.view.menu.MenuItemImpl;
import android.util.AttributeSet;
import android.view.View;

import com.afollestad.appthemeengine.ATE;
import com.afollestad.appthemeengine.ATEActivity;
import com.afollestad.appthemeengine.Config;
import com.afollestad.appthemeengine.util.TintHelper;
import com.afollestad.appthemeengine.viewprocessors.ViewProcessor;

import java.lang.reflect.Field;

/**
 * @author Aidan Follestad (afollestad)
 */
class ATEActionMenuItemView extends ActionMenuItemView implements ViewInterface {

    public ATEActionMenuItemView(Context context) {
        super(context);
        init(context, null);
    }

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

    public ATEActionMenuItemView(Context context, AttributeSet attrs, @Nullable ATEActivity keyContext) {
        super(context, attrs);
        init(context, keyContext);
    }

    private String mKey;
    private int mTintColor;
    private Drawable mIcon;
    private boolean mCheckedActionView;

    private void init(Context context, @Nullable ATEActivity keyContext) {
        if (keyContext == null && context instanceof ATEActivity)
            keyContext = (ATEActivity) context;
        mKey = null;
        if (keyContext != null)
            mKey = keyContext.getATEKey();

        if (mIcon != null)
            setIcon(mIcon); // invalidates initial icon tint
        else invalidateTintColor();

        ATE.themeView(context, this, mKey);
        setTextColor(mTintColor); // sets menu item text color
    }

    private void invalidateTintColor() {
        // TODO get a reference to toolbar instead of null here?
        final int mToolbarColor = Config.toolbarColor(getContext(), mKey, null);
        mTintColor = Config.getToolbarTitleColor(getContext(), null, mKey, mToolbarColor);
    }

    @Override
    public void setIcon(Drawable icon) {
        invalidateTintColor();
        mIcon = TintHelper.createTintedDrawable(icon, mTintColor);
        super.setIcon(mIcon);
        invalidateActionView();
    }

    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        invalidateActionView();
    }

    @SuppressWarnings("unchecked")
    private void invalidateActionView() {
        if (mCheckedActionView) return;
        mCheckedActionView = true;
        View actionView = getActionView();
        if (actionView != null) {
            ViewProcessor processor = ATE.getViewProcessor(actionView.getClass());
            if (processor != null)
                processor.process(getContext(), mKey, actionView, null);
        }
    }

    @Nullable
    private View getActionView() {
        try {
            final Field itemData = getClass().getSuperclass().getDeclaredField("mItemData");
            itemData.setAccessible(true);
            final MenuItemImpl menuImpl = (MenuItemImpl) itemData.get(this);
            if (menuImpl == null) return null;
            return menuImpl.getActionView();
        } catch (Throwable t) {
            throw new RuntimeException("Failed to get ActionView from an ActionMenuItemView: " + t.getLocalizedMessage(), t);
        }
    }

    @Override
    public boolean setsStatusBarColor() {
        return false;
    }

    @Override
    public boolean setsToolbarColor() {
        return false;
    }
}


text:
import re

import pytest

from waterbutler.providers.github.path import GitHubPath

class TestGitHubPath:

    def test_id_accessors(self):
        gh_path = GitHubPath('/foo', _ids=[('master', None), ('master', 'abcea54as123')])

        assert gh_path.branch_ref == 'master'
        assert gh_path.file_sha == 'abcea54as123'

    def test_child_inherits_branch(self):
        gh_parent = GitHubPath('/foo/', _ids=[('master', None), ('master', 'abcea54as123')])
        gh_child = gh_parent.child('foo')

        assert gh_child.branch_ref == 'master'
        assert gh_child.file_sha is None

    def test_child_given_explicit_branch(self):
        gh_parent = GitHubPath('/foo/', _ids=[('master', None), ('master', 'abcea54as123')])
        gh_child = gh_parent.child('foo', _id=('develop', '413006763'))

        assert gh_child.branch_ref == 'develop'
        assert gh_child.file_sha == '413006763'


text:
/*
function menutoggle(ulid) {
	ul = document.getElementById(ulid)
	x = ul.style.display;
	if(x=='none') ul.style.display='block' else ul.style.display='none'
}
*/
ban = document.getElementById("aplicaciones")
lis = ban.getElementsByTagName('li')
var uls=new Array();
for(i in lis) {
	li = lis[i]
	liid = li.id
	ulid="list-"+liid.substr(5)
	ul = document.getElementById(ulid)
	if(ul) {
		ul.style.display = 'none'
		li.setAttribute('onclick',"menutoggle('"+ulid+"')")
		li.setAttribute('onmouseover',"this.style.cursor='pointer'")
		uls.push(ul)
	}
}

function menutoggle(ulid) {
	for(i in uls) {
		ul=uls[i]
		if(ul.id==ulid) {
			if(ul.style.display=='block')
				ul.style.display='none'
			else
				ul.style.display='block'
		}
		else
			ul.style.display='none'
	}
}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

$lang['email_must_be_array'] = 'Passed an array, the email validation method must be.  Yes, hmmm.';
$lang['email_invalid_address'] = 'Invalid email address: %s';
$lang['email_attachment_missing'] = 'To locate the following email attachment unable.  : %s';
$lang['email_attachment_unreadable'] = 'To locate the following email attachment unable.  Yes, hmmm.: %s';
$lang['email_no_from'] = 'Send mail with no "From"  Header, I cannot.  Yeesssssss.';
$lang['email_no_recipients'] = 'Recipients (To, Cc, or Bcc) must you include ';
$lang['email_send_failure_phpmail'] = 'To send email using PHP mail() unable.  Your server might be configured to send mail using this method not.  Hmmmmmm.';
$lang['email_send_failure_sendmail'] = 'To send email using PHP sendmail unable.  Your server might be configured to send mail using this method not.  Hmmmmmm.';
$lang['email_send_failure_smtp'] = 'To send email using PHP SMTP unable.  Your server might be configured to send mail using this method not.  Hmmmmmm.';
$lang['email_sent'] = 'Been successfully sent using the following protocol, your message has.  Yes, hmmm.: %s';
$lang['email_no_socket'] = 'To open a socket to sendmail unable.  Check settings.  Yes, hmmm.';
$lang['email_no_hostname'] = 'Specify a smtp hostname, you did not.  ';
$lang['email_smtp_error'] = 'Encountered, the following SMTP error was: %s';
$lang['email_no_smtp_unpw'] = 'Error: a SMTP username and password assign you must.';
$lang['email_failed_smtp_login'] = 'To send, AUTH LOGIN command failed. Error: %s';
$lang['email_smtp_auth_un'] = 'Authenticate username, failed it did. Error: %s';
$lang['email_smtp_auth_pw'] = 'Authenticate password, failed it did. Error: %s';
$lang['email_smtp_data_failure'] = 'To send data, unable am I: %s';
$lang['email_exit_status'] = 'Exit status code: %s. Yesss.';

/* End of file email_lang.php */
/* Location: ./application/language/english/email_lang.php */


text:
package com.alibaba.json.bvt.parser;

import java.io.StringReader;

import junit.framework.TestCase;

import org.junit.Assert;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONReader;

public class JSONReaderScannerTest_jsonobject extends TestCase {

    public void test_e() throws Exception {
        JSONReader reader = new JSONReader(new StringReader("{\"type\\t\":'AA'}"));
        JSONObject vo = new JSONObject();
        reader.readObject(vo);
        Assert.assertEquals("AA", vo.get("type\t"));
        reader.close();
    }

    public static class VO {

        private Type type;

        public Type getType() {
            return type;
        }

        public void setType(Type type) {
            this.type = type;
        }

    }

    public static enum Type {
        AA, BB, CC
    }
}


text:
#include "PolySceneEntityInstance.h"
#include "PolyLogger.h"
#include "PolyCoreServices.h"
#include "PolyResourceManager.h"
#include "PolyMaterial.h"
#include "PolySceneLight.h"
#include "PolySceneMesh.h"
#include "PolySceneLabel.h"
#include "PolySceneSound.h"
#include "PolyCamera.h"

using namespace Polycode;

SceneEntityInstanceResourceEntry::SceneEntityInstanceResourceEntry(SceneEntityInstance *instance)  : Resource(Resource::RESOURCE_ENTITY_INSTANCE) {
	this->instance = instance;
}

SceneEntityInstanceResourceEntry::~SceneEntityInstanceResourceEntry() {

}

SceneEntityInstance *SceneEntityInstanceResourceEntry::getInstance() {
	return instance;
}

void SceneEntityInstanceResourceEntry::reloadResource() {
	instance->reloadEntityInstance();
	Resource::reloadResource();
}

SceneEntityInstance *SceneEntityInstance::BlankSceneEntityInstance(Scene *parentScene) {
	return new SceneEntityInstance(parentScene);
}

SceneEntityInstance::SceneEntityInstance(Scene *parentScene, const String& fileName, ResourcePool *loadIntoPool) : Entity(), loadIntoPool(loadIntoPool) {
    createNewLayer("default");
    this->parentScene = parentScene;
	resourceEntry = new SceneEntityInstanceResourceEntry(this);
    topLevelResourcePool = CoreServices::getInstance()->getResourceManager()->getGlobalPool();
	loadFromFile(fileName);
	resourceEntry->setResourceName(fileName);
	resourceEntry->setResourcePath(fileName);
	cloneUsingReload = false;
	ownsChildren = true;
}

SceneEntityInstance::SceneEntityInstance(Scene *parentScene) : Entity() {
    createNewLayer("default");
    this->parentScene = parentScene;
	cloneUsingReload = true;
	ownsChildren = true;
    topLevelResourcePool = CoreServices::getInstance()->getResourceManager()->getGlobalPool();
	resourceEntry = new SceneEntityInstanceResourceEntry(this);
}

SceneEntityInstance::~SceneEntityInstance() {
    for(int i=0; i < layers.size(); i++) {
            delete layers[i];
    }

	CoreServices::getInstance()->getResourceManager()->removeResource(resourceEntry);
	delete resourceEntry;
    for(int i=0; i < resourcePools.size(); i++) {
        CoreServices::getInstance()->getResourceManager()->unsubscibeFromResourcePool(resourcePools[i]);
    }
}

void SceneEntityInstance::reloadEntityInstance() {
	loadFromFile(fileName);
}

SceneEntityInstanceResourceEntry *SceneEntityInstance::getResourceEntry() {
	return resourceEntry;
}

Entity *SceneEntityInstance::Clone(bool deepClone, bool ignoreEditorOnly) const {
	SceneEntityInstance *newEntity;
	if(cloneUsingReload) {
		newEntity = new SceneEntityInstance(parentScene, fileName, loadIntoPool);
	} else {
		newEntity = new SceneEntityInstance(parentScene);
	}
	applyClone(newEntity, deepClone, ignoreEditorOnly);
	return newEntity;
}

void SceneEntityInstance::applyClone(Entity *clone, bool deepClone, bool ignoreEditorOnly) const {
	if(cloneUsingReload) {
		Entity::applyClone(clone, false, ignoreEditorOnly);
	} else {
		Entity::applyClone(clone, deepClone, ignoreEditorOnly);
		SceneEntityInstance *_clone = (SceneEntityInstance*) clone;
		_clone->fileName = fileName;
	}
}

void SceneEntityInstance::linkResourcePool(ResourcePool *pool) {
    for(int i=0; i < resourcePools.size(); i++) {
        if(resourcePools[i] == pool) {
            return;
        }
    }
    pool->setFallbackPool(topLevelResourcePool);
    topLevelResourcePool = pool;
    CoreServices::getInstance()->getResourceManager()->subscribeToResourcePool(pool);
    resourcePools.push_back(pool);
}

unsigned int SceneEntityInstance::getNumLinkedResourePools() {
    return resourcePools.size();
}

ResourcePool *SceneEntityInstance::getLinkedResourcePoolAtIndex(unsigned int index) {
    return resourcePools[index];
}

void SceneEntityInstance::rebuildResourceLinks() {
    for(int i=0; i < resourcePools.size(); i++) {
        if(i == 0) {
            resourcePools[i]->setFallbackPool(CoreServices::getInstance()->getResourceManager()->getGlobalPool());
        } else {
            resourcePools[i]->setFallbackPool(resourcePools[i-1]);
        }
    }

    if(resourcePools.size() > 0) {
        topLevelResourcePool = resourcePools[resourcePools.size()-1];
    } else {
        topLevelResourcePool = CoreServices::getInstance()->getResourceManager()->getGlobalPool();
    }
}

void SceneEntityInstance::unlinkResourcePool(ResourcePool *pool) {
    for(int i=0; i < resourcePools.size(); i++) {
        if(resourcePools[i] == pool) {
            resourcePools.erase(resourcePools.begin() + i);
            rebuildResourceLinks();
            CoreServices::getInstance()->getResourceManager()->unsubscibeFromResourcePool(pool);
            return;
        }
    }
}

void SceneEntityInstance::applySceneMesh(ObjectEntry *entry, SceneMesh *sceneMesh) {
	if(!entry) {
		return;
    }

    if((*entry)["sendBoneMatricesToMaterial"]) {
        sceneMesh->sendBoneMatricesToMaterial = (*entry)["sendBoneMatricesToMaterial"]->boolVal;
    }

    if((*entry)["alphaTest"]) {
        sceneMesh->alphaTest = (*entry)["alphaTest"]->boolVal;
    }

    if((*entry)["backfaceCulled"]) {
        sceneMesh->backfaceCulled = (*entry)["backfaceCulled"]->boolVal;
    }

    ObjectEntry *materialName =(*entry)["material"];
    if(materialName) {
        sceneMesh->setMaterialByName(materialName->stringVal, topLevelResourcePool);
        if(sceneMesh->getMaterial()) {
            ObjectEntry *optionsEntry =(*entry)["shader_options"];
            if(optionsEntry) {
                for(int i=0; i < optionsEntry->length; i++) {
                    ObjectEntry *shaderEntry =(*optionsEntry)[i];
                    if(shaderEntry) {

                        // parse in texture bindings
                        ObjectEntry *texturesEntry =(*shaderEntry)["textures"];
                        if(texturesEntry) {
                            for(int j=0; j < texturesEntry->length; j++) {
                                ObjectEntry *textureEntry =(*texturesEntry)[j];
                                if(textureEntry) {
                                    ObjectEntry *nameEntry = (*textureEntry)["name"];
                                    if(nameEntry && textureEntry->stringVal != "") {

                                        if(textureEntry->name == "cubemap") {
                                            Cubemap *cubemap;

                                            cubemap = (Cubemap*)topLevelResourcePool->getResource(Resource::RESOURCE_CUBEMAP, textureEntry->stringVal);

                                                                                if(cubemap) {
                                                sceneMesh->getLocalShaderOptions()->addCubemap(nameEntry->stringVal, cubemap);
                                            }
                                        } else {
                                            sceneMesh->getLocalShaderOptions()->addTexture(nameEntry->stringVal, CoreServices::getInstance()->getMaterialManager()->createTextureFromFile(textureEntry->stringVal, Services()->getMaterialManager()->clampDefault, Services()->getMaterialManager()->mipmapsDefault, loadIntoPool));
                                        }
                                    }
                                }
                            }
                        }

                        ObjectEntry *paramsEntry =(*shaderEntry)["params"];
                        if(paramsEntry) {
                            for(int j=0; j < paramsEntry->length; j++) {
                                ObjectEntry *paramEntry =(*paramsEntry)[j];
                                if(paramEntry) {
                                    ObjectEntry *nameEntry = (*paramEntry)["name"];
                                    ObjectEntry *valueEntry = (*paramEntry)["value"];
                                    if(nameEntry && valueEntry) {
                                        Shader *materialShader = sceneMesh->getMaterial()->getShader(i);
                                        if(materialShader) {
                                            int type = materialShader->getExpectedParamType(nameEntry->stringVal);
                                            LocalShaderParam *param = sceneMesh->getLocalShaderOptions()->addParam(type, nameEntry->stringVal);
                                            if(param) {
                                                param->setParamValueFromString(type, valueEntry->stringVal);
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
        }
    }

}

void SceneEntityInstance::parseObjectIntoCurve(ObjectEntry *entry, BezierCurve *curve) {
	curve->clearControlPoints();
	ObjectEntry *controlPoints =(*entry)["controlPoints"];
	if(controlPoints) {
		for(int i=0; i < controlPoints->length; i++) {
			ObjectEntry *controlPoint = ((*controlPoints))[i];
			if(controlPoint) {
				Vector3 vpt1;
				Vector3 vpt2;
				Vector3 vpt3;

				ObjectEntry *pt1 = ((*controlPoint))["pt1"];
				if(pt1) {
					vpt1.x = ((*pt1))["x"]->NumberVal;
					vpt1.y = ((*pt1))["y"]->NumberVal;
					vpt1.z = ((*pt1))["z"]->NumberVal;
				}

				ObjectEntry *pt2 = ((*controlPoint))["pt2"];
				if(pt2) {
					vpt2.x = ((*pt2))["x"]->NumberVal;
					vpt2.y = ((*pt2))["y"]->NumberVal;
					vpt2.z = ((*pt2))["z"]->NumberVal;

				}

				ObjectEntry *pt3 = ((*controlPoint))["pt3"];
				if(pt3) {
					vpt3.x = ((*pt3))["x"]->NumberVal;
					vpt3.y = ((*pt3))["y"]->NumberVal;
					vpt3.z = ((*pt3))["z"]->NumberVal;
				}

				curve->addControlPoint(vpt1.x, vpt1.y, vpt1.z, vpt2.x, vpt2.y, vpt2.z, vpt3.x, vpt3.y, vpt3.z);
			}
		}
	}

}

Entity *SceneEntityInstance::loadObjectEntryIntoEntity(ObjectEntry *entry, Entity *targetEntity, int entityFileVersion) {

	Entity *entity = NULL;

	ObjectEntry *entityType = (*entry)["type"];
	if(entityType) {
        if(entityType->stringVal == "SceneEntityInstance") {
            ObjectEntry *instanceEntry = (*entry)["SceneEntityInstance"];
            String filePath = (*instanceEntry)["filePath"]->stringVal;
            SceneEntityInstance *instance = new SceneEntityInstance(parentScene, filePath, loadIntoPool);
            entity = instance;
         } else if(entityType->stringVal == "SceneCurve") {
			ObjectEntry *curveEntry = (*entry)["SceneCurve"];

             SceneCurve *curve = new SceneCurve();

            if(curveEntry) {
                curve->renderCurve = (*curveEntry)["render"]->boolVal;
                curve->curveResolution = (*curveEntry)["resolution"]->intVal;
                parseObjectIntoCurve((*curveEntry)["curve"], curve->getCurve());
            }

             entity = curve;

         } else if(entityType->stringVal == "SceneSprite") {

			ObjectEntry *spriteEntry = (*entry)["SceneSprite"];
			String spriteSetName = (*spriteEntry)["sprite_set"]->stringVal;

             SpriteSet *spriteSet = (SpriteSet*)CoreServices::getInstance()->getResourceManager()->getResourcePoolByName(spriteSetName);

             if(spriteSet) {
                 SceneSprite *sprite = new SceneSprite(spriteSet);

                 String spriteName = (*spriteEntry)["sprite"]->stringVal;
                 sprite->setSpriteByName(spriteName);

                 String stateName = (*spriteEntry)["state"]->stringVal;

                 if(sprite->getCurrentSprite()) {
                     SpriteState *state = sprite->getCurrentSprite()->getStateByName(stateName);
                     if(state) {
                         sprite->setSpriteState(state, 0, false);
                     }

                     ObjectEntry *randomFrameEntry = (*spriteEntry)["random_frame"];
                     if(randomFrameEntry) {
                        sprite->setStartOnRandomFrame(randomFrameEntry->boolVal);
                     }

                 }

                 entity = sprite;
                 applySceneMesh((*entry)["SceneMesh"], sprite);
             }

        } else 	if(entityType->stringVal == "SceneLabel") {
			ObjectEntry *labelEntry = (*entry)["SceneLabel"];

			String text = (*labelEntry)["text"]->stringVal;
			String font = (*labelEntry)["font"]->stringVal;
			int size = (*labelEntry)["size"]->intVal;
            Number actualHeight = (*labelEntry)["actualHeight"]->NumberVal;
			int aaMode = (*labelEntry)["aaMode"]->intVal;

			SceneLabel *label = new SceneLabel(text, size, font, aaMode, actualHeight);
            label->setAnchorPoint(0.0, 0.0, 0.0);
            label->snapToPixels = false;
            label->positionAtBaseline = false;
            applySceneMesh((*entry)["SceneMesh"], label);
            if(label->getLocalShaderOptions()) {
                label->getLocalShaderOptions()->clearTexture("diffuse");
                label->getLocalShaderOptions()->addTexture("diffuse", label->getTexture());
            }

			entity = label;
        } else if(entityType->stringVal == "SceneParticleEmitter") {

			ObjectEntry *emitterEntry = (*entry)["SceneParticleEmitter"];
            SceneParticleEmitter *emitter = new SceneParticleEmitter(1, 1, 1);

            emitter->setParticleType((*emitterEntry)["type"]->intVal);
            emitter->setParticleSpeed((*emitterEntry)["speed"]->NumberVal);
            emitter->setParticleCount((*emitterEntry)["count"]->intVal);
            emitter->setParticleLifetime((*emitterEntry)["lifetime"]->NumberVal);
            emitter->setParticleSize((*emitterEntry)["size"]->NumberVal);
            emitter->setParticlesInWorldSpace((*emitterEntry)["world"]->boolVal);
            emitter->setLoopParticles((*emitterEntry)["loop"]->boolVal);

            emitter->setParticleRotationSpeed(Vector3((*emitterEntry)["rX"]->NumberVal, (*emitterEntry)["rY"]->NumberVal, (*emitterEntry)["rZ"]->NumberVal));
            emitter->setGravity(Vector3((*emitterEntry)["gX"]->NumberVal, (*emitterEntry)["gY"]->NumberVal, (*emitterEntry)["gZ"]->NumberVal));
            emitter->setParticleDirection(Vector3((*emitterEntry)["dirX"]->NumberVal, (*emitterEntry)["dirY"]->NumberVal, (*emitterEntry)["dirZ"]->NumberVal));
            emitter->setEmitterSize(Vector3((*emitterEntry)["eX"]->NumberVal, (*emitterEntry)["eY"]->NumberVal, (*emitterEntry)["eZ"]->NumberVal));
            emitter->setDirectionDeviation(Vector3((*emitterEntry)["devX"]->NumberVal, (*emitterEntry)["devY"]->NumberVal, (*emitterEntry)["devZ"]->NumberVal));

            emitter->setPerlinEnabled((*emitterEntry)["perlin"]->boolVal);
            if(emitter->getPerlinEnabled()) {
                emitter->setPerlinValue(Vector3((*emitterEntry)["pX"]->NumberVal, (*emitterEntry)["pY"]->NumberVal, (*emitterEntry)["pZ"]->NumberVal));
            }

            emitter->useColorCurves = (*emitterEntry)["useColorCurves"]->boolVal;
            emitter->useScaleCurve = (*emitterEntry)["useScaleCurve"]->boolVal;

            parseObjectIntoCurve((*emitterEntry)["colorCurveR"], &emitter->colorCurveR);
            parseObjectIntoCurve((*emitterEntry)["colorCurveG"], &emitter->colorCurveG);
            parseObjectIntoCurve((*emitterEntry)["colorCurveB"], &emitter->colorCurveB);
            parseObjectIntoCurve((*emitterEntry)["colorCurveA"], &emitter->colorCurveA);
            parseObjectIntoCurve((*emitterEntry)["scaleCurve"], &emitter->scaleCurve);

            applySceneMesh((*entry)["SceneMesh"], emitter);
			entity = emitter;

		} else if(entityType->stringVal == "SceneLight") {

			ObjectEntry *lightEntry = (*entry)["SceneLight"];
            if(lightEntry) {
                int lightType = (*lightEntry)["type"]->intVal;
                SceneLight *newLight  = new SceneLight(lightType, parentScene, 0);

                newLight->setIntensity((*lightEntry)["intensity"]->NumberVal);

                ObjectEntry *importanceEntry = (*lightEntry)["importance"];
                if(importanceEntry) {
                    newLight->setLightImportance(importanceEntry->intVal);
                }

                newLight->lightColor.setColor((*lightEntry)["cR"]->NumberVal, (*lightEntry)["cG"]->NumberVal, (*lightEntry)["cB"]->NumberVal, (*lightEntry)["cA"]->NumberVal);
                newLight->specularLightColor.setColor((*lightEntry)["scR"]->NumberVal, (*lightEntry)["scG"]->NumberVal, (*lightEntry)["scB"]->NumberVal, (*lightEntry)["scA"]->NumberVal);

                newLight->setAttenuation((*lightEntry)["cAtt"]->NumberVal, (*lightEntry)["lAtt"]->NumberVal, (*lightEntry)["qAtt"]->NumberVal);

                if(newLight->getType() == SceneLight::SPOT_LIGHT) {
                    newLight->setSpotlightProperties((*lightEntry)["spotCutoff"]->NumberVal, (*lightEntry)["spotExponent"]->NumberVal);

                    if((*lightEntry)["shadows"]->boolVal) {
                        newLight->enableShadows(true, (*lightEntry)["shadowmapRes"]->intVal);
                        newLight->setShadowMapFOV((*lightEntry)["shadowmapFOV"]->NumberVal);
                    }
                }

                parentScene->addLight(newLight);
                entity = newLight;
            }

        } else if(entityType->stringVal == "ScenePrimitive") {
			ObjectEntry *scenePrimitiveEntry = (*entry)["ScenePrimitive"];
			int pType = (*scenePrimitiveEntry)["type"]->intVal;
			Number p1 = (*scenePrimitiveEntry)["p1"]->NumberVal;
			Number p2 = (*scenePrimitiveEntry)["p2"]->NumberVal;
			Number p3 = (*scenePrimitiveEntry)["p3"]->NumberVal;
			Number p4 = (*scenePrimitiveEntry)["p4"]->NumberVal;
			Number p5 = (*scenePrimitiveEntry)["p5"]->NumberVal;

			ScenePrimitive *primitive = new ScenePrimitive(pType, p1, p2, p3, p4, p5);
			entity = primitive;
            applySceneMesh((*entry)["SceneMesh"], primitive);
		} else if(entityType->stringVal == "SceneMesh") {
			ObjectEntry *meshEntry = (*entry)["SceneMesh"];
            if(meshEntry) {
                ObjectEntry *fileName = (*meshEntry)["file"];
                if(fileName) {
                    SceneMesh *newMesh = new SceneMesh(fileName->stringVal);
                    applySceneMesh(meshEntry, newMesh);
                    newMesh->cacheToVertexBuffer(true);
                    entity = newMesh;
                }
            }
        } else if(entityType->stringVal == "SceneSound") {
			ObjectEntry *soundEntry = (*entry)["SceneSound"];

			String filePath = (*soundEntry)["filePath"]->stringVal;
			Number refDistance = (*soundEntry)["refDistance"]->NumberVal;
			Number maxDistance = (*soundEntry)["maxDistance"]->NumberVal;
			Number volume = (*soundEntry)["volume"]->NumberVal;
			Number pitch = (*soundEntry)["pitch"]->NumberVal;

			SceneSound *sound = new SceneSound(filePath, refDistance, maxDistance);
			sound->getSound()->setVolume(volume);
			sound->getSound()->setPitch(pitch);

            if((*soundEntry)["loopOnLoad"]) {
                bool loopOnLoad = (*soundEntry)["loopOnLoad"]->boolVal;
                sound->setLoopOnLoad(loopOnLoad);
                if(loopOnLoad) {
                    sound->getSound()->Play(true);
                }
            }

			entity = sound;
        } else if(entityType->stringVal == "Camera") {
			ObjectEntry *cameraEntry = (*entry)["Camera"];

			Camera *camera = new Camera(parentScene);

            camera->setExposureLevel((*cameraEntry)["exposure"]->NumberVal);
            camera->setClippingPlanes((*cameraEntry)["nearClip"]->NumberVal, (*cameraEntry)["farClip"]->NumberVal);
            camera->setOrthoMode((*cameraEntry)["ortho"]->boolVal);

            if(camera->getOrthoMode()) {
				camera->setOrthoSizeMode((*cameraEntry)["sizeMode"]->intVal);
                camera->setOrthoSize((*cameraEntry)["orthoWidth"]->NumberVal, (*cameraEntry)["orthoHeight"]->NumberVal);
            } else {
                camera->setFOV((*cameraEntry)["fov"]->NumberVal);
            }

			entity = camera;
		}

	}

	if(!entity) {
		if(targetEntity) {
			entity = targetEntity;
		} else {
			entity = new Entity();
		}
	}

	entity->ownsChildren = true;

    Vector3 bBox;
	entry->readNumber("bbX", &bBox.x);
	entry->readNumber("bbY", &bBox.y);
	entry->readNumber("bbZ", &bBox.z);
    entity->setLocalBoundingBox(bBox);

	entity->color.r = (*entry)["cR"]->NumberVal;
	entity->color.g = (*entry)["cG"]->NumberVal;
	entity->color.b = (*entry)["cB"]->NumberVal;
	entity->color.a = (*entry)["cA"]->NumberVal;

	if(!targetEntity) {
		entity->blendingMode = (*entry)["blendMode"]->intVal;

        entity->setScale((*entry)["sX"]->NumberVal, (*entry)["sY"]->NumberVal, (*entry)["sZ"]->NumberVal);
        entity->setPosition((*entry)["pX"]->NumberVal, (*entry)["pY"]->NumberVal, (*entry)["pZ"]->NumberVal);

        if(entityFileVersion > 1) {
            entity->setRotationQuat((*entry)["rW"]->NumberVal, (*entry)["rX"]->NumberVal, (*entry)["rY"]->NumberVal, (*entry)["rZ"]->NumberVal);
        } else {
            entity->setRotationEuler(Vector3((*entry)["rX"]->NumberVal, (*entry)["rY"]->NumberVal, (*entry)["rZ"]->NumberVal));
        }
	}

	if((*entry)["id"]->stringVal != "") {
		entity->id = (*entry)["id"]->stringVal;
	}

    if((*entry)["layerID"]) {
        entity->layerID = (unsigned int)((*entry)["layerID"]->intVal);
    }

	String tagString = (*entry)["tags"]->stringVal;

	if(tagString != "") {
		std::vector<String> tags = tagString.split(",");
		for(int i=0; i < tags.size(); i++) {
			entity->addTag(tags[i]);
		}
	}

	ObjectEntry *props = (*entry)["props"];
	if(props) {
		for(int i=0; i < props->length; i++) {
			ObjectEntry *prop = ((*props))[i];
			if(prop) {
				entity->setEntityProp((*prop)["name"]->stringVal, (*prop)["value"]->stringVal);
			}
		}
	}

	ObjectEntry *children = (*entry)["children"];

	if(children) {
		for(int i=0; i < children->length; i++) {
			ObjectEntry *childEntry = ((*children))[i];
			ScreenEntity *childEntity = loadObjectEntryIntoEntity(childEntry, NULL, entityFileVersion);
			entity->addChild(childEntity);
		}
	}

	return entity;
}

String SceneEntityInstance::getFileName() const {
	return fileName;
}

ResourcePool *SceneEntityInstance::getTopLevelResourcePool() {
    return topLevelResourcePool;
}

void SceneEntityInstance::clearInstance() {

    resourcePools.clear();
    topLevelResourcePool = CoreServices::getInstance()->getResourceManager()->getGlobalPool();
	for(int i=0; i < children.size(); i++) {
		children[i]->setOwnsChildrenRecursive(true);
		delete children[i];
	}
    children.clear();
}

bool SceneEntityInstance::hasLayerID(unsigned char layerID) const {
    for(int i=0; i < layers.size(); i++) {
        if(layers[i]->layerID == layerID) {
            return true;
        }
    }
    return false;
}

SceneEntityInstanceLayer::SceneEntityInstanceLayer(SceneEntityInstance *instance, String name) {
    this->instance = instance;
    this->name = name;
    visible = true;
}

void SceneEntityInstanceLayer::setLayerVisibility(bool val) {
    visible = val;

    std::vector<Entity*> entities = instance->getEntitiesByLayerID(layerID, true);
    for(int i=0; i < entities.size(); i++) {
        entities[i]->visible = val;
    }
}

SceneEntityInstanceLayer *SceneEntityInstance::createNewLayer(String name) {
    SceneEntityInstanceLayer *newLayer = new SceneEntityInstanceLayer(this, name);

    unsigned char layerID;
    for(layerID=0; layerID <= 255; layerID++) {
        if(!hasLayerID(layerID)) {
            break;
        }
    }
    newLayer->layerID = layerID;
    layers.push_back(newLayer);
    return newLayer;
}

unsigned int SceneEntityInstance::getNumLayers() const {
    return layers.size();
}

void SceneEntityInstance::removeLayer(SceneEntityInstanceLayer *layer) {
    for(int i=0; i < layers.size(); i++) {
        if(layers[i] == layer) {
            delete layers[i];
            layers.erase(layers.begin()+i);
        }
    }
}

SceneEntityInstanceLayer *SceneEntityInstance::getLayerAtIndex(unsigned int index) const {
    if(index < layers.size()) {
        return layers[index];
    } else {
        return NULL;
    }
}

bool SceneEntityInstance::loadFromFile(const String& fileName) {

	clearInstance();

	resourceEntry->resourceFileTime = OSBasics::getFileTime(fileName);

	this->ownsChildren = true;
	this->fileName = fileName;
	Object loadObject;
	if(!loadObject.loadFromBinary(fileName)) {
        if(!loadObject.loadFromXML(fileName)) {
            Logger::log("Error loading entity instance.\n");
        }
	}

    int entityFileVersion = 1;

    ObjectEntry *versionObject = loadObject.root["version"];
    if(versionObject) {
        entityFileVersion = versionObject->intVal;
    }

	ObjectEntry *settings = loadObject.root["settings"];
    if(settings) {

        ObjectEntry *layersEntry = (*settings)["layers"];
        if(layersEntry) {
            for(int i=0; i < layersEntry->length; i++) {
                ObjectEntry *layer = (*layersEntry)[i];
                if(layer) {
                    ObjectEntry *name = (*layer)["name"];
                    ObjectEntry *layerID = (*layer)["id"];
                    ObjectEntry *visible = (*layer)["visible"];
                    if(name && layerID && visible) {
                        SceneEntityInstanceLayer *newLayer = new SceneEntityInstanceLayer(this, name->stringVal);
                        newLayer->visible = visible->boolVal;
                        newLayer->layerID = (unsigned char) layerID->intVal;
                        layers.push_back(newLayer);
                    }
                }
            }
        }
        ObjectEntry *resPools = (*settings)["linkedResourcePools"];
        if(resPools) {
            for(int i=0; i < resPools->length; i++) {
                ObjectEntry *resPool = (*resPools)[i];
                if(resPool) {
                    ObjectEntry *path = (*resPool)["path"];
                    if(path) {
                        ResourcePool *newPool = CoreServices::getInstance()->getResourceManager()->getResourcePoolByName(path->stringVal);

                        if(!newPool) {

                            String extension = path->stringVal.substr(path->stringVal.find_last_of(".")+1, path->stringVal.length());

                            if(extension == "mat") {
                                newPool = new ResourcePool(path->stringVal,  CoreServices::getInstance()->getResourceManager()->getGlobalPool());
                                newPool->deleteOnUnsubscribe = true;
                                CoreServices::getInstance()->getMaterialManager()->loadMaterialLibraryIntoPool(newPool, path->stringVal);
                            } else if( extension == "sprites") {
                                SpriteSet *spriteSet = new SpriteSet(path->stringVal,  CoreServices::getInstance()->getResourceManager()->getGlobalPool());
                                spriteSet->deleteOnUnsubscribe = true;
                                newPool = spriteSet;

                            }

                            CoreServices::getInstance()->getResourceManager()->addResourcePool(newPool);
                        }

                        linkResourcePool(newPool);
                    }
                }
            }
        }
    }

	ObjectEntry *root = loadObject.root["root"];
	if(root) {
		loadObjectEntryIntoEntity(root, this, entityFileVersion);
	}

    for(int i=0; i < layers.size(); i++ ) {
        SceneEntityInstanceLayer *layer = layers[i];
        if(layer->layerID != 0) {
            if(layer->visible == false) {
                std::vector<Entity*> layerEntities = getEntitiesByLayerID(layer->layerID, true);
                for(int j=0; j < layerEntities.size(); j++) {
                    layerEntities[j]->visible = false;
                }
            }
        }
    }

	return true;
}