repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
zgagnon/colossus | colossus-metrics/src/test/scala/colossus/metrics/CounterSpec.scala | 1330 | package colossus.metrics
import scala.concurrent.duration._
class CounterSpec extends MetricIntegrationSpec {
"Basic Counter" must {
"increment" in {
val c = new BasicCounter(CounterParams("/foo"))
c.increment()
c.value().get must equal(1)
}
"decrement" in {
val c = new BasicCounter(CounterParams("/foo"))
c.increment()
c.decrement()
c.value().get must equal(0)
}
"delta" in {
val c = new BasicCounter(CounterParams("/foo"))
c.delta(5)
c.delta(-1)
c.value().get must equal(4)
}
"correctly handle tags" in {
val c = new BasicCounter(CounterParams("/foo"))
c.increment(Map("a" -> "a"))
c.delta(2, Map("a" -> "b"))
c.value(Map("a" -> "a")).get must equal(1)
c.value(Map("a" -> "b")).get must equal(2)
}
}
"Shared counter" must {
"report the correct event" in {
import akka.testkit.TestProbe
import colossus.metrics.testkit.TestSharedCollection
import EventLocality._
val probe = TestProbe()
val collection = new TestSharedCollection(probe)
val counter: Shared[Counter] = collection.getOrAdd(Counter("/foo"))
counter.delta(2, Map("a" -> "aa"))
probe.expectMsg(10.seconds, Counter.Delta("/foo", 2, Map("a" -> "aa")))
}
}
}
| apache-2.0 |
mbebenita/shumway.ts | tests/Fidelity/test262/suite/ch15/15.8/15.8.2/15.8.2.5/S15.8.2.5_A24.js | 7372 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Math.atan2, recommended that implementations use the approximation algorithms for IEEE 754 arithmetic contained in fdlibm
*
* @path ch15/15.8/15.8.2/15.8.2.5/S15.8.2.5_A24.js
* @description Checking if Math.atan2(argument1, argument2) is approximately equals to its mathematical values on the set of 64 argument1 values and 64 argument2 values; all the sample values is calculated with LibC
*/
$INCLUDE("math_precision.js");
$INCLUDE("math_isequal.js");
// CHECK#1
vnum = 64;
var x1 = new Array();
x1[0] = -16.00000000000000000000;
x1[1] = -15.49206349206349200000;
x1[2] = -14.98412698412698400000;
x1[3] = -14.47619047619047600000;
x1[4] = -13.96825396825396800000;
x1[5] = -13.46031746031746000000;
x1[6] = -12.95238095238095300000;
x1[7] = -12.44444444444444500000;
x1[8] = -11.93650793650793700000;
x1[9] = -11.42857142857142900000;
x1[10] = -10.92063492063492100000;
x1[11] = -10.41269841269841300000;
x1[12] = -9.90476190476190510000;
x1[13] = -9.39682539682539720000;
x1[14] = -8.88888888888888930000;
x1[15] = -8.38095238095238140000;
x1[16] = -7.87301587301587350000;
x1[17] = -7.36507936507936560000;
x1[18] = -6.85714285714285770000;
x1[19] = -6.34920634920634970000;
x1[20] = -5.84126984126984180000;
x1[21] = -5.33333333333333390000;
x1[22] = -4.82539682539682600000;
x1[23] = -4.31746031746031810000;
x1[24] = -3.80952380952381020000;
x1[25] = -3.30158730158730230000;
x1[26] = -2.79365079365079440000;
x1[27] = -2.28571428571428650000;
x1[28] = -1.77777777777777860000;
x1[29] = -1.26984126984127070000;
x1[30] = -0.76190476190476275000;
x1[31] = -0.25396825396825484000;
x1[32] = 0.25396825396825307000;
x1[33] = 0.76190476190476275000;
x1[34] = 1.26984126984126890000;
x1[35] = 1.77777777777777860000;
x1[36] = 2.28571428571428470000;
x1[37] = 2.79365079365079440000;
x1[38] = 3.30158730158730050000;
x1[39] = 3.80952380952381020000;
x1[40] = 4.31746031746031630000;
x1[41] = 4.82539682539682600000;
x1[42] = 5.33333333333333210000;
x1[43] = 5.84126984126984180000;
x1[44] = 6.34920634920634800000;
x1[45] = 6.85714285714285770000;
x1[46] = 7.36507936507936380000;
x1[47] = 7.87301587301587350000;
x1[48] = 8.38095238095237960000;
x1[49] = 8.88888888888888930000;
x1[50] = 9.39682539682539540000;
x1[51] = 9.90476190476190510000;
x1[52] = 10.41269841269841100000;
x1[53] = 10.92063492063492100000;
x1[54] = 11.42857142857142700000;
x1[55] = 11.93650793650793700000;
x1[56] = 12.44444444444444300000;
x1[57] = 12.95238095238095300000;
x1[58] = 13.46031746031745900000;
x1[59] = 13.96825396825396800000;
x1[60] = 14.47619047619047400000;
x1[61] = 14.98412698412698400000;
x1[62] = 15.49206349206349000000;
x1[63] = 16.00000000000000000000;
var x2 = new Array();
x2[0] = -8.00000000000000000000;
x2[1] = -7.74603174603174600000;
x2[2] = -7.49206349206349210000;
x2[3] = -7.23809523809523810000;
x2[4] = -6.98412698412698420000;
x2[5] = -6.73015873015873020000;
x2[6] = -6.47619047619047630000;
x2[7] = -6.22222222222222230000;
x2[8] = -5.96825396825396840000;
x2[9] = -5.71428571428571440000;
x2[10] = -5.46031746031746050000;
x2[11] = -5.20634920634920650000;
x2[12] = -4.95238095238095260000;
x2[13] = -4.69841269841269860000;
x2[14] = -4.44444444444444460000;
x2[15] = -4.19047619047619070000;
x2[16] = -3.93650793650793670000;
x2[17] = -3.68253968253968280000;
x2[18] = -3.42857142857142880000;
x2[19] = -3.17460317460317490000;
x2[20] = -2.92063492063492090000;
x2[21] = -2.66666666666666700000;
x2[22] = -2.41269841269841300000;
x2[23] = -2.15873015873015910000;
x2[24] = -1.90476190476190510000;
x2[25] = -1.65079365079365110000;
x2[26] = -1.39682539682539720000;
x2[27] = -1.14285714285714320000;
x2[28] = -0.88888888888888928000;
x2[29] = -0.63492063492063533000;
x2[30] = -0.38095238095238138000;
x2[31] = -0.12698412698412742000;
x2[32] = 0.12698412698412653000;
x2[33] = 0.38095238095238138000;
x2[34] = 0.63492063492063444000;
x2[35] = 0.88888888888888928000;
x2[36] = 1.14285714285714230000;
x2[37] = 1.39682539682539720000;
x2[38] = 1.65079365079365030000;
x2[39] = 1.90476190476190510000;
x2[40] = 2.15873015873015820000;
x2[41] = 2.41269841269841300000;
x2[42] = 2.66666666666666610000;
x2[43] = 2.92063492063492090000;
x2[44] = 3.17460317460317400000;
x2[45] = 3.42857142857142880000;
x2[46] = 3.68253968253968190000;
x2[47] = 3.93650793650793670000;
x2[48] = 4.19047619047618980000;
x2[49] = 4.44444444444444460000;
x2[50] = 4.69841269841269770000;
x2[51] = 4.95238095238095260000;
x2[52] = 5.20634920634920560000;
x2[53] = 5.46031746031746050000;
x2[54] = 5.71428571428571350000;
x2[55] = 5.96825396825396840000;
x2[56] = 6.22222222222222140000;
x2[57] = 6.47619047619047630000;
x2[58] = 6.73015873015872930000;
x2[59] = 6.98412698412698420000;
x2[60] = 7.23809523809523720000;
x2[61] = 7.49206349206349210000;
x2[62] = 7.74603174603174520000;
x2[63] = 8.00000000000000000000;
var y = new Array();
y[0] = -2.03444393579570270000;
y[1] = -2.03444393579570270000;
y[2] = -2.03444393579570270000;
y[3] = -2.03444393579570270000;
y[4] = -2.03444393579570270000;
y[5] = -2.03444393579570270000;
y[6] = -2.03444393579570270000;
y[7] = -2.03444393579570270000;
y[8] = -2.03444393579570270000;
y[9] = -2.03444393579570270000;
y[10] = -2.03444393579570270000;
y[11] = -2.03444393579570270000;
y[12] = -2.03444393579570270000;
y[13] = -2.03444393579570270000;
y[14] = -2.03444393579570270000;
y[15] = -2.03444393579570270000;
y[16] = -2.03444393579570270000;
y[17] = -2.03444393579570270000;
y[18] = -2.03444393579570270000;
y[19] = -2.03444393579570270000;
y[20] = -2.03444393579570270000;
y[21] = -2.03444393579570270000;
y[22] = -2.03444393579570270000;
y[23] = -2.03444393579570270000;
y[24] = -2.03444393579570270000;
y[25] = -2.03444393579570270000;
y[26] = -2.03444393579570270000;
y[27] = -2.03444393579570270000;
y[28] = -2.03444393579570270000;
y[29] = -2.03444393579570270000;
y[30] = -2.03444393579570270000;
y[31] = -2.03444393579570270000;
y[32] = 1.10714871779409040000;
y[33] = 1.10714871779409040000;
y[34] = 1.10714871779409040000;
y[35] = 1.10714871779409040000;
y[36] = 1.10714871779409040000;
y[37] = 1.10714871779409040000;
y[38] = 1.10714871779409040000;
y[39] = 1.10714871779409040000;
y[40] = 1.10714871779409040000;
y[41] = 1.10714871779409040000;
y[42] = 1.10714871779409040000;
y[43] = 1.10714871779409040000;
y[44] = 1.10714871779409040000;
y[45] = 1.10714871779409040000;
y[46] = 1.10714871779409040000;
y[47] = 1.10714871779409040000;
y[48] = 1.10714871779409040000;
y[49] = 1.10714871779409040000;
y[50] = 1.10714871779409040000;
y[51] = 1.10714871779409040000;
y[52] = 1.10714871779409040000;
y[53] = 1.10714871779409040000;
y[54] = 1.10714871779409040000;
y[55] = 1.10714871779409040000;
y[56] = 1.10714871779409040000;
y[57] = 1.10714871779409040000;
y[58] = 1.10714871779409040000;
y[59] = 1.10714871779409040000;
y[60] = 1.10714871779409040000;
y[61] = 1.10714871779409040000;
y[62] = 1.10714871779409040000;
y[63] = 1.10714871779409040000;
var val;
for (i = 0; i < vnum; i++)
{
val = Math.atan2(x1[i], x2[i]);
if (!isEqual(val, y[i]))
{
$ERROR("\nx1 = " + x1[i] + "\nx2 = " + x2[i] + "\nlibc.atan2(x1,x2) = " + y[i] + "\nMath.atan2(x1,x2) = " + Math.atan2(x1[i],x2[i]) + "\nMath.abs(libc.atan2(x1,x2) - Math.atan2(x1,x2)) > " + prec + "\n\n");
}
}
| apache-2.0 |
GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/aria-query/lib/etc/roles/dpub/docDedicationRole.js | 867 | "use strict";
var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var docDedicationRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {
'aria-disabled': null,
'aria-errormessage': null,
'aria-expanded': null,
'aria-haspopup': null,
'aria-invalid': null
},
relatedConcepts: [{
concept: {
name: 'dedication [EPUB-SSV]'
},
module: 'EPUB'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = docDedicationRole;
exports.default = _default; | apache-2.0 |
mre/gollum | vendor/github.com/aws/aws-sdk-go/aws/request/request.go | 16481 | package request
import (
"bytes"
"fmt"
"io"
"net"
"net/http"
"net/url"
"reflect"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/client/metadata"
)
// CanceledErrorCode is the error code that will be returned by an
// API request that was canceled. Requests given a aws.Context may
// return this error when canceled.
const CanceledErrorCode = "RequestCanceled"
// A Request is the service request to be made.
type Request struct {
Config aws.Config
ClientInfo metadata.ClientInfo
Handlers Handlers
Retryer
Time time.Time
ExpireTime time.Duration
Operation *Operation
HTTPRequest *http.Request
HTTPResponse *http.Response
Body io.ReadSeeker
BodyStart int64 // offset from beginning of Body that the request body starts
Params interface{}
Error error
Data interface{}
RequestID string
RetryCount int
Retryable *bool
RetryDelay time.Duration
NotHoist bool
SignedHeaderVals http.Header
LastSignedAt time.Time
context aws.Context
built bool
// Need to persist an intermediate body between the input Body and HTTP
// request body because the HTTP Client's transport can maintain a reference
// to the HTTP request's body after the client has returned. This value is
// safe to use concurrently and wrap the input Body for each HTTP request.
safeBody *offsetReader
}
// An Operation is the service API operation to be made.
type Operation struct {
Name string
HTTPMethod string
HTTPPath string
*Paginator
BeforePresignFn func(r *Request) error
}
// New returns a new Request pointer for the service API
// operation and parameters.
//
// Params is any value of input parameters to be the request payload.
// Data is pointer value to an object which the request's response
// payload will be deserialized to.
func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers,
retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request {
method := operation.HTTPMethod
if method == "" {
method = "POST"
}
httpReq, _ := http.NewRequest(method, "", nil)
var err error
httpReq.URL, err = url.Parse(clientInfo.Endpoint + operation.HTTPPath)
if err != nil {
httpReq.URL = &url.URL{}
err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err)
}
r := &Request{
Config: cfg,
ClientInfo: clientInfo,
Handlers: handlers.Copy(),
Retryer: retryer,
Time: time.Now(),
ExpireTime: 0,
Operation: operation,
HTTPRequest: httpReq,
Body: nil,
Params: params,
Error: err,
Data: data,
}
r.SetBufferBody([]byte{})
return r
}
// A Option is a functional option that can augment or modify a request when
// using a WithContext API operation method.
type Option func(*Request)
// WithGetResponseHeader builds a request Option which will retrieve a single
// header value from the HTTP Response. If there are multiple values for the
// header key use WithGetResponseHeaders instead to access the http.Header
// map directly. The passed in val pointer must be non-nil.
//
// This Option can be used multiple times with a single API operation.
//
// var id2, versionID string
// svc.PutObjectWithContext(ctx, params,
// request.WithGetResponseHeader("x-amz-id-2", &id2),
// request.WithGetResponseHeader("x-amz-version-id", &versionID),
// )
func WithGetResponseHeader(key string, val *string) Option {
return func(r *Request) {
r.Handlers.Complete.PushBack(func(req *Request) {
*val = req.HTTPResponse.Header.Get(key)
})
}
}
// WithGetResponseHeaders builds a request Option which will retrieve the
// headers from the HTTP response and assign them to the passed in headers
// variable. The passed in headers pointer must be non-nil.
//
// var headers http.Header
// svc.PutObjectWithContext(ctx, params, request.WithGetResponseHeaders(&headers))
func WithGetResponseHeaders(headers *http.Header) Option {
return func(r *Request) {
r.Handlers.Complete.PushBack(func(req *Request) {
*headers = req.HTTPResponse.Header
})
}
}
// WithLogLevel is a request option that will set the request to use a specific
// log level when the request is made.
//
// svc.PutObjectWithContext(ctx, params, request.WithLogLevel(aws.LogDebugWithHTTPBody)
func WithLogLevel(l aws.LogLevelType) Option {
return func(r *Request) {
r.Config.LogLevel = aws.LogLevel(l)
}
}
// ApplyOptions will apply each option to the request calling them in the order
// the were provided.
func (r *Request) ApplyOptions(opts ...Option) {
for _, opt := range opts {
opt(r)
}
}
// Context will always returns a non-nil context. If Request does not have a
// context aws.BackgroundContext will be returned.
func (r *Request) Context() aws.Context {
if r.context != nil {
return r.context
}
return aws.BackgroundContext()
}
// SetContext adds a Context to the current request that can be used to cancel
// a in-flight request. The Context value must not be nil, or this method will
// panic.
//
// Unlike http.Request.WithContext, SetContext does not return a copy of the
// Request. It is not safe to use use a single Request value for multiple
// requests. A new Request should be created for each API operation request.
//
// Go 1.6 and below:
// The http.Request's Cancel field will be set to the Done() value of
// the context. This will overwrite the Cancel field's value.
//
// Go 1.7 and above:
// The http.Request.WithContext will be used to set the context on the underlying
// http.Request. This will create a shallow copy of the http.Request. The SDK
// may create sub contexts in the future for nested requests such as retries.
func (r *Request) SetContext(ctx aws.Context) {
if ctx == nil {
panic("context cannot be nil")
}
setRequestContext(r, ctx)
}
// WillRetry returns if the request's can be retried.
func (r *Request) WillRetry() bool {
return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries()
}
// ParamsFilled returns if the request's parameters have been populated
// and the parameters are valid. False is returned if no parameters are
// provided or invalid.
func (r *Request) ParamsFilled() bool {
return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid()
}
// DataFilled returns true if the request's data for response deserialization
// target has been set and is a valid. False is returned if data is not
// set, or is invalid.
func (r *Request) DataFilled() bool {
return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid()
}
// SetBufferBody will set the request's body bytes that will be sent to
// the service API.
func (r *Request) SetBufferBody(buf []byte) {
r.SetReaderBody(bytes.NewReader(buf))
}
// SetStringBody sets the body of the request to be backed by a string.
func (r *Request) SetStringBody(s string) {
r.SetReaderBody(strings.NewReader(s))
}
// SetReaderBody will set the request's body reader.
func (r *Request) SetReaderBody(reader io.ReadSeeker) {
r.Body = reader
r.ResetBody()
}
// Presign returns the request's signed URL. Error will be returned
// if the signing fails.
func (r *Request) Presign(expireTime time.Duration) (string, error) {
r.ExpireTime = expireTime
r.NotHoist = false
if r.Operation.BeforePresignFn != nil {
r = r.copy()
err := r.Operation.BeforePresignFn(r)
if err != nil {
return "", err
}
}
r.Sign()
if r.Error != nil {
return "", r.Error
}
return r.HTTPRequest.URL.String(), nil
}
// PresignRequest behaves just like presign, but hoists all headers and signs them.
// Also returns the signed hash back to the user
func (r *Request) PresignRequest(expireTime time.Duration) (string, http.Header, error) {
r.ExpireTime = expireTime
r.NotHoist = true
r.Sign()
if r.Error != nil {
return "", nil, r.Error
}
return r.HTTPRequest.URL.String(), r.SignedHeaderVals, nil
}
func debugLogReqError(r *Request, stage string, retrying bool, err error) {
if !r.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) {
return
}
retryStr := "not retrying"
if retrying {
retryStr = "will retry"
}
r.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v",
stage, r.ClientInfo.ServiceName, r.Operation.Name, retryStr, err))
}
// Build will build the request's object so it can be signed and sent
// to the service. Build will also validate all the request's parameters.
// Anny additional build Handlers set on this request will be run
// in the order they were set.
//
// The request will only be built once. Multiple calls to build will have
// no effect.
//
// If any Validate or Build errors occur the build will stop and the error
// which occurred will be returned.
func (r *Request) Build() error {
if !r.built {
r.Handlers.Validate.Run(r)
if r.Error != nil {
debugLogReqError(r, "Validate Request", false, r.Error)
return r.Error
}
r.Handlers.Build.Run(r)
if r.Error != nil {
debugLogReqError(r, "Build Request", false, r.Error)
return r.Error
}
r.built = true
}
return r.Error
}
// Sign will sign the request returning error if errors are encountered.
//
// Send will build the request prior to signing. All Sign Handlers will
// be executed in the order they were set.
func (r *Request) Sign() error {
r.Build()
if r.Error != nil {
debugLogReqError(r, "Build Request", false, r.Error)
return r.Error
}
r.Handlers.Sign.Run(r)
return r.Error
}
// ResetBody rewinds the request body backto its starting position, and
// set's the HTTP Request body reference. When the body is read prior
// to being sent in the HTTP request it will need to be rewound.
func (r *Request) ResetBody() {
if r.safeBody != nil {
r.safeBody.Close()
}
r.safeBody = newOffsetReader(r.Body, r.BodyStart)
// Go 1.8 tightened and clarified the rules code needs to use when building
// requests with the http package. Go 1.8 removed the automatic detection
// of if the Request.Body was empty, or actually had bytes in it. The SDK
// always sets the Request.Body even if it is empty and should not actually
// be sent. This is incorrect.
//
// Go 1.8 did add a http.NoBody value that the SDK can use to tell the http
// client that the request really should be sent without a body. The
// Request.Body cannot be set to nil, which is preferable, because the
// field is exported and could introduce nil pointer dereferences for users
// of the SDK if they used that field.
//
// Related golang/go#18257
l, err := computeBodyLength(r.Body)
if err != nil {
r.Error = awserr.New("SerializationError", "failed to compute request body size", err)
return
}
if l == 0 {
r.HTTPRequest.Body = noBodyReader
} else if l > 0 {
r.HTTPRequest.Body = r.safeBody
} else {
// Hack to prevent sending bodies for methods where the body
// should be ignored by the server. Sending bodies on these
// methods without an associated ContentLength will cause the
// request to socket timeout because the server does not handle
// Transfer-Encoding: chunked bodies for these methods.
//
// This would only happen if a aws.ReaderSeekerCloser was used with
// a io.Reader that was not also an io.Seeker.
switch r.Operation.HTTPMethod {
case "GET", "HEAD", "DELETE":
r.HTTPRequest.Body = noBodyReader
default:
r.HTTPRequest.Body = r.safeBody
}
}
}
// Attempts to compute the length of the body of the reader using the
// io.Seeker interface. If the value is not seekable because of being
// a ReaderSeekerCloser without an unerlying Seeker -1 will be returned.
// If no error occurs the length of the body will be returned.
func computeBodyLength(r io.ReadSeeker) (int64, error) {
seekable := true
// Determine if the seeker is actually seekable. ReaderSeekerCloser
// hides the fact that a io.Readers might not actually be seekable.
switch v := r.(type) {
case aws.ReaderSeekerCloser:
seekable = v.IsSeeker()
case *aws.ReaderSeekerCloser:
seekable = v.IsSeeker()
}
if !seekable {
return -1, nil
}
curOffset, err := r.Seek(0, 1)
if err != nil {
return 0, err
}
endOffset, err := r.Seek(0, 2)
if err != nil {
return 0, err
}
_, err = r.Seek(curOffset, 0)
if err != nil {
return 0, err
}
return endOffset - curOffset, nil
}
// GetBody will return an io.ReadSeeker of the Request's underlying
// input body with a concurrency safe wrapper.
func (r *Request) GetBody() io.ReadSeeker {
return r.safeBody
}
// Send will send the request returning error if errors are encountered.
//
// Send will sign the request prior to sending. All Send Handlers will
// be executed in the order they were set.
//
// Canceling a request is non-deterministic. If a request has been canceled,
// then the transport will choose, randomly, one of the state channels during
// reads or getting the connection.
//
// readLoop() and getConn(req *Request, cm connectMethod)
// https://github.com/golang/go/blob/master/src/net/http/transport.go
//
// Send will not close the request.Request's body.
func (r *Request) Send() error {
defer func() {
// Regardless of success or failure of the request trigger the Complete
// request handlers.
r.Handlers.Complete.Run(r)
}()
for {
if aws.BoolValue(r.Retryable) {
if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) {
r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d",
r.ClientInfo.ServiceName, r.Operation.Name, r.RetryCount))
}
// The previous http.Request will have a reference to the r.Body
// and the HTTP Client's Transport may still be reading from
// the request's body even though the Client's Do returned.
r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil)
r.ResetBody()
// Closing response body to ensure that no response body is leaked
// between retry attempts.
if r.HTTPResponse != nil && r.HTTPResponse.Body != nil {
r.HTTPResponse.Body.Close()
}
}
r.Sign()
if r.Error != nil {
return r.Error
}
r.Retryable = nil
r.Handlers.Send.Run(r)
if r.Error != nil {
if !shouldRetryCancel(r) {
return r.Error
}
err := r.Error
r.Handlers.Retry.Run(r)
r.Handlers.AfterRetry.Run(r)
if r.Error != nil {
debugLogReqError(r, "Send Request", false, r.Error)
return r.Error
}
debugLogReqError(r, "Send Request", true, err)
continue
}
r.Handlers.UnmarshalMeta.Run(r)
r.Handlers.ValidateResponse.Run(r)
if r.Error != nil {
err := r.Error
r.Handlers.UnmarshalError.Run(r)
r.Handlers.Retry.Run(r)
r.Handlers.AfterRetry.Run(r)
if r.Error != nil {
debugLogReqError(r, "Validate Response", false, r.Error)
return r.Error
}
debugLogReqError(r, "Validate Response", true, err)
continue
}
r.Handlers.Unmarshal.Run(r)
if r.Error != nil {
err := r.Error
r.Handlers.Retry.Run(r)
r.Handlers.AfterRetry.Run(r)
if r.Error != nil {
debugLogReqError(r, "Unmarshal Response", false, r.Error)
return r.Error
}
debugLogReqError(r, "Unmarshal Response", true, err)
continue
}
break
}
return nil
}
// copy will copy a request which will allow for local manipulation of the
// request.
func (r *Request) copy() *Request {
req := &Request{}
*req = *r
req.Handlers = r.Handlers.Copy()
op := *r.Operation
req.Operation = &op
return req
}
// AddToUserAgent adds the string to the end of the request's current user agent.
func AddToUserAgent(r *Request, s string) {
curUA := r.HTTPRequest.Header.Get("User-Agent")
if len(curUA) > 0 {
s = curUA + " " + s
}
r.HTTPRequest.Header.Set("User-Agent", s)
}
func shouldRetryCancel(r *Request) bool {
awsErr, ok := r.Error.(awserr.Error)
timeoutErr := false
errStr := r.Error.Error()
if ok {
if awsErr.Code() == CanceledErrorCode {
return false
}
err := awsErr.OrigErr()
netErr, netOK := err.(net.Error)
timeoutErr = netOK && netErr.Temporary()
if urlErr, ok := err.(*url.Error); !timeoutErr && ok {
errStr = urlErr.Err.Error()
}
}
// There can be two types of canceled errors here.
// The first being a net.Error and the other being an error.
// If the request was timed out, we want to continue the retry
// process. Otherwise, return the canceled error.
return timeoutErr ||
(errStr != "net/http: request canceled" &&
errStr != "net/http: request canceled while waiting for connection")
}
| apache-2.0 |
mothpc/immutables | generator-fixture/src/org/immutables/generator/fixture/ForComprehencer.java | 975 | /*
Copyright 2014 Immutables Authors and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.immutables.generator.fixture;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.immutables.generator.AbstractTemplate;
import org.immutables.generator.Generator;
@Generator.Template
public class ForComprehencer extends AbstractTemplate {
public final List<Integer> points = ImmutableList.of(1, 2, 3, 5, 8, 13);
}
| apache-2.0 |
mrgroen/reCAPTCHA | test/javasource/system/proxies/SoapFault.java | 6467 | // This file was generated by Mendix Business Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package system.proxies;
import com.mendix.core.Core;
import com.mendix.core.CoreException;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.systemwideinterfaces.core.IMendixIdentifier;
import com.mendix.systemwideinterfaces.core.IMendixObject;
/**
*
*/
public class SoapFault extends system.proxies.Error
{
/**
* Internal name of this entity
*/
public static final String entityName = "System.SoapFault";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
Code("Code"),
Reason("Reason"),
Node("Node"),
Role("Role"),
Detail("Detail"),
ErrorType("ErrorType"),
Message("Message"),
Stacktrace("Stacktrace");
private String metaName;
MemberNames(String s)
{
metaName = s;
}
@Override
public String toString()
{
return metaName;
}
}
public SoapFault(IContext context)
{
this(context, Core.instantiate(context, "System.SoapFault"));
}
protected SoapFault(IContext context, IMendixObject soapFaultMendixObject)
{
super(context, soapFaultMendixObject);
if (!Core.isSubClassOf("System.SoapFault", soapFaultMendixObject.getType()))
throw new IllegalArgumentException("The given object is not a System.SoapFault");
}
/**
* @deprecated Use 'SoapFault.load(IContext, IMendixIdentifier)' instead.
*/
@Deprecated
public static system.proxies.SoapFault initialize(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException
{
return system.proxies.SoapFault.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.getSudoContext() can be used to obtain sudo access).
*/
public static system.proxies.SoapFault initialize(IContext context, IMendixObject mendixObject)
{
return new system.proxies.SoapFault(context, mendixObject);
}
public static system.proxies.SoapFault load(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException
{
IMendixObject mendixObject = Core.retrieveId(context, mendixIdentifier);
return system.proxies.SoapFault.initialize(context, mendixObject);
}
/**
* @return value of Code
*/
public final String getCode()
{
return getCode(getContext());
}
/**
* @param context
* @return value of Code
*/
public final String getCode(IContext context)
{
return (String) getMendixObject().getValue(context, MemberNames.Code.toString());
}
/**
* Set value of Code
* @param code
*/
public final void setCode(String code)
{
setCode(getContext(), code);
}
/**
* Set value of Code
* @param context
* @param code
*/
public final void setCode(IContext context, String code)
{
getMendixObject().setValue(context, MemberNames.Code.toString(), code);
}
/**
* @return value of Reason
*/
public final String getReason()
{
return getReason(getContext());
}
/**
* @param context
* @return value of Reason
*/
public final String getReason(IContext context)
{
return (String) getMendixObject().getValue(context, MemberNames.Reason.toString());
}
/**
* Set value of Reason
* @param reason
*/
public final void setReason(String reason)
{
setReason(getContext(), reason);
}
/**
* Set value of Reason
* @param context
* @param reason
*/
public final void setReason(IContext context, String reason)
{
getMendixObject().setValue(context, MemberNames.Reason.toString(), reason);
}
/**
* @return value of Node
*/
public final String getNode()
{
return getNode(getContext());
}
/**
* @param context
* @return value of Node
*/
public final String getNode(IContext context)
{
return (String) getMendixObject().getValue(context, MemberNames.Node.toString());
}
/**
* Set value of Node
* @param node
*/
public final void setNode(String node)
{
setNode(getContext(), node);
}
/**
* Set value of Node
* @param context
* @param node
*/
public final void setNode(IContext context, String node)
{
getMendixObject().setValue(context, MemberNames.Node.toString(), node);
}
/**
* @return value of Role
*/
public final String getRole()
{
return getRole(getContext());
}
/**
* @param context
* @return value of Role
*/
public final String getRole(IContext context)
{
return (String) getMendixObject().getValue(context, MemberNames.Role.toString());
}
/**
* Set value of Role
* @param role
*/
public final void setRole(String role)
{
setRole(getContext(), role);
}
/**
* Set value of Role
* @param context
* @param role
*/
public final void setRole(IContext context, String role)
{
getMendixObject().setValue(context, MemberNames.Role.toString(), role);
}
/**
* @return value of Detail
*/
public final String getDetail()
{
return getDetail(getContext());
}
/**
* @param context
* @return value of Detail
*/
public final String getDetail(IContext context)
{
return (String) getMendixObject().getValue(context, MemberNames.Detail.toString());
}
/**
* Set value of Detail
* @param detail
*/
public final void setDetail(String detail)
{
setDetail(getContext(), detail);
}
/**
* Set value of Detail
* @param context
* @param detail
*/
public final void setDetail(IContext context, String detail)
{
getMendixObject().setValue(context, MemberNames.Detail.toString(), detail);
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final system.proxies.SoapFault that = (system.proxies.SoapFault) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static String getType()
{
return "System.SoapFault";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@Override
@Deprecated
public String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
| apache-2.0 |
carynbear/cordova-lib | cordova-lib/src/plugman/plugman.js | 8113 | /*
*
* Copyright 2013 Anis Kadri
*
* 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.
*
*/
// copyright (c) 2013 Andrew Lunny, Adobe Systems
var events = require('cordova-common').events;
var Q = require('q');
function addProperty(o, symbol, modulePath, doWrap) {
var val = null;
if (doWrap) {
o[symbol] = function() {
val = val || require(modulePath);
if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
// If args exist and the last one is a function, it's the callback.
var args = Array.prototype.slice.call(arguments);
var cb = args.pop();
val.apply(o, args).done(function(result) {cb(undefined, result);}, cb);
} else {
val.apply(o, arguments).done(null, function(err){ throw err; });
}
};
} else {
// The top-level plugman.foo
Object.defineProperty(o, symbol, {
configurable: true,
get : function() { val = val || require(modulePath); return val; },
set : function(v) { val = v; }
});
}
// The plugman.raw.foo
Object.defineProperty(o.raw, symbol, {
configurable: true,
get : function() { val = val || require(modulePath); return val; },
set : function(v) { val = v; }
});
}
var plugman = {
on: events.on.bind(events),
off: events.removeListener.bind(events),
removeAllListeners: events.removeAllListeners.bind(events),
emit: events.emit.bind(events),
raw: {}
};
addProperty(plugman, 'install', './install', true);
addProperty(plugman, 'uninstall', './uninstall', true);
addProperty(plugman, 'fetch', './fetch', true);
addProperty(plugman, 'browserify', './browserify');
addProperty(plugman, 'help', './help');
addProperty(plugman, 'config', './config', true);
addProperty(plugman, 'owner', './owner', true);
addProperty(plugman, 'search', './search', true);
addProperty(plugman, 'info', './info', true);
addProperty(plugman, 'create', './create', true);
addProperty(plugman, 'platform', './platform_operation', true);
addProperty(plugman, 'createpackagejson', './createpackagejson', true);
plugman.commands = {
'config' : function(cli_opts) {
plugman.config(cli_opts.argv.remain, function(err) {
if (err) throw err;
else console.log('done');
});
},
'owner' : function(cli_opts) {
plugman.owner(cli_opts.argv.remain);
},
'install' : function(cli_opts) {
if(!cli_opts.platform || !cli_opts.project || !cli_opts.plugin) {
return console.log(plugman.help());
}
if(cli_opts.browserify === true) {
plugman.prepare = require('./prepare-browserify');
}
var cli_variables = {};
if (cli_opts.variable) {
cli_opts.variable.forEach(function (variable) {
var tokens = variable.split('=');
var key = tokens.shift().toUpperCase();
if (/^[\w-_]+$/.test(key)) cli_variables[key] = tokens.join('=');
});
}
var opts = {
subdir: '.',
cli_variables: cli_variables,
fetch: cli_opts.fetch || false,
save: cli_opts.save || false,
www_dir: cli_opts.www,
searchpath: cli_opts.searchpath,
link: cli_opts.link,
projectRoot: cli_opts.project
};
var p = Q();
cli_opts.plugin.forEach(function (pluginSrc) {
p = p.then(function () {
return plugman.raw.install(cli_opts.platform, cli_opts.project, pluginSrc, cli_opts.plugins_dir, opts);
});
});
return p;
},
'uninstall': function(cli_opts) {
if(!cli_opts.platform || !cli_opts.project || !cli_opts.plugin) {
return console.log(plugman.help());
}
if(cli_opts.browserify === true) {
plugman.prepare = require('./prepare-browserify');
}
var p = Q();
cli_opts.plugin.forEach(function (pluginSrc) {
var opts = {
www_dir: cli_opts.www,
save: cli_opts.save || false,
fetch: cli_opts.fetch || false,
projectRoot: cli_opts.project
};
p = p.then(function () {
return plugman.raw.uninstall(cli_opts.platform, cli_opts.project, pluginSrc, cli_opts.plugins_dir, opts);
});
});
return p;
},
'search' : function(cli_opts) {
plugman.search(cli_opts.argv.remain, function(err, plugins) {
if (err) throw err;
else {
for(var plugin in plugins) {
console.log(plugins[plugin].name, '-', plugins[plugin].description || 'no description provided');
}
}
});
},
'info' : function(cli_opts) {
plugman.info(cli_opts.argv.remain, function(err, plugin_info) {
if (err) throw err;
else {
console.log('name:', plugin_info.name);
console.log('version:', plugin_info.version);
if (plugin_info.engines) {
for(var i = 0, j = plugin_info.engines.length ; i < j ; i++) {
console.log(plugin_info.engines[i].name, 'version:', plugin_info.engines[i].version);
}
}
}
});
},
'publish' : function() {
events.emit('error', 'The publish functionality is not supported anymore since the Cordova Plugin registry\n' +
'is moving to read-only state. For publishing use corresponding \'npm\' commands.\n\n' +
'If for any reason you still need for \'plugman publish\' - consider downgrade to [email protected]');
},
'unpublish': function(cli_opts) {
events.emit('error', 'The publish functionality is not supported anymore since the Cordova Plugin registry\n' +
'is moving to read-only state. For publishing/unpublishing use corresponding \'npm\' commands.\n\n' +
'If for any reason you still need for \'plugman unpublish\' - consider downgrade to [email protected]');
},
'create': function(cli_opts) {
if( !cli_opts.name || !cli_opts.plugin_id || !cli_opts.plugin_version) {
return console.log( plugman.help() );
}
var cli_variables = {};
if (cli_opts.variable) {
cli_opts.variable.forEach(function (variable) {
var tokens = variable.split('=');
var key = tokens.shift().toUpperCase();
if (/^[\w-_]+$/.test(key)) cli_variables[key] = tokens.join('=');
});
}
plugman.create( cli_opts.name, cli_opts.plugin_id, cli_opts.plugin_version, cli_opts.path || '.', cli_variables );
},
'platform': function(cli_opts) {
var operation = cli_opts.argv.remain[ 0 ] || '';
if( ( operation !== 'add' && operation !== 'remove' ) || !cli_opts.platform_name ) {
return console.log( plugman.help() );
}
plugman.platform( { operation: operation, platform_name: cli_opts.platform_name } );
},
'createpackagejson' : function(cli_opts) {
var plugin_path = cli_opts.argv.remain[0];
if(!plugin_path) {
return console.log(plugman.help());
}
plugman.createpackagejson(plugin_path);
},
};
module.exports = plugman;
| apache-2.0 |
plietar/certificate-transparency | python/ct/cert_analysis/tld_check_test.py | 798 | #!/usr/bin/env python
# coding=utf-8
import mock
import unittest
from ct.cert_analysis import tld_check
def gen_dns_name(name):
dns_name = mock.Mock()
dns_name.value = name
return dns_name
EXAMPLE = gen_dns_name("example.com")
class TLDCheckTest(unittest.TestCase):
@mock.patch('ct.cert_analysis.tld_list.TLDList')
def test_tld_list_not_created_until_check_called(self, tld_list):
instance = mock.Mock()
instance.match_certificate_name.return_value = [False, False, False]
tld_list.return_value = instance
self.assertIsNone(tld_check.CheckTldMatches.TLD_LIST_)
_ = tld_check.CheckTldMatches.check([EXAMPLE], "dNSNames: ")
self.assertIsNotNone(tld_check.CheckTldMatches.TLD_LIST_)
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
babble/babble | include/ruby/lib/ruby/1.8/irb/extend-command.rb | 6848 | #
# irb/extend-command.rb - irb extend command
# $Release Version: 0.9.5$
# $Revision: 2906 $
# $Date: 2007-02-01 18:35:06 -0600 (Thu, 01 Feb 2007) $
# by Keiju ISHITSUKA([email protected])
#
# --
#
#
#
module IRB
#
# IRB extended command
#
module ExtendCommandBundle
EXCB = ExtendCommandBundle
NO_OVERRIDE = 0
OVERRIDE_PRIVATE_ONLY = 0x01
OVERRIDE_ALL = 0x02
def irb_exit(ret = 0)
irb_context.exit(ret)
end
def irb_context
IRB.CurrentContext
end
@ALIASES = [
[:context, :irb_context, NO_OVERRIDE],
[:conf, :irb_context, NO_OVERRIDE],
[:irb_quit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
[:exit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
[:quit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
]
@EXTEND_COMMANDS = [
[:irb_current_working_workspace, :CurrentWorkingWorkspace, "irb/cmd/chws",
[:irb_print_working_workspace, OVERRIDE_ALL],
[:irb_cwws, OVERRIDE_ALL],
[:irb_pwws, OVERRIDE_ALL],
# [:irb_cww, OVERRIDE_ALL],
# [:irb_pww, OVERRIDE_ALL],
[:cwws, NO_OVERRIDE],
[:pwws, NO_OVERRIDE],
# [:cww, NO_OVERRIDE],
# [:pww, NO_OVERRIDE],
[:irb_current_working_binding, OVERRIDE_ALL],
[:irb_print_working_binding, OVERRIDE_ALL],
[:irb_cwb, OVERRIDE_ALL],
[:irb_pwb, OVERRIDE_ALL],
# [:cwb, NO_OVERRIDE],
# [:pwb, NO_OVERRIDE]
],
[:irb_change_workspace, :ChangeWorkspace, "irb/cmd/chws",
[:irb_chws, OVERRIDE_ALL],
# [:irb_chw, OVERRIDE_ALL],
[:irb_cws, OVERRIDE_ALL],
# [:irb_cw, OVERRIDE_ALL],
[:chws, NO_OVERRIDE],
# [:chw, NO_OVERRIDE],
[:cws, NO_OVERRIDE],
# [:cw, NO_OVERRIDE],
[:irb_change_binding, OVERRIDE_ALL],
[:irb_cb, OVERRIDE_ALL],
[:cb, NO_OVERRIDE]],
[:irb_workspaces, :Workspaces, "irb/cmd/pushws",
[:workspaces, NO_OVERRIDE],
[:irb_bindings, OVERRIDE_ALL],
[:bindings, NO_OVERRIDE]],
[:irb_push_workspace, :PushWorkspace, "irb/cmd/pushws",
[:irb_pushws, OVERRIDE_ALL],
# [:irb_pushw, OVERRIDE_ALL],
[:pushws, NO_OVERRIDE],
# [:pushw, NO_OVERRIDE],
[:irb_push_binding, OVERRIDE_ALL],
[:irb_pushb, OVERRIDE_ALL],
[:pushb, NO_OVERRIDE]],
[:irb_pop_workspace, :PopWorkspace, "irb/cmd/pushws",
[:irb_popws, OVERRIDE_ALL],
# [:irb_popw, OVERRIDE_ALL],
[:popws, NO_OVERRIDE],
# [:popw, NO_OVERRIDE],
[:irb_pop_binding, OVERRIDE_ALL],
[:irb_popb, OVERRIDE_ALL],
[:popb, NO_OVERRIDE]],
[:irb_load, :Load, "irb/cmd/load"],
[:irb_require, :Require, "irb/cmd/load"],
[:irb_source, :Source, "irb/cmd/load",
[:source, NO_OVERRIDE]],
[:irb, :IrbCommand, "irb/cmd/subirb"],
[:irb_jobs, :Jobs, "irb/cmd/subirb",
[:jobs, NO_OVERRIDE]],
[:irb_fg, :Foreground, "irb/cmd/subirb",
[:fg, NO_OVERRIDE]],
[:irb_kill, :Kill, "irb/cmd/subirb",
[:kill, OVERRIDE_PRIVATE_ONLY]],
[:irb_help, :Help, "irb/cmd/help",
[:help, NO_OVERRIDE]],
]
def self.install_extend_commands
for args in @EXTEND_COMMANDS
def_extend_command(*args)
end
end
# aliases = [commans_alias, flag], ...
def self.def_extend_command(cmd_name, cmd_class, load_file = nil, *aliases)
case cmd_class
when Symbol
cmd_class = cmd_class.id2name
when String
when Class
cmd_class = cmd_class.name
end
if load_file
eval %[
def #{cmd_name}(*opts, &b)
require "#{load_file}"
eval %[
def #{cmd_name}(*opts, &b)
ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b)
end
]
send :#{cmd_name}, *opts, &b
end
]
else
eval %[
def #{cmd_name}(*opts, &b)
ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b)
end
]
end
for ali, flag in aliases
@ALIASES.push [ali, cmd_name, flag]
end
end
# override = {NO_OVERRIDE, OVERRIDE_PRIVATE_ONLY, OVERRIDE_ALL}
def install_alias_method(to, from, override = NO_OVERRIDE)
to = to.id2name unless to.kind_of?(String)
from = from.id2name unless from.kind_of?(String)
if override == OVERRIDE_ALL or
(override == OVERRIDE_PRIVATE_ONLY) && !respond_to?(to) or
(override == NO_OVERRIDE) && !respond_to?(to, true)
target = self
(class<<self;self;end).instance_eval{
if target.respond_to?(to, true) &&
!target.respond_to?(EXCB.irb_original_method_name(to), true)
alias_method(EXCB.irb_original_method_name(to), to)
end
alias_method to, from
}
else
print "irb: warn: can't alias #{to} from #{from}.\n"
end
end
def self.irb_original_method_name(method_name)
"irb_" + method_name + "_org"
end
def self.extend_object(obj)
unless (class<<obj;ancestors;end).include?(EXCB)
super
for ali, com, flg in @ALIASES
obj.install_alias_method(ali, com, flg)
end
end
end
install_extend_commands
end
# extension support for Context
module ContextExtender
CE = ContextExtender
@EXTEND_COMMANDS = [
[:eval_history=, "irb/ext/history.rb"],
[:use_tracer=, "irb/ext/tracer.rb"],
[:math_mode=, "irb/ext/math-mode.rb"],
[:use_loader=, "irb/ext/use-loader.rb"],
[:save_history=, "irb/ext/save-history.rb"],
]
def self.install_extend_commands
for args in @EXTEND_COMMANDS
def_extend_command(*args)
end
end
def self.def_extend_command(cmd_name, load_file, *aliases)
Context.module_eval %[
def #{cmd_name}(*opts, &b)
Context.module_eval {remove_method(:#{cmd_name})}
require "#{load_file}"
send :#{cmd_name}, *opts, &b
end
for ali in aliases
alias_method ali, cmd_name
end
]
end
CE.install_extend_commands
end
module MethodExtender
def def_pre_proc(base_method, extend_method)
base_method = base_method.to_s
extend_method = extend_method.to_s
alias_name = new_alias_name(base_method)
module_eval %[
alias_method alias_name, base_method
def #{base_method}(*opts)
send :#{extend_method}, *opts
send :#{alias_name}, *opts
end
]
end
def def_post_proc(base_method, extend_method)
base_method = base_method.to_s
extend_method = extend_method.to_s
alias_name = new_alias_name(base_method)
module_eval %[
alias_method alias_name, base_method
def #{base_method}(*opts)
send :#{alias_name}, *opts
send :#{extend_method}, *opts
end
]
end
# return #{prefix}#{name}#{postfix}<num>
def new_alias_name(name, prefix = "__alias_of__", postfix = "__")
base_name = "#{prefix}#{name}#{postfix}"
all_methods = instance_methods(true) + private_instance_methods(true)
same_methods = all_methods.grep(/^#{Regexp.quote(base_name)}[0-9]*$/)
return base_name if same_methods.empty?
no = same_methods.size
while !same_methods.include?(alias_name = base_name + no)
no += 1
end
alias_name
end
end
end
| apache-2.0 |
MeRPG/EndHQ-Libraries | src/org/apache/commons/lang3/JavaVersion.java | 4582 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;
/**
* <p>An enum representing all the versions of the Java specification.
* This is intended to mirror available values from the
* <em>java.specification.version</em> System property. </p>
*
* @since 3.0
* @version $Id: JavaVersion.java 1583482 2014-03-31 22:54:57Z niallp $
*/
public enum JavaVersion {
/**
* The Java version reported by Android. This is not an official Java version number.
*/
JAVA_0_9(1.5f, "0.9"),
/**
* Java 1.1.
*/
JAVA_1_1(1.1f, "1.1"),
/**
* Java 1.2.
*/
JAVA_1_2(1.2f, "1.2"),
/**
* Java 1.3.
*/
JAVA_1_3(1.3f, "1.3"),
/**
* Java 1.4.
*/
JAVA_1_4(1.4f, "1.4"),
/**
* Java 1.5.
*/
JAVA_1_5(1.5f, "1.5"),
/**
* Java 1.6.
*/
JAVA_1_6(1.6f, "1.6"),
/**
* Java 1.7.
*/
JAVA_1_7(1.7f, "1.7"),
/**
* Java 1.8.
*/
JAVA_1_8(1.8f, "1.8");
/**
* The float value.
*/
private final float value;
/**
* The standard name.
*/
private final String name;
/**
* Constructor.
*
* @param value the float value
* @param name the standard name, not null
*/
JavaVersion(final float value, final String name) {
this.value = value;
this.name = name;
}
//-----------------------------------------------------------------------
/**
* <p>Whether this version of Java is at least the version of Java passed in.</p>
*
* <p>For example:<br>
* {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}<p>
*
* @param requiredVersion the version to check against, not null
* @return true if this version is equal to or greater than the specified version
*/
public boolean atLeast(final JavaVersion requiredVersion) {
return this.value >= requiredVersion.value;
}
/**
* Transforms the given string with a Java version number to the
* corresponding constant of this enumeration class. This method is used
* internally.
*
* @param nom the Java version as string
* @return the corresponding enumeration constant or <b>null</b> if the
* version is unknown
*/
// helper for static importing
static JavaVersion getJavaVersion(final String nom) {
return get(nom);
}
/**
* Transforms the given string with a Java version number to the
* corresponding constant of this enumeration class. This method is used
* internally.
*
* @param nom the Java version as string
* @return the corresponding enumeration constant or <b>null</b> if the
* version is unknown
*/
static JavaVersion get(final String nom) {
if ("0.9".equals(nom)) {
return JAVA_0_9;
} else if ("1.1".equals(nom)) {
return JAVA_1_1;
} else if ("1.2".equals(nom)) {
return JAVA_1_2;
} else if ("1.3".equals(nom)) {
return JAVA_1_3;
} else if ("1.4".equals(nom)) {
return JAVA_1_4;
} else if ("1.5".equals(nom)) {
return JAVA_1_5;
} else if ("1.6".equals(nom)) {
return JAVA_1_6;
} else if ("1.7".equals(nom)) {
return JAVA_1_7;
} else if ("1.8".equals(nom)) {
return JAVA_1_8;
} else {
return null;
}
}
//-----------------------------------------------------------------------
/**
* <p>The string value is overridden to return the standard name.</p>
*
* <p>For example, <code>"1.5"</code>.</p>
*
* @return the name, not null
*/
@Override
public String toString() {
return name;
}
}
| apache-2.0 |
Ryman/rust | src/test/run-fail/rt-set-exit-status.rs | 764 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern:whatever
#![feature(phase)]
#[phase(syntax, link)] extern crate log;
use std::os;
fn main() {
error!("whatever");
// 101 is the code the runtime uses on task failure and the value
// compiletest expects run-fail tests to return.
os::set_exit_status(101);
}
| apache-2.0 |
myxyz/zstack | header/src/main/java/org/zstack/header/zone/ZoneVO.java | 287 | package org.zstack.header.zone;
import org.zstack.header.tag.AutoDeleteTag;
import org.zstack.header.vo.EO;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table
@EO(EOClazz = ZoneEO.class)
@AutoDeleteTag
public class ZoneVO extends ZoneAO {
}
| apache-2.0 |
fceller/arangodb | 3rdParty/boost/1.69.0/libs/geometry/test/algorithms/set_operations/intersection/test_intersection.hpp | 12818 | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.
// This file was modified by Oracle on 2016, 2017.
// Modifications copyright (c) 2016-2017, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_TEST_INTERSECTION_HPP
#define BOOST_GEOMETRY_TEST_INTERSECTION_HPP
#include <fstream>
#include <iomanip>
#include <boost/foreach.hpp>
#include <boost/variant/variant.hpp>
#include <boost/geometry/algorithms/intersection.hpp>
#include <boost/geometry/algorithms/area.hpp>
#include <boost/geometry/algorithms/correct.hpp>
#include <boost/geometry/algorithms/is_valid.hpp>
#include <boost/geometry/algorithms/length.hpp>
#include <boost/geometry/algorithms/num_points.hpp>
#include <boost/geometry/algorithms/num_interior_rings.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/geometry/io/wkt/wkt.hpp>
#if defined(TEST_WITH_SVG)
# include <boost/geometry/io/svg/svg_mapper.hpp>
#endif
#include <geometry_test_common.hpp>
#include "../setop_output_type.hpp"
#include "../check_validity.hpp"
struct ut_settings
{
double percentage;
bool test_validity;
bool debug;
explicit ut_settings(double p = 0.0001, bool tv = true)
: percentage(p)
, test_validity(tv)
, debug(false)
{}
};
template
<
typename G1,
typename G2,
typename ResultType,
typename IntersectionOutput
>
typename bg::default_area_result<G1>::type
check_result(
IntersectionOutput const& intersection_output,
std::string const& caseid,
std::size_t expected_count, std::size_t expected_holes_count,
int expected_point_count, double expected_length_or_area,
ut_settings const& settings)
{
typedef typename boost::range_value<IntersectionOutput>::type OutputType;
bool const is_line = bg::geometry_id<OutputType>::type::value == 2;
typename bg::default_area_result<G1>::type length_or_area = 0;
int n = 0;
std::size_t nholes = 0;
for (typename IntersectionOutput::const_iterator it = intersection_output.begin();
it != intersection_output.end();
++it)
{
if (expected_point_count > 0)
{
// here n should rather be of type std::size_t, but expected_point_count
// is set to -1 in some test cases so type int was left for now
n += static_cast<int>(bg::num_points(*it, true));
}
if (expected_holes_count > 0)
{
nholes += bg::num_interior_rings(*it);
}
// instead of specialization we check it run-time here
length_or_area += is_line
? bg::length(*it)
: bg::area(*it);
if (settings.debug)
{
std::cout << std::setprecision(20) << bg::wkt(*it) << std::endl;
}
}
if (settings.test_validity)
{
std::string message;
bool const valid = check_validity<ResultType>::apply(intersection_output, message);
BOOST_CHECK_MESSAGE(valid,
"intersection: " << caseid << " not valid: " << message
<< " type: " << (type_for_assert_message<G1, G2>()));
}
#if ! defined(BOOST_GEOMETRY_NO_BOOST_TEST)
#if ! defined(BOOST_GEOMETRY_NO_ROBUSTNESS)
if (expected_point_count > 0)
{
BOOST_CHECK_MESSAGE(bg::math::abs(n - expected_point_count) < 3,
"intersection: " << caseid
<< " #points expected: " << expected_point_count
<< " detected: " << n
<< " type: " << (type_for_assert_message<G1, G2>())
);
}
#endif
if (expected_count > 0)
{
BOOST_CHECK_MESSAGE(intersection_output.size() == expected_count,
"intersection: " << caseid
<< " #outputs expected: " << expected_count
<< " detected: " << intersection_output.size()
<< " type: " << (type_for_assert_message<G1, G2>())
);
}
if (expected_holes_count > 0)
{
BOOST_CHECK_MESSAGE(nholes == expected_holes_count,
"intersection: " << caseid
<< " #holes expected: " << expected_holes_count
<< " detected: " << nholes
<< " type: " << (type_for_assert_message<G1, G2>())
);
}
double const detected_length_or_area = boost::numeric_cast<double>(length_or_area);
if (settings.percentage > 0.0)
{
BOOST_CHECK_CLOSE(detected_length_or_area, expected_length_or_area, settings.percentage);
}
else
{
// In some cases (geos_2) the intersection is either 0, or a tiny rectangle,
// depending on compiler/settings. That cannot be tested by CLOSE
BOOST_CHECK_LE(detected_length_or_area, expected_length_or_area);
}
#endif
return length_or_area;
}
template <typename OutputType, typename CalculationType, typename G1, typename G2>
typename bg::default_area_result<G1>::type test_intersection(std::string const& caseid,
G1 const& g1, G2 const& g2,
std::size_t expected_count = 0, std::size_t expected_holes_count = 0,
int expected_point_count = 0, double expected_length_or_area = 0,
ut_settings const& settings = ut_settings())
{
if (settings.debug)
{
std::cout << std::endl << "case " << caseid << std::endl;
}
typedef typename setop_output_type<OutputType>::type result_type;
typedef typename bg::point_type<G1>::type point_type;
boost::ignore_unused<point_type>();
#if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE)
if (! settings.debug)
{
// Check _inserter behaviour with stratey
typedef typename bg::strategy::intersection::services::default_strategy
<
typename bg::cs_tag<point_type>::type
>::type strategy_type;
result_type clip;
bg::detail::intersection::intersection_insert<OutputType>(g1, g2, std::back_inserter(clip), strategy_type());
}
#endif
typename bg::default_area_result<G1>::type length_or_area = 0;
// Check normal behaviour
result_type intersection_output;
bg::intersection(g1, g2, intersection_output);
check_result<G1, G2, result_type>(intersection_output, caseid, expected_count,
expected_holes_count, expected_point_count, expected_length_or_area,
settings);
#if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE)
// Check variant behaviour
intersection_output.clear();
bg::intersection(boost::variant<G1>(g1), g2, intersection_output);
check_result<G1, G2, result_type>(intersection_output, caseid, expected_count,
expected_holes_count, expected_point_count, expected_length_or_area,
settings);
intersection_output.clear();
bg::intersection(g1, boost::variant<G2>(g2), intersection_output);
check_result<G1, G2, result_type>(intersection_output, caseid, expected_count,
expected_holes_count, expected_point_count, expected_length_or_area,
settings);
intersection_output.clear();
bg::intersection(boost::variant<G1>(g1), boost::variant<G2>(g2), intersection_output);
check_result<G1, G2, result_type>(intersection_output, caseid, expected_count,
expected_holes_count, expected_point_count, expected_length_or_area,
settings);
#endif
#if defined(TEST_WITH_SVG)
{
bool const is_line = bg::geometry_id<OutputType>::type::value == 2;
typedef typename bg::coordinate_type<G1>::type coordinate_type;
bool const ccw =
bg::point_order<G1>::value == bg::counterclockwise
|| bg::point_order<G2>::value == bg::counterclockwise;
bool const open =
bg::closure<G1>::value == bg::open
|| bg::closure<G2>::value == bg::open;
std::ostringstream filename;
filename << "intersection_"
<< caseid << "_"
<< string_from_type<coordinate_type>::name()
<< string_from_type<CalculationType>::name()
<< (ccw ? "_ccw" : "")
<< (open ? "_open" : "")
#if defined(BOOST_GEOMETRY_NO_SELF_TURNS)
<< "_no_self"
#endif
#if defined(BOOST_GEOMETRY_NO_ROBUSTNESS)
<< "_no_rob"
#endif
<< ".svg";
std::ofstream svg(filename.str().c_str());
bg::svg_mapper<point_type> mapper(svg, 500, 500);
mapper.add(g1);
mapper.add(g2);
mapper.map(g1, is_line
? "opacity:0.6;stroke:rgb(0,255,0);stroke-width:5"
: "fill-opacity:0.5;fill:rgb(153,204,0);"
"stroke:rgb(153,204,0);stroke-width:3");
mapper.map(g2, "fill-opacity:0.3;fill:rgb(51,51,153);"
"stroke:rgb(51,51,153);stroke-width:3");
for (typename result_type::const_iterator it = intersection_output.begin();
it != intersection_output.end(); ++it)
{
mapper.map(*it, "fill-opacity:0.2;stroke-opacity:0.4;fill:rgb(255,0,0);"
"stroke:rgb(255,0,255);stroke-width:8");
}
}
#endif
if (settings.debug)
{
std::cout << "end case " << caseid << std::endl;
}
return length_or_area;
}
template <typename OutputType, typename CalculationType, typename G1, typename G2>
typename bg::default_area_result<G1>::type test_intersection(std::string const& caseid,
G1 const& g1, G2 const& g2,
std::size_t expected_count = 0, int expected_point_count = 0,
double expected_length_or_area = 0,
ut_settings const& settings = ut_settings())
{
return test_intersection<OutputType, CalculationType>(
caseid, g1, g2, expected_count, 0, expected_point_count,
expected_length_or_area, settings
);
}
template <typename OutputType, typename G1, typename G2>
typename bg::default_area_result<G1>::type test_one(std::string const& caseid,
std::string const& wkt1, std::string const& wkt2,
std::size_t expected_count = 0, std::size_t expected_holes_count = 0,
int expected_point_count = 0, double expected_length_or_area = 0,
ut_settings const& settings = ut_settings())
{
G1 g1;
bg::read_wkt(wkt1, g1);
G2 g2;
bg::read_wkt(wkt2, g2);
// Reverse if necessary
bg::correct(g1);
bg::correct(g2);
return test_intersection<OutputType, void>(caseid, g1, g2,
expected_count, expected_holes_count, expected_point_count,
expected_length_or_area, settings);
}
template <typename OutputType, typename G1, typename G2>
typename bg::default_area_result<G1>::type test_one(std::string const& caseid,
std::string const& wkt1, std::string const& wkt2,
std::size_t expected_count = 0, int expected_point_count = 0,
double expected_length_or_area = 0,
ut_settings const& settings = ut_settings())
{
return test_one<OutputType, G1, G2>(caseid, wkt1, wkt2,
expected_count, 0, expected_point_count,
expected_length_or_area,
settings);
}
template <typename OutputType, typename Areal, typename Linear>
void test_one_lp(std::string const& caseid,
std::string const& wkt_areal, std::string const& wkt_linear,
std::size_t expected_count = 0, int expected_point_count = 0,
double expected_length = 0,
ut_settings const& settings = ut_settings())
{
#ifdef BOOST_GEOMETRY_TEST_DEBUG
std::cout << caseid << " -- start" << std::endl;
#endif
Areal areal;
bg::read_wkt(wkt_areal, areal);
bg::correct(areal);
Linear linear;
bg::read_wkt(wkt_linear, linear);
test_intersection<OutputType, void>(caseid, areal, linear,
expected_count, expected_point_count,
expected_length, settings);
// A linestring reversed should deliver exactly the same.
bg::reverse(linear);
test_intersection<OutputType, void>(caseid + "_rev", areal, linear,
expected_count, expected_point_count,
expected_length, settings);
#ifdef BOOST_GEOMETRY_TEST_DEBUG
std::cout << caseid << " -- end" << std::endl;
#endif
}
template <typename Geometry1, typename Geometry2>
void test_point_output(std::string const& wkt1, std::string const& wkt2, unsigned int expected_count)
{
Geometry1 g1;
bg::read_wkt(wkt1, g1);
bg::correct(g1);
Geometry2 g2;
bg::read_wkt(wkt2, g2);
bg::correct(g2);
bg::model::multi_point<typename bg::point_type<Geometry1>::type> points;
bg::intersection(g1, g2, points);
BOOST_CHECK_EQUAL(points.size(), expected_count);
}
#endif
| apache-2.0 |
jack-moseley/gobblin | gobblin-core/src/main/java/org/apache/gobblin/writer/HiveWritableHdfsDataWriter.java | 4568 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.gobblin.writer;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.JobConf;
import com.google.common.base.Preconditions;
import org.apache.gobblin.configuration.State;
/**
* An extension to {@link FsDataWriter} that writes {@link Writable} records using an
* {@link org.apache.hadoop.mapred.OutputFormat} that implements {@link HiveOutputFormat}.
*
* The records are written using a {@link RecordWriter} created by
* {@link HiveOutputFormat#getHiveRecordWriter(JobConf, org.apache.hadoop.fs.Path, Class, boolean,
* java.util.Properties, org.apache.hadoop.util.Progressable)}.
*
* @author Ziyang Liu
*/
public class HiveWritableHdfsDataWriter extends FsDataWriter<Writable> {
protected RecordWriter writer;
protected final AtomicLong count = new AtomicLong(0);
// the close method may be invoked multiple times, but the underlying writer only supports close being called once
private boolean closed = false;
public HiveWritableHdfsDataWriter(HiveWritableHdfsDataWriterBuilder<?> builder, State properties) throws IOException {
super(builder, properties);
Preconditions.checkArgument(this.properties.contains(HiveWritableHdfsDataWriterBuilder.WRITER_OUTPUT_FORMAT_CLASS));
this.writer = getWriter();
}
private RecordWriter getWriter() throws IOException {
try {
HiveOutputFormat<?, ?> outputFormat = HiveOutputFormat.class
.cast(Class.forName(this.properties.getProp(HiveWritableHdfsDataWriterBuilder.WRITER_OUTPUT_FORMAT_CLASS))
.newInstance());
@SuppressWarnings("unchecked")
Class<? extends Writable> writableClass = (Class<? extends Writable>) Class
.forName(this.properties.getProp(HiveWritableHdfsDataWriterBuilder.WRITER_WRITABLE_CLASS));
// Merging Job Properties into JobConf for easy tuning
JobConf loadedJobConf = new JobConf();
for (Object key : this.properties.getProperties().keySet()) {
loadedJobConf.set((String)key, this.properties.getProp((String)key));
}
return outputFormat.getHiveRecordWriter(loadedJobConf, this.stagingFile, writableClass, true,
this.properties.getProperties(), null);
} catch (Throwable t) {
throw new IOException(String.format("Failed to create writer"), t);
}
}
@Override
public void write(Writable record) throws IOException {
Preconditions.checkNotNull(record);
this.writer.write(record);
this.count.incrementAndGet();
}
@Override
public long recordsWritten() {
return this.count.get();
}
@Override
public long bytesWritten() throws IOException {
if (!this.fs.exists(this.outputFile)) {
return 0;
}
return this.fs.getFileStatus(this.outputFile).getLen();
}
@Override
public void close() throws IOException {
closeInternal();
super.close();
}
@Override
public void commit() throws IOException {
closeInternal();
super.commit();
}
private void closeInternal() throws IOException {
// close the underlying writer if not already closed. The close can only be called once for the underlying writer,
// so remember the state
if (!this.closed) {
this.writer.close(false);
// release reference to allow GC since this writer can hold onto large buffers for some formats like ORC.
this.writer = null;
this.closed = true;
}
}
@Override
public boolean isSpeculativeAttemptSafe() {
return this.writerAttemptIdOptional.isPresent() && this.getClass() == HiveWritableHdfsDataWriter.class;
}
}
| apache-2.0 |
juvchan/azure-powershell | src/ResourceManager/Dns/Commands.Dns/Records/SetAzureDnsRecordSet.cs | 2655 | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using System.Collections;
using System.Management.Automation;
using Microsoft.Azure.Commands.Dns.Models;
using ProjectResources = Microsoft.Azure.Commands.Dns.Properties.Resources;
namespace Microsoft.Azure.Commands.Dns
{
/// <summary>
/// Updates an existing record set.
/// </summary>
[Cmdlet(VerbsCommon.Set, "AzureRmDnsRecordSet"), OutputType(typeof(DnsRecordSet))]
public class SetAzureDnsRecordSet : DnsBaseCmdlet
{
[Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The record set in which to add the record.")]
[ValidateNotNullOrEmpty]
public DnsRecordSet RecordSet { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Do not use the ETag field of the RecordSet parameter for optimistic concurrency checks.", ParameterSetName = "Object")]
public SwitchParameter Overwrite { get; set; }
public override void ExecuteCmdlet()
{
if ((string.IsNullOrWhiteSpace(this.RecordSet.Etag) || this.RecordSet.Etag == "*") && !this.Overwrite.IsPresent)
{
throw new PSArgumentException(string.Format(ProjectResources.Error_EtagNotSpecified, typeof(DnsRecordSet).Name));
}
DnsRecordSet recordSetToUpdate = (DnsRecordSet)this.RecordSet.Clone();
if (recordSetToUpdate.ZoneName != null && recordSetToUpdate.ZoneName.EndsWith("."))
{
recordSetToUpdate.ZoneName = recordSetToUpdate.ZoneName.TrimEnd('.');
this.WriteWarning(string.Format("Modifying zone name to remove terminating '.'. Zone name used is \"{0}\".", recordSetToUpdate.ZoneName));
}
DnsRecordSet result = this.DnsClient.UpdateDnsRecordSet(recordSetToUpdate, this.Overwrite.IsPresent);
WriteVerbose(ProjectResources.Success);
WriteObject(result);
}
}
}
| apache-2.0 |
azmodii/aifh | vol1/java-examples/src/main/java/com/heatonresearch/aifh/distance/EuclideanDistance.java | 1701 | /*
* Artificial Intelligence for Humans
* Volume 1: Fundamental Algorithms
* Java Version
* http://www.aifh.org
* http://www.jeffheaton.com
*
* Code repository:
* https://github.com/jeffheaton/aifh
* Copyright 2013 by Jeff Heaton
*
* 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package com.heatonresearch.aifh.distance;
/**
* The Euclidean distance is the straight-line distance between two points. It is calculated by taking the
* square root of the sum of squares differences between each point in the vector.
* <p/>
* http://www.heatonresearch.com/wiki/Euclidean_Distance
*/
public class EuclideanDistance extends AbstractDistance {
/**
* {@inheritDoc}
*/
@Override
public double calculate(final double[] position1, final int pos1, final double[] position2, final int pos2, final int length) {
double sum = 0;
for (int i = 0; i < length; i++) {
final double d = position1[i + pos1] - position2[i + pos1];
sum += d * d;
}
return Math.sqrt(sum);
}
}
| apache-2.0 |
wapalxj/Java | javaworkplace/source/src/javax/swing/event/TreeSelectionEvent.java | 6867 | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.swing.event;
import java.util.EventObject;
import javax.swing.tree.TreePath;
/**
* An event that characterizes a change in the current
* selection. The change is based on any number of paths.
* TreeSelectionListeners will generally query the source of
* the event for the new selected status of each potentially
* changed row.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see TreeSelectionListener
* @see javax.swing.tree.TreeSelectionModel
*
* @author Scott Violet
*/
public class TreeSelectionEvent extends EventObject
{
/** Paths this event represents. */
protected TreePath[] paths;
/** For each path identifies if that path is in fact new. */
protected boolean[] areNew;
/** leadSelectionPath before the paths changed, may be null. */
protected TreePath oldLeadSelectionPath;
/** leadSelectionPath after the paths changed, may be null. */
protected TreePath newLeadSelectionPath;
/**
* Represents a change in the selection of a TreeSelectionModel.
* paths identifies the paths that have been either added or
* removed from the selection.
*
* @param source source of event
* @param paths the paths that have changed in the selection
*/
public TreeSelectionEvent(Object source, TreePath[] paths,
boolean[] areNew, TreePath oldLeadSelectionPath,
TreePath newLeadSelectionPath)
{
super(source);
this.paths = paths;
this.areNew = areNew;
this.oldLeadSelectionPath = oldLeadSelectionPath;
this.newLeadSelectionPath = newLeadSelectionPath;
}
/**
* Represents a change in the selection of a TreeSelectionModel.
* path identifies the path that have been either added or
* removed from the selection.
*
* @param source source of event
* @param path the path that has changed in the selection
* @param isNew whether or not the path is new to the selection, false
* means path was removed from the selection.
*/
public TreeSelectionEvent(Object source, TreePath path, boolean isNew,
TreePath oldLeadSelectionPath,
TreePath newLeadSelectionPath)
{
super(source);
paths = new TreePath[1];
paths[0] = path;
areNew = new boolean[1];
areNew[0] = isNew;
this.oldLeadSelectionPath = oldLeadSelectionPath;
this.newLeadSelectionPath = newLeadSelectionPath;
}
/**
* Returns the paths that have been added or removed from the
* selection.
*/
public TreePath[] getPaths()
{
int numPaths;
TreePath[] retPaths;
numPaths = paths.length;
retPaths = new TreePath[numPaths];
System.arraycopy(paths, 0, retPaths, 0, numPaths);
return retPaths;
}
/**
* Returns the first path element.
*/
public TreePath getPath()
{
return paths[0];
}
/**
* Returns whether the path identified by {@code getPath} was
* added to the selection. A return value of {@code true}
* indicates the path identified by {@code getPath} was added to
* the selection. A return value of {@code false} indicates {@code
* getPath} was selected, but is no longer selected.
*
* @return {@code true} if {@code getPath} was added to the selection,
* {@code false} otherwise
*/
public boolean isAddedPath() {
return areNew[0];
}
/**
* Returns whether the specified path was added to the selection.
* A return value of {@code true} indicates the path identified by
* {@code path} was added to the selection. A return value of
* {@code false} indicates {@code path} is no longer selected. This method
* is only valid for the paths returned from {@code getPaths()}; invoking
* with a path not included in {@code getPaths()} throws an
* {@code IllegalArgumentException}.
*
* @param path the path to test
* @return {@code true} if {@code path} was added to the selection,
* {@code false} otherwise
* @throws IllegalArgumentException if {@code path} is not contained
* in {@code getPaths}
* @see #getPaths
*/
public boolean isAddedPath(TreePath path) {
for(int counter = paths.length - 1; counter >= 0; counter--)
if(paths[counter].equals(path))
return areNew[counter];
throw new IllegalArgumentException("path is not a path identified by the TreeSelectionEvent");
}
/**
* Returns whether the path at {@code getPaths()[index]} was added
* to the selection. A return value of {@code true} indicates the
* path was added to the selection. A return value of {@code false}
* indicates the path is no longer selected.
*
* @param index the index of the path to test
* @return {@code true} if the path was added to the selection,
* {@code false} otherwise
* @throws IllegalArgumentException if index is outside the range of
* {@code getPaths}
* @see #getPaths
*
* @since 1.3
*/
public boolean isAddedPath(int index) {
if (paths == null || index < 0 || index >= paths.length) {
throw new IllegalArgumentException("index is beyond range of added paths identified by TreeSelectionEvent");
}
return areNew[index];
}
/**
* Returns the path that was previously the lead path.
*/
public TreePath getOldLeadSelectionPath() {
return oldLeadSelectionPath;
}
/**
* Returns the current lead path.
*/
public TreePath getNewLeadSelectionPath() {
return newLeadSelectionPath;
}
/**
* Returns a copy of the receiver, but with the source being newSource.
*/
public Object cloneWithSource(Object newSource) {
// Fix for IE bug - crashing
return new TreeSelectionEvent(newSource, paths,areNew,
oldLeadSelectionPath,
newLeadSelectionPath);
}
}
| apache-2.0 |
enj/origin | vendor/github.com/google/certificate-transparency-go/trillian/ctfe/cert_quota.go | 1489 | // Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ctfe
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/google/certificate-transparency-go/x509"
)
// CertificateQuotaUserPrefix is prepended to all User quota ids association
// with intermediate certificates.
const CertificateQuotaUserPrefix = "@intermediate"
// QuotaUserForCert returns a User quota id string for the passed in
// certificate.
// This is intended to be used for quota limiting by intermediate certificates,
// but the function does not enforce anything about the passed in cert.
//
// Format returned is:
// "CertificateQuotaUserPrefix Subject hex(SHA256(SubjectPublicKeyInfo)[0:5])"
// See tests for examples.
func QuotaUserForCert(c *x509.Certificate) string {
spkiHash := sha256.Sum256(c.RawSubjectPublicKeyInfo)
return fmt.Sprintf("%s %s %s", CertificateQuotaUserPrefix, c.Subject.String(), hex.EncodeToString(spkiHash[0:5]))
}
| apache-2.0 |
graetzer/arangodb | 3rdParty/V8/v7.9.317/src/torque/type-inference.cc | 4361 | // Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/torque/type-inference.h"
namespace v8 {
namespace internal {
namespace torque {
TypeArgumentInference::TypeArgumentInference(
const NameVector& type_parameters,
const TypeVector& explicit_type_arguments,
const std::vector<TypeExpression*>& term_parameters,
const TypeVector& term_argument_types)
: num_explicit_(explicit_type_arguments.size()),
type_parameter_from_name_(type_parameters.size()),
inferred_(type_parameters.size()) {
if (num_explicit_ > type_parameters.size()) {
Fail("more explicit type arguments than expected");
return;
}
if (term_parameters.size() != term_argument_types.size()) {
Fail("number of term parameters does not match number of term arguments!");
return;
}
for (size_t i = 0; i < type_parameters.size(); i++) {
type_parameter_from_name_[type_parameters[i]->value] = i;
}
for (size_t i = 0; i < num_explicit_; i++) {
inferred_[i] = {explicit_type_arguments[i]};
}
for (size_t i = 0; i < term_parameters.size(); i++) {
Match(term_parameters[i], term_argument_types[i]);
if (HasFailed()) return;
}
for (size_t i = 0; i < type_parameters.size(); i++) {
if (!inferred_[i]) {
Fail("failed to infer arguments for all type parameters");
return;
}
}
}
TypeVector TypeArgumentInference::GetResult() const {
CHECK(!HasFailed());
TypeVector result(inferred_.size());
std::transform(
inferred_.begin(), inferred_.end(), result.begin(),
[](base::Optional<const Type*> maybe_type) { return *maybe_type; });
return result;
}
void TypeArgumentInference::Match(TypeExpression* parameter,
const Type* argument_type) {
if (BasicTypeExpression* basic =
BasicTypeExpression::DynamicCast(parameter)) {
// If the parameter is referring to one of the type parameters, substitute
if (basic->namespace_qualification.empty() && !basic->is_constexpr) {
auto result = type_parameter_from_name_.find(basic->name);
if (result != type_parameter_from_name_.end()) {
size_t type_parameter_index = result->second;
if (type_parameter_index < num_explicit_) {
return;
}
base::Optional<const Type*>& maybe_inferred =
inferred_[type_parameter_index];
if (maybe_inferred && *maybe_inferred != argument_type) {
Fail("found conflicting types for generic parameter");
} else {
inferred_[type_parameter_index] = {argument_type};
}
return;
}
}
// Try to recurse in case of generic types
if (!basic->generic_arguments.empty()) {
auto* argument_struct_type = StructType::DynamicCast(argument_type);
if (argument_struct_type) {
MatchGeneric(basic, argument_struct_type);
}
}
// NOTE: We could also check whether ground parameter types match the
// argument types, but we are only interested in inferring type arguments
// here
} else {
// TODO(gsps): Perform inference on function and union types
}
}
void TypeArgumentInference::MatchGeneric(BasicTypeExpression* parameter,
const StructType* argument_type) {
QualifiedName qualified_name{parameter->namespace_qualification,
parameter->name};
GenericStructType* generic_struct =
Declarations::LookupUniqueGenericStructType(qualified_name);
auto& specialized_from = argument_type->GetSpecializedFrom();
if (!specialized_from || specialized_from->generic != generic_struct) {
return Fail("found conflicting generic type constructors");
}
auto& parameters = parameter->generic_arguments;
auto& argument_types = specialized_from->specialized_types;
if (parameters.size() != argument_types.size()) {
Error(
"cannot infer types from generic-struct-typed parameter with "
"incompatible number of arguments")
.Position(parameter->pos)
.Throw();
}
for (size_t i = 0; i < parameters.size(); i++) {
Match(parameters[i], argument_types[i]);
if (HasFailed()) return;
}
}
} // namespace torque
} // namespace internal
} // namespace v8
| apache-2.0 |
ronniehedrick/scapeshift | client/src/components/dashboard/messaging/message-item.js | 572 | import React, { Component } from 'react';
import cookie from 'react-cookie';
const currentUser = cookie.load('user');
class MessageItem extends Component {
render() {
return (
<div className={currentUser == this.props.author._id ? 'message current-user' : 'message'}>
<span className="message-body">{this.props.message}</span>
<br />
<span className="message-byline">From {this.props.author.profile.firstName} {this.props.author.profile.lastName} | {this.props.timestamp}</span>
</div>
);
}
}
export default MessageItem;
| apache-2.0 |
karimull/osc-core | osc-common/src/main/java/org/osc/core/common/alarm/EventType.java | 1127 | /*******************************************************************************
* Copyright (c) Intel Corporation
* Copyright (c) 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.osc.core.common.alarm;
public enum EventType {
JOB_FAILURE("Job Failure"),
SYSTEM_FAILURE("System Failure"),
DAI_FAILURE("DAI Failure");
private final String text;
private EventType(final String text) {
this.text = text;
}
@Override
public String toString() {
return this.text;
}
}
| apache-2.0 |
mrinsss/Full-Repo | hizmetuzmani/js/jquery/ui/minified/jquery.effects.bounce.min.js | 1686 | /*
* jQuery UI Effects Bounce 1.8.4
*
* Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Effects/Bounce
*
* Depends:
* jquery.effects.core.js
*/
(function(e){e.effects.bounce=function(b){return this.queue(function(){var a=e(this),l=["position","top","left"],h=e.effects.setMode(a,b.options.mode||"effect"),d=b.options.direction||"up",c=b.options.distance||20,m=b.options.times||5,i=b.duration||250;/show|hide/.test(h)&&l.push("opacity");e.effects.save(a,l);a.show();e.effects.createWrapper(a);var f=d=="up"||d=="down"?"top":"left";d=d=="up"||d=="left"?"pos":"neg";c=b.options.distance||(f=="top"?a.outerHeight({margin:true})/3:a.outerWidth({margin:true})/
3);if(h=="show")a.css("opacity",0).css(f,d=="pos"?-c:c);if(h=="hide")c/=m*2;h!="hide"&&m--;if(h=="show"){var g={opacity:1};g[f]=(d=="pos"?"+=":"-=")+c;a.animate(g,i/2,b.options.easing);c/=2;m--}for(g=0;g<m;g++){var j={},k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing);c=h=="hide"?c*2:c/2}if(h=="hide"){g={opacity:0};g[f]=(d=="pos"?"-=":"+=")+c;a.animate(g,i/2,b.options.easing,function(){a.hide();e.effects.restore(a,l);e.effects.removeWrapper(a);
b.callback&&b.callback.apply(this,arguments)})}else{j={};k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing,function(){e.effects.restore(a,l);e.effects.removeWrapper(a);b.callback&&b.callback.apply(this,arguments)})}a.queue("fx",function(){a.dequeue()});a.dequeue()})}})(jQuery);
| apache-2.0 |
romartin/dashbuilder | dashbuilder-client/dashbuilder-dataset-client/src/main/java/org/dashbuilder/dataset/client/uuid/ClientUUIDGenerator.java | 1218 | /*
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dashbuilder.dataset.client.uuid;
import javax.enterprise.context.ApplicationScoped;
import com.google.gwt.dom.client.Document;
import org.dashbuilder.dataset.uuid.UUIDGenerator;
@ApplicationScoped
public class ClientUUIDGenerator implements UUIDGenerator {
public String newUuid() {
return Document.get().createUniqueId();
}
public String newUuidBase64() {
return Document.get().createUniqueId();
}
public String uuidToBase64(String str) {
return str;
}
public String uuidFromBase64(String str) {
return str;
}
}
| apache-2.0 |
lukeiwanski/tensorflow-opencl | tensorflow/compiler/xla/service/hlo_execution_profile.cc | 4717 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_execution_profile.h"
#include <algorithm>
#include <utility>
#include <vector>
#include "tensorflow/compiler/xla/metric_table_report.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
namespace xla {
void HloExecutionProfile::AddProfileResult(const HloInstruction* hlo,
uint64 cycles_taken) {
hlo_to_cycles_taken_[hlo] = cycles_taken;
}
uint64 HloExecutionProfile::GetProfileResult(const HloInstruction& hlo) const {
auto iter = hlo_to_cycles_taken_.find(&hlo);
if (iter == hlo_to_cycles_taken_.end()) {
return 0;
}
return iter->second;
}
string HloExecutionProfile::ToString(
const DeviceDescription& device_description,
const HloCostAnalysis& cost_analysis) const {
using Item = std::pair<const HloInstruction*, uint64>;
std::vector<Item> items(hlo_to_cycles_taken_.begin(),
hlo_to_cycles_taken_.end());
auto custom_less = [](const Item& lhs, const Item& rhs) {
return lhs.second > rhs.second;
};
std::sort(items.begin(), items.end(), custom_less);
string result;
const int64 total_cycles = total_cycles_executed();
double clock_rate_ghz = device_description.clock_rate_ghz();
const auto cycles_to_microseconds = [&](double cycles) {
return cycles / clock_rate_ghz / 1000.0;
};
auto append_item = [&](int64 cycles, int64 flops, int64 bytes_accessed,
const string& name) {
double nsecs = cycles / clock_rate_ghz;
string bytes_per_sec;
string bytes_per_cycle;
if (bytes_accessed >= 0) {
bytes_per_sec = tensorflow::strings::HumanReadableNumBytes(
bytes_accessed / (nsecs / 1e9));
bytes_per_cycle =
tensorflow::strings::HumanReadableNumBytes(bytes_accessed / cycles);
} else {
bytes_per_sec = "<unknown>";
bytes_per_cycle = "<unknown>";
}
tensorflow::strings::StrAppend(
&result,
tensorflow::strings::Printf(
"%15lld cycles (%6.2f%%) :: %12.1f usec @ f_nom :: %18s :: %12s/s "
":: "
"%12s/cycle :: "
"%s",
cycles, cycles / static_cast<double>(total_cycles) * 100,
cycles_to_microseconds(cycles),
flops <= 0 ? "<none>" : HumanReadableNumFlops(flops, nsecs).c_str(),
bytes_per_sec.c_str(), bytes_per_cycle.c_str(), name.c_str()));
};
tensorflow::strings::StrAppend(
&result,
tensorflow::strings::Printf("HLO execution profile: (%s @ f_nom)\n\t",
tensorflow::strings::HumanReadableElapsedTime(
total_cycles / clock_rate_ghz / 1e9)
.c_str()));
append_item(total_cycles, -1, -1, "[total]");
for (const auto& item : items) {
const HloInstruction* hlo = item.first;
tensorflow::strings::StrAppend(&result, "\n\t");
int64 flops = hlo == nullptr ? -1 : cost_analysis.flop_count(*hlo);
int64 bytes_accessed =
hlo == nullptr ? -1 : cost_analysis.bytes_accessed(*hlo);
string display = hlo == nullptr ? "<none>" : hlo->ToString();
append_item(item.second, flops, bytes_accessed, display);
}
MetricTableReport table;
table.SetMetricName("microseconds");
table.SetEntryName("ops");
table.SetShowCategoryTable();
for (const auto& item : items) {
MetricTableReport::Entry entry;
entry.text = item.first->ToString();
entry.short_text = item.first->ToString(/*compact_operands=*/true);
entry.category_text = item.first->ToCategory();
entry.metric = cycles_to_microseconds(item.second);
table.AddEntry(std::move(entry));
}
result += table.MakeReport(cycles_to_microseconds(total_cycles));
return result;
}
} // namespace xla
| apache-2.0 |
heriram/incubator-asterixdb | asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/util/InsertUpsertCheckUtil.java | 4591 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.asterix.optimizer.rules.util;
import java.util.List;
import org.apache.asterix.om.functions.BuiltinFunctions;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalPlan;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag;
import org.apache.hyracks.algebricks.core.algebra.expressions.UnnestingFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.SubplanOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.UnnestOperator;
public class InsertUpsertCheckUtil {
private InsertUpsertCheckUtil() {
}
/**
*
* Checks the query plan rooted at <code>op</code> to see whether there is an invalid returning expression
* for insert/upsert, i.e., an returning expression that contains dataset accesses.
*
* @param op,
* the operator in consideration
* @return true if the returning expression after insert/upsert is invalid; false otherwise.
*/
public static boolean check(ILogicalOperator op) {
return checkTopDown(op, false);
}
// Checks the query plan rooted at <code>op</code> top down to see whether there is an invalid returning expression
// for insert/upsert, i.e., a returning expression that contains dataset accesses.
private static boolean checkTopDown(ILogicalOperator op, boolean hasSubplanAboveWithDatasetAccess) {
boolean metSubplanWithDataScan = hasSubplanAboveWithDatasetAccess;
if (op.getOperatorTag() == LogicalOperatorTag.SUBPLAN) {
SubplanOperator subplanOp = (SubplanOperator) op;
metSubplanWithDataScan = containsDatasetAccess(subplanOp);
}
if (op.getOperatorTag() == LogicalOperatorTag.INSERT_DELETE_UPSERT && metSubplanWithDataScan) {
return true;
}
for (Mutable<ILogicalOperator> inputOpRef : op.getInputs()) {
if (checkTopDown(inputOpRef.getValue(), metSubplanWithDataScan)) {
return true;
}
}
return false;
}
// Checks whether a subplan operator contains a dataset accesses in its nested pipeline.
private static boolean containsDatasetAccess(SubplanOperator subplanOp) {
List<ILogicalPlan> nestedPlans = subplanOp.getNestedPlans();
for (ILogicalPlan nestedPlan : nestedPlans) {
for (Mutable<ILogicalOperator> opRef : nestedPlan.getRoots()) {
if (containsDatasetAccessInternal(opRef.getValue())) {
return true;
}
}
}
return false;
}
// Checks whether a query plan rooted at <code>op</code> contains dataset accesses.
private static boolean containsDatasetAccessInternal(ILogicalOperator op) {
if (op.getOperatorTag() == LogicalOperatorTag.UNNEST) {
UnnestOperator unnestOp = (UnnestOperator) op;
ILogicalExpression unnestExpr = unnestOp.getExpressionRef().getValue();
UnnestingFunctionCallExpression unnestingFuncExpr = (UnnestingFunctionCallExpression) unnestExpr;
return unnestingFuncExpr.getFunctionIdentifier().equals(BuiltinFunctions.DATASET);
}
if (op.getOperatorTag() == LogicalOperatorTag.SUBPLAN && containsDatasetAccess((SubplanOperator) op)) {
return true;
}
for (Mutable<ILogicalOperator> childRef : op.getInputs()) {
if (containsDatasetAccessInternal(childRef.getValue())) {
return true;
}
}
return false;
}
}
| apache-2.0 |
tootedom/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/auth/DefaultAWSCredentialsProviderChain.java | 1679 | /*
* Copyright 2012-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.auth;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
/**
* AWS credentials provider chain that looks for credentials in this order:
* <ul>
* <li>Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY</li>
* <li>Java System Properties - aws.accessKeyId and aws.secretKey</li>
* <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li>
* <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li>
* </ul>
*
* @see EnvironmentVariableCredentialsProvider
* @see SystemPropertiesCredentialsProvider
* @see ProfileCredentialsProvider
* @see InstanceProfileCredentialsProvider
*/
public class DefaultAWSCredentialsProviderChain extends AWSCredentialsProviderChain {
public DefaultAWSCredentialsProviderChain() {
super(new EnvironmentVariableCredentialsProvider(),
new SystemPropertiesCredentialsProvider(),
new ProfileCredentialsProvider(),
new InstanceProfileCredentialsProvider());
}
} | apache-2.0 |
jreichhold/chef-repo | vendor/ruby/2.0.0/gems/chef-0.8.10/lib/chef/resource/bash.rb | 972 | #
# Author:: Adam Jacob (<[email protected]>)
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
require 'chef/resource/script'
class Chef
class Resource
class Bash < Chef::Resource::Script
def initialize(name, collection=nil, node=nil)
super(name, collection, node)
@resource_name = :bash
@interpreter = "bash"
end
end
end
end | apache-2.0 |
barosl/rust | src/test/compile-fail/no-reuse-move-arc.rs | 809 | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::sync::Arc;
use std::task;
fn main() {
let v = vec!(1i, 2, 3, 4, 5, 6, 7, 8, 9, 10);
let arc_v = Arc::new(v);
task::spawn(proc() {
assert_eq!((*arc_v)[3], 4);
});
assert_eq!((*arc_v)[2], 3); //~ ERROR use of moved value: `arc_v`
println!("{}", *arc_v); //~ ERROR use of moved value: `arc_v`
}
| apache-2.0 |
xiaguangme/demo | 07.ElasticSearch_demo/elasticsearch-2.4.0-sources/org/elasticsearch/action/exists/ExistsResponse.java | 2095 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.exists;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.support.broadcast.BroadcastResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import java.io.IOException;
import java.util.List;
/**
* @deprecated use {@link org.elasticsearch.action.search.SearchRequest} instead and set `size` to `0` and `terminate_after` to `1`
*/
@Deprecated
public class ExistsResponse extends BroadcastResponse {
private boolean exists = false;
ExistsResponse() {
}
ExistsResponse(boolean exists, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
super(totalShards, successfulShards, failedShards, shardFailures);
this.exists = exists;
}
/**
* Whether the documents matching the query provided exists
*/
public boolean exists() {
return exists;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
exists = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(exists);
}
}
| apache-2.0 |
pentaho/big-data-plugin | legacy/src/main/java/org/pentaho/di/ui/hadoop/configuration/HadoopConfigurationsXulDialog.java | 6847 | /*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2019 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.hadoop.configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.hadoop.HadoopConfigurationInfo;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.ui.core.dialog.ShowHelpDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.spoon.XulSpoonResourceBundle;
import org.pentaho.di.ui.spoon.XulSpoonSettingsManager;
import org.pentaho.di.ui.xul.KettleXulLoader;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulRunner;
import org.pentaho.ui.xul.containers.XulDialog;
import org.pentaho.ui.xul.containers.XulListbox;
import org.pentaho.ui.xul.impl.AbstractXulEventHandler;
import org.pentaho.ui.xul.swt.SwtXulRunner;
import org.pentaho.ui.xul.swt.tags.SwtButton;
import org.pentaho.ui.xul.swt.tags.SwtDialog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by bryan on 8/13/15.
*/
public class HadoopConfigurationsXulDialog extends AbstractXulEventHandler {
private static final Class<?> PKG = HadoopConfigurationsXulDialog.class;
private static final String CONTROLLER_NAME = "hadoopConfigurationsXulDialog";
private static final String XUL = "org/pentaho/di/ui/hadoop/configuration/select-config.xul";
private static final Log logger = LogFactory.getLog( HadoopConfigurationsXulDialog.class );
private final Shell shell;
private final List<HadoopConfigurationInfo> hadoopConfigurationInfos;
private XulDialog selectDialog;
private boolean accept = false;
public HadoopConfigurationsXulDialog( Shell aShell, List<HadoopConfigurationInfo> hadoopConfigurationInfos ) {
this.shell = aShell;
this.hadoopConfigurationInfos = new ArrayList<>( hadoopConfigurationInfos );
Collections.sort( this.hadoopConfigurationInfos, new Comparator<HadoopConfigurationInfo>() {
@Override public int compare( HadoopConfigurationInfo o1, HadoopConfigurationInfo o2 ) {
int result = o1.getName().compareTo( o2.getName() );
if ( result == 0 ) {
result = o1.getId().compareTo( o2.getId() );
}
return result;
}
} );
setName( CONTROLLER_NAME );
}
public String open() {
String selectedShim = "";
try {
KettleXulLoader e = new KettleXulLoader();
e.setOuterContext( shell );
e.setIconsSize( 24, 24 );
e.setSettingsManager( XulSpoonSettingsManager.getInstance() );
e.registerClassLoader( getClass().getClassLoader() );
e.registerClassLoader( KettleXulLoader.class.getClassLoader() );
XulDomContainer container = e.loadXul( XUL, new XulSpoonResourceBundle( PKG ) );
container.addEventHandler( this );
XulRunner runner = new SwtXulRunner();
runner.addContainer( container );
runner.initialize();
SwtButton helpButton = (SwtButton) container.getDocumentRoot().getElementById( "helpButton" );
Button managedObject = (Button) helpButton.getManagedObject();
managedObject.setImage( GUIResource.getInstance().getImageHelpWeb() );
selectDialog = (XulDialog) container.getDocumentRoot().getElementById( "hadoopConfigurationSelectionDialog" );
XulListbox hadoopConfigurationSelectionDialogMenuListBox =
(XulListbox) container.getDocumentRoot().getElementById(
"hadoopConfigurationSelectionDialogMenuListBox" );
int selectedIndex = -1;
List<String> configs = new ArrayList<>();
boolean previousConfigHadSameName = false;
for ( int i = 0; i < hadoopConfigurationInfos.size(); i++ ) {
HadoopConfigurationInfo hadoopConfigurationInfo = hadoopConfigurationInfos.get( i );
if ( hadoopConfigurationInfo.isWillBeActiveAfterRestart() ) {
selectedIndex = i;
}
boolean nextConfigHasSameName =
i < hadoopConfigurationInfos.size() - 1 && hadoopConfigurationInfos.get( i + 1 ).getName()
.equals( hadoopConfigurationInfo.getName() );
if ( previousConfigHadSameName || nextConfigHasSameName ) {
configs.add( hadoopConfigurationInfo.getName() + " (" + hadoopConfigurationInfo.getId() + ")" );
} else {
configs.add( hadoopConfigurationInfo.getName() );
}
previousConfigHadSameName = nextConfigHasSameName;
}
hadoopConfigurationSelectionDialogMenuListBox.setElements( configs );
if ( selectedIndex >= 0 ) {
hadoopConfigurationSelectionDialogMenuListBox.setSelectedIndex( selectedIndex );
}
hadoopConfigurationSelectionDialogMenuListBox.setRows( 6 );
selectDialog.show();
if ( accept ) {
selectedShim =
hadoopConfigurationInfos.get( hadoopConfigurationSelectionDialogMenuListBox.getSelectedIndex() ).getId();
}
( (SwtDialog) selectDialog ).dispose();
} catch ( Exception var4 ) {
logger.info( var4 );
}
return selectedShim;
}
public void cancel() {
selectDialog.hide();
}
public void accept() {
accept = true;
selectDialog.hide();
}
public void showHelp() {
String docUrl =
Const.getDocUrl( BaseMessages.getString( PKG, "HadoopConfigurationSelectionDialog.Help.Url" ) );
ShowHelpDialog showHelpDialog = new ShowHelpDialog( shell,
BaseMessages.getString( PKG, "HadoopConfigurationSelectionDialog.Help.Title" ),
docUrl,
BaseMessages.getString( PKG, "HadoopConfigurationSelectionDialog.Help.Header" ) ) {
// Parent is modal so we have to be as well
@Override
protected Shell createShell( Shell parent ) {
return new Shell( parent, SWT.CLOSE | SWT.RESIZE | SWT.MAX | SWT.MIN | SWT.APPLICATION_MODAL );
}
};
showHelpDialog.open();
showHelpDialog.dispose();
}
}
| apache-2.0 |
glaucio-melo-movile/activemq-artemis | tests/activemq5-unit-tests/src/test/java/org/apache/activemq/broker/policy/AbortSlowAckConsumer1Test.java | 2733 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker.policy;
import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.policy.AbortSlowAckConsumerStrategy;
import org.apache.activemq.broker.region.policy.AbortSlowConsumerStrategy;
import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class AbortSlowAckConsumer1Test extends AbortSlowConsumer1Test {
protected long maxTimeSinceLastAck = 5 * 1000;
public AbortSlowAckConsumer1Test(Boolean abortConnection, Boolean topic) {
super(abortConnection, topic);
}
@Override
protected AbortSlowConsumerStrategy createSlowConsumerStrategy() {
return new AbortSlowConsumerStrategy();
}
@Override
protected BrokerService createBroker() throws Exception {
BrokerService broker = super.createBroker();
PolicyEntry policy = new PolicyEntry();
AbortSlowAckConsumerStrategy strategy = new AbortSlowAckConsumerStrategy();
strategy.setAbortConnection(abortConnection);
strategy.setCheckPeriod(checkPeriod);
strategy.setMaxSlowDuration(maxSlowDuration);
strategy.setMaxTimeSinceLastAck(maxTimeSinceLastAck);
policy.setSlowConsumerStrategy(strategy);
policy.setQueuePrefetch(10);
policy.setTopicPrefetch(10);
PolicyMap pMap = new PolicyMap();
pMap.setDefaultEntry(policy);
broker.setDestinationPolicy(pMap);
return broker;
}
@Override
protected ConnectionFactory createConnectionFactory() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
factory.getPrefetchPolicy().setAll(1);
return factory;
}
}
| apache-2.0 |
rohmano/azure-powershell | src/ResourceManager/TrafficManager/Commands.TrafficManager2/Utilities/TrafficManagerClient.cs | 13911 | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Models;
namespace Microsoft.Azure.Commands.TrafficManager.Utilities
{
using Management.TrafficManager;
using Management.TrafficManager.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
public class TrafficManagerClient
{
public const string ProfileResourceLocation = "global";
public Action<string> VerboseLogger { get; set; }
public Action<string> ErrorLogger { get; set; }
public TrafficManagerClient(AzureContext context)
: this(AzureSession.ClientFactory.CreateClient<TrafficManagerManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager))
{
}
public TrafficManagerClient(ITrafficManagerManagementClient client)
{
this.TrafficManagerManagementClient = client;
}
public ITrafficManagerManagementClient TrafficManagerManagementClient { get; set; }
public TrafficManagerProfile CreateTrafficManagerProfile(string resourceGroupName, string profileName, string profileStatus, string trafficRoutingMethod, string relativeDnsName, uint ttl, string monitorProtocol, uint monitorPort, string monitorPath, Hashtable tag)
{
ProfileCreateOrUpdateResponse response = this.TrafficManagerManagementClient.Profiles.CreateOrUpdate(
resourceGroupName,
profileName,
new ProfileCreateOrUpdateParameters
{
Profile = new Profile
{
Name = profileName,
Location = TrafficManagerClient.ProfileResourceLocation,
Properties = new ProfileProperties
{
ProfileStatus = profileStatus,
TrafficRoutingMethod = trafficRoutingMethod,
DnsConfig = new DnsConfig
{
RelativeName = relativeDnsName,
Ttl = ttl
},
MonitorConfig = new MonitorConfig
{
Protocol = monitorProtocol,
Port = monitorPort,
Path = monitorPath
}
},
Tags = TagsConversionHelper.CreateTagDictionary(tag, validate: true),
}
});
return TrafficManagerClient.GetPowershellTrafficManagerProfile(resourceGroupName, profileName, response.Profile);
}
public TrafficManagerEndpoint CreateTrafficManagerEndpoint(string resourceGroupName, string profileName, string endpointType, string endpointName, string targetResourceId, string target, string endpointStatus, uint? weight, uint? priority, string endpointLocation, uint? minChildEndpoints, IList<string> geoMapping)
{
EndpointCreateOrUpdateResponse response = this.TrafficManagerManagementClient.Endpoints.CreateOrUpdate(
resourceGroupName,
profileName,
endpointType,
endpointName,
new EndpointCreateOrUpdateParameters
{
Endpoint = new Endpoint
{
Name = endpointName,
Type = TrafficManagerEndpoint.ToSDKEndpointType(endpointType),
Properties = new EndpointProperties
{
EndpointLocation = endpointLocation,
EndpointStatus = endpointStatus,
GeoMapping = geoMapping,
MinChildEndpoints = minChildEndpoints,
Priority = priority,
Target = target,
TargetResourceId = targetResourceId,
Weight = weight,
}
}
});
return TrafficManagerClient.GetPowershellTrafficManagerEndpoint(response.Endpoint.Id, resourceGroupName, profileName, endpointType, endpointName, response.Endpoint.Properties);
}
public TrafficManagerProfile GetTrafficManagerProfile(string resourceGroupName, string profileName)
{
ProfileGetResponse response = this.TrafficManagerManagementClient.Profiles.Get(resourceGroupName, profileName);
return TrafficManagerClient.GetPowershellTrafficManagerProfile(resourceGroupName, profileName, response.Profile);
}
public TrafficManagerEndpoint GetTrafficManagerEndpoint(string resourceGroupName, string profileName, string endpointType, string endpointName)
{
EndpointGetResponse response = this.TrafficManagerManagementClient.Endpoints.Get(resourceGroupName, profileName, endpointType, endpointName);
return TrafficManagerClient.GetPowershellTrafficManagerEndpoint(
response.Endpoint.Id,
resourceGroupName,
profileName,
endpointType,
endpointName,
response.Endpoint.Properties);
}
public TrafficManagerProfile[] ListTrafficManagerProfiles(string resourceGroupName = null)
{
ProfileListResponse response =
resourceGroupName == null ?
this.TrafficManagerManagementClient.Profiles.ListAll() :
this.TrafficManagerManagementClient.Profiles.ListAllInResourceGroup(resourceGroupName);
return response.Profiles.Select(profile => TrafficManagerClient.GetPowershellTrafficManagerProfile(
resourceGroupName ?? TrafficManagerClient.ExtractResourceGroupFromId(profile.Id),
profile.Name,
profile)).ToArray();
}
public TrafficManagerProfile SetTrafficManagerProfile(TrafficManagerProfile profile)
{
var parameters = new ProfileCreateOrUpdateParameters
{
Profile = profile.ToSDKProfile()
};
ProfileCreateOrUpdateResponse response = this.TrafficManagerManagementClient.Profiles.CreateOrUpdate(
profile.ResourceGroupName,
profile.Name,
parameters
);
return TrafficManagerClient.GetPowershellTrafficManagerProfile(profile.ResourceGroupName, profile.Name, response.Profile);
}
public TrafficManagerEndpoint SetTrafficManagerEndpoint(TrafficManagerEndpoint endpoint)
{
var parameters = new EndpointCreateOrUpdateParameters
{
Endpoint = endpoint.ToSDKEndpoint()
};
EndpointCreateOrUpdateResponse response = this.TrafficManagerManagementClient.Endpoints.CreateOrUpdate(
endpoint.ResourceGroupName,
endpoint.ProfileName,
endpoint.Type,
endpoint.Name,
parameters);
return TrafficManagerClient.GetPowershellTrafficManagerEndpoint(
endpoint.Id,
endpoint.ResourceGroupName,
endpoint.ProfileName,
endpoint.Type,
endpoint.Name,
response.Endpoint.Properties);
}
public bool DeleteTrafficManagerProfile(TrafficManagerProfile profile)
{
AzureOperationResponse response = this.TrafficManagerManagementClient.Profiles.Delete(profile.ResourceGroupName, profile.Name);
return response.StatusCode.Equals(HttpStatusCode.OK);
}
public bool DeleteTrafficManagerEndpoint(TrafficManagerEndpoint trafficManagerEndpoint)
{
AzureOperationResponse response = this.TrafficManagerManagementClient.Endpoints.Delete(
trafficManagerEndpoint.ResourceGroupName,
trafficManagerEndpoint.ProfileName,
trafficManagerEndpoint.Type,
trafficManagerEndpoint.Name);
return response.StatusCode.Equals(HttpStatusCode.OK);
}
public bool EnableDisableTrafficManagerProfile(TrafficManagerProfile profile, bool shouldEnableProfileStatus)
{
profile.ProfileStatus = shouldEnableProfileStatus ? Constants.StatusEnabled : Constants.StatusDisabled;
Profile sdkProfile = profile.ToSDKProfile();
sdkProfile.Properties.DnsConfig = null;
sdkProfile.Properties.Endpoints = null;
sdkProfile.Properties.TrafficRoutingMethod = null;
sdkProfile.Properties.MonitorConfig = null;
var parameters = new ProfileUpdateParameters
{
Profile = sdkProfile
};
AzureOperationResponse response = this.TrafficManagerManagementClient.Profiles.Update(profile.ResourceGroupName, profile.Name, parameters);
return response.StatusCode.Equals(HttpStatusCode.OK);
}
public bool EnableDisableTrafficManagerEndpoint(TrafficManagerEndpoint endpoint, bool shouldEnableEndpointStatus)
{
endpoint.EndpointStatus = shouldEnableEndpointStatus ? Constants.StatusEnabled : Constants.StatusDisabled;
Endpoint sdkEndpoint = endpoint.ToSDKEndpointForPatch();
sdkEndpoint.Properties.EndpointStatus = endpoint.EndpointStatus;
var parameters = new EndpointUpdateParameters
{
Endpoint = sdkEndpoint
};
AzureOperationResponse response = this.TrafficManagerManagementClient.Endpoints.Update(
endpoint.ResourceGroupName,
endpoint.ProfileName,
endpoint.Type,
endpoint.Name,
parameters);
return response.StatusCode.Equals(HttpStatusCode.Created);
}
private static TrafficManagerProfile GetPowershellTrafficManagerProfile(string resourceGroupName, string profileName, Profile mamlProfile)
{
var profile = new TrafficManagerProfile
{
Id = mamlProfile.Id,
Name = profileName,
ResourceGroupName = resourceGroupName,
ProfileStatus = mamlProfile.Properties.ProfileStatus,
RelativeDnsName = mamlProfile.Properties.DnsConfig.RelativeName,
Ttl = mamlProfile.Properties.DnsConfig.Ttl,
TrafficRoutingMethod = mamlProfile.Properties.TrafficRoutingMethod,
MonitorProtocol = mamlProfile.Properties.MonitorConfig.Protocol,
MonitorPort = mamlProfile.Properties.MonitorConfig.Port,
MonitorPath = mamlProfile.Properties.MonitorConfig.Path
};
if (mamlProfile.Properties.Endpoints != null)
{
profile.Endpoints = new List<TrafficManagerEndpoint>();
foreach (Endpoint endpoint in mamlProfile.Properties.Endpoints)
{
profile.Endpoints.Add(
GetPowershellTrafficManagerEndpoint(
endpoint.Id,
resourceGroupName,
profileName,
endpoint.Type,
endpoint.Name,
endpoint.Properties));
}
}
return profile;
}
private static string ExtractResourceGroupFromId(string id)
{
return id.Split('/')[4];
}
private static TrafficManagerEndpoint GetPowershellTrafficManagerEndpoint(string id, string resourceGroupName, string profileName, string endpointType, string endpointName, EndpointProperties mamlEndpointProperties)
{
return new TrafficManagerEndpoint
{
Id = id,
ResourceGroupName = resourceGroupName,
ProfileName = profileName,
Name = endpointName,
Type = endpointType,
EndpointStatus = mamlEndpointProperties.EndpointStatus,
EndpointMonitorStatus = mamlEndpointProperties.EndpointMonitorStatus,
GeoMapping = mamlEndpointProperties.GeoMapping != null ? mamlEndpointProperties.GeoMapping.ToList() : null,
Location = mamlEndpointProperties.EndpointLocation,
MinChildEndpoints = mamlEndpointProperties.MinChildEndpoints,
Priority = mamlEndpointProperties.Priority,
Target = mamlEndpointProperties.Target,
TargetResourceId = mamlEndpointProperties.TargetResourceId,
Weight = mamlEndpointProperties.Weight,
};
}
}
}
| apache-2.0 |
baslr/ArangoDB | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/language/expressions/compound-assignment/S11.13.2_A4.2_T2.4.js | 951 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The production x /= y is the same as x = x / y
es5id: 11.13.2_A4.2_T2.4
description: >
Type(x) is different from Type(y) and both types vary between
Number (primitive or object) and Undefined
---*/
var x;
//CHECK#1
x = 1;
x /= undefined;
if (isNaN(x) !== true) {
$ERROR('#1: x = 1; x /= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x /= 1;
if (isNaN(x) !== true) {
$ERROR('#2: x = undefined; x /= 1; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#3
x = new Number(1);
x /= undefined;
if (isNaN(x) !== true) {
$ERROR('#3: x = new Number(1); x /= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#4
x = undefined;
x /= new Number(1);
if (isNaN(x) !== true) {
$ERROR('#4: x = undefined; x /= new Number(1); x === Not-a-Number. Actual: ' + (x));
}
| apache-2.0 |
Mainflux/mainflux-lite | readers/postgres/doc.go | 185 | // Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
// Package postgres contains repository implementations using Postgres as
// the underlying database.
package postgres
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-cloudtasks/v2beta2/1.27.0/com/google/api/services/cloudtasks/v2beta2/model/SetIamPolicyRequest.java | 2687 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudtasks.v2beta2.model;
/**
* Request message for `SetIamPolicy` method.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Tasks API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class SetIamPolicyRequest extends com.google.api.client.json.GenericJson {
/**
* REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is
* limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform
* services (such as Projects) might reject them.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Policy policy;
/**
* REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is
* limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform
* services (such as Projects) might reject them.
* @return value or {@code null} for none
*/
public Policy getPolicy() {
return policy;
}
/**
* REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is
* limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform
* services (such as Projects) might reject them.
* @param policy policy or {@code null} for none
*/
public SetIamPolicyRequest setPolicy(Policy policy) {
this.policy = policy;
return this;
}
@Override
public SetIamPolicyRequest set(String fieldName, Object value) {
return (SetIamPolicyRequest) super.set(fieldName, value);
}
@Override
public SetIamPolicyRequest clone() {
return (SetIamPolicyRequest) super.clone();
}
}
| apache-2.0 |
davebarnes97/geode | geode-lucene/src/distributedTest/java/org/apache/geode/cache/lucene/PaginationDUnitTest.java | 6287 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.lucene;
import static org.apache.geode.cache.lucene.test.LuceneTestUtilities.INDEX_NAME;
import static org.apache.geode.cache.lucene.test.LuceneTestUtilities.REGION_NAME;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.PartitionedRegionStorageException;
import org.apache.geode.cache.Region;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.SerializableRunnableIF;
import org.apache.geode.test.junit.categories.LuceneTest;
@Category({LuceneTest.class})
@RunWith(JUnitParamsRunner.class)
public class PaginationDUnitTest extends LuceneQueriesAccessorBase {
protected static final int PAGE_SIZE = 2;
protected static final int FLUSH_WAIT_TIME_MS = 60000;
@Override
protected RegionTestableType[] getListOfRegionTestTypes() {
return new RegionTestableType[] {RegionTestableType.PARTITION_REDUNDANT_PERSISTENT};
}
protected void putEntryInEachBucket() {
accessor.invoke(() -> {
final Cache cache = getCache();
Region<Object, Object> region = cache.getRegion(REGION_NAME);
IntStream.range(0, NUM_BUCKETS).forEach(i -> region.put(i, new TestObject("hello world")));
});
}
@Test
@Parameters(method = "getListOfRegionTestTypes")
public void partitionedRegionStorageExceptionWhenAllDataStoreAreClosedWhilePagination(
RegionTestableType regionTestType) {
SerializableRunnableIF createIndex = () -> {
LuceneService luceneService = LuceneServiceProvider.get(getCache());
luceneService.createIndexFactory().setFields("text").create(INDEX_NAME, REGION_NAME);
};
dataStore1.invoke(() -> initDataStore(createIndex, regionTestType));
accessor.invoke(() -> initAccessor(createIndex, regionTestType));
putEntryInEachBucket();
assertTrue(waitForFlushBeforeExecuteTextSearch(dataStore1, FLUSH_WAIT_TIME_MS));
accessor.invoke(() -> {
Cache cache = getCache();
LuceneService service = LuceneServiceProvider.get(cache);
LuceneQuery<Integer, TestObject> query;
query = service.createLuceneQueryFactory().setLimit(1000).setPageSize(PAGE_SIZE)
.create(INDEX_NAME, REGION_NAME, "world", "text");
PageableLuceneQueryResults<Integer, TestObject> pages = query.findPages();
assertTrue(pages.hasNext());
List<LuceneResultStruct<Integer, TestObject>> page = pages.next();
assertEquals(page.size(), PAGE_SIZE, page.size());
dataStore1.invoke(() -> closeCache());
try {
page = pages.next();
fail();
} catch (Exception e) {
Assert.assertEquals(
"Expected Exception = PartitionedRegionStorageException but hit " + e.toString(), true,
e instanceof PartitionedRegionStorageException);
}
});
}
@Test
@Parameters(method = "getListOfRegionTestTypes")
public void noExceptionWhenOneDataStoreIsClosedButOneIsStillUpWhilePagination(
RegionTestableType regionTestType) {
SerializableRunnableIF createIndex = () -> {
LuceneService luceneService = LuceneServiceProvider.get(getCache());
luceneService.createIndexFactory().setFields("text").create(INDEX_NAME, REGION_NAME);
};
dataStore1.invoke(() -> initDataStore(createIndex, regionTestType));
dataStore2.invoke(() -> initDataStore(createIndex, regionTestType));
accessor.invoke(() -> initAccessor(createIndex, regionTestType));
putEntryInEachBucket();
assertTrue(waitForFlushBeforeExecuteTextSearch(dataStore1, FLUSH_WAIT_TIME_MS));
accessor.invoke(() -> {
List<LuceneResultStruct<Integer, TestObject>> combinedResult = new ArrayList<>();
Cache cache = getCache();
LuceneService service = LuceneServiceProvider.get(cache);
LuceneQuery<Integer, TestObject> query;
query = service.createLuceneQueryFactory().setLimit(1000).setPageSize(PAGE_SIZE)
.create(INDEX_NAME, REGION_NAME, "world", "text");
PageableLuceneQueryResults<Integer, TestObject> pages = query.findPages();
assertTrue(pages.hasNext());
List<LuceneResultStruct<Integer, TestObject>> page = pages.next();
combinedResult.addAll(page);
assertEquals(PAGE_SIZE, page.size());
dataStore1.invoke(() -> closeCache());
for (int i = 0; i < ((NUM_BUCKETS / PAGE_SIZE) - 1); i++) {
page = pages.next();
assertEquals(PAGE_SIZE, page.size());
combinedResult.addAll(page);
}
validateTheCombinedResult(combinedResult);
});
}
private void validateTheCombinedResult(
final List<LuceneResultStruct<Integer, TestObject>> combinedResult) {
Map<Integer, TestObject> resultMap = combinedResult.stream()
.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
assertEquals(NUM_BUCKETS, resultMap.size());
for (int i = 0; i < NUM_BUCKETS; i++) {
assertEquals("The aggregate result does not contain the key = " + i, true,
resultMap.containsKey(i));
assertEquals(new TestObject("hello world"), resultMap.get(i));
}
}
}
| apache-2.0 |
stianst/keycloak | testsuite/integration-arquillian/tests/other/webauthn/src/main/java/org/keycloak/testsuite/webauthn/authenticators/KcVirtualAuthenticator.java | 4009 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.webauthn.authenticators;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;
import java.util.Arrays;
import java.util.Map;
/**
* Keycloak Virtual Authenticator
* <p>
* Used as wrapper for VirtualAuthenticator and its options*
*
* @author <a href="mailto:[email protected]">Martin Bartos</a>
*/
public class KcVirtualAuthenticator {
private final VirtualAuthenticator authenticator;
private final Options options;
public KcVirtualAuthenticator(VirtualAuthenticator authenticator, VirtualAuthenticatorOptions options) {
this.authenticator = authenticator;
this.options = new Options(options);
}
public VirtualAuthenticator getAuthenticator() {
return authenticator;
}
public Options getOptions() {
return options;
}
public static final class Options {
private final VirtualAuthenticatorOptions options;
private final VirtualAuthenticatorOptions.Protocol protocol;
private final VirtualAuthenticatorOptions.Transport transport;
private final boolean hasResidentKey;
private final boolean hasUserVerification;
private final boolean isUserConsenting;
private final boolean isUserVerified;
private final Map<String, Object> map;
private Options(VirtualAuthenticatorOptions options) {
this.options = options;
this.map = options.toMap();
this.protocol = protocolFromMap(map);
this.transport = transportFromMap(map);
this.hasResidentKey = (Boolean) map.get("hasResidentKey");
this.hasUserVerification = (Boolean) map.get("hasUserVerification");
this.isUserConsenting = (Boolean) map.get("isUserConsenting");
this.isUserVerified = (Boolean) map.get("isUserVerified");
}
public VirtualAuthenticatorOptions.Protocol getProtocol() {
return protocol;
}
public VirtualAuthenticatorOptions.Transport getTransport() {
return transport;
}
public boolean hasResidentKey() {
return hasResidentKey;
}
public boolean hasUserVerification() {
return hasUserVerification;
}
public boolean isUserConsenting() {
return isUserConsenting;
}
public boolean isUserVerified() {
return isUserVerified;
}
public VirtualAuthenticatorOptions clone() {
return options;
}
public Map<String, Object> asMap() {
return map;
}
private static VirtualAuthenticatorOptions.Protocol protocolFromMap(Map<String, Object> map) {
return Arrays.stream(VirtualAuthenticatorOptions.Protocol.values())
.filter(f -> f.id.equals(map.get("protocol")))
.findFirst().orElse(null);
}
private static VirtualAuthenticatorOptions.Transport transportFromMap(Map<String, Object> map) {
return Arrays.stream(VirtualAuthenticatorOptions.Transport.values())
.filter(f -> f.id.equals(map.get("transport")))
.findFirst().orElse(null);
}
}
}
| apache-2.0 |
michaelschiff/druid | processing/src/main/java/org/apache/druid/segment/QueryableIndexColumnSelectorFactory.java | 7457 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.segment;
import org.apache.druid.java.util.common.io.Closer;
import org.apache.druid.query.dimension.DimensionSpec;
import org.apache.druid.query.extraction.ExtractionFn;
import org.apache.druid.segment.column.BaseColumn;
import org.apache.druid.segment.column.ColumnCapabilities;
import org.apache.druid.segment.column.ColumnHolder;
import org.apache.druid.segment.column.DictionaryEncodedColumn;
import org.apache.druid.segment.column.ValueType;
import org.apache.druid.segment.data.ReadableOffset;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* The basic implementation of {@link ColumnSelectorFactory} over a historical segment (i. e. {@link QueryableIndex}).
* It's counterpart for incremental index is {@link
* org.apache.druid.segment.incremental.IncrementalIndexColumnSelectorFactory}.
*/
class QueryableIndexColumnSelectorFactory implements ColumnSelectorFactory
{
private final QueryableIndex index;
private final VirtualColumns virtualColumns;
private final boolean descending;
private final Closer closer;
protected final ReadableOffset offset;
// Share Column objects, since they cache decompressed buffers internally, and we can avoid recomputation if the
// same column is used by more than one part of a query.
private final Map<String, BaseColumn> columnCache;
// Share selectors too, for the same reason that we cache columns (they may cache things internally).
private final Map<DimensionSpec, DimensionSelector> dimensionSelectorCache;
private final Map<String, ColumnValueSelector> valueSelectorCache;
QueryableIndexColumnSelectorFactory(
QueryableIndex index,
VirtualColumns virtualColumns,
boolean descending,
Closer closer,
ReadableOffset offset,
Map<String, BaseColumn> columnCache
)
{
this.index = index;
this.virtualColumns = virtualColumns;
this.descending = descending;
this.closer = closer;
this.offset = offset;
this.columnCache = columnCache;
this.dimensionSelectorCache = new HashMap<>();
this.valueSelectorCache = new HashMap<>();
}
@Override
public DimensionSelector makeDimensionSelector(DimensionSpec dimensionSpec)
{
Function<DimensionSpec, DimensionSelector> mappingFunction = spec -> {
if (virtualColumns.exists(spec.getDimension())) {
DimensionSelector dimensionSelector = virtualColumns.makeDimensionSelector(dimensionSpec, index, offset);
if (dimensionSelector == null) {
return virtualColumns.makeDimensionSelector(dimensionSpec, this);
} else {
return dimensionSelector;
}
}
return spec.decorate(makeDimensionSelectorUndecorated(spec));
};
// We cannot use dimensionSelectorCache.computeIfAbsent() here since the function being
// applied may modify the dimensionSelectorCache itself through virtual column references,
// triggering a ConcurrentModificationException in JDK 9 and above.
DimensionSelector dimensionSelector = dimensionSelectorCache.get(dimensionSpec);
if (dimensionSelector == null) {
dimensionSelector = mappingFunction.apply(dimensionSpec);
dimensionSelectorCache.put(dimensionSpec, dimensionSelector);
}
return dimensionSelector;
}
private DimensionSelector makeDimensionSelectorUndecorated(DimensionSpec dimensionSpec)
{
final String dimension = dimensionSpec.getDimension();
final ExtractionFn extractionFn = dimensionSpec.getExtractionFn();
final ColumnHolder columnHolder = index.getColumnHolder(dimension);
if (columnHolder == null) {
return DimensionSelector.constant(null, extractionFn);
}
if (dimension.equals(ColumnHolder.TIME_COLUMN_NAME)) {
return new SingleScanTimeDimensionSelector(makeColumnValueSelector(dimension), extractionFn, descending);
}
ValueType type = columnHolder.getCapabilities().getType();
if (type.isNumeric()) {
return type.makeNumericWrappingDimensionSelector(makeColumnValueSelector(dimension), extractionFn);
}
final DictionaryEncodedColumn column = getCachedColumn(dimension, DictionaryEncodedColumn.class);
if (column != null) {
return column.makeDimensionSelector(offset, extractionFn);
} else {
return DimensionSelector.constant(null, extractionFn);
}
}
@Override
public ColumnValueSelector<?> makeColumnValueSelector(String columnName)
{
Function<String, ColumnValueSelector<?>> mappingFunction = name -> {
if (virtualColumns.exists(columnName)) {
ColumnValueSelector<?> selector = virtualColumns.makeColumnValueSelector(columnName, index, offset);
if (selector == null) {
return virtualColumns.makeColumnValueSelector(columnName, this);
} else {
return selector;
}
}
BaseColumn column = getCachedColumn(columnName, BaseColumn.class);
if (column != null) {
return column.makeColumnValueSelector(offset);
} else {
return NilColumnValueSelector.instance();
}
};
// We cannot use valueSelectorCache.computeIfAbsent() here since the function being
// applied may modify the valueSelectorCache itself through virtual column references,
// triggering a ConcurrentModificationException in JDK 9 and above.
ColumnValueSelector<?> columnValueSelector = valueSelectorCache.get(columnName);
if (columnValueSelector == null) {
columnValueSelector = mappingFunction.apply(columnName);
valueSelectorCache.put(columnName, columnValueSelector);
}
return columnValueSelector;
}
@Nullable
@SuppressWarnings("unchecked")
private <T extends BaseColumn> T getCachedColumn(final String columnName, final Class<T> clazz)
{
return (T) columnCache.computeIfAbsent(
columnName,
name -> {
ColumnHolder holder = index.getColumnHolder(name);
if (holder != null && clazz.isAssignableFrom(holder.getColumn().getClass())) {
return closer.register(holder.getColumn());
} else {
// Return null from the lambda in computeIfAbsent() results in no recorded value in the columnCache and
// the column variable is set to null.
return null;
}
}
);
}
@Override
@Nullable
public ColumnCapabilities getColumnCapabilities(String columnName)
{
if (virtualColumns.exists(columnName)) {
return virtualColumns.getColumnCapabilities(columnName);
}
return QueryableIndexStorageAdapter.getColumnCapabilities(index, columnName);
}
}
| apache-2.0 |
wvdd007/azure-activedirectory-identitymodel-extensions-for-dotnet | tests/System.IdentityModel.Tokens.Jwt.Tests/TokenValidationParametersTests.cs | 13012 | //-----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// 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.
//-----------------------------------------------------------------------
using Microsoft.IdentityModel.Test;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Reflection;
using System.Security.Claims;
using System.Text;
namespace System.IdentityModel.Test
{
/// <summary>
///
/// </summary>
[TestClass]
public class TokenValidationParametersTests
{
/// <summary>
/// Test Context Wrapper instance on top of TestContext. Provides better accessor functions
/// </summary>
protected TestContextProvider _testContextProvider;
public TestContext TestContext { get; set; }
[ClassInitialize]
public static void ClassSetup( TestContext testContext )
{
// Start local STS
}
[ClassCleanup]
public static void ClassCleanup()
{
// Stop local STS
}
[TestInitialize]
public void Initialize()
{
_testContextProvider = new TestContextProvider( TestContext );
}
[TestMethod]
[TestProperty( "TestCaseID", "5763D198-1A0A-474D-A5D3-A5BBC496EE7B" )]
[Description( "Tests: Publics" )]
public void TokenValidationParameters_Publics()
{
TokenValidationParameters validationParameters = new TokenValidationParameters();
Type type = typeof(TokenValidationParameters);
PropertyInfo[] properties = type.GetProperties();
if (properties.Length != 30)
Assert.Fail("Number of properties has changed from 30 to: " + properties.Length + ", adjust tests");
SecurityKey issuerSigningKey = KeyingMaterial.DefaultSymmetricSecurityKey_256;
SecurityKey issuerSigningKey2 = KeyingMaterial.SymmetricSecurityKey2_256;
List<SecurityKey> issuerSigningKeys =
new List<SecurityKey>
{
KeyingMaterial.DefaultSymmetricSecurityKey_256,
KeyingMaterial.SymmetricSecurityKey2_256
};
List<SecurityKey> issuerSigningKeysDup =
new List<SecurityKey>
{
new InMemorySymmetricSecurityKey(KeyingMaterial.SymmetricKeyBytes2_256),
new InMemorySymmetricSecurityKey(KeyingMaterial.DefaultSymmetricKeyBytes_256)
};
string validAudience = "ValidAudience";
List<string> validAudiences = new List<string>{ validAudience };
string validIssuer = "ValidIssuer";
List<string> validIssuers = new List<string>{ validIssuer };
TokenValidationParameters validationParametersInline = new TokenValidationParameters()
{
AudienceValidator = IdentityUtilities.AudienceValidatorReturnsTrue,
IssuerSigningKey = issuerSigningKey,
IssuerSigningKeyResolver = (token, securityToken, keyIdentifier, tvp) => { return issuerSigningKey; },
IssuerSigningKeys = issuerSigningKeys,
IssuerValidator = IdentityUtilities.IssuerValidatorEcho,
LifetimeValidator = IdentityUtilities.LifetimeValidatorReturnsTrue,
SaveSigninToken = true,
ValidateAudience = false,
ValidateIssuer = false,
ValidAudience = validAudience,
ValidAudiences = validAudiences,
ValidIssuer = validIssuer,
ValidIssuers = validIssuers,
};
Assert.IsTrue(object.ReferenceEquals(validationParametersInline.IssuerSigningKey, issuerSigningKey));
Assert.IsTrue(validationParametersInline.SaveSigninToken);
Assert.IsFalse(validationParametersInline.ValidateAudience);
Assert.IsFalse(validationParametersInline.ValidateIssuer);
Assert.IsTrue(object.ReferenceEquals(validationParametersInline.ValidAudience, validAudience));
Assert.IsTrue(object.ReferenceEquals(validationParametersInline.ValidAudiences, validAudiences));
Assert.IsTrue(object.ReferenceEquals(validationParametersInline.ValidIssuer, validIssuer));
TokenValidationParameters validationParametersSets = new TokenValidationParameters();
validationParametersSets.AudienceValidator = IdentityUtilities.AudienceValidatorReturnsTrue;
validationParametersSets.IssuerSigningKey = new InMemorySymmetricSecurityKey(KeyingMaterial.DefaultSymmetricKeyBytes_256);
validationParametersSets.IssuerSigningKeyResolver = (token, securityToken, keyIdentifier, tvp) => { return issuerSigningKey2; };
validationParametersSets.IssuerSigningKeys = issuerSigningKeysDup;
validationParametersSets.IssuerValidator = IdentityUtilities.IssuerValidatorEcho;
validationParametersSets.LifetimeValidator = IdentityUtilities.LifetimeValidatorReturnsTrue;
validationParametersSets.SaveSigninToken = true;
validationParametersSets.ValidateAudience = false;
validationParametersSets.ValidateIssuer = false;
validationParametersSets.ValidAudience = validAudience;
validationParametersSets.ValidAudiences = validAudiences;
validationParametersSets.ValidIssuer = validIssuer;
validationParametersSets.ValidIssuers = validIssuers;
Assert.IsTrue(IdentityComparer.AreEqual<TokenValidationParameters>(validationParametersInline, validationParametersSets));
TokenValidationParameters tokenValidationParametersCloned = validationParametersInline.Clone() as TokenValidationParameters;
Assert.IsTrue(IdentityComparer.AreEqual<TokenValidationParameters>(tokenValidationParametersCloned, validationParametersInline));
//tokenValidationParametersCloned.AudienceValidator(new string[]{"bob"}, JwtTestTokens.Simple();
string id = Guid.NewGuid().ToString();
DerivedTokenValidationParameters derivedValidationParameters = new DerivedTokenValidationParameters(id, validationParametersInline);
DerivedTokenValidationParameters derivedValidationParametersCloned = derivedValidationParameters.Clone() as DerivedTokenValidationParameters;
Assert.IsTrue(IdentityComparer.AreEqual<TokenValidationParameters>(derivedValidationParameters, derivedValidationParametersCloned));
Assert.AreEqual(derivedValidationParameters.InternalString, derivedValidationParametersCloned.InternalString);
}
[TestMethod]
[TestProperty("TestCaseID", "5C8D86B6-08C8-416D-995E-FE6856E70999")]
[Description("Tests: GetSets, covers defaults")]
public void TokenValidationParameters_GetSets()
{
TokenValidationParameters validationParameters = new TokenValidationParameters();
Type type = typeof(TokenValidationParameters);
PropertyInfo[] properties = type.GetProperties();
if (properties.Length != 30)
Assert.Fail("Number of public fields has changed from 30 to: " + properties.Length + ", adjust tests");
GetSetContext context =
new GetSetContext
{
PropertyNamesAndSetGetValue = new List<KeyValuePair<string, List<object>>>
{
new KeyValuePair<string, List<object>>("AuthenticationType", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
new KeyValuePair<string, List<object>>("CertificateValidator", new List<object>{(string)null, X509CertificateValidator.None, X509CertificateValidatorEx.None}),
new KeyValuePair<string, List<object>>("ClockSkew", new List<object>{TokenValidationParameters.DefaultClockSkew, TimeSpan.FromHours(2), TimeSpan.FromMinutes(1)}),
new KeyValuePair<string, List<object>>("IssuerSigningKey", new List<object>{(SecurityKey)null, KeyingMaterial.DefaultAsymmetricKey_Public_2048, KeyingMaterial.DefaultSymmetricSecurityKey_256}),
new KeyValuePair<string, List<object>>("IssuerSigningKeys", new List<object>{(IEnumerable<SecurityKey>)null, new List<SecurityKey>{KeyingMaterial.DefaultAsymmetricKey_Public_2048, KeyingMaterial.DefaultSymmetricSecurityKey_256}, new List<SecurityKey>()}),
new KeyValuePair<string, List<object>>("IssuerSigningToken", new List<object>{(SecurityToken)null, KeyingMaterial.DefaultSymmetricSecurityToken_256, KeyingMaterial.DefaultAsymmetricX509Token_2048}),
new KeyValuePair<string, List<object>>("IssuerSigningTokens", new List<object>{(IEnumerable<SecurityToken>)null, new List<SecurityToken>{KeyingMaterial.DefaultAsymmetricX509Token_2048, KeyingMaterial.DefaultSymmetricSecurityToken_256}, new List<SecurityToken>()}),
new KeyValuePair<string, List<object>>("NameClaimType", new List<object>{ClaimsIdentity.DefaultNameClaimType, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
new KeyValuePair<string, List<object>>("RoleClaimType", new List<object>{ClaimsIdentity.DefaultRoleClaimType, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
new KeyValuePair<string, List<object>>("RequireExpirationTime", new List<object>{true, false, true}),
new KeyValuePair<string, List<object>>("RequireSignedTokens", new List<object>{true, false, true}),
new KeyValuePair<string, List<object>>("SaveSigninToken", new List<object>{false, true, false}),
new KeyValuePair<string, List<object>>("ValidateActor", new List<object>{false, true, false}),
new KeyValuePair<string, List<object>>("ValidateAudience", new List<object>{true, false, true}),
new KeyValuePair<string, List<object>>("ValidateIssuer", new List<object>{true, false, true}),
new KeyValuePair<string, List<object>>("ValidateLifetime", new List<object>{true, false, true}),
new KeyValuePair<string, List<object>>("ValidIssuer", new List<object>{(string)null, Guid.NewGuid().ToString(), Guid.NewGuid().ToString()}),
},
Object = validationParameters,
};
TestUtilities.GetSet(context);
if (context.Errors.Count != 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(Environment.NewLine);
foreach (string str in context.Errors)
sb.AppendLine(str);
Assert.Fail(sb.ToString());
}
Assert.IsNull(validationParameters.AudienceValidator);
Assert.IsNotNull(validationParameters.ClientDecryptionTokens);
Assert.AreEqual(validationParameters.ClientDecryptionTokens.Count, 0);
Assert.IsNull(validationParameters.LifetimeValidator);
Assert.IsNull(validationParameters.IssuerSigningKeyResolver);
Assert.IsNull(validationParameters.IssuerValidator);
Assert.IsNull(validationParameters.ValidAudiences);
Assert.IsNull(validationParameters.ValidIssuers);
}
class DerivedTokenValidationParameters : TokenValidationParameters
{
string _internalString;
public DerivedTokenValidationParameters(string internalString, TokenValidationParameters validationParameters)
: base(validationParameters)
{
_internalString = internalString;
}
protected DerivedTokenValidationParameters(DerivedTokenValidationParameters other)
: base(other)
{
_internalString = other._internalString;
}
public string InternalString{ get {return _internalString; }}
public override TokenValidationParameters Clone()
{
return new DerivedTokenValidationParameters(this);
}
}
}
}
| apache-2.0 |
opsengine/chef | chef/lib/chef/resource/mdadm.rb | 1801 | #
# Author:: Joe Williams (<[email protected]>)
# Copyright:: Copyright (c) 2009 Joe Williams
# License:: Apache License, Version 2.0
#
# 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.
#
require 'chef/resource'
class Chef
class Resource
class Mdadm < Chef::Resource
def initialize(name, run_context=nil)
super
@resource_name = :mdadm
@chunk = 16
@devices = []
@exists = false
@level = 1
@raid_device = name
@action = :create
@allowed_actions.push(:create, :assemble, :stop)
end
def chunk(arg=nil)
set_or_return(
:chunk,
arg,
:kind_of => [ Integer ]
)
end
def devices(arg=nil)
set_or_return(
:devices,
arg,
:kind_of => [ Array ]
)
end
def exists(arg=nil)
set_or_return(
:exists,
arg,
:kind_of => [ TrueClass, FalseClass ]
)
end
def level(arg=nil)
set_or_return(
:level,
arg,
:kind_of => [ Integer ]
)
end
def raid_device(arg=nil)
set_or_return(
:raid_device,
arg,
:kind_of => [ String ]
)
end
end
end
end
| apache-2.0 |
mpimenov/omim | android/src/com/mapswithme/util/statistics/Analytics.java | 278 | package com.mapswithme.util.statistics;
import androidx.annotation.NonNull;
public class Analytics
{
@NonNull
private final String mName;
public Analytics(@NonNull String name)
{
mName = name;
}
@NonNull
public String getName()
{
return mName;
}
}
| apache-2.0 |
ya7lelkom/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201411/CreativeSet.java | 11556 | /**
* CreativeSet.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201411;
/**
* A creative set is comprised of a master creative and its companion
* creatives.
*/
public class CreativeSet implements java.io.Serializable {
/* Uniquely identifies the {@code CreativeSet}. This attribute
* is
* read-only and is assigned by Google when a creative
* set is created. */
private java.lang.Long id;
/* The name of the creative set. This attribute is required and
* has a
* maximum length of 255 characters. */
private java.lang.String name;
/* The ID of the master creative associated with this creative
* set. This attribute is required. */
private java.lang.Long masterCreativeId;
/* The IDs of the companion creatives associated with this creative
* set. This attribute is
* required. */
private long[] companionCreativeIds;
/* The date and time this creative set was last modified. */
private com.google.api.ads.dfp.axis.v201411.DateTime lastModifiedDateTime;
public CreativeSet() {
}
public CreativeSet(
java.lang.Long id,
java.lang.String name,
java.lang.Long masterCreativeId,
long[] companionCreativeIds,
com.google.api.ads.dfp.axis.v201411.DateTime lastModifiedDateTime) {
this.id = id;
this.name = name;
this.masterCreativeId = masterCreativeId;
this.companionCreativeIds = companionCreativeIds;
this.lastModifiedDateTime = lastModifiedDateTime;
}
/**
* Gets the id value for this CreativeSet.
*
* @return id * Uniquely identifies the {@code CreativeSet}. This attribute
* is
* read-only and is assigned by Google when a creative
* set is created.
*/
public java.lang.Long getId() {
return id;
}
/**
* Sets the id value for this CreativeSet.
*
* @param id * Uniquely identifies the {@code CreativeSet}. This attribute
* is
* read-only and is assigned by Google when a creative
* set is created.
*/
public void setId(java.lang.Long id) {
this.id = id;
}
/**
* Gets the name value for this CreativeSet.
*
* @return name * The name of the creative set. This attribute is required and
* has a
* maximum length of 255 characters.
*/
public java.lang.String getName() {
return name;
}
/**
* Sets the name value for this CreativeSet.
*
* @param name * The name of the creative set. This attribute is required and
* has a
* maximum length of 255 characters.
*/
public void setName(java.lang.String name) {
this.name = name;
}
/**
* Gets the masterCreativeId value for this CreativeSet.
*
* @return masterCreativeId * The ID of the master creative associated with this creative
* set. This attribute is required.
*/
public java.lang.Long getMasterCreativeId() {
return masterCreativeId;
}
/**
* Sets the masterCreativeId value for this CreativeSet.
*
* @param masterCreativeId * The ID of the master creative associated with this creative
* set. This attribute is required.
*/
public void setMasterCreativeId(java.lang.Long masterCreativeId) {
this.masterCreativeId = masterCreativeId;
}
/**
* Gets the companionCreativeIds value for this CreativeSet.
*
* @return companionCreativeIds * The IDs of the companion creatives associated with this creative
* set. This attribute is
* required.
*/
public long[] getCompanionCreativeIds() {
return companionCreativeIds;
}
/**
* Sets the companionCreativeIds value for this CreativeSet.
*
* @param companionCreativeIds * The IDs of the companion creatives associated with this creative
* set. This attribute is
* required.
*/
public void setCompanionCreativeIds(long[] companionCreativeIds) {
this.companionCreativeIds = companionCreativeIds;
}
public long getCompanionCreativeIds(int i) {
return this.companionCreativeIds[i];
}
public void setCompanionCreativeIds(int i, long _value) {
this.companionCreativeIds[i] = _value;
}
/**
* Gets the lastModifiedDateTime value for this CreativeSet.
*
* @return lastModifiedDateTime * The date and time this creative set was last modified.
*/
public com.google.api.ads.dfp.axis.v201411.DateTime getLastModifiedDateTime() {
return lastModifiedDateTime;
}
/**
* Sets the lastModifiedDateTime value for this CreativeSet.
*
* @param lastModifiedDateTime * The date and time this creative set was last modified.
*/
public void setLastModifiedDateTime(com.google.api.ads.dfp.axis.v201411.DateTime lastModifiedDateTime) {
this.lastModifiedDateTime = lastModifiedDateTime;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CreativeSet)) return false;
CreativeSet other = (CreativeSet) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.id==null && other.getId()==null) ||
(this.id!=null &&
this.id.equals(other.getId()))) &&
((this.name==null && other.getName()==null) ||
(this.name!=null &&
this.name.equals(other.getName()))) &&
((this.masterCreativeId==null && other.getMasterCreativeId()==null) ||
(this.masterCreativeId!=null &&
this.masterCreativeId.equals(other.getMasterCreativeId()))) &&
((this.companionCreativeIds==null && other.getCompanionCreativeIds()==null) ||
(this.companionCreativeIds!=null &&
java.util.Arrays.equals(this.companionCreativeIds, other.getCompanionCreativeIds()))) &&
((this.lastModifiedDateTime==null && other.getLastModifiedDateTime()==null) ||
(this.lastModifiedDateTime!=null &&
this.lastModifiedDateTime.equals(other.getLastModifiedDateTime())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getId() != null) {
_hashCode += getId().hashCode();
}
if (getName() != null) {
_hashCode += getName().hashCode();
}
if (getMasterCreativeId() != null) {
_hashCode += getMasterCreativeId().hashCode();
}
if (getCompanionCreativeIds() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getCompanionCreativeIds());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getCompanionCreativeIds(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getLastModifiedDateTime() != null) {
_hashCode += getLastModifiedDateTime().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CreativeSet.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "CreativeSet"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("id");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "id"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("name");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "name"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("masterCreativeId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "masterCreativeId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("companionCreativeIds");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "companionCreativeIds"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lastModifiedDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "lastModifiedDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
jeremyeder/origin | vendor/k8s.io/kubernetes/pkg/kubelet/cm/container_manager_windows.go | 6151 | // +build windows
/*
Copyright 2015 The Kubernetes Authors.
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.
*/
// containerManagerImpl implements container manager on Windows.
// Only GetNodeAllocatableReservation() and GetCapacity() are implemented now.
package cm
import (
"fmt"
"k8s.io/klog/v2"
"k8s.io/mount-utils"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/client-go/tools/record"
internalapi "k8s.io/cri-api/pkg/apis"
podresourcesapi "k8s.io/kubelet/pkg/apis/podresources/v1"
kubefeatures "k8s.io/kubernetes/pkg/features"
"k8s.io/kubernetes/pkg/kubelet/cadvisor"
"k8s.io/kubernetes/pkg/kubelet/cm/cpumanager"
"k8s.io/kubernetes/pkg/kubelet/cm/topologymanager"
"k8s.io/kubernetes/pkg/kubelet/config"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/kubelet/lifecycle"
"k8s.io/kubernetes/pkg/kubelet/pluginmanager/cache"
"k8s.io/kubernetes/pkg/kubelet/status"
schedulerframework "k8s.io/kubernetes/pkg/scheduler/framework"
)
type containerManagerImpl struct {
// Capacity of this node.
capacity v1.ResourceList
// Interface for cadvisor.
cadvisorInterface cadvisor.Interface
// Config of this node.
nodeConfig NodeConfig
}
type noopWindowsResourceAllocator struct{}
func (ra *noopWindowsResourceAllocator) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {
return lifecycle.PodAdmitResult{
Admit: true,
}
}
func (cm *containerManagerImpl) Start(node *v1.Node,
activePods ActivePodsFunc,
sourcesReady config.SourcesReady,
podStatusProvider status.PodStatusProvider,
runtimeService internalapi.RuntimeService) error {
klog.V(2).Infof("Starting Windows container manager")
if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.LocalStorageCapacityIsolation) {
rootfs, err := cm.cadvisorInterface.RootFsInfo()
if err != nil {
return fmt.Errorf("failed to get rootfs info: %v", err)
}
for rName, rCap := range cadvisor.EphemeralStorageCapacityFromFsInfo(rootfs) {
cm.capacity[rName] = rCap
}
}
return nil
}
// NewContainerManager creates windows container manager.
func NewContainerManager(mountUtil mount.Interface, cadvisorInterface cadvisor.Interface, nodeConfig NodeConfig, failSwapOn bool, devicePluginEnabled bool, recorder record.EventRecorder) (ContainerManager, error) {
// It is safe to invoke `MachineInfo` on cAdvisor before logically initializing cAdvisor here because
// machine info is computed and cached once as part of cAdvisor object creation.
// But `RootFsInfo` and `ImagesFsInfo` are not available at this moment so they will be called later during manager starts
machineInfo, err := cadvisorInterface.MachineInfo()
if err != nil {
return nil, err
}
capacity := cadvisor.CapacityFromMachineInfo(machineInfo)
return &containerManagerImpl{
capacity: capacity,
nodeConfig: nodeConfig,
cadvisorInterface: cadvisorInterface,
}, nil
}
func (cm *containerManagerImpl) SystemCgroupsLimit() v1.ResourceList {
return v1.ResourceList{}
}
func (cm *containerManagerImpl) GetNodeConfig() NodeConfig {
return NodeConfig{}
}
func (cm *containerManagerImpl) GetMountedSubsystems() *CgroupSubsystems {
return &CgroupSubsystems{}
}
func (cm *containerManagerImpl) GetQOSContainersInfo() QOSContainersInfo {
return QOSContainersInfo{}
}
func (cm *containerManagerImpl) UpdateQOSCgroups() error {
return nil
}
func (cm *containerManagerImpl) Status() Status {
return Status{}
}
func (cm *containerManagerImpl) GetNodeAllocatableReservation() v1.ResourceList {
evictionReservation := hardEvictionReservation(cm.nodeConfig.HardEvictionThresholds, cm.capacity)
result := make(v1.ResourceList)
for k := range cm.capacity {
value := resource.NewQuantity(0, resource.DecimalSI)
if cm.nodeConfig.SystemReserved != nil {
value.Add(cm.nodeConfig.SystemReserved[k])
}
if cm.nodeConfig.KubeReserved != nil {
value.Add(cm.nodeConfig.KubeReserved[k])
}
if evictionReservation != nil {
value.Add(evictionReservation[k])
}
if !value.IsZero() {
result[k] = *value
}
}
return result
}
func (cm *containerManagerImpl) GetCapacity() v1.ResourceList {
return cm.capacity
}
func (cm *containerManagerImpl) GetPluginRegistrationHandler() cache.PluginHandler {
return nil
}
func (cm *containerManagerImpl) GetDevicePluginResourceCapacity() (v1.ResourceList, v1.ResourceList, []string) {
return nil, nil, []string{}
}
func (cm *containerManagerImpl) NewPodContainerManager() PodContainerManager {
return &podContainerManagerStub{}
}
func (cm *containerManagerImpl) GetResources(pod *v1.Pod, container *v1.Container) (*kubecontainer.RunContainerOptions, error) {
return &kubecontainer.RunContainerOptions{}, nil
}
func (cm *containerManagerImpl) UpdatePluginResources(*schedulerframework.NodeInfo, *lifecycle.PodAdmitAttributes) error {
return nil
}
func (cm *containerManagerImpl) InternalContainerLifecycle() InternalContainerLifecycle {
return &internalContainerLifecycleImpl{cpumanager.NewFakeManager(), topologymanager.NewFakeManager()}
}
func (cm *containerManagerImpl) GetPodCgroupRoot() string {
return ""
}
func (cm *containerManagerImpl) GetDevices(_, _ string) []*podresourcesapi.ContainerDevices {
return nil
}
func (cm *containerManagerImpl) ShouldResetExtendedResourceCapacity() bool {
return false
}
func (cm *containerManagerImpl) GetAllocateResourcesPodAdmitHandler() lifecycle.PodAdmitHandler {
return &noopWindowsResourceAllocator{}
}
func (cm *containerManagerImpl) UpdateAllocatedDevices() {
return
}
func (cm *containerManagerImpl) GetCPUs(_, _ string) []int64 {
return nil
}
| apache-2.0 |
sarvex/tensorflow | tensorflow/python/framework/experimental/tape.py | 2291 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Experimental impl for GradientTape using unified APIs, for testing only."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework.experimental import _tape
from tensorflow.python.framework.experimental import context_stack
from tensorflow.python.framework.experimental import gradient_registry
from tensorflow.python.util import nest
class GradientTape(object):
"""GradientTape using the unified API."""
def __init__(self, persistent=False):
self._c_tape = _tape.Tape(persistent)
ctx = context_stack.get_default()
self._tape_context = _tape.TapeContext(
ctx, self._c_tape, gradient_registry.get_global_registry())
self._ctx_manager = None
def watch(self, t):
self._c_tape.Watch(t)
# TODO(srbs): Add support for unconnected_gradients.
def gradient(self, targets, sources, output_gradients=None):
ctx = context_stack.get_default()
flat_targets = nest.flatten(targets)
flat_sources = nest.flatten(sources)
out_grads = self._c_tape.ComputeGradient(ctx, flat_targets, flat_sources,
output_gradients or [])
return nest.pack_sequence_as(sources, out_grads)
def __enter__(self):
"""Enters a context inside which operations are recorded on this tape."""
self._ctx_manager = context_stack.set_default(self._tape_context)
self._ctx_manager.__enter__()
return self
def __exit__(self, typ, value, traceback):
self._ctx_manager.__exit__(typ, value, traceback)
self._ctx_manager = None
| apache-2.0 |
gfyoung/elasticsearch | server/src/main/java/org/elasticsearch/indices/store/IndicesStore.java | 21479 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.indices.store;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.ClusterStateObserver;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardState;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportChannel;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestHandler;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportResponseHandler;
import org.elasticsearch.transport.TransportService;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class IndicesStore extends AbstractComponent implements ClusterStateListener, Closeable {
// TODO this class can be foled into either IndicesService and partially into IndicesClusterStateService there is no need for a separate public service
public static final Setting<TimeValue> INDICES_STORE_DELETE_SHARD_TIMEOUT =
Setting.positiveTimeSetting("indices.store.delete.shard.timeout", new TimeValue(30, TimeUnit.SECONDS),
Property.NodeScope);
public static final String ACTION_SHARD_EXISTS = "internal:index/shard/exists";
private static final EnumSet<IndexShardState> ACTIVE_STATES = EnumSet.of(IndexShardState.STARTED);
private final IndicesService indicesService;
private final ClusterService clusterService;
private final TransportService transportService;
private final ThreadPool threadPool;
// Cache successful shard deletion checks to prevent unnecessary file system lookups
private final Set<ShardId> folderNotFoundCache = new HashSet<>();
private TimeValue deleteShardTimeout;
@Inject
public IndicesStore(Settings settings, IndicesService indicesService,
ClusterService clusterService, TransportService transportService, ThreadPool threadPool) {
super(settings);
this.indicesService = indicesService;
this.clusterService = clusterService;
this.transportService = transportService;
this.threadPool = threadPool;
transportService.registerRequestHandler(ACTION_SHARD_EXISTS, ShardActiveRequest::new, ThreadPool.Names.SAME, new ShardActiveRequestHandler());
this.deleteShardTimeout = INDICES_STORE_DELETE_SHARD_TIMEOUT.get(settings);
// Doesn't make sense to delete shards on non-data nodes
if (DiscoveryNode.isDataNode(settings)) {
// we double check nothing has changed when responses come back from other nodes.
// it's easier to do that check when the current cluster state is visible.
// also it's good in general to let things settle down
clusterService.addListener(this);
}
}
@Override
public void close() {
if (DiscoveryNode.isDataNode(settings)) {
clusterService.removeListener(this);
}
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
if (!event.routingTableChanged()) {
return;
}
if (event.state().blocks().disableStatePersistence()) {
return;
}
RoutingTable routingTable = event.state().routingTable();
// remove entries from cache that don't exist in the routing table anymore (either closed or deleted indices)
// - removing shard data of deleted indices is handled by IndicesClusterStateService
// - closed indices don't need to be removed from the cache but we do it anyway for code simplicity
for (Iterator<ShardId> it = folderNotFoundCache.iterator(); it.hasNext(); ) {
ShardId shardId = it.next();
if (routingTable.hasIndex(shardId.getIndex()) == false) {
it.remove();
}
}
// remove entries from cache which are allocated to this node
final String localNodeId = event.state().nodes().getLocalNodeId();
RoutingNode localRoutingNode = event.state().getRoutingNodes().node(localNodeId);
if (localRoutingNode != null) {
for (ShardRouting routing : localRoutingNode) {
folderNotFoundCache.remove(routing.shardId());
}
}
for (IndexRoutingTable indexRoutingTable : routingTable) {
// Note, closed indices will not have any routing information, so won't be deleted
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
ShardId shardId = indexShardRoutingTable.shardId();
if (folderNotFoundCache.contains(shardId) == false && shardCanBeDeleted(localNodeId, indexShardRoutingTable)) {
IndexService indexService = indicesService.indexService(indexRoutingTable.getIndex());
final IndexSettings indexSettings;
if (indexService == null) {
IndexMetaData indexMetaData = event.state().getMetaData().getIndexSafe(indexRoutingTable.getIndex());
indexSettings = new IndexSettings(indexMetaData, settings);
} else {
indexSettings = indexService.getIndexSettings();
}
IndicesService.ShardDeletionCheckResult shardDeletionCheckResult = indicesService.canDeleteShardContent(shardId, indexSettings);
switch (shardDeletionCheckResult) {
case FOLDER_FOUND_CAN_DELETE:
deleteShardIfExistElseWhere(event.state(), indexShardRoutingTable);
break;
case NO_FOLDER_FOUND:
folderNotFoundCache.add(shardId);
break;
case NO_LOCAL_STORAGE:
assert false : "shard deletion only runs on data nodes which always have local storage";
// nothing to do
break;
case STILL_ALLOCATED:
// nothing to do
break;
default:
assert false : "unknown shard deletion check result: " + shardDeletionCheckResult;
}
}
}
}
}
static boolean shardCanBeDeleted(String localNodeId, IndexShardRoutingTable indexShardRoutingTable) {
// a shard can be deleted if all its copies are active, and its not allocated on this node
if (indexShardRoutingTable.size() == 0) {
// should not really happen, there should always be at least 1 (primary) shard in a
// shard replication group, in any case, protected from deleting something by mistake
return false;
}
for (ShardRouting shardRouting : indexShardRoutingTable) {
// be conservative here, check on started, not even active
if (shardRouting.started() == false) {
return false;
}
// check if shard is active on the current node
if (localNodeId.equals(shardRouting.currentNodeId())) {
return false;
}
}
return true;
}
private void deleteShardIfExistElseWhere(ClusterState state, IndexShardRoutingTable indexShardRoutingTable) {
List<Tuple<DiscoveryNode, ShardActiveRequest>> requests = new ArrayList<>(indexShardRoutingTable.size());
String indexUUID = indexShardRoutingTable.shardId().getIndex().getUUID();
ClusterName clusterName = state.getClusterName();
for (ShardRouting shardRouting : indexShardRoutingTable) {
assert shardRouting.started() : "expected started shard but was " + shardRouting;
DiscoveryNode currentNode = state.nodes().get(shardRouting.currentNodeId());
requests.add(new Tuple<>(currentNode, new ShardActiveRequest(clusterName, indexUUID, shardRouting.shardId(), deleteShardTimeout)));
}
ShardActiveResponseHandler responseHandler = new ShardActiveResponseHandler(indexShardRoutingTable.shardId(), state.getVersion(),
requests.size());
for (Tuple<DiscoveryNode, ShardActiveRequest> request : requests) {
logger.trace("{} sending shard active check to {}", request.v2().shardId, request.v1());
transportService.sendRequest(request.v1(), ACTION_SHARD_EXISTS, request.v2(), responseHandler);
}
}
private class ShardActiveResponseHandler implements TransportResponseHandler<ShardActiveResponse> {
private final ShardId shardId;
private final int expectedActiveCopies;
private final long clusterStateVersion;
private final AtomicInteger awaitingResponses;
private final AtomicInteger activeCopies;
ShardActiveResponseHandler(ShardId shardId, long clusterStateVersion, int expectedActiveCopies) {
this.shardId = shardId;
this.expectedActiveCopies = expectedActiveCopies;
this.clusterStateVersion = clusterStateVersion;
this.awaitingResponses = new AtomicInteger(expectedActiveCopies);
this.activeCopies = new AtomicInteger();
}
@Override
public ShardActiveResponse read(StreamInput in) throws IOException {
return new ShardActiveResponse(in);
}
@Override
public void handleResponse(ShardActiveResponse response) {
logger.trace("{} is {}active on node {}", shardId, response.shardActive ? "" : "not ", response.node);
if (response.shardActive) {
activeCopies.incrementAndGet();
}
if (awaitingResponses.decrementAndGet() == 0) {
allNodesResponded();
}
}
@Override
public void handleException(TransportException exp) {
logger.debug(() -> new ParameterizedMessage("shards active request failed for {}", shardId), exp);
if (awaitingResponses.decrementAndGet() == 0) {
allNodesResponded();
}
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
private void allNodesResponded() {
if (activeCopies.get() != expectedActiveCopies) {
logger.trace("not deleting shard {}, expected {} active copies, but only {} found active copies", shardId, expectedActiveCopies, activeCopies.get());
return;
}
ClusterState latestClusterState = clusterService.state();
if (clusterStateVersion != latestClusterState.getVersion()) {
logger.trace("not deleting shard {}, the latest cluster state version[{}] is not equal to cluster state before shard active api call [{}]", shardId, latestClusterState.getVersion(), clusterStateVersion);
return;
}
clusterService.getClusterApplierService().runOnApplierThread("indices_store ([" + shardId + "] active fully on other nodes)",
currentState -> {
if (clusterStateVersion != currentState.getVersion()) {
logger.trace("not deleting shard {}, the update task state version[{}] is not equal to cluster state before shard active api call [{}]", shardId, currentState.getVersion(), clusterStateVersion);
return;
}
try {
indicesService.deleteShardStore("no longer used", shardId, currentState);
} catch (Exception ex) {
logger.debug(() -> new ParameterizedMessage("{} failed to delete unallocated shard, ignoring", shardId), ex);
}
},
(source, e) -> logger.error(() -> new ParameterizedMessage("{} unexpected error during deletion of unallocated shard", shardId), e)
);
}
}
private class ShardActiveRequestHandler implements TransportRequestHandler<ShardActiveRequest> {
@Override
public void messageReceived(final ShardActiveRequest request, final TransportChannel channel, Task task) throws Exception {
IndexShard indexShard = getShard(request);
// make sure shard is really there before register cluster state observer
if (indexShard == null) {
channel.sendResponse(new ShardActiveResponse(false, clusterService.localNode()));
} else {
// create observer here. we need to register it here because we need to capture the current cluster state
// which will then be compared to the one that is applied when we call waitForNextChange(). if we create it
// later we might miss an update and wait forever in case no new cluster state comes in.
// in general, using a cluster state observer here is a workaround for the fact that we cannot listen on shard state changes explicitly.
// instead we wait for the cluster state changes because we know any shard state change will trigger or be
// triggered by a cluster state change.
ClusterStateObserver observer = new ClusterStateObserver(clusterService, request.timeout, logger, threadPool.getThreadContext());
// check if shard is active. if so, all is good
boolean shardActive = shardActive(indexShard);
if (shardActive) {
channel.sendResponse(new ShardActiveResponse(true, clusterService.localNode()));
} else {
// shard is not active, might be POST_RECOVERY so check if cluster state changed inbetween or wait for next change
observer.waitForNextChange(new ClusterStateObserver.Listener() {
@Override
public void onNewClusterState(ClusterState state) {
sendResult(shardActive(getShard(request)));
}
@Override
public void onClusterServiceClose() {
sendResult(false);
}
@Override
public void onTimeout(TimeValue timeout) {
sendResult(shardActive(getShard(request)));
}
public void sendResult(boolean shardActive) {
try {
channel.sendResponse(new ShardActiveResponse(shardActive, clusterService.localNode()));
} catch (IOException e) {
logger.error(() -> new ParameterizedMessage("failed send response for shard active while trying to delete shard {} - shard will probably not be removed", request.shardId), e);
} catch (EsRejectedExecutionException e) {
logger.error(() -> new ParameterizedMessage("failed send response for shard active while trying to delete shard {} - shard will probably not be removed", request.shardId), e);
}
}
}, newState -> {
// the shard is not there in which case we want to send back a false (shard is not active), so the cluster state listener must be notified
// or the shard is active in which case we want to send back that the shard is active
// here we could also evaluate the cluster state and get the information from there. we
// don't do it because we would have to write another method for this that would have the same effect
IndexShard currentShard = getShard(request);
return currentShard == null || shardActive(currentShard);
});
}
}
}
private boolean shardActive(IndexShard indexShard) {
if (indexShard != null) {
return ACTIVE_STATES.contains(indexShard.state());
}
return false;
}
private IndexShard getShard(ShardActiveRequest request) {
ClusterName thisClusterName = clusterService.getClusterName();
if (!thisClusterName.equals(request.clusterName)) {
logger.trace("shard exists request meant for cluster[{}], but this is cluster[{}], ignoring request", request.clusterName, thisClusterName);
return null;
}
ShardId shardId = request.shardId;
IndexService indexService = indicesService.indexService(shardId.getIndex());
if (indexService != null && indexService.indexUUID().equals(request.indexUUID)) {
return indexService.getShardOrNull(shardId.id());
}
return null;
}
}
private static class ShardActiveRequest extends TransportRequest {
protected TimeValue timeout = null;
private ClusterName clusterName;
private String indexUUID;
private ShardId shardId;
ShardActiveRequest() {
}
ShardActiveRequest(ClusterName clusterName, String indexUUID, ShardId shardId, TimeValue timeout) {
this.shardId = shardId;
this.indexUUID = indexUUID;
this.clusterName = clusterName;
this.timeout = timeout;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
clusterName = new ClusterName(in);
indexUUID = in.readString();
shardId = ShardId.readShardId(in);
timeout = new TimeValue(in.readLong(), TimeUnit.MILLISECONDS);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
clusterName.writeTo(out);
out.writeString(indexUUID);
shardId.writeTo(out);
out.writeLong(timeout.millis());
}
}
private static class ShardActiveResponse extends TransportResponse {
private final boolean shardActive;
private final DiscoveryNode node;
ShardActiveResponse(boolean shardActive, DiscoveryNode node) {
this.shardActive = shardActive;
this.node = node;
}
ShardActiveResponse(StreamInput in) throws IOException {
shardActive = in.readBoolean();
node = new DiscoveryNode(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(shardActive);
node.writeTo(out);
}
}
}
| apache-2.0 |
sll8192/adstar | uikit/src/com/netease/nim/uikit/common/util/string/HexDump.java | 4170 | package com.netease.nim.uikit.common.util.string;
import java.io.IOException;
import java.io.StringReader;
public class HexDump {
class HexTablifier {
private int m_row = 8;
private String m_pre = "";
private String m_post = "\n";
public HexTablifier() {
}
public HexTablifier(int row) {
this(row, "", "\n");
}
public HexTablifier(int row, String pre) {
this(row, pre, "\n");
}
public HexTablifier(int row, String pre, String post) {
m_row = row;
m_pre = pre;
m_post = post;
}
public String format(String hex) {
StringReader reader = new StringReader(hex);
StringBuilder builder = new StringBuilder(hex.length() * 2);
try {
while (getHexLine(builder, reader)) {
}
} catch (IOException e) {
// 不应该有异常出现。
}
return builder.toString();
}
private boolean getHexLine(StringBuilder builder, StringReader reader)
throws IOException {
StringBuilder lineBuilder = new StringBuilder();
boolean result = true;
for (int i = 0; i < m_row; i++) {
result = getHexByte(lineBuilder, reader);
if (result == false)
break;
}
if (lineBuilder.length() > 0) {
builder.append(m_pre);
builder.append(lineBuilder);
builder.append(m_post);
}
return result;
}
private boolean getHexByte(StringBuilder builder, StringReader reader)
throws IOException {
char[] hexByte = new char[4];
int bytesRead = reader.read(hexByte);
if (bytesRead == -1)
return false;
builder.append(hexByte, 0, bytesRead);
builder.append(" ");
return bytesRead == 4;
}
}
private static final char m_hexCodes[] = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final int m_shifts[] = { 60, 56, 52, 48, 44, 40, 36, 32, 28,
24, 20, 16, 12, 8, 4, 0 };
public static String tablify(byte[] bytes) {
return (new HexDump()).new HexTablifier().format(HexDump.toHex(bytes));
}
public static String tablify(byte[] bytes, int row) {
return (new HexDump()).new HexTablifier(row).format(HexDump
.toHex(bytes));
}
public static String tablify(byte[] bytes, int row, String pre) {
return (new HexDump()).new HexTablifier(row, pre).format(HexDump
.toHex(bytes));
}
public static String tablify(String hex, int row, String pre, String post) {
return (new HexDump()).new HexTablifier(row, pre, post).format(hex);
}
private static String toHex(final long value, final int digitNum) {
StringBuilder result = new StringBuilder(digitNum);
for (int j = 0; j < digitNum; j++) {
int index = (int) ((value >> m_shifts[j + (16 - digitNum)]) & 15);
result.append(m_hexCodes[index]);
}
return result.toString();
}
public static String toHex(final byte value) {
return toHex(value, 2);
}
public static String toHex(final short value) {
return toHex(value, 4);
}
public static String toHex(final int value) {
return toHex(value, 8);
}
public static String toHex(final long value) {
return toHex(value, 16);
}
public static String toHex(final byte[] value) {
return toHex(value, 0, value.length);
}
public static String toHex(final byte[] value, final int offset,
final int length) {
StringBuilder retVal = new StringBuilder();
int end = offset + length;
for (int x = offset; x < end; x++)
retVal.append(toHex(value[x]));
return retVal.toString();
}
public static byte[] restoreBytes(String hex) {
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; ++i) {
int c1 = charToNumber(hex.charAt(2 * i));
int c2 = charToNumber(hex.charAt(2 * i + 1));
if (c1 == -1 || c2 == -1) {
return null;
}
bytes[i] = (byte) ((c1 << 4) + c2);
}
return bytes;
}
private static int charToNumber(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 0xa;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 0xA;
} else {
return -1;
}
}
}
| apache-2.0 |
renzifeng/renzifeng | node_modules/hexo-renderer-marked/node_modules/hexo-util/node_modules/highlight.js/lib/languages/javascript.js | 3503 | module.exports = function(hljs) {
return {
aliases: ['js'],
keywords: {
keyword:
'in of if for while finally var new function do return void else break catch ' +
'instanceof with throw case default try this switch continue typeof delete ' +
'let yield const export super debugger as async await ' +
// ECMAScript 6 modules import
'import from as'
,
literal:
'true false null undefined NaN Infinity',
built_in:
'eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent ' +
'encodeURI encodeURIComponent escape unescape Object Function Boolean Error ' +
'EvalError InternalError RangeError ReferenceError StopIteration SyntaxError ' +
'TypeError URIError Number Math Date String RegExp Array Float32Array ' +
'Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array ' +
'Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require ' +
'module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect ' +
'Promise'
},
contains: [
{
className: 'meta',
relevance: 10,
begin: /^\s*['"]use (strict|asm)['"]/
},
{
className: 'meta',
begin: /^#!/, end: /$/
},
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
{ // template string
className: 'string',
begin: '`', end: '`',
contains: [
hljs.BACKSLASH_ESCAPE,
{
className: 'subst',
begin: '\\$\\{', end: '\\}'
}
]
},
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
{
className: 'number',
variants: [
{ begin: '\\b(0[bB][01]+)' },
{ begin: '\\b(0[oO][0-7]+)' },
{ begin: hljs.C_NUMBER_RE }
],
relevance: 0
},
{ // "value" container
begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*',
keywords: 'return throw case',
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.REGEXP_MODE,
{ // E4X / JSX
begin: /</, end: />\s*[);\]]/,
relevance: 0,
subLanguage: 'xml'
}
],
relevance: 0
},
{
className: 'function',
beginKeywords: 'function', end: /\{/, excludeEnd: true,
contains: [
hljs.inherit(hljs.TITLE_MODE, {begin: /[A-Za-z$_][0-9A-Za-z$_]*/}),
{
className: 'params',
begin: /\(/, end: /\)/,
excludeBegin: true,
excludeEnd: true,
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
}
],
illegal: /\[|%/
},
{
begin: /\$[(.]/ // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
},
{
begin: '\\.' + hljs.IDENT_RE, relevance: 0 // hack: prevents detection of keywords after dots
},
{ // ES6 class
className: 'class',
beginKeywords: 'class', end: /[{;=]/, excludeEnd: true,
illegal: /[:"\[\]]/,
contains: [
{beginKeywords: 'extends'},
hljs.UNDERSCORE_TITLE_MODE
]
},
{
beginKeywords: 'constructor', end: /\{/, excludeEnd: true
}
],
illegal: /#(?!!)/
};
}; | apache-2.0 |
robhoes/xenadmin | XenAdmin/Dialogs/IscsiChoicesDialog.cs | 2854 | /* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XenAdmin.Wizards.NewSRWizard_Pages;
using XenAdmin.Network;
namespace XenAdmin.Dialogs
{
/// <summary>
/// When an existing SR is found on an iSCSI LUN, asks the user if they want
/// to attach the SR, wipe the LUN and create a new SR, or do nothing (cancel).
///
/// DialogResult.Yes - Reattach
/// DialogResult.No - Format
/// DialogResult.Cancel - Cancel
/// </summary>
public partial class IscsiChoicesDialog : XenDialogBase
{
public IscsiChoicesDialog(IXenConnection connection, XenAPI.SR.SRInfo srInfo)
: base(connection)
{
InitializeComponent();
this.labelSRinfo.Text = String.Format(Messages.ISCSI_DIALOG_SR_DETAILS,
Util.DiskSizeString(srInfo.Size), srInfo.UUID);
}
public IscsiChoicesDialog(IXenConnection connection, FibreChannelDevice dev)
: base(connection)
{
InitializeComponent();
this.labelSRinfo.Text = String.Format(Messages.ISCSI_DIALOG_SR_DETAILS_FOR_FIBRECHANNEL,
dev.Vendor, dev.Serial, string.IsNullOrEmpty(dev.SCSIid) ? dev.Path : dev.SCSIid, Util.DiskSizeString(dev.Size));
}
}
}
| bsd-2-clause |
tribouille/MediaInfoLib | Source/MediaInfo/Audio/File_Aac_Others.cpp | 17035 | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if defined(MEDIAINFO_AAC_YES)
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_Aac.h"
#if defined(MEDIAINFO_RIFF_YES)
#include "MediaInfo/Multiple/File_Riff.h"
#endif
#include <cmath>
using namespace std;
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//***************************************************************************
// Speech coding (HVXC)
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::HvxcSpecificConfig()
{
Element_Begin1("HvxcSpecificConfig");
bool isBaseLayer;
Get_SB(isBaseLayer, "isBaseLayer");
if (isBaseLayer)
HVXCconfig();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::HVXCconfig()
{
Element_Begin1("HVXCconfig");
Skip_SB( "HVXCvarMode");
Skip_S1(2, "HVXCrateMode");
Skip_SB( "extensionFlag");
//~ if (extensionFlag) {
/*< to be defined in MPEG-4 Version 2 >*/
//~ }
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::ErrorResilientHvxcSpecificConfig() {
Element_Begin1("ErrorResilientHvxcSpecificConfig");
bool isBaseLayer;
Get_SB(isBaseLayer,"isBaseLayer");
if (isBaseLayer) {
ErHVXCconfig();
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::ErHVXCconfig()
{
Element_Begin1("ErHVXCconfig");
bool extensionFlag;
Skip_SB( "HVXCvarMode");
Skip_S1(2, "HVXCrateMode");
Get_SB (extensionFlag, "extensionFlag");
if (extensionFlag) {
Skip_SB( "var_ScalableFlag");
}
Element_End0();
}
//***************************************************************************
// Speech Coding (CELP)
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::CelpSpecificConfig ()
{
Element_Begin1("CelpSpecificConfig");
bool isBaseLayer;
Get_SB(isBaseLayer, "isBaseLayer");
if (isBaseLayer)
{
CelpHeader ();
}
else
{
bool isBWSLayer;
Get_SB(isBWSLayer, "isBWSLayer");
if (isBWSLayer)
{
//~ CelpBWSenhHeader ()
//~ {
Skip_S1(2, "BWS_configuration");
//~ }
}
else
{
Skip_S1(2, "CELP-BRS-id");
}
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::CelpHeader ()
{
Element_Begin1("CelpHeader");
bool ExcitationMode;
Get_SB(ExcitationMode, "ExcitationMode");
Skip_SB( "SampleRateMode");
Skip_SB( "FineRateControl");
if (ExcitationMode == 1/*RPE*/)
{
Skip_S1(3, "RPE_Configuration");
}
if (ExcitationMode == 0/*MPE*/)
{
Skip_S1(5, "MPE_Configuration");
Skip_S1(2, "NumEnhLayers");
Skip_SB( "BandwidthScalabilityMode");
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::ErrorResilientCelpSpecificConfig ()
{
Element_Begin1("ErrorResilientCelpSpecificConfig");
bool isBaseLayer;
Get_SB(isBaseLayer, "isBaseLayer");
if (isBaseLayer)
{
ER_SC_CelpHeader ();
}
else
{
bool isBWSLayer;
Get_SB(isBWSLayer, "isBWSLayer");
if (isBWSLayer)
{
//~ CelpBWSenhHeader ()
//~ {
Skip_S1(2, "BWS_configuration");
//~ }
}
else
{
Skip_S1(2, "CELP-BRS-id");
}
}
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::ER_SC_CelpHeader ()
{
Element_Begin1("ER_SC_CelpHeader");
bool ExcitationMode;
Get_SB(ExcitationMode, "ExcitationMode");
Skip_SB( "SampleRateMode");
Skip_SB( "FineRateControl");
Skip_SB( "SilenceCompression");
if (ExcitationMode == 1/*RPE*/) {
Skip_S1(3, "RPE_Configuration");
}
if (ExcitationMode == 0/*MPE*/) {
Skip_S1(5, "MPE_Configuration");
Skip_S1(2, "NumEnhLayers");
Skip_SB( "BandwidthScalabilityMode");
}
Element_End0();
}
//***************************************************************************
// Structured Audio (SA)
//***************************************************************************
//***************************************************************************
// Text to Speech Interface (TTSI)
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::TTSSpecificConfig()
{
Element_Begin1("TTSSpecificConfig");
//~ TTS_Sequence()
//~ {
Skip_S1(5, "TTS_Sequence_ID");
Skip_BS(18, "Language_Code");
Skip_SB( "Gender_Enable");
Skip_SB( "Age_Enable");
Skip_SB( "Speech_Rate_Enable");
Skip_SB( "Prosody_Enable");
Skip_SB( "Video_Enable");
Skip_SB( "Lip_Shape_Enable");
Skip_SB( "Trick_Mode_Enable");
//~ }
Element_End0();
}
//***************************************************************************
// Parametric Audio (HILN)
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::HILNconfig()
{
Element_Begin1("HILNconfig");
Skip_SB( "HILNquantMode");
Skip_S1(8, "HILNmaxNumLine");
Skip_S1(4, "HILNsampleRateCode");
Skip_S2(12, "HILNframeLength");
Skip_S1(2, "HILNcontMode");
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::HILNenexConfig()
{
Element_Begin1("HILNenexConfig");
bool HILNenhaLayer;
Get_SB(HILNenhaLayer, "HILNenhaLayer");
if (HILNenhaLayer)
Skip_S1(2, "HILNenhaQuantMode");
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::ParametricSpecificConfig()
{
Element_Begin1("ParametricSpecificConfig");
bool isBaseLayer;
Get_SB(isBaseLayer, "isBaseLayer");
if (isBaseLayer)
PARAconfig();
else
HILNenexConfig();
Element_End0();
}
//---------------------------------------------------------------------------
void File_Aac::PARAconfig()
{
Element_Begin1("PARAconfig");
int8u PARAmode;
Get_S1(2,PARAmode, "PARAmode");
if (PARAmode != 1)
ErHVXCconfig();
if (PARAmode != 0)
HILNconfig();
bool PARAextensionFlag;
Get_SB(PARAextensionFlag, "PARAextensionFlag");
if (PARAextensionFlag) {
/* to be defined in MPEG-4 Phase 3 */
}
Element_End0();
}
//***************************************************************************
// Technical description of parametric coding for high quality audio
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::SSCSpecificConfig ()
{
Element_Begin1("SSCSpecificConfig");
Skip_S1(2,"decoder_level");
Skip_S1(4,"update_rate");
Skip_S1(2,"synthesis_method");
if (channelConfiguration != 1)
{
int8u mode_ext;
Get_S1(2,mode_ext,"mode_ext");
if ((channelConfiguration == 2) && (mode_ext == 1))
{
/*reserved*/
}
}
Element_End0();
}
//***************************************************************************
// MPEG-1/2 Audio
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::MPEG_1_2_SpecificConfig()
{
Element_Begin1("MPEG_1_2_SpecificConfig");
Skip_SB( "extension");
Element_End0();
}
//***************************************************************************
// Technical description of lossless coding of oversampled audio
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::DSTSpecificConfig()
{
Element_Begin1("DSTSpecificConfig");
Skip_SB("DSDDST_Coded");
Skip_S2(14,"N_Channels");
Skip_SB("reserved");
Element_End0();
}
//***************************************************************************
// Audio Lossless
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::ALSSpecificConfig()
{
//Not in spec, but something weird in the example I have
int32u Junk;
while (Data_BS_Remain())
{
Peek_S4(32, Junk);
if (Junk!=0x414C5300)
{
Skip_SB( "Unknown");
}
else
break;
}
if (Data_BS_Remain()==0)
return; //There is a problem
Element_Begin1("ALSSpecificConfig");
bool chan_config,chan_sort,crc_enabled,aux_data_enabled;
int32u samp_freq, samples;
int16u channels,frame_length;
int8u ra_flag,random_access, file_type;
Skip_BS(32,"als_id");
Get_BS (32, samp_freq, "samp_freq");
Get_BS (32, samples, "samples");
Get_S2 (16, channels, "channels"); Param_Info2(channels+1, " channel(s)");
Get_S1 (3, file_type, "file_type");
Skip_S1(3,"resolution");
Skip_SB("floating");
Skip_SB("msb_first");
Get_S2 (16,frame_length,"frame_length");
Get_S1 (8,random_access,"random_access");
Get_S1 (2,ra_flag,"ra_flag");
Skip_SB("adapt_order");
Skip_S1(2,"coef_table");
Skip_SB("long_term_prediction");
Skip_S2(10,"max_order");
Skip_S1(2,"block_switching");
Skip_SB("bgmc_mode");
Skip_SB("sb_part");
Skip_SB("joint_stereo");
Skip_SB("mc_coding");
Get_SB (chan_config,"chan_config");
Get_SB (chan_sort,"chan_sort");
Get_SB (crc_enabled,"crc_enabled");
Skip_SB("RLSLMS");
Skip_BS(5,"(reserved)");
Get_SB (aux_data_enabled,"aux_data_enabled");
if (chan_config)
Skip_S2(16,"chan_config_info");
if (chan_sort)
{
int16u ChBits=(int16u)ceil(log((double)(channels+1))/log((double)2));
for (int8u c=0; c<=channels; c++)
Skip_BS(ChBits, "chan_pos[c]");
}
if(Data_BS_Remain()%8)
Skip_S1(Data_BS_Remain()%8, "byte_align");
BS_End();
int32u header_size,trailer_size;
Get_B4(header_size, "header_size");
Get_B4(trailer_size, "trailer_size");
#ifdef MEDIAINFO_RIFF_YES
if (file_type==1) //WAVE file
{
Element_Begin1("orig_header");
File_Riff MI;
Open_Buffer_Init(&MI);
Open_Buffer_Continue(&MI, Buffer+Buffer_Offset+(size_t)Element_Offset, header_size);
Element_Offset+=header_size;
File__Analyze::Finish(&MI); //No merge of data, only for trace information, because this is the data about the decoded stream, not the encoded stream
Element_End0();
}
else
#endif //MEDIAINFO_RIFF_YES
Skip_XX(header_size, "orig_header[]");
Skip_XX(trailer_size, "orig_trailer[]");
if (crc_enabled)
Skip_B4( "crc");
if ((ra_flag == 2) && (random_access > 0))
for (int32u f=0; f<((samples-1)/(frame_length+1))+1; f++)
Skip_B4( "ra_unit_size[f]");
if (aux_data_enabled)
{
int32u aux_size;
Get_B4(aux_size, "aux_size");
Skip_XX(aux_size, "aux_data[]");
}
Element_End0();
BS_Begin(); //To be in sync with other objectTypes
FILLING_BEGIN();
//Filling
File__Analyze::Stream_Prepare(Stream_Audio);
Fill(Stream_Audio, StreamPos_Last, Audio_Channel_s_, channels+1);
//Forcing default confignuration (something weird in the example I have)
channelConfiguration=0;
sampling_frequency_index=(int8u)-1;
Frequency_b=samp_freq;
FILLING_END();
}
//***************************************************************************
// Scalable lossless
//***************************************************************************
//---------------------------------------------------------------------------
void File_Aac::SLSSpecificConfig()
{
Element_Begin1("SLSSpecificConfig");
Skip_S1(3,"pcmWordLength");
Skip_SB("aac_core_present");
Skip_SB("lle_main_stream");
Skip_SB("reserved_bit");
Skip_S1(3,"frameLength");
if (!channelConfiguration)
program_config_element();
Element_End0();
}
} //NameSpace
#endif //MEDIAINFO_AAC_YES
| bsd-2-clause |
stgraber/homebrew-core | Formula/highlight.rb | 1686 | class Highlight < Formula
desc "Convert source code to formatted text with syntax highlighting"
homepage "http://www.andre-simon.de/doku/highlight/en/highlight.php"
url "http://www.andre-simon.de/zip/highlight-4.1.tar.bz2"
sha256 "3a4b6aa55b9837ea217f78e1f52bb294dbf3aaf4ccf8a5553cf859be4fbf3907"
license "GPL-3.0-or-later"
head "https://gitlab.com/saalen/highlight.git", branch: "master"
livecheck do
url "http://www.andre-simon.de/zip/download.php"
regex(/href=.*?highlight[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 arm64_monterey: "6727bd0348ec08e9855fd4574cf8a564d94cba5c3195f1bb9852f9733c351f08"
sha256 arm64_big_sur: "90c97137575b00aaa9050fb14f049e6b1dcfe236ae4266d7e684706f09a58f0f"
sha256 monterey: "4186adee8552304558aa2fd7af70db3355b92650564324b6cd02770bd22d4887"
sha256 big_sur: "e364d145b581f0622acf1cc9476142b8e318efa60495ca6e9c1f44ed560a2d66"
sha256 catalina: "4238b72def77283c7cedf385639bd9b28b5d0e3fb5d5c0bc6ec6fe6d06ae7bcf"
sha256 mojave: "81057a5898f59793eda32340275cb8bf87da61e6330bb5d0e925690c678b606b"
sha256 x86_64_linux: "f6f656122700a511ed946ca5a3d4db0e05db5c6f4f988567e866dfc50938a406"
end
depends_on "boost" => :build
depends_on "pkg-config" => :build
depends_on "lua"
on_linux do
depends_on "gcc"
end
fails_with gcc: "5" # needs C++17
def install
conf_dir = etc/"highlight/" # highlight needs a final / for conf_dir
system "make", "PREFIX=#{prefix}", "conf_dir=#{conf_dir}"
system "make", "PREFIX=#{prefix}", "conf_dir=#{conf_dir}", "install"
end
test do
system bin/"highlight", doc/"extras/highlight_pipe.php"
end
end
| bsd-2-clause |
agimofcarmen/xenadmin | XenModel/Utils/PropertyManager.cs | 3073 | /* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace XenAdmin.Core
{
public class PropertyManager
{
// resource file with internationalized display strings
public static System.Resources.ResourceManager FriendlyNames = new System.Resources.ResourceManager("XenAdmin.FriendlyNames", typeof(PropertyManager).Assembly);
/// <summary>
/// Returns null if no match is found.
/// </summary>
public static string GetFriendlyName(string s)
{
string result = FriendlyNames.GetString(s);
#if DEBUG
Debug.Assert(result != null, string.Format("{0} doesn't exist in FriendlyNames", s));
#endif
return result;
}
/// <summary>
/// Return the result of GetFriendlyName(s), or GetFriendlyName(defkey) if the former returns null.
/// Returns null if no match is found for defkey.
/// </summary>
public static string GetFriendlyName(string s, string defkey)
{
string result = FriendlyNames.GetString(s) ?? FriendlyNames.GetString(defkey);
#if DEBUG
Debug.Assert(result != null, string.Format("{0} doesn't exist in FriendlyNames", s));
#endif
return result;
}
/// <summary>
/// Returns true if this culture is loaded
/// </summary>
public static bool IsCultureLoaded(CultureInfo ci)
{
return FriendlyNames.GetResourceSet(ci, false, false) != null;
}
}
}
| bsd-2-clause |
aaryani/CoreTardisTemp | tardis/tardis_portal/tests/slapd.py | 13708 | """
Utilities for starting up a test slapd server
and talking to it with ldapsearch/ldapadd.
"""
import sys
import os
import socket
import time
import subprocess
import logging
import tempfile
from os import path as os_path
_log = logging.getLogger("slapd")
def quote(s):
'''Quotes the " and \ characters in a string and surrounds with "..."
'''
return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
def mkdirs(path):
"""Creates the directory path unless it already exists"""
if not os.access(os.path.join(path, os.path.curdir), os.F_OK):
_log.debug("creating temp directory %s", path)
os.mkdir(path)
return path
def delete_directory_content(path):
for dirpath, dirnames, filenames in os.walk(path, topdown=False):
for n in filenames:
_log.info("remove %s", os.path.join(dirpath, n))
os.remove(os.path.join(dirpath, n))
for n in dirnames:
_log.info("rmdir %s", os.path.join(dirpath, n))
os.rmdir(os.path.join(dirpath, n))
LOCALHOST = '127.0.0.1'
def find_available_tcp_port(host=LOCALHOST):
s = socket.socket()
s.bind((host, 0))
port = s.getsockname()[1]
s.close()
_log.info("Found available port %d", port)
return port
class Slapd:
"""
Controller class for a slapd instance, OpenLDAP's server.
This class creates a temporary data store for slapd, runs it
on a private port, and initialises it with a top-level dc and
the root user.
When a reference to an instance of this class is lost, the slapd
server is shut down.
"""
_log = logging.getLogger("Slapd")
# Use /var/tmp to placate apparmour on Ubuntu:
TEST_UTILS_DIR = os_path.abspath(os_path.split(__file__)[0])
PATH_TMPDIR = "/var/tmp/python-ldap-test"
PATH_TMPDIR = tempfile.mkdtemp()
PATH_SBINDIR = "/usr/sbin"
PATH_BINDIR = "/usr/bin"
PATH_SCHEMA_DIR = TEST_UTILS_DIR + "/ldap_schemas/"
PATH_LDAPADD = os.path.join(PATH_BINDIR, "ldapadd")
PATH_LDAPSEARCH = os.path.join(PATH_BINDIR, "ldapsearch")
PATH_SLAPD = os.path.join(PATH_SBINDIR, "slapd")
PATH_SLAPTEST = os.path.join(PATH_SBINDIR, "slaptest")
# TODO add paths for other OSs
def check_paths(cls):
"""
Checks that the configured executable paths look valid.
If they don't, then logs warning messages (not errors).
"""
for name, path in (
("slapd", cls.PATH_SLAPD),
("ldapadd", cls.PATH_LDAPADD),
("ldapsearch", cls.PATH_LDAPSEARCH),
):
cls._log.debug("checking %s executable at %s", name, path)
if not os.access(path, os.X_OK):
cls._log.warn("cannot find %s executable at %s", name, path)
return False
return True
check_paths = classmethod(check_paths)
def __init__(self):
self._config = []
self._proc = None
self._port = 0
self._tmpdir = self.PATH_TMPDIR
self._dn_suffix = "dc=python-ldap,dc=org"
self._root_cn = "Manager"
self._root_password = "password"
self._slapd_debug_level = 0
# Setters
def set_port(self, port):
self._port = port
def set_dn_suffix(self, dn):
self._dn_suffix = dn
def set_root_cn(self, cn):
self._root_cn = cn
def set_root_password(self, pw):
self._root_password = pw
def set_tmpdir(self, path):
self._tmpdir = path
def set_slapd_debug_level(self, level):
self._slapd_debug_level = level
def set_debug(self):
self._log.setLevel(logging.DEBUG)
self.set_slapd_debug_level('Any')
# getters
def get_url(self):
return "ldap://%s:%d/" % self.get_address()
def get_address(self):
if self._port == 0:
self._port = find_available_tcp_port(LOCALHOST)
return (LOCALHOST, self._port)
def get_dn_suffix(self):
return self._dn_suffix
def get_root_dn(self):
return "cn=" + self._root_cn + "," + self.get_dn_suffix()
def get_root_password(self):
return self._root_password
def get_tmpdir(self):
return self._tmpdir
def __del__(self):
self.stop()
def configure(self, cfg):
"""
Appends slapd.conf configuration lines to cfg.
Also re-initializes any backing storage.
Feel free to subclass and override this method.
"""
# Global
schema_list = os.listdir(self.PATH_SCHEMA_DIR)
schema_list.sort()
for schema in schema_list:
cfg.append("include " + quote(self.PATH_SCHEMA_DIR + schema))
cfg.append("allow bind_v2")
# Database
ldif_dir = mkdirs(os.path.join(self.get_tmpdir(), "ldif-data"))
delete_directory_content(ldif_dir) # clear it out
cfg.append("database ldif")
cfg.append("directory " + quote(ldif_dir))
cfg.append("suffix " + quote(self.get_dn_suffix()))
cfg.append("rootdn " + quote(self.get_root_dn()))
cfg.append("rootpw " + quote(self.get_root_password()))
def _write_config(self):
"""Writes the slapd.conf file out, and returns the path to it."""
path = os.path.join(self._tmpdir, "slapd.conf")
ldif_dir = mkdirs(self._tmpdir)
if os.access(path, os.F_OK):
self._log.debug("deleting existing %s", path)
os.remove(path)
self._log.debug("writing config to %s", path)
file(path, "w").writelines([line + "\n" for line in self._config])
return path
def start(self):
"""
Starts the slapd server process running, and waits for it to come up.
"""
if self._proc is None:
ok = False
config_path = None
try:
self.configure(self._config)
self._test_configuration()
self._start_slapd()
self._wait_for_slapd()
ok = True
self._log.debug("slapd ready at %s", self.get_url())
self.started()
finally:
if not ok:
if config_path:
try:
os.remove(config_path)
except os.error:
pass
if self._proc:
self.stop()
def _start_slapd(self):
# Spawns/forks the slapd process
config_path = self._write_config()
self._log.info("starting slapd")
self._proc = subprocess.Popen([self.PATH_SLAPD,
"-f", config_path,
"-h", self.get_url(),
"-d", str(self._slapd_debug_level),
])
self._proc_config = config_path
def _wait_for_slapd(self):
# Waits until the LDAP server socket is open, or slapd crashed
s = socket.socket()
while 1:
if self._proc.poll() is not None:
self._stopped()
raise RuntimeError("slapd exited before opening port")
try:
self._log.debug("Connecting to %s", repr(self.get_address()))
s.connect(self.get_address())
s.close()
return
except socket.error:
time.sleep(1)
def stop(self):
"""Stops the slapd server, and waits for it to terminate"""
if self._proc is not None:
self._log.debug("stopping slapd")
if hasattr(self._proc, 'terminate'):
self._proc.terminate()
else:
import posix
import signal
posix.kill(self._proc.pid, signal.SIGHUP)
#time.sleep(1)
#posix.kill(self._proc.pid, signal.SIGTERM)
#posix.kill(self._proc.pid, signal.SIGKILL)
self.wait()
def restart(self):
"""
Restarts the slapd server; ERASING previous content.
Starts the server even it if isn't already running.
"""
self.stop()
self.start()
def wait(self):
"""Waits for the slapd process to terminate by itself."""
if self._proc:
self._proc.wait()
self._stopped()
def _stopped(self):
"""Called when the slapd server is known to have terminated"""
if self._proc is not None:
self._log.info("slapd terminated")
self._proc = None
try:
os.remove(self._proc_config)
except os.error:
self._log.debug("could not remove %s", self._proc_config)
def _test_configuration(self):
config_path = self._write_config()
try:
self._log.debug("testing configuration")
verboseflag = "-Q"
if self._log.isEnabledFor(logging.DEBUG):
verboseflag = "-v"
p = subprocess.Popen([
self.PATH_SLAPTEST,
verboseflag,
"-f", config_path
])
if p.wait() != 0:
raise RuntimeError("configuration test failed")
self._log.debug("configuration seems ok")
finally:
os.remove(config_path)
def ldapadd(self, ldif, extra_args=[]):
"""Runs ldapadd on this slapd instance, passing it the ldif content"""
self._log.debug("adding %s", repr(ldif))
p = subprocess.Popen([self.PATH_LDAPADD,
"-x",
"-D", self.get_root_dn(),
"-w", self.get_root_password(),
"-H", self.get_url()] + extra_args,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.communicate(ldif)
if p.wait() != 0:
raise RuntimeError("ldapadd process failed")
def ldapsearch(self, base=None, filter='(objectClass=*)', attrs=[],
scope='sub', extra_args=[]):
if base is None:
base = self.get_dn_suffix()
self._log.debug("ldapsearch filter=%s", repr(filter))
p = subprocess.Popen([self.PATH_LDAPSEARCH,
"-x",
"-D", self.get_root_dn(),
"-w", self.get_root_password(),
"-H", self.get_url(),
"-b", base,
"-s", scope,
"-LL",
] + extra_args + [filter] + attrs,
stdout=subprocess.PIPE)
output = p.communicate()[0]
if p.wait() != 0:
raise RuntimeError("ldapadd process failed")
# RFC 2849: LDIF format
# unfold
lines = []
for l in output.split('\n'):
if l.startswith(' '):
lines[-1] = lines[-1] + l[1:]
elif l == '' and lines and lines[-1] == '':
pass # ignore multiple blank lines
else:
lines.append(l)
# Remove comments
lines = [l for l in lines if not l.startswith("#")]
# Remove leading version and blank line(s)
if lines and lines[0] == '':
del lines[0]
if not lines or lines[0] != 'version: 1':
raise RuntimeError("expected 'version: 1', got " + repr(lines[:1]))
del lines[0]
if lines and lines[0] == '':
del lines[0]
# ensure the ldif ends with a blank line (unless it is just blank)
if lines and lines[-1] != '':
lines.append('')
objects = []
obj = []
for line in lines:
if line == '': # end of an object
if obj[0][0] != 'dn':
raise RuntimeError("first line not dn", repr(obj))
objects.append((obj[0][1], obj[1:]))
obj = []
else:
attr, value = line.split(':', 2)
if value.startswith(': '):
value = base64.decodestring(value[2:])
elif value.startswith(' '):
value = value[1:]
else:
raise RuntimeError("bad line: " + repr(line))
obj.append((attr, value))
assert obj == []
return objects
def started(self):
"""
This method is called when the LDAP server has started up and is empty.
By default, this method adds the two initial objects,
the domain object and the root user object.
"""
assert self.get_dn_suffix().startswith("dc=")
suffix_dc = self.get_dn_suffix().split(',')[0][3:]
assert self.get_root_dn().startswith("cn=")
assert self.get_root_dn().endswith("," + self.get_dn_suffix())
root_cn = self.get_root_dn().split(',')[0][3:]
self._log.debug("adding %s and %s",
self.get_dn_suffix(),
self.get_root_dn())
self.ldapadd("\n".join([
'dn: ' + self.get_dn_suffix(),
'objectClass: dcObject',
'objectClass: organization',
'dc: ' + suffix_dc,
'o: ' + suffix_dc,
'',
'dn: ' + self.get_root_dn(),
'objectClass: organizationalRole',
'cn: ' + root_cn,
''
]))
Slapd.check_paths()
if __name__ == '__main__' and sys.argv == ['run']:
logging.basicConfig(level=logging.DEBUG)
slapd = Slapd()
print("Starting slapd...")
slapd.start()
print("Contents of LDAP server follow:\n")
for dn, attrs in slapd.ldapsearch():
print("dn: " + dn)
for name, val in attrs:
print(name + ": " + val)
print("")
print(slapd.get_url())
slapd.wait()
| bsd-3-clause |
dinhkhanh/trac | trac/upgrades/db29.py | 1969 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/.
import shutil
from trac.util import create_unique_file
from trac.util.text import exception_to_unicode
_svn_components = [
'svn_fs.SubversionConnector',
'svn_prop.SubversionMergePropertyDiffRenderer',
'svn_prop.SubversionMergePropertyRenderer',
'svn_prop.SubversionPropertyRenderer',
]
_old_path = 'trac.versioncontrol.'
_new_path = 'tracopt.versioncontrol.svn.'
def do_upgrade(env, version, cursor):
"""Automatically enable tracopt.versioncontrol.svn.* components,
unless they were explicitly disabled or the new svn components are
already enabled.
"""
enable = [c for c in _svn_components
if env.is_component_enabled(_old_path + c) and
not env.is_component_enabled(_new_path + c)]
if not enable:
return
try:
backup, f = create_unique_file(env.config.filename
+ '.tracopt-svn.bak')
f.close()
shutil.copyfile(env.config.filename, backup)
env.log.info("Saved backup of configuration file in %s", backup)
except IOError, e:
env.log.warn("Couldn't save backup of configuration file (%s)",
exception_to_unicode(e))
for c in enable:
env.config.set('components', _new_path + c, 'enabled')
env.config.save()
env.log.info("Enabled components %r to cope with the move from %s to %s.",
enable,
_old_path.replace('.', '/'), _new_path.replace('.', '/'))
| bsd-3-clause |
chromium/chromium | components/webapps/browser/android/webapps_icon_utils.cc | 5443 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/webapps/browser/android/webapps_icon_utils.h"
#include "base/android/build_info.h"
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "components/webapps/browser/android/webapps_jni_headers/WebappsIconUtils_jni.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/color_analysis.h"
#include "url/android/gurl_android.h"
#include "url/gurl.h"
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
namespace webapps {
namespace {
int g_ideal_homescreen_icon_size = -1;
int g_minimum_homescreen_icon_size = -1;
int g_ideal_splash_image_size = -1;
int g_minimum_splash_image_size = -1;
int g_ideal_monochrome_icon_size = -1;
int g_ideal_adaptive_launcher_icon_size = -1;
int g_ideal_shortcut_icon_size = -1;
// Retrieves and caches the ideal and minimum sizes of the Home screen icon,
// the splash screen image, and the shortcut icons.
void GetIconSizes() {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jintArray> java_size_array =
Java_WebappsIconUtils_getIconSizes(env);
std::vector<int> sizes;
base::android::JavaIntArrayToIntVector(env, java_size_array, &sizes);
// Check that the size returned is what is expected.
DCHECK_EQ(7u, sizes.size());
// This ordering must be kept up to date with the Java WebappsIconUtils.
g_ideal_homescreen_icon_size = sizes[0];
g_minimum_homescreen_icon_size = sizes[1];
g_ideal_splash_image_size = sizes[2];
g_minimum_splash_image_size = sizes[3];
g_ideal_monochrome_icon_size = sizes[4];
g_ideal_adaptive_launcher_icon_size = sizes[5];
g_ideal_shortcut_icon_size = sizes[6];
// Try to ensure that the data returned is sensible.
DCHECK_LE(g_minimum_homescreen_icon_size, g_ideal_homescreen_icon_size);
DCHECK_LE(g_minimum_splash_image_size, g_ideal_splash_image_size);
}
} // anonymous namespace
int WebappsIconUtils::GetIdealHomescreenIconSizeInPx() {
if (g_ideal_homescreen_icon_size == -1)
GetIconSizes();
return g_ideal_homescreen_icon_size;
}
int WebappsIconUtils::GetMinimumHomescreenIconSizeInPx() {
if (g_minimum_homescreen_icon_size == -1)
GetIconSizes();
return g_minimum_homescreen_icon_size;
}
int WebappsIconUtils::GetIdealSplashImageSizeInPx() {
if (g_ideal_splash_image_size == -1)
GetIconSizes();
return g_ideal_splash_image_size;
}
int WebappsIconUtils::GetMinimumSplashImageSizeInPx() {
if (g_minimum_splash_image_size == -1)
GetIconSizes();
return g_minimum_splash_image_size;
}
int WebappsIconUtils::GetIdealAdaptiveLauncherIconSizeInPx() {
if (g_ideal_adaptive_launcher_icon_size == -1)
GetIconSizes();
return g_ideal_adaptive_launcher_icon_size;
}
int WebappsIconUtils::GetIdealShortcutIconSizeInPx() {
if (g_ideal_shortcut_icon_size == -1)
GetIconSizes();
return g_ideal_shortcut_icon_size;
}
bool WebappsIconUtils::DoesAndroidSupportMaskableIcons() {
return base::android::BuildInfo::GetInstance()->sdk_int() >=
base::android::SDK_VERSION_OREO;
}
SkBitmap WebappsIconUtils::FinalizeLauncherIconInBackground(
const SkBitmap& bitmap,
bool is_icon_maskable,
const GURL& url,
bool* is_generated) {
base::AssertLongCPUWorkAllowed();
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jobject> result;
*is_generated = false;
if (!bitmap.isNull()) {
if (Java_WebappsIconUtils_isIconLargeEnoughForLauncher(env, bitmap.width(),
bitmap.height())) {
ScopedJavaLocalRef<jobject> java_bitmap =
gfx::ConvertToJavaBitmap(bitmap);
result = Java_WebappsIconUtils_createHomeScreenIconFromWebIcon(
base::android::AttachCurrentThread(), java_bitmap, is_icon_maskable);
}
}
if (result.is_null()) {
ScopedJavaLocalRef<jobject> java_url =
url::GURLAndroid::FromNativeGURL(env, url);
SkColor mean_color = SkColorSetRGB(0x91, 0x91, 0x91);
if (!bitmap.isNull())
mean_color = color_utils::CalculateKMeanColorOfBitmap(bitmap);
*is_generated = true;
result = Java_WebappsIconUtils_generateHomeScreenIcon(
env, java_url, SkColorGetR(mean_color), SkColorGetG(mean_color),
SkColorGetB(mean_color));
}
return result.obj()
? gfx::CreateSkBitmapFromJavaBitmap(gfx::JavaBitmap(result))
: SkBitmap();
}
SkBitmap WebappsIconUtils::GenerateAdaptiveIconBitmap(const SkBitmap& bitmap) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jobject> result;
if (!bitmap.isNull()) {
ScopedJavaLocalRef<jobject> java_bitmap = gfx::ConvertToJavaBitmap(bitmap);
result = Java_WebappsIconUtils_generateAdaptiveIconBitmap(env, java_bitmap);
}
return result.obj()
? gfx::CreateSkBitmapFromJavaBitmap(gfx::JavaBitmap(result))
: SkBitmap();
}
int WebappsIconUtils::GetIdealIconCornerRadiusPxForPromptUI() {
return Java_WebappsIconUtils_getIdealIconCornerRadiusPxForPromptUI(
base::android::AttachCurrentThread());
}
void WebappsIconUtils::SetIdealShortcutSizeForTesting(int size) {
g_ideal_shortcut_icon_size = size;
}
} // namespace webapps
| bsd-3-clause |
mou4e/zirconium | android_webview/browser/child_frame.cc | 881 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/browser/child_frame.h"
#include "cc/output/compositor_frame.h"
namespace android_webview {
ChildFrame::ChildFrame(scoped_ptr<cc::CompositorFrame> frame,
const gfx::Rect& viewport_rect_for_tile_priority,
const gfx::Transform& transform_for_tile_priority,
bool offscreen_pre_raster,
bool is_layer)
: frame(frame.Pass()),
viewport_rect_for_tile_priority(viewport_rect_for_tile_priority),
transform_for_tile_priority(transform_for_tile_priority),
offscreen_pre_raster(offscreen_pre_raster),
is_layer(is_layer) {
}
ChildFrame::~ChildFrame() {
}
} // namespace webview
| bsd-3-clause |
dandanwei/spree | frontend/spec/features/coupon_code_spec.rb | 3383 | require 'spec_helper'
describe "Coupon code promotions", type: :feature, js: true do
let!(:country) { create(:country, name: "United States of America", states_required: true) }
let!(:state) { create(:state, name: "Alabama", country: country) }
let!(:zone) { create(:zone) }
let!(:shipping_method) { create(:shipping_method) }
let!(:payment_method) { create(:check_payment_method) }
let!(:product) { create(:product, name: "RoR Mug", price: 20) }
context "visitor makes checkout as guest without registration" do
def create_basic_coupon_promotion(code)
promotion = Spree::Promotion.create!(name: code.titleize,
code: code,
starts_at: 1.day.ago,
expires_at: 1.day.from_now)
calculator = Spree::Calculator::FlatRate.new
calculator.preferred_amount = 10
action = Spree::Promotion::Actions::CreateItemAdjustments.new
action.calculator = calculator
action.promotion = promotion
action.save
promotion.reload # so that promotion.actions is available
end
let!(:promotion) { create_basic_coupon_promotion("onetwo") }
# OrdersController
context "on the payment page" do
before do
visit spree.root_path
click_link "RoR Mug"
click_button "add-to-cart-button"
click_button "Checkout"
fill_in "order_email", with: "[email protected]"
fill_in "First Name", with: "John"
fill_in "Last Name", with: "Smith"
fill_in "Street Address", with: "1 John Street"
fill_in "City", with: "City of John"
fill_in "Zip", with: "01337"
select country.name, from: "Country"
select state.name, from: "order[bill_address_attributes][state_id]"
fill_in "Phone", with: "555-555-5555"
# To shipping method screen
click_button "Save and Continue"
# To payment screen
click_button "Save and Continue"
end
it "informs about an invalid coupon code" do
fill_in "order_coupon_code", with: "coupon_codes_rule_man"
click_button "Save and Continue"
expect(page).to have_content(Spree.t(:coupon_code_not_found))
end
it "informs the user about a coupon code which has exceeded its usage" do
promotion.update_column(:usage_limit, 5)
allow_any_instance_of(promotion.class).to receive_messages(credits_count: 10)
fill_in "order_coupon_code", with: "onetwo"
click_button "Save and Continue"
expect(page).to have_content(Spree.t(:coupon_code_max_usage))
end
it "can enter an invalid coupon code, then a real one" do
fill_in "order_coupon_code", with: "coupon_codes_rule_man"
click_button "Save and Continue"
expect(page).to have_content(Spree.t(:coupon_code_not_found))
fill_in "order_coupon_code", with: "onetwo"
click_button "Save and Continue"
expect(page).to have_content("Promotion (Onetwo) -$10.00")
end
context "with a promotion" do
it "applies a promotion to an order" do
fill_in "order_coupon_code", with: "onetwo"
click_button "Save and Continue"
expect(page).to have_content("Promotion (Onetwo) -$10.00")
end
end
end
end
end
| bsd-3-clause |
danakj/chromium | components/test/data/autofill/automated_integration/action_recorder_extension/content/action_handler.js | 13663 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
const LEFT_BUTTON = 0;
const RIGHT_BUTTON = 2;
/**
* Create an editing timer that will execute a command if the timer is not
* triggered within a given timeout interval.
*/
class EditingTimer {
/**
* @constructor
* @param {Element} element Target editable element
* @param {Function} callback Function to call if the timeout occurs
* @param {Number} interval Timeout interval in ms
*/
constructor(element, callback, interval) {
this._element = element;
this._timer = 0;
this._callback = callback;
this._interval = interval;
this._mouseOutListener = () => { this.cancel(true); };
this._addMouseOutListener();
this._element.addEventListener('keyup', (event) => {
this.trigger();
this._addMouseOutListener();
});
}
/**
* Start/postpone the timeout
*/
trigger() {
this._removeMouseOutListener();
clearTimeout(this._timer);
this._timer = setTimeout(this._callback, this._interval);
}
/**
* Cancel the timeout immediately and optionally fire the callback.
* @param {Boolean*} executeCallback Callback will be executed if truthy
*/
cancel(executeCallback) {
this._removeMouseOutListener();
clearTimeout(this._timer);
if (executeCallback) {
this._callback();
}
}
_addMouseOutListener() {
this._element.addEventListener('mouseout', this._mouseOutListener);
}
_removeMouseOutListener() {
this._element.removeEventListener('mouseout', this._mouseOutListener);
}
}
class ActionHandler {
constructor() { this._startListeners(); }
/**
* Returns true if |element| is probably a clickable element.
*
* @param {Element} element The element to be checked
* @return {boolean} True if the element is probably clickable
*/
_isClickableElementOrInput(element) {
return (
element.tagName == 'INPUT' || element.tagName == 'A' ||
element.tagName == 'BUTTON' || element.tagName == 'SUBMIT' ||
element.getAttribute('href'));
}
/**
* Returns |element|, if |element| is clickable element. Otherwise, returns
* clickable children or parent of the given element |element|.
* Font element might consume a user click, but ChromeDriver will be unable to
* click on the font element, so find an actually clickable element to target.
*
* @param {Element} element The element where a clickable tag should be find.
* @return {Element} The clicable element.
*/
_fixElementSelection(element) {
if (this._isClickableElementOrInput(element)) {
return element;
}
const clickableChildren = element.querySelectorAll(
':scope input, :scope a, :scope button, :scope submit, :scope [href]');
// If any of the children are clickable, use them.
if (clickableChildren.length > 0) {
return clickableChildren[0];
}
// Check if any of the parent elements (within 5) are clickable.
let parent = element;
for (let i = 0; i < 5; i++) {
parent = parent.parentElement;
if (!parent) {
break;
}
if (this._isClickableElementOrInput(parent)) {
return parent;
}
}
return element;
}
/**
* Send the message object to the appropriate parent.
*
* If this is not the root frame in the tab then the message will be sent to
* the direct parent frame. However, if this is the root frame, the message
* is sent to the background script.
*
* @param {Object} object Message payload
*/
_sendMessageToParent(object) {
if (this._frameId === 0) {
chrome.runtime.sendMessage(object);
} else {
if (object) {
object.url = document.location.href;
}
chrome.runtime.sendMessage({
type: 'forward-message-to-tab',
args: [this._tabId, object, {frameId: this._parentFrameId}]
});
}
}
/**
* Construct action an object.
*
* @param {String} type Action type code (ex. 'type', 'left-click')
* @param {String} selector XPath reference to the element within the current
* frame
* @param {...*} ...args Remaining args that're to be applied to the
* action's constructor
*/
_createAction(type, selector, ...args) {
return {type: type, selector: selector, args: args};
}
_registerTypeAction(element) {
const selector = xPathTools.xPath(element, true);
const value = element.value;
this._log(`Typing detected on: ${selector} with '${value}'`);
this._sendMessageToParent(
{type: 'action', data: this._createAction('type', selector, value)});
}
_registerSelectAction(event) {
const element = event.target;
const selector = xPathTools.xPath(element, true);
this._log('Select detected on:', selector);
this._sendMessageToParent({
type: 'action',
data: this._createAction('select', selector, element.value)
});
}
/**
* Register the child frame's action by switching context to and from that of
* the frame and sending it to the parent of this frame.
*
* @param {Object} action Action data object to wrap with context switching
* @param {String} url URL of child iframe (used to select element)
*/
_registerChildAction(action, url) {
this._registerChildActions([action], url);
}
/**
* Register the child frame's actions by switching context to and from that of
* the frame and sending it to the parent of this frame.
*
* @param {Array} actions Array of action data objects to wrap with context
* switching
* @param {String} url URL of child iframe (used to select element)
*/
_registerChildActions(actions, url) {
const element = document.querySelector(`iframe[src="${url}"]`);
if (element === null) {
return console.error(
`[Frame: ${this._frameId}] Unable to find iframe for child actions:`,
url);
}
const selector = xPathTools.xPath(element, true);
actions.unshift(this._createAction('set-context', selector));
actions.push(
this._createAction('set-context', 'None', undefined, selector));
this._sendMessageToParent({type: 'actions', data: actions});
}
/**
* Create a listener for a given editable element.
*
* If the element is a text input field then typing events will be generated
* after 1000ms of inactivity (once typing has commenced), or if the mouse
* leaves the field.
*
* @param {Element} element Target DOM Element
*/
_addEditableElementListener(element) {
switch (element.localName) {
case 'input':
case 'textarea':
switch (element.getAttribute('type')) {
case 'radio':
case 'submit':
break;
default:
const editTimer = new EditingTimer(
element, () => { this._registerTypeAction(element); }, 1000);
}
break;
case 'select':
element.addEventListener(
'change', (event) => { this._registerSelectAction(event); });
break;
}
}
/**
* Create a mutation observer that watches for elements that are added
* post-DOMContentLoaded by the site's custom js.
*
* This will attach change listeners on all new editable elements.
*
* Note: You must also attach listeners to existing elements.
*/
_setupMutationObserver() {
this._mutationObserver = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(newNode => {
if (newNode.nodeType === Node.ELEMENT_NODE) {
this._addEditableElementListener(newNode);
}
});
});
});
this._mutationObserver.observe(document, {childList: true});
}
/**
* Retrieves data about this tab & frame from the background script.
* @param {Function} cb Called once the data has been retrieved
*/
_setupChildMessageHandler(cb) {
chrome.runtime.sendMessage({type: 'get-frame-info'}, (response) => {
this._tabId = response.tabId;
this._frameId = response.frameId;
this._parentFrameId = response.parentFrameId;
this._log(`Parent frame id is ${this._parentFrameId}`);
cb();
});
}
/**
* Setup all the event & message listeners that're required to detect and
* report actions.
*/
_startListeners() {
this._setupChildMessageHandler(() => {
this._setupMutationObserver();
const editableElements =
document.querySelectorAll('input,textarea,select');
editableElements.forEach(
(element) => { this._addEditableElementListener(element); });
/**
* Listen for messages from the background script
*/
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (!request) {
console.error('Invalid request from background script.', request);
return;
}
let element = null;
switch (request.type) {
case 'fill-element':
if (!request.selector) {
return console.error(
'Unable to fill element, invalid request selector', request);
}
this._log('Filling element', request.selector);
element = this._getElementByXPath(request.selector);
if (element === null) {
return console.error('Unable to fill element, not found');
}
this._log(`Filling element with '${request.content}'`);
element.value = request.content;
this._registerTypeAction(element);
break;
case 'fill-email':
if (!request.selector) {
return console.error(
'Unable to fill element, invalid request selector', request);
}
this._log('Filling element', request.selector);
element = this._getElementByXPath(request.selector);
if (element === null) {
return console.error('Unable to fill element, not found');
}
this._log('Filling element with random email');
element.value = this._generateEmail();
this._sendMessageToParent({
type: 'action',
data: this._createAction('fill-email', request.selector)
});
break;
case 'fill-password':
if (!request.selector) {
return console.error(
'Unable to fill element, invalid request selector', request);
}
this._log('Filling element', request.selector);
element = this._getElementByXPath(request.selector);
if (element === null) {
return console.error('Unable to fill element, not found');
}
this._log('Filling element with random password');
element.value = this._generatePassword();
this._sendMessageToParent({
type: 'action',
data: this._createAction('fill-password', request.selector)
});
break;
case 'action':
// Handle a child frame's action
this._log('Child frame action received:', request.data);
this._registerChildAction(request.data, request.url);
break;
case 'actions':
// Handle a child frame's actions
this._log('Child frame actions received:', request.data);
this._registerChildActions(request.data, request.url);
break;
default:
console.error(`Unknown request type: ${request.type}`);
}
});
/**
* Click event listener
*/
document.addEventListener('mousedown', (event) => {
const element = this._fixElementSelection(event.target);
const selector = xPathTools.xPath(element, true);
let type;
switch (event.button) {
case LEFT_BUTTON:
this._log(`Left-click detected on: ${selector}`);
type = 'left-click';
this._sendMessageToParent(
{type: 'action', data: this._createAction(type, selector)});
break;
case RIGHT_BUTTON:
this._log(`Right-click detected on: ${selector}`);
type = 'right-click';
chrome.runtime.sendMessage(
{type: 'action', data: this._createAction(type, selector)});
break;
default:
return console.error(
'Unknown button used for mousedown:', event.button);
}
}, true);
});
}
_getElementByXPath(xpath) {
return document
.evaluate(
xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
.singleNodeValue;
}
_generateString(length) {
length = length || 8;
const lowerCaseChars = 'abcdefghijklmnopqrstuvwxyz';
let result = '';
for (let i = 0; i < length; i++) {
let charIndex = Math.floor(Math.random() * lowerCaseChars.length);
result += lowerCaseChars[charIndex];
}
return result;
}
_generateEmail() {
return `${this._generateString()}@${this._generateString()}.co.uk`;
}
_generatePassword() { return `${this._generateString()}!234&`; }
_log(message, ...args) {
console.log(`[Frame: ${this._frameId}] ${message}`, ...args);
}
}
const actionHandler = new ActionHandler();
| bsd-3-clause |
pozdnyakov/chromium-crosswalk | chrome/browser/sync/sync_ui_util_unittest.cc | 16605 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <set>
#include "base/basictypes.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/fake_auth_status_provider.h"
#include "chrome/browser/signin/fake_signin_manager.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/sync/profile_sync_service_mock.h"
#include "chrome/browser/sync/sync_ui_util.h"
#include "content/public/test/test_browser_thread.h"
#include "grit/generated_resources.h"
#include "testing/gmock/include/gmock/gmock-actions.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
using ::testing::AtMost;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::SetArgPointee;
using ::testing::_;
using content::BrowserThread;
// A number of distinct states of the ProfileSyncService can be generated for
// tests.
enum DistinctState {
STATUS_CASE_SETUP_IN_PROGRESS,
STATUS_CASE_SETUP_ERROR,
STATUS_CASE_AUTHENTICATING,
STATUS_CASE_AUTH_ERROR,
STATUS_CASE_PROTOCOL_ERROR,
STATUS_CASE_PASSPHRASE_ERROR,
STATUS_CASE_SYNCED,
STATUS_CASE_SYNC_DISABLED_BY_POLICY,
NUMBER_OF_STATUS_CASES
};
namespace {
// Utility function to test that GetStatusLabelsForSyncGlobalError returns
// the correct results for the given states.
void VerifySyncGlobalErrorResult(NiceMock<ProfileSyncServiceMock>* service,
const SigninManagerBase& signin,
GoogleServiceAuthError::State error_state,
bool is_signed_in,
bool is_error) {
EXPECT_CALL(*service, HasSyncSetupCompleted())
.WillRepeatedly(Return(is_signed_in));
GoogleServiceAuthError auth_error(error_state);
EXPECT_CALL(*service, GetAuthError()).WillRepeatedly(ReturnRef(auth_error));
string16 label1, label2, label3;
sync_ui_util::GetStatusLabelsForSyncGlobalError(
service, signin, &label1, &label2, &label3);
EXPECT_EQ(label1.empty(), !is_error);
EXPECT_EQ(label2.empty(), !is_error);
EXPECT_EQ(label3.empty(), !is_error);
}
} // namespace
// Test that GetStatusLabelsForSyncGlobalError returns an error if a
// passphrase is required.
TEST(SyncUIUtilTest, PassphraseGlobalError) {
base::MessageLoopForUI message_loop;
content::TestBrowserThread ui_thread(BrowserThread::UI, &message_loop);
scoped_ptr<Profile> profile(
ProfileSyncServiceMock::MakeSignedInTestingProfile());
NiceMock<ProfileSyncServiceMock> service(profile.get());
FakeSigninManagerBase signin;
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(Return(false));
EXPECT_CALL(service, IsPassphraseRequired())
.WillRepeatedly(Return(true));
EXPECT_CALL(service, IsPassphraseRequiredForDecryption())
.WillRepeatedly(Return(true));
VerifySyncGlobalErrorResult(
&service, signin, GoogleServiceAuthError::NONE, true, true);
}
// Test that GetStatusLabelsForSyncGlobalError returns an error if a
// passphrase is required and not for auth errors.
TEST(SyncUIUtilTest, AuthAndPassphraseGlobalError) {
base::MessageLoopForUI message_loop;
content::TestBrowserThread ui_thread(BrowserThread::UI, &message_loop);
scoped_ptr<Profile> profile(
ProfileSyncServiceMock::MakeSignedInTestingProfile());
NiceMock<ProfileSyncServiceMock> service(profile.get());
FakeSigninManagerBase signin;
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(Return(false));
EXPECT_CALL(service, IsPassphraseRequired())
.WillRepeatedly(Return(true));
EXPECT_CALL(service, IsPassphraseRequiredForDecryption())
.WillRepeatedly(Return(true));
EXPECT_CALL(service, HasSyncSetupCompleted())
.WillRepeatedly(Return(true));
GoogleServiceAuthError auth_error(
GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
EXPECT_CALL(service, GetAuthError()).WillRepeatedly(ReturnRef(auth_error));
string16 menu_label, label2, label3;
sync_ui_util::GetStatusLabelsForSyncGlobalError(
&service, signin, &menu_label, &label2, &label3);
// Make sure we are still displaying the passphrase error badge (don't show
// auth errors through SyncUIUtil).
EXPECT_EQ(menu_label, l10n_util::GetStringUTF16(
IDS_SYNC_PASSPHRASE_ERROR_WRENCH_MENU_ITEM));
}
// Test that GetStatusLabelsForSyncGlobalError does not indicate errors for
// auth errors (these are reported through SigninGlobalError).
TEST(SyncUIUtilTest, AuthStateGlobalError) {
base::MessageLoopForUI message_loop;
content::TestBrowserThread ui_thread(BrowserThread::UI, &message_loop);
scoped_ptr<Profile> profile(
ProfileSyncServiceMock::MakeSignedInTestingProfile());
NiceMock<ProfileSyncServiceMock> service(profile.get());
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(Return(false));
GoogleServiceAuthError::State table[] = {
GoogleServiceAuthError::NONE,
GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS,
GoogleServiceAuthError::USER_NOT_SIGNED_UP,
GoogleServiceAuthError::CONNECTION_FAILED,
GoogleServiceAuthError::CAPTCHA_REQUIRED,
GoogleServiceAuthError::ACCOUNT_DELETED,
GoogleServiceAuthError::ACCOUNT_DISABLED,
GoogleServiceAuthError::SERVICE_UNAVAILABLE,
GoogleServiceAuthError::TWO_FACTOR,
GoogleServiceAuthError::REQUEST_CANCELED,
GoogleServiceAuthError::HOSTED_NOT_ALLOWED
};
FakeSigninManagerBase signin;
for (size_t i = 0; i < arraysize(table); ++i) {
VerifySyncGlobalErrorResult(&service, signin, table[i], true, false);
VerifySyncGlobalErrorResult(&service, signin, table[i], false, false);
}
}
// TODO(tim): This shouldn't be required. r194857 removed the
// AuthInProgress override from FakeSigninManager, which meant this test started
// using the "real" SigninManager AuthInProgress logic. Without that override,
// it's no longer possible to test both chrome os + desktop flows as part of the
// same test, because AuthInProgress is always false on chrome os. Most of the
// tests are unaffected, but STATUS_CASE_AUTHENTICATING can't exist in both
// versions, so it we will require two separate tests, one using SigninManager
// and one using SigninManagerBase (which require different setup procedures.
class FakeSigninManagerForSyncUIUtilTest : public FakeSigninManagerBase {
public:
explicit FakeSigninManagerForSyncUIUtilTest(Profile* profile)
: auth_in_progress_(false) {
Initialize(profile, NULL);
}
virtual ~FakeSigninManagerForSyncUIUtilTest() {
}
virtual bool AuthInProgress() const OVERRIDE {
return auth_in_progress_;
}
void set_auth_in_progress() {
auth_in_progress_ = true;
}
private:
bool auth_in_progress_;
};
// Loads a ProfileSyncServiceMock to emulate one of a number of distinct cases
// in order to perform tests on the generated messages.
void GetDistinctCase(ProfileSyncServiceMock& service,
FakeSigninManagerForSyncUIUtilTest* signin,
FakeAuthStatusProvider* provider,
int caseNumber) {
// Auth Error object is returned by reference in mock and needs to stay in
// scope throughout test, so it is owned by calling method. However it is
// immutable so can only be allocated in this method.
switch (caseNumber) {
case STATUS_CASE_SETUP_IN_PROGRESS: {
EXPECT_CALL(service, HasSyncSetupCompleted())
.WillRepeatedly(Return(false));
EXPECT_CALL(service, FirstSetupInProgress())
.WillRepeatedly(Return(true));
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(status),
Return(false)));
return;
}
case STATUS_CASE_SETUP_ERROR: {
EXPECT_CALL(service, HasSyncSetupCompleted())
.WillRepeatedly(Return(false));
EXPECT_CALL(service, FirstSetupInProgress())
.WillRepeatedly(Return(false));
EXPECT_CALL(service, HasUnrecoverableError())
.WillRepeatedly(Return(true));
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(status),
Return(false)));
return;
}
case STATUS_CASE_AUTHENTICATING: {
EXPECT_CALL(service, HasSyncSetupCompleted())
.WillRepeatedly(Return(true));
EXPECT_CALL(service, sync_initialized()).WillRepeatedly(Return(true));
EXPECT_CALL(service, IsPassphraseRequired())
.WillRepeatedly(Return(false));
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(status),
Return(false)));
EXPECT_CALL(service, HasUnrecoverableError())
.WillRepeatedly(Return(false));
signin->set_auth_in_progress();
return;
}
case STATUS_CASE_AUTH_ERROR: {
EXPECT_CALL(service, HasSyncSetupCompleted())
.WillRepeatedly(Return(true));
EXPECT_CALL(service, sync_initialized()).WillRepeatedly(Return(true));
EXPECT_CALL(service, IsPassphraseRequired())
.WillRepeatedly(Return(false));
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(status),
Return(false)));
provider->SetAuthError(GoogleServiceAuthError(
GoogleServiceAuthError::SERVICE_UNAVAILABLE));
EXPECT_CALL(service, HasUnrecoverableError())
.WillRepeatedly(Return(false));
return;
}
case STATUS_CASE_PROTOCOL_ERROR: {
EXPECT_CALL(service, HasSyncSetupCompleted())
.WillRepeatedly(Return(true));
EXPECT_CALL(service, sync_initialized()).WillRepeatedly(Return(true));
EXPECT_CALL(service, IsPassphraseRequired())
.WillRepeatedly(Return(false));
syncer::SyncProtocolError protocolError;
protocolError.action = syncer::STOP_AND_RESTART_SYNC;
browser_sync::SyncBackendHost::Status status;
status.sync_protocol_error = protocolError;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(status),
Return(false)));
EXPECT_CALL(service, HasUnrecoverableError())
.WillRepeatedly(Return(false));
return;
}
case STATUS_CASE_PASSPHRASE_ERROR: {
EXPECT_CALL(service, HasSyncSetupCompleted())
.WillRepeatedly(Return(true));
EXPECT_CALL(service, sync_initialized()).WillRepeatedly(Return(true));
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(status),
Return(false)));
EXPECT_CALL(service, HasUnrecoverableError())
.WillRepeatedly(Return(false));
EXPECT_CALL(service, IsPassphraseRequired())
.WillRepeatedly(Return(true));
EXPECT_CALL(service, IsPassphraseRequiredForDecryption())
.WillRepeatedly(Return(true));
return;
}
case STATUS_CASE_SYNCED: {
EXPECT_CALL(service, HasSyncSetupCompleted())
.WillRepeatedly(Return(true));
EXPECT_CALL(service, sync_initialized()).WillRepeatedly(Return(true));
EXPECT_CALL(service, IsPassphraseRequired())
.WillRepeatedly(Return(false));
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(status),
Return(false)));
EXPECT_CALL(service, HasUnrecoverableError())
.WillRepeatedly(Return(false));
EXPECT_CALL(service, IsPassphraseRequired())
.WillRepeatedly(Return(false));
return;
}
case STATUS_CASE_SYNC_DISABLED_BY_POLICY: {
EXPECT_CALL(service, IsManaged()).WillRepeatedly(Return(true));
EXPECT_CALL(service, HasSyncSetupCompleted())
.WillRepeatedly(Return(false));
EXPECT_CALL(service, sync_initialized()).WillRepeatedly(Return(false));
EXPECT_CALL(service, IsPassphraseRequired())
.WillRepeatedly(Return(false));
browser_sync::SyncBackendHost::Status status;
EXPECT_CALL(service, QueryDetailedSyncStatus(_))
.WillRepeatedly(DoAll(SetArgPointee<0>(status),
Return(false)));
EXPECT_CALL(service, HasUnrecoverableError())
.WillRepeatedly(Return(false));
return;
}
default:
NOTREACHED();
}
}
// This test ensures that a each distinctive ProfileSyncService statuses
// will return a unique combination of status and link messages from
// GetStatusLabels().
TEST(SyncUIUtilTest, DistinctCasesReportUniqueMessageSets) {
std::set<string16> messages;
for (int idx = 0; idx != NUMBER_OF_STATUS_CASES; idx++) {
scoped_ptr<Profile> profile(new TestingProfile());
ProfileSyncServiceMock service(profile.get());
FakeSigninManagerForSyncUIUtilTest signin(profile.get());
signin.SetAuthenticatedUsername("[email protected]");
scoped_ptr<FakeAuthStatusProvider> provider(
new FakeAuthStatusProvider(signin.signin_global_error()));
GetDistinctCase(service, &signin, provider.get(), idx);
string16 status_label;
string16 link_label;
sync_ui_util::GetStatusLabels(&service,
signin,
sync_ui_util::WITH_HTML,
&status_label,
&link_label);
// If the status and link message combination is already present in the set
// of messages already seen, this is a duplicate rather than a unique
// message, and the test has failed.
EXPECT_FALSE(status_label.empty()) <<
"Empty status label returned for case #" << idx;
string16 combined_label =
status_label + string16(ASCIIToUTF16("#")) + link_label;
EXPECT_TRUE(messages.find(combined_label) == messages.end()) <<
"Duplicate message for case #" << idx << ": " << combined_label;
messages.insert(combined_label);
testing::Mock::VerifyAndClearExpectations(&service);
testing::Mock::VerifyAndClearExpectations(&signin);
provider.reset();
signin.Shutdown();
}
}
// This test ensures that the html_links parameter on GetStatusLabels() is
// honored.
TEST(SyncUIUtilTest, HtmlNotIncludedInStatusIfNotRequested) {
for (int idx = 0; idx != NUMBER_OF_STATUS_CASES; idx++) {
scoped_ptr<Profile> profile(
ProfileSyncServiceMock::MakeSignedInTestingProfile());
ProfileSyncServiceMock service(profile.get());
FakeSigninManagerForSyncUIUtilTest signin(profile.get());
signin.SetAuthenticatedUsername("[email protected]");
scoped_ptr<FakeAuthStatusProvider> provider(
new FakeAuthStatusProvider(signin.signin_global_error()));
GetDistinctCase(service, &signin, provider.get(), idx);
string16 status_label;
string16 link_label;
sync_ui_util::GetStatusLabels(&service,
signin,
sync_ui_util::PLAIN_TEXT,
&status_label,
&link_label);
// Ensures a search for string 'href' (found in links, not a string to be
// found in an English language message) fails when links are excluded from
// the status label.
EXPECT_FALSE(status_label.empty());
EXPECT_EQ(status_label.find(string16(ASCIIToUTF16("href"))),
string16::npos);
testing::Mock::VerifyAndClearExpectations(&service);
testing::Mock::VerifyAndClearExpectations(&signin);
provider.reset();
signin.Shutdown();
}
}
| bsd-3-clause |
blakeembrey/istanbul | test/instrumentation/test-es6-export.js | 738 | /*jslint nomen: true */
var helper = require('../helper'),
code,
verifier;
if (require('../es6').isExportAvailable()) {
module.exports = {
'should cover export statements': function (test) {
code = [
'export function bar() { return 2 }',
'output = bar()'
];
verifier = helper.verifier(__filename, code, {
esModules: true,
noAutoWrap: true
});
verifier.verify(test, [], 2, {
lines: {'1': 1, '2': 1},
branches: {},
functions: {'1': 1},
statements: {'1': 1, '2': 1, '3': 1}
});
test.done();
}
};
}
| bsd-3-clause |
XiaosongWei/chromium-crosswalk | mandoline/services/core_services/application_delegate_factory_default.cc | 488 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mandoline/services/core_services/application_delegate_factory.h"
#include "mojo/shell/public/cpp/application_delegate.h"
namespace core_services {
scoped_ptr<mojo::ApplicationDelegate> CreatePlatformSpecificApplicationDelegate(
const std::string& url) {
return nullptr;
}
} // namespace core_services
| bsd-3-clause |
sqlwang/DeviceManagementSystem | backend/webapp/ext/examples/classic/locale/multi-lang.js | 6092 | Ext.require([
'Ext.data.*',
'Ext.tip.QuickTipManager',
'Ext.form.*',
'Ext.grid.Panel'
]);
Ext.onReady(function(){
MultiLangDemo = (function() {
// get the selected language code parameter from url (if exists)
var params = Ext.urlDecode(window.location.search.substring(1));
//Ext.form.Field.prototype.msgTarget = 'side';
return {
init: function() {
Ext.tip.QuickTipManager.init();
/* Language chooser combobox */
var store = Ext.create('Ext.data.ArrayStore', {
fields: ['code', 'language'],
data : Ext.exampledata.languages // from languages.js
});
var combo = Ext.create('Ext.form.field.ComboBox', {
renderTo: 'languages',
store: store,
displayField:'language',
queryMode: 'local',
emptyText: 'Select a language...',
hideLabel: true,
listeners: {
select: function(cb, record) {
var search = location.search,
index = search.indexOf('&'),
params = Ext.urlEncode({'lang': record.get('code')});
location.search = (index === -1) ? params : params + search.substr(index);
}
}
});
var record, url;
if (params.lang) {
// check if there's really a language with that language code
record = store.findRecord('code', params.lang, null, null, null, true);
// if language was found in store assign it as current value in combobox
if (record) {
combo.setValue(record.data.language);
}
url = Ext.util.Format.format('../../../' + (Ext.devMode ? 'build/' : '') + 'classic/locale/locale-{0}.js', params.lang);
Ext.Loader.loadScript({
url: url,
onLoad: this.onSuccess,
onError: this.onFailure,
scope: this
}
);
} else {
this.setupDemo();
}
},
onSuccess: function() {
var me = this;
// Give the locale file onReady a chance to process
setTimeout(function() {
me.setupDemo();
}, 1);
},
onFailure: function() {
Ext.Msg.alert('Failure', 'Failed to load locale file.');
this.setupDemo();
},
setupDemo: function() {
// Grid needs to be this wide to handle the largest language case for the toolbar.
// In this case, it's Russian.
var width = 720;
/* Email field */
Ext.create('Ext.FormPanel', {
renderTo: 'emailfield',
labelWidth: 100, // label settings here cascade unless overridden
frame: true,
title: 'Email Field',
bodyPadding: '5 5 0',
width: width,
defaults: {
msgTarget: 'side',
width: width - 40
},
defaultType: 'textfield',
items: [{
fieldLabel: 'Email',
name: 'email',
vtype: 'email'
}]
});
/* Datepicker */
Ext.create('Ext.FormPanel', {
renderTo: 'datefield',
labelWidth: 100, // label settings here cascade unless overridden
frame: true,
title: 'Datepicker',
bodyPadding: '5 5 0',
width: width,
defaults: {
msgTarget: 'side',
width: width - 40
},
defaultType: 'datefield',
items: [{
fieldLabel: 'Date',
name: 'date'
}]
});
// shorthand alias
var monthArray = Ext.Array.map(Ext.Date.monthNames, function (e) { return [e]; });
var ds = Ext.create('Ext.data.Store', {
fields: ['month'],
remoteSort: true,
pageSize: 6,
proxy: {
type: 'memory',
enablePaging: true,
data: monthArray,
reader: {
type: 'array'
}
}
});
Ext.create('Ext.grid.Panel', {
renderTo: 'grid',
width: width,
height: 330,
title:'Month Browser',
columns:[{
text: 'Month of the year',
dataIndex: 'month',
width: 240
}],
store: ds,
bbar: Ext.create('Ext.toolbar.Paging', {
pageSize: 6,
store: ds,
displayInfo: true
})
});
// trigger the data store load
ds.load();
}
};
})();
MultiLangDemo.init();
});
| bsd-3-clause |
joone/chromium-crosswalk | third_party/WebKit/Source/modules/app_banner/AppBannerController.cpp | 1442 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "modules/app_banner/AppBannerController.h"
#include "core/EventTypeNames.h"
#include "core/dom/Document.h"
#include "core/frame/DOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "modules/app_banner/BeforeInstallPromptEvent.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "public/platform/WebVector.h"
#include "public/platform/modules/app_banner/WebAppBannerClient.h"
#include "public/platform/modules/app_banner/WebAppBannerPromptReply.h"
namespace blink {
// static
void AppBannerController::willShowInstallBannerPrompt(int requestId, WebAppBannerClient* client, LocalFrame* frame, const WebVector<WebString>& platforms, WebAppBannerPromptReply* reply)
{
ASSERT(RuntimeEnabledFeatures::appBannerEnabled());
Vector<String> wtfPlatforms;
for (const WebString& platform : platforms)
wtfPlatforms.append(platform);
// dispatchEvent() returns whether the default behavior can happen. In other
// words, it returns false if preventDefault() was called.
*reply = frame->domWindow()->dispatchEvent(BeforeInstallPromptEvent::create(EventTypeNames::beforeinstallprompt, frame->document(), wtfPlatforms, requestId, client))
? WebAppBannerPromptReply::None : WebAppBannerPromptReply::Cancel;
}
} // namespace blink
| bsd-3-clause |
jason-p-pickering/dhis2-persian-calendar | dhis-2/dhis-web/dhis-web-light/src/main/java/org/hisp/dhis/light/interpretation/action/PostInterpretation.java | 3760 | package org.hisp.dhis.light.interpretation.action;
/*
* Copyright (c) 2004-2017, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.hisp.dhis.chart.Chart;
import org.hisp.dhis.chart.ChartService;
import org.hisp.dhis.interpretation.Interpretation;
import org.hisp.dhis.interpretation.InterpretationService;
import org.hisp.dhis.user.CurrentUserService;
import com.opensymphony.xwork2.Action;
public class PostInterpretation
implements Action
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private InterpretationService interpretationService;
public void setInterpretationService( InterpretationService interpretationService )
{
this.interpretationService = interpretationService;
}
private CurrentUserService currentUserService;
public void setCurrentUserService( CurrentUserService currentUserService )
{
this.currentUserService = currentUserService;
}
private ChartService chartService;
public void setChartService( ChartService chartService )
{
this.chartService = chartService;
}
// -------------------------------------------------------------------------
// Input & Output
// -------------------------------------------------------------------------
private int id;
public void setId( int id )
{
this.id = id;
}
private String interpretation;
public void setInterpretation( String interpretation )
{
this.interpretation = interpretation;
}
// -------------------------------------------------------------------------
// Action Implementation
// -------------------------------------------------------------------------
@Override
public String execute()
throws Exception
{
Chart c = chartService.getChart( id );
Interpretation i = new Interpretation( c, null, interpretation );
i.setUser( currentUserService.getCurrentUser() );
interpretationService.saveInterpretation( i );
return SUCCESS;
}
}
| bsd-3-clause |
bartbresse/MGMT | app/library/Google/Service/YouTube.php | 303145 | <?php
/*
* Copyright 2010 Google Inc.
*
* 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.
*/
/**
* Service definition for YouTube (v3).
*
* <p>
* Programmatic access to YouTube features.
* </p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/youtube/v3" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_YouTube extends Google_Service
{
/** Manage your YouTube account. */
const YOUTUBE = "https://www.googleapis.com/auth/youtube";
/** View your YouTube account. */
const YOUTUBE_READONLY = "https://www.googleapis.com/auth/youtube.readonly";
/** Manage your YouTube videos. */
const YOUTUBE_UPLOAD = "https://www.googleapis.com/auth/youtube.upload";
/** View and manage your assets and associated content on YouTube. */
const YOUTUBEPARTNER = "https://www.googleapis.com/auth/youtubepartner";
/** View private information of your YouTube channel relevant during the audit process with a YouTube partner. */
const YOUTUBEPARTNER_CHANNEL_AUDIT = "https://www.googleapis.com/auth/youtubepartner-channel-audit";
public $activities;
public $channelBanners;
public $channelSections;
public $channels;
public $guideCategories;
public $i18nLanguages;
public $i18nRegions;
public $liveBroadcasts;
public $liveStreams;
public $playlistItems;
public $playlists;
public $search;
public $subscriptions;
public $thumbnails;
public $videoCategories;
public $videos;
public $watermarks;
/**
* Constructs the internal representation of the YouTube service.
*
* @param Google_Client $client
*/
public function __construct(Google_Client $client)
{
parent::__construct($client);
$this->servicePath = 'youtube/v3/';
$this->version = 'v3';
$this->serviceName = 'youtube';
$this->activities = new Google_Service_YouTube_Activities_Resource(
$this,
$this->serviceName,
'activities',
array(
'methods' => array(
'insert' => array(
'path' => 'activities',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'activities',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'publishedBefore' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'home' => array(
'location' => 'query',
'type' => 'boolean',
),
'publishedAfter' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->channelBanners = new Google_Service_YouTube_ChannelBanners_Resource(
$this,
$this->serviceName,
'channelBanners',
array(
'methods' => array(
'insert' => array(
'path' => 'channelBanners/insert',
'httpMethod' => 'POST',
'parameters' => array(
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->channelSections = new Google_Service_YouTube_ChannelSections_Resource(
$this,
$this->serviceName,
'channelSections',
array(
'methods' => array(
'delete' => array(
'path' => 'channelSections',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'channelSections',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'channelSections',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'channelSections',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
$this->channels = new Google_Service_YouTube_Channels_Resource(
$this,
$this->serviceName,
'channels',
array(
'methods' => array(
'list' => array(
'path' => 'channels',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'managedByMe' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'forUsername' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'mySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
'categoryId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'channels',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->guideCategories = new Google_Service_YouTube_GuideCategories_Resource(
$this,
$this->serviceName,
'guideCategories',
array(
'methods' => array(
'list' => array(
'path' => 'guideCategories',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->i18nLanguages = new Google_Service_YouTube_I18nLanguages_Resource(
$this,
$this->serviceName,
'i18nLanguages',
array(
'methods' => array(
'list' => array(
'path' => 'i18nLanguages',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->i18nRegions = new Google_Service_YouTube_I18nRegions_Resource(
$this,
$this->serviceName,
'i18nRegions',
array(
'methods' => array(
'list' => array(
'path' => 'i18nRegions',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveBroadcasts = new Google_Service_YouTube_LiveBroadcasts_Resource(
$this,
$this->serviceName,
'liveBroadcasts',
array(
'methods' => array(
'bind' => array(
'path' => 'liveBroadcasts/bind',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'streamId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'control' => array(
'path' => 'liveBroadcasts/control',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'displaySlate' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'offsetTimeMs' => array(
'location' => 'query',
'type' => 'string',
),
'walltime' => array(
'location' => 'query',
'type' => 'string',
),
),
),'delete' => array(
'path' => 'liveBroadcasts',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'liveBroadcasts',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'liveBroadcasts',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'broadcastStatus' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
),
),'transition' => array(
'path' => 'liveBroadcasts/transition',
'httpMethod' => 'POST',
'parameters' => array(
'broadcastStatus' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'liveBroadcasts',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveStreams = new Google_Service_YouTube_LiveStreams_Resource(
$this,
$this->serviceName,
'liveStreams',
array(
'methods' => array(
'delete' => array(
'path' => 'liveStreams',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'liveStreams',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'liveStreams',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'liveStreams',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->playlistItems = new Google_Service_YouTube_PlaylistItems_Resource(
$this,
$this->serviceName,
'playlistItems',
array(
'methods' => array(
'delete' => array(
'path' => 'playlistItems',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'playlistItems',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'playlistItems',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'playlistId' => array(
'location' => 'query',
'type' => 'string',
),
'videoId' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'playlistItems',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
$this->playlists = new Google_Service_YouTube_Playlists_Resource(
$this,
$this->serviceName,
'playlists',
array(
'methods' => array(
'delete' => array(
'path' => 'playlists',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'playlists',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'playlists',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'playlists',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->search = new Google_Service_YouTube_Search_Resource(
$this,
$this->serviceName,
'search',
array(
'methods' => array(
'list' => array(
'path' => 'search',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'eventType' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'videoSyndicated' => array(
'location' => 'query',
'type' => 'string',
),
'channelType' => array(
'location' => 'query',
'type' => 'string',
),
'videoCaption' => array(
'location' => 'query',
'type' => 'string',
),
'publishedAfter' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'forContentOwner' => array(
'location' => 'query',
'type' => 'boolean',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'location' => array(
'location' => 'query',
'type' => 'string',
),
'locationRadius' => array(
'location' => 'query',
'type' => 'string',
),
'videoType' => array(
'location' => 'query',
'type' => 'string',
),
'type' => array(
'location' => 'query',
'type' => 'string',
),
'topicId' => array(
'location' => 'query',
'type' => 'string',
),
'publishedBefore' => array(
'location' => 'query',
'type' => 'string',
),
'videoDimension' => array(
'location' => 'query',
'type' => 'string',
),
'videoLicense' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'relatedToVideoId' => array(
'location' => 'query',
'type' => 'string',
),
'videoDefinition' => array(
'location' => 'query',
'type' => 'string',
),
'videoDuration' => array(
'location' => 'query',
'type' => 'string',
),
'forMine' => array(
'location' => 'query',
'type' => 'boolean',
),
'q' => array(
'location' => 'query',
'type' => 'string',
),
'safeSearch' => array(
'location' => 'query',
'type' => 'string',
),
'videoEmbeddable' => array(
'location' => 'query',
'type' => 'string',
),
'videoCategoryId' => array(
'location' => 'query',
'type' => 'string',
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->subscriptions = new Google_Service_YouTube_Subscriptions_Resource(
$this,
$this->serviceName,
'subscriptions',
array(
'methods' => array(
'delete' => array(
'path' => 'subscriptions',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'subscriptions',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'subscriptions',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'forChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'mySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->thumbnails = new Google_Service_YouTube_Thumbnails_Resource(
$this,
$this->serviceName,
'thumbnails',
array(
'methods' => array(
'set' => array(
'path' => 'thumbnails/set',
'httpMethod' => 'POST',
'parameters' => array(
'videoId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videoCategories = new Google_Service_YouTube_VideoCategories_Resource(
$this,
$this->serviceName,
'videoCategories',
array(
'methods' => array(
'list' => array(
'path' => 'videoCategories',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videos = new Google_Service_YouTube_Videos_Resource(
$this,
$this->serviceName,
'videos',
array(
'methods' => array(
'delete' => array(
'path' => 'videos',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'getRating' => array(
'path' => 'videos/getRating',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'videos',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'stabilize' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'notifySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
'autoLevels' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'videos',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'locale' => array(
'location' => 'query',
'type' => 'string',
),
'videoCategoryId' => array(
'location' => 'query',
'type' => 'string',
),
'chart' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'myRating' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
),
),
),'rate' => array(
'path' => 'videos/rate',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'rating' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'videos',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->watermarks = new Google_Service_YouTube_Watermarks_Resource(
$this,
$this->serviceName,
'watermarks',
array(
'methods' => array(
'set' => array(
'path' => 'watermarks/set',
'httpMethod' => 'POST',
'parameters' => array(
'channelId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'unset' => array(
'path' => 'watermarks/unset',
'httpMethod' => 'POST',
'parameters' => array(
'channelId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
}
}
/**
* The "activities" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $activities = $youtubeService->activities;
* </code>
*/
class Google_Service_YouTube_Activities_Resource extends Google_Service_Resource
{
/**
* Posts a bulletin for a specific channel. (The user submitting the request
* must be authorized to act on the channel's behalf.)
*
* Note: Even though an activity resource can contain information about actions
* like a user rating a video or marking a video as a favorite, you need to use
* other API methods to generate those activity resources. For example, you
* would use the API's videos.rate() method to rate a video and the
* playlistItems.insert() method to mark a video as a favorite.
* (activities.insert)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet and contentDetails.
* @param Google_Activity $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_YouTube_Activity
*/
public function insert($part, Google_Service_YouTube_Activity $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_YouTube_Activity");
}
/**
* Returns a list of channel activity events that match the request criteria.
* For example, you can retrieve events associated with a particular channel,
* events associated with the user's subscriptions and Google+ friends, or the
* YouTube home page feed, which is customized for each user.
* (activities.listActivities)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more activity resource properties
* that the API response will include. The part names that you can include in the parameter value
* are id, snippet, and contentDetails.
If the parameter identifies a property that contains child
* properties, the child properties will be included in the response. For example, in a activity
* resource, the snippet property contains other properties that identify the type of activity, a
* display title for the activity, and so forth. If you set part=snippet, the API response will
* also contain all of those nested properties.
* @param array $optParams Optional parameters.
*
* @opt_param string regionCode
* The regionCode parameter instructs the API to return results for the specified country. The
* parameter value is an ISO 3166-1 alpha-2 country code. YouTube uses this value when the
* authorized user's previous activity on YouTube does not provide enough information to generate
* the activity feed.
* @opt_param string publishedBefore
* The publishedBefore parameter specifies the date and time before which an activity must have
* occurred for that activity to be included in the API response. If the parameter value specifies
* a day, but not a time, then any activities that occurred that day will be excluded from the
* result set. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
* @opt_param string channelId
* The channelId parameter specifies a unique YouTube channel ID. The API will then return a list
* of that channel's activities.
* @opt_param bool mine
* Set this parameter's value to true to retrieve a feed of the authenticated user's activities.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
* @opt_param bool home
* Set this parameter's value to true to retrieve the activity feed that displays on the YouTube
* home page for the currently authenticated user.
* @opt_param string publishedAfter
* The publishedAfter parameter specifies the earliest date and time that an activity could have
* occurred for that activity to be included in the API response. If the parameter value specifies
* a day, but not a time, then any activities that occurred that day will be included in the result
* set. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
* @return Google_Service_YouTube_ActivityListResponse
*/
public function listActivities($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_ActivityListResponse");
}
}
/**
* The "channelBanners" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $channelBanners = $youtubeService->channelBanners;
* </code>
*/
class Google_Service_YouTube_ChannelBanners_Resource extends Google_Service_Resource
{
/**
* Uploads a channel banner image to YouTube. This method represents the first
* two steps in a three-step process to update the banner image for a channel:
*
* - Call the channelBanners.insert method to upload the binary image data to
* YouTube. The image must have a 16:9 aspect ratio and be at least 2120x1192
* pixels. - Extract the url property's value from the response that the API
* returns for step 1. - Call the channels.update method to update the channel's
* branding settings. Set the brandingSettings.image.bannerExternalUrl
* property's value to the URL obtained in step 2. (channelBanners.insert)
*
* @param Google_ChannelBannerResource $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_ChannelBannerResource
*/
public function insert(Google_Service_YouTube_ChannelBannerResource $postBody, $optParams = array())
{
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_YouTube_ChannelBannerResource");
}
}
/**
* The "channelSections" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $channelSections = $youtubeService->channelSections;
* </code>
*/
class Google_Service_YouTube_ChannelSections_Resource extends Google_Service_Resource
{
/**
* Deletes a channelSection. (channelSections.delete)
*
* @param string $id
* The id parameter specifies the YouTube channelSection ID for the resource that is being deleted.
* In a channelSection resource, the id property specifies the YouTube channelSection ID.
* @param array $optParams Optional parameters.
*/
public function delete($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Adds a channelSection for the authenticated user's channel.
* (channelSections.insert)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet and contentDetails.
* @param Google_ChannelSection $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_ChannelSection
*/
public function insert($part, Google_Service_YouTube_ChannelSection $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_YouTube_ChannelSection");
}
/**
* Returns channelSection resources that match the API request criteria.
* (channelSections.listChannelSections)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more channelSection resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id, snippet, and contentDetails.
If the parameter identifies a property
* that contains child properties, the child properties will be included in the response. For
* example, in a channelSection resource, the snippet property contains other properties, such as a
* display title for the channelSection. If you set part=snippet, the API response will also
* contain all of those nested properties.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string channelId
* The channelId parameter specifies a YouTube channel ID. The API will only return that channel's
* channelSections.
* @opt_param string id
* The id parameter specifies a comma-separated list of the YouTube channelSection ID(s) for the
* resource(s) that are being retrieved. In a channelSection resource, the id property specifies
* the YouTube channelSection ID.
* @opt_param bool mine
* Set this parameter's value to true to retrieve a feed of the authenticated user's
* channelSections.
* @return Google_Service_YouTube_ChannelSectionListResponse
*/
public function listChannelSections($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_ChannelSectionListResponse");
}
/**
* Update a channelSection. (channelSections.update)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet and contentDetails.
* @param Google_ChannelSection $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_YouTube_ChannelSection
*/
public function update($part, Google_Service_YouTube_ChannelSection $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_YouTube_ChannelSection");
}
}
/**
* The "channels" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $channels = $youtubeService->channels;
* </code>
*/
class Google_Service_YouTube_Channels_Resource extends Google_Service_Resource
{
/**
* Returns a collection of zero or more channel resources that match the request
* criteria. (channels.listChannels)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more channel resource properties
* that the API response will include. The part names that you can include in the parameter value
* are id, snippet, contentDetails, statistics, topicDetails, and invideoPromotion.
If the
* parameter identifies a property that contains child properties, the child properties will be
* included in the response. For example, in a channel resource, the contentDetails property
* contains other properties, such as the uploads properties. As such, if you set
* part=contentDetails, the API response will also contain all of those nested properties.
* @param array $optParams Optional parameters.
*
* @opt_param bool managedByMe
* Set this parameter's value to true to instruct the API to only return channels managed by the
* content owner that the onBehalfOfContentOwner parameter specifies. The user must be
* authenticated as a CMS account linked to the specified content owner and onBehalfOfContentOwner
* must be provided.
* @opt_param string onBehalfOfContentOwner
* The onBehalfOfContentOwner parameter indicates that the authenticated user is acting on behalf
* of the content owner specified in the parameter value. This parameter is intended for YouTube
* content partners that own and manage many different YouTube channels. It allows content owners
* to authenticate once and get access to all their video and channel data, without having to
* provide authentication credentials for each individual channel. The actual CMS account that the
* user authenticates with needs to be linked to the specified YouTube content owner.
* @opt_param string forUsername
* The forUsername parameter specifies a YouTube username, thereby requesting the channel
* associated with that username.
* @opt_param bool mine
* Set this parameter's value to true to instruct the API to only return channels owned by the
* authenticated user.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set.
* @opt_param string id
* The id parameter specifies a comma-separated list of the YouTube channel ID(s) for the
* resource(s) that are being retrieved. In a channel resource, the id property specifies the
* channel's YouTube channel ID.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
* @opt_param bool mySubscribers
* Set this parameter's value to true to retrieve a list of channels that subscribed to the
* authenticated user's channel.
* @opt_param string categoryId
* The categoryId parameter specifies a YouTube guide category, thereby requesting YouTube channels
* associated with that category.
* @return Google_Service_YouTube_ChannelListResponse
*/
public function listChannels($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_ChannelListResponse");
}
/**
* Updates a channel's metadata. (channels.update)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are id and invideoPromotion.
Note that this
* method will override the existing values for all of the mutable properties that are contained in
* any parts that the parameter value specifies.
* @param Google_Channel $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* The onBehalfOfContentOwner parameter indicates that the authenticated user is acting on behalf
* of the content owner specified in the parameter value. This parameter is intended for YouTube
* content partners that own and manage many different YouTube channels. It allows content owners
* to authenticate once and get access to all their video and channel data, without having to
* provide authentication credentials for each individual channel. The actual CMS account that the
* user authenticates with needs to be linked to the specified YouTube content owner.
* @return Google_Service_YouTube_Channel
*/
public function update($part, Google_Service_YouTube_Channel $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_YouTube_Channel");
}
}
/**
* The "guideCategories" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $guideCategories = $youtubeService->guideCategories;
* </code>
*/
class Google_Service_YouTube_GuideCategories_Resource extends Google_Service_Resource
{
/**
* Returns a list of categories that can be associated with YouTube channels.
* (guideCategories.listGuideCategories)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more guideCategory resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id and snippet.
If the parameter identifies a property that contains child
* properties, the child properties will be included in the response. For example, in a
* guideCategory resource, the snippet property contains other properties, such as the category's
* title. If you set part=snippet, the API response will also contain all of those nested
* properties.
* @param array $optParams Optional parameters.
*
* @opt_param string regionCode
* The regionCode parameter instructs the API to return the list of guide categories available in
* the specified country. The parameter value is an ISO 3166-1 alpha-2 country code.
* @opt_param string id
* The id parameter specifies a comma-separated list of the YouTube channel category ID(s) for the
* resource(s) that are being retrieved. In a guideCategory resource, the id property specifies the
* YouTube channel category ID.
* @opt_param string hl
* The hl parameter specifies the language that will be used for text values in the API response.
* @return Google_Service_YouTube_GuideCategoryListResponse
*/
public function listGuideCategories($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_GuideCategoryListResponse");
}
}
/**
* The "i18nLanguages" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $i18nLanguages = $youtubeService->i18nLanguages;
* </code>
*/
class Google_Service_YouTube_I18nLanguages_Resource extends Google_Service_Resource
{
/**
* Returns a list of supported languages. (i18nLanguages.listI18nLanguages)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more i18nLanguage resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id and snippet.
* @param array $optParams Optional parameters.
*
* @opt_param string hl
* The hl parameter specifies the language that should be used for text values in the API response.
* @return Google_Service_YouTube_I18nLanguageListResponse
*/
public function listI18nLanguages($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_I18nLanguageListResponse");
}
}
/**
* The "i18nRegions" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $i18nRegions = $youtubeService->i18nRegions;
* </code>
*/
class Google_Service_YouTube_I18nRegions_Resource extends Google_Service_Resource
{
/**
* Returns a list of supported regions. (i18nRegions.listI18nRegions)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more i18nRegion resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id and snippet.
* @param array $optParams Optional parameters.
*
* @opt_param string hl
* The hl parameter specifies the language that should be used for text values in the API response.
* @return Google_Service_YouTube_I18nRegionListResponse
*/
public function listI18nRegions($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_I18nRegionListResponse");
}
}
/**
* The "liveBroadcasts" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $liveBroadcasts = $youtubeService->liveBroadcasts;
* </code>
*/
class Google_Service_YouTube_LiveBroadcasts_Resource extends Google_Service_Resource
{
/**
* Binds a YouTube broadcast to a stream or removes an existing binding between
* a broadcast and a stream. A broadcast can only be bound to one video stream.
* (liveBroadcasts.bind)
*
* @param string $id
* The id parameter specifies the unique ID of the broadcast that is being bound to a video stream.
* @param string $part
* The part parameter specifies a comma-separated list of one or more liveBroadcast resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id, snippet, contentDetails, and status.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string streamId
* The streamId parameter specifies the unique ID of the video stream that is being bound to a
* broadcast. If this parameter is omitted, the API will remove any existing binding between the
* broadcast and a video stream.
* @return Google_Service_YouTube_LiveBroadcast
*/
public function bind($id, $part, $optParams = array())
{
$params = array('id' => $id, 'part' => $part);
$params = array_merge($params, $optParams);
return $this->call('bind', array($params), "Google_Service_YouTube_LiveBroadcast");
}
/**
* Controls the settings for a slate that can be displayed in the broadcast
* stream. (liveBroadcasts.control)
*
* @param string $id
* The id parameter specifies the YouTube live broadcast ID that uniquely identifies the broadcast
* in which the slate is being updated.
* @param string $part
* The part parameter specifies a comma-separated list of one or more liveBroadcast resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id, snippet, contentDetails, and status.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param bool displaySlate
* The displaySlate parameter specifies whether the slate is being enabled or disabled.
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string offsetTimeMs
* The offsetTimeMs parameter specifies a positive time offset when the specified slate change will
* occur. The value is measured in milliseconds from the beginning of the broadcast's monitor
* stream, which is the time that the testing phase for the broadcast began. Even though it is
* specified in milliseconds, the value is actually an approximation, and YouTube completes the
* requested action as closely as possible to that time.
If you do not specify a value for this
* parameter, then YouTube performs the action as soon as possible. See the Getting started guide
* for more details.
Important: You should only specify a value for this parameter if your
* broadcast stream is delayed.
* @opt_param string walltime
* The walltime parameter specifies the wall clock time at which the specified slate change will
* occur.
* @return Google_Service_YouTube_LiveBroadcast
*/
public function control($id, $part, $optParams = array())
{
$params = array('id' => $id, 'part' => $part);
$params = array_merge($params, $optParams);
return $this->call('control', array($params), "Google_Service_YouTube_LiveBroadcast");
}
/**
* Deletes a broadcast. (liveBroadcasts.delete)
*
* @param string $id
* The id parameter specifies the YouTube live broadcast ID for the resource that is being deleted.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
*/
public function delete($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Creates a broadcast. (liveBroadcasts.insert)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* properties that you can include in the parameter value are id, snippet, contentDetails, and
* status.
* @param Google_LiveBroadcast $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_LiveBroadcast
*/
public function insert($part, Google_Service_YouTube_LiveBroadcast $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_YouTube_LiveBroadcast");
}
/**
* Returns a list of YouTube broadcasts that match the API request parameters.
* (liveBroadcasts.listLiveBroadcasts)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more liveBroadcast resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id, snippet, contentDetails, and status.
* @param array $optParams Optional parameters.
*
* @opt_param string broadcastStatus
* The broadcastStatus parameter filters the API response to only include broadcasts with the
* specified status.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param bool mine
* The mine parameter can be used to instruct the API to only return broadcasts owned by the
* authenticated user. Set the parameter value to true to only retrieve your own broadcasts.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
* @opt_param string id
* The id parameter specifies a comma-separated list of YouTube broadcast IDs that identify the
* broadcasts being retrieved. In a liveBroadcast resource, the id property specifies the
* broadcast's ID.
* @return Google_Service_YouTube_LiveBroadcastListResponse
*/
public function listLiveBroadcasts($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_LiveBroadcastListResponse");
}
/**
* Changes the status of a YouTube live broadcast and initiates any processes
* associated with the new status. For example, when you transition a
* broadcast's status to testing, YouTube starts to transmit video to that
* broadcast's monitor stream. Before calling this method, you should confirm
* that the value of the status.streamStatus property for the stream bound to
* your broadcast is active. (liveBroadcasts.transition)
*
* @param string $broadcastStatus
* The broadcastStatus parameter identifies the state to which the broadcast is changing. Note that
* to transition a broadcast to either the testing or live state, the status.streamStatus must be
* active for the stream that the broadcast is bound to.
* @param string $id
* The id parameter specifies the unique ID of the broadcast that is transitioning to another
* status.
* @param string $part
* The part parameter specifies a comma-separated list of one or more liveBroadcast resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id, snippet, contentDetails, and status.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_LiveBroadcast
*/
public function transition($broadcastStatus, $id, $part, $optParams = array())
{
$params = array('broadcastStatus' => $broadcastStatus, 'id' => $id, 'part' => $part);
$params = array_merge($params, $optParams);
return $this->call('transition', array($params), "Google_Service_YouTube_LiveBroadcast");
}
/**
* Updates a broadcast. For example, you could modify the broadcast settings
* defined in the liveBroadcast resource's contentDetails object.
* (liveBroadcasts.update)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* properties that you can include in the parameter value are id, snippet, contentDetails, and
* status.
Note that this method will override the existing values for all of the mutable
* properties that are contained in any parts that the parameter value specifies. For example, a
* broadcast's privacy status is defined in the status part. As such, if your request is updating a
* private or unlisted broadcast, and the request's part parameter value includes the status part,
* the broadcast's privacy setting will be updated to whatever value the request body specifies. If
* the request body does not specify a value, the existing privacy setting will be removed and the
* broadcast will revert to the default privacy setting.
* @param Google_LiveBroadcast $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_LiveBroadcast
*/
public function update($part, Google_Service_YouTube_LiveBroadcast $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_YouTube_LiveBroadcast");
}
}
/**
* The "liveStreams" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $liveStreams = $youtubeService->liveStreams;
* </code>
*/
class Google_Service_YouTube_LiveStreams_Resource extends Google_Service_Resource
{
/**
* Deletes a video stream. (liveStreams.delete)
*
* @param string $id
* The id parameter specifies the YouTube live stream ID for the resource that is being deleted.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
*/
public function delete($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Creates a video stream. The stream enables you to send your video to YouTube,
* which can then broadcast the video to your audience. (liveStreams.insert)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* properties that you can include in the parameter value are id, snippet, cdn, and status.
* @param Google_LiveStream $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_LiveStream
*/
public function insert($part, Google_Service_YouTube_LiveStream $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_YouTube_LiveStream");
}
/**
* Returns a list of video streams that match the API request parameters.
* (liveStreams.listLiveStreams)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more liveStream resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id, snippet, cdn, and status.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param bool mine
* The mine parameter can be used to instruct the API to only return streams owned by the
* authenticated user. Set the parameter value to true to only retrieve your own streams.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set. Acceptable values are 0 to 50, inclusive. The default value is 5.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
* @opt_param string id
* The id parameter specifies a comma-separated list of YouTube stream IDs that identify the
* streams being retrieved. In a liveStream resource, the id property specifies the stream's ID.
* @return Google_Service_YouTube_LiveStreamListResponse
*/
public function listLiveStreams($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_LiveStreamListResponse");
}
/**
* Updates a video stream. If the properties that you want to change cannot be
* updated, then you need to create a new stream with the proper settings.
* (liveStreams.update)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* properties that you can include in the parameter value are id, snippet, cdn, and status.
Note
* that this method will override the existing values for all of the mutable properties that are
* contained in any parts that the parameter value specifies. If the request body does not specify
* a value for a mutable property, the existing value for that property will be removed.
* @param Google_LiveStream $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_LiveStream
*/
public function update($part, Google_Service_YouTube_LiveStream $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_YouTube_LiveStream");
}
}
/**
* The "playlistItems" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $playlistItems = $youtubeService->playlistItems;
* </code>
*/
class Google_Service_YouTube_PlaylistItems_Resource extends Google_Service_Resource
{
/**
* Deletes a playlist item. (playlistItems.delete)
*
* @param string $id
* The id parameter specifies the YouTube playlist item ID for the playlist item that is being
* deleted. In a playlistItem resource, the id property specifies the playlist item's ID.
* @param array $optParams Optional parameters.
*/
public function delete($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Adds a resource to a playlist. (playlistItems.insert)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet, contentDetails, and status.
* @param Google_PlaylistItem $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_PlaylistItem
*/
public function insert($part, Google_Service_YouTube_PlaylistItem $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_YouTube_PlaylistItem");
}
/**
* Returns a collection of playlist items that match the API request parameters.
* You can retrieve all of the playlist items in a specified playlist or
* retrieve one or more playlist items by their unique IDs.
* (playlistItems.listPlaylistItems)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more playlistItem resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id, snippet, contentDetails, and status.
If the parameter identifies a
* property that contains child properties, the child properties will be included in the response.
* For example, in a playlistItem resource, the snippet property contains numerous fields,
* including the title, description, position, and resourceId properties. As such, if you set
* part=snippet, the API response will contain all of those properties.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string playlistId
* The playlistId parameter specifies the unique ID of the playlist for which you want to retrieve
* playlist items. Note that even though this is an optional parameter, every request to retrieve
* playlist items must specify a value for either the id parameter or the playlistId parameter.
* @opt_param string videoId
* The videoId parameter specifies that the request should return only the playlist items that
* contain the specified video.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
* @opt_param string id
* The id parameter specifies a comma-separated list of one or more unique playlist item IDs.
* @return Google_Service_YouTube_PlaylistItemListResponse
*/
public function listPlaylistItems($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_PlaylistItemListResponse");
}
/**
* Modifies a playlist item. For example, you could update the item's position
* in the playlist. (playlistItems.update)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet, contentDetails, and status.
Note
* that this method will override the existing values for all of the mutable properties that are
* contained in any parts that the parameter value specifies. For example, a playlist item can
* specify a start time and end time, which identify the times portion of the video that should
* play when users watch the video in the playlist. If your request is updating a playlist item
* that sets these values, and the request's part parameter value includes the contentDetails part,
* the playlist item's start and end times will be updated to whatever value the request body
* specifies. If the request body does not specify values, the existing start and end times will be
* removed and replaced with the default settings.
* @param Google_PlaylistItem $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_YouTube_PlaylistItem
*/
public function update($part, Google_Service_YouTube_PlaylistItem $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_YouTube_PlaylistItem");
}
}
/**
* The "playlists" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $playlists = $youtubeService->playlists;
* </code>
*/
class Google_Service_YouTube_Playlists_Resource extends Google_Service_Resource
{
/**
* Deletes a playlist. (playlists.delete)
*
* @param string $id
* The id parameter specifies the YouTube playlist ID for the playlist that is being deleted. In a
* playlist resource, the id property specifies the playlist's ID.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
*/
public function delete($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Creates a playlist. (playlists.insert)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet and status.
* @param Google_Playlist $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_Playlist
*/
public function insert($part, Google_Service_YouTube_Playlist $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_YouTube_Playlist");
}
/**
* Returns a collection of playlists that match the API request parameters. For
* example, you can retrieve all playlists that the authenticated user owns, or
* you can retrieve one or more playlists by their unique IDs.
* (playlists.listPlaylists)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more playlist resource properties
* that the API response will include. The part names that you can include in the parameter value
* are id, snippet, status, and contentDetails.
If the parameter identifies a property that
* contains child properties, the child properties will be included in the response. For example,
* in a playlist resource, the snippet property contains properties like author, title,
* description, tags, and timeCreated. As such, if you set part=snippet, the API response will
* contain all of those properties.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string channelId
* This value indicates that the API should only return the specified channel's playlists.
* @opt_param bool mine
* Set this parameter's value to true to instruct the API to only return playlists owned by the
* authenticated user.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
* @opt_param string id
* The id parameter specifies a comma-separated list of the YouTube playlist ID(s) for the
* resource(s) that are being retrieved. In a playlist resource, the id property specifies the
* playlist's YouTube playlist ID.
* @return Google_Service_YouTube_PlaylistListResponse
*/
public function listPlaylists($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_PlaylistListResponse");
}
/**
* Modifies a playlist. For example, you could change a playlist's title,
* description, or privacy status. (playlists.update)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet and status.
Note that this method
* will override the existing values for all of the mutable properties that are contained in any
* parts that the parameter value specifies. For example, a playlist's privacy setting is contained
* in the status part. As such, if your request is updating a private playlist, and the request's
* part parameter value includes the status part, the playlist's privacy setting will be updated to
* whatever value the request body specifies. If the request body does not specify a value, the
* existing privacy setting will be removed and the playlist will revert to the default privacy
* setting.
* @param Google_Playlist $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_Playlist
*/
public function update($part, Google_Service_YouTube_Playlist $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_YouTube_Playlist");
}
}
/**
* The "search" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $search = $youtubeService->search;
* </code>
*/
class Google_Service_YouTube_Search_Resource extends Google_Service_Resource
{
/**
* Returns a collection of search results that match the query parameters
* specified in the API request. By default, a search result set identifies
* matching video, channel, and playlist resources, but you can also configure
* queries to only retrieve a specific type of resource. (search.listSearch)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more search resource properties
* that the API response will include. The part names that you can include in the parameter value
* are id and snippet.
If the parameter identifies a property that contains child properties, the
* child properties will be included in the response. For example, in a search result, the snippet
* property contains other properties that identify the result's title, description, and so forth.
* If you set part=snippet, the API response will also contain all of those nested properties.
* @param array $optParams Optional parameters.
*
* @opt_param string eventType
* The eventType parameter restricts a search to broadcast events.
* @opt_param string channelId
* The channelId parameter indicates that the API response should only contain resources created by
* the channel
* @opt_param string videoSyndicated
* The videoSyndicated parameter lets you to restrict a search to only videos that can be played
* outside youtube.com.
* @opt_param string channelType
* The channelType parameter lets you restrict a search to a particular type of channel.
* @opt_param string videoCaption
* The videoCaption parameter indicates whether the API should filter video search results based on
* whether they have captions.
* @opt_param string publishedAfter
* The publishedAfter parameter indicates that the API response should only contain resources
* created after the specified time. The value is an RFC 3339 formatted date-time value
* (1970-01-01T00:00:00Z).
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
* @opt_param bool forContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The forContentOwner
* parameter restricts the search to only retrieve resources owned by the content owner specified
* by the onBehalfOfContentOwner parameter. The user must be authenticated using a CMS account
* linked to the specified content owner and onBehalfOfContentOwner must be provided.
* @opt_param string regionCode
* The regionCode parameter instructs the API to return search results for the specified country.
* The parameter value is an ISO 3166-1 alpha-2 country code.
* @opt_param string location
* The location parameter restricts a search to videos that have a geographical location specified
* in their metadata. The value is a string that specifies geographic latitude/longitude
* coordinates e.g. (37.42307,-122.08427)
* @opt_param string locationRadius
* The locationRadius, in conjunction with the location parameter, defines a geographic area. If
* the geographic coordinates associated with a video fall within that area, then the video may be
* included in search results. This parameter value must be a floating point number followed by a
* measurement unit. Valid measurement units are m, km, ft, and mi. For example, valid parameter
* values include 1500m, 5km, 10000ft, and 0.75mi. The API does not support locationRadius
* parameter values larger than 1000 kilometers.
* @opt_param string videoType
* The videoType parameter lets you restrict a search to a particular type of videos.
* @opt_param string type
* The type parameter restricts a search query to only retrieve a particular type of resource. The
* value is a comma-separated list of resource types.
* @opt_param string topicId
* The topicId parameter indicates that the API response should only contain resources associated
* with the specified topic. The value identifies a Freebase topic ID.
* @opt_param string publishedBefore
* The publishedBefore parameter indicates that the API response should only contain resources
* created before the specified time. The value is an RFC 3339 formatted date-time value
* (1970-01-01T00:00:00Z).
* @opt_param string videoDimension
* The videoDimension parameter lets you restrict a search to only retrieve 2D or 3D videos.
* @opt_param string videoLicense
* The videoLicense parameter filters search results to only include videos with a particular
* license. YouTube lets video uploaders choose to attach either the Creative Commons license or
* the standard YouTube license to each of their videos.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set.
* @opt_param string relatedToVideoId
* The relatedToVideoId parameter retrieves a list of videos that are related to the video that the
* parameter value identifies. The parameter value must be set to a YouTube video ID and, if you
* are using this parameter, the type parameter must be set to video.
* @opt_param string videoDefinition
* The videoDefinition parameter lets you restrict a search to only include either high definition
* (HD) or standard definition (SD) videos. HD videos are available for playback in at least 720p,
* though higher resolutions, like 1080p, might also be available.
* @opt_param string videoDuration
* The videoDuration parameter filters video search results based on their duration.
* @opt_param bool forMine
* The forMine parameter restricts the search to only retrieve videos owned by the authenticated
* user. If you set this parameter to true, then the type parameter's value must also be set to
* video.
* @opt_param string q
* The q parameter specifies the query term to search for.
* @opt_param string safeSearch
* The safeSearch parameter indicates whether the search results should include restricted content
* as well as standard content.
* @opt_param string videoEmbeddable
* The videoEmbeddable parameter lets you to restrict a search to only videos that can be embedded
* into a webpage.
* @opt_param string videoCategoryId
* The videoCategoryId parameter filters video search results based on their category.
* @opt_param string order
* The order parameter specifies the method that will be used to order resources in the API
* response.
* @return Google_Service_YouTube_SearchListResponse
*/
public function listSearch($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_SearchListResponse");
}
}
/**
* The "subscriptions" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $subscriptions = $youtubeService->subscriptions;
* </code>
*/
class Google_Service_YouTube_Subscriptions_Resource extends Google_Service_Resource
{
/**
* Deletes a subscription. (subscriptions.delete)
*
* @param string $id
* The id parameter specifies the YouTube subscription ID for the resource that is being deleted.
* In a subscription resource, the id property specifies the YouTube subscription ID.
* @param array $optParams Optional parameters.
*/
public function delete($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Adds a subscription for the authenticated user's channel.
* (subscriptions.insert)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet and contentDetails.
* @param Google_Subscription $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_YouTube_Subscription
*/
public function insert($part, Google_Service_YouTube_Subscription $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_YouTube_Subscription");
}
/**
* Returns subscription resources that match the API request criteria.
* (subscriptions.listSubscriptions)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more subscription resource
* properties that the API response will include. The part names that you can include in the
* parameter value are id, snippet, and contentDetails.
If the parameter identifies a property
* that contains child properties, the child properties will be included in the response. For
* example, in a subscription resource, the snippet property contains other properties, such as a
* display title for the subscription. If you set part=snippet, the API response will also contain
* all of those nested properties.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param string channelId
* The channelId parameter specifies a YouTube channel ID. The API will only return that channel's
* subscriptions.
* @opt_param bool mine
* Set this parameter's value to true to retrieve a feed of the authenticated user's subscriptions.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set.
* @opt_param string forChannelId
* The forChannelId parameter specifies a comma-separated list of channel IDs. The API response
* will then only contain subscriptions matching those channels.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
* @opt_param bool mySubscribers
* Set this parameter's value to true to retrieve a feed of the subscribers of the authenticated
* user.
* @opt_param string order
* The order parameter specifies the method that will be used to sort resources in the API
* response.
* @opt_param string id
* The id parameter specifies a comma-separated list of the YouTube subscription ID(s) for the
* resource(s) that are being retrieved. In a subscription resource, the id property specifies the
* YouTube subscription ID.
* @return Google_Service_YouTube_SubscriptionListResponse
*/
public function listSubscriptions($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_SubscriptionListResponse");
}
}
/**
* The "thumbnails" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $thumbnails = $youtubeService->thumbnails;
* </code>
*/
class Google_Service_YouTube_Thumbnails_Resource extends Google_Service_Resource
{
/**
* Uploads a custom video thumbnail to YouTube and sets it for a video.
* (thumbnails.set)
*
* @param string $videoId
* The videoId parameter specifies a YouTube video ID for which the custom video thumbnail is being
* provided.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* The onBehalfOfContentOwner parameter indicates that the authenticated user is acting on behalf
* of the content owner specified in the parameter value. This parameter is intended for YouTube
* content partners that own and manage many different YouTube channels. It allows content owners
* to authenticate once and get access to all their video and channel data, without having to
* provide authentication credentials for each individual channel. The actual CMS account that the
* user authenticates with needs to be linked to the specified YouTube content owner.
* @return Google_Service_YouTube_ThumbnailSetResponse
*/
public function set($videoId, $optParams = array())
{
$params = array('videoId' => $videoId);
$params = array_merge($params, $optParams);
return $this->call('set', array($params), "Google_Service_YouTube_ThumbnailSetResponse");
}
}
/**
* The "videoCategories" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $videoCategories = $youtubeService->videoCategories;
* </code>
*/
class Google_Service_YouTube_VideoCategories_Resource extends Google_Service_Resource
{
/**
* Returns a list of categories that can be associated with YouTube videos.
* (videoCategories.listVideoCategories)
*
* @param string $part
* The part parameter specifies the videoCategory resource parts that the API response will
* include. Supported values are id and snippet.
* @param array $optParams Optional parameters.
*
* @opt_param string regionCode
* The regionCode parameter instructs the API to return the list of video categories available in
* the specified country. The parameter value is an ISO 3166-1 alpha-2 country code.
* @opt_param string id
* The id parameter specifies a comma-separated list of video category IDs for the resources that
* you are retrieving.
* @opt_param string hl
* The hl parameter specifies the language that should be used for text values in the API response.
* @return Google_Service_YouTube_VideoCategoryListResponse
*/
public function listVideoCategories($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_VideoCategoryListResponse");
}
}
/**
* The "videos" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $videos = $youtubeService->videos;
* </code>
*/
class Google_Service_YouTube_Videos_Resource extends Google_Service_Resource
{
/**
* Deletes a YouTube video. (videos.delete)
*
* @param string $id
* The id parameter specifies the YouTube video ID for the resource that is being deleted. In a
* video resource, the id property specifies the video's ID.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The actual CMS account that the user authenticates with must be linked to
* the specified YouTube content owner.
*/
public function delete($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Retrieves the ratings that the authorized user gave to a list of specified
* videos. (videos.getRating)
*
* @param string $id
* The id parameter specifies a comma-separated list of the YouTube video ID(s) for the resource(s)
* for which you are retrieving rating data. In a video resource, the id property specifies the
* video's ID.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @return Google_Service_YouTube_VideoGetRatingResponse
*/
public function getRating($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('getRating', array($params), "Google_Service_YouTube_VideoGetRatingResponse");
}
/**
* Uploads a video to YouTube and optionally sets the video's metadata.
* (videos.insert)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet, contentDetails, fileDetails,
* liveStreamingDetails, player, processingDetails, recordingDetails, statistics, status,
* suggestions, and topicDetails. However, not all of those parts contain properties that can be
* set when setting or updating a video's metadata. For example, the statistics object encapsulates
* statistics that YouTube calculates for a video and does not contain values that you can set or
* modify. If the parameter value specifies a part that does not contain mutable values, that part
* will still be included in the API response.
* @param Google_Video $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param bool stabilize
* The stabilize parameter indicates whether YouTube should adjust the video to remove shaky camera
* motions.
* @opt_param string onBehalfOfContentOwnerChannel
* This parameter can only be used in a properly authorized request. Note: This parameter is
* intended exclusively for YouTube content partners.
The onBehalfOfContentOwnerChannel parameter
* specifies the YouTube channel ID of the channel to which a video is being added. This parameter
* is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it
* can only be used in conjunction with that parameter. In addition, the request must be authorized
* using a CMS account that is linked to the content owner that the onBehalfOfContentOwner
* parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value
* specifies must be linked to the content owner that the onBehalfOfContentOwner parameter
* specifies.
This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and perform actions on
* behalf of the channel specified in the parameter value, without having to provide authentication
* credentials for each separate channel.
* @opt_param bool notifySubscribers
* The notifySubscribers parameter indicates whether YouTube should send notification to
* subscribers about the inserted video.
* @opt_param bool autoLevels
* The autoLevels parameter indicates whether YouTube should automatically enhance the video's
* lighting and color.
* @return Google_Service_YouTube_Video
*/
public function insert($part, Google_Service_YouTube_Video $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_YouTube_Video");
}
/**
* Returns a list of videos that match the API request parameters.
* (videos.listVideos)
*
* @param string $part
* The part parameter specifies a comma-separated list of one or more video resource properties
* that the API response will include. The part names that you can include in the parameter value
* are id, snippet, contentDetails, fileDetails, liveStreamingDetails, player, processingDetails,
* recordingDetails, statistics, status, suggestions, and topicDetails.
If the parameter
* identifies a property that contains child properties, the child properties will be included in
* the response. For example, in a video resource, the snippet property contains the channelId,
* title, description, tags, and categoryId properties. As such, if you set part=snippet, the API
* response will contain all of those properties.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
* @opt_param string regionCode
* The regionCode parameter instructs the API to select a video chart available in the specified
* region. This parameter can only be used in conjunction with the chart parameter. The parameter
* value is an ISO 3166-1 alpha-2 country code.
* @opt_param string locale
* DEPRECATED
* @opt_param string videoCategoryId
* The videoCategoryId parameter identifies the video category for which the chart should be
* retrieved. This parameter can only be used in conjunction with the chart parameter. By default,
* charts are not restricted to a particular category.
* @opt_param string chart
* The chart parameter identifies the chart that you want to retrieve.
* @opt_param string maxResults
* The maxResults parameter specifies the maximum number of items that should be returned in the
* result set.
Note: This parameter is supported for use in conjunction with the myRating
* parameter, but it is not supported for use in conjunction with the id parameter.
* @opt_param string pageToken
* The pageToken parameter identifies a specific page in the result set that should be returned. In
* an API response, the nextPageToken and prevPageToken properties identify other pages that could
* be retrieved.
Note: This parameter is supported for use in conjunction with the myRating
* parameter, but it is not supported for use in conjunction with the id parameter.
* @opt_param string myRating
* Set this parameter's value to like or dislike to instruct the API to only return videos liked or
* disliked by the authenticated user.
* @opt_param string id
* The id parameter specifies a comma-separated list of the YouTube video ID(s) for the resource(s)
* that are being retrieved. In a video resource, the id property specifies the video's ID.
* @return Google_Service_YouTube_VideoListResponse
*/
public function listVideos($part, $optParams = array())
{
$params = array('part' => $part);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_YouTube_VideoListResponse");
}
/**
* Add a like or dislike rating to a video or remove a rating from a video.
* (videos.rate)
*
* @param string $id
* The id parameter specifies the YouTube video ID of the video that is being rated or having its
* rating removed.
* @param string $rating
* Specifies the rating to record.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The CMS account that the user authenticates with must be linked to the
* specified YouTube content owner.
*/
public function rate($id, $rating, $optParams = array())
{
$params = array('id' => $id, 'rating' => $rating);
$params = array_merge($params, $optParams);
return $this->call('rate', array($params));
}
/**
* Updates a video's metadata. (videos.update)
*
* @param string $part
* The part parameter serves two purposes in this operation. It identifies the properties that the
* write operation will set as well as the properties that the API response will include.
The part
* names that you can include in the parameter value are snippet, contentDetails, fileDetails,
* liveStreamingDetails, player, processingDetails, recordingDetails, statistics, status,
* suggestions, and topicDetails.
Note that this method will override the existing values for all
* of the mutable properties that are contained in any parts that the parameter value specifies.
* For example, a video's privacy setting is contained in the status part. As such, if your request
* is updating a private video, and the request's part parameter value includes the status part,
* the video's privacy setting will be updated to whatever value the request body specifies. If the
* request body does not specify a value, the existing privacy setting will be removed and the
* video will revert to the default privacy setting.
In addition, not all of those parts contain
* properties that can be set when setting or updating a video's metadata. For example, the
* statistics object encapsulates statistics that YouTube calculates for a video and does not
* contain values that you can set or modify. If the parameter value specifies a part that does not
* contain mutable values, that part will still be included in the API response.
* @param Google_Video $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* Note: This parameter is intended exclusively for YouTube content partners.
The
* onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify
* a YouTube CMS user who is acting on behalf of the content owner specified in the parameter
* value. This parameter is intended for YouTube content partners that own and manage many
* different YouTube channels. It allows content owners to authenticate once and get access to all
* their video and channel data, without having to provide authentication credentials for each
* individual channel. The actual CMS account that the user authenticates with must be linked to
* the specified YouTube content owner.
* @return Google_Service_YouTube_Video
*/
public function update($part, Google_Service_YouTube_Video $postBody, $optParams = array())
{
$params = array('part' => $part, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_YouTube_Video");
}
}
/**
* The "watermarks" collection of methods.
* Typical usage is:
* <code>
* $youtubeService = new Google_Service_YouTube(...);
* $watermarks = $youtubeService->watermarks;
* </code>
*/
class Google_Service_YouTube_Watermarks_Resource extends Google_Service_Resource
{
/**
* Uploads a watermark image to YouTube and sets it for a channel.
* (watermarks.set)
*
* @param string $channelId
* The channelId parameter specifies a YouTube channel ID for which the watermark is being
* provided.
* @param Google_InvideoBranding $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* The onBehalfOfContentOwner parameter indicates that the authenticated user is acting on behalf
* of the content owner specified in the parameter value. This parameter is intended for YouTube
* content partners that own and manage many different YouTube channels. It allows content owners
* to authenticate once and get access to all their video and channel data, without having to
* provide authentication credentials for each individual channel. The actual CMS account that the
* user authenticates with needs to be linked to the specified YouTube content owner.
*/
public function set($channelId, Google_Service_YouTube_InvideoBranding $postBody, $optParams = array())
{
$params = array('channelId' => $channelId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('set', array($params));
}
/**
* Deletes a watermark. (watermarks.unsetWatermarks)
*
* @param string $channelId
* The channelId parameter specifies a YouTube channel ID for which the watermark is being unset.
* @param array $optParams Optional parameters.
*
* @opt_param string onBehalfOfContentOwner
* The onBehalfOfContentOwner parameter indicates that the authenticated user is acting on behalf
* of the content owner specified in the parameter value. This parameter is intended for YouTube
* content partners that own and manage many different YouTube channels. It allows content owners
* to authenticate once and get access to all their video and channel data, without having to
* provide authentication credentials for each individual channel. The actual CMS account that the
* user authenticates with needs to be linked to the specified YouTube content owner.
*/
public function unsetWatermarks($channelId, $optParams = array())
{
$params = array('channelId' => $channelId);
$params = array_merge($params, $optParams);
return $this->call('unset', array($params));
}
}
class Google_Service_YouTube_AccessPolicy extends Google_Collection
{
public $allowed;
public $exception;
public function setAllowed($allowed)
{
$this->allowed = $allowed;
}
public function getAllowed()
{
return $this->allowed;
}
public function setException($exception)
{
$this->exception = $exception;
}
public function getException()
{
return $this->exception;
}
}
class Google_Service_YouTube_Activity extends Google_Model
{
protected $contentDetailsType = 'Google_Service_YouTube_ActivityContentDetails';
protected $contentDetailsDataType = '';
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_ActivitySnippet';
protected $snippetDataType = '';
public function setContentDetails(Google_Service_YouTube_ActivityContentDetails $contentDetails)
{
$this->contentDetails = $contentDetails;
}
public function getContentDetails()
{
return $this->contentDetails;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_ActivitySnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
}
class Google_Service_YouTube_ActivityContentDetails extends Google_Model
{
protected $bulletinType = 'Google_Service_YouTube_ActivityContentDetailsBulletin';
protected $bulletinDataType = '';
protected $channelItemType = 'Google_Service_YouTube_ActivityContentDetailsChannelItem';
protected $channelItemDataType = '';
protected $commentType = 'Google_Service_YouTube_ActivityContentDetailsComment';
protected $commentDataType = '';
protected $favoriteType = 'Google_Service_YouTube_ActivityContentDetailsFavorite';
protected $favoriteDataType = '';
protected $likeType = 'Google_Service_YouTube_ActivityContentDetailsLike';
protected $likeDataType = '';
protected $playlistItemType = 'Google_Service_YouTube_ActivityContentDetailsPlaylistItem';
protected $playlistItemDataType = '';
protected $promotedItemType = 'Google_Service_YouTube_ActivityContentDetailsPromotedItem';
protected $promotedItemDataType = '';
protected $recommendationType = 'Google_Service_YouTube_ActivityContentDetailsRecommendation';
protected $recommendationDataType = '';
protected $socialType = 'Google_Service_YouTube_ActivityContentDetailsSocial';
protected $socialDataType = '';
protected $subscriptionType = 'Google_Service_YouTube_ActivityContentDetailsSubscription';
protected $subscriptionDataType = '';
protected $uploadType = 'Google_Service_YouTube_ActivityContentDetailsUpload';
protected $uploadDataType = '';
public function setBulletin(Google_Service_YouTube_ActivityContentDetailsBulletin $bulletin)
{
$this->bulletin = $bulletin;
}
public function getBulletin()
{
return $this->bulletin;
}
public function setChannelItem(Google_Service_YouTube_ActivityContentDetailsChannelItem $channelItem)
{
$this->channelItem = $channelItem;
}
public function getChannelItem()
{
return $this->channelItem;
}
public function setComment(Google_Service_YouTube_ActivityContentDetailsComment $comment)
{
$this->comment = $comment;
}
public function getComment()
{
return $this->comment;
}
public function setFavorite(Google_Service_YouTube_ActivityContentDetailsFavorite $favorite)
{
$this->favorite = $favorite;
}
public function getFavorite()
{
return $this->favorite;
}
public function setLike(Google_Service_YouTube_ActivityContentDetailsLike $like)
{
$this->like = $like;
}
public function getLike()
{
return $this->like;
}
public function setPlaylistItem(Google_Service_YouTube_ActivityContentDetailsPlaylistItem $playlistItem)
{
$this->playlistItem = $playlistItem;
}
public function getPlaylistItem()
{
return $this->playlistItem;
}
public function setPromotedItem(Google_Service_YouTube_ActivityContentDetailsPromotedItem $promotedItem)
{
$this->promotedItem = $promotedItem;
}
public function getPromotedItem()
{
return $this->promotedItem;
}
public function setRecommendation(Google_Service_YouTube_ActivityContentDetailsRecommendation $recommendation)
{
$this->recommendation = $recommendation;
}
public function getRecommendation()
{
return $this->recommendation;
}
public function setSocial(Google_Service_YouTube_ActivityContentDetailsSocial $social)
{
$this->social = $social;
}
public function getSocial()
{
return $this->social;
}
public function setSubscription(Google_Service_YouTube_ActivityContentDetailsSubscription $subscription)
{
$this->subscription = $subscription;
}
public function getSubscription()
{
return $this->subscription;
}
public function setUpload(Google_Service_YouTube_ActivityContentDetailsUpload $upload)
{
$this->upload = $upload;
}
public function getUpload()
{
return $this->upload;
}
}
class Google_Service_YouTube_ActivityContentDetailsBulletin extends Google_Model
{
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
}
class Google_Service_YouTube_ActivityContentDetailsChannelItem extends Google_Model
{
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
}
class Google_Service_YouTube_ActivityContentDetailsComment extends Google_Model
{
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
}
class Google_Service_YouTube_ActivityContentDetailsFavorite extends Google_Model
{
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
}
class Google_Service_YouTube_ActivityContentDetailsLike extends Google_Model
{
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
}
class Google_Service_YouTube_ActivityContentDetailsPlaylistItem extends Google_Model
{
public $playlistId;
public $playlistItemId;
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
public function setPlaylistId($playlistId)
{
$this->playlistId = $playlistId;
}
public function getPlaylistId()
{
return $this->playlistId;
}
public function setPlaylistItemId($playlistItemId)
{
$this->playlistItemId = $playlistItemId;
}
public function getPlaylistItemId()
{
return $this->playlistItemId;
}
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
}
class Google_Service_YouTube_ActivityContentDetailsPromotedItem extends Google_Collection
{
public $adTag;
public $clickTrackingUrl;
public $creativeViewUrl;
public $ctaType;
public $customCtaButtonText;
public $descriptionText;
public $destinationUrl;
public $forecastingUrl;
public $impressionUrl;
public $videoId;
public function setAdTag($adTag)
{
$this->adTag = $adTag;
}
public function getAdTag()
{
return $this->adTag;
}
public function setClickTrackingUrl($clickTrackingUrl)
{
$this->clickTrackingUrl = $clickTrackingUrl;
}
public function getClickTrackingUrl()
{
return $this->clickTrackingUrl;
}
public function setCreativeViewUrl($creativeViewUrl)
{
$this->creativeViewUrl = $creativeViewUrl;
}
public function getCreativeViewUrl()
{
return $this->creativeViewUrl;
}
public function setCtaType($ctaType)
{
$this->ctaType = $ctaType;
}
public function getCtaType()
{
return $this->ctaType;
}
public function setCustomCtaButtonText($customCtaButtonText)
{
$this->customCtaButtonText = $customCtaButtonText;
}
public function getCustomCtaButtonText()
{
return $this->customCtaButtonText;
}
public function setDescriptionText($descriptionText)
{
$this->descriptionText = $descriptionText;
}
public function getDescriptionText()
{
return $this->descriptionText;
}
public function setDestinationUrl($destinationUrl)
{
$this->destinationUrl = $destinationUrl;
}
public function getDestinationUrl()
{
return $this->destinationUrl;
}
public function setForecastingUrl($forecastingUrl)
{
$this->forecastingUrl = $forecastingUrl;
}
public function getForecastingUrl()
{
return $this->forecastingUrl;
}
public function setImpressionUrl($impressionUrl)
{
$this->impressionUrl = $impressionUrl;
}
public function getImpressionUrl()
{
return $this->impressionUrl;
}
public function setVideoId($videoId)
{
$this->videoId = $videoId;
}
public function getVideoId()
{
return $this->videoId;
}
}
class Google_Service_YouTube_ActivityContentDetailsRecommendation extends Google_Model
{
public $reason;
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
protected $seedResourceIdType = 'Google_Service_YouTube_ResourceId';
protected $seedResourceIdDataType = '';
public function setReason($reason)
{
$this->reason = $reason;
}
public function getReason()
{
return $this->reason;
}
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
public function setSeedResourceId(Google_Service_YouTube_ResourceId $seedResourceId)
{
$this->seedResourceId = $seedResourceId;
}
public function getSeedResourceId()
{
return $this->seedResourceId;
}
}
class Google_Service_YouTube_ActivityContentDetailsSocial extends Google_Model
{
public $author;
public $imageUrl;
public $referenceUrl;
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
public $type;
public function setAuthor($author)
{
$this->author = $author;
}
public function getAuthor()
{
return $this->author;
}
public function setImageUrl($imageUrl)
{
$this->imageUrl = $imageUrl;
}
public function getImageUrl()
{
return $this->imageUrl;
}
public function setReferenceUrl($referenceUrl)
{
$this->referenceUrl = $referenceUrl;
}
public function getReferenceUrl()
{
return $this->referenceUrl;
}
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_YouTube_ActivityContentDetailsSubscription extends Google_Model
{
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
}
class Google_Service_YouTube_ActivityContentDetailsUpload extends Google_Model
{
public $videoId;
public function setVideoId($videoId)
{
$this->videoId = $videoId;
}
public function getVideoId()
{
return $this->videoId;
}
}
class Google_Service_YouTube_ActivityListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_Activity';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_ActivitySnippet extends Google_Model
{
public $channelId;
public $channelTitle;
public $description;
public $groupId;
public $publishedAt;
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
public $type;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setChannelTitle($channelTitle)
{
$this->channelTitle = $channelTitle;
}
public function getChannelTitle()
{
return $this->channelTitle;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setGroupId($groupId)
{
$this->groupId = $groupId;
}
public function getGroupId()
{
return $this->groupId;
}
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
}
public function getPublishedAt()
{
return $this->publishedAt;
}
public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
{
$this->thumbnails = $thumbnails;
}
public function getThumbnails()
{
return $this->thumbnails;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_YouTube_CdnSettings extends Google_Model
{
public $format;
protected $ingestionInfoType = 'Google_Service_YouTube_IngestionInfo';
protected $ingestionInfoDataType = '';
public $ingestionType;
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
public function setIngestionInfo(Google_Service_YouTube_IngestionInfo $ingestionInfo)
{
$this->ingestionInfo = $ingestionInfo;
}
public function getIngestionInfo()
{
return $this->ingestionInfo;
}
public function setIngestionType($ingestionType)
{
$this->ingestionType = $ingestionType;
}
public function getIngestionType()
{
return $this->ingestionType;
}
}
class Google_Service_YouTube_Channel extends Google_Model
{
protected $auditDetailsType = 'Google_Service_YouTube_ChannelAuditDetails';
protected $auditDetailsDataType = '';
protected $brandingSettingsType = 'Google_Service_YouTube_ChannelBrandingSettings';
protected $brandingSettingsDataType = '';
protected $contentDetailsType = 'Google_Service_YouTube_ChannelContentDetails';
protected $contentDetailsDataType = '';
protected $contentOwnerDetailsType = 'Google_Service_YouTube_ChannelContentOwnerDetails';
protected $contentOwnerDetailsDataType = '';
protected $conversionPingsType = 'Google_Service_YouTube_ChannelConversionPings';
protected $conversionPingsDataType = '';
public $etag;
public $id;
protected $invideoPromotionType = 'Google_Service_YouTube_InvideoPromotion';
protected $invideoPromotionDataType = '';
public $kind;
protected $snippetType = 'Google_Service_YouTube_ChannelSnippet';
protected $snippetDataType = '';
protected $statisticsType = 'Google_Service_YouTube_ChannelStatistics';
protected $statisticsDataType = '';
protected $statusType = 'Google_Service_YouTube_ChannelStatus';
protected $statusDataType = '';
protected $topicDetailsType = 'Google_Service_YouTube_ChannelTopicDetails';
protected $topicDetailsDataType = '';
public function setAuditDetails(Google_Service_YouTube_ChannelAuditDetails $auditDetails)
{
$this->auditDetails = $auditDetails;
}
public function getAuditDetails()
{
return $this->auditDetails;
}
public function setBrandingSettings(Google_Service_YouTube_ChannelBrandingSettings $brandingSettings)
{
$this->brandingSettings = $brandingSettings;
}
public function getBrandingSettings()
{
return $this->brandingSettings;
}
public function setContentDetails(Google_Service_YouTube_ChannelContentDetails $contentDetails)
{
$this->contentDetails = $contentDetails;
}
public function getContentDetails()
{
return $this->contentDetails;
}
public function setContentOwnerDetails(Google_Service_YouTube_ChannelContentOwnerDetails $contentOwnerDetails)
{
$this->contentOwnerDetails = $contentOwnerDetails;
}
public function getContentOwnerDetails()
{
return $this->contentOwnerDetails;
}
public function setConversionPings(Google_Service_YouTube_ChannelConversionPings $conversionPings)
{
$this->conversionPings = $conversionPings;
}
public function getConversionPings()
{
return $this->conversionPings;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setInvideoPromotion(Google_Service_YouTube_InvideoPromotion $invideoPromotion)
{
$this->invideoPromotion = $invideoPromotion;
}
public function getInvideoPromotion()
{
return $this->invideoPromotion;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_ChannelSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
public function setStatistics(Google_Service_YouTube_ChannelStatistics $statistics)
{
$this->statistics = $statistics;
}
public function getStatistics()
{
return $this->statistics;
}
public function setStatus(Google_Service_YouTube_ChannelStatus $status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
public function setTopicDetails(Google_Service_YouTube_ChannelTopicDetails $topicDetails)
{
$this->topicDetails = $topicDetails;
}
public function getTopicDetails()
{
return $this->topicDetails;
}
}
class Google_Service_YouTube_ChannelAuditDetails extends Google_Model
{
public $communityGuidelinesGoodStanding;
public $contentIdClaimsGoodStanding;
public $copyrightStrikesGoodStanding;
public $overallGoodStanding;
public function setCommunityGuidelinesGoodStanding($communityGuidelinesGoodStanding)
{
$this->communityGuidelinesGoodStanding = $communityGuidelinesGoodStanding;
}
public function getCommunityGuidelinesGoodStanding()
{
return $this->communityGuidelinesGoodStanding;
}
public function setContentIdClaimsGoodStanding($contentIdClaimsGoodStanding)
{
$this->contentIdClaimsGoodStanding = $contentIdClaimsGoodStanding;
}
public function getContentIdClaimsGoodStanding()
{
return $this->contentIdClaimsGoodStanding;
}
public function setCopyrightStrikesGoodStanding($copyrightStrikesGoodStanding)
{
$this->copyrightStrikesGoodStanding = $copyrightStrikesGoodStanding;
}
public function getCopyrightStrikesGoodStanding()
{
return $this->copyrightStrikesGoodStanding;
}
public function setOverallGoodStanding($overallGoodStanding)
{
$this->overallGoodStanding = $overallGoodStanding;
}
public function getOverallGoodStanding()
{
return $this->overallGoodStanding;
}
}
class Google_Service_YouTube_ChannelBannerResource extends Google_Model
{
public $etag;
public $kind;
public $url;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setUrl($url)
{
$this->url = $url;
}
public function getUrl()
{
return $this->url;
}
}
class Google_Service_YouTube_ChannelBrandingSettings extends Google_Collection
{
protected $channelType = 'Google_Service_YouTube_ChannelSettings';
protected $channelDataType = '';
protected $hintsType = 'Google_Service_YouTube_PropertyValue';
protected $hintsDataType = 'array';
protected $imageType = 'Google_Service_YouTube_ImageSettings';
protected $imageDataType = '';
protected $watchType = 'Google_Service_YouTube_WatchSettings';
protected $watchDataType = '';
public function setChannel(Google_Service_YouTube_ChannelSettings $channel)
{
$this->channel = $channel;
}
public function getChannel()
{
return $this->channel;
}
public function setHints($hints)
{
$this->hints = $hints;
}
public function getHints()
{
return $this->hints;
}
public function setImage(Google_Service_YouTube_ImageSettings $image)
{
$this->image = $image;
}
public function getImage()
{
return $this->image;
}
public function setWatch(Google_Service_YouTube_WatchSettings $watch)
{
$this->watch = $watch;
}
public function getWatch()
{
return $this->watch;
}
}
class Google_Service_YouTube_ChannelContentDetails extends Google_Model
{
public $googlePlusUserId;
protected $relatedPlaylistsType = 'Google_Service_YouTube_ChannelContentDetailsRelatedPlaylists';
protected $relatedPlaylistsDataType = '';
public function setGooglePlusUserId($googlePlusUserId)
{
$this->googlePlusUserId = $googlePlusUserId;
}
public function getGooglePlusUserId()
{
return $this->googlePlusUserId;
}
public function setRelatedPlaylists(Google_Service_YouTube_ChannelContentDetailsRelatedPlaylists $relatedPlaylists)
{
$this->relatedPlaylists = $relatedPlaylists;
}
public function getRelatedPlaylists()
{
return $this->relatedPlaylists;
}
}
class Google_Service_YouTube_ChannelContentDetailsRelatedPlaylists extends Google_Model
{
public $favorites;
public $likes;
public $uploads;
public $watchHistory;
public $watchLater;
public function setFavorites($favorites)
{
$this->favorites = $favorites;
}
public function getFavorites()
{
return $this->favorites;
}
public function setLikes($likes)
{
$this->likes = $likes;
}
public function getLikes()
{
return $this->likes;
}
public function setUploads($uploads)
{
$this->uploads = $uploads;
}
public function getUploads()
{
return $this->uploads;
}
public function setWatchHistory($watchHistory)
{
$this->watchHistory = $watchHistory;
}
public function getWatchHistory()
{
return $this->watchHistory;
}
public function setWatchLater($watchLater)
{
$this->watchLater = $watchLater;
}
public function getWatchLater()
{
return $this->watchLater;
}
}
class Google_Service_YouTube_ChannelContentOwnerDetails extends Google_Model
{
public $contentOwner;
public $timeLinked;
public function setContentOwner($contentOwner)
{
$this->contentOwner = $contentOwner;
}
public function getContentOwner()
{
return $this->contentOwner;
}
public function setTimeLinked($timeLinked)
{
$this->timeLinked = $timeLinked;
}
public function getTimeLinked()
{
return $this->timeLinked;
}
}
class Google_Service_YouTube_ChannelConversionPing extends Google_Model
{
public $context;
public $conversionUrl;
public function setContext($context)
{
$this->context = $context;
}
public function getContext()
{
return $this->context;
}
public function setConversionUrl($conversionUrl)
{
$this->conversionUrl = $conversionUrl;
}
public function getConversionUrl()
{
return $this->conversionUrl;
}
}
class Google_Service_YouTube_ChannelConversionPings extends Google_Collection
{
protected $pingsType = 'Google_Service_YouTube_ChannelConversionPing';
protected $pingsDataType = 'array';
public function setPings($pings)
{
$this->pings = $pings;
}
public function getPings()
{
return $this->pings;
}
}
class Google_Service_YouTube_ChannelListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_Channel';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_ChannelSection extends Google_Model
{
protected $contentDetailsType = 'Google_Service_YouTube_ChannelSectionContentDetails';
protected $contentDetailsDataType = '';
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_ChannelSectionSnippet';
protected $snippetDataType = '';
public function setContentDetails(Google_Service_YouTube_ChannelSectionContentDetails $contentDetails)
{
$this->contentDetails = $contentDetails;
}
public function getContentDetails()
{
return $this->contentDetails;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_ChannelSectionSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
}
class Google_Service_YouTube_ChannelSectionContentDetails extends Google_Collection
{
public $channels;
public $playlists;
public function setChannels($channels)
{
$this->channels = $channels;
}
public function getChannels()
{
return $this->channels;
}
public function setPlaylists($playlists)
{
$this->playlists = $playlists;
}
public function getPlaylists()
{
return $this->playlists;
}
}
class Google_Service_YouTube_ChannelSectionListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_ChannelSection';
protected $itemsDataType = 'array';
public $kind;
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_ChannelSectionSnippet extends Google_Model
{
public $channelId;
public $position;
public $style;
public $title;
public $type;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setPosition($position)
{
$this->position = $position;
}
public function getPosition()
{
return $this->position;
}
public function setStyle($style)
{
$this->style = $style;
}
public function getStyle()
{
return $this->style;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_YouTube_ChannelSettings extends Google_Collection
{
public $defaultTab;
public $description;
public $featuredChannelsTitle;
public $featuredChannelsUrls;
public $keywords;
public $moderateComments;
public $profileColor;
public $showBrowseView;
public $showRelatedChannels;
public $title;
public $trackingAnalyticsAccountId;
public $unsubscribedTrailer;
public function setDefaultTab($defaultTab)
{
$this->defaultTab = $defaultTab;
}
public function getDefaultTab()
{
return $this->defaultTab;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setFeaturedChannelsTitle($featuredChannelsTitle)
{
$this->featuredChannelsTitle = $featuredChannelsTitle;
}
public function getFeaturedChannelsTitle()
{
return $this->featuredChannelsTitle;
}
public function setFeaturedChannelsUrls($featuredChannelsUrls)
{
$this->featuredChannelsUrls = $featuredChannelsUrls;
}
public function getFeaturedChannelsUrls()
{
return $this->featuredChannelsUrls;
}
public function setKeywords($keywords)
{
$this->keywords = $keywords;
}
public function getKeywords()
{
return $this->keywords;
}
public function setModerateComments($moderateComments)
{
$this->moderateComments = $moderateComments;
}
public function getModerateComments()
{
return $this->moderateComments;
}
public function setProfileColor($profileColor)
{
$this->profileColor = $profileColor;
}
public function getProfileColor()
{
return $this->profileColor;
}
public function setShowBrowseView($showBrowseView)
{
$this->showBrowseView = $showBrowseView;
}
public function getShowBrowseView()
{
return $this->showBrowseView;
}
public function setShowRelatedChannels($showRelatedChannels)
{
$this->showRelatedChannels = $showRelatedChannels;
}
public function getShowRelatedChannels()
{
return $this->showRelatedChannels;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function setTrackingAnalyticsAccountId($trackingAnalyticsAccountId)
{
$this->trackingAnalyticsAccountId = $trackingAnalyticsAccountId;
}
public function getTrackingAnalyticsAccountId()
{
return $this->trackingAnalyticsAccountId;
}
public function setUnsubscribedTrailer($unsubscribedTrailer)
{
$this->unsubscribedTrailer = $unsubscribedTrailer;
}
public function getUnsubscribedTrailer()
{
return $this->unsubscribedTrailer;
}
}
class Google_Service_YouTube_ChannelSnippet extends Google_Model
{
public $description;
public $publishedAt;
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
}
public function getPublishedAt()
{
return $this->publishedAt;
}
public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
{
$this->thumbnails = $thumbnails;
}
public function getThumbnails()
{
return $this->thumbnails;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_ChannelStatistics extends Google_Model
{
public $commentCount;
public $hiddenSubscriberCount;
public $subscriberCount;
public $videoCount;
public $viewCount;
public function setCommentCount($commentCount)
{
$this->commentCount = $commentCount;
}
public function getCommentCount()
{
return $this->commentCount;
}
public function setHiddenSubscriberCount($hiddenSubscriberCount)
{
$this->hiddenSubscriberCount = $hiddenSubscriberCount;
}
public function getHiddenSubscriberCount()
{
return $this->hiddenSubscriberCount;
}
public function setSubscriberCount($subscriberCount)
{
$this->subscriberCount = $subscriberCount;
}
public function getSubscriberCount()
{
return $this->subscriberCount;
}
public function setVideoCount($videoCount)
{
$this->videoCount = $videoCount;
}
public function getVideoCount()
{
return $this->videoCount;
}
public function setViewCount($viewCount)
{
$this->viewCount = $viewCount;
}
public function getViewCount()
{
return $this->viewCount;
}
}
class Google_Service_YouTube_ChannelStatus extends Google_Model
{
public $isLinked;
public $privacyStatus;
public function setIsLinked($isLinked)
{
$this->isLinked = $isLinked;
}
public function getIsLinked()
{
return $this->isLinked;
}
public function setPrivacyStatus($privacyStatus)
{
$this->privacyStatus = $privacyStatus;
}
public function getPrivacyStatus()
{
return $this->privacyStatus;
}
}
class Google_Service_YouTube_ChannelTopicDetails extends Google_Collection
{
public $topicIds;
public function setTopicIds($topicIds)
{
$this->topicIds = $topicIds;
}
public function getTopicIds()
{
return $this->topicIds;
}
}
class Google_Service_YouTube_ContentRating extends Google_Model
{
public $acbRating;
public $agcomRating;
public $anatelRating;
public $bbfcRating;
public $bfvcRating;
public $bmukkRating;
public $catvRating;
public $catvfrRating;
public $cbfcRating;
public $cccRating;
public $cceRating;
public $chfilmRating;
public $chvrsRating;
public $cicfRating;
public $cnaRating;
public $csaRating;
public $cscfRating;
public $czfilmRating;
public $djctqRating;
public $eefilmRating;
public $egfilmRating;
public $eirinRating;
public $fcbmRating;
public $fcoRating;
public $fmocRating;
public $fpbRating;
public $fskRating;
public $grfilmRating;
public $icaaRating;
public $ifcoRating;
public $ilfilmRating;
public $incaaRating;
public $kfcbRating;
public $kijkwijzerRating;
public $kmrbRating;
public $lsfRating;
public $mccaaRating;
public $mccypRating;
public $mdaRating;
public $medietilsynetRating;
public $mekuRating;
public $mibacRating;
public $mocRating;
public $moctwRating;
public $mpaaRating;
public $mtrcbRating;
public $nbcRating;
public $nbcplRating;
public $nfrcRating;
public $nfvcbRating;
public $nkclvRating;
public $oflcRating;
public $pefilmRating;
public $rcnofRating;
public $resorteviolenciaRating;
public $rtcRating;
public $rteRating;
public $russiaRating;
public $skfilmRating;
public $smaisRating;
public $smsaRating;
public $tvpgRating;
public $ytRating;
public function setAcbRating($acbRating)
{
$this->acbRating = $acbRating;
}
public function getAcbRating()
{
return $this->acbRating;
}
public function setAgcomRating($agcomRating)
{
$this->agcomRating = $agcomRating;
}
public function getAgcomRating()
{
return $this->agcomRating;
}
public function setAnatelRating($anatelRating)
{
$this->anatelRating = $anatelRating;
}
public function getAnatelRating()
{
return $this->anatelRating;
}
public function setBbfcRating($bbfcRating)
{
$this->bbfcRating = $bbfcRating;
}
public function getBbfcRating()
{
return $this->bbfcRating;
}
public function setBfvcRating($bfvcRating)
{
$this->bfvcRating = $bfvcRating;
}
public function getBfvcRating()
{
return $this->bfvcRating;
}
public function setBmukkRating($bmukkRating)
{
$this->bmukkRating = $bmukkRating;
}
public function getBmukkRating()
{
return $this->bmukkRating;
}
public function setCatvRating($catvRating)
{
$this->catvRating = $catvRating;
}
public function getCatvRating()
{
return $this->catvRating;
}
public function setCatvfrRating($catvfrRating)
{
$this->catvfrRating = $catvfrRating;
}
public function getCatvfrRating()
{
return $this->catvfrRating;
}
public function setCbfcRating($cbfcRating)
{
$this->cbfcRating = $cbfcRating;
}
public function getCbfcRating()
{
return $this->cbfcRating;
}
public function setCccRating($cccRating)
{
$this->cccRating = $cccRating;
}
public function getCccRating()
{
return $this->cccRating;
}
public function setCceRating($cceRating)
{
$this->cceRating = $cceRating;
}
public function getCceRating()
{
return $this->cceRating;
}
public function setChfilmRating($chfilmRating)
{
$this->chfilmRating = $chfilmRating;
}
public function getChfilmRating()
{
return $this->chfilmRating;
}
public function setChvrsRating($chvrsRating)
{
$this->chvrsRating = $chvrsRating;
}
public function getChvrsRating()
{
return $this->chvrsRating;
}
public function setCicfRating($cicfRating)
{
$this->cicfRating = $cicfRating;
}
public function getCicfRating()
{
return $this->cicfRating;
}
public function setCnaRating($cnaRating)
{
$this->cnaRating = $cnaRating;
}
public function getCnaRating()
{
return $this->cnaRating;
}
public function setCsaRating($csaRating)
{
$this->csaRating = $csaRating;
}
public function getCsaRating()
{
return $this->csaRating;
}
public function setCscfRating($cscfRating)
{
$this->cscfRating = $cscfRating;
}
public function getCscfRating()
{
return $this->cscfRating;
}
public function setCzfilmRating($czfilmRating)
{
$this->czfilmRating = $czfilmRating;
}
public function getCzfilmRating()
{
return $this->czfilmRating;
}
public function setDjctqRating($djctqRating)
{
$this->djctqRating = $djctqRating;
}
public function getDjctqRating()
{
return $this->djctqRating;
}
public function setEefilmRating($eefilmRating)
{
$this->eefilmRating = $eefilmRating;
}
public function getEefilmRating()
{
return $this->eefilmRating;
}
public function setEgfilmRating($egfilmRating)
{
$this->egfilmRating = $egfilmRating;
}
public function getEgfilmRating()
{
return $this->egfilmRating;
}
public function setEirinRating($eirinRating)
{
$this->eirinRating = $eirinRating;
}
public function getEirinRating()
{
return $this->eirinRating;
}
public function setFcbmRating($fcbmRating)
{
$this->fcbmRating = $fcbmRating;
}
public function getFcbmRating()
{
return $this->fcbmRating;
}
public function setFcoRating($fcoRating)
{
$this->fcoRating = $fcoRating;
}
public function getFcoRating()
{
return $this->fcoRating;
}
public function setFmocRating($fmocRating)
{
$this->fmocRating = $fmocRating;
}
public function getFmocRating()
{
return $this->fmocRating;
}
public function setFpbRating($fpbRating)
{
$this->fpbRating = $fpbRating;
}
public function getFpbRating()
{
return $this->fpbRating;
}
public function setFskRating($fskRating)
{
$this->fskRating = $fskRating;
}
public function getFskRating()
{
return $this->fskRating;
}
public function setGrfilmRating($grfilmRating)
{
$this->grfilmRating = $grfilmRating;
}
public function getGrfilmRating()
{
return $this->grfilmRating;
}
public function setIcaaRating($icaaRating)
{
$this->icaaRating = $icaaRating;
}
public function getIcaaRating()
{
return $this->icaaRating;
}
public function setIfcoRating($ifcoRating)
{
$this->ifcoRating = $ifcoRating;
}
public function getIfcoRating()
{
return $this->ifcoRating;
}
public function setIlfilmRating($ilfilmRating)
{
$this->ilfilmRating = $ilfilmRating;
}
public function getIlfilmRating()
{
return $this->ilfilmRating;
}
public function setIncaaRating($incaaRating)
{
$this->incaaRating = $incaaRating;
}
public function getIncaaRating()
{
return $this->incaaRating;
}
public function setKfcbRating($kfcbRating)
{
$this->kfcbRating = $kfcbRating;
}
public function getKfcbRating()
{
return $this->kfcbRating;
}
public function setKijkwijzerRating($kijkwijzerRating)
{
$this->kijkwijzerRating = $kijkwijzerRating;
}
public function getKijkwijzerRating()
{
return $this->kijkwijzerRating;
}
public function setKmrbRating($kmrbRating)
{
$this->kmrbRating = $kmrbRating;
}
public function getKmrbRating()
{
return $this->kmrbRating;
}
public function setLsfRating($lsfRating)
{
$this->lsfRating = $lsfRating;
}
public function getLsfRating()
{
return $this->lsfRating;
}
public function setMccaaRating($mccaaRating)
{
$this->mccaaRating = $mccaaRating;
}
public function getMccaaRating()
{
return $this->mccaaRating;
}
public function setMccypRating($mccypRating)
{
$this->mccypRating = $mccypRating;
}
public function getMccypRating()
{
return $this->mccypRating;
}
public function setMdaRating($mdaRating)
{
$this->mdaRating = $mdaRating;
}
public function getMdaRating()
{
return $this->mdaRating;
}
public function setMedietilsynetRating($medietilsynetRating)
{
$this->medietilsynetRating = $medietilsynetRating;
}
public function getMedietilsynetRating()
{
return $this->medietilsynetRating;
}
public function setMekuRating($mekuRating)
{
$this->mekuRating = $mekuRating;
}
public function getMekuRating()
{
return $this->mekuRating;
}
public function setMibacRating($mibacRating)
{
$this->mibacRating = $mibacRating;
}
public function getMibacRating()
{
return $this->mibacRating;
}
public function setMocRating($mocRating)
{
$this->mocRating = $mocRating;
}
public function getMocRating()
{
return $this->mocRating;
}
public function setMoctwRating($moctwRating)
{
$this->moctwRating = $moctwRating;
}
public function getMoctwRating()
{
return $this->moctwRating;
}
public function setMpaaRating($mpaaRating)
{
$this->mpaaRating = $mpaaRating;
}
public function getMpaaRating()
{
return $this->mpaaRating;
}
public function setMtrcbRating($mtrcbRating)
{
$this->mtrcbRating = $mtrcbRating;
}
public function getMtrcbRating()
{
return $this->mtrcbRating;
}
public function setNbcRating($nbcRating)
{
$this->nbcRating = $nbcRating;
}
public function getNbcRating()
{
return $this->nbcRating;
}
public function setNbcplRating($nbcplRating)
{
$this->nbcplRating = $nbcplRating;
}
public function getNbcplRating()
{
return $this->nbcplRating;
}
public function setNfrcRating($nfrcRating)
{
$this->nfrcRating = $nfrcRating;
}
public function getNfrcRating()
{
return $this->nfrcRating;
}
public function setNfvcbRating($nfvcbRating)
{
$this->nfvcbRating = $nfvcbRating;
}
public function getNfvcbRating()
{
return $this->nfvcbRating;
}
public function setNkclvRating($nkclvRating)
{
$this->nkclvRating = $nkclvRating;
}
public function getNkclvRating()
{
return $this->nkclvRating;
}
public function setOflcRating($oflcRating)
{
$this->oflcRating = $oflcRating;
}
public function getOflcRating()
{
return $this->oflcRating;
}
public function setPefilmRating($pefilmRating)
{
$this->pefilmRating = $pefilmRating;
}
public function getPefilmRating()
{
return $this->pefilmRating;
}
public function setRcnofRating($rcnofRating)
{
$this->rcnofRating = $rcnofRating;
}
public function getRcnofRating()
{
return $this->rcnofRating;
}
public function setResorteviolenciaRating($resorteviolenciaRating)
{
$this->resorteviolenciaRating = $resorteviolenciaRating;
}
public function getResorteviolenciaRating()
{
return $this->resorteviolenciaRating;
}
public function setRtcRating($rtcRating)
{
$this->rtcRating = $rtcRating;
}
public function getRtcRating()
{
return $this->rtcRating;
}
public function setRteRating($rteRating)
{
$this->rteRating = $rteRating;
}
public function getRteRating()
{
return $this->rteRating;
}
public function setRussiaRating($russiaRating)
{
$this->russiaRating = $russiaRating;
}
public function getRussiaRating()
{
return $this->russiaRating;
}
public function setSkfilmRating($skfilmRating)
{
$this->skfilmRating = $skfilmRating;
}
public function getSkfilmRating()
{
return $this->skfilmRating;
}
public function setSmaisRating($smaisRating)
{
$this->smaisRating = $smaisRating;
}
public function getSmaisRating()
{
return $this->smaisRating;
}
public function setSmsaRating($smsaRating)
{
$this->smsaRating = $smsaRating;
}
public function getSmsaRating()
{
return $this->smsaRating;
}
public function setTvpgRating($tvpgRating)
{
$this->tvpgRating = $tvpgRating;
}
public function getTvpgRating()
{
return $this->tvpgRating;
}
public function setYtRating($ytRating)
{
$this->ytRating = $ytRating;
}
public function getYtRating()
{
return $this->ytRating;
}
}
class Google_Service_YouTube_GeoPoint extends Google_Model
{
public $altitude;
public $latitude;
public $longitude;
public function setAltitude($altitude)
{
$this->altitude = $altitude;
}
public function getAltitude()
{
return $this->altitude;
}
public function setLatitude($latitude)
{
$this->latitude = $latitude;
}
public function getLatitude()
{
return $this->latitude;
}
public function setLongitude($longitude)
{
$this->longitude = $longitude;
}
public function getLongitude()
{
return $this->longitude;
}
}
class Google_Service_YouTube_GuideCategory extends Google_Model
{
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_GuideCategorySnippet';
protected $snippetDataType = '';
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_GuideCategorySnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
}
class Google_Service_YouTube_GuideCategoryListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_GuideCategory';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_GuideCategorySnippet extends Google_Model
{
public $channelId;
public $title;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_I18nLanguage extends Google_Model
{
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_I18nLanguageSnippet';
protected $snippetDataType = '';
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_I18nLanguageSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
}
class Google_Service_YouTube_I18nLanguageListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_I18nLanguage';
protected $itemsDataType = 'array';
public $kind;
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_I18nLanguageSnippet extends Google_Model
{
public $hl;
public $name;
public function setHl($hl)
{
$this->hl = $hl;
}
public function getHl()
{
return $this->hl;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class Google_Service_YouTube_I18nRegion extends Google_Model
{
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_I18nRegionSnippet';
protected $snippetDataType = '';
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_I18nRegionSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
}
class Google_Service_YouTube_I18nRegionListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_I18nRegion';
protected $itemsDataType = 'array';
public $kind;
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_I18nRegionSnippet extends Google_Model
{
public $gl;
public $name;
public function setGl($gl)
{
$this->gl = $gl;
}
public function getGl()
{
return $this->gl;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class Google_Service_YouTube_ImageSettings extends Google_Model
{
protected $backgroundImageUrlType = 'Google_Service_YouTube_LocalizedProperty';
protected $backgroundImageUrlDataType = '';
public $bannerExternalUrl;
public $bannerImageUrl;
public $bannerMobileExtraHdImageUrl;
public $bannerMobileHdImageUrl;
public $bannerMobileImageUrl;
public $bannerMobileLowImageUrl;
public $bannerMobileMediumHdImageUrl;
public $bannerTabletExtraHdImageUrl;
public $bannerTabletHdImageUrl;
public $bannerTabletImageUrl;
public $bannerTabletLowImageUrl;
public $bannerTvHighImageUrl;
public $bannerTvImageUrl;
public $bannerTvLowImageUrl;
public $bannerTvMediumImageUrl;
protected $largeBrandedBannerImageImapScriptType = 'Google_Service_YouTube_LocalizedProperty';
protected $largeBrandedBannerImageImapScriptDataType = '';
protected $largeBrandedBannerImageUrlType = 'Google_Service_YouTube_LocalizedProperty';
protected $largeBrandedBannerImageUrlDataType = '';
protected $smallBrandedBannerImageImapScriptType = 'Google_Service_YouTube_LocalizedProperty';
protected $smallBrandedBannerImageImapScriptDataType = '';
protected $smallBrandedBannerImageUrlType = 'Google_Service_YouTube_LocalizedProperty';
protected $smallBrandedBannerImageUrlDataType = '';
public $trackingImageUrl;
public $watchIconImageUrl;
public function setBackgroundImageUrl(Google_Service_YouTube_LocalizedProperty $backgroundImageUrl)
{
$this->backgroundImageUrl = $backgroundImageUrl;
}
public function getBackgroundImageUrl()
{
return $this->backgroundImageUrl;
}
public function setBannerExternalUrl($bannerExternalUrl)
{
$this->bannerExternalUrl = $bannerExternalUrl;
}
public function getBannerExternalUrl()
{
return $this->bannerExternalUrl;
}
public function setBannerImageUrl($bannerImageUrl)
{
$this->bannerImageUrl = $bannerImageUrl;
}
public function getBannerImageUrl()
{
return $this->bannerImageUrl;
}
public function setBannerMobileExtraHdImageUrl($bannerMobileExtraHdImageUrl)
{
$this->bannerMobileExtraHdImageUrl = $bannerMobileExtraHdImageUrl;
}
public function getBannerMobileExtraHdImageUrl()
{
return $this->bannerMobileExtraHdImageUrl;
}
public function setBannerMobileHdImageUrl($bannerMobileHdImageUrl)
{
$this->bannerMobileHdImageUrl = $bannerMobileHdImageUrl;
}
public function getBannerMobileHdImageUrl()
{
return $this->bannerMobileHdImageUrl;
}
public function setBannerMobileImageUrl($bannerMobileImageUrl)
{
$this->bannerMobileImageUrl = $bannerMobileImageUrl;
}
public function getBannerMobileImageUrl()
{
return $this->bannerMobileImageUrl;
}
public function setBannerMobileLowImageUrl($bannerMobileLowImageUrl)
{
$this->bannerMobileLowImageUrl = $bannerMobileLowImageUrl;
}
public function getBannerMobileLowImageUrl()
{
return $this->bannerMobileLowImageUrl;
}
public function setBannerMobileMediumHdImageUrl($bannerMobileMediumHdImageUrl)
{
$this->bannerMobileMediumHdImageUrl = $bannerMobileMediumHdImageUrl;
}
public function getBannerMobileMediumHdImageUrl()
{
return $this->bannerMobileMediumHdImageUrl;
}
public function setBannerTabletExtraHdImageUrl($bannerTabletExtraHdImageUrl)
{
$this->bannerTabletExtraHdImageUrl = $bannerTabletExtraHdImageUrl;
}
public function getBannerTabletExtraHdImageUrl()
{
return $this->bannerTabletExtraHdImageUrl;
}
public function setBannerTabletHdImageUrl($bannerTabletHdImageUrl)
{
$this->bannerTabletHdImageUrl = $bannerTabletHdImageUrl;
}
public function getBannerTabletHdImageUrl()
{
return $this->bannerTabletHdImageUrl;
}
public function setBannerTabletImageUrl($bannerTabletImageUrl)
{
$this->bannerTabletImageUrl = $bannerTabletImageUrl;
}
public function getBannerTabletImageUrl()
{
return $this->bannerTabletImageUrl;
}
public function setBannerTabletLowImageUrl($bannerTabletLowImageUrl)
{
$this->bannerTabletLowImageUrl = $bannerTabletLowImageUrl;
}
public function getBannerTabletLowImageUrl()
{
return $this->bannerTabletLowImageUrl;
}
public function setBannerTvHighImageUrl($bannerTvHighImageUrl)
{
$this->bannerTvHighImageUrl = $bannerTvHighImageUrl;
}
public function getBannerTvHighImageUrl()
{
return $this->bannerTvHighImageUrl;
}
public function setBannerTvImageUrl($bannerTvImageUrl)
{
$this->bannerTvImageUrl = $bannerTvImageUrl;
}
public function getBannerTvImageUrl()
{
return $this->bannerTvImageUrl;
}
public function setBannerTvLowImageUrl($bannerTvLowImageUrl)
{
$this->bannerTvLowImageUrl = $bannerTvLowImageUrl;
}
public function getBannerTvLowImageUrl()
{
return $this->bannerTvLowImageUrl;
}
public function setBannerTvMediumImageUrl($bannerTvMediumImageUrl)
{
$this->bannerTvMediumImageUrl = $bannerTvMediumImageUrl;
}
public function getBannerTvMediumImageUrl()
{
return $this->bannerTvMediumImageUrl;
}
public function setLargeBrandedBannerImageImapScript(Google_Service_YouTube_LocalizedProperty $largeBrandedBannerImageImapScript)
{
$this->largeBrandedBannerImageImapScript = $largeBrandedBannerImageImapScript;
}
public function getLargeBrandedBannerImageImapScript()
{
return $this->largeBrandedBannerImageImapScript;
}
public function setLargeBrandedBannerImageUrl(Google_Service_YouTube_LocalizedProperty $largeBrandedBannerImageUrl)
{
$this->largeBrandedBannerImageUrl = $largeBrandedBannerImageUrl;
}
public function getLargeBrandedBannerImageUrl()
{
return $this->largeBrandedBannerImageUrl;
}
public function setSmallBrandedBannerImageImapScript(Google_Service_YouTube_LocalizedProperty $smallBrandedBannerImageImapScript)
{
$this->smallBrandedBannerImageImapScript = $smallBrandedBannerImageImapScript;
}
public function getSmallBrandedBannerImageImapScript()
{
return $this->smallBrandedBannerImageImapScript;
}
public function setSmallBrandedBannerImageUrl(Google_Service_YouTube_LocalizedProperty $smallBrandedBannerImageUrl)
{
$this->smallBrandedBannerImageUrl = $smallBrandedBannerImageUrl;
}
public function getSmallBrandedBannerImageUrl()
{
return $this->smallBrandedBannerImageUrl;
}
public function setTrackingImageUrl($trackingImageUrl)
{
$this->trackingImageUrl = $trackingImageUrl;
}
public function getTrackingImageUrl()
{
return $this->trackingImageUrl;
}
public function setWatchIconImageUrl($watchIconImageUrl)
{
$this->watchIconImageUrl = $watchIconImageUrl;
}
public function getWatchIconImageUrl()
{
return $this->watchIconImageUrl;
}
}
class Google_Service_YouTube_IngestionInfo extends Google_Model
{
public $backupIngestionAddress;
public $ingestionAddress;
public $streamName;
public function setBackupIngestionAddress($backupIngestionAddress)
{
$this->backupIngestionAddress = $backupIngestionAddress;
}
public function getBackupIngestionAddress()
{
return $this->backupIngestionAddress;
}
public function setIngestionAddress($ingestionAddress)
{
$this->ingestionAddress = $ingestionAddress;
}
public function getIngestionAddress()
{
return $this->ingestionAddress;
}
public function setStreamName($streamName)
{
$this->streamName = $streamName;
}
public function getStreamName()
{
return $this->streamName;
}
}
class Google_Service_YouTube_InvideoBranding extends Google_Model
{
public $imageBytes;
public $imageUrl;
protected $positionType = 'Google_Service_YouTube_InvideoPosition';
protected $positionDataType = '';
public $targetChannelId;
protected $timingType = 'Google_Service_YouTube_InvideoTiming';
protected $timingDataType = '';
public function setImageBytes($imageBytes)
{
$this->imageBytes = $imageBytes;
}
public function getImageBytes()
{
return $this->imageBytes;
}
public function setImageUrl($imageUrl)
{
$this->imageUrl = $imageUrl;
}
public function getImageUrl()
{
return $this->imageUrl;
}
public function setPosition(Google_Service_YouTube_InvideoPosition $position)
{
$this->position = $position;
}
public function getPosition()
{
return $this->position;
}
public function setTargetChannelId($targetChannelId)
{
$this->targetChannelId = $targetChannelId;
}
public function getTargetChannelId()
{
return $this->targetChannelId;
}
public function setTiming(Google_Service_YouTube_InvideoTiming $timing)
{
$this->timing = $timing;
}
public function getTiming()
{
return $this->timing;
}
}
class Google_Service_YouTube_InvideoPosition extends Google_Model
{
public $cornerPosition;
public $type;
public function setCornerPosition($cornerPosition)
{
$this->cornerPosition = $cornerPosition;
}
public function getCornerPosition()
{
return $this->cornerPosition;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_YouTube_InvideoPromotion extends Google_Collection
{
protected $defaultTimingType = 'Google_Service_YouTube_InvideoTiming';
protected $defaultTimingDataType = '';
protected $itemsType = 'Google_Service_YouTube_PromotedItem';
protected $itemsDataType = 'array';
protected $positionType = 'Google_Service_YouTube_InvideoPosition';
protected $positionDataType = '';
public function setDefaultTiming(Google_Service_YouTube_InvideoTiming $defaultTiming)
{
$this->defaultTiming = $defaultTiming;
}
public function getDefaultTiming()
{
return $this->defaultTiming;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setPosition(Google_Service_YouTube_InvideoPosition $position)
{
$this->position = $position;
}
public function getPosition()
{
return $this->position;
}
}
class Google_Service_YouTube_InvideoTiming extends Google_Model
{
public $durationMs;
public $offsetMs;
public $type;
public function setDurationMs($durationMs)
{
$this->durationMs = $durationMs;
}
public function getDurationMs()
{
return $this->durationMs;
}
public function setOffsetMs($offsetMs)
{
$this->offsetMs = $offsetMs;
}
public function getOffsetMs()
{
return $this->offsetMs;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_YouTube_LiveBroadcast extends Google_Model
{
protected $contentDetailsType = 'Google_Service_YouTube_LiveBroadcastContentDetails';
protected $contentDetailsDataType = '';
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_LiveBroadcastSnippet';
protected $snippetDataType = '';
protected $statusType = 'Google_Service_YouTube_LiveBroadcastStatus';
protected $statusDataType = '';
public function setContentDetails(Google_Service_YouTube_LiveBroadcastContentDetails $contentDetails)
{
$this->contentDetails = $contentDetails;
}
public function getContentDetails()
{
return $this->contentDetails;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_LiveBroadcastSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
public function setStatus(Google_Service_YouTube_LiveBroadcastStatus $status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
}
class Google_Service_YouTube_LiveBroadcastContentDetails extends Google_Model
{
public $boundStreamId;
public $enableClosedCaptions;
public $enableContentEncryption;
public $enableDvr;
public $enableEmbed;
protected $monitorStreamType = 'Google_Service_YouTube_MonitorStreamInfo';
protected $monitorStreamDataType = '';
public $recordFromStart;
public $startWithSlate;
public function setBoundStreamId($boundStreamId)
{
$this->boundStreamId = $boundStreamId;
}
public function getBoundStreamId()
{
return $this->boundStreamId;
}
public function setEnableClosedCaptions($enableClosedCaptions)
{
$this->enableClosedCaptions = $enableClosedCaptions;
}
public function getEnableClosedCaptions()
{
return $this->enableClosedCaptions;
}
public function setEnableContentEncryption($enableContentEncryption)
{
$this->enableContentEncryption = $enableContentEncryption;
}
public function getEnableContentEncryption()
{
return $this->enableContentEncryption;
}
public function setEnableDvr($enableDvr)
{
$this->enableDvr = $enableDvr;
}
public function getEnableDvr()
{
return $this->enableDvr;
}
public function setEnableEmbed($enableEmbed)
{
$this->enableEmbed = $enableEmbed;
}
public function getEnableEmbed()
{
return $this->enableEmbed;
}
public function setMonitorStream(Google_Service_YouTube_MonitorStreamInfo $monitorStream)
{
$this->monitorStream = $monitorStream;
}
public function getMonitorStream()
{
return $this->monitorStream;
}
public function setRecordFromStart($recordFromStart)
{
$this->recordFromStart = $recordFromStart;
}
public function getRecordFromStart()
{
return $this->recordFromStart;
}
public function setStartWithSlate($startWithSlate)
{
$this->startWithSlate = $startWithSlate;
}
public function getStartWithSlate()
{
return $this->startWithSlate;
}
}
class Google_Service_YouTube_LiveBroadcastListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_LiveBroadcast';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_LiveBroadcastSnippet extends Google_Model
{
public $actualEndTime;
public $actualStartTime;
public $channelId;
public $description;
public $publishedAt;
public $scheduledEndTime;
public $scheduledStartTime;
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
public function setActualEndTime($actualEndTime)
{
$this->actualEndTime = $actualEndTime;
}
public function getActualEndTime()
{
return $this->actualEndTime;
}
public function setActualStartTime($actualStartTime)
{
$this->actualStartTime = $actualStartTime;
}
public function getActualStartTime()
{
return $this->actualStartTime;
}
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
}
public function getPublishedAt()
{
return $this->publishedAt;
}
public function setScheduledEndTime($scheduledEndTime)
{
$this->scheduledEndTime = $scheduledEndTime;
}
public function getScheduledEndTime()
{
return $this->scheduledEndTime;
}
public function setScheduledStartTime($scheduledStartTime)
{
$this->scheduledStartTime = $scheduledStartTime;
}
public function getScheduledStartTime()
{
return $this->scheduledStartTime;
}
public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
{
$this->thumbnails = $thumbnails;
}
public function getThumbnails()
{
return $this->thumbnails;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_LiveBroadcastStatus extends Google_Model
{
public $lifeCycleStatus;
public $privacyStatus;
public $recordingStatus;
public function setLifeCycleStatus($lifeCycleStatus)
{
$this->lifeCycleStatus = $lifeCycleStatus;
}
public function getLifeCycleStatus()
{
return $this->lifeCycleStatus;
}
public function setPrivacyStatus($privacyStatus)
{
$this->privacyStatus = $privacyStatus;
}
public function getPrivacyStatus()
{
return $this->privacyStatus;
}
public function setRecordingStatus($recordingStatus)
{
$this->recordingStatus = $recordingStatus;
}
public function getRecordingStatus()
{
return $this->recordingStatus;
}
}
class Google_Service_YouTube_LiveStream extends Google_Model
{
protected $cdnType = 'Google_Service_YouTube_CdnSettings';
protected $cdnDataType = '';
protected $contentDetailsType = 'Google_Service_YouTube_LiveStreamContentDetails';
protected $contentDetailsDataType = '';
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_LiveStreamSnippet';
protected $snippetDataType = '';
protected $statusType = 'Google_Service_YouTube_LiveStreamStatus';
protected $statusDataType = '';
public function setCdn(Google_Service_YouTube_CdnSettings $cdn)
{
$this->cdn = $cdn;
}
public function getCdn()
{
return $this->cdn;
}
public function setContentDetails(Google_Service_YouTube_LiveStreamContentDetails $contentDetails)
{
$this->contentDetails = $contentDetails;
}
public function getContentDetails()
{
return $this->contentDetails;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_LiveStreamSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
public function setStatus(Google_Service_YouTube_LiveStreamStatus $status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
}
class Google_Service_YouTube_LiveStreamContentDetails extends Google_Model
{
public $closedCaptionsIngestionUrl;
public function setClosedCaptionsIngestionUrl($closedCaptionsIngestionUrl)
{
$this->closedCaptionsIngestionUrl = $closedCaptionsIngestionUrl;
}
public function getClosedCaptionsIngestionUrl()
{
return $this->closedCaptionsIngestionUrl;
}
}
class Google_Service_YouTube_LiveStreamListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_LiveStream';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_LiveStreamSnippet extends Google_Model
{
public $channelId;
public $description;
public $publishedAt;
public $title;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
}
public function getPublishedAt()
{
return $this->publishedAt;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_LiveStreamStatus extends Google_Model
{
public $streamStatus;
public function setStreamStatus($streamStatus)
{
$this->streamStatus = $streamStatus;
}
public function getStreamStatus()
{
return $this->streamStatus;
}
}
class Google_Service_YouTube_LocalizedProperty extends Google_Collection
{
public $default;
protected $localizedType = 'Google_Service_YouTube_LocalizedString';
protected $localizedDataType = 'array';
public function setDefault($default)
{
$this->default = $default;
}
public function getDefault()
{
return $this->default;
}
public function setLocalized($localized)
{
$this->localized = $localized;
}
public function getLocalized()
{
return $this->localized;
}
}
class Google_Service_YouTube_LocalizedString extends Google_Model
{
public $language;
public $value;
public function setLanguage($language)
{
$this->language = $language;
}
public function getLanguage()
{
return $this->language;
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
}
class Google_Service_YouTube_MonitorStreamInfo extends Google_Model
{
public $broadcastStreamDelayMs;
public $embedHtml;
public $enableMonitorStream;
public function setBroadcastStreamDelayMs($broadcastStreamDelayMs)
{
$this->broadcastStreamDelayMs = $broadcastStreamDelayMs;
}
public function getBroadcastStreamDelayMs()
{
return $this->broadcastStreamDelayMs;
}
public function setEmbedHtml($embedHtml)
{
$this->embedHtml = $embedHtml;
}
public function getEmbedHtml()
{
return $this->embedHtml;
}
public function setEnableMonitorStream($enableMonitorStream)
{
$this->enableMonitorStream = $enableMonitorStream;
}
public function getEnableMonitorStream()
{
return $this->enableMonitorStream;
}
}
class Google_Service_YouTube_PageInfo extends Google_Model
{
public $resultsPerPage;
public $totalResults;
public function setResultsPerPage($resultsPerPage)
{
$this->resultsPerPage = $resultsPerPage;
}
public function getResultsPerPage()
{
return $this->resultsPerPage;
}
public function setTotalResults($totalResults)
{
$this->totalResults = $totalResults;
}
public function getTotalResults()
{
return $this->totalResults;
}
}
class Google_Service_YouTube_Playlist extends Google_Model
{
protected $contentDetailsType = 'Google_Service_YouTube_PlaylistContentDetails';
protected $contentDetailsDataType = '';
public $etag;
public $id;
public $kind;
protected $playerType = 'Google_Service_YouTube_PlaylistPlayer';
protected $playerDataType = '';
protected $snippetType = 'Google_Service_YouTube_PlaylistSnippet';
protected $snippetDataType = '';
protected $statusType = 'Google_Service_YouTube_PlaylistStatus';
protected $statusDataType = '';
public function setContentDetails(Google_Service_YouTube_PlaylistContentDetails $contentDetails)
{
$this->contentDetails = $contentDetails;
}
public function getContentDetails()
{
return $this->contentDetails;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setPlayer(Google_Service_YouTube_PlaylistPlayer $player)
{
$this->player = $player;
}
public function getPlayer()
{
return $this->player;
}
public function setSnippet(Google_Service_YouTube_PlaylistSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
public function setStatus(Google_Service_YouTube_PlaylistStatus $status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
}
class Google_Service_YouTube_PlaylistContentDetails extends Google_Model
{
public $itemCount;
public function setItemCount($itemCount)
{
$this->itemCount = $itemCount;
}
public function getItemCount()
{
return $this->itemCount;
}
}
class Google_Service_YouTube_PlaylistItem extends Google_Model
{
protected $contentDetailsType = 'Google_Service_YouTube_PlaylistItemContentDetails';
protected $contentDetailsDataType = '';
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_PlaylistItemSnippet';
protected $snippetDataType = '';
protected $statusType = 'Google_Service_YouTube_PlaylistItemStatus';
protected $statusDataType = '';
public function setContentDetails(Google_Service_YouTube_PlaylistItemContentDetails $contentDetails)
{
$this->contentDetails = $contentDetails;
}
public function getContentDetails()
{
return $this->contentDetails;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_PlaylistItemSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
public function setStatus(Google_Service_YouTube_PlaylistItemStatus $status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
}
class Google_Service_YouTube_PlaylistItemContentDetails extends Google_Model
{
public $endAt;
public $note;
public $startAt;
public $videoId;
public function setEndAt($endAt)
{
$this->endAt = $endAt;
}
public function getEndAt()
{
return $this->endAt;
}
public function setNote($note)
{
$this->note = $note;
}
public function getNote()
{
return $this->note;
}
public function setStartAt($startAt)
{
$this->startAt = $startAt;
}
public function getStartAt()
{
return $this->startAt;
}
public function setVideoId($videoId)
{
$this->videoId = $videoId;
}
public function getVideoId()
{
return $this->videoId;
}
}
class Google_Service_YouTube_PlaylistItemListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_PlaylistItem';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_PlaylistItemSnippet extends Google_Model
{
public $channelId;
public $channelTitle;
public $description;
public $playlistId;
public $position;
public $publishedAt;
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setChannelTitle($channelTitle)
{
$this->channelTitle = $channelTitle;
}
public function getChannelTitle()
{
return $this->channelTitle;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setPlaylistId($playlistId)
{
$this->playlistId = $playlistId;
}
public function getPlaylistId()
{
return $this->playlistId;
}
public function setPosition($position)
{
$this->position = $position;
}
public function getPosition()
{
return $this->position;
}
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
}
public function getPublishedAt()
{
return $this->publishedAt;
}
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
{
$this->thumbnails = $thumbnails;
}
public function getThumbnails()
{
return $this->thumbnails;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_PlaylistItemStatus extends Google_Model
{
public $privacyStatus;
public function setPrivacyStatus($privacyStatus)
{
$this->privacyStatus = $privacyStatus;
}
public function getPrivacyStatus()
{
return $this->privacyStatus;
}
}
class Google_Service_YouTube_PlaylistListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_Playlist';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_PlaylistPlayer extends Google_Model
{
public $embedHtml;
public function setEmbedHtml($embedHtml)
{
$this->embedHtml = $embedHtml;
}
public function getEmbedHtml()
{
return $this->embedHtml;
}
}
class Google_Service_YouTube_PlaylistSnippet extends Google_Collection
{
public $channelId;
public $channelTitle;
public $description;
public $publishedAt;
public $tags;
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setChannelTitle($channelTitle)
{
$this->channelTitle = $channelTitle;
}
public function getChannelTitle()
{
return $this->channelTitle;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
}
public function getPublishedAt()
{
return $this->publishedAt;
}
public function setTags($tags)
{
$this->tags = $tags;
}
public function getTags()
{
return $this->tags;
}
public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
{
$this->thumbnails = $thumbnails;
}
public function getThumbnails()
{
return $this->thumbnails;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_PlaylistStatus extends Google_Model
{
public $privacyStatus;
public function setPrivacyStatus($privacyStatus)
{
$this->privacyStatus = $privacyStatus;
}
public function getPrivacyStatus()
{
return $this->privacyStatus;
}
}
class Google_Service_YouTube_PromotedItem extends Google_Model
{
public $customMessage;
protected $idType = 'Google_Service_YouTube_PromotedItemId';
protected $idDataType = '';
public $promotedByContentOwner;
protected $timingType = 'Google_Service_YouTube_InvideoTiming';
protected $timingDataType = '';
public function setCustomMessage($customMessage)
{
$this->customMessage = $customMessage;
}
public function getCustomMessage()
{
return $this->customMessage;
}
public function setId(Google_Service_YouTube_PromotedItemId $id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setPromotedByContentOwner($promotedByContentOwner)
{
$this->promotedByContentOwner = $promotedByContentOwner;
}
public function getPromotedByContentOwner()
{
return $this->promotedByContentOwner;
}
public function setTiming(Google_Service_YouTube_InvideoTiming $timing)
{
$this->timing = $timing;
}
public function getTiming()
{
return $this->timing;
}
}
class Google_Service_YouTube_PromotedItemId extends Google_Model
{
public $recentlyUploadedBy;
public $type;
public $videoId;
public $websiteUrl;
public function setRecentlyUploadedBy($recentlyUploadedBy)
{
$this->recentlyUploadedBy = $recentlyUploadedBy;
}
public function getRecentlyUploadedBy()
{
return $this->recentlyUploadedBy;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
public function setVideoId($videoId)
{
$this->videoId = $videoId;
}
public function getVideoId()
{
return $this->videoId;
}
public function setWebsiteUrl($websiteUrl)
{
$this->websiteUrl = $websiteUrl;
}
public function getWebsiteUrl()
{
return $this->websiteUrl;
}
}
class Google_Service_YouTube_PropertyValue extends Google_Model
{
public $property;
public $value;
public function setProperty($property)
{
$this->property = $property;
}
public function getProperty()
{
return $this->property;
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
}
class Google_Service_YouTube_ResourceId extends Google_Model
{
public $channelId;
public $kind;
public $playlistId;
public $videoId;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setPlaylistId($playlistId)
{
$this->playlistId = $playlistId;
}
public function getPlaylistId()
{
return $this->playlistId;
}
public function setVideoId($videoId)
{
$this->videoId = $videoId;
}
public function getVideoId()
{
return $this->videoId;
}
}
class Google_Service_YouTube_SearchListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_SearchResult';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_SearchResult extends Google_Model
{
public $etag;
protected $idType = 'Google_Service_YouTube_ResourceId';
protected $idDataType = '';
public $kind;
protected $snippetType = 'Google_Service_YouTube_SearchResultSnippet';
protected $snippetDataType = '';
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId(Google_Service_YouTube_ResourceId $id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_SearchResultSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
}
class Google_Service_YouTube_SearchResultSnippet extends Google_Model
{
public $channelId;
public $channelTitle;
public $description;
public $liveBroadcastContent;
public $publishedAt;
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setChannelTitle($channelTitle)
{
$this->channelTitle = $channelTitle;
}
public function getChannelTitle()
{
return $this->channelTitle;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setLiveBroadcastContent($liveBroadcastContent)
{
$this->liveBroadcastContent = $liveBroadcastContent;
}
public function getLiveBroadcastContent()
{
return $this->liveBroadcastContent;
}
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
}
public function getPublishedAt()
{
return $this->publishedAt;
}
public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
{
$this->thumbnails = $thumbnails;
}
public function getThumbnails()
{
return $this->thumbnails;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_Subscription extends Google_Model
{
protected $contentDetailsType = 'Google_Service_YouTube_SubscriptionContentDetails';
protected $contentDetailsDataType = '';
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_SubscriptionSnippet';
protected $snippetDataType = '';
protected $subscriberSnippetType = 'Google_Service_YouTube_SubscriptionSubscriberSnippet';
protected $subscriberSnippetDataType = '';
public function setContentDetails(Google_Service_YouTube_SubscriptionContentDetails $contentDetails)
{
$this->contentDetails = $contentDetails;
}
public function getContentDetails()
{
return $this->contentDetails;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_SubscriptionSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
public function setSubscriberSnippet(Google_Service_YouTube_SubscriptionSubscriberSnippet $subscriberSnippet)
{
$this->subscriberSnippet = $subscriberSnippet;
}
public function getSubscriberSnippet()
{
return $this->subscriberSnippet;
}
}
class Google_Service_YouTube_SubscriptionContentDetails extends Google_Model
{
public $activityType;
public $newItemCount;
public $totalItemCount;
public function setActivityType($activityType)
{
$this->activityType = $activityType;
}
public function getActivityType()
{
return $this->activityType;
}
public function setNewItemCount($newItemCount)
{
$this->newItemCount = $newItemCount;
}
public function getNewItemCount()
{
return $this->newItemCount;
}
public function setTotalItemCount($totalItemCount)
{
$this->totalItemCount = $totalItemCount;
}
public function getTotalItemCount()
{
return $this->totalItemCount;
}
}
class Google_Service_YouTube_SubscriptionListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_Subscription';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_SubscriptionSnippet extends Google_Model
{
public $channelId;
public $channelTitle;
public $description;
public $publishedAt;
protected $resourceIdType = 'Google_Service_YouTube_ResourceId';
protected $resourceIdDataType = '';
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setChannelTitle($channelTitle)
{
$this->channelTitle = $channelTitle;
}
public function getChannelTitle()
{
return $this->channelTitle;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
}
public function getPublishedAt()
{
return $this->publishedAt;
}
public function setResourceId(Google_Service_YouTube_ResourceId $resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
{
$this->thumbnails = $thumbnails;
}
public function getThumbnails()
{
return $this->thumbnails;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_SubscriptionSubscriberSnippet extends Google_Model
{
public $channelId;
public $description;
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
{
$this->thumbnails = $thumbnails;
}
public function getThumbnails()
{
return $this->thumbnails;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_Thumbnail extends Google_Model
{
public $height;
public $url;
public $width;
public function setHeight($height)
{
$this->height = $height;
}
public function getHeight()
{
return $this->height;
}
public function setUrl($url)
{
$this->url = $url;
}
public function getUrl()
{
return $this->url;
}
public function setWidth($width)
{
$this->width = $width;
}
public function getWidth()
{
return $this->width;
}
}
class Google_Service_YouTube_ThumbnailDetails extends Google_Model
{
protected $defaultType = 'Google_Service_YouTube_Thumbnail';
protected $defaultDataType = '';
protected $highType = 'Google_Service_YouTube_Thumbnail';
protected $highDataType = '';
protected $maxresType = 'Google_Service_YouTube_Thumbnail';
protected $maxresDataType = '';
protected $mediumType = 'Google_Service_YouTube_Thumbnail';
protected $mediumDataType = '';
protected $standardType = 'Google_Service_YouTube_Thumbnail';
protected $standardDataType = '';
public function setDefault(Google_Service_YouTube_Thumbnail $default)
{
$this->default = $default;
}
public function getDefault()
{
return $this->default;
}
public function setHigh(Google_Service_YouTube_Thumbnail $high)
{
$this->high = $high;
}
public function getHigh()
{
return $this->high;
}
public function setMaxres(Google_Service_YouTube_Thumbnail $maxres)
{
$this->maxres = $maxres;
}
public function getMaxres()
{
return $this->maxres;
}
public function setMedium(Google_Service_YouTube_Thumbnail $medium)
{
$this->medium = $medium;
}
public function getMedium()
{
return $this->medium;
}
public function setStandard(Google_Service_YouTube_Thumbnail $standard)
{
$this->standard = $standard;
}
public function getStandard()
{
return $this->standard;
}
}
class Google_Service_YouTube_ThumbnailSetResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $itemsDataType = 'array';
public $kind;
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_TokenPagination extends Google_Model
{
}
class Google_Service_YouTube_Video extends Google_Model
{
protected $ageGatingType = 'Google_Service_YouTube_VideoAgeGating';
protected $ageGatingDataType = '';
protected $contentDetailsType = 'Google_Service_YouTube_VideoContentDetails';
protected $contentDetailsDataType = '';
protected $conversionPingsType = 'Google_Service_YouTube_VideoConversionPings';
protected $conversionPingsDataType = '';
public $etag;
protected $fileDetailsType = 'Google_Service_YouTube_VideoFileDetails';
protected $fileDetailsDataType = '';
public $id;
public $kind;
protected $liveStreamingDetailsType = 'Google_Service_YouTube_VideoLiveStreamingDetails';
protected $liveStreamingDetailsDataType = '';
protected $monetizationDetailsType = 'Google_Service_YouTube_VideoMonetizationDetails';
protected $monetizationDetailsDataType = '';
protected $playerType = 'Google_Service_YouTube_VideoPlayer';
protected $playerDataType = '';
protected $processingDetailsType = 'Google_Service_YouTube_VideoProcessingDetails';
protected $processingDetailsDataType = '';
protected $projectDetailsType = 'Google_Service_YouTube_VideoProjectDetails';
protected $projectDetailsDataType = '';
protected $recordingDetailsType = 'Google_Service_YouTube_VideoRecordingDetails';
protected $recordingDetailsDataType = '';
protected $snippetType = 'Google_Service_YouTube_VideoSnippet';
protected $snippetDataType = '';
protected $statisticsType = 'Google_Service_YouTube_VideoStatistics';
protected $statisticsDataType = '';
protected $statusType = 'Google_Service_YouTube_VideoStatus';
protected $statusDataType = '';
protected $suggestionsType = 'Google_Service_YouTube_VideoSuggestions';
protected $suggestionsDataType = '';
protected $topicDetailsType = 'Google_Service_YouTube_VideoTopicDetails';
protected $topicDetailsDataType = '';
public function setAgeGating(Google_Service_YouTube_VideoAgeGating $ageGating)
{
$this->ageGating = $ageGating;
}
public function getAgeGating()
{
return $this->ageGating;
}
public function setContentDetails(Google_Service_YouTube_VideoContentDetails $contentDetails)
{
$this->contentDetails = $contentDetails;
}
public function getContentDetails()
{
return $this->contentDetails;
}
public function setConversionPings(Google_Service_YouTube_VideoConversionPings $conversionPings)
{
$this->conversionPings = $conversionPings;
}
public function getConversionPings()
{
return $this->conversionPings;
}
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setFileDetails(Google_Service_YouTube_VideoFileDetails $fileDetails)
{
$this->fileDetails = $fileDetails;
}
public function getFileDetails()
{
return $this->fileDetails;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setLiveStreamingDetails(Google_Service_YouTube_VideoLiveStreamingDetails $liveStreamingDetails)
{
$this->liveStreamingDetails = $liveStreamingDetails;
}
public function getLiveStreamingDetails()
{
return $this->liveStreamingDetails;
}
public function setMonetizationDetails(Google_Service_YouTube_VideoMonetizationDetails $monetizationDetails)
{
$this->monetizationDetails = $monetizationDetails;
}
public function getMonetizationDetails()
{
return $this->monetizationDetails;
}
public function setPlayer(Google_Service_YouTube_VideoPlayer $player)
{
$this->player = $player;
}
public function getPlayer()
{
return $this->player;
}
public function setProcessingDetails(Google_Service_YouTube_VideoProcessingDetails $processingDetails)
{
$this->processingDetails = $processingDetails;
}
public function getProcessingDetails()
{
return $this->processingDetails;
}
public function setProjectDetails(Google_Service_YouTube_VideoProjectDetails $projectDetails)
{
$this->projectDetails = $projectDetails;
}
public function getProjectDetails()
{
return $this->projectDetails;
}
public function setRecordingDetails(Google_Service_YouTube_VideoRecordingDetails $recordingDetails)
{
$this->recordingDetails = $recordingDetails;
}
public function getRecordingDetails()
{
return $this->recordingDetails;
}
public function setSnippet(Google_Service_YouTube_VideoSnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
public function setStatistics(Google_Service_YouTube_VideoStatistics $statistics)
{
$this->statistics = $statistics;
}
public function getStatistics()
{
return $this->statistics;
}
public function setStatus(Google_Service_YouTube_VideoStatus $status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
public function setSuggestions(Google_Service_YouTube_VideoSuggestions $suggestions)
{
$this->suggestions = $suggestions;
}
public function getSuggestions()
{
return $this->suggestions;
}
public function setTopicDetails(Google_Service_YouTube_VideoTopicDetails $topicDetails)
{
$this->topicDetails = $topicDetails;
}
public function getTopicDetails()
{
return $this->topicDetails;
}
}
class Google_Service_YouTube_VideoAgeGating extends Google_Model
{
public $alcoholContent;
public $restricted;
public $videoGameRating;
public function setAlcoholContent($alcoholContent)
{
$this->alcoholContent = $alcoholContent;
}
public function getAlcoholContent()
{
return $this->alcoholContent;
}
public function setRestricted($restricted)
{
$this->restricted = $restricted;
}
public function getRestricted()
{
return $this->restricted;
}
public function setVideoGameRating($videoGameRating)
{
$this->videoGameRating = $videoGameRating;
}
public function getVideoGameRating()
{
return $this->videoGameRating;
}
}
class Google_Service_YouTube_VideoCategory extends Google_Model
{
public $etag;
public $id;
public $kind;
protected $snippetType = 'Google_Service_YouTube_VideoCategorySnippet';
protected $snippetDataType = '';
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSnippet(Google_Service_YouTube_VideoCategorySnippet $snippet)
{
$this->snippet = $snippet;
}
public function getSnippet()
{
return $this->snippet;
}
}
class Google_Service_YouTube_VideoCategoryListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_VideoCategory';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_VideoCategorySnippet extends Google_Model
{
public $assignable;
public $channelId;
public $title;
public function setAssignable($assignable)
{
$this->assignable = $assignable;
}
public function getAssignable()
{
return $this->assignable;
}
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_VideoContentDetails extends Google_Model
{
public $caption;
protected $contentRatingType = 'Google_Service_YouTube_ContentRating';
protected $contentRatingDataType = '';
protected $countryRestrictionType = 'Google_Service_YouTube_AccessPolicy';
protected $countryRestrictionDataType = '';
public $definition;
public $dimension;
public $duration;
public $licensedContent;
protected $regionRestrictionType = 'Google_Service_YouTube_VideoContentDetailsRegionRestriction';
protected $regionRestrictionDataType = '';
public function setCaption($caption)
{
$this->caption = $caption;
}
public function getCaption()
{
return $this->caption;
}
public function setContentRating(Google_Service_YouTube_ContentRating $contentRating)
{
$this->contentRating = $contentRating;
}
public function getContentRating()
{
return $this->contentRating;
}
public function setCountryRestriction(Google_Service_YouTube_AccessPolicy $countryRestriction)
{
$this->countryRestriction = $countryRestriction;
}
public function getCountryRestriction()
{
return $this->countryRestriction;
}
public function setDefinition($definition)
{
$this->definition = $definition;
}
public function getDefinition()
{
return $this->definition;
}
public function setDimension($dimension)
{
$this->dimension = $dimension;
}
public function getDimension()
{
return $this->dimension;
}
public function setDuration($duration)
{
$this->duration = $duration;
}
public function getDuration()
{
return $this->duration;
}
public function setLicensedContent($licensedContent)
{
$this->licensedContent = $licensedContent;
}
public function getLicensedContent()
{
return $this->licensedContent;
}
public function setRegionRestriction(Google_Service_YouTube_VideoContentDetailsRegionRestriction $regionRestriction)
{
$this->regionRestriction = $regionRestriction;
}
public function getRegionRestriction()
{
return $this->regionRestriction;
}
}
class Google_Service_YouTube_VideoContentDetailsRegionRestriction extends Google_Collection
{
public $allowed;
public $blocked;
public function setAllowed($allowed)
{
$this->allowed = $allowed;
}
public function getAllowed()
{
return $this->allowed;
}
public function setBlocked($blocked)
{
$this->blocked = $blocked;
}
public function getBlocked()
{
return $this->blocked;
}
}
class Google_Service_YouTube_VideoConversionPing extends Google_Model
{
public $context;
public $conversionUrl;
public function setContext($context)
{
$this->context = $context;
}
public function getContext()
{
return $this->context;
}
public function setConversionUrl($conversionUrl)
{
$this->conversionUrl = $conversionUrl;
}
public function getConversionUrl()
{
return $this->conversionUrl;
}
}
class Google_Service_YouTube_VideoConversionPings extends Google_Collection
{
protected $pingsType = 'Google_Service_YouTube_VideoConversionPing';
protected $pingsDataType = 'array';
public function setPings($pings)
{
$this->pings = $pings;
}
public function getPings()
{
return $this->pings;
}
}
class Google_Service_YouTube_VideoFileDetails extends Google_Collection
{
protected $audioStreamsType = 'Google_Service_YouTube_VideoFileDetailsAudioStream';
protected $audioStreamsDataType = 'array';
public $bitrateBps;
public $container;
public $creationTime;
public $durationMs;
public $fileName;
public $fileSize;
public $fileType;
protected $recordingLocationType = 'Google_Service_YouTube_GeoPoint';
protected $recordingLocationDataType = '';
protected $videoStreamsType = 'Google_Service_YouTube_VideoFileDetailsVideoStream';
protected $videoStreamsDataType = 'array';
public function setAudioStreams($audioStreams)
{
$this->audioStreams = $audioStreams;
}
public function getAudioStreams()
{
return $this->audioStreams;
}
public function setBitrateBps($bitrateBps)
{
$this->bitrateBps = $bitrateBps;
}
public function getBitrateBps()
{
return $this->bitrateBps;
}
public function setContainer($container)
{
$this->container = $container;
}
public function getContainer()
{
return $this->container;
}
public function setCreationTime($creationTime)
{
$this->creationTime = $creationTime;
}
public function getCreationTime()
{
return $this->creationTime;
}
public function setDurationMs($durationMs)
{
$this->durationMs = $durationMs;
}
public function getDurationMs()
{
return $this->durationMs;
}
public function setFileName($fileName)
{
$this->fileName = $fileName;
}
public function getFileName()
{
return $this->fileName;
}
public function setFileSize($fileSize)
{
$this->fileSize = $fileSize;
}
public function getFileSize()
{
return $this->fileSize;
}
public function setFileType($fileType)
{
$this->fileType = $fileType;
}
public function getFileType()
{
return $this->fileType;
}
public function setRecordingLocation(Google_Service_YouTube_GeoPoint $recordingLocation)
{
$this->recordingLocation = $recordingLocation;
}
public function getRecordingLocation()
{
return $this->recordingLocation;
}
public function setVideoStreams($videoStreams)
{
$this->videoStreams = $videoStreams;
}
public function getVideoStreams()
{
return $this->videoStreams;
}
}
class Google_Service_YouTube_VideoFileDetailsAudioStream extends Google_Model
{
public $bitrateBps;
public $channelCount;
public $codec;
public $vendor;
public function setBitrateBps($bitrateBps)
{
$this->bitrateBps = $bitrateBps;
}
public function getBitrateBps()
{
return $this->bitrateBps;
}
public function setChannelCount($channelCount)
{
$this->channelCount = $channelCount;
}
public function getChannelCount()
{
return $this->channelCount;
}
public function setCodec($codec)
{
$this->codec = $codec;
}
public function getCodec()
{
return $this->codec;
}
public function setVendor($vendor)
{
$this->vendor = $vendor;
}
public function getVendor()
{
return $this->vendor;
}
}
class Google_Service_YouTube_VideoFileDetailsVideoStream extends Google_Model
{
public $aspectRatio;
public $bitrateBps;
public $codec;
public $frameRateFps;
public $heightPixels;
public $rotation;
public $vendor;
public $widthPixels;
public function setAspectRatio($aspectRatio)
{
$this->aspectRatio = $aspectRatio;
}
public function getAspectRatio()
{
return $this->aspectRatio;
}
public function setBitrateBps($bitrateBps)
{
$this->bitrateBps = $bitrateBps;
}
public function getBitrateBps()
{
return $this->bitrateBps;
}
public function setCodec($codec)
{
$this->codec = $codec;
}
public function getCodec()
{
return $this->codec;
}
public function setFrameRateFps($frameRateFps)
{
$this->frameRateFps = $frameRateFps;
}
public function getFrameRateFps()
{
return $this->frameRateFps;
}
public function setHeightPixels($heightPixels)
{
$this->heightPixels = $heightPixels;
}
public function getHeightPixels()
{
return $this->heightPixels;
}
public function setRotation($rotation)
{
$this->rotation = $rotation;
}
public function getRotation()
{
return $this->rotation;
}
public function setVendor($vendor)
{
$this->vendor = $vendor;
}
public function getVendor()
{
return $this->vendor;
}
public function setWidthPixels($widthPixels)
{
$this->widthPixels = $widthPixels;
}
public function getWidthPixels()
{
return $this->widthPixels;
}
}
class Google_Service_YouTube_VideoGetRatingResponse extends Google_Collection
{
public $etag;
protected $itemsType = 'Google_Service_YouTube_VideoRating';
protected $itemsDataType = 'array';
public $kind;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
}
class Google_Service_YouTube_VideoListResponse extends Google_Collection
{
public $etag;
public $eventId;
protected $itemsType = 'Google_Service_YouTube_Video';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
protected $pageInfoType = 'Google_Service_YouTube_PageInfo';
protected $pageInfoDataType = '';
public $prevPageToken;
protected $tokenPaginationType = 'Google_Service_YouTube_TokenPagination';
protected $tokenPaginationDataType = '';
public $visitorId;
public function setEtag($etag)
{
$this->etag = $etag;
}
public function getEtag()
{
return $this->etag;
}
public function setEventId($eventId)
{
$this->eventId = $eventId;
}
public function getEventId()
{
return $this->eventId;
}
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setPageInfo(Google_Service_YouTube_PageInfo $pageInfo)
{
$this->pageInfo = $pageInfo;
}
public function getPageInfo()
{
return $this->pageInfo;
}
public function setPrevPageToken($prevPageToken)
{
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken()
{
return $this->prevPageToken;
}
public function setTokenPagination(Google_Service_YouTube_TokenPagination $tokenPagination)
{
$this->tokenPagination = $tokenPagination;
}
public function getTokenPagination()
{
return $this->tokenPagination;
}
public function setVisitorId($visitorId)
{
$this->visitorId = $visitorId;
}
public function getVisitorId()
{
return $this->visitorId;
}
}
class Google_Service_YouTube_VideoLiveStreamingDetails extends Google_Model
{
public $actualEndTime;
public $actualStartTime;
public $concurrentViewers;
public $scheduledEndTime;
public $scheduledStartTime;
public function setActualEndTime($actualEndTime)
{
$this->actualEndTime = $actualEndTime;
}
public function getActualEndTime()
{
return $this->actualEndTime;
}
public function setActualStartTime($actualStartTime)
{
$this->actualStartTime = $actualStartTime;
}
public function getActualStartTime()
{
return $this->actualStartTime;
}
public function setConcurrentViewers($concurrentViewers)
{
$this->concurrentViewers = $concurrentViewers;
}
public function getConcurrentViewers()
{
return $this->concurrentViewers;
}
public function setScheduledEndTime($scheduledEndTime)
{
$this->scheduledEndTime = $scheduledEndTime;
}
public function getScheduledEndTime()
{
return $this->scheduledEndTime;
}
public function setScheduledStartTime($scheduledStartTime)
{
$this->scheduledStartTime = $scheduledStartTime;
}
public function getScheduledStartTime()
{
return $this->scheduledStartTime;
}
}
class Google_Service_YouTube_VideoMonetizationDetails extends Google_Model
{
protected $accessType = 'Google_Service_YouTube_AccessPolicy';
protected $accessDataType = '';
public function setAccess(Google_Service_YouTube_AccessPolicy $access)
{
$this->access = $access;
}
public function getAccess()
{
return $this->access;
}
}
class Google_Service_YouTube_VideoPlayer extends Google_Model
{
public $embedHtml;
public function setEmbedHtml($embedHtml)
{
$this->embedHtml = $embedHtml;
}
public function getEmbedHtml()
{
return $this->embedHtml;
}
}
class Google_Service_YouTube_VideoProcessingDetails extends Google_Model
{
public $editorSuggestionsAvailability;
public $fileDetailsAvailability;
public $processingFailureReason;
public $processingIssuesAvailability;
protected $processingProgressType = 'Google_Service_YouTube_VideoProcessingDetailsProcessingProgress';
protected $processingProgressDataType = '';
public $processingStatus;
public $tagSuggestionsAvailability;
public $thumbnailsAvailability;
public function setEditorSuggestionsAvailability($editorSuggestionsAvailability)
{
$this->editorSuggestionsAvailability = $editorSuggestionsAvailability;
}
public function getEditorSuggestionsAvailability()
{
return $this->editorSuggestionsAvailability;
}
public function setFileDetailsAvailability($fileDetailsAvailability)
{
$this->fileDetailsAvailability = $fileDetailsAvailability;
}
public function getFileDetailsAvailability()
{
return $this->fileDetailsAvailability;
}
public function setProcessingFailureReason($processingFailureReason)
{
$this->processingFailureReason = $processingFailureReason;
}
public function getProcessingFailureReason()
{
return $this->processingFailureReason;
}
public function setProcessingIssuesAvailability($processingIssuesAvailability)
{
$this->processingIssuesAvailability = $processingIssuesAvailability;
}
public function getProcessingIssuesAvailability()
{
return $this->processingIssuesAvailability;
}
public function setProcessingProgress(Google_Service_YouTube_VideoProcessingDetailsProcessingProgress $processingProgress)
{
$this->processingProgress = $processingProgress;
}
public function getProcessingProgress()
{
return $this->processingProgress;
}
public function setProcessingStatus($processingStatus)
{
$this->processingStatus = $processingStatus;
}
public function getProcessingStatus()
{
return $this->processingStatus;
}
public function setTagSuggestionsAvailability($tagSuggestionsAvailability)
{
$this->tagSuggestionsAvailability = $tagSuggestionsAvailability;
}
public function getTagSuggestionsAvailability()
{
return $this->tagSuggestionsAvailability;
}
public function setThumbnailsAvailability($thumbnailsAvailability)
{
$this->thumbnailsAvailability = $thumbnailsAvailability;
}
public function getThumbnailsAvailability()
{
return $this->thumbnailsAvailability;
}
}
class Google_Service_YouTube_VideoProcessingDetailsProcessingProgress extends Google_Model
{
public $partsProcessed;
public $partsTotal;
public $timeLeftMs;
public function setPartsProcessed($partsProcessed)
{
$this->partsProcessed = $partsProcessed;
}
public function getPartsProcessed()
{
return $this->partsProcessed;
}
public function setPartsTotal($partsTotal)
{
$this->partsTotal = $partsTotal;
}
public function getPartsTotal()
{
return $this->partsTotal;
}
public function setTimeLeftMs($timeLeftMs)
{
$this->timeLeftMs = $timeLeftMs;
}
public function getTimeLeftMs()
{
return $this->timeLeftMs;
}
}
class Google_Service_YouTube_VideoProjectDetails extends Google_Collection
{
public $tags;
public function setTags($tags)
{
$this->tags = $tags;
}
public function getTags()
{
return $this->tags;
}
}
class Google_Service_YouTube_VideoRating extends Google_Model
{
public $rating;
public $videoId;
public function setRating($rating)
{
$this->rating = $rating;
}
public function getRating()
{
return $this->rating;
}
public function setVideoId($videoId)
{
$this->videoId = $videoId;
}
public function getVideoId()
{
return $this->videoId;
}
}
class Google_Service_YouTube_VideoRecordingDetails extends Google_Model
{
protected $locationType = 'Google_Service_YouTube_GeoPoint';
protected $locationDataType = '';
public $locationDescription;
public $recordingDate;
public function setLocation(Google_Service_YouTube_GeoPoint $location)
{
$this->location = $location;
}
public function getLocation()
{
return $this->location;
}
public function setLocationDescription($locationDescription)
{
$this->locationDescription = $locationDescription;
}
public function getLocationDescription()
{
return $this->locationDescription;
}
public function setRecordingDate($recordingDate)
{
$this->recordingDate = $recordingDate;
}
public function getRecordingDate()
{
return $this->recordingDate;
}
}
class Google_Service_YouTube_VideoSnippet extends Google_Collection
{
public $categoryId;
public $channelId;
public $channelTitle;
public $description;
public $liveBroadcastContent;
public $publishedAt;
public $tags;
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
public function setCategoryId($categoryId)
{
$this->categoryId = $categoryId;
}
public function getCategoryId()
{
return $this->categoryId;
}
public function setChannelId($channelId)
{
$this->channelId = $channelId;
}
public function getChannelId()
{
return $this->channelId;
}
public function setChannelTitle($channelTitle)
{
$this->channelTitle = $channelTitle;
}
public function getChannelTitle()
{
return $this->channelTitle;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setLiveBroadcastContent($liveBroadcastContent)
{
$this->liveBroadcastContent = $liveBroadcastContent;
}
public function getLiveBroadcastContent()
{
return $this->liveBroadcastContent;
}
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
}
public function getPublishedAt()
{
return $this->publishedAt;
}
public function setTags($tags)
{
$this->tags = $tags;
}
public function getTags()
{
return $this->tags;
}
public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
{
$this->thumbnails = $thumbnails;
}
public function getThumbnails()
{
return $this->thumbnails;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
class Google_Service_YouTube_VideoStatistics extends Google_Model
{
public $commentCount;
public $dislikeCount;
public $favoriteCount;
public $likeCount;
public $viewCount;
public function setCommentCount($commentCount)
{
$this->commentCount = $commentCount;
}
public function getCommentCount()
{
return $this->commentCount;
}
public function setDislikeCount($dislikeCount)
{
$this->dislikeCount = $dislikeCount;
}
public function getDislikeCount()
{
return $this->dislikeCount;
}
public function setFavoriteCount($favoriteCount)
{
$this->favoriteCount = $favoriteCount;
}
public function getFavoriteCount()
{
return $this->favoriteCount;
}
public function setLikeCount($likeCount)
{
$this->likeCount = $likeCount;
}
public function getLikeCount()
{
return $this->likeCount;
}
public function setViewCount($viewCount)
{
$this->viewCount = $viewCount;
}
public function getViewCount()
{
return $this->viewCount;
}
}
class Google_Service_YouTube_VideoStatus extends Google_Model
{
public $embeddable;
public $failureReason;
public $license;
public $privacyStatus;
public $publicStatsViewable;
public $publishAt;
public $rejectionReason;
public $uploadStatus;
public function setEmbeddable($embeddable)
{
$this->embeddable = $embeddable;
}
public function getEmbeddable()
{
return $this->embeddable;
}
public function setFailureReason($failureReason)
{
$this->failureReason = $failureReason;
}
public function getFailureReason()
{
return $this->failureReason;
}
public function setLicense($license)
{
$this->license = $license;
}
public function getLicense()
{
return $this->license;
}
public function setPrivacyStatus($privacyStatus)
{
$this->privacyStatus = $privacyStatus;
}
public function getPrivacyStatus()
{
return $this->privacyStatus;
}
public function setPublicStatsViewable($publicStatsViewable)
{
$this->publicStatsViewable = $publicStatsViewable;
}
public function getPublicStatsViewable()
{
return $this->publicStatsViewable;
}
public function setPublishAt($publishAt)
{
$this->publishAt = $publishAt;
}
public function getPublishAt()
{
return $this->publishAt;
}
public function setRejectionReason($rejectionReason)
{
$this->rejectionReason = $rejectionReason;
}
public function getRejectionReason()
{
return $this->rejectionReason;
}
public function setUploadStatus($uploadStatus)
{
$this->uploadStatus = $uploadStatus;
}
public function getUploadStatus()
{
return $this->uploadStatus;
}
}
class Google_Service_YouTube_VideoSuggestions extends Google_Collection
{
public $editorSuggestions;
public $processingErrors;
public $processingHints;
public $processingWarnings;
protected $tagSuggestionsType = 'Google_Service_YouTube_VideoSuggestionsTagSuggestion';
protected $tagSuggestionsDataType = 'array';
public function setEditorSuggestions($editorSuggestions)
{
$this->editorSuggestions = $editorSuggestions;
}
public function getEditorSuggestions()
{
return $this->editorSuggestions;
}
public function setProcessingErrors($processingErrors)
{
$this->processingErrors = $processingErrors;
}
public function getProcessingErrors()
{
return $this->processingErrors;
}
public function setProcessingHints($processingHints)
{
$this->processingHints = $processingHints;
}
public function getProcessingHints()
{
return $this->processingHints;
}
public function setProcessingWarnings($processingWarnings)
{
$this->processingWarnings = $processingWarnings;
}
public function getProcessingWarnings()
{
return $this->processingWarnings;
}
public function setTagSuggestions($tagSuggestions)
{
$this->tagSuggestions = $tagSuggestions;
}
public function getTagSuggestions()
{
return $this->tagSuggestions;
}
}
class Google_Service_YouTube_VideoSuggestionsTagSuggestion extends Google_Collection
{
public $categoryRestricts;
public $tag;
public function setCategoryRestricts($categoryRestricts)
{
$this->categoryRestricts = $categoryRestricts;
}
public function getCategoryRestricts()
{
return $this->categoryRestricts;
}
public function setTag($tag)
{
$this->tag = $tag;
}
public function getTag()
{
return $this->tag;
}
}
class Google_Service_YouTube_VideoTopicDetails extends Google_Collection
{
public $relevantTopicIds;
public $topicIds;
public function setRelevantTopicIds($relevantTopicIds)
{
$this->relevantTopicIds = $relevantTopicIds;
}
public function getRelevantTopicIds()
{
return $this->relevantTopicIds;
}
public function setTopicIds($topicIds)
{
$this->topicIds = $topicIds;
}
public function getTopicIds()
{
return $this->topicIds;
}
}
class Google_Service_YouTube_WatchSettings extends Google_Model
{
public $backgroundColor;
public $featuredPlaylistId;
public $textColor;
public function setBackgroundColor($backgroundColor)
{
$this->backgroundColor = $backgroundColor;
}
public function getBackgroundColor()
{
return $this->backgroundColor;
}
public function setFeaturedPlaylistId($featuredPlaylistId)
{
$this->featuredPlaylistId = $featuredPlaylistId;
}
public function getFeaturedPlaylistId()
{
return $this->featuredPlaylistId;
}
public function setTextColor($textColor)
{
$this->textColor = $textColor;
}
public function getTextColor()
{
return $this->textColor;
}
}
| bsd-3-clause |
chromium/chromium | third_party/blink/renderer/core/page/scrolling/overscroll_controller.cc | 2829 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/page/scrolling/overscroll_controller.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
#include "third_party/blink/renderer/core/style/computed_style_base_constants.h"
#include "third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/size_f.h"
namespace blink {
namespace {
// Report Overscroll if OverscrollDelta is greater than minimumOverscrollDelta
// to maintain consistency as done in the compositor.
const float kMinimumOverscrollDelta = 0.1;
void AdjustOverscroll(gfx::Vector2dF* unused_delta) {
DCHECK(unused_delta);
if (std::abs(unused_delta->x()) < kMinimumOverscrollDelta)
unused_delta->set_x(0);
if (std::abs(unused_delta->y()) < kMinimumOverscrollDelta)
unused_delta->set_y(0);
}
} // namespace
OverscrollController::OverscrollController(
const VisualViewport& visual_viewport,
ChromeClient& chrome_client)
: visual_viewport_(&visual_viewport), chrome_client_(&chrome_client) {}
void OverscrollController::Trace(Visitor* visitor) const {
visitor->Trace(visual_viewport_);
visitor->Trace(chrome_client_);
}
void OverscrollController::ResetAccumulated(bool reset_x, bool reset_y) {
if (reset_x)
accumulated_root_overscroll_.set_x(0);
if (reset_y)
accumulated_root_overscroll_.set_y(0);
}
void OverscrollController::HandleOverscroll(
const ScrollResult& scroll_result,
const gfx::PointF& position_in_root_frame,
const gfx::Vector2dF& velocity_in_root_frame) {
DCHECK(visual_viewport_);
DCHECK(chrome_client_);
gfx::Vector2dF unused_delta(scroll_result.unused_scroll_delta_x,
scroll_result.unused_scroll_delta_y);
AdjustOverscroll(&unused_delta);
gfx::Vector2dF delta_in_viewport =
gfx::ScaleVector2d(unused_delta, visual_viewport_->Scale());
gfx::Vector2dF velocity_in_viewport =
gfx::ScaleVector2d(velocity_in_root_frame, visual_viewport_->Scale());
gfx::PointF position_in_viewport =
visual_viewport_->RootFrameToViewport(position_in_root_frame);
ResetAccumulated(scroll_result.did_scroll_x, scroll_result.did_scroll_y);
if (!delta_in_viewport.IsZero()) {
accumulated_root_overscroll_ += delta_in_viewport;
chrome_client_->DidOverscroll(delta_in_viewport,
accumulated_root_overscroll_,
position_in_viewport, velocity_in_viewport);
}
}
} // namespace blink
| bsd-3-clause |
joone/chromium-crosswalk | third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp | 21339 | /*
* Copyright (c) 2010, Google Inc. All rights reserved.
* Copyright (C) 2008, 2011 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "platform/scroll/ScrollableArea.h"
#include "platform/HostWindow.h"
#include "platform/Logging.h"
#include "platform/geometry/DoubleRect.h"
#include "platform/geometry/FloatPoint.h"
#include "platform/geometry/LayoutRect.h"
#include "platform/graphics/GraphicsLayer.h"
#include "platform/scroll/ProgrammaticScrollAnimator.h"
#include "platform/scroll/ScrollbarTheme.h"
#include "wtf/PassOwnPtr.h"
#include "platform/TraceEvent.h"
static const int kPixelsPerLineStep = 40;
static const float kMinFractionToStepWhenPaging = 0.875f;
namespace blink {
struct SameSizeAsScrollableArea {
virtual ~SameSizeAsScrollableArea();
#if ENABLE(ASSERT) && ENABLE(OILPAN)
VerifyEagerFinalization verifyEager;
#endif
OwnPtrWillBeMember<void*> pointer[2];
unsigned bitfields : 16;
IntPoint origin;
};
static_assert(sizeof(ScrollableArea) == sizeof(SameSizeAsScrollableArea), "ScrollableArea should stay small");
int ScrollableArea::pixelsPerLineStep()
{
return kPixelsPerLineStep;
}
float ScrollableArea::minFractionToStepWhenPaging()
{
return kMinFractionToStepWhenPaging;
}
int ScrollableArea::maxOverlapBetweenPages()
{
static int maxOverlapBetweenPages = ScrollbarTheme::theme().maxOverlapBetweenPages();
return maxOverlapBetweenPages;
}
ScrollableArea::ScrollableArea()
: m_inLiveResize(false)
, m_scrollbarOverlayStyle(ScrollbarOverlayStyleDefault)
, m_scrollOriginChanged(false)
, m_horizontalScrollbarNeedsPaintInvalidation(false)
, m_verticalScrollbarNeedsPaintInvalidation(false)
, m_scrollCornerNeedsPaintInvalidation(false)
{
}
ScrollableArea::~ScrollableArea()
{
}
void ScrollableArea::clearScrollAnimators()
{
#if OS(MACOSX) && ENABLE(OILPAN)
if (m_scrollAnimator)
m_scrollAnimator->dispose();
#endif
m_scrollAnimator.clear();
m_programmaticScrollAnimator.clear();
}
ScrollAnimatorBase& ScrollableArea::scrollAnimator() const
{
if (!m_scrollAnimator)
m_scrollAnimator = ScrollAnimatorBase::create(const_cast<ScrollableArea*>(this));
return *m_scrollAnimator;
}
ProgrammaticScrollAnimator& ScrollableArea::programmaticScrollAnimator() const
{
if (!m_programmaticScrollAnimator)
m_programmaticScrollAnimator = ProgrammaticScrollAnimator::create(const_cast<ScrollableArea*>(this));
return *m_programmaticScrollAnimator;
}
void ScrollableArea::setScrollOrigin(const IntPoint& origin)
{
if (m_scrollOrigin != origin) {
m_scrollOrigin = origin;
m_scrollOriginChanged = true;
}
}
GraphicsLayer* ScrollableArea::layerForContainer() const
{
return layerForScrolling() ? layerForScrolling()->parent() : 0;
}
ScrollbarOrientation ScrollableArea::scrollbarOrientationFromDirection(ScrollDirectionPhysical direction) const
{
return (direction == ScrollUp || direction == ScrollDown) ? VerticalScrollbar : HorizontalScrollbar;
}
float ScrollableArea::scrollStep(ScrollGranularity granularity, ScrollbarOrientation orientation) const
{
switch (granularity) {
case ScrollByLine:
return lineStep(orientation);
case ScrollByPage:
return pageStep(orientation);
case ScrollByDocument:
return documentStep(orientation);
case ScrollByPixel:
case ScrollByPrecisePixel:
return pixelStep(orientation);
default:
ASSERT_NOT_REACHED();
return 0.0f;
}
}
ScrollResultOneDimensional ScrollableArea::userScroll(ScrollDirectionPhysical direction, ScrollGranularity granularity, float delta)
{
ScrollbarOrientation orientation = scrollbarOrientationFromDirection(direction);
if (!userInputScrollable(orientation))
return ScrollResultOneDimensional(false, delta);
cancelProgrammaticScrollAnimation();
float step = scrollStep(granularity, orientation);
if (direction == ScrollUp || direction == ScrollLeft)
delta = -delta;
return scrollAnimator().userScroll(orientation, granularity, step, delta);
}
void ScrollableArea::setScrollPosition(const DoublePoint& position, ScrollType scrollType, ScrollBehavior behavior)
{
if (behavior == ScrollBehaviorAuto)
behavior = scrollBehaviorStyle();
if (scrollType == CompositorScroll)
scrollPositionChanged(clampScrollPosition(position), CompositorScroll);
else if (scrollType == ProgrammaticScroll)
programmaticScrollHelper(position, behavior);
else if (scrollType == UserScroll)
userScrollHelper(position, behavior);
else
ASSERT_NOT_REACHED();
}
void ScrollableArea::scrollBy(const DoubleSize& delta, ScrollType type, ScrollBehavior behavior)
{
setScrollPosition(scrollPositionDouble() + delta, type, behavior);
}
void ScrollableArea::setScrollPositionSingleAxis(ScrollbarOrientation orientation, double position, ScrollType scrollType, ScrollBehavior behavior)
{
DoublePoint newPosition;
if (orientation == HorizontalScrollbar)
newPosition = DoublePoint(position, scrollAnimator().currentPosition().y());
else
newPosition = DoublePoint(scrollAnimator().currentPosition().x(), position);
// TODO(bokan): Note, this doesn't use the derived class versions since this method is currently used
// exclusively by code that adjusts the position by the scroll origin and the derived class versions
// differ on whether they take that into account or not.
ScrollableArea::setScrollPosition(newPosition, scrollType, behavior);
}
void ScrollableArea::programmaticScrollHelper(const DoublePoint& position, ScrollBehavior scrollBehavior)
{
cancelScrollAnimation();
if (scrollBehavior == ScrollBehaviorSmooth)
programmaticScrollAnimator().animateToOffset(toFloatPoint(position));
else
programmaticScrollAnimator().scrollToOffsetWithoutAnimation(toFloatPoint(position));
}
void ScrollableArea::userScrollHelper(const DoublePoint& position, ScrollBehavior scrollBehavior)
{
cancelProgrammaticScrollAnimation();
double x = userInputScrollable(HorizontalScrollbar) ? position.x() : scrollAnimator().currentPosition().x();
double y = userInputScrollable(VerticalScrollbar) ? position.y() : scrollAnimator().currentPosition().y();
// Smooth user scrolls (keyboard, wheel clicks) are handled via the userScroll method.
// TODO(bokan): The userScroll method should probably be modified to call this method
// and ScrollAnimatorBase to have a simpler animateToOffset method like the
// ProgrammaticScrollAnimator.
ASSERT(scrollBehavior == ScrollBehaviorInstant);
scrollAnimator().scrollToOffsetWithoutAnimation(FloatPoint(x, y));
}
LayoutRect ScrollableArea::scrollIntoView(const LayoutRect& rectInContent, const ScrollAlignment& alignX, const ScrollAlignment& alignY, ScrollType)
{
// TODO(bokan): This should really be implemented here but ScrollAlignment is in Core which is a dependency violation.
ASSERT_NOT_REACHED();
return LayoutRect();
}
void ScrollableArea::scrollPositionChanged(const DoublePoint& position, ScrollType scrollType)
{
TRACE_EVENT0("blink", "ScrollableArea::scrollPositionChanged");
DoublePoint oldPosition = scrollPositionDouble();
DoublePoint truncatedPosition = shouldUseIntegerScrollOffset() ? flooredIntPoint(position) : position;
// Tell the derived class to scroll its contents.
setScrollOffset(truncatedPosition, scrollType);
Scrollbar* verticalScrollbar = this->verticalScrollbar();
// Tell the scrollbars to update their thumb postions.
if (Scrollbar* horizontalScrollbar = this->horizontalScrollbar()) {
horizontalScrollbar->offsetDidChange();
if (horizontalScrollbar->isOverlayScrollbar() && !hasLayerForHorizontalScrollbar())
setScrollbarNeedsPaintInvalidation(HorizontalScrollbar);
}
if (verticalScrollbar) {
verticalScrollbar->offsetDidChange();
if (verticalScrollbar->isOverlayScrollbar() && !hasLayerForVerticalScrollbar())
setScrollbarNeedsPaintInvalidation(VerticalScrollbar);
}
if (scrollPositionDouble() != oldPosition) {
// FIXME: Pass in DoubleSize. crbug.com/414283.
scrollAnimator().notifyContentAreaScrolled(toFloatSize(scrollPositionDouble() - oldPosition));
}
scrollAnimator().setCurrentPosition(toFloatPoint(position));
}
bool ScrollableArea::scrollBehaviorFromString(const String& behaviorString, ScrollBehavior& behavior)
{
if (behaviorString == "auto")
behavior = ScrollBehaviorAuto;
else if (behaviorString == "instant")
behavior = ScrollBehaviorInstant;
else if (behaviorString == "smooth")
behavior = ScrollBehaviorSmooth;
else
return false;
return true;
}
// NOTE: Only called from Internals for testing.
void ScrollableArea::setScrollOffsetFromInternals(const IntPoint& offset)
{
scrollPositionChanged(DoublePoint(offset), ProgrammaticScroll);
}
void ScrollableArea::willStartLiveResize()
{
if (m_inLiveResize)
return;
m_inLiveResize = true;
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->willStartLiveResize();
}
void ScrollableArea::willEndLiveResize()
{
if (!m_inLiveResize)
return;
m_inLiveResize = false;
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->willEndLiveResize();
}
void ScrollableArea::contentAreaWillPaint() const
{
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->contentAreaWillPaint();
}
void ScrollableArea::mouseEnteredContentArea() const
{
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->mouseEnteredContentArea();
}
void ScrollableArea::mouseExitedContentArea() const
{
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->mouseEnteredContentArea();
}
void ScrollableArea::mouseMovedInContentArea() const
{
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->mouseMovedInContentArea();
}
void ScrollableArea::mouseEnteredScrollbar(Scrollbar& scrollbar) const
{
scrollAnimator().mouseEnteredScrollbar(scrollbar);
}
void ScrollableArea::mouseExitedScrollbar(Scrollbar& scrollbar) const
{
scrollAnimator().mouseExitedScrollbar(scrollbar);
}
void ScrollableArea::contentAreaDidShow() const
{
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->contentAreaDidShow();
}
void ScrollableArea::contentAreaDidHide() const
{
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->contentAreaDidHide();
}
void ScrollableArea::finishCurrentScrollAnimations() const
{
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->finishCurrentScrollAnimations();
}
void ScrollableArea::didAddScrollbar(Scrollbar& scrollbar, ScrollbarOrientation orientation)
{
if (orientation == VerticalScrollbar)
scrollAnimator().didAddVerticalScrollbar(scrollbar);
else
scrollAnimator().didAddHorizontalScrollbar(scrollbar);
// <rdar://problem/9797253> AppKit resets the scrollbar's style when you attach a scrollbar
setScrollbarOverlayStyle(scrollbarOverlayStyle());
}
void ScrollableArea::willRemoveScrollbar(Scrollbar& scrollbar, ScrollbarOrientation orientation)
{
if (orientation == VerticalScrollbar)
scrollAnimator().willRemoveVerticalScrollbar(scrollbar);
else
scrollAnimator().willRemoveHorizontalScrollbar(scrollbar);
}
void ScrollableArea::contentsResized()
{
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->contentsResized();
}
bool ScrollableArea::hasOverlayScrollbars() const
{
Scrollbar* vScrollbar = verticalScrollbar();
if (vScrollbar && vScrollbar->isOverlayScrollbar())
return true;
Scrollbar* hScrollbar = horizontalScrollbar();
return hScrollbar && hScrollbar->isOverlayScrollbar();
}
void ScrollableArea::setScrollbarOverlayStyle(ScrollbarOverlayStyle overlayStyle)
{
m_scrollbarOverlayStyle = overlayStyle;
if (Scrollbar* scrollbar = horizontalScrollbar()) {
ScrollbarTheme::theme().updateScrollbarOverlayStyle(*scrollbar);
setScrollbarNeedsPaintInvalidation(HorizontalScrollbar);
}
if (Scrollbar* scrollbar = verticalScrollbar()) {
ScrollbarTheme::theme().updateScrollbarOverlayStyle(*scrollbar);
setScrollbarNeedsPaintInvalidation(VerticalScrollbar);
}
}
void ScrollableArea::setScrollbarNeedsPaintInvalidation(ScrollbarOrientation orientation)
{
if (orientation == HorizontalScrollbar) {
if (GraphicsLayer* graphicsLayer = layerForHorizontalScrollbar()) {
graphicsLayer->setNeedsDisplay();
graphicsLayer->setContentsNeedsDisplay();
}
m_horizontalScrollbarNeedsPaintInvalidation = true;
} else {
if (GraphicsLayer* graphicsLayer = layerForVerticalScrollbar()) {
graphicsLayer->setNeedsDisplay();
graphicsLayer->setContentsNeedsDisplay();
}
m_verticalScrollbarNeedsPaintInvalidation = true;
}
scrollControlWasSetNeedsPaintInvalidation();
}
void ScrollableArea::setScrollCornerNeedsPaintInvalidation()
{
if (GraphicsLayer* graphicsLayer = layerForScrollCorner()) {
graphicsLayer->setNeedsDisplay();
return;
}
m_scrollCornerNeedsPaintInvalidation = true;
scrollControlWasSetNeedsPaintInvalidation();
}
bool ScrollableArea::hasLayerForHorizontalScrollbar() const
{
return layerForHorizontalScrollbar();
}
bool ScrollableArea::hasLayerForVerticalScrollbar() const
{
return layerForVerticalScrollbar();
}
bool ScrollableArea::hasLayerForScrollCorner() const
{
return layerForScrollCorner();
}
void ScrollableArea::layerForScrollingDidChange(WebCompositorAnimationTimeline* timeline)
{
if (ProgrammaticScrollAnimator* programmaticScrollAnimator = existingProgrammaticScrollAnimator())
programmaticScrollAnimator->layerForCompositedScrollingDidChange(timeline);
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->layerForCompositedScrollingDidChange(timeline);
}
bool ScrollableArea::scheduleAnimation()
{
if (HostWindow* window = hostWindow()) {
window->scheduleAnimation(widget());
return true;
}
return false;
}
void ScrollableArea::serviceScrollAnimations(double monotonicTime)
{
bool requiresAnimationService = false;
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator()) {
scrollAnimator->tickAnimation(monotonicTime);
if (scrollAnimator->hasAnimationThatRequiresService())
requiresAnimationService = true;
}
if (ProgrammaticScrollAnimator* programmaticScrollAnimator = existingProgrammaticScrollAnimator()) {
programmaticScrollAnimator->tickAnimation(monotonicTime);
if (programmaticScrollAnimator->hasAnimationThatRequiresService())
requiresAnimationService = true;
}
if (!requiresAnimationService)
deregisterForAnimation();
}
void ScrollableArea::updateCompositorScrollAnimations()
{
if (ProgrammaticScrollAnimator* programmaticScrollAnimator = existingProgrammaticScrollAnimator())
programmaticScrollAnimator->updateCompositorAnimations();
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->updateCompositorAnimations();
}
void ScrollableArea::notifyCompositorAnimationFinished(int groupId)
{
if (ProgrammaticScrollAnimator* programmaticScrollAnimator = existingProgrammaticScrollAnimator())
programmaticScrollAnimator->notifyCompositorAnimationFinished(groupId);
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->notifyCompositorAnimationFinished(groupId);
}
void ScrollableArea::notifyCompositorAnimationAborted(int groupId)
{
if (ProgrammaticScrollAnimator* programmaticScrollAnimator = existingProgrammaticScrollAnimator())
programmaticScrollAnimator->notifyCompositorAnimationAborted(groupId);
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->notifyCompositorAnimationAborted(groupId);
}
void ScrollableArea::cancelScrollAnimation()
{
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->cancelAnimation();
}
void ScrollableArea::cancelProgrammaticScrollAnimation()
{
if (ProgrammaticScrollAnimator* programmaticScrollAnimator = existingProgrammaticScrollAnimator())
programmaticScrollAnimator->cancelAnimation();
}
bool ScrollableArea::shouldScrollOnMainThread() const
{
if (GraphicsLayer* layer = layerForScrolling()) {
return layer->platformLayer()->shouldScrollOnMainThread();
}
return true;
}
DoubleRect ScrollableArea::visibleContentRectDouble(IncludeScrollbarsInRect scrollbarInclusion) const
{
return visibleContentRect(scrollbarInclusion);
}
IntRect ScrollableArea::visibleContentRect(IncludeScrollbarsInRect scrollbarInclusion) const
{
int verticalScrollbarWidth = 0;
int horizontalScrollbarHeight = 0;
if (scrollbarInclusion == IncludeScrollbars) {
if (Scrollbar* verticalBar = verticalScrollbar())
verticalScrollbarWidth = !verticalBar->isOverlayScrollbar() ? verticalBar->width() : 0;
if (Scrollbar* horizontalBar = horizontalScrollbar())
horizontalScrollbarHeight = !horizontalBar->isOverlayScrollbar() ? horizontalBar->height() : 0;
}
return IntRect(scrollPosition().x(),
scrollPosition().y(),
std::max(0, visibleWidth() + verticalScrollbarWidth),
std::max(0, visibleHeight() + horizontalScrollbarHeight));
}
IntPoint ScrollableArea::clampScrollPosition(const IntPoint& scrollPosition) const
{
return scrollPosition.shrunkTo(maximumScrollPosition()).expandedTo(minimumScrollPosition());
}
DoublePoint ScrollableArea::clampScrollPosition(const DoublePoint& scrollPosition) const
{
return scrollPosition.shrunkTo(maximumScrollPositionDouble()).expandedTo(minimumScrollPositionDouble());
}
int ScrollableArea::lineStep(ScrollbarOrientation) const
{
return pixelsPerLineStep();
}
int ScrollableArea::pageStep(ScrollbarOrientation orientation) const
{
IntRect visibleRect = visibleContentRect(IncludeScrollbars);
int length = (orientation == HorizontalScrollbar) ? visibleRect.width() : visibleRect.height();
int minPageStep = static_cast<float>(length) * minFractionToStepWhenPaging();
int pageStep = std::max(minPageStep, length - maxOverlapBetweenPages());
return std::max(pageStep, 1);
}
int ScrollableArea::documentStep(ScrollbarOrientation orientation) const
{
return scrollSize(orientation);
}
float ScrollableArea::pixelStep(ScrollbarOrientation) const
{
return 1;
}
IntSize ScrollableArea::excludeScrollbars(const IntSize& size) const
{
int verticalScrollbarWidth = 0;
int horizontalScrollbarHeight = 0;
if (Scrollbar* verticalBar = verticalScrollbar())
verticalScrollbarWidth = !verticalBar->isOverlayScrollbar() ? verticalBar->width() : 0;
if (Scrollbar* horizontalBar = horizontalScrollbar())
horizontalScrollbarHeight = !horizontalBar->isOverlayScrollbar() ? horizontalBar->height() : 0;
return IntSize(std::max(0, size.width() - verticalScrollbarWidth),
std::max(0, size.height() - horizontalScrollbarHeight));
}
DEFINE_TRACE(ScrollableArea)
{
visitor->trace(m_scrollAnimator);
visitor->trace(m_programmaticScrollAnimator);
}
} // namespace blink
| bsd-3-clause |
chromium/chromium | tools/check_grd_for_unused_strings.py | 7058 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Without any args, this simply loads the IDs out of a bunch of the Chrome GRD
files, and then checks the subset of the code that loads the strings to try
and figure out what isn't in use any more.
You can give paths to GRD files and source directories to control what is
check instead.
"""
from __future__ import print_function
import os
import re
import sys
import xml.sax
# Extra messages along the way
# 1 - Print ids that are found in sources but not in the found id set
# 2 - Files that aren't processes (don't match the source name regex)
DEBUG = 0
class GrdIDExtractor(xml.sax.handler.ContentHandler):
"""Extracts the IDs from messages in GRIT files"""
def __init__(self):
self.id_set_ = set()
def startElement(self, name, attrs):
if name == 'message':
self.id_set_.add(attrs['name'])
def allIDs(self):
"""Return all the IDs found"""
return self.id_set_.copy()
def CheckForUnusedGrdIDsInSources(grd_files, src_dirs):
"""Will collect the message ids out of the given GRD files and then scan
the source directories to try and figure out what ids are not currently
being used by any source.
grd_files:
A list of GRD files to collect the ids from.
src_dirs:
A list of directories to walk looking for source files.
"""
# Collect all the ids into a large map
all_ids = set()
file_id_map = {}
for y in grd_files:
handler = GrdIDExtractor()
xml.sax.parse(y, handler)
files_ids = handler.allIDs()
file_id_map[y] = files_ids
all_ids |= files_ids
# The regex that will be used to check sources
id_regex = re.compile('IDS_[A-Z0-9_]+')
# Make sure the regex matches every id found.
got_err = False
for x in all_ids:
match = id_regex.search(x)
if match is None:
print('ERROR: "%s" did not match our regex' % x)
got_err = True
if not match.group(0) is x:
print('ERROR: "%s" did not fully match our regex' % x)
got_err = True
if got_err:
return 1
# The regex for deciding what is a source file
src_regex = re.compile('\.(([chm])|(mm)|(cc)|(cp)|(cpp)|(xib)|(py))$')
ids_left = all_ids.copy()
# Scanning time.
for src_dir in src_dirs:
for root, dirs, files in os.walk(src_dir):
# Remove svn directories from recursion
if '.svn' in dirs:
dirs.remove('.svn')
for file in files:
if src_regex.search(file.lower()):
full_path = os.path.join(root, file)
src_file_contents = open(full_path).read()
for match in sorted(set(id_regex.findall(src_file_contents))):
if match in ids_left:
ids_left.remove(match)
if DEBUG:
if not match in all_ids:
print('%s had "%s", which was not in the found IDs' % \
(full_path, match))
elif DEBUG > 1:
full_path = os.path.join(root, file)
print('Skipping %s.' % full_path)
# Anything left?
if len(ids_left) > 0:
print('The following ids are in GRD files, but *appear* to be unused:')
for file_path, file_ids in file_id_map.iteritems():
missing = ids_left.intersection(file_ids)
if len(missing) > 0:
print(' %s:' % file_path)
print('\n'.join(' %s' % (x) for x in sorted(missing)))
return 0
def main():
# script lives in src/tools
tools_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
src_dir = os.path.dirname(tools_dir)
# Collect the args into the right buckets
src_dirs = []
grd_files = []
for arg in sys.argv[1:]:
if arg.lower().endswith('.grd') or arg.lower().endswith('.grdp'):
grd_files.append(arg)
else:
src_dirs.append(arg)
# If no GRD files were given, default them:
if len(grd_files) == 0:
ash_base_dir = os.path.join(src_dir, 'ash')
ash_shortcut_viewer_dir = os.path.join(ash_base_dir, 'shortcut_viewer')
chrome_dir = os.path.join(src_dir, 'chrome')
chrome_app_dir = os.path.join(chrome_dir, 'app')
chrome_app_res_dir = os.path.join(chrome_app_dir, 'resources')
device_base_dir = os.path.join(src_dir, 'device')
services_dir = os.path.join(src_dir, 'services')
ui_dir = os.path.join(src_dir, 'ui')
ui_strings_dir = os.path.join(ui_dir, 'strings')
ui_chromeos_dir = os.path.join(ui_dir, 'chromeos')
grd_files = [
os.path.join(ash_base_dir, 'ash_strings.grd'),
os.path.join(ash_shortcut_viewer_dir, 'shortcut_viewer_strings.grd'),
os.path.join(chrome_app_dir, 'chromium_strings.grd'),
os.path.join(chrome_app_dir, 'generated_resources.grd'),
os.path.join(chrome_app_dir, 'google_chrome_strings.grd'),
os.path.join(chrome_app_res_dir, 'locale_settings.grd'),
os.path.join(chrome_app_res_dir, 'locale_settings_chromiumos.grd'),
os.path.join(chrome_app_res_dir, 'locale_settings_google_chromeos.grd'),
os.path.join(chrome_app_res_dir, 'locale_settings_linux.grd'),
os.path.join(chrome_app_res_dir, 'locale_settings_mac.grd'),
os.path.join(chrome_app_res_dir, 'locale_settings_win.grd'),
os.path.join(chrome_app_dir, 'theme', 'theme_resources.grd'),
os.path.join(chrome_dir, 'browser', 'browser_resources.grd'),
os.path.join(chrome_dir, 'common', 'common_resources.grd'),
os.path.join(chrome_dir, 'renderer', 'resources',
'renderer_resources.grd'),
os.path.join(device_base_dir, 'bluetooth', 'bluetooth_strings.grd'),
os.path.join(device_base_dir, 'fido', 'fido_strings.grd'),
os.path.join(services_dir, 'services_strings.grd'),
os.path.join(src_dir, 'chromeos', 'chromeos_strings.grd'),
os.path.join(src_dir, 'extensions', 'strings',
'extensions_strings.grd'),
os.path.join(src_dir, 'ui', 'resources', 'ui_resources.grd'),
os.path.join(src_dir, 'ui', 'webui', 'resources',
'webui_resources.grd'),
os.path.join(ui_strings_dir, 'app_locale_settings.grd'),
os.path.join(ui_strings_dir, 'ax_strings.grd'),
os.path.join(ui_strings_dir, 'ui_strings.grd'),
os.path.join(ui_chromeos_dir, 'ui_chromeos_strings.grd'),
]
# If no source directories were given, default them:
if len(src_dirs) == 0:
src_dirs = [
os.path.join(src_dir, 'app'),
os.path.join(src_dir, 'ash'),
os.path.join(src_dir, 'chrome'),
os.path.join(src_dir, 'components'),
os.path.join(src_dir, 'content'),
os.path.join(src_dir, 'device'),
os.path.join(src_dir, 'extensions'),
os.path.join(src_dir, 'ui'),
# nsNSSCertHelper.cpp has a bunch of ids
os.path.join(src_dir, 'third_party', 'mozilla_security_manager'),
os.path.join(chrome_dir, 'installer'),
]
return CheckForUnusedGrdIDsInSources(grd_files, src_dirs)
if __name__ == '__main__':
sys.exit(main())
| bsd-3-clause |
arthuralee/react-native | Libraries/Network/fetch.js | 445 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
/* globals Headers, Request, Response */
'use strict';
// side-effectful require() to put fetch,
// Headers, Request, Response in global scope
require('whatwg-fetch');
module.exports = {fetch, Headers, Request, Response};
| bsd-3-clause |
jason-p-pickering/dhis2-persian-calendar | dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/commons/action/GetDataElementGroupAction.java | 3308 | package org.hisp.dhis.commons.action;
/*
* Copyright (c) 2004-2017, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.hisp.dhis.dataelement.DataElementGroup;
import org.hisp.dhis.dataelement.DataElementService;
import com.opensymphony.xwork2.Action;
/**
* @author Torgeir Lorange Ostby
*/
public class GetDataElementGroupAction
implements Action
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private DataElementService dataElementService;
public void setDataElementService( DataElementService dataElementService )
{
this.dataElementService = dataElementService;
}
// -------------------------------------------------------------------------
// Input & Output
// -------------------------------------------------------------------------
private Integer id;
public void setId( Integer id )
{
this.id = id;
}
private DataElementGroup dataElementGroup;
public DataElementGroup getDataElementGroup()
{
return dataElementGroup;
}
private int memberCount;
public int getMemberCount()
{
return memberCount;
}
// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute()
{
if ( id != null )
{
dataElementGroup = dataElementService.getDataElementGroup( id );
memberCount = dataElementGroup.getMembers().size();
}
return SUCCESS;
}
}
| bsd-3-clause |
joone/chromium-crosswalk | content/browser/accessibility/accessibility_tree_formatter_win.cc | 14081 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/accessibility/accessibility_tree_formatter.h"
#include <oleacc.h>
#include <stddef.h>
#include <stdint.h>
#include <string>
#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "content/browser/accessibility/accessibility_tree_formatter_utils_win.h"
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "content/browser/accessibility/browser_accessibility_win.h"
#include "third_party/iaccessible2/ia2_api_all.h"
#include "ui/base/win/atl_module.h"
namespace content {
class AccessibilityTreeFormatterWin : public AccessibilityTreeFormatter {
public:
explicit AccessibilityTreeFormatterWin();
~AccessibilityTreeFormatterWin() override;
private:
const base::FilePath::StringType GetExpectedFileSuffix() override;
const std::string GetAllowEmptyString() override;
const std::string GetAllowString() override;
const std::string GetDenyString() override;
void AddProperties(const BrowserAccessibility& node,
base::DictionaryValue* dict) override;
base::string16 ToString(const base::DictionaryValue& node) override;
};
// static
AccessibilityTreeFormatter* AccessibilityTreeFormatter::Create() {
return new AccessibilityTreeFormatterWin();
}
AccessibilityTreeFormatterWin::AccessibilityTreeFormatterWin() {
ui::win::CreateATLModuleIfNeeded();
}
AccessibilityTreeFormatterWin::~AccessibilityTreeFormatterWin() {
}
const char* ALL_ATTRIBUTES[] = {
"name",
"value",
"states",
"attributes",
"role_name",
"ia2_hypertext",
"currentValue",
"minimumValue",
"maximumValue",
"description",
"default_action",
"keyboard_shortcut",
"location",
"size",
"index_in_parent",
"n_relations",
"group_level",
"similar_items_in_group",
"position_in_group",
"table_rows",
"table_columns",
"row_index",
"column_index",
"n_characters",
"caret_offset",
"n_selections",
"selection_start",
"selection_end"
};
namespace {
base::string16 GetIA2Hypertext(BrowserAccessibilityWin& ax_object) {
base::win::ScopedBstr text_bstr;
HRESULT hr;
hr = ax_object.get_text(0, IA2_TEXT_OFFSET_LENGTH, text_bstr.Receive());
if (FAILED(hr))
return base::string16();
base::string16 ia2_hypertext(text_bstr, text_bstr.Length());
// IA2 Spec calls embedded objects hyperlinks. We stick to embeds for clarity.
LONG number_of_embeds;
hr = ax_object.get_nHyperlinks(&number_of_embeds);
if (FAILED(hr) || number_of_embeds == 0)
return ia2_hypertext;
// Replace all embedded characters with the child indices of the accessibility
// objects they refer to.
base::string16 embedded_character(1,
BrowserAccessibilityWin::kEmbeddedCharacter);
size_t character_index = 0;
size_t hypertext_index = 0;
while (hypertext_index < ia2_hypertext.length()) {
if (ia2_hypertext[hypertext_index] !=
BrowserAccessibilityWin::kEmbeddedCharacter) {
++character_index;
++hypertext_index;
continue;
}
LONG index_of_embed;
hr = ax_object.get_hyperlinkIndex(character_index, &index_of_embed);
// S_FALSE will be returned if no embedded object is found at the given
// embedded character offset. Exclude child index from such cases.
LONG child_index = -1;
if (hr == S_OK) {
DCHECK_GE(index_of_embed, 0);
base::win::ScopedComPtr<IAccessibleHyperlink> embedded_object;
hr = ax_object.get_hyperlink(
index_of_embed, embedded_object.Receive());
DCHECK(SUCCEEDED(hr));
base::win::ScopedComPtr<IAccessible2> ax_embed;
hr = embedded_object.QueryInterface(ax_embed.Receive());
DCHECK(SUCCEEDED(hr));
hr = ax_embed->get_indexInParent(&child_index);
DCHECK(SUCCEEDED(hr));
}
base::string16 child_index_str(L"<obj");
if (child_index >= 0) {
base::StringAppendF(&child_index_str, L"%d>", child_index);
} else {
base::StringAppendF(&child_index_str, L">");
}
base::ReplaceFirstSubstringAfterOffset(&ia2_hypertext, hypertext_index,
embedded_character, child_index_str);
++character_index;
hypertext_index += child_index_str.length();
--number_of_embeds;
}
DCHECK_EQ(number_of_embeds, 0);
return ia2_hypertext;
}
} // Namespace
void AccessibilityTreeFormatterWin::AddProperties(
const BrowserAccessibility& node, base::DictionaryValue* dict) {
dict->SetInteger("id", node.GetId());
BrowserAccessibilityWin* ax_object =
const_cast<BrowserAccessibility*>(&node)->ToBrowserAccessibilityWin();
DCHECK(ax_object);
VARIANT variant_self;
variant_self.vt = VT_I4;
variant_self.lVal = CHILDID_SELF;
dict->SetString("role", IAccessible2RoleToString(ax_object->ia2_role()));
base::win::ScopedBstr temp_bstr;
if (SUCCEEDED(ax_object->get_accName(variant_self, temp_bstr.Receive())))
dict->SetString("name", base::string16(temp_bstr, temp_bstr.Length()));
temp_bstr.Reset();
if (SUCCEEDED(ax_object->get_accValue(variant_self, temp_bstr.Receive())))
dict->SetString("value", base::string16(temp_bstr, temp_bstr.Length()));
temp_bstr.Reset();
std::vector<base::string16> state_strings;
int32_t ia_state = ax_object->ia_state();
// Avoid flakiness: these states depend on whether the window is focused
// and the position of the mouse cursor.
ia_state &= ~STATE_SYSTEM_HOTTRACKED;
ia_state &= ~STATE_SYSTEM_OFFSCREEN;
IAccessibleStateToStringVector(ia_state, &state_strings);
IAccessible2StateToStringVector(ax_object->ia2_state(), &state_strings);
base::ListValue* states = new base::ListValue;
for (const auto& state_string : state_strings)
states->AppendString(base::UTF16ToUTF8(state_string));
dict->Set("states", states);
const std::vector<base::string16>& ia2_attributes =
ax_object->ia2_attributes();
base::ListValue* attributes = new base::ListValue;
for (const auto& ia2_attribute : ia2_attributes)
attributes->AppendString(base::UTF16ToUTF8(ia2_attribute));
dict->Set("attributes", attributes);
dict->SetString("role_name", ax_object->role_name());
dict->SetString("ia2_hypertext", GetIA2Hypertext(*ax_object));
VARIANT currentValue;
if (ax_object->get_currentValue(¤tValue) == S_OK)
dict->SetDouble("currentValue", V_R8(¤tValue));
VARIANT minimumValue;
if (ax_object->get_minimumValue(&minimumValue) == S_OK)
dict->SetDouble("minimumValue", V_R8(&minimumValue));
VARIANT maximumValue;
if (ax_object->get_maximumValue(&maximumValue) == S_OK)
dict->SetDouble("maximumValue", V_R8(&maximumValue));
if (SUCCEEDED(ax_object->get_accDescription(variant_self,
temp_bstr.Receive()))) {
dict->SetString("description", base::string16(temp_bstr,
temp_bstr.Length()));
}
temp_bstr.Reset();
if (SUCCEEDED(ax_object->get_accDefaultAction(variant_self,
temp_bstr.Receive()))) {
dict->SetString("default_action", base::string16(temp_bstr,
temp_bstr.Length()));
}
temp_bstr.Reset();
if (SUCCEEDED(
ax_object->get_accKeyboardShortcut(variant_self, temp_bstr.Receive()))) {
dict->SetString("keyboard_shortcut", base::string16(temp_bstr,
temp_bstr.Length()));
}
temp_bstr.Reset();
if (SUCCEEDED(ax_object->get_accHelp(variant_self, temp_bstr.Receive())))
dict->SetString("help", base::string16(temp_bstr, temp_bstr.Length()));
temp_bstr.Reset();
BrowserAccessibility* root = node.manager()->GetRoot();
LONG left, top, width, height;
LONG root_left, root_top, root_width, root_height;
if (SUCCEEDED(ax_object->accLocation(
&left, &top, &width, &height, variant_self)) &&
SUCCEEDED(root->ToBrowserAccessibilityWin()->accLocation(
&root_left, &root_top, &root_width, &root_height, variant_self))) {
base::DictionaryValue* location = new base::DictionaryValue;
location->SetInteger("x", left - root_left);
location->SetInteger("y", top - root_top);
dict->Set("location", location);
base::DictionaryValue* size = new base::DictionaryValue;
size->SetInteger("width", width);
size->SetInteger("height", height);
dict->Set("size", size);
}
LONG index_in_parent;
if (SUCCEEDED(ax_object->get_indexInParent(&index_in_parent)))
dict->SetInteger("index_in_parent", index_in_parent);
LONG n_relations;
if (SUCCEEDED(ax_object->get_nRelations(&n_relations)))
dict->SetInteger("n_relations", n_relations);
LONG group_level, similar_items_in_group, position_in_group;
if (SUCCEEDED(ax_object->get_groupPosition(&group_level,
&similar_items_in_group,
&position_in_group))) {
dict->SetInteger("group_level", group_level);
dict->SetInteger("similar_items_in_group", similar_items_in_group);
dict->SetInteger("position_in_group", position_in_group);
}
LONG table_rows;
if (SUCCEEDED(ax_object->get_nRows(&table_rows)))
dict->SetInteger("table_rows", table_rows);
LONG table_columns;
if (SUCCEEDED(ax_object->get_nRows(&table_columns)))
dict->SetInteger("table_columns", table_columns);
LONG row_index;
if (SUCCEEDED(ax_object->get_rowIndex(&row_index)))
dict->SetInteger("row_index", row_index);
LONG column_index;
if (SUCCEEDED(ax_object->get_columnIndex(&column_index)))
dict->SetInteger("column_index", column_index);
LONG n_characters;
if (SUCCEEDED(ax_object->get_nCharacters(&n_characters)))
dict->SetInteger("n_characters", n_characters);
LONG caret_offset;
if (ax_object->get_caretOffset(&caret_offset) == S_OK)
dict->SetInteger("caret_offset", caret_offset);
LONG n_selections;
if (SUCCEEDED(ax_object->get_nSelections(&n_selections))) {
dict->SetInteger("n_selections", n_selections);
if (n_selections > 0) {
LONG start, end;
if (SUCCEEDED(ax_object->get_selection(0, &start, &end))) {
dict->SetInteger("selection_start", start);
dict->SetInteger("selection_end", end);
}
}
}
}
base::string16 AccessibilityTreeFormatterWin::ToString(
const base::DictionaryValue& dict) {
base::string16 line;
if (show_ids()) {
int id_value;
dict.GetInteger("id", &id_value);
WriteAttribute(true, base::IntToString16(id_value), &line);
}
base::string16 role_value;
dict.GetString("role", &role_value);
WriteAttribute(true, base::UTF16ToUTF8(role_value), &line);
for (const char* attribute_name : ALL_ATTRIBUTES) {
const base::Value* value;
if (!dict.Get(attribute_name, &value))
continue;
switch (value->GetType()) {
case base::Value::TYPE_STRING: {
base::string16 string_value;
value->GetAsString(&string_value);
WriteAttribute(false,
base::StringPrintf(L"%ls='%ls'",
base::UTF8ToUTF16(attribute_name).c_str(),
string_value.c_str()),
&line);
break;
}
case base::Value::TYPE_INTEGER: {
int int_value;
value->GetAsInteger(&int_value);
WriteAttribute(false,
base::StringPrintf(L"%ls=%d",
base::UTF8ToUTF16(
attribute_name).c_str(),
int_value),
&line);
break;
}
case base::Value::TYPE_DOUBLE: {
double double_value;
value->GetAsDouble(&double_value);
WriteAttribute(false,
base::StringPrintf(L"%ls=%.2f",
base::UTF8ToUTF16(
attribute_name).c_str(),
double_value),
&line);
break;
}
case base::Value::TYPE_LIST: {
// Currently all list values are string and are written without
// attribute names.
const base::ListValue* list_value;
value->GetAsList(&list_value);
for (base::ListValue::const_iterator it = list_value->begin();
it != list_value->end();
++it) {
base::string16 string_value;
if ((*it)->GetAsString(&string_value))
WriteAttribute(false, string_value, &line);
}
break;
}
case base::Value::TYPE_DICTIONARY: {
// Currently all dictionary values are coordinates.
// Revisit this if that changes.
const base::DictionaryValue* dict_value;
value->GetAsDictionary(&dict_value);
if (strcmp(attribute_name, "size") == 0) {
WriteAttribute(false,
FormatCoordinates("size", "width", "height",
*dict_value),
&line);
} else if (strcmp(attribute_name, "location") == 0) {
WriteAttribute(false,
FormatCoordinates("location", "x", "y", *dict_value),
&line);
}
break;
}
default:
NOTREACHED();
break;
}
}
return line;
}
const base::FilePath::StringType
AccessibilityTreeFormatterWin::GetExpectedFileSuffix() {
return FILE_PATH_LITERAL("-expected-win.txt");
}
const std::string AccessibilityTreeFormatterWin::GetAllowEmptyString() {
return "@WIN-ALLOW-EMPTY:";
}
const std::string AccessibilityTreeFormatterWin::GetAllowString() {
return "@WIN-ALLOW:";
}
const std::string AccessibilityTreeFormatterWin::GetDenyString() {
return "@WIN-DENY:";
}
} // namespace content
| bsd-3-clause |
taylorjonl/coreclr | tests/src/JIT/jit64/valuetypes/nullable/castclass/castclass/castclass014.cs | 1015 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// <Area> Nullable - CastClass </Area>
// <Title> Nullable type with castclass expr </Title>
// <Description>
// checking type of IntPtr using cast expr
// </Description>
// <RelatedBugs> </RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
using System;
internal class NullableTest
{
private static bool BoxUnboxToNQ(object o)
{
return Helper.Compare((IntPtr)(ValueType)o, Helper.Create(default(IntPtr)));
}
private static bool BoxUnboxToQ(object o)
{
return Helper.Compare((IntPtr?)(ValueType)o, Helper.Create(default(IntPtr)));
}
private static int Main()
{
IntPtr? s = Helper.Create(default(IntPtr));
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| mit |
Neurosploit/StratisBitcoinFullNode | src/Stratis.Bitcoin/Interfaces/IBlockStoreQueue.cs | 599 | using NBitcoin;
using Stratis.Bitcoin.Primitives;
namespace Stratis.Bitcoin.Interfaces
{
public interface IBlockStoreQueue : IBlockStore
{
/// <summary>Adds a block to the saving queue.</summary>
/// <param name="chainedHeaderBlock">The block and its chained header pair to be added to pending storage.</param>
void AddToPending(ChainedHeaderBlock chainedHeaderBlock);
/// <summary>The highest stored block in the block store cache or <c>null</c> if block store feature is not enabled.</summary>
ChainedHeader BlockStoreCacheTip { get; }
}
}
| mit |
XrXr/data | packages/ember-data/lib/system/store/container-instance-cache.js | 2828 | import Ember from 'ember';
/**
* The `ContainerInstanceCache` serves as a lazy cache for looking up
* instances of serializers and adapters. It has some additional logic for
* finding the 'fallback' adapter or serializer.
*
* The 'fallback' adapter or serializer is an adapter or serializer that is looked up
* when the preferred lookup fails. For example, say you try to look up `adapter:post`,
* but there is no entry (app/adapters/post.js in EmberCLI) for `adapter:post` in the registry.
*
* The `fallbacks` array passed will then be used; the first entry in the fallbacks array
* that exists in the container will then be cached for `adapter:post`. So, the next time you
* look up `adapter:post`, you'll get the `adapter:application` instance (or whatever the fallback
* was if `adapter:application` doesn't exist).
*
* @private
* @class ContainerInstanceCache
*
*/
export default function ContainerInstanceCache(container) {
this._container = container;
this._cache = Object.create(null);
}
ContainerInstanceCache.prototype = Object.create(null);
Ember.merge(ContainerInstanceCache.prototype, {
get: function(type, preferredKey, fallbacks) {
let cache = this._cache;
let preferredLookupKey = `${type}:${preferredKey}`;
if (!(preferredLookupKey in cache)) {
let instance = this.instanceFor(preferredLookupKey) || this._findInstance(type, fallbacks);
if (instance) {
cache[preferredLookupKey] = instance;
}
}
return cache[preferredLookupKey];
},
_findInstance: function(type, fallbacks) {
for (let i = 0, length = fallbacks.length; i < length; i++) {
let fallback = fallbacks[i];
let lookupKey = `${type}:${fallback}`;
let instance = this.instanceFor(lookupKey);
if (instance) {
return instance;
}
}
},
instanceFor: function(key) {
if (key === 'adapter:-rest') {
Ember.deprecate('You are currently using the default DS.RESTAdapter adapter. For Ember 2.0 the default adapter will be DS.JSONAPIAdapter. If you would like to continue using DS.RESTAdapter please create an application adapter that extends DS.RESTAdapter.');
}
let cache = this._cache;
if (!cache[key]) {
let instance = this._container.lookup(key);
if (instance) {
cache[key] = instance;
}
}
return cache[key];
},
destroy: function() {
let cache = this._cache;
let cacheEntries = Object.keys(cache);
for (let i = 0, length = cacheEntries.length; i < length; i++) {
let cacheKey = cacheEntries[i];
let cacheEntry = cache[cacheKey];
if (cacheEntry) {
cacheEntry.destroy();
}
}
this._container = null;
},
constructor: ContainerInstanceCache,
toString: function() {
return 'ContainerInstanceCache';
}
});
| mit |
edumonti/cocorico | src/Cocorico/MessageBundle/DependencyInjection/Configuration.php | 1061 | <?php
/*
* This file is part of the Cocorico package.
*
* (c) Cocolabs SAS <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cocorico\MessageBundle\DependencyInjection;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
// $treeBuilder = new TreeBuilder();
// $rootNode = $treeBuilder->root('cocorico_message');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
// return $treeBuilder;
}
}
| mit |
stevemao/mout | tests/spec/random/spec-random.js | 678 | define(['mout/random/random'], function(random){
describe('random/random', function(){
it('should use Math.random as default PRNG', function () {
expect( random.get ).toBe( Math.random );
});
it('should return the value generated by the provided PRNG', function () {
var n = 0;
random.get = function(){
return ++n % 2? 0 : 1;
};
expect( random() ).toEqual( 0 );
expect( random() ).toEqual( 1 );
expect( random() ).toEqual( 0 );
expect( random() ).toEqual( 1 );
random.get = Math.random; // reset
});
});
});
| mit |
aalfson/globalize | test/globalize/destroy_test.rb | 855 | # encoding: utf-8
require File.expand_path('../../test_helper', __FILE__)
class DestroyTest < MiniTest::Spec
describe '.destroy_all' do
before do
@posts = [Post.create(:title => 'title'), Post.create(:title => 'title')]
Globalize.with_locale(:ja) do
@posts[0].update_attributes(:title => 'タイトル1')
@posts[1].update_attributes(:title => 'タイトル2')
end
end
describe 'with conditions including translated attributes' do
it 'destroys translations' do
Post.destroy_all(:title => 'title')
assert_equal 0, Post::Translation.count
end
end
describe 'called on a relation with translated attributes' do
it 'destroys translations' do
Post.where(:title => 'title').destroy_all
assert_equal 0, Post::Translation.count
end
end
end
end
| mit |
AndyButland/Umbraco-CMS | src/umbraco.editorControls/tags/library.cs | 11287 | using System;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;
using umbraco.DataLayer;
using System.Linq;
using System.Collections.Generic;
using umbraco.interfaces;
namespace umbraco.editorControls.tags
{
public class library
{
/// <summary>
/// Gets everything (content, media, members) in Umbraco with the specified tags.
/// It returns the found nodes as:
/// <root>
/// <node><data/>...</node>
/// <node><data/>...</node>
/// etc...
/// </root>
/// </summary>
/// <param name="tags">Commaseparated tags.</param>
/// <returns>
/// A XpathNodeIterator
///</returns>
public static XPathNodeIterator getEverythingWithTags(string tags)
{
var nodes = umbraco.cms.businesslogic.Tags.Tag.GetNodesWithTags(tags);
XmlDocument xmlDoc = new XmlDocument();
XmlNode root = xmlDoc.CreateElement("root");
foreach (var n in nodes)
{
root.AppendChild(n.ToXml(xmlDoc, true));
}
xmlDoc.AppendChild(root);
return xmlDoc.CreateNavigator().Select(".");
}
/// <summary>
/// Gets all content nodes in Umbraco with the specified tag.
/// It returns the found nodes as:
/// <root>
/// <node><data/>...</node>
/// <node><data/>...</node>
/// etc...
/// </root>
/// </summary>
/// <param name="tags">Commaseparated tags.</param>
/// <returns>
/// A XpathNodeIterator
///</returns>
public static XPathNodeIterator getContentsWithTags(string tags)
{
XmlDocument xmlDoc = new XmlDocument();
var docs = umbraco.cms.businesslogic.Tags.Tag.GetDocumentsWithTags(tags);
XmlNode root = xmlDoc.CreateElement("root");
foreach(var d in docs)
{
root.AppendChild(d.ToXml(xmlDoc, true));
}
xmlDoc.AppendChild(root);
return xmlDoc.CreateNavigator().Select(".");
}
/// <summary>
/// Returns all members (does not care about groups and types) in Umbraco with the specified tag.
/// It returns the found nodes as:
/// <root>
/// <node><data/>...</node>
/// <node><data/>...</node>
/// etc...
/// </root>
/// </summary>
/// <param name="tags">Comma separated tags.</param>
/// <returns>
/// A XpathNodeIterator
///</returns>
public static XPathNodeIterator getMembersWithTags(string tags)
{
//TODO: Implement a 'real' getter to get media items.
//I ported this code to the cms assembly and noticed none of these methods actually do anything different:
// getMediaWithTags
// getMembersWithTags
//they just return CMSNodes!
var nodes = umbraco.cms.businesslogic.Tags.Tag.GetNodesWithTags(tags);
XmlDocument xmlDoc = new XmlDocument();
XmlNode root = xmlDoc.CreateElement("root");
foreach (var n in nodes)
{
root.AppendChild(n.ToXml(xmlDoc, true));
}
xmlDoc.AppendChild(root);
return xmlDoc.CreateNavigator().Select(".");
}
/// <summary>
/// Returns all media nodes in Umbraco with the specified tag.
/// It returns the found nodes as:
/// <root>
/// <node><data/>...</node>
/// <node><data/>...</node>
/// etc...
/// </root>
/// </summary>
/// <param name="tags">Commaseparated tags.</param>
/// <returns>
/// A XpathNodeIterator
///</returns>
public static XPathNodeIterator getMediaWithTags(string tags)
{
//TODO: Implement a 'real' getter to get media items.
//I ported this code to the cms assembly and noticed none of these methods actually do anything different:
// getMediaWithTags
// getMembersWithTags
//they just return CMSNodes!
var nodes = umbraco.cms.businesslogic.Tags.Tag.GetNodesWithTags(tags);
XmlDocument xmlDoc = new XmlDocument();
XmlNode root = xmlDoc.CreateElement("root");
foreach(var n in nodes)
{
root.AppendChild(n.ToXml(xmlDoc, true));
}
xmlDoc.AppendChild(root);
return xmlDoc.CreateNavigator().Select(".");
}
/// <summary>
/// Gets all tags
/// It returns the found nodes as:
/// <tags>
/// <tag id="" nodesTagged="" group="">tagname<tag>
/// etc...
/// </tags>
/// Each tag node will contain it's numeric ID, number of nodes tagged with it, and the tags group.
/// </summary>
/// <returns>
/// A XpathNodeIterator
///</returns>
public static XPathNodeIterator getAllTags()
{
string xmlVal = "<tags>\n";
var tags = umbraco.cms.businesslogic.Tags.Tag.GetTags();
foreach(var t in tags)
{
xmlVal += "<tag id=\"" + t.Id.ToString() + "\" group=\"" + t.Group + "\" nodesTagged=\"" + t.NodeCount.ToString() + "\">" + t.TagCaption + "</tag>\n";
}
xmlVal += "</tags>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlVal);
return doc.CreateNavigator().Select(".");
}
/// <summary>
/// Gets all tags in a specific group
/// It returns the found nodes as:
/// <tags>
/// <tag id="" nodesTagged="" group="">tagname<tag>
/// etc...
/// </tags>
/// Each tag node will contain it's numeric ID, number of nodes tagged with it, and the tags group.
/// </summary>
/// <returns>
/// A XpathNodeIterator
///</returns>
public static XPathNodeIterator getAllTagsInGroup(string group)
{
string xmlVal = "<tags>\n";
var tags = umbraco.cms.businesslogic.Tags.Tag.GetTags(group);
foreach (var t in tags)
{
xmlVal += "<tag id=\"" + t.Id.ToString() +"\" group=\"" + t.Group + "\" nodesTagged=\"" + t.NodeCount.ToString() + "\">" + t.TagCaption + "</tag>\n";
}
xmlVal += "</tags>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlVal);
return doc.CreateNavigator().Select(".");
}
/// <summary>
/// Gets all tags associated with a specific node ID
/// It returns the found nodes as:
/// <tags>
/// <tag id="" nodesTagged="" group="">tagname<tag>
/// etc...
/// </tags>
/// Each tag node will contain it's numeric ID, number of nodes tagged with it, and the tags group.
/// </summary>
/// <returns>
/// A XpathNodeIterator
///</returns>
public static XPathNodeIterator getTagsFromNode(string nodeId)
{
string xmlVal = "<tags>\n";
var tags = umbraco.cms.businesslogic.Tags.Tag.GetTags(int.Parse(nodeId));
foreach (var t in tags)
{
xmlVal += "<tag id=\"" + t.Id.ToString() + "\" group=\"" + t.Group + "\" nodesTagged=\"" + t.NodeCount.ToString() + "\">" + t.TagCaption + "</tag>\n";
}
xmlVal += "</tags>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlVal);
return doc.CreateNavigator().Select(".");
}
#region Obsolete
[Obsolete("use the umbraco.cms.businesslogic.Tags.Tag class instead")]
public static void addTagsToNode(int nodeId, string tags, string group)
{
umbraco.cms.businesslogic.Tags.Tag.AddTagsToNode(nodeId, tags, group);
}
[Obsolete("use the umbraco.cms.businesslogic.Tags.Tag class instead")]
public static void RemoveTagFromNode(int nodeId, string tag, string group)
{
umbraco.cms.businesslogic.Tags.Tag.RemoveTagFromNode(nodeId, tag, group);
}
[Obsolete("use the umbraco.cms.businesslogic.Tags.Tag class instead")]
public static int AddTag(string tag, string group)
{
return umbraco.cms.businesslogic.Tags.Tag.AddTag(tag, group);
}
[Obsolete("use the umbraco.cms.businesslogic.Tags.Tag class instead")]
public static int GetTagId(string tag, string group)
{
return umbraco.cms.businesslogic.Tags.Tag.GetTagId(tag, group);
}
/// <summary>
/// Gets the tags from node as ITag objects.
/// </summary>
/// <param name="nodeId">The node id.</param>
/// <returns></returns>
[Obsolete("Use the umbraco.cms.businesslogic.Tags.Tag class instead")]
public static List<umbraco.interfaces.ITag> GetTagsFromNodeAsITags(int nodeId)
{
return umbraco.cms.businesslogic.Tags.Tag.GetTags(nodeId).Cast<ITag>().ToList();
}
/// <summary>
/// Gets the tags from group as ITag objects.
/// </summary>
/// <param name="group">The group.</param>
/// <returns></returns>
[Obsolete("Use the umbraco.cms.businesslogic.Tags.Tag class instead")]
public static List<umbraco.interfaces.ITag> GetTagsFromGroupAsITags(string group)
{
return umbraco.cms.businesslogic.Tags.Tag.GetTags(group).Cast<ITag>().ToList();
}
/// <summary>
/// Gets all the tags as ITag objects
/// </summary>
/// <param name="nodeId">The node id.</param>
/// <returns></returns>
[Obsolete("Use the umbraco.cms.businesslogic.Tags.Tag class instead")]
public static List<umbraco.interfaces.ITag> GetTagsAsITags()
{
return umbraco.cms.businesslogic.Tags.Tag.GetTags().Cast<ITag>().ToList();
}
#endregion
}
[Obsolete("Use umbraco.cms.businesslogic.Tags.Tag class instead")]
public class Tag : umbraco.interfaces.ITag
{
public Tag() { }
public Tag(int id, string tag, string group)
{
Id = id;
TagCaption = tag;
Group = group;
}
#region ITag Members
public int Id
{
get;
set;
}
public string TagCaption
{
get;
set;
}
public string Group
{
get;
set;
}
#endregion
}
}
| mit |
chjj/bitcoin | src/qt/locale/bitcoin_bg.ts | 62375 | <TS language="bg" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Double-click to edit address or label</source>
<translation>Двоен клик за редакция на адрес или име</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Създаване на нов адрес</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копиране на избрания адрес</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&Копирай</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Изтрий избрания адрес от списъка</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Запишете данните от текущия раздел във файл</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Изтриване</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>Адреси за изпращане</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>Адреси за получаване</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>Копирай &име</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Редактирай</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Изнасяне на списъка с адреси</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>CSV файл (*.csv)</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Грешка при изнасянето</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Име</translation>
</message>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<source>(no label)</source>
<translation>(без име)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>Въведи парола</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Нова парола</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Още веднъж</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Криптиране на портфейла</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Тази операция изисква Вашата парола за отключване на портфейла.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Отключване на портфейла</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Тази операция изисква Вашата парола за декриптиране на портфейла.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Декриптиране на портфейла</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Смяна на паролата</translation>
</message>
<message>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Въведете текущата и новата парола за портфейла.</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Потвърждаване на криптирането</translation>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation>ВНИМАНИЕ: Ако защитите вашият портфейл и изгубите ключовата дума, вие ще <b>ИЗГУБИТЕ ВСИЧКИТЕ СИ БИТКОЙНОВЕ</b>!</translation>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Наистина ли искате да шифрирате портфейла?</translation>
</message>
<message>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>ВАЖНО: Всякакви стари бекъп версии, които сте направили на вашият портфейл трябва да бъдат заменени със ново-генерирания, криптиран портфейл файл. От съображения за сигурност, предишните бекъпи на некриптираните портфейли ще станат неизползваеми веднага щом започнете да използвате новият криптиран портфейл.</translation>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation>Внимание: Caps Lock (главни букви) е включен.</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Портфейлът е криптиран</translation>
</message>
<message>
<source>Bitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>Биткоин ще се затоври сега за да завърши процеса на криптиране. Запомнете, че криптирането на вашия портефейл не може напълно да предпази вашите Бит-монети от кражба чрез зловреден софтуер, инфектирал вашия компютър</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Криптирането беше неуспешно</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Криптирането на портфейла беше неуспешно поради неизвестен проблем. Портфейлът не е криптиран.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Паролите не съвпадат</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Отключването беше неуспешно</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Паролата въведена за декриптиране на портфейла е грешна.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Декриптирането беше неуспешно</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Паролата на портфейла беше променена успешно.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Подписване на &съобщение...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Синхронизиране с мрежата...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Баланс</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Обобщена информация за портфейла</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Трансакции</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>История на трансакциите</translation>
</message>
<message>
<source>E&xit</source>
<translation>Из&ход</translation>
</message>
<message>
<source>Quit application</source>
<translation>Изход от приложението</translation>
</message>
<message>
<source>About &Qt</source>
<translation>За &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Покажи информация за Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Опции...</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&Криптиране на портфейла...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Запазване на портфейла...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>&Смяна на паролата...</translation>
</message>
<message>
<source>Send coins to a Bitcoin address</source>
<translation>Изпращане към Биткоин адрес</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Променя паролата за портфейла</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>&Проверка на съобщение...</translation>
</message>
<message>
<source>Bitcoin</source>
<translation>Биткоин</translation>
</message>
<message>
<source>Wallet</source>
<translation>Портфейл</translation>
</message>
<message>
<source>&Send</source>
<translation>&Изпращане</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Покажи / Скрий</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Показване и скриване на основния прозорец</translation>
</message>
<message>
<source>&File</source>
<translation>&Файл</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Настройки</translation>
</message>
<message>
<source>&Help</source>
<translation>&Помощ</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Раздели</translation>
</message>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message numerus="yes">
<source>%n active connection(s) to Bitcoin network</source>
<translation><numerusform>%n връзка към Биткоин мрежата</numerusform><numerusform>%n връзки към Биткоин мрежата</numerusform></translation>
</message>
<message numerus="yes">
<source>%n hour(s)</source>
<translation><numerusform>%n час</numerusform><numerusform>%n часа</numerusform></translation>
</message>
<message numerus="yes">
<source>%n day(s)</source>
<translation><numerusform>%n ден</numerusform><numerusform>%n дни</numerusform></translation>
</message>
<message numerus="yes">
<source>%n week(s)</source>
<translation><numerusform>%n седмица</numerusform><numerusform>%n седмици</numerusform></translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 и %2</translation>
</message>
<message numerus="yes">
<source>%n year(s)</source>
<translation><numerusform>%n година</numerusform><numerusform>%n години</numerusform></translation>
</message>
<message>
<source>Error</source>
<translation>Грешка</translation>
</message>
<message>
<source>Warning</source>
<translation>Предупреждение</translation>
</message>
<message>
<source>Information</source>
<translation>Данни</translation>
</message>
<message>
<source>Up to date</source>
<translation>Синхронизиран</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Зарежда блокове...</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Изходяща трансакция</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Входяща трансакция</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Портфейлът е <b>криптиран</b> и <b>отключен</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Портфейлът е <b>криптиран</b> и <b>заключен</b></translation>
</message>
</context>
<context>
<name>ClientModel</name>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Bytes:</source>
<translation>Байтове:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Сума:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Приоритет:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Такса:</translation>
</message>
<message>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Потвърждения</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Потвърдени</translation>
</message>
<message>
<source>Priority</source>
<translation>Приоритет</translation>
</message>
<message>
<source>Copy address</source>
<translation>Копирай адрес</translation>
</message>
<message>
<source>Copy label</source>
<translation>Копирай име</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Копирай сума</translation>
</message>
<message>
<source>yes</source>
<translation>да</translation>
</message>
<message>
<source>no</source>
<translation>не</translation>
</message>
<message>
<source>(no label)</source>
<translation>(без име)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Редактиране на адрес</translation>
</message>
<message>
<source>&Label</source>
<translation>&Име</translation>
</message>
<message>
<source>&Address</source>
<translation>&Адрес</translation>
</message>
<message>
<source>New receiving address</source>
<translation>Нов адрес за получаване</translation>
</message>
<message>
<source>New sending address</source>
<translation>Нов адрес за изпращане</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Редактиране на входящ адрес</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Редактиране на изходящ адрес</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation>Вече има адрес "%1" в списъка с адреси.</translation>
</message>
<message>
<source>The entered address "%1" is not a valid Bitcoin address.</source>
<translation>"%1" не е валиден Биткоин адрес.</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Отключването на портфейла беше неуспешно.</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Създаването на ключ беше неуспешно.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation>Ще се създаде нова папка за данни.</translation>
</message>
<message>
<source>name</source>
<translation>име</translation>
</message>
<message>
<source>Path already exists, and is not a directory.</source>
<translation>Пътят вече съществува и не е папка.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>версия</translation>
</message>
<message>
<source>Usage:</source>
<translation>Използване:</translation>
</message>
<message>
<source>UI options</source>
<translation>UI Опции</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Добре дошли</translation>
</message>
<message>
<source>Error</source>
<translation>Грешка</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Опции</translation>
</message>
<message>
<source>&Main</source>
<translation>&Основни</translation>
</message>
<message>
<source>Pay transaction &fee</source>
<translation>&Такса за изходяща трансакция</translation>
</message>
<message>
<source>&Start Bitcoin on system login</source>
<translation>&Пускане на Биткоин при вход в системата</translation>
</message>
<message>
<source>&Network</source>
<translation>&Мрежа</translation>
</message>
<message>
<source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Автоматично отваряне на входящия Bitcoin порт. Работи само с рутери поддържащи UPnP.</translation>
</message>
<message>
<source>Map port using &UPnP</source>
<translation>Отваряне на входящия порт чрез &UPnP</translation>
</message>
<message>
<source>Proxy &IP:</source>
<translation>Прокси & АйПи:</translation>
</message>
<message>
<source>&Port:</source>
<translation>&Порт:</translation>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Порт на прокси сървъра (пр. 9050)</translation>
</message>
<message>
<source>&Window</source>
<translation>&Прозорец</translation>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation>След минимизиране ще е видима само иконата в системния трей.</translation>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Минимизиране в системния трей</translation>
</message>
<message>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>При затваряне на прозореца приложението остава минимизирано. Ако изберете тази опция, приложението може да се затвори само чрез Изход в менюто.</translation>
</message>
<message>
<source>M&inimize on close</source>
<translation>М&инимизиране при затваряне</translation>
</message>
<message>
<source>&Display</source>
<translation>&Интерфейс</translation>
</message>
<message>
<source>User Interface &language:</source>
<translation>Език:</translation>
</message>
<message>
<source>The user interface language can be set here. This setting will take effect after restarting Bitcoin.</source>
<translation>Промяната на езика ще влезе в сила след рестартиране на Биткоин.</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>Мерни единици:</translation>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Изберете единиците, показвани по подразбиране в интерфейса.</translation>
</message>
<message>
<source>&OK</source>
<translation>ОК</translation>
</message>
<message>
<source>&Cancel</source>
<translation>Отказ</translation>
</message>
<message>
<source>default</source>
<translation>подразбиране</translation>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation>Прокси адресът е невалиден.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<source>Wallet</source>
<translation>Портфейл</translation>
</message>
<message>
<source>Available:</source>
<translation>Налично:</translation>
</message>
<message>
<source>Pending:</source>
<translation>Изчакващо:</translation>
</message>
<message>
<source>Total:</source>
<translation>Общо:</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>Текущият ви общ баланс</translation>
</message>
<message>
<source><b>Recent transactions</b></source>
<translation><b>Последни трансакции</b></translation>
</message>
<message>
<source>out of sync</source>
<translation>несинхронизиран</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<source>Payment acknowledged</source>
<translation>Плащането е приета</translation>
</message>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>Client name</source>
<translation>Име на клиента</translation>
</message>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>Client version</source>
<translation>Версия на клиента</translation>
</message>
<message>
<source>&Information</source>
<translation>Данни</translation>
</message>
<message>
<source>Using OpenSSL version</source>
<translation>Използване на OpenSSL версия</translation>
</message>
<message>
<source>Network</source>
<translation>Мрежа</translation>
</message>
<message>
<source>Name</source>
<translation>Име</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Брой връзки</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Текущ брой блокове</translation>
</message>
<message>
<source>Last block time</source>
<translation>Време на последния блок</translation>
</message>
<message>
<source>Totals</source>
<translation>Общо:</translation>
</message>
<message>
<source>Open the Bitcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Отворете Биткой дебъг лог файла от настоящата Data папка. Може да отнеме няколко секунди при по - големи лог файлове.</translation>
</message>
<message>
<source>Clear console</source>
<translation>Изчисти конзолата</translation>
</message>
<message>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Използвайте стрелки надолу и нагореза разглеждане на историятаот команди и <b>Ctrl-L</b> за изчистване на конзолата.</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Label:</source>
<translation>&Име:</translation>
</message>
<message>
<source>Clear</source>
<translation>Изчистване</translation>
</message>
<message>
<source>Show</source>
<translation>Показване</translation>
</message>
<message>
<source>Remove</source>
<translation>Премахване</translation>
</message>
<message>
<source>Copy label</source>
<translation>Копирай име</translation>
</message>
<message>
<source>Copy message</source>
<translation>Копиране на съобщението</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Копирай сума</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Payment information</source>
<translation>Данни за плащането</translation>
</message>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<source>Label</source>
<translation>Име</translation>
</message>
<message>
<source>Message</source>
<translation>Съобщение</translation>
</message>
<message>
<source>Error encoding URI into QR Code.</source>
<translation>Грешка при създаването на QR Code от URI.</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Label</source>
<translation>Име</translation>
</message>
<message>
<source>Message</source>
<translation>Съобщение</translation>
</message>
<message>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<source>(no label)</source>
<translation>(без име)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Изпращане</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Байтове:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Сума:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Приоритет:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Такса:</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Изпращане към повече от един получател</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>Добави &получател</translation>
</message>
<message>
<source>Clear &All</source>
<translation>&Изчисти</translation>
</message>
<message>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Потвърдете изпращането</translation>
</message>
<message>
<source>S&end</source>
<translation>И&зпрати</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>Потвърждаване</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Копирай сума</translation>
</message>
<message>
<source>or</source>
<translation>или</translation>
</message>
<message>
<source>The recipient address is not valid, please recheck.</source>
<translation>Невалиден адрес на получателя.</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>Сумата трябва да е по-голяма от 0.</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>Сумата надвишава текущия баланс</translation>
</message>
<message>
<source>Transaction creation failed!</source>
<translation>Грешка при създаването на трансакция!</translation>
</message>
<message>
<source>(no label)</source>
<translation>(без име)</translation>
</message>
<message>
<source>Are you sure you want to send?</source>
<translation>Наистина ли искате да изпратите?</translation>
</message>
<message>
<source>added as transaction fee</source>
<translation>добавено като такса за трансакция</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>С&ума:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>Плати &На:</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>Въведете име за този адрес, за да го добавите в списъка с адреси</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Име:</translation>
</message>
<message>
<source>This is a normal payment.</source>
<translation>Това е нормално плащане.</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Вмъкни от клипборда</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Remove this entry</source>
<translation>Премахване на този запис</translation>
</message>
<message>
<source>Message:</source>
<translation>Съобщение:</translation>
</message>
<message>
<source>Pay To:</source>
<translation>Плащане на:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Signatures - Sign / Verify a Message</source>
<translation>Подпиши / Провери съобщение</translation>
</message>
<message>
<source>&Sign Message</source>
<translation>&Подпиши</translation>
</message>
<message>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Можете да подпишете съобщение като доказателство, че притежавате определен адрес. Бъдете внимателни и не подписвайте съобщения, които биха разкрили лична информация без вашето съгласие.</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Вмъкни от клипборда</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation>Въведете съобщението тук</translation>
</message>
<message>
<source>Signature</source>
<translation>Подпис</translation>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation>Копиране на текущия подпис</translation>
</message>
<message>
<source>Sign the message to prove you own this Bitcoin address</source>
<translation>Подпишете съобщение като доказателство, че притежавате определен адрес</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Подпиши &съобщение</translation>
</message>
<message>
<source>Clear &All</source>
<translation>&Изчисти</translation>
</message>
<message>
<source>&Verify Message</source>
<translation>&Провери</translation>
</message>
<message>
<source>Verify the message to ensure it was signed with the specified Bitcoin address</source>
<translation>Проверете съобщение, за да сте сигурни че е подписано с определен Биткоин адрес</translation>
</message>
<message>
<source>Click "Sign Message" to generate signature</source>
<translation>Натиснете "Подписване на съобщение" за да създадете подпис</translation>
</message>
<message>
<source>The entered address is invalid.</source>
<translation>Въведеният адрес е невалиден.</translation>
</message>
<message>
<source>Please check the address and try again.</source>
<translation>Моля проверете адреса и опитайте отново.</translation>
</message>
<message>
<source>Wallet unlock was cancelled.</source>
<translation>Отключването на портфейла беше отменено.</translation>
</message>
<message>
<source>Private key for the entered address is not available.</source>
<translation>Не е наличен частният ключ за въведеният адрес.</translation>
</message>
<message>
<source>Message signing failed.</source>
<translation>Подписването на съобщение бе неуспешно.</translation>
</message>
<message>
<source>Message signed.</source>
<translation>Съобщението е подписано.</translation>
</message>
<message>
<source>The signature could not be decoded.</source>
<translation>Подписът не може да бъде декодиран.</translation>
</message>
<message>
<source>Please check the signature and try again.</source>
<translation>Проверете подписа и опитайте отново.</translation>
</message>
<message>
<source>The signature did not match the message digest.</source>
<translation>Подписът не отговаря на комбинацията от съобщение и адрес.</translation>
</message>
<message>
<source>Message verification failed.</source>
<translation>Проверката на съобщението беше неуспешна.</translation>
</message>
<message>
<source>Message verified.</source>
<translation>Съобщението е потвърдено.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation>Подлежи на промяна до %1</translation>
</message>
<message>
<source>%1/offline</source>
<translation>%1/офлайн</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/непотвърдени</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>включена в %1 блока</translation>
</message>
<message>
<source>Status</source>
<translation>Статус</translation>
</message>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Source</source>
<translation>Източник</translation>
</message>
<message>
<source>Generated</source>
<translation>Издадени</translation>
</message>
<message>
<source>From</source>
<translation>От</translation>
</message>
<message>
<source>To</source>
<translation>За</translation>
</message>
<message>
<source>own address</source>
<translation>собствен адрес</translation>
</message>
<message>
<source>label</source>
<translation>име</translation>
</message>
<message>
<source>Credit</source>
<translation>Кредит</translation>
</message>
<message>
<source>not accepted</source>
<translation>не е приет</translation>
</message>
<message>
<source>Debit</source>
<translation>Дебит</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Такса</translation>
</message>
<message>
<source>Net amount</source>
<translation>Сума нето</translation>
</message>
<message>
<source>Message</source>
<translation>Съобщение</translation>
</message>
<message>
<source>Comment</source>
<translation>Коментар</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>ID</translation>
</message>
<message>
<source>Merchant</source>
<translation>Търговец</translation>
</message>
<message>
<source>Transaction</source>
<translation>Трансакция</translation>
</message>
<message>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<source>true</source>
<translation>true</translation>
</message>
<message>
<source>false</source>
<translation>false</translation>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation>, все още не е изпратено</translation>
</message>
<message>
<source>unknown</source>
<translation>неизвестен</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>Transaction details</source>
<translation>Трансакция</translation>
</message>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Описание на трансакцията</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<source>Open until %1</source>
<translation>Подлежи на промяна до %1</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>Потвърдени (%1 потвърждения)</translation>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Блокът не е получен от останалите участници и най-вероятно няма да бъде одобрен.</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>Генерирана, но отхвърлена от мрежата</translation>
</message>
<message>
<source>Unconfirmed</source>
<translation>Непотвърдено</translation>
</message>
<message>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Потвърждаване (%1 от %2 препоръчвани потвърждения)</translation>
</message>
<message>
<source>Conflicted</source>
<translation>Конфликтно</translation>
</message>
<message>
<source>Received with</source>
<translation>Получени с</translation>
</message>
<message>
<source>Received from</source>
<translation>Получен от</translation>
</message>
<message>
<source>Sent to</source>
<translation>Изпратени на</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Плащане към себе си</translation>
</message>
<message>
<source>Mined</source>
<translation>Емитирани</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Състояние на трансакцията. Задръжте върху това поле за брой потвърждения.</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Дата и час на получаване.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Вид трансакция.</translation>
</message>
<message>
<source>Destination address of transaction.</source>
<translation>Получател на трансакцията.</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>Сума извадена или добавена към баланса.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Всички</translation>
</message>
<message>
<source>Today</source>
<translation>Днес</translation>
</message>
<message>
<source>This week</source>
<translation>Тази седмица</translation>
</message>
<message>
<source>This month</source>
<translation>Този месец</translation>
</message>
<message>
<source>Last month</source>
<translation>Предния месец</translation>
</message>
<message>
<source>This year</source>
<translation>Тази година</translation>
</message>
<message>
<source>Range...</source>
<translation>От - до...</translation>
</message>
<message>
<source>Received with</source>
<translation>Получени</translation>
</message>
<message>
<source>Sent to</source>
<translation>Изпратени на</translation>
</message>
<message>
<source>To yourself</source>
<translation>Собствени</translation>
</message>
<message>
<source>Mined</source>
<translation>Емитирани</translation>
</message>
<message>
<source>Other</source>
<translation>Други</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>Търсене по адрес или име</translation>
</message>
<message>
<source>Min amount</source>
<translation>Минимална сума</translation>
</message>
<message>
<source>Copy address</source>
<translation>Копирай адрес</translation>
</message>
<message>
<source>Copy label</source>
<translation>Копирай име</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Копирай сума</translation>
</message>
<message>
<source>Edit label</source>
<translation>Редактирай име</translation>
</message>
<message>
<source>Show transaction details</source>
<translation>Подробности за трансакцията</translation>
</message>
<message>
<source>Export Transaction History</source>
<translation>Изнасяне историята на трансакциите</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Грешка при изнасянето</translation>
</message>
<message>
<source>Exporting Successful</source>
<translation>Изнасянето е успешна</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>CSV файл (*.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Потвърдени</translation>
</message>
<message>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<source>Label</source>
<translation>Име</translation>
</message>
<message>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<source>ID</source>
<translation>ИД</translation>
</message>
<message>
<source>Range:</source>
<translation>От:</translation>
</message>
<message>
<source>to</source>
<translation>до</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
<message>
<source>No wallet has been loaded.</source>
<translation>Няма зареден портфейл.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Изпращане</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Запишете данните от текущия раздел във файл</translation>
</message>
<message>
<source>Backup Wallet</source>
<translation>Запазване на портфейла</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>Опции:</translation>
</message>
<message>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation>Задаване на файл с настройки (по подразбиране bitcoin.conf)</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>Определете директория за данните</translation>
</message>
<message>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Праг на прекъсване на връзката при непорядъчно държащи се пиъри (по подразбиране:100)</translation>
</message>
<message>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Брой секунди до възтановяване на връзката за зле държащите се пиъри (по подразбиране:86400)</translation>
</message>
<message>
<source>Use the test network</source>
<translation>Използвайте тестовата мрежа</translation>
</message>
<message>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Внимание: -paytxfee има голяма стойност! Това е таксата за транзакциите, която ще платите ако направите транзакция.</translation>
</message>
<message>
<source>(default: 1)</source>
<translation>(по подразбиране 1)</translation>
</message>
<message>
<source>(default: wallet.dat)</source>
<translation>(по подразбиране wallet.dat)</translation>
</message>
<message>
<source>Connection options:</source>
<translation>Настройки на връзката:</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Грешка: мястото на диска е малко!</translation>
</message>
<message>
<source>Error: system error: </source>
<translation>Грешка: системна грешка:</translation>
</message>
<message>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Провалено "слушане" на всеки порт. Използвайте -listen=0 ако искате това.</translation>
</message>
<message>
<source>Failed to read block info</source>
<translation>Грешка при четене данни на блок</translation>
</message>
<message>
<source>Failed to read block</source>
<translation>Грешка при четене на блок</translation>
</message>
<message>
<source>Failed to write block info</source>
<translation>Грешка при запис данни на блок</translation>
</message>
<message>
<source>Failed to write block</source>
<translation>Грешка при запис на блок</translation>
</message>
<message>
<source>Importing...</source>
<translation>Внасяне...</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>Проверка на блоковете...</translation>
</message>
<message>
<source>Verifying wallet...</source>
<translation>Проверка на портфейла...</translation>
</message>
<message>
<source>Wallet options:</source>
<translation>Настройки на портфейла:</translation>
</message>
<message>
<source>Information</source>
<translation>Данни</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Изпрати локализиращата или дебъг информацията към конзолата, вместо файлът debug.log</translation>
</message>
<message>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Задайте минимален размер на блок-а в байтове (подразбиране: 0)</translation>
</message>
<message>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Определете таймаут за свързване в милисекунди (подразбиране: 5000)</translation>
</message>
<message>
<source>System error: </source>
<translation>Системна грешка:</translation>
</message>
<message>
<source>Transaction amount too small</source>
<translation>Сумата на трансакцията е твърде малка</translation>
</message>
<message>
<source>Transaction amounts must be positive</source>
<translation>Сумите на трансакциите трябва да са положителни</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>Трансакцията е твърде голяма</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>Потребителско име за JSON-RPC връзките</translation>
</message>
<message>
<source>Warning</source>
<translation>Предупреждение</translation>
</message>
<message>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Внимание: Използвате остаряла версия, необходимо е обновление!</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>Парола за JSON-RPC връзките</translation>
</message>
<message>
<source>Upgrade wallet to latest format</source>
<translation>Обновяване на портфейла до най-новия формат</translation>
</message>
<message>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Повторно сканиране на блок-връзка за липсващи портфейлни трансакции</translation>
</message>
<message>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Използвайте OpenSSL (https) за JSON-RPC връзките</translation>
</message>
<message>
<source>Server certificate file (default: server.cert)</source>
<translation>Сертификатен файл на сървъра (По подразбиране:server.cert)</translation>
</message>
<message>
<source>Server private key (default: server.pem)</source>
<translation>Поверителен ключ за сървъра (default: server.pem)</translation>
</message>
<message>
<source>This help message</source>
<translation>Това помощно съобщение</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>Зареждане на адресите...</translation>
</message>
<message>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Грешка при зареждане на wallet.dat: портфейлът е повреден</translation>
</message>
<message>
<source>Error loading wallet.dat</source>
<translation>Грешка при зареждане на wallet.dat</translation>
</message>
<message>
<source>Invalid -proxy address: '%s'</source>
<translation>Невалиден -proxy address: '%s'</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Недостатъчно средства</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Зареждане на блок индекса...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Зареждане на портфейла...</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Преразглеждане на последовтелността от блокове...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Зареждането е завършено</translation>
</message>
<message>
<source>Error</source>
<translation>Грешка</translation>
</message>
</context>
</TS> | mit |
NablaT/TemplateDemo | src/app/core/profile/profile.component.spec.ts | 325 | /* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { ProfileComponent } from './profile.component';
describe('Component: Profile', () => {
it('should create an instance', () => {
let component = new ProfileComponent();
expect(component).toBeTruthy();
});
});
| mit |
pepakam/TelerikAcademy | WebDesign/Slice&Dice/4. HTML5 Everywhere/html5-everywhere-homework/task2_geolocation - v3/scripts/js-webshim/dev/shims/geolocation.js | 4747 | (function($){
if(navigator.geolocation){return;}
var domWrite = function(){
setTimeout(function(){
throw('document.write is overwritten by geolocation shim. This method is incompatible with this plugin');
}, 1);
},
id = 0
;
var geoOpts = $.webshims.cfg.geolocation || {};
navigator.geolocation = (function(){
var pos;
var api = {
getCurrentPosition: function(success, error, opts){
var locationAPIs = 2,
errorTimer,
googleTimer,
calledEnd,
endCallback = function(){
if(calledEnd){return;}
if(pos){
calledEnd = true;
success($.extend({timestamp: new Date().getTime()}, pos));
resetCallback();
if(window.JSON && window.sessionStorage){
try{
sessionStorage.setItem('storedGeolocationData654321', JSON.stringify(pos));
} catch(e){}
}
} else if(error && !locationAPIs) {
calledEnd = true;
resetCallback();
error({ code: 2, message: "POSITION_UNAVAILABLE"});
}
},
googleCallback = function(){
locationAPIs--;
getGoogleCoords();
endCallback();
},
resetCallback = function(){
$(document).unbind('google-loader', resetCallback);
clearTimeout(googleTimer);
clearTimeout(errorTimer);
},
getGoogleCoords = function(){
if(pos || !window.google || !google.loader || !google.loader.ClientLocation){return false;}
var cl = google.loader.ClientLocation;
pos = {
coords: {
latitude: cl.latitude,
longitude: cl.longitude,
altitude: null,
accuracy: 43000,
altitudeAccuracy: null,
heading: parseInt('NaN', 10),
velocity: null
},
//extension similiar to FF implementation
address: $.extend({streetNumber: '', street: '', premises: '', county: '', postalCode: ''}, cl.address)
};
return true;
},
getInitCoords = function(){
if(pos){return;}
getGoogleCoords();
if(pos || !window.JSON || !window.sessionStorage){return;}
try{
pos = sessionStorage.getItem('storedGeolocationData654321');
pos = (pos) ? JSON.parse(pos) : false;
if(!pos.coords){pos = false;}
} catch(e){
pos = false;
}
}
;
getInitCoords();
if(!pos){
if(geoOpts.confirmText && !confirm(geoOpts.confirmText.replace('{location}', location.hostname))){
if(error){
error({ code: 1, message: "PERMISSION_DENIED"});
}
return;
}
$.ajax({
url: 'http://freegeoip.net/json/',
dataType: 'jsonp',
cache: true,
jsonp: 'callback',
success: function(data){
locationAPIs--;
if(!data){return;}
pos = pos || {
coords: {
latitude: data.latitude,
longitude: data.longitude,
altitude: null,
accuracy: 43000,
altitudeAccuracy: null,
heading: parseInt('NaN', 10),
velocity: null
},
//extension similiar to FF implementation
address: {
city: data.city,
country: data.country_name,
countryCode: data.country_code,
county: "",
postalCode: data.zipcode,
premises: "",
region: data.region_name,
street: "",
streetNumber: ""
}
};
endCallback();
},
error: function(){
locationAPIs--;
endCallback();
}
});
clearTimeout(googleTimer);
if (!window.google || !window.google.loader) {
googleTimer = setTimeout(function(){
//destroys document.write!!!
if (geoOpts.destroyWrite) {
document.write = domWrite;
document.writeln = domWrite;
}
$(document).one('google-loader', googleCallback);
$.webshims.loader.loadScript('http://www.google.com/jsapi', false, 'google-loader');
}, 800);
} else {
locationAPIs--;
}
} else {
setTimeout(endCallback, 1);
return;
}
if(opts && opts.timeout){
errorTimer = setTimeout(function(){
resetCallback();
if(error) {
error({ code: 3, message: "TIMEOUT"});
}
}, opts.timeout);
} else {
errorTimer = setTimeout(function(){
locationAPIs = 0;
endCallback();
}, 10000);
}
},
clearWatch: $.noop
};
api.watchPosition = function(a, b, c){
api.getCurrentPosition(a, b, c);
id++;
return id;
};
return api;
})();
$.webshims.isReady('geolocation', true);
})(jQuery);
| mit |
AndreyZaets/rita | qza9ukxv9w/model/extension/report/marketing.php | 1998 | <?php
class ModelExtensionReportMarketing extends Model {
public function getMarketing($data = array()) {
$sql = "SELECT m.marketing_id, m.name AS campaign, m.code, m.clicks AS clicks, (SELECT COUNT(DISTINCT order_id) FROM `" . DB_PREFIX . "order` o1 WHERE o1.marketing_id = m.marketing_id";
if (!empty($data['filter_order_status_id'])) {
$sql .= " AND o1.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
} else {
$sql .= " AND o1.order_status_id > '0'";
}
if (!empty($data['filter_date_start'])) {
$sql .= " AND DATE(o1.date_added) >= '" . $this->db->escape($data['filter_date_start']) . "'";
}
if (!empty($data['filter_date_end'])) {
$sql .= " AND DATE(o1.date_added) <= '" . $this->db->escape($data['filter_date_end']) . "'";
}
$sql .= ") AS `orders`, (SELECT SUM(total) FROM `" . DB_PREFIX . "order` o2 WHERE o2.marketing_id = m.marketing_id";
if (!empty($data['filter_order_status_id'])) {
$sql .= " AND o2.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
} else {
$sql .= " AND o2.order_status_id > '0'";
}
if (!empty($data['filter_date_start'])) {
$sql .= " AND DATE(o2.date_added) >= '" . $this->db->escape($data['filter_date_start']) . "'";
}
if (!empty($data['filter_date_end'])) {
$sql .= " AND DATE(o2.date_added) <= '" . $this->db->escape($data['filter_date_end']) . "'";
}
$sql .= " GROUP BY o2.marketing_id) AS `total` FROM `" . DB_PREFIX . "marketing` m ORDER BY m.date_added ASC";
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
}
public function getTotalMarketing($data = array()) {
$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "marketing`");
return $query->row['total'];
}
} | mit |
wizardbeard/agency-iq | test/helpers/stations_helper_test.rb | 75 | require 'test_helper'
class StationsHelperTest < ActionView::TestCase
end
| mit |
yizhang82/corert | src/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/NativeFormat/NativeFormatRuntimeGenericParameterTypeInfoForMethods.UnificationKey.cs | 2229 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.MethodInfos;
using System.Reflection.Runtime.TypeInfos;
using Internal.Reflection.Tracing;
using Internal.Metadata.NativeFormat;
namespace System.Reflection.Runtime.TypeInfos.NativeFormat
{
internal sealed partial class NativeFormatRuntimeGenericParameterTypeInfoForMethods : NativeFormatRuntimeGenericParameterTypeInfo, IKeyedItem<NativeFormatRuntimeGenericParameterTypeInfoForMethods.UnificationKey>
{
//
// Key for unification.
//
internal struct UnificationKey : IEquatable<UnificationKey>
{
public UnificationKey(RuntimeNamedMethodInfo methodOwner, MetadataReader reader, GenericParameterHandle genericParameterHandle)
{
MethodOwner = methodOwner;
GenericParameterHandle = genericParameterHandle;
Reader = reader;
}
public RuntimeNamedMethodInfo MethodOwner { get; }
public MetadataReader Reader { get; }
public GenericParameterHandle GenericParameterHandle { get; }
public override bool Equals(object obj)
{
if (!(obj is UnificationKey))
return false;
return Equals((UnificationKey)obj);
}
public bool Equals(UnificationKey other)
{
if (!(GenericParameterHandle.Equals(other.GenericParameterHandle)))
return false;
if (!(Reader == other.Reader))
return false;
if (!MethodOwner.Equals(other.MethodOwner))
return false;
return true;
}
public override int GetHashCode()
{
return GenericParameterHandle.GetHashCode();
}
}
}
}
| mit |
tangkun75/jenkins | core/src/main/java/jenkins/model/ParameterizedJobMixIn.java | 22003 | /*
* The MIT License
*
* Copyright 2014 Jesse Glick.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.model;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.model.Action;
import hudson.model.BuildableItem;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Item;
import static hudson.model.Item.CONFIGURE;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.listeners.ItemListener;
import hudson.model.queue.QueueTaskFuture;
import hudson.search.SearchIndexBuilder;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AlternativeUiTextProvider;
import hudson.views.BuildButtonColumn;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.servlet.ServletException;
import static javax.servlet.http.HttpServletResponse.SC_CREATED;
import static javax.servlet.http.HttpServletResponse.SC_CONFLICT;
import jenkins.model.lazy.LazyBuildMixIn;
import jenkins.triggers.SCMTriggerItem;
import jenkins.util.TimeDuration;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.accmod.restrictions.ProtectedExternally;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* Allows a {@link Job} to make use of {@link ParametersDefinitionProperty} and be scheduled in various ways.
* Stateless so there is no need to keep an instance of it in a field.
* Besides implementing {@link ParameterizedJob}, you should
* <ul>
* <li>override {@link Job#makeSearchIndex} to call {@link #extendSearchIndex}
* <li>override {@link Job#performDelete} to call {@link ParameterizedJob#makeDisabled}
* <li>override {@link Job#getIconColor} to call {@link ParameterizedJob#isDisabled}
* <li>use {@code <p:config-disableBuild/>}
* <li>use {@code <p:makeDisabled/>}
* </ul>
* @since 1.556
*/
@SuppressWarnings("unchecked") // AbstractItem.getParent does not correctly override; scheduleBuild2 inherently untypable
public abstract class ParameterizedJobMixIn<JobT extends Job<JobT, RunT> & ParameterizedJobMixIn.ParameterizedJob<JobT, RunT> & Queue.Task, RunT extends Run<JobT, RunT> & Queue.Executable> {
protected abstract JobT asJob();
/** @see BuildableItem#scheduleBuild() */
@SuppressWarnings("deprecation")
public final boolean scheduleBuild() {
return scheduleBuild(asJob().getQuietPeriod(), new Cause.LegacyCodeCause());
}
/** @see BuildableItem#scheduleBuild(Cause) */
public final boolean scheduleBuild(Cause c) {
return scheduleBuild(asJob().getQuietPeriod(), c);
}
/** @see BuildableItem#scheduleBuild(int) */
@SuppressWarnings("deprecation")
public final boolean scheduleBuild(int quietPeriod) {
return scheduleBuild(quietPeriod, new Cause.LegacyCodeCause());
}
/** @see BuildableItem#scheduleBuild(int, Cause) */
public final boolean scheduleBuild(int quietPeriod, Cause c) {
return scheduleBuild2(quietPeriod, c != null ? Collections.<Action>singletonList(new CauseAction(c)) : Collections.<Action>emptyList()) != null;
}
/**
* Standard implementation of {@link ParameterizedJob#scheduleBuild2}.
*/
public final @CheckForNull QueueTaskFuture<RunT> scheduleBuild2(int quietPeriod, Action... actions) {
Queue.Item i = scheduleBuild2(quietPeriod, Arrays.asList(actions));
return i != null ? (QueueTaskFuture) i.getFuture() : null;
}
/**
* Convenience method to schedule a build.
* Useful for {@link Trigger} implementations, for example.
* If you need to wait for the build to start (or finish), use {@link Queue.Item#getFuture}.
* @param job a job which might be schedulable
* @param quietPeriod seconds to wait before starting; use {@code -1} to use the job’s default settings
* @param actions various actions to associate with the scheduling, such as {@link ParametersAction} or {@link CauseAction}
* @return a newly created, or reused, queue item if the job could be scheduled; null if it was refused for some reason (e.g., some {@link Queue.QueueDecisionHandler} rejected it), or if {@code job} is not a {@link ParameterizedJob} or it is not {@link Job#isBuildable})
* @since 1.621
*/
public static @CheckForNull Queue.Item scheduleBuild2(final Job<?,?> job, int quietPeriod, Action... actions) {
if (!(job instanceof ParameterizedJob)) {
return null;
}
return new ParameterizedJobMixIn() {
@Override protected Job asJob() {
return job;
}
}.scheduleBuild2(quietPeriod == -1 ? ((ParameterizedJob) job).getQuietPeriod() : quietPeriod, Arrays.asList(actions));
}
@CheckForNull Queue.Item scheduleBuild2(int quietPeriod, List<Action> actions) {
if (!asJob().isBuildable())
return null;
List<Action> queueActions = new ArrayList<Action>(actions);
if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
queueActions.add(new ParametersAction(getDefaultParametersValues()));
}
return Jenkins.getInstance().getQueue().schedule2(asJob(), quietPeriod, queueActions).getItem();
}
private List<ParameterValue> getDefaultParametersValues() {
ParametersDefinitionProperty paramDefProp = asJob().getProperty(ParametersDefinitionProperty.class);
ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
/*
* This check is made ONLY if someone will call this method even if isParametrized() is false.
*/
if(paramDefProp == null)
return defValues;
/* Scan for all parameter with an associated default values */
for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
{
ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if(defaultValue != null)
defValues.add(defaultValue);
}
return defValues;
}
/**
* Standard implementation of {@link ParameterizedJob#isParameterized}.
*/
public final boolean isParameterized() {
return asJob().getProperty(ParametersDefinitionProperty.class) != null;
}
/**
* Standard implementation of {@link ParameterizedJob#doBuild}.
*/
@SuppressWarnings("deprecation")
public final void doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
if (delay == null) {
delay = new TimeDuration(asJob().getQuietPeriod());
}
if (!asJob().isBuildable()) {
throw HttpResponses.error(SC_CONFLICT, new IOException(asJob().getFullName() + " is not buildable"));
}
// if a build is parameterized, let that take over
ParametersDefinitionProperty pp = asJob().getProperty(ParametersDefinitionProperty.class);
if (pp != null && !req.getMethod().equals("POST")) {
// show the parameter entry form.
req.getView(pp, "index.jelly").forward(req, rsp);
return;
}
hudson.model.BuildAuthorizationToken.checkPermission(asJob(), asJob().getAuthToken(), req, rsp);
if (pp != null) {
pp._doBuild(req, rsp, delay);
return;
}
Queue.Item item = Jenkins.getInstance().getQueue().schedule2(asJob(), delay.getTime(), getBuildCause(asJob(), req)).getItem();
if (item != null) {
rsp.sendRedirect(SC_CREATED, req.getContextPath() + '/' + item.getUrl());
} else {
rsp.sendRedirect(".");
}
}
/**
* Standard implementation of {@link ParameterizedJob#doBuildWithParameters}.
*/
@SuppressWarnings("deprecation")
public final void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
hudson.model.BuildAuthorizationToken.checkPermission(asJob(), asJob().getAuthToken(), req, rsp);
ParametersDefinitionProperty pp = asJob().getProperty(ParametersDefinitionProperty.class);
if (!asJob().isBuildable()) {
throw HttpResponses.error(SC_CONFLICT, new IOException(asJob().getFullName() + " is not buildable!"));
}
if (pp != null) {
pp.buildWithParameters(req, rsp, delay);
} else {
throw new IllegalStateException("This build is not parameterized!");
}
}
/**
* Standard implementation of {@link ParameterizedJob#doCancelQueue}.
*/
@RequirePOST
public final void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
asJob().checkPermission(Item.CANCEL);
Jenkins.getInstance().getQueue().cancel(asJob());
rsp.forwardToPreviousPage(req);
}
/**
* Use from a {@link Job#makeSearchIndex} override.
* @param sib the super value
* @return the value to return
*/
public final SearchIndexBuilder extendSearchIndex(SearchIndexBuilder sib) {
if (asJob().isBuildable() && asJob().hasPermission(Item.BUILD)) {
sib.add("build", "build");
}
return sib;
}
/**
* Computes the build cause, using RemoteCause or UserCause as appropriate.
*/
@Restricted(NoExternalUse.class)
public static final CauseAction getBuildCause(ParameterizedJob job, StaplerRequest req) {
Cause cause;
@SuppressWarnings("deprecation")
hudson.model.BuildAuthorizationToken authToken = job.getAuthToken();
if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
// Optional additional cause text when starting via token
String causeText = req.getParameter("cause");
cause = new Cause.RemoteCause(req.getRemoteAddr(), causeText);
} else {
cause = new Cause.UserIdCause();
}
return new CauseAction(cause);
}
/**
* Allows customization of the human-readable display name to be rendered in the <i>Build Now</i> link.
* @see #getBuildNowText
* @since 1.624
*/
public static final AlternativeUiTextProvider.Message<ParameterizedJob> BUILD_NOW_TEXT = new AlternativeUiTextProvider.Message<ParameterizedJob>();
/**
* Suggested implementation of {@link ParameterizedJob#getBuildNowText}.
*/
public final String getBuildNowText() {
return isParameterized() ? AlternativeUiTextProvider.get(BUILD_NOW_TEXT, asJob(), Messages.ParameterizedJobMixIn_build_with_parameters())
: AlternativeUiTextProvider.get(BUILD_NOW_TEXT, asJob(), Messages.ParameterizedJobMixIn_build_now());
}
/**
* Checks for the existence of a specific trigger on a job.
* @param <T> a trigger type
* @param job a job
* @param clazz the type of the trigger
* @return a configured trigger of the requested type, or null if there is none such, or {@code job} is not a {@link ParameterizedJob}
* @since 1.621
*/
public static @CheckForNull <T extends Trigger<?>> T getTrigger(Job<?,?> job, Class<T> clazz) {
if (!(job instanceof ParameterizedJob)) {
return null;
}
for (Trigger<?> t : ((ParameterizedJob<?, ?>) job).getTriggers().values()) {
if (clazz.isInstance(t)) {
return clazz.cast(t);
}
}
return null;
}
/**
* Marker for job using this mixin, and default implementations of many methods.
*/
public interface ParameterizedJob<JobT extends Job<JobT, RunT> & ParameterizedJobMixIn.ParameterizedJob<JobT, RunT> & Queue.Task, RunT extends Run<JobT, RunT> & Queue.Executable> extends BuildableItem {
/**
* Used for CLI binding.
*/
@Restricted(DoNotUse.class)
@SuppressWarnings("rawtypes")
@CLIResolver
static ParameterizedJob resolveForCLI(@Argument(required=true, metaVar="NAME", usage="Job name") String name) throws CmdLineException {
ParameterizedJob item = Jenkins.getInstance().getItemByFullName(name, ParameterizedJob.class);
if (item == null) {
ParameterizedJob project = Items.findNearest(ParameterizedJob.class, name, Jenkins.getInstance());
throw new CmdLineException(null, project == null ?
hudson.model.Messages.AbstractItem_NoSuchJobExistsWithoutSuggestion(name) :
hudson.model.Messages.AbstractItem_NoSuchJobExists(name, project.getFullName()));
}
return item;
}
/**
* Creates a helper object.
* (Would have been done entirely as an interface with default methods had this been designed for Java 8.)
*/
default ParameterizedJobMixIn<JobT, RunT> getParameterizedJobMixIn() {
return new ParameterizedJobMixIn<JobT, RunT>() {
@SuppressWarnings("unchecked") // untypable
@Override protected JobT asJob() {
return (JobT) ParameterizedJob.this;
}
};
}
@SuppressWarnings("deprecation")
@CheckForNull hudson.model.BuildAuthorizationToken getAuthToken();
/**
* Quiet period for the job.
* @return by default, {@link Jenkins#getQuietPeriod}
*/
default int getQuietPeriod() {
return Jenkins.getInstance().getQuietPeriod();
}
/**
* Text to display for a build button.
* Uses {@link #BUILD_NOW_TEXT}.
* @see ParameterizedJobMixIn#getBuildNowText
*/
default String getBuildNowText() {
return getParameterizedJobMixIn().getBuildNowText();
}
/**
* Gets currently configured triggers.
* You may use {@code <p:config-trigger/>} to configure them.
* @return a map from trigger kind to instance
* @see #getTrigger
*/
Map<TriggerDescriptor,Trigger<?>> getTriggers();
/**
* @deprecated use {@link #scheduleBuild(Cause)}
*/
@Deprecated
@Override
default boolean scheduleBuild() {
return getParameterizedJobMixIn().scheduleBuild();
}
@Override
default boolean scheduleBuild(Cause c) {
return getParameterizedJobMixIn().scheduleBuild(c);
}
/**
* @deprecated use {@link #scheduleBuild(int, Cause)}
*/
@Deprecated
@Override
default boolean scheduleBuild(int quietPeriod) {
return getParameterizedJobMixIn().scheduleBuild(quietPeriod);
}
@Override
default boolean scheduleBuild(int quietPeriod, Cause c) {
return getParameterizedJobMixIn().scheduleBuild(quietPeriod, c);
}
/**
* Provides a standard implementation of {@link SCMTriggerItem#scheduleBuild2} to schedule a build with the ability to wait for its result.
* That job method is often used during functional tests ({@code JenkinsRule.assertBuildStatusSuccess}).
* @param quietPeriod seconds to wait before starting (normally 0)
* @param actions various actions to associate with the scheduling, such as {@link ParametersAction} or {@link CauseAction}
* @return a handle by which you may wait for the build to complete (or just start); or null if the build was not actually scheduled for some reason
*/
@CheckForNull
default QueueTaskFuture<RunT> scheduleBuild2(int quietPeriod, Action... actions) {
return getParameterizedJobMixIn().scheduleBuild2(quietPeriod, actions);
}
/**
* Schedules a new build command.
* @see ParameterizedJobMixIn#doBuild
*/
default void doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
getParameterizedJobMixIn().doBuild(req, rsp, delay);
}
/**
* Supports build trigger with parameters via an HTTP GET or POST.
* Currently only String parameters are supported.
* @see ParameterizedJobMixIn#doBuildWithParameters
*/
default void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
getParameterizedJobMixIn().doBuildWithParameters(req, rsp, delay);
}
/**
* Cancels a scheduled build.
* @see ParameterizedJobMixIn#doCancelQueue
*/
@RequirePOST
default void doCancelQueue(StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
getParameterizedJobMixIn().doCancelQueue(req, rsp);
}
/**
* Schedules a new SCM polling command.
*/
@SuppressWarnings("deprecation")
default void doPolling(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
if (!(this instanceof SCMTriggerItem)) {
rsp.sendError(404);
return;
}
hudson.model.BuildAuthorizationToken.checkPermission((Job) this, getAuthToken(), req, rsp);
((SCMTriggerItem) this).schedulePolling();
rsp.sendRedirect(".");
}
/**
* For use from {@link BuildButtonColumn}.
* @see ParameterizedJobMixIn#isParameterized
*/
default boolean isParameterized() {
return getParameterizedJobMixIn().isParameterized();
}
default boolean isDisabled() {
return false;
}
@Restricted(ProtectedExternally.class)
default void setDisabled(boolean disabled) {
throw new UnsupportedOperationException("must be implemented if supportsMakeDisabled is overridden");
}
/**
* Specifies whether this project may be disabled by the user.
* @return true if the GUI should allow {@link #doDisable} and the like
*/
default boolean supportsMakeDisabled() {
return false;
}
/**
* Marks the build as disabled.
* The method will ignore the disable command if {@link #supportsMakeDisabled()}
* returns false. The enable command will be executed in any case.
* @param b true - disable, false - enable
*/
default void makeDisabled(boolean b) throws IOException {
if (isDisabled() == b) {
return; // noop
}
if (b && !supportsMakeDisabled()) {
return; // do nothing if the disabling is unsupported
}
setDisabled(b);
if (b) {
Jenkins.getInstance().getQueue().cancel(this);
}
save();
ItemListener.fireOnUpdated(this);
}
@CLIMethod(name="disable-job")
@RequirePOST
default HttpResponse doDisable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(true);
return new HttpRedirect(".");
}
@CLIMethod(name="enable-job")
@RequirePOST
default HttpResponse doEnable() throws IOException, ServletException {
checkPermission(CONFIGURE);
makeDisabled(false);
return new HttpRedirect(".");
}
@Override
default RunT createExecutable() throws IOException {
if (isDisabled()) {
return null;
}
if (this instanceof LazyBuildMixIn.LazyLoadingJob) {
return (RunT) ((LazyBuildMixIn.LazyLoadingJob) this).getLazyBuildMixIn().newBuild();
}
return null;
}
default boolean isBuildable() {
return !isDisabled() && !((Job) this).isHoldOffBuildUntilSave();
}
}
}
| mit |
greenaddress/material-dialogs | commons/src/main/java/com/afollestad/materialdialogs/prefs/PrefUtil.java | 2798 | package com.afollestad.materialdialogs.prefs;
import android.content.Context;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import com.afollestad.materialdialogs.commons.R;
import java.lang.reflect.Method;
/**
* @author Aidan Follestad (afollestad)
*/
class PrefUtil {
private PrefUtil() {
}
public static void setLayoutResource(@NonNull Context context, @NonNull Preference preference, @Nullable AttributeSet attrs) {
boolean foundLayout = false;
if (attrs != null) {
for (int i = 0; i < attrs.getAttributeCount(); i++) {
final String namespace = ((XmlResourceParser) attrs).getAttributeNamespace(0);
if (namespace.equals("http://schemas.android.com/apk/res/android") &&
attrs.getAttributeName(i).equals("layout")) {
foundLayout = true;
break;
}
}
}
boolean useStockLayout = false;
if (attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.Preference, 0, 0);
try {
useStockLayout = a.getBoolean(R.styleable.Preference_useStockLayout, false);
} finally {
a.recycle();
}
}
if (!foundLayout && !useStockLayout)
preference.setLayoutResource(R.layout.md_preference_custom);
}
public static void registerOnActivityDestroyListener(@NonNull Preference preference, @NonNull PreferenceManager.OnActivityDestroyListener listener) {
try {
PreferenceManager pm = preference.getPreferenceManager();
Method method = pm.getClass().getDeclaredMethod(
"registerOnActivityDestroyListener",
PreferenceManager.OnActivityDestroyListener.class);
method.setAccessible(true);
method.invoke(pm, listener);
} catch (Exception ignored) {
}
}
public static void unregisterOnActivityDestroyListener(@NonNull Preference preference, @NonNull PreferenceManager.OnActivityDestroyListener listener) {
try {
PreferenceManager pm = preference.getPreferenceManager();
Method method = pm.getClass().getDeclaredMethod(
"unregisterOnActivityDestroyListener",
PreferenceManager.OnActivityDestroyListener.class);
method.setAccessible(true);
method.invoke(pm, listener);
} catch (Exception ignored) {
}
}
}
| mit |
axelitus/fork-ews-managed-api | Enumerations/AvailabilityData.cs | 1796 | /*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
/// <summary>
/// Defines the type of data that can be requested via GetUserAvailability.
/// </summary>
public enum AvailabilityData
{
/// <summary>
/// Only return free/busy data.
/// </summary>
FreeBusy,
/// <summary>
/// Only return suggestions.
/// </summary>
Suggestions,
/// <summary>
/// Return both free/busy data and suggestions.
/// </summary>
FreeBusyAndSuggestions
}
} | mit |
sramzan/bo-sr-stem | node_modules/@uirouter/core/lib-esm/transition/transitionHook.js | 8795 | /**
* @coreapi
* @module transition
*/
/** for typedoc */
import { TransitionHookPhase } from './interface';
import { defaults, noop, silentRejection } from '../common/common';
import { fnToString, maxLength } from '../common/strings';
import { isPromise } from '../common/predicates';
import { is, parse } from '../common/hof';
import { trace } from '../common/trace';
import { services } from '../common/coreservices';
import { Rejection } from './rejectFactory';
import { TargetState } from '../state/targetState';
var defaultOptions = {
current: noop,
transition: null,
traceData: {},
bind: null,
};
/** @hidden */
var TransitionHook = (function () {
function TransitionHook(transition, stateContext, registeredHook, options) {
var _this = this;
this.transition = transition;
this.stateContext = stateContext;
this.registeredHook = registeredHook;
this.options = options;
this.isSuperseded = function () {
return _this.type.hookPhase === TransitionHookPhase.RUN && !_this.options.transition.isActive();
};
this.options = defaults(options, defaultOptions);
this.type = registeredHook.eventType;
}
TransitionHook.prototype.logError = function (err) {
this.transition.router.stateService.defaultErrorHandler()(err);
};
TransitionHook.prototype.invokeHook = function () {
var _this = this;
var hook = this.registeredHook;
if (hook._deregistered)
return;
var notCurrent = this.getNotCurrentRejection();
if (notCurrent)
return notCurrent;
var options = this.options;
trace.traceHookInvocation(this, this.transition, options);
var invokeCallback = function () {
return hook.callback.call(options.bind, _this.transition, _this.stateContext);
};
var normalizeErr = function (err) {
return Rejection.normalize(err).toPromise();
};
var handleError = function (err) {
return hook.eventType.getErrorHandler(_this)(err);
};
var handleResult = function (result) {
return hook.eventType.getResultHandler(_this)(result);
};
try {
var result = invokeCallback();
if (!this.type.synchronous && isPromise(result)) {
return result.catch(normalizeErr)
.then(handleResult, handleError);
}
else {
return handleResult(result);
}
}
catch (err) {
// If callback throws (synchronously)
return handleError(Rejection.normalize(err));
}
};
/**
* This method handles the return value of a Transition Hook.
*
* A hook can return false (cancel), a TargetState (redirect),
* or a promise (which may later resolve to false or a redirect)
*
* This also handles "transition superseded" -- when a new transition
* was started while the hook was still running
*/
TransitionHook.prototype.handleHookResult = function (result) {
var _this = this;
var notCurrent = this.getNotCurrentRejection();
if (notCurrent)
return notCurrent;
// Hook returned a promise
if (isPromise(result)) {
// Wait for the promise, then reprocess with the resulting value
return result.then(function (val) { return _this.handleHookResult(val); });
}
trace.traceHookResult(result, this.transition, this.options);
// Hook returned false
if (result === false) {
// Abort this Transition
return Rejection.aborted("Hook aborted transition").toPromise();
}
var isTargetState = is(TargetState);
// hook returned a TargetState
if (isTargetState(result)) {
// Halt the current Transition and redirect (a new Transition) to the TargetState.
return Rejection.redirected(result).toPromise();
}
};
/**
* Return a Rejection promise if the transition is no longer current due
* to a stopped router (disposed), or a new transition has started and superseded this one.
*/
TransitionHook.prototype.getNotCurrentRejection = function () {
var router = this.transition.router;
// The router is stopped
if (router._disposed) {
return Rejection.aborted("UIRouter instance #" + router.$id + " has been stopped (disposed)").toPromise();
}
if (this.transition._aborted) {
return Rejection.aborted().toPromise();
}
// This transition is no longer current.
// Another transition started while this hook was still running.
if (this.isSuperseded()) {
// Abort this transition
return Rejection.superseded(this.options.current()).toPromise();
}
};
TransitionHook.prototype.toString = function () {
var _a = this, options = _a.options, registeredHook = _a.registeredHook;
var event = parse("traceData.hookType")(options) || "internal", context = parse("traceData.context.state.name")(options) || parse("traceData.context")(options) || "unknown", name = fnToString(registeredHook.callback);
return event + " context: " + context + ", " + maxLength(200, name);
};
/**
* Chains together an array of TransitionHooks.
*
* Given a list of [[TransitionHook]] objects, chains them together.
* Each hook is invoked after the previous one completes.
*
* #### Example:
* ```js
* var hooks: TransitionHook[] = getHooks();
* let promise: Promise<any> = TransitionHook.chain(hooks);
*
* promise.then(handleSuccess, handleError);
* ```
*
* @param hooks the list of hooks to chain together
* @param waitFor if provided, the chain is `.then()`'ed off this promise
* @returns a `Promise` for sequentially invoking the hooks (in order)
*/
TransitionHook.chain = function (hooks, waitFor) {
// Chain the next hook off the previous
var createHookChainR = function (prev, nextHook) {
return prev.then(function () { return nextHook.invokeHook(); });
};
return hooks.reduce(createHookChainR, waitFor || services.$q.when());
};
/**
* Invokes all the provided TransitionHooks, in order.
* Each hook's return value is checked.
* If any hook returns a promise, then the rest of the hooks are chained off that promise, and the promise is returned.
* If no hook returns a promise, then all hooks are processed synchronously.
*
* @param hooks the list of TransitionHooks to invoke
* @param doneCallback a callback that is invoked after all the hooks have successfully completed
*
* @returns a promise for the async result, or the result of the callback
*/
TransitionHook.invokeHooks = function (hooks, doneCallback) {
for (var idx = 0; idx < hooks.length; idx++) {
var hookResult = hooks[idx].invokeHook();
if (isPromise(hookResult)) {
var remainingHooks = hooks.slice(idx + 1);
return TransitionHook.chain(remainingHooks, hookResult)
.then(doneCallback);
}
}
return doneCallback();
};
/**
* Run all TransitionHooks, ignoring their return value.
*/
TransitionHook.runAllHooks = function (hooks) {
hooks.forEach(function (hook) { return hook.invokeHook(); });
};
return TransitionHook;
}());
export { TransitionHook };
/**
* These GetResultHandler(s) are used by [[invokeHook]] below
* Each HookType chooses a GetResultHandler (See: [[TransitionService._defineCoreEvents]])
*/
TransitionHook.HANDLE_RESULT = function (hook) { return function (result) {
return hook.handleHookResult(result);
}; };
/**
* If the result is a promise rejection, log it.
* Otherwise, ignore the result.
*/
TransitionHook.LOG_REJECTED_RESULT = function (hook) { return function (result) {
isPromise(result) && result.catch(function (err) {
return hook.logError(Rejection.normalize(err));
});
return undefined;
}; };
/**
* These GetErrorHandler(s) are used by [[invokeHook]] below
* Each HookType chooses a GetErrorHandler (See: [[TransitionService._defineCoreEvents]])
*/
TransitionHook.LOG_ERROR = function (hook) { return function (error) {
return hook.logError(error);
}; };
TransitionHook.REJECT_ERROR = function (hook) { return function (error) {
return silentRejection(error);
}; };
TransitionHook.THROW_ERROR = function (hook) { return function (error) {
throw error;
}; };
//# sourceMappingURL=transitionHook.js.map | mit |
seuffert/rclone | vendor/github.com/aws/aws-sdk-go/service/mq/service.go | 2994 | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package mq
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol/restjson"
)
// MQ provides the API operation methods for making requests to
// AmazonMQ. See this package's package overview docs
// for details on the service.
//
// MQ methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type MQ struct {
*client.Client
}
// Used for custom client initialization logic
var initClient func(*client.Client)
// Used for custom request initialization logic
var initRequest func(*request.Request)
// Service information constants
const (
ServiceName = "mq" // Service endpoint prefix API calls made to.
EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata.
)
// New creates a new instance of the MQ client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a MQ client from just a session.
// svc := mq.New(mySession)
//
// // Create a MQ client with additional configuration
// svc := mq.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *MQ {
c := p.ClientConfig(EndpointsID, cfgs...)
if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = "mq"
}
return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *MQ {
svc := &MQ{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: ServiceName,
SigningName: signingName,
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "2017-11-27",
JSONVersion: "1.1",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(restjson.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(restjson.UnmarshalErrorHandler)
// Run custom client initialization if present
if initClient != nil {
initClient(svc.Client)
}
return svc
}
// newRequest creates a new request for a MQ operation and runs any
// custom request initialization.
func (c *MQ) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
}
| mit |
Vrian7ipx/cascadadev | vendor/league/oauth2-server/src/League/OAuth2/Server/Grant/GrantTypeInterface.php | 2124 | <?php
/**
* OAuth 2.0 Grant type interface
*
* @package php-loep/oauth2-server
* @author Alex Bilbie <[email protected]>
* @copyright Copyright (c) 2013 PHP League of Extraordinary Packages
* @license http://mit-license.org/
* @link http://github.com/php-loep/oauth2-server
*/
namespace League\OAuth2\Server\Grant;
use League\OAuth2\Server\Request;
use League\OAuth2\Server\Authorization;
use League\OAuth2\Server\Exception;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Storage\SessionInterface;
use League\OAuth2\Server\Storage\ClientInterface;
use League\OAuth2\Server\Storage\ScopeInterface;
interface GrantTypeInterface
{
/**
* Constructor
* @param Authorization $authServer Authorization server instance
* @return void
*/
public function __construct(Authorization $authServer);
/**
* Returns the grant identifier (used to validate grant_type in League\OAuth2\Server\Authorization::issueAccessToken())
* @return string
*/
public function getIdentifier();
/**
* Returns the response type (used to validate response_type in League\OAuth2\Server\Grant\AuthCode::checkAuthoriseParams())
* @return null|string
*/
public function getResponseType();
/**
* Complete the grant flow
*
* Example response:
* <code>
* array(
* 'access_token' => (string), // The access token
* 'refresh_token' => (string), // The refresh token (only set if the refresh token grant is enabled)
* 'token_type' => 'bearer', // Almost always "bearer" (exceptions: JWT, SAML)
* 'expires' => (int), // The timestamp of when the access token will expire
* 'expires_in' => (int) // The number of seconds before the access token will expire
* )
* </code>
*
* @param null|array $inputParams Null unless the input parameters have been manually set
* @return array An array of parameters to be passed back to the client
*/
public function completeFlow($inputParams = null);
}
| mit |
lokeswaraswamy522/neonet | node_modules/npm-run-all/bin/run-p/main.js | 2310 | /**
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const runAll = require("../../lib")
const parseCLIArgs = require("../common/parse-cli-args")
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Parses arguments, then run specified npm-scripts.
*
* @param {string[]} args - Arguments to parse.
* @param {stream.Writable} stdout - A writable stream to print logs.
* @param {stream.Writable} stderr - A writable stream to print errors.
* @returns {Promise} A promise which comes to be fulfilled when all npm-scripts are completed.
* @private
*/
module.exports = function npmRunAll(args, stdout, stderr) {
try {
const stdin = process.stdin
const argv = parseCLIArgs(args, {parallel: true}, {singleMode: true})
const group = argv.lastGroup
if (group.patterns.length === 0) {
return Promise.resolve(null)
}
const promise = runAll(
group.patterns,
{
stdout,
stderr,
stdin,
parallel: group.parallel,
maxParallel: argv.maxParallel,
continueOnError: argv.continueOnError,
printLabel: argv.printLabel,
printName: argv.printName,
config: argv.config,
packageConfig: argv.packageConfig,
silent: argv.silent,
arguments: argv.rest,
race: argv.race,
npmPath: argv.npmPath,
}
)
if (!argv.silent) {
promise.catch(err => {
//eslint-disable-next-line no-console
console.error("ERROR:", err.message)
})
}
return promise
}
catch (err) {
//eslint-disable-next-line no-console
console.error("ERROR:", err.message)
return Promise.reject(err)
}
}
| mit |
deepakprakash/chattic | Godeps/_workspace/src/github.com/julienschmidt/httprouter/router_test.go | 9335 | // Copyright 2013 Julien Schmidt. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
package httprouter
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
type mockResponseWriter struct{}
func (m *mockResponseWriter) Header() (h http.Header) {
return http.Header{}
}
func (m *mockResponseWriter) Write(p []byte) (n int, err error) {
return len(p), nil
}
func (m *mockResponseWriter) WriteString(s string) (n int, err error) {
return len(s), nil
}
func (m *mockResponseWriter) WriteHeader(int) {}
func TestParams(t *testing.T) {
ps := Params{
Param{"param1", "value1"},
Param{"param2", "value2"},
Param{"param3", "value3"},
}
for i := range ps {
if val := ps.ByName(ps[i].Key); val != ps[i].Value {
t.Errorf("Wrong value for %s: Got %s; Want %s", ps[i].Key, val, ps[i].Value)
}
}
if val := ps.ByName("noKey"); val != "" {
t.Errorf("Expected empty string for not found key; got: %s", val)
}
}
func TestRouter(t *testing.T) {
router := New()
routed := false
router.Handle("GET", "/user/:name", func(w http.ResponseWriter, r *http.Request, ps Params) {
routed = true
want := Params{Param{"name", "gopher"}}
if !reflect.DeepEqual(ps, want) {
t.Fatalf("wrong wildcard values: want %v, got %v", want, ps)
}
})
w := new(mockResponseWriter)
req, _ := http.NewRequest("GET", "/user/gopher", nil)
router.ServeHTTP(w, req)
if !routed {
t.Fatal("routing failed")
}
}
type handlerStruct struct {
handeled *bool
}
func (h handlerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
*h.handeled = true
}
func TestRouterAPI(t *testing.T) {
var get, head, post, put, patch, delete, handler, handlerFunc bool
httpHandler := handlerStruct{&handler}
router := New()
router.GET("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) {
get = true
})
router.HEAD("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) {
head = true
})
router.POST("/POST", func(w http.ResponseWriter, r *http.Request, _ Params) {
post = true
})
router.PUT("/PUT", func(w http.ResponseWriter, r *http.Request, _ Params) {
put = true
})
router.PATCH("/PATCH", func(w http.ResponseWriter, r *http.Request, _ Params) {
patch = true
})
router.DELETE("/DELETE", func(w http.ResponseWriter, r *http.Request, _ Params) {
delete = true
})
router.Handler("GET", "/Handler", httpHandler)
router.HandlerFunc("GET", "/HandlerFunc", func(w http.ResponseWriter, r *http.Request) {
handlerFunc = true
})
w := new(mockResponseWriter)
r, _ := http.NewRequest("GET", "/GET", nil)
router.ServeHTTP(w, r)
if !get {
t.Error("routing GET failed")
}
r, _ = http.NewRequest("HEAD", "/GET", nil)
router.ServeHTTP(w, r)
if !head {
t.Error("routing HEAD failed")
}
r, _ = http.NewRequest("POST", "/POST", nil)
router.ServeHTTP(w, r)
if !post {
t.Error("routing POST failed")
}
r, _ = http.NewRequest("PUT", "/PUT", nil)
router.ServeHTTP(w, r)
if !put {
t.Error("routing PUT failed")
}
r, _ = http.NewRequest("PATCH", "/PATCH", nil)
router.ServeHTTP(w, r)
if !patch {
t.Error("routing PATCH failed")
}
r, _ = http.NewRequest("DELETE", "/DELETE", nil)
router.ServeHTTP(w, r)
if !delete {
t.Error("routing DELETE failed")
}
r, _ = http.NewRequest("GET", "/Handler", nil)
router.ServeHTTP(w, r)
if !handler {
t.Error("routing Handler failed")
}
r, _ = http.NewRequest("GET", "/HandlerFunc", nil)
router.ServeHTTP(w, r)
if !handlerFunc {
t.Error("routing HandlerFunc failed")
}
}
func TestRouterRoot(t *testing.T) {
router := New()
recv := catchPanic(func() {
router.GET("noSlashRoot", nil)
})
if recv == nil {
t.Fatal("registering path not beginning with '/' did not panic")
}
}
func TestRouterNotAllowed(t *testing.T) {
handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}
router := New()
router.POST("/path", handlerFunc)
// Test not allowed
r, _ := http.NewRequest("GET", "/path", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == http.StatusMethodNotAllowed) {
t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", w.Code, w.Header())
}
w = httptest.NewRecorder()
responseText := "custom method"
router.MethodNotAllowed = func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusTeapot)
w.Write([]byte(responseText))
}
router.ServeHTTP(w, r)
if got := w.Body.String(); !(got == responseText) {
t.Errorf("unexpected response got %q want %q", got, responseText)
}
if w.Code != http.StatusTeapot {
t.Errorf("unexpected response code %d want %d", w.Code, http.StatusTeapot)
}
}
func TestRouterNotFound(t *testing.T) {
handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}
router := New()
router.GET("/path", handlerFunc)
router.GET("/dir/", handlerFunc)
router.GET("/", handlerFunc)
testRoutes := []struct {
route string
code int
header string
}{
{"/path/", 301, "map[Location:[/path]]"}, // TSR -/
{"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/
{"", 301, "map[Location:[/]]"}, // TSR +/
{"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case
{"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case
{"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/
{"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/
{"/../path", 301, "map[Location:[/path]]"}, // CleanPath
{"/nope", 404, ""}, // NotFound
}
for _, tr := range testRoutes {
r, _ := http.NewRequest("GET", tr.route, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == tr.code && (w.Code == 404 || fmt.Sprint(w.Header()) == tr.header)) {
t.Errorf("NotFound handling route %s failed: Code=%d, Header=%v", tr.route, w.Code, w.Header())
}
}
// Test custom not found handler
var notFound bool
router.NotFound = func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(404)
notFound = true
}
r, _ := http.NewRequest("GET", "/nope", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == 404 && notFound == true) {
t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header())
}
// Test other method than GET (want 307 instead of 301)
router.PATCH("/path", handlerFunc)
r, _ = http.NewRequest("PATCH", "/path/", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == 307 && fmt.Sprint(w.Header()) == "map[Location:[/path]]") {
t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header())
}
// Test special case where no node for the prefix "/" exists
router = New()
router.GET("/a", handlerFunc)
r, _ = http.NewRequest("GET", "/", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == 404) {
t.Errorf("NotFound handling route / failed: Code=%d", w.Code)
}
}
func TestRouterPanicHandler(t *testing.T) {
router := New()
panicHandled := false
router.PanicHandler = func(rw http.ResponseWriter, r *http.Request, p interface{}) {
panicHandled = true
}
router.Handle("PUT", "/user/:name", func(_ http.ResponseWriter, _ *http.Request, _ Params) {
panic("oops!")
})
w := new(mockResponseWriter)
req, _ := http.NewRequest("PUT", "/user/gopher", nil)
defer func() {
if rcv := recover(); rcv != nil {
t.Fatal("handling panic failed")
}
}()
router.ServeHTTP(w, req)
if !panicHandled {
t.Fatal("simulating failed")
}
}
func TestRouterLookup(t *testing.T) {
routed := false
wantHandle := func(_ http.ResponseWriter, _ *http.Request, _ Params) {
routed = true
}
wantParams := Params{Param{"name", "gopher"}}
router := New()
// try empty router first
handle, _, tsr := router.Lookup("GET", "/nope")
if handle != nil {
t.Fatalf("Got handle for unregistered pattern: %v", handle)
}
if tsr {
t.Error("Got wrong TSR recommendation!")
}
// insert route and try again
router.GET("/user/:name", wantHandle)
handle, params, tsr := router.Lookup("GET", "/user/gopher")
if handle == nil {
t.Fatal("Got no handle!")
} else {
handle(nil, nil, nil)
if !routed {
t.Fatal("Routing failed!")
}
}
if !reflect.DeepEqual(params, wantParams) {
t.Fatalf("Wrong parameter values: want %v, got %v", wantParams, params)
}
handle, _, tsr = router.Lookup("GET", "/user/gopher/")
if handle != nil {
t.Fatalf("Got handle for unregistered pattern: %v", handle)
}
if !tsr {
t.Error("Got no TSR recommendation!")
}
handle, _, tsr = router.Lookup("GET", "/nope")
if handle != nil {
t.Fatalf("Got handle for unregistered pattern: %v", handle)
}
if tsr {
t.Error("Got wrong TSR recommendation!")
}
}
type mockFileSystem struct {
opened bool
}
func (mfs *mockFileSystem) Open(name string) (http.File, error) {
mfs.opened = true
return nil, errors.New("this is just a mock")
}
func TestRouterServeFiles(t *testing.T) {
router := New()
mfs := &mockFileSystem{}
recv := catchPanic(func() {
router.ServeFiles("/noFilepath", mfs)
})
if recv == nil {
t.Fatal("registering path not ending with '*filepath' did not panic")
}
router.ServeFiles("/*filepath", mfs)
w := new(mockResponseWriter)
r, _ := http.NewRequest("GET", "/favicon.ico", nil)
router.ServeHTTP(w, r)
if !mfs.opened {
t.Error("serving file failed")
}
}
| mit |
Vegetam/BoostrapPageGenerator4 | bootstap 4 alpha 6/ckeditor/plugins/bidi/lang/zh.js | 260 | /*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'bidi', 'zh', {
ltr: '文字方向從左至右',
rtl: '文字方向從右至左'
} );
| mit |
Blueteak/SteamVR_Unity_Toolkit | Assets/VRTK/Scripts/Helper/VRTK_UIGraphicRaycaster.cs | 6493 | namespace VRTK
{
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class VRTK_UIGraphicRaycaster : GraphicRaycaster
{
public GameObject raycastSource;
private struct VRGraphic
{
public Graphic graphic;
public float distance;
public Vector3 position;
public Vector2 pointerPosition;
}
private Canvas m_Canvas;
private Vector2 lastKnownPosition;
private const float UI_CONTROL_OFFSET = 0.00001f;
[NonSerialized]
private List<VRGraphic> m_RaycastResults = new List<VRGraphic>();
[NonSerialized]
private static readonly List<VRGraphic> s_SortedGraphics = new List<VRGraphic>();
public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
{
if (canvas == null)
{
return;
}
m_RaycastResults.Clear();
var ray = new Ray(eventData.pointerCurrentRaycast.worldPosition, eventData.pointerCurrentRaycast.worldNormal);
Raycast(canvas, eventCamera, ray, m_RaycastResults);
SetNearestRaycast(ref eventData, resultAppendList);
}
private void SetNearestRaycast(ref PointerEventData eventData, List<RaycastResult> resultAppendList)
{
RaycastResult? nearestRaycast = null;
for (var index = 0; index < m_RaycastResults.Count; index++)
{
RaycastResult castResult = new RaycastResult();
castResult.gameObject = m_RaycastResults[index].graphic.gameObject;
castResult.module = this;
castResult.distance = m_RaycastResults[index].distance;
castResult.screenPosition = m_RaycastResults[index].pointerPosition;
castResult.worldPosition = m_RaycastResults[index].position;
castResult.index = resultAppendList.Count;
castResult.depth = m_RaycastResults[index].graphic.depth;
castResult.sortingLayer = canvas.sortingLayerID;
castResult.sortingOrder = canvas.sortingOrder;
if (!nearestRaycast.HasValue || castResult.distance < nearestRaycast.Value.distance)
{
nearestRaycast = castResult;
}
resultAppendList.Add(castResult);
}
if (nearestRaycast.HasValue)
{
eventData.position = nearestRaycast.Value.screenPosition;
eventData.delta = eventData.position - lastKnownPosition;
lastKnownPosition = eventData.position;
eventData.pointerCurrentRaycast = nearestRaycast.Value;
}
}
private float GetHitDistance(Ray ray)
{
var hitDistance = float.MaxValue;
if (canvas.renderMode != RenderMode.ScreenSpaceOverlay && blockingObjects != BlockingObjects.None)
{
var maxDistance = Vector3.Distance(ray.origin, canvas.transform.position);
if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All)
{
RaycastHit hit;
Physics.Raycast(ray, out hit, maxDistance);
if (hit.collider && !hit.collider.GetComponent<VRTK_PlayerObject>())
{
hitDistance = hit.distance;
}
}
if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All)
{
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, maxDistance);
if (hit.collider != null && !hit.collider.GetComponent<VRTK_PlayerObject>())
{
hitDistance = hit.fraction * maxDistance;
}
}
}
return hitDistance;
}
private void Raycast(Canvas canvas, Camera eventCamera, Ray ray, List<VRGraphic> results)
{
var hitDistance = GetHitDistance(ray);
var canvasGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas);
for (int i = 0; i < canvasGraphics.Count; ++i)
{
var graphic = canvasGraphics[i];
if (graphic.depth == -1 || !graphic.raycastTarget)
{
continue;
}
var graphicTransform = graphic.transform;
Vector3 graphicFormward = graphicTransform.forward;
float distance = (Vector3.Dot(graphicFormward, graphicTransform.position - ray.origin) / Vector3.Dot(graphicFormward, ray.direction));
if (distance < 0)
{
continue;
}
if ((distance - UI_CONTROL_OFFSET) > hitDistance)
{
continue;
}
Vector3 position = ray.GetPoint(distance);
Vector2 pointerPosition = eventCamera.WorldToScreenPoint(position);
if (!RectTransformUtility.RectangleContainsScreenPoint(graphic.rectTransform, pointerPosition, eventCamera))
{
continue;
}
if (graphic.Raycast(pointerPosition, eventCamera))
{
var vrGraphic = new VRGraphic();
vrGraphic.graphic = graphic;
vrGraphic.position = position;
vrGraphic.distance = distance;
vrGraphic.pointerPosition = pointerPosition;
s_SortedGraphics.Add(vrGraphic);
}
}
s_SortedGraphics.Sort((g1, g2) => g2.graphic.depth.CompareTo(g1.graphic.depth));
for (int i = 0; i < s_SortedGraphics.Count; ++i)
{
results.Add(s_SortedGraphics[i]);
}
s_SortedGraphics.Clear();
}
private Canvas canvas
{
get
{
if (m_Canvas != null)
{
return m_Canvas;
}
m_Canvas = gameObject.GetComponent<Canvas>();
return m_Canvas;
}
}
}
} | mit |
SaloGala/angular-es | public/docs/_examples/attribute-directives/ts/app/app.component.ts | 184 | // #docregion
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent { }
// #enddocregion
| mit |
juristr/angular | packages/core/test/metadata/resource_loading_spec.ts | 6191 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component} from '../../src/core';
import {clearResolutionOfComponentResourcesQueue, isComponentResourceResolutionQueueEmpty, resolveComponentResources} from '../../src/metadata/resource_loading';
import {ComponentType} from '../../src/render3/interfaces/definition';
import {compileComponent} from '../../src/render3/jit/directive';
describe('resource_loading', () => {
afterEach(clearResolutionOfComponentResourcesQueue);
describe('error handling', () => {
it('should throw an error when compiling component that has unresolved templateUrl', () => {
const MyComponent: ComponentType<any> = (class MyComponent{}) as any;
compileComponent(MyComponent, {templateUrl: 'someUrl'});
expect(() => MyComponent.ngComponentDef).toThrowError(`
Component 'MyComponent' is not resolved:
- templateUrl: someUrl
Did you run and wait for 'resolveComponentResources()'?`.trim());
});
it('should throw an error when compiling component that has unresolved styleUrls', () => {
const MyComponent: ComponentType<any> = (class MyComponent{}) as any;
compileComponent(MyComponent, {styleUrls: ['someUrl1', 'someUrl2']});
expect(() => MyComponent.ngComponentDef).toThrowError(`
Component 'MyComponent' is not resolved:
- styleUrls: ["someUrl1","someUrl2"]
Did you run and wait for 'resolveComponentResources()'?`.trim());
});
it('should throw an error when compiling component that has unresolved templateUrl and styleUrls',
() => {
const MyComponent: ComponentType<any> = (class MyComponent{}) as any;
compileComponent(
MyComponent, {templateUrl: 'someUrl', styleUrls: ['someUrl1', 'someUrl2']});
expect(() => MyComponent.ngComponentDef).toThrowError(`
Component 'MyComponent' is not resolved:
- templateUrl: someUrl
- styleUrls: ["someUrl1","someUrl2"]
Did you run and wait for 'resolveComponentResources()'?`.trim());
});
});
describe('resolution', () => {
const URLS: {[url: string]: Promise<string>} = {
'test://content': Promise.resolve('content'),
'test://style1': Promise.resolve('style1'),
'test://style2': Promise.resolve('style2'),
};
let resourceFetchCount: number;
function testResolver(url: string): Promise<string> {
resourceFetchCount++;
return URLS[url] || Promise.reject('NOT_FOUND: ' + url);
}
beforeEach(() => resourceFetchCount = 0);
it('should resolve template', async() => {
const MyComponent: ComponentType<any> = (class MyComponent{}) as any;
const metadata: Component = {templateUrl: 'test://content'};
compileComponent(MyComponent, metadata);
await resolveComponentResources(testResolver);
expect(MyComponent.ngComponentDef).toBeDefined();
expect(metadata.template).toBe('content');
expect(resourceFetchCount).toBe(1);
});
it('should resolve styleUrls', async() => {
const MyComponent: ComponentType<any> = (class MyComponent{}) as any;
const metadata: Component = {template: '', styleUrls: ['test://style1', 'test://style2']};
compileComponent(MyComponent, metadata);
await resolveComponentResources(testResolver);
expect(MyComponent.ngComponentDef).toBeDefined();
expect(metadata.styleUrls).toBe(undefined);
expect(metadata.styles).toEqual(['style1', 'style2']);
expect(resourceFetchCount).toBe(2);
});
it('should cache multiple resolution to same URL', async() => {
const MyComponent: ComponentType<any> = (class MyComponent{}) as any;
const metadata: Component = {template: '', styleUrls: ['test://style1', 'test://style1']};
compileComponent(MyComponent, metadata);
await resolveComponentResources(testResolver);
expect(MyComponent.ngComponentDef).toBeDefined();
expect(metadata.styleUrls).toBe(undefined);
expect(metadata.styles).toEqual(['style1', 'style1']);
expect(resourceFetchCount).toBe(1);
});
it('should keep order even if the resolution is out of order', async() => {
const MyComponent: ComponentType<any> = (class MyComponent{}) as any;
const metadata: Component = {
template: '',
styles: ['existing'],
styleUrls: ['test://style1', 'test://style2']
};
compileComponent(MyComponent, metadata);
const resolvers: any[] = [];
const resolved = resolveComponentResources(
(url) => new Promise((resolve, response) => resolvers.push(url, resolve)));
// Out of order resolution
expect(resolvers[0]).toEqual('test://style1');
expect(resolvers[2]).toEqual('test://style2');
resolvers[3]('second');
resolvers[1]('first');
await resolved;
expect(metadata.styleUrls).toBe(undefined);
expect(metadata.styles).toEqual(['existing', 'first', 'second']);
});
it('should not add components without external resources to resolution queue', () => {
const MyComponent: ComponentType<any> = (class MyComponent{}) as any;
const MyComponent2: ComponentType<any> = (class MyComponent{}) as any;
compileComponent(MyComponent, {template: ''});
expect(isComponentResourceResolutionQueueEmpty()).toBe(true);
compileComponent(MyComponent2, {templateUrl: 'test://template'});
expect(isComponentResourceResolutionQueueEmpty()).toBe(false);
});
});
describe('fetch', () => {
function fetch(url: string): Promise<Response> {
return Promise.resolve({
text() { return 'response for ' + url; }
} as any as Response);
}
it('should work with fetch', async() => {
const MyComponent: ComponentType<any> = (class MyComponent{}) as any;
const metadata: Component = {templateUrl: 'test://content'};
compileComponent(MyComponent, metadata);
await resolveComponentResources(fetch);
expect(MyComponent.ngComponentDef).toBeDefined();
expect(metadata.template).toBe('response for test://content');
});
});
});
| mit |
yifanjiang/osem | app/controllers/commercials_controller.rb | 1655 | class CommercialsController < ApplicationController
load_resource :conference, find_by: :short_title
before_action :set_event
load_and_authorize_resource through: :event
def new
@commercial = @event.commercials.build
authorize! :new, @commercial
end
def edit; end
def create
@commercial = @event.commercials.build(commercial_params)
authorize! :create, @commercial
if @commercial.save
redirect_to edit_conference_proposal_path(conference_id: @conference.short_title, id: @event.id, anchor: 'commercials-content'),
notice: 'Commercial was successfully created.'
else
flash[:error] = "An error prohibited this Commercial from being saved: #{@commercial.errors.full_messages.join('. ')}."
render :new
end
end
def update
if @commercial.update(commercial_params)
redirect_to edit_conference_proposal_path(conference_id: @conference.short_title, id: @event.id, anchor: 'commercials-content'),
notice: 'Commercial was successfully updated.'
else
flash[:error] = "An error prohibited this Commercial from being saved: #{@commercial.errors.full_messages.join('. ')}."
render :edit
end
end
def destroy
@commercial.destroy
redirect_to edit_conference_proposal_path(conference_id: @conference.short_title, id: @event.id),
notice: 'Commercial was successfully destroyed.'
end
private
def set_event
@event = @conference.events.find(params[:proposal_id])
end
def commercial_params
#params.require(:commercial).permit(:commercial_id, :commercial_type)
params[:commercial]
end
end
| mit |
YatharthROCK/agar | libraries/processing.py-0202-macosx/examples.py/Topics/AdvancedData/list_example.py | 1641 | """
* List of objects
* based on ArrayListClass Daniel Shiffman.
*
* This example demonstrates how to use a Python list to store
* a variable number of objects. Items can be added and removed
* from the list.
*
* Click the mouse to add bouncing balls.
"""
balls = []
ballWidth = 48
# Simple bouncing ball class
class Ball:
def __init__(self, tempX, tempY, tempW):
self.x = tempX
self.y = tempY
self.w = tempW
self.speed = 0
self.gravity = 0.1
self.life = 255
def move(self):
# Add gravity to speed
self.speed = self.speed + self.gravity
# Add speed to y location
self.y = self.y + self.speed
# If square reaches the bottom
# Reverse speed
if self.y > height:
# Dampening
self.speed = self.speed * -0.8
self.y = height
self.life -= 1
def finished(self):
# Balls fade out
return self.life < 0
def display(self):
# Display the circle
fill(0, self.life)
#stroke(0,life)
ellipse(self.x, self.y, self.w, self.w)
def setup():
size(200, 200)
smooth()
noStroke()
# Start by adding one element
balls.append(Ball(width / 2, 0, ballWidth))
def draw():
background(255)
# Count down backwards from the end of the list
for ball in reversed(balls):
ball.move()
ball.display()
if ball.finished():
balls.remove(ball)
def mousePressed():
# A new ball object is added to the list (by default to the end)
balls.append(Ball(mouseX, mouseY, ballWidth))
| mit |
mono/debugger-libs | Mono.Debugger.Soft/Mono.Debugger.Soft/SuspendPolicy.cs | 149 |
namespace Mono.Debugger.Soft
{
// Keep it in sync with debugger-agent.h
public enum SuspendPolicy {
None = 0,
EventThread = 1,
All = 2
}
}
| mit |
ensemblr/llvm-project-boilerplate | include/llvm/projects/test-suite/MultiSource/Benchmarks/7zip/CPP/7zip/Compress/LZMA_Alone/LzmaBench.cpp | 24921 | // LzmaBench.cpp
#include "StdAfx.h"
#include "LzmaBench.h"
#ifndef _WIN32
#define USE_POSIX_TIME
#define USE_POSIX_TIME2
#endif
#ifdef USE_POSIX_TIME
#include <time.h>
#ifdef USE_POSIX_TIME2
#include <sys/time.h>
#endif
#endif
#ifdef _WIN32
#define USE_ALLOCA
#endif
#ifdef USE_ALLOCA
#ifdef _WIN32
#include <malloc.h>
#else
#include <stdlib.h>
#endif
#endif
#include "../../../../C/7zCrc.h"
#include "../../../../C/Alloc.h"
#include "../../../Common/MyCom.h"
#ifdef BENCH_MT
#include "../../../Windows/Synchronization.h"
#include "../../../Windows/Thread.h"
#endif
#ifdef EXTERNAL_LZMA
#include "../../../Windows/PropVariant.h"
#include "../../ICoder.h"
#else
#include "../LzmaDecoder.h"
#include "../LzmaEncoder.h"
#endif
static const UInt32 kUncompressMinBlockSize = 1 << 26;
static const UInt32 kAdditionalSize = (1 << 16);
static const UInt32 kCompressedAdditionalSize = (1 << 10);
static const UInt32 kMaxLzmaPropSize = 5;
class CBaseRandomGenerator
{
UInt32 A1;
UInt32 A2;
public:
CBaseRandomGenerator() { Init(); }
void Init() { A1 = 362436069; A2 = 521288629;}
UInt32 GetRnd()
{
return
((A1 = 36969 * (A1 & 0xffff) + (A1 >> 16)) << 16) +
((A2 = 18000 * (A2 & 0xffff) + (A2 >> 16)) );
}
};
class CBenchBuffer
{
public:
size_t BufferSize;
Byte *Buffer;
CBenchBuffer(): Buffer(0) {}
virtual ~CBenchBuffer() { Free(); }
void Free()
{
::MidFree(Buffer);
Buffer = 0;
}
bool Alloc(size_t bufferSize)
{
if (Buffer != 0 && BufferSize == bufferSize)
return true;
Free();
Buffer = (Byte *)::MidAlloc(bufferSize);
BufferSize = bufferSize;
return (Buffer != 0);
}
};
class CBenchRandomGenerator: public CBenchBuffer
{
CBaseRandomGenerator *RG;
public:
void Set(CBaseRandomGenerator *rg) { RG = rg; }
UInt32 GetVal(UInt32 &res, int numBits)
{
UInt32 val = res & (((UInt32)1 << numBits) - 1);
res >>= numBits;
return val;
}
UInt32 GetLen(UInt32 &res)
{
UInt32 len = GetVal(res, 2);
return GetVal(res, 1 + len);
}
void Generate()
{
UInt32 pos = 0;
UInt32 rep0 = 1;
while (pos < BufferSize)
{
UInt32 res = RG->GetRnd();
res >>= 1;
if (GetVal(res, 1) == 0 || pos < 1024)
Buffer[pos++] = (Byte)(res & 0xFF);
else
{
UInt32 len;
len = 1 + GetLen(res);
if (GetVal(res, 3) != 0)
{
len += GetLen(res);
do
{
UInt32 ppp = GetVal(res, 5) + 6;
res = RG->GetRnd();
if (ppp > 30)
continue;
rep0 = /* (1 << ppp) +*/ GetVal(res, ppp);
res = RG->GetRnd();
}
while (rep0 >= pos);
rep0++;
}
for (UInt32 i = 0; i < len && pos < BufferSize; i++, pos++)
Buffer[pos] = Buffer[pos - rep0];
}
}
}
};
class CBenchmarkInStream:
public ISequentialInStream,
public CMyUnknownImp
{
const Byte *Data;
size_t Pos;
size_t Size;
public:
MY_UNKNOWN_IMP
void Init(const Byte *data, size_t size)
{
Data = data;
Size = size;
Pos = 0;
}
STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
};
STDMETHODIMP CBenchmarkInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
{
size_t remain = Size - Pos;
UInt32 kMaxBlockSize = (1 << 20);
if (size > kMaxBlockSize)
size = kMaxBlockSize;
if (size > remain)
size = (UInt32)remain;
for (UInt32 i = 0; i < size; i++)
((Byte *)data)[i] = Data[Pos + i];
Pos += size;
if(processedSize != NULL)
*processedSize = size;
return S_OK;
}
class CBenchmarkOutStream:
public ISequentialOutStream,
public CBenchBuffer,
public CMyUnknownImp
{
// bool _overflow;
public:
UInt32 Pos;
// CBenchmarkOutStream(): _overflow(false) {}
void Init()
{
// _overflow = false;
Pos = 0;
}
MY_UNKNOWN_IMP
STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
};
STDMETHODIMP CBenchmarkOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)
{
size_t curSize = BufferSize - Pos;
if (curSize > size)
curSize = size;
memcpy(Buffer + Pos, data, curSize);
Pos += (UInt32)curSize;
if(processedSize != NULL)
*processedSize = (UInt32)curSize;
if (curSize != size)
{
// _overflow = true;
return E_FAIL;
}
return S_OK;
}
class CCrcOutStream:
public ISequentialOutStream,
public CMyUnknownImp
{
public:
UInt32 Crc;
MY_UNKNOWN_IMP
void Init() { Crc = CRC_INIT_VAL; }
STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
};
STDMETHODIMP CCrcOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)
{
Crc = CrcUpdate(Crc, data, size);
if (processedSize != NULL)
*processedSize = size;
return S_OK;
}
static UInt64 GetTimeCount()
{
#ifdef USE_POSIX_TIME
#ifdef USE_POSIX_TIME2
timeval v;
if (gettimeofday(&v, 0) == 0)
return (UInt64)(v.tv_sec) * 1000000 + v.tv_usec;
return (UInt64)time(NULL) * 1000000;
#else
return time(NULL);
#endif
#else
/*
LARGE_INTEGER value;
if (::QueryPerformanceCounter(&value))
return value.QuadPart;
*/
return GetTickCount();
#endif
}
static UInt64 GetFreq()
{
#ifdef USE_POSIX_TIME
#ifdef USE_POSIX_TIME2
return 1000000;
#else
return 1;
#endif
#else
/*
LARGE_INTEGER value;
if (::QueryPerformanceFrequency(&value))
return value.QuadPart;
*/
return 1000;
#endif
}
#ifndef USE_POSIX_TIME
static inline UInt64 GetTime64(const FILETIME &t) { return ((UInt64)t.dwHighDateTime << 32) | t.dwLowDateTime; }
#endif
static UInt64 GetUserTime()
{
#ifdef USE_POSIX_TIME
return clock();
#else
FILETIME creationTime, exitTime, kernelTime, userTime;
if (::GetProcessTimes(::GetCurrentProcess(), &creationTime, &exitTime, &kernelTime, &userTime) != 0)
return GetTime64(userTime) + GetTime64(kernelTime);
return (UInt64)GetTickCount() * 10000;
#endif
}
static UInt64 GetUserFreq()
{
#ifdef USE_POSIX_TIME
return CLOCKS_PER_SEC;
#else
return 10000000;
#endif
}
class CBenchProgressStatus
{
#ifdef BENCH_MT
NWindows::NSynchronization::CCriticalSection CS;
#endif
public:
HRESULT Res;
bool EncodeMode;
void SetResult(HRESULT res)
{
#ifdef BENCH_MT
NWindows::NSynchronization::CCriticalSectionLock lock(CS);
#endif
Res = res;
}
HRESULT GetResult()
{
#ifdef BENCH_MT
NWindows::NSynchronization::CCriticalSectionLock lock(CS);
#endif
return Res;
}
};
class CBenchProgressInfo:
public ICompressProgressInfo,
public CMyUnknownImp
{
public:
CBenchProgressStatus *Status;
CBenchInfo BenchInfo;
HRESULT Res;
IBenchCallback *callback;
CBenchProgressInfo(): callback(0) {}
MY_UNKNOWN_IMP
STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize);
};
void SetStartTime(CBenchInfo &bi)
{
bi.GlobalFreq = GetFreq();
bi.UserFreq = GetUserFreq();
bi.GlobalTime = ::GetTimeCount();
bi.UserTime = ::GetUserTime();
}
void SetFinishTime(const CBenchInfo &biStart, CBenchInfo &dest)
{
dest.GlobalFreq = GetFreq();
dest.UserFreq = GetUserFreq();
dest.GlobalTime = ::GetTimeCount() - biStart.GlobalTime;
dest.UserTime = ::GetUserTime() - biStart.UserTime;
}
STDMETHODIMP CBenchProgressInfo::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)
{
HRESULT res = Status->GetResult();
if (res != S_OK)
return res;
if (!callback)
return res;
CBenchInfo info = BenchInfo;
SetFinishTime(BenchInfo, info);
if (Status->EncodeMode)
{
info.UnpackSize = *inSize;
info.PackSize = *outSize;
res = callback->SetEncodeResult(info, false);
}
else
{
info.PackSize = BenchInfo.PackSize + *inSize;
info.UnpackSize = BenchInfo.UnpackSize + *outSize;
res = callback->SetDecodeResult(info, false);
}
if (res != S_OK)
Status->SetResult(res);
return res;
}
static const int kSubBits = 8;
static UInt32 GetLogSize(UInt32 size)
{
for (int i = kSubBits; i < 32; i++)
for (UInt32 j = 0; j < (1 << kSubBits); j++)
if (size <= (((UInt32)1) << i) + (j << (i - kSubBits)))
return (i << kSubBits) + j;
return (32 << kSubBits);
}
static void NormalizeVals(UInt64 &v1, UInt64 &v2)
{
while (v1 > 1000000)
{
v1 >>= 1;
v2 >>= 1;
}
}
UInt64 GetUsage(const CBenchInfo &info)
{
UInt64 userTime = info.UserTime;
UInt64 userFreq = info.UserFreq;
UInt64 globalTime = info.GlobalTime;
UInt64 globalFreq = info.GlobalFreq;
NormalizeVals(userTime, userFreq);
NormalizeVals(globalFreq, globalTime);
if (userFreq == 0)
userFreq = 1;
if (globalTime == 0)
globalTime = 1;
return userTime * globalFreq * 1000000 / userFreq / globalTime;
}
UInt64 GetRatingPerUsage(const CBenchInfo &info, UInt64 rating)
{
UInt64 userTime = info.UserTime;
UInt64 userFreq = info.UserFreq;
UInt64 globalTime = info.GlobalTime;
UInt64 globalFreq = info.GlobalFreq;
NormalizeVals(userFreq, userTime);
NormalizeVals(globalTime, globalFreq);
if (globalFreq == 0)
globalFreq = 1;
if (userTime == 0)
userTime = 1;
return userFreq * globalTime / globalFreq * rating / userTime;
}
static UInt64 MyMultDiv64(UInt64 value, UInt64 elapsedTime, UInt64 freq)
{
UInt64 elTime = elapsedTime;
NormalizeVals(freq, elTime);
if (elTime == 0)
elTime = 1;
return value * freq / elTime;
}
UInt64 GetCompressRating(UInt32 dictionarySize, UInt64 elapsedTime, UInt64 freq, UInt64 size)
{
UInt64 t = GetLogSize(dictionarySize) - (kBenchMinDicLogSize << kSubBits);
UInt64 numCommandsForOne = 870 + ((t * t * 5) >> (2 * kSubBits));
UInt64 numCommands = (UInt64)(size) * numCommandsForOne;
return MyMultDiv64(numCommands, elapsedTime, freq);
}
UInt64 GetDecompressRating(UInt64 elapsedTime, UInt64 freq, UInt64 outSize, UInt64 inSize, UInt32 numIterations)
{
UInt64 numCommands = (inSize * 200 + outSize * 4) * numIterations;
return MyMultDiv64(numCommands, elapsedTime, freq);
}
#ifdef EXTERNAL_LZMA
typedef UInt32 (WINAPI * CreateObjectPointer)(const GUID *clsID,
const GUID *interfaceID, void **outObject);
#endif
struct CEncoderInfo;
struct CEncoderInfo
{
#ifdef BENCH_MT
NWindows::CThread thread[2];
#endif
CMyComPtr<ICompressCoder> encoder;
CBenchProgressInfo *progressInfoSpec[2];
CMyComPtr<ICompressProgressInfo> progressInfo[2];
UInt32 NumIterations;
#ifdef USE_ALLOCA
size_t AllocaSize;
#endif
struct CDecoderInfo
{
CEncoderInfo *Encoder;
UInt32 DecoderIndex;
#ifdef USE_ALLOCA
size_t AllocaSize;
#endif
bool CallbackMode;
};
CDecoderInfo decodersInfo[2];
CMyComPtr<ICompressCoder> decoders[2];
HRESULT Results[2];
CBenchmarkOutStream *outStreamSpec;
CMyComPtr<ISequentialOutStream> outStream;
IBenchCallback *callback;
UInt32 crc;
UInt32 kBufferSize;
UInt32 compressedSize;
CBenchRandomGenerator rg;
CBenchmarkOutStream *propStreamSpec;
CMyComPtr<ISequentialOutStream> propStream;
HRESULT Init(UInt32 dictionarySize, UInt32 numThreads, CBaseRandomGenerator *rg);
HRESULT Encode();
HRESULT Decode(UInt32 decoderIndex);
CEncoderInfo(): outStreamSpec(0), callback(0), propStreamSpec(0) {}
#ifdef BENCH_MT
static THREAD_FUNC_DECL EncodeThreadFunction(void *param)
{
CEncoderInfo *encoder = (CEncoderInfo *)param;
#ifdef USE_ALLOCA
alloca(encoder->AllocaSize);
#endif
HRESULT res = encoder->Encode();
encoder->Results[0] = res;
if (res != S_OK)
encoder->progressInfoSpec[0]->Status->SetResult(res);
return 0;
}
static THREAD_FUNC_DECL DecodeThreadFunction(void *param)
{
CDecoderInfo *decoder = (CDecoderInfo *)param;
#ifdef USE_ALLOCA
alloca(decoder->AllocaSize);
#endif
CEncoderInfo *encoder = decoder->Encoder;
encoder->Results[decoder->DecoderIndex] = encoder->Decode(decoder->DecoderIndex);
return 0;
}
HRESULT CreateEncoderThread()
{
return thread[0].Create(EncodeThreadFunction, this);
}
HRESULT CreateDecoderThread(int index, bool callbackMode
#ifdef USE_ALLOCA
, size_t allocaSize
#endif
)
{
CDecoderInfo &decoder = decodersInfo[index];
decoder.DecoderIndex = index;
decoder.Encoder = this;
#ifdef USE_ALLOCA
decoder.AllocaSize = allocaSize;
#endif
decoder.CallbackMode = callbackMode;
return thread[index].Create(DecodeThreadFunction, &decoder);
}
#endif
};
HRESULT CEncoderInfo::Init(UInt32 dictionarySize, UInt32 numThreads, CBaseRandomGenerator *rgLoc)
{
rg.Set(rgLoc);
kBufferSize = dictionarySize + kAdditionalSize;
UInt32 kCompressedBufferSize = (kBufferSize / 2) + kCompressedAdditionalSize;
if (!rg.Alloc(kBufferSize))
return E_OUTOFMEMORY;
rg.Generate();
crc = CrcCalc(rg.Buffer, rg.BufferSize);
outStreamSpec = new CBenchmarkOutStream;
if (!outStreamSpec->Alloc(kCompressedBufferSize))
return E_OUTOFMEMORY;
outStream = outStreamSpec;
propStreamSpec = 0;
if (!propStream)
{
propStreamSpec = new CBenchmarkOutStream;
propStream = propStreamSpec;
}
if (!propStreamSpec->Alloc(kMaxLzmaPropSize))
return E_OUTOFMEMORY;
propStreamSpec->Init();
PROPID propIDs[] =
{
NCoderPropID::kDictionarySize,
NCoderPropID::kNumThreads
};
const int kNumProps = sizeof(propIDs) / sizeof(propIDs[0]);
PROPVARIANT props[kNumProps];
props[0].vt = VT_UI4;
props[0].ulVal = dictionarySize;
props[1].vt = VT_UI4;
props[1].ulVal = numThreads;
{
CMyComPtr<ICompressSetCoderProperties> setCoderProperties;
RINOK(encoder.QueryInterface(IID_ICompressSetCoderProperties, &setCoderProperties));
if (!setCoderProperties)
return E_FAIL;
RINOK(setCoderProperties->SetCoderProperties(propIDs, props, kNumProps));
CMyComPtr<ICompressWriteCoderProperties> writeCoderProperties;
encoder.QueryInterface(IID_ICompressWriteCoderProperties, &writeCoderProperties);
if (writeCoderProperties)
{
RINOK(writeCoderProperties->WriteCoderProperties(propStream));
}
}
return S_OK;
}
HRESULT CEncoderInfo::Encode()
{
CBenchmarkInStream *inStreamSpec = new CBenchmarkInStream;
CMyComPtr<ISequentialInStream> inStream = inStreamSpec;
inStreamSpec->Init(rg.Buffer, rg.BufferSize);
outStreamSpec->Init();
RINOK(encoder->Code(inStream, outStream, 0, 0, progressInfo[0]));
compressedSize = outStreamSpec->Pos;
encoder.Release();
return S_OK;
}
HRESULT CEncoderInfo::Decode(UInt32 decoderIndex)
{
CBenchmarkInStream *inStreamSpec = new CBenchmarkInStream;
CMyComPtr<ISequentialInStream> inStream = inStreamSpec;
CMyComPtr<ICompressCoder> &decoder = decoders[decoderIndex];
CMyComPtr<ICompressSetDecoderProperties2> compressSetDecoderProperties;
decoder.QueryInterface(IID_ICompressSetDecoderProperties2, &compressSetDecoderProperties);
if (!compressSetDecoderProperties)
return E_FAIL;
CCrcOutStream *crcOutStreamSpec = new CCrcOutStream;
CMyComPtr<ISequentialOutStream> crcOutStream = crcOutStreamSpec;
CBenchProgressInfo *pi = progressInfoSpec[decoderIndex];
pi->BenchInfo.UnpackSize = 0;
pi->BenchInfo.PackSize = 0;
for (UInt32 j = 0; j < NumIterations; j++)
{
inStreamSpec->Init(outStreamSpec->Buffer, compressedSize);
crcOutStreamSpec->Init();
RINOK(compressSetDecoderProperties->SetDecoderProperties2(propStreamSpec->Buffer, propStreamSpec->Pos));
UInt64 outSize = kBufferSize;
RINOK(decoder->Code(inStream, crcOutStream, 0, &outSize, progressInfo[decoderIndex]));
if (CRC_GET_DIGEST(crcOutStreamSpec->Crc) != crc)
return S_FALSE;
pi->BenchInfo.UnpackSize += kBufferSize;
pi->BenchInfo.PackSize += compressedSize;
}
decoder.Release();
return S_OK;
}
static const UInt32 kNumThreadsMax = (1 << 16);
struct CBenchEncoders
{
CEncoderInfo *encoders;
CBenchEncoders(UInt32 num): encoders(0) { encoders = new CEncoderInfo[num]; }
~CBenchEncoders() { delete []encoders; }
};
HRESULT LzmaBench(
#ifdef EXTERNAL_LZMA
CCodecs *codecs,
#endif
UInt32 numThreads, UInt32 dictionarySize, IBenchCallback *callback)
{
UInt32 numEncoderThreads =
#ifdef BENCH_MT
(numThreads > 1 ? numThreads / 2 : 1);
#else
1;
#endif
UInt32 numSubDecoderThreads =
#ifdef BENCH_MT
(numThreads > 1 ? 2 : 1);
#else
1;
#endif
if (dictionarySize < (1 << kBenchMinDicLogSize) || numThreads < 1 || numEncoderThreads > kNumThreadsMax)
{
return E_INVALIDARG;
}
CBenchEncoders encodersSpec(numEncoderThreads);
CEncoderInfo *encoders = encodersSpec.encoders;
#ifdef EXTERNAL_LZMA
UString name = L"LZMA";
#endif
UInt32 i;
for (i = 0; i < numEncoderThreads; i++)
{
CEncoderInfo &encoder = encoders[i];
encoder.callback = (i == 0) ? callback : 0;
#ifdef EXTERNAL_LZMA
RINOK(codecs->CreateCoder(name, true, encoder.encoder));
#else
encoder.encoder = new NCompress::NLzma::CEncoder;
#endif
for (UInt32 j = 0; j < numSubDecoderThreads; j++)
{
#ifdef EXTERNAL_LZMA
RINOK(codecs->CreateCoder(name, false, encoder.decoders[j]));
#else
encoder.decoders[j] = new NCompress::NLzma::CDecoder;
#endif
}
}
CBaseRandomGenerator rg;
rg.Init();
for (i = 0; i < numEncoderThreads; i++)
{
RINOK(encoders[i].Init(dictionarySize, numThreads, &rg));
}
CBenchProgressStatus status;
status.Res = S_OK;
status.EncodeMode = true;
for (i = 0; i < numEncoderThreads; i++)
{
CEncoderInfo &encoder = encoders[i];
for (int j = 0; j < 2; j++)
{
encoder.progressInfo[j] = encoder.progressInfoSpec[j] = new CBenchProgressInfo;
encoder.progressInfoSpec[j]->Status = &status;
}
if (i == 0)
{
encoder.progressInfoSpec[0]->callback = callback;
encoder.progressInfoSpec[0]->BenchInfo.NumIterations = numEncoderThreads;
SetStartTime(encoder.progressInfoSpec[0]->BenchInfo);
}
#ifdef BENCH_MT
if (numEncoderThreads > 1)
{
#ifdef USE_ALLOCA
encoder.AllocaSize = (i * 16 * 21) & 0x7FF;
#endif
RINOK(encoder.CreateEncoderThread())
}
else
#endif
{
RINOK(encoder.Encode());
}
}
#ifdef BENCH_MT
if (numEncoderThreads > 1)
for (i = 0; i < numEncoderThreads; i++)
encoders[i].thread[0].Wait();
#endif
RINOK(status.Res);
CBenchInfo info;
SetFinishTime(encoders[0].progressInfoSpec[0]->BenchInfo, info);
info.UnpackSize = 0;
info.PackSize = 0;
info.NumIterations = 1; // progressInfoSpec->NumIterations;
for (i = 0; i < numEncoderThreads; i++)
{
CEncoderInfo &encoder = encoders[i];
info.UnpackSize += encoder.kBufferSize;
info.PackSize += encoder.compressedSize;
}
RINOK(callback->SetEncodeResult(info, true));
status.Res = S_OK;
status.EncodeMode = false;
UInt32 numDecoderThreads = numEncoderThreads * numSubDecoderThreads;
for (i = 0; i < numEncoderThreads; i++)
{
CEncoderInfo &encoder = encoders[i];
encoder.NumIterations = 2 + kUncompressMinBlockSize / encoder.kBufferSize;
if (i == 0)
{
encoder.progressInfoSpec[0]->callback = callback;
encoder.progressInfoSpec[0]->BenchInfo.NumIterations = numDecoderThreads;
SetStartTime(encoder.progressInfoSpec[0]->BenchInfo);
}
#ifdef BENCH_MT
if (numDecoderThreads > 1)
{
for (UInt32 j = 0; j < numSubDecoderThreads; j++)
{
HRESULT res = encoder.CreateDecoderThread(j, (i == 0 && j == 0)
#ifdef USE_ALLOCA
, ((i * numSubDecoderThreads + j) * 16 * 21) & 0x7FF
#endif
);
RINOK(res);
}
}
else
#endif
{
RINOK(encoder.Decode(0));
}
}
#ifdef BENCH_MT
HRESULT res = S_OK;
if (numDecoderThreads > 1)
for (i = 0; i < numEncoderThreads; i++)
for (UInt32 j = 0; j < numSubDecoderThreads; j++)
{
CEncoderInfo &encoder = encoders[i];
encoder.thread[j].Wait();
if (encoder.Results[j] != S_OK)
res = encoder.Results[j];
}
RINOK(res);
#endif
RINOK(status.Res);
SetFinishTime(encoders[0].progressInfoSpec[0]->BenchInfo, info);
info.UnpackSize = 0;
info.PackSize = 0;
info.NumIterations = numSubDecoderThreads * encoders[0].NumIterations;
for (i = 0; i < numEncoderThreads; i++)
{
CEncoderInfo &encoder = encoders[i];
info.UnpackSize += encoder.kBufferSize;
info.PackSize += encoder.compressedSize;
}
RINOK(callback->SetDecodeResult(info, false));
RINOK(callback->SetDecodeResult(info, true));
return S_OK;
}
inline UInt64 GetLZMAUsage(bool multiThread, UInt32 dictionary)
{
UInt32 hs = dictionary - 1;
hs |= (hs >> 1);
hs |= (hs >> 2);
hs |= (hs >> 4);
hs |= (hs >> 8);
hs >>= 1;
hs |= 0xFFFF;
if (hs > (1 << 24))
hs >>= 1;
hs++;
return ((hs + (1 << 16)) + (UInt64)dictionary * 2) * 4 + (UInt64)dictionary * 3 / 2 +
(1 << 20) + (multiThread ? (6 << 20) : 0);
}
UInt64 GetBenchMemoryUsage(UInt32 numThreads, UInt32 dictionary)
{
const UInt32 kBufferSize = dictionary;
const UInt32 kCompressedBufferSize = (kBufferSize / 2);
UInt32 numSubThreads = (numThreads > 1) ? 2 : 1;
UInt32 numBigThreads = numThreads / numSubThreads;
return (kBufferSize + kCompressedBufferSize +
GetLZMAUsage((numThreads > 1), dictionary) + (2 << 20)) * numBigThreads;
}
static bool CrcBig(const void *data, UInt32 size, UInt32 numCycles, UInt32 crcBase)
{
for (UInt32 i = 0; i < numCycles; i++)
if (CrcCalc(data, size) != crcBase)
return false;
return true;
}
#ifdef BENCH_MT
struct CCrcInfo
{
NWindows::CThread Thread;
const Byte *Data;
UInt32 Size;
UInt32 NumCycles;
UInt32 Crc;
bool Res;
void Wait()
{
Thread.Wait();
Thread.Close();
}
};
static THREAD_FUNC_DECL CrcThreadFunction(void *param)
{
CCrcInfo *p = (CCrcInfo *)param;
p->Res = CrcBig(p->Data, p->Size, p->NumCycles, p->Crc);
return 0;
}
struct CCrcThreads
{
UInt32 NumThreads;
CCrcInfo *Items;
CCrcThreads(): Items(0), NumThreads(0) {}
void WaitAll()
{
for (UInt32 i = 0; i < NumThreads; i++)
Items[i].Wait();
NumThreads = 0;
}
~CCrcThreads()
{
WaitAll();
delete []Items;
}
};
#endif
static UInt32 CrcCalc1(const Byte *buf, UInt32 size)
{
UInt32 crc = CRC_INIT_VAL;;
for (UInt32 i = 0; i < size; i++)
crc = CRC_UPDATE_BYTE(crc, buf[i]);
return CRC_GET_DIGEST(crc);
}
static void RandGen(Byte *buf, UInt32 size, CBaseRandomGenerator &RG)
{
for (UInt32 i = 0; i < size; i++)
buf[i] = (Byte)RG.GetRnd();
}
static UInt32 RandGenCrc(Byte *buf, UInt32 size, CBaseRandomGenerator &RG)
{
RandGen(buf, size, RG);
return CrcCalc1(buf, size);
}
bool CrcInternalTest()
{
CBenchBuffer buffer;
const UInt32 kBufferSize0 = (1 << 8);
const UInt32 kBufferSize1 = (1 << 10);
const UInt32 kCheckSize = (1 << 5);
if (!buffer.Alloc(kBufferSize0 + kBufferSize1))
return false;
Byte *buf = buffer.Buffer;
UInt32 i;
for (i = 0; i < kBufferSize0; i++)
buf[i] = (Byte)i;
UInt32 crc1 = CrcCalc1(buf, kBufferSize0);
if (crc1 != 0x29058C73)
return false;
CBaseRandomGenerator RG;
RandGen(buf + kBufferSize0, kBufferSize1, RG);
for (i = 0; i < kBufferSize0 + kBufferSize1 - kCheckSize; i++)
for (UInt32 j = 0; j < kCheckSize; j++)
if (CrcCalc1(buf + i, j) != CrcCalc(buf + i, j))
return false;
return true;
}
HRESULT CrcBench(UInt32 numThreads, UInt32 bufferSize, UInt64 &speed)
{
if (numThreads == 0)
numThreads = 1;
CBenchBuffer buffer;
size_t totalSize = (size_t)bufferSize * numThreads;
if (totalSize / numThreads != bufferSize)
return E_OUTOFMEMORY;
if (!buffer.Alloc(totalSize))
return E_OUTOFMEMORY;
Byte *buf = buffer.Buffer;
CBaseRandomGenerator RG;
UInt32 numCycles = ((UInt32)1 << 30) / ((bufferSize >> 2) + 1) + 1;
UInt64 timeVal;
#ifdef BENCH_MT
CCrcThreads threads;
if (numThreads > 1)
{
threads.Items = new CCrcInfo[numThreads];
UInt32 i;
for (i = 0; i < numThreads; i++)
{
CCrcInfo &info = threads.Items[i];
Byte *data = buf + (size_t)bufferSize * i;
info.Data = data;
info.NumCycles = numCycles;
info.Size = bufferSize;
info.Crc = RandGenCrc(data, bufferSize, RG);
}
timeVal = GetTimeCount();
for (i = 0; i < numThreads; i++)
{
CCrcInfo &info = threads.Items[i];
RINOK(info.Thread.Create(CrcThreadFunction, &info));
threads.NumThreads++;
}
threads.WaitAll();
for (i = 0; i < numThreads; i++)
if (!threads.Items[i].Res)
return S_FALSE;
}
else
#endif
{
UInt32 crc = RandGenCrc(buf, bufferSize, RG);
timeVal = GetTimeCount();
if (!CrcBig(buf, bufferSize, numCycles, crc))
return S_FALSE;
}
timeVal = GetTimeCount() - timeVal;
if (timeVal == 0)
timeVal = 1;
UInt64 size = (UInt64)numCycles * totalSize;
speed = MyMultDiv64(size, timeVal, GetFreq());
return S_OK;
}
| mit |
nice-fungal/ldaptive | lib/messages/compare_request.js | 1655 | // Copyright 2011 Mark Cavage, Inc. All rights reserved.
var assert = require('assert-plus');
var util = require('util');
var LDAPMessage = require('./message');
var Protocol = require('../protocol');
var lassert = require('../assert');
///--- API
function CompareRequest(options) {
options = options || {};
assert.object(options);
assert.optionalString(options.attribute);
assert.optionalString(options.value);
lassert.optionalStringDN(options.entry);
options.protocolOp = Protocol.LDAP_REQ_COMPARE;
LDAPMessage.call(this, options);
this.entry = options.entry || null;
this.attribute = options.attribute || '';
this.value = options.value || '';
}
util.inherits(CompareRequest, LDAPMessage);
Object.defineProperties(CompareRequest.prototype, {
type: {
get: function getType() { return 'CompareRequest'; },
configurable: false
},
_dn: {
get: function getDN() { return this.entry; },
configurable: false
}
});
CompareRequest.prototype._parse = function (ber) {
assert.ok(ber);
this.entry = ber.readString();
ber.readSequence();
this.attribute = ber.readString().toLowerCase();
this.value = ber.readString();
return true;
};
CompareRequest.prototype._toBer = function (ber) {
assert.ok(ber);
ber.writeString(this.entry.toString());
ber.startSequence();
ber.writeString(this.attribute);
ber.writeString(this.value);
ber.endSequence();
return ber;
};
CompareRequest.prototype._json = function (j) {
assert.ok(j);
j.entry = this.entry.toString();
j.attribute = this.attribute;
j.value = this.value;
return j;
};
///--- Exports
module.exports = CompareRequest;
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.