code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
// Package storage provides access to the Cloud Storage JSON API.
//
// See https://developers.google.com/storage/docs/json_api/
//
// Usage example:
//
// import "google.golang.org/api/storage/v1"
// ...
// storageService, err := storage.New(oauthHttpClient)
package storage // import "google.golang.org/api/storage/v1"
import (
"bytes"
"encoding/json"
"errors"
"fmt"
context "golang.org/x/net/context"
ctxhttp "golang.org/x/net/context/ctxhttp"
gensupport "google.golang.org/api/gensupport"
googleapi "google.golang.org/api/googleapi"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = gensupport.MarshalJSON
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = context.Canceled
var _ = ctxhttp.Do
const apiId = "storage:v1"
const apiName = "storage"
const apiVersion = "v1"
const basePath = "https://www.googleapis.com/storage/v1/"
// OAuth2 scopes used by this API.
const (
// View and manage your data across Google Cloud Platform services
CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
// View your data across Google Cloud Platform services
CloudPlatformReadOnlyScope = "https://www.googleapis.com/auth/cloud-platform.read-only"
// Manage your data and permissions in Google Cloud Storage
DevstorageFullControlScope = "https://www.googleapis.com/auth/devstorage.full_control"
// View your data in Google Cloud Storage
DevstorageReadOnlyScope = "https://www.googleapis.com/auth/devstorage.read_only"
// Manage your data in Google Cloud Storage
DevstorageReadWriteScope = "https://www.googleapis.com/auth/devstorage.read_write"
)
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.BucketAccessControls = NewBucketAccessControlsService(s)
s.Buckets = NewBucketsService(s)
s.Channels = NewChannelsService(s)
s.DefaultObjectAccessControls = NewDefaultObjectAccessControlsService(s)
s.ObjectAccessControls = NewObjectAccessControlsService(s)
s.Objects = NewObjectsService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
BucketAccessControls *BucketAccessControlsService
Buckets *BucketsService
Channels *ChannelsService
DefaultObjectAccessControls *DefaultObjectAccessControlsService
ObjectAccessControls *ObjectAccessControlsService
Objects *ObjectsService
}
func (s *Service) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewBucketAccessControlsService(s *Service) *BucketAccessControlsService {
rs := &BucketAccessControlsService{s: s}
return rs
}
type BucketAccessControlsService struct {
s *Service
}
func NewBucketsService(s *Service) *BucketsService {
rs := &BucketsService{s: s}
return rs
}
type BucketsService struct {
s *Service
}
func NewChannelsService(s *Service) *ChannelsService {
rs := &ChannelsService{s: s}
return rs
}
type ChannelsService struct {
s *Service
}
func NewDefaultObjectAccessControlsService(s *Service) *DefaultObjectAccessControlsService {
rs := &DefaultObjectAccessControlsService{s: s}
return rs
}
type DefaultObjectAccessControlsService struct {
s *Service
}
func NewObjectAccessControlsService(s *Service) *ObjectAccessControlsService {
rs := &ObjectAccessControlsService{s: s}
return rs
}
type ObjectAccessControlsService struct {
s *Service
}
func NewObjectsService(s *Service) *ObjectsService {
rs := &ObjectsService{s: s}
return rs
}
type ObjectsService struct {
s *Service
}
// Bucket: A bucket.
type Bucket struct {
// Acl: Access controls on the bucket.
Acl []*BucketAccessControl `json:"acl,omitempty"`
// Cors: The bucket's Cross-Origin Resource Sharing (CORS)
// configuration.
Cors []*BucketCors `json:"cors,omitempty"`
// DefaultObjectAcl: Default access controls to apply to new objects
// when no ACL is provided.
DefaultObjectAcl []*ObjectAccessControl `json:"defaultObjectAcl,omitempty"`
// Etag: HTTP 1.1 Entity tag for the bucket.
Etag string `json:"etag,omitempty"`
// Id: The ID of the bucket. For buckets, the id and name properities
// are the same.
Id string `json:"id,omitempty"`
// Kind: The kind of item this is. For buckets, this is always
// storage#bucket.
Kind string `json:"kind,omitempty"`
// Lifecycle: The bucket's lifecycle configuration. See lifecycle
// management for more information.
Lifecycle *BucketLifecycle `json:"lifecycle,omitempty"`
// Location: The location of the bucket. Object data for objects in the
// bucket resides in physical storage within this region. Defaults to
// US. See the developer's guide for the authoritative list.
Location string `json:"location,omitempty"`
// Logging: The bucket's logging configuration, which defines the
// destination bucket and optional name prefix for the current bucket's
// logs.
Logging *BucketLogging `json:"logging,omitempty"`
// Metageneration: The metadata generation of this bucket.
Metageneration int64 `json:"metageneration,omitempty,string"`
// Name: The name of the bucket.
Name string `json:"name,omitempty"`
// Owner: The owner of the bucket. This is always the project team's
// owner group.
Owner *BucketOwner `json:"owner,omitempty"`
// ProjectNumber: The project number of the project the bucket belongs
// to.
ProjectNumber uint64 `json:"projectNumber,omitempty,string"`
// SelfLink: The URI of this bucket.
SelfLink string `json:"selfLink,omitempty"`
// StorageClass: The bucket's default storage class, used whenever no
// storageClass is specified for a newly-created object. This defines
// how objects in the bucket are stored and determines the SLA and the
// cost of storage. Values include MULTI_REGIONAL, REGIONAL, STANDARD,
// NEARLINE, COLDLINE, and DURABLE_REDUCED_AVAILABILITY. If this value
// is not specified when the bucket is created, it will default to
// STANDARD. For more information, see storage classes.
StorageClass string `json:"storageClass,omitempty"`
// TimeCreated: The creation time of the bucket in RFC 3339 format.
TimeCreated string `json:"timeCreated,omitempty"`
// Updated: The modification time of the bucket in RFC 3339 format.
Updated string `json:"updated,omitempty"`
// Versioning: The bucket's versioning configuration.
Versioning *BucketVersioning `json:"versioning,omitempty"`
// Website: The bucket's website configuration, controlling how the
// service behaves when accessing bucket contents as a web site. See the
// Static Website Examples for more information.
Website *BucketWebsite `json:"website,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Acl") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Acl") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Bucket) MarshalJSON() ([]byte, error) {
type noMethod Bucket
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type BucketCors struct {
// MaxAgeSeconds: The value, in seconds, to return in the
// Access-Control-Max-Age header used in preflight responses.
MaxAgeSeconds int64 `json:"maxAgeSeconds,omitempty"`
// Method: The list of HTTP methods on which to include CORS response
// headers, (GET, OPTIONS, POST, etc) Note: "*" is permitted in the list
// of methods, and means "any method".
Method []string `json:"method,omitempty"`
// Origin: The list of Origins eligible to receive CORS response
// headers. Note: "*" is permitted in the list of origins, and means
// "any Origin".
Origin []string `json:"origin,omitempty"`
// ResponseHeader: The list of HTTP headers other than the simple
// response headers to give permission for the user-agent to share
// across domains.
ResponseHeader []string `json:"responseHeader,omitempty"`
// ForceSendFields is a list of field names (e.g. "MaxAgeSeconds") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MaxAgeSeconds") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketCors) MarshalJSON() ([]byte, error) {
type noMethod BucketCors
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketLifecycle: The bucket's lifecycle configuration. See lifecycle
// management for more information.
type BucketLifecycle struct {
// Rule: A lifecycle management rule, which is made of an action to take
// and the condition(s) under which the action will be taken.
Rule []*BucketLifecycleRule `json:"rule,omitempty"`
// ForceSendFields is a list of field names (e.g. "Rule") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Rule") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLifecycle) MarshalJSON() ([]byte, error) {
type noMethod BucketLifecycle
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type BucketLifecycleRule struct {
// Action: The action to take.
Action *BucketLifecycleRuleAction `json:"action,omitempty"`
// Condition: The condition(s) under which the action will be taken.
Condition *BucketLifecycleRuleCondition `json:"condition,omitempty"`
// ForceSendFields is a list of field names (e.g. "Action") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Action") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLifecycleRule) MarshalJSON() ([]byte, error) {
type noMethod BucketLifecycleRule
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketLifecycleRuleAction: The action to take.
type BucketLifecycleRuleAction struct {
// StorageClass: Target storage class. Required iff the type of the
// action is SetStorageClass.
StorageClass string `json:"storageClass,omitempty"`
// Type: Type of the action. Currently, only Delete and SetStorageClass
// are supported.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "StorageClass") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "StorageClass") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLifecycleRuleAction) MarshalJSON() ([]byte, error) {
type noMethod BucketLifecycleRuleAction
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketLifecycleRuleCondition: The condition(s) under which the action
// will be taken.
type BucketLifecycleRuleCondition struct {
// Age: Age of an object (in days). This condition is satisfied when an
// object reaches the specified age.
Age int64 `json:"age,omitempty"`
// CreatedBefore: A date in RFC 3339 format with only the date part (for
// instance, "2013-01-15"). This condition is satisfied when an object
// is created before midnight of the specified date in UTC.
CreatedBefore string `json:"createdBefore,omitempty"`
// IsLive: Relevant only for versioned objects. If the value is true,
// this condition matches live objects; if the value is false, it
// matches archived objects.
IsLive bool `json:"isLive,omitempty"`
// MatchesStorageClass: Objects having any of the storage classes
// specified by this condition will be matched. Values include
// MULTI_REGIONAL, REGIONAL, NEARLINE, COLDLINE, STANDARD, and
// DURABLE_REDUCED_AVAILABILITY.
MatchesStorageClass []string `json:"matchesStorageClass,omitempty"`
// NumNewerVersions: Relevant only for versioned objects. If the value
// is N, this condition is satisfied when there are at least N versions
// (including the live version) newer than this version of the object.
NumNewerVersions int64 `json:"numNewerVersions,omitempty"`
// ForceSendFields is a list of field names (e.g. "Age") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Age") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLifecycleRuleCondition) MarshalJSON() ([]byte, error) {
type noMethod BucketLifecycleRuleCondition
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketLogging: The bucket's logging configuration, which defines the
// destination bucket and optional name prefix for the current bucket's
// logs.
type BucketLogging struct {
// LogBucket: The destination bucket where the current bucket's logs
// should be placed.
LogBucket string `json:"logBucket,omitempty"`
// LogObjectPrefix: A prefix for log object names.
LogObjectPrefix string `json:"logObjectPrefix,omitempty"`
// ForceSendFields is a list of field names (e.g. "LogBucket") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LogBucket") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketLogging) MarshalJSON() ([]byte, error) {
type noMethod BucketLogging
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketOwner: The owner of the bucket. This is always the project
// team's owner group.
type BucketOwner struct {
// Entity: The entity, in the form project-owner-projectId.
Entity string `json:"entity,omitempty"`
// EntityId: The ID for the entity.
EntityId string `json:"entityId,omitempty"`
// ForceSendFields is a list of field names (e.g. "Entity") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Entity") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketOwner) MarshalJSON() ([]byte, error) {
type noMethod BucketOwner
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketVersioning: The bucket's versioning configuration.
type BucketVersioning struct {
// Enabled: While set to true, versioning is fully enabled for this
// bucket.
Enabled bool `json:"enabled,omitempty"`
// ForceSendFields is a list of field names (e.g. "Enabled") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Enabled") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketVersioning) MarshalJSON() ([]byte, error) {
type noMethod BucketVersioning
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketWebsite: The bucket's website configuration, controlling how
// the service behaves when accessing bucket contents as a web site. See
// the Static Website Examples for more information.
type BucketWebsite struct {
// MainPageSuffix: If the requested object path is missing, the service
// will ensure the path has a trailing '/', append this suffix, and
// attempt to retrieve the resulting object. This allows the creation of
// index.html objects to represent directory pages.
MainPageSuffix string `json:"mainPageSuffix,omitempty"`
// NotFoundPage: If the requested object path is missing, and any
// mainPageSuffix object is missing, if applicable, the service will
// return the named object from this bucket as the content for a 404 Not
// Found result.
NotFoundPage string `json:"notFoundPage,omitempty"`
// ForceSendFields is a list of field names (e.g. "MainPageSuffix") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MainPageSuffix") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *BucketWebsite) MarshalJSON() ([]byte, error) {
type noMethod BucketWebsite
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketAccessControl: An access-control entry.
type BucketAccessControl struct {
// Bucket: The name of the bucket.
Bucket string `json:"bucket,omitempty"`
// Domain: The domain associated with the entity, if any.
Domain string `json:"domain,omitempty"`
// Email: The email address associated with the entity, if any.
Email string `json:"email,omitempty"`
// Entity: The entity holding the permission, in one of the following
// forms:
// - user-userId
// - user-email
// - group-groupId
// - group-email
// - domain-domain
// - project-team-projectId
// - allUsers
// - allAuthenticatedUsers Examples:
// - The user liz@example.com would be user-liz@example.com.
// - The group example@googlegroups.com would be
// group-example@googlegroups.com.
// - To refer to all members of the Google Apps for Business domain
// example.com, the entity would be domain-example.com.
Entity string `json:"entity,omitempty"`
// EntityId: The ID for the entity, if any.
EntityId string `json:"entityId,omitempty"`
// Etag: HTTP 1.1 Entity tag for the access-control entry.
Etag string `json:"etag,omitempty"`
// Id: The ID of the access-control entry.
Id string `json:"id,omitempty"`
// Kind: The kind of item this is. For bucket access control entries,
// this is always storage#bucketAccessControl.
Kind string `json:"kind,omitempty"`
// ProjectTeam: The project team associated with the entity, if any.
ProjectTeam *BucketAccessControlProjectTeam `json:"projectTeam,omitempty"`
// Role: The access permission for the entity.
Role string `json:"role,omitempty"`
// SelfLink: The link to this access-control entry.
SelfLink string `json:"selfLink,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Bucket") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Bucket") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketAccessControl) MarshalJSON() ([]byte, error) {
type noMethod BucketAccessControl
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketAccessControlProjectTeam: The project team associated with the
// entity, if any.
type BucketAccessControlProjectTeam struct {
// ProjectNumber: The project number.
ProjectNumber string `json:"projectNumber,omitempty"`
// Team: The team.
Team string `json:"team,omitempty"`
// ForceSendFields is a list of field names (e.g. "ProjectNumber") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ProjectNumber") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketAccessControlProjectTeam) MarshalJSON() ([]byte, error) {
type noMethod BucketAccessControlProjectTeam
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BucketAccessControls: An access-control list.
type BucketAccessControls struct {
// Items: The list of items.
Items []*BucketAccessControl `json:"items,omitempty"`
// Kind: The kind of item this is. For lists of bucket access control
// entries, this is always storage#bucketAccessControls.
Kind string `json:"kind,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Items") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Items") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BucketAccessControls) MarshalJSON() ([]byte, error) {
type noMethod BucketAccessControls
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Buckets: A list of buckets.
type Buckets struct {
// Items: The list of items.
Items []*Bucket `json:"items,omitempty"`
// Kind: The kind of item this is. For lists of buckets, this is always
// storage#buckets.
Kind string `json:"kind,omitempty"`
// NextPageToken: The continuation token, used to page through large
// result sets. Provide this value in a subsequent request to return the
// next page of results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Items") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Items") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Buckets) MarshalJSON() ([]byte, error) {
type noMethod Buckets
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Channel: An notification channel used to watch for resource changes.
type Channel struct {
// Address: The address where notifications are delivered for this
// channel.
Address string `json:"address,omitempty"`
// Expiration: Date and time of notification channel expiration,
// expressed as a Unix timestamp, in milliseconds. Optional.
Expiration int64 `json:"expiration,omitempty,string"`
// Id: A UUID or similar unique string that identifies this channel.
Id string `json:"id,omitempty"`
// Kind: Identifies this as a notification channel used to watch for
// changes to a resource. Value: the fixed string "api#channel".
Kind string `json:"kind,omitempty"`
// Params: Additional parameters controlling delivery channel behavior.
// Optional.
Params map[string]string `json:"params,omitempty"`
// Payload: A Boolean value to indicate whether payload is wanted.
// Optional.
Payload bool `json:"payload,omitempty"`
// ResourceId: An opaque ID that identifies the resource being watched
// on this channel. Stable across different API versions.
ResourceId string `json:"resourceId,omitempty"`
// ResourceUri: A version-specific identifier for the watched resource.
ResourceUri string `json:"resourceUri,omitempty"`
// Token: An arbitrary string delivered to the target address with each
// notification delivered over this channel. Optional.
Token string `json:"token,omitempty"`
// Type: The type of delivery mechanism used for this channel.
Type string `json:"type,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Address") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Address") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Channel) MarshalJSON() ([]byte, error) {
type noMethod Channel
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ComposeRequest: A Compose request.
type ComposeRequest struct {
// Destination: Properties of the resulting object.
Destination *Object `json:"destination,omitempty"`
// Kind: The kind of item this is.
Kind string `json:"kind,omitempty"`
// SourceObjects: The list of source objects that will be concatenated
// into a single object.
SourceObjects []*ComposeRequestSourceObjects `json:"sourceObjects,omitempty"`
// ForceSendFields is a list of field names (e.g. "Destination") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Destination") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ComposeRequest) MarshalJSON() ([]byte, error) {
type noMethod ComposeRequest
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type ComposeRequestSourceObjects struct {
// Generation: The generation of this object to use as the source.
Generation int64 `json:"generation,omitempty,string"`
// Name: The source object's name. The source object's bucket is
// implicitly the destination bucket.
Name string `json:"name,omitempty"`
// ObjectPreconditions: Conditions that must be met for this operation
// to execute.
ObjectPreconditions *ComposeRequestSourceObjectsObjectPreconditions `json:"objectPreconditions,omitempty"`
// ForceSendFields is a list of field names (e.g. "Generation") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Generation") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ComposeRequestSourceObjects) MarshalJSON() ([]byte, error) {
type noMethod ComposeRequestSourceObjects
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ComposeRequestSourceObjectsObjectPreconditions: Conditions that must
// be met for this operation to execute.
type ComposeRequestSourceObjectsObjectPreconditions struct {
// IfGenerationMatch: Only perform the composition if the generation of
// the source object that would be used matches this value. If this
// value and a generation are both specified, they must be the same
// value or the call will fail.
IfGenerationMatch int64 `json:"ifGenerationMatch,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "IfGenerationMatch")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IfGenerationMatch") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ComposeRequestSourceObjectsObjectPreconditions) MarshalJSON() ([]byte, error) {
type noMethod ComposeRequestSourceObjectsObjectPreconditions
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Object: An object.
type Object struct {
// Acl: Access controls on the object.
Acl []*ObjectAccessControl `json:"acl,omitempty"`
// Bucket: The name of the bucket containing this object.
Bucket string `json:"bucket,omitempty"`
// CacheControl: Cache-Control directive for the object data. If
// omitted, and the object is accessible to all anonymous users, the
// default will be public, max-age=3600.
CacheControl string `json:"cacheControl,omitempty"`
// ComponentCount: Number of underlying components that make up this
// object. Components are accumulated by compose operations.
ComponentCount int64 `json:"componentCount,omitempty"`
// ContentDisposition: Content-Disposition of the object data.
ContentDisposition string `json:"contentDisposition,omitempty"`
// ContentEncoding: Content-Encoding of the object data.
ContentEncoding string `json:"contentEncoding,omitempty"`
// ContentLanguage: Content-Language of the object data.
ContentLanguage string `json:"contentLanguage,omitempty"`
// ContentType: Content-Type of the object data. If contentType is not
// specified, object downloads will be served as
// application/octet-stream.
ContentType string `json:"contentType,omitempty"`
// Crc32c: CRC32c checksum, as described in RFC 4960, Appendix B;
// encoded using base64 in big-endian byte order. For more information
// about using the CRC32c checksum, see Hashes and ETags: Best
// Practices.
Crc32c string `json:"crc32c,omitempty"`
// CustomerEncryption: Metadata of customer-supplied encryption key, if
// the object is encrypted by such a key.
CustomerEncryption *ObjectCustomerEncryption `json:"customerEncryption,omitempty"`
// Etag: HTTP 1.1 Entity tag for the object.
Etag string `json:"etag,omitempty"`
// Generation: The content generation of this object. Used for object
// versioning.
Generation int64 `json:"generation,omitempty,string"`
// Id: The ID of the object, including the bucket name, object name, and
// generation number.
Id string `json:"id,omitempty"`
// Kind: The kind of item this is. For objects, this is always
// storage#object.
Kind string `json:"kind,omitempty"`
// Md5Hash: MD5 hash of the data; encoded using base64. For more
// information about using the MD5 hash, see Hashes and ETags: Best
// Practices.
Md5Hash string `json:"md5Hash,omitempty"`
// MediaLink: Media download link.
MediaLink string `json:"mediaLink,omitempty"`
// Metadata: User-provided metadata, in key/value pairs.
Metadata map[string]string `json:"metadata,omitempty"`
// Metageneration: The version of the metadata for this object at this
// generation. Used for preconditions and for detecting changes in
// metadata. A metageneration number is only meaningful in the context
// of a particular generation of a particular object.
Metageneration int64 `json:"metageneration,omitempty,string"`
// Name: The name of the object. Required if not specified by URL
// parameter.
Name string `json:"name,omitempty"`
// Owner: The owner of the object. This will always be the uploader of
// the object.
Owner *ObjectOwner `json:"owner,omitempty"`
// SelfLink: The link to this object.
SelfLink string `json:"selfLink,omitempty"`
// Size: Content-Length of the data in bytes.
Size uint64 `json:"size,omitempty,string"`
// StorageClass: Storage class of the object.
StorageClass string `json:"storageClass,omitempty"`
// TimeCreated: The creation time of the object in RFC 3339 format.
TimeCreated string `json:"timeCreated,omitempty"`
// TimeDeleted: The deletion time of the object in RFC 3339 format. Will
// be returned if and only if this version of the object has been
// deleted.
TimeDeleted string `json:"timeDeleted,omitempty"`
// TimeStorageClassUpdated: The time at which the object's storage class
// was last changed. When the object is initially created, it will be
// set to timeCreated.
TimeStorageClassUpdated string `json:"timeStorageClassUpdated,omitempty"`
// Updated: The modification time of the object metadata in RFC 3339
// format.
Updated string `json:"updated,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Acl") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Acl") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Object) MarshalJSON() ([]byte, error) {
type noMethod Object
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectCustomerEncryption: Metadata of customer-supplied encryption
// key, if the object is encrypted by such a key.
type ObjectCustomerEncryption struct {
// EncryptionAlgorithm: The encryption algorithm.
EncryptionAlgorithm string `json:"encryptionAlgorithm,omitempty"`
// KeySha256: SHA256 hash value of the encryption key.
KeySha256 string `json:"keySha256,omitempty"`
// ForceSendFields is a list of field names (e.g. "EncryptionAlgorithm")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EncryptionAlgorithm") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ObjectCustomerEncryption) MarshalJSON() ([]byte, error) {
type noMethod ObjectCustomerEncryption
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectOwner: The owner of the object. This will always be the
// uploader of the object.
type ObjectOwner struct {
// Entity: The entity, in the form user-userId.
Entity string `json:"entity,omitempty"`
// EntityId: The ID for the entity.
EntityId string `json:"entityId,omitempty"`
// ForceSendFields is a list of field names (e.g. "Entity") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Entity") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ObjectOwner) MarshalJSON() ([]byte, error) {
type noMethod ObjectOwner
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectAccessControl: An access-control entry.
type ObjectAccessControl struct {
// Bucket: The name of the bucket.
Bucket string `json:"bucket,omitempty"`
// Domain: The domain associated with the entity, if any.
Domain string `json:"domain,omitempty"`
// Email: The email address associated with the entity, if any.
Email string `json:"email,omitempty"`
// Entity: The entity holding the permission, in one of the following
// forms:
// - user-userId
// - user-email
// - group-groupId
// - group-email
// - domain-domain
// - project-team-projectId
// - allUsers
// - allAuthenticatedUsers Examples:
// - The user liz@example.com would be user-liz@example.com.
// - The group example@googlegroups.com would be
// group-example@googlegroups.com.
// - To refer to all members of the Google Apps for Business domain
// example.com, the entity would be domain-example.com.
Entity string `json:"entity,omitempty"`
// EntityId: The ID for the entity, if any.
EntityId string `json:"entityId,omitempty"`
// Etag: HTTP 1.1 Entity tag for the access-control entry.
Etag string `json:"etag,omitempty"`
// Generation: The content generation of the object, if applied to an
// object.
Generation int64 `json:"generation,omitempty,string"`
// Id: The ID of the access-control entry.
Id string `json:"id,omitempty"`
// Kind: The kind of item this is. For object access control entries,
// this is always storage#objectAccessControl.
Kind string `json:"kind,omitempty"`
// Object: The name of the object, if applied to an object.
Object string `json:"object,omitempty"`
// ProjectTeam: The project team associated with the entity, if any.
ProjectTeam *ObjectAccessControlProjectTeam `json:"projectTeam,omitempty"`
// Role: The access permission for the entity.
Role string `json:"role,omitempty"`
// SelfLink: The link to this access-control entry.
SelfLink string `json:"selfLink,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Bucket") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Bucket") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ObjectAccessControl) MarshalJSON() ([]byte, error) {
type noMethod ObjectAccessControl
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectAccessControlProjectTeam: The project team associated with the
// entity, if any.
type ObjectAccessControlProjectTeam struct {
// ProjectNumber: The project number.
ProjectNumber string `json:"projectNumber,omitempty"`
// Team: The team.
Team string `json:"team,omitempty"`
// ForceSendFields is a list of field names (e.g. "ProjectNumber") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ProjectNumber") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ObjectAccessControlProjectTeam) MarshalJSON() ([]byte, error) {
type noMethod ObjectAccessControlProjectTeam
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ObjectAccessControls: An access-control list.
type ObjectAccessControls struct {
// Items: The list of items.
Items []*ObjectAccessControl `json:"items,omitempty"`
// Kind: The kind of item this is. For lists of object access control
// entries, this is always storage#objectAccessControls.
Kind string `json:"kind,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Items") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Items") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ObjectAccessControls) MarshalJSON() ([]byte, error) {
type noMethod ObjectAccessControls
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Objects: A list of objects.
type Objects struct {
// Items: The list of items.
Items []*Object `json:"items,omitempty"`
// Kind: The kind of item this is. For lists of objects, this is always
// storage#objects.
Kind string `json:"kind,omitempty"`
// NextPageToken: The continuation token, used to page through large
// result sets. Provide this value in a subsequent request to return the
// next page of results.
NextPageToken string `json:"nextPageToken,omitempty"`
// Prefixes: The list of prefixes of objects matching-but-not-listed up
// to and including the requested delimiter.
Prefixes []string `json:"prefixes,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Items") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Items") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Objects) MarshalJSON() ([]byte, error) {
type noMethod Objects
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Policy: A bucket/object IAM policy.
type Policy struct {
// Bindings: An association between a role, which comes with a set of
// permissions, and members who may assume that role.
Bindings []*PolicyBindings `json:"bindings,omitempty"`
// Etag: HTTP 1.1 Entity tag for the policy.
Etag string `json:"etag,omitempty"`
// Kind: The kind of item this is. For policies, this is always
// storage#policy. This field is ignored on input.
Kind string `json:"kind,omitempty"`
// ResourceId: The ID of the resource to which this policy belongs. Will
// be of the form buckets/bucket for buckets, and
// buckets/bucket/objects/object for objects. A specific generation may
// be specified by appending #generationNumber to the end of the object
// name, e.g. buckets/my-bucket/objects/data.txt#17. The current
// generation can be denoted with #0. This field is ignored on input.
ResourceId string `json:"resourceId,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Bindings") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Bindings") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Policy) MarshalJSON() ([]byte, error) {
type noMethod Policy
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
type PolicyBindings struct {
// Members: A collection of identifiers for members who may assume the
// provided role. Recognized identifiers are as follows:
// - allUsers — A special identifier that represents anyone on the
// internet; with or without a Google account.
// - allAuthenticatedUsers — A special identifier that represents
// anyone who is authenticated with a Google account or a service
// account.
// - user:emailid — An email address that represents a specific
// account. For example, user:alice@gmail.com or user:joe@example.com.
//
// - serviceAccount:emailid — An email address that represents a
// service account. For example,
// serviceAccount:my-other-app@appspot.gserviceaccount.com .
// - group:emailid — An email address that represents a Google group.
// For example, group:admins@example.com.
// - domain:domain — A Google Apps domain name that represents all the
// users of that domain. For example, domain:google.com or
// domain:example.com.
// - projectOwner:projectid — Owners of the given project. For
// example, projectOwner:my-example-project
// - projectEditor:projectid — Editors of the given project. For
// example, projectEditor:my-example-project
// - projectViewer:projectid — Viewers of the given project. For
// example, projectViewer:my-example-project
Members []string `json:"members,omitempty"`
// Role: The role to which members belong. Two types of roles are
// supported: new IAM roles, which grant permissions that do not map
// directly to those provided by ACLs, and legacy IAM roles, which do
// map directly to ACL permissions. All roles are of the format
// roles/storage.specificRole.
// The new IAM roles are:
// - roles/storage.admin — Full control of Google Cloud Storage
// resources.
// - roles/storage.objectViewer — Read-Only access to Google Cloud
// Storage objects.
// - roles/storage.objectCreator — Access to create objects in Google
// Cloud Storage.
// - roles/storage.objectAdmin — Full control of Google Cloud Storage
// objects. The legacy IAM roles are:
// - roles/storage.legacyObjectReader — Read-only access to objects
// without listing. Equivalent to an ACL entry on an object with the
// READER role.
// - roles/storage.legacyObjectOwner — Read/write access to existing
// objects without listing. Equivalent to an ACL entry on an object with
// the OWNER role.
// - roles/storage.legacyBucketReader — Read access to buckets with
// object listing. Equivalent to an ACL entry on a bucket with the
// READER role.
// - roles/storage.legacyBucketWriter — Read access to buckets with
// object listing/creation/deletion. Equivalent to an ACL entry on a
// bucket with the WRITER role.
// - roles/storage.legacyBucketOwner — Read and write access to
// existing buckets with object listing/creation/deletion. Equivalent to
// an ACL entry on a bucket with the OWNER role.
Role string `json:"role,omitempty"`
// ForceSendFields is a list of field names (e.g. "Members") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Members") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *PolicyBindings) MarshalJSON() ([]byte, error) {
type noMethod PolicyBindings
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// RewriteResponse: A rewrite response.
type RewriteResponse struct {
// Done: true if the copy is finished; otherwise, false if the copy is
// in progress. This property is always present in the response.
Done bool `json:"done,omitempty"`
// Kind: The kind of item this is.
Kind string `json:"kind,omitempty"`
// ObjectSize: The total size of the object being copied in bytes. This
// property is always present in the response.
ObjectSize uint64 `json:"objectSize,omitempty,string"`
// Resource: A resource containing the metadata for the copied-to
// object. This property is present in the response only when copying
// completes.
Resource *Object `json:"resource,omitempty"`
// RewriteToken: A token to use in subsequent requests to continue
// copying data. This token is present in the response only when there
// is more data to copy.
RewriteToken string `json:"rewriteToken,omitempty"`
// TotalBytesRewritten: The total bytes written so far, which can be
// used to provide a waiting user with a progress indicator. This
// property is always present in the response.
TotalBytesRewritten uint64 `json:"totalBytesRewritten,omitempty,string"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Done") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Done") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *RewriteResponse) MarshalJSON() ([]byte, error) {
type noMethod RewriteResponse
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TestIamPermissionsResponse: A
// storage.(buckets|objects).testIamPermissions response.
type TestIamPermissionsResponse struct {
// Kind: The kind of item this is.
Kind string `json:"kind,omitempty"`
// Permissions: The permissions held by the caller. Permissions are
// always of the format storage.resource.capability, where resource is
// one of buckets or objects. The supported permissions are as follows:
//
// - storage.buckets.delete — Delete bucket.
// - storage.buckets.get — Read bucket metadata.
// - storage.buckets.getIamPolicy — Read bucket IAM policy.
// - storage.buckets.create — Create bucket.
// - storage.buckets.list — List buckets.
// - storage.buckets.setIamPolicy — Update bucket IAM policy.
// - storage.buckets.update — Update bucket metadata.
// - storage.objects.delete — Delete object.
// - storage.objects.get — Read object data and metadata.
// - storage.objects.getIamPolicy — Read object IAM policy.
// - storage.objects.create — Create object.
// - storage.objects.list — List objects.
// - storage.objects.setIamPolicy — Update object IAM policy.
// - storage.objects.update — Update object metadata.
Permissions []string `json:"permissions,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Kind") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Kind") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TestIamPermissionsResponse) MarshalJSON() ([]byte, error) {
type noMethod TestIamPermissionsResponse
raw := noMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// method id "storage.bucketAccessControls.delete":
type BucketAccessControlsDeleteCall struct {
s *Service
bucket string
entity string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes the ACL entry for the specified entity on
// the specified bucket.
func (r *BucketAccessControlsService) Delete(bucket string, entity string) *BucketAccessControlsDeleteCall {
c := &BucketAccessControlsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsDeleteCall) Fields(s ...googleapi.Field) *BucketAccessControlsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsDeleteCall) Context(ctx context.Context) *BucketAccessControlsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.delete" call.
func (c *BucketAccessControlsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Permanently deletes the ACL entry for the specified entity on the specified bucket.",
// "httpMethod": "DELETE",
// "id": "storage.bucketAccessControls.delete",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl/{entity}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.get":
type BucketAccessControlsGetCall struct {
s *Service
bucket string
entity string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Returns the ACL entry for the specified entity on the specified
// bucket.
func (r *BucketAccessControlsService) Get(bucket string, entity string) *BucketAccessControlsGetCall {
c := &BucketAccessControlsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsGetCall) Fields(s ...googleapi.Field) *BucketAccessControlsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketAccessControlsGetCall) IfNoneMatch(entityTag string) *BucketAccessControlsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsGetCall) Context(ctx context.Context) *BucketAccessControlsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.get" call.
// Exactly one of *BucketAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsGetCall) Do(opts ...googleapi.CallOption) (*BucketAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the ACL entry for the specified entity on the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.bucketAccessControls.get",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl/{entity}",
// "response": {
// "$ref": "BucketAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.insert":
type BucketAccessControlsInsertCall struct {
s *Service
bucket string
bucketaccesscontrol *BucketAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a new ACL entry on the specified bucket.
func (r *BucketAccessControlsService) Insert(bucket string, bucketaccesscontrol *BucketAccessControl) *BucketAccessControlsInsertCall {
c := &BucketAccessControlsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.bucketaccesscontrol = bucketaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsInsertCall) Fields(s ...googleapi.Field) *BucketAccessControlsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsInsertCall) Context(ctx context.Context) *BucketAccessControlsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucketaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.insert" call.
// Exactly one of *BucketAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsInsertCall) Do(opts ...googleapi.CallOption) (*BucketAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new ACL entry on the specified bucket.",
// "httpMethod": "POST",
// "id": "storage.bucketAccessControls.insert",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl",
// "request": {
// "$ref": "BucketAccessControl"
// },
// "response": {
// "$ref": "BucketAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.list":
type BucketAccessControlsListCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves ACL entries on the specified bucket.
func (r *BucketAccessControlsService) List(bucket string) *BucketAccessControlsListCall {
c := &BucketAccessControlsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsListCall) Fields(s ...googleapi.Field) *BucketAccessControlsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketAccessControlsListCall) IfNoneMatch(entityTag string) *BucketAccessControlsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsListCall) Context(ctx context.Context) *BucketAccessControlsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.list" call.
// Exactly one of *BucketAccessControls or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControls.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsListCall) Do(opts ...googleapi.CallOption) (*BucketAccessControls, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControls{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves ACL entries on the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.bucketAccessControls.list",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl",
// "response": {
// "$ref": "BucketAccessControls"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.patch":
type BucketAccessControlsPatchCall struct {
s *Service
bucket string
entity string
bucketaccesscontrol *BucketAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an ACL entry on the specified bucket. This method
// supports patch semantics.
func (r *BucketAccessControlsService) Patch(bucket string, entity string, bucketaccesscontrol *BucketAccessControl) *BucketAccessControlsPatchCall {
c := &BucketAccessControlsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
c.bucketaccesscontrol = bucketaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsPatchCall) Fields(s ...googleapi.Field) *BucketAccessControlsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsPatchCall) Context(ctx context.Context) *BucketAccessControlsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucketaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.patch" call.
// Exactly one of *BucketAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsPatchCall) Do(opts ...googleapi.CallOption) (*BucketAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an ACL entry on the specified bucket. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.bucketAccessControls.patch",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl/{entity}",
// "request": {
// "$ref": "BucketAccessControl"
// },
// "response": {
// "$ref": "BucketAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.bucketAccessControls.update":
type BucketAccessControlsUpdateCall struct {
s *Service
bucket string
entity string
bucketaccesscontrol *BucketAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates an ACL entry on the specified bucket.
func (r *BucketAccessControlsService) Update(bucket string, entity string, bucketaccesscontrol *BucketAccessControl) *BucketAccessControlsUpdateCall {
c := &BucketAccessControlsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
c.bucketaccesscontrol = bucketaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketAccessControlsUpdateCall) Fields(s ...googleapi.Field) *BucketAccessControlsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketAccessControlsUpdateCall) Context(ctx context.Context) *BucketAccessControlsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketAccessControlsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketAccessControlsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucketaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.bucketAccessControls.update" call.
// Exactly one of *BucketAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *BucketAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketAccessControlsUpdateCall) Do(opts ...googleapi.CallOption) (*BucketAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BucketAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an ACL entry on the specified bucket.",
// "httpMethod": "PUT",
// "id": "storage.bucketAccessControls.update",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/acl/{entity}",
// "request": {
// "$ref": "BucketAccessControl"
// },
// "response": {
// "$ref": "BucketAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.buckets.delete":
type BucketsDeleteCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes an empty bucket.
func (r *BucketsService) Delete(bucket string) *BucketsDeleteCall {
c := &BucketsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": If set, only deletes the bucket if its
// metageneration matches this value.
func (c *BucketsDeleteCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *BucketsDeleteCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": If set, only deletes the bucket if its
// metageneration does not match this value.
func (c *BucketsDeleteCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *BucketsDeleteCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsDeleteCall) Fields(s ...googleapi.Field) *BucketsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsDeleteCall) Context(ctx context.Context) *BucketsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.delete" call.
func (c *BucketsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Permanently deletes an empty bucket.",
// "httpMethod": "DELETE",
// "id": "storage.buckets.delete",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "If set, only deletes the bucket if its metageneration matches this value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "If set, only deletes the bucket if its metageneration does not match this value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.get":
type BucketsGetCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Returns metadata for the specified bucket.
func (r *BucketsService) Get(bucket string) *BucketsGetCall {
c := &BucketsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration matches
// the given value.
func (c *BucketsGetCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *BucketsGetCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration does not
// match the given value.
func (c *BucketsGetCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *BucketsGetCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsGetCall) Projection(projection string) *BucketsGetCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsGetCall) Fields(s ...googleapi.Field) *BucketsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketsGetCall) IfNoneMatch(entityTag string) *BucketsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsGetCall) Context(ctx context.Context) *BucketsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.get" call.
// Exactly one of *Bucket or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Bucket.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsGetCall) Do(opts ...googleapi.CallOption) (*Bucket, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Bucket{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns metadata for the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.buckets.get",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}",
// "response": {
// "$ref": "Bucket"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.getIamPolicy":
type BucketsGetIamPolicyCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Returns an IAM policy for the specified bucket.
func (r *BucketsService) GetIamPolicy(bucket string) *BucketsGetIamPolicyCall {
c := &BucketsGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsGetIamPolicyCall) Fields(s ...googleapi.Field) *BucketsGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketsGetIamPolicyCall) IfNoneMatch(entityTag string) *BucketsGetIamPolicyCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsGetIamPolicyCall) Context(ctx context.Context) *BucketsGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/iam")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns an IAM policy for the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.buckets.getIamPolicy",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/iam",
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.insert":
type BucketsInsertCall struct {
s *Service
bucket *Bucket
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a new bucket.
func (r *BucketsService) Insert(projectid string, bucket *Bucket) *BucketsInsertCall {
c := &BucketsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("project", projectid)
c.bucket = bucket
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Project team owners get OWNER access, and
// allAuthenticatedUsers get READER access.
// "private" - Project team owners get OWNER access.
// "projectPrivate" - Project team members get access according to
// their roles.
// "publicRead" - Project team owners get OWNER access, and allUsers
// get READER access.
// "publicReadWrite" - Project team owners get OWNER access, and
// allUsers get WRITER access.
func (c *BucketsInsertCall) PredefinedAcl(predefinedAcl string) *BucketsInsertCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// PredefinedDefaultObjectAcl sets the optional parameter
// "predefinedDefaultObjectAcl": Apply a predefined set of default
// object access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *BucketsInsertCall) PredefinedDefaultObjectAcl(predefinedDefaultObjectAcl string) *BucketsInsertCall {
c.urlParams_.Set("predefinedDefaultObjectAcl", predefinedDefaultObjectAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl, unless the bucket resource
// specifies acl or defaultObjectAcl properties, when it defaults to
// full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsInsertCall) Projection(projection string) *BucketsInsertCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsInsertCall) Fields(s ...googleapi.Field) *BucketsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsInsertCall) Context(ctx context.Context) *BucketsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucket)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.insert" call.
// Exactly one of *Bucket or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Bucket.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsInsertCall) Do(opts ...googleapi.CallOption) (*Bucket, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Bucket{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new bucket.",
// "httpMethod": "POST",
// "id": "storage.buckets.insert",
// "parameterOrder": [
// "project"
// ],
// "parameters": {
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "private",
// "projectPrivate",
// "publicRead",
// "publicReadWrite"
// ],
// "enumDescriptions": [
// "Project team owners get OWNER access, and allAuthenticatedUsers get READER access.",
// "Project team owners get OWNER access.",
// "Project team members get access according to their roles.",
// "Project team owners get OWNER access, and allUsers get READER access.",
// "Project team owners get OWNER access, and allUsers get WRITER access."
// ],
// "location": "query",
// "type": "string"
// },
// "predefinedDefaultObjectAcl": {
// "description": "Apply a predefined set of default object access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "project": {
// "description": "A valid API project identifier.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b",
// "request": {
// "$ref": "Bucket"
// },
// "response": {
// "$ref": "Bucket"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.list":
type BucketsListCall struct {
s *Service
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves a list of buckets for a given project.
func (r *BucketsService) List(projectid string) *BucketsListCall {
c := &BucketsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.urlParams_.Set("project", projectid)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of buckets to return in a single response. The service will use this
// parameter or 1,000 items, whichever is smaller.
func (c *BucketsListCall) MaxResults(maxResults int64) *BucketsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": A
// previously-returned page token representing part of the larger set of
// results to view.
func (c *BucketsListCall) PageToken(pageToken string) *BucketsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Prefix sets the optional parameter "prefix": Filter results to
// buckets whose names begin with this prefix.
func (c *BucketsListCall) Prefix(prefix string) *BucketsListCall {
c.urlParams_.Set("prefix", prefix)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsListCall) Projection(projection string) *BucketsListCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsListCall) Fields(s ...googleapi.Field) *BucketsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketsListCall) IfNoneMatch(entityTag string) *BucketsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsListCall) Context(ctx context.Context) *BucketsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.list" call.
// Exactly one of *Buckets or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Buckets.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsListCall) Do(opts ...googleapi.CallOption) (*Buckets, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Buckets{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of buckets for a given project.",
// "httpMethod": "GET",
// "id": "storage.buckets.list",
// "parameterOrder": [
// "project"
// ],
// "parameters": {
// "maxResults": {
// "default": "1000",
// "description": "Maximum number of buckets to return in a single response. The service will use this parameter or 1,000 items, whichever is smaller.",
// "format": "uint32",
// "location": "query",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A previously-returned page token representing part of the larger set of results to view.",
// "location": "query",
// "type": "string"
// },
// "prefix": {
// "description": "Filter results to buckets whose names begin with this prefix.",
// "location": "query",
// "type": "string"
// },
// "project": {
// "description": "A valid API project identifier.",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b",
// "response": {
// "$ref": "Buckets"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *BucketsListCall) Pages(ctx context.Context, f func(*Buckets) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "storage.buckets.patch":
type BucketsPatchCall struct {
s *Service
bucket string
bucket2 *Bucket
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates a bucket. Changes to the bucket will be readable
// immediately after writing, but configuration changes may take time to
// propagate. This method supports patch semantics.
func (r *BucketsService) Patch(bucket string, bucket2 *Bucket) *BucketsPatchCall {
c := &BucketsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.bucket2 = bucket2
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration matches
// the given value.
func (c *BucketsPatchCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *BucketsPatchCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration does not
// match the given value.
func (c *BucketsPatchCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *BucketsPatchCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Project team owners get OWNER access, and
// allAuthenticatedUsers get READER access.
// "private" - Project team owners get OWNER access.
// "projectPrivate" - Project team members get access according to
// their roles.
// "publicRead" - Project team owners get OWNER access, and allUsers
// get READER access.
// "publicReadWrite" - Project team owners get OWNER access, and
// allUsers get WRITER access.
func (c *BucketsPatchCall) PredefinedAcl(predefinedAcl string) *BucketsPatchCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// PredefinedDefaultObjectAcl sets the optional parameter
// "predefinedDefaultObjectAcl": Apply a predefined set of default
// object access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *BucketsPatchCall) PredefinedDefaultObjectAcl(predefinedDefaultObjectAcl string) *BucketsPatchCall {
c.urlParams_.Set("predefinedDefaultObjectAcl", predefinedDefaultObjectAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsPatchCall) Projection(projection string) *BucketsPatchCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsPatchCall) Fields(s ...googleapi.Field) *BucketsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsPatchCall) Context(ctx context.Context) *BucketsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucket2)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.patch" call.
// Exactly one of *Bucket or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Bucket.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsPatchCall) Do(opts ...googleapi.CallOption) (*Bucket, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Bucket{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.buckets.patch",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "private",
// "projectPrivate",
// "publicRead",
// "publicReadWrite"
// ],
// "enumDescriptions": [
// "Project team owners get OWNER access, and allAuthenticatedUsers get READER access.",
// "Project team owners get OWNER access.",
// "Project team members get access according to their roles.",
// "Project team owners get OWNER access, and allUsers get READER access.",
// "Project team owners get OWNER access, and allUsers get WRITER access."
// ],
// "location": "query",
// "type": "string"
// },
// "predefinedDefaultObjectAcl": {
// "description": "Apply a predefined set of default object access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}",
// "request": {
// "$ref": "Bucket"
// },
// "response": {
// "$ref": "Bucket"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.buckets.setIamPolicy":
type BucketsSetIamPolicyCall struct {
s *Service
bucket string
policy *Policy
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetIamPolicy: Updates an IAM policy for the specified bucket.
func (r *BucketsService) SetIamPolicy(bucket string, policy *Policy) *BucketsSetIamPolicyCall {
c := &BucketsSetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.policy = policy
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsSetIamPolicyCall) Fields(s ...googleapi.Field) *BucketsSetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsSetIamPolicyCall) Context(ctx context.Context) *BucketsSetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsSetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsSetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.policy)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/iam")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.setIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsSetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an IAM policy for the specified bucket.",
// "httpMethod": "PUT",
// "id": "storage.buckets.setIamPolicy",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/iam",
// "request": {
// "$ref": "Policy"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.testIamPermissions":
type BucketsTestIamPermissionsCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Tests a set of permissions on the given bucket to
// see which, if any, are held by the caller.
func (r *BucketsService) TestIamPermissions(bucket string, permissions []string) *BucketsTestIamPermissionsCall {
c := &BucketsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.urlParams_.SetMulti("permissions", append([]string{}, permissions...))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsTestIamPermissionsCall) Fields(s ...googleapi.Field) *BucketsTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *BucketsTestIamPermissionsCall) IfNoneMatch(entityTag string) *BucketsTestIamPermissionsCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsTestIamPermissionsCall) Context(ctx context.Context) *BucketsTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/iam/testPermissions")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *BucketsTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Tests a set of permissions on the given bucket to see which, if any, are held by the caller.",
// "httpMethod": "GET",
// "id": "storage.buckets.testIamPermissions",
// "parameterOrder": [
// "bucket",
// "permissions"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "permissions": {
// "description": "Permissions to test.",
// "location": "query",
// "repeated": true,
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/iam/testPermissions",
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.buckets.update":
type BucketsUpdateCall struct {
s *Service
bucket string
bucket2 *Bucket
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates a bucket. Changes to the bucket will be readable
// immediately after writing, but configuration changes may take time to
// propagate.
func (r *BucketsService) Update(bucket string, bucket2 *Bucket) *BucketsUpdateCall {
c := &BucketsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.bucket2 = bucket2
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration matches
// the given value.
func (c *BucketsUpdateCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *BucketsUpdateCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the return of the bucket metadata
// conditional on whether the bucket's current metageneration does not
// match the given value.
func (c *BucketsUpdateCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *BucketsUpdateCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Project team owners get OWNER access, and
// allAuthenticatedUsers get READER access.
// "private" - Project team owners get OWNER access.
// "projectPrivate" - Project team members get access according to
// their roles.
// "publicRead" - Project team owners get OWNER access, and allUsers
// get READER access.
// "publicReadWrite" - Project team owners get OWNER access, and
// allUsers get WRITER access.
func (c *BucketsUpdateCall) PredefinedAcl(predefinedAcl string) *BucketsUpdateCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// PredefinedDefaultObjectAcl sets the optional parameter
// "predefinedDefaultObjectAcl": Apply a predefined set of default
// object access controls to this bucket.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *BucketsUpdateCall) PredefinedDefaultObjectAcl(predefinedDefaultObjectAcl string) *BucketsUpdateCall {
c.urlParams_.Set("predefinedDefaultObjectAcl", predefinedDefaultObjectAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit owner, acl and defaultObjectAcl properties.
func (c *BucketsUpdateCall) Projection(projection string) *BucketsUpdateCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *BucketsUpdateCall) Fields(s ...googleapi.Field) *BucketsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *BucketsUpdateCall) Context(ctx context.Context) *BucketsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *BucketsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *BucketsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.bucket2)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.buckets.update" call.
// Exactly one of *Bucket or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Bucket.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *BucketsUpdateCall) Do(opts ...googleapi.CallOption) (*Bucket, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Bucket{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a bucket. Changes to the bucket will be readable immediately after writing, but configuration changes may take time to propagate.",
// "httpMethod": "PUT",
// "id": "storage.buckets.update",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "private",
// "projectPrivate",
// "publicRead",
// "publicReadWrite"
// ],
// "enumDescriptions": [
// "Project team owners get OWNER access, and allAuthenticatedUsers get READER access.",
// "Project team owners get OWNER access.",
// "Project team members get access according to their roles.",
// "Project team owners get OWNER access, and allUsers get READER access.",
// "Project team owners get OWNER access, and allUsers get WRITER access."
// ],
// "location": "query",
// "type": "string"
// },
// "predefinedDefaultObjectAcl": {
// "description": "Apply a predefined set of default object access controls to this bucket.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit owner, acl and defaultObjectAcl properties."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}",
// "request": {
// "$ref": "Bucket"
// },
// "response": {
// "$ref": "Bucket"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.channels.stop":
type ChannelsStopCall struct {
s *Service
channel *Channel
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Stop: Stop watching resources through this channel
func (r *ChannelsService) Stop(channel *Channel) *ChannelsStopCall {
c := &ChannelsStopCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.channel = channel
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ChannelsStopCall) Fields(s ...googleapi.Field) *ChannelsStopCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ChannelsStopCall) Context(ctx context.Context) *ChannelsStopCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ChannelsStopCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ChannelsStopCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "channels/stop")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.channels.stop" call.
func (c *ChannelsStopCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Stop watching resources through this channel",
// "httpMethod": "POST",
// "id": "storage.channels.stop",
// "path": "channels/stop",
// "request": {
// "$ref": "Channel",
// "parameterName": "resource"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.delete":
type DefaultObjectAccessControlsDeleteCall struct {
s *Service
bucket string
entity string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes the default object ACL entry for the
// specified entity on the specified bucket.
func (r *DefaultObjectAccessControlsService) Delete(bucket string, entity string) *DefaultObjectAccessControlsDeleteCall {
c := &DefaultObjectAccessControlsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsDeleteCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsDeleteCall) Context(ctx context.Context) *DefaultObjectAccessControlsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.delete" call.
func (c *DefaultObjectAccessControlsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Permanently deletes the default object ACL entry for the specified entity on the specified bucket.",
// "httpMethod": "DELETE",
// "id": "storage.defaultObjectAccessControls.delete",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl/{entity}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.get":
type DefaultObjectAccessControlsGetCall struct {
s *Service
bucket string
entity string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Returns the default object ACL entry for the specified entity on
// the specified bucket.
func (r *DefaultObjectAccessControlsService) Get(bucket string, entity string) *DefaultObjectAccessControlsGetCall {
c := &DefaultObjectAccessControlsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsGetCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *DefaultObjectAccessControlsGetCall) IfNoneMatch(entityTag string) *DefaultObjectAccessControlsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsGetCall) Context(ctx context.Context) *DefaultObjectAccessControlsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.get" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsGetCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the default object ACL entry for the specified entity on the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.defaultObjectAccessControls.get",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl/{entity}",
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.insert":
type DefaultObjectAccessControlsInsertCall struct {
s *Service
bucket string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a new default object ACL entry on the specified
// bucket.
func (r *DefaultObjectAccessControlsService) Insert(bucket string, objectaccesscontrol *ObjectAccessControl) *DefaultObjectAccessControlsInsertCall {
c := &DefaultObjectAccessControlsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsInsertCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsInsertCall) Context(ctx context.Context) *DefaultObjectAccessControlsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.insert" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsInsertCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new default object ACL entry on the specified bucket.",
// "httpMethod": "POST",
// "id": "storage.defaultObjectAccessControls.insert",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.list":
type DefaultObjectAccessControlsListCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves default object ACL entries on the specified bucket.
func (r *DefaultObjectAccessControlsService) List(bucket string) *DefaultObjectAccessControlsListCall {
c := &DefaultObjectAccessControlsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": If present, only return default ACL listing
// if the bucket's current metageneration matches this value.
func (c *DefaultObjectAccessControlsListCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *DefaultObjectAccessControlsListCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": If present, only return default ACL
// listing if the bucket's current metageneration does not match the
// given value.
func (c *DefaultObjectAccessControlsListCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *DefaultObjectAccessControlsListCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsListCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *DefaultObjectAccessControlsListCall) IfNoneMatch(entityTag string) *DefaultObjectAccessControlsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsListCall) Context(ctx context.Context) *DefaultObjectAccessControlsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.list" call.
// Exactly one of *ObjectAccessControls or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControls.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsListCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControls, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControls{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves default object ACL entries on the specified bucket.",
// "httpMethod": "GET",
// "id": "storage.defaultObjectAccessControls.list",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "If present, only return default ACL listing if the bucket's current metageneration matches this value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "If present, only return default ACL listing if the bucket's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl",
// "response": {
// "$ref": "ObjectAccessControls"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.patch":
type DefaultObjectAccessControlsPatchCall struct {
s *Service
bucket string
entity string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates a default object ACL entry on the specified bucket.
// This method supports patch semantics.
func (r *DefaultObjectAccessControlsService) Patch(bucket string, entity string, objectaccesscontrol *ObjectAccessControl) *DefaultObjectAccessControlsPatchCall {
c := &DefaultObjectAccessControlsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsPatchCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsPatchCall) Context(ctx context.Context) *DefaultObjectAccessControlsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.patch" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsPatchCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a default object ACL entry on the specified bucket. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.defaultObjectAccessControls.patch",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl/{entity}",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.defaultObjectAccessControls.update":
type DefaultObjectAccessControlsUpdateCall struct {
s *Service
bucket string
entity string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates a default object ACL entry on the specified bucket.
func (r *DefaultObjectAccessControlsService) Update(bucket string, entity string, objectaccesscontrol *ObjectAccessControl) *DefaultObjectAccessControlsUpdateCall {
c := &DefaultObjectAccessControlsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.entity = entity
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *DefaultObjectAccessControlsUpdateCall) Fields(s ...googleapi.Field) *DefaultObjectAccessControlsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *DefaultObjectAccessControlsUpdateCall) Context(ctx context.Context) *DefaultObjectAccessControlsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *DefaultObjectAccessControlsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *DefaultObjectAccessControlsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/defaultObjectAcl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.defaultObjectAccessControls.update" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *DefaultObjectAccessControlsUpdateCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates a default object ACL entry on the specified bucket.",
// "httpMethod": "PUT",
// "id": "storage.defaultObjectAccessControls.update",
// "parameterOrder": [
// "bucket",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/defaultObjectAcl/{entity}",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.delete":
type ObjectAccessControlsDeleteCall struct {
s *Service
bucket string
object string
entity string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes the ACL entry for the specified entity on
// the specified object.
func (r *ObjectAccessControlsService) Delete(bucket string, object string, entity string) *ObjectAccessControlsDeleteCall {
c := &ObjectAccessControlsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.entity = entity
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsDeleteCall) Generation(generation int64) *ObjectAccessControlsDeleteCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsDeleteCall) Fields(s ...googleapi.Field) *ObjectAccessControlsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsDeleteCall) Context(ctx context.Context) *ObjectAccessControlsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.delete" call.
func (c *ObjectAccessControlsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Permanently deletes the ACL entry for the specified entity on the specified object.",
// "httpMethod": "DELETE",
// "id": "storage.objectAccessControls.delete",
// "parameterOrder": [
// "bucket",
// "object",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl/{entity}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.get":
type ObjectAccessControlsGetCall struct {
s *Service
bucket string
object string
entity string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Returns the ACL entry for the specified entity on the specified
// object.
func (r *ObjectAccessControlsService) Get(bucket string, object string, entity string) *ObjectAccessControlsGetCall {
c := &ObjectAccessControlsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.entity = entity
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsGetCall) Generation(generation int64) *ObjectAccessControlsGetCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsGetCall) Fields(s ...googleapi.Field) *ObjectAccessControlsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectAccessControlsGetCall) IfNoneMatch(entityTag string) *ObjectAccessControlsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsGetCall) Context(ctx context.Context) *ObjectAccessControlsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.get" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsGetCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns the ACL entry for the specified entity on the specified object.",
// "httpMethod": "GET",
// "id": "storage.objectAccessControls.get",
// "parameterOrder": [
// "bucket",
// "object",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl/{entity}",
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.insert":
type ObjectAccessControlsInsertCall struct {
s *Service
bucket string
object string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Insert: Creates a new ACL entry on the specified object.
func (r *ObjectAccessControlsService) Insert(bucket string, object string, objectaccesscontrol *ObjectAccessControl) *ObjectAccessControlsInsertCall {
c := &ObjectAccessControlsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsInsertCall) Generation(generation int64) *ObjectAccessControlsInsertCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsInsertCall) Fields(s ...googleapi.Field) *ObjectAccessControlsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsInsertCall) Context(ctx context.Context) *ObjectAccessControlsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.insert" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsInsertCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a new ACL entry on the specified object.",
// "httpMethod": "POST",
// "id": "storage.objectAccessControls.insert",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.list":
type ObjectAccessControlsListCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves ACL entries on the specified object.
func (r *ObjectAccessControlsService) List(bucket string, object string) *ObjectAccessControlsListCall {
c := &ObjectAccessControlsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsListCall) Generation(generation int64) *ObjectAccessControlsListCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsListCall) Fields(s ...googleapi.Field) *ObjectAccessControlsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectAccessControlsListCall) IfNoneMatch(entityTag string) *ObjectAccessControlsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsListCall) Context(ctx context.Context) *ObjectAccessControlsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.list" call.
// Exactly one of *ObjectAccessControls or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControls.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsListCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControls, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControls{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves ACL entries on the specified object.",
// "httpMethod": "GET",
// "id": "storage.objectAccessControls.list",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl",
// "response": {
// "$ref": "ObjectAccessControls"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.patch":
type ObjectAccessControlsPatchCall struct {
s *Service
bucket string
object string
entity string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an ACL entry on the specified object. This method
// supports patch semantics.
func (r *ObjectAccessControlsService) Patch(bucket string, object string, entity string, objectaccesscontrol *ObjectAccessControl) *ObjectAccessControlsPatchCall {
c := &ObjectAccessControlsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.entity = entity
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsPatchCall) Generation(generation int64) *ObjectAccessControlsPatchCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsPatchCall) Fields(s ...googleapi.Field) *ObjectAccessControlsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsPatchCall) Context(ctx context.Context) *ObjectAccessControlsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.patch" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsPatchCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an ACL entry on the specified object. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.objectAccessControls.patch",
// "parameterOrder": [
// "bucket",
// "object",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl/{entity}",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objectAccessControls.update":
type ObjectAccessControlsUpdateCall struct {
s *Service
bucket string
object string
entity string
objectaccesscontrol *ObjectAccessControl
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates an ACL entry on the specified object.
func (r *ObjectAccessControlsService) Update(bucket string, object string, entity string, objectaccesscontrol *ObjectAccessControl) *ObjectAccessControlsUpdateCall {
c := &ObjectAccessControlsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.entity = entity
c.objectaccesscontrol = objectaccesscontrol
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectAccessControlsUpdateCall) Generation(generation int64) *ObjectAccessControlsUpdateCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectAccessControlsUpdateCall) Fields(s ...googleapi.Field) *ObjectAccessControlsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectAccessControlsUpdateCall) Context(ctx context.Context) *ObjectAccessControlsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectAccessControlsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectAccessControlsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.objectaccesscontrol)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/acl/{entity}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
"entity": c.entity,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objectAccessControls.update" call.
// Exactly one of *ObjectAccessControl or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ObjectAccessControl.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectAccessControlsUpdateCall) Do(opts ...googleapi.CallOption) (*ObjectAccessControl, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ObjectAccessControl{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an ACL entry on the specified object.",
// "httpMethod": "PUT",
// "id": "storage.objectAccessControls.update",
// "parameterOrder": [
// "bucket",
// "object",
// "entity"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of a bucket.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "entity": {
// "description": "The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/acl/{entity}",
// "request": {
// "$ref": "ObjectAccessControl"
// },
// "response": {
// "$ref": "ObjectAccessControl"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objects.compose":
type ObjectsComposeCall struct {
s *Service
destinationBucket string
destinationObject string
composerequest *ComposeRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Compose: Concatenates a list of existing objects into a new object in
// the same bucket.
func (r *ObjectsService) Compose(destinationBucket string, destinationObject string, composerequest *ComposeRequest) *ObjectsComposeCall {
c := &ObjectsComposeCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.destinationBucket = destinationBucket
c.destinationObject = destinationObject
c.composerequest = composerequest
return c
}
// DestinationPredefinedAcl sets the optional parameter
// "destinationPredefinedAcl": Apply a predefined set of access controls
// to the destination object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsComposeCall) DestinationPredefinedAcl(destinationPredefinedAcl string) *ObjectsComposeCall {
c.urlParams_.Set("destinationPredefinedAcl", destinationPredefinedAcl)
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsComposeCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsComposeCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsComposeCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsComposeCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsComposeCall) Fields(s ...googleapi.Field) *ObjectsComposeCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do and Download
// methods. Any pending HTTP request will be aborted if the provided
// context is canceled.
func (c *ObjectsComposeCall) Context(ctx context.Context) *ObjectsComposeCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsComposeCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsComposeCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.composerequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{destinationBucket}/o/{destinationObject}/compose")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"destinationBucket": c.destinationBucket,
"destinationObject": c.destinationObject,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Download fetches the API endpoint's "media" value, instead of the normal
// API response value. If the returned error is nil, the Response is guaranteed to
// have a 2xx status code. Callers must close the Response.Body as usual.
func (c *ObjectsComposeCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("media")
if err != nil {
return nil, err
}
if err := googleapi.CheckMediaResponse(res); err != nil {
res.Body.Close()
return nil, err
}
return res, nil
}
// Do executes the "storage.objects.compose" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsComposeCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Concatenates a list of existing objects into a new object in the same bucket.",
// "httpMethod": "POST",
// "id": "storage.objects.compose",
// "parameterOrder": [
// "destinationBucket",
// "destinationObject"
// ],
// "parameters": {
// "destinationBucket": {
// "description": "Name of the bucket in which to store the new object.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationObject": {
// "description": "Name of the new object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationPredefinedAcl": {
// "description": "Apply a predefined set of access controls to the destination object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{destinationBucket}/o/{destinationObject}/compose",
// "request": {
// "$ref": "ComposeRequest"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsMediaDownload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.copy":
type ObjectsCopyCall struct {
s *Service
sourceBucket string
sourceObject string
destinationBucket string
destinationObject string
object *Object
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Copy: Copies a source object to a destination object. Optionally
// overrides metadata.
func (r *ObjectsService) Copy(sourceBucket string, sourceObject string, destinationBucket string, destinationObject string, object *Object) *ObjectsCopyCall {
c := &ObjectsCopyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.sourceBucket = sourceBucket
c.sourceObject = sourceObject
c.destinationBucket = destinationBucket
c.destinationObject = destinationObject
c.object = object
return c
}
// DestinationPredefinedAcl sets the optional parameter
// "destinationPredefinedAcl": Apply a predefined set of access controls
// to the destination object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsCopyCall) DestinationPredefinedAcl(destinationPredefinedAcl string) *ObjectsCopyCall {
c.urlParams_.Set("destinationPredefinedAcl", destinationPredefinedAcl)
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the destination object's
// current generation matches the given value.
func (c *ObjectsCopyCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the destination object's current generation does not match the given
// value.
func (c *ObjectsCopyCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the destination object's current metageneration matches the given
// value.
func (c *ObjectsCopyCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the destination object's current metageneration does not
// match the given value.
func (c *ObjectsCopyCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// IfSourceGenerationMatch sets the optional parameter
// "ifSourceGenerationMatch": Makes the operation conditional on whether
// the source object's generation matches the given value.
func (c *ObjectsCopyCall) IfSourceGenerationMatch(ifSourceGenerationMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifSourceGenerationMatch", fmt.Sprint(ifSourceGenerationMatch))
return c
}
// IfSourceGenerationNotMatch sets the optional parameter
// "ifSourceGenerationNotMatch": Makes the operation conditional on
// whether the source object's generation does not match the given
// value.
func (c *ObjectsCopyCall) IfSourceGenerationNotMatch(ifSourceGenerationNotMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifSourceGenerationNotMatch", fmt.Sprint(ifSourceGenerationNotMatch))
return c
}
// IfSourceMetagenerationMatch sets the optional parameter
// "ifSourceMetagenerationMatch": Makes the operation conditional on
// whether the source object's current metageneration matches the given
// value.
func (c *ObjectsCopyCall) IfSourceMetagenerationMatch(ifSourceMetagenerationMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifSourceMetagenerationMatch", fmt.Sprint(ifSourceMetagenerationMatch))
return c
}
// IfSourceMetagenerationNotMatch sets the optional parameter
// "ifSourceMetagenerationNotMatch": Makes the operation conditional on
// whether the source object's current metageneration does not match the
// given value.
func (c *ObjectsCopyCall) IfSourceMetagenerationNotMatch(ifSourceMetagenerationNotMatch int64) *ObjectsCopyCall {
c.urlParams_.Set("ifSourceMetagenerationNotMatch", fmt.Sprint(ifSourceMetagenerationNotMatch))
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl, unless the object resource
// specifies the acl property, when it defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsCopyCall) Projection(projection string) *ObjectsCopyCall {
c.urlParams_.Set("projection", projection)
return c
}
// SourceGeneration sets the optional parameter "sourceGeneration": If
// present, selects a specific revision of the source object (as opposed
// to the latest version, the default).
func (c *ObjectsCopyCall) SourceGeneration(sourceGeneration int64) *ObjectsCopyCall {
c.urlParams_.Set("sourceGeneration", fmt.Sprint(sourceGeneration))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsCopyCall) Fields(s ...googleapi.Field) *ObjectsCopyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do and Download
// methods. Any pending HTTP request will be aborted if the provided
// context is canceled.
func (c *ObjectsCopyCall) Context(ctx context.Context) *ObjectsCopyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsCopyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsCopyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"sourceBucket": c.sourceBucket,
"sourceObject": c.sourceObject,
"destinationBucket": c.destinationBucket,
"destinationObject": c.destinationObject,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Download fetches the API endpoint's "media" value, instead of the normal
// API response value. If the returned error is nil, the Response is guaranteed to
// have a 2xx status code. Callers must close the Response.Body as usual.
func (c *ObjectsCopyCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("media")
if err != nil {
return nil, err
}
if err := googleapi.CheckMediaResponse(res); err != nil {
res.Body.Close()
return nil, err
}
return res, nil
}
// Do executes the "storage.objects.copy" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsCopyCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Copies a source object to a destination object. Optionally overrides metadata.",
// "httpMethod": "POST",
// "id": "storage.objects.copy",
// "parameterOrder": [
// "sourceBucket",
// "sourceObject",
// "destinationBucket",
// "destinationObject"
// ],
// "parameters": {
// "destinationBucket": {
// "description": "Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationObject": {
// "description": "Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationPredefinedAcl": {
// "description": "Apply a predefined set of access controls to the destination object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the destination object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the destination object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the destination object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the destination object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceGenerationMatch": {
// "description": "Makes the operation conditional on whether the source object's generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the source object's generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the source object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the source object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// },
// "sourceBucket": {
// "description": "Name of the bucket in which to find the source object.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "sourceGeneration": {
// "description": "If present, selects a specific revision of the source object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "sourceObject": {
// "description": "Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsMediaDownload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.delete":
type ObjectsDeleteCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes an object and its metadata. Deletions are permanent
// if versioning is not enabled for the bucket, or if the generation
// parameter is used.
func (r *ObjectsService) Delete(bucket string, object string) *ObjectsDeleteCall {
c := &ObjectsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// Generation sets the optional parameter "generation": If present,
// permanently deletes a specific revision of this object (as opposed to
// the latest version, the default).
func (c *ObjectsDeleteCall) Generation(generation int64) *ObjectsDeleteCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsDeleteCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsDeleteCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's current generation does not match the given value.
func (c *ObjectsDeleteCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsDeleteCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsDeleteCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsDeleteCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsDeleteCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsDeleteCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsDeleteCall) Fields(s ...googleapi.Field) *ObjectsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsDeleteCall) Context(ctx context.Context) *ObjectsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("DELETE", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.delete" call.
func (c *ObjectsDeleteCall) Do(opts ...googleapi.CallOption) error {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return err
}
return nil
// {
// "description": "Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used.",
// "httpMethod": "DELETE",
// "id": "storage.objects.delete",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}",
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.get":
type ObjectsGetCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Retrieves an object or its metadata.
func (r *ObjectsService) Get(bucket string, object string) *ObjectsGetCall {
c := &ObjectsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsGetCall) Generation(generation int64) *ObjectsGetCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's generation
// matches the given value.
func (c *ObjectsGetCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsGetCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's generation does not match the given value.
func (c *ObjectsGetCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsGetCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsGetCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsGetCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsGetCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsGetCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsGetCall) Projection(projection string) *ObjectsGetCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsGetCall) Fields(s ...googleapi.Field) *ObjectsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectsGetCall) IfNoneMatch(entityTag string) *ObjectsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do and Download
// methods. Any pending HTTP request will be aborted if the provided
// context is canceled.
func (c *ObjectsGetCall) Context(ctx context.Context) *ObjectsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Download fetches the API endpoint's "media" value, instead of the normal
// API response value. If the returned error is nil, the Response is guaranteed to
// have a 2xx status code. Callers must close the Response.Body as usual.
func (c *ObjectsGetCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("media")
if err != nil {
return nil, err
}
if err := googleapi.CheckMediaResponse(res); err != nil {
res.Body.Close()
return nil, err
}
return res, nil
}
// Do executes the "storage.objects.get" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsGetCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves an object or its metadata.",
// "httpMethod": "GET",
// "id": "storage.objects.get",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}",
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsMediaDownload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.getIamPolicy":
type ObjectsGetIamPolicyCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// GetIamPolicy: Returns an IAM policy for the specified object.
func (r *ObjectsService) GetIamPolicy(bucket string, object string) *ObjectsGetIamPolicyCall {
c := &ObjectsGetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsGetIamPolicyCall) Generation(generation int64) *ObjectsGetIamPolicyCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsGetIamPolicyCall) Fields(s ...googleapi.Field) *ObjectsGetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectsGetIamPolicyCall) IfNoneMatch(entityTag string) *ObjectsGetIamPolicyCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsGetIamPolicyCall) Context(ctx context.Context) *ObjectsGetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsGetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsGetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/iam")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.getIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns an IAM policy for the specified object.",
// "httpMethod": "GET",
// "id": "storage.objects.getIamPolicy",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/iam",
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.insert":
type ObjectsInsertCall struct {
s *Service
bucket string
object *Object
urlParams_ gensupport.URLParams
media_ io.Reader
mediaBuffer_ *gensupport.MediaBuffer
mediaType_ string
mediaSize_ int64 // mediaSize, if known. Used only for calls to progressUpdater_.
progressUpdater_ googleapi.ProgressUpdater
ctx_ context.Context
header_ http.Header
}
// Insert: Stores a new object and metadata.
func (r *ObjectsService) Insert(bucket string, object *Object) *ObjectsInsertCall {
c := &ObjectsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
return c
}
// ContentEncoding sets the optional parameter "contentEncoding": If
// set, sets the contentEncoding property of the final object to this
// value. Setting this parameter is equivalent to setting the
// contentEncoding metadata property. This can be useful when uploading
// an object with uploadType=media to indicate the encoding of the
// content being uploaded.
func (c *ObjectsInsertCall) ContentEncoding(contentEncoding string) *ObjectsInsertCall {
c.urlParams_.Set("contentEncoding", contentEncoding)
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsInsertCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsInsertCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's current generation does not match the given value.
func (c *ObjectsInsertCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsInsertCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsInsertCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsInsertCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsInsertCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsInsertCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// Name sets the optional parameter "name": Name of the object. Required
// when the object metadata is not otherwise provided. Overrides the
// object metadata's name value, if any. For information about how to
// URL encode object names to be path safe, see Encoding URI Path Parts.
func (c *ObjectsInsertCall) Name(name string) *ObjectsInsertCall {
c.urlParams_.Set("name", name)
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsInsertCall) PredefinedAcl(predefinedAcl string) *ObjectsInsertCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl, unless the object resource
// specifies the acl property, when it defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsInsertCall) Projection(projection string) *ObjectsInsertCall {
c.urlParams_.Set("projection", projection)
return c
}
// Media specifies the media to upload in one or more chunks. The chunk
// size may be controlled by supplying a MediaOption generated by
// googleapi.ChunkSize. The chunk size defaults to
// googleapi.DefaultUploadChunkSize.The Content-Type header used in the
// upload request will be determined by sniffing the contents of r,
// unless a MediaOption generated by googleapi.ContentType is
// supplied.
// At most one of Media and ResumableMedia may be set.
func (c *ObjectsInsertCall) Media(r io.Reader, options ...googleapi.MediaOption) *ObjectsInsertCall {
if ct := c.object.ContentType; ct != "" {
options = append([]googleapi.MediaOption{googleapi.ContentType(ct)}, options...)
}
opts := googleapi.ProcessMediaOptions(options)
chunkSize := opts.ChunkSize
if !opts.ForceEmptyContentType {
r, c.mediaType_ = gensupport.DetermineContentType(r, opts.ContentType)
}
c.media_, c.mediaBuffer_ = gensupport.PrepareUpload(r, chunkSize)
return c
}
// ResumableMedia specifies the media to upload in chunks and can be
// canceled with ctx.
//
// Deprecated: use Media instead.
//
// At most one of Media and ResumableMedia may be set. mediaType
// identifies the MIME media type of the upload, such as "image/png". If
// mediaType is "", it will be auto-detected. The provided ctx will
// supersede any context previously provided to the Context method.
func (c *ObjectsInsertCall) ResumableMedia(ctx context.Context, r io.ReaderAt, size int64, mediaType string) *ObjectsInsertCall {
c.ctx_ = ctx
rdr := gensupport.ReaderAtToReader(r, size)
rdr, c.mediaType_ = gensupport.DetermineContentType(rdr, mediaType)
c.mediaBuffer_ = gensupport.NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize)
c.media_ = nil
c.mediaSize_ = size
return c
}
// ProgressUpdater provides a callback function that will be called
// after every chunk. It should be a low-latency function in order to
// not slow down the upload operation. This should only be called when
// using ResumableMedia (as opposed to Media).
func (c *ObjectsInsertCall) ProgressUpdater(pu googleapi.ProgressUpdater) *ObjectsInsertCall {
c.progressUpdater_ = pu
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsInsertCall) Fields(s ...googleapi.Field) *ObjectsInsertCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
// This context will supersede any context previously provided to the
// ResumableMedia method.
func (c *ObjectsInsertCall) Context(ctx context.Context) *ObjectsInsertCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsInsertCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsInsertCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o")
if c.media_ != nil || c.mediaBuffer_ != nil {
urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1)
protocol := "multipart"
if c.mediaBuffer_ != nil {
protocol = "resumable"
}
c.urlParams_.Set("uploadType", protocol)
}
if body == nil {
body = new(bytes.Buffer)
reqHeaders.Set("Content-Type", "application/json")
}
if c.media_ != nil {
combined, ctype := gensupport.CombineBodyMedia(body, "application/json", c.media_, c.mediaType_)
defer combined.Close()
reqHeaders.Set("Content-Type", ctype)
body = combined
}
if c.mediaBuffer_ != nil && c.mediaType_ != "" {
reqHeaders.Set("X-Upload-Content-Type", c.mediaType_)
}
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.insert" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsInsertCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
if c.mediaBuffer_ != nil {
loc := res.Header.Get("Location")
rx := &gensupport.ResumableUpload{
Client: c.s.client,
UserAgent: c.s.userAgent(),
URI: loc,
Media: c.mediaBuffer_,
MediaType: c.mediaType_,
Callback: func(curr int64) {
if c.progressUpdater_ != nil {
c.progressUpdater_(curr, c.mediaSize_)
}
},
}
ctx := c.ctx_
if ctx == nil {
ctx = context.TODO()
}
res, err = rx.Upload(ctx)
if err != nil {
return nil, err
}
defer res.Body.Close()
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Stores a new object and metadata.",
// "httpMethod": "POST",
// "id": "storage.objects.insert",
// "mediaUpload": {
// "accept": [
// "*/*"
// ],
// "protocols": {
// "resumable": {
// "multipart": true,
// "path": "/resumable/upload/storage/v1/b/{bucket}/o"
// },
// "simple": {
// "multipart": true,
// "path": "/upload/storage/v1/b/{bucket}/o"
// }
// }
// },
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "contentEncoding": {
// "description": "If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded.",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "name": {
// "description": "Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "query",
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/o",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsMediaDownload": true,
// "supportsMediaUpload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.list":
type ObjectsListCall struct {
s *Service
bucket string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Retrieves a list of objects matching the criteria.
func (r *ObjectsService) List(bucket string) *ObjectsListCall {
c := &ObjectsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
return c
}
// Delimiter sets the optional parameter "delimiter": Returns results in
// a directory-like mode. items will contain only objects whose names,
// aside from the prefix, do not contain delimiter. Objects whose names,
// aside from the prefix, contain delimiter will have their name,
// truncated after the delimiter, returned in prefixes. Duplicate
// prefixes are omitted.
func (c *ObjectsListCall) Delimiter(delimiter string) *ObjectsListCall {
c.urlParams_.Set("delimiter", delimiter)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of items plus prefixes to return in a single page of responses. As
// duplicate prefixes are omitted, fewer total results may be returned
// than requested. The service will use this parameter or 1,000 items,
// whichever is smaller.
func (c *ObjectsListCall) MaxResults(maxResults int64) *ObjectsListCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": A
// previously-returned page token representing part of the larger set of
// results to view.
func (c *ObjectsListCall) PageToken(pageToken string) *ObjectsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Prefix sets the optional parameter "prefix": Filter results to
// objects whose names begin with this prefix.
func (c *ObjectsListCall) Prefix(prefix string) *ObjectsListCall {
c.urlParams_.Set("prefix", prefix)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsListCall) Projection(projection string) *ObjectsListCall {
c.urlParams_.Set("projection", projection)
return c
}
// Versions sets the optional parameter "versions": If true, lists all
// versions of an object as distinct results. The default is false. For
// more information, see Object Versioning.
func (c *ObjectsListCall) Versions(versions bool) *ObjectsListCall {
c.urlParams_.Set("versions", fmt.Sprint(versions))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsListCall) Fields(s ...googleapi.Field) *ObjectsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectsListCall) IfNoneMatch(entityTag string) *ObjectsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsListCall) Context(ctx context.Context) *ObjectsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.list" call.
// Exactly one of *Objects or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Objects.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsListCall) Do(opts ...googleapi.CallOption) (*Objects, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Objects{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Retrieves a list of objects matching the criteria.",
// "httpMethod": "GET",
// "id": "storage.objects.list",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which to look for objects.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "delimiter": {
// "description": "Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "1000",
// "description": "Maximum number of items plus prefixes to return in a single page of responses. As duplicate prefixes are omitted, fewer total results may be returned than requested. The service will use this parameter or 1,000 items, whichever is smaller.",
// "format": "uint32",
// "location": "query",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A previously-returned page token representing part of the larger set of results to view.",
// "location": "query",
// "type": "string"
// },
// "prefix": {
// "description": "Filter results to objects whose names begin with this prefix.",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// },
// "versions": {
// "description": "If true, lists all versions of an object as distinct results. The default is false. For more information, see Object Versioning.",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "b/{bucket}/o",
// "response": {
// "$ref": "Objects"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsSubscription": true
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ObjectsListCall) Pages(ctx context.Context, f func(*Objects) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "storage.objects.patch":
type ObjectsPatchCall struct {
s *Service
bucket string
object string
object2 *Object
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates an object's metadata. This method supports patch
// semantics.
func (r *ObjectsService) Patch(bucket string, object string, object2 *Object) *ObjectsPatchCall {
c := &ObjectsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.object2 = object2
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsPatchCall) Generation(generation int64) *ObjectsPatchCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsPatchCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsPatchCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's current generation does not match the given value.
func (c *ObjectsPatchCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsPatchCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsPatchCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsPatchCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsPatchCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsPatchCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsPatchCall) PredefinedAcl(predefinedAcl string) *ObjectsPatchCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsPatchCall) Projection(projection string) *ObjectsPatchCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsPatchCall) Fields(s ...googleapi.Field) *ObjectsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsPatchCall) Context(ctx context.Context) *ObjectsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object2)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PATCH", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.patch" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsPatchCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an object's metadata. This method supports patch semantics.",
// "httpMethod": "PATCH",
// "id": "storage.objects.patch",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ]
// }
}
// method id "storage.objects.rewrite":
type ObjectsRewriteCall struct {
s *Service
sourceBucket string
sourceObject string
destinationBucket string
destinationObject string
object *Object
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Rewrite: Rewrites a source object to a destination object. Optionally
// overrides metadata.
func (r *ObjectsService) Rewrite(sourceBucket string, sourceObject string, destinationBucket string, destinationObject string, object *Object) *ObjectsRewriteCall {
c := &ObjectsRewriteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.sourceBucket = sourceBucket
c.sourceObject = sourceObject
c.destinationBucket = destinationBucket
c.destinationObject = destinationObject
c.object = object
return c
}
// DestinationPredefinedAcl sets the optional parameter
// "destinationPredefinedAcl": Apply a predefined set of access controls
// to the destination object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsRewriteCall) DestinationPredefinedAcl(destinationPredefinedAcl string) *ObjectsRewriteCall {
c.urlParams_.Set("destinationPredefinedAcl", destinationPredefinedAcl)
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the destination object's
// current generation matches the given value.
func (c *ObjectsRewriteCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the destination object's current generation does not match the given
// value.
func (c *ObjectsRewriteCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the destination object's current metageneration matches the given
// value.
func (c *ObjectsRewriteCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the destination object's current metageneration does not
// match the given value.
func (c *ObjectsRewriteCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// IfSourceGenerationMatch sets the optional parameter
// "ifSourceGenerationMatch": Makes the operation conditional on whether
// the source object's generation matches the given value.
func (c *ObjectsRewriteCall) IfSourceGenerationMatch(ifSourceGenerationMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifSourceGenerationMatch", fmt.Sprint(ifSourceGenerationMatch))
return c
}
// IfSourceGenerationNotMatch sets the optional parameter
// "ifSourceGenerationNotMatch": Makes the operation conditional on
// whether the source object's generation does not match the given
// value.
func (c *ObjectsRewriteCall) IfSourceGenerationNotMatch(ifSourceGenerationNotMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifSourceGenerationNotMatch", fmt.Sprint(ifSourceGenerationNotMatch))
return c
}
// IfSourceMetagenerationMatch sets the optional parameter
// "ifSourceMetagenerationMatch": Makes the operation conditional on
// whether the source object's current metageneration matches the given
// value.
func (c *ObjectsRewriteCall) IfSourceMetagenerationMatch(ifSourceMetagenerationMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifSourceMetagenerationMatch", fmt.Sprint(ifSourceMetagenerationMatch))
return c
}
// IfSourceMetagenerationNotMatch sets the optional parameter
// "ifSourceMetagenerationNotMatch": Makes the operation conditional on
// whether the source object's current metageneration does not match the
// given value.
func (c *ObjectsRewriteCall) IfSourceMetagenerationNotMatch(ifSourceMetagenerationNotMatch int64) *ObjectsRewriteCall {
c.urlParams_.Set("ifSourceMetagenerationNotMatch", fmt.Sprint(ifSourceMetagenerationNotMatch))
return c
}
// MaxBytesRewrittenPerCall sets the optional parameter
// "maxBytesRewrittenPerCall": The maximum number of bytes that will be
// rewritten per rewrite request. Most callers shouldn't need to specify
// this parameter - it is primarily in place to support testing. If
// specified the value must be an integral multiple of 1 MiB (1048576).
// Also, this only applies to requests where the source and destination
// span locations and/or storage classes. Finally, this value must not
// change across rewrite calls else you'll get an error that the
// rewriteToken is invalid.
func (c *ObjectsRewriteCall) MaxBytesRewrittenPerCall(maxBytesRewrittenPerCall int64) *ObjectsRewriteCall {
c.urlParams_.Set("maxBytesRewrittenPerCall", fmt.Sprint(maxBytesRewrittenPerCall))
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl, unless the object resource
// specifies the acl property, when it defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsRewriteCall) Projection(projection string) *ObjectsRewriteCall {
c.urlParams_.Set("projection", projection)
return c
}
// RewriteToken sets the optional parameter "rewriteToken": Include this
// field (from the previous rewrite response) on each rewrite request
// after the first one, until the rewrite response 'done' flag is true.
// Calls that provide a rewriteToken can omit all other request fields,
// but if included those fields must match the values provided in the
// first rewrite request.
func (c *ObjectsRewriteCall) RewriteToken(rewriteToken string) *ObjectsRewriteCall {
c.urlParams_.Set("rewriteToken", rewriteToken)
return c
}
// SourceGeneration sets the optional parameter "sourceGeneration": If
// present, selects a specific revision of the source object (as opposed
// to the latest version, the default).
func (c *ObjectsRewriteCall) SourceGeneration(sourceGeneration int64) *ObjectsRewriteCall {
c.urlParams_.Set("sourceGeneration", fmt.Sprint(sourceGeneration))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsRewriteCall) Fields(s ...googleapi.Field) *ObjectsRewriteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsRewriteCall) Context(ctx context.Context) *ObjectsRewriteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsRewriteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsRewriteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"sourceBucket": c.sourceBucket,
"sourceObject": c.sourceObject,
"destinationBucket": c.destinationBucket,
"destinationObject": c.destinationObject,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.rewrite" call.
// Exactly one of *RewriteResponse or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *RewriteResponse.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectsRewriteCall) Do(opts ...googleapi.CallOption) (*RewriteResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &RewriteResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Rewrites a source object to a destination object. Optionally overrides metadata.",
// "httpMethod": "POST",
// "id": "storage.objects.rewrite",
// "parameterOrder": [
// "sourceBucket",
// "sourceObject",
// "destinationBucket",
// "destinationObject"
// ],
// "parameters": {
// "destinationBucket": {
// "description": "Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationObject": {
// "description": "Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "destinationPredefinedAcl": {
// "description": "Apply a predefined set of access controls to the destination object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the destination object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the destination object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the destination object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the destination object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceGenerationMatch": {
// "description": "Makes the operation conditional on whether the source object's generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the source object's generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the source object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifSourceMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the source object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "maxBytesRewrittenPerCall": {
// "description": "The maximum number of bytes that will be rewritten per rewrite request. Most callers shouldn't need to specify this parameter - it is primarily in place to support testing. If specified the value must be an integral multiple of 1 MiB (1048576). Also, this only applies to requests where the source and destination span locations and/or storage classes. Finally, this value must not change across rewrite calls else you'll get an error that the rewriteToken is invalid.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// },
// "rewriteToken": {
// "description": "Include this field (from the previous rewrite response) on each rewrite request after the first one, until the rewrite response 'done' flag is true. Calls that provide a rewriteToken can omit all other request fields, but if included those fields must match the values provided in the first rewrite request.",
// "location": "query",
// "type": "string"
// },
// "sourceBucket": {
// "description": "Name of the bucket in which to find the source object.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "sourceGeneration": {
// "description": "If present, selects a specific revision of the source object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "sourceObject": {
// "description": "Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "RewriteResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.setIamPolicy":
type ObjectsSetIamPolicyCall struct {
s *Service
bucket string
object string
policy *Policy
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// SetIamPolicy: Updates an IAM policy for the specified object.
func (r *ObjectsService) SetIamPolicy(bucket string, object string, policy *Policy) *ObjectsSetIamPolicyCall {
c := &ObjectsSetIamPolicyCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.policy = policy
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsSetIamPolicyCall) Generation(generation int64) *ObjectsSetIamPolicyCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsSetIamPolicyCall) Fields(s ...googleapi.Field) *ObjectsSetIamPolicyCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsSetIamPolicyCall) Context(ctx context.Context) *ObjectsSetIamPolicyCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsSetIamPolicyCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsSetIamPolicyCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.policy)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/iam")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.setIamPolicy" call.
// Exactly one of *Policy or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Policy.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsSetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Policy{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an IAM policy for the specified object.",
// "httpMethod": "PUT",
// "id": "storage.objects.setIamPolicy",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/iam",
// "request": {
// "$ref": "Policy"
// },
// "response": {
// "$ref": "Policy"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.testIamPermissions":
type ObjectsTestIamPermissionsCall struct {
s *Service
bucket string
object string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// TestIamPermissions: Tests a set of permissions on the given object to
// see which, if any, are held by the caller.
func (r *ObjectsService) TestIamPermissions(bucket string, object string, permissions []string) *ObjectsTestIamPermissionsCall {
c := &ObjectsTestIamPermissionsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.urlParams_.SetMulti("permissions", append([]string{}, permissions...))
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsTestIamPermissionsCall) Generation(generation int64) *ObjectsTestIamPermissionsCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsTestIamPermissionsCall) Fields(s ...googleapi.Field) *ObjectsTestIamPermissionsCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ObjectsTestIamPermissionsCall) IfNoneMatch(entityTag string) *ObjectsTestIamPermissionsCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsTestIamPermissionsCall) Context(ctx context.Context) *ObjectsTestIamPermissionsCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsTestIamPermissionsCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}/iam/testPermissions")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("GET", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.testIamPermissions" call.
// Exactly one of *TestIamPermissionsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *TestIamPermissionsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ObjectsTestIamPermissionsCall) Do(opts ...googleapi.CallOption) (*TestIamPermissionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &TestIamPermissionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Tests a set of permissions on the given object to see which, if any, are held by the caller.",
// "httpMethod": "GET",
// "id": "storage.objects.testIamPermissions",
// "parameterOrder": [
// "bucket",
// "object",
// "permissions"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "permissions": {
// "description": "Permissions to test.",
// "location": "query",
// "repeated": true,
// "required": true,
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}/iam/testPermissions",
// "response": {
// "$ref": "TestIamPermissionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ]
// }
}
// method id "storage.objects.update":
type ObjectsUpdateCall struct {
s *Service
bucket string
object string
object2 *Object
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Update: Updates an object's metadata.
func (r *ObjectsService) Update(bucket string, object string, object2 *Object) *ObjectsUpdateCall {
c := &ObjectsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.object = object
c.object2 = object2
return c
}
// Generation sets the optional parameter "generation": If present,
// selects a specific revision of this object (as opposed to the latest
// version, the default).
func (c *ObjectsUpdateCall) Generation(generation int64) *ObjectsUpdateCall {
c.urlParams_.Set("generation", fmt.Sprint(generation))
return c
}
// IfGenerationMatch sets the optional parameter "ifGenerationMatch":
// Makes the operation conditional on whether the object's current
// generation matches the given value.
func (c *ObjectsUpdateCall) IfGenerationMatch(ifGenerationMatch int64) *ObjectsUpdateCall {
c.urlParams_.Set("ifGenerationMatch", fmt.Sprint(ifGenerationMatch))
return c
}
// IfGenerationNotMatch sets the optional parameter
// "ifGenerationNotMatch": Makes the operation conditional on whether
// the object's current generation does not match the given value.
func (c *ObjectsUpdateCall) IfGenerationNotMatch(ifGenerationNotMatch int64) *ObjectsUpdateCall {
c.urlParams_.Set("ifGenerationNotMatch", fmt.Sprint(ifGenerationNotMatch))
return c
}
// IfMetagenerationMatch sets the optional parameter
// "ifMetagenerationMatch": Makes the operation conditional on whether
// the object's current metageneration matches the given value.
func (c *ObjectsUpdateCall) IfMetagenerationMatch(ifMetagenerationMatch int64) *ObjectsUpdateCall {
c.urlParams_.Set("ifMetagenerationMatch", fmt.Sprint(ifMetagenerationMatch))
return c
}
// IfMetagenerationNotMatch sets the optional parameter
// "ifMetagenerationNotMatch": Makes the operation conditional on
// whether the object's current metageneration does not match the given
// value.
func (c *ObjectsUpdateCall) IfMetagenerationNotMatch(ifMetagenerationNotMatch int64) *ObjectsUpdateCall {
c.urlParams_.Set("ifMetagenerationNotMatch", fmt.Sprint(ifMetagenerationNotMatch))
return c
}
// PredefinedAcl sets the optional parameter "predefinedAcl": Apply a
// predefined set of access controls to this object.
//
// Possible values:
// "authenticatedRead" - Object owner gets OWNER access, and
// allAuthenticatedUsers get READER access.
// "bucketOwnerFullControl" - Object owner gets OWNER access, and
// project team owners get OWNER access.
// "bucketOwnerRead" - Object owner gets OWNER access, and project
// team owners get READER access.
// "private" - Object owner gets OWNER access.
// "projectPrivate" - Object owner gets OWNER access, and project team
// members get access according to their roles.
// "publicRead" - Object owner gets OWNER access, and allUsers get
// READER access.
func (c *ObjectsUpdateCall) PredefinedAcl(predefinedAcl string) *ObjectsUpdateCall {
c.urlParams_.Set("predefinedAcl", predefinedAcl)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to full.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsUpdateCall) Projection(projection string) *ObjectsUpdateCall {
c.urlParams_.Set("projection", projection)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsUpdateCall) Fields(s ...googleapi.Field) *ObjectsUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do and Download
// methods. Any pending HTTP request will be aborted if the provided
// context is canceled.
func (c *ObjectsUpdateCall) Context(ctx context.Context) *ObjectsUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.object2)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/{object}")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("PUT", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
"object": c.object,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Download fetches the API endpoint's "media" value, instead of the normal
// API response value. If the returned error is nil, the Response is guaranteed to
// have a 2xx status code. Callers must close the Response.Body as usual.
func (c *ObjectsUpdateCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("media")
if err != nil {
return nil, err
}
if err := googleapi.CheckMediaResponse(res); err != nil {
res.Body.Close()
return nil, err
}
return res, nil
}
// Do executes the "storage.objects.update" call.
// Exactly one of *Object or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Object.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsUpdateCall) Do(opts ...googleapi.CallOption) (*Object, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Object{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates an object's metadata.",
// "httpMethod": "PUT",
// "id": "storage.objects.update",
// "parameterOrder": [
// "bucket",
// "object"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which the object resides.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "generation": {
// "description": "If present, selects a specific revision of this object (as opposed to the latest version, the default).",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current generation matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifGenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current generation does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration matches the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "ifMetagenerationNotMatch": {
// "description": "Makes the operation conditional on whether the object's current metageneration does not match the given value.",
// "format": "int64",
// "location": "query",
// "type": "string"
// },
// "object": {
// "description": "Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "predefinedAcl": {
// "description": "Apply a predefined set of access controls to this object.",
// "enum": [
// "authenticatedRead",
// "bucketOwnerFullControl",
// "bucketOwnerRead",
// "private",
// "projectPrivate",
// "publicRead"
// ],
// "enumDescriptions": [
// "Object owner gets OWNER access, and allAuthenticatedUsers get READER access.",
// "Object owner gets OWNER access, and project team owners get OWNER access.",
// "Object owner gets OWNER access, and project team owners get READER access.",
// "Object owner gets OWNER access.",
// "Object owner gets OWNER access, and project team members get access according to their roles.",
// "Object owner gets OWNER access, and allUsers get READER access."
// ],
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to full.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "b/{bucket}/o/{object}",
// "request": {
// "$ref": "Object"
// },
// "response": {
// "$ref": "Object"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/devstorage.full_control"
// ],
// "supportsMediaDownload": true,
// "useMediaDownloadService": true
// }
}
// method id "storage.objects.watchAll":
type ObjectsWatchAllCall struct {
s *Service
bucket string
channel *Channel
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// WatchAll: Watch for changes on all objects in a bucket.
func (r *ObjectsService) WatchAll(bucket string, channel *Channel) *ObjectsWatchAllCall {
c := &ObjectsWatchAllCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.bucket = bucket
c.channel = channel
return c
}
// Delimiter sets the optional parameter "delimiter": Returns results in
// a directory-like mode. items will contain only objects whose names,
// aside from the prefix, do not contain delimiter. Objects whose names,
// aside from the prefix, contain delimiter will have their name,
// truncated after the delimiter, returned in prefixes. Duplicate
// prefixes are omitted.
func (c *ObjectsWatchAllCall) Delimiter(delimiter string) *ObjectsWatchAllCall {
c.urlParams_.Set("delimiter", delimiter)
return c
}
// MaxResults sets the optional parameter "maxResults": Maximum number
// of items plus prefixes to return in a single page of responses. As
// duplicate prefixes are omitted, fewer total results may be returned
// than requested. The service will use this parameter or 1,000 items,
// whichever is smaller.
func (c *ObjectsWatchAllCall) MaxResults(maxResults int64) *ObjectsWatchAllCall {
c.urlParams_.Set("maxResults", fmt.Sprint(maxResults))
return c
}
// PageToken sets the optional parameter "pageToken": A
// previously-returned page token representing part of the larger set of
// results to view.
func (c *ObjectsWatchAllCall) PageToken(pageToken string) *ObjectsWatchAllCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Prefix sets the optional parameter "prefix": Filter results to
// objects whose names begin with this prefix.
func (c *ObjectsWatchAllCall) Prefix(prefix string) *ObjectsWatchAllCall {
c.urlParams_.Set("prefix", prefix)
return c
}
// Projection sets the optional parameter "projection": Set of
// properties to return. Defaults to noAcl.
//
// Possible values:
// "full" - Include all properties.
// "noAcl" - Omit the owner, acl property.
func (c *ObjectsWatchAllCall) Projection(projection string) *ObjectsWatchAllCall {
c.urlParams_.Set("projection", projection)
return c
}
// Versions sets the optional parameter "versions": If true, lists all
// versions of an object as distinct results. The default is false. For
// more information, see Object Versioning.
func (c *ObjectsWatchAllCall) Versions(versions bool) *ObjectsWatchAllCall {
c.urlParams_.Set("versions", fmt.Sprint(versions))
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ObjectsWatchAllCall) Fields(s ...googleapi.Field) *ObjectsWatchAllCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ObjectsWatchAllCall) Context(ctx context.Context) *ObjectsWatchAllCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ObjectsWatchAllCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ObjectsWatchAllCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o/watch")
urls += "?" + c.urlParams_.Encode()
req, _ := http.NewRequest("POST", urls, body)
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"bucket": c.bucket,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "storage.objects.watchAll" call.
// Exactly one of *Channel or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Channel.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ObjectsWatchAllCall) Do(opts ...googleapi.CallOption) (*Channel, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Channel{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := json.NewDecoder(res.Body).Decode(target); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Watch for changes on all objects in a bucket.",
// "httpMethod": "POST",
// "id": "storage.objects.watchAll",
// "parameterOrder": [
// "bucket"
// ],
// "parameters": {
// "bucket": {
// "description": "Name of the bucket in which to look for objects.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "delimiter": {
// "description": "Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.",
// "location": "query",
// "type": "string"
// },
// "maxResults": {
// "default": "1000",
// "description": "Maximum number of items plus prefixes to return in a single page of responses. As duplicate prefixes are omitted, fewer total results may be returned than requested. The service will use this parameter or 1,000 items, whichever is smaller.",
// "format": "uint32",
// "location": "query",
// "minimum": "0",
// "type": "integer"
// },
// "pageToken": {
// "description": "A previously-returned page token representing part of the larger set of results to view.",
// "location": "query",
// "type": "string"
// },
// "prefix": {
// "description": "Filter results to objects whose names begin with this prefix.",
// "location": "query",
// "type": "string"
// },
// "projection": {
// "description": "Set of properties to return. Defaults to noAcl.",
// "enum": [
// "full",
// "noAcl"
// ],
// "enumDescriptions": [
// "Include all properties.",
// "Omit the owner, acl property."
// ],
// "location": "query",
// "type": "string"
// },
// "versions": {
// "description": "If true, lists all versions of an object as distinct results. The default is false. For more information, see Object Versioning.",
// "location": "query",
// "type": "boolean"
// }
// },
// "path": "b/{bucket}/o/watch",
// "request": {
// "$ref": "Channel",
// "parameterName": "resource"
// },
// "response": {
// "$ref": "Channel"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only",
// "https://www.googleapis.com/auth/devstorage.full_control",
// "https://www.googleapis.com/auth/devstorage.read_only",
// "https://www.googleapis.com/auth/devstorage.read_write"
// ],
// "supportsSubscription": true
// }
}
| mpl/camlistore | vendor/google.golang.org/api/storage/v1/storage-gen.go | GO | apache-2.0 | 338,935 |
/*
Copyright 2016 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.
*/
package fake
import (
api "k8s.io/client-go/pkg/api"
unversioned "k8s.io/client-go/pkg/api/unversioned"
v1 "k8s.io/client-go/pkg/api/v1"
labels "k8s.io/client-go/pkg/labels"
watch "k8s.io/client-go/pkg/watch"
testing "k8s.io/client-go/testing"
)
// FakeResourceQuotas implements ResourceQuotaInterface
type FakeResourceQuotas struct {
Fake *FakeCore
ns string
}
var resourcequotasResource = unversioned.GroupVersionResource{Group: "", Version: "v1", Resource: "resourcequotas"}
func (c *FakeResourceQuotas) Create(resourceQuota *v1.ResourceQuota) (result *v1.ResourceQuota, err error) {
obj, err := c.Fake.
Invokes(testing.NewCreateAction(resourcequotasResource, c.ns, resourceQuota), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
func (c *FakeResourceQuotas) Update(resourceQuota *v1.ResourceQuota) (result *v1.ResourceQuota, err error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateAction(resourcequotasResource, c.ns, resourceQuota), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
func (c *FakeResourceQuotas) UpdateStatus(resourceQuota *v1.ResourceQuota) (*v1.ResourceQuota, error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateSubresourceAction(resourcequotasResource, "status", c.ns, resourceQuota), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
func (c *FakeResourceQuotas) Delete(name string, options *v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(resourcequotasResource, c.ns, name), &v1.ResourceQuota{})
return err
}
func (c *FakeResourceQuotas) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
action := testing.NewDeleteCollectionAction(resourcequotasResource, c.ns, listOptions)
_, err := c.Fake.Invokes(action, &v1.ResourceQuotaList{})
return err
}
func (c *FakeResourceQuotas) Get(name string) (result *v1.ResourceQuota, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(resourcequotasResource, c.ns, name), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
func (c *FakeResourceQuotas) List(opts v1.ListOptions) (result *v1.ResourceQuotaList, err error) {
obj, err := c.Fake.
Invokes(testing.NewListAction(resourcequotasResource, c.ns, opts), &v1.ResourceQuotaList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1.ResourceQuotaList{}
for _, item := range obj.(*v1.ResourceQuotaList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested resourceQuotas.
func (c *FakeResourceQuotas) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(resourcequotasResource, c.ns, opts))
}
// Patch applies the patch and returns the patched resourceQuota.
func (c *FakeResourceQuotas) Patch(name string, pt api.PatchType, data []byte, subresources ...string) (result *v1.ResourceQuota, err error) {
obj, err := c.Fake.
Invokes(testing.NewPatchSubresourceAction(resourcequotasResource, c.ns, name, data, subresources...), &v1.ResourceQuota{})
if obj == nil {
return nil, err
}
return obj.(*v1.ResourceQuota), err
}
| craigyam/amalgam8 | vendor/k8s.io/client-go/kubernetes/typed/core/v1/fake/fake_resourcequota.go | GO | apache-2.0 | 4,021 |
<?php
include_once dirname(__FILE__).'/../../bootstrap/unit.php';
class myQuery extends opDoctrineQuery
{
public static $lastQueryCacheHash = '';
public function calculateQueryCacheHash()
{
self::$lastQueryCacheHash = parent::calculateQueryCacheHash();
return self::$lastQueryCacheHash;
}
}
$_app = 'pc_frontend';
$_env = 'test';
$configuration = ProjectConfiguration::getApplicationConfiguration($_app, $_env, true);
new sfDatabaseManager($configuration);
Doctrine_Manager::getInstance()->setAttribute(Doctrine::ATTR_QUERY_CLASS, 'myQuery');
$t = new lime_test(null, new lime_output_color());
// --
$keys = array();
Doctrine::getTable('AdminUser')->find(1);
$keys['find'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findAll();
$keys['find_all'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findById(1);
$keys['find_by_id'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findOneById(1);
$keys['find_one_by_id'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findByIdAndUsername(1, 'admin');
$keys['find_by_id_and_username'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findOneByIdAndUsername(1, 'admin');
$keys['find_one_by_id_and_username'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findByUsernameAndPassword('admin', 'password');
$keys['find_by_username_and_password'] = myQuery::$lastQueryCacheHash;
Doctrine::getTable('AdminUser')->findOneByUsernameAndPassword('admin', 'password');
$keys['find_one_by_username_and_password'] = myQuery::$lastQueryCacheHash;
$t->isnt($keys['find'], $keys['find_all'], '->find() and ->findAll() generates different query cache keys');
$t->isnt($keys['find'], $keys['find_by_id'], '->find() and ->findById() generates different query cache keys');
$t->is($keys['find'], $keys['find_one_by_id'], '->find() and ->findOneById() generates same query cache keys');
$t->isnt($keys['find'], $keys['find_by_id_and_username'], '->find() and ->findByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find'], $keys['find_one_by_id_and_username'], '->find() and ->findOneByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find'], $keys['find_by_username_and_password'], '->find() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find'], $keys['find_one_by_username_and_password'], '->find() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_by_id'], '->findAll() and ->findById() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_one_by_id'], '->findAll() and ->findOneById() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_by_id_and_username'], '->findAll() and ->findByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_one_by_id_and_username'], '->findAll() and ->findOneByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_by_username_and_password'], '->findAll() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_all'], $keys['find_one_by_username_and_password'], '->findAll() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_one_by_id'], '->findById() and ->findOneById() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_by_id_and_username'], '->findById() and ->findByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_one_by_id_and_username'], '->findById() and ->findOneById() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_by_username_and_password'], '->findById() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_id'], $keys['find_one_by_username_and_password'], '->findById() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_one_by_id'], $keys['find_by_id_and_username'], '->findOneById() and ->findByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_one_by_id'], $keys['find_one_by_id_and_username'], '->findOneById() and ->findOneByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_one_by_id'], $keys['find_by_username_and_password'], '->findOneById() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_one_by_id'], $keys['find_one_by_username_and_password'], '->findOneById() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_id_and_username'], $keys['find_one_by_id_and_username'], '->findByIdAndUsername() and ->findOneByIdAndUsername() generates different query cache keys');
$t->isnt($keys['find_by_id_and_username'], $keys['find_by_username_and_password'], '->findByIdAndUsername() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_id_and_username'], $keys['find_one_by_username_and_password'], '->findByIdAndUsername() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_one_by_id_and_username'], $keys['find_by_username_and_password'], '->findOneByIdAndUsername() and ->findByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_one_by_id_and_username'], $keys['find_one_by_username_and_password'], '->findOneByIdAndUsername() and ->findOneByUsernameAndPassword() generates different query cache keys');
$t->isnt($keys['find_by_username_and_password'], $keys['find_one_by_username_and_password'], '->findByUsernameAndPassword() and ->findOneByUsernameAndPassword() generates different query cache keys');
| imamura623/OpenPNE38x_PluginBundledVersion | test/unit/util/opDoctrineQueryTest.php | PHP | apache-2.0 | 5,917 |
cask 'wifispoof' do
version '3.4.3'
sha256 '31465240307e6e2f36f9345c0600489e3458d81922f3a4ded66fe9881503f606'
# sweetpproductions.com/products was verified as official when first introduced to the cask
url "https://sweetpproductions.com/products/wifispoof#{version.major}/WiFiSpoof#{version.major}.dmg"
appcast "https://sweetpproductions.com/products/wifispoof#{version.major}/appcast.xml"
name 'WiFiSpoof'
homepage 'https://wifispoof.com/'
auto_updates true
app 'WiFiSpoof.app'
end
| gyndav/homebrew-cask | Casks/wifispoof.rb | Ruby | bsd-2-clause | 504 |
# -*- coding: utf-8 -*-
import os
from operator import itemgetter
from gluon.storage import Storage
from gluon.dal import DAL, Field, Row
DBHOST = os.environ.get('DBHOST', 'localhost')
DATABASE_URI = 'mysql://benchmarkdbuser:benchmarkdbpass@%s:3306/hello_world' % DBHOST
class Dal(object):
def __init__(self, table=None, pool_size=8):
self.db = DAL(DATABASE_URI, migrate_enabled=False, pool_size=pool_size)
if table == 'World':
self.db.define_table('World', Field('randomNumber', 'integer'))
elif table == 'Fortune':
self.db.define_table('Fortune', Field('message'))
def get_world(self, wid):
# Setting `cacheable=True` improves performance by foregoing the creation
# of some non-essential attributes. It does *not* actually cache the
# database results (it simply produces a Rows object that *could be* cached).
return self.db(self.db.World.id == wid).select(cacheable=True)[0].as_dict()
def update_world(self, wid, randomNumber):
self.db(self.db.World.id == wid).update(randomNumber=randomNumber)
def get_fortunes(self, new_message):
fortunes = self.db(self.db.Fortune).select(cacheable=True)
fortunes.records.append(Row(new_message))
return fortunes.sort(itemgetter('message'))
class RawDal(Dal):
def __init__(self):
super(RawDal, self).__init__()
self.world_updates = []
def get_world(self, wid):
return self.db.executesql('SELECT * FROM World WHERE id = %s',
placeholders=[wid], as_dict=True)[0]
def update_world(self, wid, randomNumber):
self.world_updates.extend([randomNumber, wid])
def flush_world_updates(self):
query = ';'.join('UPDATE World SET randomNumber=%s WHERE id=%s'
for _ in xrange(len(self.world_updates) / 2))
self.db.executesql(query, placeholders=self.world_updates)
def get_fortunes(self, new_message):
fortunes = self.db.executesql('SELECT * FROM Fortune', as_dict=True)
fortunes.append(new_message)
return sorted(fortunes, key=itemgetter('message'))
def num_queries(queries):
try:
num = int(queries)
return 1 if num < 1 else 500 if num > 500 else num
except ValueError:
return 1
| ashawnbandy-te-tfb/FrameworkBenchmarks | frameworks/Python/web2py/app/standard/modules/database.py | Python | bsd-3-clause | 2,330 |
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* Copyright (C) 2003, 2006, 2009, 2012 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/rendering/RenderApplet.h"
#include "core/frame/UseCounter.h"
#include "core/html/HTMLAppletElement.h"
namespace blink {
RenderApplet::RenderApplet(HTMLAppletElement* applet)
: RenderEmbeddedObject(applet)
{
setInline(true);
UseCounter::count(document(), UseCounter::HTMLAppletElement);
}
RenderApplet::~RenderApplet()
{
}
} // namespace blink
| mxOBS/deb-pkg_trusty_chromium-browser | third_party/WebKit/Source/core/rendering/RenderApplet.cpp | C++ | bsd-3-clause | 1,302 |
// Copyright 2013 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 "ui/compositor/test/test_compositor_host.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/thread_task_runner_handle.h"
#include "ui/compositor/compositor.h"
#include "ui/gfx/geometry/rect.h"
namespace ui {
class TestCompositorHostOzone : public TestCompositorHost {
public:
TestCompositorHostOzone(const gfx::Rect& bounds,
ui::ContextFactory* context_factory);
~TestCompositorHostOzone() override;
private:
// Overridden from TestCompositorHost:
void Show() override;
ui::Compositor* GetCompositor() override;
gfx::Rect bounds_;
ui::ContextFactory* context_factory_;
scoped_ptr<ui::Compositor> compositor_;
DISALLOW_COPY_AND_ASSIGN(TestCompositorHostOzone);
};
TestCompositorHostOzone::TestCompositorHostOzone(
const gfx::Rect& bounds,
ui::ContextFactory* context_factory)
: bounds_(bounds),
context_factory_(context_factory) {}
TestCompositorHostOzone::~TestCompositorHostOzone() {}
void TestCompositorHostOzone::Show() {
// Ozone should rightly have a backing native framebuffer
// An in-memory array draw into by OSMesa is a reasonble
// fascimile of a dumb framebuffer at present.
// GLSurface will allocate the array so long as it is provided
// with a non-0 widget.
// TODO(rjkroege): Use a "real" ozone widget when it is
// available: http://crbug.com/255128
compositor_.reset(new ui::Compositor(1,
context_factory_,
base::ThreadTaskRunnerHandle::Get()));
compositor_->SetScaleAndSize(1.0f, bounds_.size());
}
ui::Compositor* TestCompositorHostOzone::GetCompositor() {
return compositor_.get();
}
// static
TestCompositorHost* TestCompositorHost::Create(
const gfx::Rect& bounds,
ui::ContextFactory* context_factory) {
return new TestCompositorHostOzone(bounds, context_factory);
}
} // namespace ui
| ltilve/chromium | ui/compositor/test/test_compositor_host_ozone.cc | C++ | bsd-3-clause | 2,222 |
// Copyright 2014 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.
'use strict';
// This file relies on the fact that the following declaration has been made
// in runtime.js:
// var $Array = global.Array;
// -------------------------------------------------------------------
// Proposed for ES7
// https://github.com/tc39/Array.prototype.includes
// 6e3b78c927aeda20b9d40e81303f9d44596cd904
function ArrayIncludes(searchElement, fromIndex) {
var array = ToObject(this);
var len = ToLength(array.length);
if (len === 0) {
return false;
}
var n = ToInteger(fromIndex);
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
while (k < len) {
var elementK = array[k];
if (SameValueZero(searchElement, elementK)) {
return true;
}
++k;
}
return false;
}
// -------------------------------------------------------------------
function HarmonyArrayIncludesExtendArrayPrototype() {
%CheckIsBootstrapping();
%FunctionSetLength(ArrayIncludes, 1);
// Set up the non-enumerable functions on the Array prototype object.
InstallFunctions($Array.prototype, DONT_ENUM, $Array(
"includes", ArrayIncludes
));
}
HarmonyArrayIncludesExtendArrayPrototype();
| sgraham/nope | v8/src/harmony-array-includes.js | JavaScript | bsd-3-clause | 1,359 |
/*
LumX v1.5.14
(c) 2014-2017 LumApps http://ui.lumapps.com
License: MIT
*/
(function()
{
'use strict';
angular.module('lumx.utils.depth', []);
angular.module('lumx.utils.event-scheduler', []);
angular.module('lumx.utils.transclude-replace', []);
angular.module('lumx.utils.utils', []);
angular.module('lumx.utils', [
'lumx.utils.depth',
'lumx.utils.event-scheduler',
'lumx.utils.transclude-replace',
'lumx.utils.utils'
]);
angular.module('lumx.button', []);
angular.module('lumx.checkbox', []);
angular.module('lumx.data-table', []);
angular.module('lumx.date-picker', []);
angular.module('lumx.dialog', ['lumx.utils.event-scheduler']);
angular.module('lumx.dropdown', ['lumx.utils.event-scheduler']);
angular.module('lumx.fab', []);
angular.module('lumx.file-input', []);
angular.module('lumx.icon', []);
angular.module('lumx.notification', ['lumx.utils.event-scheduler']);
angular.module('lumx.progress', []);
angular.module('lumx.radio-button', []);
angular.module('lumx.ripple', []);
angular.module('lumx.search-filter', []);
angular.module('lumx.select', []);
angular.module('lumx.stepper', []);
angular.module('lumx.switch', []);
angular.module('lumx.tabs', []);
angular.module('lumx.text-field', []);
angular.module('lumx.tooltip', []);
angular.module('lumx', [
'lumx.button',
'lumx.checkbox',
'lumx.data-table',
'lumx.date-picker',
'lumx.dialog',
'lumx.dropdown',
'lumx.fab',
'lumx.file-input',
'lumx.icon',
'lumx.notification',
'lumx.progress',
'lumx.radio-button',
'lumx.ripple',
'lumx.search-filter',
'lumx.select',
'lumx.stepper',
'lumx.switch',
'lumx.tabs',
'lumx.text-field',
'lumx.tooltip',
'lumx.utils'
]);
})();
(function()
{
'use strict';
angular
.module('lumx.utils.depth')
.service('LxDepthService', LxDepthService);
function LxDepthService()
{
var service = this;
var depth = 1000;
service.getDepth = getDepth;
service.register = register;
////////////
function getDepth()
{
return depth;
}
function register()
{
depth++;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.utils.event-scheduler')
.service('LxEventSchedulerService', LxEventSchedulerService);
LxEventSchedulerService.$inject = ['$document', 'LxUtils'];
function LxEventSchedulerService($document, LxUtils)
{
var service = this;
var handlers = {};
var schedule = {};
service.register = register;
service.unregister = unregister;
////////////
function handle(event)
{
var scheduler = schedule[event.type];
if (angular.isDefined(scheduler))
{
for (var i = 0, length = scheduler.length; i < length; i++)
{
var handler = scheduler[i];
if (angular.isDefined(handler) && angular.isDefined(handler.callback) && angular.isFunction(handler.callback))
{
handler.callback(event);
if (event.isPropagationStopped())
{
break;
}
}
}
}
}
function register(eventName, callback)
{
var handler = {
eventName: eventName,
callback: callback
};
var id = LxUtils.generateUUID();
handlers[id] = handler;
if (angular.isUndefined(schedule[eventName]))
{
schedule[eventName] = [];
$document.on(eventName, handle);
}
schedule[eventName].unshift(handlers[id]);
return id;
}
function unregister(id)
{
var found = false;
var handler = handlers[id];
if (angular.isDefined(handler) && angular.isDefined(schedule[handler.eventName]))
{
var index = schedule[handler.eventName].indexOf(handler);
if (angular.isDefined(index) && index > -1)
{
schedule[handler.eventName].splice(index, 1);
delete handlers[id];
found = true;
}
if (schedule[handler.eventName].length === 0)
{
delete schedule[handler.eventName];
$document.off(handler.eventName, handle);
}
}
return found;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.utils.transclude-replace')
.directive('ngTranscludeReplace', ngTranscludeReplace);
ngTranscludeReplace.$inject = ['$log'];
function ngTranscludeReplace($log)
{
return {
terminal: true,
restrict: 'EA',
link: link
};
function link(scope, element, attrs, ctrl, transclude)
{
if (!transclude)
{
$log.error('orphan',
'Illegal use of ngTranscludeReplace directive in the template! ' +
'No parent directive that requires a transclusion found. ');
return;
}
transclude(function(clone)
{
if (clone.length)
{
element.replaceWith(clone);
}
else
{
element.remove();
}
});
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.utils.utils')
.service('LxUtils', LxUtils);
function LxUtils()
{
var service = this;
service.debounce = debounce;
service.generateUUID = generateUUID;
service.disableBodyScroll = disableBodyScroll;
////////////
// http://underscorejs.org/#debounce (1.8.3)
function debounce(func, wait, immediate)
{
var timeout, args, context, timestamp, result;
wait = wait || 500;
var later = function()
{
var last = Date.now() - timestamp;
if (last < wait && last >= 0)
{
timeout = setTimeout(later, wait - last);
}
else
{
timeout = null;
if (!immediate)
{
result = func.apply(context, args);
if (!timeout)
{
context = args = null;
}
}
}
};
var debounced = function()
{
context = this;
args = arguments;
timestamp = Date.now();
var callNow = immediate && !timeout;
if (!timeout)
{
timeout = setTimeout(later, wait);
}
if (callNow)
{
result = func.apply(context, args);
context = args = null;
}
return result;
};
debounced.clear = function()
{
clearTimeout(timeout);
timeout = context = args = null;
};
return debounced;
}
function generateUUID()
{
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)
{
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8))
.toString(16);
});
return uuid.toUpperCase();
}
function disableBodyScroll()
{
var body = document.body;
var documentElement = document.documentElement;
var prevDocumentStyle = documentElement.style.cssText || '';
var prevBodyStyle = body.style.cssText || '';
var viewportTop = window.scrollY || window.pageYOffset || 0;
var clientWidth = body.clientWidth;
var hasVerticalScrollbar = body.scrollHeight > window.innerHeight + 1;
if (hasVerticalScrollbar)
{
angular.element('body').css({
position: 'fixed',
width: '100%',
top: -viewportTop + 'px'
});
}
if (body.clientWidth < clientWidth)
{
body.style.overflow = 'hidden';
}
// This should be applied after the manipulation to the body, because
// adding a scrollbar can potentially resize it, causing the measurement
// to change.
if (hasVerticalScrollbar)
{
documentElement.style.overflowY = 'scroll';
}
return function restoreScroll()
{
// Reset the inline style CSS to the previous.
body.style.cssText = prevBodyStyle;
documentElement.style.cssText = prevDocumentStyle;
// The body loses its scroll position while being fixed.
body.scrollTop = viewportTop;
};
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.button')
.directive('lxButton', lxButton);
function lxButton()
{
var buttonClass;
return {
restrict: 'E',
templateUrl: getTemplateUrl,
compile: compile,
replace: true,
transclude: true
};
function compile(element, attrs)
{
setButtonStyle(element, attrs.lxSize, attrs.lxColor, attrs.lxType);
return function(scope, element, attrs)
{
attrs.$observe('lxSize', function(lxSize)
{
setButtonStyle(element, lxSize, attrs.lxColor, attrs.lxType);
});
attrs.$observe('lxColor', function(lxColor)
{
setButtonStyle(element, attrs.lxSize, lxColor, attrs.lxType);
});
attrs.$observe('lxType', function(lxType)
{
setButtonStyle(element, attrs.lxSize, attrs.lxColor, lxType);
});
element.on('click', function(event)
{
if (attrs.disabled === true)
{
event.preventDefault();
event.stopImmediatePropagation();
}
});
};
}
function getTemplateUrl(element, attrs)
{
return isAnchor(attrs) ? 'link.html' : 'button.html';
}
function isAnchor(attrs)
{
return angular.isDefined(attrs.href) || angular.isDefined(attrs.ngHref) || angular.isDefined(attrs.ngLink) || angular.isDefined(attrs.uiSref);
}
function setButtonStyle(element, size, color, type)
{
var buttonBase = 'btn';
var buttonSize = angular.isDefined(size) ? size : 'm';
var buttonColor = angular.isDefined(color) ? color : 'primary';
var buttonType = angular.isDefined(type) ? type : 'raised';
element.removeClass(buttonClass);
buttonClass = buttonBase + ' btn--' + buttonSize + ' btn--' + buttonColor + ' btn--' + buttonType;
element.addClass(buttonClass);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.checkbox')
.directive('lxCheckbox', lxCheckbox)
.directive('lxCheckboxLabel', lxCheckboxLabel)
.directive('lxCheckboxHelp', lxCheckboxHelp);
function lxCheckbox()
{
return {
restrict: 'E',
templateUrl: 'checkbox.html',
scope:
{
lxColor: '@?',
name: '@?',
ngChange: '&?',
ngDisabled: '=?',
ngFalseValue: '@?',
ngModel: '=',
ngTrueValue: '@?',
theme: '@?lxTheme'
},
controller: LxCheckboxController,
controllerAs: 'lxCheckbox',
bindToController: true,
transclude: true,
replace: true
};
}
LxCheckboxController.$inject = ['$scope', '$timeout', 'LxUtils'];
function LxCheckboxController($scope, $timeout, LxUtils)
{
var lxCheckbox = this;
var checkboxId;
var checkboxHasChildren;
var timer;
lxCheckbox.getCheckboxId = getCheckboxId;
lxCheckbox.getCheckboxHasChildren = getCheckboxHasChildren;
lxCheckbox.setCheckboxId = setCheckboxId;
lxCheckbox.setCheckboxHasChildren = setCheckboxHasChildren;
lxCheckbox.triggerNgChange = triggerNgChange;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
init();
////////////
function getCheckboxId()
{
return checkboxId;
}
function getCheckboxHasChildren()
{
return checkboxHasChildren;
}
function init()
{
setCheckboxId(LxUtils.generateUUID());
setCheckboxHasChildren(false);
lxCheckbox.ngTrueValue = angular.isUndefined(lxCheckbox.ngTrueValue) ? true : lxCheckbox.ngTrueValue;
lxCheckbox.ngFalseValue = angular.isUndefined(lxCheckbox.ngFalseValue) ? false : lxCheckbox.ngFalseValue;
lxCheckbox.lxColor = angular.isUndefined(lxCheckbox.lxColor) ? 'accent' : lxCheckbox.lxColor;
}
function setCheckboxId(_checkboxId)
{
checkboxId = _checkboxId;
}
function setCheckboxHasChildren(_checkboxHasChildren)
{
checkboxHasChildren = _checkboxHasChildren;
}
function triggerNgChange()
{
timer = $timeout(lxCheckbox.ngChange);
}
}
function lxCheckboxLabel()
{
return {
restrict: 'AE',
require: ['^lxCheckbox', '^lxCheckboxLabel'],
templateUrl: 'checkbox-label.html',
link: link,
controller: LxCheckboxLabelController,
controllerAs: 'lxCheckboxLabel',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].setCheckboxHasChildren(true);
ctrls[1].setCheckboxId(ctrls[0].getCheckboxId());
}
}
function LxCheckboxLabelController()
{
var lxCheckboxLabel = this;
var checkboxId;
lxCheckboxLabel.getCheckboxId = getCheckboxId;
lxCheckboxLabel.setCheckboxId = setCheckboxId;
////////////
function getCheckboxId()
{
return checkboxId;
}
function setCheckboxId(_checkboxId)
{
checkboxId = _checkboxId;
}
}
function lxCheckboxHelp()
{
return {
restrict: 'AE',
require: '^lxCheckbox',
templateUrl: 'checkbox-help.html',
transclude: true,
replace: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.data-table')
.directive('lxDataTable', lxDataTable);
function lxDataTable()
{
return {
restrict: 'E',
templateUrl: 'data-table.html',
scope:
{
border: '=?lxBorder',
selectable: '=?lxSelectable',
thumbnail: '=?lxThumbnail',
tbody: '=lxTbody',
thead: '=lxThead'
},
link: link,
controller: LxDataTableController,
controllerAs: 'lxDataTable',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
attrs.$observe('id', function(_newId)
{
ctrl.id = _newId;
});
}
}
LxDataTableController.$inject = ['$rootScope', '$sce', '$scope'];
function LxDataTableController($rootScope, $sce, $scope)
{
var lxDataTable = this;
lxDataTable.areAllRowsSelected = areAllRowsSelected;
lxDataTable.border = angular.isUndefined(lxDataTable.border) ? true : lxDataTable.border;
lxDataTable.sort = sort;
lxDataTable.toggle = toggle;
lxDataTable.toggleAllSelected = toggleAllSelected;
lxDataTable.$sce = $sce;
lxDataTable.allRowsSelected = false;
lxDataTable.selectedRows = [];
$scope.$on('lx-data-table__select', function(event, id, row)
{
if (id === lxDataTable.id && angular.isDefined(row))
{
if (angular.isArray(row) && row.length > 0)
{
row = row[0];
}
_select(row);
}
});
$scope.$on('lx-data-table__select-all', function(event, id)
{
if (id === lxDataTable.id)
{
_selectAll();
}
});
$scope.$on('lx-data-table__unselect', function(event, id, row)
{
if (id === lxDataTable.id && angular.isDefined(row))
{
if (angular.isArray(row) && row.length > 0)
{
row = row[0];
}
_unselect(row);
}
});
$scope.$on('lx-data-table__unselect-all', function(event, id)
{
if (id === lxDataTable.id)
{
_unselectAll();
}
});
////////////
function _selectAll()
{
lxDataTable.selectedRows.length = 0;
for (var i = 0, len = lxDataTable.tbody.length; i < len; i++)
{
if (!lxDataTable.tbody[i].lxDataTableDisabled)
{
lxDataTable.tbody[i].lxDataTableSelected = true;
lxDataTable.selectedRows.push(lxDataTable.tbody[i]);
}
}
lxDataTable.allRowsSelected = true;
$rootScope.$broadcast('lx-data-table__unselected', lxDataTable.id, lxDataTable.selectedRows);
}
function _select(row)
{
toggle(row, true);
}
function _unselectAll()
{
for (var i = 0, len = lxDataTable.tbody.length; i < len; i++)
{
if (!lxDataTable.tbody[i].lxDataTableDisabled)
{
lxDataTable.tbody[i].lxDataTableSelected = false;
}
}
lxDataTable.allRowsSelected = false;
lxDataTable.selectedRows.length = 0;
$rootScope.$broadcast('lx-data-table__selected', lxDataTable.id, lxDataTable.selectedRows);
}
function _unselect(row)
{
toggle(row, false);
}
////////////
function areAllRowsSelected()
{
var displayedRows = 0;
for (var i = 0, len = lxDataTable.tbody.length; i < len; i++)
{
if (!lxDataTable.tbody[i].lxDataTableDisabled)
{
displayedRows++;
}
}
if (displayedRows === lxDataTable.selectedRows.length)
{
lxDataTable.allRowsSelected = true;
}
else
{
lxDataTable.allRowsSelected = false;
}
}
function sort(_column)
{
if (!_column.sortable)
{
return;
}
for (var i = 0, len = lxDataTable.thead.length; i < len; i++)
{
if (lxDataTable.thead[i].sortable && lxDataTable.thead[i].name !== _column.name)
{
lxDataTable.thead[i].sort = undefined;
}
}
if (!_column.sort || _column.sort === 'desc')
{
_column.sort = 'asc';
}
else
{
_column.sort = 'desc';
}
$rootScope.$broadcast('lx-data-table__sorted', lxDataTable.id, _column);
}
function toggle(_row, _newSelectedStatus)
{
if (_row.lxDataTableDisabled || !lxDataTable.selectable)
{
return;
}
_row.lxDataTableSelected = angular.isDefined(_newSelectedStatus) ? _newSelectedStatus : !_row.lxDataTableSelected;
if (_row.lxDataTableSelected)
{
// Make sure it's not already in.
if (lxDataTable.selectedRows.length === 0 || (lxDataTable.selectedRows.length && lxDataTable.selectedRows.indexOf(_row) === -1))
{
lxDataTable.selectedRows.push(_row);
lxDataTable.areAllRowsSelected();
$rootScope.$broadcast('lx-data-table__selected', lxDataTable.id, lxDataTable.selectedRows);
}
}
else
{
if (lxDataTable.selectedRows.length && lxDataTable.selectedRows.indexOf(_row) > -1)
{
lxDataTable.selectedRows.splice(lxDataTable.selectedRows.indexOf(_row), 1);
lxDataTable.allRowsSelected = false;
$rootScope.$broadcast('lx-data-table__unselected', lxDataTable.id, lxDataTable.selectedRows);
}
}
}
function toggleAllSelected()
{
if (lxDataTable.allRowsSelected)
{
_unselectAll();
}
else
{
_selectAll();
}
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.data-table')
.service('LxDataTableService', LxDataTableService);
LxDataTableService.$inject = ['$rootScope'];
function LxDataTableService($rootScope)
{
var service = this;
service.select = select;
service.selectAll = selectAll;
service.unselect = unselect;
service.unselectAll = unselectAll;
////////////
function select(_dataTableId, row)
{
$rootScope.$broadcast('lx-data-table__select', _dataTableId, row);
}
function selectAll(_dataTableId)
{
$rootScope.$broadcast('lx-data-table__select-all', _dataTableId);
}
function unselect(_dataTableId, row)
{
$rootScope.$broadcast('lx-data-table__unselect', _dataTableId, row);
}
function unselectAll(_dataTableId)
{
$rootScope.$broadcast('lx-data-table__unselect-all', _dataTableId);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.date-picker')
.directive('lxDatePicker', lxDatePicker);
lxDatePicker.$inject = ['LxDatePickerService', 'LxUtils'];
function lxDatePicker(LxDatePickerService, LxUtils)
{
return {
restrict: 'AE',
templateUrl: 'date-picker.html',
scope:
{
autoClose: '=?lxAutoClose',
callback: '&?lxCallback',
color: '@?lxColor',
escapeClose: '=?lxEscapeClose',
inputFormat: '@?lxInputFormat',
maxDate: '=?lxMaxDate',
ngModel: '=',
minDate: '=?lxMinDate',
locale: '@lxLocale'
},
link: link,
controller: LxDatePickerController,
controllerAs: 'lxDatePicker',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs)
{
if (angular.isDefined(attrs.id))
{
attrs.$observe('id', function(_newId)
{
scope.lxDatePicker.pickerId = _newId;
LxDatePickerService.registerScope(scope.lxDatePicker.pickerId, scope);
});
}
else
{
scope.lxDatePicker.pickerId = LxUtils.generateUUID();
LxDatePickerService.registerScope(scope.lxDatePicker.pickerId, scope);
}
}
}
LxDatePickerController.$inject = ['$element', '$scope', '$timeout', '$transclude', 'LxDatePickerService', 'LxUtils'];
function LxDatePickerController($element, $scope, $timeout, $transclude, LxDatePickerService, LxUtils)
{
var lxDatePicker = this;
var input;
var modelController;
var timer1;
var timer2;
var watcher1;
var watcher2;
lxDatePicker.closeDatePicker = closeDatePicker;
lxDatePicker.displayYearSelection = displayYearSelection;
lxDatePicker.hideYearSelection = hideYearSelection;
lxDatePicker.getDateFormatted = getDateFormatted;
lxDatePicker.nextMonth = nextMonth;
lxDatePicker.openDatePicker = openDatePicker;
lxDatePicker.previousMonth = previousMonth;
lxDatePicker.select = select;
lxDatePicker.selectYear = selectYear;
lxDatePicker.autoClose = angular.isDefined(lxDatePicker.autoClose) ? lxDatePicker.autoClose : true;
lxDatePicker.color = angular.isDefined(lxDatePicker.color) ? lxDatePicker.color : 'primary';
lxDatePicker.element = $element.find('.lx-date-picker');
lxDatePicker.escapeClose = angular.isDefined(lxDatePicker.escapeClose) ? lxDatePicker.escapeClose : true;
lxDatePicker.isOpen = false;
lxDatePicker.moment = moment;
lxDatePicker.yearSelection = false;
lxDatePicker.uuid = LxUtils.generateUUID();
$transclude(function(clone)
{
if (clone.length)
{
lxDatePicker.hasInput = true;
timer1 = $timeout(function()
{
input = $element.find('.lx-date-input input');
modelController = input.data('$ngModelController');
watcher2 = $scope.$watch(function()
{
return modelController.$viewValue;
}, function(newValue, oldValue)
{
if (angular.isUndefined(newValue))
{
lxDatePicker.ngModel = undefined;
}
});
});
}
});
watcher1 = $scope.$watch(function()
{
return lxDatePicker.ngModel;
}, init);
$scope.$on('$destroy', function()
{
$timeout.cancel(timer1);
$timeout.cancel(timer2);
if (angular.isFunction(watcher1))
{
watcher1();
}
if (angular.isFunction(watcher2))
{
watcher2();
}
});
////////////
function closeDatePicker()
{
LxDatePickerService.close(lxDatePicker.pickerId);
}
function displayYearSelection()
{
lxDatePicker.yearSelection = true;
timer2 = $timeout(function()
{
var yearSelector = angular.element('.lx-date-picker__year-selector');
var activeYear = yearSelector.find('.lx-date-picker__year--is-active');
yearSelector.scrollTop(yearSelector.scrollTop() + activeYear.position().top - yearSelector.height() / 2 + activeYear.height() / 2);
});
}
function hideYearSelection()
{
lxDatePicker.yearSelection = false;
}
function generateCalendar()
{
lxDatePicker.days = [];
var previousDay = angular.copy(lxDatePicker.ngModelMoment).date(0);
var firstDayOfMonth = angular.copy(lxDatePicker.ngModelMoment).date(1);
var lastDayOfMonth = firstDayOfMonth.clone().endOf('month');
var maxDays = lastDayOfMonth.date();
lxDatePicker.emptyFirstDays = [];
for (var i = firstDayOfMonth.day() === 0 ? 6 : firstDayOfMonth.day() - 1; i > 0; i--)
{
lxDatePicker.emptyFirstDays.push(
{});
}
for (var j = 0; j < maxDays; j++)
{
var date = angular.copy(previousDay.add(1, 'days'));
date.selected = angular.isDefined(lxDatePicker.ngModel) && date.isSame(lxDatePicker.ngModel, 'day');
date.today = date.isSame(moment(), 'day');
if (angular.isDefined(lxDatePicker.minDate) && date.toDate() < lxDatePicker.minDate)
{
date.disabled = true;
}
if (angular.isDefined(lxDatePicker.maxDate) && date.toDate() > lxDatePicker.maxDate)
{
date.disabled = true;
}
lxDatePicker.days.push(date);
}
lxDatePicker.emptyLastDays = [];
for (var k = 7 - (lastDayOfMonth.day() === 0 ? 7 : lastDayOfMonth.day()); k > 0; k--)
{
lxDatePicker.emptyLastDays.push(
{});
}
}
function getDateFormatted()
{
var dateFormatted = lxDatePicker.ngModelMoment.format('llll').replace(lxDatePicker.ngModelMoment.format('LT'), '').trim().replace(lxDatePicker.ngModelMoment.format('YYYY'), '').trim();
var dateFormattedLastChar = dateFormatted.slice(-1);
if (dateFormattedLastChar === ',')
{
dateFormatted = dateFormatted.slice(0, -1);
}
return dateFormatted;
}
function init()
{
moment.locale(lxDatePicker.locale);
lxDatePicker.ngModelMoment = angular.isDefined(lxDatePicker.ngModel) ? moment(angular.copy(lxDatePicker.ngModel)) : moment();
lxDatePicker.days = [];
lxDatePicker.daysOfWeek = [moment.weekdaysMin(1), moment.weekdaysMin(2), moment.weekdaysMin(3), moment.weekdaysMin(4), moment.weekdaysMin(5), moment.weekdaysMin(6), moment.weekdaysMin(0)];
lxDatePicker.years = [];
for (var y = moment().year() - 100; y <= moment().year() + 100; y++)
{
lxDatePicker.years.push(y);
}
generateCalendar();
}
function nextMonth()
{
lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.add(1, 'month');
generateCalendar();
}
function openDatePicker()
{
LxDatePickerService.open(lxDatePicker.pickerId);
}
function previousMonth()
{
lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.subtract(1, 'month');
generateCalendar();
}
function select(_day)
{
if (!_day.disabled)
{
lxDatePicker.ngModel = _day.toDate();
lxDatePicker.ngModelMoment = angular.copy(_day);
if (angular.isDefined(lxDatePicker.callback))
{
lxDatePicker.callback(
{
newDate: lxDatePicker.ngModel
});
}
if (angular.isDefined(modelController) && lxDatePicker.inputFormat)
{
modelController.$setViewValue(angular.copy(_day).format(lxDatePicker.inputFormat));
modelController.$render();
}
generateCalendar();
}
}
function selectYear(_year)
{
lxDatePicker.yearSelection = false;
lxDatePicker.ngModelMoment = lxDatePicker.ngModelMoment.year(_year);
generateCalendar();
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.date-picker')
.service('LxDatePickerService', LxDatePickerService);
LxDatePickerService.$inject = ['$rootScope', '$timeout', 'LxDepthService', 'LxEventSchedulerService'];
function LxDatePickerService($rootScope, $timeout, LxDepthService, LxEventSchedulerService)
{
var service = this;
var activeDatePickerId;
var datePickerFilter;
var idEventScheduler;
var scopeMap = {};
service.close = closeDatePicker;
service.open = openDatePicker;
service.registerScope = registerScope;
////////////
function closeDatePicker(_datePickerId)
{
if (angular.isDefined(idEventScheduler))
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
activeDatePickerId = undefined;
$rootScope.$broadcast('lx-date-picker__close-start', _datePickerId);
datePickerFilter.removeClass('lx-date-picker-filter--is-shown');
scopeMap[_datePickerId].element.removeClass('lx-date-picker--is-shown');
$timeout(function()
{
angular.element('body').removeClass('no-scroll-date-picker-' + scopeMap[_datePickerId].uuid);
datePickerFilter.remove();
scopeMap[_datePickerId].element
.hide()
.appendTo(scopeMap[_datePickerId].elementParent);
scopeMap[_datePickerId].isOpen = false;
$rootScope.$broadcast('lx-date-picker__close-end', _datePickerId);
}, 600);
}
function onKeyUp(_event)
{
if (_event.keyCode == 27 && angular.isDefined(activeDatePickerId))
{
closeDatePicker(activeDatePickerId);
}
_event.stopPropagation();
}
function openDatePicker(_datePickerId)
{
LxDepthService.register();
activeDatePickerId = _datePickerId;
angular.element('body').addClass('no-scroll-date-picker-' + scopeMap[_datePickerId].uuid);
datePickerFilter = angular.element('<div/>',
{
class: 'lx-date-picker-filter'
});
datePickerFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
if (scopeMap[activeDatePickerId].autoClose)
{
datePickerFilter.on('click', function()
{
closeDatePicker(activeDatePickerId);
});
}
if (scopeMap[activeDatePickerId].escapeClose)
{
idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp);
}
scopeMap[activeDatePickerId].element
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show();
$timeout(function()
{
$rootScope.$broadcast('lx-date-picker__open-start', activeDatePickerId);
scopeMap[activeDatePickerId].isOpen = true;
datePickerFilter.addClass('lx-date-picker-filter--is-shown');
scopeMap[activeDatePickerId].element.addClass('lx-date-picker--is-shown');
}, 100);
$timeout(function()
{
$rootScope.$broadcast('lx-date-picker__open-end', activeDatePickerId);
}, 700);
}
function registerScope(_datePickerId, _datePickerScope)
{
scopeMap[_datePickerId] = _datePickerScope.lxDatePicker;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.dialog')
.directive('lxDialog', lxDialog)
.directive('lxDialogHeader', lxDialogHeader)
.directive('lxDialogContent', lxDialogContent)
.directive('lxDialogFooter', lxDialogFooter)
.directive('lxDialogClose', lxDialogClose);
function lxDialog()
{
return {
restrict: 'E',
template: '<div class="dialog" ng-class="{ \'dialog--l\': !lxDialog.size || lxDialog.size === \'l\', \'dialog--s\': lxDialog.size === \'s\', \'dialog--m\': lxDialog.size === \'m\' }"><div ng-if="lxDialog.isOpen" ng-transclude></div></div>',
scope:
{
autoClose: '=?lxAutoClose',
escapeClose: '=?lxEscapeClose',
size: '@?lxSize'
},
link: link,
controller: LxDialogController,
controllerAs: 'lxDialog',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl)
{
attrs.$observe('id', function(_newId)
{
ctrl.id = _newId;
});
}
}
LxDialogController.$inject = ['$element', '$interval', '$rootScope', '$scope', '$timeout', '$window', 'LxDepthService', 'LxEventSchedulerService', 'LxUtils'];
function LxDialogController($element, $interval, $rootScope, $scope, $timeout, $window, LxDepthService, LxEventSchedulerService, LxUtils)
{
var lxDialog = this;
var dialogFilter = angular.element('<div/>',
{
class: 'dialog-filter'
});
var dialogHeight;
var dialogInterval;
var dialogScrollable;
var elementParent = $element.parent();
var idEventScheduler;
var resizeDebounce;
var windowHeight;
lxDialog.autoClose = angular.isDefined(lxDialog.autoClose) ? lxDialog.autoClose : true;
lxDialog.escapeClose = angular.isDefined(lxDialog.escapeClose) ? lxDialog.escapeClose : true;
lxDialog.isOpen = false;
lxDialog.uuid = LxUtils.generateUUID();
$scope.$on('lx-dialog__open', function(event, id)
{
if (id === lxDialog.id)
{
open();
}
});
$scope.$on('lx-dialog__close', function(event, id)
{
if (id === lxDialog.id)
{
close();
}
});
$scope.$on('$destroy', function()
{
close();
});
////////////
function checkDialogHeight()
{
var dialog = $element;
var dialogHeader = dialog.find('.dialog__header');
var dialogContent = dialog.find('.dialog__content');
var dialogFooter = dialog.find('.dialog__footer');
if (!dialogFooter.length)
{
dialogFooter = dialog.find('.dialog__actions');
}
if (angular.isUndefined(dialogHeader))
{
return;
}
var heightToCheck = 60 + dialogHeader.outerHeight() + dialogContent.outerHeight() + dialogFooter.outerHeight();
if (dialogHeight === heightToCheck && windowHeight === $window.innerHeight)
{
return;
}
dialogHeight = heightToCheck;
windowHeight = $window.innerHeight;
if (heightToCheck >= $window.innerHeight)
{
dialog.addClass('dialog--is-fixed');
dialogScrollable
.css(
{
top: dialogHeader.outerHeight(),
bottom: dialogFooter.outerHeight()
})
.off('scroll', checkScrollEnd)
.on('scroll', checkScrollEnd);
}
else
{
dialog.removeClass('dialog--is-fixed');
dialogScrollable
.removeAttr('style')
.off('scroll', checkScrollEnd);
}
}
function checkDialogHeightOnResize()
{
if (resizeDebounce)
{
$timeout.cancel(resizeDebounce);
}
resizeDebounce = $timeout(function()
{
checkDialogHeight();
}, 200);
}
function checkScrollEnd()
{
if (dialogScrollable.scrollTop() + dialogScrollable.innerHeight() >= dialogScrollable[0].scrollHeight)
{
$rootScope.$broadcast('lx-dialog__scroll-end', lxDialog.id);
dialogScrollable.off('scroll', checkScrollEnd);
$timeout(function()
{
dialogScrollable.on('scroll', checkScrollEnd);
}, 500);
}
}
function onKeyUp(_event)
{
if (_event.keyCode == 27)
{
close();
}
_event.stopPropagation();
}
function open()
{
if (lxDialog.isOpen)
{
return;
}
LxDepthService.register();
angular.element('body').addClass('no-scroll-dialog-' + lxDialog.uuid);
dialogFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
if (lxDialog.autoClose)
{
dialogFilter.on('click', function()
{
close();
});
}
if (lxDialog.escapeClose)
{
idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp);
}
$element
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show();
$timeout(function()
{
$rootScope.$broadcast('lx-dialog__open-start', lxDialog.id);
lxDialog.isOpen = true;
dialogFilter.addClass('dialog-filter--is-shown');
$element.addClass('dialog--is-shown');
}, 100);
$timeout(function()
{
if ($element.find('.dialog__scrollable').length === 0)
{
$element.find('.dialog__content').wrap(angular.element('<div/>',
{
class: 'dialog__scrollable'
}));
}
dialogScrollable = $element.find('.dialog__scrollable');
}, 200);
$timeout(function()
{
$rootScope.$broadcast('lx-dialog__open-end', lxDialog.id);
}, 700);
dialogInterval = $interval(function()
{
checkDialogHeight();
}, 500);
angular.element($window).on('resize', checkDialogHeightOnResize);
}
function close()
{
if (!lxDialog.isOpen)
{
return;
}
if (angular.isDefined(idEventScheduler))
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
angular.element($window).off('resize', checkDialogHeightOnResize);
$element.find('.dialog__scrollable').off('scroll', checkScrollEnd);
$rootScope.$broadcast('lx-dialog__close-start', lxDialog.id);
if (resizeDebounce)
{
$timeout.cancel(resizeDebounce);
}
$interval.cancel(dialogInterval);
dialogFilter.removeClass('dialog-filter--is-shown');
$element.removeClass('dialog--is-shown');
$timeout(function()
{
angular.element('body').removeClass('no-scroll-dialog-' + lxDialog.uuid);
dialogFilter.remove();
$element
.hide()
.removeClass('dialog--is-fixed')
.appendTo(elementParent);
lxDialog.isOpen = false;
dialogHeight = undefined;
$rootScope.$broadcast('lx-dialog__close-end', lxDialog.id);
}, 600);
}
}
function lxDialogHeader()
{
return {
restrict: 'E',
template: '<div class="dialog__header" ng-transclude></div>',
replace: true,
transclude: true
};
}
function lxDialogContent()
{
return {
restrict: 'E',
template: '<div class="dialog__scrollable"><div class="dialog__content" ng-transclude></div></div>',
replace: true,
transclude: true
};
}
function lxDialogFooter()
{
return {
restrict: 'E',
template: '<div class="dialog__footer" ng-transclude></div>',
replace: true,
transclude: true
};
}
lxDialogClose.$inject = ['LxDialogService'];
function lxDialogClose(LxDialogService)
{
return {
restrict: 'A',
link: function(scope, element)
{
element.on('click', function()
{
LxDialogService.close(element.parents('.dialog').attr('id'));
});
scope.$on('$destroy', function()
{
element.off();
});
}
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.dialog')
.service('LxDialogService', LxDialogService);
LxDialogService.$inject = ['$rootScope'];
function LxDialogService($rootScope)
{
var service = this;
service.open = open;
service.close = close;
////////////
function open(_dialogId)
{
$rootScope.$broadcast('lx-dialog__open', _dialogId);
}
function close(_dialogId)
{
$rootScope.$broadcast('lx-dialog__close', _dialogId);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.dropdown')
.directive('lxDropdown', lxDropdown)
.directive('lxDropdownToggle', lxDropdownToggle)
.directive('lxDropdownMenu', lxDropdownMenu)
.directive('lxDropdownFilter', lxDropdownFilter);
function lxDropdown()
{
return {
restrict: 'E',
templateUrl: 'dropdown.html',
scope:
{
depth: '@?lxDepth',
effect: '@?lxEffect',
escapeClose: '=?lxEscapeClose',
hover: '=?lxHover',
hoverDelay: '=?lxHoverDelay',
offset: '@?lxOffset',
overToggle: '=?lxOverToggle',
position: '@?lxPosition',
width: '@?lxWidth'
},
link: link,
controller: LxDropdownController,
controllerAs: 'lxDropdown',
bindToController: true,
transclude: true
};
function link(scope, element, attrs, ctrl)
{
var backwardOneWay = ['position', 'width'];
var backwardTwoWay = ['escapeClose', 'overToggle'];
angular.forEach(backwardOneWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
attrs.$observe(attribute, function(newValue)
{
scope.lxDropdown[attribute] = newValue;
});
}
});
angular.forEach(backwardTwoWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
scope.$watch(function()
{
return scope.$parent.$eval(attrs[attribute]);
}, function(newValue)
{
scope.lxDropdown[attribute] = newValue;
});
}
});
attrs.$observe('id', function(_newId)
{
ctrl.uuid = _newId;
});
scope.$on('$destroy', function()
{
if (ctrl.isOpen)
{
ctrl.closeDropdownMenu();
}
});
}
}
LxDropdownController.$inject = ['$element', '$interval', '$scope', '$timeout', '$window', 'LxDepthService',
'LxDropdownService', 'LxEventSchedulerService', 'LxUtils'
];
function LxDropdownController($element, $interval, $scope, $timeout, $window, LxDepthService,
LxDropdownService, LxEventSchedulerService, LxUtils)
{
var lxDropdown = this;
var dropdownInterval;
var dropdownMenu;
var dropdownToggle;
var idEventScheduler;
var openTimeout;
var positionTarget;
var scrollMask = angular.element('<div/>',
{
class: 'scroll-mask'
});
var enableBodyScroll;
lxDropdown.closeDropdownMenu = closeDropdownMenu;
lxDropdown.openDropdownMenu = openDropdownMenu;
lxDropdown.registerDropdownMenu = registerDropdownMenu;
lxDropdown.registerDropdownToggle = registerDropdownToggle;
lxDropdown.toggle = toggle;
lxDropdown.uuid = LxUtils.generateUUID();
lxDropdown.effect = angular.isDefined(lxDropdown.effect) ? lxDropdown.effect : 'expand';
lxDropdown.escapeClose = angular.isDefined(lxDropdown.escapeClose) ? lxDropdown.escapeClose : true;
lxDropdown.hasToggle = false;
lxDropdown.isOpen = false;
lxDropdown.overToggle = angular.isDefined(lxDropdown.overToggle) ? lxDropdown.overToggle : false;
lxDropdown.position = angular.isDefined(lxDropdown.position) ? lxDropdown.position : 'left';
$scope.$on('lx-dropdown__open', function(_event, _params)
{
if (_params.uuid === lxDropdown.uuid && !lxDropdown.isOpen)
{
LxDropdownService.closeActiveDropdown();
LxDropdownService.registerActiveDropdownUuid(lxDropdown.uuid);
positionTarget = _params.target;
registerDropdownToggle(angular.element(positionTarget));
openDropdownMenu();
}
});
$scope.$on('lx-dropdown__close', function(_event, _params)
{
if (_params.uuid === lxDropdown.uuid && lxDropdown.isOpen)
{
closeDropdownMenu();
}
});
$scope.$on('$destroy', function()
{
$timeout.cancel(openTimeout);
});
////////////
function closeDropdownMenu()
{
$interval.cancel(dropdownInterval);
LxDropdownService.resetActiveDropdownUuid();
var velocityProperties;
var velocityEasing;
scrollMask.remove();
if (angular.isFunction(enableBodyScroll)) {
enableBodyScroll();
}
enableBodyScroll = undefined;
if (lxDropdown.hasToggle)
{
dropdownToggle
.off('wheel')
.css('z-index', '');
}
dropdownMenu
.off('wheel')
.css(
{
overflow: 'hidden'
});
if (lxDropdown.effect === 'expand')
{
velocityProperties = {
width: 0,
height: 0
};
velocityEasing = 'easeOutQuint';
}
else if (lxDropdown.effect === 'fade')
{
velocityProperties = {
opacity: 0
};
velocityEasing = 'linear';
}
if (lxDropdown.effect === 'expand' || lxDropdown.effect === 'fade')
{
dropdownMenu.velocity(velocityProperties,
{
duration: 200,
easing: velocityEasing,
complete: function()
{
dropdownMenu
.removeAttr('style')
.removeClass('dropdown-menu--is-open')
.appendTo($element.find('.dropdown'));
$scope.$apply(function()
{
lxDropdown.isOpen = false;
if (lxDropdown.escapeClose)
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
});
}
});
}
else if (lxDropdown.effect === 'none')
{
dropdownMenu
.removeAttr('style')
.removeClass('dropdown-menu--is-open')
.appendTo($element.find('.dropdown'));
lxDropdown.isOpen = false;
if (lxDropdown.escapeClose)
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}
}
}
function getAvailableHeight()
{
var availableHeightOnTop;
var availableHeightOnBottom;
var direction;
var dropdownToggleHeight = dropdownToggle.outerHeight();
var dropdownToggleTop = dropdownToggle.offset().top - angular.element($window).scrollTop();
var windowHeight = $window.innerHeight;
if (lxDropdown.overToggle)
{
availableHeightOnTop = dropdownToggleTop + dropdownToggleHeight;
availableHeightOnBottom = windowHeight - dropdownToggleTop;
}
else
{
availableHeightOnTop = dropdownToggleTop;
availableHeightOnBottom = windowHeight - (dropdownToggleTop + dropdownToggleHeight);
}
if (availableHeightOnTop > availableHeightOnBottom)
{
direction = 'top';
}
else
{
direction = 'bottom';
}
return {
top: availableHeightOnTop,
bottom: availableHeightOnBottom,
direction: direction
};
}
function initDropdownPosition()
{
var availableHeight = getAvailableHeight();
var dropdownMenuWidth;
var dropdownMenuLeft;
var dropdownMenuRight;
var dropdownToggleWidth = dropdownToggle.outerWidth();
var dropdownToggleHeight = dropdownToggle.outerHeight();
var dropdownToggleTop = dropdownToggle.offset().top - angular.element($window).scrollTop();
var windowWidth = $window.innerWidth;
var windowHeight = $window.innerHeight;
if (angular.isDefined(lxDropdown.width))
{
if (lxDropdown.width.indexOf('%') > -1)
{
dropdownMenuWidth = dropdownToggleWidth * (lxDropdown.width.slice(0, -1) / 100);
}
else
{
dropdownMenuWidth = lxDropdown.width;
}
}
else
{
dropdownMenuWidth = 'auto';
}
if (lxDropdown.position === 'left')
{
dropdownMenuLeft = dropdownToggle.offset().left;
dropdownMenuRight = 'auto';
}
else if (lxDropdown.position === 'right')
{
dropdownMenuLeft = 'auto';
dropdownMenuRight = windowWidth - dropdownToggle.offset().left - dropdownToggleWidth;
}
else if (lxDropdown.position === 'center')
{
dropdownMenuLeft = (dropdownToggle.offset().left + (dropdownToggleWidth / 2)) - (dropdownMenuWidth / 2);
dropdownMenuRight = 'auto';
}
dropdownMenu.css(
{
left: dropdownMenuLeft,
right: dropdownMenuRight,
width: dropdownMenuWidth
});
if (availableHeight.direction === 'top')
{
dropdownMenu.css(
{
bottom: lxDropdown.overToggle ? (windowHeight - dropdownToggleTop - dropdownToggleHeight) : (windowHeight - dropdownToggleTop + ~~lxDropdown.offset)
});
return availableHeight.top;
}
else if (availableHeight.direction === 'bottom')
{
dropdownMenu.css(
{
top: lxDropdown.overToggle ? dropdownToggleTop : (dropdownToggleTop + dropdownToggleHeight + ~~lxDropdown.offset)
});
return availableHeight.bottom;
}
}
function openDropdownMenu()
{
lxDropdown.isOpen = true;
LxDepthService.register();
scrollMask
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
scrollMask.on('wheel', function preventDefault(e) {
e.preventDefault();
});
enableBodyScroll = LxUtils.disableBodyScroll();
if (lxDropdown.hasToggle)
{
dropdownToggle
.css('z-index', LxDepthService.getDepth() + 1)
.on('wheel', function preventDefault(e) {
e.preventDefault();
});
}
dropdownMenu
.addClass('dropdown-menu--is-open')
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body');
dropdownMenu.on('wheel', function preventDefault(e) {
var d = e.originalEvent.deltaY;
if (d < 0 && dropdownMenu.scrollTop() === 0) {
e.preventDefault();
}
else {
if (d > 0 && (dropdownMenu.scrollTop() == dropdownMenu.get(0).scrollHeight - dropdownMenu.innerHeight())) {
e.preventDefault();
}
}
});
if (lxDropdown.escapeClose)
{
idEventScheduler = LxEventSchedulerService.register('keyup', onKeyUp);
}
openTimeout = $timeout(function()
{
var availableHeight = initDropdownPosition() - ~~lxDropdown.offset;
var dropdownMenuHeight = dropdownMenu.outerHeight();
var dropdownMenuWidth = dropdownMenu.outerWidth();
var enoughHeight = true;
if (availableHeight < dropdownMenuHeight)
{
enoughHeight = false;
dropdownMenuHeight = availableHeight;
}
if (lxDropdown.effect === 'expand')
{
dropdownMenu.css(
{
width: 0,
height: 0,
opacity: 1,
overflow: 'hidden'
});
dropdownMenu.find('.dropdown-menu__content').css(
{
width: dropdownMenuWidth,
height: dropdownMenuHeight
});
dropdownMenu.velocity(
{
width: dropdownMenuWidth
},
{
duration: 200,
easing: 'easeOutQuint',
queue: false
});
dropdownMenu.velocity(
{
height: dropdownMenuHeight
},
{
duration: 500,
easing: 'easeOutQuint',
queue: false,
complete: function()
{
dropdownMenu.css(
{
overflow: 'auto'
});
if (angular.isUndefined(lxDropdown.width))
{
dropdownMenu.css(
{
width: 'auto'
});
}
$timeout(updateDropdownMenuHeight);
dropdownMenu.find('.dropdown-menu__content').removeAttr('style');
dropdownInterval = $interval(updateDropdownMenuHeight, 500);
}
});
}
else if (lxDropdown.effect === 'fade')
{
dropdownMenu.css(
{
height: dropdownMenuHeight
});
dropdownMenu.velocity(
{
opacity: 1,
},
{
duration: 200,
easing: 'linear',
queue: false,
complete: function()
{
$timeout(updateDropdownMenuHeight);
dropdownInterval = $interval(updateDropdownMenuHeight, 500);
}
});
}
else if (lxDropdown.effect === 'none')
{
dropdownMenu.css(
{
opacity: 1
});
$timeout(updateDropdownMenuHeight);
dropdownInterval = $interval(updateDropdownMenuHeight, 500);
}
});
}
function onKeyUp(_event)
{
if (_event.keyCode == 27)
{
closeDropdownMenu();
}
_event.stopPropagation();
}
function registerDropdownMenu(_dropdownMenu)
{
dropdownMenu = _dropdownMenu;
}
function registerDropdownToggle(_dropdownToggle)
{
if (!positionTarget)
{
lxDropdown.hasToggle = true;
}
dropdownToggle = _dropdownToggle;
}
function toggle()
{
if (!lxDropdown.isOpen)
{
openDropdownMenu();
}
else
{
closeDropdownMenu();
}
}
function updateDropdownMenuHeight()
{
if (positionTarget)
{
registerDropdownToggle(angular.element(positionTarget));
}
var availableHeight = getAvailableHeight();
var dropdownMenuHeight = dropdownMenu.find('.dropdown-menu__content').outerHeight();
dropdownMenu.css(
{
height: 'auto'
});
if ((availableHeight[availableHeight.direction] - ~~lxDropdown.offset) < dropdownMenuHeight)
{
if (availableHeight.direction === 'top')
{
dropdownMenu.css(
{
top: 0
});
}
else if (availableHeight.direction === 'bottom')
{
dropdownMenu.css(
{
bottom: 0
});
}
}
else
{
if (availableHeight.direction === 'top')
{
dropdownMenu.css(
{
top: 'auto'
});
}
else if (availableHeight.direction === 'bottom')
{
dropdownMenu.css(
{
bottom: 'auto'
});
}
}
}
}
lxDropdownToggle.$inject = ['$timeout', 'LxDropdownService'];
function lxDropdownToggle($timeout, LxDropdownService)
{
return {
restrict: 'AE',
templateUrl: 'dropdown-toggle.html',
require: '^lxDropdown',
scope: true,
link: link,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl)
{
var hoverTimeout = [];
var mouseEvent = ctrl.hover ? 'mouseenter' : 'click';
ctrl.registerDropdownToggle(element);
element.on(mouseEvent, function(_event)
{
if (mouseEvent === 'mouseenter' && 'ontouchstart' in window) {
return;
}
if (!ctrl.hover)
{
_event.stopPropagation();
}
LxDropdownService.closeActiveDropdown();
LxDropdownService.registerActiveDropdownUuid(ctrl.uuid);
if (ctrl.hover)
{
ctrl.mouseOnToggle = true;
if (!ctrl.isOpen)
{
hoverTimeout[0] = $timeout(function()
{
scope.$apply(function()
{
ctrl.openDropdownMenu();
});
}, ctrl.hoverDelay);
}
}
else
{
scope.$apply(function()
{
ctrl.toggle();
});
}
});
if (ctrl.hover)
{
element.on('mouseleave', function()
{
ctrl.mouseOnToggle = false;
$timeout.cancel(hoverTimeout[0]);
hoverTimeout[1] = $timeout(function()
{
if (!ctrl.mouseOnMenu)
{
scope.$apply(function()
{
ctrl.closeDropdownMenu();
});
}
}, ctrl.hoverDelay);
});
}
scope.$on('$destroy', function()
{
element.off();
if (ctrl.hover)
{
$timeout.cancel(hoverTimeout[0]);
$timeout.cancel(hoverTimeout[1]);
}
});
}
}
lxDropdownMenu.$inject = ['$timeout'];
function lxDropdownMenu($timeout)
{
return {
restrict: 'E',
templateUrl: 'dropdown-menu.html',
require: ['lxDropdownMenu', '^lxDropdown'],
scope: true,
link: link,
controller: LxDropdownMenuController,
controllerAs: 'lxDropdownMenu',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrls)
{
var hoverTimeout;
ctrls[1].registerDropdownMenu(element);
ctrls[0].setParentController(ctrls[1]);
if (ctrls[1].hover)
{
element.on('mouseenter', function()
{
ctrls[1].mouseOnMenu = true;
});
element.on('mouseleave', function()
{
ctrls[1].mouseOnMenu = false;
hoverTimeout = $timeout(function()
{
if (!ctrls[1].mouseOnToggle)
{
scope.$apply(function()
{
ctrls[1].closeDropdownMenu();
});
}
}, ctrls[1].hoverDelay);
});
}
scope.$on('$destroy', function()
{
if (ctrls[1].hover)
{
element.off();
$timeout.cancel(hoverTimeout);
}
});
}
}
LxDropdownMenuController.$inject = ['$element'];
function LxDropdownMenuController($element)
{
var lxDropdownMenu = this;
lxDropdownMenu.setParentController = setParentController;
////////////
function addDropdownDepth()
{
if (lxDropdownMenu.parentCtrl.depth)
{
$element.addClass('dropdown-menu--depth-' + lxDropdownMenu.parentCtrl.depth);
}
else
{
$element.addClass('dropdown-menu--depth-1');
}
}
function setParentController(_parentCtrl)
{
lxDropdownMenu.parentCtrl = _parentCtrl;
addDropdownDepth();
}
}
lxDropdownFilter.$inject = ['$timeout'];
function lxDropdownFilter($timeout)
{
return {
restrict: 'A',
link: link
};
function link(scope, element)
{
var focusTimeout;
element.on('click', function(_event)
{
_event.stopPropagation();
});
focusTimeout = $timeout(function()
{
element.find('input').focus();
}, 200);
scope.$on('$destroy', function()
{
$timeout.cancel(focusTimeout);
element.off();
});
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.dropdown')
.service('LxDropdownService', LxDropdownService);
LxDropdownService.$inject = ['$document', '$rootScope', '$timeout'];
function LxDropdownService($document, $rootScope, $timeout)
{
var service = this;
var activeDropdownUuid;
service.close = close;
service.closeActiveDropdown = closeActiveDropdown;
service.open = open;
service.isOpen = isOpen;
service.registerActiveDropdownUuid = registerActiveDropdownUuid;
service.resetActiveDropdownUuid = resetActiveDropdownUuid;
$document.on('click', closeActiveDropdown);
////////////
function close(_uuid)
{
$rootScope.$broadcast('lx-dropdown__close',
{
uuid: _uuid
});
}
function closeActiveDropdown()
{
$rootScope.$broadcast('lx-dropdown__close',
{
uuid: activeDropdownUuid
});
}
function open(_uuid, _target)
{
$rootScope.$broadcast('lx-dropdown__open',
{
uuid: _uuid,
target: _target
});
}
function isOpen(_uuid)
{
return activeDropdownUuid === _uuid;
}
function registerActiveDropdownUuid(_uuid)
{
activeDropdownUuid = _uuid;
}
function resetActiveDropdownUuid()
{
activeDropdownUuid = undefined;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.fab')
.directive('lxFab', lxFab)
.directive('lxFabTrigger', lxFabTrigger)
.directive('lxFabActions', lxFabActions);
function lxFab()
{
return {
restrict: 'E',
templateUrl: 'fab.html',
scope: true,
link: link,
controller: LxFabController,
controllerAs: 'lxFab',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
attrs.$observe('lxDirection', function(newDirection)
{
ctrl.setFabDirection(newDirection);
});
}
}
function LxFabController()
{
var lxFab = this;
lxFab.setFabDirection = setFabDirection;
////////////
function setFabDirection(_direction)
{
lxFab.lxDirection = _direction;
}
}
function lxFabTrigger()
{
return {
restrict: 'E',
require: '^lxFab',
templateUrl: 'fab-trigger.html',
transclude: true,
replace: true
};
}
function lxFabActions()
{
return {
restrict: 'E',
require: '^lxFab',
templateUrl: 'fab-actions.html',
link: link,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
scope.parentCtrl = ctrl;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.file-input')
.directive('lxFileInput', lxFileInput);
function lxFileInput()
{
return {
restrict: 'E',
templateUrl: 'file-input.html',
scope:
{
label: '@lxLabel',
callback: '&?lxCallback'
},
link: link,
controller: LxFileInputController,
controllerAs: 'lxFileInput',
bindToController: true,
replace: true
};
function link(scope, element, attrs, ctrl)
{
var input = element.find('input');
input
.on('change', ctrl.updateModel)
.on('blur', function()
{
element.removeClass('input-file--is-focus');
});
scope.$on('$destroy', function()
{
input.off();
});
}
}
LxFileInputController.$inject = ['$element', '$scope', '$timeout'];
function LxFileInputController($element, $scope, $timeout)
{
var lxFileInput = this;
var input = $element.find('input');
var timer;
lxFileInput.updateModel = updateModel;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
////////////
function setFileName()
{
if (input.val())
{
lxFileInput.fileName = input.val().replace(/C:\\fakepath\\/i, '');
$element.addClass('input-file--is-focus');
$element.addClass('input-file--is-active');
}
else
{
lxFileInput.fileName = undefined;
$element.removeClass('input-file--is-active');
}
input.val(undefined);
}
function updateModel()
{
if (angular.isDefined(lxFileInput.callback))
{
lxFileInput.callback(
{
newFile: input[0].files[0]
});
}
timer = $timeout(setFileName);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.icon')
.directive('lxIcon', lxIcon);
function lxIcon()
{
return {
restrict: 'E',
templateUrl: 'icon.html',
scope:
{
color: '@?lxColor',
id: '@lxId',
size: '@?lxSize',
type: '@?lxType'
},
controller: LxIconController,
controllerAs: 'lxIcon',
bindToController: true,
replace: true
};
}
function LxIconController()
{
var lxIcon = this;
lxIcon.getClass = getClass;
////////////
function getClass()
{
var iconClass = [];
iconClass.push('mdi-' + lxIcon.id);
if (angular.isDefined(lxIcon.size))
{
iconClass.push('icon--' + lxIcon.size);
}
if (angular.isDefined(lxIcon.color))
{
iconClass.push('icon--' + lxIcon.color);
}
if (angular.isDefined(lxIcon.type))
{
iconClass.push('icon--' + lxIcon.type);
}
return iconClass;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.notification')
.service('LxNotificationService', LxNotificationService);
LxNotificationService.$inject = ['$injector', '$rootScope', '$timeout', 'LxDepthService', 'LxEventSchedulerService'];
function LxNotificationService($injector, $rootScope, $timeout, LxDepthService, LxEventSchedulerService)
{
var service = this;
var dialogFilter;
var dialog;
var idEventScheduler;
var notificationList = [];
var actionClicked = false;
service.alert = showAlertDialog;
service.confirm = showConfirmDialog;
service.error = notifyError;
service.info = notifyInfo;
service.notify = notify;
service.success = notifySuccess;
service.warning = notifyWarning;
////////////
//
// NOTIFICATION
//
function deleteNotification(_notification, _callback)
{
_callback = (!angular.isFunction(_callback)) ? angular.noop : _callback;
var notifIndex = notificationList.indexOf(_notification);
var dnOffset = angular.isDefined(notificationList[notifIndex]) ? 24 + notificationList[notifIndex].height : 24;
for (var idx = 0; idx < notifIndex; idx++)
{
if (notificationList.length > 1)
{
notificationList[idx].margin -= dnOffset;
notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px');
}
}
_notification.elem.removeClass('notification--is-shown');
$timeout(function()
{
_notification.elem.remove();
// Find index again because notificationList may have changed
notifIndex = notificationList.indexOf(_notification);
if (notifIndex != -1)
{
notificationList.splice(notifIndex, 1);
}
_callback(actionClicked);
actionClicked = false
}, 400);
}
function getElementHeight(_elem)
{
return parseFloat(window.getComputedStyle(_elem, null).height);
}
function moveNotificationUp()
{
var newNotifIndex = notificationList.length - 1;
notificationList[newNotifIndex].height = getElementHeight(notificationList[newNotifIndex].elem[0]);
var upOffset = 0;
for (var idx = newNotifIndex; idx >= 0; idx--)
{
if (notificationList.length > 1 && idx !== newNotifIndex)
{
upOffset = 24 + notificationList[newNotifIndex].height;
notificationList[idx].margin += upOffset;
notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px');
}
}
}
function notify(_text, _icon, _sticky, _color, _action, _callback, _delay)
{
var $compile = $injector.get('$compile');
LxDepthService.register();
var notification = angular.element('<div/>',
{
class: 'notification'
});
var notificationText = angular.element('<span/>',
{
class: 'notification__content',
html: _text
});
var notificationTimeout;
var notificationDelay = _delay || 6000;
if (angular.isDefined(_icon))
{
var notificationIcon = angular.element('<i/>',
{
class: 'notification__icon mdi mdi-' + _icon
});
notification
.addClass('notification--has-icon')
.append(notificationIcon);
}
if (angular.isDefined(_color))
{
notification.addClass('notification--' + _color);
}
notification.append(notificationText);
if (angular.isDefined(_action))
{
var notificationAction = angular.element('<button/>',
{
class: 'notification__action btn btn--m btn--flat',
html: _action
});
if (angular.isDefined(_color))
{
notificationAction.addClass('btn--' + _color);
}
else
{
notificationAction.addClass('btn--white');
}
notificationAction.attr('lx-ripple', '');
$compile(notificationAction)($rootScope);
notificationAction.bind('click', function()
{
actionClicked = true;
});
notification
.addClass('notification--has-action')
.append(notificationAction);
}
notification
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
$timeout(function()
{
notification.addClass('notification--is-shown');
}, 100);
var data = {
elem: notification,
margin: 0
};
notificationList.push(data);
moveNotificationUp();
notification.bind('click', function()
{
deleteNotification(data, _callback);
if (angular.isDefined(notificationTimeout))
{
$timeout.cancel(notificationTimeout);
}
});
if (angular.isUndefined(_sticky) || !_sticky)
{
notificationTimeout = $timeout(function()
{
deleteNotification(data, _callback);
}, notificationDelay);
}
}
function notifyError(_text, _sticky)
{
notify(_text, 'alert-circle', _sticky, 'red');
}
function notifyInfo(_text, _sticky)
{
notify(_text, 'information-outline', _sticky, 'blue');
}
function notifySuccess(_text, _sticky)
{
notify(_text, 'check', _sticky, 'green');
}
function notifyWarning(_text, _sticky)
{
notify(_text, 'alert', _sticky, 'orange');
}
//
// ALERT & CONFIRM
//
function buildDialogActions(_buttons, _callback, _unbind)
{
var $compile = $injector.get('$compile');
var dialogActions = angular.element('<div/>',
{
class: 'dialog__actions'
});
var dialogLastBtn = angular.element('<button/>',
{
class: 'btn btn--m btn--blue btn--flat',
text: _buttons.ok
});
if (angular.isDefined(_buttons.cancel))
{
var dialogFirstBtn = angular.element('<button/>',
{
class: 'btn btn--m btn--red btn--flat',
text: _buttons.cancel
});
dialogFirstBtn.attr('lx-ripple', '');
$compile(dialogFirstBtn)($rootScope);
dialogActions.append(dialogFirstBtn);
dialogFirstBtn.bind('click', function()
{
_callback(false);
closeDialog();
});
}
dialogLastBtn.attr('lx-ripple', '');
$compile(dialogLastBtn)($rootScope);
dialogActions.append(dialogLastBtn);
dialogLastBtn.bind('click', function()
{
_callback(true);
closeDialog();
});
if (!_unbind)
{
idEventScheduler = LxEventSchedulerService.register('keyup', function(event)
{
if (event.keyCode == 13)
{
_callback(true);
closeDialog();
}
else if (event.keyCode == 27)
{
_callback(angular.isUndefined(_buttons.cancel));
closeDialog();
}
event.stopPropagation();
});
}
return dialogActions;
}
function buildDialogContent(_text)
{
var dialogContent = angular.element('<div/>',
{
class: 'dialog__content p++ pt0 tc-black-2',
text: _text
});
return dialogContent;
}
function buildDialogHeader(_title)
{
var dialogHeader = angular.element('<div/>',
{
class: 'dialog__header p++ fs-title',
text: _title
});
return dialogHeader;
}
function closeDialog()
{
if (angular.isDefined(idEventScheduler))
{
$timeout(function()
{
LxEventSchedulerService.unregister(idEventScheduler);
idEventScheduler = undefined;
}, 1);
}
dialogFilter.removeClass('dialog-filter--is-shown');
dialog.removeClass('dialog--is-shown');
$timeout(function()
{
dialogFilter.remove();
dialog.remove();
}, 600);
}
function showAlertDialog(_title, _text, _button, _callback, _unbind)
{
LxDepthService.register();
dialogFilter = angular.element('<div/>',
{
class: 'dialog-filter'
});
dialog = angular.element('<div/>',
{
class: 'dialog dialog--alert'
});
var dialogHeader = buildDialogHeader(_title);
var dialogContent = buildDialogContent(_text);
var dialogActions = buildDialogActions(
{
ok: _button
}, _callback, _unbind);
dialogFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
dialog
.append(dialogHeader)
.append(dialogContent)
.append(dialogActions)
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show()
.focus();
$timeout(function()
{
angular.element(document.activeElement).blur();
dialogFilter.addClass('dialog-filter--is-shown');
dialog.addClass('dialog--is-shown');
}, 100);
}
function showConfirmDialog(_title, _text, _buttons, _callback, _unbind)
{
LxDepthService.register();
dialogFilter = angular.element('<div/>',
{
class: 'dialog-filter'
});
dialog = angular.element('<div/>',
{
class: 'dialog dialog--alert'
});
var dialogHeader = buildDialogHeader(_title);
var dialogContent = buildDialogContent(_text);
var dialogActions = buildDialogActions(_buttons, _callback, _unbind);
dialogFilter
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
dialog
.append(dialogHeader)
.append(dialogContent)
.append(dialogActions)
.css('z-index', LxDepthService.getDepth() + 1)
.appendTo('body')
.show()
.focus();
$timeout(function()
{
angular.element(document.activeElement).blur();
dialogFilter.addClass('dialog-filter--is-shown');
dialog.addClass('dialog--is-shown');
}, 100);
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.progress')
.directive('lxProgress', lxProgress);
function lxProgress()
{
return {
restrict: 'E',
templateUrl: 'progress.html',
scope:
{
lxColor: '@?',
lxDiameter: '@?',
lxType: '@',
lxValue: '@'
},
controller: LxProgressController,
controllerAs: 'lxProgress',
bindToController: true,
replace: true
};
}
function LxProgressController()
{
var lxProgress = this;
lxProgress.getCircularProgressValue = getCircularProgressValue;
lxProgress.getLinearProgressValue = getLinearProgressValue;
lxProgress.getProgressDiameter = getProgressDiameter;
init();
////////////
function getCircularProgressValue()
{
if (angular.isDefined(lxProgress.lxValue))
{
return {
'stroke-dasharray': lxProgress.lxValue * 1.26 + ',200'
};
}
}
function getLinearProgressValue()
{
if (angular.isDefined(lxProgress.lxValue))
{
return {
'transform': 'scale(' + lxProgress.lxValue / 100 + ', 1)'
};
}
}
function getProgressDiameter()
{
if (lxProgress.lxType === 'circular')
{
return {
'transform': 'scale(' + parseInt(lxProgress.lxDiameter) / 100 + ')'
};
}
return;
}
function init()
{
lxProgress.lxDiameter = angular.isDefined(lxProgress.lxDiameter) ? lxProgress.lxDiameter : 100;
lxProgress.lxColor = angular.isDefined(lxProgress.lxColor) ? lxProgress.lxColor : 'primary';
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.radio-button')
.directive('lxRadioGroup', lxRadioGroup)
.directive('lxRadioButton', lxRadioButton)
.directive('lxRadioButtonLabel', lxRadioButtonLabel)
.directive('lxRadioButtonHelp', lxRadioButtonHelp);
function lxRadioGroup()
{
return {
restrict: 'E',
templateUrl: 'radio-group.html',
transclude: true,
replace: true
};
}
function lxRadioButton()
{
return {
restrict: 'E',
templateUrl: 'radio-button.html',
scope:
{
lxColor: '@?',
name: '@',
ngChange: '&?',
ngDisabled: '=?',
ngModel: '=',
ngValue: '=?',
value: '@?'
},
controller: LxRadioButtonController,
controllerAs: 'lxRadioButton',
bindToController: true,
transclude: true,
replace: true
};
}
LxRadioButtonController.$inject = ['$scope', '$timeout', 'LxUtils'];
function LxRadioButtonController($scope, $timeout, LxUtils)
{
var lxRadioButton = this;
var radioButtonId;
var radioButtonHasChildren;
var timer;
lxRadioButton.getRadioButtonId = getRadioButtonId;
lxRadioButton.getRadioButtonHasChildren = getRadioButtonHasChildren;
lxRadioButton.setRadioButtonId = setRadioButtonId;
lxRadioButton.setRadioButtonHasChildren = setRadioButtonHasChildren;
lxRadioButton.triggerNgChange = triggerNgChange;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
init();
////////////
function getRadioButtonId()
{
return radioButtonId;
}
function getRadioButtonHasChildren()
{
return radioButtonHasChildren;
}
function init()
{
setRadioButtonId(LxUtils.generateUUID());
setRadioButtonHasChildren(false);
if (angular.isDefined(lxRadioButton.value) && angular.isUndefined(lxRadioButton.ngValue))
{
lxRadioButton.ngValue = lxRadioButton.value;
}
lxRadioButton.lxColor = angular.isUndefined(lxRadioButton.lxColor) ? 'accent' : lxRadioButton.lxColor;
}
function setRadioButtonId(_radioButtonId)
{
radioButtonId = _radioButtonId;
}
function setRadioButtonHasChildren(_radioButtonHasChildren)
{
radioButtonHasChildren = _radioButtonHasChildren;
}
function triggerNgChange()
{
timer = $timeout(lxRadioButton.ngChange);
}
}
function lxRadioButtonLabel()
{
return {
restrict: 'AE',
require: ['^lxRadioButton', '^lxRadioButtonLabel'],
templateUrl: 'radio-button-label.html',
link: link,
controller: LxRadioButtonLabelController,
controllerAs: 'lxRadioButtonLabel',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].setRadioButtonHasChildren(true);
ctrls[1].setRadioButtonId(ctrls[0].getRadioButtonId());
}
}
function LxRadioButtonLabelController()
{
var lxRadioButtonLabel = this;
var radioButtonId;
lxRadioButtonLabel.getRadioButtonId = getRadioButtonId;
lxRadioButtonLabel.setRadioButtonId = setRadioButtonId;
////////////
function getRadioButtonId()
{
return radioButtonId;
}
function setRadioButtonId(_radioButtonId)
{
radioButtonId = _radioButtonId;
}
}
function lxRadioButtonHelp()
{
return {
restrict: 'AE',
require: '^lxRadioButton',
templateUrl: 'radio-button-help.html',
transclude: true,
replace: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.ripple')
.directive('lxRipple', lxRipple);
lxRipple.$inject = ['$timeout'];
function lxRipple($timeout)
{
return {
restrict: 'A',
link: link,
};
function link(scope, element, attrs)
{
var timer;
element
.css(
{
position: 'relative',
overflow: 'hidden'
})
.on('mousedown', function(e)
{
var ripple;
if (element.find('.ripple').length === 0)
{
ripple = angular.element('<span/>',
{
class: 'ripple'
});
if (attrs.lxRipple)
{
ripple.addClass('bgc-' + attrs.lxRipple);
}
element.prepend(ripple);
}
else
{
ripple = element.find('.ripple');
}
ripple.removeClass('ripple--is-animated');
if (!ripple.height() && !ripple.width())
{
var diameter = Math.max(element.outerWidth(), element.outerHeight());
ripple.css(
{
height: diameter,
width: diameter
});
}
var x = e.pageX - element.offset().left - ripple.width() / 2;
var y = e.pageY - element.offset().top - ripple.height() / 2;
ripple.css(
{
top: y + 'px',
left: x + 'px'
}).addClass('ripple--is-animated');
timer = $timeout(function()
{
ripple.removeClass('ripple--is-animated');
}, 651);
});
scope.$on('$destroy', function()
{
$timeout.cancel(timer);
element.off();
});
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.search-filter')
.filter('lxSearchHighlight', lxSearchHighlight)
.directive('lxSearchFilter', lxSearchFilter);
lxSearchHighlight.$inject = ['$sce'];
function lxSearchHighlight($sce)
{
function escapeRegexp(queryToEscape)
{
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function (matchItem, query, icon)
{
var string = '';
if (icon)
{
string += '<i class="mdi mdi-' + icon + '"></i>';
}
string += query && matchItem ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
return $sce.trustAsHtml(string);
};
}
function lxSearchFilter()
{
return {
restrict: 'E',
templateUrl: 'search-filter.html',
scope:
{
autocomplete: '&?lxAutocomplete',
closed: '=?lxClosed',
color: '@?lxColor',
icon: '@?lxIcon',
onSelect: '=?lxOnSelect',
searchOnFocus: '=?lxSearchOnFocus',
theme: '@?lxTheme',
width: '@?lxWidth'
},
link: link,
controller: LxSearchFilterController,
controllerAs: 'lxSearchFilter',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl, transclude)
{
var input;
attrs.$observe('lxWidth', function(newWidth)
{
if (angular.isDefined(scope.lxSearchFilter.closed) && scope.lxSearchFilter.closed)
{
element.find('.search-filter__container').css('width', newWidth);
}
});
transclude(function()
{
input = element.find('input');
ctrl.setInput(input);
ctrl.setModel(input.data('$ngModelController'));
input.on('focus', ctrl.focusInput);
input.on('blur', ctrl.blurInput);
input.on('keydown', ctrl.keyEvent);
});
scope.$on('$destroy', function()
{
input.off();
});
}
}
LxSearchFilterController.$inject = ['$element', '$scope', 'LxDropdownService', 'LxNotificationService', 'LxUtils'];
function LxSearchFilterController($element, $scope, LxDropdownService, LxNotificationService, LxUtils)
{
var lxSearchFilter = this;
var debouncedAutocomplete;
var input;
var itemSelected = false;
lxSearchFilter.blurInput = blurInput;
lxSearchFilter.clearInput = clearInput;
lxSearchFilter.focusInput = focusInput;
lxSearchFilter.getClass = getClass;
lxSearchFilter.keyEvent = keyEvent;
lxSearchFilter.openInput = openInput;
lxSearchFilter.selectItem = selectItem;
lxSearchFilter.setInput = setInput;
lxSearchFilter.setModel = setModel;
lxSearchFilter.activeChoiceIndex = -1;
lxSearchFilter.color = angular.isDefined(lxSearchFilter.color) ? lxSearchFilter.color : 'black';
lxSearchFilter.dropdownId = LxUtils.generateUUID();
lxSearchFilter.theme = angular.isDefined(lxSearchFilter.theme) ? lxSearchFilter.theme : 'light';
////////////
function blurInput()
{
if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed && !input.val())
{
$element.velocity(
{
width: 40
},
{
duration: 400,
easing: 'easeOutQuint',
queue: false
});
}
if (!input.val())
{
lxSearchFilter.modelController.$setViewValue(undefined);
}
}
function clearInput()
{
lxSearchFilter.modelController.$setViewValue(undefined);
lxSearchFilter.modelController.$render();
// Temporarily disabling search on focus since we never want to trigger it when clearing the input.
var searchOnFocus = lxSearchFilter.searchOnFocus;
lxSearchFilter.searchOnFocus = false;
input.focus();
lxSearchFilter.searchOnFocus = searchOnFocus;
}
function focusInput()
{
if (!lxSearchFilter.searchOnFocus)
{
return;
}
updateAutocomplete(lxSearchFilter.modelController.$viewValue, true);
}
function getClass()
{
var searchFilterClass = [];
if (angular.isUndefined(lxSearchFilter.closed) || !lxSearchFilter.closed)
{
searchFilterClass.push('search-filter--opened-mode');
}
if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed)
{
searchFilterClass.push('search-filter--closed-mode');
}
if (input.val())
{
searchFilterClass.push('search-filter--has-clear-button');
}
if (angular.isDefined(lxSearchFilter.color))
{
searchFilterClass.push('search-filter--' + lxSearchFilter.color);
}
if (angular.isDefined(lxSearchFilter.theme))
{
searchFilterClass.push('search-filter--theme-' + lxSearchFilter.theme);
}
if (angular.isFunction(lxSearchFilter.autocomplete))
{
searchFilterClass.push('search-filter--autocomplete');
}
if (LxDropdownService.isOpen(lxSearchFilter.dropdownId))
{
searchFilterClass.push('search-filter--is-open');
}
return searchFilterClass;
}
function keyEvent(_event)
{
if (!angular.isFunction(lxSearchFilter.autocomplete))
{
return;
}
if (!LxDropdownService.isOpen(lxSearchFilter.dropdownId))
{
lxSearchFilter.activeChoiceIndex = -1;
}
switch (_event.keyCode) {
case 13:
keySelect();
if (lxSearchFilter.activeChoiceIndex > -1)
{
_event.preventDefault();
}
break;
case 38:
keyUp();
_event.preventDefault();
break;
case 40:
keyDown();
_event.preventDefault();
break;
}
$scope.$apply();
}
function keyDown()
{
if (lxSearchFilter.autocompleteList.length)
{
lxSearchFilter.activeChoiceIndex += 1;
if (lxSearchFilter.activeChoiceIndex >= lxSearchFilter.autocompleteList.length)
{
lxSearchFilter.activeChoiceIndex = 0;
}
}
}
function keySelect()
{
if (!lxSearchFilter.autocompleteList || lxSearchFilter.activeChoiceIndex === -1)
{
return;
}
selectItem(lxSearchFilter.autocompleteList[lxSearchFilter.activeChoiceIndex]);
}
function keyUp()
{
if (lxSearchFilter.autocompleteList.length)
{
lxSearchFilter.activeChoiceIndex -= 1;
if (lxSearchFilter.activeChoiceIndex < 0)
{
lxSearchFilter.activeChoiceIndex = lxSearchFilter.autocompleteList.length - 1;
}
}
}
function onAutocompleteSuccess(autocompleteList)
{
lxSearchFilter.autocompleteList = autocompleteList;
if (lxSearchFilter.autocompleteList.length)
{
LxDropdownService.open(lxSearchFilter.dropdownId, $element);
}
else
{
LxDropdownService.close(lxSearchFilter.dropdownId);
}
lxSearchFilter.isLoading = false;
}
function onAutocompleteError(error)
{
LxNotificationService.error(error);
lxSearchFilter.isLoading = false;
}
function openInput()
{
if (angular.isDefined(lxSearchFilter.closed) && lxSearchFilter.closed)
{
$element.velocity(
{
width: angular.isDefined(lxSearchFilter.width) ? parseInt(lxSearchFilter.width) : 240
},
{
duration: 400,
easing: 'easeOutQuint',
queue: false,
complete: function()
{
input.focus();
}
});
}
else
{
input.focus();
}
}
function selectItem(_item)
{
itemSelected = true;
LxDropdownService.close(lxSearchFilter.dropdownId);
lxSearchFilter.modelController.$setViewValue(_item);
lxSearchFilter.modelController.$render();
if (angular.isFunction(lxSearchFilter.onSelect))
{
lxSearchFilter.onSelect(_item);
}
}
function setInput(_input)
{
input = _input;
}
function setModel(_modelController)
{
lxSearchFilter.modelController = _modelController;
if (angular.isFunction(lxSearchFilter.autocomplete) && angular.isFunction(lxSearchFilter.autocomplete()))
{
debouncedAutocomplete = LxUtils.debounce(function()
{
lxSearchFilter.isLoading = true;
(lxSearchFilter.autocomplete()).apply(this, arguments);
}, 500);
lxSearchFilter.modelController.$parsers.push(updateAutocomplete);
}
}
function updateAutocomplete(_newValue, _immediate)
{
if ((_newValue || (angular.isUndefined(_newValue) && lxSearchFilter.searchOnFocus)) && !itemSelected)
{
if (_immediate)
{
lxSearchFilter.isLoading = true;
(lxSearchFilter.autocomplete())(_newValue, onAutocompleteSuccess, onAutocompleteError);
}
else
{
debouncedAutocomplete(_newValue, onAutocompleteSuccess, onAutocompleteError);
}
}
else
{
debouncedAutocomplete.clear();
LxDropdownService.close(lxSearchFilter.dropdownId);
}
itemSelected = false;
return _newValue;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.select')
.filter('filterChoices', filterChoices)
.directive('lxSelect', lxSelect)
.directive('lxSelectSelected', lxSelectSelected)
.directive('lxSelectChoices', lxSelectChoices);
filterChoices.$inject = ['$filter'];
function filterChoices($filter)
{
return function(choices, externalFilter, textFilter)
{
if (externalFilter)
{
return choices;
}
var toFilter = [];
if (!angular.isArray(choices))
{
if (angular.isObject(choices))
{
for (var idx in choices)
{
if (angular.isArray(choices[idx]))
{
toFilter = toFilter.concat(choices[idx]);
}
}
}
}
else
{
toFilter = choices;
}
return $filter('filter')(toFilter, textFilter);
};
}
function lxSelect()
{
return {
restrict: 'E',
templateUrl: 'select.html',
scope:
{
allowClear: '=?lxAllowClear',
allowNewValue: '=?lxAllowNewValue',
autocomplete: '=?lxAutocomplete',
newValueTransform: '=?lxNewValueTransform',
choices: '=?lxChoices',
choicesCustomStyle: '=?lxChoicesCustomStyle',
customStyle: '=?lxCustomStyle',
displayFilter: '=?lxDisplayFilter',
error: '=?lxError',
filter: '&?lxFilter',
fixedLabel: '=?lxFixedLabel',
helper: '=?lxHelper',
helperMessage: '@?lxHelperMessage',
label: '@?lxLabel',
loading: '=?lxLoading',
modelToSelection: '&?lxModelToSelection',
multiple: '=?lxMultiple',
ngChange: '&?',
ngDisabled: '=?',
ngModel: '=',
selectionToModel: '&?lxSelectionToModel',
theme: '@?lxTheme',
valid: '=?lxValid',
viewMode: '@?lxViewMode'
},
link: link,
controller: LxSelectController,
controllerAs: 'lxSelect',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs)
{
var backwardOneWay = ['customStyle'];
var backwardTwoWay = ['allowClear', 'choices', 'error', 'loading', 'multiple', 'valid'];
angular.forEach(backwardOneWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
attrs.$observe(attribute, function(newValue)
{
scope.lxSelect[attribute] = newValue;
});
}
});
angular.forEach(backwardTwoWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
scope.$watch(function()
{
return scope.$parent.$eval(attrs[attribute]);
}, function(newValue)
{
if (attribute === 'multiple' && angular.isUndefined(newValue))
{
scope.lxSelect[attribute] = true;
}
else
{
scope.lxSelect[attribute] = newValue;
}
});
}
});
attrs.$observe('placeholder', function(newValue)
{
scope.lxSelect.label = newValue;
});
attrs.$observe('change', function(newValue)
{
scope.lxSelect.ngChange = function(data)
{
return scope.$parent.$eval(newValue, data);
};
});
attrs.$observe('filter', function(newValue)
{
scope.lxSelect.filter = function(data)
{
return scope.$parent.$eval(newValue, data);
};
scope.lxSelect.displayFilter = true;
});
attrs.$observe('modelToSelection', function(newValue)
{
scope.lxSelect.modelToSelection = function(data)
{
return scope.$parent.$eval(newValue, data);
};
});
attrs.$observe('selectionToModel', function(newValue)
{
scope.lxSelect.selectionToModel = function(data)
{
return scope.$parent.$eval(newValue, data);
};
});
}
}
LxSelectController.$inject = ['$interpolate', '$element', '$filter', '$sce', 'LxDropdownService', 'LxUtils'];
function LxSelectController($interpolate, $element, $filter, $sce, LxDropdownService, LxUtils)
{
var lxSelect = this;
var choiceTemplate;
var selectedTemplate;
lxSelect.displayChoice = displayChoice;
lxSelect.displaySelected = displaySelected;
lxSelect.displaySubheader = displaySubheader;
lxSelect.getFilteredChoices = getFilteredChoices;
lxSelect.getSelectedModel = getSelectedModel;
lxSelect.isSelected = isSelected;
lxSelect.keyEvent = keyEvent;
lxSelect.registerChoiceTemplate = registerChoiceTemplate;
lxSelect.registerSelectedTemplate = registerSelectedTemplate;
lxSelect.select = select;
lxSelect.toggleChoice = toggleChoice;
lxSelect.unselect = unselect;
lxSelect.updateFilter = updateFilter;
lxSelect.helperDisplayable = helperDisplayable;
lxSelect.activeChoiceIndex = -1;
lxSelect.activeSelectedIndex = -1;
lxSelect.uuid = LxUtils.generateUUID();
lxSelect.filterModel = undefined;
lxSelect.ngModel = angular.isUndefined(lxSelect.ngModel) && lxSelect.multiple ? [] : lxSelect.ngModel;
lxSelect.unconvertedModel = lxSelect.multiple ? [] : undefined;
lxSelect.viewMode = angular.isUndefined(lxSelect.viewMode) ? 'field' : 'chips';
////////////
function arrayObjectIndexOf(arr, obj)
{
for (var i = 0; i < arr.length; i++)
{
if (angular.equals(arr[i], obj))
{
return i;
}
}
return -1;
}
function displayChoice(_choice)
{
var choiceScope = {
$choice: _choice
};
return $sce.trustAsHtml($interpolate(choiceTemplate)(choiceScope));
}
function displaySelected(_selected)
{
var selectedScope = {};
if (!angular.isArray(lxSelect.choices))
{
var found = false;
for (var header in lxSelect.choices)
{
if (found)
{
break;
}
if (lxSelect.choices.hasOwnProperty(header))
{
for (var idx = 0, len = lxSelect.choices[header].length; idx < len; idx++)
{
if (angular.equals(_selected, lxSelect.choices[header][idx]))
{
selectedScope.$selectedSubheader = header;
found = true;
break;
}
}
}
}
}
if (angular.isDefined(_selected))
{
selectedScope.$selected = _selected;
}
else
{
selectedScope.$selected = getSelectedModel();
}
return $sce.trustAsHtml($interpolate(selectedTemplate)(selectedScope));
}
function displaySubheader(_subheader)
{
return $sce.trustAsHtml(_subheader);
}
function getFilteredChoices()
{
return $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
}
function getSelectedModel()
{
if (angular.isDefined(lxSelect.modelToSelection) || angular.isDefined(lxSelect.selectionToModel))
{
return lxSelect.unconvertedModel;
}
else
{
return lxSelect.ngModel;
}
}
function isSelected(_choice)
{
if (lxSelect.multiple && angular.isDefined(getSelectedModel()))
{
return arrayObjectIndexOf(getSelectedModel(), _choice) !== -1;
}
else if (angular.isDefined(getSelectedModel()))
{
return angular.equals(getSelectedModel(), _choice);
}
}
function keyEvent(_event)
{
if (_event.keyCode !== 8)
{
lxSelect.activeSelectedIndex = -1;
}
if (!LxDropdownService.isOpen('dropdown-' + lxSelect.uuid))
{
lxSelect.activeChoiceIndex = -1;
}
switch (_event.keyCode) {
case 8:
keyRemove();
break;
case 13:
keySelect();
_event.preventDefault();
break;
case 38:
keyUp();
_event.preventDefault();
break;
case 40:
keyDown();
_event.preventDefault();
break;
}
}
function keyDown()
{
var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
if (filteredChoices.length)
{
lxSelect.activeChoiceIndex += 1;
if (lxSelect.activeChoiceIndex >= filteredChoices.length)
{
lxSelect.activeChoiceIndex = 0;
}
}
if (lxSelect.autocomplete)
{
LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid);
}
}
function keyRemove()
{
if (lxSelect.filterModel || !lxSelect.getSelectedModel().length)
{
return;
}
if (lxSelect.activeSelectedIndex === -1)
{
lxSelect.activeSelectedIndex = lxSelect.getSelectedModel().length - 1;
}
else
{
unselect(lxSelect.getSelectedModel()[lxSelect.activeSelectedIndex]);
}
}
function keySelect()
{
var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
if (filteredChoices.length && filteredChoices[lxSelect.activeChoiceIndex])
{
toggleChoice(filteredChoices[lxSelect.activeChoiceIndex]);
}
else if (lxSelect.filterModel && lxSelect.allowNewValue)
{
if (angular.isArray(getSelectedModel()))
{
var value = angular.isFunction(lxSelect.newValueTransform) ? lxSelect.newValueTransform(lxSelect.filterModel) : lxSelect.filterModel;
var identical = getSelectedModel().some(function (item) {
return angular.equals(item, value);
});
if (!identical)
{
getSelectedModel().push(value);
}
}
lxSelect.filterModel = undefined;
LxDropdownService.close('dropdown-' + lxSelect.uuid);
}
}
function keyUp()
{
var filteredChoices = $filter('filterChoices')(lxSelect.choices, lxSelect.filter, lxSelect.filterModel);
if (filteredChoices.length)
{
lxSelect.activeChoiceIndex -= 1;
if (lxSelect.activeChoiceIndex < 0)
{
lxSelect.activeChoiceIndex = filteredChoices.length - 1;
}
}
if (lxSelect.autocomplete)
{
LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid);
}
}
function registerChoiceTemplate(_choiceTemplate)
{
choiceTemplate = _choiceTemplate;
}
function registerSelectedTemplate(_selectedTemplate)
{
selectedTemplate = _selectedTemplate;
}
function select(_choice)
{
if (lxSelect.multiple && angular.isUndefined(lxSelect.ngModel))
{
lxSelect.ngModel = [];
}
if (angular.isDefined(lxSelect.selectionToModel))
{
lxSelect.selectionToModel(
{
data: _choice,
callback: function(resp)
{
if (lxSelect.multiple)
{
lxSelect.ngModel.push(resp);
}
else
{
lxSelect.ngModel = resp;
}
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
}
}
});
}
else
{
if (lxSelect.multiple)
{
lxSelect.ngModel.push(_choice);
}
else
{
lxSelect.ngModel = _choice;
}
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
}
}
}
function toggleChoice(_choice, _event)
{
if (lxSelect.multiple && !lxSelect.autocomplete)
{
_event.stopPropagation();
}
if (lxSelect.multiple && isSelected(_choice))
{
unselect(_choice);
}
else
{
select(_choice);
}
if (lxSelect.autocomplete)
{
lxSelect.activeChoiceIndex = -1;
lxSelect.filterModel = undefined;
LxDropdownService.close('dropdown-' + lxSelect.uuid);
}
}
function unselect(_choice)
{
if (angular.isDefined(lxSelect.selectionToModel))
{
lxSelect.selectionToModel(
{
data: _choice,
callback: function(resp)
{
removeElement(lxSelect.ngModel, resp);
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
lxSelect.activeSelectedIndex = -1;
}
}
});
removeElement(lxSelect.unconvertedModel, _choice);
}
else
{
removeElement(lxSelect.ngModel, _choice);
if (lxSelect.autocomplete)
{
$element.find('.lx-select-selected__filter').focus();
lxSelect.activeSelectedIndex = -1;
}
}
}
function updateFilter()
{
if (angular.isDefined(lxSelect.filter))
{
lxSelect.filter(
{
newValue: lxSelect.filterModel
});
}
if (lxSelect.autocomplete)
{
lxSelect.activeChoiceIndex = -1;
if (lxSelect.filterModel)
{
LxDropdownService.open('dropdown-' + lxSelect.uuid, '#lx-select-selected-wrapper-' + lxSelect.uuid);
}
else
{
LxDropdownService.close('dropdown-' + lxSelect.uuid);
}
}
}
function helperDisplayable() {
// If helper message is not defined, message is not displayed...
if (angular.isUndefined(lxSelect.helperMessage))
{
return false;
}
// If helper is defined return it's state.
if (angular.isDefined(lxSelect.helper))
{
return lxSelect.helper;
}
// Else check if there's choices.
var choices = lxSelect.getFilteredChoices();
if (angular.isArray(choices))
{
return !choices.length;
}
else if (angular.isObject(choices))
{
return !Object.keys(choices).length;
}
return true;
}
function removeElement(model, element)
{
var index = -1;
for (var i = 0, len = model.length; i < len; i++)
{
if (angular.equals(element, model[i]))
{
index = i;
break;
}
}
if (index > -1)
{
model.splice(index, 1);
}
}
}
function lxSelectSelected()
{
return {
restrict: 'E',
require: ['lxSelectSelected', '^lxSelect'],
templateUrl: 'select-selected.html',
link: link,
controller: LxSelectSelectedController,
controllerAs: 'lxSelectSelected',
bindToController: true,
transclude: true
};
function link(scope, element, attrs, ctrls, transclude)
{
ctrls[0].setParentController(ctrls[1]);
transclude(scope, function(clone)
{
var template = '';
for (var i = 0; i < clone.length; i++)
{
template += clone[i].data || clone[i].outerHTML || '';
}
ctrls[1].registerSelectedTemplate(template);
});
}
}
function LxSelectSelectedController()
{
var lxSelectSelected = this;
lxSelectSelected.clearModel = clearModel;
lxSelectSelected.setParentController = setParentController;
lxSelectSelected.removeSelected = removeSelected;
////////////
function clearModel(_event)
{
_event.stopPropagation();
lxSelectSelected.parentCtrl.ngModel = undefined;
lxSelectSelected.parentCtrl.unconvertedModel = undefined;
}
function setParentController(_parentCtrl)
{
lxSelectSelected.parentCtrl = _parentCtrl;
}
function removeSelected(_selected, _event)
{
_event.stopPropagation();
lxSelectSelected.parentCtrl.unselect(_selected);
}
}
function lxSelectChoices()
{
return {
restrict: 'E',
require: ['lxSelectChoices', '^lxSelect'],
templateUrl: 'select-choices.html',
link: link,
controller: LxSelectChoicesController,
controllerAs: 'lxSelectChoices',
bindToController: true,
transclude: true
};
function link(scope, element, attrs, ctrls, transclude)
{
ctrls[0].setParentController(ctrls[1]);
transclude(scope, function(clone)
{
var template = '';
for (var i = 0; i < clone.length; i++)
{
template += clone[i].data || clone[i].outerHTML || '';
}
ctrls[1].registerChoiceTemplate(template);
});
}
}
LxSelectChoicesController.$inject = ['$scope', '$timeout'];
function LxSelectChoicesController($scope, $timeout)
{
var lxSelectChoices = this;
var timer;
lxSelectChoices.isArray = isArray;
lxSelectChoices.setParentController = setParentController;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
////////////
function isArray()
{
return angular.isArray(lxSelectChoices.parentCtrl.choices);
}
function setParentController(_parentCtrl)
{
lxSelectChoices.parentCtrl = _parentCtrl;
$scope.$watch(function()
{
return lxSelectChoices.parentCtrl.ngModel;
}, function(newModel, oldModel)
{
timer = $timeout(function()
{
if (newModel !== oldModel && angular.isDefined(lxSelectChoices.parentCtrl.ngChange))
{
lxSelectChoices.parentCtrl.ngChange(
{
newValue: newModel,
oldValue: oldModel
});
}
if (angular.isDefined(lxSelectChoices.parentCtrl.modelToSelection) || angular.isDefined(lxSelectChoices.parentCtrl.selectionToModel))
{
toSelection();
}
});
}, true);
}
function toSelection()
{
if (lxSelectChoices.parentCtrl.multiple)
{
lxSelectChoices.parentCtrl.unconvertedModel = [];
angular.forEach(lxSelectChoices.parentCtrl.ngModel, function(item)
{
lxSelectChoices.parentCtrl.modelToSelection(
{
data: item,
callback: function(resp)
{
lxSelectChoices.parentCtrl.unconvertedModel.push(resp);
}
});
});
}
else
{
lxSelectChoices.parentCtrl.modelToSelection(
{
data: lxSelectChoices.parentCtrl.ngModel,
callback: function(resp)
{
lxSelectChoices.parentCtrl.unconvertedModel = resp;
}
});
}
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.stepper')
.directive('lxStepper', lxStepper)
.directive('lxStep', lxStep)
.directive('lxStepNav', lxStepNav);
/* Stepper */
function lxStepper()
{
return {
restrict: 'E',
templateUrl: 'stepper.html',
scope: {
cancel: '&?lxCancel',
complete: '&lxComplete',
isLinear: '=?lxIsLinear',
labels: '=?lxLabels',
layout: '@?lxLayout'
},
controller: LxStepperController,
controllerAs: 'lxStepper',
bindToController: true,
transclude: true
};
}
function LxStepperController()
{
var lxStepper = this;
var _classes = [];
var _defaultValues = {
isLinear: true,
labels: {
'back': 'Back',
'cancel': 'Cancel',
'continue': 'Continue',
'optional': 'Optional'
},
layout: 'horizontal'
};
lxStepper.addStep = addStep;
lxStepper.getClasses = getClasses;
lxStepper.goToStep = goToStep;
lxStepper.isComplete = isComplete;
lxStepper.updateStep = updateStep;
lxStepper.activeIndex = 0;
lxStepper.isLinear = angular.isDefined(lxStepper.isLinear) ? lxStepper.isLinear : _defaultValues.isLinear;
lxStepper.labels = angular.isDefined(lxStepper.labels) ? lxStepper.labels : _defaultValues.labels;
lxStepper.layout = angular.isDefined(lxStepper.layout) ? lxStepper.layout : _defaultValues.layout;
lxStepper.steps = [];
////////////
function addStep(step)
{
lxStepper.steps.push(step);
}
function getClasses()
{
_classes.length = 0;
_classes.push('lx-stepper--layout-' + lxStepper.layout);
if (lxStepper.isLinear)
{
_classes.push('lx-stepper--is-linear');
}
if (lxStepper.steps[lxStepper.activeIndex].feedback)
{
_classes.push('lx-stepper--step-has-feedback');
}
if (lxStepper.steps[lxStepper.activeIndex].isLoading)
{
_classes.push('lx-stepper--step-is-loading');
}
return _classes;
}
function goToStep(index, bypass)
{
// Check if the the wanted step previous steps are optionals. If so, check if the step before the last optional step is valid to allow going to the wanted step from the nav (only if linear stepper).
var stepBeforeLastOptionalStep;
if (!bypass && lxStepper.isLinear)
{
for (var i = index - 1; i >= 0; i--)
{
if (angular.isDefined(lxStepper.steps[i]) && !lxStepper.steps[i].isOptional)
{
stepBeforeLastOptionalStep = lxStepper.steps[i];
break;
}
}
if (angular.isDefined(stepBeforeLastOptionalStep) && stepBeforeLastOptionalStep.isValid === true)
{
bypass = true;
}
}
// Check if the wanted step previous step is not valid to disallow going to the wanted step from the nav (only if linear stepper).
if (!bypass && lxStepper.isLinear && angular.isDefined(lxStepper.steps[index - 1]) && (angular.isUndefined(lxStepper.steps[index - 1].isValid) || lxStepper.steps[index - 1].isValid === false))
{
return;
}
if (index < lxStepper.steps.length)
{
lxStepper.activeIndex = parseInt(index);
}
}
function isComplete()
{
var countMandatory = 0;
var countValid = 0;
for (var i = 0, len = lxStepper.steps.length; i < len; i++)
{
if (!lxStepper.steps[i].isOptional)
{
countMandatory++;
if (lxStepper.steps[i].isValid === true) {
countValid++;
}
}
}
if (countValid === countMandatory)
{
lxStepper.complete();
return true;
}
}
function updateStep(step)
{
for (var i = 0, len = lxStepper.steps.length; i < len; i++)
{
if (lxStepper.steps[i].uuid === step.uuid)
{
lxStepper.steps[i].index = step.index;
lxStepper.steps[i].label = step.label;
return;
}
}
}
}
/* Step */
function lxStep()
{
return {
restrict: 'E',
require: ['lxStep', '^lxStepper'],
templateUrl: 'step.html',
scope: {
feedback: '@?lxFeedback',
isEditable: '=?lxIsEditable',
isOptional: '=?lxIsOptional',
label: '@lxLabel',
submit: '&?lxSubmit',
validate: '&?lxValidate'
},
link: link,
controller: LxStepController,
controllerAs: 'lxStep',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].init(ctrls[1], element.index());
attrs.$observe('lxFeedback', function(feedback)
{
ctrls[0].setFeedback(feedback);
});
attrs.$observe('lxLabel', function(label)
{
ctrls[0].setLabel(label);
});
attrs.$observe('lxIsEditable', function(isEditable)
{
ctrls[0].setIsEditable(isEditable);
});
attrs.$observe('lxIsOptional', function(isOptional)
{
ctrls[0].setIsOptional(isOptional);
});
}
}
LxStepController.$inject = ['$q', 'LxNotificationService', 'LxUtils'];
function LxStepController($q, LxNotificationService, LxUtils)
{
var lxStep = this;
var _classes = [];
var _nextStepIndex;
lxStep.getClasses = getClasses;
lxStep.init = init;
lxStep.previousStep = previousStep;
lxStep.setFeedback = setFeedback;
lxStep.setLabel = setLabel;
lxStep.setIsEditable = setIsEditable;
lxStep.setIsOptional = setIsOptional;
lxStep.submitStep = submitStep;
lxStep.step = {
errorMessage: undefined,
feedback: undefined,
index: undefined,
isEditable: false,
isLoading: false,
isOptional: false,
isValid: undefined,
label: undefined,
uuid: LxUtils.generateUUID()
};
////////////
function getClasses()
{
_classes.length = 0;
if (lxStep.step.index === lxStep.parent.activeIndex)
{
_classes.push('lx-step--is-active');
}
return _classes;
}
function init(parent, index)
{
lxStep.parent = parent;
lxStep.step.index = index;
lxStep.parent.addStep(lxStep.step);
}
function previousStep()
{
if (lxStep.step.index > 0)
{
lxStep.parent.goToStep(lxStep.step.index - 1);
}
}
function setFeedback(feedback)
{
lxStep.step.feedback = feedback;
updateParentStep();
}
function setLabel(label)
{
lxStep.step.label = label;
updateParentStep();
}
function setIsEditable(isEditable)
{
lxStep.step.isEditable = isEditable;
updateParentStep();
}
function setIsOptional(isOptional)
{
lxStep.step.isOptional = isOptional;
updateParentStep();
}
function submitStep()
{
if (lxStep.step.isValid === true && !lxStep.step.isEditable)
{
lxStep.parent.goToStep(_nextStepIndex, true);
return;
}
var validateFunction = lxStep.validate;
var validity = true;
if (angular.isFunction(validateFunction))
{
validity = validateFunction();
}
if (validity === true)
{
lxStep.step.isLoading = true;
updateParentStep();
var submitFunction = lxStep.submit;
if (!angular.isFunction(submitFunction))
{
submitFunction = function()
{
return $q(function(resolve)
{
resolve();
});
};
}
var promise = submitFunction();
promise.then(function(nextStepIndex)
{
lxStep.step.isValid = true;
updateParentStep();
var isComplete = lxStep.parent.isComplete();
if (!isComplete)
{
_nextStepIndex = angular.isDefined(nextStepIndex) && nextStepIndex > lxStep.parent.activeIndex && (!lxStep.parent.isLinear || (lxStep.parent.isLinear && lxStep.parent.steps[nextStepIndex - 1].isOptional)) ? nextStepIndex : lxStep.step.index + 1;
lxStep.parent.goToStep(_nextStepIndex, true);
}
}).catch(function(error)
{
LxNotificationService.error(error);
}).finally(function()
{
lxStep.step.isLoading = false;
updateParentStep();
});
}
else
{
lxStep.step.isValid = false;
lxStep.step.errorMessage = validity;
updateParentStep();
}
}
function updateParentStep()
{
lxStep.parent.updateStep(lxStep.step);
}
}
/* Step nav */
function lxStepNav()
{
return {
restrict: 'E',
require: ['lxStepNav', '^lxStepper'],
templateUrl: 'step-nav.html',
scope: {
activeIndex: '@lxActiveIndex',
step: '=lxStep'
},
link: link,
controller: LxStepNavController,
controllerAs: 'lxStepNav',
bindToController: true,
replace: true,
transclude: false
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].init(ctrls[1]);
}
}
function LxStepNavController()
{
var lxStepNav = this;
var _classes = [];
lxStepNav.getClasses = getClasses;
lxStepNav.init = init;
////////////
function getClasses()
{
_classes.length = 0;
if (parseInt(lxStepNav.step.index) === parseInt(lxStepNav.activeIndex))
{
_classes.push('lx-step-nav--is-active');
}
if (lxStepNav.step.isValid === true)
{
_classes.push('lx-step-nav--is-valid');
}
else if (lxStepNav.step.isValid === false)
{
_classes.push('lx-step-nav--has-error');
}
if (lxStepNav.step.isEditable)
{
_classes.push('lx-step-nav--is-editable');
}
if (lxStepNav.step.isOptional)
{
_classes.push('lx-step-nav--is-optional');
}
return _classes;
}
function init(parent, index)
{
lxStepNav.parent = parent;
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.switch')
.directive('lxSwitch', lxSwitch)
.directive('lxSwitchLabel', lxSwitchLabel)
.directive('lxSwitchHelp', lxSwitchHelp);
function lxSwitch()
{
return {
restrict: 'E',
templateUrl: 'switch.html',
scope:
{
ngModel: '=',
name: '@?',
ngTrueValue: '@?',
ngFalseValue: '@?',
ngChange: '&?',
ngDisabled: '=?',
lxColor: '@?',
lxPosition: '@?'
},
controller: LxSwitchController,
controllerAs: 'lxSwitch',
bindToController: true,
transclude: true,
replace: true
};
}
LxSwitchController.$inject = ['$scope', '$timeout', 'LxUtils'];
function LxSwitchController($scope, $timeout, LxUtils)
{
var lxSwitch = this;
var switchId;
var switchHasChildren;
var timer;
lxSwitch.getSwitchId = getSwitchId;
lxSwitch.getSwitchHasChildren = getSwitchHasChildren;
lxSwitch.setSwitchId = setSwitchId;
lxSwitch.setSwitchHasChildren = setSwitchHasChildren;
lxSwitch.triggerNgChange = triggerNgChange;
$scope.$on('$destroy', function()
{
$timeout.cancel(timer);
});
init();
////////////
function getSwitchId()
{
return switchId;
}
function getSwitchHasChildren()
{
return switchHasChildren;
}
function init()
{
setSwitchId(LxUtils.generateUUID());
setSwitchHasChildren(false);
lxSwitch.ngTrueValue = angular.isUndefined(lxSwitch.ngTrueValue) ? true : lxSwitch.ngTrueValue;
lxSwitch.ngFalseValue = angular.isUndefined(lxSwitch.ngFalseValue) ? false : lxSwitch.ngFalseValue;
lxSwitch.lxColor = angular.isUndefined(lxSwitch.lxColor) ? 'accent' : lxSwitch.lxColor;
lxSwitch.lxPosition = angular.isUndefined(lxSwitch.lxPosition) ? 'left' : lxSwitch.lxPosition;
}
function setSwitchId(_switchId)
{
switchId = _switchId;
}
function setSwitchHasChildren(_switchHasChildren)
{
switchHasChildren = _switchHasChildren;
}
function triggerNgChange()
{
timer = $timeout(lxSwitch.ngChange);
}
}
function lxSwitchLabel()
{
return {
restrict: 'AE',
require: ['^lxSwitch', '^lxSwitchLabel'],
templateUrl: 'switch-label.html',
link: link,
controller: LxSwitchLabelController,
controllerAs: 'lxSwitchLabel',
bindToController: true,
transclude: true,
replace: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].setSwitchHasChildren(true);
ctrls[1].setSwitchId(ctrls[0].getSwitchId());
}
}
function LxSwitchLabelController()
{
var lxSwitchLabel = this;
var switchId;
lxSwitchLabel.getSwitchId = getSwitchId;
lxSwitchLabel.setSwitchId = setSwitchId;
////////////
function getSwitchId()
{
return switchId;
}
function setSwitchId(_switchId)
{
switchId = _switchId;
}
}
function lxSwitchHelp()
{
return {
restrict: 'AE',
require: '^lxSwitch',
templateUrl: 'switch-help.html',
transclude: true,
replace: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.tabs')
.directive('lxTabs', lxTabs)
.directive('lxTab', lxTab)
.directive('lxTabsPanes', lxTabsPanes)
.directive('lxTabPane', lxTabPane);
function lxTabs()
{
return {
restrict: 'E',
templateUrl: 'tabs.html',
scope:
{
layout: '@?lxLayout',
theme: '@?lxTheme',
color: '@?lxColor',
indicator: '@?lxIndicator',
activeTab: '=?lxActiveTab',
panesId: '@?lxPanesId',
links: '=?lxLinks'
},
controller: LxTabsController,
controllerAs: 'lxTabs',
bindToController: true,
replace: true,
transclude: true
};
}
LxTabsController.$inject = ['LxUtils', '$element', '$scope', '$timeout'];
function LxTabsController(LxUtils, $element, $scope, $timeout)
{
var lxTabs = this;
var tabsLength;
var timer1;
var timer2;
var timer3;
var timer4;
lxTabs.removeTab = removeTab;
lxTabs.setActiveTab = setActiveTab;
lxTabs.setViewMode = setViewMode;
lxTabs.tabIsActive = tabIsActive;
lxTabs.updateTabs = updateTabs;
lxTabs.activeTab = angular.isDefined(lxTabs.activeTab) ? lxTabs.activeTab : 0;
lxTabs.color = angular.isDefined(lxTabs.color) ? lxTabs.color : 'primary';
lxTabs.indicator = angular.isDefined(lxTabs.indicator) ? lxTabs.indicator : 'accent';
lxTabs.layout = angular.isDefined(lxTabs.layout) ? lxTabs.layout : 'full';
lxTabs.tabs = [];
lxTabs.theme = angular.isDefined(lxTabs.theme) ? lxTabs.theme : 'light';
lxTabs.viewMode = angular.isDefined(lxTabs.links) ? 'separate' : 'gather';
$scope.$watch(function()
{
return lxTabs.activeTab;
}, function(_newActiveTab, _oldActiveTab)
{
timer1 = $timeout(function()
{
setIndicatorPosition(_oldActiveTab);
if (lxTabs.viewMode === 'separate')
{
angular.element('#' + lxTabs.panesId).find('.tabs__pane').hide();
angular.element('#' + lxTabs.panesId).find('.tabs__pane').eq(lxTabs.activeTab).show();
}
});
});
$scope.$watch(function()
{
return lxTabs.links;
}, function(_newLinks)
{
lxTabs.viewMode = angular.isDefined(_newLinks) ? 'separate' : 'gather';
angular.forEach(_newLinks, function(link, index)
{
var tab = {
uuid: (angular.isUndefined(link.uuid) || link.uuid.length === 0) ? LxUtils.generateUUID() : link.uuid,
index: index,
label: link.label,
icon: link.icon,
disabled: link.disabled
};
updateTabs(tab);
});
});
timer2 = $timeout(function()
{
tabsLength = lxTabs.tabs.length;
});
$scope.$on('$destroy', function()
{
$timeout.cancel(timer1);
$timeout.cancel(timer2);
$timeout.cancel(timer3);
$timeout.cancel(timer4);
});
////////////
function removeTab(_tab)
{
lxTabs.tabs.splice(_tab.index, 1);
angular.forEach(lxTabs.tabs, function(tab, index)
{
tab.index = index;
});
if (lxTabs.activeTab === 0)
{
timer3 = $timeout(function()
{
setIndicatorPosition();
});
}
else
{
setActiveTab(lxTabs.tabs[0]);
}
}
function setActiveTab(_tab)
{
if (!_tab.disabled)
{
lxTabs.activeTab = _tab.index;
}
}
function setIndicatorPosition(_previousActiveTab)
{
var direction = lxTabs.activeTab > _previousActiveTab ? 'right' : 'left';
var indicator = $element.find('.tabs__indicator');
var activeTab = $element.find('.tabs__link').eq(lxTabs.activeTab);
var indicatorLeft = activeTab.position().left;
var indicatorRight = $element.outerWidth() - (indicatorLeft + activeTab.outerWidth());
if (angular.isUndefined(_previousActiveTab))
{
indicator.css(
{
left: indicatorLeft,
right: indicatorRight
});
}
else
{
var animationProperties = {
duration: 200,
easing: 'easeOutQuint'
};
if (direction === 'left')
{
indicator.velocity(
{
left: indicatorLeft
}, animationProperties);
indicator.velocity(
{
right: indicatorRight
}, animationProperties);
}
else
{
indicator.velocity(
{
right: indicatorRight
}, animationProperties);
indicator.velocity(
{
left: indicatorLeft
}, animationProperties);
}
}
}
function setViewMode(_viewMode)
{
lxTabs.viewMode = _viewMode;
}
function tabIsActive(_index)
{
return lxTabs.activeTab === _index;
}
function updateTabs(_tab)
{
var newTab = true;
angular.forEach(lxTabs.tabs, function(tab)
{
if (tab.index === _tab.index)
{
newTab = false;
tab.uuid = _tab.uuid;
tab.icon = _tab.icon;
tab.label = _tab.label;
}
});
if (newTab)
{
lxTabs.tabs.push(_tab);
if (angular.isDefined(tabsLength))
{
timer4 = $timeout(function()
{
setIndicatorPosition();
});
}
}
}
}
function lxTab()
{
return {
restrict: 'E',
require: ['lxTab', '^lxTabs'],
templateUrl: 'tab.html',
scope:
{
ngDisabled: '=?'
},
link: link,
controller: LxTabController,
controllerAs: 'lxTab',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrls)
{
ctrls[0].init(ctrls[1], element.index());
attrs.$observe('lxLabel', function(_newLabel)
{
ctrls[0].setLabel(_newLabel);
});
attrs.$observe('lxIcon', function(_newIcon)
{
ctrls[0].setIcon(_newIcon);
});
}
}
LxTabController.$inject = ['$scope', 'LxUtils'];
function LxTabController($scope, LxUtils)
{
var lxTab = this;
var parentCtrl;
var tab = {
uuid: LxUtils.generateUUID(),
index: undefined,
label: undefined,
icon: undefined,
disabled: false
};
lxTab.init = init;
lxTab.setIcon = setIcon;
lxTab.setLabel = setLabel;
lxTab.tabIsActive = tabIsActive;
$scope.$watch(function()
{
return lxTab.ngDisabled;
}, function(_isDisabled)
{
if (_isDisabled)
{
tab.disabled = true;
}
else
{
tab.disabled = false;
}
parentCtrl.updateTabs(tab);
});
$scope.$on('$destroy', function()
{
parentCtrl.removeTab(tab);
});
////////////
function init(_parentCtrl, _index)
{
parentCtrl = _parentCtrl;
tab.index = _index;
parentCtrl.updateTabs(tab);
}
function setIcon(_icon)
{
tab.icon = _icon;
parentCtrl.updateTabs(tab);
}
function setLabel(_label)
{
tab.label = _label;
parentCtrl.updateTabs(tab);
}
function tabIsActive()
{
return parentCtrl.tabIsActive(tab.index);
}
}
function lxTabsPanes()
{
return {
restrict: 'E',
templateUrl: 'tabs-panes.html',
scope: true,
replace: true,
transclude: true
};
}
function lxTabPane()
{
return {
restrict: 'E',
templateUrl: 'tab-pane.html',
scope: true,
replace: true,
transclude: true
};
}
})();
(function()
{
'use strict';
angular
.module('lumx.text-field')
.directive('lxTextField', lxTextField);
lxTextField.$inject = ['$timeout'];
function lxTextField($timeout)
{
return {
restrict: 'E',
templateUrl: 'text-field.html',
scope:
{
allowClear: '=?lxAllowClear',
error: '=?lxError',
fixedLabel: '=?lxFixedLabel',
focus: '=?lxFocus',
icon: '@?lxIcon',
label: '@lxLabel',
ngDisabled: '=?',
theme: '@?lxTheme',
valid: '=?lxValid'
},
link: link,
controller: LxTextFieldController,
controllerAs: 'lxTextField',
bindToController: true,
replace: true,
transclude: true
};
function link(scope, element, attrs, ctrl, transclude)
{
var backwardOneWay = ['icon', 'label', 'theme'];
var backwardTwoWay = ['error', 'fixedLabel', 'valid'];
var input;
var timer;
angular.forEach(backwardOneWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
attrs.$observe(attribute, function(newValue)
{
scope.lxTextField[attribute] = newValue;
});
}
});
angular.forEach(backwardTwoWay, function(attribute)
{
if (angular.isDefined(attrs[attribute]))
{
scope.$watch(function()
{
return scope.$parent.$eval(attrs[attribute]);
}, function(newValue)
{
scope.lxTextField[attribute] = newValue;
});
}
});
transclude(function()
{
input = element.find('textarea');
if (input[0])
{
input.on('cut paste drop keydown', function()
{
timer = $timeout(ctrl.updateTextareaHeight);
});
}
else
{
input = element.find('input');
}
input.addClass('text-field__input');
ctrl.setInput(input);
ctrl.setModel(input.data('$ngModelController'));
input.on('focus', function()
{
var phase = scope.$root.$$phase;
if (phase === '$apply' || phase === '$digest')
{
ctrl.focusInput();
}
else
{
scope.$apply(ctrl.focusInput);
}
});
input.on('blur', ctrl.blurInput);
});
scope.$on('$destroy', function()
{
$timeout.cancel(timer);
input.off();
});
}
}
LxTextFieldController.$inject = ['$scope', '$timeout'];
function LxTextFieldController($scope, $timeout)
{
var lxTextField = this;
var input;
var modelController;
var timer1;
var timer2;
lxTextField.blurInput = blurInput;
lxTextField.clearInput = clearInput;
lxTextField.focusInput = focusInput;
lxTextField.hasValue = hasValue;
lxTextField.setInput = setInput;
lxTextField.setModel = setModel;
lxTextField.updateTextareaHeight = updateTextareaHeight;
$scope.$watch(function()
{
return modelController.$viewValue;
}, function(newValue, oldValue)
{
if (angular.isDefined(newValue) && newValue)
{
lxTextField.isActive = true;
}
else
{
lxTextField.isActive = false;
}
});
$scope.$watch(function()
{
return lxTextField.focus;
}, function(newValue, oldValue)
{
if (angular.isDefined(newValue) && newValue)
{
$timeout(function()
{
input.focus();
// Reset the value so we can re-focus the field later on if we want to.
lxTextField.focus = false;
});
}
});
$scope.$on('$destroy', function()
{
$timeout.cancel(timer1);
$timeout.cancel(timer2);
});
////////////
function blurInput()
{
if (!hasValue())
{
$scope.$apply(function()
{
lxTextField.isActive = false;
});
}
$scope.$apply(function()
{
lxTextField.isFocus = false;
});
}
function clearInput(_event)
{
_event.stopPropagation();
modelController.$setViewValue(undefined);
modelController.$render();
}
function focusInput()
{
lxTextField.isActive = true;
lxTextField.isFocus = true;
}
function hasValue()
{
return angular.isDefined(input.val()) && input.val().length > 0;
}
function init()
{
lxTextField.isActive = hasValue();
lxTextField.focus = angular.isDefined(lxTextField.focus) ? lxTextField.focus : false;
lxTextField.isFocus = lxTextField.focus;
}
function setInput(_input)
{
input = _input;
timer1 = $timeout(init);
if (input.selector === 'textarea')
{
timer2 = $timeout(updateTextareaHeight);
}
}
function setModel(_modelControler)
{
modelController = _modelControler;
}
function updateTextareaHeight()
{
var tmpTextArea = angular.element('<textarea class="text-field__input" style="width: ' + input.width() + 'px;">' + input.val() + '</textarea>');
tmpTextArea.appendTo('body');
input.css(
{
height: tmpTextArea[0].scrollHeight + 'px'
});
tmpTextArea.remove();
}
}
})();
(function()
{
'use strict';
angular
.module('lumx.tooltip')
.directive('lxTooltip', lxTooltip);
function lxTooltip()
{
return {
restrict: 'A',
scope:
{
tooltip: '@lxTooltip',
position: '@?lxTooltipPosition'
},
link: link,
controller: LxTooltipController,
controllerAs: 'lxTooltip',
bindToController: true
};
function link(scope, element, attrs, ctrl)
{
if (angular.isDefined(attrs.lxTooltip))
{
attrs.$observe('lxTooltip', function(newValue)
{
ctrl.updateTooltipText(newValue);
});
}
if (angular.isDefined(attrs.lxTooltipPosition))
{
attrs.$observe('lxTooltipPosition', function(newValue)
{
scope.lxTooltip.position = newValue;
});
}
element.on('mouseenter', ctrl.showTooltip);
element.on('mouseleave', ctrl.hideTooltip);
scope.$on('$destroy', function()
{
element.off();
});
}
}
LxTooltipController.$inject = ['$element', '$scope', '$timeout', 'LxDepthService'];
function LxTooltipController($element, $scope, $timeout, LxDepthService)
{
var lxTooltip = this;
var timer1;
var timer2;
var tooltip;
var tooltipBackground;
var tooltipLabel;
lxTooltip.hideTooltip = hideTooltip;
lxTooltip.showTooltip = showTooltip;
lxTooltip.updateTooltipText = updateTooltipText;
lxTooltip.position = angular.isDefined(lxTooltip.position) ? lxTooltip.position : 'top';
$scope.$on('$destroy', function()
{
if (angular.isDefined(tooltip))
{
tooltip.remove();
tooltip = undefined;
}
$timeout.cancel(timer1);
$timeout.cancel(timer2);
});
////////////
function hideTooltip()
{
if (angular.isDefined(tooltip))
{
tooltip.removeClass('tooltip--is-active');
timer1 = $timeout(function()
{
if (angular.isDefined(tooltip))
{
tooltip.remove();
tooltip = undefined;
}
}, 200);
}
}
function setTooltipPosition()
{
var width = $element.outerWidth(),
height = $element.outerHeight(),
top = $element.offset().top,
left = $element.offset().left;
tooltip
.append(tooltipBackground)
.append(tooltipLabel)
.appendTo('body');
if (lxTooltip.position === 'top')
{
tooltip.css(
{
left: left - (tooltip.outerWidth() / 2) + (width / 2),
top: top - tooltip.outerHeight()
});
}
else if (lxTooltip.position === 'bottom')
{
tooltip.css(
{
left: left - (tooltip.outerWidth() / 2) + (width / 2),
top: top + height
});
}
else if (lxTooltip.position === 'left')
{
tooltip.css(
{
left: left - tooltip.outerWidth(),
top: top + (height / 2) - (tooltip.outerHeight() / 2)
});
}
else if (lxTooltip.position === 'right')
{
tooltip.css(
{
left: left + width,
top: top + (height / 2) - (tooltip.outerHeight() / 2)
});
}
}
function showTooltip()
{
if (angular.isUndefined(tooltip))
{
LxDepthService.register();
tooltip = angular.element('<div/>',
{
class: 'tooltip tooltip--' + lxTooltip.position
});
tooltipBackground = angular.element('<div/>',
{
class: 'tooltip__background'
});
tooltipLabel = angular.element('<span/>',
{
class: 'tooltip__label',
text: lxTooltip.tooltip
});
setTooltipPosition();
tooltip
.append(tooltipBackground)
.append(tooltipLabel)
.css('z-index', LxDepthService.getDepth())
.appendTo('body');
timer2 = $timeout(function()
{
tooltip.addClass('tooltip--is-active');
});
}
}
function updateTooltipText(_newValue)
{
if (angular.isDefined(tooltipLabel))
{
tooltipLabel.text(_newValue);
}
}
}
})();
angular.module("lumx.dropdown").run(['$templateCache', function(a) { a.put('dropdown.html', '<div class="dropdown"\n' +
' ng-class="{ \'dropdown--has-toggle\': lxDropdown.hasToggle,\n' +
' \'dropdown--is-open\': lxDropdown.isOpen }"\n' +
' ng-transclude></div>\n' +
'');
a.put('dropdown-toggle.html', '<div class="dropdown-toggle" ng-transclude></div>\n' +
'');
a.put('dropdown-menu.html', '<div class="dropdown-menu">\n' +
' <div class="dropdown-menu__content" ng-transclude ng-if="lxDropdownMenu.parentCtrl.isOpen"></div>\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.file-input").run(['$templateCache', function(a) { a.put('file-input.html', '<div class="input-file">\n' +
' <span class="input-file__label">{{ lxFileInput.label }}</span>\n' +
' <span class="input-file__filename">{{ lxFileInput.fileName }}</span>\n' +
' <input type="file" class="input-file__input">\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.text-field").run(['$templateCache', function(a) { a.put('text-field.html', '<div class="text-field"\n' +
' ng-class="{ \'text-field--error\': lxTextField.error,\n' +
' \'text-field--fixed-label\': lxTextField.fixedLabel,\n' +
' \'text-field--has-icon\': lxTextField.icon,\n' +
' \'text-field--has-value\': lxTextField.hasValue(),\n' +
' \'text-field--is-active\': lxTextField.isActive,\n' +
' \'text-field--is-disabled\': lxTextField.ngDisabled,\n' +
' \'text-field--is-focus\': lxTextField.isFocus,\n' +
' \'text-field--theme-light\': !lxTextField.theme || lxTextField.theme === \'light\',\n' +
' \'text-field--theme-dark\': lxTextField.theme === \'dark\',\n' +
' \'text-field--valid\': lxTextField.valid }">\n' +
' <div class="text-field__icon" ng-if="lxTextField.icon">\n' +
' <i class="mdi mdi-{{ lxTextField.icon }}"></i>\n' +
' </div>\n' +
'\n' +
' <label class="text-field__label">\n' +
' {{ lxTextField.label }}\n' +
' </label>\n' +
'\n' +
' <div ng-transclude></div>\n' +
'\n' +
' <span class="text-field__clear" ng-click="lxTextField.clearInput($event)" ng-if="lxTextField.allowClear">\n' +
' <i class="mdi mdi-close-circle"></i>\n' +
' </span>\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.search-filter").run(['$templateCache', function(a) { a.put('search-filter.html', '<div class="search-filter" ng-class="lxSearchFilter.getClass()">\n' +
' <div class="search-filter__container">\n' +
' <div class="search-filter__button">\n' +
' <lx-button type="submit" lx-size="l" lx-color="{{ lxSearchFilter.color }}" lx-type="icon" ng-click="lxSearchFilter.openInput()">\n' +
' <i class="mdi mdi-magnify"></i>\n' +
' </lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="search-filter__input" ng-transclude></div>\n' +
'\n' +
' <div class="search-filter__clear">\n' +
' <lx-button type="button" lx-size="l" lx-color="{{ lxSearchFilter.color }}" lx-type="icon" ng-click="lxSearchFilter.clearInput()">\n' +
' <i class="mdi mdi-close"></i>\n' +
' </lx-button>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <div class="search-filter__loader" ng-if="lxSearchFilter.isLoading">\n' +
' <lx-progress lx-type="linear"></lx-progress>\n' +
' </div>\n' +
'\n' +
' <lx-dropdown id="{{ lxSearchFilter.dropdownId }}" lx-effect="none" lx-width="100%" ng-if="lxSearchFilter.autocomplete">\n' +
' <lx-dropdown-menu class="search-filter__autocomplete-list">\n' +
' <ul>\n' +
' <li ng-repeat="item in lxSearchFilter.autocompleteList track by $index">\n' +
' <a class="search-filter__autocomplete-item"\n' +
' ng-class="{ \'search-filter__autocomplete-item--is-active\': lxSearchFilter.activeChoiceIndex === $index }"\n' +
' ng-click="lxSearchFilter.selectItem(item)"\n' +
' ng-bind-html="item | lxSearchHighlight:lxSearchFilter.modelController.$viewValue:lxSearchFilter.icon"></a>\n' +
' </li>\n' +
' </ul>\n' +
' </lx-dropdown-menu>\n' +
' </lx-dropdown>\n' +
'</div>');
}]);
angular.module("lumx.select").run(['$templateCache', function(a) { a.put('select.html', '<div class="lx-select"\n' +
' ng-class="{ \'lx-select--error\': lxSelect.error,\n' +
' \'lx-select--fixed-label\': lxSelect.fixedLabel && lxSelect.viewMode === \'field\',\n' +
' \'lx-select--is-active\': (!lxSelect.multiple && lxSelect.getSelectedModel()) || (lxSelect.multiple && lxSelect.getSelectedModel().length),\n' +
' \'lx-select--is-disabled\': lxSelect.ngDisabled,\n' +
' \'lx-select--is-multiple\': lxSelect.multiple,\n' +
' \'lx-select--is-unique\': !lxSelect.multiple,\n' +
' \'lx-select--theme-light\': !lxSelect.theme || lxSelect.theme === \'light\',\n' +
' \'lx-select--theme-dark\': lxSelect.theme === \'dark\',\n' +
' \'lx-select--valid\': lxSelect.valid,\n' +
' \'lx-select--custom-style\': lxSelect.customStyle,\n' +
' \'lx-select--default-style\': !lxSelect.customStyle,\n' +
' \'lx-select--view-mode-field\': !lxSelect.multiple || (lxSelect.multiple && lxSelect.viewMode === \'field\'),\n' +
' \'lx-select--view-mode-chips\': lxSelect.multiple && lxSelect.viewMode === \'chips\',\n' +
' \'lx-select--autocomplete\': lxSelect.autocomplete }">\n' +
' <span class="lx-select-label" ng-if="!lxSelect.autocomplete">\n' +
' {{ ::lxSelect.label }}\n' +
' </span>\n' +
'\n' +
' <lx-dropdown id="dropdown-{{ lxSelect.uuid }}" lx-width="100%" lx-effect="{{ lxSelect.autocomplete ? \'none\' : \'expand\' }}">\n' +
' <ng-transclude></ng-transclude>\n' +
' </lx-dropdown>\n' +
'</div>\n' +
'');
a.put('select-selected.html', '<div>\n' +
' <lx-dropdown-toggle ng-if="::!lxSelectSelected.parentCtrl.autocomplete">\n' +
' <ng-include src="\'select-selected-content.html\'"></ng-include>\n' +
' </lx-dropdown-toggle>\n' +
'\n' +
' <ng-include src="\'select-selected-content.html\'" ng-if="::lxSelectSelected.parentCtrl.autocomplete"></ng-include>\n' +
'</div>\n' +
'');
a.put('select-selected-content.html', '<div class="lx-select-selected-wrapper" id="lx-select-selected-wrapper-{{ lxSelectSelected.parentCtrl.uuid }}">\n' +
' <div class="lx-select-selected" ng-if="!lxSelectSelected.parentCtrl.multiple && lxSelectSelected.parentCtrl.getSelectedModel()">\n' +
' <span class="lx-select-selected__value"\n' +
' ng-bind-html="lxSelectSelected.parentCtrl.displaySelected()"></span>\n' +
'\n' +
' <a class="lx-select-selected__clear"\n' +
' ng-click="lxSelectSelected.clearModel($event)"\n' +
' ng-if="::lxSelectSelected.parentCtrl.allowClear">\n' +
' <i class="mdi mdi-close-circle"></i>\n' +
' </a>\n' +
' </div>\n' +
'\n' +
' <div class="lx-select-selected" ng-if="lxSelectSelected.parentCtrl.multiple">\n' +
' <span class="lx-select-selected__tag"\n' +
' ng-class="{ \'lx-select-selected__tag--is-active\': lxSelectSelected.parentCtrl.activeSelectedIndex === $index }"\n' +
' ng-click="lxSelectSelected.removeSelected(selected, $event)"\n' +
' ng-repeat="selected in lxSelectSelected.parentCtrl.getSelectedModel()"\n' +
' ng-bind-html="lxSelectSelected.parentCtrl.displaySelected(selected)"></span>\n' +
'\n' +
' <input type="text"\n' +
' placeholder="{{ ::lxSelectSelected.parentCtrl.label }}"\n' +
' class="lx-select-selected__filter"\n' +
' ng-model="lxSelectSelected.parentCtrl.filterModel"\n' +
' ng-change="lxSelectSelected.parentCtrl.updateFilter()"\n' +
' ng-keydown="lxSelectSelected.parentCtrl.keyEvent($event)"\n' +
' ng-if="::lxSelectSelected.parentCtrl.autocomplete && !lxSelectSelected.parentCtrl.ngDisabled">\n' +
' </div>\n' +
'</div>');
a.put('select-choices.html', '<lx-dropdown-menu class="lx-select-choices"\n' +
' ng-class="{ \'lx-select-choices--custom-style\': lxSelectChoices.parentCtrl.choicesCustomStyle,\n' +
' \'lx-select-choices--default-style\': !lxSelectChoices.parentCtrl.choicesCustomStyle,\n' +
' \'lx-select-choices--is-multiple\': lxSelectChoices.parentCtrl.multiple,\n' +
' \'lx-select-choices--is-unique\': !lxSelectChoices.parentCtrl.multiple, }">\n' +
' <ul>\n' +
' <li class="lx-select-choices__filter" ng-if="::lxSelectChoices.parentCtrl.displayFilter && !lxSelectChoices.parentCtrl.autocomplete">\n' +
' <lx-search-filter lx-dropdown-filter>\n' +
' <input type="text" ng-model="lxSelectChoices.parentCtrl.filterModel" ng-change="lxSelectChoices.parentCtrl.updateFilter()">\n' +
' </lx-search-filter>\n' +
' </li>\n' +
' \n' +
' <div ng-if="::lxSelectChoices.isArray()">\n' +
' <li class="lx-select-choices__choice"\n' +
' ng-class="{ \'lx-select-choices__choice--is-selected\': lxSelectChoices.parentCtrl.isSelected(choice),\n' +
' \'lx-select-choices__choice--is-focus\': lxSelectChoices.parentCtrl.activeChoiceIndex === $index }"\n' +
' ng-repeat="choice in lxSelectChoices.parentCtrl.choices | filterChoices:lxSelectChoices.parentCtrl.filter:lxSelectChoices.parentCtrl.filterModel"\n' +
' ng-bind-html="::lxSelectChoices.parentCtrl.displayChoice(choice)"\n' +
' ng-click="lxSelectChoices.parentCtrl.toggleChoice(choice, $event)"></li>\n' +
' </div>\n' +
'\n' +
' <div ng-if="::!lxSelectChoices.isArray()">\n' +
' <li class="lx-select-choices__subheader"\n' +
' ng-repeat-start="(subheader, children) in lxSelectChoices.parentCtrl.choices"\n' +
' ng-bind-html="::lxSelectChoices.parentCtrl.displaySubheader(subheader)"></li>\n' +
'\n' +
' <li class="lx-select-choices__choice"\n' +
' ng-class="{ \'lx-select-choices__choice--is-selected\': lxSelectChoices.parentCtrl.isSelected(choice),\n' +
' \'lx-select-choices__choice--is-focus\': lxSelectChoices.parentCtrl.activeChoiceIndex === $index }"\n' +
' ng-repeat-end\n' +
' ng-repeat="choice in children | filterChoices:lxSelectChoices.parentCtrl.filter:lxSelectChoices.parentCtrl.filterModel"\n' +
' ng-bind-html="::lxSelectChoices.parentCtrl.displayChoice(choice)"\n' +
' ng-click="lxSelectChoices.parentCtrl.toggleChoice(choice, $event)"></li>\n' +
' </div>\n' +
'\n' +
' <li class="lx-select-choices__subheader" ng-if="lxSelectChoices.parentCtrl.helperDisplayable()">\n' +
' {{ lxSelectChoices.parentCtrl.helperMessage }}\n' +
' </li>\n' +
'\n' +
' <li class="lx-select-choices__loader" ng-if="lxSelectChoices.parentCtrl.loading">\n' +
' <lx-progress lx-type="circular" lx-color="primary" lx-diameter="20"></lx-progress>\n' +
' </li>\n' +
' </ul>\n' +
'</lx-dropdown-menu>\n' +
'');
}]);
angular.module("lumx.tabs").run(['$templateCache', function(a) { a.put('tabs.html', '<div class="tabs tabs--layout-{{ lxTabs.layout }} tabs--theme-{{ lxTabs.theme }} tabs--color-{{ lxTabs.color }} tabs--indicator-{{ lxTabs.indicator }}">\n' +
' <div class="tabs__links">\n' +
' <a class="tabs__link"\n' +
' ng-class="{ \'tabs__link--is-active\': lxTabs.tabIsActive(tab.index),\n' +
' \'tabs__link--is-disabled\': tab.disabled }"\n' +
' ng-repeat="tab in lxTabs.tabs"\n' +
' ng-click="lxTabs.setActiveTab(tab)"\n' +
' lx-ripple>\n' +
' <i class="mdi mdi-{{ tab.icon }}" ng-if="tab.icon"></i>\n' +
' <span ng-if="tab.label">{{ tab.label }}</span>\n' +
' </a>\n' +
' </div>\n' +
' \n' +
' <div class="tabs__panes" ng-if="lxTabs.viewMode === \'gather\'" ng-transclude></div>\n' +
' <div class="tabs__indicator"></div>\n' +
'</div>\n' +
'');
a.put('tabs-panes.html', '<div class="tabs">\n' +
' <div class="tabs__panes" ng-transclude></div>\n' +
'</div>');
a.put('tab.html', '<div class="tabs__pane" ng-class="{ \'tabs__pane--is-disabled\': lxTab.ngDisabled }">\n' +
' <div ng-if="lxTab.tabIsActive()" ng-transclude></div>\n' +
'</div>\n' +
'');
a.put('tab-pane.html', '<div class="tabs__pane" ng-transclude></div>\n' +
'');
}]);
angular.module("lumx.date-picker").run(['$templateCache', function(a) { a.put('date-picker.html', '<div class="lx-date">\n' +
' <!-- Date picker input -->\n' +
' <div class="lx-date-input" ng-click="lxDatePicker.openDatePicker()" ng-if="lxDatePicker.hasInput">\n' +
' <ng-transclude></ng-transclude>\n' +
' </div>\n' +
' \n' +
' <!-- Date picker -->\n' +
' <div class="lx-date-picker lx-date-picker--{{ lxDatePicker.color }}">\n' +
' <div ng-if="lxDatePicker.isOpen">\n' +
' <!-- Date picker: header -->\n' +
' <div class="lx-date-picker__header">\n' +
' <a class="lx-date-picker__current-year"\n' +
' ng-class="{ \'lx-date-picker__current-year--is-active\': lxDatePicker.yearSelection }"\n' +
' ng-click="lxDatePicker.displayYearSelection()">\n' +
' {{ lxDatePicker.moment(lxDatePicker.ngModel).format(\'YYYY\') }}\n' +
' </a>\n' +
'\n' +
' <a class="lx-date-picker__current-date"\n' +
' ng-class="{ \'lx-date-picker__current-date--is-active\': !lxDatePicker.yearSelection }"\n' +
' ng-click="lxDatePicker.hideYearSelection()">\n' +
' {{ lxDatePicker.getDateFormatted() }}\n' +
' </a>\n' +
' </div>\n' +
' \n' +
' <!-- Date picker: content -->\n' +
' <div class="lx-date-picker__content">\n' +
' <!-- Calendar -->\n' +
' <div class="lx-date-picker__calendar" ng-if="!lxDatePicker.yearSelection">\n' +
' <div class="lx-date-picker__nav">\n' +
' <lx-button lx-size="l" lx-color="black" lx-type="icon" ng-click="lxDatePicker.previousMonth()">\n' +
' <i class="mdi mdi-chevron-left"></i>\n' +
' </lx-button>\n' +
'\n' +
' <span>{{ lxDatePicker.ngModelMoment.format(\'MMMM YYYY\') }}</span>\n' +
' \n' +
' <lx-button lx-size="l" lx-color="black" lx-type="icon" ng-click="lxDatePicker.nextMonth()">\n' +
' <i class="mdi mdi-chevron-right"></i>\n' +
' </lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="lx-date-picker__days-of-week">\n' +
' <span ng-repeat="day in lxDatePicker.daysOfWeek">{{ day }}</span>\n' +
' </div>\n' +
'\n' +
' <div class="lx-date-picker__days">\n' +
' <span class="lx-date-picker__day lx-date-picker__day--is-empty"\n' +
' ng-repeat="x in lxDatePicker.emptyFirstDays"> </span>\n' +
'\n' +
' <div class="lx-date-picker__day"\n' +
' ng-class="{ \'lx-date-picker__day--is-selected\': day.selected,\n' +
' \'lx-date-picker__day--is-today\': day.today && !day.selected,\n' +
' \'lx-date-picker__day--is-disabled\': day.disabled }"\n' +
' ng-repeat="day in lxDatePicker.days">\n' +
' <a ng-click="lxDatePicker.select(day)">{{ day ? day.format(\'D\') : \'\' }}</a>\n' +
' </div>\n' +
'\n' +
' <span class="lx-date-picker__day lx-date-picker__day--is-empty"\n' +
' ng-repeat="x in lxDatePicker.emptyLastDays"> </span>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <!-- Year selection -->\n' +
' <div class="lx-date-picker__year-selector" ng-if="lxDatePicker.yearSelection">\n' +
' <a class="lx-date-picker__year"\n' +
' ng-class="{ \'lx-date-picker__year--is-active\': year == lxDatePicker.moment(lxDatePicker.ngModel).format(\'YYYY\') }"\n' +
' ng-repeat="year in lxDatePicker.years"\n' +
' ng-click="lxDatePicker.selectYear(year)"\n' +
' ng-if="lxDatePicker.yearSelection">\n' +
' {{ year }}\n' +
' </a>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <!-- Actions -->\n' +
' <div class="lx-date-picker__actions">\n' +
' <lx-button lx-color="{{ lxDatePicker.color }}" lx-type="flat" ng-click="lxDatePicker.closeDatePicker()">\n' +
' Ok\n' +
' </lx-button>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
}]);
angular.module("lumx.progress").run(['$templateCache', function(a) { a.put('progress.html', '<div class="progress-container progress-container--{{ lxProgress.lxType }} progress-container--{{ lxProgress.lxColor }}"\n' +
' ng-class="{ \'progress-container--determinate\': lxProgress.lxValue,\n' +
' \'progress-container--indeterminate\': !lxProgress.lxValue }">\n' +
' <div class="progress-circular"\n' +
' ng-if="lxProgress.lxType === \'circular\'"\n' +
' ng-style="lxProgress.getProgressDiameter()">\n' +
' <svg class="progress-circular__svg">\n' +
' <circle class="progress-circular__path" cx="50" cy="50" r="20" fill="none" stroke-width="4" stroke-miterlimit="10" ng-style="lxProgress.getCircularProgressValue()">\n' +
' </svg>\n' +
' </div>\n' +
'\n' +
' <div class="progress-linear" ng-if="lxProgress.lxType === \'linear\'">\n' +
' <div class="progress-linear__background"></div>\n' +
' <div class="progress-linear__bar progress-linear__bar--first" ng-style="lxProgress.getLinearProgressValue()"></div>\n' +
' <div class="progress-linear__bar progress-linear__bar--second"></div>\n' +
' </div>\n' +
'</div>\n' +
'');
}]);
angular.module("lumx.button").run(['$templateCache', function(a) { a.put('link.html', '<a ng-transclude lx-ripple></a>\n' +
'');
a.put('button.html', '<button ng-transclude lx-ripple></button>\n' +
'');
}]);
angular.module("lumx.checkbox").run(['$templateCache', function(a) { a.put('checkbox.html', '<div class="checkbox checkbox--{{ lxCheckbox.lxColor }}"\n' +
' ng-class="{ \'checkbox--theme-light\': !lxCheckbox.theme || lxCheckbox.theme === \'light\',\n' +
' \'checkbox--theme-dark\': lxCheckbox.theme === \'dark\' }" >\n' +
' <input id="{{ lxCheckbox.getCheckboxId() }}"\n' +
' type="checkbox"\n' +
' class="checkbox__input"\n' +
' name="{{ lxCheckbox.name }}"\n' +
' ng-model="lxCheckbox.ngModel"\n' +
' ng-true-value="{{ lxCheckbox.ngTrueValue }}"\n' +
' ng-false-value="{{ lxCheckbox.ngFalseValue }}"\n' +
' ng-change="lxCheckbox.triggerNgChange()"\n' +
' ng-disabled="lxCheckbox.ngDisabled">\n' +
'\n' +
' <label for="{{ lxCheckbox.getCheckboxId() }}" class="checkbox__label" ng-transclude ng-if="!lxCheckbox.getCheckboxHasChildren()"></label>\n' +
' <ng-transclude-replace ng-if="lxCheckbox.getCheckboxHasChildren()"></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('checkbox-label.html', '<label for="{{ lxCheckboxLabel.getCheckboxId() }}" class="checkbox__label" ng-transclude></label>\n' +
'');
a.put('checkbox-help.html', '<span class="checkbox__help" ng-transclude></span>\n' +
'');
}]);
angular.module("lumx.radio-button").run(['$templateCache', function(a) { a.put('radio-group.html', '<div class="radio-group" ng-transclude></div>\n' +
'');
a.put('radio-button.html', '<div class="radio-button radio-button--{{ lxRadioButton.lxColor }}">\n' +
' <input id="{{ lxRadioButton.getRadioButtonId() }}"\n' +
' type="radio"\n' +
' class="radio-button__input"\n' +
' name="{{ lxRadioButton.name }}"\n' +
' ng-model="lxRadioButton.ngModel"\n' +
' ng-value="lxRadioButton.ngValue"\n' +
' ng-change="lxRadioButton.triggerNgChange()"\n' +
' ng-disabled="lxRadioButton.ngDisabled">\n' +
'\n' +
' <label for="{{ lxRadioButton.getRadioButtonId() }}" class="radio-button__label" ng-transclude ng-if="!lxRadioButton.getRadioButtonHasChildren()"></label>\n' +
' <ng-transclude-replace ng-if="lxRadioButton.getRadioButtonHasChildren()"></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('radio-button-label.html', '<label for="{{ lxRadioButtonLabel.getRadioButtonId() }}" class="radio-button__label" ng-transclude></label>\n' +
'');
a.put('radio-button-help.html', '<span class="radio-button__help" ng-transclude></span>\n' +
'');
}]);
angular.module("lumx.stepper").run(['$templateCache', function(a) { a.put('stepper.html', '<div class="lx-stepper" ng-class="lxStepper.getClasses()">\n' +
' <div class="lx-stepper__header" ng-if="lxStepper.layout === \'horizontal\'">\n' +
' <div class="lx-stepper__nav">\n' +
' <lx-step-nav lx-active-index="{{ lxStepper.activeIndex }}" lx-step="step" ng-repeat="step in lxStepper.steps"></lx-step-nav>\n' +
' </div>\n' +
'\n' +
' <div class="lx-stepper__feedback" ng-if="lxStepper.steps[lxStepper.activeIndex].feedback">\n' +
' <span>{{ lxStepper.steps[lxStepper.activeIndex].feedback }}</span>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <div class="lx-stepper__steps" ng-transclude></div>\n' +
'</div>');
a.put('step.html', '<div class="lx-step" ng-class="lxStep.getClasses()">\n' +
' <div class="lx-step__nav" ng-if="lxStep.parent.layout === \'vertical\'">\n' +
' <lx-step-nav lx-active-index="{{ lxStep.parent.activeIndex }}" lx-step="lxStep.step"></lx-step-nav>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__wrapper" ng-if="lxStep.parent.activeIndex === lxStep.step.index">\n' +
' <div class="lx-step__content">\n' +
' <ng-transclude></ng-transclude>\n' +
'\n' +
' <div class="lx-step__progress" ng-if="lxStep.step.isLoading">\n' +
' <lx-progress lx-type="circular"></lx-progress>\n' +
' </div>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__actions" ng-if="lxStep.parent.activeIndex === lxStep.step.index">\n' +
' <div class="lx-step__action lx-step__action--continue">\n' +
' <lx-button ng-click="lxStep.submitStep()" ng-disabled="lxStep.isLoading">{{ lxStep.parent.labels.continue }}</lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__action lx-step__action--cancel" ng-if="lxStep.parent.cancel">\n' +
' <lx-button lx-color="black" lx-type="flat" ng-click="lxStep.parent.cancel()" ng-disabled="lxStep.isLoading">{{ lxStep.parent.labels.cancel }}</lx-button>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step__action lx-step__action--back" ng-if="lxStep.parent.isLinear">\n' +
' <lx-button lx-color="black" lx-type="flat" ng-click="lxStep.previousStep()" ng-disabled="lxStep.isLoading || lxStep.step.index === 0">{{ lxStep.parent.labels.back }}</lx-button>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
a.put('step-nav.html', '<div class="lx-step-nav" ng-click="lxStepNav.parent.goToStep(lxStepNav.step.index)" ng-class="lxStepNav.getClasses()" lx-ripple>\n' +
' <div class="lx-step-nav__indicator lx-step-nav__indicator--index" ng-if="lxStepNav.step.isValid === undefined">\n' +
' <span>{{ lxStepNav.step.index + 1 }}</span>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__indicator lx-step-nav__indicator--icon" ng-if="lxStepNav.step.isValid === true">\n' +
' <lx-icon lx-id="check" ng-if="!lxStepNav.step.isEditable"></lx-icon>\n' +
' <lx-icon lx-id="pencil" ng-if="lxStepNav.step.isEditable"></lx-icon>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__indicator lx-step-nav__indicator--error" ng-if="lxStepNav.step.isValid === false">\n' +
' <lx-icon lx-id="alert"></lx-icon>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__wrapper">\n' +
' <div class="lx-step-nav__label">\n' +
' <span>{{ lxStepNav.step.label }}</span>\n' +
' </div>\n' +
'\n' +
' <div class="lx-step-nav__state">\n' +
' <span ng-if="(lxStepNav.step.isValid === undefined || lxStepNav.step.isValid === true) && lxStepNav.step.isOptional">{{ lxStepNav.parent.labels.optional }}</span>\n' +
' <span ng-if="lxStepNav.step.isValid === false">{{ lxStepNav.step.errorMessage }}</span>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
}]);
angular.module("lumx.switch").run(['$templateCache', function(a) { a.put('switch.html', '<div class="switch switch--{{ lxSwitch.lxColor }} switch--{{ lxSwitch.lxPosition }}">\n' +
' <input id="{{ lxSwitch.getSwitchId() }}"\n' +
' type="checkbox"\n' +
' class="switch__input"\n' +
' name="{{ lxSwitch.name }}"\n' +
' ng-model="lxSwitch.ngModel"\n' +
' ng-true-value="{{ lxSwitch.ngTrueValue }}"\n' +
' ng-false-value="{{ lxSwitch.ngFalseValue }}"\n' +
' ng-change="lxSwitch.triggerNgChange()"\n' +
' ng-disabled="lxSwitch.ngDisabled">\n' +
'\n' +
' <label for="{{ lxSwitch.getSwitchId() }}" class="switch__label" ng-transclude ng-if="!lxSwitch.getSwitchHasChildren()"></label>\n' +
' <ng-transclude-replace ng-if="lxSwitch.getSwitchHasChildren()"></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('switch-label.html', '<label for="{{ lxSwitchLabel.getSwitchId() }}" class="switch__label" ng-transclude></label>\n' +
'');
a.put('switch-help.html', '<span class="switch__help" ng-transclude></span>\n' +
'');
}]);
angular.module("lumx.fab").run(['$templateCache', function(a) { a.put('fab.html', '<div class="fab">\n' +
' <ng-transclude-replace></ng-transclude-replace>\n' +
'</div>\n' +
'');
a.put('fab-trigger.html', '<div class="fab__primary" ng-transclude></div>\n' +
'');
a.put('fab-actions.html', '<div class="fab__actions fab__actions--{{ parentCtrl.lxDirection }}" ng-transclude></div>\n' +
'');
}]);
angular.module("lumx.icon").run(['$templateCache', function(a) { a.put('icon.html', '<i class="icon mdi" ng-class="lxIcon.getClass()"></i>');
}]);
angular.module("lumx.data-table").run(['$templateCache', function(a) { a.put('data-table.html', '<div class="data-table-container">\n' +
' <table class="data-table"\n' +
' ng-class="{ \'data-table--no-border\': !lxDataTable.border,\n' +
' \'data-table--thumbnail\': lxDataTable.thumbnail }">\n' +
' <thead>\n' +
' <tr ng-class="{ \'data-table__selectable-row\': lxDataTable.selectable,\n' +
' \'data-table__selectable-row--is-selected\': lxDataTable.selectable && lxDataTable.allRowsSelected }">\n' +
' <th ng-if="lxDataTable.thumbnail"></th>\n' +
' <th ng-click="lxDataTable.toggleAllSelected()"\n' +
' ng-if="lxDataTable.selectable"></th>\n' +
' <th ng-class=" { \'data-table__sortable-cell\': th.sortable,\n' +
' \'data-table__sortable-cell--asc\': th.sortable && th.sort === \'asc\',\n' +
' \'data-table__sortable-cell--desc\': th.sortable && th.sort === \'desc\' }"\n' +
' ng-click="lxDataTable.sort(th)"\n' +
' ng-repeat="th in lxDataTable.thead track by $index"\n' +
' ng-if="!lxDataTable.thumbnail || (lxDataTable.thumbnail && $index != 0)">\n' +
' <lx-icon lx-id="{{ th.icon }}" ng-if="th.icon"></lx-icon>\n' +
' <span>{{ th.label }}</span>\n' +
' </th>\n' +
' </tr>\n' +
' </thead>\n' +
'\n' +
' <tbody>\n' +
' <tr ng-class="{ \'data-table__selectable-row\': lxDataTable.selectable,\n' +
' \'data-table__selectable-row--is-disabled\': lxDataTable.selectable && tr.lxDataTableDisabled,\n' +
' \'data-table__selectable-row--is-selected\': lxDataTable.selectable && tr.lxDataTableSelected }"\n' +
' ng-repeat="tr in lxDataTable.tbody"\n' +
' ng-click="lxDataTable.toggle(tr)">\n' +
' <td ng-if="lxDataTable.thumbnail">\n' +
' <div ng-if="lxDataTable.thead[0].format" ng-bind-html="lxDataTable.$sce.trustAsHtml(lxDataTable.thead[0].format(tr))"></div>\n' +
' </td>\n' +
' <td ng-if="lxDataTable.selectable"></td>\n' +
' <td ng-repeat="th in lxDataTable.thead track by $index"\n' +
' ng-if="!lxDataTable.thumbnail || (lxDataTable.thumbnail && $index != 0)">\n' +
' <span ng-if="!th.format">{{ tr[th.name] }}</span>\n' +
' <div ng-if="th.format" ng-bind-html="lxDataTable.$sce.trustAsHtml(th.format(tr))"></div>\n' +
' </td>\n' +
' </tr>\n' +
' </tbody>\n' +
' </table>\n' +
'</div>');
}]); | tholu/cdnjs | ajax/libs/lumx/1.5.14/lumx.js | JavaScript | mit | 203,404 |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
if (ENABLE_AREA_LAYOUTS == false) {
die(t('Area layouts have been disabled.'));
}
global $c;
$form = Loader::helper('form');
//Loader::model('layout');
if( intval($_REQUEST['lpID']) ){
$layoutPreset = LayoutPreset::getByID($_REQUEST['lpID']);
if(is_object($layoutPreset)){
$layout = $layoutPreset->getLayoutObject();
}
}elseif(intval($_REQUEST['layoutID'])){
$layout = Layout::getById( intval($_REQUEST['layoutID']) );
}else $layout = new Layout( array('type'=>'table','rows'=>1,'columns'=>3 ) );
if(!$layout ){
echo t('Error: Layout not found');
}else{
$layoutPresets=LayoutPreset::getList();
if(intval($layout->lpID))
$layoutPreset = LayoutPreset::getById($layout->lpID);
?>
<?php if (!$_REQUEST['refresh']) { ?>
<div id="ccm-layout-edit-wrapper">
<?php } ?>
<style type="text/css">
#ccmLayoutConfigOptions { margin-top:12px; }
#ccmLayoutConfigOptions table td { padding-bottom:4px; vertical-align:top; padding-bottom:12px; padding-right:12px; }
#ccmLayoutConfigOptions table td.padBottom { }
</style>
<form method="post" class="ccm-ui" id="ccmAreaLayoutForm" action="<?php echo $action?>" style="width:96%; margin:auto;">
<input id="ccmAreaLayoutForm_layoutID" name="layoutID" type="hidden" value="<?php echo intval( $layout->layoutID ) ?>" />
<input id="ccmAreaLayoutForm_arHandle" name="arHandle" type="hidden" value="<?php echo htmlentities( $a->getAreaHandle(), ENT_COMPAT, APP_CHARSET) ?>" />
<?php if (count($layoutPresets) > 0) { ?>
<h2><?php echo t('Saved Presets')?></h2>
<input type="hidden" id="ccm-layout-refresh-action" value="<?php echo $refreshAction?>" />
<select id="ccmLayoutPresentIdSelector" name="lpID">
<option value="0"><?php echo t('** Custom (No Preset)') ?></option>
<?php foreach($layoutPresets as $availablePreset){ ?>
<option value="<?php echo $availablePreset->getLayoutPresetID() ?>" <?php echo ($availablePreset->getLayoutPresetID()==intval($layout->lpID))?'selected':''?>><?php echo $availablePreset->getLayoutPresetName() ?></option>
<?php } ?>
</select>
<a href="javascript:void(0)" id="ccm-layout-delete-preset" style="display: none" onclick="ccmLayoutEdit.deletePreset()"><img src="<?php echo ASSETS_URL_IMAGES?>/icons/delete_small.png" style="vertical-align: middle" width="16" height="16" border="0" /></a>
<br/><br/>
<?php } ?>
<div id="ccmLayoutConfigOptions">
<table>
<tr>
<td><?php echo t('Columns')?>:</td>
<td class="val">
<input name="layout_columns" type="text" value="<?php echo intval($layout->columns) ?>" size=2 />
</td>
</tr>
<tr>
<td class="padBottom"><?php echo t('Rows')?>:</td>
<td class="val padBottom">
<input name="layout_rows" type="text" value="<?php echo intval($layout->rows) ?>" size=2 />
</td>
</tr>
<tr>
<td class="padBottom"><?php echo t('Spacing')?>:</td>
<td class="val padBottom">
<input name="spacing" type="text" value="<?php echo intval($layout->spacing) ?>" size=2 /> <?php echo t('px')?>
</td>
</tr>
<tr>
<td class="padBottom"><label for="locked"><?php echo t('Lock Widths') ?>:</label></td>
<td class="val padBottom">
<input id="locked" name="locked" type="checkbox" value="1" <?php echo ( intval($layout->locked) ) ? 'checked="checked"' : '' ?> />
</td>
</tr>
</table>
</div>
<?php
//To Do: only provide this option if there's 1) blocks in the main area, or 2) existing layouts
if( !intval($layout->layoutID) ){ ?>
<?php /*
<div style="margin:16px 0px">
<?php echo t('Add layout to: ') ?>
<input name="add_to_position" type="radio" value="top" /> <?php echo t('top') ?>
<input name="add_to_position" type="radio" value="bottom" checked="checked" /> <?php echo t('bottom') ?>
</div>
*/ ?>
<input type="hidden" name="add_to_position" value="bottom" />
<?php } ?>
<?php if ( is_object($layoutPreset) ) { ?>
<div id="layoutPresetActions" style="display: none">
<label class="radio"><?php echo $form->radio('layoutPresetAction', 'update_existing_preset', true)?> <?php echo t('Update "%s" preset everywhere it is used?', $layoutPreset->getLayoutPresetName())?></label>
<label class="radio"><?php echo $form->radio('layoutPresetAction', 'save_as_custom')?> <?php echo t('Use this layout here, and leave "%s" unchanged?', $layoutPreset->getLayoutPresetName())?></label>
<label class="radio"><?php echo $form->radio('layoutPresetAction', 'create_new_preset')?> <?php echo t('Save this style as a new preset?')?><br/><span style="margin-left: 20px"><?php echo $form->text('layoutPresetNameAlt', array('style' => 'width: 127px', 'disabled' => true))?></span></label>
</div>
<?php } ?>
<div id="layoutPresetActionNew" style="margin-bottom:16px;">
<label for="layoutPresetAction" class="checkbox inline">
<?php echo $form->checkbox('layoutPresetAction', 'create_new_preset')?>
<?php echo t('Save this style as a new preset.')?>
</label>
<span style="margin-left: 10px"><?php echo $form->text('layoutPresetName', array('style' => 'width: 127px', 'disabled' => true))?></span>
</div>
<?php if(!$_REQUEST['refresh']) { ?>
<div class="ccm-buttons dialog-buttons">
<a href="#" class="btn ccm-button-left cancel" onclick="jQuery.fn.dialog.closeTop(); return false"><?php echo t('Cancel')?></a>
<a href="javascript:void(0)" onclick="$('#ccmAreaLayoutForm').submit()" class="ccm-button-right accept btn primary"><?php echo intval($layout->layoutID)?t('Save Changes'):t('Add')?></a>
</div>
<?php } ?>
</form>
<script type="text/javascript">
$(function() { ccmLayoutEdit.init(); });
</script>
<?php if (!$_REQUEST['refresh']) { ?>
</div>
<?php } ?>
<?php } ?> | HB-Biomedical-Technologies/hbbt-web-skeleton | www/concrete/elements/block_area_layout.php | PHP | mit | 5,830 |
// File: chapter14/appUnderTest/app/scripts/app.js
angular.module('fifaApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/team_list.html',
controller: 'TeamListCtrl as teamListCtrl'
})
.when('/login', {
templateUrl: 'views/login.html',
})
.when('/team/:code', {
templateUrl: 'views/team_details.html',
controller:'TeamDetailsCtrl as teamDetailsCtrl',
resolve: {
auth: ['$q', '$location', 'UserService',
function($q, $location, UserService) {
return UserService.session().then(
function(success) {},
function(err) {
$location.path('/login');
return $q.reject(err);
});
}]
}
});
$routeProvider.otherwise({
redirectTo: '/'
});
});
| dikshay/angularjs-up-and-running | chapter14/appUnderTest/app/scripts/app.js | JavaScript | mit | 881 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2015 Natale Patriciello <natale.patriciello@gmail.com>
* 2016 Stefano Avallone <stavallo@unina.it>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "traffic-control-layer.h"
#include "ns3/log.h"
#include "ns3/object-vector.h"
#include "ns3/packet.h"
#include "ns3/queue-disc.h"
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("TrafficControlLayer");
NS_OBJECT_ENSURE_REGISTERED (TrafficControlLayer);
TypeId
TrafficControlLayer::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::TrafficControlLayer")
.SetParent<Object> ()
.SetGroupName ("TrafficControl")
.AddConstructor<TrafficControlLayer> ()
.AddAttribute ("RootQueueDiscList", "The list of root queue discs associated to this Traffic Control layer.",
ObjectVectorValue (),
MakeObjectVectorAccessor (&TrafficControlLayer::m_rootQueueDiscs),
MakeObjectVectorChecker<QueueDisc> ())
;
return tid;
}
TypeId
TrafficControlLayer::GetInstanceTypeId (void) const
{
return GetTypeId ();
}
TrafficControlLayer::TrafficControlLayer ()
: Object ()
{
NS_LOG_FUNCTION_NOARGS ();
}
void
TrafficControlLayer::DoDispose (void)
{
NS_LOG_FUNCTION (this);
m_node = 0;
m_rootQueueDiscs.clear ();
m_handlers.clear ();
m_netDeviceQueueToQueueDiscMap.clear ();
Object::DoDispose ();
}
void
TrafficControlLayer::DoInitialize (void)
{
NS_LOG_FUNCTION (this);
for (uint32_t j = 0; j < m_rootQueueDiscs.size (); j++)
{
if (m_rootQueueDiscs[j])
{
Ptr<NetDevice> device = m_node->GetDevice (j);
// NetDevices supporting flow control can set the number of device transmission
// queues through the NetDevice queue interface during initialization. Thus,
// ensure that the device has completed initialization
device->Initialize ();
std::map<Ptr<NetDevice>, NetDeviceInfo>::iterator qdMap = m_netDeviceQueueToQueueDiscMap.find (device);
NS_ASSERT (qdMap != m_netDeviceQueueToQueueDiscMap.end ());
Ptr<NetDeviceQueueInterface> devQueueIface = qdMap->second.first;
NS_ASSERT (devQueueIface);
devQueueIface->SetQueueDiscInstalled (true);
// set the wake callbacks on netdevice queues
if (m_rootQueueDiscs[j]->GetWakeMode () == QueueDisc::WAKE_ROOT)
{
for (uint32_t i = 0; i < devQueueIface->GetTxQueuesN (); i++)
{
devQueueIface->GetTxQueue (i)->SetWakeCallback (MakeCallback (&QueueDisc::Run, m_rootQueueDiscs[j]));
qdMap->second.second.push_back (m_rootQueueDiscs[j]);
}
}
else if (m_rootQueueDiscs[j]->GetWakeMode () == QueueDisc::WAKE_CHILD)
{
NS_ASSERT_MSG (m_rootQueueDiscs[j]->GetNQueueDiscClasses () == devQueueIface->GetTxQueuesN (),
"The number of child queue discs does not match the number of netdevice queues");
for (uint32_t i = 0; i < devQueueIface->GetTxQueuesN (); i++)
{
devQueueIface->GetTxQueue (i)->SetWakeCallback (MakeCallback (&QueueDisc::Run,
m_rootQueueDiscs[j]->GetQueueDiscClass (i)->GetQueueDisc ()));
qdMap->second.second.push_back (m_rootQueueDiscs[j]->GetQueueDiscClass (i)->GetQueueDisc ());
}
}
// initialize the queue disc
m_rootQueueDiscs[j]->Initialize ();
}
}
Object::DoInitialize ();
}
void
TrafficControlLayer::SetupDevice (Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << device);
// ensure this setup is done just once (in case of dual stack nodes)
if (device->GetObject<NetDeviceQueueInterface> ())
{
NS_LOG_DEBUG ("The setup for this device has been already done.");
return;
}
// create a NetDeviceQueueInterface object and aggregate it to the device
Ptr<NetDeviceQueueInterface> devQueueIface = CreateObject<NetDeviceQueueInterface> ();
device->AggregateObject (devQueueIface);
// store a pointer to the created queue interface
NS_ASSERT_MSG (m_netDeviceQueueToQueueDiscMap.find (device) == m_netDeviceQueueToQueueDiscMap.end (),
"This is a bug: SetupDevice should be called only once per device");
m_netDeviceQueueToQueueDiscMap[device] = NetDeviceInfo (devQueueIface, QueueDiscVector ());
}
void
TrafficControlLayer::RegisterProtocolHandler (Node::ProtocolHandler handler,
uint16_t protocolType, Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << protocolType << device);
struct ProtocolHandlerEntry entry;
entry.handler = handler;
entry.protocol = protocolType;
entry.device = device;
entry.promiscuous = false;
m_handlers.push_back (entry);
NS_LOG_DEBUG ("Handler for NetDevice: " << device << " registered for protocol " <<
protocolType << ".");
}
void
TrafficControlLayer::SetRootQueueDiscOnDevice (Ptr<NetDevice> device, Ptr<QueueDisc> qDisc)
{
NS_LOG_FUNCTION (this << device);
uint32_t index = GetDeviceIndex (device);
NS_ASSERT_MSG (index < m_node->GetNDevices (), "The provided device does not belong to"
<< " the node which this TrafficControlLayer object is aggregated to" );
if (index >= m_rootQueueDiscs.size ())
{
m_rootQueueDiscs.resize (index+1);
}
NS_ASSERT_MSG (m_rootQueueDiscs[index] == 0, "Cannot install a root queue disc on a "
<< "device already having one. Delete the existing queue disc first.");
m_rootQueueDiscs[index] = qDisc;
}
Ptr<QueueDisc>
TrafficControlLayer::GetRootQueueDiscOnDevice (Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << device);
uint32_t index = GetDeviceIndex (device);
NS_ASSERT_MSG (index < m_node->GetNDevices (), "The provided device does not belong to"
<< " the node which this TrafficControlLayer object is aggregated to" );
if (index >= m_rootQueueDiscs.size ())
{
m_rootQueueDiscs.resize (index+1);
}
return m_rootQueueDiscs[index];
}
void
TrafficControlLayer::DeleteRootQueueDiscOnDevice (Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << device);
uint32_t index = GetDeviceIndex (device);
NS_ASSERT_MSG (index < m_node->GetNDevices (), "The provided device does not belong to"
<< " the node which this TrafficControlLayer object is aggregated to" );
NS_ASSERT_MSG (index < m_rootQueueDiscs.size () && m_rootQueueDiscs[index] != 0, "No root queue disc"
<< " installed on device " << device);
// remove the root queue disc
m_rootQueueDiscs[index] = 0;
}
void
TrafficControlLayer::SetNode (Ptr<Node> node)
{
NS_LOG_FUNCTION (this << node);
m_node = node;
}
void
TrafficControlLayer::NotifyNewAggregate ()
{
NS_LOG_FUNCTION (this);
if (m_node == 0)
{
Ptr<Node> node = this->GetObject<Node> ();
//verify that it's a valid node and that
//the node was not set before
if (node != 0)
{
this->SetNode (node);
}
}
Object::NotifyNewAggregate ();
}
uint32_t
TrafficControlLayer::GetDeviceIndex (Ptr<NetDevice> device)
{
NS_LOG_FUNCTION (this << device);
uint32_t i;
for (i = 0; i < m_node->GetNDevices () && device != m_node->GetDevice (i); i++);
return i;
}
void
TrafficControlLayer::Receive (Ptr<NetDevice> device, Ptr<const Packet> p,
uint16_t protocol, const Address &from, const Address &to,
NetDevice::PacketType packetType)
{
NS_LOG_FUNCTION (this << device << p << protocol << from << to << packetType);
bool found = false;
for (ProtocolHandlerList::iterator i = m_handlers.begin ();
i != m_handlers.end (); i++)
{
if (i->device == 0
|| (i->device != 0 && i->device == device))
{
if (i->protocol == 0
|| i->protocol == protocol)
{
NS_LOG_DEBUG ("Found handler for packet " << p << ", protocol " <<
protocol << " and NetDevice " << device <<
". Send packet up");
i->handler (device, p, protocol, from, to, packetType);
found = true;
}
}
}
if (! found)
{
NS_FATAL_ERROR ("Handler for protocol " << p << " and device " << device <<
" not found. It isn't forwarded up; it dies here.");
}
}
void
TrafficControlLayer::Send (Ptr<NetDevice> device, Ptr<QueueDiscItem> item)
{
NS_LOG_FUNCTION (this << device << item);
NS_LOG_DEBUG ("Send packet to device " << device << " protocol number " <<
item->GetProtocol ());
std::map<Ptr<NetDevice>, NetDeviceInfo>::iterator qdMap = m_netDeviceQueueToQueueDiscMap.find (device);
NS_ASSERT (qdMap != m_netDeviceQueueToQueueDiscMap.end ());
Ptr<NetDeviceQueueInterface> devQueueIface = qdMap->second.first;
NS_ASSERT (devQueueIface);
// determine the transmission queue of the device where the packet will be enqueued
uint8_t txq = devQueueIface->GetSelectedQueue (item);
NS_ASSERT (txq < devQueueIface->GetTxQueuesN ());
if (qdMap->second.second.empty ())
{
// The device has no attached queue disc, thus add the header to the packet and
// send it directly to the device if the selected queue is not stopped
if (!devQueueIface->GetTxQueue (txq)->IsStopped ())
{
item->AddHeader ();
device->Send (item->GetPacket (), item->GetAddress (), item->GetProtocol ());
}
}
else
{
// Enqueue the packet in the queue disc associated with the netdevice queue
// selected for the packet and try to dequeue packets from such queue disc
item->SetTxQueueIndex (txq);
Ptr<QueueDisc> qDisc = qdMap->second.second[txq];
NS_ASSERT (qDisc);
qDisc->Enqueue (item);
qDisc->Run ();
}
}
} // namespace ns3
| Vivek-anand-jain/Implementation-of-BLUE-in-ns-3 | src/traffic-control/model/traffic-control-layer.cc | C++ | gpl-2.0 | 10,705 |
package autotest.afe;
import java.util.ArrayList;
import java.util.List;
public class CheckBoxPanel {
public static interface Display {
public ICheckBox generateCheckBox(int index);
}
private List<ICheckBox> checkBoxes = new ArrayList<ICheckBox>();
private Display display;
public void bindDisplay(Display display) {
this.display = display;
}
public ICheckBox generateCheckBox() {
return display.generateCheckBox(checkBoxes.size());
}
public void add(ICheckBox checkBox) {
checkBoxes.add(checkBox);
}
public List<ICheckBox> getChecked() {
List<ICheckBox> result = new ArrayList<ICheckBox>();
for(ICheckBox checkBox : checkBoxes) {
if (checkBox.getValue()) {
result.add(checkBox);
}
}
return result;
}
public void setEnabled(boolean enabled) {
for(ICheckBox thisBox : checkBoxes) {
thisBox.setEnabled(enabled);
}
}
public void reset() {
for (ICheckBox thisBox : checkBoxes) {
thisBox.setValue(false);
}
}
}
| spcui/autotest | frontend/client/src/autotest/afe/CheckBoxPanel.java | Java | gpl-2.0 | 1,139 |
package autotest.tko;
import autotest.common.Utils;
public abstract class LabelField extends ParameterizedField {
@Override
public String getSqlCondition(String value) {
String condition = " IS NOT NULL";
if (value.equals(Utils.JSON_NULL)) {
condition = " IS NULL";
}
return getFilteringName() + condition;
}
@Override
public String getFilteringName() {
return getQuotedSqlName() + ".id";
}
}
| nacc/autotest | frontend/client/src/autotest/tko/LabelField.java | Java | gpl-2.0 | 472 |
tinymce.PluginManager.add("insertdatetime", function (e) {
function t(t, n) {
function i(e, t) {
if (e = "" + e, e.length < t)for (var n = 0; n < t - e.length; n++)e = "0" + e;
return e
}
return n = n || new Date, t = t.replace("%D", "%m/%d/%Y"), t = t.replace("%r", "%I:%M:%S %p"), t = t.replace("%Y", "" + n.getFullYear()), t = t.replace("%y", "" + n.getYear()), t = t.replace("%m", i(n.getMonth() + 1, 2)), t = t.replace("%d", i(n.getDate(), 2)), t = t.replace("%H", "" + i(n.getHours(), 2)), t = t.replace("%M", "" + i(n.getMinutes(), 2)), t = t.replace("%S", "" + i(n.getSeconds(), 2)), t = t.replace("%I", "" + ((n.getHours() + 11) % 12 + 1)), t = t.replace("%p", "" + (n.getHours() < 12 ? "AM" : "PM")), t = t.replace("%B", "" + e.translate(s[n.getMonth()])), t = t.replace("%b", "" + e.translate(o[n.getMonth()])), t = t.replace("%A", "" + e.translate(r[n.getDay()])), t = t.replace("%a", "" + e.translate(a[n.getDay()])), t = t.replace("%%", "%")
}
function n(n) {
var i = t(n);
if (e.settings.insertdatetime_element) {
var a;
a = /%[HMSIp]/.test(n) ? t("%Y-%m-%dT%H:%M") : t("%Y-%m-%d"), i = '<time datetime="' + a + '">' + i + "</time>";
var r = e.dom.getParent(e.selection.getStart(), "time");
if (r)return e.dom.setOuterHTML(r, i), void 0
}
e.insertContent(i)
}
var i, a = "Sun Mon Tue Wed Thu Fri Sat Sun".split(" "), r = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" "), o = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "), s = "January February March April May June July August September October November December".split(" "), l = [];
e.addCommand("mceInsertDate", function () {
n(e.getParam("insertdatetime_dateformat", e.translate("%Y-%m-%d")))
}), e.addCommand("mceInsertTime", function () {
n(e.getParam("insertdatetime_timeformat", e.translate("%H:%M:%S")))
}), e.addButton("inserttime", {
type: "splitbutton", title: "Insert time", onclick: function () {
n(i || "%H:%M:%S")
}, menu: l
}), tinymce.each(e.settings.insertdatetime_formats || ["%H:%M:%S", "%Y-%m-%d", "%I:%M:%S %p", "%D"], function (e) {
l.push({
text: t(e), onclick: function () {
i = e, n(e)
}
})
}), e.addMenuItem("insertdatetime", {icon: "date", text: "Insert date/time", menu: l, context: "insert"})
}); | DaveB95/CS3012Website | vendors/tinymce/plugins/insertdatetime/plugin.min.js | JavaScript | gpl-2.0 | 2,505 |
<?php
if (!$os)
{
if (strstr($sysDescr, "KYOCERA ")) { $os = "kyocera"; }
}
?> | mehulsbhatt/librenms | includes/discovery/os/kyocera.inc.php | PHP | gpl-3.0 | 82 |
/*!
* JavaScript for the debug toolbar profiler, enabled through $wgDebugToolbar
* and StartProfiler.php.
*
* @author Erik Bernhardson
* @since 1.23
*/
( function ( mw, $ ) {
'use strict';
/**
* @singleton
* @class mw.Debug.profile
*/
var profile = mw.Debug.profile = {
/**
* Object containing data for the debug toolbar
*
* @property ProfileData
*/
data: null,
/**
* @property DOMElement
*/
container: null,
/**
* Initializes the profiling pane.
*/
init: function ( data, width, mergeThresholdPx, dropThresholdPx ) {
data = data || mw.config.get( 'debugInfo' ).profile;
profile.width = width || $(window).width() - 20;
// merge events from same pixel(some events are very granular)
mergeThresholdPx = mergeThresholdPx || 2;
// only drop events if requested
dropThresholdPx = dropThresholdPx || 0;
if ( !Array.prototype.map || !Array.prototype.reduce || !Array.prototype.filter ) {
profile.container = profile.buildRequiresES5();
} else if ( data.length === 0 ) {
profile.container = profile.buildNoData();
} else {
// generate a flyout
profile.data = new ProfileData( data, profile.width, mergeThresholdPx, dropThresholdPx );
// draw it
profile.container = profile.buildSvg( profile.container );
profile.attachFlyout();
}
return profile.container;
},
buildRequiresES5: function () {
return $( '<div>' )
.text( 'An ES5 compatible javascript engine is required for the profile visualization.' )
.get( 0 );
},
buildNoData: function () {
return $( '<div>' ).addClass( 'mw-debug-profile-no-data' )
.text( 'No events recorded, ensure profiling is enabled in StartProfiler.php.' )
.get( 0 );
},
/**
* Creates DOM nodes appropriately namespaced for SVG.
*
* @param string tag to create
* @return DOMElement
*/
createSvgElement: document.createElementNS
? document.createElementNS.bind( document, 'http://www.w3.org/2000/svg' )
// throw a error for browsers which does not support document.createElementNS (IE<8)
: function () { throw new Error( 'document.createElementNS not supported' ); },
/**
* @param DOMElement|undefined
*/
buildSvg: function ( node ) {
var container, group, i, g,
timespan = profile.data.timespan,
gapPerEvent = 38,
space = 10.5,
currentHeight = space,
totalHeight = 0;
profile.ratio = ( profile.width - space * 2 ) / ( timespan.end - timespan.start );
totalHeight += gapPerEvent * profile.data.groups.length;
if ( node ) {
$( node ).empty();
} else {
node = profile.createSvgElement( 'svg' );
node.setAttribute( 'version', '1.2' );
node.setAttribute( 'baseProfile', 'tiny' );
}
node.style.height = totalHeight;
node.style.width = profile.width;
// use a container that can be transformed
container = profile.createSvgElement( 'g' );
node.appendChild( container );
for ( i = 0; i < profile.data.groups.length; i++ ) {
group = profile.data.groups[i];
g = profile.buildTimeline( group );
g.setAttribute( 'transform', 'translate( 0 ' + currentHeight + ' )' );
container.appendChild( g );
currentHeight += gapPerEvent;
}
return node;
},
/**
* @param Object group of periods to transform into graphics
*/
buildTimeline: function ( group ) {
var text, tspan, line, i,
sum = group.timespan.sum,
ms = ' ~ ' + ( sum < 1 ? sum.toFixed( 2 ) : sum.toFixed( 0 ) ) + ' ms',
timeline = profile.createSvgElement( 'g' );
timeline.setAttribute( 'class', 'mw-debug-profile-timeline' );
// draw label
text = profile.createSvgElement( 'text' );
text.setAttribute( 'x', profile.xCoord( group.timespan.start ) );
text.setAttribute( 'y', 0 );
text.textContent = group.name;
timeline.appendChild( text );
// draw metadata
tspan = profile.createSvgElement( 'tspan' );
tspan.textContent = ms;
text.appendChild( tspan );
// draw timeline periods
for ( i = 0; i < group.periods.length; i++ ) {
timeline.appendChild( profile.buildPeriod( group.periods[i] ) );
}
// full-width line under each timeline
line = profile.createSvgElement( 'line' );
line.setAttribute( 'class', 'mw-debug-profile-underline' );
line.setAttribute( 'x1', 0 );
line.setAttribute( 'y1', 28 );
line.setAttribute( 'x2', profile.width );
line.setAttribute( 'y2', 28 );
timeline.appendChild( line );
return timeline;
},
/**
* @param Object period to transform into graphics
*/
buildPeriod: function ( period ) {
var node,
head = profile.xCoord( period.start ),
tail = profile.xCoord( period.end ),
g = profile.createSvgElement( 'g' );
g.setAttribute( 'class', 'mw-debug-profile-period' );
$( g ).data( 'period', period );
if ( head + 16 > tail ) {
node = profile.createSvgElement( 'rect' );
node.setAttribute( 'x', head );
node.setAttribute( 'y', 8 );
node.setAttribute( 'width', 2 );
node.setAttribute( 'height', 9 );
g.appendChild( node );
node = profile.createSvgElement( 'rect' );
node.setAttribute( 'x', head );
node.setAttribute( 'y', 8 );
node.setAttribute( 'width', ( period.end - period.start ) * profile.ratio || 2 );
node.setAttribute( 'height', 6 );
g.appendChild( node );
} else {
node = profile.createSvgElement( 'polygon' );
node.setAttribute( 'points', pointList( [
[ head, 8 ],
[ head, 19 ],
[ head + 8, 8 ],
[ head, 8]
] ) );
g.appendChild( node );
node = profile.createSvgElement( 'polygon' );
node.setAttribute( 'points', pointList( [
[ tail, 8 ],
[ tail, 19 ],
[ tail - 8, 8 ],
[ tail, 8 ]
] ) );
g.appendChild( node );
node = profile.createSvgElement( 'line' );
node.setAttribute( 'x1', head );
node.setAttribute( 'y1', 9 );
node.setAttribute( 'x2', tail );
node.setAttribute( 'y2', 9 );
g.appendChild( node );
}
return g;
},
/**
* @param Object
*/
buildFlyout: function ( period ) {
var contained, sum, ms, mem, i,
node = $( '<div>' );
for ( i = 0; i < period.contained.length; i++ ) {
contained = period.contained[i];
sum = contained.end - contained.start;
ms = '' + ( sum < 1 ? sum.toFixed( 2 ) : sum.toFixed( 0 ) ) + ' ms';
mem = formatBytes( contained.memory );
$( '<div>' ).text( contained.source.name )
.append( $( '<span>' ).text( ' ~ ' + ms + ' / ' + mem ).addClass( 'mw-debug-profile-meta' ) )
.appendTo( node );
}
return node;
},
/**
* Attach a hover flyout to all .mw-debug-profile-period groups.
*/
attachFlyout: function () {
// for some reason addClass and removeClass from jQuery
// arn't working on svg elements in chrome <= 33.0 (possibly more)
var $container = $( profile.container ),
addClass = function ( node, value ) {
var current = node.getAttribute( 'class' ),
list = current ? current.split( ' ' ) : false,
idx = list ? list.indexOf( value ) : -1;
if ( idx === -1 ) {
node.setAttribute( 'class', current ? ( current + ' ' + value ) : value );
}
},
removeClass = function ( node, value ) {
var current = node.getAttribute( 'class' ),
list = current ? current.split( ' ' ) : false,
idx = list ? list.indexOf( value ) : -1;
if ( idx !== -1 ) {
list.splice( idx, 1 );
node.setAttribute( 'class', list.join( ' ' ) );
}
},
// hide all tipsy flyouts
hide = function () {
$container.find( '.mw-debug-profile-period.tipsy-visible' )
.each( function () {
removeClass( this, 'tipsy-visible' );
$( this ).tipsy( 'hide' );
} );
};
$container.find( '.mw-debug-profile-period' ).tipsy( {
fade: true,
gravity: function () {
return $.fn.tipsy.autoNS.call( this )
+ $.fn.tipsy.autoWE.call( this );
},
className: 'mw-debug-profile-tipsy',
center: false,
html: true,
trigger: 'manual',
title: function () {
return profile.buildFlyout( $( this ).data( 'period' ) ).html();
}
} ).on( 'mouseenter', function () {
hide();
addClass( this, 'tipsy-visible' );
$( this ).tipsy( 'show' );
} );
$container.on( 'mouseleave', function ( event ) {
var $from = $( event.relatedTarget ),
$to = $( event.target );
// only close the tipsy if we are not
if ( $from.closest( '.tipsy' ).length === 0 &&
$to.closest( '.tipsy' ).length === 0 &&
$to.get( 0 ).namespaceURI !== 'http://www.w4.org/2000/svg'
) {
hide();
}
} ).on( 'click', function () {
// convenience method for closing
hide();
} );
},
/**
* @return number the x co-ordinate for the specified timestamp
*/
xCoord: function ( msTimestamp ) {
return ( msTimestamp - profile.data.timespan.start ) * profile.ratio;
}
};
function ProfileData( data, width, mergeThresholdPx, dropThresholdPx ) {
// validate input data
this.data = data.map( function ( event ) {
event.periods = event.periods.filter( function ( period ) {
return period.start && period.end
&& period.start < period.end
// period start must be a reasonable ms timestamp
&& period.start > 1000000;
} );
return event;
} ).filter( function ( event ) {
return event.name && event.periods.length > 0;
} );
// start and end time of the data
this.timespan = this.data.reduce( function ( result, event ) {
return event.periods.reduce( periodMinMax, result );
}, periodMinMax.initial() );
// transform input data
this.groups = this.collate( width, mergeThresholdPx, dropThresholdPx );
return this;
}
/**
* There are too many unique events to display a line for each,
* so this does a basic grouping.
*/
ProfileData.groupOf = function ( label ) {
var pos, prefix = 'Profile section ended by close(): ';
if ( label.indexOf( prefix ) === 0 ) {
label = label.substring( prefix.length );
}
pos = [ '::', ':', '-' ].reduce( function ( result, separator ) {
var pos = label.indexOf( separator );
if ( pos === -1 ) {
return result;
} else if ( result === -1 ) {
return pos;
} else {
return Math.min( result, pos );
}
}, -1 );
if ( pos === -1 ) {
return label;
} else {
return label.substring( 0, pos );
}
};
/**
* @return Array list of objects with `name` and `events` keys
*/
ProfileData.groupEvents = function ( events ) {
var group, i,
groups = {};
// Group events together
for ( i = events.length - 1; i >= 0; i-- ) {
group = ProfileData.groupOf( events[i].name );
if ( groups[group] ) {
groups[group].push( events[i] );
} else {
groups[group] = [events[i]];
}
}
// Return an array of groups
return Object.keys( groups ).map( function ( group ) {
return {
name: group,
events: groups[group]
};
} );
};
ProfileData.periodSorter = function ( a, b ) {
if ( a.start === b.start ) {
return a.end - b.end;
}
return a.start - b.start;
};
ProfileData.genMergePeriodReducer = function ( mergeThresholdMs ) {
return function ( result, period ) {
if ( result.length === 0 ) {
// period is first result
return [{
start: period.start,
end: period.end,
contained: [period]
}];
}
var last = result[result.length - 1];
if ( period.end < last.end ) {
// end is contained within previous
result[result.length - 1].contained.push( period );
} else if ( period.start - mergeThresholdMs < last.end ) {
// neighbors within merging distance
result[result.length - 1].end = period.end;
result[result.length - 1].contained.push( period );
} else {
// period is next result
result.push({
start: period.start,
end: period.end,
contained: [period]
});
}
return result;
};
};
/**
* Collect all periods from the grouped events and apply merge and
* drop transformations
*/
ProfileData.extractPeriods = function ( events, mergeThresholdMs, dropThresholdMs ) {
// collect the periods from all events
return events.reduce( function ( result, event ) {
if ( !event.periods.length ) {
return result;
}
result.push.apply( result, event.periods.map( function ( period ) {
// maintain link from period to event
period.source = event;
return period;
} ) );
return result;
}, [] )
// sort combined periods
.sort( ProfileData.periodSorter )
// Apply merge threshold. Original periods
// are maintained in the `contained` property
.reduce( ProfileData.genMergePeriodReducer( mergeThresholdMs ), [] )
// Apply drop threshold
.filter( function ( period ) {
return period.end - period.start > dropThresholdMs;
} );
};
/**
* runs a callback on all periods in the group. Only valid after
* groups.periods[0..n].contained are populated. This runs against
* un-transformed data and is better suited to summing or other
* stat collection
*/
ProfileData.reducePeriods = function ( group, callback, result ) {
return group.periods.reduce( function ( result, period ) {
return period.contained.reduce( callback, result );
}, result );
};
/**
* Transforms this.data grouping by labels, merging neighboring
* events in the groups, and drops events and groups below the
* display threshold. Groups are returned sorted by starting time.
*/
ProfileData.prototype.collate = function ( width, mergeThresholdPx, dropThresholdPx ) {
// ms to pixel ratio
var ratio = ( this.timespan.end - this.timespan.start ) / width,
// transform thresholds to ms
mergeThresholdMs = mergeThresholdPx * ratio,
dropThresholdMs = dropThresholdPx * ratio;
return ProfileData.groupEvents( this.data )
// generate data about the grouped events
.map( function ( group ) {
// Cleaned periods from all events
group.periods = ProfileData.extractPeriods( group.events, mergeThresholdMs, dropThresholdMs );
// min and max timestamp per group
group.timespan = ProfileData.reducePeriods( group, periodMinMax, periodMinMax.initial() );
// ms from first call to end of last call
group.timespan.length = group.timespan.end - group.timespan.start;
// collect the un-transformed periods
group.timespan.sum = ProfileData.reducePeriods( group, function ( result, period ) {
result.push( period );
return result;
}, [] )
// sort by start time
.sort( ProfileData.periodSorter )
// merge overlapping
.reduce( ProfileData.genMergePeriodReducer( 0 ), [] )
// sum
.reduce( function ( result, period ) {
return result + period.end - period.start;
}, 0 );
return group;
}, this )
// remove groups that have had all their periods filtered
.filter( function ( group ) {
return group.periods.length > 0;
} )
// sort events by first start
.sort( function ( a, b ) {
return ProfileData.periodSorter( a.timespan, b.timespan );
} );
};
// reducer to find edges of period array
function periodMinMax( result, period ) {
if ( period.start < result.start ) {
result.start = period.start;
}
if ( period.end > result.end ) {
result.end = period.end;
}
return result;
}
periodMinMax.initial = function () {
return { start: Number.POSITIVE_INFINITY, end: Number.NEGATIVE_INFINITY };
};
function formatBytes( bytes ) {
var i, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if ( bytes === 0 ) {
return '0 Bytes';
}
i = parseInt( Math.floor( Math.log( bytes ) / Math.log( 1024 ) ), 10 );
return Math.round( bytes / Math.pow( 1024, i ), 2 ) + ' ' + sizes[i];
}
// turns a 2d array into a point list for svg
// polygon points attribute
// ex: [[1,2],[3,4],[4,2]] = '1,2 3,4 4,2'
function pointList( pairs ) {
return pairs.map( function ( pair ) {
return pair.join( ',' );
} ).join( ' ' );
}
}( mediaWiki, jQuery ) );
| kylethayer/bioladder | wiki/resources/src/mediawiki/mediawiki.debug.profile.js | JavaScript | gpl-3.0 | 15,945 |
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
contextMenuItems = [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$); | europeana/broken_dont_bother_exhibitions | webtree/themes/main/javascripts/mediaelement-2.7/src/js/mep-feature-contextmenu.js | JavaScript | gpl-3.0 | 4,424 |
<?php
/*
* $Id$
*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
/**
* Doctrine_Ticket_1365_TestCase
*
* @package Doctrine
* @author David Stendardi <david.stendardi@adenclassifieds.com>
* @category Query
* @link www.doctrine-project.org
* @since 0.10.4
* @version $Revision$
*/
class Doctrine_Ticket_1365_TestCase extends Doctrine_UnitTestCase
{
public function testInit()
{
$this->dbh = new Doctrine_Adapter_Mock('mysql');
$this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh);
$this->conn->setCharset('utf8');
$this->conn->setAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM, true);
}
public function prepareData()
{
}
public function prepareTables()
{
$this->tables = array();
$this->tables[] = 'T1365_Person';
$this->tables[] = 'T1365_Skill';
$this->tables[] = 'T1365_PersonHasSkill';
parent :: prepareTables();
}
public function testTicket()
{
$q = Doctrine_Query::create()
->select('s.*, phs.*')
->from('T1365_Skill s')
->leftJoin('s.T1365_PersonHasSkill phs')
->where('phs.value0 > phs.value1');
$this->assertEqual(
$q->getSqlQuery(),
'SELECT l.id AS l__id, l.name AS l__name, ' .
'l2.id AS l2__id, l2.fk_person_id AS l2__fk_person_id, l2.fk_skill_id AS l2__fk_skill_id, l2.value0 AS l2__value0, l2.value1 AS l2__value1 ' .
'FROM la__skill l LEFT JOIN la__person_has_skill l2 ON l.id = l2.fk_skill_id ' .
'WHERE (l2.value0 > l2.value1)'
);
}
}
class T1365_Person extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('la__person');
$this->hasColumn('name', 'string', 255);
}
public function setUp()
{
$this->hasMany('T1365_PersonHasSkill', array('local' => 'id', 'foreign' => 'fk_person_id'));
}
}
class T1365_Skill extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('la__skill');
$this->hasColumn('name', 'string', 255);
}
public function setUp()
{
$this->hasMany('T1365_PersonHasSkill', array('local' => 'id', 'foreign' => 'fk_skill_id'));
}
}
class T1365_PersonHasSkill extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('la__person_has_skill');
$this->hasColumn('fk_person_id', 'integer', 8, array(
'type' => 'integer', 'length' => '8'
));
$this->hasColumn('fk_skill_id', 'integer', 8, array(
'type' => 'integer', 'length' => '8'
));
$this->hasColumn('value0', 'enum', 3, array(
'type' => 'enum', 'values' => array(
0 => '0', 1 => '1', 2 => '2', 3 => '3'
), 'default' => 0, 'notnull' => true, 'length' => '3'
));
$this->hasColumn('value1', 'enum', 3, array(
'type' => 'enum', 'values' => array(
0 => '0', 1 => '1', 2 => '2', 3 => '3'
), 'default' => 0, 'notnull' => true, 'length' => '3'
));
}
public function setUp()
{
$this->hasOne('T1365_Person', array('local' => 'fk_person_id', 'foreign' => 'id'));
$this->hasOne('T1365_Skill', array('local' => 'fk_skill_id', 'foreign' => 'id'));
}
} | aripringle/doctrine1 | tests/Ticket/1365TestCase.php | PHP | lgpl-2.1 | 4,392 |
package servicefabric
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// VersionClient is the azure Service Fabric Resource Provider API Client
type VersionClient struct {
BaseClient
}
// NewVersionClient creates an instance of the VersionClient client.
func NewVersionClient() VersionClient {
return NewVersionClientWithBaseURI(DefaultBaseURI)
}
// NewVersionClientWithBaseURI creates an instance of the VersionClient client.
func NewVersionClientWithBaseURI(baseURI string) VersionClient {
return VersionClient{NewWithBaseURI(baseURI)}
}
// Delete unprovisions an application type version resource.
//
// subscriptionID is the customer subscription identifier resourceGroupName is the name of the resource group.
// clusterName is the name of the cluster resource applicationTypeName is the name of the application type name
// resource version is the application type version.
func (client VersionClient) Delete(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string) (result VersionDeleteFuture, err error) {
req, err := client.DeletePreparer(ctx, subscriptionID, resourceGroupName, clusterName, applicationTypeName, version)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client VersionClient) DeletePreparer(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationTypeName": autorest.Encode("path", applicationTypeName),
"clusterName": autorest.Encode("path", clusterName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", subscriptionID),
"version": autorest.Encode("path", version),
}
const APIVersion = "2017-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client VersionClient) DeleteSender(req *http.Request) (future VersionDeleteFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent))
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client VersionClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get returns an application type version resource.
//
// subscriptionID is the customer subscription identifier resourceGroupName is the name of the resource group.
// clusterName is the name of the cluster resource applicationTypeName is the name of the application type name
// resource version is the application type version.
func (client VersionClient) Get(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string) (result VersionResource, err error) {
req, err := client.GetPreparer(ctx, subscriptionID, resourceGroupName, clusterName, applicationTypeName, version)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client VersionClient) GetPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationTypeName": autorest.Encode("path", applicationTypeName),
"clusterName": autorest.Encode("path", clusterName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", subscriptionID),
"version": autorest.Encode("path", version),
}
const APIVersion = "2017-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client VersionClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client VersionClient) GetResponder(resp *http.Response) (result VersionResource, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List returns all versions for the specified application type.
//
// subscriptionID is the customer subscription identifier resourceGroupName is the name of the resource group.
// clusterName is the name of the cluster resource applicationTypeName is the name of the application type name
// resource
func (client VersionClient) List(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string) (result VersionResourceList, err error) {
req, err := client.ListPreparer(ctx, subscriptionID, resourceGroupName, clusterName, applicationTypeName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client VersionClient) ListPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationTypeName": autorest.Encode("path", applicationTypeName),
"clusterName": autorest.Encode("path", clusterName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", subscriptionID),
}
const APIVersion = "2017-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client VersionClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client VersionClient) ListResponder(resp *http.Response) (result VersionResourceList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Put provisions an application type version resource.
//
// subscriptionID is the customer subscription identifier resourceGroupName is the name of the resource group.
// clusterName is the name of the cluster resource applicationTypeName is the name of the application type name
// resource version is the application type version. parameters is the application type version resource.
func (client VersionClient) Put(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string, parameters VersionResource) (result VersionPutFuture, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.VersionProperties", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.VersionProperties.AppPackageURL", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil {
return result, validation.NewError("servicefabric.VersionClient", "Put", err.Error())
}
req, err := client.PutPreparer(ctx, subscriptionID, resourceGroupName, clusterName, applicationTypeName, version, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Put", nil, "Failure preparing request")
return
}
result, err = client.PutSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabric.VersionClient", "Put", result.Response(), "Failure sending request")
return
}
return
}
// PutPreparer prepares the Put request.
func (client VersionClient) PutPreparer(ctx context.Context, subscriptionID string, resourceGroupName string, clusterName string, applicationTypeName string, version string, parameters VersionResource) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationTypeName": autorest.Encode("path", applicationTypeName),
"clusterName": autorest.Encode("path", clusterName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", subscriptionID),
"version": autorest.Encode("path", version),
}
const APIVersion = "2017-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// PutSender sends the Put request. The method will close the
// http.Response Body if it receives an error.
func (client VersionClient) PutSender(req *http.Request) (future VersionPutFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
return
}
// PutResponder handles the response to the Put request. The method always
// closes the http.Response Body.
func (client VersionClient) PutResponder(resp *http.Response) (result VersionResource, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| wjiangjay/origin | vendor/github.com/Azure/azure-sdk-for-go/services/servicefabric/mgmt/2017-07-01-preview/servicefabric/versiongroup.go | GO | apache-2.0 | 14,585 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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 com.jetbrains.python.codeInsight.functionTypeComments;
import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyFunctionTypeAnnotation;
import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyParameterTypeList;
import com.jetbrains.python.psi.PyElementType;
/**
* @author Mikhail Golubev
*/
public interface PyFunctionTypeAnnotationElementTypes {
PyElementType FUNCTION_SIGNATURE = new PyElementType("FUNCTION_SIGNATURE", PyFunctionTypeAnnotation.class);
PyElementType PARAMETER_TYPE_LIST = new PyElementType("PARAMETER_TYPE_LIST", PyParameterTypeList.class);
}
| asedunov/intellij-community | python/src/com/jetbrains/python/codeInsight/functionTypeComments/PyFunctionTypeAnnotationElementTypes.java | Java | apache-2.0 | 1,200 |
/**
* Implementation of Multi-User Chat (XEP-0045).
*/
package org.jivesoftware.openfire.muc.spi; | zuoyebushiwo/openfire-my-study | src/java/org/jivesoftware/openfire/muc/spi/package-info.java | Java | apache-2.0 | 99 |
/*
* 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 com.facebook.presto.sql.gen;
import com.facebook.presto.byteCode.ByteCodeBlock;
import com.facebook.presto.byteCode.ByteCodeNode;
import com.facebook.presto.byteCode.ClassDefinition;
import com.facebook.presto.byteCode.MethodDefinition;
import com.facebook.presto.byteCode.Parameter;
import com.facebook.presto.byteCode.ParameterizedType;
import com.facebook.presto.byteCode.Scope;
import com.facebook.presto.byteCode.Variable;
import com.facebook.presto.byteCode.control.ForLoop;
import com.facebook.presto.byteCode.control.IfStatement;
import com.facebook.presto.byteCode.instruction.LabelNode;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.operator.PageProcessor;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.ConstantExpression;
import com.facebook.presto.sql.relational.Expressions;
import com.facebook.presto.sql.relational.InputReferenceExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.facebook.presto.sql.relational.RowExpressionVisitor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import io.airlift.slice.Slice;
import java.util.List;
import java.util.TreeSet;
import static com.facebook.presto.byteCode.Access.PUBLIC;
import static com.facebook.presto.byteCode.Access.a;
import static com.facebook.presto.byteCode.OpCode.NOP;
import static com.facebook.presto.byteCode.Parameter.arg;
import static com.facebook.presto.byteCode.ParameterizedType.type;
import static com.facebook.presto.sql.gen.ByteCodeUtils.generateWrite;
import static com.facebook.presto.sql.gen.ByteCodeUtils.loadConstant;
import static java.lang.String.format;
import static java.util.Collections.nCopies;
public class PageProcessorCompiler
implements BodyCompiler<PageProcessor>
{
private final Metadata metadata;
public PageProcessorCompiler(Metadata metadata)
{
this.metadata = metadata;
}
@Override
public void generateMethods(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter, List<RowExpression> projections)
{
generateProcessMethod(classDefinition, filter, projections);
generateFilterMethod(classDefinition, callSiteBinder, filter);
for (int i = 0; i < projections.size(); i++) {
generateProjectMethod(classDefinition, callSiteBinder, "project_" + i, projections.get(i));
}
}
private void generateProcessMethod(ClassDefinition classDefinition, RowExpression filter, List<RowExpression> projections)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter start = arg("start", int.class);
Parameter end = arg("end", int.class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "process", type(int.class), session, page, start, end, pageBuilder);
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
Variable position = scope.declareVariable(int.class, "position");
method.getBody()
.comment("int position = start;")
.getVariable(start)
.putVariable(position);
List<Integer> allInputChannels = getInputChannels(Iterables.concat(projections, ImmutableList.of(filter)));
for (int channel : allInputChannels) {
Variable blockVariable = scope.declareVariable(Block.class, "block_" + channel);
method.getBody()
.comment("Block %s = page.getBlock(%s);", blockVariable.getName(), channel)
.getVariable(page)
.push(channel)
.invokeVirtual(Page.class, "getBlock", Block.class, int.class)
.putVariable(blockVariable);
}
//
// for loop loop body
//
LabelNode done = new LabelNode("done");
ByteCodeBlock loopBody = new ByteCodeBlock();
ForLoop loop = new ForLoop()
.initialize(NOP)
.condition(new ByteCodeBlock()
.comment("position < end")
.getVariable(position)
.getVariable(end)
.invokeStatic(CompilerOperations.class, "lessThan", boolean.class, int.class, int.class)
)
.update(new ByteCodeBlock()
.comment("position++")
.incrementVariable(position, (byte) 1))
.body(loopBody);
loopBody.comment("if (pageBuilder.isFull()) break;")
.getVariable(pageBuilder)
.invokeVirtual(PageBuilder.class, "isFull", boolean.class)
.ifTrueGoto(done);
// if (filter(cursor))
IfStatement filterBlock = new IfStatement();
filterBlock.condition()
.append(thisVariable)
.getVariable(session)
.append(pushBlockVariables(scope, getInputChannels(filter)))
.getVariable(position)
.invokeVirtual(classDefinition.getType(),
"filter",
type(boolean.class),
ImmutableList.<ParameterizedType>builder()
.add(type(ConnectorSession.class))
.addAll(nCopies(getInputChannels(filter).size(), type(Block.class)))
.add(type(int.class))
.build());
filterBlock.ifTrue()
.append(pageBuilder)
.invokeVirtual(PageBuilder.class, "declarePosition", void.class);
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
List<Integer> inputChannels = getInputChannels(projections.get(projectionIndex));
filterBlock.ifTrue()
.append(thisVariable)
.append(session)
.append(pushBlockVariables(scope, inputChannels))
.getVariable(position);
filterBlock.ifTrue()
.comment("pageBuilder.getBlockBuilder(%d)", projectionIndex)
.append(pageBuilder)
.push(projectionIndex)
.invokeVirtual(PageBuilder.class, "getBlockBuilder", BlockBuilder.class, int.class);
filterBlock.ifTrue()
.comment("project_%d(session, block_%s, position, blockBuilder)", projectionIndex, inputChannels)
.invokeVirtual(classDefinition.getType(),
"project_" + projectionIndex,
type(void.class),
ImmutableList.<ParameterizedType>builder()
.add(type(ConnectorSession.class))
.addAll(nCopies(inputChannels.size(), type(Block.class)))
.add(type(int.class))
.add(type(BlockBuilder.class))
.build());
}
loopBody.append(filterBlock);
method.getBody()
.append(loop)
.visitLabel(done)
.comment("return position;")
.getVariable(position)
.retInt();
}
private void generateFilterMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> blocks = toBlockParameters(getInputChannels(filter));
Parameter position = arg("position", int.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(boolean.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(blocks)
.add(position)
.build());
method.comment("Filter: %s", filter.toString());
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable(type(boolean.class), "wasNull");
ByteCodeExpressionVisitor visitor = new ByteCodeExpressionVisitor(
callSiteBinder,
fieldReferenceCompiler(callSiteBinder, position, wasNullVariable),
metadata.getFunctionRegistry());
ByteCodeNode body = filter.accept(visitor, scope);
LabelNode end = new LabelNode("end");
method
.getBody()
.comment("boolean wasNull = false;")
.putVariable(wasNullVariable, false)
.append(body)
.getVariable(wasNullVariable)
.ifFalseGoto(end)
.pop(boolean.class)
.push(false)
.visitLabel(end)
.retBoolean();
}
private void generateProjectMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, String methodName, RowExpression projection)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> inputs = toBlockParameters(getInputChannels(projection));
Parameter position = arg("position", int.class);
Parameter output = arg("output", BlockBuilder.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
methodName,
type(void.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(inputs)
.add(position)
.add(output)
.build());
method.comment("Projection: %s", projection.toString());
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable(type(boolean.class), "wasNull");
ByteCodeBlock body = method.getBody()
.comment("boolean wasNull = false;")
.putVariable(wasNullVariable, false);
ByteCodeExpressionVisitor visitor = new ByteCodeExpressionVisitor(callSiteBinder, fieldReferenceCompiler(callSiteBinder, position, wasNullVariable), metadata.getFunctionRegistry());
body.getVariable(output)
.comment("evaluate projection: " + projection.toString())
.append(projection.accept(visitor, scope))
.append(generateWrite(callSiteBinder, scope, wasNullVariable, projection.getType()))
.ret();
}
private static List<Integer> getInputChannels(Iterable<RowExpression> expressions)
{
TreeSet<Integer> channels = new TreeSet<>();
for (RowExpression expression : Expressions.subExpressions(expressions)) {
if (expression instanceof InputReferenceExpression) {
channels.add(((InputReferenceExpression) expression).getField());
}
}
return ImmutableList.copyOf(channels);
}
private static List<Integer> getInputChannels(RowExpression expression)
{
return getInputChannels(ImmutableList.of(expression));
}
private static List<Parameter> toBlockParameters(List<Integer> inputChannels)
{
ImmutableList.Builder<Parameter> parameters = ImmutableList.builder();
for (int channel : inputChannels) {
parameters.add(arg("block_" + channel, Block.class));
}
return parameters.build();
}
private static ByteCodeNode pushBlockVariables(Scope scope, List<Integer> inputs)
{
ByteCodeBlock block = new ByteCodeBlock();
for (int channel : inputs) {
block.append(scope.getVariable("block_" + channel));
}
return block;
}
private RowExpressionVisitor<Scope, ByteCodeNode> fieldReferenceCompiler(final CallSiteBinder callSiteBinder, final Variable positionVariable, final Variable wasNullVariable)
{
return new RowExpressionVisitor<Scope, ByteCodeNode>()
{
@Override
public ByteCodeNode visitInputReference(InputReferenceExpression node, Scope scope)
{
int field = node.getField();
Type type = node.getType();
Variable block = scope.getVariable("block_" + field);
Class<?> javaType = type.getJavaType();
if (!javaType.isPrimitive() && javaType != Slice.class) {
javaType = Object.class;
}
IfStatement ifStatement = new IfStatement();
ifStatement.condition()
.setDescription(format("block_%d.get%s()", field, type))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Block.class, "isNull", boolean.class, int.class);
ifStatement.ifTrue()
.putVariable(wasNullVariable, true)
.pushJavaDefault(javaType);
String methodName = "get" + Primitives.wrap(javaType).getSimpleName();
ifStatement.ifFalse()
.append(loadConstant(callSiteBinder.bind(type, Type.class)))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Type.class, methodName, javaType, Block.class, int.class);
return ifStatement;
}
@Override
public ByteCodeNode visitCall(CallExpression call, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
@Override
public ByteCodeNode visitConstant(ConstantExpression literal, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
};
}
}
| deciament/presto | presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java | Java | apache-2.0 | 15,098 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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 com.jetbrains.python.inspections.quickfix;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ex.InspectionProfileModifiableModelKt;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.inspections.unresolvedReference.PyUnresolvedReferencesInspection;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class AddIgnoredIdentifierQuickFix implements LocalQuickFix, LowPriorityAction {
public static final String END_WILDCARD = ".*";
@NotNull private final QualifiedName myIdentifier;
private final boolean myIgnoreAllAttributes;
public AddIgnoredIdentifierQuickFix(@NotNull QualifiedName identifier, boolean ignoreAllAttributes) {
myIdentifier = identifier;
myIgnoreAllAttributes = ignoreAllAttributes;
}
@NotNull
@Override
public String getName() {
if (myIgnoreAllAttributes) {
return "Mark all unresolved attributes of '" + myIdentifier + "' as ignored";
}
else {
return "Ignore unresolved reference '" + myIdentifier + "'";
}
}
@NotNull
@Override
public String getFamilyName() {
return "Ignore unresolved reference";
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final PsiElement context = descriptor.getPsiElement();
InspectionProfileModifiableModelKt.modifyAndCommitProjectProfile(project, model -> {
PyUnresolvedReferencesInspection inspection =
(PyUnresolvedReferencesInspection)model.getUnwrappedTool(PyUnresolvedReferencesInspection.class.getSimpleName(), context);
String name = myIdentifier.toString();
if (myIgnoreAllAttributes) {
name += END_WILDCARD;
}
assert inspection != null;
if (!inspection.ignoredIdentifiers.contains(name)) {
inspection.ignoredIdentifiers.add(name);
}
});
}
}
| jk1/intellij-community | python/src/com/jetbrains/python/inspections/quickfix/AddIgnoredIdentifierQuickFix.java | Java | apache-2.0 | 2,763 |
module Vmdb
module Initializer
def self.init
_log.info "- Program Name: #{$PROGRAM_NAME}, PID: #{Process.pid}, ENV['MIQ_GUID']: #{ENV['MIQ_GUID']}, ENV['EVMSERVER']: #{ENV['EVMSERVER']}"
# When these classes are deserialized in ActiveRecord (e.g. EmsEvent, MiqQueue), they need to be preloaded
require 'VMwareWebService/VimTypes'
# UiWorker called in Development Mode
# * command line(rails server)
# * debugger
if defined?(Rails::Server)
# preload_for_worker_role depends on seeding, principally MiqDatabase
EvmDatabase.seed_primordial
MiqUiWorker.preload_for_worker_role
MiqServer.my_server.starting_server_record
MiqServer.my_server.update_attributes(:status => "started")
end
# Rails console needs session store configured
if defined?(Rails::Console)
MiqUiWorker.preload_for_console
end
end
end
end
| NaNi-Z/manageiq | lib/vmdb/initializer.rb | Ruby | apache-2.0 | 937 |
from fabric.api import *
import fabric.contrib.project as project
import os
import shutil
import sys
import SocketServer
from pelican.server import ComplexHTTPRequestHandler
# Local path configuration (can be absolute or relative to fabfile)
env.deploy_path = 'output'
DEPLOY_PATH = env.deploy_path
# Remote server configuration
production = 'root@localhost:22'
dest_path = '/var/www'
# Rackspace Cloud Files configuration settings
env.cloudfiles_username = 'my_rackspace_username'
env.cloudfiles_api_key = 'my_rackspace_api_key'
env.cloudfiles_container = 'my_cloudfiles_container'
# Github Pages configuration
env.github_pages_branch = "master"
# Port for `serve`
PORT = 8000
def clean():
"""Remove generated files"""
if os.path.isdir(DEPLOY_PATH):
shutil.rmtree(DEPLOY_PATH)
os.makedirs(DEPLOY_PATH)
def build():
"""Build local version of site"""
local('pelican -s pelicanconf.py')
def rebuild():
"""`build` with the delete switch"""
local('pelican -d -s pelicanconf.py')
def regenerate():
"""Automatically regenerate site upon file modification"""
local('pelican -r -s pelicanconf.py')
def serve():
"""Serve site at http://localhost:8000/"""
os.chdir(env.deploy_path)
class AddressReuseTCPServer(SocketServer.TCPServer):
allow_reuse_address = True
server = AddressReuseTCPServer(('', PORT), ComplexHTTPRequestHandler)
sys.stderr.write('Serving on port {0} ...\n'.format(PORT))
server.serve_forever()
def reserve():
"""`build`, then `serve`"""
build()
serve()
def preview():
"""Build production version of site"""
local('pelican -s publishconf.py')
def cf_upload():
"""Publish to Rackspace Cloud Files"""
rebuild()
with lcd(DEPLOY_PATH):
local('swift -v -A https://auth.api.rackspacecloud.com/v1.0 '
'-U {cloudfiles_username} '
'-K {cloudfiles_api_key} '
'upload -c {cloudfiles_container} .'.format(**env))
@hosts(production)
def publish():
"""Publish to production via rsync"""
local('pelican -s publishconf.py')
project.rsync_project(
remote_dir=dest_path,
exclude=".DS_Store",
local_dir=DEPLOY_PATH.rstrip('/') + '/',
delete=True,
extra_opts='-c',
)
def gh_pages():
"""Publish to GitHub Pages"""
rebuild()
local("ghp-import -b {github_pages_branch} {deploy_path} -p".format(**env))
| oscarvarto/oscarvarto.github.io | fabfile.py | Python | apache-2.0 | 2,437 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.jvm.actions;
public interface CreateConstructorRequest extends CreateExecutableRequest {
}
| smmribeiro/intellij-community | java/java-analysis-api/src/com/intellij/lang/jvm/actions/CreateConstructorRequest.java | Java | apache-2.0 | 259 |
package com.baidu.disconf.web.service.user.vo;
public class VisitorVo {
private Long id;
private String name;
private String role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "VisitorVo [id=" + id + ", name=" + name + ", role=" + role + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((role == null) ? 0 : role.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
VisitorVo other = (VisitorVo) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (role == null) {
if (other.role != null) {
return false;
}
} else if (!role.equals(other.role)) {
return false;
}
return true;
}
}
| markyao/disconf | disconf-web/src/main/java/com/baidu/disconf/web/service/user/vo/VisitorVo.java | Java | apache-2.0 | 1,901 |
import os.path
import sys
import re
import warnings
import cx_Oracle
from django.db import connection, models
from django.db.backends.util import truncate_name
from django.core.management.color import no_style
from django.db.models.fields import NOT_PROVIDED
from django.db.utils import DatabaseError
# In revision r16016 function get_sequence_name has been transformed into
# method of DatabaseOperations class. To make code backward-compatible we
# need to handle both situations.
try:
from django.db.backends.oracle.base import get_sequence_name\
as original_get_sequence_name
except ImportError:
original_get_sequence_name = None
from south.db import generic
warnings.warn("! WARNING: South's Oracle support is still alpha. "
"Be wary of possible bugs.")
class DatabaseOperations(generic.DatabaseOperations):
"""
Oracle implementation of database operations.
"""
backend_name = 'oracle'
alter_string_set_type = 'ALTER TABLE %(table_name)s MODIFY %(column)s %(type)s %(nullity)s;'
alter_string_set_default = 'ALTER TABLE %(table_name)s MODIFY %(column)s DEFAULT %(default)s;'
add_column_string = 'ALTER TABLE %s ADD %s;'
delete_column_string = 'ALTER TABLE %s DROP COLUMN %s;'
add_constraint_string = 'ALTER TABLE %(table_name)s ADD CONSTRAINT %(constraint)s %(clause)s'
allows_combined_alters = False
has_booleans = False
constraints_dict = {
'P': 'PRIMARY KEY',
'U': 'UNIQUE',
'C': 'CHECK',
'R': 'FOREIGN KEY'
}
def get_sequence_name(self, table_name):
if original_get_sequence_name is None:
return self._get_connection().ops._get_sequence_name(table_name)
else:
return original_get_sequence_name(table_name)
#TODO: This will cause very obscure bugs if anyone uses a column name or string value
# that looks like a column definition (with 'CHECK', 'DEFAULT' and/or 'NULL' in it)
# e.g. "CHECK MATE" varchar(10) DEFAULT 'NULL'
def adj_column_sql(self, col):
# Syntax fixes -- Oracle is picky about clause order
col = re.sub('(?P<constr>CHECK \(.*\))(?P<any>.*)(?P<default>DEFAULT \d+)',
lambda mo: '%s %s%s'%(mo.group('default'), mo.group('constr'), mo.group('any')), col) #syntax fix for boolean/integer field only
col = re.sub('(?P<not_null>(NOT )?NULL) (?P<misc>(.* )?)(?P<default>DEFAULT.+)',
lambda mo: '%s %s %s'%(mo.group('default'),mo.group('not_null'),mo.group('misc') or ''), col) #fix order of NULL/NOT NULL and DEFAULT
return col
def check_meta(self, table_name):
return table_name in [ m._meta.db_table for m in models.get_models() ] #caching provided by Django
def normalize_name(self, name):
"""
Get the properly shortened and uppercased identifier as returned by quote_name(), but without the actual quotes.
"""
nn = self.quote_name(name)
if nn[0] == '"' and nn[-1] == '"':
nn = nn[1:-1]
return nn
@generic.invalidate_table_constraints
def create_table(self, table_name, fields):
qn = self.quote_name(table_name)
columns = []
autoinc_sql = ''
for field_name, field in fields:
col = self.column_sql(table_name, field_name, field)
if not col:
continue
col = self.adj_column_sql(col)
columns.append(col)
if isinstance(field, models.AutoField):
autoinc_sql = connection.ops.autoinc_sql(table_name, field_name)
sql = 'CREATE TABLE %s (%s);' % (qn, ', '.join([col for col in columns]))
self.execute(sql)
if autoinc_sql:
self.execute(autoinc_sql[0])
self.execute(autoinc_sql[1])
@generic.invalidate_table_constraints
def delete_table(self, table_name, cascade=True):
qn = self.quote_name(table_name)
# Note: PURGE is not valid syntax for Oracle 9i (it was added in 10)
if cascade:
self.execute('DROP TABLE %s CASCADE CONSTRAINTS;' % qn)
else:
self.execute('DROP TABLE %s;' % qn)
# If the table has an AutoField a sequence was created.
sequence_sql = """
DECLARE
i INTEGER;
BEGIN
SELECT COUNT(*) INTO i FROM USER_CATALOG
WHERE TABLE_NAME = '%(sq_name)s' AND TABLE_TYPE = 'SEQUENCE';
IF i = 1 THEN
EXECUTE IMMEDIATE 'DROP SEQUENCE "%(sq_name)s"';
END IF;
END;
/""" % {'sq_name': self.get_sequence_name(table_name)}
self.execute(sequence_sql)
@generic.invalidate_table_constraints
def alter_column(self, table_name, name, field, explicit_name=True):
if self.dry_run:
if self.debug:
print ' - no dry run output for alter_column() due to dynamic DDL, sorry'
return
qn = self.quote_name(table_name)
# hook for the field to do any resolution prior to it's attributes being queried
if hasattr(field, 'south_init'):
field.south_init()
field = self._field_sanity(field)
# Add _id or whatever if we need to
field.set_attributes_from_name(name)
if not explicit_name:
name = field.column
qn_col = self.quote_name(name)
# First, change the type
# This will actually also add any CHECK constraints needed,
# since e.g. 'type' for a BooleanField is 'NUMBER(1) CHECK (%(qn_column)s IN (0,1))'
params = {
'table_name':qn,
'column': qn_col,
'type': self._db_type_for_alter_column(field),
'nullity': 'NOT NULL',
'default': 'NULL'
}
if field.null:
params['nullity'] = 'NULL'
if not field.null and field.has_default():
params['default'] = self._default_value_workaround(field.get_default())
sql_templates = [
(self.alter_string_set_type, params),
(self.alter_string_set_default, params.copy()),
]
# drop CHECK constraints. Make sure this is executed before the ALTER TABLE statements
# generated above, since those statements recreate the constraints we delete here.
check_constraints = self._constraints_affecting_columns(table_name, [name], "CHECK")
for constraint in check_constraints:
self.execute(self.delete_check_sql % {
'table': self.quote_name(table_name),
'constraint': self.quote_name(constraint),
})
for sql_template, params in sql_templates:
try:
self.execute(sql_template % params)
except DatabaseError, exc:
description = str(exc)
# Oracle complains if a column is already NULL/NOT NULL
if 'ORA-01442' in description or 'ORA-01451' in description:
# so we just drop NULL/NOT NULL part from target sql and retry
params['nullity'] = ''
sql = sql_template % params
self.execute(sql)
# Oracle also has issues if we try to change a regular column
# to a LOB or vice versa (also REF, object, VARRAY or nested
# table, but these don't come up much in Django apps)
elif 'ORA-22858' in description or 'ORA-22859' in description:
self._alter_column_lob_workaround(table_name, name, field)
else:
raise
def _alter_column_lob_workaround(self, table_name, name, field):
"""
Oracle refuses to change a column type from/to LOB to/from a regular
column. In Django, this shows up when the field is changed from/to
a TextField.
What we need to do instead is:
- Rename the original column
- Add the desired field as new
- Update the table to transfer values from old to new
- Drop old column
"""
renamed = self._generate_temp_name(name)
self.rename_column(table_name, name, renamed)
self.add_column(table_name, name, field, keep_default=False)
self.execute("UPDATE %s set %s=%s" % (
self.quote_name(table_name),
self.quote_name(name),
self.quote_name(renamed),
))
self.delete_column(table_name, renamed)
def _generate_temp_name(self, for_name):
suffix = hex(hash(for_name)).upper()[1:]
return self.normalize_name(for_name + "_" + suffix)
@generic.copy_column_constraints #TODO: Appears to be nulled by the delete decorator below...
@generic.delete_column_constraints
def rename_column(self, table_name, old, new):
if old == new:
# Short-circuit out
return []
self.execute('ALTER TABLE %s RENAME COLUMN %s TO %s;' % (
self.quote_name(table_name),
self.quote_name(old),
self.quote_name(new),
))
@generic.invalidate_table_constraints
def add_column(self, table_name, name, field, keep_default=True):
sql = self.column_sql(table_name, name, field)
sql = self.adj_column_sql(sql)
if sql:
params = (
self.quote_name(table_name),
sql
)
sql = self.add_column_string % params
self.execute(sql)
# Now, drop the default if we need to
if not keep_default and field.default is not None:
field.default = NOT_PROVIDED
self.alter_column(table_name, name, field, explicit_name=False)
def delete_column(self, table_name, name):
return super(DatabaseOperations, self).delete_column(self.quote_name(table_name), name)
def lookup_constraint(self, db_name, table_name, column_name=None):
if column_name:
# Column names in the constraint cache come from the database,
# make sure we use the properly shortened/uppercased version
# for lookup.
column_name = self.normalize_name(column_name)
return super(DatabaseOperations, self).lookup_constraint(db_name, table_name, column_name)
def _constraints_affecting_columns(self, table_name, columns, type="UNIQUE"):
if columns:
columns = [self.normalize_name(c) for c in columns]
return super(DatabaseOperations, self)._constraints_affecting_columns(table_name, columns, type)
def _field_sanity(self, field):
"""
This particular override stops us sending DEFAULTs for BooleanField.
"""
if isinstance(field, models.BooleanField) and field.has_default():
field.default = int(field.to_python(field.get_default()))
return field
def _default_value_workaround(self, value):
from datetime import date,time,datetime
if isinstance(value, (date,time,datetime)):
return "'%s'" % value
else:
return super(DatabaseOperations, self)._default_value_workaround(value)
def _fill_constraint_cache(self, db_name, table_name):
self._constraint_cache.setdefault(db_name, {})
self._constraint_cache[db_name][table_name] = {}
rows = self.execute("""
SELECT user_cons_columns.constraint_name,
user_cons_columns.column_name,
user_constraints.constraint_type
FROM user_constraints
JOIN user_cons_columns ON
user_constraints.table_name = user_cons_columns.table_name AND
user_constraints.constraint_name = user_cons_columns.constraint_name
WHERE user_constraints.table_name = '%s'
""" % self.normalize_name(table_name))
for constraint, column, kind in rows:
self._constraint_cache[db_name][table_name].setdefault(column, set())
self._constraint_cache[db_name][table_name][column].add((self.constraints_dict[kind], constraint))
return
| edisonlz/fruit | web_project/base/site-packages/south/db/oracle.py | Python | apache-2.0 | 12,431 |
package org.opencv.samples.puzzle15;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.core.Point;
import org.opencv.imgproc.Imgproc;
import android.util.Log;
/**
* This class is a controller for puzzle game.
* It converts the image from Camera into the shuffled image
*/
public class Puzzle15Processor {
private static final int GRID_SIZE = 4;
private static final int GRID_AREA = GRID_SIZE * GRID_SIZE;
private static final int GRID_EMPTY_INDEX = GRID_AREA - 1;
private static final String TAG = "Puzzle15Processor";
private static final Scalar GRID_EMPTY_COLOR = new Scalar(0x33, 0x33, 0x33, 0xFF);
private int[] mIndexes;
private int[] mTextWidths;
private int[] mTextHeights;
private Mat mRgba15;
private Mat[] mCells15;
private boolean mShowTileNumbers = true;
public Puzzle15Processor() {
mTextWidths = new int[GRID_AREA];
mTextHeights = new int[GRID_AREA];
mIndexes = new int [GRID_AREA];
for (int i = 0; i < GRID_AREA; i++)
mIndexes[i] = i;
}
/* this method is intended to make processor prepared for a new game */
public synchronized void prepareNewGame() {
do {
shuffle(mIndexes);
} while (!isPuzzleSolvable());
}
/* This method is to make the processor know the size of the frames that
* will be delivered via puzzleFrame.
* If the frames will be different size - then the result is unpredictable
*/
public synchronized void prepareGameSize(int width, int height) {
mRgba15 = new Mat(height, width, CvType.CV_8UC4);
mCells15 = new Mat[GRID_AREA];
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
int k = i * GRID_SIZE + j;
mCells15[k] = mRgba15.submat(i * height / GRID_SIZE, (i + 1) * height / GRID_SIZE, j * width / GRID_SIZE, (j + 1) * width / GRID_SIZE);
}
}
for (int i = 0; i < GRID_AREA; i++) {
Size s = Imgproc.getTextSize(Integer.toString(i + 1), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, 2, null);
mTextHeights[i] = (int) s.height;
mTextWidths[i] = (int) s.width;
}
}
/* this method to be called from the outside. it processes the frame and shuffles
* the tiles as specified by mIndexes array
*/
public synchronized Mat puzzleFrame(Mat inputPicture) {
Mat[] cells = new Mat[GRID_AREA];
int rows = inputPicture.rows();
int cols = inputPicture.cols();
rows = rows - rows%4;
cols = cols - cols%4;
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
int k = i * GRID_SIZE + j;
cells[k] = inputPicture.submat(i * inputPicture.rows() / GRID_SIZE, (i + 1) * inputPicture.rows() / GRID_SIZE, j * inputPicture.cols()/ GRID_SIZE, (j + 1) * inputPicture.cols() / GRID_SIZE);
}
}
rows = rows - rows%4;
cols = cols - cols%4;
// copy shuffled tiles
for (int i = 0; i < GRID_AREA; i++) {
int idx = mIndexes[i];
if (idx == GRID_EMPTY_INDEX)
mCells15[i].setTo(GRID_EMPTY_COLOR);
else {
cells[idx].copyTo(mCells15[i]);
if (mShowTileNumbers) {
Imgproc.putText(mCells15[i], Integer.toString(1 + idx), new Point((cols / GRID_SIZE - mTextWidths[idx]) / 2,
(rows / GRID_SIZE + mTextHeights[idx]) / 2), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, new Scalar(255, 0, 0, 255), 2);
}
}
}
for (int i = 0; i < GRID_AREA; i++)
cells[i].release();
drawGrid(cols, rows, mRgba15);
return mRgba15;
}
public void toggleTileNumbers() {
mShowTileNumbers = !mShowTileNumbers;
}
public void deliverTouchEvent(int x, int y) {
int rows = mRgba15.rows();
int cols = mRgba15.cols();
int row = (int) Math.floor(y * GRID_SIZE / rows);
int col = (int) Math.floor(x * GRID_SIZE / cols);
if (row < 0 || row >= GRID_SIZE || col < 0 || col >= GRID_SIZE) {
Log.e(TAG, "It is not expected to get touch event outside of picture");
return ;
}
int idx = row * GRID_SIZE + col;
int idxtoswap = -1;
// left
if (idxtoswap < 0 && col > 0)
if (mIndexes[idx - 1] == GRID_EMPTY_INDEX)
idxtoswap = idx - 1;
// right
if (idxtoswap < 0 && col < GRID_SIZE - 1)
if (mIndexes[idx + 1] == GRID_EMPTY_INDEX)
idxtoswap = idx + 1;
// top
if (idxtoswap < 0 && row > 0)
if (mIndexes[idx - GRID_SIZE] == GRID_EMPTY_INDEX)
idxtoswap = idx - GRID_SIZE;
// bottom
if (idxtoswap < 0 && row < GRID_SIZE - 1)
if (mIndexes[idx + GRID_SIZE] == GRID_EMPTY_INDEX)
idxtoswap = idx + GRID_SIZE;
// swap
if (idxtoswap >= 0) {
synchronized (this) {
int touched = mIndexes[idx];
mIndexes[idx] = mIndexes[idxtoswap];
mIndexes[idxtoswap] = touched;
}
}
}
private void drawGrid(int cols, int rows, Mat drawMat) {
for (int i = 1; i < GRID_SIZE; i++) {
Imgproc.line(drawMat, new Point(0, i * rows / GRID_SIZE), new Point(cols, i * rows / GRID_SIZE), new Scalar(0, 255, 0, 255), 3);
Imgproc.line(drawMat, new Point(i * cols / GRID_SIZE, 0), new Point(i * cols / GRID_SIZE, rows), new Scalar(0, 255, 0, 255), 3);
}
}
private static void shuffle(int[] array) {
for (int i = array.length; i > 1; i--) {
int temp = array[i - 1];
int randIx = (int) (Math.random() * i);
array[i - 1] = array[randIx];
array[randIx] = temp;
}
}
private boolean isPuzzleSolvable() {
int sum = 0;
for (int i = 0; i < GRID_AREA; i++) {
if (mIndexes[i] == GRID_EMPTY_INDEX)
sum += (i / GRID_SIZE) + 1;
else {
int smaller = 0;
for (int j = i + 1; j < GRID_AREA; j++) {
if (mIndexes[j] < mIndexes[i])
smaller++;
}
sum += smaller;
}
}
return sum % 2 == 0;
}
}
| apavlenko/opencv | samples/android/15-puzzle/src/org/opencv/samples/puzzle15/Puzzle15Processor.java | Java | bsd-3-clause | 6,624 |
// Copyright 2013 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 "apps/app_lifetime_monitor_factory.h"
#include "apps/app_lifetime_monitor.h"
#include "apps/app_window_registry.h"
#include "chrome/browser/profiles/profile.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/extensions_browser_client.h"
namespace apps {
// static
AppLifetimeMonitor* AppLifetimeMonitorFactory::GetForProfile(Profile* profile) {
return static_cast<AppLifetimeMonitor*>(
GetInstance()->GetServiceForBrowserContext(profile, false));
}
AppLifetimeMonitorFactory* AppLifetimeMonitorFactory::GetInstance() {
return Singleton<AppLifetimeMonitorFactory>::get();
}
AppLifetimeMonitorFactory::AppLifetimeMonitorFactory()
: BrowserContextKeyedServiceFactory(
"AppLifetimeMonitor",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(AppWindowRegistry::Factory::GetInstance());
}
AppLifetimeMonitorFactory::~AppLifetimeMonitorFactory() {}
KeyedService* AppLifetimeMonitorFactory::BuildServiceInstanceFor(
content::BrowserContext* profile) const {
return new AppLifetimeMonitor(static_cast<Profile*>(profile));
}
bool AppLifetimeMonitorFactory::ServiceIsCreatedWithBrowserContext() const {
return true;
}
content::BrowserContext* AppLifetimeMonitorFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return extensions::ExtensionsBrowserClient::Get()->
GetOriginalContext(context);
}
} // namespace apps
| 7kbird/chrome | apps/app_lifetime_monitor_factory.cc | C++ | bsd-3-clause | 1,638 |
// Copyright (c) 2011 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 "chrome/browser/ui/views/status_icons/status_tray_linux.h"
#include "build/build_config.h"
#if !defined(OS_CHROMEOS)
#include "chrome/browser/ui/views/status_icons/status_icon_linux_wrapper.h"
#include "ui/views/linux_ui/linux_ui.h"
StatusTrayLinux::StatusTrayLinux() {
}
StatusTrayLinux::~StatusTrayLinux() {
}
StatusIcon* StatusTrayLinux::CreatePlatformStatusIcon(
StatusIconType type,
const gfx::ImageSkia& image,
const base::string16& tool_tip) {
return StatusIconLinuxWrapper::CreateWrappedStatusIcon(image, tool_tip);
}
StatusTray* StatusTray::Create() {
const views::LinuxUI* linux_ui = views::LinuxUI::instance();
// Only create a status tray if we can actually create status icons.
if (linux_ui && linux_ui->IsStatusIconSupported())
return new StatusTrayLinux();
return NULL;
}
#else // defined(OS_CHROMEOS)
StatusTray* StatusTray::Create() {
return NULL;
}
#endif
| XiaosongWei/chromium-crosswalk | chrome/browser/ui/views/status_icons/status_tray_linux.cc | C++ | bsd-3-clause | 1,089 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The production x >>>= y is the same as x = x >>> y
*
* @path ch11/11.13/11.13.2/S11.13.2_A4.8_T1.3.js
* @description Type(x) and Type(y) vary between primitive string and String object
*/
//CHECK#1
x = "1";
x >>>= "1";
if (x !== 0) {
$ERROR('#1: x = "1"; x >>>= "1"; x === 0. Actual: ' + (x));
}
//CHECK#2
x = new String("1");
x >>>= "1";
if (x !== 0) {
$ERROR('#2: x = new String("1"); x >>>= "1"; x === 0. Actual: ' + (x));
}
//CHECK#3
x = "1";
x >>>= new String("1");
if (x !== 0) {
$ERROR('#3: x = "1"; x >>>= new String("1"); x === 0. Actual: ' + (x));
}
//CHECK#4
x = new String("1");
x >>>= new String("1");
if (x !== 0) {
$ERROR('#4: x = new String("1"); x >>>= new String("1"); x === 0. Actual: ' + (x));
}
//CHECK#5
x = "x";
x >>>= "1";
if (x !== 0) {
$ERROR('#5: x = "x"; x >>>= "1"; x === 0. Actual: ' + (x));
}
//CHECK#6
x = "1";
x >>>= "x";
if (x !== 1) {
$ERROR('#6: x = "1"; x >>>= "x"; x === 1. Actual: ' + (x));
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch11/11.13/11.13.2/S11.13.2_A4.8_T1.3.js | JavaScript | bsd-3-clause | 1,023 |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* @path ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-258.js
* @description Object.create - 'get' property of one property in 'Properties' is the primitive value null (8.10.5 step 7.b)
*/
function testcase() {
try {
Object.create({}, {
prop: {
get: null
}
});
return false;
} catch (e) {
return (e instanceof TypeError);
}
}
runTestCase(testcase);
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-258.js | JavaScript | bsd-3-clause | 543 |
module.exports = require('./lib/socket.io'); | thetomcraig/redwood | web/node_modules/socket.io/index.js | JavaScript | isc | 44 |
var _complement = require('./internal/_complement');
var _curry2 = require('./internal/_curry2');
var filter = require('./filter');
/**
* Similar to `filter`, except that it keeps only values for which the given predicate
* function returns falsy. The predicate function is passed one argument: *(value)*.
*
* Acts as a transducer if a transformer is given in list position.
* @see R.transduce
*
* @func
* @memberOf R
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} The new filtered array.
* @see R.filter
* @example
*
* var isOdd = function(n) {
* return n % 2 === 1;
* };
* R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]
*/
module.exports = _curry2(function reject(fn, list) {
return filter(_complement(fn), list);
});
| concertcoder/leaky-ionic-app | www/lib/ramda/src/reject.js | JavaScript | mit | 899 |
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/Asana-Math/Size1/Regular/Main.js
*
* Copyright (c) 2013-2014 The MathJax Consortium
*
* 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.
*/
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['AsanaMathJax_Size1'] = {
directory: 'Size1/Regular',
family: 'AsanaMathJax_Size1',
testString: '\u0302\u0303\u0305\u0306\u030C\u0332\u0333\u033F\u2016\u2044\u2045\u2046\u20D6\u20D7\u220F',
0x20: [0,0,249,0,0],
0x28: [981,490,399,84,360],
0x29: [981,490,399,40,316],
0x5B: [984,492,350,84,321],
0x5D: [984,492,350,84,321],
0x7B: [981,490,362,84,328],
0x7C: [908,367,241,86,156],
0x7D: [981,490,362,84,328],
0x302: [783,-627,453,0,453],
0x303: [763,-654,700,0,701],
0x305: [587,-542,510,0,511],
0x306: [664,-506,383,0,384],
0x30C: [783,-627,736,0,737],
0x332: [-130,175,510,0,511],
0x333: [-130,283,510,0,511],
0x33F: [695,-542,510,0,511],
0x2016: [908,367,436,86,351],
0x2044: [742,463,382,-69,383],
0x2045: [943,401,353,64,303],
0x2046: [943,401,358,30,269],
0x20D6: [790,-519,807,0,807],
0x20D7: [790,-519,807,0,807],
0x220F: [901,448,1431,78,1355],
0x2210: [901,448,1431,78,1355],
0x2211: [893,446,1224,89,1135],
0x221A: [1280,0,770,63,803],
0x2229: [1039,520,1292,124,1169],
0x222B: [1310,654,1000,54,1001],
0x222C: [1310,654,1659,54,1540],
0x222D: [1310,654,2198,54,2079],
0x222E: [1310,654,1120,54,1001],
0x222F: [1310,654,1659,54,1540],
0x2230: [1310,654,2198,54,2079],
0x2231: [1310,654,1120,54,1001],
0x2232: [1310,654,1146,80,1027],
0x2233: [1310,654,1120,54,1001],
0x22C0: [1040,519,1217,85,1132],
0x22C1: [1040,519,1217,85,1132],
0x22C2: [1039,520,1292,124,1169],
0x22C3: [1039,520,1292,124,1169],
0x2308: [980,490,390,84,346],
0x2309: [980,490,390,84,346],
0x230A: [980,490,390,84,346],
0x230B: [980,490,390,84,346],
0x23B4: [755,-518,977,0,978],
0x23B5: [-238,475,977,0,978],
0x23DC: [821,-545,972,0,973],
0x23DD: [-545,821,972,0,973],
0x23DE: [789,-545,1572,51,1522],
0x23DF: [-545,789,1572,51,1522],
0x23E0: [755,-545,1359,0,1360],
0x23E1: [-545,755,1359,0,1360],
0x27C5: [781,240,450,53,397],
0x27C6: [781,240,450,53,397],
0x27E6: [684,341,502,84,473],
0x27E7: [684,341,502,84,473],
0x27E8: [681,340,422,53,371],
0x27E9: [681,340,422,53,371],
0x27EA: [681,340,605,53,554],
0x27EB: [681,340,605,53,554],
0x29FC: [915,457,518,50,469],
0x29FD: [915,457,518,49,469],
0x2A00: [1100,550,1901,124,1778],
0x2A01: [1100,550,1901,124,1778],
0x2A02: [1100,550,1901,124,1778],
0x2A03: [1039,520,1292,124,1169],
0x2A04: [1039,520,1292,124,1169],
0x2A05: [1024,513,1292,124,1169],
0x2A06: [1024,513,1292,124,1169],
0x2A07: [1039,520,1415,86,1330],
0x2A08: [1039,520,1415,86,1330],
0x2A09: [888,445,1581,124,1459],
0x2A0C: [1310,654,2736,54,2617],
0x2A0D: [1310,654,1120,54,1001],
0x2A0E: [1310,654,1120,54,1001],
0x2A0F: [1310,654,1120,54,1001],
0x2A10: [1310,654,1120,54,1001],
0x2A11: [1310,654,1182,54,1063],
0x2A12: [1310,654,1120,54,1001],
0x2A13: [1310,654,1120,54,1001],
0x2A14: [1310,654,1120,54,1001],
0x2A15: [1310,654,1120,54,1001],
0x2A16: [1310,654,1120,54,1001],
0x2A17: [1310,654,1431,54,1362],
0x2A18: [1310,654,1120,54,1001],
0x2A19: [1310,654,1120,54,1001],
0x2A1A: [1310,654,1120,54,1001],
0x2A1B: [1471,654,1130,54,1011],
0x2A1C: [1471,654,1156,80,1037]
};
MathJax.Callback.Queue(
["initFont",MathJax.OutputJax["HTML-CSS"],"AsanaMathJax_Size1"],
["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Size1/Regular/Main.js"]
);
| uva/mathjax-rails-assets | vendor/assets/javascripts/jax/output/HTML-CSS/fonts/Asana-Math/Size1/Regular/Main.js | JavaScript | mit | 4,163 |
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/Neo-Euler/Variants/Regular/Main.js
*
* Copyright (c) 2013-2014 The MathJax Consortium
*
* 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.
*/
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['NeoEulerMathJax_Variants'] = {
directory: 'Variants/Regular',
family: 'NeoEulerMathJax_Variants',
testString: '\u00A0\u2032\u2033\u2034\u2035\u2036\u2037\u2057\uE200\uE201\uE202\uE203\uE204\uE205\uE206',
0x20: [0,0,333,0,0],
0xA0: [0,0,333,0,0],
0x2032: [559,-41,329,48,299],
0x2033: [559,-41,640,48,610],
0x2034: [559,-41,950,48,920],
0x2035: [559,-41,329,48,299],
0x2036: [559,-41,640,48,610],
0x2037: [559,-41,950,48,919],
0x2057: [559,-41,1260,48,1230],
0xE200: [493,13,501,41,456],
0xE201: [469,1,501,46,460],
0xE202: [474,-1,501,59,485],
0xE203: [474,182,501,38,430],
0xE204: [476,192,501,10,482],
0xE205: [458,184,501,47,441],
0xE206: [700,13,501,45,471],
0xE207: [468,181,501,37,498],
0xE208: [706,10,501,40,461],
0xE209: [470,182,501,27,468]
};
MathJax.Callback.Queue(
["initFont",MathJax.OutputJax["HTML-CSS"],"NeoEulerMathJax_Variants"],
["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Variants/Regular/Main.js"]
);
| uva/mathjax-rails-assets | vendor/assets/javascripts/jax/output/HTML-CSS/fonts/Neo-Euler/Variants/Regular/Main.js | JavaScript | mit | 1,809 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v9.0.3
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("./context/context");
var LINE_SEPARATOR = '\r\n';
var XmlFactory = (function () {
function XmlFactory() {
}
XmlFactory.prototype.createXml = function (xmlElement, booleanTransformer) {
var _this = this;
var props = "";
if (xmlElement.properties) {
if (xmlElement.properties.prefixedAttributes) {
xmlElement.properties.prefixedAttributes.forEach(function (prefixedSet) {
Object.keys(prefixedSet.map).forEach(function (key) {
props += _this.returnAttributeIfPopulated(prefixedSet.prefix + key, prefixedSet.map[key], booleanTransformer);
});
});
}
if (xmlElement.properties.rawMap) {
Object.keys(xmlElement.properties.rawMap).forEach(function (key) {
props += _this.returnAttributeIfPopulated(key, xmlElement.properties.rawMap[key], booleanTransformer);
});
}
}
var result = "<" + xmlElement.name + props;
if (!xmlElement.children && !xmlElement.textNode) {
return result + "/>" + LINE_SEPARATOR;
}
if (xmlElement.textNode) {
return result + ">" + xmlElement.textNode + "</" + xmlElement.name + ">" + LINE_SEPARATOR;
}
result += ">" + LINE_SEPARATOR;
xmlElement.children.forEach(function (it) {
result += _this.createXml(it, booleanTransformer);
});
return result + "</" + xmlElement.name + ">" + LINE_SEPARATOR;
};
XmlFactory.prototype.returnAttributeIfPopulated = function (key, value, booleanTransformer) {
if (!value) {
return "";
}
var xmlValue = value;
if ((typeof (value) === 'boolean')) {
if (booleanTransformer) {
xmlValue = booleanTransformer(value);
}
}
xmlValue = '"' + xmlValue + '"';
return " " + key + "=" + xmlValue;
};
return XmlFactory;
}());
XmlFactory = __decorate([
context_1.Bean('xmlFactory')
], XmlFactory);
exports.XmlFactory = XmlFactory;
| extend1994/cdnjs | ajax/libs/ag-grid/9.0.4/lib/xmlFactory.js | JavaScript | mit | 2,992 |
/**
* High performant way to check whether an element with a specific class name is in the given document
* Optimized for being heavily executed
* Unleashes the power of live node lists
*
* @param {Object} doc The document object of the context where to check
* @param {String} tagName Upper cased tag name
* @example
* wysihtml5.dom.hasElementWithClassName(document, "foobar");
*/
(function(wysihtml5) {
var LIVE_CACHE = {},
DOCUMENT_IDENTIFIER = 1;
function _getDocumentIdentifier(doc) {
return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++);
}
wysihtml5.dom.hasElementWithClassName = function(doc, className) {
// getElementsByClassName is not supported by IE<9
// but is sometimes mocked via library code (which then doesn't return live node lists)
if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) {
return !!doc.querySelector("." + className);
}
var key = _getDocumentIdentifier(doc) + ":" + className,
cacheEntry = LIVE_CACHE[key];
if (!cacheEntry) {
cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className);
}
return cacheEntry.length > 0;
};
})(wysihtml5);
| StepicOrg/wysihtml5 | src/dom/has_element_with_class_name.js | JavaScript | mit | 1,231 |
<?php
/*
Plugin Name: MediaFire API
Description: Check links to files hosted on MediaFire.
Version: 1.0
Author: Janis Elsts
ModuleID: mediafire-checker
ModuleCategory: checker
ModuleContext: on-demand
ModuleLazyInit: true
ModuleClassName: blcMediaFireChecker
ModulePriority: 100
ModuleCheckerUrlPattern: @^http://(?:www\.)?mediafire\.com/(?:(?:download\.php)?\?|download/)([0-9a-zA-Z]{11,20})(?:$|[^0-9a-zA-Z])@
*/
/**
* MediaFire link checker.
*
* @package Broken Link Checker
* @author Janis Elsts
* @access public
*/
class blcMediaFireChecker extends blcChecker {
/**
* Determine if the checker can parse a specific URL.
* Always returns true because the ModuleCheckerUrlPattern header constitutes sufficient verification.
*
* @param string $url
* @param array $parsed
* @return bool True.
*/
function can_check($url, $parsed){
return true;
}
/**
* Check a MediaFire link.
*
* @param string $url
* @return array
*/
function check($url){
$result = array(
'final_url' => $url,
'redirect_count' => 0,
'timeout' => false,
'broken' => false,
'log' => "<em>(Using MediaFire checker module)</em>\n\n",
'http_code' => 0,
'result_hash' => '',
);
//URLs like http://www.mediafire.com/download.php?03mj0mwmnnm are technically valid,
//but they introduce unnecessary redirects.
$url = str_replace('download.php','', $url);
//Since MediaFire doesn't have an API, we just send a HEAD request
//and try do divine the file state from the response headers.
$start = microtime_float();
$rez = $this->head($url);
$result['request_duration'] = microtime_float() - $start;
if ( is_wp_error($rez) ){
//An unexpected error.
$result['broken'] = true;
$result['log'] .= "Error : " . $rez->get_error_message();
if ( $data = $rez->get_error_data() ){
$result['log'] .= "\n\nError data : " . print_r($data, true);
}
} else {
$result['http_code'] = intval($rez['response']['code']);
if ( $result['http_code'] == 200 ){
//200 - OK
$result['broken'] = false;
$result['log'] .= "File OK";
} elseif ( isset($rez['headers']['location']) ) {
//Redirect = either an error or a redirect to the full file URL.
//For errors, the redirect URL is structured like this : '/error.php?errno=320'.
//The 'errno' argument contains an (undocumented) error code.
$result['broken'] = true;
if ( strpos($rez['headers']['location'], '/download/') !== false ) {
$result['broken'] = false;
$result['http_code'] = 200;
$result['log'] .= "File OK";
$result['log'] .= "\nFull URL: " . $rez['headers']['location'];
} elseif ( strpos($rez['headers']['location'], 'errno=320') !== false ){
$result['status_code'] = BLC_LINK_STATUS_ERROR;
$result['status_text'] = __('Not Found', 'broken-link-checker');
$result['http_code'] = 0;
$result['log'] .= "The file is invalid or has been removed.";
} elseif ( strpos($rez['headers']['location'], 'errno=378') !== false ) {
$result['status_code'] = BLC_LINK_STATUS_ERROR;
$result['status_text'] = __('Not Found', 'broken-link-checker');
$result['http_code'] = 0;
$result['log'] .= "The file has been removed due to a violation of MediaFire ToS.";
} elseif ( strpos($rez['headers']['location'], 'errno=388') !== false ) {
$result['status_code'] = BLC_LINK_STATUS_WARNING;
$result['status_text'] = __('Permission Denied', 'broken-link-checker');
$result['http_code'] = 0;
$result['log'] .= "Permission denied. Most likely the plugin sent too many requests too quickly. Try again later.";
} else {
$result['status_code'] = BLC_LINK_STATUS_INFO;
$result['status_text'] = __('Unknown Error', 'broken-link-checker');
$result['log'] .= "Unknown error.\n\n";
foreach($rez['headers'] as $name => $value){
$result['log'] .= sprintf("%s: %s\n", $name, $value);
}
}
} else {
$result['log'] .= "Unknown error.\n\n" . implode("\n",$rez['headers']);
}
}
//Generate the result hash (used for detecting false positives)
$result['result_hash'] = implode('|', array(
'mediafire',
$result['http_code'],
$result['broken']?'broken':'0',
$result['timeout']?'timeout':'0'
));
return $result;
}
/**
* Perform a HEAD request to the specified URL.
*
* Note :
*
* Since the MediaFire checker works by parsing the "Location" header, redirect following
* _must_ be disabled. This can become a problem on servers where WP is forced to fall back
* on using WP_Http_Fopen which ignores the 'redirection' flag. WP_Http_Fsockopen would work,
* but it has the lowest priority of all transports.
*
* Alas, there is no way to reliably influence which transport is chosen - the WP_Http::_getTransport
* function caches the available choices, so plugins can disable individual transports only during
* its first run. Therefore, we must pick the best transport manually.
*
* @param string $url
* @return array|WP_Error
*/
function head($url){
$conf = blc_get_configuration();
$args = array(
'timeout' => $conf->options['timeout'],
'redirection' => 0,
'_redirection' => 0, //Internal flag that turns off redirect handling. See WP_Http::handle_redirects()
);
return wp_remote_head($url, $args);
}
}
| SayenkoDesign/playground | wp-content/plugins/broken-link-checker/modules/extras/mediafire.php | PHP | gpl-2.0 | 5,392 |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# create a scene with one of each cell type
# Voxel
voxelPoints = vtk.vtkPoints()
voxelPoints.SetNumberOfPoints(8)
voxelPoints.InsertPoint(0,0,0,0)
voxelPoints.InsertPoint(1,1,0,0)
voxelPoints.InsertPoint(2,0,1,0)
voxelPoints.InsertPoint(3,1,1,0)
voxelPoints.InsertPoint(4,0,0,1)
voxelPoints.InsertPoint(5,1,0,1)
voxelPoints.InsertPoint(6,0,1,1)
voxelPoints.InsertPoint(7,1,1,1)
aVoxel = vtk.vtkVoxel()
aVoxel.GetPointIds().SetId(0,0)
aVoxel.GetPointIds().SetId(1,1)
aVoxel.GetPointIds().SetId(2,2)
aVoxel.GetPointIds().SetId(3,3)
aVoxel.GetPointIds().SetId(4,4)
aVoxel.GetPointIds().SetId(5,5)
aVoxel.GetPointIds().SetId(6,6)
aVoxel.GetPointIds().SetId(7,7)
aVoxelGrid = vtk.vtkUnstructuredGrid()
aVoxelGrid.Allocate(1,1)
aVoxelGrid.InsertNextCell(aVoxel.GetCellType(),aVoxel.GetPointIds())
aVoxelGrid.SetPoints(voxelPoints)
aVoxelMapper = vtk.vtkDataSetMapper()
aVoxelMapper.SetInputData(aVoxelGrid)
aVoxelActor = vtk.vtkActor()
aVoxelActor.SetMapper(aVoxelMapper)
aVoxelActor.GetProperty().BackfaceCullingOn()
# Hexahedron
hexahedronPoints = vtk.vtkPoints()
hexahedronPoints.SetNumberOfPoints(8)
hexahedronPoints.InsertPoint(0,0,0,0)
hexahedronPoints.InsertPoint(1,1,0,0)
hexahedronPoints.InsertPoint(2,1,1,0)
hexahedronPoints.InsertPoint(3,0,1,0)
hexahedronPoints.InsertPoint(4,0,0,1)
hexahedronPoints.InsertPoint(5,1,0,1)
hexahedronPoints.InsertPoint(6,1,1,1)
hexahedronPoints.InsertPoint(7,0,1,1)
aHexahedron = vtk.vtkHexahedron()
aHexahedron.GetPointIds().SetId(0,0)
aHexahedron.GetPointIds().SetId(1,1)
aHexahedron.GetPointIds().SetId(2,2)
aHexahedron.GetPointIds().SetId(3,3)
aHexahedron.GetPointIds().SetId(4,4)
aHexahedron.GetPointIds().SetId(5,5)
aHexahedron.GetPointIds().SetId(6,6)
aHexahedron.GetPointIds().SetId(7,7)
aHexahedronGrid = vtk.vtkUnstructuredGrid()
aHexahedronGrid.Allocate(1,1)
aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(),aHexahedron.GetPointIds())
aHexahedronGrid.SetPoints(hexahedronPoints)
aHexahedronMapper = vtk.vtkDataSetMapper()
aHexahedronMapper.SetInputData(aHexahedronGrid)
aHexahedronActor = vtk.vtkActor()
aHexahedronActor.SetMapper(aHexahedronMapper)
aHexahedronActor.AddPosition(2,0,0)
aHexahedronActor.GetProperty().BackfaceCullingOn()
# Tetra
tetraPoints = vtk.vtkPoints()
tetraPoints.SetNumberOfPoints(4)
tetraPoints.InsertPoint(0,0,0,0)
tetraPoints.InsertPoint(1,1,0,0)
tetraPoints.InsertPoint(2,.5,1,0)
tetraPoints.InsertPoint(3,.5,.5,1)
aTetra = vtk.vtkTetra()
aTetra.GetPointIds().SetId(0,0)
aTetra.GetPointIds().SetId(1,1)
aTetra.GetPointIds().SetId(2,2)
aTetra.GetPointIds().SetId(3,3)
aTetraGrid = vtk.vtkUnstructuredGrid()
aTetraGrid.Allocate(1,1)
aTetraGrid.InsertNextCell(aTetra.GetCellType(),aTetra.GetPointIds())
aTetraGrid.SetPoints(tetraPoints)
aTetraMapper = vtk.vtkDataSetMapper()
aTetraMapper.SetInputData(aTetraGrid)
aTetraActor = vtk.vtkActor()
aTetraActor.SetMapper(aTetraMapper)
aTetraActor.AddPosition(4,0,0)
aTetraActor.GetProperty().BackfaceCullingOn()
# Wedge
wedgePoints = vtk.vtkPoints()
wedgePoints.SetNumberOfPoints(6)
wedgePoints.InsertPoint(0,0,1,0)
wedgePoints.InsertPoint(1,0,0,0)
wedgePoints.InsertPoint(2,0,.5,.5)
wedgePoints.InsertPoint(3,1,1,0)
wedgePoints.InsertPoint(4,1,0,0)
wedgePoints.InsertPoint(5,1,.5,.5)
aWedge = vtk.vtkWedge()
aWedge.GetPointIds().SetId(0,0)
aWedge.GetPointIds().SetId(1,1)
aWedge.GetPointIds().SetId(2,2)
aWedge.GetPointIds().SetId(3,3)
aWedge.GetPointIds().SetId(4,4)
aWedge.GetPointIds().SetId(5,5)
aWedgeGrid = vtk.vtkUnstructuredGrid()
aWedgeGrid.Allocate(1,1)
aWedgeGrid.InsertNextCell(aWedge.GetCellType(),aWedge.GetPointIds())
aWedgeGrid.SetPoints(wedgePoints)
aWedgeMapper = vtk.vtkDataSetMapper()
aWedgeMapper.SetInputData(aWedgeGrid)
aWedgeActor = vtk.vtkActor()
aWedgeActor.SetMapper(aWedgeMapper)
aWedgeActor.AddPosition(6,0,0)
aWedgeActor.GetProperty().BackfaceCullingOn()
# Pyramid
pyramidPoints = vtk.vtkPoints()
pyramidPoints.SetNumberOfPoints(5)
pyramidPoints.InsertPoint(0,0,0,0)
pyramidPoints.InsertPoint(1,1,0,0)
pyramidPoints.InsertPoint(2,1,1,0)
pyramidPoints.InsertPoint(3,0,1,0)
pyramidPoints.InsertPoint(4,.5,.5,1)
aPyramid = vtk.vtkPyramid()
aPyramid.GetPointIds().SetId(0,0)
aPyramid.GetPointIds().SetId(1,1)
aPyramid.GetPointIds().SetId(2,2)
aPyramid.GetPointIds().SetId(3,3)
aPyramid.GetPointIds().SetId(4,4)
aPyramidGrid = vtk.vtkUnstructuredGrid()
aPyramidGrid.Allocate(1,1)
aPyramidGrid.InsertNextCell(aPyramid.GetCellType(),aPyramid.GetPointIds())
aPyramidGrid.SetPoints(pyramidPoints)
aPyramidMapper = vtk.vtkDataSetMapper()
aPyramidMapper.SetInputData(aPyramidGrid)
aPyramidActor = vtk.vtkActor()
aPyramidActor.SetMapper(aPyramidMapper)
aPyramidActor.AddPosition(8,0,0)
aPyramidActor.GetProperty().BackfaceCullingOn()
# Pixel
pixelPoints = vtk.vtkPoints()
pixelPoints.SetNumberOfPoints(4)
pixelPoints.InsertPoint(0,0,0,0)
pixelPoints.InsertPoint(1,1,0,0)
pixelPoints.InsertPoint(2,0,1,0)
pixelPoints.InsertPoint(3,1,1,0)
aPixel = vtk.vtkPixel()
aPixel.GetPointIds().SetId(0,0)
aPixel.GetPointIds().SetId(1,1)
aPixel.GetPointIds().SetId(2,2)
aPixel.GetPointIds().SetId(3,3)
aPixelGrid = vtk.vtkUnstructuredGrid()
aPixelGrid.Allocate(1,1)
aPixelGrid.InsertNextCell(aPixel.GetCellType(),aPixel.GetPointIds())
aPixelGrid.SetPoints(pixelPoints)
aPixelMapper = vtk.vtkDataSetMapper()
aPixelMapper.SetInputData(aPixelGrid)
aPixelActor = vtk.vtkActor()
aPixelActor.SetMapper(aPixelMapper)
aPixelActor.AddPosition(0,0,2)
aPixelActor.GetProperty().BackfaceCullingOn()
# Quad
quadPoints = vtk.vtkPoints()
quadPoints.SetNumberOfPoints(4)
quadPoints.InsertPoint(0,0,0,0)
quadPoints.InsertPoint(1,1,0,0)
quadPoints.InsertPoint(2,1,1,0)
quadPoints.InsertPoint(3,0,1,0)
aQuad = vtk.vtkQuad()
aQuad.GetPointIds().SetId(0,0)
aQuad.GetPointIds().SetId(1,1)
aQuad.GetPointIds().SetId(2,2)
aQuad.GetPointIds().SetId(3,3)
aQuadGrid = vtk.vtkUnstructuredGrid()
aQuadGrid.Allocate(1,1)
aQuadGrid.InsertNextCell(aQuad.GetCellType(),aQuad.GetPointIds())
aQuadGrid.SetPoints(quadPoints)
aQuadMapper = vtk.vtkDataSetMapper()
aQuadMapper.SetInputData(aQuadGrid)
aQuadActor = vtk.vtkActor()
aQuadActor.SetMapper(aQuadMapper)
aQuadActor.AddPosition(2,0,2)
aQuadActor.GetProperty().BackfaceCullingOn()
# Triangle
trianglePoints = vtk.vtkPoints()
trianglePoints.SetNumberOfPoints(3)
trianglePoints.InsertPoint(0,0,0,0)
trianglePoints.InsertPoint(1,1,0,0)
trianglePoints.InsertPoint(2,.5,.5,0)
aTriangle = vtk.vtkTriangle()
aTriangle.GetPointIds().SetId(0,0)
aTriangle.GetPointIds().SetId(1,1)
aTriangle.GetPointIds().SetId(2,2)
aTriangleGrid = vtk.vtkUnstructuredGrid()
aTriangleGrid.Allocate(1,1)
aTriangleGrid.InsertNextCell(aTriangle.GetCellType(),aTriangle.GetPointIds())
aTriangleGrid.SetPoints(trianglePoints)
aTriangleMapper = vtk.vtkDataSetMapper()
aTriangleMapper.SetInputData(aTriangleGrid)
aTriangleActor = vtk.vtkActor()
aTriangleActor.SetMapper(aTriangleMapper)
aTriangleActor.AddPosition(4,0,2)
aTriangleActor.GetProperty().BackfaceCullingOn()
# Polygon
polygonPoints = vtk.vtkPoints()
polygonPoints.SetNumberOfPoints(4)
polygonPoints.InsertPoint(0,0,0,0)
polygonPoints.InsertPoint(1,1,0,0)
polygonPoints.InsertPoint(2,1,1,0)
polygonPoints.InsertPoint(3,0,1,0)
aPolygon = vtk.vtkPolygon()
aPolygon.GetPointIds().SetNumberOfIds(4)
aPolygon.GetPointIds().SetId(0,0)
aPolygon.GetPointIds().SetId(1,1)
aPolygon.GetPointIds().SetId(2,2)
aPolygon.GetPointIds().SetId(3,3)
aPolygonGrid = vtk.vtkUnstructuredGrid()
aPolygonGrid.Allocate(1,1)
aPolygonGrid.InsertNextCell(aPolygon.GetCellType(),aPolygon.GetPointIds())
aPolygonGrid.SetPoints(polygonPoints)
aPolygonMapper = vtk.vtkDataSetMapper()
aPolygonMapper.SetInputData(aPolygonGrid)
aPolygonActor = vtk.vtkActor()
aPolygonActor.SetMapper(aPolygonMapper)
aPolygonActor.AddPosition(6,0,2)
aPolygonActor.GetProperty().BackfaceCullingOn()
# Triangle Strip
triangleStripPoints = vtk.vtkPoints()
triangleStripPoints.SetNumberOfPoints(5)
triangleStripPoints.InsertPoint(0,0,1,0)
triangleStripPoints.InsertPoint(1,0,0,0)
triangleStripPoints.InsertPoint(2,1,1,0)
triangleStripPoints.InsertPoint(3,1,0,0)
triangleStripPoints.InsertPoint(4,2,1,0)
aTriangleStrip = vtk.vtkTriangleStrip()
aTriangleStrip.GetPointIds().SetNumberOfIds(5)
aTriangleStrip.GetPointIds().SetId(0,0)
aTriangleStrip.GetPointIds().SetId(1,1)
aTriangleStrip.GetPointIds().SetId(2,2)
aTriangleStrip.GetPointIds().SetId(3,3)
aTriangleStrip.GetPointIds().SetId(4,4)
aTriangleStripGrid = vtk.vtkUnstructuredGrid()
aTriangleStripGrid.Allocate(1,1)
aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(),aTriangleStrip.GetPointIds())
aTriangleStripGrid.SetPoints(triangleStripPoints)
aTriangleStripMapper = vtk.vtkDataSetMapper()
aTriangleStripMapper.SetInputData(aTriangleStripGrid)
aTriangleStripActor = vtk.vtkActor()
aTriangleStripActor.SetMapper(aTriangleStripMapper)
aTriangleStripActor.AddPosition(8,0,2)
aTriangleStripActor.GetProperty().BackfaceCullingOn()
# Line
linePoints = vtk.vtkPoints()
linePoints.SetNumberOfPoints(2)
linePoints.InsertPoint(0,0,0,0)
linePoints.InsertPoint(1,1,1,0)
aLine = vtk.vtkLine()
aLine.GetPointIds().SetId(0,0)
aLine.GetPointIds().SetId(1,1)
aLineGrid = vtk.vtkUnstructuredGrid()
aLineGrid.Allocate(1,1)
aLineGrid.InsertNextCell(aLine.GetCellType(),aLine.GetPointIds())
aLineGrid.SetPoints(linePoints)
aLineMapper = vtk.vtkDataSetMapper()
aLineMapper.SetInputData(aLineGrid)
aLineActor = vtk.vtkActor()
aLineActor.SetMapper(aLineMapper)
aLineActor.AddPosition(0,0,4)
aLineActor.GetProperty().BackfaceCullingOn()
# Poly line
polyLinePoints = vtk.vtkPoints()
polyLinePoints.SetNumberOfPoints(3)
polyLinePoints.InsertPoint(0,0,0,0)
polyLinePoints.InsertPoint(1,1,1,0)
polyLinePoints.InsertPoint(2,1,0,0)
aPolyLine = vtk.vtkPolyLine()
aPolyLine.GetPointIds().SetNumberOfIds(3)
aPolyLine.GetPointIds().SetId(0,0)
aPolyLine.GetPointIds().SetId(1,1)
aPolyLine.GetPointIds().SetId(2,2)
aPolyLineGrid = vtk.vtkUnstructuredGrid()
aPolyLineGrid.Allocate(1,1)
aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(),aPolyLine.GetPointIds())
aPolyLineGrid.SetPoints(polyLinePoints)
aPolyLineMapper = vtk.vtkDataSetMapper()
aPolyLineMapper.SetInputData(aPolyLineGrid)
aPolyLineActor = vtk.vtkActor()
aPolyLineActor.SetMapper(aPolyLineMapper)
aPolyLineActor.AddPosition(2,0,4)
aPolyLineActor.GetProperty().BackfaceCullingOn()
# Vertex
vertexPoints = vtk.vtkPoints()
vertexPoints.SetNumberOfPoints(1)
vertexPoints.InsertPoint(0,0,0,0)
aVertex = vtk.vtkVertex()
aVertex.GetPointIds().SetId(0,0)
aVertexGrid = vtk.vtkUnstructuredGrid()
aVertexGrid.Allocate(1,1)
aVertexGrid.InsertNextCell(aVertex.GetCellType(),aVertex.GetPointIds())
aVertexGrid.SetPoints(vertexPoints)
aVertexMapper = vtk.vtkDataSetMapper()
aVertexMapper.SetInputData(aVertexGrid)
aVertexActor = vtk.vtkActor()
aVertexActor.SetMapper(aVertexMapper)
aVertexActor.AddPosition(0,0,6)
aVertexActor.GetProperty().BackfaceCullingOn()
# Poly Vertex
polyVertexPoints = vtk.vtkPoints()
polyVertexPoints.SetNumberOfPoints(3)
polyVertexPoints.InsertPoint(0,0,0,0)
polyVertexPoints.InsertPoint(1,1,0,0)
polyVertexPoints.InsertPoint(2,1,1,0)
aPolyVertex = vtk.vtkPolyVertex()
aPolyVertex.GetPointIds().SetNumberOfIds(3)
aPolyVertex.GetPointIds().SetId(0,0)
aPolyVertex.GetPointIds().SetId(1,1)
aPolyVertex.GetPointIds().SetId(2,2)
aPolyVertexGrid = vtk.vtkUnstructuredGrid()
aPolyVertexGrid.Allocate(1,1)
aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(),aPolyVertex.GetPointIds())
aPolyVertexGrid.SetPoints(polyVertexPoints)
aPolyVertexMapper = vtk.vtkDataSetMapper()
aPolyVertexMapper.SetInputData(aPolyVertexGrid)
aPolyVertexActor = vtk.vtkActor()
aPolyVertexActor.SetMapper(aPolyVertexMapper)
aPolyVertexActor.AddPosition(2,0,6)
aPolyVertexActor.GetProperty().BackfaceCullingOn()
# Pentagonal prism
pentaPoints = vtk.vtkPoints()
pentaPoints.SetNumberOfPoints(10)
pentaPoints.InsertPoint(0,0.25,0.0,0.0)
pentaPoints.InsertPoint(1,0.75,0.0,0.0)
pentaPoints.InsertPoint(2,1.0,0.5,0.0)
pentaPoints.InsertPoint(3,0.5,1.0,0.0)
pentaPoints.InsertPoint(4,0.0,0.5,0.0)
pentaPoints.InsertPoint(5,0.25,0.0,1.0)
pentaPoints.InsertPoint(6,0.75,0.0,1.0)
pentaPoints.InsertPoint(7,1.0,0.5,1.0)
pentaPoints.InsertPoint(8,0.5,1.0,1.0)
pentaPoints.InsertPoint(9,0.0,0.5,1.0)
aPenta = vtk.vtkPentagonalPrism()
aPenta.GetPointIds().SetId(0,0)
aPenta.GetPointIds().SetId(1,1)
aPenta.GetPointIds().SetId(2,2)
aPenta.GetPointIds().SetId(3,3)
aPenta.GetPointIds().SetId(4,4)
aPenta.GetPointIds().SetId(5,5)
aPenta.GetPointIds().SetId(6,6)
aPenta.GetPointIds().SetId(7,7)
aPenta.GetPointIds().SetId(8,8)
aPenta.GetPointIds().SetId(9,9)
aPentaGrid = vtk.vtkUnstructuredGrid()
aPentaGrid.Allocate(1,1)
aPentaGrid.InsertNextCell(aPenta.GetCellType(),aPenta.GetPointIds())
aPentaGrid.SetPoints(pentaPoints)
aPentaMapper = vtk.vtkDataSetMapper()
aPentaMapper.SetInputData(aPentaGrid)
aPentaActor = vtk.vtkActor()
aPentaActor.SetMapper(aPentaMapper)
aPentaActor.AddPosition(10,0,0)
aPentaActor.GetProperty().BackfaceCullingOn()
# Hexagonal prism
hexaPoints = vtk.vtkPoints()
hexaPoints.SetNumberOfPoints(12)
hexaPoints.InsertPoint(0,0.0,0.0,0.0)
hexaPoints.InsertPoint(1,0.5,0.0,0.0)
hexaPoints.InsertPoint(2,1.0,0.5,0.0)
hexaPoints.InsertPoint(3,1.0,1.0,0.0)
hexaPoints.InsertPoint(4,0.5,1.0,0.0)
hexaPoints.InsertPoint(5,0.0,0.5,0.0)
hexaPoints.InsertPoint(6,0.0,0.0,1.0)
hexaPoints.InsertPoint(7,0.5,0.0,1.0)
hexaPoints.InsertPoint(8,1.0,0.5,1.0)
hexaPoints.InsertPoint(9,1.0,1.0,1.0)
hexaPoints.InsertPoint(10,0.5,1.0,1.0)
hexaPoints.InsertPoint(11,0.0,0.5,1.0)
aHexa = vtk.vtkHexagonalPrism()
aHexa.GetPointIds().SetId(0,0)
aHexa.GetPointIds().SetId(1,1)
aHexa.GetPointIds().SetId(2,2)
aHexa.GetPointIds().SetId(3,3)
aHexa.GetPointIds().SetId(4,4)
aHexa.GetPointIds().SetId(5,5)
aHexa.GetPointIds().SetId(6,6)
aHexa.GetPointIds().SetId(7,7)
aHexa.GetPointIds().SetId(8,8)
aHexa.GetPointIds().SetId(9,9)
aHexa.GetPointIds().SetId(10,10)
aHexa.GetPointIds().SetId(11,11)
aHexaGrid = vtk.vtkUnstructuredGrid()
aHexaGrid.Allocate(1,1)
aHexaGrid.InsertNextCell(aHexa.GetCellType(),aHexa.GetPointIds())
aHexaGrid.SetPoints(hexaPoints)
aHexaMapper = vtk.vtkDataSetMapper()
aHexaMapper.SetInputData(aHexaGrid)
aHexaActor = vtk.vtkActor()
aHexaActor.SetMapper(aHexaMapper)
aHexaActor.AddPosition(12,0,0)
aHexaActor.GetProperty().BackfaceCullingOn()
ren1.SetBackground(.1,.2,.4)
ren1.AddActor(aVoxelActor)
aVoxelActor.GetProperty().SetDiffuseColor(1,0,0)
ren1.AddActor(aHexahedronActor)
aHexahedronActor.GetProperty().SetDiffuseColor(1,1,0)
ren1.AddActor(aTetraActor)
aTetraActor.GetProperty().SetDiffuseColor(0,1,0)
ren1.AddActor(aWedgeActor)
aWedgeActor.GetProperty().SetDiffuseColor(0,1,1)
ren1.AddActor(aPyramidActor)
aPyramidActor.GetProperty().SetDiffuseColor(1,0,1)
ren1.AddActor(aPixelActor)
aPixelActor.GetProperty().SetDiffuseColor(0,1,1)
ren1.AddActor(aQuadActor)
aQuadActor.GetProperty().SetDiffuseColor(1,0,1)
ren1.AddActor(aTriangleActor)
aTriangleActor.GetProperty().SetDiffuseColor(.3,1,.5)
ren1.AddActor(aPolygonActor)
aPolygonActor.GetProperty().SetDiffuseColor(1,.4,.5)
ren1.AddActor(aTriangleStripActor)
aTriangleStripActor.GetProperty().SetDiffuseColor(.3,.7,1)
ren1.AddActor(aLineActor)
aLineActor.GetProperty().SetDiffuseColor(.2,1,1)
ren1.AddActor(aPolyLineActor)
aPolyLineActor.GetProperty().SetDiffuseColor(1,1,1)
ren1.AddActor(aVertexActor)
aVertexActor.GetProperty().SetDiffuseColor(1,1,1)
ren1.AddActor(aPolyVertexActor)
aPolyVertexActor.GetProperty().SetDiffuseColor(1,1,1)
ren1.AddActor(aPentaActor)
aPentaActor.GetProperty().SetDiffuseColor(.2,.4,.7)
ren1.AddActor(aHexaActor)
aHexaActor.GetProperty().SetDiffuseColor(.7,.5,1)
ren1.ResetCamera()
ren1.GetActiveCamera().Azimuth(30)
ren1.GetActiveCamera().Elevation(20)
ren1.GetActiveCamera().Dolly(1.25)
ren1.ResetCameraClippingRange()
renWin.Render()
cellPicker = vtk.vtkCellPicker()
pointPicker = vtk.vtkPointPicker()
worldPicker = vtk.vtkWorldPointPicker()
cellCount = 0
pointCount = 0
ren1.IsInViewport(0,0)
x = 0
while x <= 265:
y = 100
while y <= 200:
cellPicker.Pick(x,y,0,ren1)
pointPicker.Pick(x,y,0,ren1)
worldPicker.Pick(x,y,0,ren1)
if (cellPicker.GetCellId() != "-1"):
cellCount = cellCount + 1
pass
if (pointPicker.GetPointId() != "-1"):
pointCount = pointCount + 1
pass
y = y + 6
x = x + 6
# render the image
#
iren.Initialize()
# --- end of script --
| HopeFOAM/HopeFOAM | ThirdParty-0.1/ParaView-5.0.1/VTK/Rendering/Core/Testing/Python/pickCells.py | Python | gpl-3.0 | 16,540 |
#include <kccachedb.h>
using namespace std;
using namespace kyotocabinet;
// main routine
int main(int argc, char** argv) {
// create the database object
GrassDB db;
// open the database
if (!db.open("*", GrassDB::OWRITER | GrassDB::OCREATE)) {
cerr << "open error: " << db.error().name() << endl;
}
// store records
if (!db.set("foo", "hop") ||
!db.set("bar", "step") ||
!db.set("baz", "jump")) {
cerr << "set error: " << db.error().name() << endl;
}
// retrieve a record
string value;
if (db.get("foo", &value)) {
cout << value << endl;
} else {
cerr << "get error: " << db.error().name() << endl;
}
// traverse records
DB::Cursor* cur = db.cursor();
cur->jump();
string ckey, cvalue;
while (cur->get(&ckey, &cvalue, true)) {
cout << ckey << ":" << cvalue << endl;
}
delete cur;
// close the database
if (!db.close()) {
cerr << "close error: " << db.error().name() << endl;
}
return 0;
}
| sapo/kyoto | kyotocabinet/example/kcgrassex.cc | C++ | gpl-3.0 | 983 |
<?php
// This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2011 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC. If not, see <http://www.gnu.org/licenses/>.
// web interfaces for viewing and controlling batches
ini_set('display_errors', 'stdout');
error_reporting(E_ALL);
require_once("../inc/util.inc");
require_once("../inc/boinc_db.inc");
require_once("../inc/result.inc");
require_once("../inc/submit_db.inc");
function show_batch($user) {
$batch_id = get_int('batch_id');
$batch = BoincBatch::lookup_id($batch_id);
if (!$batch || $batch->user_id != $user->id) {
error_page("no batch");
}
page_head("Batch $batch->id");
$results = BoincResult::enum("batch=$batch->id order by workunitid");
$i = 0;
result_table_start(true, true, null);
foreach ($results as $result) {
show_result_row($result, true, true, true, $i++);
}
end_table();
page_tail();
}
function show_batches($user) {
$batches = BoincBatch::enum("user_id=$user->id");
page_head("Batches");
start_table();
table_header("Batch ID", "Submitted", "# jobs");
foreach ($batches as $batch) {
echo "<tr>
<td><a href=submit_status.php?action=show_batch&batch_id=$batch->id>$batch->id</a></td>
<td>".time_str($batch->create_time)."</td>
<td>$batch->njobs</td>
</tr>
";
}
end_table();
page_tail();
}
$user = get_logged_in_user();
$action = get_str('action', true);
switch ($action) {
case '': show_batches($user); break;
case 'show_batch': show_batch($user);
}
?>
| hanxue/Boinc | html/user/submit_status.php | PHP | gpl-3.0 | 2,189 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import copy
from openerp import models
from openerp.addons.account.report.account_financial_report import\
report_account_common
class report_account_common_horizontal(report_account_common):
def __init__(self, cr, uid, name, context=None):
super(report_account_common_horizontal, self).__init__(
cr, uid, name, context=context)
self.localcontext.update({
'get_left_lines': self.get_left_lines,
'get_right_lines': self.get_right_lines,
})
def get_lines(self, data, side=None):
data = copy.deepcopy(data)
if data['form']['used_context'] is None:
data['form']['used_context'] = {}
data['form']['used_context'].update(
account_financial_report_horizontal_side=side)
return super(report_account_common_horizontal, self).get_lines(
data)
def get_left_lines(self, data):
return self.get_lines(data, side='left')
def get_right_lines(self, data):
return self.get_lines(data, side='right')
class ReportFinancial(models.AbstractModel):
_inherit = 'report.account.report_financial'
_wrapped_report_class = report_account_common_horizontal
| Ehtaga/account-financial-reporting | account_financial_report_horizontal/report/report_financial.py | Python | agpl-3.0 | 2,192 |
/* Copyright (c) 2001-2009, The HSQL Development Group
* 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 HSQL Development Group 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* 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.
*/
package org.hsqldb_voltpatches.lib;
/**
* This should be used as the datatype for parameters and instance variables
* instead of HsqlArrayList or HsqlLinkedList to allow interchangable use of the
* two.
*
* @author dnordahl@users
* @version 1.7.2
* @since 1.7.2
*/
public interface HsqlList extends Collection {
void add(int index, Object element);
boolean add(Object element);
Object get(int index);
Object remove(int index);
Object set(int index, Object element);
boolean isEmpty();
int size();
Iterator iterator();
}
| kumarrus/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/HsqlList.java | Java | agpl-3.0 | 2,168 |
//===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the LiveDebugVariables analysis.
//
// Remove all DBG_VALUE instructions referencing virtual registers and replace
// them with a data structure tracking where live user variables are kept - in a
// virtual register or in a stack slot.
//
// Allow the data structure to be updated during register allocation when values
// are moved between registers and stack slots. Finally emit new DBG_VALUE
// instructions after register allocation is complete.
//
//===----------------------------------------------------------------------===//
#include "LiveDebugVariables.h"
#include "llvm/ADT/IntervalMap.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/LexicalScopes.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/VirtRegMap.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include <memory>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "livedebug"
static cl::opt<bool>
EnableLDV("live-debug-variables", cl::init(true),
cl::desc("Enable the live debug variables pass"), cl::Hidden);
STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
char LiveDebugVariables::ID = 0;
INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
"Debug Variable Analysis", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
"Debug Variable Analysis", false, false)
void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<MachineDominatorTree>();
AU.addRequiredTransitive<LiveIntervals>();
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
}
LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(nullptr) {
initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
}
/// LocMap - Map of where a user value is live, and its location.
typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
namespace {
/// UserValueScopes - Keeps track of lexical scopes associated with a
/// user value's source location.
class UserValueScopes {
DebugLoc DL;
LexicalScopes &LS;
SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
public:
UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
/// dominates - Return true if current scope dominates at least one machine
/// instruction in a given machine basic block.
bool dominates(MachineBasicBlock *MBB) {
if (LBlocks.empty())
LS.getMachineBasicBlocks(DL, LBlocks);
return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
}
};
} // end anonymous namespace
/// UserValue - A user value is a part of a debug info user variable.
///
/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
/// holds part of a user variable. The part is identified by a byte offset.
///
/// UserValues are grouped into equivalence classes for easier searching. Two
/// user values are related if they refer to the same variable, or if they are
/// held by the same virtual register. The equivalence class is the transitive
/// closure of that relation.
namespace {
class LDVImpl;
class UserValue {
const MDNode *Variable; ///< The debug info variable we are part of.
const MDNode *Expression; ///< Any complex address expression.
unsigned offset; ///< Byte offset into variable.
bool IsIndirect; ///< true if this is a register-indirect+offset value.
DebugLoc dl; ///< The debug location for the variable. This is
///< used by dwarf writer to find lexical scope.
UserValue *leader; ///< Equivalence class leader.
UserValue *next; ///< Next value in equivalence class, or null.
/// Numbered locations referenced by locmap.
SmallVector<MachineOperand, 4> locations;
/// Map of slot indices where this value is live.
LocMap locInts;
/// coalesceLocation - After LocNo was changed, check if it has become
/// identical to another location, and coalesce them. This may cause LocNo or
/// a later location to be erased, but no earlier location will be erased.
void coalesceLocation(unsigned LocNo);
/// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
LiveIntervals &LIS, const TargetInstrInfo &TII);
/// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
/// is live. Returns true if any changes were made.
bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
LiveIntervals &LIS);
public:
/// UserValue - Create a new UserValue.
UserValue(const MDNode *var, const MDNode *expr, unsigned o, bool i,
DebugLoc L, LocMap::Allocator &alloc)
: Variable(var), Expression(expr), offset(o), IsIndirect(i),
dl(std::move(L)), leader(this), next(nullptr), locInts(alloc) {}
/// getLeader - Get the leader of this value's equivalence class.
UserValue *getLeader() {
UserValue *l = leader;
while (l != l->leader)
l = l->leader;
return leader = l;
}
/// getNext - Return the next UserValue in the equivalence class.
UserValue *getNext() const { return next; }
/// match - Does this UserValue match the parameters?
bool match(const MDNode *Var, const MDNode *Expr, const DILocation *IA,
unsigned Offset, bool indirect) const {
return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA &&
Offset == offset && indirect == IsIndirect;
}
/// merge - Merge equivalence classes.
static UserValue *merge(UserValue *L1, UserValue *L2) {
L2 = L2->getLeader();
if (!L1)
return L2;
L1 = L1->getLeader();
if (L1 == L2)
return L1;
// Splice L2 before L1's members.
UserValue *End = L2;
while (End->next) {
End->leader = L1;
End = End->next;
}
End->leader = L1;
End->next = L1->next;
L1->next = L2;
return L1;
}
/// getLocationNo - Return the location number that matches Loc.
unsigned getLocationNo(const MachineOperand &LocMO) {
if (LocMO.isReg()) {
if (LocMO.getReg() == 0)
return ~0u;
// For register locations we dont care about use/def and other flags.
for (unsigned i = 0, e = locations.size(); i != e; ++i)
if (locations[i].isReg() &&
locations[i].getReg() == LocMO.getReg() &&
locations[i].getSubReg() == LocMO.getSubReg())
return i;
} else
for (unsigned i = 0, e = locations.size(); i != e; ++i)
if (LocMO.isIdenticalTo(locations[i]))
return i;
locations.push_back(LocMO);
// We are storing a MachineOperand outside a MachineInstr.
locations.back().clearParent();
// Don't store def operands.
if (locations.back().isReg())
locations.back().setIsUse();
return locations.size() - 1;
}
/// mapVirtRegs - Ensure that all virtual register locations are mapped.
void mapVirtRegs(LDVImpl *LDV);
/// addDef - Add a definition point to this value.
void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
// Add a singular (Idx,Idx) -> Loc mapping.
LocMap::iterator I = locInts.find(Idx);
if (!I.valid() || I.start() != Idx)
I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
else
// A later DBG_VALUE at the same SlotIndex overrides the old location.
I.setValue(getLocationNo(LocMO));
}
/// extendDef - Extend the current definition as far as possible down the
/// dominator tree. Stop when meeting an existing def or when leaving the live
/// range of VNI.
/// End points where VNI is no longer live are added to Kills.
/// @param Idx Starting point for the definition.
/// @param LocNo Location number to propagate.
/// @param LR Restrict liveness to where LR has the value VNI. May be null.
/// @param VNI When LR is not null, this is the value to restrict to.
/// @param Kills Append end points of VNI's live range to Kills.
/// @param LIS Live intervals analysis.
/// @param MDT Dominator tree.
void extendDef(SlotIndex Idx, unsigned LocNo,
LiveRange *LR, const VNInfo *VNI,
SmallVectorImpl<SlotIndex> *Kills,
LiveIntervals &LIS, MachineDominatorTree &MDT,
UserValueScopes &UVS);
/// addDefsFromCopies - The value in LI/LocNo may be copies to other
/// registers. Determine if any of the copies are available at the kill
/// points, and add defs if possible.
/// @param LI Scan for copies of the value in LI->reg.
/// @param LocNo Location number of LI->reg.
/// @param Kills Points where the range of LocNo could be extended.
/// @param NewDefs Append (Idx, LocNo) of inserted defs here.
void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
const SmallVectorImpl<SlotIndex> &Kills,
SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
MachineRegisterInfo &MRI,
LiveIntervals &LIS);
/// computeIntervals - Compute the live intervals of all locations after
/// collecting all their def points.
void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
LiveIntervals &LIS, MachineDominatorTree &MDT,
UserValueScopes &UVS);
/// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
/// live. Returns true if any changes were made.
bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
LiveIntervals &LIS);
/// rewriteLocations - Rewrite virtual register locations according to the
/// provided virtual register map.
void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
/// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
void emitDebugValues(VirtRegMap *VRM,
LiveIntervals &LIS, const TargetInstrInfo &TRI);
/// getDebugLoc - Return DebugLoc of this UserValue.
DebugLoc getDebugLoc() { return dl;}
void print(raw_ostream &, const TargetRegisterInfo *);
};
} // namespace
/// LDVImpl - Implementation of the LiveDebugVariables pass.
namespace {
class LDVImpl {
LiveDebugVariables &pass;
LocMap::Allocator allocator;
MachineFunction *MF;
LiveIntervals *LIS;
LexicalScopes LS;
MachineDominatorTree *MDT;
const TargetRegisterInfo *TRI;
/// Whether emitDebugValues is called.
bool EmitDone;
/// Whether the machine function is modified during the pass.
bool ModifiedMF;
/// userValues - All allocated UserValue instances.
SmallVector<std::unique_ptr<UserValue>, 8> userValues;
/// Map virtual register to eq class leader.
typedef DenseMap<unsigned, UserValue*> VRMap;
VRMap virtRegToEqClass;
/// Map user variable to eq class leader.
typedef DenseMap<const MDNode *, UserValue*> UVMap;
UVMap userVarMap;
/// getUserValue - Find or create a UserValue.
UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
unsigned Offset, bool IsIndirect, const DebugLoc &DL);
/// lookupVirtReg - Find the EC leader for VirtReg or null.
UserValue *lookupVirtReg(unsigned VirtReg);
/// handleDebugValue - Add DBG_VALUE instruction to our maps.
/// @param MI DBG_VALUE instruction
/// @param Idx Last valid SLotIndex before instruction.
/// @return True if the DBG_VALUE instruction should be deleted.
bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
/// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
/// a UserValue def for each instruction.
/// @param mf MachineFunction to be scanned.
/// @return True if any debug values were found.
bool collectDebugValues(MachineFunction &mf);
/// computeIntervals - Compute the live intervals of all user values after
/// collecting all their def points.
void computeIntervals();
public:
LDVImpl(LiveDebugVariables *ps)
: pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {}
bool runOnMachineFunction(MachineFunction &mf);
/// clear - Release all memory.
void clear() {
MF = nullptr;
userValues.clear();
virtRegToEqClass.clear();
userVarMap.clear();
// Make sure we call emitDebugValues if the machine function was modified.
assert((!ModifiedMF || EmitDone) &&
"Dbg values are not emitted in LDV");
EmitDone = false;
ModifiedMF = false;
LS.reset();
}
/// mapVirtReg - Map virtual register to an equivalence class.
void mapVirtReg(unsigned VirtReg, UserValue *EC);
/// splitRegister - Replace all references to OldReg with NewRegs.
void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
/// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
void emitDebugValues(VirtRegMap *VRM);
void print(raw_ostream&);
};
} // namespace
static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
const LLVMContext &Ctx) {
if (!DL)
return;
auto *Scope = cast<DIScope>(DL.getScope());
// Omit the directory, because it's likely to be long and uninteresting.
CommentOS << Scope->getFilename();
CommentOS << ':' << DL.getLine();
if (DL.getCol() != 0)
CommentOS << ':' << DL.getCol();
DebugLoc InlinedAtDL = DL.getInlinedAt();
if (!InlinedAtDL)
return;
CommentOS << " @[ ";
printDebugLoc(InlinedAtDL, CommentOS, Ctx);
CommentOS << " ]";
}
static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
const DILocation *DL) {
const LLVMContext &Ctx = V->getContext();
StringRef Res = V->getName();
if (!Res.empty())
OS << Res << "," << V->getLine();
if (auto *InlinedAt = DL->getInlinedAt()) {
if (DebugLoc InlinedAtDL = InlinedAt) {
OS << " @[";
printDebugLoc(InlinedAtDL, OS, Ctx);
OS << "]";
}
}
}
void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
auto *DV = cast<DILocalVariable>(Variable);
OS << "!\"";
printExtendedName(OS, DV, dl);
OS << "\"\t";
if (offset)
OS << '+' << offset;
for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
OS << " [" << I.start() << ';' << I.stop() << "):";
if (I.value() == ~0u)
OS << "undef";
else
OS << I.value();
}
for (unsigned i = 0, e = locations.size(); i != e; ++i) {
OS << " Loc" << i << '=';
locations[i].print(OS, TRI);
}
OS << '\n';
}
void LDVImpl::print(raw_ostream &OS) {
OS << "********** DEBUG VARIABLES **********\n";
for (unsigned i = 0, e = userValues.size(); i != e; ++i)
userValues[i]->print(OS, TRI);
}
void UserValue::coalesceLocation(unsigned LocNo) {
unsigned KeepLoc = 0;
for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
if (KeepLoc == LocNo)
continue;
if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
break;
}
// No matches.
if (KeepLoc == locations.size())
return;
// Keep the smaller location, erase the larger one.
unsigned EraseLoc = LocNo;
if (KeepLoc > EraseLoc)
std::swap(KeepLoc, EraseLoc);
locations.erase(locations.begin() + EraseLoc);
// Rewrite values.
for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
unsigned v = I.value();
if (v == EraseLoc)
I.setValue(KeepLoc); // Coalesce when possible.
else if (v > EraseLoc)
I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
}
}
void UserValue::mapVirtRegs(LDVImpl *LDV) {
for (unsigned i = 0, e = locations.size(); i != e; ++i)
if (locations[i].isReg() &&
TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
LDV->mapVirtReg(locations[i].getReg(), this);
}
UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
unsigned Offset, bool IsIndirect,
const DebugLoc &DL) {
UserValue *&Leader = userVarMap[Var];
if (Leader) {
UserValue *UV = Leader->getLeader();
Leader = UV;
for (; UV; UV = UV->getNext())
if (UV->match(Var, Expr, DL->getInlinedAt(), Offset, IsIndirect))
return UV;
}
userValues.push_back(
make_unique<UserValue>(Var, Expr, Offset, IsIndirect, DL, allocator));
UserValue *UV = userValues.back().get();
Leader = UserValue::merge(Leader, UV);
return UV;
}
void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
UserValue *&Leader = virtRegToEqClass[VirtReg];
Leader = UserValue::merge(Leader, EC);
}
UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
return UV->getLeader();
return nullptr;
}
bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
// DBG_VALUE loc, offset, variable
if (MI.getNumOperands() != 4 ||
!(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
!MI.getOperand(2).isMetadata()) {
DEBUG(dbgs() << "Can't handle " << MI);
return false;
}
// Get or create the UserValue for (variable,offset).
bool IsIndirect = MI.isIndirectDebugValue();
unsigned Offset = IsIndirect ? MI.getOperand(1).getImm() : 0;
const MDNode *Var = MI.getDebugVariable();
const MDNode *Expr = MI.getDebugExpression();
//here.
UserValue *UV = getUserValue(Var, Expr, Offset, IsIndirect, MI.getDebugLoc());
UV->addDef(Idx, MI.getOperand(0));
return true;
}
bool LDVImpl::collectDebugValues(MachineFunction &mf) {
bool Changed = false;
for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
++MFI) {
MachineBasicBlock *MBB = &*MFI;
for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
MBBI != MBBE;) {
if (!MBBI->isDebugValue()) {
++MBBI;
continue;
}
// DBG_VALUE has no slot index, use the previous instruction instead.
SlotIndex Idx =
MBBI == MBB->begin()
? LIS->getMBBStartIdx(MBB)
: LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
// Handle consecutive DBG_VALUE instructions with the same slot index.
do {
if (handleDebugValue(*MBBI, Idx)) {
MBBI = MBB->erase(MBBI);
Changed = true;
} else
++MBBI;
} while (MBBI != MBBE && MBBI->isDebugValue());
}
}
return Changed;
}
/// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
/// data-flow analysis to propagate them beyond basic block boundaries.
void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, LiveRange *LR,
const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
LiveIntervals &LIS, MachineDominatorTree &MDT,
UserValueScopes &UVS) {
SlotIndex Start = Idx;
MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
SlotIndex Stop = LIS.getMBBEndIdx(MBB);
LocMap::iterator I = locInts.find(Start);
// Limit to VNI's live range.
bool ToEnd = true;
if (LR && VNI) {
LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
if (!Segment || Segment->valno != VNI) {
if (Kills)
Kills->push_back(Start);
return;
}
if (Segment->end < Stop) {
Stop = Segment->end;
ToEnd = false;
}
}
// There could already be a short def at Start.
if (I.valid() && I.start() <= Start) {
// Stop when meeting a different location or an already extended interval.
Start = Start.getNextSlot();
if (I.value() != LocNo || I.stop() != Start)
return;
// This is a one-slot placeholder. Just skip it.
++I;
}
// Limited by the next def.
if (I.valid() && I.start() < Stop) {
Stop = I.start();
ToEnd = false;
}
// Limited by VNI's live range.
else if (!ToEnd && Kills)
Kills->push_back(Stop);
if (Start < Stop)
I.insert(Start, Stop, LocNo);
}
void
UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
const SmallVectorImpl<SlotIndex> &Kills,
SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
MachineRegisterInfo &MRI, LiveIntervals &LIS) {
if (Kills.empty())
return;
// Don't track copies from physregs, there are too many uses.
if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
return;
// Collect all the (vreg, valno) pairs that are copies of LI.
SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
MachineInstr *MI = MO.getParent();
// Copies of the full value.
if (MO.getSubReg() || !MI->isCopy())
continue;
unsigned DstReg = MI->getOperand(0).getReg();
// Don't follow copies to physregs. These are usually setting up call
// arguments, and the argument registers are always call clobbered. We are
// better off in the source register which could be a callee-saved register,
// or it could be spilled.
if (!TargetRegisterInfo::isVirtualRegister(DstReg))
continue;
// Is LocNo extended to reach this copy? If not, another def may be blocking
// it, or we are looking at a wrong value of LI.
SlotIndex Idx = LIS.getInstructionIndex(*MI);
LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
if (!I.valid() || I.value() != LocNo)
continue;
if (!LIS.hasInterval(DstReg))
continue;
LiveInterval *DstLI = &LIS.getInterval(DstReg);
const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
CopyValues.push_back(std::make_pair(DstLI, DstVNI));
}
if (CopyValues.empty())
return;
DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
// Try to add defs of the copied values for each kill point.
for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
SlotIndex Idx = Kills[i];
for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
LiveInterval *DstLI = CopyValues[j].first;
const VNInfo *DstVNI = CopyValues[j].second;
if (DstLI->getVNInfoAt(Idx) != DstVNI)
continue;
// Check that there isn't already a def at Idx
LocMap::iterator I = locInts.find(Idx);
if (I.valid() && I.start() <= Idx)
continue;
DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
<< DstVNI->id << " in " << *DstLI << '\n');
MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
I.insert(Idx, Idx.getNextSlot(), LocNo);
NewDefs.push_back(std::make_pair(Idx, LocNo));
break;
}
}
}
void
UserValue::computeIntervals(MachineRegisterInfo &MRI,
const TargetRegisterInfo &TRI,
LiveIntervals &LIS,
MachineDominatorTree &MDT,
UserValueScopes &UVS) {
SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
// Collect all defs to be extended (Skipping undefs).
for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
if (I.value() != ~0u)
Defs.push_back(std::make_pair(I.start(), I.value()));
// Extend all defs, and possibly add new ones along the way.
for (unsigned i = 0; i != Defs.size(); ++i) {
SlotIndex Idx = Defs[i].first;
unsigned LocNo = Defs[i].second;
const MachineOperand &Loc = locations[LocNo];
if (!Loc.isReg()) {
extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS, MDT, UVS);
continue;
}
// Register locations are constrained to where the register value is live.
if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
LiveInterval *LI = nullptr;
const VNInfo *VNI = nullptr;
if (LIS.hasInterval(Loc.getReg())) {
LI = &LIS.getInterval(Loc.getReg());
VNI = LI->getVNInfoAt(Idx);
}
SmallVector<SlotIndex, 16> Kills;
extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS);
if (LI)
addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
continue;
}
// For physregs, use the live range of the first regunit as a guide.
unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
LiveRange *LR = &LIS.getRegUnit(Unit);
const VNInfo *VNI = LR->getVNInfoAt(Idx);
// Don't track copies from physregs, it is too expensive.
extendDef(Idx, LocNo, LR, VNI, nullptr, LIS, MDT, UVS);
}
// Finally, erase all the undefs.
for (LocMap::iterator I = locInts.begin(); I.valid();)
if (I.value() == ~0u)
I.erase();
else
++I;
}
void LDVImpl::computeIntervals() {
for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
UserValueScopes UVS(userValues[i]->getDebugLoc(), LS);
userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS);
userValues[i]->mapVirtRegs(this);
}
}
bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
clear();
MF = &mf;
LIS = &pass.getAnalysis<LiveIntervals>();
MDT = &pass.getAnalysis<MachineDominatorTree>();
TRI = mf.getSubtarget().getRegisterInfo();
LS.initialize(mf);
DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
<< mf.getName() << " **********\n");
bool Changed = collectDebugValues(mf);
computeIntervals();
DEBUG(print(dbgs()));
ModifiedMF = Changed;
return Changed;
}
static void removeDebugValues(MachineFunction &mf) {
for (MachineBasicBlock &MBB : mf) {
for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
if (!MBBI->isDebugValue()) {
++MBBI;
continue;
}
MBBI = MBB.erase(MBBI);
}
}
}
bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
if (!EnableLDV)
return false;
if (!mf.getFunction()->getSubprogram()) {
removeDebugValues(mf);
return false;
}
if (!pImpl)
pImpl = new LDVImpl(this);
return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
}
void LiveDebugVariables::releaseMemory() {
if (pImpl)
static_cast<LDVImpl*>(pImpl)->clear();
}
LiveDebugVariables::~LiveDebugVariables() {
if (pImpl)
delete static_cast<LDVImpl*>(pImpl);
}
//===----------------------------------------------------------------------===//
// Live Range Splitting
//===----------------------------------------------------------------------===//
bool
UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
LiveIntervals& LIS) {
DEBUG({
dbgs() << "Splitting Loc" << OldLocNo << '\t';
print(dbgs(), nullptr);
});
bool DidChange = false;
LocMap::iterator LocMapI;
LocMapI.setMap(locInts);
for (unsigned i = 0; i != NewRegs.size(); ++i) {
LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
if (LI->empty())
continue;
// Don't allocate the new LocNo until it is needed.
unsigned NewLocNo = ~0u;
// Iterate over the overlaps between locInts and LI.
LocMapI.find(LI->beginIndex());
if (!LocMapI.valid())
continue;
LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
LiveInterval::iterator LIE = LI->end();
while (LocMapI.valid() && LII != LIE) {
// At this point, we know that LocMapI.stop() > LII->start.
LII = LI->advanceTo(LII, LocMapI.start());
if (LII == LIE)
break;
// Now LII->end > LocMapI.start(). Do we have an overlap?
if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
// Overlapping correct location. Allocate NewLocNo now.
if (NewLocNo == ~0u) {
MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
MO.setSubReg(locations[OldLocNo].getSubReg());
NewLocNo = getLocationNo(MO);
DidChange = true;
}
SlotIndex LStart = LocMapI.start();
SlotIndex LStop = LocMapI.stop();
// Trim LocMapI down to the LII overlap.
if (LStart < LII->start)
LocMapI.setStartUnchecked(LII->start);
if (LStop > LII->end)
LocMapI.setStopUnchecked(LII->end);
// Change the value in the overlap. This may trigger coalescing.
LocMapI.setValue(NewLocNo);
// Re-insert any removed OldLocNo ranges.
if (LStart < LocMapI.start()) {
LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
++LocMapI;
assert(LocMapI.valid() && "Unexpected coalescing");
}
if (LStop > LocMapI.stop()) {
++LocMapI;
LocMapI.insert(LII->end, LStop, OldLocNo);
--LocMapI;
}
}
// Advance to the next overlap.
if (LII->end < LocMapI.stop()) {
if (++LII == LIE)
break;
LocMapI.advanceTo(LII->start);
} else {
++LocMapI;
if (!LocMapI.valid())
break;
LII = LI->advanceTo(LII, LocMapI.start());
}
}
}
// Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
locations.erase(locations.begin() + OldLocNo);
LocMapI.goToBegin();
while (LocMapI.valid()) {
unsigned v = LocMapI.value();
if (v == OldLocNo) {
DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
<< LocMapI.stop() << ")\n");
LocMapI.erase();
} else {
if (v > OldLocNo)
LocMapI.setValueUnchecked(v-1);
++LocMapI;
}
}
DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
return DidChange;
}
bool
UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
LiveIntervals &LIS) {
bool DidChange = false;
// Split locations referring to OldReg. Iterate backwards so splitLocation can
// safely erase unused locations.
for (unsigned i = locations.size(); i ; --i) {
unsigned LocNo = i-1;
const MachineOperand *Loc = &locations[LocNo];
if (!Loc->isReg() || Loc->getReg() != OldReg)
continue;
DidChange |= splitLocation(LocNo, NewRegs, LIS);
}
return DidChange;
}
void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
bool DidChange = false;
for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
if (!DidChange)
return;
// Map all of the new virtual registers.
UserValue *UV = lookupVirtReg(OldReg);
for (unsigned i = 0; i != NewRegs.size(); ++i)
mapVirtReg(NewRegs[i], UV);
}
void LiveDebugVariables::
splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
if (pImpl)
static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
}
void
UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
// Iterate over locations in reverse makes it easier to handle coalescing.
for (unsigned i = locations.size(); i ; --i) {
unsigned LocNo = i-1;
MachineOperand &Loc = locations[LocNo];
// Only virtual registers are rewritten.
if (!Loc.isReg() || !Loc.getReg() ||
!TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
continue;
unsigned VirtReg = Loc.getReg();
if (VRM.isAssignedReg(VirtReg) &&
TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
// This can create a %noreg operand in rare cases when the sub-register
// index is no longer available. That means the user value is in a
// non-existent sub-register, and %noreg is exactly what we want.
Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
} else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
// FIXME: Translate SubIdx to a stackslot offset.
Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
} else {
Loc.setReg(0);
Loc.setSubReg(0);
}
coalesceLocation(LocNo);
}
}
/// findInsertLocation - Find an iterator for inserting a DBG_VALUE
/// instruction.
static MachineBasicBlock::iterator
findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
LiveIntervals &LIS) {
SlotIndex Start = LIS.getMBBStartIdx(MBB);
Idx = Idx.getBaseIndex();
// Try to find an insert location by going backwards from Idx.
MachineInstr *MI;
while (!(MI = LIS.getInstructionFromIndex(Idx))) {
// We've reached the beginning of MBB.
if (Idx == Start) {
MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
return I;
}
Idx = Idx.getPrevIndex();
}
// Don't insert anything after the first terminator, though.
return MI->isTerminator() ? MBB->getFirstTerminator() :
std::next(MachineBasicBlock::iterator(MI));
}
void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
unsigned LocNo,
LiveIntervals &LIS,
const TargetInstrInfo &TII) {
MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
MachineOperand &Loc = locations[LocNo];
++NumInsertedDebugValues;
assert(cast<DILocalVariable>(Variable)
->isValidLocationForIntrinsic(getDebugLoc()) &&
"Expected inlined-at fields to agree");
if (Loc.isReg())
BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
IsIndirect, Loc.getReg(), offset, Variable, Expression);
else
BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
.addOperand(Loc)
.addImm(offset)
.addMetadata(Variable)
.addMetadata(Expression);
}
void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
const TargetInstrInfo &TII) {
MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
SlotIndex Start = I.start();
SlotIndex Stop = I.stop();
unsigned LocNo = I.value();
DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
// This interval may span multiple basic blocks.
// Insert a DBG_VALUE into each one.
while(Stop > MBBEnd) {
// Move to the next block.
Start = MBBEnd;
if (++MBB == MFEnd)
break;
MBBEnd = LIS.getMBBEndIdx(&*MBB);
DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
}
DEBUG(dbgs() << '\n');
if (MBB == MFEnd)
break;
++I;
}
}
void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
if (!MF)
return;
const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
DEBUG(userValues[i]->print(dbgs(), TRI));
userValues[i]->rewriteLocations(*VRM, *TRI);
userValues[i]->emitDebugValues(VRM, *LIS, *TII);
}
EmitDone = true;
}
void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
if (pImpl)
static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
}
bool LiveDebugVariables::doInitialization(Module &M) {
return Pass::doInitialization(M);
}
#ifndef NDEBUG
LLVM_DUMP_METHOD void LiveDebugVariables::dump() {
if (pImpl)
static_cast<LDVImpl*>(pImpl)->print(dbgs());
}
#endif
| cd80/UtilizedLLVM | lib/CodeGen/LiveDebugVariables.cpp | C++ | unlicense | 36,643 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.ml.action;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.tasks.BaseTasksResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.StatusToXContentObject;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.ml.job.config.JobUpdate;
import org.elasticsearch.xpack.core.ml.job.config.MlFilter;
import org.elasticsearch.xpack.core.ml.job.config.ModelPlotConfig;
import org.elasticsearch.xpack.core.ml.job.config.PerPartitionCategorizationConfig;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
public class UpdateProcessAction extends ActionType<UpdateProcessAction.Response> {
public static final UpdateProcessAction INSTANCE = new UpdateProcessAction();
public static final String NAME = "cluster:internal/xpack/ml/job/update/process";
private UpdateProcessAction() {
super(NAME, UpdateProcessAction.Response::new);
}
public static class Response extends BaseTasksResponse implements StatusToXContentObject, Writeable {
private final boolean isUpdated;
public Response() {
super(null, null);
this.isUpdated = true;
}
public Response(StreamInput in) throws IOException {
super(in);
isUpdated = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(isUpdated);
}
public boolean isUpdated() {
return isUpdated;
}
@Override
public RestStatus status() {
return RestStatus.ACCEPTED;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("updated", isUpdated);
builder.endObject();
return builder;
}
@Override
public int hashCode() {
return Objects.hashCode(isUpdated);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Response other = (Response) obj;
return this.isUpdated == other.isUpdated;
}
}
public static class Request extends JobTaskRequest<Request> {
private ModelPlotConfig modelPlotConfig;
private PerPartitionCategorizationConfig perPartitionCategorizationConfig;
private List<JobUpdate.DetectorUpdate> detectorUpdates;
private MlFilter filter;
private boolean updateScheduledEvents = false;
public Request(StreamInput in) throws IOException {
super(in);
modelPlotConfig = in.readOptionalWriteable(ModelPlotConfig::new);
perPartitionCategorizationConfig = in.readOptionalWriteable(PerPartitionCategorizationConfig::new);
if (in.readBoolean()) {
detectorUpdates = in.readList(JobUpdate.DetectorUpdate::new);
}
filter = in.readOptionalWriteable(MlFilter::new);
updateScheduledEvents = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalWriteable(modelPlotConfig);
out.writeOptionalWriteable(perPartitionCategorizationConfig);
boolean hasDetectorUpdates = detectorUpdates != null;
out.writeBoolean(hasDetectorUpdates);
if (hasDetectorUpdates) {
out.writeList(detectorUpdates);
}
out.writeOptionalWriteable(filter);
out.writeBoolean(updateScheduledEvents);
}
public Request(
String jobId,
ModelPlotConfig modelPlotConfig,
PerPartitionCategorizationConfig perPartitionCategorizationConfig,
List<JobUpdate.DetectorUpdate> detectorUpdates,
MlFilter filter,
boolean updateScheduledEvents
) {
super(jobId);
this.modelPlotConfig = modelPlotConfig;
this.perPartitionCategorizationConfig = perPartitionCategorizationConfig;
this.detectorUpdates = detectorUpdates;
this.filter = filter;
this.updateScheduledEvents = updateScheduledEvents;
}
public ModelPlotConfig getModelPlotConfig() {
return modelPlotConfig;
}
public PerPartitionCategorizationConfig getPerPartitionCategorizationConfig() {
return perPartitionCategorizationConfig;
}
public List<JobUpdate.DetectorUpdate> getDetectorUpdates() {
return detectorUpdates;
}
public MlFilter getFilter() {
return filter;
}
public boolean isUpdateScheduledEvents() {
return updateScheduledEvents;
}
@Override
public int hashCode() {
return Objects.hash(
getJobId(),
modelPlotConfig,
perPartitionCategorizationConfig,
detectorUpdates,
filter,
updateScheduledEvents
);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Request other = (Request) obj;
return Objects.equals(getJobId(), other.getJobId())
&& Objects.equals(modelPlotConfig, other.modelPlotConfig)
&& Objects.equals(perPartitionCategorizationConfig, other.perPartitionCategorizationConfig)
&& Objects.equals(detectorUpdates, other.detectorUpdates)
&& Objects.equals(filter, other.filter)
&& Objects.equals(updateScheduledEvents, other.updateScheduledEvents);
}
}
}
| GlenRSmith/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/UpdateProcessAction.java | Java | apache-2.0 | 6,629 |
{
"EL": {"custom":["org.nutz.el.issue279.Uuuid"]}
} | lzxz1234/nutz | test/org/nutz/el/issue279/279.js | JavaScript | apache-2.0 | 51 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal class SpacingFormattingRule : BaseFormattingRule
{
public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation<AdjustSpacesOperation> nextOperation)
{
if (optionSet == null)
{
return nextOperation.Invoke();
}
System.Diagnostics.Debug.Assert(previousToken.Parent != null && currentToken.Parent != null);
var previousKind = previousToken.Kind();
var currentKind = currentToken.Kind();
var previousParentKind = previousToken.Parent.Kind();
var currentParentKind = currentToken.Parent.Kind();
// For Method Declaration
if (currentToken.IsOpenParenInParameterList() && previousKind == SyntaxKind.IdentifierToken)
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName);
}
// For Generic Method Declaration
if (currentToken.IsOpenParenInParameterList() && previousKind == SyntaxKind.GreaterThanToken && previousParentKind == SyntaxKind.TypeParameterList)
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName);
}
// Case: public static implicit operator string(Program p) { return null; }
if (previousToken.IsKeyword() && currentToken.IsOpenParenInParameterListOfAConversionOperatorDeclaration())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName);
}
// Case: public static Program operator !(Program p) { return null; }
if (previousToken.Parent.IsKind(SyntaxKind.OperatorDeclaration) && currentToken.IsOpenParenInParameterListOfAOperationDeclaration())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpacingAfterMethodDeclarationName);
}
if (previousToken.IsOpenParenInParameterList() && currentToken.IsCloseParenInParameterList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses);
}
if (previousToken.IsOpenParenInParameterList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis);
}
if (currentToken.IsCloseParenInParameterList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis);
}
// For Method Call
if (currentToken.IsOpenParenInArgumentList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterMethodCallName);
}
if (previousToken.IsOpenParenInArgumentList() && currentToken.IsCloseParenInArgumentList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses);
}
if (previousToken.IsOpenParenInArgumentList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses);
}
if (currentToken.IsCloseParenInArgumentList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses);
}
// For spacing around: typeof, default, and sizeof; treat like a Method Call
if (currentKind == SyntaxKind.OpenParenToken && IsFunctionLikeKeywordExpressionKind(currentParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterMethodCallName);
}
if (previousKind == SyntaxKind.OpenParenToken && IsFunctionLikeKeywordExpressionKind(previousParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses);
}
if (currentKind == SyntaxKind.CloseParenToken && IsFunctionLikeKeywordExpressionKind(currentParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinMethodCallParentheses);
}
// For Spacing b/n control flow keyword and paren. Parent check not needed.
if (currentKind == SyntaxKind.OpenParenToken &&
(previousKind == SyntaxKind.IfKeyword || previousKind == SyntaxKind.WhileKeyword || previousKind == SyntaxKind.SwitchKeyword ||
previousKind == SyntaxKind.ForKeyword || previousKind == SyntaxKind.ForEachKeyword || previousKind == SyntaxKind.CatchKeyword ||
previousKind == SyntaxKind.UsingKeyword))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword);
}
// For spacing between parenthesis and expression
if ((previousParentKind == SyntaxKind.ParenthesizedExpression && previousKind == SyntaxKind.OpenParenToken) ||
(currentParentKind == SyntaxKind.ParenthesizedExpression && currentKind == SyntaxKind.CloseParenToken))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinExpressionParentheses);
}
// For spacing between the parenthesis and the cast expression
if ((previousParentKind == SyntaxKind.CastExpression && previousKind == SyntaxKind.OpenParenToken) ||
(currentParentKind == SyntaxKind.CastExpression && currentKind == SyntaxKind.CloseParenToken))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinCastParentheses);
}
// For spacing between the parenthesis and the expression inside the control flow expression
if (previousKind == SyntaxKind.OpenParenToken && IsControlFlowLikeKeywordStatementKind(previousParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinOtherParentheses);
}
// Semicolons in an empty for statement. i.e. for(;;)
if (previousKind == SyntaxKind.OpenParenToken || previousKind == SyntaxKind.SemicolonToken)
{
if (previousToken.Parent.Kind() == SyntaxKind.ForStatement)
{
var forStatement = (ForStatementSyntax)previousToken.Parent;
if (forStatement.Initializers.Count == 0 &&
forStatement.Declaration == null &&
forStatement.Condition == null &&
forStatement.Incrementors.Count == 0)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
}
}
if (currentKind == SyntaxKind.CloseParenToken && IsControlFlowLikeKeywordStatementKind(currentParentKind))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinOtherParentheses);
}
// For spacing after the cast
if (previousParentKind == SyntaxKind.CastExpression && previousKind == SyntaxKind.CloseParenToken)
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterCast);
}
// For spacing Before Square Braces
if (currentKind == SyntaxKind.OpenBracketToken && HasFormattableBracketParent(currentToken) && !previousToken.IsOpenBraceOrCommaOfObjectInitializer())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeOpenSquareBracket);
}
// For spacing empty square braces
if (previousKind == SyntaxKind.OpenBracketToken && (currentKind == SyntaxKind.CloseBracketToken || currentKind == SyntaxKind.OmittedArraySizeExpressionToken) && HasFormattableBracketParent(previousToken))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets);
}
// For spacing square brackets within
if (previousKind == SyntaxKind.OpenBracketToken && HasFormattableBracketParent(previousToken))
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinSquareBrackets);
}
else if (currentKind == SyntaxKind.CloseBracketToken && HasFormattableBracketParent(currentToken))
{
if (currentToken.Parent is ArrayRankSpecifierSyntax)
{
var parent = currentToken.Parent as ArrayRankSpecifierSyntax;
if ((parent.Sizes.Any() && parent.Sizes.First().Kind() != SyntaxKind.OmittedArraySizeExpression) || parent.Sizes.SeparatorCount > 0)
{
// int []: added spacing operation on open [
// int[1], int[,]: need spacing operation
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinSquareBrackets);
}
}
else
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceWithinSquareBrackets);
}
}
// For spacing delimiters - after colon
if (previousToken.IsColonInTypeBaseList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration);
}
// For spacing delimiters - before colon
if (currentToken.IsColonInTypeBaseList())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration);
}
// For spacing delimiters - after comma
if ((previousToken.IsCommaInArgumentOrParameterList() && currentKind != SyntaxKind.OmittedTypeArgumentToken) ||
previousToken.IsCommaInInitializerExpression())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterComma);
}
// For spacing delimiters - before comma
if ((currentToken.IsCommaInArgumentOrParameterList() && previousKind != SyntaxKind.OmittedTypeArgumentToken) ||
currentToken.IsCommaInInitializerExpression())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeComma);
}
// For Spacing delimiters - after Dot
if (previousToken.IsDotInMemberAccessOrQualifiedName())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterDot);
}
// For spacing delimiters - before Dot
if (currentToken.IsDotInMemberAccessOrQualifiedName())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeDot);
}
// For spacing delimiters - after semicolon
if (previousToken.IsSemicolonInForStatement() && currentKind != SyntaxKind.CloseParenToken)
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement);
}
// For spacing delimiters - before semicolon
if (currentToken.IsSemicolonInForStatement())
{
return AdjustSpacesOperationZeroOrOne(optionSet, CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement);
}
// For spacing around the binary operators
if (currentToken.Parent is BinaryExpressionSyntax ||
previousToken.Parent is BinaryExpressionSyntax ||
currentToken.Parent is AssignmentExpressionSyntax ||
previousToken.Parent is AssignmentExpressionSyntax)
{
switch (optionSet.GetOption(CSharpFormattingOptions.SpacingAroundBinaryOperator))
{
case BinaryOperatorSpacingOptions.Single:
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
case BinaryOperatorSpacingOptions.Remove:
if (currentKind == SyntaxKind.IsKeyword ||
currentKind == SyntaxKind.AsKeyword ||
previousKind == SyntaxKind.IsKeyword ||
previousKind == SyntaxKind.AsKeyword)
{
// User want spaces removed but at least one is required for the "as" & "is" keyword
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
else
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
case BinaryOperatorSpacingOptions.Ignore:
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces);
default:
System.Diagnostics.Debug.Assert(false, "Invalid BinaryOperatorSpacingOptions");
break;
}
}
// No space after $" and $@" at the start of an interpolated string
if (previousKind == SyntaxKind.InterpolatedStringStartToken ||
previousKind == SyntaxKind.InterpolatedVerbatimStringStartToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// No space before " at the end of an interpolated string
if (currentKind == SyntaxKind.InterpolatedStringEndToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// No space before { or after } in interpolations
if ((currentKind == SyntaxKind.OpenBraceToken && currentToken.Parent is InterpolationSyntax) ||
(previousKind == SyntaxKind.CloseBraceToken && previousToken.Parent is InterpolationSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// Preserve space after { or before } in interpolations (i.e. between the braces and the expression)
if ((previousKind == SyntaxKind.OpenBraceToken && previousToken.Parent is InterpolationSyntax) ||
(currentKind == SyntaxKind.CloseBraceToken && currentToken.Parent is InterpolationSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces);
}
// No space before or after , in interpolation alignment clause
if ((previousKind == SyntaxKind.CommaToken && previousToken.Parent is InterpolationAlignmentClauseSyntax) ||
(currentKind == SyntaxKind.CommaToken && currentToken.Parent is InterpolationAlignmentClauseSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// No space before or after : in interpolation format clause
if ((previousKind == SyntaxKind.ColonToken && previousToken.Parent is InterpolationFormatClauseSyntax) ||
(currentKind == SyntaxKind.ColonToken && currentToken.Parent is InterpolationFormatClauseSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
return nextOperation.Invoke();
}
public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, SyntaxToken lastToken, OptionSet optionSet, NextAction<SuppressOperation> nextOperation)
{
nextOperation.Invoke(list);
SuppressVariableDeclaration(list, node, optionSet);
}
private void SuppressVariableDeclaration(List<SuppressOperation> list, SyntaxNode node, OptionSet optionSet)
{
if (node.IsKind(SyntaxKind.FieldDeclaration) || node.IsKind(SyntaxKind.EventDeclaration) ||
node.IsKind(SyntaxKind.EventFieldDeclaration) || node.IsKind(SyntaxKind.LocalDeclarationStatement))
{
if (optionSet.GetOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration))
{
var firstToken = node.GetFirstToken(includeZeroWidth: true);
var lastToken = node.GetLastToken(includeZeroWidth: true);
list.Add(FormattingOperations.CreateSuppressOperation(firstToken, lastToken, SuppressOption.NoSpacing));
}
}
}
private AdjustSpacesOperation AdjustSpacesOperationZeroOrOne(OptionSet optionSet, Option<bool> option, AdjustSpacesOption explicitOption = AdjustSpacesOption.ForceSpacesIfOnSingleLine)
{
if (optionSet.GetOption(option))
{
return CreateAdjustSpacesOperation(1, explicitOption);
}
else
{
return CreateAdjustSpacesOperation(0, explicitOption);
}
}
private bool HasFormattableBracketParent(SyntaxToken token)
{
return token.Parent.IsKind(SyntaxKind.ArrayRankSpecifier, SyntaxKind.BracketedArgumentList, SyntaxKind.BracketedParameterList, SyntaxKind.ImplicitArrayCreationExpression);
}
private bool IsFunctionLikeKeywordExpressionKind(SyntaxKind syntaxKind)
{
return (syntaxKind == SyntaxKind.TypeOfExpression || syntaxKind == SyntaxKind.DefaultExpression || syntaxKind == SyntaxKind.SizeOfExpression);
}
private bool IsControlFlowLikeKeywordStatementKind(SyntaxKind syntaxKind)
{
return (syntaxKind == SyntaxKind.IfStatement || syntaxKind == SyntaxKind.WhileStatement || syntaxKind == SyntaxKind.SwitchStatement ||
syntaxKind == SyntaxKind.ForStatement || syntaxKind == SyntaxKind.ForEachStatement || syntaxKind == SyntaxKind.DoStatement ||
syntaxKind == SyntaxKind.CatchDeclaration || syntaxKind == SyntaxKind.UsingStatement || syntaxKind == SyntaxKind.LockStatement ||
syntaxKind == SyntaxKind.FixedStatement);
}
}
}
| KevinRansom/roslyn | src/Workspaces/CSharp/Portable/Formatting/Rules/SpacingFormattingRule.cs | C# | apache-2.0 | 19,660 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.threadpool;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ThreadPoolStats implements Writeable, ToXContentFragment, Iterable<ThreadPoolStats.Stats> {
public static class Stats implements Writeable, ToXContentFragment, Comparable<Stats> {
private final String name;
private final int threads;
private final int queue;
private final int active;
private final long rejected;
private final int largest;
private final long completed;
public Stats(String name, int threads, int queue, int active, long rejected, int largest, long completed) {
this.name = name;
this.threads = threads;
this.queue = queue;
this.active = active;
this.rejected = rejected;
this.largest = largest;
this.completed = completed;
}
public Stats(StreamInput in) throws IOException {
name = in.readString();
threads = in.readInt();
queue = in.readInt();
active = in.readInt();
rejected = in.readLong();
largest = in.readInt();
completed = in.readLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeInt(threads);
out.writeInt(queue);
out.writeInt(active);
out.writeLong(rejected);
out.writeInt(largest);
out.writeLong(completed);
}
public String getName() {
return this.name;
}
public int getThreads() {
return this.threads;
}
public int getQueue() {
return this.queue;
}
public int getActive() {
return this.active;
}
public long getRejected() {
return rejected;
}
public int getLargest() {
return largest;
}
public long getCompleted() {
return this.completed;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
if (threads != -1) {
builder.field(Fields.THREADS, threads);
}
if (queue != -1) {
builder.field(Fields.QUEUE, queue);
}
if (active != -1) {
builder.field(Fields.ACTIVE, active);
}
if (rejected != -1) {
builder.field(Fields.REJECTED, rejected);
}
if (largest != -1) {
builder.field(Fields.LARGEST, largest);
}
if (completed != -1) {
builder.field(Fields.COMPLETED, completed);
}
builder.endObject();
return builder;
}
@Override
public int compareTo(Stats other) {
if ((getName() == null) && (other.getName() == null)) {
return 0;
} else if ((getName() != null) && (other.getName() == null)) {
return 1;
} else if (getName() == null) {
return -1;
} else {
int compare = getName().compareTo(other.getName());
if (compare == 0) {
compare = Integer.compare(getThreads(), other.getThreads());
}
return compare;
}
}
}
private List<Stats> stats;
public ThreadPoolStats(List<Stats> stats) {
Collections.sort(stats);
this.stats = stats;
}
public ThreadPoolStats(StreamInput in) throws IOException {
stats = in.readList(Stats::new);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeList(stats);
}
@Override
public Iterator<Stats> iterator() {
return stats.iterator();
}
static final class Fields {
static final String THREAD_POOL = "thread_pool";
static final String THREADS = "threads";
static final String QUEUE = "queue";
static final String ACTIVE = "active";
static final String REJECTED = "rejected";
static final String LARGEST = "largest";
static final String COMPLETED = "completed";
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject(Fields.THREAD_POOL);
for (Stats stat : stats) {
stat.toXContent(builder, params);
}
builder.endObject();
return builder;
}
}
| GlenRSmith/elasticsearch | server/src/main/java/org/elasticsearch/threadpool/ThreadPoolStats.java | Java | apache-2.0 | 5,488 |
/*
* Copyright 2003,2004 The Apache Software Foundation
*
* 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 net.sf.cglib.proxy;
import java.util.List;
import net.sf.cglib.core.*;
interface CallbackGenerator
{
void generate(ClassEmitter ce, Context context, List methods) throws Exception;
void generateStatic(CodeEmitter e, Context context, List methods) throws Exception;
interface Context
{
ClassLoader getClassLoader();
CodeEmitter beginMethod(ClassEmitter ce, MethodInfo method);
int getOriginalModifiers(MethodInfo method);
int getIndex(MethodInfo method);
void emitCallback(CodeEmitter ce, int index);
Signature getImplSignature(MethodInfo method);
void emitInvoke(CodeEmitter e, MethodInfo method);
}
}
| vongosling/cglib-ext | src/proxy/net/sf/cglib/proxy/CallbackGenerator.java | Java | apache-2.0 | 1,311 |
RSpec::Matchers.define :have_rule do |rule|
match do |subject|
if subject.class.name == 'Serverspec::Type::Iptables'
subject.has_rule?(rule, @table, @chain)
else
subject.has_rule?(rule)
end
end
chain :with_table do |table|
@table = table
end
chain :with_chain do |chain|
@chain = chain
end
end
| memelet/serverspec | lib/serverspec/matchers/have_rule.rb | Ruby | mit | 340 |
/*
* Copyright 2012 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.drools.workbench.models.datamodel.rule;
public class ExpressionUnboundFact extends ExpressionPart {
private String factType;
public ExpressionUnboundFact() {
}
public ExpressionUnboundFact( String factType ) {
super( factType,
factType,
factType );
this.factType = factType;
}
public String getFactType() {
return factType;
}
@Override
public void accept( ExpressionVisitor visitor ) {
visitor.visit( this );
}
@Override
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
if ( !super.equals( o ) ) {
return false;
}
ExpressionUnboundFact that = (ExpressionUnboundFact) o;
if ( factType != null ? !factType.equals( that.factType ) : that.factType != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = ~~result;
result = 31 * result + ( factType != null ? factType.hashCode() : 0 );
result = ~~result;
return result;
}
}
| rokn/Count_Words_2015 | testing/drools-master/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/rule/ExpressionUnboundFact.java | Java | mit | 1,906 |
<?php
/**
* @file
* Initiates a browser-based installation of Drupal.
*/
// Change the directory to the Drupal root.
chdir('..');
/**
* Global flag to indicate the site is in installation mode.
*
* The constant is defined using define() instead of const so that PHP
* versions prior to 5.3 can display proper PHP requirements instead of causing
* a fatal error.
*/
define('MAINTENANCE_MODE', 'install');
// Exit early if running an incompatible PHP version to avoid fatal errors.
// The minimum version is specified explicitly, as DRUPAL_MINIMUM_PHP is not
// yet available. It is defined in bootstrap.inc, but it is not possible to
// load that file yet as it would cause a fatal error on older versions of PHP.
if (version_compare(PHP_VERSION, '5.4.2') < 0) {
print 'Your PHP installation is too old. Drupal requires at least PHP 5.4.2. See the <a href="http://drupal.org/requirements">system requirements</a> page for more information.';
exit;
}
// Start the installer.
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/includes/install.core.inc';
install_drupal();
| drupaals/demo.com | d8/core/install.php | PHP | gpl-2.0 | 1,109 |
import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
import codecs
from pattern.vector import Document, PORTER, LEMMA
# A Document is a "bag-of-words" that splits a string into words and counts them.
# A list of words or dictionary of (word, count)-items can also be given.
# Words (or more generally "features") and their word count ("feature weights")
# can be used to compare documents. The word count in a document is normalized
# between 0.0-1.0 so that shorted documents can be compared to longer documents.
# Words can be stemmed or lemmatized before counting them.
# The purpose of stemming is to bring variant forms a word together.
# For example, "conspiracy" and "conspired" are both stemmed to "conspir".
# Nowadays, lemmatization is usually preferred over stemming,
# e.g., "conspiracies" => "conspiracy", "conspired" => "conspire".
s = """
The shuttle Discovery, already delayed three times by technical problems and bad weather,
was grounded again Friday, this time by a potentially dangerous gaseous hydrogen leak
in a vent line attached to the ship's external tank.
The Discovery was initially scheduled to make its 39th and final flight last Monday,
bearing fresh supplies and an intelligent robot for the International Space Station.
But complications delayed the flight from Monday to Friday,
when the hydrogen leak led NASA to conclude that the shuttle would not be ready to launch
before its flight window closed this Monday.
"""
# With threshold=1, only words that occur more than once are counted.
# With stopwords=False, words like "the", "and", "I", "is" are ignored.
document = Document(s, threshold=1, stopwords=False)
print document.words
print
# The /corpus folder contains texts mined from Wikipedia.
# Below is the mining script (we already executed it for you):
#import os, codecs
#from pattern.web import Wikipedia
#
#w = Wikipedia()
#for q in (
# "badger", "bear", "dog", "dolphin", "lion", "parakeet",
# "rabbit", "shark", "sparrow", "tiger", "wolf"):
# s = w.search(q, cached=True)
# s = s.plaintext()
# print os.path.join("corpus2", q+".txt")
# f = codecs.open(os.path.join("corpus2", q+".txt"), "w", encoding="utf-8")
# f.write(s)
# f.close()
# Loading a document from a text file:
f = os.path.join(os.path.dirname(__file__), "corpus", "wolf.txt")
s = codecs.open(f, encoding="utf-8").read()
document = Document(s, name="wolf", stemmer=PORTER)
print document
print document.keywords(top=10) # (weight, feature)-items.
print
# Same document, using lemmatization instead of stemming (slower):
document = Document(s, name="wolf", stemmer=LEMMA)
print document
print document.keywords(top=10)
print
# In summary, a document is a bag-of-words representation of a text.
# Bag-of-words means that the word order is discarded.
# The dictionary of words (features) and their normalized word count (weights)
# is also called the document vector:
document = Document("a black cat and a white cat", stopwords=True)
print document.words
print document.vector.features
for feature, weight in document.vector.items():
print feature, weight
# Document vectors can be bundled into a Model (next example). | krishna11888/ai | third_party/pattern/examples/05-vector/01-document.py | Python | gpl-2.0 | 3,205 |
/*
* Dynamic To Top Plugin
* http://www.mattvarone.com
*
* By Matt Varone
* @sksmatt
*
*/
var mv_dynamic_to_top;(function($,mv_dynamic_to_top){jQuery.fn.DynamicToTop=function(options){var defaults={text:mv_dynamic_to_top.text,min:parseInt(mv_dynamic_to_top.min,10),fade_in:600,fade_out:400,speed:parseInt(mv_dynamic_to_top.speed,10),easing:mv_dynamic_to_top.easing,version:mv_dynamic_to_top.version,id:'dynamic-to-top'},settings=$.extend(defaults,options);if(settings.version===""||settings.version==='0'){settings.text='<span> </span>';}
if(!$.isFunction(settings.easing)){settings.easing='linear';}
var $toTop=$('<a href=\"#\" id=\"'+settings.id+'\"></a>').html(settings.text);$toTop.hide().appendTo('body').click(function(){$('html, body').stop().animate({scrollTop:0},settings.speed,settings.easing);return false;});$(window).scroll(function(){var sd=jQuery(window).scrollTop();if(typeof document.body.style.maxHeight==="undefined"){$toTop.css({'position':'absolute','top':sd+$(window).height()-mv_dynamic_to_top.margin});}
if(sd>settings.min){$toTop.fadeIn(settings.fade_in);}else{$toTop.fadeOut(settings.fade_out);}});};$('body').DynamicToTop();})(jQuery,mv_dynamic_to_top); | richardPZH/wordpress-plus | wp-content/plugins/dynamic-to-top/js/dynamic.to.top.min.js | JavaScript | gpl-2.0 | 1,192 |
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build irix
package syscall
//sysnb raw_ptrace(request int, pid int, addr *byte, data *byte) (err Errno)
//ptrace(request _C_int, pid Pid_t, addr *byte, data *byte) _C_long
| krichter722/gcc | libgo/go/syscall/libcall_irix.go | GO | gpl-2.0 | 338 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'role', language 'en', branch 'MOODLE_20_STABLE'
*
* @package core_role
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['addinganewrole'] = 'Adding a new role';
$string['addrole'] = 'Add a new role';
$string['advancedoverride'] = 'Advanced role override';
$string['allow'] = 'Allow';
$string['allowassign'] = 'Allow role assignments';
$string['allowed'] = 'Allowed';
$string['allowoverride'] = 'Allow role overrides';
$string['allowroletoassign'] = 'Allow users with role {$a->fromrole} to assign the role {$a->targetrole}';
$string['allowroletooverride'] = 'Allow users with role {$a->fromrole} to override the role {$a->targetrole}';
$string['allowroletoswitch'] = 'Allow users with role {$a->fromrole} to switch roles to the role {$a->targetrole}';
$string['allowswitch'] = 'Allow role switches';
$string['allsiteusers'] = 'All site users';
$string['archetype'] = 'Role archetype';
$string['archetype_help'] = 'The role archetype determines the permissions when a role is reset to default. It also determines any new permissions for the role when the site is upgraded.';
$string['archetypecoursecreator'] = 'ARCHETYPE: Course creator';
$string['archetypeeditingteacher'] = 'ARCHETYPE: Teacher (editing)';
$string['archetypefrontpage'] = 'ARCHETYPE: Authenticated user on frontpage';
$string['archetypeguest'] = 'ARCHETYPE: Guest';
$string['archetypemanager'] = 'ARCHETYPE: Manager';
$string['archetypestudent'] = 'ARCHETYPE: Student';
$string['archetypeteacher'] = 'ARCHETYPE: Teacher (non-editing)';
$string['archetypeuser'] = 'ARCHETYPE: Authenticated user';
$string['assignanotherrole'] = 'Assign another role';
$string['assignerror'] = 'Error while assigning the role {$a->role} to user {$a->user}.';
$string['assignglobalroles'] = 'Assign system roles';
$string['assignedroles'] = 'Assigned roles';
$string['assignmentcontext'] = 'Assignment context';
$string['assignmentoptions'] = 'Assignment options';
$string['assignrolenameincontext'] = 'Assign role \'{$a->role}\' in {$a->context}';
$string['assignrole'] = 'Assign role';
$string['assignroles'] = 'Assign roles';
$string['assignroles_help'] = 'By assigning a role to a user in a context, you are granting them the permissions contained in that role, for the current context and all lower contexts. For example, if a user is assigned the role of student in a course, they will also have the role of student for all activities and blocks within the course.';
$string['assignroles_link'] = 'admin/roles/assign';
$string['assignrolesin'] = 'Assign roles in {$a}';
$string['assignrolesrelativetothisuser'] = 'Assign roles relative to this user';
$string['backtoallroles'] = 'Back to the list of all roles';
$string['backup:anonymise'] = 'Anonymise user data on backup';
$string['backup:backupactivity'] = 'Backup activities';
$string['backup:backupcourse'] = 'Backup courses';
$string['backup:backupsection'] = 'Backup sections';
$string['backup:configure'] = 'Configure backup options';
$string['backup:downloadfile'] = 'Download files from backup areas';
$string['backup:backuptargethub'] = 'Backup for hub';
$string['backup:backuptargetimport'] = 'Backup for import';
$string['backup:userinfo'] = 'Backup user data';
$string['badges:awardbadge'] = 'Award badge to a user';
$string['badges:createbadge'] = 'Create/duplicate badges';
$string['badges:configuredetails'] = 'Set up/edit badge details';
$string['badges:configurecriteria'] = 'Set up/edit criteria of earning a badge';
$string['badges:configuremessages'] = 'Configure badge messages';
$string['badges:deletebadge'] = 'Delete badges';
$string['badges:earnbadge'] = 'Earn badge';
$string['badges:manageglobalsettings'] = 'Manage badges global settings';
$string['badges:manageownbadges'] = 'View and manage own earned badges';
$string['badges:viewawarded'] = 'View users who earned a specific badge without being able to award a badge';
$string['badges:viewbadges'] = 'View available badges without earning them';
$string['badges:viewotherbadges'] = 'View public badges in other users\' profiles';
$string['block:edit'] = 'Edit a block\'s settings';
$string['block:view'] = 'View block';
$string['blog:associatecourse'] = 'This capability is deprecated and does nothing.';
$string['blog:associatemodule'] = 'This capability is deprecated and does nothing.';
$string['blog:create'] = 'Create new blog entries';
$string['blog:manageentries'] = 'Edit and manage entries';
$string['blog:manageexternal'] = 'Edit and manage external blogs';
$string['blog:manageofficialtags'] = 'Manage official tags';
$string['blog:managepersonaltags'] = 'Manage personal tags';
$string['blog:search'] = 'Search blog entries';
$string['blog:view'] = 'View blog entries';
$string['blog:viewdrafts'] = 'View draft blog entries';
$string['calendar:manageentries'] = 'Manage any calendar entries';
$string['calendar:managegroupentries'] = 'Manage group calendar entries';
$string['calendar:manageownentries'] = 'Manage own calendar entries';
$string['capabilities'] = 'Capabilities';
$string['capability'] = 'Capability';
$string['category:create'] = 'Create categories';
$string['category:delete'] = 'Delete categories';
$string['category:manage'] = 'Manage categories';
$string['category:update'] = 'Update categories';
$string['category:viewhiddencategories'] = 'See hidden categories';
$string['category:visibility'] = 'See hidden categories';
$string['cohort:assign'] = 'Add and remove cohort members';
$string['cohort:view'] = 'View site-wide cohorts';
$string['cohort:manage'] = 'Create, delete and move cohorts';
$string['comment:delete'] = 'Delete comments';
$string['comment:post'] = 'Post comments';
$string['comment:view'] = 'Read comments';
$string['community:add'] = 'Use the community block to search hubs and find courses';
$string['community:download'] = 'Download a course from the community block';
$string['confirmaddadmin'] = 'Do you really want to add user <strong>{$a}</strong> as new site administrator?';
$string['confirmdeladmin'] = 'Do you really want to remove user <strong>{$a}</strong> from the list of site administrators?';
$string['confirmroleprevent'] = 'Do you really want to remove <strong>{$a->role}</strong> from the list of allowed roles for capability {$a->cap} in context {$a->context}?';
$string['confirmroleunprohibit'] = 'Do you really want to remove <strong>{$a->role}</strong> from the list of prohibited roles for capability {$a->cap} in context {$a->context}?';
$string['confirmunassign'] = 'Are you sure you wish to remove this role from this user?';
$string['confirmunassigntitle'] = 'Confirm role change';
$string['confirmunassignyes'] = 'Remove';
$string['confirmunassignno'] = 'Cancel';
$string['context'] = 'Context';
$string['course:activityvisibility'] = 'Hide/show activities';
$string['course:bulkmessaging'] = 'Send a message to many people';
$string['course:create'] = 'Create courses';
$string['course:delete'] = 'Delete courses';
$string['course:viewsuspendedusers'] = 'View suspended users';
$string['course:changecategory'] = 'Change course category';
$string['course:changefullname'] = 'Change course full name';
$string['course:changeidnumber'] = 'Change course ID number';
$string['course:changeshortname'] = 'Change course short name';
$string['course:changesummary'] = 'Change course summary';
$string['course:enrolconfig'] = 'Configure enrol instances in courses';
$string['course:enrolreview'] = 'Review course enrolments';
$string['course:ignorefilesizelimits'] = 'Use files larger than any file size restrictions';
$string['course:isincompletionreports'] = 'Be shown on completion reports';
$string['course:manageactivities'] = 'Manage activities';
$string['course:managefiles'] = 'Manage files';
$string['course:managegrades'] = 'Manage grades';
$string['course:managegroups'] = 'Manage groups';
$string['course:managescales'] = 'Manage scales';
$string['course:markcomplete'] = 'Mark users as complete in course completion';
$string['course:movesections'] = 'Move sections';
$string['course:publish'] = 'Publish a course into hub';
$string['course:request'] = 'Request new courses';
$string['course:reset'] = 'Reset course';
$string['course:reviewotherusers'] = 'Review other users';
$string['course:sectionvisibility'] = 'Control section visibility';
$string['course:setcurrentsection'] = 'Set current section';
$string['course:update'] = 'Update course settings';
$string['course:useremail'] = 'Enable/disable email address';
$string['course:view'] = 'View courses without participation';
$string['course:viewcoursegrades'] = 'View course grades';
$string['course:viewhiddenactivities'] = 'View hidden activities';
$string['course:viewhiddencourses'] = 'View hidden courses';
$string['course:viewhiddensections'] = 'View hidden sections';
$string['course:viewhiddenuserfields'] = 'View hidden user fields';
$string['course:viewparticipants'] = 'View participants';
$string['course:viewscales'] = 'View scales';
$string['course:visibility'] = 'Hide/show courses';
$string['createrolebycopying'] = 'Create a new role by copying {$a}';
$string['createthisrole'] = 'Create this role';
$string['currentcontext'] = 'Current context';
$string['currentrole'] = 'Current role';
$string['customroledescription'] = 'Custom description';
$string['customroledescription_help'] = 'Descriptions of standard roles are localised automatically if the custom description is empty.';
$string['customrolename'] = 'Custom full name';
$string['customrolename_help'] = 'Names of standard roles are localised automatically if the custom name is empty. You must provide a full name for all custom roles.';
$string['defaultrole'] = 'Default role';
$string['defaultx'] = 'Default: {$a}';
$string['defineroles'] = 'Define roles';
$string['deletecourseoverrides'] = 'Delete all overrides in course';
$string['deletelocalroles'] = 'Delete all local role assignments';
$string['deleterolesure'] = '<p>Are you sure that you want to delete role "{$a->name} ({$a->shortname})"?</p><p>Currently this role is assigned to {$a->count} users.</p>';
$string['deletexrole'] = 'Delete {$a} role';
$string['duplicaterole'] = 'Duplicate role';
$string['duplicaterolesure'] = '<p>Are you sure that you want to duplicate role "{$a->name} ({$a->shortname})"?</p>';
$string['editingrolex'] = 'Editing role \'{$a}\'';
$string['editrole'] = 'Edit role';
$string['editxrole'] = 'Edit {$a} role';
$string['errorbadrolename'] = 'Incorrect role name';
$string['errorbadroleshortname'] = 'Incorrect role short name';
$string['errorexistsrolename'] = 'Role name already exists';
$string['errorexistsroleshortname'] = 'Role name already exists';
$string['eventroleallowassignupdated'] = 'Allow role assignment';
$string['eventroleallowoverrideupdated'] = 'Allow role override';
$string['eventroleallowswitchupdated'] = 'Allow role switch';
$string['eventroleassigned'] = 'Role assigned';
$string['eventrolecapabilitiesupdated'] = 'Role capabilities updated';
$string['eventroledeleted'] = 'Role deleted';
$string['eventroleunassigned'] = 'Role unassigned';
$string['existingadmins'] = 'Current site administrators';
$string['existingusers'] = '{$a} existing users';
$string['explanation'] = 'Explanation';
$string['export'] = 'Export';
$string['extusers'] = 'Existing users';
$string['extusersmatching'] = 'Existing users matching \'{$a}\'';
$string['filter:manage'] = 'Manage local filter settings';
$string['frontpageuser'] = 'Authenticated user on frontpage';
$string['frontpageuserdescription'] = 'All logged in users in the frontpage course.';
$string['globalrole'] = 'System role';
$string['globalroleswarning'] = 'WARNING! Any roles you assign from this page will apply to the assigned users throughout the entire system, including the front page and all the courses.';
$string['gotoassignroles'] = 'Go to Assign roles for this {$a->contextlevel}';
$string['gotoassignsystemroles'] = 'Go to Assign system roles';
$string['grade:edit'] = 'Edit grades';
$string['grade:export'] = 'Export grades';
$string['grade:hide'] = 'Hide/unhide grades or items';
$string['grade:import'] = 'Import grades';
$string['grade:lock'] = 'Lock grades or items';
$string['grade:manage'] = 'Manage grade items';
$string['grade:managegradingforms'] = 'Manage advanced grading methods';
$string['grade:managesharedforms'] = 'Manage advanced grading form templates';
$string['grade:sharegradingforms'] = 'Share advanced grading form as a template';
$string['grade:manageletters'] = 'Manage letter grades';
$string['grade:manageoutcomes'] = 'Manage grade outcomes';
$string['grade:override'] = 'Override grades';
$string['grade:unlock'] = 'Unlock grades or items';
$string['grade:view'] = 'View own grades';
$string['grade:viewall'] = 'View grades of other users';
$string['grade:viewhidden'] = 'View hidden grades for owner';
$string['highlightedcellsshowdefault'] = 'The permissions highlighted in the table below are the defaults for the role archetype currently selected above.';
$string['highlightedcellsshowinherit'] = 'The highlighted cells in the table below show the permission (if any) that will be inherited. Apart from the capabilities whose permission you actually want to alter, you should leave everything set to Inherit.';
$string['checkglobalpermissions'] = 'Check system permissions';
$string['checkpermissions'] = 'Check permissions';
$string['checkpermissionsin'] = 'Check permissions in {$a}';
$string['checksystempermissionsfor'] = 'Check system permissions for {$a->fullname}';
$string['checkuserspermissionshere'] = 'Check permissions for {$a->fullname} has in this {$a->contextlevel}';
$string['chooseroletoassign'] = 'Please choose a role to assign';
$string['inactiveformorethan'] = 'inactive for more than {$a->timeperiod}';
$string['ingroup'] = 'in the group "{$a->group}"';
$string['inherit'] = 'Inherit';
$string['invalidpresetfile'] = 'Invalid role definition file';
$string['legacy:admin'] = 'LEGACY ROLE: Administrator';
$string['legacy:coursecreator'] = 'LEGACY ROLE: Course creator';
$string['legacy:editingteacher'] = 'LEGACY ROLE: Teacher (editing)';
$string['legacy:guest'] = 'LEGACY ROLE: Guest';
$string['legacy:student'] = 'LEGACY ROLE: Student';
$string['legacy:teacher'] = 'LEGACY ROLE: Teacher (non-editing)';
$string['legacytype'] = 'Legacy role type';
$string['legacy:user'] = 'LEGACY ROLE: Authenticated user';
$string['listallroles'] = 'List all roles';
$string['localroles'] = 'Locally assigned roles';
$string['mainadmin'] = 'Main administrator';
$string['mainadminset'] = 'Set main admin';
$string['manageadmins'] = 'Manage site administrators';
$string['manager'] = 'Manager';
$string['managerdescription'] = 'Managers can access course and modify them, they usually do not participate in courses.';
$string['manageroles'] = 'Manage roles';
$string['maybeassignedin'] = 'Context types where this role may be assigned';
$string['morethan'] = 'More than {$a}';
$string['multipleroles'] = 'Multiple roles';
$string['my:manageblocks'] = 'Manage Dashboard page blocks';
$string['my:configsyspages'] = 'Configure system templates for Dashboard pages';
$string['neededroles'] = 'Roles with permission';
$string['nocapabilitiesincontext'] = 'No capabilities available in this context';
$string['noneinthisx'] = 'None in this {$a}';
$string['noneinthisxmatching'] = 'No users matching \'{$a->search}\' in this {$a->contexttype}';
$string['norole'] = 'No role';
$string['noroles'] = 'No roles';
$string['noroleassignments'] = 'This user does not have any role assignments anywhere in this site.';
$string['notabletoassignroleshere'] = 'You are not able to assign any roles here';
$string['notabletooverrideroleshere'] = 'You are not able to override the permissions on any roles here';
$string['notes:manage'] = 'Manage notes';
$string['notes:view'] = 'View notes';
$string['notset'] = 'Not set';
$string['overrideanotherrole'] = 'Override another role';
$string['overridecontext'] = 'Override context';
$string['overridepermissions'] = 'Override permissions';
$string['overridepermissions_help'] = 'Permissions overrides enable selected capabilities to be allowed or prevented in a specific context.';
$string['overridepermissions_link'] = 'admin/roles/override';
$string['overridepermissionsforrole'] = 'Override permissions for role \'{$a->role}\' in {$a->context}';
$string['overridepermissionsin'] = 'Override permissions in {$a}';
$string['overrideroles'] = 'Override roles';
$string['overriderolesin'] = 'Override roles in {$a}';
$string['overrides'] = 'Overrides';
$string['overridesbycontext'] = 'Overrides (by context)';
$string['permission'] = 'Permission';
$string['permission_help'] = 'Permissions are capability settings. There are 4 options:
* Not set
* Allow - Permission is granted for the capability
* Prevent - Permission is removed for the capability, even if allowed in a higher context
* Prohibit - Permission is completely denied and cannot be overridden at any lower (more specific) context';
$string['permissions'] = 'Permissions';
$string['permissionsforuser'] = 'Permissions for user {$a}';
$string['permissionsincontext'] = 'Permissions in {$a}';
$string['portfolio:export'] = 'Export to portfolios';
$string['potentialusers'] = '{$a} potential users';
$string['potusers'] = 'Potential users';
$string['potusersmatching'] = 'Potential users matching \'{$a}\'';
$string['prevent'] = 'Prevent';
$string['prohibit'] = 'Prohibit';
$string['prohibitedroles'] = 'Prohibited';
$string['question:add'] = 'Add new questions';
$string['question:config'] = 'Configure question types';
$string['question:editall'] = 'Edit all questions';
$string['question:editmine'] = 'Edit your own questions';
$string['question:flag'] = 'Flag questions while attempting them';
$string['question:managecategory'] = 'Edit question categories';
$string['question:moveall'] = 'Move all questions';
$string['question:movemine'] = 'Move your own questions';
$string['question:useall'] = 'Use all questions';
$string['question:usemine'] = 'Use your own questions';
$string['question:viewall'] = 'View all questions';
$string['question:viewmine'] = 'View your own questions';
$string['rating:rate'] = 'Add ratings to items';
$string['rating:view'] = 'View the total rating you received';
$string['rating:viewany'] = 'View total ratings that anyone received';
$string['rating:viewall'] = 'View all raw ratings given by individuals';
$string['resetrole'] = 'Reset';
$string['resettingrole'] = 'Resetting role \'{$a}\'';
$string['restore:configure'] = 'Configure restore options';
$string['restore:createuser'] = 'Create users on restore';
$string['restore:restoreactivity'] = 'Restore activities';
$string['restore:restoresection'] = 'Restore sections';
$string['restore:restorecourse'] = 'Restore courses';
$string['restore:restoretargethub'] = 'Restore from files targeted as hub';
$string['restore:restoretargetimport'] = 'Restore from files targeted as import';
$string['restore:rolldates'] = 'Allowed to roll activity configuration dates on restore';
$string['restore:uploadfile'] = 'Upload files to backup areas';
$string['restore:userinfo'] = 'Restore user data';
$string['restore:viewautomatedfilearea'] = 'Restore courses from automated backups';
$string['risks'] = 'Risks';
$string['roleallowheader'] = 'Allow role:';
$string['roleallowinfo'] = 'Select a role to be added to the list of allowed roles in context {$a->context}, capability {$a->cap}:';
$string['role:assign'] = 'Assign roles to users';
$string['roleassignments'] = 'Role assignments';
$string['roledefinitions'] = 'Role definitions';
$string['rolefullname'] = 'Role name';
$string['roleincontext'] = '{$a->role} in {$a->context}';
$string['role:manage'] = 'Create and manage roles';
$string['role:override'] = 'Override permissions for others';
$string['role:review'] = 'Review permissions for others';
$string['roleprohibitheader'] = 'Prohibit role';
$string['roleprohibitinfo'] = 'Select a role to be added to the list of prohibited roles in context {$a->context}, capability {$a->cap}:';
$string['rolerisks'] = 'Role risks';
$string['roles'] = 'Roles';
$string['roles_help'] = 'A role is a collection of permissions defined for the whole system that you can assign to specific users in specific contexts.';
$string['roles_link'] = 'roles';
$string['role:safeoverride'] = 'Override safe permissions for others';
$string['roleselect'] = 'Select role';
$string['rolesforuser'] = 'Roles for user {$a}';
$string['roleshortname'] = 'Short name';
$string['roleshortname_help'] = 'Role short name is a low level role identifier in which only ASCII alphanumeric characters are allowed. Do not change short names of standard roles.';
$string['role:switchroles'] = 'Switch to other roles';
$string['roletoassign'] = 'Role to assign';
$string['roletooverride'] = 'Role to override';
$string['safeoverridenotice'] = 'Note: Capabilities with higher risks are locked because you are only allowed to override safe capabilities.';
$string['selectanotheruser'] = 'Select another user';
$string['selectauser'] = 'Select a user';
$string['selectrole'] = 'Select a role';
$string['showallroles'] = 'Show all roles';
$string['showthisuserspermissions'] = 'Show this user\'s permissions';
$string['site:accessallgroups'] = 'Access all groups';
$string['siteadministrators'] = 'Site administrators';
$string['site:approvecourse'] = 'Approve course creation';
$string['site:backup'] = 'Backup courses';
$string['site:config'] = 'Change site configuration';
$string['site:doanything'] = 'Allowed to do everything';
$string['site:doclinks'] = 'Show links to offsite docs';
$string['site:forcelanguage'] = 'Override course language';
$string['site:import'] = 'Import other courses into a course';
$string['site:manageblocks'] = 'Manage blocks on a page';
$string['site:mnetloginfromremote'] = 'Login from a remote application via MNet';
$string['site:mnetlogintoremote'] = 'Roam to a remote application via MNet';
$string['site:readallmessages'] = 'Read all messages on site';
$string['site:restore'] = 'Restore courses';
$string['site:sendmessage'] = 'Send messages to any user';
$string['site:trustcontent'] = 'Trust submitted content';
$string['site:uploadusers'] = 'Upload new users from file';
$string['site:viewfullnames'] = 'Always see full names of users';
$string['site:viewparticipants'] = 'View participants';
$string['site:viewreports'] = 'View reports';
$string['site:viewuseridentity'] = 'See full user identity in lists';
$string['tag:create'] = 'Create new tags';
$string['tag:edit'] = 'Edit existing tags';
$string['tag:editblocks'] = 'Edit blocks in tags pages';
$string['tag:manage'] = 'Manage all tags';
$string['tag:flag'] = 'Flag tags as inappropriate';
$string['thisusersroles'] = 'This user\'s role assignments';
$string['thisnewrole'] = 'This new role';
$string['unassignarole'] = 'Unassign role {$a}';
$string['unassignerror'] = 'Error while unassigning the role {$a->role} from user {$a->user}.';
$string['unassignconfirm'] = 'Do you really want to unassign "{$a->role}" role from user "{$a->user}"?';
$string['user:changeownpassword'] = 'Change own password';
$string['user:create'] = 'Create users';
$string['user:delete'] = 'Delete users';
$string['user:editmessageprofile'] = 'Edit user messaging profile';
$string['user:editownmessageprofile'] = 'Edit own user messaging profile';
$string['user:editownprofile'] = 'Edit own user profile';
$string['user:editprofile'] = 'Edit user profile';
$string['user:ignoreuserquota'] = 'Ignore user quota limit';
$string['user:loginas'] = 'Login as other users';
$string['user:manageblocks'] = 'Manage blocks on user profile of other users';
$string['user:manageownblocks'] = 'Manage blocks on own public user profile';
$string['user:manageownfiles'] = 'Manage files on own private file areas';
$string['user:managesyspages'] = 'Configure default page layout for public user profiles';
$string['user:readuserblogs'] = 'View all user blogs';
$string['user:readuserposts'] = 'View all user forum posts';
$string['user:update'] = 'Update user profiles';
$string['user:viewalldetails'] = 'View user full information';
$string['user:viewdetails'] = 'View user profiles';
$string['user:viewhiddendetails'] = 'View hidden details of users';
$string['user:viewlastip'] = 'View user last ip address';
$string['user:viewuseractivitiesreport'] = 'See user activity reports';
$string['user:viewusergrades'] = 'View user grades';
$string['roleresetdefaults'] = 'Defaults';
$string['roleresetrole'] = 'Use role or archetype';
$string['rolerepreset'] = 'Use role preset';
$string['usersfrom'] = 'Users from {$a}';
$string['usersfrommatching'] = 'Users from {$a->contextname} matching \'{$a->search}\'';
$string['usersinthisx'] = 'Users in this {$a}';
$string['usersinthisxmatching'] = 'Users in this {$a->contexttype} matching \'{$a->search}\'';
$string['userswithrole'] = 'All users with a role';
$string['userswiththisrole'] = 'Users with role';
$string['useshowadvancedtochange'] = 'Use \'Show advanced\' to change';
$string['viewingdefinitionofrolex'] = 'Viewing the definition of role \'{$a}\'';
$string['viewrole'] = 'View role details';
$string['webservice:createtoken'] = 'Create a web service token';
$string['webservice:createmobiletoken'] = 'Create a web service token for mobile access';
$string['whydoesuserhavecap'] = 'Why does {$a->fullname} have capability {$a->capability} in context {$a->context}?';
$string['whydoesusernothavecap'] = 'Why does {$a->fullname} not have capability {$a->capability} in context {$a->context}?';
$string['xroleassignments'] = '{$a}\'s role assignments';
$string['xuserswiththerole'] = 'Users with the role "{$a->role}"';
| nagyistoce/moodle | lang/en/role.php | PHP | gpl-3.0 | 26,335 |
// 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.
#nullable disable
using System;
using Microsoft.CodeAnalysis.ErrorReporting;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class ExceptionHelpersTests : TestBase
{
/// <summary>
/// Test that throwing OperationCanceledException does NOT trigger FailFast
/// </summary>
[Fact]
public void TestExecuteWithErrorReportingThrowOperationCanceledException()
{
var finallyExecuted = false;
void a()
{
try
{
throw new OperationCanceledException();
}
finally
{
finallyExecuted = true;
}
}
try
{
try
{
a();
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
Assert.True(false, "Should not get here because an exception should be thrown before this point.");
}
catch (OperationCanceledException)
{
Assert.True(finallyExecuted);
return;
}
Assert.True(false, "Should have returned in the catch block before this point.");
}
}
}
| AmadeusW/roslyn | src/Workspaces/CoreTest/UtilityTest/ExceptionHelpersTests.cs | C# | apache-2.0 | 1,686 |
"""
CMSIS-DAP Interface Firmware
Copyright (c) 2009-2013 ARM Limited
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.
Extract and patch the interface without bootloader
"""
from options import get_options
from paths import get_interface_path, TMP_DIR
from utils import gen_binary, is_lpc, split_path
from os.path import join
if __name__ == '__main__':
options = get_options()
in_path = get_interface_path(options.interface, options.target, bootloader=False)
_, name, _ = split_path(in_path)
out_path = join(TMP_DIR, name + '.bin')
print '\nELF: %s' % in_path
gen_binary(in_path, out_path, is_lpc(options.interface))
print "\nBINARY: %s" % out_path
| flyhung/CMSIS-DAP | tools/get_binary.py | Python | apache-2.0 | 1,166 |
/*
* Copyright 2014 Soichiro Kashima
*
* 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 com.marshalchen.common.demoofui.observablescrollview;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ObservableWebView;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.marshalchen.common.demoofui.R;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
public class ToolbarControlWebViewActivity extends ActionBarActivity {
private View mHeaderView;
private View mToolbarView;
private ObservableScrollView mScrollView;
private boolean mFirstScroll;
private boolean mDragging;
private int mBaseTranslationY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.observable_scroll_view_activity_toolbarcontrolwebview);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
mHeaderView = findViewById(R.id.header);
ViewCompat.setElevation(mHeaderView, getResources().getDimension(R.dimen.toolbar_elevation));
mToolbarView = findViewById(R.id.toolbar);
mScrollView = (ObservableScrollView) findViewById(R.id.scroll);
mScrollView.setScrollViewCallbacks(mScrollViewScrollCallbacks);
ObservableWebView mWebView = (ObservableWebView) findViewById(R.id.web);
mWebView.setScrollViewCallbacks(mWebViewScrollCallbacks);
mWebView.loadUrl("file:///android_asset/lipsum.html");
}
private ObservableScrollViewCallbacks mScrollViewScrollCallbacks = new ObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
if (mDragging) {
int toolbarHeight = mToolbarView.getHeight();
if (mFirstScroll) {
mFirstScroll = false;
float currentHeaderTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (-toolbarHeight < currentHeaderTranslationY && toolbarHeight < scrollY) {
mBaseTranslationY = scrollY;
}
}
int headerTranslationY = Math.min(0, Math.max(-toolbarHeight, -(scrollY - mBaseTranslationY)));
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewHelper.setTranslationY(mHeaderView, headerTranslationY);
}
}
@Override
public void onDownMotionEvent() {
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
mDragging = false;
mBaseTranslationY = 0;
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
int toolbarHeight = mToolbarView.getHeight();
if (scrollState == ScrollState.UP) {
if (toolbarHeight < mScrollView.getCurrentScrollY()) {
if (headerTranslationY != -toolbarHeight) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(-toolbarHeight).setDuration(200).start();
}
}
} else if (scrollState == ScrollState.DOWN) {
if (toolbarHeight < mScrollView.getCurrentScrollY()) {
if (headerTranslationY != 0) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start();
}
}
}
}
};
private ObservableScrollViewCallbacks mWebViewScrollCallbacks = new ObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
}
@Override
public void onDownMotionEvent() {
// Workaround: WebView inside a ScrollView absorbs down motion events, so observing
// down motion event from the WebView is required.
mFirstScroll = mDragging = true;
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
}
};
}
| cymcsg/UltimateAndroid | deprecated/UltimateAndroidGradle/demoofui/src/main/java/com/marshalchen/common/demoofui/observablescrollview/ToolbarControlWebViewActivity.java | Java | apache-2.0 | 5,205 |
/*
* Copyright (C) 2016 Square, 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.
*/
package okhttp3;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSource;
import okio.Okio;
import okio.Source;
import okio.Timeout;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public final class ResponseTest {
@Test public void peekShorterThanResponse() throws Exception {
Response response = newResponse(responseBody("abcdef"));
ResponseBody peekedBody = response.peekBody(3);
assertEquals("abc", peekedBody.string());
assertEquals("abcdef", response.body().string());
}
@Test public void peekLongerThanResponse() throws Exception {
Response response = newResponse(responseBody("abc"));
ResponseBody peekedBody = response.peekBody(6);
assertEquals("abc", peekedBody.string());
assertEquals("abc", response.body().string());
}
@Test public void peekAfterReadingResponse() throws Exception {
Response response = newResponse(responseBody("abc"));
assertEquals("abc", response.body().string());
try {
response.peekBody(3);
fail();
} catch (IllegalStateException expected) {
}
}
@Test public void eachPeakIsIndependent() throws Exception {
Response response = newResponse(responseBody("abcdef"));
ResponseBody p1 = response.peekBody(4);
ResponseBody p2 = response.peekBody(2);
assertEquals("abcdef", response.body().string());
assertEquals("abcd", p1.string());
assertEquals("ab", p2.string());
}
/**
* Returns a new response body that refuses to be read once it has been closed. This is true of
* most {@link BufferedSource} instances, but not of {@link Buffer}.
*/
private ResponseBody responseBody(String content) {
final Buffer data = new Buffer().writeUtf8(content);
Source source = new Source() {
boolean closed;
@Override public void close() throws IOException {
closed = true;
}
@Override public long read(Buffer sink, long byteCount) throws IOException {
if (closed) throw new IllegalStateException();
return data.read(sink, byteCount);
}
@Override public Timeout timeout() {
return Timeout.NONE;
}
};
return ResponseBody.create(null, -1, Okio.buffer(source));
}
private Response newResponse(ResponseBody responseBody) {
return new Response.Builder()
.request(new Request.Builder()
.url("https://example.com/")
.build())
.protocol(Protocol.HTTP_1_1)
.code(200)
.body(responseBody)
.build();
}
}
| zmarkan/okhttp | okhttp-tests/src/test/java/okhttp3/ResponseTest.java | Java | apache-2.0 | 3,177 |
<?php
/**
* HTML cache invalidation of all pages linking to a given title.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Cache
*/
/**
* Class to invalidate the HTML cache of all the pages linking to a given title.
*
* @ingroup Cache
*/
class HTMLCacheUpdate implements DeferrableUpdate {
/**
* @var Title
*/
public $mTitle;
public $mTable;
/**
* @param $titleTo
* @param $table
* @param $start bool
* @param $end bool
*/
function __construct( Title $titleTo, $table ) {
$this->mTitle = $titleTo;
$this->mTable = $table;
}
public function doUpdate() {
wfProfileIn( __METHOD__ );
$job = new HTMLCacheUpdateJob(
$this->mTitle,
array(
'table' => $this->mTable,
) + Job::newRootJobParams( // "overall" refresh links job info
"htmlCacheUpdate:{$this->mTable}:{$this->mTitle->getPrefixedText()}"
)
);
$count = $this->mTitle->getBacklinkCache()->getNumLinks( $this->mTable, 200 );
if ( $count >= 200 ) { // many backlinks
JobQueueGroup::singleton()->push( $job );
JobQueueGroup::singleton()->deduplicateRootJob( $job );
} else { // few backlinks ($count might be off even if 0)
$dbw = wfGetDB( DB_MASTER );
$dbw->onTransactionIdle( function() use ( $job ) {
$job->run(); // just do the purge query now
} );
}
wfProfileOut( __METHOD__ );
}
}
| BRL-CAD/web | wiki/includes/cache/HTMLCacheUpdate.php | PHP | bsd-2-clause | 2,065 |
cask :v1 => 'witgui' do
version '2.1.2'
sha256 '4e108153a2cce9fede1358b265dfcd7d9f03c15658e2c9278ddad8a04260cf9b'
url "http://desairem.altervista.org/witgui/download.php?version=#{version}"
name 'Witgui'
appcast 'http://desairem.altervista.org/witgui/appcast.xml',
:sha256 => 'f982fdb6f7cfe0a307fad75e5e523096630f5eef88aa543014d2eed2d6f4b01d'
homepage 'http://desairem.altervista.org/witgui/wordpress/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Witgui.app'
end
| vmrob/homebrew-cask | Casks/witgui.rb | Ruby | bsd-2-clause | 566 |
import { MacOption24 } from "../../";
export = MacOption24;
| markogresak/DefinitelyTyped | types/carbon__icons-react/lib/mac--option/24.d.ts | TypeScript | mit | 61 |
export default (...modifiers): Array<string> => {};
| recipesjs/ingredients | test/fixtures/flow/type-annotations/102/actual.js | JavaScript | mit | 52 |
<?php
namespace Concrete\Core\Search;
use Concrete\Core\Application\EditResponse;
use Concrete\Core\Entity\Search\Query;
use Concrete\Core\Search\Result\Result as SearchResult;
interface SessionQueryProviderInterface
{
function setSessionCurrentQuery(Query $query);
function getSessionCurrentQuery();
function clearSessionCurrentQuery();
function getSessionNamespace();
}
| Akhenoth/Factorian | concrete/src/Search/SessionQueryProviderInterface.php | PHP | mit | 393 |
import { LogoTumblr16 } from "../../";
export = LogoTumblr16;
| markogresak/DefinitelyTyped | types/carbon__icons-react/lib/logo--tumblr/16.d.ts | TypeScript | mit | 63 |
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Axel Kohlmeyer (Temple U)
------------------------------------------------------------------------- */
#include "pppm_omp.h"
#include "atom.h"
#include "comm.h"
#include "domain.h"
#include "error.h"
#include "fix_omp.h"
#include "force.h"
#include "memory.h"
#include "math_const.h"
#include "math_special.h"
#include <string.h>
#include <math.h>
#include "suffix.h"
using namespace LAMMPS_NS;
using namespace MathConst;
using namespace MathSpecial;
#ifdef FFT_SINGLE
#define ZEROF 0.0f
#else
#define ZEROF 0.0
#endif
#define EPS_HOC 1.0e-7
/* ---------------------------------------------------------------------- */
PPPMOMP::PPPMOMP(LAMMPS *lmp, int narg, char **arg) :
PPPM(lmp, narg, arg), ThrOMP(lmp, THR_KSPACE)
{
triclinic_support = 0;
suffix_flag |= Suffix::OMP;
}
/* ----------------------------------------------------------------------
allocate memory that depends on # of K-vectors and order
------------------------------------------------------------------------- */
void PPPMOMP::allocate()
{
PPPM::allocate();
#if defined(_OPENMP)
#pragma omp parallel default(none)
#endif
{
#if defined(_OPENMP)
const int tid = omp_get_thread_num();
#else
const int tid = 0;
#endif
ThrData *thr = fix->get_thr(tid);
thr->init_pppm(order,memory);
}
}
/* ----------------------------------------------------------------------
free memory that depends on # of K-vectors and order
------------------------------------------------------------------------- */
void PPPMOMP::deallocate()
{
PPPM::deallocate();
#if defined(_OPENMP)
#pragma omp parallel default(none)
#endif
{
#if defined(_OPENMP)
const int tid = omp_get_thread_num();
#else
const int tid = 0;
#endif
ThrData *thr = fix->get_thr(tid);
thr->init_pppm(-order,memory);
}
}
/* ----------------------------------------------------------------------
pre-compute modified (Hockney-Eastwood) Coulomb Green's function
------------------------------------------------------------------------- */
void PPPMOMP::compute_gf_ik()
{
const double * const prd = (triclinic==0) ? domain->prd : domain->prd_lamda;
const double xprd = prd[0];
const double yprd = prd[1];
const double zprd = prd[2];
const double zprd_slab = zprd*slab_volfactor;
const double unitkx = (MY_2PI/xprd);
const double unitky = (MY_2PI/yprd);
const double unitkz = (MY_2PI/zprd_slab);
const int nbx = static_cast<int> ((g_ewald*xprd/(MY_PI*nx_pppm)) *
pow(-log(EPS_HOC),0.25));
const int nby = static_cast<int> ((g_ewald*yprd/(MY_PI*ny_pppm)) *
pow(-log(EPS_HOC),0.25));
const int nbz = static_cast<int> ((g_ewald*zprd_slab/(MY_PI*nz_pppm)) *
pow(-log(EPS_HOC),0.25));
const int numk = nxhi_fft - nxlo_fft + 1;
const int numl = nyhi_fft - nylo_fft + 1;
const int twoorder = 2*order;
#if defined(_OPENMP)
#pragma omp parallel default(none)
#endif
{
double snx,sny,snz;
double argx,argy,argz,wx,wy,wz,sx,sy,sz,qx,qy,qz;
double sum1,dot1,dot2;
double numerator,denominator;
double sqk;
int k,l,m,nx,ny,nz,kper,lper,mper,n,nfrom,nto,tid;
loop_setup_thr(nfrom, nto, tid, nfft, comm->nthreads);
for (n = nfrom; n < nto; ++n) {
m = n / (numl*numk);
l = (n - m*numl*numk) / numk;
k = n - m*numl*numk - l*numk;
m += nzlo_fft;
l += nylo_fft;
k += nxlo_fft;
mper = m - nz_pppm*(2*m/nz_pppm);
snz = square(sin(0.5*unitkz*mper*zprd_slab/nz_pppm));
lper = l - ny_pppm*(2*l/ny_pppm);
sny = square(sin(0.5*unitky*lper*yprd/ny_pppm));
kper = k - nx_pppm*(2*k/nx_pppm);
snx = square(sin(0.5*unitkx*kper*xprd/nx_pppm));
sqk = square(unitkx*kper) + square(unitky*lper) + square(unitkz*mper);
if (sqk != 0.0) {
numerator = 12.5663706/sqk;
denominator = gf_denom(snx,sny,snz);
sum1 = 0.0;
for (nx = -nbx; nx <= nbx; nx++) {
qx = unitkx*(kper+nx_pppm*nx);
sx = exp(-0.25*square(qx/g_ewald));
argx = 0.5*qx*xprd/nx_pppm;
wx = powsinxx(argx,twoorder);
for (ny = -nby; ny <= nby; ny++) {
qy = unitky*(lper+ny_pppm*ny);
sy = exp(-0.25*square(qy/g_ewald));
argy = 0.5*qy*yprd/ny_pppm;
wy = powsinxx(argy,twoorder);
for (nz = -nbz; nz <= nbz; nz++) {
qz = unitkz*(mper+nz_pppm*nz);
sz = exp(-0.25*square(qz/g_ewald));
argz = 0.5*qz*zprd_slab/nz_pppm;
wz = powsinxx(argz,twoorder);
dot1 = unitkx*kper*qx + unitky*lper*qy + unitkz*mper*qz;
dot2 = qx*qx+qy*qy+qz*qz;
sum1 += (dot1/dot2) * sx*sy*sz * wx*wy*wz;
}
}
}
greensfn[n] = numerator*sum1/denominator;
} else greensfn[n] = 0.0;
}
} // end of parallel region
}
/* ----------------------------------------------------------------------
compute optimized Green's function for energy calculation
------------------------------------------------------------------------- */
void PPPMOMP::compute_gf_ad()
{
const double * const prd = (triclinic==0) ? domain->prd : domain->prd_lamda;
const double xprd = prd[0];
const double yprd = prd[1];
const double zprd = prd[2];
const double zprd_slab = zprd*slab_volfactor;
const double unitkx = (MY_2PI/xprd);
const double unitky = (MY_2PI/yprd);
const double unitkz = (MY_2PI/zprd_slab);
const int numk = nxhi_fft - nxlo_fft + 1;
const int numl = nyhi_fft - nylo_fft + 1;
const int twoorder = 2*order;
double sf0=0.0,sf1=0.0,sf2=0.0,sf3=0.0,sf4=0.0,sf5=0.0;
#if defined(_OPENMP)
#pragma omp parallel default(none) reduction(+:sf0,sf1,sf2,sf3,sf4,sf5)
#endif
{
double snx,sny,snz,sqk;
double argx,argy,argz,wx,wy,wz,sx,sy,sz,qx,qy,qz;
double numerator,denominator;
int k,l,m,kper,lper,mper,n,nfrom,nto,tid;
loop_setup_thr(nfrom, nto, tid, nfft, comm->nthreads);
for (n = nfrom; n < nto; ++n) {
m = n / (numl*numk);
l = (n - m*numl*numk) / numk;
k = n - m*numl*numk - l*numk;
m += nzlo_fft;
l += nylo_fft;
k += nxlo_fft;
mper = m - nz_pppm*(2*m/nz_pppm);
qz = unitkz*mper;
snz = square(sin(0.5*qz*zprd_slab/nz_pppm));
sz = exp(-0.25*square(qz/g_ewald));
argz = 0.5*qz*zprd_slab/nz_pppm;
wz = powsinxx(argz,twoorder);
lper = l - ny_pppm*(2*l/ny_pppm);
qy = unitky*lper;
sny = square(sin(0.5*qy*yprd/ny_pppm));
sy = exp(-0.25*square(qy/g_ewald));
argy = 0.5*qy*yprd/ny_pppm;
wy = powsinxx(argy,twoorder);
kper = k - nx_pppm*(2*k/nx_pppm);
qx = unitkx*kper;
snx = square(sin(0.5*qx*xprd/nx_pppm));
sx = exp(-0.25*square(qx/g_ewald));
argx = 0.5*qx*xprd/nx_pppm;
wx = powsinxx(argx,twoorder);
sqk = qx*qx + qy*qy + qz*qz;
if (sqk != 0.0) {
numerator = MY_4PI/sqk;
denominator = gf_denom(snx,sny,snz);
greensfn[n] = numerator*sx*sy*sz*wx*wy*wz/denominator;
sf0 += sf_precoeff1[n]*greensfn[n];
sf1 += sf_precoeff2[n]*greensfn[n];
sf2 += sf_precoeff3[n]*greensfn[n];
sf3 += sf_precoeff4[n]*greensfn[n];
sf4 += sf_precoeff5[n]*greensfn[n];
sf5 += sf_precoeff6[n]*greensfn[n];
} else {
greensfn[n] = 0.0;
sf0 += sf_precoeff1[n]*greensfn[n];
sf1 += sf_precoeff2[n]*greensfn[n];
sf2 += sf_precoeff3[n]*greensfn[n];
sf3 += sf_precoeff4[n]*greensfn[n];
sf4 += sf_precoeff5[n]*greensfn[n];
sf5 += sf_precoeff6[n]*greensfn[n];
}
}
} // end of paralle region
// compute the coefficients for the self-force correction
double prex, prey, prez, tmp[6];
prex = prey = prez = MY_PI/volume;
prex *= nx_pppm/xprd;
prey *= ny_pppm/yprd;
prez *= nz_pppm/zprd_slab;
tmp[0] = sf0 * prex;
tmp[1] = sf1 * prex*2;
tmp[2] = sf2 * prey;
tmp[3] = sf3 * prey*2;
tmp[4] = sf4 * prez;
tmp[5] = sf5 * prez*2;
// communicate values with other procs
MPI_Allreduce(tmp,sf_coeff,6,MPI_DOUBLE,MPI_SUM,world);
}
/* ----------------------------------------------------------------------
run the regular toplevel compute method from plain PPPM
which will have individual methods replaced by our threaded
versions and then call the obligatory force reduction.
------------------------------------------------------------------------- */
void PPPMOMP::compute(int eflag, int vflag)
{
PPPM::compute(eflag,vflag);
#if defined(_OPENMP)
#pragma omp parallel default(none) shared(eflag,vflag)
#endif
{
#if defined(_OPENMP)
const int tid = omp_get_thread_num();
#else
const int tid = 0;
#endif
ThrData *thr = fix->get_thr(tid);
reduce_thr(this, eflag, vflag, thr);
} // end of omp parallel region
}
/* ----------------------------------------------------------------------
create discretized "density" on section of global grid due to my particles
density(x,y,z) = charge "density" at grid points of my 3d brick
(nxlo:nxhi,nylo:nyhi,nzlo:nzhi) is extent of my brick (including ghosts)
in global grid
------------------------------------------------------------------------- */
void PPPMOMP::make_rho()
{
// clear 3d density array
FFT_SCALAR * _noalias const d = &(density_brick[nzlo_out][nylo_out][nxlo_out]);
memset(d,0,ngrid*sizeof(FFT_SCALAR));
// no local atoms => nothing else to do
const int nlocal = atom->nlocal;
if (nlocal == 0) return;
const int ix = nxhi_out - nxlo_out + 1;
const int iy = nyhi_out - nylo_out + 1;
#if defined(_OPENMP)
#pragma omp parallel default(none)
#endif
{
const double * _noalias const q = atom->q;
const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0];
const int3_t * _noalias const p2g = (int3_t *) part2grid[0];
const double boxlox = boxlo[0];
const double boxloy = boxlo[1];
const double boxloz = boxlo[2];
// determine range of grid points handled by this thread
int i,jfrom,jto,tid;
loop_setup_thr(jfrom,jto,tid,ngrid,comm->nthreads);
// get per thread data
ThrData *thr = fix->get_thr(tid);
FFT_SCALAR * const * const r1d = static_cast<FFT_SCALAR **>(thr->get_rho1d());
// loop over my charges, add their contribution to nearby grid points
// (nx,ny,nz) = global coords of grid pt to "lower left" of charge
// (dx,dy,dz) = distance to "lower left" grid pt
// loop over all local atoms for all threads
for (i = 0; i < nlocal; i++) {
const int nx = p2g[i].a;
const int ny = p2g[i].b;
const int nz = p2g[i].t;
// pre-screen whether this atom will ever come within
// reach of the data segement this thread is updating.
if ( ((nz+nlower-nzlo_out)*ix*iy >= jto)
|| ((nz+nupper-nzlo_out+1)*ix*iy < jfrom) ) continue;
const FFT_SCALAR dx = nx+shiftone - (x[i].x-boxlox)*delxinv;
const FFT_SCALAR dy = ny+shiftone - (x[i].y-boxloy)*delyinv;
const FFT_SCALAR dz = nz+shiftone - (x[i].z-boxloz)*delzinv;
compute_rho1d_thr(r1d,dx,dy,dz);
const FFT_SCALAR z0 = delvolinv * q[i];
for (int n = nlower; n <= nupper; ++n) {
const int jn = (nz+n-nzlo_out)*ix*iy;
const FFT_SCALAR y0 = z0*r1d[2][n];
for (int m = nlower; m <= nupper; ++m) {
const int jm = jn+(ny+m-nylo_out)*ix;
const FFT_SCALAR x0 = y0*r1d[1][m];
for (int l = nlower; l <= nupper; ++l) {
const int jl = jm+nx+l-nxlo_out;
// make sure each thread only updates
// "his" elements of the density grid
if (jl >= jto) break;
if (jl < jfrom) continue;
d[jl] += x0*r1d[0][l];
}
}
}
}
}
}
/* ----------------------------------------------------------------------
interpolate from grid to get electric field & force on my particles for ik
------------------------------------------------------------------------- */
void PPPMOMP::fieldforce_ik()
{
// loop over my charges, interpolate electric field from nearby grid points
// (nx,ny,nz) = global coords of grid pt to "lower left" of charge
// (dx,dy,dz) = distance to "lower left" grid pt
// (mx,my,mz) = global coords of moving stencil pt
// ek = 3 components of E-field on particle
const int nthreads = comm->nthreads;
const int nlocal = atom->nlocal;
// no local atoms => nothing to do
if (nlocal == 0) return;
const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0];
const double * _noalias const q = atom->q;
const int3_t * _noalias const p2g = (int3_t *) part2grid[0];
const double qqrd2e = force->qqrd2e;
const double boxlox = boxlo[0];
const double boxloy = boxlo[1];
const double boxloz = boxlo[2];
#if defined(_OPENMP)
#pragma omp parallel default(none)
#endif
{
FFT_SCALAR x0,y0,z0,ekx,eky,ekz;
int i,ifrom,ito,tid,l,m,n,mx,my,mz;
loop_setup_thr(ifrom,ito,tid,nlocal,nthreads);
// get per thread data
ThrData *thr = fix->get_thr(tid);
dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0];
FFT_SCALAR * const * const r1d = static_cast<FFT_SCALAR **>(thr->get_rho1d());
for (i = ifrom; i < ito; ++i) {
const int nx = p2g[i].a;
const int ny = p2g[i].b;
const int nz = p2g[i].t;
const FFT_SCALAR dx = nx+shiftone - (x[i].x-boxlox)*delxinv;
const FFT_SCALAR dy = ny+shiftone - (x[i].y-boxloy)*delyinv;
const FFT_SCALAR dz = nz+shiftone - (x[i].z-boxloz)*delzinv;
compute_rho1d_thr(r1d,dx,dy,dz);
ekx = eky = ekz = ZEROF;
for (n = nlower; n <= nupper; n++) {
mz = n+nz;
z0 = r1d[2][n];
for (m = nlower; m <= nupper; m++) {
my = m+ny;
y0 = z0*r1d[1][m];
for (l = nlower; l <= nupper; l++) {
mx = l+nx;
x0 = y0*r1d[0][l];
ekx -= x0*vdx_brick[mz][my][mx];
eky -= x0*vdy_brick[mz][my][mx];
ekz -= x0*vdz_brick[mz][my][mx];
}
}
}
// convert E-field to force
const double qfactor = qqrd2e * scale * q[i];
f[i].x += qfactor*ekx;
f[i].y += qfactor*eky;
if (slabflag != 2) f[i].z += qfactor*ekz;
}
} // end of parallel region
}
/* ----------------------------------------------------------------------
interpolate from grid to get electric field & force on my particles for ad
------------------------------------------------------------------------- */
void PPPMOMP::fieldforce_ad()
{
const int nthreads = comm->nthreads;
const int nlocal = atom->nlocal;
// no local atoms => nothing to do
if (nlocal == 0) return;
const double *prd = (triclinic == 0) ? domain->prd : domain->prd_lamda;
const double hx_inv = nx_pppm/prd[0];
const double hy_inv = ny_pppm/prd[1];
const double hz_inv = nz_pppm/prd[2];
// loop over my charges, interpolate electric field from nearby grid points
// (nx,ny,nz) = global coords of grid pt to "lower left" of charge
// (dx,dy,dz) = distance to "lower left" grid pt
// (mx,my,mz) = global coords of moving stencil pt
// ek = 3 components of E-field on particle
const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0];
const double * _noalias const q = atom->q;
const int3_t * _noalias const p2g = (int3_t *) part2grid[0];
const double qqrd2e = force->qqrd2e;
const double boxlox = boxlo[0];
const double boxloy = boxlo[1];
const double boxloz = boxlo[2];
#if defined(_OPENMP)
#pragma omp parallel default(none)
#endif
{
double s1,s2,s3,sf;
FFT_SCALAR ekx,eky,ekz;
int i,ifrom,ito,tid,l,m,n,mx,my,mz;
loop_setup_thr(ifrom,ito,tid,nlocal,nthreads);
// get per thread data
ThrData *thr = fix->get_thr(tid);
dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0];
FFT_SCALAR * const * const r1d = static_cast<FFT_SCALAR **>(thr->get_rho1d());
FFT_SCALAR * const * const d1d = static_cast<FFT_SCALAR **>(thr->get_drho1d());
for (i = ifrom; i < ito; ++i) {
const int nx = p2g[i].a;
const int ny = p2g[i].b;
const int nz = p2g[i].t;
const FFT_SCALAR dx = nx+shiftone - (x[i].x-boxlox)*delxinv;
const FFT_SCALAR dy = ny+shiftone - (x[i].y-boxloy)*delyinv;
const FFT_SCALAR dz = nz+shiftone - (x[i].z-boxloz)*delzinv;
compute_rho1d_thr(r1d,dx,dy,dz);
compute_drho1d_thr(d1d,dx,dy,dz);
ekx = eky = ekz = ZEROF;
for (n = nlower; n <= nupper; n++) {
mz = n+nz;
for (m = nlower; m <= nupper; m++) {
my = m+ny;
for (l = nlower; l <= nupper; l++) {
mx = l+nx;
ekx += d1d[0][l]*r1d[1][m]*r1d[2][n]*u_brick[mz][my][mx];
eky += r1d[0][l]*d1d[1][m]*r1d[2][n]*u_brick[mz][my][mx];
ekz += r1d[0][l]*r1d[1][m]*d1d[2][n]*u_brick[mz][my][mx];
}
}
}
ekx *= hx_inv;
eky *= hy_inv;
ekz *= hz_inv;
// convert E-field to force and substract self forces
const double qi = q[i];
const double qfactor = qqrd2e * scale * qi;
s1 = x[i].x*hx_inv;
sf = sf_coeff[0]*sin(MY_2PI*s1);
sf += sf_coeff[1]*sin(MY_4PI*s1);
sf *= 2.0*qi;
f[i].x += qfactor*(ekx - sf);
s2 = x[i].y*hy_inv;
sf = sf_coeff[2]*sin(MY_2PI*s2);
sf += sf_coeff[3]*sin(MY_4PI*s2);
sf *= 2.0*qi;
f[i].y += qfactor*(eky - sf);
s3 = x[i].z*hz_inv;
sf = sf_coeff[4]*sin(MY_2PI*s3);
sf += sf_coeff[5]*sin(MY_4PI*s3);
sf *= 2.0*qi;
if (slabflag != 2) f[i].z += qfactor*(ekz - sf);
}
} // end of parallel region
}
/* ----------------------------------------------------------------------
interpolate from grid to get per-atom energy/virial
------------------------------------------------------------------------- */
void PPPMOMP::fieldforce_peratom()
{
const int nthreads = comm->nthreads;
const int nlocal = atom->nlocal;
// no local atoms => nothing to do
if (nlocal == 0) return;
// loop over my charges, interpolate from nearby grid points
// (nx,ny,nz) = global coords of grid pt to "lower left" of charge
// (dx,dy,dz) = distance to "lower left" grid pt
// (mx,my,mz) = global coords of moving stencil pt
const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0];
const double * _noalias const q = atom->q;
#if defined(_OPENMP)
#pragma omp parallel default(none)
#endif
{
FFT_SCALAR dx,dy,dz,x0,y0,z0;
FFT_SCALAR u,v0,v1,v2,v3,v4,v5;
int i,ifrom,ito,tid,l,m,n,nx,ny,nz,mx,my,mz;
loop_setup_thr(ifrom,ito,tid,nlocal,nthreads);
// get per thread data
ThrData *thr = fix->get_thr(tid);
FFT_SCALAR * const * const r1d = static_cast<FFT_SCALAR **>(thr->get_rho1d());
for (i = ifrom; i < ito; ++i) {
nx = part2grid[i][0];
ny = part2grid[i][1];
nz = part2grid[i][2];
dx = nx+shiftone - (x[i].x-boxlo[0])*delxinv;
dy = ny+shiftone - (x[i].y-boxlo[1])*delyinv;
dz = nz+shiftone - (x[i].z-boxlo[2])*delzinv;
compute_rho1d_thr(r1d,dx,dy,dz);
u = v0 = v1 = v2 = v3 = v4 = v5 = ZEROF;
for (n = nlower; n <= nupper; n++) {
mz = n+nz;
z0 = r1d[2][n];
for (m = nlower; m <= nupper; m++) {
my = m+ny;
y0 = z0*r1d[1][m];
for (l = nlower; l <= nupper; l++) {
mx = l+nx;
x0 = y0*r1d[0][l];
if (eflag_atom) u += x0*u_brick[mz][my][mx];
if (vflag_atom) {
v0 += x0*v0_brick[mz][my][mx];
v1 += x0*v1_brick[mz][my][mx];
v2 += x0*v2_brick[mz][my][mx];
v3 += x0*v3_brick[mz][my][mx];
v4 += x0*v4_brick[mz][my][mx];
v5 += x0*v5_brick[mz][my][mx];
}
}
}
}
const double qi = q[i];
if (eflag_atom) eatom[i] += qi*u;
if (vflag_atom) {
vatom[i][0] += qi*v0;
vatom[i][1] += qi*v1;
vatom[i][2] += qi*v2;
vatom[i][3] += qi*v3;
vatom[i][4] += qi*v4;
vatom[i][5] += qi*v5;
}
}
} // end of parallel region
}
/* ----------------------------------------------------------------------
charge assignment into rho1d
dx,dy,dz = distance of particle from "lower left" grid point
------------------------------------------------------------------------- */
void PPPMOMP::compute_rho1d_thr(FFT_SCALAR * const * const r1d, const FFT_SCALAR &dx,
const FFT_SCALAR &dy, const FFT_SCALAR &dz)
{
int k,l;
FFT_SCALAR r1,r2,r3;
for (k = (1-order)/2; k <= order/2; k++) {
r1 = r2 = r3 = ZEROF;
for (l = order-1; l >= 0; l--) {
r1 = rho_coeff[l][k] + r1*dx;
r2 = rho_coeff[l][k] + r2*dy;
r3 = rho_coeff[l][k] + r3*dz;
}
r1d[0][k] = r1;
r1d[1][k] = r2;
r1d[2][k] = r3;
}
}
/* ----------------------------------------------------------------------
charge assignment into drho1d
dx,dy,dz = distance of particle from "lower left" grid point
------------------------------------------------------------------------- */
void PPPMOMP::compute_drho1d_thr(FFT_SCALAR * const * const d1d, const FFT_SCALAR &dx,
const FFT_SCALAR &dy, const FFT_SCALAR &dz)
{
int k,l;
FFT_SCALAR r1,r2,r3;
for (k = (1-order)/2; k <= order/2; k++) {
r1 = r2 = r3 = ZEROF;
for (l = order-2; l >= 0; l--) {
r1 = drho_coeff[l][k] + r1*dx;
r2 = drho_coeff[l][k] + r2*dy;
r3 = drho_coeff[l][k] + r3*dz;
}
d1d[0][k] = r1;
d1d[1][k] = r2;
d1d[2][k] = r3;
}
}
| ganzenmg/lammps_current | src/USER-OMP/pppm_omp.cpp | C++ | gpl-2.0 | 22,330 |
(function (_, $, Backbone, Drupal, drupalSettings) {
"use strict";
/**
* State of an in-place editable entity in the DOM.
*/
Drupal.edit.EntityModel = Drupal.edit.BaseModel.extend({
defaults: {
// The DOM element that represents this entity. It may seem bizarre to
// have a DOM element in a Backbone Model, but we need to be able to map
// entities in the DOM to EntityModels in memory.
el: null,
// An entity ID, of the form "<entity type>/<entity ID>", e.g. "node/1".
entityID: null,
// An entity instance ID. The first intance of a specific entity (i.e. with
// a given entity ID) is assigned 0, the second 1, and so on.
entityInstanceID: null,
// The unique ID of this entity instance on the page, of the form "<entity
// type>/<entity ID>[entity instance ID]", e.g. "node/1[0]".
id: null,
// The label of the entity.
label: null,
// A Drupal.edit.FieldCollection for all fields of this entity.
fields: null,
// The attributes below are stateful. The ones above will never change
// during the life of a EntityModel instance.
// Indicates whether this instance of this entity is currently being
// edited in-place.
isActive: false,
// Whether one or more fields have already been stored in TempStore.
inTempStore: false,
// Whether one or more fields have already been stored in TempStore *or*
// the field that's currently being edited is in the 'changed' or a later
// state. In other words, this boolean indicates whether a "Save" button is
// necessary or not.
isDirty: false,
// Whether the request to the server has been made to commit this entity.
// Used to prevent multiple such requests.
isCommitting: false,
// The current processing state of an entity.
state: 'closed',
// The IDs of the fields whose new values have been stored in TempStore. We
// must store this on the EntityModel as well (even though it already is on
// the FieldModel) because when a field is rerendered, its FieldModel is
// destroyed and this allows us to transition it back to the proper state.
fieldsInTempStore: [],
// A flag the tells the application that this EntityModel must be reloaded
// in order to restore the original values to its fields in the client.
reload: false
},
/**
* @inheritdoc
*/
initialize: function () {
this.set('fields', new Drupal.edit.FieldCollection());
// Respond to entity state changes.
this.listenTo(this, 'change:state', this.stateChange);
// The state of the entity is largely dependent on the state of its
// fields.
this.listenTo(this.get('fields'), 'change:state', this.fieldStateChange);
// Call Drupal.edit.BaseModel's initialize() method.
Drupal.edit.BaseModel.prototype.initialize.call(this);
},
/**
* Updates FieldModels' states when an EntityModel change occurs.
*
* @param Drupal.edit.EntityModel entityModel
* @param String state
* The state of the associated entity. One of Drupal.edit.EntityModel.states.
* @param Object options
*/
stateChange: function (entityModel, state, options) {
var to = state;
switch (to) {
case 'closed':
this.set({
'isActive': false,
'inTempStore': false,
'isDirty': false
});
break;
case 'launching':
break;
case 'opening':
// Set the fields to candidate state.
entityModel.get('fields').each(function (fieldModel) {
fieldModel.set('state', 'candidate', options);
});
break;
case 'opened':
// The entity is now ready for editing!
this.set('isActive', true);
break;
case 'committing':
// The user indicated they want to save the entity.
var fields = this.get('fields');
// For fields that are in an active state, transition them to candidate.
fields.chain()
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], ['active']).length;
})
.each(function (fieldModel) {
fieldModel.set('state', 'candidate');
});
// For fields that are in a changed state, field values must first be
// stored in TempStore.
fields.chain()
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], Drupal.edit.app.changedFieldStates).length;
})
.each(function (fieldModel) {
fieldModel.set('state', 'saving');
});
break;
case 'deactivating':
var changedFields = this.get('fields')
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], ['changed', 'invalid']).length;
});
// If the entity contains unconfirmed or unsaved changes, return the
// entity to an opened state and ask the user if they would like to save
// the changes or discard the changes.
// 1. One of the fields is in a changed state. The changed field might
// just be a change in the client or it might have been saved to
// tempstore.
// 2. The saved flag is empty and the confirmed flag is empty. If the
// entity has been saved to the server, the fields changed in the
// client are irrelevant. If the changes are confirmed, then proceed
// to set the fields to candidate state.
if ((changedFields.length || this.get('fieldsInTempStore').length) && (!options.saved && !options.confirmed)) {
// Cancel deactivation until the user confirms save or discard.
this.set('state', 'opened', {confirming: true});
// An action in reaction to state change must be deferred.
_.defer(function () {
Drupal.edit.app.confirmEntityDeactivation(entityModel);
});
}
else {
var invalidFields = this.get('fields')
.filter(function (fieldModel) {
return _.intersection([fieldModel.get('state')], ['invalid']).length;
});
// Indicate if this EntityModel needs to be reloaded in order to
// restore the original values of its fields.
entityModel.set('reload', (this.get('fieldsInTempStore').length || invalidFields.length));
// Set all fields to the 'candidate' state. A changed field may have to
// go through confirmation first.
entityModel.get('fields').each(function (fieldModel) {
// If the field is already in the candidate state, trigger a change
// event so that the entityModel can move to the next state in
// deactivation.
if (_.intersection([fieldModel.get('state')], ['candidate', 'highlighted']).length) {
fieldModel.trigger('change:state', fieldModel, fieldModel.get('state'), options);
}
else {
fieldModel.set('state', 'candidate', options);
}
});
}
break;
case 'closing':
// Set all fields to the 'inactive' state.
options.reason = 'stop';
this.get('fields').each(function (fieldModel) {
fieldModel.set({
'inTempStore': false,
'state': 'inactive'
}, options);
});
break;
}
},
/**
* Updates a Field and Entity model's "inTempStore" when appropriate.
*
* Helper function.
*
* @param Drupal.edit.EntityModel entityModel
* The model of the entity for which a field's state attribute has changed.
* @param Drupal.edit.FieldModel fieldModel
* The model of the field whose state attribute has changed.
*
* @see fieldStateChange()
*/
_updateInTempStoreAttributes: function (entityModel, fieldModel) {
var current = fieldModel.get('state');
var previous = fieldModel.previous('state');
var fieldsInTempStore = entityModel.get('fieldsInTempStore');
// If the fieldModel changed to the 'saved' state: remember that this
// field was saved to TempStore.
if (current === 'saved') {
// Mark the entity as saved in TempStore, so that we can pass the
// proper "reset TempStore" boolean value when communicating with the
// server.
entityModel.set('inTempStore', true);
// Mark the field as saved in TempStore, so that visual indicators
// signifying just that may be rendered.
fieldModel.set('inTempStore', true);
// Remember that this field is in TempStore, restore when rerendered.
fieldsInTempStore.push(fieldModel.get('fieldID'));
fieldsInTempStore = _.uniq(fieldsInTempStore);
entityModel.set('fieldsInTempStore', fieldsInTempStore);
}
// If the fieldModel changed to the 'candidate' state from the
// 'inactive' state, then this is a field for this entity that got
// rerendered. Restore its previous 'inTempStore' attribute value.
else if (current === 'candidate' && previous === 'inactive') {
fieldModel.set('inTempStore', _.intersection([fieldModel.get('fieldID')], fieldsInTempStore).length > 0);
}
},
/**
* Reacts to state changes in this entity's fields.
*
* @param Drupal.edit.FieldModel fieldModel
* The model of the field whose state attribute changed.
* @param String state
* The state of the associated field. One of Drupal.edit.FieldModel.states.
*/
fieldStateChange: function (fieldModel, state) {
var entityModel = this;
var fieldState = state;
// Switch on the entityModel state.
// The EntityModel responds to FieldModel state changes as a function of its
// state. For example, a field switching back to 'candidate' state when its
// entity is in the 'opened' state has no effect on the entity. But that
// same switch back to 'candidate' state of a field when the entity is in
// the 'committing' state might allow the entity to proceed with the commit
// flow.
switch (this.get('state')) {
case 'closed':
case 'launching':
// It should be impossible to reach these: fields can't change state
// while the entity is closed or still launching.
break;
case 'opening':
// We must change the entity to the 'opened' state, but it must first be
// confirmed that all of its fieldModels have transitioned to the
// 'candidate' state.
// We do this here, because this is called every time a fieldModel
// changes state, hence each time this is called, we get closer to the
// goal of having all fieldModels in the 'candidate' state.
// A state change in reaction to another state change must be deferred.
_.defer(function () {
entityModel.set('state', 'opened', {
'accept-field-states': Drupal.edit.app.readyFieldStates
});
});
break;
case 'opened':
// Set the isDirty attribute when appropriate so that it is known when
// to display the "Save" button in the entity toolbar.
// Note that once a field has been changed, there's no way to discard
// that change, hence it will have to be saved into TempStore, or the
// in-place editing of this field will have to be stopped completely.
// In other words: once any field enters the 'changed' field, then for
// the remainder of the in-place editing session, the entity is by
// definition dirty.
if (fieldState === 'changed') {
entityModel.set('isDirty', true);
}
else {
this._updateInTempStoreAttributes(entityModel, fieldModel);
}
break;
case 'committing':
// If the field save returned a validation error, set the state of the
// entity back to 'opened'.
if (fieldState === 'invalid') {
// A state change in reaction to another state change must be deferred.
_.defer(function() {
entityModel.set('state', 'opened', { reason: 'invalid' });
});
}
else {
this._updateInTempStoreAttributes(entityModel, fieldModel);
}
// Attempt to save the entity. If the entity's fields are not yet all in
// a ready state, the save will not be processed.
var options = {
'accept-field-states': Drupal.edit.app.readyFieldStates
};
if (entityModel.set('isCommitting', true, options)) {
entityModel.save({
success: function () {
entityModel.set({
'state': 'deactivating',
'isCommitting' : false
}, {'saved': true});
},
error: function () {
// Reset the "isCommitting" mutex.
entityModel.set('isCommitting', false);
// Change the state back to "opened", to allow the user to hit the
// "Save" button again.
entityModel.set('state', 'opened', { reason: 'networkerror' });
// Show a modal to inform the user of the network error.
var message = Drupal.t('Your changes to <q>@entity-title</q> could not be saved, either due to a website problem or a network connection problem.<br>Please try again.', { '@entity-title' : entityModel.get('label') });
Drupal.edit.util.networkErrorModal(Drupal.t('Sorry!'), message);
}
});
}
break;
case 'deactivating':
// When setting the entity to 'closing', require that all fieldModels
// are in either the 'candidate' or 'highlighted' state.
// A state change in reaction to another state change must be deferred.
_.defer(function() {
entityModel.set('state', 'closing', {
'accept-field-states': Drupal.edit.app.readyFieldStates
});
});
break;
case 'closing':
// When setting the entity to 'closed', require that all fieldModels are
// in the 'inactive' state.
// A state change in reaction to another state change must be deferred.
_.defer(function() {
entityModel.set('state', 'closed', {
'accept-field-states': ['inactive']
});
});
break;
}
},
/**
* Fires an AJAX request to the REST save URL for an entity.
*
* @param options
* An object of options that contains:
* - success: (optional) A function to invoke if the entity is success-
* fully saved.
*/
save: function (options) {
var entityModel = this;
// @todo Simplify this once https://drupal.org/node/1533366 lands.
// @see https://drupal.org/node/2029999.
var id = 'edit-save-entity';
// Create a temporary element to be able to use Drupal.ajax.
var $el = $('#edit-entity-toolbar').find('.action-save'); // This is the span element inside the button.
// Create a Drupal.ajax instance to save the entity.
var entitySaverAjax = new Drupal.ajax(id, $el, {
url: Drupal.edit.util.buildUrl(entityModel.get('entityID'), drupalSettings.edit.entitySaveURL),
event: 'edit-save.edit',
progress: { type: 'none' },
error: function () {
$el.off('edit-save.edit');
// Let the Drupal.edit.EntityModel Backbone model's error() method
// handle errors.
options.error.call(entityModel);
}
});
// Work-around for https://drupal.org/node/2019481 in Drupal 7.
entitySaverAjax.commands = {};
// Entity saved successfully.
entitySaverAjax.commands.editEntitySaved = function(ajax, response, status) {
// Clean up.
$(ajax.element).off('edit-save.edit');
// All fields have been moved from TempStore to permanent storage, update
// the "inTempStore" attribute on FieldModels, on the EntityModel and
// clear EntityModel's "fieldInTempStore" attribute.
entityModel.get('fields').each(function (fieldModel) {
fieldModel.set('inTempStore', false);
});
entityModel.set('inTempStore', false);
entityModel.set('fieldsInTempStore', []);
// Invoke the optional success callback.
if (options.success) {
options.success.call(entityModel);
}
};
// Trigger the AJAX request, which will will return the editEntitySaved AJAX
// command to which we then react.
$el.trigger('edit-save.edit');
},
/**
* {@inheritdoc}
*
* @param Object attrs
* The attributes changes in the save or set call.
* @param Object options
* An object with the following option:
* - String reason (optional): a string that conveys a particular reason
* to allow for an exceptional state change.
* - Array accept-field-states (optional) An array of strings that
* represent field states that the entities must be in to validate. For
* example, if accept-field-states is ['candidate', 'highlighted'], then
* all the fields of the entity must be in either of these two states
* for the save or set call to validate and proceed.
*/
validate: function (attrs, options) {
var acceptedFieldStates = options['accept-field-states'] || [];
// Validate state change.
var currentState = this.get('state');
var nextState = attrs.state;
if (currentState !== nextState) {
// Ensure it's a valid state.
if (_.indexOf(this.constructor.states, nextState) === -1) {
return '"' + nextState + '" is an invalid state';
}
// Ensure it's a state change that is allowed.
// Check if the acceptStateChange function accepts it.
if (!this._acceptStateChange(currentState, nextState, options)) {
return 'state change not accepted';
}
// If that function accepts it, then ensure all fields are also in an
// acceptable state.
else if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) {
return 'state change not accepted because fields are not in acceptable state';
}
}
// Validate setting isCommitting = true.
var currentIsCommitting = this.get('isCommitting');
var nextIsCommitting = attrs.isCommitting;
if (currentIsCommitting === false && nextIsCommitting === true) {
if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) {
return 'isCommitting change not accepted because fields are not in acceptable state';
}
}
else if (currentIsCommitting === true && nextIsCommitting === true) {
return "isCommiting is a mutex, hence only changes are allowed";
}
},
// Like @see AppView.acceptEditorStateChange()
_acceptStateChange: function (from, to, context) {
var accept = true;
// In general, enforce the states sequence. Disallow going back from a
// "later" state to an "earlier" state, except in explicitly allowed
// cases.
if (!this.constructor.followsStateSequence(from, to)) {
accept = false;
// Allow: closing -> closed.
// Necessary to stop editing an entity.
if (from === 'closing' && to === 'closed') {
accept = true;
}
// Allow: committing -> opened.
// Necessary to be able to correct an invalid field, or to hit the "Save"
// button again after a server/network error.
else if (from === 'committing' && to === 'opened' && context.reason && (context.reason === 'invalid' || context.reason === 'networkerror')) {
accept = true;
}
// Allow: deactivating -> opened.
// Necessary to be able to confirm changes with the user.
else if (from === 'deactivating' && to === 'opened' && context.confirming) {
accept = true;
}
// Allow: opened -> deactivating.
// Necessary to be able to stop editing.
else if (from === 'opened' && to === 'deactivating' && context.confirmed) {
accept = true;
}
}
return accept;
},
/**
* @param Array acceptedFieldStates
* @see validate()
* @return Boolean
*/
_fieldsHaveAcceptableStates: function (acceptedFieldStates) {
var accept = true;
// If no acceptable field states are provided, assume all field states are
// acceptable. We want to let validation pass as a default and only
// check validity on calls to set that explicitly request it.
if (acceptedFieldStates.length > 0) {
var fieldStates = this.get('fields').pluck('state') || [];
// If not all fields are in one of the accepted field states, then we
// still can't allow this state change.
if (_.difference(fieldStates, acceptedFieldStates).length) {
accept = false;
}
}
return accept;
},
/**
* @inheritdoc
*/
destroy: function (options) {
Drupal.edit.BaseModel.prototype.destroy.call(this, options);
this.stopListening();
// Destroy all fields of this entity.
this.get('fields').each(function (fieldModel) {
fieldModel.destroy();
});
},
/**
* {@inheritdoc}
*/
sync: function () {
// We don't use REST updates to sync.
return;
}
}, {
/**
* A list (sequence) of all possible states an entity can be in during
* in-place editing.
*/
states: [
// Initial state, like field's 'inactive' OR the user has just finished
// in-place editing this entity.
// - Trigger: none (initial) or EntityModel (finished).
// - Expected behavior: (when not initial state): tear down
// EntityToolbarView, in-place editors and related views.
'closed',
// User has activated in-place editing of this entity.
// - Trigger: user.
// - Expected behavior: the EntityToolbarView is gets set up, in-place
// editors (EditorViews) and related views for this entity's fields are
// set up. Upon completion of those, the state is changed to 'opening'.
'launching',
// Launching has finished.
// - Trigger: application.
// - Guarantees: in-place editors ready for use, all entity and field views
// have been set up, all fields are in the 'inactive' state.
// - Expected behavior: all fields are changed to the 'candidate' state and
// once this is completed, the entity state will be changed to 'opened'.
'opening',
// Opening has finished.
// - Trigger: EntityModel.
// - Guarantees: see 'opening', all fields are in the 'candidate' state.
// - Expected behavior: the user is able to actually use in-place editing.
'opened',
// User has clicked the 'Save' button (and has thus changed at least one
// field).
// - Trigger: user.
// - Guarantees: see 'opened', plus: either a changed field is in TempStore,
// or the user has just modified a field without activating (switching to)
// another field.
// - Expected behavior: 1) if any of the fields are not yet in TempStore,
// save them to TempStore, 2) if then any of the fields has the 'invalid'
// state, then change the entity state back to 'opened', otherwise: save
// the entity by committing it from TempStore into permanent storage.
'committing',
// User has clicked the 'Close' button, or has clicked the 'Save' button and
// that was successfully completed.
// - Trigger: user or EntityModel.
// - Guarantees: when having clicked 'Close' hardly any: fields may be in a
// variety of states; when having clicked 'Save': all fields are in the
// 'candidate' state.
// - Expected behavior: transition all fields to the 'candidate' state,
// possibly requiring confirmation in the case of having clicked 'Close'.
'deactivating',
// Deactivation has been completed.
// - Trigger: EntityModel.
// - Guarantees: all fields are in the 'candidate' state.
// - Expected behavior: change all fields to the 'inactive' state.
'closing'
],
/**
* Indicates whether the 'from' state comes before the 'to' state.
*
* @param String from
* One of Drupal.edit.EntityModel.states.
* @param String to
* One of Drupal.edit.EntityModel.states.
* @return Boolean
*/
followsStateSequence: function (from, to) {
return _.indexOf(this.states, from) < _.indexOf(this.states, to);
}
});
Drupal.edit.EntityCollection = Backbone.Collection.extend({
model: Drupal.edit.EntityModel
});
}(_, jQuery, Backbone, Drupal, Drupal.settings));
| christopherhuntley/daphnedixon | sites/all/modules/edit/js/models/EntityModel.js | JavaScript | gpl-2.0 | 24,459 |
<?php if (!defined('W3TC')) die(); ?>
<?php $this->checkbox('minify.html.strip.crlf', false, 'html_') ?> Line break removal</label><br />
| sudocoda/rs27 | wp-content/plugins/w3-total-cache/inc/options/minify/html.php | PHP | gpl-2.0 | 140 |
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.media.sound;
/**
* This class is used to identify destinations in connection blocks,
* see ModelConnectionBlock.
*
* @author Karl Helgason
*/
public final class ModelDestination {
public static final ModelIdentifier DESTINATION_NONE = null;
public static final ModelIdentifier DESTINATION_KEYNUMBER
= new ModelIdentifier("noteon", "keynumber");
public static final ModelIdentifier DESTINATION_VELOCITY
= new ModelIdentifier("noteon", "velocity");
public static final ModelIdentifier DESTINATION_PITCH
= new ModelIdentifier("osc", "pitch"); // cent
public static final ModelIdentifier DESTINATION_GAIN
= new ModelIdentifier("mixer", "gain"); // cB
public static final ModelIdentifier DESTINATION_PAN
= new ModelIdentifier("mixer", "pan"); // 0.1 %
public static final ModelIdentifier DESTINATION_REVERB
= new ModelIdentifier("mixer", "reverb"); // 0.1 %
public static final ModelIdentifier DESTINATION_CHORUS
= new ModelIdentifier("mixer", "chorus"); // 0.1 %
public static final ModelIdentifier DESTINATION_LFO1_DELAY
= new ModelIdentifier("lfo", "delay", 0); // timecent
public static final ModelIdentifier DESTINATION_LFO1_FREQ
= new ModelIdentifier("lfo", "freq", 0); // cent
public static final ModelIdentifier DESTINATION_LFO2_DELAY
= new ModelIdentifier("lfo", "delay", 1); // timecent
public static final ModelIdentifier DESTINATION_LFO2_FREQ
= new ModelIdentifier("lfo", "freq", 1); // cent
public static final ModelIdentifier DESTINATION_EG1_DELAY
= new ModelIdentifier("eg", "delay", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_ATTACK
= new ModelIdentifier("eg", "attack", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_HOLD
= new ModelIdentifier("eg", "hold", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_DECAY
= new ModelIdentifier("eg", "decay", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_SUSTAIN
= new ModelIdentifier("eg", "sustain", 0);
// 0.1 % (I want this to be value not %)
public static final ModelIdentifier DESTINATION_EG1_RELEASE
= new ModelIdentifier("eg", "release", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_SHUTDOWN
= new ModelIdentifier("eg", "shutdown", 0); // timecent
public static final ModelIdentifier DESTINATION_EG2_DELAY
= new ModelIdentifier("eg", "delay", 1); // timecent
public static final ModelIdentifier DESTINATION_EG2_ATTACK
= new ModelIdentifier("eg", "attack", 1); // timecent
public static final ModelIdentifier DESTINATION_EG2_HOLD
= new ModelIdentifier("eg", "hold", 1); // 0.1 %
public static final ModelIdentifier DESTINATION_EG2_DECAY
= new ModelIdentifier("eg", "decay", 1); // timecent
public static final ModelIdentifier DESTINATION_EG2_SUSTAIN
= new ModelIdentifier("eg", "sustain", 1);
// 0.1 % ( I want this to be value not %)
public static final ModelIdentifier DESTINATION_EG2_RELEASE
= new ModelIdentifier("eg", "release", 1); // timecent
public static final ModelIdentifier DESTINATION_EG2_SHUTDOWN
= new ModelIdentifier("eg", "shutdown", 1); // timecent
public static final ModelIdentifier DESTINATION_FILTER_FREQ
= new ModelIdentifier("filter", "freq", 0); // cent
public static final ModelIdentifier DESTINATION_FILTER_Q
= new ModelIdentifier("filter", "q", 0); // cB
private ModelIdentifier destination = DESTINATION_NONE;
private ModelTransform transform = new ModelStandardTransform();
public ModelDestination() {
}
public ModelDestination(ModelIdentifier id) {
destination = id;
}
public ModelIdentifier getIdentifier() {
return destination;
}
public void setIdentifier(ModelIdentifier destination) {
this.destination = destination;
}
public ModelTransform getTransform() {
return transform;
}
public void setTransform(ModelTransform transform) {
this.transform = transform;
}
}
| FauxFaux/jdk9-jdk | src/java.desktop/share/classes/com/sun/media/sound/ModelDestination.java | Java | gpl-2.0 | 5,633 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2015 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::extrudeModels::linearDirection
Description
Extrudes by transforming points in a specified direction by a given distance
\*---------------------------------------------------------------------------*/
#ifndef linearDirection_H
#define linearDirection_H
#include "point.H"
#include "extrudeModel.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace extrudeModels
{
/*---------------------------------------------------------------------------*\
Class linearDirection Declaration
\*---------------------------------------------------------------------------*/
class linearDirection
:
public extrudeModel
{
// Private data
//- Extrude direction
vector direction_;
//- Layer thickness
scalar thickness_;
public:
//- Runtime type information
TypeName("linearDirection");
// Constructors
//- Construct from dictionary
linearDirection(const dictionary& dict);
//- Destructor
virtual ~linearDirection();
// Member Operators
point operator()
(
const point& surfacePoint,
const vector& surfaceNormal,
const label layer
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace extrudeModels
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| OpenFOAM/OpenFOAM-2.3.x | src/mesh/extrudeModel/linearDirection/linearDirection.H | C++ | gpl-3.0 | 2,664 |
/*
YUI 3.5.1 (build 22)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('event-valuechange', function(Y) {
/**
Adds a synthetic `valueChange` event that fires when the `value` property of an
`<input>` or `<textarea>` node changes as a result of a keystroke, mouse
operation, or input method editor (IME) input event.
Usage:
YUI().use('event-valuechange', function (Y) {
Y.one('#my-input').on('valueChange', function (e) {
});
});
@module event-valuechange
**/
/**
Provides the implementation for the synthetic `valueChange` event. This class
isn't meant to be used directly, but is public to make monkeypatching possible.
Usage:
YUI().use('event-valuechange', function (Y) {
Y.one('#my-input').on('valueChange', function (e) {
});
});
@class ValueChange
@static
*/
var DATA_KEY = '_valuechange',
VALUE = 'value',
config, // defined at the end of this file
// Just a simple namespace to make methods overridable.
VC = {
// -- Static Constants -----------------------------------------------------
/**
Interval (in milliseconds) at which to poll for changes to the value of an
element with one or more `valueChange` subscribers when the user is likely
to be interacting with it.
@property POLL_INTERVAL
@type Number
@default 50
@static
**/
POLL_INTERVAL: 50,
/**
Timeout (in milliseconds) after which to stop polling when there hasn't been
any new activity (keypresses, mouse clicks, etc.) on an element.
@property TIMEOUT
@type Number
@default 10000
@static
**/
TIMEOUT: 10000,
// -- Protected Static Methods ---------------------------------------------
/**
Called at an interval to poll for changes to the value of the specified
node.
@method _poll
@param {Node} node Node to poll.
@param {Object} options Options object.
@param {EventFacade} [options.e] Event facade of the event that
initiated the polling.
@protected
@static
**/
_poll: function (node, options) {
var domNode = node._node, // performance cheat; getValue() is a big hit when polling
event = options.e,
newVal = domNode && domNode.value,
vcData = node._data && node._data[DATA_KEY], // another perf cheat
facade, prevVal;
if (!domNode || !vcData) {
VC._stopPolling(node);
return;
}
prevVal = vcData.prevVal;
if (newVal !== prevVal) {
vcData.prevVal = newVal;
facade = {
_event : event,
currentTarget: (event && event.currentTarget) || node,
newVal : newVal,
prevVal : prevVal,
target : (event && event.target) || node
};
Y.Object.each(vcData.notifiers, function (notifier) {
notifier.fire(facade);
});
VC._refreshTimeout(node);
}
},
/**
Restarts the inactivity timeout for the specified node.
@method _refreshTimeout
@param {Node} node Node to refresh.
@param {SyntheticEvent.Notifier} notifier
@protected
@static
**/
_refreshTimeout: function (node, notifier) {
// The node may have been destroyed, so check that it still exists
// before trying to get its data. Otherwise an error will occur.
if (!node._node) {
return;
}
var vcData = node.getData(DATA_KEY);
VC._stopTimeout(node); // avoid dupes
// If we don't see any changes within the timeout period (10 seconds by
// default), stop polling.
vcData.timeout = setTimeout(function () {
VC._stopPolling(node, notifier);
}, VC.TIMEOUT);
},
/**
Begins polling for changes to the `value` property of the specified node. If
polling is already underway for the specified node, it will not be restarted
unless the `force` option is `true`
@method _startPolling
@param {Node} node Node to watch.
@param {SyntheticEvent.Notifier} notifier
@param {Object} options Options object.
@param {EventFacade} [options.e] Event facade of the event that
initiated the polling.
@param {Boolean} [options.force=false] If `true`, polling will be
restarted even if we're already polling this node.
@protected
@static
**/
_startPolling: function (node, notifier, options) {
if (!node.test('input,textarea')) {
return;
}
var vcData = node.getData(DATA_KEY);
if (!vcData) {
vcData = {prevVal: node.get(VALUE)};
node.setData(DATA_KEY, vcData);
}
vcData.notifiers || (vcData.notifiers = {});
// Don't bother continuing if we're already polling this node, unless
// `options.force` is true.
if (vcData.interval) {
if (options.force) {
VC._stopPolling(node, notifier); // restart polling, but avoid dupe polls
} else {
vcData.notifiers[Y.stamp(notifier)] = notifier;
return;
}
}
// Poll for changes to the node's value. We can't rely on keyboard
// events for this, since the value may change due to a mouse-initiated
// paste event, an IME input event, or for some other reason that
// doesn't trigger a key event.
vcData.notifiers[Y.stamp(notifier)] = notifier;
vcData.interval = setInterval(function () {
VC._poll(node, vcData, options);
}, VC.POLL_INTERVAL);
VC._refreshTimeout(node, notifier);
},
/**
Stops polling for changes to the specified node's `value` attribute.
@method _stopPolling
@param {Node} node Node to stop polling on.
@param {SyntheticEvent.Notifier} [notifier] Notifier to remove from the
node. If not specified, all notifiers will be removed.
@protected
@static
**/
_stopPolling: function (node, notifier) {
// The node may have been destroyed, so check that it still exists
// before trying to get its data. Otherwise an error will occur.
if (!node._node) {
return;
}
var vcData = node.getData(DATA_KEY) || {};
clearInterval(vcData.interval);
delete vcData.interval;
VC._stopTimeout(node);
if (notifier) {
vcData.notifiers && delete vcData.notifiers[Y.stamp(notifier)];
} else {
vcData.notifiers = {};
}
},
/**
Clears the inactivity timeout for the specified node, if any.
@method _stopTimeout
@param {Node} node
@protected
@static
**/
_stopTimeout: function (node) {
var vcData = node.getData(DATA_KEY) || {};
clearTimeout(vcData.timeout);
delete vcData.timeout;
},
// -- Protected Static Event Handlers --------------------------------------
/**
Stops polling when a node's blur event fires.
@method _onBlur
@param {EventFacade} e
@param {SyntheticEvent.Notifier} notifier
@protected
@static
**/
_onBlur: function (e, notifier) {
VC._stopPolling(e.currentTarget, notifier);
},
/**
Resets a node's history and starts polling when a focus event occurs.
@method _onFocus
@param {EventFacade} e
@param {SyntheticEvent.Notifier} notifier
@protected
@static
**/
_onFocus: function (e, notifier) {
var node = e.currentTarget,
vcData = node.getData(DATA_KEY);
if (!vcData) {
vcData = {};
node.setData(DATA_KEY, vcData);
}
vcData.prevVal = node.get(VALUE);
VC._startPolling(node, notifier, {e: e});
},
/**
Starts polling when a node receives a keyDown event.
@method _onKeyDown
@param {EventFacade} e
@param {SyntheticEvent.Notifier} notifier
@protected
@static
**/
_onKeyDown: function (e, notifier) {
VC._startPolling(e.currentTarget, notifier, {e: e});
},
/**
Starts polling when an IME-related keyUp event occurs on a node.
@method _onKeyUp
@param {EventFacade} e
@param {SyntheticEvent.Notifier} notifier
@protected
@static
**/
_onKeyUp: function (e, notifier) {
// These charCodes indicate that an IME has started. We'll restart
// polling and give the IME up to 10 seconds (by default) to finish.
if (e.charCode === 229 || e.charCode === 197) {
VC._startPolling(e.currentTarget, notifier, {
e : e,
force: true
});
}
},
/**
Starts polling when a node receives a mouseDown event.
@method _onMouseDown
@param {EventFacade} e
@param {SyntheticEvent.Notifier} notifier
@protected
@static
**/
_onMouseDown: function (e, notifier) {
VC._startPolling(e.currentTarget, notifier, {e: e});
},
/**
Called when the `valuechange` event receives a new subscriber.
@method _onSubscribe
@param {Node} node
@param {Subscription} sub
@param {SyntheticEvent.Notifier} notifier
@param {Function|String} [filter] Filter function or selector string. Only
provided for delegate subscriptions.
@protected
@static
**/
_onSubscribe: function (node, sub, notifier, filter) {
var _valuechange, callbacks, nodes;
callbacks = {
blur : VC._onBlur,
focus : VC._onFocus,
keydown : VC._onKeyDown,
keyup : VC._onKeyUp,
mousedown: VC._onMouseDown
};
// Store a utility object on the notifier to hold stuff that needs to be
// passed around to trigger event handlers, polling handlers, etc.
_valuechange = notifier._valuechange = {};
if (filter) {
// If a filter is provided, then this is a delegated subscription.
_valuechange.delegated = true;
// Add a function to the notifier that we can use to find all
// nodes that pass the delegate filter.
_valuechange.getNodes = function () {
return node.all('input,textarea').filter(filter);
};
// Store the initial values for each descendant of the container
// node that passes the delegate filter.
_valuechange.getNodes().each(function (child) {
if (!child.getData(DATA_KEY)) {
child.setData(DATA_KEY, {prevVal: child.get(VALUE)});
}
});
notifier._handles = Y.delegate(callbacks, node, filter, null,
notifier);
} else {
// This is a normal (non-delegated) event subscription.
if (!node.test('input,textarea')) {
return;
}
if (!node.getData(DATA_KEY)) {
node.setData(DATA_KEY, {prevVal: node.get(VALUE)});
}
notifier._handles = node.on(callbacks, null, null, notifier);
}
},
/**
Called when the `valuechange` event loses a subscriber.
@method _onUnsubscribe
@param {Node} node
@param {Subscription} subscription
@param {SyntheticEvent.Notifier} notifier
@protected
@static
**/
_onUnsubscribe: function (node, subscription, notifier) {
var _valuechange = notifier._valuechange;
notifier._handles && notifier._handles.detach();
if (_valuechange.delegated) {
_valuechange.getNodes().each(function (child) {
VC._stopPolling(child, notifier);
});
} else {
VC._stopPolling(node, notifier);
}
}
};
/**
Synthetic event that fires when the `value` property of an `<input>` or
`<textarea>` node changes as a result of a user-initiated keystroke, mouse
operation, or input method editor (IME) input event.
Unlike the `onchange` event, this event fires when the value actually changes
and not when the element loses focus. This event also reports IME and
multi-stroke input more reliably than `oninput` or the various key events across
browsers.
For performance reasons, only focused nodes are monitored for changes, so
programmatic value changes on nodes that don't have focus won't be detected.
@example
YUI().use('event-valuechange', function (Y) {
Y.one('#my-input').on('valueChange', function (e) {
});
});
@event valuechange
@param {String} prevVal Previous value prior to the latest change.
@param {String} newVal New value after the latest change.
@for YUI
**/
config = {
detach: VC._onUnsubscribe,
on : VC._onSubscribe,
delegate : VC._onSubscribe,
detachDelegate: VC._onUnsubscribe,
publishConfig: {
emitFacade: true
}
};
Y.Event.define('valuechange', config);
Y.Event.define('valueChange', config); // deprecated, but supported for backcompat
Y.ValueChange = VC;
}, '3.5.1' ,{requires:['event-focus', 'event-synthetic']});
| sergiomt/zesped | src/webapp/js/yui/event-valuechange/event-valuechange.js | JavaScript | agpl-3.0 | 13,297 |
"""
Read/Write AMQP frames over network transports.
2009-01-14 Barry Pederson <bp@barryp.org>
"""
# Copyright (C) 2009 Barry Pederson <bp@barryp.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
import re
import socket
#
# See if Python 2.6+ SSL support is available
#
try:
import ssl
HAVE_PY26_SSL = True
except:
HAVE_PY26_SSL = False
try:
bytes
except:
# Python 2.5 and lower
bytes = str
from struct import pack, unpack
AMQP_PORT = 5672
# Yes, Advanced Message Queuing Protocol Protocol is redundant
AMQP_PROTOCOL_HEADER = 'AMQP\x01\x01\x09\x01'.encode('latin_1')
# Match things like: [fe80::1]:5432, from RFC 2732
IPV6_LITERAL = re.compile(r'\[([\.0-9a-f:]+)\](?::(\d+))?')
class _AbstractTransport(object):
"""
Common superclass for TCP and SSL transports
"""
def __init__(self, host, connect_timeout):
msg = 'socket.getaddrinfo() for %s returned an empty list' % host
port = AMQP_PORT
m = IPV6_LITERAL.match(host)
if m:
host = m.group(1)
if m.group(2):
port = int(m.group(2))
else:
if ':' in host:
host, port = host.rsplit(':', 1)
port = int(port)
self.sock = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.SOL_TCP):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
self.sock.settimeout(connect_timeout)
self.sock.connect(sa)
except socket.error, msg:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
# Didn't connect, return the most recent error message
raise socket.error, msg
self.sock.settimeout(None)
self.sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self._setup_transport()
self._write(AMQP_PROTOCOL_HEADER)
def __del__(self):
self.close()
def _read(self, n):
"""
Read exactly n bytes from the peer
"""
raise NotImplementedError('Must be overriden in subclass')
def _setup_transport(self):
"""
Do any additional initialization of the class (used
by the subclasses).
"""
pass
def _shutdown_transport(self):
"""
Do any preliminary work in shutting down the connection.
"""
pass
def _write(self, s):
"""
Completely write a string to the peer.
"""
raise NotImplementedError('Must be overriden in subclass')
def close(self):
if self.sock is not None:
self._shutdown_transport()
# Call shutdown first to make sure that pending messages
# reach the AMQP broker if the program exits after
# calling this method.
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
self.sock = None
def read_frame(self):
"""
Read an AMQP frame.
"""
frame_type, channel, size = unpack('>BHI', self._read(7))
payload = self._read(size)
ch = ord(self._read(1))
if ch == 206: # '\xce'
return frame_type, channel, payload
else:
raise Exception('Framing Error, received 0x%02x while expecting 0xce' % ch)
def write_frame(self, frame_type, channel, payload):
"""
Write out an AMQP frame.
"""
size = len(payload)
self._write(pack('>BHI%dsB' % size,
frame_type, channel, size, payload, 0xce))
class SSLTransport(_AbstractTransport):
"""
Transport that works over SSL
"""
def __init__(self, host, connect_timeout, ssl):
if isinstance(ssl, dict):
self.sslopts = ssl
self.sslobj = None
super(SSLTransport, self).__init__(host, connect_timeout)
def _setup_transport(self):
"""
Wrap the socket in an SSL object, either the
new Python 2.6 version, or the older Python 2.5 and
lower version.
"""
if HAVE_PY26_SSL:
if hasattr(self, 'sslopts'):
self.sslobj = ssl.wrap_socket(self.sock, **self.sslopts)
else:
self.sslobj = ssl.wrap_socket(self.sock)
self.sslobj.do_handshake()
else:
self.sslobj = socket.ssl(self.sock)
def _shutdown_transport(self):
"""
Unwrap a Python 2.6 SSL socket, so we can call shutdown()
"""
if HAVE_PY26_SSL and (self.sslobj is not None):
self.sock = self.sslobj.unwrap()
self.sslobj = None
def _read(self, n):
"""
It seems that SSL Objects read() method may not supply as much
as you're asking for, at least with extremely large messages.
somewhere > 16K - found this in the test_channel.py test_large
unittest.
"""
result = self.sslobj.read(n)
while len(result) < n:
s = self.sslobj.read(n - len(result))
if not s:
raise IOError('Socket closed')
result += s
return result
def _write(self, s):
"""
Write a string out to the SSL socket fully.
"""
while s:
n = self.sslobj.write(s)
if not n:
raise IOError('Socket closed')
s = s[n:]
class TCPTransport(_AbstractTransport):
"""
Transport that deals directly with TCP socket.
"""
def _setup_transport(self):
"""
Setup to _write() directly to the socket, and
do our own buffered reads.
"""
self._write = self.sock.sendall
self._read_buffer = bytes()
def _read(self, n):
"""
Read exactly n bytes from the socket
"""
while len(self._read_buffer) < n:
s = self.sock.recv(65536)
if not s:
raise IOError('Socket closed')
self._read_buffer += s
result = self._read_buffer[:n]
self._read_buffer = self._read_buffer[n:]
return result
def create_transport(host, connect_timeout, ssl=False):
"""
Given a few parameters from the Connection constructor,
select and create a subclass of _AbstractTransport.
"""
if ssl:
return SSLTransport(host, connect_timeout, ssl)
else:
return TCPTransport(host, connect_timeout)
| mzdaniel/oh-mainline | vendor/packages/amqplib/amqplib/client_0_8/transport.py | Python | agpl-3.0 | 7,349 |
$(document).delegate('.storage_graph_link', 'click', function(e){
var anchor = this,
el = $(anchor),
id = el.attr('data-status');
if(e.ctrlKey || e.metaKey){
return true;
}else{
e.preventDefault();
}
var cell = document.getElementById(id);
var text = el.html();
if (text == '[:: show ::]') {
anchor.innerHTML = '[:: hide ::]';
if (cell.nodeName == 'IMG') { // <img src='...'/>
cell.src=anchor.href;
} else {
$.ajax({
type: "get",
url: anchor.href,
success : function(response, textStatus) {
cell.style.display = 'block';
cell.parentNode.style.display = 'block';
cell.innerHTML = response;
var data = $('#countTrendMeta',cell).text();
graphLineChart($('#countTrend',cell)[0],eval('('+data+')'));
data = $('#longTrendMeta',cell).text();
graphLineChart($('#longTrend',cell)[0],eval('('+data+')'));
data = $('#avgTrendMeta',cell).text();
graphLineChart($('#avgTrend',cell)[0],eval('('+data+')'));
data = $('#errorTrendMeta',cell).text();
graphLineChart($('#errorTrend',cell)[0],eval('('+data+')'));
data = $('#piechartMeta',cell).text();
graphPieChart($('#piechart',cell)[0],eval('('+data+')'));
}
});
}
} else {
anchor.innerHTML = '[:: show ::]';
cell.style.display = 'none';
cell.parentNode.style.display = 'none';
}
}) | jialinsun/cat | cat-home/src/main/webapp/js/storage.js | JavaScript | apache-2.0 | 1,379 |
/*
* 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.axis2.jaxws.message.databinding.impl;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMOutputFormat;
import org.apache.axis2.jaxws.ExceptionFactory;
import org.apache.axis2.jaxws.message.Message;
import org.apache.axis2.jaxws.message.databinding.SOAPEnvelopeBlock;
import org.apache.axis2.jaxws.message.factory.BlockFactory;
import org.apache.axis2.jaxws.message.factory.MessageFactory;
import org.apache.axis2.jaxws.message.impl.BlockImpl;
import org.apache.axis2.jaxws.message.util.SOAPElementReader;
import org.apache.axis2.jaxws.registry.FactoryRegistry;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.ws.WebServiceException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
/**
*
*
*/
public class SOAPEnvelopeBlockImpl extends BlockImpl implements SOAPEnvelopeBlock {
/**
* Called by SOAPEnvelopeBlockFactory
*
* @param busObject
* @param busContext
* @param qName
* @param factory
*/
public SOAPEnvelopeBlockImpl(Object busObject, Object busContext,
QName qName, BlockFactory factory) {
super(busObject,
busContext,
(qName == null) ? getQName((SOAPEnvelope)busObject) : qName,
factory);
}
/**
* Called by SOAPEnvelopeBlockFactory
*
* @param omElement
* @param busContext
* @param qName
* @param factory
*/
public SOAPEnvelopeBlockImpl(OMElement omElement, Object busContext,
QName qName, BlockFactory factory) {
super(omElement, busContext, qName, factory);
}
/* (non-Javadoc)
* @see org.apache.axis2.jaxws.message.impl.BlockImpl#_getBOFromReader(javax.xml.stream.XMLStreamReader, java.lang.Object)
*/
@Override
protected Object _getBOFromReader(XMLStreamReader reader, Object busContext)
throws XMLStreamException, WebServiceException {
MessageFactory mf = (MessageFactory)FactoryRegistry.getFactory(MessageFactory.class);
Message message = mf.createFrom(reader, null);
SOAPEnvelope env = message.getAsSOAPEnvelope();
this.setQName(getQName(env));
return env;
}
/* (non-Javadoc)
* @see org.apache.axis2.jaxws.message.impl.BlockImpl#_getReaderFromBO(java.lang.Object, java.lang.Object)
*/
@Override
protected XMLStreamReader _getReaderFromBO(Object busObj, Object busContext)
throws XMLStreamException, WebServiceException {
return new SOAPElementReader((SOAPElement)busObj);
}
/* (non-Javadoc)
* @see org.apache.axis2.jaxws.message.impl.BlockImpl#_outputFromBO(java.lang.Object, java.lang.Object, javax.xml.stream.XMLStreamWriter)
*/
@Override
protected void _outputFromBO(Object busObject, Object busContext,
XMLStreamWriter writer)
throws XMLStreamException, WebServiceException {
XMLStreamReader reader = _getReaderFromBO(busObject, busContext);
_outputFromReader(reader, writer);
}
/**
* Get the QName of the envelope
*
* @param env
* @return QName
*/
private static QName getQName(SOAPEnvelope env) {
return new QName(env.getNamespaceURI(), env.getLocalName(), env.getPrefix());
}
public boolean isElementData() {
return true;
}
public void close() {
return; // Nothing to close
}
public InputStream getXMLInputStream(String encoding) throws UnsupportedEncodingException {
byte[] bytes = getXMLBytes(encoding);
return new ByteArrayInputStream(bytes);
}
public Object getObject() {
try {
return getBusinessObject(false);
} catch (XMLStreamException e) {
throw ExceptionFactory.makeWebServiceException(e);
}
}
public boolean isDestructiveRead() {
return false;
}
public boolean isDestructiveWrite() {
return false;
}
public byte[] getXMLBytes(String encoding) throws UnsupportedEncodingException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OMOutputFormat format = new OMOutputFormat();
format.setCharSetEncoding(encoding);
try {
serialize(baos, format);
baos.flush();
return baos.toByteArray();
} catch (XMLStreamException e) {
throw ExceptionFactory.makeWebServiceException(e);
} catch (IOException e) {
throw ExceptionFactory.makeWebServiceException(e);
}
}
}
| arunasujith/wso2-axis2 | modules/jaxws/src/org/apache/axis2/jaxws/message/databinding/impl/SOAPEnvelopeBlockImpl.java | Java | apache-2.0 | 5,741 |
/*
* 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.cassandra.schema;
import java.util.Map;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
/**
* An immutable class representing keyspace parameters (durability and replication).
*/
public final class KeyspaceParams
{
public static final boolean DEFAULT_DURABLE_WRITES = true;
/**
* This determines durable writes for the {@link org.apache.cassandra.config.SchemaConstants#SCHEMA_KEYSPACE_NAME}
* and {@link org.apache.cassandra.config.SchemaConstants#SYSTEM_KEYSPACE_NAME} keyspaces,
* the only reason it is not final is for commitlog unit tests. It should only be changed for testing purposes.
*/
@VisibleForTesting
public static boolean DEFAULT_LOCAL_DURABLE_WRITES = true;
public enum Option
{
DURABLE_WRITES,
REPLICATION;
@Override
public String toString()
{
return name().toLowerCase();
}
}
public final boolean durableWrites;
public final ReplicationParams replication;
public KeyspaceParams(boolean durableWrites, ReplicationParams replication)
{
this.durableWrites = durableWrites;
this.replication = replication;
}
public static KeyspaceParams create(boolean durableWrites, Map<String, String> replication)
{
return new KeyspaceParams(durableWrites, ReplicationParams.fromMap(replication));
}
public static KeyspaceParams local()
{
return new KeyspaceParams(DEFAULT_LOCAL_DURABLE_WRITES, ReplicationParams.local());
}
public static KeyspaceParams simple(int replicationFactor)
{
return new KeyspaceParams(true, ReplicationParams.simple(replicationFactor));
}
public static KeyspaceParams simpleTransient(int replicationFactor)
{
return new KeyspaceParams(false, ReplicationParams.simple(replicationFactor));
}
public static KeyspaceParams nts(Object... args)
{
return new KeyspaceParams(true, ReplicationParams.nts(args));
}
public void validate(String name)
{
replication.validate(name);
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (!(o instanceof KeyspaceParams))
return false;
KeyspaceParams p = (KeyspaceParams) o;
return durableWrites == p.durableWrites && replication.equals(p.replication);
}
@Override
public int hashCode()
{
return Objects.hashCode(durableWrites, replication);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add(Option.DURABLE_WRITES.toString(), durableWrites)
.add(Option.REPLICATION.toString(), replication)
.toString();
}
}
| yhnishi/cassandra | src/java/org/apache/cassandra/schema/KeyspaceParams.java | Java | apache-2.0 | 3,724 |
// 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.
#nullable disable
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal partial class CSharpExtensionMethodReducer : AbstractCSharpReducer
{
private static readonly ObjectPool<IReductionRewriter> s_pool = new(
() => new Rewriter(s_pool));
public CSharpExtensionMethodReducer() : base(s_pool)
{
}
private static readonly Func<InvocationExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyExtensionMethod = SimplifyExtensionMethod;
private static SyntaxNode SimplifyExtensionMethod(
InvocationExpressionSyntax node,
SemanticModel semanticModel,
OptionSet optionSet,
CancellationToken cancellationToken)
{
var rewrittenNode = node;
if (node.Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
{
var memberAccessName = (MemberAccessExpressionSyntax)node.Expression;
rewrittenNode = TryReduceExtensionMethod(node, semanticModel, rewrittenNode, memberAccessName.Name);
}
else if (node.Expression is SimpleNameSyntax)
{
rewrittenNode = TryReduceExtensionMethod(node, semanticModel, rewrittenNode, (SimpleNameSyntax)node.Expression);
}
return rewrittenNode;
}
private static InvocationExpressionSyntax TryReduceExtensionMethod(InvocationExpressionSyntax node, SemanticModel semanticModel, InvocationExpressionSyntax rewrittenNode, SimpleNameSyntax expressionName)
{
var targetSymbol = semanticModel.GetSymbolInfo(expressionName);
if (targetSymbol.Symbol != null && targetSymbol.Symbol.Kind == SymbolKind.Method)
{
var targetMethodSymbol = (IMethodSymbol)targetSymbol.Symbol;
if (!targetMethodSymbol.IsReducedExtension())
{
var argumentList = node.ArgumentList;
var noOfArguments = argumentList.Arguments.Count;
if (noOfArguments > 0)
{
MemberAccessExpressionSyntax newMemberAccess = null;
var invocationExpressionNodeExpression = node.Expression;
// Ensure the first expression is parenthesized so that we don't cause any
// precedence issues when we take the extension method and tack it on the
// end of it.
var expression = argumentList.Arguments[0].Expression.Parenthesize();
if (node.Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression)
{
newMemberAccess = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression, expression,
((MemberAccessExpressionSyntax)invocationExpressionNodeExpression).OperatorToken,
((MemberAccessExpressionSyntax)invocationExpressionNodeExpression).Name);
}
else if (node.Expression.Kind() == SyntaxKind.IdentifierName)
{
newMemberAccess = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression, expression,
(IdentifierNameSyntax)invocationExpressionNodeExpression.WithoutLeadingTrivia());
}
else if (node.Expression.Kind() == SyntaxKind.GenericName)
{
newMemberAccess = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression, expression,
(GenericNameSyntax)invocationExpressionNodeExpression.WithoutLeadingTrivia());
}
else
{
Debug.Assert(false, "The expression kind is not MemberAccessExpression or IdentifierName or GenericName to be converted to Member Access Expression for Ext Method Reduction");
}
if (newMemberAccess == null)
{
return node;
}
// Preserve Trivia
newMemberAccess = newMemberAccess.WithLeadingTrivia(node.GetLeadingTrivia());
// Below removes the first argument
// we need to reuse the separators to maintain existing formatting & comments in the arguments itself
var newArguments = SyntaxFactory.SeparatedList<ArgumentSyntax>(argumentList.Arguments.GetWithSeparators().AsEnumerable().Skip(2));
var rewrittenArgumentList = argumentList.WithArguments(newArguments);
var candidateRewrittenNode = SyntaxFactory.InvocationExpression(newMemberAccess, rewrittenArgumentList);
var oldSymbol = semanticModel.GetSymbolInfo(node).Symbol;
var newSymbol = semanticModel.GetSpeculativeSymbolInfo(
node.SpanStart,
candidateRewrittenNode,
SpeculativeBindingOption.BindAsExpression).Symbol;
if (oldSymbol != null && newSymbol != null)
{
if (newSymbol.Kind == SymbolKind.Method && oldSymbol.Equals(((IMethodSymbol)newSymbol).GetConstructedReducedFrom()))
{
rewrittenNode = candidateRewrittenNode;
}
}
}
}
}
return rewrittenNode;
}
}
}
| shyamnamboodiripad/roslyn | src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpExtensionMethodReducer.cs | C# | apache-2.0 | 6,511 |
/*
* 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.kafka.connect.storage;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.runtime.WorkerConfig;
import org.apache.kafka.connect.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* Implementation of OffsetBackingStore that doesn't actually persist any data. To ensure this
* behaves similarly to a real backing store, operations are executed asynchronously on a
* background thread.
*/
public class MemoryOffsetBackingStore implements OffsetBackingStore {
private static final Logger log = LoggerFactory.getLogger(MemoryOffsetBackingStore.class);
protected Map<ByteBuffer, ByteBuffer> data = new HashMap<>();
protected ExecutorService executor;
public MemoryOffsetBackingStore() {
}
@Override
public void configure(WorkerConfig config) {
}
@Override
public void start() {
executor = Executors.newSingleThreadExecutor();
}
@Override
public void stop() {
if (executor != null) {
executor.shutdown();
// Best effort wait for any get() and set() tasks (and caller's callbacks) to complete.
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (!executor.shutdownNow().isEmpty()) {
throw new ConnectException("Failed to stop MemoryOffsetBackingStore. Exiting without cleanly " +
"shutting down pending tasks and/or callbacks.");
}
executor = null;
}
}
@Override
public Future<Map<ByteBuffer, ByteBuffer>> get(
final Collection<ByteBuffer> keys,
final Callback<Map<ByteBuffer, ByteBuffer>> callback) {
return executor.submit(new Callable<Map<ByteBuffer, ByteBuffer>>() {
@Override
public Map<ByteBuffer, ByteBuffer> call() throws Exception {
Map<ByteBuffer, ByteBuffer> result = new HashMap<>();
for (ByteBuffer key : keys) {
result.put(key, data.get(key));
}
if (callback != null)
callback.onCompletion(null, result);
return result;
}
});
}
@Override
public Future<Void> set(final Map<ByteBuffer, ByteBuffer> values,
final Callback<Void> callback) {
return executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (Map.Entry<ByteBuffer, ByteBuffer> entry : values.entrySet()) {
data.put(entry.getKey(), entry.getValue());
}
save();
if (callback != null)
callback.onCompletion(null, null);
return null;
}
});
}
// Hook to allow subclasses to persist data
protected void save() {
}
}
| wangcy6/storm_app | frame/kafka-0.11.0/kafka-0.11.0.1-src/connect/runtime/src/main/java/org/apache/kafka/connect/storage/MemoryOffsetBackingStore.java | Java | apache-2.0 | 4,169 |
// 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.
#nullable disable
#if NETCOREAPP
using System;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
namespace Roslyn.Test.Utilities.CoreClr
{
internal static class SharedConsole
{
private static TextWriter s_savedConsoleOut;
private static TextWriter s_savedConsoleError;
private static AsyncLocal<StringWriter> s_currentOut;
private static AsyncLocal<StringWriter> s_currentError;
internal static void OverrideConsole()
{
s_savedConsoleOut = Console.Out;
s_savedConsoleError = Console.Error;
s_currentOut = new AsyncLocal<StringWriter>();
s_currentError = new AsyncLocal<StringWriter>();
Console.SetOut(new SharedConsoleOutWriter());
Console.SetError(new SharedConsoleErrorWriter());
}
public static void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput)
{
var outputWriter = new CappedStringWriter(expectedLength);
var errorOutputWriter = new CappedStringWriter(expectedLength);
var savedOutput = s_currentOut.Value;
var savedError = s_currentError.Value;
try
{
s_currentOut.Value = outputWriter;
s_currentError.Value = errorOutputWriter;
action();
}
finally
{
s_currentOut.Value = savedOutput;
s_currentError.Value = savedError;
}
output = outputWriter.ToString();
errorOutput = errorOutputWriter.ToString();
}
private sealed class SharedConsoleOutWriter : SharedConsoleWriter
{
public override TextWriter Underlying => s_currentOut.Value ?? s_savedConsoleOut;
}
private sealed class SharedConsoleErrorWriter : SharedConsoleWriter
{
public override TextWriter Underlying => s_currentError.Value ?? s_savedConsoleError;
}
private abstract class SharedConsoleWriter : TextWriter
{
public override Encoding Encoding => Underlying.Encoding;
public abstract TextWriter Underlying { get; }
public override void Write(char value) => Underlying.Write(value);
}
}
}
#endif
| brettfo/roslyn | src/Test/Utilities/Portable/Platform/CoreClr/SharedConsoleOutWriter.cs | C# | apache-2.0 | 2,634 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WebMatrix.Extensibility;
using NuGet;
using NuGet.WebMatrix.Data;
namespace NuGet.WebMatrix
{
internal class FilterManager
{
private ListViewFilter _installedFilter;
private ListViewFilter _updatesFilter;
private ListViewFilter _disabledFilter;
private VirtualizingListViewFilter _allFilter;
// Task scheduler for executing tasks on the primary thread
private TaskScheduler _scheduler;
/// <summary>
/// Initializes a new instance of the <see cref="T:FilterManager"/> class.
/// </summary>
internal FilterManager(NuGetModel model, TaskScheduler scheduler, INuGetGalleryDescriptor descriptor)
{
Debug.Assert(model != null, "Model must not be null");
Debug.Assert(scheduler != null, "TaskScheduler must not be null");
this.Model = model;
Filters = new ObservableCollection<IListViewFilter>();
_installedFilter = new ListViewFilter(Resources.Filter_Installed, string.Format(Resources.Filter_InstalledDescription, descriptor.PackageKind), supportsPrerelease: false);
_installedFilter.FilteredItems.SortDescriptions.Clear();
_updatesFilter = new ListViewFilter(Resources.Filter_Updated, string.Format(Resources.Filter_UpdatedDescription, descriptor.PackageKind), supportsPrerelease: true);
_updatesFilter.FilteredItems.SortDescriptions.Clear();
_disabledFilter = new ListViewFilter(Resources.Filter_Disabled, string.Format(Resources.Filter_DisabledDescription, descriptor.PackageKind), supportsPrerelease: false);
_disabledFilter.FilteredItems.SortDescriptions.Clear();
_scheduler = scheduler;
}
internal ObservableCollection<IListViewFilter> Filters
{
get;
private set;
}
public NuGetModel Model
{
get;
private set;
}
internal ListViewFilter InstalledFilter
{
get
{
return _installedFilter;
}
}
private VirtualizingListViewFilter AllFilter
{
get
{
return _allFilter;
}
}
private ListViewFilter DisabledFilter
{
get
{
return _disabledFilter;
}
}
public void UpdateFilters()
{
// populate the installed packages first, followed by disabled filter (other categories depend on this information)
var populateInstalledTask = StartPopulatingInstalledAndDisabledFilters();
populateInstalledTask.Wait();
// Start populating the filters
var populateFiltersTask = StartPopulatingAllAndUpdateFilters();
populateFiltersTask.Wait();
}
private Task StartPopulatingInstalledAndDisabledFilters()
{
return Task.Factory.StartNew(() =>
{
// after we get the installed packages, use them to populate the 'installed' and 'disabled' filters
var installedTask = Task.Factory
.StartNew<IEnumerable<PackageViewModel>>(GetInstalledPackages, TaskCreationOptions.AttachedToParent);
installedTask.ContinueWith(
UpdateInstalledFilter,
CancellationToken.None,
TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.OnlyOnRanToCompletion,
this._scheduler);
installedTask.ContinueWith(
UpdateDisabledFilter,
CancellationToken.None,
TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.OnlyOnRanToCompletion,
this._scheduler);
});
}
private Task StartPopulatingAllAndUpdateFilters()
{
// the child tasks here are created with AttachedToParent, the outer task will not
// complete until all children have.
return Task.Factory.StartNew(() =>
{
// each of these operations is a two-step process
// 1. Get the packages
// 2. Create view models and add to filters
Task.Factory
.StartNew(UpdateTheAllFilter, TaskCreationOptions.AttachedToParent);
Task.Factory
.StartNew<IEnumerable<IPackage>>(GetUpdatePackages, TaskCreationOptions.AttachedToParent)
.ContinueWith(
UpdateUpdatesFilter(),
CancellationToken.None,
TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.OnlyOnRanToCompletion,
this._scheduler);
})
.ContinueWith(AddFilters, this._scheduler);
}
private void AddFilters(Task task)
{
Filters.Clear();
// always show the 'all' filter
Filters.Add(_allFilter);
if (_updatesFilter.Count > 0)
{
Filters.Add(_updatesFilter);
}
// always show the installed filter
Filters.Add(_installedFilter);
if (_disabledFilter.Count > 0)
{
Filters.Add(_disabledFilter);
}
if (task.IsFaulted)
{
throw task.Exception;
}
}
private void UpdateTheAllFilter()
{
// updating the 'all' filter can take a matter of seconds -- so only update when it's timed out
if (this._allFilter == null)
{
this._allFilter = new VirtualizingListViewFilter(
Resources.Filter_All,
Resources.Filter_AllDescription,
(p) => new PackageViewModel(this.Model, p as IPackage, PackageViewModelAction.InstallOrUninstall));
this.AllFilter.Sort = (p) => p.DownloadCount;
if (!String.IsNullOrWhiteSpace(this.Model.FeedSource.FilterTag))
{
this.AllFilter.Filter = FilterManager.BuildTagFilterExpression(this.Model.FeedSource.FilterTag);
}
this.AllFilter.PackageManager = this.Model.PackageManager;
}
}
private void UpdateInstalledFilter(Task<IEnumerable<PackageViewModel>> task)
{
var installed = task.Result;
_installedFilter.Items.Clear();
foreach (var viewModel in installed)
{
_installedFilter.Items.Add(new ListViewItemWrapper()
{
Item = viewModel,
SearchText = viewModel.SearchText,
Name = viewModel.Name,
});
}
}
private void UpdateDisabledFilter(Task<IEnumerable<PackageViewModel>> task)
{
var installed = task.Result;
_disabledFilter.Items.Clear();
foreach (var viewModel in installed)
{
if (!viewModel.IsEnabled)
{
_disabledFilter.Items.Add(new ListViewItemWrapper()
{
Item = viewModel,
SearchText = viewModel.SearchText,
Name = viewModel.Name,
});
}
}
}
private Action<Task<IEnumerable<IPackage>>> UpdateUpdatesFilter()
{
return (task) =>
{
if (task.Result == null)
{
return;
}
_updatesFilter.Items.Clear();
var packages = task.Result;
foreach (var package in packages)
{
var packageViewModel = new PackageViewModel(this.Model, package, PackageViewModelAction.Update);
_updatesFilter.Items.Add(new ListViewItemWrapper()
{
Item = packageViewModel,
SearchText = packageViewModel.SearchText,
Name = packageViewModel.Name,
});
}
};
}
/// <summary>
/// Filters the given set of packages on the given tag. If the filter tag is null or whitespace,
/// all packages are returned. (Case-Insensitive)
/// </summary>
/// <param name="packages">Input packages</param>
/// <param name="filterTag">The tag to filter</param>
/// <returns>The set of packages containing the given tag tag</returns>
/// <remarks>
/// This implementation (IQueryable) is based on the nature of the NuGet remote package service.
/// The filter clause applied here is pushed up to the server, which will dramatically increase the
/// performance. If you tweak the body of this function, expect to find things that work locally,
/// and fail when hitting the server-side.
/// </remarks>
public static IQueryable<IPackage> FilterOnTag(IQueryable<IPackage> packages, string filterTag)
{
Debug.Assert(packages != null, "Packages cannot be null");
if (string.IsNullOrWhiteSpace(filterTag))
{
return packages;
}
// we're doing this padding because we don't get to call string.split
// when this is running on a remote package list (inside the lambda)
//
// the tag value on the package is considered untrusted input, so we make sure
// it has a leading and trailing space, as does the search text.
// it's also possible that package.Tags might be delimited by spaces and commas
// like: ' foo, bar '
string loweredFilterTag = filterTag.ToLowerInvariant().Trim();
string loweredPaddedFilterTag = " " + loweredFilterTag + " ";
string loweredCommaPaddedFilterTag = " " + loweredFilterTag + ", ";
return packages
.Where(package => package.Tags != null)
.Where(package =>
(" " + package.Tags.ToLower().Trim() + " ").Contains(loweredPaddedFilterTag)
|| (" " + package.Tags.ToLower().Trim() + " ").Contains(loweredCommaPaddedFilterTag));
}
public static Expression<Func<IPackage, bool>> BuildTagFilterExpression(string filterTag)
{
// we're doing this padding because we don't get to call string.split
// when this is running on a remote package list (inside the lambda)
//
// the tag value on the package is considered untrusted input, so we make sure
// it has a leading and trailing space, as does the search text.
// it's also possible that package.Tags might be delimited by spaces and commas
// like: ' foo, bar '
string loweredFilterTag = filterTag.ToLowerInvariant().Trim();
string loweredPaddedFilterTag = " " + loweredFilterTag + " ";
string loweredCommaPaddedFilterTag = " " + loweredFilterTag + ", ";
return (package) => package.Tags != null &&
((" " + package.Tags.ToLower().Trim() + " ").Contains(loweredPaddedFilterTag) ||
(" " + package.Tags.ToLower().Trim() + " ").Contains(loweredCommaPaddedFilterTag));
}
private IEnumerable<PackageViewModel> GetInstalledPackages()
{
var installed = FilterOnTag(this.Model.GetInstalledPackages().AsQueryable(), this.Model.FeedSource.FilterTag);
//// From the installed tab, the only possible operation is uninstall and update is NOT supported
//// For this reason, retrieving the remote package is not worthwhile
//// Plus, Downloads count will not be shown in installed tab, which is fine
//// Note that 'ALL' tab continues to support all applicable operations on a selected package including 'Update'
IEnumerable<PackageViewModel> viewModels;
viewModels = installed.Select((local) => new PackageViewModel(
this.Model,
local,
true,
PackageViewModelAction.InstallOrUninstall));
return viewModels;
}
private IEnumerable<IPackage> GetUpdatePackages()
{
IEnumerable<IPackage> allPackages = this.Model.GetPackagesWithUpdates();
return FilterOnTag(allPackages.AsQueryable(), this.Model.FeedSource.FilterTag);
}
}
}
| mrward/NuGet.V2 | WebMatrixExtension/NuGetExtension/Core/FilterManager.cs | C# | apache-2.0 | 13,110 |
/**
* Copyright 2017 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.
*/
import { MDCFoundation } from 'material__base';
import { cssClasses, strings } from './constants';
import { MSDDialogAdapter } from './adapter';
export class MDCDialogFoundation extends MDCFoundation<MSDDialogAdapter> {
static readonly cssClasses: cssClasses;
static readonly strings: strings;
static readonly defaultAdapter: MSDDialogAdapter;
open(): void;
close(): void;
isOpen(): boolean;
accept(shouldNotify: boolean): void;
cancel(shouldNotify: boolean): void;
}
export default MDCDialogFoundation;
| laurentiustamate94/DefinitelyTyped | types/material__dialog/foundation.d.ts | TypeScript | mit | 1,164 |
/* Area: ffi_closure, unwind info
Purpose: Check if the unwind information is passed correctly.
Limitations: none.
PR: none.
Originator: Jeff Sturm <jsturm@one-point.com> */
/* { dg-do run } */
#include "ffitestcxx.h"
#if defined HAVE_STDINT_H
#include <stdint.h>
#endif
#if defined HAVE_INTTYPES_H
#include <inttypes.h>
#endif
void
closure_test_fn(ffi_cif* cif __UNUSED__, void* resp __UNUSED__,
void** args __UNUSED__, void* userdata __UNUSED__)
{
throw 9;
}
typedef void (*closure_test_type)();
void closure_test_fn1(ffi_cif* cif __UNUSED__, void* resp,
void** args, void* userdata __UNUSED__)
{
*(ffi_arg*)resp =
(int)*(float *)args[0] +(int)(*(float *)args[1]) +
(int)(*(float *)args[2]) + (int)*(float *)args[3] +
(int)(*(signed short *)args[4]) + (int)(*(float *)args[5]) +
(int)*(float *)args[6] + (int)(*(int *)args[7]) +
(int)(*(double*)args[8]) + (int)*(int *)args[9] +
(int)(*(int *)args[10]) + (int)(*(float *)args[11]) +
(int)*(int *)args[12] + (int)(*(int *)args[13]) +
(int)(*(int *)args[14]) + *(int *)args[15] + (int)(intptr_t)userdata;
printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
(int)*(float *)args[0], (int)(*(float *)args[1]),
(int)(*(float *)args[2]), (int)*(float *)args[3],
(int)(*(signed short *)args[4]), (int)(*(float *)args[5]),
(int)*(float *)args[6], (int)(*(int *)args[7]),
(int)(*(double *)args[8]), (int)*(int *)args[9],
(int)(*(int *)args[10]), (int)(*(float *)args[11]),
(int)*(int *)args[12], (int)(*(int *)args[13]),
(int)(*(int *)args[14]), *(int *)args[15],
(int)(intptr_t)userdata, (int)*(ffi_arg*)resp);
throw (int)*(ffi_arg*)resp;
}
typedef int (*closure_test_type1)(float, float, float, float, signed short,
float, float, int, double, int, int, float,
int, int, int, int);
int main (void)
{
ffi_cif cif;
void *code;
ffi_closure *pcl = (ffi_closure *)ffi_closure_alloc(sizeof(ffi_closure), &code);
ffi_type * cl_arg_types[17];
{
cl_arg_types[1] = NULL;
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0,
&ffi_type_void, cl_arg_types) == FFI_OK);
CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn, NULL, code) == FFI_OK);
try
{
(*((closure_test_type)(code)))();
} catch (int exception_code)
{
CHECK(exception_code == 9);
}
printf("part one OK\n");
/* { dg-output "part one OK" } */
}
{
cl_arg_types[0] = &ffi_type_float;
cl_arg_types[1] = &ffi_type_float;
cl_arg_types[2] = &ffi_type_float;
cl_arg_types[3] = &ffi_type_float;
cl_arg_types[4] = &ffi_type_sshort;
cl_arg_types[5] = &ffi_type_float;
cl_arg_types[6] = &ffi_type_float;
cl_arg_types[7] = &ffi_type_uint;
cl_arg_types[8] = &ffi_type_double;
cl_arg_types[9] = &ffi_type_uint;
cl_arg_types[10] = &ffi_type_uint;
cl_arg_types[11] = &ffi_type_float;
cl_arg_types[12] = &ffi_type_uint;
cl_arg_types[13] = &ffi_type_uint;
cl_arg_types[14] = &ffi_type_uint;
cl_arg_types[15] = &ffi_type_uint;
cl_arg_types[16] = NULL;
/* Initialize the cif */
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
&ffi_type_sint, cl_arg_types) == FFI_OK);
CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn1,
(void *) 3 /* userdata */, code) == FFI_OK);
try
{
(*((closure_test_type1)code))
(1.1, 2.2, 3.3, 4.4, 127, 5.5, 6.6, 8, 9, 10, 11, 12.0, 13,
19, 21, 1);
/* { dg-output "\n1 2 3 4 127 5 6 8 9 10 11 12 13 19 21 1 3: 255" } */
} catch (int exception_code)
{
CHECK(exception_code == 255);
}
printf("part two OK\n");
/* { dg-output "\npart two OK" } */
}
exit(0);
}
| teeple/pns_server | work/install/Python-2.7.4/Modules/_ctypes/libffi/testsuite/libffi.special/unwindtest.cc | C++ | gpl-2.0 | 3,804 |
var utils = require('./connection_utils'),
inherits = require('util').inherits,
net = require('net'),
EventEmitter = require('events').EventEmitter,
inherits = require('util').inherits,
MongoReply = require("../responses/mongo_reply").MongoReply,
Connection = require("./connection").Connection;
var ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) {
if(typeof host !== 'string' || typeof port !== 'number') throw "host and port must be specified [" + host + ":" + port + "]";
// Set up event emitter
EventEmitter.call(this);
// Keep all options for the socket in a specific collection allowing the user to specify the
// Wished upon socket connection parameters
this.socketOptions = typeof socketOptions === 'object' ? socketOptions : {};
this.socketOptions.host = host;
this.socketOptions.port = port;
this.bson = bson;
// PoolSize is always + 1 for special reserved "measurment" socket (like ping, stats etc)
this.poolSize = poolSize;
this.minPoolSize = Math.floor(this.poolSize / 2) + 1;
// Set default settings for the socket options
utils.setIntegerParameter(this.socketOptions, 'timeout', 0);
// Delay before writing out the data to the server
utils.setBooleanParameter(this.socketOptions, 'noDelay', true);
// Delay before writing out the data to the server
utils.setIntegerParameter(this.socketOptions, 'keepAlive', 0);
// Set the encoding of the data read, default is binary == null
utils.setStringParameter(this.socketOptions, 'encoding', null);
// Allows you to set a throttling bufferSize if you need to stop overflows
utils.setIntegerParameter(this.socketOptions, 'bufferSize', 0);
// Internal structures
this.openConnections = [];
// Assign connection id's
this.connectionId = 0;
// Current index for selection of pool connection
this.currentConnectionIndex = 0;
// The pool state
this._poolState = 'disconnected';
// timeout control
this._timeout = false;
}
inherits(ConnectionPool, EventEmitter);
ConnectionPool.prototype.setMaxBsonSize = function(maxBsonSize) {
if(maxBsonSize == null){
maxBsonSize = Connection.DEFAULT_MAX_BSON_SIZE;
}
for(var i = 0; i < this.openConnections.length; i++) {
this.openConnections[i].maxBsonSize = maxBsonSize;
}
}
// Start a function
var _connect = function(_self) {
return new function() {
// Create a new connection instance
var connection = new Connection(_self.connectionId++, _self.socketOptions);
// Set logger on pool
connection.logger = _self.logger;
// Connect handler
connection.on("connect", function(err, connection) {
// Add connection to list of open connections
_self.openConnections.push(connection);
// If the number of open connections is equal to the poolSize signal ready pool
if(_self.openConnections.length === _self.poolSize && _self._poolState !== 'disconnected') {
// Set connected
_self._poolState = 'connected';
// Emit pool ready
_self.emit("poolReady");
} else if(_self.openConnections.length < _self.poolSize) {
// We need to open another connection, make sure it's in the next
// tick so we don't get a cascade of errors
process.nextTick(function() {
_connect(_self);
});
}
});
var numberOfErrors = 0
// Error handler
connection.on("error", function(err, connection) {
numberOfErrors++;
// If we are already disconnected ignore the event
if(_self._poolState != 'disconnected' && _self.listeners("error").length > 0) {
_self.emit("error", err);
}
// Set disconnected
_self._poolState = 'disconnected';
// Stop
_self.stop();
});
// Close handler
connection.on("close", function() {
// If we are already disconnected ignore the event
if(_self._poolState !== 'disconnected' && _self.listeners("close").length > 0) {
_self.emit("close");
}
// Set disconnected
_self._poolState = 'disconnected';
// Stop
_self.stop();
});
// Timeout handler
connection.on("timeout", function(err, connection) {
// If we are already disconnected ignore the event
if(_self._poolState !== 'disconnected' && _self.listeners("timeout").length > 0) {
_self.emit("timeout", err);
}
// Set disconnected
_self._poolState = 'disconnected';
// Stop
_self.stop();
});
// Parse error, needs a complete shutdown of the pool
connection.on("parseError", function() {
// If we are already disconnected ignore the event
if(_self._poolState !== 'disconnected' && _self.listeners("parseError").length > 0) {
_self.emit("parseError", new Error("parseError occured"));
}
_self.stop();
});
connection.on("message", function(message) {
_self.emit("message", message);
});
// Start connection in the next tick
connection.start();
}();
}
// Start method, will throw error if no listeners are available
// Pass in an instance of the listener that contains the api for
// finding callbacks for a given message etc.
ConnectionPool.prototype.start = function() {
var markerDate = new Date().getTime();
var self = this;
if(this.listeners("poolReady").length == 0) {
throw "pool must have at least one listener ready that responds to the [poolReady] event";
}
// Set pool state to connecting
this._poolState = 'connecting';
this._timeout = false;
_connect(self);
}
// Restart a connection pool (on a close the pool might be in a wrong state)
ConnectionPool.prototype.restart = function() {
// Close all connections
this.stop(false);
// Now restart the pool
this.start();
}
// Stop the connections in the pool
ConnectionPool.prototype.stop = function(removeListeners) {
removeListeners = removeListeners == null ? true : removeListeners;
// Set disconnected
this._poolState = 'disconnected';
// Clear all listeners if specified
if(removeListeners) {
this.removeAllEventListeners();
}
// Close all connections
for(var i = 0; i < this.openConnections.length; i++) {
this.openConnections[i].close();
}
// Clean up
this.openConnections = [];
}
// Check the status of the connection
ConnectionPool.prototype.isConnected = function() {
return this._poolState === 'connected';
}
// Checkout a connection from the pool for usage, or grab a specific pool instance
ConnectionPool.prototype.checkoutConnection = function(id) {
var index = (this.currentConnectionIndex++ % (this.openConnections.length));
var connection = this.openConnections[index];
return connection;
}
ConnectionPool.prototype.getAllConnections = function() {
return this.openConnections;
}
// Remove all non-needed event listeners
ConnectionPool.prototype.removeAllEventListeners = function() {
this.removeAllListeners("close");
this.removeAllListeners("error");
this.removeAllListeners("timeout");
this.removeAllListeners("connect");
this.removeAllListeners("end");
this.removeAllListeners("parseError");
this.removeAllListeners("message");
this.removeAllListeners("poolReady");
}
| cw0100/cwse | nodejs/node_modules/rrestjs/node_modules/mongodb/lib/mongodb/connection/connection_pool.js | JavaScript | gpl-2.0 | 7,246 |
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using SmartStore.Core.Domain.Tasks;
namespace SmartStore.Core.Events
{
/// <summary>
/// to initialize scheduled tasks in Application_Start
/// </summary>
public class AppInitScheduledTasksEvent
{
public IList<ScheduleTask> ScheduledTasks { get; set; }
}
}
| ibindura/SmartStoreNET | src/Libraries/SmartStore.Core/Events/CommonMessages/AppInitScheduledTasksEvent.cs | C# | gpl-3.0 | 357 |
#include <iostream>
#include <seqan/stream.h>
using namespace seqan;
int main(int argc, char const ** argv)
{
if (argc != 2)
{
std::cerr << "USAGE: tutorial_solution1 VALUE\n";
return 1;
}
// Lexical casting with the 1-argument lexicalCast().
{
int i = 0;
unsigned u = 0;
double d = 0;
try
{
d = lexicalCast<double>(argv[1]);
i = lexicalCast<int>(argv[1]);
u = lexicalCast<unsigned>(argv[1]);
}
catch (BadLexicalCast & e)
{
std::cerr << e.what() << std::endl;
}
std::cout << "lexicalCast<int>(" << argv[1] << ") == " << i << '\n';
std::cout << "lexicalCast<unsinged>(" << argv[1] << ") == " << u << '\n';
std::cout << "lexicalCast<double>(" << argv[1] << ") == " << d << '\n';
}
// Lexical casting with the 2-argument lexicalCast().
{
int i = 0;
unsigned u = 0;
double d = 0;
bool bi = lexicalCast(i, argv[1]);
bool bu = lexicalCast(u, argv[1]);
bool bd = lexicalCast(d, argv[1]);
std::cout << "lexicalCast2<int>(" << argv[1] << ") == (" << bi << ", " << i << ")\n";
std::cout << "lexicalCast2<unsigned>(" << argv[1] << ") == (" << bu << ", " << u << ")\n";
std::cout << "lexicalCast2<double>(" << argv[1] << ") == (" << bd << ", " << d << ")\n";
}
// Lexical casting with the 2-argument lexicalCast() that throws exceptions.
{
int i = 0;
unsigned u = 0;
double d = 0;
try
{
lexicalCastWithException(d, argv[1]);
lexicalCastWithException(i, argv[1]);
lexicalCastWithException(u, argv[1]);
}
catch (BadLexicalCast & e)
{
std::cerr << e.what() << std::endl;
}
std::cout << "lexicalCast2<int>(" << argv[1] << ") == (" << i << ")\n";
std::cout << "lexicalCast2<unsigned>(" << argv[1] << ") == (" << u << ")\n";
std::cout << "lexicalCast2<double>(" << argv[1] << ") == (" << d << ")\n";
}
return 0;
}
| rrahn/jst_bench | include/seqan/demos/tutorial/custom_io/solution4.cpp | C++ | gpl-3.0 | 2,177 |
define(
({
"collapse": "Spusti traku s alatima editora",
"expand": "Proširi traku s alatima editora"
})
);
| avz-cmf/zaboy-middleware | www/js/dojox/editor/plugins/nls/hr/CollapsibleToolbar.js | JavaScript | gpl-3.0 | 110 |
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package upgrader
import (
"github.com/juju/juju/agent/tools"
"github.com/juju/juju/version"
)
// UpgradeReadyError is returned by an Upgrader to report that
// an upgrade is ready to be performed and a restart is due.
type UpgradeReadyError struct {
AgentName string
OldTools version.Binary
NewTools version.Binary
DataDir string
}
func (e *UpgradeReadyError) Error() string {
return "must restart: an agent upgrade is available"
}
// ChangeAgentTools does the actual agent upgrade.
// It should be called just before an agent exits, so that
// it will restart running the new tools.
func (e *UpgradeReadyError) ChangeAgentTools() error {
agentTools, err := tools.ChangeAgentTools(e.DataDir, e.AgentName, e.NewTools)
if err != nil {
return err
}
logger.Infof("upgraded from %v to %v (%q)", e.OldTools, agentTools.Version, agentTools.URL)
return nil
}
| tsakas/juju | worker/upgrader/error.go | GO | agpl-3.0 | 967 |
// stdafx.cpp : source file that includes just the standard includes
// xpad.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
string format(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
int result = -1, length = 256;
char* buffer = NULL;
while(result == -1)
{
if(buffer) delete [] buffer;
buffer = new char[length + 1];
memset(buffer, 0, length + 1);
result = _vsnprintf(buffer, length, fmt, args);
length *= 2;
}
va_end(args);
string s(buffer);
delete [] buffer;
return s;
}
| Pistachioman/pcsx2 | plugins/CDVDolio/stdafx.cpp | C++ | lgpl-3.0 | 679 |
<?php
/*
* Copyright 2014 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.
*/
class Google_Service_HangoutsChat_Image extends Google_Model
{
public $aspectRatio;
public $imageUrl;
protected $onClickType = 'Google_Service_HangoutsChat_OnClick';
protected $onClickDataType = '';
public function setAspectRatio($aspectRatio)
{
$this->aspectRatio = $aspectRatio;
}
public function getAspectRatio()
{
return $this->aspectRatio;
}
public function setImageUrl($imageUrl)
{
$this->imageUrl = $imageUrl;
}
public function getImageUrl()
{
return $this->imageUrl;
}
/**
* @param Google_Service_HangoutsChat_OnClick
*/
public function setOnClick(Google_Service_HangoutsChat_OnClick $onClick)
{
$this->onClick = $onClick;
}
/**
* @return Google_Service_HangoutsChat_OnClick
*/
public function getOnClick()
{
return $this->onClick;
}
}
| drthomas21/WordPress_Tutorial | wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/HangoutsChat/Image.php | PHP | apache-2.0 | 1,427 |
// ----------------------------------------------------------------------------------
//
// 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.
// ----------------------------------------------------------------------------------
namespace Microsoft.Azure.Commands.Sql.SecureConnection.Model
{
/// <summary>
/// A class representing a database's secure connection policy
/// </summary>
public class DatabaseSecureConnectionPolicyModel : BaseSecureConnectionPolicyModel
{
/// <summary>
/// The internal ConnectionString field
/// </summary>
private ConnectionStrings m_ConnectionStrings;
/// <summary>
/// Gets or sets the database name
/// </summary>
public string DatabaseName { get; set; }
/// <summary>
/// Lazy set of the connection string object
/// </summary>
public ConnectionStrings ConnectionStrings
{
get
{
if (m_ConnectionStrings == null)
{
if (ProxyDnsName != null && ProxyPort != null && ServerName != null && DatabaseName != null)
{
m_ConnectionStrings = new ConnectionStrings(ProxyDnsName, ProxyPort, ServerName, DatabaseName);
}
}
return m_ConnectionStrings;
}
}
}
}
| atpham256/azure-powershell | src/ResourceManager/Sql/Commands.Sql/Secure Connection/Model/DatabaseSecureConnectionPolicyModel.cs | C# | apache-2.0 | 1,931 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.PopulateSwitch
{
internal static class PopulateSwitchHelpers
{
public const string MissingCases = nameof(MissingCases);
public const string MissingDefaultCase = nameof(MissingDefaultCase);
public static bool HasDefaultCase(ISwitchOperation switchStatement)
{
for (var index = switchStatement.Cases.Length - 1; index >= 0; index--)
{
if (HasDefaultCase(switchStatement.Cases[index]))
{
return true;
}
}
return false;
}
private static bool HasDefaultCase(ISwitchCaseOperation switchCase)
{
foreach (var clause in switchCase.Clauses)
{
if (clause.CaseKind == CaseKind.Default)
{
return true;
}
}
return false;
}
public static ICollection<ISymbol> GetMissingEnumMembers(ISwitchOperation switchStatement)
{
var switchExpression = switchStatement.Value;
var switchExpressionType = switchExpression?.Type;
var enumMembers = new Dictionary<long, ISymbol>();
if (switchExpressionType?.TypeKind == TypeKind.Enum)
{
if (!TryGetAllEnumMembers(switchExpressionType, enumMembers) ||
!TryRemoveExistingEnumMembers(switchStatement, enumMembers))
{
return SpecializedCollections.EmptyCollection<ISymbol>();
}
}
return enumMembers.Values;
}
private static bool TryRemoveExistingEnumMembers(ISwitchOperation switchStatement, Dictionary<long, ISymbol> enumValues)
{
foreach (var switchCase in switchStatement.Cases)
{
foreach (var clause in switchCase.Clauses)
{
switch (clause.CaseKind)
{
default:
case CaseKind.None:
case CaseKind.Relational:
case CaseKind.Range:
// This was some sort of complex switch. For now just ignore
// these and assume that they're complete.
return false;
case CaseKind.Default:
// ignore the 'default/else' clause.
continue;
case CaseKind.SingleValue:
var value = ((ISingleValueCaseClauseOperation)clause).Value;
if (value == null || !value.ConstantValue.HasValue)
{
// We had a case which didn't resolve properly.
// Assume the switch is complete.
return false;
}
var caseValue = IntegerUtilities.ToInt64(value.ConstantValue.Value);
enumValues.Remove(caseValue);
break;
}
}
}
return true;
}
private static bool TryGetAllEnumMembers(
ITypeSymbol enumType,
Dictionary<long, ISymbol> enumValues)
{
foreach (var member in enumType.GetMembers())
{
// skip `.ctor` and `__value`
var fieldSymbol = member as IFieldSymbol;
if (fieldSymbol == null || fieldSymbol.Type.SpecialType != SpecialType.None)
{
continue;
}
if (fieldSymbol.ConstantValue == null)
{
// We have an enum that has problems with it (i.e. non-const members). We won't
// be able to determine properly if the switch is complete. Assume it is so we
// don't offer to do anything.
return false;
}
// Multiple enum members may have the same value. Only consider the first one
// we run int.
var enumValue = IntegerUtilities.ToInt64(fieldSymbol.ConstantValue);
if (!enumValues.ContainsKey(enumValue))
{
enumValues.Add(enumValue, fieldSymbol);
}
}
return true;
}
}
}
| mmitche/roslyn | src/Features/Core/Portable/PopulateSwitch/PopulateSwitchHelpers.cs | C# | apache-2.0 | 4,898 |
'use strict';
angular.module('openshiftConsole')
.directive('overviewDeployment', function($location, $timeout, LabelFilter) {
return {
restrict: 'E',
scope: {
// Replication controller / deployment fields
rc: '=',
deploymentConfigId: '=',
deploymentConfigMissing: '=',
deploymentConfigDifferentService: '=',
// Nested podTemplate fields
imagesByDockerReference: '=',
builds: '=',
// Pods
pods: '='
},
templateUrl: 'views/_overview-deployment.html',
controller: function($scope) {
$scope.viewPodsForDeployment = function(deployment) {
$location.url("/project/" + deployment.metadata.namespace + "/browse/pods");
$timeout(function() {
LabelFilter.setLabelSelector(new LabelSelector(deployment.spec.selector, true));
}, 1);
};
}
};
})
.directive('overviewMonopod', function() {
return {
restrict: 'E',
scope: {
pod: '='
},
templateUrl: 'views/_overview-monopod.html'
};
})
.directive('podTemplate', function() {
return {
restrict: 'E',
scope: {
podTemplate: '=',
imagesByDockerReference: '=',
builds: '='
},
templateUrl: 'views/_pod-template.html'
};
})
.directive('pods', function() {
return {
restrict: 'E',
scope: {
pods: '=',
projectName: '@?' //TODO optional for now
},
templateUrl: 'views/_pods.html',
controller: function($scope) {
$scope.phases = [
"Failed",
"Pending",
"Running",
"Succeeded",
"Unknown"
];
$scope.expandedPhase = null;
$scope.warningsExpanded = false;
$scope.expandPhase = function(phase, warningsExpanded, $event) {
$scope.expandedPhase = phase;
$scope.warningsExpanded = warningsExpanded;
if ($event) {
$event.stopPropagation();
}
};
}
};
})
.directive('podContent', function() {
// sub-directive used by the pods directive
return {
restrict: 'E',
scope: {
pod: '=',
troubled: '='
},
templateUrl: 'views/directives/_pod-content.html'
};
})
.directive('triggers', function() {
var hideBuildKey = function(build) {
return 'hide/build/' + build.metadata.namespace + '/' + build.metadata.name;
};
return {
restrict: 'E',
scope: {
triggers: '='
},
link: function(scope) {
scope.isBuildHidden = function(build) {
var key = hideBuildKey(build);
return sessionStorage.getItem(key) === 'true';
};
scope.hideBuild = function(build) {
var key = hideBuildKey(build);
sessionStorage.setItem(key, 'true');
};
},
templateUrl: 'views/_triggers.html'
};
})
.directive('deploymentConfigMetadata', function() {
return {
restrict: 'E',
scope: {
deploymentConfigId: '=',
exists: '=',
differentService: '='
},
templateUrl: 'views/_deployment-config-metadata.html'
};
});
| domenicbove/origin | assets/app/scripts/directives/resources.js | JavaScript | apache-2.0 | 3,240 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
#
# Copyright (c) 2013-2015 Noviat nv/sa (www.noviat.com).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import account
from . import res_partner
from . import ir_actions
| damdam-s/account-financial-tools | account_move_line_search_extension/__init__.py | Python | agpl-3.0 | 1,056 |
# -*- coding: utf-8 -*-
from odoo.tests.common import HttpCase
from odoo.exceptions import ValidationError
class AccountingTestCase(HttpCase):
""" This class extends the base TransactionCase, in order to test the
accounting with localization setups. It is configured to run the tests after
the installation of all modules, and will SKIP TESTS ifit cannot find an already
configured accounting (which means no localization module has been installed).
"""
post_install = True
at_install = False
def setUp(self):
super(AccountingTestCase, self).setUp()
domain = [('company_id', '=', self.env.ref('base.main_company').id)]
if not self.env['account.account'].search_count(domain):
self.skipTest("No Chart of account found")
def check_complete_move(self, move, theorical_lines):
for aml in move.line_ids:
line = (aml.name, round(aml.debit, 2), round(aml.credit, 2))
if line in theorical_lines:
theorical_lines.remove(line)
else:
raise ValidationError('Unexpected journal item. (label: %s, debit: %s, credit: %s)' % (aml.name, round(aml.debit, 2), round(aml.credit, 2)))
if theorical_lines:
raise ValidationError('Remaining theorical line (not found). %s)' % ([(aml[0], aml[1], aml[2]) for aml in theorical_lines]))
return True
def ensure_account_property(self, property_name):
'''Ensure the ir.property targetting an account.account passed as parameter exists.
In case it's not: create it with a random account. This is useful when testing with
partially defined localization (missing stock properties for example)
:param property_name: The name of the property.
'''
company_id = self.env.user.company_id
field_id = self.env['ir.model.fields'].search(
[('model', '=', 'product.template'), ('name', '=', property_name)], limit=1)
property_id = self.env['ir.property'].search([
('company_id', '=', company_id.id),
('name', '=', property_name),
('res_id', '=', None),
('fields_id', '=', field_id.id)], limit=1)
account_id = self.env['account.account'].search([('company_id', '=', company_id.id)], limit=1)
value_reference = 'account.account,%d' % account_id.id
if property_id and not property_id.value_reference:
property_id.value_reference = value_reference
else:
self.env['ir.property'].create({
'name': property_name,
'company_id': company_id.id,
'fields_id': field_id.id,
'value_reference': value_reference,
})
| Aravinthu/odoo | addons/account/tests/account_test_classes.py | Python | agpl-3.0 | 2,749 |
require "helper"
describe Octokit::EnterpriseAdminClient::Orgs do
before do
Octokit.reset!
@admin_client = enterprise_admin_client
end
describe ".create_organization", :vcr do
it "creates a new organization" do
@admin_client.create_organization('SuchAGreatOrg', 'gjtorikian')
expect(@admin_client.last_response.status).to eq(201)
assert_requested :post, github_enterprise_url("admin/organizations")
end
end # .create_organization
end
| iainbeeston/octokit.rb | spec/octokit/enterprise_admin_client/orgs_spec.rb | Ruby | mit | 479 |
// Type definitions for es6-promise
// Project: https://github.com/jakearchibald/ES6-Promise
// Definitions by: François de Campredon <https://github.com/fdecampredon>, vvakame <https://github.com/vvakame>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Thenable<T> {
then<U>(onFulfilled?: (value: T) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
then<U>(onFulfilled?: (value: T) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>;
}
declare class Promise<T> implements Thenable<T> {
/**
* If you call resolve in the body of the callback passed to the constructor,
* your promise is fulfilled with result object passed to resolve.
* If you call reject your promise is rejected with the object passed to reject.
* For consistency and debugging (eg stack traces), obj should be an instanceof Error.
* Any errors thrown in the constructor callback will be implicitly passed to reject().
*/
constructor(callback: (resolve : (value?: T | Thenable<T>) => void, reject: (error?: any) => void) => void);
/**
* onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects.
* Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called.
* Both callbacks have a single parameter , the fulfillment value or rejection reason.
* "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve.
* If an error is thrown in the callback, the returned promise rejects with that error.
*
* @param onFulfilled called when/if "promise" resolves
* @param onRejected called when/if "promise" rejects
*/
then<U>(onFulfilled?: (value: T) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Promise<U>;
then<U>(onFulfilled?: (value: T) => U | Thenable<U>, onRejected?: (error: any) => void): Promise<U>;
/**
* Sugar for promise.then(undefined, onRejected)
*
* @param onRejected called when/if "promise" rejects
*/
catch<U>(onRejected?: (error: any) => U | Thenable<U>): Promise<U>;
}
declare namespace Promise {
/**
* Make a new promise from the thenable.
* A thenable is promise-like in as far as it has a "then" method.
*/
function resolve<T>(value?: T | Thenable<T>): Promise<T>;
/**
* Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error
*/
function reject(error: any): Promise<any>;
function reject<T>(error: T): Promise<T>;
/**
* Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects.
* the array passed to all can be a mixture of promise-like objects and other objects.
* The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value.
*/
function all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>, T8 | Thenable<T8>, T9 | Thenable<T9>, T10 | Thenable<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
function all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>, T8 | Thenable<T8>, T9 | Thenable<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
function all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>, T8 | Thenable<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
function all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
function all<T1, T2, T3, T4, T5, T6>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
function all<T1, T2, T3, T4, T5>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>]): Promise<[T1, T2, T3, T4, T5]>;
function all<T1, T2, T3, T4>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>]): Promise<[T1, T2, T3, T4]>;
function all<T1, T2, T3>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>]): Promise<[T1, T2, T3]>;
function all<T1, T2>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>]): Promise<[T1, T2]>;
function all<T>(values: (T | Thenable<T>)[]): Promise<T[]>;
/**
* Make a Promise that fulfills when any item fulfills, and rejects if any item rejects.
*/
function race<T>(promises: (T | Thenable<T>)[]): Promise<T>;
}
declare module 'es6-promise' {
var foo: typeof Promise; // Temp variable to reference Promise in local context
namespace rsvp {
export var Promise: typeof foo;
export function polyfill(): void;
}
export = rsvp;
}
| AbraaoAlves/DefinitelyTyped | types/es6-promise/index.d.ts | TypeScript | mit | 5,199 |
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
namespace Respect\Validation\Rules\SubdivisionCode;
use Respect\Validation\Rules\AbstractSearcher;
/**
* Validator for Somalia subdivision code.
*
* ISO 3166-1 alpha-2: SO
*
* @link http://www.geonames.org/SO/administrative-division-somalia.html
*/
class SoSubdivisionCode extends AbstractSearcher
{
public $haystack = [
'AW', // Awdal
'BK', // Bakool
'BN', // Banaadir
'BR', // Bari
'BY', // Bay
'GA', // Galguduud
'GE', // Gedo
'HI', // Hiiraan
'JD', // Jubbada Dhexe
'JH', // Jubbada Hoose
'MU', // Mudug
'NU', // Nugaal
'SA', // Sanaag
'SD', // Shabeellaha Dhexe
'SH', // Shabeellaha Hoose
'SO', // Sool
'TO', // Togdheer
'WO', // Woqooyi Galbeed
];
public $compareIdentical = true;
}
| SiliconSouthTech/farmeazy | vendor/respect/validation/library/Rules/SubdivisionCode/SoSubdivisionCode.php | PHP | mit | 1,108 |