text:
"""Capability unit test for matter_endpoints_accessor module."""
from unittest import mock

from absl.testing import parameterized
from gazoo_device import errors
from gazoo_device.capabilities import matter_endpoints_accessor_pw_rpc
from gazoo_device.capabilities import matter_endpoints_and_clusters
from gazoo_device.capabilities.matter_endpoints import on_off_light
from gazoo_device.capabilities.matter_endpoints import unsupported_endpoint
from gazoo_device.capabilities.matter_endpoints.interfaces import endpoint_base
from gazoo_device.protos import attributes_service_pb2
from gazoo_device.protos import descriptor_service_pb2
from gazoo_device.switchboard import switchboard
from gazoo_device.tests.unit_tests.utils import fake_device_test_case

_FAKE_ENDPOINT_ID = 0
_FAKE_DEVICE_TYPE_ID = 10
_FAKE_CLUSTER_ID = 0
_FAKE_RPC_TIMEOUT_S = 10
_FAKE_DEVICE_NAME = "fake-device-name"
_FAKE_ENDPOINT_NAME = "fake_endpoint_name"
_FAKE_CLUSTER_NAME = "fake_cluster_name"
_FAKE_ENDPOINT_IDS = [_FAKE_ENDPOINT_ID]
_FAKE_ENDPOINT_CLS = mock.Mock(DEVICE_TYPE_ID=_FAKE_DEVICE_TYPE_ID)
_FAKE_ENDPOINT_INST = mock.Mock(spec=endpoint_base.EndpointBase)
_FAKE_CLUSTER_CLS = mock.Mock(CLUSTER_ID=_FAKE_CLUSTER_ID)
_FAKE_ENDPOINT_ID_TO_CLS = {_FAKE_ENDPOINT_ID: _FAKE_ENDPOINT_CLS}
_FAKE_ENDPOINT_CLS_TO_ID = {_FAKE_ENDPOINT_CLS: _FAKE_ENDPOINT_ID}
_FAKE_ENDPOINT_ID_TO_CLUSTERS = {_FAKE_ENDPOINT_ID: [_FAKE_CLUSTER_CLS]}
_FAKE_ENDPOINT_ID_TO_DEVICE_TYPE_ID = {_FAKE_ENDPOINT_ID: _FAKE_DEVICE_TYPE_ID}
_FAKE_NOT_IMPLEMENTED_CLUSTER_ID = 1
_FAKE_ATTRIBUTE_ID = 0
_FAKE_ATTRIBUTE_TYPE = attributes_service_pb2.AttributeType.ZCL_BOOLEAN_ATTRIBUTE_TYPE

class MatterEndpointsAccessorPwPpcTest(
    fake_device_test_case.FakeDeviceTestCase):
  """Unit test for MatterEndpointsAccessorPwRpc."""

  def setUp(self):
    super().setUp()
    self.fake_switchboard_call = mock.Mock(
        spec=switchboard.SwitchboardDefault.call)
    self.uut = matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc(
        device_name=_FAKE_DEVICE_NAME,
        switchboard_call=self.fake_switchboard_call,
        rpc_timeout_s=_FAKE_RPC_TIMEOUT_S)
    _FAKE_ENDPOINT_CLS.return_value = _FAKE_ENDPOINT_INST

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "get_supported_clusters",
      return_value={
          _FAKE_CLUSTER_CLS,
      })
  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "get_endpoint_class_and_device_type_id",
      side_effect=[(_FAKE_ENDPOINT_CLS, _FAKE_DEVICE_TYPE_ID)])
  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "get_supported_endpoint_ids",
      return_value=_FAKE_ENDPOINT_IDS)
  def test_fetch_endpoints_and_clusters_on_success(
      self, mock_get_suppored_endpoint_ids, mock_get_endpoint_cls,
      mock_get_supported_clusters):
    """Verifies descriptor RPC service is triggered successfully."""
    self.uut.reset()

    self.uut._fetch_endpoints_and_clusters()

    self.assertEqual(
        _FAKE_DEVICE_TYPE_ID,
        self.uut.endpoint_id_to_class[_FAKE_ENDPOINT_ID].DEVICE_TYPE_ID)
    self.assertIn(_FAKE_ENDPOINT_ID, self.uut.endpoint_class_to_id.values())
    self.assertEqual(
        _FAKE_CLUSTER_ID,
        self.uut.endpoint_id_to_clusters[_FAKE_ENDPOINT_ID].pop().CLUSTER_ID)
    mock_get_suppored_endpoint_ids.assert_called_once()
    mock_get_endpoint_cls.assert_called_once()
    mock_get_supported_clusters.assert_called_once()

  def test_get_supported_endpoint_ids(self):
    """Verifies get_supported_endpoint_ids method on success."""
    fake_endpoint = descriptor_service_pb2.Endpoint(endpoint=_FAKE_ENDPOINT_ID)
    fake_supported_endpoints = [fake_endpoint.SerializeToString()]
    self.fake_switchboard_call.return_value = fake_supported_endpoints

    self.assertEqual([_FAKE_ENDPOINT_ID], self.uut.get_supported_endpoint_ids())

  @mock.patch.object(
      matter_endpoints_and_clusters.MATTER_DEVICE_TYPE_ID_TO_CLASS,
      "get",
      return_value=_FAKE_ENDPOINT_CLS)
  def test_get_endpoint_class_and_device_type_id(self, mock_mapping):
    """Verifies get_endpoint_class_and_device_type_id on success."""
    fake_device_type = descriptor_service_pb2.DeviceType(
        device_type=_FAKE_DEVICE_TYPE_ID)
    fake_device_types = [fake_device_type.SerializeToString()]
    self.fake_switchboard_call.return_value = fake_device_types

    self.assertEqual(
        (_FAKE_ENDPOINT_CLS, _FAKE_DEVICE_TYPE_ID),
        self.uut.get_endpoint_class_and_device_type_id(_FAKE_ENDPOINT_ID))

  def test_reset_method_on_success(self):
    """Verifies reset method on success."""
    self.uut.reset()

    self.assertEqual({}, self.uut._endpoint_id_to_class)
    self.assertEqual({}, self.uut._endpoint_class_to_id)
    self.assertEqual({}, self.uut._endpoint_id_to_clusters)

  @parameterized.parameters(
      dict(cluster_id=_FAKE_CLUSTER_ID, cluster_class=_FAKE_CLUSTER_CLS),
      dict(cluster_id=_FAKE_NOT_IMPLEMENTED_CLUSTER_ID, cluster_class=None))
  @mock.patch.object(matter_endpoints_and_clusters.CLUSTER_ID_TO_CLASS_PW_RPC,
                     "get")
  def test_get_supported_clusters_on_success(self, mock_get, cluster_id,
                                             cluster_class):
    """Verifies get_supported_clusters method on success."""
    mock_get.return_value = cluster_class
    fake_cluster = descriptor_service_pb2.Cluster(cluster_id=cluster_id)
    fake_clusters = [fake_cluster.SerializeToString()]
    self.fake_switchboard_call.return_value = fake_clusters

    expected_cluster_classes = (
        set() if cluster_class is None else {
            cluster_class,
        })
    self.assertEqual(
        expected_cluster_classes,
        self.uut.get_supported_clusters(endpoint_id=_FAKE_ENDPOINT_ID))

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "_fetch_endpoints_and_clusters")
  def test_get_method_on_success_with_supported_endpoint(self, mock_fetch):
    """Verifies the get endpoint method on success with supported endpoint."""
    self.uut._endpoint_id_to_class = _FAKE_ENDPOINT_ID_TO_CLS
    self.uut._endpoint_id_to_clusters = _FAKE_ENDPOINT_ID_TO_CLUSTERS
    self.uut._endpoint_id_to_device_type_id = _FAKE_ENDPOINT_ID_TO_DEVICE_TYPE_ID
    self.uut._endpoints.clear()

    _FAKE_ENDPOINT_CLS.return_value = _FAKE_ENDPOINT_INST
    self.assertEqual(_FAKE_ENDPOINT_INST, self.uut.get(_FAKE_ENDPOINT_ID))

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "_fetch_endpoints_and_clusters")
  def test_get_method_on_success_with_unsupported_endpoint(self, mock_fetch):
    """Verifies the get endpoint method on success with unsupported endpoint."""
    self.uut._endpoint_id_to_class = {
        _FAKE_ENDPOINT_ID: unsupported_endpoint.UnsupportedEndpoint
    }
    self.uut._endpoint_id_to_clusters = _FAKE_ENDPOINT_ID_TO_CLUSTERS
    self.uut._endpoint_id_to_device_type_id = _FAKE_ENDPOINT_ID_TO_DEVICE_TYPE_ID
    self.uut._endpoints.clear()

    self.assertIsInstance(
        self.uut.get(_FAKE_ENDPOINT_ID),
        unsupported_endpoint.UnsupportedEndpoint)

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "_fetch_endpoints_and_clusters")
  def test_get_method_on_failure_invalid_id(self, mock_fetch):
    """Verifies get endpoint method on failure for invalid endpoint ID."""
    self.uut._endpoint_id_to_class = {}

    with self.assertRaisesRegex(
        errors.DeviceError, f"Endpoint ID {_FAKE_ENDPOINT_ID} on "
        f"{_FAKE_DEVICE_NAME} does not exist"):
      self.uut.get(_FAKE_ENDPOINT_ID)

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "_fetch_endpoints_and_clusters")
  def test_list_endpoints(self, mock_fetch):
    """Verifies the list endpoints method on success."""
    self.uut._endpoint_id_to_class = _FAKE_ENDPOINT_ID_TO_CLS
    self.assertEqual(_FAKE_ENDPOINT_ID_TO_CLS, self.uut.list())

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "get",
      return_value=_FAKE_ENDPOINT_INST)
  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "_fetch_endpoints_and_clusters")
  def test_get_endpoint_instance_by_class_on_success(self, mock_fetch,
                                                     mock_get):
    """Verifies get_endpoint_instance_by_class method on success."""
    self.uut._endpoint_class_to_id = _FAKE_ENDPOINT_CLS_TO_ID

    self.assertEqual(
        _FAKE_ENDPOINT_INST,
        self.uut.get_endpoint_instance_by_class(_FAKE_ENDPOINT_CLS))
    mock_get.assert_called_once()

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "_fetch_endpoints_and_clusters")
  def test_get_endpoint_instance_by_class_on_failure(self, mock_fetch):
    """Verifies get_endpoint_instance_by_class with unsupported endpoint."""
    self.uut._endpoint_class_to_id = {}

    with self.assertRaisesRegex(errors.DeviceError, "is not supported on"):
      self.uut.get_endpoint_instance_by_class(_FAKE_ENDPOINT_CLS)

  @parameterized.parameters(
      dict(supported_endpoint=on_off_light.OnOffLightEndpoint, expected=True),
      dict(supported_endpoint=None, expected=False))
  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc, "list")
  def test_has_endpoints_on_success(self, mock_list, supported_endpoint,
                                    expected):
    """Verifies has_endpoints method on success."""
    mock_list.return_value = {_FAKE_ENDPOINT_ID: supported_endpoint}
    endpoint_name = on_off_light.OnOffLightEndpoint.get_capability_name()

    self.assertEqual(expected, self.uut.has_endpoints([endpoint_name]))

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "_fetch_endpoints_and_clusters")
  def test_has_endpoints_on_failure_invalid_endpoint(self, mock_fetch):
    """Verifies has_endpoints method on failure with invalid endpoint."""
    self.assertFalse(self.uut.has_endpoints([_FAKE_ENDPOINT_NAME]))

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc,
      "get_supported_endpoint_flavors")
  def test_get_supported_endpoints_on_success(
      self, mock_get_supported_endpoint_flavors):
    """Verifies get_supported_endpoints method on success."""
    fake_endpoint = mock.Mock(spec=endpoint_base.EndpointBase)
    fake_endpoint.get_capability_name.return_value = _FAKE_ENDPOINT_NAME
    mock_get_supported_endpoint_flavors.return_value = [fake_endpoint]

    self.assertEqual([_FAKE_ENDPOINT_NAME], self.uut.get_supported_endpoints())

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc, "list")
  def test_get_supported_endpoint_flavors_on_success(self, mock_list):
    """Verifies get_supported_endpoint_flavors method on success."""
    fake_endpoint = mock.Mock(spec=endpoint_base.EndpointBase)
    mock_list.return_value = {_FAKE_ENDPOINT_ID: fake_endpoint}

    self.assertEqual([fake_endpoint], self.uut.get_supported_endpoint_flavors())

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc, "get")
  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc, "list")
  def test_get_supported_endpoints_and_clusters(self, mock_list, mock_get):
    """Verifies get_supported_endpoints_and_clusters method on success."""
    mock_list.return_value = [_FAKE_ENDPOINT_ID]
    mock_get.return_value.get_supported_clusters.return_value = [
        _FAKE_CLUSTER_NAME
    ]

    self.assertEqual({_FAKE_ENDPOINT_ID: [_FAKE_CLUSTER_NAME]},
                     self.uut.get_supported_endpoints_and_clusters())

  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc, "get")
  @mock.patch.object(
      matter_endpoints_accessor_pw_rpc.MatterEndpointsAccessorPwRpc, "list")
  def test_get_supported_endpoint_instances_and_cluster_flavors(
      self, mock_list, mock_get):
    """Verifies get_supported_endpoint_instances_and_cluster_flavors method."""
    mock_list.return_value = [_FAKE_ENDPOINT_ID]
    mock_get.return_value = _FAKE_ENDPOINT_INST
    _FAKE_ENDPOINT_INST.get_supported_cluster_flavors.return_value = [
        _FAKE_CLUSTER_CLS
    ]
    expected_mapping = {_FAKE_ENDPOINT_INST: [_FAKE_CLUSTER_CLS]}

    self.assertEqual(
        expected_mapping,
        self.uut.get_supported_endpoint_instances_and_cluster_flavors())

  def test_ember_api_read(self):
    """Verifies Ember API read method on success."""
    data = attributes_service_pb2.AttributeData(data_bool=True)
    self.fake_switchboard_call.return_value = data.SerializeToString()

    self.assertEqual(
        data,
        self.uut.read(
            endpoint_id=_FAKE_ENDPOINT_ID,
            cluster_id=_FAKE_CLUSTER_ID,
            attribute_id=_FAKE_ATTRIBUTE_ID,
            attribute_type=_FAKE_ATTRIBUTE_TYPE))

  def test_ember_api_write(self):
    """Verifies Ember API write method on success."""
    self.uut.write(
        endpoint_id=_FAKE_ENDPOINT_ID,
        cluster_id=_FAKE_CLUSTER_ID,
        attribute_id=_FAKE_ATTRIBUTE_ID,
        attribute_type=_FAKE_ATTRIBUTE_TYPE,
        data_bool=True)

    self.fake_switchboard_call.assert_called_once()

if __name__ == "__main__":
  fake_device_test_case.main()


text:
/**
 * Created by 米饭 on 2017-04-07.
 */

import { IWindowService} from "angular";
import * as angular from "angular";

/*@ngInject*/
export default class LocalStorageService {

    private localStorage: Storage;
    private _isSupported: boolean;

    constructor($window: IWindowService) {
        this.localStorage = $window.localStorage;
        this._isSupported = !!$window.localStorage;
    }

    set<T>(key: string, value: T | null) {
        let jsonStr = angular.toJson(value);
        this.localStorage.setItem(key, jsonStr);
    }
    get<T>(key: string): T | null {
        let jsonStr = this.localStorage.getItem(key);
        if(!jsonStr) {
            return null;
        }
        return angular.fromJson(jsonStr);
    }

    clear(): void {
        this.localStorage.clear();
    }

    remove(key: string): void {
        this.localStorage.removeItem(key);
    }

    key(index: number): string | null {
        return this.localStorage.key(index);
    }

    get isSupported(): boolean {
        return this._isSupported;
    }

    get length(): number {
        return this.localStorage.length;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/menu_meet_now"
        android:title="@string/Meet_Now" />

    <item android:id="@+id/menu_schedule_meet"
        android:title="@string/Schedule_a_Meet" />
</menu><!-- From: file:/Users/Breeze/Downloads/Products/Android/IntelliJ/trunk/moxtrasdk/products/ConversationSDK/src/main/res/menu/menu_meet_actions.xml -->


text:
"""Defines a layout that will give one of it's components as much space as
possible, while still showing the other components in the layout."""

from warnings import warn

from muntjac.ui.ordered_layout import OrderedLayout

class ExpandLayout(OrderedLayout):
    """A layout that will give one of it's components as much space as
    possible, while still showing the other components in the layout. The
    other components will in effect be given a fixed sized space, while the
    space given to the expanded component will grow/shrink to fill the rest
    of the space available - for instance when re-sizing the window.

    Note that this layout is 100% in both directions by default
    (L{setSizeFull}). Remember to set the units if you want to
    specify a fixed size. If the layout fails to show up, check that the
    parent layout is actually giving some space.

    @deprecated: Deprecated in favor of the new OrderedLayout
    """

    def __init__(self, orientation=None):
        warn('use OrderedLayout', DeprecationWarning)

        self._expanded = None

        if orientation is None:
            self.ORIENTATION_VERTICAL

        super(ExpandLayout, self).__init__(orientation)
        self.setSizeFull()

    def expand(self, c):
        """@param c: Component which container will be maximized
        """
        if self._expanded is not None:
            try:
                self.setExpandRatio(self._expanded, 0.0)
            except ValueError:
                pass  # Ignore error if component has been removed

        self._expanded = c
        if self._expanded is not None:
            self.setExpandRatio(self._expanded, 1.0)

        self.requestRepaint()

    def addComponent(self, c, index=None):
        if index is None:
            super(ExpandLayout, self).addComponent(c)
        else:
            super(ExpandLayout, self).addComponent(c, index)
        if self._expanded is None:
            self.expand(c)

    def addComponentAsFirst(self, c):
        super(ExpandLayout, self).addComponentAsFirst(c)
        if self._expanded is None:
            self.expand(c)

    def removeComponent(self, c):
        super(ExpandLayout, self).removeComponent(c)
        if c == self._expanded:
            try:
                self.expand(self.getComponentIterator().next())
            except StopIteration:
                self.expand(None)

    def replaceComponent(self, oldComponent, newComponent):
        super(ExpandLayout, self).replaceComponent(oldComponent, newComponent)
        if oldComponent == self._expanded:
            self.expand(newComponent)


text:
#define NAME_XMPP_MESSAGE_CORRECT @"replace"
#define XMLNS_XMPP_MESSAGE_CORRECT @"urn:xmpp:message-correct:0"

@implementation XMPPMessage (XEP_0308)

- (BOOL)isMessageCorrection
{
    if([[self correctedMessageID] length])
    {
        return YES;
    }else{
        return NO;
    }
}

- (NSString *)correctedMessageID
{
    return [[self elementForName:NAME_XMPP_MESSAGE_CORRECT xmlns:XMLNS_XMPP_MESSAGE_CORRECT] attributeStringValueForName:@"id"];
}

- (void)addMessageCorrectionWithID:(NSString *)messageCorrectionID
{
    NSXMLElement *replace = [NSXMLElement elementWithName:NAME_XMPP_MESSAGE_CORRECT stringValue:XMLNS_XMPP_MESSAGE_CORRECT];
    [replace addAttributeWithName:@"id" stringValue:messageCorrectionID];
    [self addChild:replace];
}

@end


text:
package main

import (
    "fmt"
    "encoding/json"
)

type server_info struct {
    IP int
    Box []string
}

func main() {
    new_server := &server_info{
        IP: 1,
        Box: []string{"abc", "bcd"}}

    test, _ := json.Marshal(new_server)
    fmt.Println(new_server)
    fmt.Println(string(test))
}


text:
module ClosureTree
  VERSION = Gem::Version.new('5.2.0') unless defined?(::ClosureTree::VERSION)
end


text:
package admin

import (
	"gopkg.in/macaron.v1"
)

func ListParam(ctx *macaron.Context) {
	ctx.HTML(200, "admin/sys/param/list")
}

func EditParam(ctx *macaron.Context) {
	ctx.HTML(200, "admin/sys/param/list")
}
func AddParam(ctx *macaron.Context) {
	ctx.HTML(200, "admin/sys/param/list")
}
func UpdateParam(ctx *macaron.Context) {
	ctx.HTML(200, "admin/sys/param/list")
}

func DelParam(ctx *macaron.Context) {
	ctx.HTML(200, "admin/sys/param/list")
}


text:
package org.apache.derby.iapi.services.diag;

import org.apache.derby.shared.common.error.StandardException;

import java.util.Properties;

/**

  The Diagnosticable class implements the Diagnostics protocol, and can
  be used as the parent class for all other Diagnosticable objects.

**/

public class DiagnosticableGeneric implements Diagnosticable
{
	/*
	** Fields of Diagnosticable
	*/
    protected Object diag_object = null;

    public DiagnosticableGeneric()
    {
    }

	/*
	** Methods of Diagnosticable
	*/
    public void init(Object obj)
    {
        // This is the pointer to the instance of the object to work on.
        this.diag_object = obj;
    }

    /**
     * Default implementation of diagnostic on the object.
     *

     * This routine returns a string with whatever diagnostic information
     * you would like to provide about this object.
     *

     * This routine should be overriden by a real implementation of the
     * diagnostic information you would like to provide.
     *

     *
	 * @return A string with diagnostic information about the object.
     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public String diag()
        throws StandardException
    {
        return(diag_object.toString());
    }

    /**
     * Default implementation of detail diagnostic on the object.
     *

     * This routine should be overriden if there is detail diagnostics to
     * be provided by a real implementation.
     *

     *
	 * @exception  StandardException  Standard exception policy.
     **/
    public void diag_detail(Properties prop)
        throws StandardException
    {
        return;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>DSR Training</title>

    <link href="css/bootstrap.min.css" rel="stylesheet"/>
    <link href="css/style.css" rel="stylesheet"/>

       <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
        data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>
      NNSR

Home

Course Training

Forms

Contact

        <form class="form-inline">

            Email address
            <input type="email" class="form-control" id="exampleInputEmail3" placeholder="Email">

            Password
            <input type="password" class="form-control" id="exampleInputPassword3" placeholder="Password">

            <input type="checkbox"> Remember me

          <button type="submit" class="btn btn-primary">Sign in</button>
        </form>

Pathway to Quality Services Developing and enhancing employee knowledge,
skills and abilities.

PURPOSE
To establish a standard and consistent process for developing and enhancing
the knowledge, skills, and abilities of the Department for Self Reliance (DSR)
to attain and maintain proficiency in areas related to their duties and
responsibilities.


text:
#ifndef FORKLIFT_DEMO_H
#define FORKLIFT_DEMO_H

class CommonExampleInterface*    ForkLiftCreateFunc(struct CommonExampleOptions& options);

#endif // FORKLIFT_DEMO_H


text:
"use strict";

const isJustOneLetter = require("../../src/buildAliases/isJustOneLetter");;

describe("buildAliases/isJustOneLetter", () => {
  it("deve verificar se uma string tem somente uma letra", () => {
    expect(isJustOneLetter("e")).toBeTruthy();
    expect(isJustOneLetter("é")).toBeFalsy();
    expect(isJustOneLetter("&")).toBeFalsy();
    expect(isJustOneLetter("eee")).toBeFalsy();
  });
});


text:
import sublime
import sublime_plugin
import re

try: # Python 3
    from .haxe_helper import wordChars, importLine, packageLine, spaceChars
except (ValueError): # Python 2
    from haxe_helper import wordChars, importLine, packageLine, spaceChars

class HaxeGenerateImport( sublime_plugin.TextCommand ):

    start = None
    size = None
    cname = None

    def get_end( self, src, offset ) :
        end = len(src)
        while offset < end:
            c = src[offset]
            offset += 1
            if not wordChars.match(c): break
        return offset - 1

    def get_start( self, src, offset ) :
        foundWord = 0
        offset -= 1
        while offset > 0:
            c = src[offset]
            offset -= 1
            if foundWord == 0:
                if spaceChars.match(c): continue
                foundWord = 1
            if not wordChars.match(c): break

        return offset + 2

    def is_membername( self, token ) :
        return token[0] >= "Z" or token == token.upper()

    def is_module( self , token ) :
        return re.search("[\.^][A-Z]+", token);

    def get_classname( self, view, src ) :
        loc = view.sel()[0]
        end = max(loc.a, loc.b)
        self.size = loc.size()
        if self.size == 0:
            end = self.get_end(src, end)
            self.start = self.get_start(src, end)
            self.size = end - self.start
        else:
            self.start = end - self.size

        self.cname = view.substr(sublime.Region(self.start, end)).rpartition(".")
        #print(self.cname)
        while (not self.cname[0] == "" and self.is_membername(self.cname[2])):
            self.size -= 1 + len(self.cname[2])
            self.cname = self.cname[0].rpartition(".")

    def compact_classname( self, edit, view ) :
        view.replace(edit, sublime.Region(self.start, self.start+self.size), self.cname[2])
        view.sel().clear()
        loc = self.start + len(self.cname[2])
        view.sel().add(sublime.Region(loc, loc))

    def get_indent( self, src, index ) :

        if src[index] == "\n": return index + 1
        return index

    def insert_import( self, edit, view, src) :
        cname = "".join(self.cname)
        clow = cname.lower()
        last = None

        for imp in importLine.finditer(src):
            if clow < imp.group(2).lower():
                ins = "{0}import {1};\n".format(imp.group(1), cname)
                view.insert(edit, self.get_indent(src, imp.start(0)), ins)
                return
            last = imp

        if not last is None:
            ins = ";\n{0}import {1}".format(last.group(1), cname)
            view.insert(edit, last.end(2), ins)
        else:
            pkg = packageLine.search(src)
            if not pkg is None:
                ins = "\n\nimport {0};".format(cname)
                view.insert(edit, pkg.end(0), ins)
            else:
                ins = "import {0};\n\n".format(cname)
                view.insert(edit, 0, ins)

    def run( self , edit ) :
        view = self.view
        src = view.substr(sublime.Region(0, view.size()))
        self.get_classname(view, src)

        if self.cname[1] == "":
            sublime.status_message("Nothing to import")
            print("Nothing to import")
            return

        self.compact_classname(edit, view)

        if re.search("import\s+{0};".format("".join(self.cname)), src):
            sublime.status_message("Already imported")
            print("Already imported")
            return

        self.insert_import(edit, view, src)


text:
from settings import *
INSTALLED_APPS.append('basic')
INSTALLED_APPS.append('slashless')

ROOT_URLCONF = 'slashless.api.urls'

DEBUG = True
APPEND_SLASH = False
TASTYPIE_ALLOW_MISSING_SLASH = True


text:
package com.systematic.trading.signals.data.api.alpha.vantage.configuration;

/**
 * @author CJ Hare
 */
public class AlphaVantageConnectionConfiguration {

	private final String endpoint;
	private final String apiKey;
	private final int numberOfRetries;
	private final int retryBackOffMs;
	private final int maximumRetrievalTimeSeconds;

	public AlphaVantageConnectionConfiguration(
	        final String endpoint,
	        final String apiKey,
	        final int numberOfRetries,
	        final int retryBackOffMs,
	        final int maximumRetrievalTimeSeconds ) {

		this.endpoint = endpoint;
		this.apiKey = apiKey;
		this.numberOfRetries = numberOfRetries;
		this.retryBackOffMs = retryBackOffMs;
		this.maximumRetrievalTimeSeconds = maximumRetrievalTimeSeconds;
	}

	public String endpoint() {

		return endpoint;
	}

	public String apiKey() {

		return apiKey;
	}

	public int numberOfRetries() {

		return numberOfRetries;
	}

	public int retryBackOffMs() {

		return retryBackOffMs;
	}

	public int maximumRetrievalTimeSeconds() {

		return maximumRetrievalTimeSeconds;
	}
}


text:
package org.anddev.andengine.engine.handler;

import org.anddev.andengine.util.SmartList;

/**
 * @author Nicolas Gramlich
 * @since 09:45:22 - 31.03.2010
 */
public class UpdateHandlerList extends SmartList<IUpdateHandler> implements IUpdateHandler {
	// ===========================================================
	// Constants
	// ===========================================================

	private static final long serialVersionUID = -8842562717687229277L;

	// ===========================================================
	// Fields
	// ===========================================================

	// ===========================================================
	// Constructors
	// ===========================================================

	public UpdateHandlerList() {

	}

	public UpdateHandlerList(final int pCapacity) {
		super(pCapacity);
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public void onUpdate(final float pSecondsElapsed) {
		final int handlerCount = this.size();
		for(int i = handlerCount - 1; i >= 0; i--) {
			this.get(i).onUpdate(pSecondsElapsed);
		}
	}

	@Override
	public void reset() {
		final int handlerCount = this.size();
		for(int i = handlerCount - 1; i >= 0; i--) {
			this.get(i).reset();
		}
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
package org.jboss.weld.environment.se.test.builder;

import javax.enterprise.context.ApplicationScoped;

@Monitored
@ApplicationScoped
public class Qux {

    public Integer ping() {
        return 10;
    }

}


text:
<?php

namespace Backpack\CRUD\app\Http\Controllers;

use Backpack\CRUD\CrudPanel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Form as Form;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Backpack\CRUD\app\Http\Controllers\CrudFeatures\Reorder;
use Backpack\CRUD\app\Http\Controllers\CrudFeatures\AjaxTable;
// CRUD Traits for non-core features
use Backpack\CRUD\app\Http\Controllers\CrudFeatures\Revisions;
use Backpack\CRUD\app\Http\Controllers\CrudFeatures\SaveActions;
use Backpack\CRUD\app\Http\Requests\CrudRequest as StoreRequest;
use Backpack\CRUD\app\Http\Requests\CrudRequest as UpdateRequest;
use Backpack\CRUD\app\Http\Controllers\CrudFeatures\ShowDetailsRow;

class CrudController extends BaseController
{
    use DispatchesJobs, ValidatesRequests;
    use AjaxTable, Reorder, Revisions, ShowDetailsRow, SaveActions;

    public $data = [];
    public $crud;
    public $request;

    public function __construct()
    {
        if (! $this->crud) {
            $this->crud = app()->make(CrudPanel::class);

            // call the setup function inside this closure to also have the request there
            // this way, developers can use things stored in session (auth variables, etc)
            $this->middleware(function ($request, $next) {
                $this->request = $request;
                $this->crud->request = $request;
                $this->setup();

                return $next($request);
            });
        }
    }

    /**
     * Allow developers to set their configuration options for a CrudPanel.
     */
    public function setup()
    {
    }

    /**
     * Display all rows in the database for this entity.
     *
     * @return Response
     */
    public function index()
    {
        $this->crud->hasAccessOrFail('list');

        $this->data['crud'] = $this->crud;
        $this->data['title'] = ucfirst($this->crud->entity_name_plural);

        // get all entries if AJAX is not enabled
        if (! $this->data['crud']->ajaxTable()) {
            $this->data['entries'] = $this->data['crud']->getEntries();
        }

        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
        return view($this->crud->getListView(), $this->data);
    }

    /**
     * Show the form for creating inserting a new row.
     *
     * @return Response
     */
    public function create()
    {
        $this->crud->hasAccessOrFail('create');

        // prepare the fields you need to show
        $this->data['crud'] = $this->crud;
        $this->data['saveAction'] = $this->getSaveAction();
        $this->data['fields'] = $this->crud->getCreateFields();
        $this->data['title'] = trans('backpack::crud.add').' '.$this->crud->entity_name;

        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
        return view($this->crud->getCreateView(), $this->data);
    }

    /**
     * Store a newly created resource in the database.
     *
     * @param StoreRequest $request - type injection used for validation using Requests
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function storeCrud(StoreRequest $request = null)
    {
        $this->crud->hasAccessOrFail('create');

        // fallback to global request instance
        if (is_null($request)) {
            $request = \Request::instance();
        }

        // replace empty values with NULL, so that it will work with MySQL strict mode on
        foreach ($request->input() as $key => $value) {
            if (empty($value) && $value !== '0') {
                $request->request->set($key, null);
            }
        }

        // insert item in the db
        $item = $this->crud->create($request->except(['save_action', '_token', '_method']));
        $this->data['entry'] = $this->crud->entry = $item;

        // show a success message
        \Alert::success(trans('backpack::crud.insert_success'))->flash();

        // save the redirect choice for next time
        $this->setSaveAction();

        return $this->performSaveAction($item->getKey());
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $this->crud->hasAccessOrFail('update');

        // get the info for that entry
        $this->data['entry'] = $this->crud->getEntry($id);
        $this->data['crud'] = $this->crud;
        $this->data['saveAction'] = $this->getSaveAction();
        $this->data['fields'] = $this->crud->getUpdateFields($id);
        $this->data['title'] = trans('backpack::crud.edit').' '.$this->crud->entity_name;

        $this->data['id'] = $id;

        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
        return view($this->crud->getEditView(), $this->data);
    }

    /**
     * Update the specified resource in the database.
     *
     * @param UpdateRequest $request - type injection used for validation using Requests
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateCrud(UpdateRequest $request = null)
    {
        $this->crud->hasAccessOrFail('update');

        // fallback to global request instance
        if (is_null($request)) {
            $request = \Request::instance();
        }

        // replace empty values with NULL, so that it will work with MySQL strict mode on
        foreach ($request->input() as $key => $value) {
            if (empty($value) && $value !== '0') {
                $request->request->set($key, null);
            }
        }

        // update the row in the db
        $item = $this->crud->update($request->get($this->crud->model->getKeyName()),
                            $request->except('save_action', '_token', '_method'));
        $this->data['entry'] = $this->crud->entry = $item;

        // show a success message
        \Alert::success(trans('backpack::crud.update_success'))->flash();

        // save the redirect choice for next time
        $this->setSaveAction();

        return $this->performSaveAction($item->getKey());
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $this->crud->hasAccessOrFail('show');

        // get the info for that entry
        $this->data['entry'] = $this->crud->getEntry($id);
        $this->data['crud'] = $this->crud;
        $this->data['title'] = trans('backpack::crud.preview').' '.$this->crud->entity_name;

        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
        return view($this->crud->getShowView(), $this->data);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return string
     */
    public function destroy($id)
    {
        $this->crud->hasAccessOrFail('delete');

        return $this->crud->delete($id);
    }
}


text:
require File.expand_path("../../spec_helper", __FILE__)

describe CouchRest::RestAPI do

  describe "class methods" do

    subject { CouchRest }

    let(:request) { RestClient::Request }
    let(:simple_response) { "{\"ok\":true}" }
    let(:parser) { MultiJson }
    let(:parser_opts) { {:max_nesting => false} }

    it "should exist" do
      should respond_to :get
      should respond_to :put
      should respond_to :post
      should respond_to :copy
      should respond_to :delete
    end

    it "should provide default headers" do
      should respond_to :default_headers
      CouchRest.default_headers.should be_a(Hash)
    end

    describe :get do
      it "should send basic request" do
        req = {:url => 'foo', :method => :get, :headers => CouchRest.default_headers}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.get('foo')
      end

      it "should never modify options" do
        options = {:timeout => 1000}
        options.freeze
        request.should_receive(:execute).and_return(simple_response)
        parser.should_receive(:decode)
        expect { CouchRest.get('foo', options) }.to_not raise_error
      end

      it "should accept 'content_type' header" do
        req = {:url => 'foo', :method => :get, :headers => CouchRest.default_headers.merge(:content_type => :foo)}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.get('foo', :content_type => :foo)
      end

      it "should accept 'accept' header" do
        req = {:url => 'foo', :method => :get, :headers => CouchRest.default_headers.merge(:accept => :foo)}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.get('foo', :accept => :foo)
      end

      it "should forward RestClient options" do
        req = {:url => 'foo', :method => :get, :timeout => 1000, :headers => CouchRest.default_headers}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.get('foo', :timeout => 1000)
      end

      it "should forward parser options" do
        req = {:url => 'foo', :method => :get, :headers => CouchRest.default_headers}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:decode).with(simple_response, parser_opts.merge(:random => 'foo'))
        CouchRest.get('foo', :random => 'foo')
      end

      it "should accept raw option" do
        req = {:url => 'foo', :method => :get, :headers => CouchRest.default_headers}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_not_receive(:decode)
        CouchRest.get('foo', :raw => true).should eql(simple_response)
      end

      it "should allow override of method (not that you'd want to!)" do
        req = {:url => 'foo', :method => :fubar, :headers => CouchRest.default_headers}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.get('foo', :method => :fubar)
      end

      it "should allow override of url (not that you'd want to!)" do
        req = {:url => 'foobardom', :method => :get, :headers => CouchRest.default_headers}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.get('foo', :url => 'foobardom')
      end

      it "should forward an exception if raised" do
        request.should_receive(:execute).and_raise(RestClient::Exception)
        expect { CouchRest.get('foo') }.to raise_error(RestClient::Exception)
      end

    end

    describe :post do
      it "should send basic request" do
        req = {:url => 'foo', :method => :post, :headers => CouchRest.default_headers, :payload => 'data'}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:encode).with('data').and_return('data')
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.post('foo', 'data')
      end

      it "should send basic request" do
        req = {:url => 'foo', :method => :post, :headers => CouchRest.default_headers, :payload => 'data'}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:encode).with('data').and_return('data')
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.post('foo', 'data')
      end

      it "should send raw request" do
        req = {:url => 'foo', :method => :post, :headers => CouchRest.default_headers, :payload => 'data'}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_not_receive(:encode)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.post('foo', 'data', :raw => true)
      end

      it "should not encode nil request" do
        req = {:url => 'foo', :method => :post, :headers => CouchRest.default_headers}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_not_receive(:encode)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.post('foo', nil)
      end

      it "should send raw request automatically if file provided" do
        f = File.open(FIXTURE_PATH + '/attachments/couchdb.png')
        req = {:url => 'foo', :method => :post, :headers => CouchRest.default_headers, :payload => f}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_not_receive(:encode)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.post('foo', f)
        f.close
      end

      it "should send raw request automatically if Tempfile provided" do
        f = Tempfile.new('couchrest')
        req = {:url => 'foo', :method => :post, :headers => CouchRest.default_headers, :payload => f}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_not_receive(:encode)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.post('foo', f)
        f.close
      end

    end

    describe :put do
      # Only test basic as practically same as post
      it "should send basic request" do
        req = {:url => 'foo', :method => :put, :headers => CouchRest.default_headers, :payload => 'data'}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:encode).with('data').and_return('data')
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.put('foo', 'data')
      end

    end

    describe :delete do
      it "should send basic request" do
        req = {:url => 'foo', :method => :delete, :headers => CouchRest.default_headers}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.delete('foo')
      end
    end

    describe :copy do
      it "should send basic request" do
        headers = CouchRest.default_headers.merge(
          'Destination' => 'fooobar'
        )
        req = {:url => 'foo', :method => :copy, :headers => headers}
        request.should_receive(:execute).with(req).and_return(simple_response)
        parser.should_receive(:decode).with(simple_response, parser_opts)
        CouchRest.copy('foo', 'fooobar')
      end

      it "should never modify header options" do
        options = {:headers => {:content_type => :foo}}
        options.freeze
        request.should_receive(:execute).and_return(simple_response)
        parser.should_receive(:decode)
        expect { CouchRest.copy('foo', 'foobar', options) }.to_not raise_error
      end

    end

  end

end


text:
''' Display a variety of visual shapes whose attributes can be associated
with data columns from ``ColumnDataSources``.

The full list of glyphs built into Bokeh is given below:

* :class:`~bokeh.models.glyphs.AnnularWedge`
* :class:`~bokeh.models.glyphs.Annulus`
* :class:`~bokeh.models.glyphs.Arc`
* :class:`~bokeh.models.glyphs.Bezier`
* :class:`~bokeh.models.glyphs.Ellipse`
* :class:`~bokeh.models.glyphs.HBar`
* :class:`~bokeh.models.glyphs.HexTile`
* :class:`~bokeh.models.glyphs.Image`
* :class:`~bokeh.models.glyphs.ImageRGBA`
* :class:`~bokeh.models.glyphs.ImageURL`
* :class:`~bokeh.models.glyphs.Line`
* :class:`~bokeh.models.glyphs.MultiLine`
* :class:`~bokeh.models.glyphs.MultiPolygons`
* :class:`~bokeh.models.glyphs.Oval`
* :class:`~bokeh.models.glyphs.Patch`
* :class:`~bokeh.models.glyphs.Patches`
* :class:`~bokeh.models.glyphs.Quad`
* :class:`~bokeh.models.glyphs.Quadratic`
* :class:`~bokeh.models.glyphs.Ray`
* :class:`~bokeh.models.glyphs.Rect`
* :class:`~bokeh.models.glyphs.Segment`
* :class:`~bokeh.models.glyphs.Step`
* :class:`~bokeh.models.glyphs.Text`
* :class:`~bokeh.models.glyphs.VBar`
* :class:`~bokeh.models.glyphs.Wedge`

All these glyphs share a minimal common interface through their base class
``Glyph``:

.. autoclass:: Glyph
    :members:

'''

#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals

import logging
log = logging.getLogger(__name__)

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Standard library imports

# External imports

# Bokeh imports
from ..core.enums import Anchor, Direction, StepMode
from ..core.has_props import abstract
from ..core.properties import (AngleSpec, Bool, DistanceSpec, Enum, Float, String,
                               Include, Instance, Int, NumberSpec, Override, StringSpec)
from ..core.property_mixins import FillProps, LineProps, ScalarFillProps, ScalarLineProps, TextProps
from ..model import Model

from .mappers import ColorMapper, LinearColorMapper

#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------

__all__ = (
    'AnnularWedge',
    'Annulus',
    'Arc',
    'Bezier',
    'Ellipse',
    'Glyph',
    'HBar',
    'HexTile',
    'Image',
    'ImageRGBA',
    'ImageURL',
    'Line',
    'MultiLine',
    'MultiPolygons',
    'Oval',
    'Patch',
    'Patches',
    'Quad',
    'Quadratic',
    'Ray',
    'Rect',
    'Segment',
    'Step',
    'Text',
    'VBar',
    'Wedge',
    'XYGlyph',
)

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

@abstract
class Glyph(Model):
    ''' Base class for all glyph models.

    '''

@abstract
class XYGlyph(Glyph):
    ''' Base class of glyphs with `x` and `y` coordinate attributes.

    '''

class AnnularWedge(XYGlyph):
    ''' Render annular wedges.

    '''

    __example__ = "examples/reference/models/AnnularWedge.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y', 'inner_radius', 'outer_radius', 'start_angle', 'end_angle', 'direction')

    x = NumberSpec(help="""
    The x-coordinates of the center of the annular wedges.
    """)

    y = NumberSpec(help="""
    The y-coordinates of the center of the annular wedges.
    """)

    inner_radius = DistanceSpec(help="""
    The inner radii of the annular wedges.
    """)

    outer_radius = DistanceSpec(help="""
    The outer radii of the annular wedges.
    """)

    start_angle = AngleSpec(help="""
    The angles to start the annular wedges, as measured from the horizontal.
    """)

    end_angle = AngleSpec(help="""
    The angles to end the annular wedges, as measured from the horizontal.
    """)

    direction = Enum(Direction, default=Direction.anticlock, help="""
    Which direction to stroke between the start and end angles.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the annular wedges.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the annular wedges.
    """)

class Annulus(XYGlyph):
    ''' Render annuli.

    '''

    __example__ = "examples/reference/models/Annulus.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y', 'inner_radius', 'outer_radius')

    x = NumberSpec(help="""
    The x-coordinates of the center of the annuli.
    """)

    y = NumberSpec(help="""
    The y-coordinates of the center of the annuli.
    """)

    inner_radius = DistanceSpec(help="""
    The inner radii of the annuli.
    """)

    outer_radius = DistanceSpec(help="""
    The outer radii of the annuli.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the annuli.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the annuli.
    """)

class Arc(XYGlyph):
    ''' Render arcs.

    '''

    __example__ = "examples/reference/models/Arc.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y', 'radius', 'start_angle', 'end_angle', 'direction')

    x = NumberSpec(help="""
    The x-coordinates of the center of the arcs.
    """)

    y = NumberSpec(help="""
    The y-coordinates of the center of the arcs.
    """)

    radius = DistanceSpec(help="""
    Radius of the arc.
    """)

    start_angle = AngleSpec(help="""
    The angles to start the arcs, as measured from the horizontal.
    """)

    end_angle = AngleSpec(help="""
    The angles to end the arcs, as measured from the horizontal.
    """)

    direction = Enum(Direction, default='anticlock', help="""
    Which direction to stroke between the start and end angles.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the arcs.
    """)

class Bezier(Glyph):
    ''' Render Bezier curves.

    For more information consult the `Wikipedia article for Bezier curve`_.

    .. _Wikipedia article for Bezier curve: http://en.wikipedia.org/wiki/Bezier_curve

    '''

    __example__ = "examples/reference/models/Bezier.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x0', 'y0', 'x1', 'y1', 'cx0', 'cy0', 'cx1', 'cy1')

    x0 = NumberSpec(help="""
    The x-coordinates of the starting points.
    """)

    y0 = NumberSpec(help="""
    The y-coordinates of the starting points.
    """)

    x1 = NumberSpec(help="""
    The x-coordinates of the ending points.
    """)

    y1 = NumberSpec(help="""
    The y-coordinates of the ending points.
    """)

    cx0 = NumberSpec(help="""
    The x-coordinates of first control points.
    """)

    cy0 = NumberSpec(help="""
    The y-coordinates of first control points.
    """)

    cx1 = NumberSpec(help="""
    The x-coordinates of second control points.
    """)

    cy1 = NumberSpec(help="""
    The y-coordinates of second control points.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the Bezier curves.
    """)

class Ellipse(XYGlyph):
    ''' Render ellipses.

    '''

    __example__ = "examples/reference/models/Ellipse.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y', 'width', 'height', 'angle')

    x = NumberSpec(help="""
    The x-coordinates of the centers of the ellipses.
    """)

    y = NumberSpec(help="""
    The y-coordinates of the centers of the ellipses.
    """)

    width = DistanceSpec(help="""
    The widths of each ellipse.
    """)

    height = DistanceSpec(help="""
    The heights of each ellipse.
    """)

    angle = AngleSpec(default=0.0, help="""
    The angle the ellipses are rotated from horizontal. [rad]
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the ovals.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the ovals.
    """)

class HBar(Glyph):
    ''' Render horizontal bars, given a center coordinate, ``height`` and
    (``left``, ``right``) coordinates.

    '''

    __example__ = "examples/reference/models/HBar.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('y', 'height', 'right', 'left')

    y = NumberSpec(help="""
    The y-coordinates of the centers of the horizontal bars.
    """)

    height = NumberSpec(help="""
    The heights of the vertical bars.
    """)

    left = NumberSpec(default=0, help="""
    The x-coordinates of the left edges.
    """)

    right = NumberSpec(help="""
    The x-coordinates of the right edges.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the horizontal bars.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the horizontal bars.
    """)

class HexTile(Glyph):
    ''' Render horizontal tiles on a regular hexagonal grid.

    '''

    __example__ = "examples/reference/models/HexTile.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('q', 'r')

    size = Float(1.0, help="""
    The radius (in data space units) of the hex tiling.

    The radius is always measured along the cartesian y-axis for "pointy_top"
    orientation, and along the cartesian x-axis for "flat_top" orientation. If
    the aspect ratio of the underlying cartesian system is not 1-1, then the
    tiles may be "squished" in one direction. To ensure that the tiles are
    always regular hexagons, consider setting the ``match_aspect`` property of
    the plot to True.
    """)

    aspect_scale = Float(1.0, help="""

    """)

    r = NumberSpec(help="""
    The "row" axial coordinates of the tile centers.
    """)

    q = NumberSpec(help="""
    The "column" axial coordinates of the tile centers.
    """)

    scale = NumberSpec(1.0, help="""
    A scale factor for individual tiles.
    """)

    orientation = String("pointytop", help="""

    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the horizontal bars.
    """)

    line_color = Override(default=None)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the horizontal bars.
    """)

class Image(XYGlyph):
    ''' Render images given as scalar data together with a color mapper.

    In addition to the defined model properties, ``Image`` also can accept
    a keyword argument ``palette`` in place of an explicit ``color_mapper``.
    The value should be a list of colors, or the name of one of the built-in
    palettes in ``bokeh.palettes``. This palette will be used to automatically
    construct a ``ColorMapper`` model for the ``color_mapper`` property.

    If both ``palette`` and ``color_mapper`` are passed, a ``ValueError``
    exception will be raised. If neither is passed, then the ``Greys9``
    palette will be used as a default.

    '''

    def __init__(self, **kwargs):
        if 'palette' in kwargs and 'color_mapper' in kwargs:
            raise ValueError("only one of 'palette' and 'color_mapper' may be specified")
        elif 'color_mapper' not in kwargs:
            # Use a palette (given or default)
            palette = kwargs.pop('palette', 'Greys9')
            mapper = LinearColorMapper(palette)
            kwargs['color_mapper'] = mapper

        super(Image, self).__init__(**kwargs)

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('image', 'x', 'y', 'dw', 'dh', 'global_alpha', 'dilate')

    # a hook to specify any additional kwargs handled by an initializer
    _extra_kws = {
        'palette': (
            'str or list[color value]',
            'a palette to construct a value for the color mapper property from'
        )
    }

    image = NumberSpec(help="""
    The arrays of scalar data for the images to be colormapped.
    """)

    x = NumberSpec(help="""
    The x-coordinates to locate the image anchors.
    """)

    y = NumberSpec(help="""
    The y-coordinates to locate the image anchors.
    """)

    dw = DistanceSpec(help="""
    The widths of the plot regions that the images will occupy.

    .. note::
        This is not the number of pixels that an image is wide.
        That number is fixed by the image itself.
    """)

    dh = DistanceSpec(help="""
    The height of the plot region that the image will occupy.

    .. note::
        This is not the number of pixels that an image is tall.
        That number is fixed by the image itself.
    """)

    global_alpha = Float(1.0, help="""
    An overall opacity that each image is rendered with (in addition
    to any alpha values applied explicitly in a color mapper).
    """)

    dilate = Bool(False, help="""
    Whether to always round fractional pixel locations in such a way
    as to make the images bigger.

    This setting may be useful if pixel rounding errors are causing
    images to have a gap between them, when they should appear flush.
    """)

    color_mapper = Instance(ColorMapper, help="""
    A ``ColorMapper`` to use to map the scalar data from ``image``
    into RGBA values for display.

    .. note::
        The color mapping step happens on the client.
    """)

    # TODO: (bev) support anchor property for Image
    # ref: https://github.com/bokeh/bokeh/issues/1763

class ImageRGBA(XYGlyph):
    ''' Render images given as RGBA data.

    '''

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('image', 'x', 'y', 'dw', 'dh', 'global_alpha', 'dilate')

    image = NumberSpec(help="""
    The arrays of RGBA data for the images.
    """)

    x = NumberSpec(help="""
    The x-coordinates to locate the image anchors.
    """)

    y = NumberSpec(help="""
    The y-coordinates to locate the image anchors.
    """)

    dw = DistanceSpec(help="""
    The widths of the plot regions that the images will occupy.

    .. note::
        This is not the number of pixels that an image is wide.
        That number is fixed by the image itself.
    """)

    dh = DistanceSpec(help="""
    The height of the plot region that the image will occupy.

    .. note::
        This is not the number of pixels that an image is tall.
        That number is fixed by the image itself.
    """)

    global_alpha = Float(1.0, help="""
    An overall opacity that each image is rendered with (in addition
    to any inherent alpha values in the image itself).
    """)

    dilate = Bool(False, help="""
    Whether to always round fractional pixel locations in such a way
    as to make the images bigger.

    This setting may be useful if pixel rounding errors are causing
    images to have a gap between them, when they should appear flush.
    """)

    # TODO: (bev) support anchor property for ImageRGBA
    # ref: https://github.com/bokeh/bokeh/issues/1763

class ImageURL(XYGlyph):
    ''' Render images loaded from given URLs.

    '''

    __example__ = "examples/reference/models/ImageURL.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('url', 'x', 'y', 'w', 'h', 'angle', 'global_alpha', 'dilate')

    url = StringSpec(default=None, help="""
    The URLs to retrieve images from.

    .. note::
        The actual retrieving and loading of the images happens on
        the client.
    """)

    x = NumberSpec(help="""
    The x-coordinates to locate the image anchors.
    """)

    y = NumberSpec(help="""
    The y-coordinates to locate the image anchors.
    """)

    w = DistanceSpec(default=None, help="""
    The width of the plot region that the image will occupy in data space.

    The default value is ``None``, in which case the image will be displayed
    at its actual image size (regardless of the units specified here).
    """)

    h = DistanceSpec(default=None, help="""
    The height of the plot region that the image will occupy in data space.

    The default value is ``None``, in which case the image will be displayed
    at its actual image size (regardless of the units specified here).
    """)

    angle = AngleSpec(default=0, help="""
    The angles to rotate the images, as measured from the horizontal.
    """)

    global_alpha = Float(1.0, help="""
    An overall opacity that each image is rendered with (in addition
    to any inherent alpha values in the image itself).
    """)

    dilate = Bool(False, help="""
    Whether to always round fractional pixel locations in such a way
    as to make the images bigger.

    This setting may be useful if pixel rounding errors are causing
    images to have a gap between them, when they should appear flush.
    """)

    anchor = Enum(Anchor, help="""
    What position of the image should be anchored at the `x`, `y`
    coordinates.
    """)

    retry_attempts = Int(0, help="""
    Number of attempts to retry loading the images from the specified URL.
    Default is zero.
    """)

    retry_timeout = Int(0, help="""
    Timeout (in ms) between retry attempts to load the image from the
    specified URL. Default is zero ms.
    """)

class Line(XYGlyph):
    ''' Render a single line.

    The ``Line`` glyph is different from most other glyphs in that the vector
    of values only produces one glyph on the Plot.

    '''
    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y')

    __example__ = "examples/reference/models/Line.py"

    x = NumberSpec(help="""
    The x-coordinates for the points of the line.
    """)

    y = NumberSpec(help="""
    The y-coordinates for the points of the line.
    """)

    line_props = Include(ScalarLineProps, use_prefix=False, help="""
    The %s values for the line.
    """)

class MultiLine(Glyph):
    ''' Render several lines.

    The data for the ``MultiLine`` glyph is different in that the vector of
    values is not a vector of scalars. Rather, it is a "list of lists".

    '''

    __example__ = "examples/reference/models/MultiLine.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('xs', 'ys')

    xs = NumberSpec(help="""
    The x-coordinates for all the lines, given as a "list of lists".
    """)

    ys = NumberSpec(help="""
    The y-coordinates for all the lines, given as a "list of lists".
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the lines.
    """)

class MultiPolygons(Glyph):
    ''' Render several MultiPolygon.

    Modeled on geoJSON - the data for the ``MultiPolygons`` glyph is
    different in that the vector of values is not a vector of scalars.
    Rather, it is a "list of lists of lists of lists".
    '''

    __example__ = "examples/reference/models/MultiPolygons.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('xs', 'ys')

    xs = NumberSpec(help="""
    The x-coordinates for all the patches, given as a nested list.

    .. note::
        Each item in ``MultiPolygons`` represents one MultiPolygon and each
        MultiPolygon is comprised of ``n`` Polygons. Each Polygon is made of
        one exterior ring optionally followed by ``m`` interior rings (holes).
    """)

    ys = NumberSpec(help="""
    The y-coordinates for all the patches, given as a "list of lists".

    .. note::
        Each item in ``MultiPolygons`` represents one MultiPolygon and each
        MultiPolygon is comprised of ``n`` Polygons. Each Polygon is made of
        one exterior ring optionally followed by ``m`` interior rings (holes).
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the multipolygons.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the multipolygons.
    """)

class Oval(XYGlyph):
    ''' Render ovals.

    This glyph renders ovals using Bezier curves, which are similar,
    but not identical to ellipses. In particular, widths equal to heights
    will not render circles. Use the ``Ellipse`` glyph for that.

    '''

    __example__ = "examples/reference/models/Oval.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y', 'width', 'height', 'angle')

    x = NumberSpec(help="""
    The x-coordinates of the centers of the ovals.
    """)

    y = NumberSpec(help="""
    The y-coordinates of the centers of the ovals.
    """)

    width = DistanceSpec(help="""
    The overall widths of each oval.
    """)

    height = DistanceSpec(help="""
    The overall height of each oval.
    """)

    angle = AngleSpec(default=0.0, help="""
    The angle the ovals are rotated from horizontal. [rad]
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the ovals.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the ovals.
    """)

class Patch(XYGlyph):
    ''' Render a single patch.

    The ``Patch`` glyph is different from most other glyphs in that the vector
    of values only produces one glyph on the Plot.

    '''

    __example__ = "examples/reference/models/Patch.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y')

    x = NumberSpec(help="""
    The x-coordinates for the points of the patch.

    .. note::
        A patch may comprise multiple polygons. In this case the
        x-coordinates for each polygon should be separated by NaN
        values in the sequence.
    """)

    y = NumberSpec(help="""
    The y-coordinates for the points of the patch.

    .. note::
        A patch may comprise multiple polygons. In this case the
        y-coordinates for each polygon should be separated by NaN
        values in the sequence.
    """)

    line_props = Include(ScalarLineProps, use_prefix=False, help="""
    The %s values for the patch.
    """)

    fill_props = Include(ScalarFillProps, use_prefix=False, help="""
    The %s values for the patch.
    """)

class Patches(Glyph):
    ''' Render several patches.

    The data for the ``Patches`` glyph is different in that the vector of
    values is not a vector of scalars. Rather, it is a "list of lists".

    '''

    __example__ = "examples/reference/models/Patches.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('xs', 'ys')

    xs = NumberSpec(help="""
    The x-coordinates for all the patches, given as a "list of lists".

    .. note::
        Individual patches may comprise multiple polygons. In this case
        the x-coordinates for each polygon should be separated by NaN
        values in the sublists.
    """)

    ys = NumberSpec(help="""
    The y-coordinates for all the patches, given as a "list of lists".

    .. note::
        Individual patches may comprise multiple polygons. In this case
        the y-coordinates for each polygon should be separated by NaN
        values in the sublists.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the patches.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the patches.
    """)

class Quad(Glyph):
    ''' Render axis-aligned quads.

    '''

    __example__ = "examples/reference/models/Quad.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('left', 'right', 'top', 'bottom')

    left = NumberSpec(help="""
    The x-coordinates of the left edges.
    """)

    right = NumberSpec(help="""
    The x-coordinates of the right edges.
    """)

    bottom = NumberSpec(help="""
    The y-coordinates of the bottom edges.
    """)

    top = NumberSpec(help="""
    The y-coordinates of the top edges.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the quads.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the quads.
    """)

class Quadratic(Glyph):
    ''' Render parabolas.

    '''

    __example__ = "examples/reference/models/Quadratic.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x0', 'y0', 'x1', 'y1', 'cx', 'cy')

    x0 = NumberSpec(help="""
    The x-coordinates of the starting points.
    """)

    y0 = NumberSpec(help="""
    The y-coordinates of the starting points.
    """)

    x1 = NumberSpec(help="""
    The x-coordinates of the ending points.
    """)

    y1 = NumberSpec(help="""
    The y-coordinates of the ending points.
    """)

    cx = NumberSpec(help="""
    The x-coordinates of the control points.
    """)

    cy = NumberSpec(help="""
    The y-coordinates of the control points.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the parabolas.
    """)

class Ray(XYGlyph):
    ''' Render rays.

    '''

    __example__ = "examples/reference/models/Ray.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y', 'length', 'angle')

    x = NumberSpec(help="""
    The x-coordinates to start the rays.
    """)

    y = NumberSpec(help="""
    The y-coordinates to start the rays.
    """)

    angle = AngleSpec(help="""
    The angles in radians to extend the rays, as measured from the horizontal.
    """)

    length = DistanceSpec(help="""
    The length to extend the ray. Note that this ``length`` defaults
    to data units (measured in the x-direction).
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the rays.
    """)

class Rect(XYGlyph):
    ''' Render rectangles.

    '''

    __example__ = "examples/reference/models/Rect.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y', 'width', 'height', 'angle', 'dilate')

    x = NumberSpec(help="""
    The x-coordinates of the centers of the rectangles.
    """)

    y = NumberSpec(help="""
    The y-coordinates of the centers of the rectangles.
    """)

    width = DistanceSpec(help="""
    The overall widths of the rectangles.
    """)

    height = DistanceSpec(help="""
    The overall heights of the rectangles.
    """)

    angle = AngleSpec(default=0.0, help="""
    The angles to rotate the rectangles, as measured from the horizontal.
    """)

    dilate = Bool(False, help="""
    Whether to always round fractional pixel locations in such a way
    as to make the rectangles bigger.

    This setting may be useful if pixel rounding errors are causing
    rectangles to have a gap between them, when they should appear
    flush.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the rectangles.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the rectangles.
    """)

class Segment(Glyph):
    ''' Render segments.

    '''

    __example__ = "examples/reference/models/Segment.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x0', 'y0', 'x1', 'y1')

    x0 = NumberSpec(help="""
    The x-coordinates of the starting points.
    """)

    y0 = NumberSpec(help="""
    The y-coordinates of the starting points.
    """)

    x1 = NumberSpec(help="""
    The x-coordinates of the ending points.
    """)

    y1 = NumberSpec(help="""
    The y-coordinates of the ending points.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the segments.
    """)

class Step(XYGlyph):
    ''' Render step lines.

    Step levels can be draw before, after, or centered on each point, according
    to the value of the ``mode`` property.

    The x-coordinates are assumed to be (and must be) sorted in ascending order
    for steps to be properly rendered.

    '''

    __example__ = "examples/reference/models/Step.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y')

    x = NumberSpec(help="""
    The x-coordinates for the steps.
    """)

    y = NumberSpec(help="""
    The y-coordinates for the steps.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the steps.
    """)

    mode = Enum(StepMode, default="before", help="""
    Where the step "level" should be drawn in relation to the x and y
    coordinates. The parameter can assume one of three values:

    * ``before``: (default) Draw step levels before each x-coordinate (no step before the first point)
    * ``after``:  Draw step levels after each x-coordinate (no step after the last point)
    * ``center``: Draw step levels centered on each x-coordinate
    """)

class Text(XYGlyph):
    ''' Render text.

    '''

    __example__ = "examples/reference/models/Text.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y', 'text', 'angle', 'x_offset', 'y_offset')

    x = NumberSpec(help="""
    The x-coordinates to locate the text anchors.
    """)

    y = NumberSpec(help="""
    The y-coordinates to locate the text anchors.
    """)

    text = StringSpec("text", help="""
    The text values to render.
    """)

    angle = AngleSpec(default=0, help="""
    The angles to rotate the text, as measured from the horizontal.
    """)

    x_offset = NumberSpec(default=0, help="""
    Offset values to apply to the x-coordinates.

    This is useful, for instance, if it is desired to "float" text a fixed
    distance in screen units from a given data position.
    """)

    y_offset = NumberSpec(default=0, help="""
    Offset values to apply to the y-coordinates.

    This is useful, for instance, if it is desired to "float" text a fixed
    distance in screen units from a given data position.
    """)

    text_props = Include(TextProps, use_prefix=False, help="""
    The %s values for the text.
    """)

class VBar(Glyph):
    ''' Render vertical bars, given a center coordinate, width and (top, bottom) coordinates.

    '''

    __example__ = "examples/reference/models/VBar.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'width', 'top', 'bottom')

    x = NumberSpec(help="""
    The x-coordinates of the centers of the vertical bars.
    """)

    width = NumberSpec(help="""
    The widths of the vertical bars.
    """)

    bottom = NumberSpec(default=0, help="""
    The y-coordinates of the bottom edges.
    """)

    top = NumberSpec(help="""
    The y-coordinates of the top edges.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the vertical bars.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the vertical bars.
    """)

class Wedge(XYGlyph):
    ''' Render wedges.

    '''

    __example__ = "examples/reference/models/Wedge.py"

    # a canonical order for positional args that can be used for any
    # functions derived from this class
    _args = ('x', 'y', 'radius', 'start_angle', 'end_angle', 'direction')

    x = NumberSpec(help="""
    The x-coordinates of the points of the wedges.
    """)

    y = NumberSpec(help="""
    The y-coordinates of the points of the wedges.
    """)

    radius = DistanceSpec(help="""
    Radii of the wedges.
    """)

    start_angle = AngleSpec(help="""
    The angles to start the wedges, as measured from the horizontal.
    """)

    end_angle = AngleSpec(help="""
    The angles to end the wedges, as measured from the horizontal.
    """)

    direction = Enum(Direction, default='anticlock', help="""
    Which direction to stroke between the start and end angles.
    """)

    line_props = Include(LineProps, use_prefix=False, help="""
    The %s values for the wedges.
    """)

    fill_props = Include(FillProps, use_prefix=False, help="""
    The %s values for the wedges.
    """)

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------

# XXX: allow `from bokeh.models.glyphs import *`
from .markers import (Asterisk, Circle, CircleCross, CircleX, Cross, Dash,
                      Diamond, DiamondCross, Hex, InvertedTriangle, Marker,
                      Square, SquareCross, SquareX, Triangle, X)

# Fool pyflakes
(Asterisk, Circle, CircleCross, CircleX, Cross, Dash, Diamond, DiamondCross,
Hex, InvertedTriangle, Marker, Square, SquareCross, SquareX, Triangle, X)


text:
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<!--
		ProcessEngineConfiguration configuration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
		//数据库配置
		configuration.setJdbcDriver("com.mysql.jdbc.Driver");
		configuration.setJdbcUrl("jdbc:mysql://localhost:3306/itcast0621activiti?useUnicode=true&characterEncoding=utf8");
		configuration.setJdbcUsername("root");
		configuration.setJdbcPassword("root");
		configuration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
	 -->
	<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">
		<property name="jdbcDriver" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/itcast0621activiti?useUnicode=true&characterEncoding=utf8"></property>
		<property name="jdbcUsername" value="root"></property>
		<property name="jdbcPassword" value="root"></property>
		<property name="databaseSchemaUpdate" value="true"></property>
	</bean>
</beans>


text:
import {
  build,
  indent,
  ISelectBuilder,
  ISelectOrBuilder,
  ISelectSchema,
  Select
} from "df/sql/builders/select";

export class UnionBuilder<S extends ISelectSchema> implements ISelectBuilder<S> {
  constructor(private selects: Array<ISelectOrBuilder<S>>) {}

  public build() {
    // TODO: Check all columns have the same values for a union.
    return Select.create<S>(
      `(
${indent(
  this.selects.map(select => build(select).query).join(`
union all
`)
)}
)`
    );
  }
}


text:
"""
Created on Mar 15, 2012

@author: haddaway, moloch

    Copyright 2012 Root the Box

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

import logging

from libs.SecurityDecorators import *
from libs.EventManager import EventManager
from handlers.BaseHandlers import BaseHandler, BaseWebSocketHandler

class NotifySocketHandler(BaseWebSocketHandler):

    """Handles websocket connections"""

    event_manager = EventManager.instance()

    def open(self):
        """When we receive a new websocket connect"""
        self.event_manager.add_connection(self)
        if self.session is not None and "team_id" in self.session:
            logging.debug(
                "Opened new websocket with user id: %s" % (self.session["user_id"],)
            )
            self.io_loop.add_callback(
                self.event_manager.push_user, self.team_id, self.user_id
            )
        else:
            logging.debug("[Web Socket] Opened public notification socket.")

    def on_close(self):
        """Lost connection to client"""
        self.event_manager.remove_connection(self)

    @property
    def team_id(self):
        if self.session is not None and "team_id" in self.session:
            return self.session["team_id"]

    @team_id.setter
    def team_id(self, value):
        raise ValueError("Cannot set team_id")

    @property
    def user_id(self):
        if self.session is not None and "user_id" in self.session:
            return self.session["user_id"]

    @user_id.setter
    def user_id(self, value):
        raise ValueError("Cannot set user_id")

class AllNotificationsHandler(BaseHandler):
    @authenticated
    def get(self, *args, **kwargs):
        user = self.get_current_user()
        self.render("notifications/view.html", user=user)


text:
#include "gtest/gtest.h"
#include "libyarnclient/LibYarnClientC.h"

class TestLibYarnClientC: public ::testing::Test {
public:
	TestLibYarnClientC(){
		char *user = "postgres";
		char *rmHost = "localhost";
		char *rmPort = "8032";
		char *schedHost = "localhost";
		char *schedPort = "8030";
		char *amHost = "localhost";
		int32_t amPort = 0;
		char *am_tracking_url = "url";
		int heartbeatInterval = 1000;
		client = NULL;
		result = newLibYarnClient(user, rmHost, rmPort, schedHost, schedPort, amHost, amPort, am_tracking_url, &client, heartbeatInterval);
	}
	~TestLibYarnClientC(){
	}
protected:
	LibYarnClient_t *client;
	int result;
	int i;
};

TEST_F(TestLibYarnClientC,TestLibYarn){
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);

	char *jobName = "libyarn";
	char *queue = "default";
	char *jobId = NULL;
	result = createJob(client, jobName, queue, &jobId);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);

	LibYarnNodeReport_t *nodeReportArray;
	int nodeReportArraySize;
	result = getClusterNodes(client, NODE_STATE_RUNNING, &nodeReportArray, &nodeReportArraySize);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);
	EXPECT_GT(nodeReportArraySize, 0);

	char *localhost = strdup(nodeReportArray[0].host);

	freeMemNodeReportArray(nodeReportArray, nodeReportArraySize);

	char *blackListAdditions[0];
	char *blackListRemovals[0];
	LibYarnNodeInfo_t preferredHosts[1];
	preferredHosts[0].hostname = localhost;
	preferredHosts[0].rackname = "/default-rack";
	preferredHosts[0].num_containers = 2;
	int preferredHostSize = 1;
	LibYarnResource_t *allocatedResourcesArray;
	int allocatedResourcesArraySize;
	result = allocateResources(client, jobId, 1, 1, 1024, 5,
					blackListAdditions, 0, blackListRemovals, 0, preferredHosts, preferredHostSize,
					&allocatedResourcesArray, &allocatedResourcesArraySize);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);

	int64_t activeContainerIds[allocatedResourcesArraySize];
	int64_t releaseContainerIds[allocatedResourcesArraySize];
	int64_t statusContainerIds[allocatedResourcesArraySize];
	for (i = 0 ; i < allocatedResourcesArraySize; i++) {
		activeContainerIds[i] = allocatedResourcesArray[i].containerId;
		releaseContainerIds[i] = allocatedResourcesArray[i].containerId;
		statusContainerIds[i] = allocatedResourcesArray[i].containerId;
	}

	result = activeResources(client, jobId, activeContainerIds, allocatedResourcesArraySize);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);

	freeMemAllocatedResourcesArray(allocatedResourcesArray, allocatedResourcesArraySize);

	sleep(10);

	int64_t *activeFailIds;
	int activeFailSize;
	result = getActiveFailContainerIds(client,&activeFailIds,&activeFailSize);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);
	EXPECT_EQ(activeFailSize, 0);

	LibYarnApplicationReport_t *applicationReport;
	result = getApplicationReport(client, jobId, &applicationReport);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);

	freeApplicationReport(applicationReport);

	LibYarnContainerReport_t *containerReportArray;
	int containerReportArraySize;
	result = getContainerReports(client, jobId, &containerReportArray, &containerReportArraySize);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);
	EXPECT_EQ(containerReportArraySize, 5);

	freeContainerReportArray(containerReportArray, containerReportArraySize);

	LibYarnContainerStatus_t *containerStatusArray;
	int containerStatusArraySize;
	result = getContainerStatuses(client, jobId, statusContainerIds,
					allocatedResourcesArraySize, &containerStatusArray,
					&containerStatusArraySize);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);
	EXPECT_EQ(containerReportArraySize, 5);

	freeContainerStatusArray(containerStatusArray, containerStatusArraySize);

	result = releaseResources(client, jobId, releaseContainerIds, allocatedResourcesArraySize);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);

	LibYarnQueueInfo_t *queueInfo = NULL;
	result = getQueueInfo(client, queue, true, true, true, &queueInfo);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);

	freeMemQueueInfo(queueInfo);

	result = finishJob(client, jobId, APPLICATION_SUCCEEDED);
	EXPECT_EQ(result, FUNCTION_SUCCEEDED);
}


text: <button type="button" class="close" data-dismiss="modal">×</button>


text:
/* global config, module, path, project */

module.exports = function(grunt) {
	grunt.registerTask('configScript', function() {
		// Core scripts
		if (project.script.core.enable === true) {
			var features = project.script.core.features,
				weeScriptRoot = config.paths.assets + '/wee/script/';

			config.script.files.push(weeScriptRoot + 'wee.js');

			// Set global data variables
			if (
				(project.data && Object.keys(project.data).length) ||
				(project.script.data && Object.keys(project.script.data).length)
			) {
				var weeScriptGlobal = config.paths.temp + '/data.js',
					configVars = Wee.$extend(project.data, project.script.data || {}),
					script = 'Wee.$set("global", ' + JSON.stringify(configVars) + ');';

				grunt.file.write(weeScriptGlobal, script);

				config.script.files.push(weeScriptGlobal);
			}

			if (features.chain === true) {
				config.script.files.push(weeScriptRoot + 'wee.chain.js');
			}

			if (features.assets === true) {
				config.script.files.push(weeScriptRoot + 'wee.assets.js');
			}

			if (features.data === true) {
				config.script.files.push(weeScriptRoot + 'wee.data.js');
			}

			if (features.dom === true) {
				config.script.files.push(weeScriptRoot + 'wee.dom.js');

				if (features.chain === true) {
					config.script.files.push(weeScriptRoot + 'chain/wee.chain.dom.js');
				}
			}

			if (features.events === true) {
				config.script.files.push(weeScriptRoot + 'wee.events.js');

				if (features.chain === true) {
					config.script.files.push(weeScriptRoot + 'chain/wee.chain.events.js');
				}
			}

			if (features.routes === true) {
				config.script.files.push(weeScriptRoot + 'wee.routes.js');
			}

			if (features.screen === true) {
				config.script.files.push(weeScriptRoot + 'wee.screen.js');
			}

			if (features.view === true) {
				config.script.files.push(weeScriptRoot + 'wee.view.js');

				if (features.chain === true) {
					config.script.files.push(weeScriptRoot + 'chain/wee.chain.view.js');
				}
			}
		}

		// Build/vendor directory scripts
		config.script.files.push(config.paths.js + '/build/vendor/**/*.js');

		// Remaining build directory scripts
		config.script.files.push(config.paths.js + '/build/**/*.js');

		// Project.config file build files
		project.script.build.forEach(function(name) {
			config.script.files.push(Wee.buildPath(config.paths.js, name));
		});

		// Custom/script.js file
		config.script.files.push(config.paths.js + '/custom/script.js');

		// Compile custom
		for (var target in project.script.compile) {
			var taskName = target.replace(/\./g, '-') + '-script',
				sources = project.script.compile[target],
				src = [];

			if (sources instanceof Array) {
				for (var source in sources) {
					src.push(Wee.buildPath(config.paths.js, sources[source]));
				}
			} else {
				src = Wee.buildPath(config.paths.js, sources);
			}

			// Merge watch config
			grunt.config.set('watch.' + taskName, {
				files: src,
				tasks: [
					'uglify:' + taskName
				]
			});

			// Create uglify task
			grunt.config.set('uglify.' + taskName, {
				files: [{
					dest: Wee.buildPath(config.paths.js, target),
					src: src
				}]
			});

			// Run task
			grunt.task.run('uglify:' + taskName);
		}

		// Configure source maps
		if (project.script.sourceMaps === true) {
			grunt.config.set('uglify.options.sourceMap', true);
			grunt.config.set('uglify.options.sourceMapName', function(dest) {
				var scriptRoot = path.normalize(config.paths.js),
					moduleRoot = path.normalize(config.paths.modules);
				dest = path.normalize(dest)
					.replace(scriptRoot, '')
					.replace(moduleRoot, '')
					.replace(/^\\|\//, '')
					.replace(/\\|\//g, '-')
					.replace('.min.js', '');

				return path.join(config.paths.maps, dest + '.js.map');
			});
		}
	});
};


text:
namespace PetCenter.Referencias.Dominio.Logica.Entidades
{
    using System;
    using System.Collections.Generic;
    using PetCenter.Referencias.Dominio.Logica.Base;

    public partial class GG_Moneda : EntidadBase
    {
        public int IdMoneda { get; set; }

        public string DesMoneda { get; set; }

        public override string NombreEntidad { get { return "GG_Moneda"; } }
    }

}


text:
describe('http.oauth1', function() {
  'use strict';
  var now = new Date().getTime();

  beforeEach(module('httpu.oauth1'));

  beforeEach(module(function($provide) {
    sandbox.useFakeTimers(now);
    $provide.decorator('$window', function($delegate) {
      $delegate.oauthSignature = {
        generate: function() {
          return 'testsignature';
        }
      };
      $delegate.Math.random = function() {
        return 0;
      };
      return $delegate;
    });
    $provide.factory('myOAuthInterceptor', ['huOAuth1InterceptorFactory',
      function(huOAuth1InterceptorFactory) {
        return huOAuth1InterceptorFactory();
      }]);
  }));

  describe('with default config', function() {
    beforeEach(module(function($httpProvider) {
      $httpProvider.interceptors.push('myOAuthInterceptor');
    }));

    it('should sign the request', inject(function($httpBackend, $http) {
      $httpBackend.expectGET('/?' + [
        'oauth_consumer_key=key',
        'oauth_nonce=00000000000',
        'oauth_signature=testsignature',
        'oauth_signature_method=HMAC-SHA1',
        'oauth_timestamp=' + Math.floor(now / 1000),
        'oauth_version=1.0'
      ].join('&')).respond(200, 'OK');

      $http.get('/', {
        oauth1: {
          consumerKey: 'key',
          consumerSecret: 'secret'
        }
      });

      $httpBackend.flush();
    }));

    it('should do nothing with no oauth config', inject(function($httpBackend, $http) {
      $httpBackend.expectGET('/').respond(200, 'OK');
      $http.get('/');
      $httpBackend.flush();
    }));

    it('should reject with invalid config', inject(function($timeout, $http) {
      $http.get('/', {
        oauth1: {}
      }).catch(function(response) {
        expect(response.error.message).to.be.eql('MissingKeySecret');
      });
      $timeout.flush();
    }));
  });

  describe('with custom timestamp getter', function() {

    it('should fail sign the request', function() {
      module(function($provide, $httpProvider) {
        $provide.factory('testGetTimestamp', ['$q', function($q) {
          return function() {
            return $q.reject(new Error('TestFail'));
          };
        }]);
        $httpProvider.interceptors.push(['huOAuth1InterceptorFactory',
          function(huOAuth1InterceptorFactory) {
            return huOAuth1InterceptorFactory({
              getTimestamp: 'testGetTimestamp'
            });
          }]);
      });

      inject(function($timeout, $http) {
        $http.get('/', {
          oauth1: {
            consumerKey: 'key',
            consumerSecret: 'secret'
          }
        }).catch(function(response) {
          expect(response.error.message).to.be.eql('TestFail');
        });
        $timeout.flush();
      });
    });
  });
});


text:
#region Copyright

#endregion

#region

using Autodesk.DesignScript.Runtime;
using Dynamo.Models;
using System.Collections.Generic;
using Dynamo.Nodes;
using Wosad.Loads.ASCE7.Entities;
using Wosad.Loads.ASCE.ASCE7_10.WindLoads.Building.DirectionalProcedure.MWFRS;
using Wosad.Common.CalculationLogger;
using Dynamo.Graph.Nodes;
using System;

#endregion

namespace Loads.ASCE7.Lateral.Wind
{

/// <summary>
///     External pressure coefficient (MWFRS)
///     Category:   Loads.ASCE7v10.Lateral.Wind
/// </summary>
///

    public partial class PressureCoefficient
    {
        /// <summary>
        ///     External pressure coefficient  used in calculation of wind loads on Main Wind-Force Resisting System (MWFRS) elements .
        /// </summary>
        /// <param name="B">  Horizontal dimension of building measured normal to wind direction </param>
        /// <param name="L">  Horizontal dimension of a building measured parallel to the wind direction </param>
        /// <param name="WindFaceType">  Type of face relative to wind direction (windward, leeward or side)  </param>
        /// <param name="Code"> Applicable version of code/standard</param>
        /// <returns name="C_p"> External pressure coefficient to be used in determination of wind loads for buildings </returns>

        [MultiReturn(new[] { "C_p" })]
        public static Dictionary<string, object> ExternalPressureCoefficientMWFRS(double B, double L, string WindFaceType, string Code = "ASCE7-10")
        {
            //Default values
            double C_p = 0;

            //Calculation logic:
            WindFace face;

            bool IsValidStringFaceType = Enum.TryParse(WindFaceType, true, out face);
            if (IsValidStringFaceType == false)
            {
                throw new Exception("Wind face type is not recognized. Use Windward, Leeward or Side. Check input string.");
            }

            CalcLog Log = new CalcLog();
            Mwfrs Mwfrs = new Mwfrs(Log);
            C_p = Mwfrs.GetWallPressureCoefficient(face, B, L);

            return new Dictionary<string, object>
            {
                { "C_p", C_p }

            };
        }

    }
}