text:
package definition

import (
	"context"
	"fmt"
	"reflect"
)

// MIME types
const (
	// acceptTypeAll indicates a accept type from http request.
	// It means client can receive any content.
	// Request content type in header "Content-Type" must not set to "*/*".
	// It only can exist in request header "Accept".
	// In most time, it locate at the last element of "Accept".
	// It's default value if client have not set "Accept" header.
	MIMEAll         = "*/*"
	MIMENone        = ""
	MIMEText        = "text/plain"
	MIMEJSON        = "application/json"
	MIMEXML         = "application/xml"
	MIMEOctetStream = "application/octet-stream"
	MIMEURLEncoded  = "application/x-www-form-urlencoded"
	MIMEFormData    = "multipart/form-data"
)

// DataErrorResults returns the most frequently-used results.
// Definition function should have two results. The first is
// any type for data, and the last is error.
func DataErrorResults(description string) []Result {
	return []Result{
		{
			Destination: Data,
			Description: description,
		},
		{
			Destination: Error,
		},
	}
}

// ParameterFor creates a simple parameter.
func ParameterFor(source Source, name string, description string) Parameter {
	return Parameter{
		Source:      source,
		Name:        name,
		Description: description,
	}
}

// PathParameterFor creates a path parameter
func PathParameterFor(name string, description string) Parameter {
	return ParameterFor(Path, name, description)
}

// QueryParameterFor creates a query parameter
func QueryParameterFor(name string, description string) Parameter {
	return ParameterFor(Query, name, description)
}

// HeaderParameterFor creates a header parameter
func HeaderParameterFor(name string, description string) Parameter {
	return ParameterFor(Header, name, description)
}

// FormParameterFor creates a form parameter
func FormParameterFor(name string, description string) Parameter {
	return ParameterFor(Form, name, description)
}

// FileParameterFor creates a file parameter
func FileParameterFor(name string, description string) Parameter {
	return ParameterFor(File, name, description)
}

// BodyParameterFor creates a body parameter
func BodyParameterFor(description string) Parameter {
	return ParameterFor(Body, "", description)
}

// PrefabParameterFor creates a prefab parameter
func PrefabParameterFor(name string, description string) Parameter {
	return ParameterFor(Prefab, name, description)
}

// AutoParameterFor creates an auto parameter
func AutoParameterFor(description string) Parameter {
	return ParameterFor(Auto, "", description)
}

// ResultFor creates a simple result.
func ResultFor(dest Destination, description string) Result {
	return Result{
		Destination: dest,
		Description: description,
	}
}

// MetaResultFor creates meta result.
func MetaResultFor(description string) Result {
	return ResultFor(Meta, description)
}

// DataResultFor creates data result.
func DataResultFor(description string) Result {
	return ResultFor(Data, description)
}

// ErrorResult creates error result.
func ErrorResult() Result {
	return ResultFor(Error, "")
}

// OperatorFunc creates operator by function.
// function must has signature:
//  func f(context.Context, string, AnyType) (AnyType, error)
// The second parameter is a string that is used to identify field.
// AnyType can be any type in go. But struct type and
// built-in data type is recommended.
func OperatorFunc(kind string, f interface{}) Operator {
	typ := reflect.TypeOf(f)
	if typ.Kind() != reflect.Func {
		panic(fmt.Sprintf("Parameter f in OperatorFunc must be a function, but got: %s", typ.Kind()))
	}
	if typ.NumIn() != 3 {
		panic(fmt.Sprintf("Function must have 3 parameters, but got: %d", typ.NumIn()))
	}
	if typ.In(0) != reflect.TypeOf((*context.Context)(nil)).Elem() {
		panic(fmt.Sprintf("The first parameter of function must be context.Context, but got: %v", typ.In(0)))
	}
	if typ.In(1) != reflect.TypeOf("") {
		panic(fmt.Sprintf("The second parameter of function must be string, but got: %v", typ.In(0)))
	}
	if typ.NumOut() != 2 {
		panic(fmt.Sprintf("Parameter f in OperatorFunc must have two results, but got: %d", typ.NumOut()))
	}
	if typ.Out(1).String() != "error" {
		panic(fmt.Sprintf("The last result of parameter f in OperatorFunc must be error, but got: %v", typ.Out(1)))
	}
	return &operatorRef{
		kind:  kind,
		in:    typ.In(2),
		out:   typ.Out(0),
		value: reflect.ValueOf(f),
	}
}

// NewOperator creates operator by function.
// function must has signature:
//  func f(context.Context, AnyType) (AnyType, error)
// AnyType can be any type in go. But struct type and
// built-in data type is recommended.
func NewOperator(kind string, in, out reflect.Type, f func(ctx context.Context, field string, object interface{}) (interface{}, error)) Operator {
	return &operator{
		kind: kind,
		in:   in,
		out:  out,
		f:    f,
	}
}

type operator struct {
	kind string
	in   reflect.Type
	out  reflect.Type
	f    func(ctx context.Context, field string, object interface{}) (interface{}, error)
}

// Kind indicates operator type.
func (o *operator) Kind() string {
	return o.kind
}

// In returns the type of the only object parameter of operator.
func (o *operator) In() reflect.Type {
	return o.in
}

// Out returns the type of the only object result of operator.
func (o *operator) Out() reflect.Type {
	return o.out
}

// Operate operates an object and return one.
func (o *operator) Operate(ctx context.Context, field string, object interface{}) (interface{}, error) {
	return o.f(ctx, field, object)
}

type operatorRef struct {
	kind  string
	in    reflect.Type
	out   reflect.Type
	value reflect.Value
}

// Kind indicates operator type.
func (o *operatorRef) Kind() string {
	return o.kind
}

// In returns the type of the only object parameter of operator.
func (o *operatorRef) In() reflect.Type {
	return o.in
}

// Out returns the type of the only object result of operator.
func (o *operatorRef) Out() reflect.Type {
	return o.out
}

// Operate operates an object and return one.
func (o *operatorRef) Operate(ctx context.Context, field string, object interface{}) (interface{}, error) {
	var objectValue reflect.Value
	if object == nil {
		objectValue = reflect.Zero(o.in)
	} else {
		objectValue = reflect.ValueOf(object)
	}

	results := o.value.Call([]reflect.Value{reflect.ValueOf(ctx), reflect.ValueOf(field), objectValue})
	v := results[1]
	if v.IsNil() {
		return results[0].Interface(), nil
	}
	return nil, results[1].Interface().(error)
}

// SimpleDescriptor creates a simple descriptor for handler.
// The descriptor consumes all content types and produces all
// accept types.
func SimpleDescriptor(method Method, path string, f interface{}) Descriptor {
	return Descriptor{
		Path: path,
		Definitions: []Definition{
			{
				Method:   method,
				Function: f,
				Consumes: []string{MIMEAll},
				Produces: []string{MIMEAll},
			},
		},
	}

}


text:
const { run } = require('./src/runner');
const { runFile } = require('./src/file-runner');

exports.run = run;
exports.runFile = runFile;

redpajama_set_name: RedPajamaGithub


text:
"""
DB Controller for web_app
"""
from models import *
import requests
import json
import authentication
from envs import *

"""******** Generics ********"""

def save_entity(entity):
    entity.save()

"""******** Devices ********"""

def get_devices(**db_filter):
    return Device.objects.all().filter(**db_filter)

def get_first_device(**db_filters):
    m_list = Device.objects.all().filter(**db_filters)
    if len(m_list) == 0:
        return None
    return m_list[0]

def add_device(**kwargs):
    Device(**kwargs).save()

def delete_device(device_id):
    m_list = Device.objects.filter(id=device_id)
    if len(m_list) == 1:
        m_list[0].delete()
    else:
        raise Exception("Not existing model or not unique identifier")

"""******** Models ********"""

def get_models(**db_filter):
    return DeviceModel.objects.all().filter(**db_filter)

def get_first_model(**db_filters):
    m_list = DeviceModel.objects.all().filter(**db_filters)
    if len(m_list) == 0:
        return None
    return m_list[0]

def add_model(**kwargs):
        DeviceModel(**kwargs).save()

def delete_model(model_id):
    m_list = DeviceModel.objects.filter(id=model_id)
    if len(m_list) == 1:
        m_list[0].delete()
    else:
        raise Exception("Not existing model or not unique identifier")


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

<LinearLayout
    android:id="@+id/ll_theme_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/bg_white"
    android:orientation="vertical"
    android:padding="@dimen/margin_16dp">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="今天是七夕节..."
        android:textColor="@color/primary_text"
        android:textSize="18sp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:layout_marginTop="12dp"
        android:background="@color/divider"/>

    <TextView
        android:id="@+id/tv_from"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="然并卵..."
        android:textColor="@color/secondary_text"
        android:textSize="10sp"/>

</LinearLayout>


text:
import time
import requests
import base64
import types
import re
import warnings

class Sabre(object):
    token = None
    APIS = {
        'v1.shop.flights.fares' : ('GET', '/v1/shop/flights/fares', 'Lead Price Calendar API'),
        'v1.historical.shop.flights.fares' : ('GET', '/v1/historical/shop/flights/fares', 'Low Fare History API'),
        'v1.lists.supported.shop.flights.origins.destinations' : ('GET', '/v1/lists/supported/shop/flights/origins-destinations', 'City Pairs Lookup API'),
        'v1.shop.calendar.flights' : ('POST', '/v1.8.1/shop/calendar/flights', 'Advanced Calendar Search API'),
        'v1.lists.supported.pointofsalecountries' : ('GET', '/v1/lists/supported/pointofsalecountries', 'Point of Sale Country Code Lookup API'),
        'v1.lists.supported.shop.themes.theme' : ('GET', '/v1/lists/supported/shop/themes/{theme}', 'Theme Airport Lookup API'),
        'v1.auth.token' : ('POST', '/v1/auth/token', 'Authentication Request'),
        'v1.lists.utilities.airlines.alliances' : ('GET', '/v1/lists/utilities/airlines/alliances/', 'Airline Alliance Lookup API'),
        'v1.historical.flights.fares' : ('GET', '/v1/historical/flights/fares', 'Fare Range API'),
        'v1.forecast.flights.fares' : ('GET', '/v1/forecast/flights/fares', 'Low Fare Forecast API'),
        'v1.lists.supported.cities' : ('GET', '/v1/lists/supported/cities', 'Multi-Airport City Lookup API'),
        'v1.lists.top.destinations' : ('GET', '/v1/lists/top/destinations', 'Top Destinations API'),
        'v1.lists.supported.countries' : ('GET', '/v1/lists/supported/countries', 'Countries Lookup API'),
        'v1.lists.supported.cities.airports' : ('GET', '/v1/lists/supported/cities/{city}/airports/', 'Airports at Cities Lookup API'),
        'v1.shop.altdates.flights' : ('POST', '/v1.8.6/shop/altdates/flights', 'Alternate Date API'),
        'v1.lists.supported.shop.themes' : ('GET', '/v1/lists/supported/shop/themes/', 'Travel Theme Lookup API'),
        'v1.lists.supported.historical.seasonality.airports' : ('GET', '/v1/lists/supported/historical/seasonality/airports', 'Travel Seasonality Airports Lookup API'),
        'v2.shop.cars' : ('POST', '/v2.4.0/shop/cars', 'Car Availability (beta) API'),
        'v3.book.flights.seatmaps' : ('POST', '/v3.0.0/book/flights/seatmaps?mode=seatmaps', 'Seat Map (beta) API'),
        'v1.historical.flights.destination.seasonality' : ('GET', '/v1/historical/flights/{destination}/seasonality', 'Travel Seasonality API'),
        'v1.lists.utilities.airlines.' : ('GET', '/v1/lists/utilities/airlines/', 'Airline Lookup API'),
        'v1.lists.utilities.aircraft.equipment' : ('GET', '/v1/lists/utilities/aircraft/equipment/', 'Aircraft Equipment Lookup API'),
        'v1.shop.flights' : ('GET', '/v1/shop/flights', 'InstaFlights Search API'),
    }

    def __init__(self, client_id, client_secret, server='https://api.test.sabre.com'):
        self.client_id = client_id
        self.client_secret = client_secret
        self.server = server
        self.credentials = self.encode_credentials()

        class Container(object):
            def __call__(self, *args, **kwargs):
                return self._call(self.endpoint, *args, **kwargs)

        self.api = Container()

        for api_name, (method, endpoint, description) in self.APIS.items():
            parts = api_name.split('.')
            obj = self.api
            for part in parts:
                if getattr(obj, part, None) is None:
                    setattr(obj, part, Container())
                obj = getattr(obj, part)

            def fn(s, endpoint, *args, **kwargs):
                e = endpoint
                if '{' in endpoint:
                    e = endpoint.format(**kwargs)
                    for arg in re.findall(r'{(\w+)}', endpoint):
                        del kwargs[arg]

                if method == 'GET':
                    kwargs = {"params": kwargs}
                else:
                    kwargs = {"data": kwargs}

                result = self.call_method(method.lower(), self.server + e, *args, **kwargs)
                assert result.status_code is 200, u"Got a {} (expecting 200): {}".format(result.status_code, result.json())
                return result.json()

            obj.endpoint = endpoint
            obj._call = types.MethodType(fn, obj, Container)

    def is_valid(self):
        self.last_check = time.time()
        if self.token and self.token['expires'] < self.last_check:
            return True
        return False

    def get_token(self):
        if self.is_valid():
            return self.token
        headers = {'Authorization': 'Basic ' + self.credentials}
        params = {'grant_type': 'client_credentials'}
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = requests.post(self.server + '/v1/auth/token', headers=headers, data=params)
        assert r.status_code is 200, 'Expecting 200 answer, got {} instead'.format(r.status_code)
        self.token = r.json()
        self.token['expires'] = self.last_check + self.token['expires_in']
        return self.token

    def encode_credentials(self):
        return base64.b64encode("{client_id}:{client_secret}".format(
                   client_id=base64.b64encode(self.client_id),
                   client_secret=base64.b64encode(self.client_secret)))

    def call_method(self, method, *args, **kwargs):
        if kwargs is None:
            kwargs = {}
        kwargs['headers'] = kwargs.get('headers', {})
        kwargs['headers'].update(Authorization='Bearer ' + self.get_token()[u'access_token'])
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            return getattr(requests, method)(*args, **kwargs)

    def get(self, *args, **kwargs):
        return self.call_method('get', *args, **kwargs)

    def post(self, *args, **kwargs):
        return self.call_method('post', *args, **kwargs)

    def api_list(self):
        for api_name, (method, endpoint, description) in self.APIS.items():
            print(u"{}: {} (endpoint: {} {})".format(api_name, description, method, endpoint))


text:
Craft Commerce Quickpay Gateway plugin

![Screenshot](resources/screenshots/plugin_logo.png)

## Installation

To install QuickpayGateway plugin, follow these steps:

1. Download & unzip the file and place the `quickpaygateway` directory into your `craft/plugins` directory
2.  -OR- do a `git clone https://github.com/voogieJames/craftcommerce-quickpay-gateway.git` and place the `quickpaygateway` into your `craft/plugins` folder.  You can then update it with `git pull`
3.  -OR- install with Composer via `composer require craftcommerce-quickpay-gateway/quickpaygateway`
4. Install plugin in the Craft Control Panel under Settings > Plugins
5. The plugin folder should be named `quickpaygateway` for Craft to see it.  GitHub recently started appending `-master` (the branch name) to the name of the folder for zip file downloads.
6. Make sure that you have `composer.phar`. Navigate to the `quickpaygateway` directory and run `composer.phar install`

-NOTE- If Craft Admin panel cannot find the plugin, that might be a permission issues, to solve it, just navigate to the craft/plugins directory and execute the following command in your terminal: `chmod 755 quickpaygateway/`

QuickpayGateway works on Craft 2.4.x and Craft 2.5.x.

## QuickpayGateway Overview

*   [QuickPay](https://quickpay.net/) is a Payment Service Provider that accept all common payment methods - credit cards, bank transfers, invoices, and more.
*   The Adapter utilizes Quickpay payment processor wrapped into Omnipay driver, which was forked from [NobrainerWeb](https://github.com/NobrainerWeb/omnipay-quickpay)
*   [Omnipay](https://omnipay.thephpleague.com/) is a payment processing library for PHP.

### Enjoy!


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

<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>twilio.rest.supersim.v1.sim.billing_period — twilio-python 7.15.3 documentation</title>
<link href="../../../../../../_static/alabaster.css" rel="stylesheet" type="text/css"/>
<link href="../../../../../../_static/pygments.css" rel="stylesheet" type="text/css"/>

<link href="../../../../../../genindex.html" rel="index" title="Index"/>
<link href="../../../../../../search.html" rel="search" title="Search"/>
<link href="../../../../../../_static/custom.css" rel="stylesheet" type="text/css"/>
<meta content="width=device-width, initial-scale=0.9, maximum-scale=0.9" name="viewport"/>

Source code for twilio.rest.supersim.v1.sim.billing_period

# coding=utf-8
r"""
This code was generated by
\ / _    _  _|   _  _
 | (_)\/(_)(_|\/| |(/_  v1.0.0
      /       /
"""

from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page

[docs]class BillingPeriodList(ListResource):

    def __init__(self, version, sim_sid):
        """
        Initialize the BillingPeriodList

        :param Version version: Version that contains the resource
        :param sim_sid: The SID of the Super SIM the Billing Period belongs to

        :returns: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodList
        :rtype: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodList
        """
        super(BillingPeriodList, self).__init__(version)

        # Path Solution
        self._solution = {'sim_sid': sim_sid, }
        self._uri = '/Sims/{sim_sid}/BillingPeriods'.format(**self._solution)

[docs]    def stream(self, limit=None, page_size=None):
        """
        Streams BillingPeriodInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param int limit: Upper limit for the number of records to return. stream()
                          guarantees to never return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, stream() will attempt to read the
                              limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.supersim.v1.sim.billing_period.BillingPeriodInstance]
        """
        limits = self._version.read_limits(limit, page_size)

        page = self.page(page_size=limits['page_size'], )

        return self._version.stream(page, limits['limit'])

[docs]    def list(self, limit=None, page_size=None):
        """
        Lists BillingPeriodInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param int limit: Upper limit for the number of records to return. list() guarantees
                          never to return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, list() will attempt to read the limit
                              with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.supersim.v1.sim.billing_period.BillingPeriodInstance]
        """
        return list(self.stream(limit=limit, page_size=page_size, ))

[docs]    def page(self, page_token=values.unset, page_number=values.unset,
             page_size=values.unset):
        """
        Retrieve a single page of BillingPeriodInstance records from the API.
        Request is executed immediately

        :param str page_token: PageToken provided by the API
        :param int page_number: Page Number, this value is simply for client state
        :param int page_size: Number of records to return, defaults to 50

        :returns: Page of BillingPeriodInstance
        :rtype: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodPage
        """
        data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })

        response = self._version.page(method='GET', uri=self._uri, params=data, )

        return BillingPeriodPage(self._version, response, self._solution)

[docs]    def get_page(self, target_url):
        """
        Retrieve a specific page of BillingPeriodInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of BillingPeriodInstance
        :rtype: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodPage
        """
        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return BillingPeriodPage(self._version, response, self._solution)

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Supersim.V1.BillingPeriodList>'

[docs]class BillingPeriodPage(Page):

    def __init__(self, version, response, solution):
        """
        Initialize the BillingPeriodPage

        :param Version version: Version that contains the resource
        :param Response response: Response from the API
        :param sim_sid: The SID of the Super SIM the Billing Period belongs to

        :returns: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodPage
        :rtype: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodPage
        """
        super(BillingPeriodPage, self).__init__(version, response)

        # Path Solution
        self._solution = solution

[docs]    def get_instance(self, payload):
        """
        Build an instance of BillingPeriodInstance

        :param dict payload: Payload response from the API

        :returns: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodInstance
        :rtype: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodInstance
        """
        return BillingPeriodInstance(self._version, payload, sim_sid=self._solution['sim_sid'], )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Supersim.V1.BillingPeriodPage>'

[docs]class BillingPeriodInstance(InstanceResource):

[docs]    class BpType(object):
        READY = "ready"
        ACTIVE = "active"

    def __init__(self, version, payload, sim_sid):
        """
        Initialize the BillingPeriodInstance

        :returns: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodInstance
        :rtype: twilio.rest.supersim.v1.sim.billing_period.BillingPeriodInstance
        """
        super(BillingPeriodInstance, self).__init__(version)

        # Marshaled Properties
        self._properties = {
            'sid': payload.get('sid'),
            'account_sid': payload.get('account_sid'),
            'sim_sid': payload.get('sim_sid'),
            'start_time': deserialize.iso8601_datetime(payload.get('start_time')),
            'end_time': deserialize.iso8601_datetime(payload.get('end_time')),
            'period_type': payload.get('period_type'),
            'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
            'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
        }

        # Context
        self._context = None
        self._solution = {'sim_sid': sim_sid, }

    @property
    def sid(self):
        """
        :returns: The SID of the Billing Period
        :rtype: unicode
        """
        return self._properties['sid']

    @property
    def account_sid(self):
        """
        :returns: The SID of the Account the Super SIM belongs to
        :rtype: unicode
        """
        return self._properties['account_sid']

    @property
    def sim_sid(self):
        """
        :returns: The SID of the Super SIM the Billing Period belongs to
        :rtype: unicode
        """
        return self._properties['sim_sid']

    @property
    def start_time(self):
        """
        :returns: The start time of the Billing Period
        :rtype: datetime
        """
        return self._properties['start_time']

    @property
    def end_time(self):
        """
        :returns: The end time of the Billing Period
        :rtype: datetime
        """
        return self._properties['end_time']

    @property
    def period_type(self):
        """
        :returns: The type of the Billing Period
        :rtype: BillingPeriodInstance.BpType
        """
        return self._properties['period_type']

    @property
    def date_created(self):
        """
        :returns: The ISO 8601 date and time in GMT when the resource was created
        :rtype: datetime
        """
        return self._properties['date_created']

    @property
    def date_updated(self):
        """
        :returns: The ISO 8601 date and time in GMT when the resource was last updated
        :rtype: datetime
        """
        return self._properties['date_updated']

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Supersim.V1.BillingPeriodInstance>'

About twilio-python

    A Python module for communicating with the Twilio API and generating TwiML.

Useful Links

Twilio's Python Helper Library Docs

twilio @ PyPI

twilio-python @ GitHub

Related Topics

Documentation overview

Module code

twilio.rest

twilio.rest.supersim

twilio.rest.supersim.v1

twilio.rest.supersim.v1.sim

Quick search

<form action="../../../../../../search.html" class="search" method="get">
<input name="q" type="text"/>
<input type="submit" value="Go"/>
<input name="check_keywords" type="hidden" value="yes"/>
<input name="area" type="hidden" value="default"/>
</form>

      ©2019, Twilio.

      |
      Powered by Sphinx 1.8.0
      & Alabaster 0.7.12


text:
body {
  display: flex;
  flex-direction: column;
  text-align: center;
  justify-content: center;
  margin: 0;
  height: 100vh;
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static CommandInterface.Utility.FileUtility;
using static CommandInterface.Utility.Utility;
using System.Xml.Linq;

namespace CommandInterface.Utility
{
    public class ProjectConstructor
    {
        public ProjectConstructor()
        {

        }

        public FileInfo ProjectPath { get; set; }
        public FileInfo SolutionPath { get; set; }
        public FileInfo CommandInterfaceProject { get; set; }

        public void CreateProject(string baseName, DirectoryInfo projectRoot, List<FileInfo> fileList)
        {
            var solutionPath = projectRoot.CombineAsFile(baseName + ".sln");
            var projectPath = projectRoot.CombineAsFile(baseName + ".csproj");
            var appConfigPath = projectRoot.CombineAsFile("App.config");
            var packagesConfigPath = projectRoot.CombineAsFile("packages.config");
            var assemblyInfoPath = projectRoot.CombineAsFile("Properties/AssemblyInfo.cs");
            var mainSourceCode = projectRoot.CombineAsFile("Program.cs");
            var projectGuid = Guid.NewGuid();
            var projectRelativePath = GetRelativePath(CommandInterfaceProject.FullName, projectRoot.FullName);
            var commandInterfaceProjectInfo = new ProjectInfo(CommandInterfaceProject);
            var commandInterfaceProjectGuid = ProjectInfo.ReadProjectGuid(CommandInterfaceProject);

            projectPath.Create(LoadAndWriteXml(ProjectTemplates.BasicTemplate, xdoc => {
                var rootNamespace = xdoc.Root.Name.Namespace;
                foreach (var srcFile in fileList)
                {
                    xdoc.Descendants().Where(e => e.Name.LocalName == "Compile").Last().AddAfterSelf(
                        new XElement(rootNamespace + "Compile",
                            new XAttribute("Include", GetRelativePath(srcFile.FullName, projectRoot.FullName))));
                }

                var guidElement = xdoc.Descendants().Where(e => e.Name.LocalName == "ProjectGuid").First();
                guidElement.Add(new XText($"{{{projectGuid.BraceExpression()}}}"));

                var configElement = xdoc.Descendants().Where(e => e.Name.LocalName == "ItemGroup" && e.Descendants().Where(f => f.Name.LocalName == "None").Count() != 0).First();
                configElement.AddAfterSelf(
                    new XElement(rootNamespace + "ItemGroup",
                        new XElement(rootNamespace + "ProjectReference",
                            new XAttribute("Include", projectRelativePath),
                            new XElement(rootNamespace + "Project", new XText(commandInterfaceProjectInfo.GuidText)),
                            new XElement(rootNamespace + "Name", new XText("CommandInterface"))
                    )));
            }));
            appConfigPath.Create(LoadAndWriteXml(ProjectTemplates.BasicAppConfig));
            packagesConfigPath.Create(LoadAndWriteXml(ProjectTemplates.BasicPackageConfig));
            assemblyInfoPath.Create(ProjectTemplates.BasicAssemblyInfo);
            mainSourceCode.Create(ProjectTemplates.BasicMainSourceCode);

            var solutionConstructor = new SolutionConstructor(solutionPath, new FileInfo[] { CommandInterfaceProject, projectPath });
            solutionConstructor.Create();

            ProjectPath = projectPath;
            SolutionPath = solutionPath;
        }
    }
}


text:
package com.jpattern.gwt.client.logger;

/**
 *
 * @author Francesco Cina'
 *
 * 12 Apr 2011
 */
public class NullLogger implements ILogger {

	@Override
	public void trace(String methodName, String message) {
	}

	@Override
	public void debug(String methodName, String message) {
	}

	@Override
	public void info(String methodName, String message) {
	}

	@Override
	public void warn(String methodName, String message) {
	}

	@Override
	public void error(String methodName, String message, Throwable e) {
	}

}


text:
#include "tensorflow/core/common_runtime/collective_param_resolver_local.h"

#include "tensorflow/core/common_runtime/device_mgr.h"

namespace tensorflow {

CollectiveParamResolverLocal::CollectiveParamResolverLocal(
    const DeviceMgr* dev_mgr, DeviceResolverInterface* dev_resolver,
    const string& task_name)
    : dev_mgr_(dev_mgr), dev_resolver_(dev_resolver), task_name_(task_name) {}

void CollectiveParamResolverLocal::CompleteGroupAsync(
    const CompleteGroupRequest* request, CompleteGroupResponse* response,
    CancellationManager* cancel_mgr, const StatusCallback& done) {
  done(
      errors::Internal("CompleteGroup is not implemented by "
                       "CollectiveParamResolverLocal which is "
                       "intended only for non-distributed deployment."));
}

void CollectiveParamResolverLocal::CompleteGroupLocal(
    const string& device, CollectiveParams* cp, const GroupRecCallback& done) {
  VLOG(1) << "CompleteGroupLocal device=" << device << " cp: " << cp << ": "
          << cp->ToString();
  std::vector<StatusCallback> to_be_called;
  GroupRec* gr = nullptr;
  {
    mutex_lock l(group_mu_);
    auto it = group_table_.find(cp->group.group_key);
    if (it == group_table_.end()) {
      gr = new GroupRec;
      gr->group.group_key = cp->group.group_key;
      gr->group.group_size = cp->group.group_size;
      gr->group.device_type = cp->group.device_type;
      group_table_[gr->group.group_key].reset(gr);
      VLOG(2) << "New group_key=" << gr->group.group_key
              << " group_size=" << gr->group.group_size;
    } else {
      gr = it->second.get();
    }
  }
  Status status;
  {
    mutex_lock gr_lock(gr->mu);
    if (!gr->device_set.empty()) {
      // Check for consistency with existing GroupRec.
      if (cp->group.device_type != gr->group.device_type) {
        status = errors::Internal(
            "Collective Op ", cp->name, " is assigned to device ", device,
            " with type ", cp->group.device_type.type_string(),
            " and group_key ", cp->group.group_key, " but that group has type ",
            gr->group.device_type.type_string());
      } else if (cp->group.group_size != gr->group.group_size) {
        status = errors::Internal(
            "Collective Op ", cp->name, " has group_size ",
            cp->group.group_size, " and group_key", cp->group.group_key,
            " but that group has size ", gr->group.group_size);
      }
    }
    if (status.ok()) {
      // Insert device if not already present.
      auto it = gr->device_set.find(device);
      if (it == gr->device_set.end()) {
        if (gr->device_set.size() == gr->group.group_size) {
          // The group is already full.
          status = errors::Internal(
              "Collective Op ", cp->name, " is assigned to device ", device,
              " and group_key ", cp->group.group_key,
              " but that group doesn't contain that device.");
        } else {
          // This is a new device that has not yet joined the group.
          gr->device_set.insert(device);
          gr->device_list.push_back(device);
          DeviceNameUtils::ParsedName parsed_device;
          DeviceNameUtils::ParseFullName(device, &parsed_device);
          string task_name = strings::StrCat("/job:", parsed_device.job,
                                             "/replica:", parsed_device.replica,
                                             "/task:", parsed_device.task);
          gr->task_set.insert(task_name);
          gr->task_list.push_back(task_name);
          gr->group.num_tasks = static_cast<int32>(gr->task_set.size());
          VLOG(1) << "group_key=" << gr->group.group_key
                  << " group_size=" << gr->group.group_size
                  << " dev_set=" << gr->device_set.size();
        }
      }
    }

    if (status.ok()) {
      // If the group is not yet complete, queue to wait for it.
      VLOG(2) << "group_size " << gr->group.group_size << " set size "
              << gr->device_set.size() << " gr " << gr;

      if (gr->device_set.size() < gr->group.group_size) {
        gr->waiting.push_back(std::bind(done, std::placeholders::_1, gr));
        return;
      }
      CHECK_EQ(gr->device_set.size(), gr->group.group_size);
      if (!gr->waiting.empty()) {
        std::swap(to_be_called, gr->waiting);
      }
    }
  }
  done(status, gr);
  for (int i = 0; i < to_be_called.size(); ++i) {
    to_be_called[i](Status::OK());
  }
}

namespace {

struct DevRec {
  string task;
  string device;
  int original_rank;
  int local_rank;
  int global_rank;
  const DeviceLocality* locality;
};
typedef std::unordered_map<string, DevRec> TaskDeviceMap;
typedef std::unordered_map<string, TaskDeviceMap> GlobalDeviceMap;

// Create a populated GlobalDeviceMap from CollInstanceParams and localities.
GlobalDeviceMap BuildDevRecs(const CollInstanceParams& ip,
                             const std::vector<DeviceLocality>& localities) {
  GlobalDeviceMap gdm;
  CHECK_EQ(ip.device_names.size(), ip.task_names.size());
  CHECK_EQ(ip.device_names.size(), localities.size());
  for (int i = 0; i < ip.device_names.size(); ++i) {
    TaskDeviceMap& tdm = gdm[ip.task_names[i]];
    DevRec* dr = &tdm[ip.device_names[i]];
    dr->task = ip.task_names[i];
    dr->device = ip.device_names[i];
    dr->original_rank = i;
    dr->local_rank = 0;   // Will be populated later by OrderTaskDeviceMap.
    dr->global_rank = 0;  // Will be populated later by EstablishGlobalRank.
    dr->locality = &localities[i];
  }
  return gdm;
}

void OrderTaskDeviceMap(TaskDeviceMap* tdm) {
  CHECK_GT(tdm->size(), 0);  // Should never be called with 0 devices
  int least_rank = -1;
  string next_device;
  std::set<string> selected;
  // Starting device is one with the least initial rank.
  for (const auto& it : *tdm) {
    if (least_rank < 0 || it.second.original_rank < least_rank) {
      least_rank = it.second.original_rank;
      next_device = it.second.device;
    }
  }
  CHECK_GE(least_rank, 0);
  DeviceNameUtils::ParsedName parsed_name;
  CHECK(DeviceNameUtils::ParseFullName(next_device, &parsed_name));
  // NOTE: InterconnectLink has only a device_id, nothing more, so for
  // the time being if there's more than one device at a task we
  // assume they're all GPUs.

  int next_rank = 0;
  while (true) {
    selected.insert(next_device);
    DevRec* dr = &(*tdm)[next_device];
    dr->local_rank = next_rank;
    ++next_rank;
    if (selected.size() == tdm->size()) {
      break;
    }
    // For the present time we assume Locality links only cover GPUs.
    // For multiple CPUs, just take them in order.
    const InterconnectLink* best_link = nullptr;
    if (parsed_name.type == "GPU") {
      for (const InterconnectLink& il : dr->locality->links().link()) {
        parsed_name.id = il.device_id();
        string endpoint_device =
            DeviceNameUtils::ParsedNameToString(parsed_name);
        if (selected.find(endpoint_device) != selected.end()) {
          continue;
        }
        if (best_link == nullptr || il.strength() > best_link->strength()) {
          best_link = &il;
        }
      }
    }
    if (best_link != nullptr) {
      // Follow the best edge
      parsed_name.id = best_link->device_id();
      next_device = DeviceNameUtils::ParsedNameToString(parsed_name);
    } else {
      // No good edges, alas. Pick the lowest initial rank among remaining
      // devices.
      least_rank = -1;
      for (const auto& it : *tdm) {
        if (selected.find(it.second.device) != selected.end()) {
          continue;
        }
        if (least_rank < 0 || it.second.original_rank < least_rank) {
          least_rank = it.second.original_rank;
          next_device = it.second.device;
        }
      }
      CHECK_GE(least_rank, 0);
    }
  }
}

// The first time a shared CollectiveParams is established for a
// shared set of instances we compute a good rank order for all the
// devices in the group, that is appropriate for a ring algorithm.
// This order need not be the same across different instance groups
// sharing the same device group where there is more than one good
// order.
GlobalDeviceMap EstablishGlobalRank(
    CollectiveParams* cp, const std::vector<DeviceLocality>& localities) {
  VLOG(1) << "EstablishGlobalRank";
  GlobalDeviceMap gdm = BuildDevRecs(cp->instance, localities);
  for (auto& iter : gdm) {
    TaskDeviceMap& tdm = iter.second;
    OrderTaskDeviceMap(&tdm);
  }
  // Connect the global rank order by the order in which tasks first appear.
  std::set<string> ordered_tasks;
  int next_rank = 0;
  for (int i = 0; i < cp->instance.task_names.size(); ++i) {
    const string& task_name = cp->instance.task_names[i];
    if (ordered_tasks.find(task_name) != ordered_tasks.end()) {
      continue;
    }
    ordered_tasks.insert(task_name);
    TaskDeviceMap* tdm = &gdm[task_name];
    for (auto& it : *tdm) {
      it.second.global_rank = it.second.local_rank + next_rank;
    }
    next_rank += tdm->size();
  }
  return gdm;
}

// Count the devices associated with each task and set
// cp->same_num_devices_per_task.  Requires cp->instance.task_names
// be sorted.
void SetDevPerTask(CollectiveParams* cp) {
  cp->instance.same_num_devices_per_task = false;
  if (cp->instance.task_names.empty()) return;
  int dev_per_task = -1;
  int count = 0;
  const string* last_task_name = &cp->instance.task_names[0];
  for (const string& task_name : cp->instance.task_names) {
    if (task_name != *last_task_name) {
      CHECK_GT(count, 0);
      if (dev_per_task < 0) {
        dev_per_task = count;
      } else {
        CHECK_GT(dev_per_task, 0);
        if (count != dev_per_task) return;
      }
      count = 1;
      last_task_name = &task_name;
    } else {
      ++count;
    }
  }
  CHECK_GT(count, 0);
  if ((dev_per_task > 0) && (count != dev_per_task)) {
    return;
  }
  cp->instance.same_num_devices_per_task = true;
  CHECK_EQ((cp->group.group_size % cp->group.num_tasks), 0);
}

// Sort cp->instance.device_names lexicographically, but do by first
// computing a reordering permutation so we can keep cp->instance.task_names
// in corresponding order.
void SortDevicesAndTasks(CollectiveParams* cp) {
  VLOG(1) << "SortDevicesAndTasks " << cp << " instance " << &cp->instance;
  CHECK(cp);
  CHECK_EQ(cp->group.group_size, cp->instance.device_names.size());
  CHECK_EQ(cp->group.group_size, cp->instance.task_names.size());
  std::vector<int> perm(cp->group.group_size);
  // TODO(tucker): substitute std::iota when the windows build supports it.
  // std::iota(perm.begin(), perm.end(), 0);
  for (int i = 0; i < perm.size(); ++i) {
    perm[i] = i;
  }
  std::sort(perm.begin(), perm.end(), [cp](const int& a, const int& b) {
    return cp->instance.device_names[a] < cp->instance.device_names[b];
  });
  std::vector<string> new_devs;
  std::vector<string> new_tasks;
  new_devs.reserve(cp->group.group_size);
  new_tasks.reserve(cp->group.group_size);
  for (int pi : perm) {
    new_devs.push_back(cp->instance.device_names[pi]);
    new_tasks.push_back(cp->instance.task_names[pi]);
  }
  cp->instance.device_names = std::move(new_devs);
  cp->instance.task_names = std::move(new_tasks);
  VLOG(1) << "Modified device_names on " << cp;
  SetDevPerTask(cp);
}

// Establish the requested number of subdivision permutations based on the
// ring order implicit in the device order.
void GenerateSubdivPerms(const string& device, int source_rank,
                         CollectiveParams* cp) {
  // Each subdiv permutation is a ring formed by rotating each
  // single-task subsequence of devices by an offset.  This makes most
  // sense when each task has the same number of devices but we can't
  // depend on that being the case so we'll compute something that
  // works in any case.

  // Start by counting the devices in each task.
  // Precondition: device_names must be sorted so that all devices in
  // the same task are adjacent.
  VLOG(2) << "Sorted task names: "
          << str_util::Join(cp->instance.task_names, ", ");
  std::vector<int> dev_per_task;
  const string* prior_task_name = &cp->instance.task_names[0];
  int dev_count = 1;
  for (int di = 1; di < cp->group.group_size; ++di) {
    if (cp->instance.task_names[di] != *prior_task_name) {
      dev_per_task.push_back(dev_count);
      dev_count = 1;
      prior_task_name = &cp->instance.task_names[di];
    } else {
      ++dev_count;
    }
  }
  dev_per_task.push_back(dev_count);
  CHECK_EQ(cp->group.num_tasks, dev_per_task.size());

  // Generate a ring permutation for each requested offset.
  CHECK_GT(cp->instance.impl_details.subdiv_offsets.size(), 0);
  VLOG(2) << "Setting up perms for cp " << cp << " subdiv_permutations "
          << &cp->instance.impl_details.subdiv_permutations;
  cp->instance.impl_details.subdiv_permutations.resize(
      cp->instance.impl_details.subdiv_offsets.size());
  cp->subdiv_rank.resize(cp->instance.impl_details.subdiv_offsets.size(), -1);
  for (int sdi = 0; sdi < cp->instance.impl_details.subdiv_offsets.size();
       ++sdi) {
    std::vector<int>& perm = cp->instance.impl_details.subdiv_permutations[sdi];
    CHECK_EQ(perm.size(), 0);
    int offset = cp->instance.impl_details.subdiv_offsets[sdi];
    int prior_dev_count = 0;
    for (int ti = 0; ti < cp->group.num_tasks; ++ti) {
      for (int di = 0; di < dev_per_task[ti]; ++di) {
        int offset_di = (di + offset) % dev_per_task[ti];
        int permuted_di = prior_dev_count + offset_di;
        perm.push_back(permuted_di);
        if (cp->instance.device_names[prior_dev_count + di] == device) {
          CHECK_EQ(prior_dev_count + di, cp->default_rank);
          cp->subdiv_rank[sdi] = permuted_di;
        }
      }
      prior_dev_count += dev_per_task[ti];
    }
    CHECK_EQ(cp->group.group_size, perm.size());
  }

  if (cp->instance.type == BROADCAST_COLLECTIVE) {
    CHECK_GE(source_rank, 0);
    cp->instance.impl_details.subdiv_source_rank.resize(
        cp->instance.impl_details.subdiv_offsets.size(), -1);
    for (int sdi = 0; sdi < cp->instance.impl_details.subdiv_source_rank.size();
         ++sdi) {
      for (int j = 0; j < cp->group.group_size; ++j) {
        if (cp->instance.impl_details.subdiv_permutations[sdi][j] ==
            source_rank) {
          cp->instance.impl_details.subdiv_source_rank[sdi] = j;
          break;
        }
      }
      CHECK_GE(cp->instance.impl_details.subdiv_source_rank[sdi], 0);
    }
  }

  if (VLOG_IS_ON(1)) {
    // Log the computed ring order for each subdiv.
    string buf;
    for (int sdi = 0;
         sdi < cp->instance.impl_details.subdiv_permutations.size(); ++sdi) {
      buf = strings::StrCat("Subdiv ", sdi, " device order:\n");
      for (int di = 0;
           di < cp->instance.impl_details.subdiv_permutations[sdi].size();
           ++di) {
        int idx = cp->instance.impl_details.subdiv_permutations[sdi][di];
        strings::StrAppend(&buf, cp->instance.device_names[idx], "\n");
      }
      strings::StrAppend(&buf, " subdiv_offsets: ");
      for (auto o : cp->instance.impl_details.subdiv_offsets)
        strings::StrAppend(&buf, o, " ");
      strings::StrAppend(&buf, " SubdivRank: ");
      for (auto d : cp->subdiv_rank) strings::StrAppend(&buf, d, " ");
      VLOG(1) << buf;
    }
  }
}

}  // namespace

void CollectiveParamResolverLocal::CompleteTaskIsLocal(const string& task_name,
                                                       CollectiveParams* cp) {
  cp->task.is_local.resize(cp->group.group_size, false);
  for (int i = 0; i < cp->group.group_size; ++i) {
    cp->task.is_local[i] = (cp->instance.task_names[i] == task_name);
  }
}

void CollectiveParamResolverLocal::SetDefaultRank(const string& device,
                                                  CollectiveParams* cp) {
  CHECK_EQ(cp->group.group_size, cp->instance.device_names.size()) << cp;
  for (int i = 0; i < cp->group.group_size; ++i) {
    if (cp->instance.device_names[i] == device) {
      cp->default_rank = i;
      break;
    }
  }
}

void CollectiveParamResolverLocal::InitInstanceSharedParams(
    const GroupRec* gr, const CollectiveParams* cp, InstanceRec* ir,
    const StatusCallback& done) {
  VLOG(1) << "InitInstanceSharedParams " << ir;
  ir->shared.instance = cp->instance;
  {
    mutex_lock gl(gr->mu);
    ir->shared.group = gr->group;
    ir->shared.instance.device_names.assign(gr->device_list.begin(),
                                            gr->device_list.end());
    ir->shared.instance.task_names.assign(gr->task_list.begin(),
                                          gr->task_list.end());
    VLOG(2) << "Initialized names for instance: "
            << ir->shared.instance.ToString();
  }
  ir->shared.default_rank = -1;

  // Sort devce_names lexicographcally, keeping task_names in
  // corresponding order.
  SortDevicesAndTasks(&ir->shared);

  // Get Locality data for all devices.

  // Set is_local and task_names in *shared prior to invoking
  // GetDeviceLocalitiesAsync.  In a distributed context this function can be
  // called by a derived class, some of the devices may be non-local and
  // GetDeviceLocalitiesAsync will use those fields to launch RPCs.
  CompleteTaskIsLocal(task_name_, &ir->shared);
  std::vector<DeviceLocality>* localities = new std::vector<DeviceLocality>;
  dev_resolver_->GetDeviceLocalitiesAsync(
      ir->shared.instance, localities,
      [this, gr, cp, ir, localities, done](const Status& s)
          EXCLUSIVE_LOCKS_REQUIRED(ir->out_mu) {
            if (s.ok()) {
              CompleteDefaultRanking(gr, cp, ir, *localities);
              done(Status::OK());
            } else {
              done(s);
            }
            delete localities;
          });
}

void CollectiveParamResolverLocal::CompleteDefaultRanking(
    const GroupRec* gr, const CollectiveParams* cp, InstanceRec* ir,
    const std::vector<DeviceLocality>& localities) {
  // Establish an instance-specific default rank order for devices
  // based on localities.  This rank order should be a good ring
  // order, if possible.
  GlobalDeviceMap gdm = EstablishGlobalRank(&ir->shared, localities);
  // Reflect the new global ranking on shared
  size_t num_devices = ir->shared.group.group_size;
  std::vector<string> new_device_names(num_devices, "");
  std::vector<string> new_task_names(num_devices, "");
  for (const auto& git : gdm) {
    const TaskDeviceMap& tdm = git.second;
    for (const auto& tit : tdm) {
      const DevRec& dr = tit.second;
      new_device_names[dr.global_rank] =
          ir->shared.instance.device_names[dr.original_rank];
      new_task_names[dr.global_rank] =
          ir->shared.instance.task_names[dr.original_rank];
    }
  }

  ir->shared.instance.device_names = new_device_names;
  ir->shared.instance.task_names = new_task_names;
  if (VLOG_IS_ON(2)) {
    string buf;
    for (const auto& d : cp->instance.device_names)
      strings::StrAppend(&buf, "\n", d);
    VLOG(2) << "Optimized device order for " << ir->shared.name << ": " << buf;
  }
}

void CollectiveParamResolverLocal::CallbackWithStatus(
    const InstanceRecCallback& done, InstanceRec* irec) {
  Status s;
  {
    mutex_lock l(irec->out_mu);
    s = irec->status;
  }
  done(s, irec);
}

void CollectiveParamResolverLocal::FindInstanceRec(
    const GroupRec* gr, CollectiveParams* cp, const InstanceRecCallback& done) {
  InstanceRec* irec = nullptr;
  bool exit_outside_locks = false;
  {
    mutex_lock l(instance_mu_);
    auto it = instance_table_.find(cp->instance.instance_key);
    if (it != instance_table_.end()) {
      irec = it->second.get();
      {
        mutex_lock l(irec->in_mu);
        if (irec->is_init) {
          exit_outside_locks = true;
        } else {
          irec->init_waiters.push_back([this, gr, cp, done](InstanceRec* irec) {
            CallbackWithStatus(done, irec);
          });
          return;
        }
      }
    } else {
      // Create new InstanceRec.
      irec = new InstanceRec;
      instance_table_[cp->instance.instance_key].reset(irec);
    }
  }
  if (exit_outside_locks) {
    CallbackWithStatus(done, irec);
    return;
  }

  CallInitInstanceSharedParams(gr, cp, irec, done);
}

void CollectiveParamResolverLocal::CallInitInstanceSharedParams(
    const GroupRec* gr, const CollectiveParams* cp, InstanceRec* ir,
    const InstanceRecCallback& done) NO_THREAD_SAFETY_ANALYSIS {
  // This function serves merely to make a function call that should
  // be thread/mutex safe but violates the simple model applied by
  // static analysis, so we turn off analysis only within this
  // function body.
  //
  // A lock on ir->out_mu must be held throughout the _bodies_ of the
  // chain of function calls initiated here, each of which calls
  // another as its last action, but it will be dropped within the
  // callback defined below, which means that the lock can be dropped
  // before all the function stack frames pop. The static analysis will
  // not allow that.
  ir->out_mu.lock();
  ir->known.resize(cp->group.group_size, false);
  InitInstanceSharedParams(
      gr, cp, ir,
      [this, ir, done](const Status& s) UNLOCK_FUNCTION(ir->out_mu) {
        DCHECK(!ir->out_mu.try_lock());
        ir->status.Update(s);
        ir->out_mu.unlock();
        // Prepare to invoke any waiters that accumlated during
        // initialization.
        std::vector<IRConsumer> init_waiters;
        {
          mutex_lock tl(instance_mu_);
          {
            mutex_lock l(ir->in_mu);
            ir->is_init = true;
            if (!ir->init_waiters.empty()) {
              std::swap(init_waiters, ir->init_waiters);
            }
          }
        }
        CallbackWithStatus(done, ir);
        for (auto& f : init_waiters) {
          f(ir);
        }
      });
}

void CollectiveParamResolverLocal::CompleteParamsAsync(
    const string& device, CollectiveParams* cp, CancellationManager* cancel_mgr,
    const StatusCallback& done) {
  VLOG(1) << "CompleteParams " << device << " for " << cp << ": "
          << cp->ToString();
  CompleteGroupLocal(
      device, cp,
      [this, device, cp, done](const Status& s, const GroupRec* gr) {
        if (s.ok()) {
          CompleteInstanceLocal(device, gr, cp, cp->is_source, done);
        } else {
          done(s);
        }
      });
}

void CollectiveParamResolverLocal::CompleteInstanceAsync(
    const CompleteInstanceRequest* request, CompleteInstanceResponse* response,
    CancellationManager* cancel_mgr, const StatusCallback& done) {
  done(
      errors::Internal("CompleteInstance is not implemented by "
                       "CollectiveParamResolverLocal which is "
                       "intended only for non-distributed deployment."));
}

void CollectiveParamResolverLocal::CompleteInstanceLocal(
    const string& device, const GroupRec* gr, CollectiveParams* cp,
    bool is_source, const StatusCallback& done) {
  VLOG(1) << "CompleteInstanceLocal " << device
          << " instance_key: " << cp->instance.instance_key << " gr " << gr;

  // Populate the group portion of *cp from *gr.  Most of it should already
  // match.
  DCHECK_EQ(cp->group.group_key, gr->group.group_key);
  DCHECK_EQ(cp->group.group_size, gr->group.group_size);
  DCHECK_EQ(cp->group.device_type, gr->group.device_type);
  cp->group = gr->group;

  // Get the shared InstanceRec for this instance.
  FindInstanceRec(gr, cp,
                  [this, device, gr, cp, is_source, done](const Status& s,
                                                          InstanceRec* ir) {
                    if (s.ok()) {
                      CompleteInstanceFromInitializedIRec(device, gr, cp, ir,
                                                          is_source, done);
                    } else {
                      done(s);
                    }
                  });
}

void CollectiveParamResolverLocal::CompleteInstanceFromInitializedIRec(
    const string& device, const GroupRec* gr, CollectiveParams* cp,
    InstanceRec* ir, bool is_source, const StatusCallback& done) {
  // Populate the fields common across instance.
  {
    mutex_lock l(ir->out_mu);
    // custom operator= does a deep copy.
    cp->instance = ir->shared.instance;
  }
  // Populate the fields common across task, also default_rank.
  SetDefaultRank(device, cp);
  CompleteTaskIsLocal(task_name_, cp);
  // If broadcast, may need to wait for source discovery.
  if (cp->instance.type == BROADCAST_COLLECTIVE) {
    CompleteInstanceSource(ir, cp, is_source,
                           [this, ir, device, cp, done](InstanceRec* irec) {
                             CHECK_EQ(ir, irec);
                             Status s;
                             int source_rank;
                             {
                               mutex_lock l(irec->out_mu);
                               s = irec->status;
                               source_rank = ir->source_rank;
                             }
                             if (s.ok()) {
                               GenerateSubdivPerms(device, source_rank, cp);
                             }
                             done(s);
                           });
    return;
  } else {
    GenerateSubdivPerms(device, 0, cp);
  }
  done(Status::OK());
}

void CollectiveParamResolverLocal::CompleteInstanceSource(InstanceRec* ir,
                                                          CollectiveParams* cp,
                                                          bool is_source,
                                                          const IRConsumer& f) {
  std::vector<IRConsumer> ready_waiters;
  {
    mutex_lock l(ir->out_mu);
    CHECK_EQ(cp->group.group_size, ir->known.size());
    CHECK_GE(cp->default_rank, 0);
    if (!ir->known[cp->default_rank]) {
      ir->known[cp->default_rank] = true;
      ++ir->known_count;
      if (is_source) {
        if (ir->source_rank >= 0) {
          ir->status = errors::Internal("Instance ", cp->instance.instance_key,
                                        " already has source ", ir->source_rank,
                                        ", recevied second claim from ",
                                        cp->default_rank);
        } else {
          ir->source_rank = cp->default_rank;
        }
      }
    }
    if (ir->known_count < ir->shared.group.group_size) {
      ir->known_waiters.push_back(f);
      return;
    }
    CHECK_EQ(ir->known_count, ir->shared.group.group_size);
    CHECK_GE(ir->source_rank, 0);
    if (!ir->known_waiters.empty()) {
      ready_waiters = std::move(ir->known_waiters);
    }
  }
  f(ir);
  for (auto& f : ready_waiters) {
    f(ir);
  }
}

}  // namespace tensorflow


text:
package edu.jhu.thrax.hadoop.features;

import java.util.Map;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;

import edu.jhu.thrax.hadoop.datatypes.RuleWritable;
import edu.jhu.thrax.util.Vocabulary;

public class TargetWordCounterFeature implements SimpleFeature {

  public static final String NAME = "target_word_count";

  private static final IntWritable ZERO = new IntWritable(0);

  public Writable score(RuleWritable r) {
    int words = 0;
    for (int tok : r.target)
      if (!Vocabulary.nt(tok)) words++;
    return new IntWritable(words);
  }

  public String getName() {
    return NAME;
  }

  public void unaryGlueRuleScore(int nt, Map<Integer, Writable> map) {
    map.put(Vocabulary.id(NAME), ZERO);
  }

  public void binaryGlueRuleScore(int nt, Map<Integer, Writable> map) {
    map.put(Vocabulary.id(NAME), ZERO);
  }
}


text:
package org.apache.qpid.protonj2.codec.encoders;

import org.apache.qpid.protonj2.buffer.ProtonBuffer;
import org.apache.qpid.protonj2.codec.EncoderState;
import org.apache.qpid.protonj2.codec.EncodingCodes;

/**
 * Base class used for all Described Type objects that are represented as a List
 *
 * @param <M> the map type that is being encoded.
 * @param <K> the key type used for the encoded map's keys.
 * @param <V> the value type used for the encoded map's values.
 */
public abstract class AbstractDescribedMapTypeEncoder<K, V, M> extends AbstractDescribedTypeEncoder<M> {

    /**
     * Determine the map type the given value can be encoded to based on the number
     * of bytes that would be needed to hold the encoded form of the resulting list
     * entries.
     * <p>
     * Most encoders will return MAP32 but for cases where the type is known to
     * be encoded to MAP8 the encoder can optimize the encode step and not compute
     * sizes.
     *
     * @param value
     *      The value that is to be encoded.
     *
     * @return the encoding code of the map type encoding needed for this object.
     */
    public byte getMapEncoding(M value) {
        return EncodingCodes.MAP32;
    }

    /**
     * Returns false when the value to be encoded has no Map body and can be
     * written as a Null body type instead of a Map type.
     *
     * @param value
     *		the value which be encoded as a map type.
     *
     * @return true if the type to be encoded has a Map body, false otherwise.
     */
    public abstract boolean hasMap(M value);

    /**
     * Gets the number of elements that will result when this type is encoded
     * into an AMQP Map type.
     *
     * @param value
     * 		the value which will be encoded as a map type.
     *
     * @return the number of elements that should comprise the encoded list.
     */
    public abstract int getMapSize(M value);

    /**
     * Performs the write of the Map entries to the given buffer, the caller
     * takes care of writing the Map preamble and tracking the final size of
     * the written elements of the Map.
     *
     * @param buffer
     *      the buffer where the type should be encoded to.
     * @param state
     *      the current encoder state.
     * @param value
     * 		the value which will be encoded as a map type.
     */
    public abstract void writeMapEntries(ProtonBuffer buffer, EncoderState state, M value);

    @Override
    public void writeType(ProtonBuffer buffer, EncoderState state, M value) {
        buffer.writeByte(EncodingCodes.DESCRIBED_TYPE_INDICATOR);
        state.getEncoder().writeUnsignedLong(buffer, state, getDescriptorCode().byteValue());

        if (hasMap(value)) {
            final int count = getMapSize(value);
            final byte encodingCode = getMapEncoding(value);

            buffer.writeByte(encodingCode);

            switch (encodingCode) {
                case EncodingCodes.MAP8:
                    writeSmallType(buffer, state, value, count);
                    break;
                case EncodingCodes.MAP32:
                    writeLargeType(buffer, state, value, count);
                    break;
            }
        } else {
            state.getEncoder().writeNull(buffer, state);
        }
    }

    private void writeSmallType(ProtonBuffer buffer, EncoderState state, M value, int elementCount) {
        final int startIndex = buffer.getWriteIndex();

        // Reserve space for the size and write the count of list elements.
        buffer.writeByte((byte) 0);
        buffer.writeByte((byte) (elementCount * 2));

        writeMapEntries(buffer, state, value);

        // Move back and write the size
        final int writeSize = (buffer.getWriteIndex() - startIndex) - Byte.BYTES;

        buffer.setByte(startIndex, writeSize);
    }

    private void writeLargeType(ProtonBuffer buffer, EncoderState state, M value, int elementCount) {
        final int startIndex = buffer.getWriteIndex();

        // Reserve space for the size and write the count of list elements.
        buffer.writeInt(0);
        buffer.writeInt(elementCount * 2);

        writeMapEntries(buffer, state, value);

        // Move back and write the size
        final int writeSize = (buffer.getWriteIndex() - startIndex) - Integer.BYTES;

        buffer.setInt(startIndex, writeSize);
    }

    @Override
    public void writeArray(ProtonBuffer buffer, EncoderState state, Object[] values) {
        // Write the Array Type encoding code, we don't optimize here.
        buffer.writeByte(EncodingCodes.ARRAY32);

        final int startIndex = buffer.getWriteIndex();

        // Reserve space for the size and write the count of list elements.
        buffer.writeInt(0);
        buffer.writeInt(values.length);

        buffer.writeByte(EncodingCodes.DESCRIBED_TYPE_INDICATOR);
        state.getEncoder().writeUnsignedLong(buffer, state, getDescriptorCode());

        writeRawArray(buffer, state, values);

        // Move back and write the size
        final int writeSize = buffer.getWriteIndex() - startIndex - Integer.BYTES;

        if (writeSize > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("Cannot encode given array, encoded size to large: " + writeSize);
        }

        buffer.setInt(startIndex, writeSize);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void writeRawArray(ProtonBuffer buffer, EncoderState state, Object[] values) {
        buffer.writeByte(EncodingCodes.MAP32);

        for (int i = 0; i < values.length; ++i) {
            final M map = (M) values[i];
            final int count = getMapSize(map);
            final int mapStartIndex = buffer.getWriteIndex();

            // Reserve space for the size and write the count of list elements.
            buffer.writeInt(0);
            buffer.writeInt(count * 2);

            writeMapEntries(buffer, state, map);

            // Move back and write the size
            final int writeSize = buffer.getWriteIndex() - mapStartIndex - Integer.BYTES;

            buffer.setInt(mapStartIndex, writeSize);
        }
    }
}


text:
package org.keycloak.services.managers;

import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.provider.Spi;

/**
 * @author Stian Thorgersen
 */
public class BruteForceProtectorSpi implements Spi {

    @Override
    public boolean isInternal() {
        return true;
    }

    @Override
    public String getName() {
        return "bruteForceProtector";
    }

    @Override
    public Class<? extends Provider> getProviderClass() {
        return BruteForceProtector.class;
    }

    @Override
    public Class<? extends ProviderFactory> getProviderFactoryClass() {
        return BruteForceProtectorFactory.class;
    }

}


text:
function Add-VSKinesisFirehoseDeliveryStreamElasticsearchRetryOptions {
    <#
    .SYNOPSIS
        Adds an AWS::KinesisFirehose::DeliveryStream.ElasticsearchRetryOptions resource property to the template. The ElasticsearchRetryOptions property type configures the retry behavior for when Amazon Kinesis Data Firehose (Kinesis Data Firehose can't deliver data to Amazon Elasticsearch Service (Amazon ES.

    .DESCRIPTION
        Adds an AWS::KinesisFirehose::DeliveryStream.ElasticsearchRetryOptions resource property to the template.
The ElasticsearchRetryOptions property type configures the retry behavior for when Amazon Kinesis Data Firehose (Kinesis Data Firehose can't deliver data to Amazon Elasticsearch Service (Amazon ES.

    .LINK
        http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchretryoptions.html

    .PARAMETER DurationInSeconds
        After an initial failure to deliver to Amazon ES, the total amount of time during which Kinesis Data Firehose re-attempts delivery including the first attempt. If Kinesis Data Firehose can't deliver the data within the specified time, it writes the data to the backup S3 bucket. For valid values, see the DurationInSeconds content for the ElasticsearchRetryOptions: https://docs.aws.amazon.com/firehose/latest/APIReference/API_ElasticsearchRetryOptions.html data type in the *Amazon Kinesis Data Firehose API Reference*.

        Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchretryoptions.html#cfn-kinesisfirehose-deliverystream-elasticsearchretryoptions-durationinseconds
        PrimitiveType: Integer
        UpdateType: Mutable

    .FUNCTIONALITY
        Vaporshell
    #>
    [OutputType('Vaporshell.Resource.KinesisFirehose.DeliveryStream.ElasticsearchRetryOptions')]
    [cmdletbinding()]
    Param
    (
        [parameter(Mandatory = $true)]
        [ValidateScript( {
                $allowedTypes = "System.Int32","Vaporshell.Function"
                if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
                    $true
                }
                else {
                    $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
                }
            })]
        $DurationInSeconds
    )
    Begin {
        $obj = [PSCustomObject]@{}
        $commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable')
    }
    Process {
        foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) {
            switch ($key) {
                Default {
                    $obj | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters.$key
                }
            }
        }
    }
    End {
        $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.KinesisFirehose.DeliveryStream.ElasticsearchRetryOptions'
        Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
    }
}


text:
package net.minecraft.item;

import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Items;
import net.minecraft.stats.StatList;
import net.minecraft.world.World;

public class ItemBow extends Item
{
    public static final String[] bowPullIconNameArray = new String[] {"pulling_0", "pulling_1", "pulling_2"};
    private static final String __OBFID = "CL_00001777";

    public ItemBow()
    {
        this.maxStackSize = 1;
        this.setMaxDamage(384);
        this.setCreativeTab(CreativeTabs.tabCombat);
    }

    /**
     * Called when the player stops using an Item (stops holding the right mouse button).
     *
     * @param timeLeft The amount of ticks left before the using would have been complete
     */
    public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityPlayer playerIn, int timeLeft)
    {
        boolean var5 = playerIn.capabilities.isCreativeMode || EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0;

        if (var5 || playerIn.inventory.hasItem(Items.arrow))
        {
            int var6 = this.getMaxItemUseDuration(stack) - timeLeft;
            float var7 = (float)var6 / 20.0F;
            var7 = (var7 * var7 + var7 * 2.0F) / 3.0F;

            if ((double)var7 < 0.1D)
            {
                return;
            }

            if (var7 > 1.0F)
            {
                var7 = 1.0F;
            }

            EntityArrow var8 = new EntityArrow(worldIn, playerIn, var7 * 2.0F);

            if (var7 == 1.0F)
            {
                var8.setIsCritical(true);
            }

            int var9 = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, stack);

            if (var9 > 0)
            {
                var8.setDamage(var8.getDamage() + (double)var9 * 0.5D + 0.5D);
            }

            int var10 = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, stack);

            if (var10 > 0)
            {
                var8.setKnockbackStrength(var10);
            }

            if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, stack) > 0)
            {
                var8.setFire(100);
            }

            stack.damageItem(1, playerIn);
            worldIn.playSoundAtEntity(playerIn, "random.bow", 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + var7 * 0.5F);

            if (var5)
            {
                var8.canBePickedUp = 2;
            }
            else
            {
                playerIn.inventory.consumeInventoryItem(Items.arrow);
            }

            playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]);

            if (!worldIn.isRemote)
            {
                worldIn.spawnEntityInWorld(var8);
            }
        }
    }

    /**
     * Called when the player finishes using this Item (E.g. finishes eating.). Not called when the player stops using
     * the Item before the action is complete.
     */
    public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityPlayer playerIn)
    {
        return stack;
    }

    /**
     * How long it takes to use or consume an item
     */
    public int getMaxItemUseDuration(ItemStack stack)
    {
        return 72000;
    }

    /**
     * returns the action that specifies what animation to play when the items is being used
     */
    public EnumAction getItemUseAction(ItemStack stack)
    {
        return EnumAction.BOW;
    }

    /**
     * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
     */
    public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn)
    {
        if (playerIn.capabilities.isCreativeMode || playerIn.inventory.hasItem(Items.arrow))
        {
            playerIn.setItemInUse(itemStackIn, this.getMaxItemUseDuration(itemStackIn));
        }

        return itemStackIn;
    }

    /**
     * Return the enchantability factor of the item, most of the time is based on material.
     */
    public int getItemEnchantability()
    {
        return 1;
    }
}


text:
Vex.Flow.Test.Annotation = {}

Vex.Flow.Test.Annotation.Start = function() {
  module("Annotation");
  Vex.Flow.Test.runTest("Simple Annotation", Vex.Flow.Test.Annotation.simple);
  Vex.Flow.Test.runRaphaelTest("Simple Annotation",
      Vex.Flow.Test.Annotation.simple);
  Vex.Flow.Test.runTest("Standard Notation Annotation",
      Vex.Flow.Test.Annotation.standard);
  Vex.Flow.Test.runTest("Harmonics", Vex.Flow.Test.Annotation.harmonic);
  Vex.Flow.Test.runRaphaelTest("Harmonics", Vex.Flow.Test.Annotation.harmonic);
  Vex.Flow.Test.runTest("Fingerpicking", Vex.Flow.Test.Annotation.picking);
  Vex.Flow.Test.runRaphaelTest("Fingerpicking (Raphael)",
      Vex.Flow.Test.Annotation.picking);
  Vex.Flow.Test.runTest("Bottom Annotation",
      Vex.Flow.Test.Annotation.bottom);
  Vex.Flow.Test.runTest("Test Justification Annotation",
      Vex.Flow.Test.Annotation.justification);
}

Vex.Flow.Test.Annotation.simple = function(options, contextBuilder) {
  var ctx = contextBuilder(options.canvas_sel, 500, 240);
  ctx.scale(1.5, 1.5); ctx.fillStyle = "#221"; ctx.strokeStyle = "#221";
  ctx.font = " 10pt Arial";
  var stave = new Vex.Flow.TabStave(10, 10, 450).
    addTabGlyph().setContext(ctx).draw();

  function newNote(tab_struct) { return new Vex.Flow.TabNote(tab_struct); }
  function newBend(text) { return new Vex.Flow.Bend(text); }
  function newAnnotation(text) { return new Vex.Flow.Annotation(text); }

  var notes = [
    newNote({
      positions: [{str: 2, fret: 10}, {str: 4, fret: 9}], duration: "h" }).
      addModifier(newAnnotation("T"), 0),
    newNote({
      positions: [{str: 2, fret: 10}], duration: "h" }).
        addModifier(newAnnotation("T"), 0).
        addModifier(newBend("Full"), 0),
  ];

  Vex.Flow.Formatter.FormatAndDraw(ctx, stave, notes, 200);
  ok(true, "Simple Annotation");
}

Vex.Flow.Test.Annotation.standard = function(options, contextBuilder) {
  var ctx = contextBuilder(options.canvas_sel, 500, 240);
  ctx.scale(1.5, 1.5); ctx.fillStyle = "#221"; ctx.strokeStyle = "#221";
  var stave = new Vex.Flow.Stave(10, 10, 450).
    addClef("treble").setContext(ctx).draw();

  function newNote(note_struct) { return new Vex.Flow.StaveNote(note_struct); }
  function newAnnotation(text) {
    return (new Vex.Flow.Annotation(text)).setFont("Times",
        Vex.Flow.Test.Font.size, "italic"); }

  var notes = [
    newNote({ keys: ["c/4", "e/4"], duration: "h"}).
      addAnnotation(0, newAnnotation("quiet")),
    newNote({ keys: ["c/4", "e/4", "c/5"], duration: "h"}).
      addAnnotation(2, newAnnotation("Allegro"))
  ];

  Vex.Flow.Formatter.FormatAndDraw(ctx, stave, notes, 200);
  ok(true, "Standard Notation Annotation");
}

Vex.Flow.Test.Annotation.harmonic = function(options, contextBuilder) {
  var ctx = contextBuilder(options.canvas_sel, 500, 240);
  ctx.scale(1.5, 1.5); ctx.fillStyle = "#221"; ctx.strokeStyle = "#221";
  ctx.font = " 10pt Arial";
  var stave = new Vex.Flow.TabStave(10, 10, 450).
    addTabGlyph().setContext(ctx).draw();

  function newNote(tab_struct) { return new Vex.Flow.TabNote(tab_struct); }
  function newBend(text) { return new Vex.Flow.Bend(text); }
  function newAnnotation(text) { return new Vex.Flow.Annotation(text); }

  var notes = [
    newNote({
      positions: [{str: 2, fret: 12}, {str: 3, fret: 12}], duration: "h" }).
      addModifier(newAnnotation("Harm."), 0),
    newNote({
      positions: [{str: 2, fret: 9}], duration: "h" }).
        addModifier(newAnnotation("(8va)").setFont("Times",
              Vex.Flow.Test.Font.size, "italic"), 0).
        addModifier(newAnnotation("A.H."), 0)
  ];

  Vex.Flow.Formatter.FormatAndDraw(ctx, stave, notes, 200);
  ok(true, "Simple Annotation");
}

Vex.Flow.Test.Annotation.picking = function(options, contextBuilder) {
  var ctx = contextBuilder(options.canvas_sel, 500, 240);
  ctx.scale(1.5, 1.5); ctx.setFillStyle("#221"); ctx.setStrokeStyle("#221");
  ctx.setFont("Arial", Vex.Flow.Test.Font.size, "");
  var stave = new Vex.Flow.TabStave(10, 10, 450).
    addTabGlyph().setContext(ctx).draw();

  function newNote(tab_struct) { return new Vex.Flow.TabNote(tab_struct); }
  function newBend(text) { return new Vex.Flow.Bend(text); }
  function newAnnotation(text) { return new Vex.Flow.Annotation(text).
    setFont("Times", Vex.Flow.Test.Font.size, "italic"); }

  var notes = [
    newNote({
      positions: [
        {str: 1, fret: 0},
        {str: 2, fret: 1},
        {str: 3, fret: 2},
        {str: 4, fret: 2},
        {str: 5, fret: 0}
        ], duration: "h" }).
      addModifier(new Vex.Flow.Vibrato().setVibratoWidth(40)),
    newNote({
      positions: [{str: 6, fret: 9}], duration: "8" }).
        addModifier(newAnnotation("p"), 0),
    newNote({
      positions: [{str: 3, fret: 9}], duration: "8" }).
        addModifier(newAnnotation("i"), 0),
    newNote({
      positions: [{str: 2, fret: 9}], duration: "8" }).
        addModifier(newAnnotation("m"), 0),
    newNote({
      positions: [{str: 1, fret: 9}], duration: "8" }).
        addModifier(newAnnotation("a"), 0)
  ];

  Vex.Flow.Formatter.FormatAndDraw(ctx, stave, notes, 200);
  ok(true, "Fingerpicking");
}

Vex.Flow.Test.Annotation.bottom = function(options, contextBuilder) {
  var ctx = contextBuilder(options.canvas_sel, 500, 240);
  ctx.scale(1.5, 1.5); ctx.fillStyle = "#221"; ctx.strokeStyle = "#221";
  var stave = new Vex.Flow.Stave(10, 10, 300).
    addClef("treble").setContext(ctx).draw();

  function newNote(note_struct) { return new Vex.Flow.StaveNote(note_struct); }
  function newAnnotation(text) {
    return (
        new Vex.Flow.Annotation(text)).
        setFont("Times", Vex.Flow.Test.Font.size).
        setVerticalJustification(Vex.Flow.Annotation.VerticalJustify.BOTTOM);
    }

  var notes = [
    newNote({ keys: ["f/4"], duration: "w"}).
      addAnnotation(0, newAnnotation("F")),
    newNote({ keys: ["a/4"], duration: "w"}).
      addAnnotation(0, newAnnotation("A")),
    newNote({ keys: ["c/5"], duration: "w"}).
      addAnnotation(0, newAnnotation("C")),
    newNote({ keys: ["e/5"], duration: "w"}).
      addAnnotation(0, newAnnotation("E"))
  ];

  Vex.Flow.Formatter.FormatAndDraw(ctx, stave, notes, 100);
  ok(true, "Bottom Annotation");
}

Vex.Flow.Test.Annotation.justification = function(options, contextBuilder) {
  var ctx = contextBuilder(options.canvas_sel, 650, 950);
  ctx.scale(1.5, 1.5); ctx.fillStyle = "#221"; ctx.strokeStyle = "#221";

  function newNote(note_struct) { return new Vex.Flow.StaveNote(note_struct); }
  function newAnnotation(text, hJustifcation, vJustifcation) {
    return (
        new Vex.Flow.Annotation(text)).
          setFont("Arial", Vex.Flow.Test.Font.size).
          setJustification(hJustifcation).
          setVerticalJustification(vJustifcation); }

  for (var v = 1; v <= 4; ++v) {
    var stave = new Vex.Flow.Stave(10, (v-1) * 150 + 40, 400).
      addClef("treble").setContext(ctx).draw();

    notes = [];

    notes.push(newNote({ keys: ["c/3"], duration: "q"}).addAnnotation(0, newAnnotation("Text", 1, v)));
    notes.push(newNote({ keys: ["c/4"], duration: "q"}).addAnnotation(0, newAnnotation("Text", 2, v)));
    notes.push(newNote({ keys: ["c/5"], duration: "q"}).addAnnotation(0, newAnnotation("Text", 3, v)));
    notes.push(newNote({ keys: ["c/6"], duration: "q"}).addAnnotation(0, newAnnotation("Text", 4, v)));

    Vex.Flow.Formatter.FormatAndDraw(ctx, stave, notes, 100);
  }

  ok(true, "Test Justification Annotation");
}